repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ainopara/Stage1st-Reader
|
Stage1st/Manager/SentryBreadcrumbsLogger.swift
|
1
|
1642
|
//
// SentryBreadcrumbsLogger.swift
// Stage1st
//
// Created by Zheng Li on 2020/2/9.
// Copyright © 2020 Renaissance. All rights reserved.
//
import CocoaLumberjack
import Sentry
private extension DDLoggerName {
static let sentryBreadcrumbs = DDLoggerName("com.ainopara.sentryBreadcrumbsLogger")
}
class SentryBreadcrumbsLogger: DDAbstractLogger {
@objc public static let shared = SentryBreadcrumbsLogger()
override var loggerName: DDLoggerName {
return .sentryBreadcrumbs
}
override func log(message logMessage: DDLogMessage) {
let message: String?
if let formatter = value(forKey: "_logFormatter") as? DDLogFormatter {
message = formatter.format(message: logMessage)
} else {
message = logMessage.message
}
guard let finalMessage = message else {
// Log Formatter decided to drop this message.
return
}
let level: SentryLevel = {
switch logMessage.level {
case .debug: return .debug
case .info: return .info
case .warning: return .warning
case .error: return .error
default: return .debug
}
}()
let rawCategory = (logMessage.tag as? S1LoggerTag)?.category.description ?? "default"
let category: String = "log / \(rawCategory)"
let breadcrumb = Breadcrumb(level: level, category: category)
breadcrumb.message = finalMessage
breadcrumb.timestamp = logMessage.timestamp
breadcrumb.level = level
SentrySDK.addBreadcrumb(crumb: breadcrumb)
}
}
|
bsd-3-clause
|
124a89e2158565c96088e5e9dd346ea4
| 28.303571 | 93 | 0.636807 | 4.784257 | false | false | false | false |
EndouMari/TabPageViewController
|
Sources/TabCollectionCell.swift
|
1
|
2601
|
//
// TabCollectionCell.swift
// TabPageViewController
//
// Created by EndouMari on 2016/02/24.
// Copyright © 2016年 EndouMari. All rights reserved.
//
import UIKit
class TabCollectionCell: UICollectionViewCell {
var tabItemButtonPressedBlock: (() -> Void)?
var option: TabPageOption = TabPageOption() {
didSet {
currentBarViewHeightConstraint.constant = option.currentBarHeight
}
}
var item: String = "" {
didSet {
itemLabel.text = item
itemLabel.invalidateIntrinsicContentSize()
invalidateIntrinsicContentSize()
}
}
var isCurrent: Bool = false {
didSet {
currentBarView.isHidden = !isCurrent
if isCurrent {
highlightTitle()
} else {
unHighlightTitle()
}
currentBarView.backgroundColor = option.currentColor
layoutIfNeeded()
}
}
@IBOutlet fileprivate weak var itemLabel: UILabel!
@IBOutlet fileprivate weak var currentBarView: UIView!
@IBOutlet fileprivate weak var currentBarViewHeightConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
currentBarView.isHidden = true
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
if item.count == 0 {
return CGSize.zero
}
return intrinsicContentSize
}
class func cellIdentifier() -> String {
return "TabCollectionCell"
}
}
// MARK: - View
extension TabCollectionCell {
override var intrinsicContentSize : CGSize {
let width: CGFloat
if let tabWidth = option.tabWidth , tabWidth > 0.0 {
width = tabWidth
} else {
width = itemLabel.intrinsicContentSize.width + option.tabMargin * 2
}
let size = CGSize(width: width, height: option.tabHeight)
return size
}
func hideCurrentBarView() {
currentBarView.isHidden = true
}
func showCurrentBarView() {
currentBarView.isHidden = false
}
func highlightTitle() {
itemLabel.textColor = option.currentColor
itemLabel.font = UIFont.boldSystemFont(ofSize: option.fontSize)
}
func unHighlightTitle() {
itemLabel.textColor = option.defaultColor
itemLabel.font = UIFont.systemFont(ofSize: option.fontSize)
}
}
// MARK: - IBAction
extension TabCollectionCell {
@IBAction fileprivate func tabItemTouchUpInside(_ button: UIButton) {
tabItemButtonPressedBlock?()
}
}
|
mit
|
c8f9a9c5b9d11de28ce5a495049bb9ab
| 23.980769 | 86 | 0.623172 | 5.114173 | false | false | false | false |
JohnSundell/Unbox
|
Sources/Unbox/Unboxer.swift
|
1
|
8516
|
/**
* Unbox
* Copyright (c) 2015-2017 John Sundell
* Licensed under the MIT license, see LICENSE file
*/
import Foundation
// MARK: - Public
/**
* Class used to Unbox (decode) values from a dictionary
*
* For each supported type, simply call `unbox(key: string)` (where `string` is a key in the dictionary that is being unboxed)
* - and the correct type will be returned. If a required (non-optional) value couldn't be unboxed `UnboxError` will be thrown.
*/
public final class Unboxer {
/// The underlying JSON dictionary that is being unboxed
public let dictionary: UnboxableDictionary
// MARK: - Initializer
/// Initialize an instance with a dictionary that can then be decoded using the `unbox()` methods.
public init(dictionary: UnboxableDictionary) {
self.dictionary = dictionary
}
/// Initialize an instance with binary data than can then be decoded using the `unbox()` methods. Throws `UnboxError` for invalid data.
public init(data: Data) throws {
self.dictionary = try JSONSerialization.unbox(data: data)
}
// MARK: - Custom unboxing API
/// Perform custom unboxing using an Unboxer (created from a dictionary) passed to a closure, or throw an UnboxError
public static func performCustomUnboxing<T>(dictionary: UnboxableDictionary, closure: (Unboxer) throws -> T?) throws -> T {
return try Unboxer(dictionary: dictionary).performCustomUnboxing(closure: closure)
}
/// Perform custom unboxing on an array of dictionaries, executing a closure with a new Unboxer for each one, or throw an UnboxError
public static func performCustomUnboxing<T>(array: [UnboxableDictionary], allowInvalidElements: Bool = false, closure: (Unboxer) throws -> T?) throws -> [T] {
return try array.map(allowInvalidElements: allowInvalidElements) {
try Unboxer(dictionary: $0).performCustomUnboxing(closure: closure)
}
}
/// Perform custom unboxing using an Unboxer (created from binary data) passed to a closure, or throw an UnboxError
public static func performCustomUnboxing<T>(data: Data, closure: @escaping (Unboxer) throws -> T?) throws -> T {
return try data.unbox(closure: closure)
}
// MARK: - Unboxing required values (by key)
/// Unbox a required value by key
public func unbox<T: UnboxCompatible>(key: String) throws -> T {
return try self.unbox(path: .key(key), transform: T.unbox)
}
/// Unbox a required collection by key
public func unbox<T: UnboxableCollection>(key: String, allowInvalidElements: Bool) throws -> T {
let transform = T.makeTransform(allowInvalidElements: allowInvalidElements)
return try self.unbox(path: .key(key), transform: transform)
}
/// Unbox a required Unboxable type by key
public func unbox<T: Unboxable>(key: String) throws -> T {
return try self.unbox(path: .key(key), transform: T.makeTransform())
}
/// Unbox a required UnboxableWithContext type by key
public func unbox<T: UnboxableWithContext>(key: String, context: T.UnboxContext) throws -> T {
return try self.unbox(path: .key(key), transform: T.makeTransform(context: context))
}
/// Unbox a required collection of UnboxableWithContext values by key
public func unbox<C: UnboxableCollection, V: UnboxableWithContext>(key: String, context: V.UnboxContext, allowInvalidElements: Bool = false) throws -> C where C.UnboxValue == V {
return try self.unbox(path: .key(key), transform: V.makeCollectionTransform(context: context, allowInvalidElements: allowInvalidElements))
}
/// Unbox a required value using a formatter by key
public func unbox<F: UnboxFormatter>(key: String, formatter: F) throws -> F.UnboxFormattedType {
return try self.unbox(path: .key(key), transform: formatter.makeTransform())
}
/// Unbox a required collection of values using a formatter by key
public func unbox<C: UnboxableCollection, F: UnboxFormatter>(key: String, formatter: F, allowInvalidElements: Bool = false) throws -> C where C.UnboxValue == F.UnboxFormattedType {
return try self.unbox(path: .key(key), transform: formatter.makeCollectionTransform(allowInvalidElements: allowInvalidElements))
}
// MARK: - Unboxing required values (by key path)
/// Unbox a required value by key path
public func unbox<T: UnboxCompatible>(keyPath: String) throws -> T {
return try self.unbox(path: .keyPath(keyPath), transform: T.unbox)
}
/// Unbox a required collection by key path
public func unbox<T: UnboxCompatible>(keyPath: String, allowInvalidElements: Bool) throws -> T where T: Collection {
let transform = T.makeTransform(allowInvalidElements: allowInvalidElements)
return try self.unbox(path: .keyPath(keyPath), transform: transform)
}
/// Unbox a required Unboxable by key path
public func unbox<T: Unboxable>(keyPath: String) throws -> T {
return try self.unbox(path: .keyPath(keyPath), transform: T.makeTransform())
}
/// Unbox a required UnboxableWithContext type by key path
public func unbox<T: UnboxableWithContext>(keyPath: String, context: T.UnboxContext) throws -> T {
return try self.unbox(path: .keyPath(keyPath), transform: T.makeTransform(context: context))
}
/// Unbox a required collection of UnboxableWithContext values by key path
public func unbox<C: UnboxableCollection, V: UnboxableWithContext>(keyPath: String, context: V.UnboxContext, allowInvalidElements: Bool = false) throws -> C where C.UnboxValue == V {
return try self.unbox(path: .keyPath(keyPath), transform: V.makeCollectionTransform(context: context, allowInvalidElements: allowInvalidElements))
}
/// Unbox a required value using a formatter by key path
public func unbox<F: UnboxFormatter>(keyPath: String, formatter: F) throws -> F.UnboxFormattedType {
return try self.unbox(path: .keyPath(keyPath), transform: formatter.makeTransform())
}
/// Unbox a required collection of values using a formatter by key path
public func unbox<C: UnboxableCollection, F: UnboxFormatter>(keyPath: String, formatter: F, allowInvalidElements: Bool = false) throws -> C where C.UnboxValue == F.UnboxFormattedType {
return try self.unbox(path: .keyPath(keyPath), transform: formatter.makeCollectionTransform(allowInvalidElements: allowInvalidElements))
}
}
// MARK: - Internal
internal extension Unboxer {
func performUnboxing<T: Unboxable>() throws -> T {
return try T(unboxer: self)
}
func performUnboxing<T: UnboxableWithContext>(context: T.UnboxContext) throws -> T {
return try T(unboxer: self, context: context)
}
}
// MARK: - Private
private extension Unboxer {
func unbox<R>(path: UnboxPath, transform: UnboxTransform<R>) throws -> R {
do {
switch path {
case .key(let key):
let value = try self.dictionary[key].orThrow(UnboxPathError.missingKey(key))
return try transform(value).orThrow(UnboxPathError.invalidValue(value, key))
case .keyPath(let keyPath):
var node: UnboxPathNode = self.dictionary
let components = keyPath.components(separatedBy: ".")
for (index, key) in components.enumerated() {
guard let nextValue = node.unboxPathValue(forKey: key) else {
throw UnboxPathError.missingKey(key)
}
if index == components.index(before: components.endIndex) {
return try transform(nextValue).orThrow(UnboxPathError.invalidValue(nextValue, key))
}
guard let nextNode = nextValue as? UnboxPathNode else {
throw UnboxPathError.invalidValue(nextValue, key)
}
node = nextNode
}
throw UnboxPathError.emptyKeyPath
}
} catch {
if let publicError = error as? UnboxError {
throw publicError
} else if let pathError = error as? UnboxPathError {
throw UnboxError.pathError(pathError, path.description)
}
throw error
}
}
func performCustomUnboxing<T>(closure: (Unboxer) throws -> T?) throws -> T {
return try closure(self).orThrow(UnboxError.customUnboxingFailed)
}
}
|
mit
|
7eb7d30bdcf146f45a6b67cd29c2b745
| 44.784946 | 188 | 0.676491 | 4.754886 | false | false | false | false |
Wakup/Wakup-iOS-SDK
|
Wakup/UIButton+VerticalLayout.swift
|
1
|
862
|
//
// UIButton+VerticalLayout.swift
// Wuakup
//
// Created by Guillermo Gutiérrez on 23/02/15.
// Copyright (c) 2015 Yellow Pineapple. All rights reserved.
//
import Foundation
extension UIButton {
func centerVerticallyWithPadding(_ padding: CGFloat) {
let imageSize = self.imageView?.frame.size ?? CGSize.zero
let titleSize = self.titleLabel?.frame.size ?? CGSize.zero
let totalHeight = imageSize.height + titleSize.height + padding
imageEdgeInsets = UIEdgeInsets(top: imageSize.height - totalHeight, left: 0, bottom: 0, right: -titleSize.width)
titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageSize.width, bottom: titleSize.height - totalHeight, right: 0)
}
func centerVertically() {
let defaultPadding: CGFloat = 6
centerVerticallyWithPadding(defaultPadding)
}
}
|
mit
|
059656c3f9d277afd8c80dca624cecf0
| 33.44 | 120 | 0.687573 | 4.507853 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015
|
04-App Architecture/Swift 4/4-4-Presentation/PresentingDemo1/PresentingDemo/ViewController.swift
|
2
|
1116
|
//
// ViewController.swift
// PresentingDemo
//
// Created by Nicholas Outram on 14/01/2016.
// Copyright © 2016 Plymouth University. All rights reserved.
//
import UIKit
class ViewController: UIViewController, ModalViewController1Protocol {
@IBOutlet weak var resultLabel: UILabel!
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.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DEMO1" {
if let vc = segue.destination as? ModalViewController1 {
vc.titleText = "DEMO 1"
vc.delegate = self
}
}
}
//Call back
func dismissWithStringData(_ str: String) {
self.dismiss(animated: true) {
self.resultLabel.text = str
}
}
}
|
mit
|
c41ac917853668ff1aed7fc643f676fa
| 22.229167 | 80 | 0.587444 | 5.022523 | false | false | false | false |
kelvincobanaj/mubu
|
Crinita/MapController.swift
|
1
|
1929
|
//
// MapController.swift
// Mubu
//
// Created by Kelvin Çobanaj on 11/04/15.
// Copyright (c) 2015 Spiranca. All rights reserved.
//
import UIKit
class MapController: UIViewController {
var url = "http://swift.gsfc.nasa.gov/results/transients/weak/QSOB0003-066"
@IBOutlet weak var imageView: UIImageView!
@IBAction func backTapped(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: {})
}
@IBAction func settingsTapped(sender: UIBarButtonItem) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let destination = storyBoard.instantiateViewControllerWithIdentifier("Settings") as SettingsController
self.presentViewController(destination, animated: true, completion: nil)
}
@IBAction func analysisTapped(sender: AnyObject) {
let data = NSData(contentsOfURL: NSURL(string: "\(url).png")!)
imageView.image = UIImage(data: data!)
}
@IBAction func missionTapped(sender: UIBarButtonItem) {
let data = NSData(contentsOfURL: NSURL(string: "\(url).mission.png")!)
imageView.image = UIImage(data: data!)
}
@IBAction func orbitTapped(sender: UIBarButtonItem) {
let data = NSData(contentsOfURL: NSURL(string: "\(url).orbit.png")!)
imageView.image = UIImage(data: data!)
}
override func viewDidLoad() {
super.viewDidLoad()
imageView.contentMode = UIViewContentMode.ScaleAspectFit
let data = NSData(contentsOfURL: NSURL(string: "\(url).png")!)
imageView.image = UIImage(data: data!)
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "pw_maze_white")!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
5c0d880762d78d52b6da73e8a1532868
| 29.603175 | 110 | 0.653527 | 4.668281 | false | false | false | false |
instant-solutions/ISTimeline
|
ISTimelineDemo/ISTimelineDemo/ViewController.swift
|
1
|
3076
|
//
// ViewController.swift
// ISTimelineDemo
//
// Created by Max Holzleitner on 13.07.16.
// Copyright © 2016 instant:solutions. All rights reserved.
//
import UIKit
import ISTimeline
class ViewController: UIViewController {
@IBOutlet weak var timeline: ISTimeline!
override func viewDidLoad() {
super.viewDidLoad()
let black = UIColor.black
let green = UIColor.init(red: 76/255, green: 175/255, blue: 80/255, alpha: 1)
let touchAction = { (point:ISPoint) in
print("point \(point.title)")
}
let myPoints = [
ISPoint(title: "06:46 AM", description: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam.", pointColor: black, lineColor: black, touchUpInside: touchAction, fill: false),
ISPoint(title: "07:00 AM", description: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr.", pointColor: black, lineColor: black, touchUpInside: touchAction, fill: false),
ISPoint(title: "07:30 AM", description: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam.", pointColor: black, lineColor: black, touchUpInside: touchAction, fill: false),
ISPoint(title: "08:00 AM", description: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt.", pointColor: green, lineColor: green, touchUpInside: touchAction, fill: true),
ISPoint(title: "11:30 AM", description: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam.", touchUpInside: touchAction),
ISPoint(title: "02:30 PM", description: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam.", touchUpInside: touchAction),
ISPoint(title: "05:00 PM", description: "Lorem ipsum dolor sit amet.", touchUpInside: touchAction),
ISPoint(title: "08:15 PM", description: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam.", touchUpInside: touchAction),
ISPoint(title: "11:45 PM", description: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam.", touchUpInside: touchAction)
]
timeline.contentInset = UIEdgeInsetsMake(20.0, 20.0, 20.0, 20.0)
timeline.points = myPoints
}
}
|
apache-2.0
|
9c14a2b14a3c36991fecbf2d2f393e16
| 74 | 397 | 0.716748 | 3.863065 | false | false | false | false |
GJJDD/gjjinSwift
|
gjjinswift/gjjinswift/Classes/GJJTabBarConfig.swift
|
1
|
5387
|
//
// GJJTabBarConfig.swift
// gjjinswift
//
// Created by apple on 2016/7/4.
// Copyright © 2016年 QiaTu HangZhou. All rights reserved.
//
import UIKit
class GJJTabBarConfig: NSObject {
lazy var takePhotoViewController:GJJTakePhotoViewController = {
GJJTakePhotoViewController()
}()
func setuptabBarController() -> UITabBarController {
let inTabBarController = UITabBarController()
// inTabBarController.delegate = self
inTabBarController.tabBar.backgroundColor = UIColor.white()
inTabBarController.tabBar.tintColor = UIColor.init(red: 220/255.0, green: 92/255.0, blue: 108/255.0, alpha: 1)
// 关注
let aboutController = GJJAboutViewController()
aboutController.title = "关注"
aboutController.tabBarItem.image = UIImage.init(named: "grayfriend")
aboutController.tabBarItem.selectedImage = UIImage.init(named: "redfriend")
// 发现
let findController = GJJFindViewController()
findController.title = "发现"
findController.tabBarItem.image = UIImage.init(named: "graydiscover")
findController.tabBarItem.selectedImage = UIImage.init(named: "reddiscover")
// 拍照
let takePhotoController = GJJTakePhotoTabbarViewController()
takePhotoController.tabBarItem.image = UIImage.init(named: "paizhao")
// in记
let inController = GJJInViewController()
inController.title = "in记"
inController.tabBarItem.image = UIImage.init(named: "grayinji")
inController.tabBarItem.selectedImage = UIImage.init(named: "redinji")
// 中心
let centerController = GJJCenterViewController()
centerController.title = "中心"
centerController.tabBarItem.image = UIImage.init(named: "graycenter")
centerController.tabBarItem.selectedImage = UIImage.init(named: "redcenter")
inTabBarController.viewControllers = [aboutController, findController,takePhotoController, inController, centerController]
// 取消上边线
UITabBar.appearance().backgroundImage = UIImage.init()
UITabBar.appearance().shadowImage = UIImage.init()
inTabBarController.tabBar .insertSubview(drawTabbarBgImageView(), at: 0)
inTabBarController.tabBar.isOpaque = true
let tabBarItem = inTabBarController.tabBar.items?[2]
tabBarItem?.imageInsets = UIEdgeInsets.init(top: -3, left: 0, bottom: 3, right: 0)
aboutController.view.backgroundColor = UIColor.red()
findController.view.backgroundColor = UIColor.purple()
inController.view.backgroundColor = UIColor.orange()
centerController.view.backgroundColor = UIColor.white()
takePhotoController.view.backgroundColor = UIColor.blue()
return inTabBarController
}
func drawTabbarBgImageView() -> UIImageView {
let radius = 30.0 // 圆半径
let tabBarHeight = 49.0
let standOutHeight = 12.0 // 突出的高度
let allFloat = (pow(Decimal(radius), 2)-pow(Decimal(radius-standOutHeight), 2))
let ww = sqrtf(Float(allFloat))
let imageView = UIImageView.init(frame: CGRect.init(x: 0.0, y: -standOutHeight, width: Double(UIScreen.main().bounds.size.width), height: tabBarHeight+standOutHeight))
let size = imageView.frame.size
let layer = CAShapeLayer.init()
let path = UIBezierPath.init()
path.move(to: CGPoint.init(x: size.width/2-CGFloat(ww), y: CGFloat(standOutHeight)))
let angleH = 0.5*((radius-standOutHeight)/radius)
let startAngle = (1+angleH)*M_PI
let endAngle = (2-angleH)*M_PI
let center = CGPoint.init(x: CGFloat((size.width)/2), y: CGFloat(radius))
path.addArc(withCenter:center , radius: CGFloat(radius), startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true)
path.addLine(to: CGPoint.init(x: CGFloat(size.width/2+(CGFloat)(ww)), y: CGFloat(standOutHeight)))
path.addLine(to: CGPoint.init(x: size.width, y:
CGFloat(standOutHeight)))
path.addLine(to: CGPoint.init(x: size.width, y: size.height))
path.addLine(to: CGPoint.init(x: 0, y: size.height))
path.addLine(to: CGPoint.init(x: 0, y: standOutHeight))
path.addLine(to: CGPoint.init(x: size.width/2-CGFloat(ww), y: CGFloat(standOutHeight)))
layer.path = path.cgPath
layer.fillColor = UIColor.white().cgColor
layer.strokeColor = UIColor.init(white: 0.765, alpha: 1.0).cgColor
layer.lineWidth = 0.5
imageView.layer .addSublayer(layer)
return imageView;
}
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if viewController.classForCoder.isSubclass(of: GJJTakePhotoTabbarViewController.classForCoder()) {
debugPrint("点我了")
viewController.present(takePhotoViewController, animated: true, completion: {
})
return false
}
return true
}
}
|
apache-2.0
|
084edd096b97ebb7e8bc51289c905d96
| 38.407407 | 175 | 0.63797 | 4.474348 | false | false | false | false |
Allow2CEO/browser-ios
|
Client/Frontend/Browser/TabTrayController.swift
|
1
|
44682
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
import Storage
import ReadingList
import Shared
import CoreData
struct TabTrayControllerUX {
static let CornerRadius = BraveUX.TabTrayCellCornerRadius
static let BackgroundColor = UIConstants.AppBackgroundColor
static let CellBackgroundColor = UIColor(red:1.0, green:1.0, blue:1.0, alpha:1)
static let TitleBoxHeight = CGFloat(32.0)
static let Margin = CGFloat(15)
static let ToolbarBarTintColor = UIConstants.AppBackgroundColor
static let ToolbarButtonOffset = CGFloat(10.0)
static let CloseButtonMargin = CGFloat(4.0)
static let CloseButtonEdgeInset = CGFloat(6)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
}
struct LightTabCellUX {
static let TabTitleTextColor = BraveUX.GreyJ
}
struct DarkTabCellUX {
static let TabTitleTextColor = UIColor.white
}
protocol TabCellDelegate: class {
func tabCellDidClose(_ cell: TabCell)
}
class TabCell: UICollectionViewCell {
static let Identifier = "TabCellIdentifier"
let shadowView = UIView()
let backgroundHolder = UIView()
let background = UIImageViewAligned()
let titleLbl: UILabel
let favicon: UIImageView = UIImageView()
let titleWrapperBackground = UIView()
let closeButton: UIButton
let placeholderFavicon: UIImageView = UIImageView()
var titleWrapper: UIView = UIView()
var animator: SwipeAnimator!
weak var delegate: TabCellDelegate?
// Changes depending on whether we're full-screen or not.
var margin = CGFloat(0)
override init(frame: CGRect) {
shadowView.layer.cornerRadius = TabTrayControllerUX.CornerRadius
shadowView.layer.masksToBounds = false
backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor
backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
backgroundHolder.layer.borderWidth = 0
backgroundHolder.layer.masksToBounds = true
background.contentMode = UIViewContentMode.scaleAspectFill
background.isUserInteractionEnabled = false
background.layer.masksToBounds = true
background.alignLeft = true
background.alignTop = true
favicon.layer.cornerRadius = 2.0
favicon.layer.masksToBounds = true
titleLbl = UILabel()
titleLbl.backgroundColor = .clear
titleLbl.textAlignment = NSTextAlignment.left
titleLbl.isUserInteractionEnabled = false
titleLbl.numberOfLines = 1
titleLbl.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold
closeButton = UIButton()
closeButton.setImage(UIImage(named: "close"), for: .normal)
closeButton.tintColor = BraveUX.GreyG
titleWrapperBackground.backgroundColor = UIColor.white
titleWrapper.backgroundColor = .clear
titleWrapper.addSubview(titleWrapperBackground)
titleWrapper.addSubview(closeButton)
titleWrapper.addSubview(titleLbl)
titleWrapper.addSubview(favicon)
super.init(frame: frame)
closeButton.addTarget(self, action: #selector(TabCell.SELclose), for: UIControlEvents.touchUpInside)
contentView.clipsToBounds = false
clipsToBounds = false
animator = SwipeAnimator(animatingView: shadowView, container: self)
shadowView.addSubview(backgroundHolder)
backgroundHolder.addSubview(background)
backgroundHolder.addSubview(titleWrapper)
contentView.addSubview(shadowView)
placeholderFavicon.layer.cornerRadius = 8.0
placeholderFavicon.layer.masksToBounds = true
backgroundHolder.addSubview(placeholderFavicon)
setupConstraints()
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: Strings.Close, target: animator, selector: #selector(SELclose))
]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupConstraints() {
let generalOffset = 4
shadowView.snp.remakeConstraints { make in
make.edges.equalTo(shadowView.superview!)
}
backgroundHolder.snp.remakeConstraints { make in
make.edges.equalTo(backgroundHolder.superview!)
}
background.snp.remakeConstraints { make in
make.edges.equalTo(background.superview!)
}
placeholderFavicon.snp.remakeConstraints { make in
make.size.equalTo(CGSize(width: 60, height: 60))
make.center.equalTo(placeholderFavicon.superview!)
}
favicon.snp.remakeConstraints { make in
make.top.left.equalTo(favicon.superview!).offset(generalOffset)
make.size.equalTo(titleWrapper.snp.height).offset(-generalOffset * 2)
}
titleWrapper.snp.remakeConstraints { make in
make.left.top.equalTo(titleWrapper.superview!)
make.width.equalTo(titleWrapper.superview!.snp.width)
make.height.equalTo(TabTrayControllerUX.TitleBoxHeight)
}
titleWrapperBackground.snp.remakeConstraints { make in
make.top.left.right.equalTo(titleWrapperBackground.superview!)
make.height.equalTo(TabTrayControllerUX.TitleBoxHeight + 15)
}
titleLbl.snp.remakeConstraints { make in
make.left.equalTo(favicon.snp.right).offset(generalOffset)
make.right.equalTo(closeButton.snp.left).offset(generalOffset)
make.top.bottom.equalTo(titleLbl.superview!)
}
closeButton.snp.remakeConstraints { make in
make.size.equalTo(titleWrapper.snp.height)
make.centerY.equalTo(titleWrapper)
make.right.equalTo(closeButton.superview!)
}
}
override func layoutSubviews() {
super.layoutSubviews()
// Frames do not seem to update until next runloop cycle
DispatchQueue.main.async {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.titleWrapperBackground.bounds
gradientLayer.colors = [UIColor(white: 1.0, alpha: 0.98).cgColor, UIColor(white: 1.0, alpha: 0.9).cgColor, UIColor.clear.cgColor]
self.titleWrapperBackground.layer.mask = gradientLayer
}
}
override func prepareForReuse() {
// TODO: Move more of this to cellForItem
// Reset any close animations.
backgroundHolder.layer.borderColor = UIColor(white: 0.0, alpha: 0.15).cgColor
backgroundHolder.layer.borderWidth = 1
shadowView.alpha = 1
shadowView.transform = CGAffineTransform.identity
shadowView.layer.shadowOpacity = 0
background.image = nil
placeholderFavicon.isHidden = true
placeholderFavicon.image = nil
favicon.image = nil
titleLbl.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold
}
override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool {
animator.close(direction == .right)
return true
}
@objc
func SELclose() {
self.animator.SELcloseWithoutGesture()
}
}
struct PrivateModeStrings {
static let toggleAccessibilityLabel = Strings.Private_Mode
static let toggleAccessibilityHint = Strings.Turns_private_mode_on_or_off
static let toggleAccessibilityValueOn = Strings.On
static let toggleAccessibilityValueOff = Strings.Off
}
protocol TabTrayDelegate: class {
func tabTrayDidDismiss(_ tabTray: TabTrayController)
func tabTrayDidAddBookmark(_ tab: Browser)
func tabTrayDidAddToReadingList(_ tab: Browser) -> ReadingListClientRecord?
func tabTrayRequestsPresentationOf(_ viewController: UIViewController)
}
class TabTrayController: UIViewController {
let tabManager: TabManager
let profile: Profile
weak var delegate: TabTrayDelegate?
var collectionView: UICollectionView!
lazy var addTabButton: UIButton = {
let addTabButton = UIButton()
addTabButton.setImage(UIImage(named: "add")?.withRenderingMode(.alwaysTemplate), for: .normal)
addTabButton.addTarget(self, action: #selector(TabTrayController.SELdidClickAddTab), for: .touchUpInside)
addTabButton.accessibilityLabel = Strings.Add_Tab
addTabButton.accessibilityIdentifier = "TabTrayController.addTabButton"
return addTabButton
}()
var collectionViewTransitionSnapshot: UIView?
/// Views to be animationed when preseting the Tab Tray.
/// There is some bug related to the blurring background the tray controller attempts to handle.
/// On animating self.view the blur effect will not animate (just pops in at the animation end),
/// and must be animated manually. Instead of animating the larger view elements, smaller pieces
/// must be animated in order to achieve a blur-incoming animation
var viewsToAnimate: [UIView] = []
fileprivate(set) internal var privateMode: Bool = false {
didSet {
if privateMode {
togglePrivateMode.isSelected = true
togglePrivateMode.accessibilityValue = PrivateModeStrings.toggleAccessibilityValueOn
togglePrivateMode.backgroundColor = .white
addTabButton.tintColor = UIColor.white
blurBackdropView.effect = UIBlurEffect(style: .dark)
} else {
togglePrivateMode.isSelected = false
togglePrivateMode.accessibilityValue = PrivateModeStrings.toggleAccessibilityValueOff
togglePrivateMode.backgroundColor = .clear
addTabButton.tintColor = BraveUX.GreyI
blurBackdropView.effect = UIBlurEffect(style: .light)
}
tabDataSource.updateData()
collectionView?.reloadData()
}
}
fileprivate var tabsToDisplay: [Browser] {
return tabManager.tabs.displayedTabsForCurrentPrivateMode
}
lazy var togglePrivateMode: UIButton = {
let button = UIButton()
button.setTitle(Strings.Private, for: .normal)
button.setTitleColor(BraveUX.GreyI, for: .normal)
button.titleLabel!.font = UIFont.systemFont(ofSize: button.titleLabel!.font.pointSize + 1, weight: UIFontWeightMedium)
button.contentEdgeInsets = UIEdgeInsetsMake(0, 4 /* left */, 0, 4 /* right */)
button.layer.cornerRadius = 4.0
button.addTarget(self, action: #selector(TabTrayController.SELdidTogglePrivateMode), for: .touchUpInside)
button.accessibilityLabel = PrivateModeStrings.toggleAccessibilityLabel
button.accessibilityHint = PrivateModeStrings.toggleAccessibilityHint
button.accessibilityIdentifier = "TabTrayController.togglePrivateMode"
return button
}()
lazy var doneButton: UIButton = {
let button = UIButton()
button.setTitle(Strings.Done, for: .normal)
button.setTitleColor(BraveUX.GreyI, for: .normal)
button.titleLabel!.font = UIFont.systemFont(ofSize: button.titleLabel!.font.pointSize + 1, weight: UIFontWeightRegular)
button.contentEdgeInsets = UIEdgeInsetsMake(0, 4 /* left */, 0, 4 /* right */)
button.layer.cornerRadius = 4.0
button.addTarget(self, action: #selector(TabTrayController.SELdidTapDoneButton), for: .touchUpInside)
button.accessibilityIdentifier = "TabTrayController.doneButton"
return button
}()
fileprivate var blurBackdropView = UIVisualEffectView()
fileprivate lazy var emptyPrivateTabsView: UIView = {
return self.newEmptyPrivateTabsView()
}()
fileprivate lazy var tabDataSource: TabManagerDataSource = {
return TabManagerDataSource(cellDelegate: self)
}()
fileprivate lazy var tabLayoutDelegate: TabLayoutDelegate = {
let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection)
delegate.tabSelectionDelegate = self
return delegate
}()
override func dismiss(animated flag: Bool, completion: (() -> Void)?) {
super.dismiss(animated: flag, completion:completion)
UIView.animate(withDuration: 0.2, animations: {
getApp().browserViewController.toolbar?.leavingTabTrayMode()
})
getApp().browserViewController.updateTabCountUsingTabManager(getApp().tabManager)
}
init(tabManager: TabManager, profile: Profile) {
self.tabManager = tabManager
self.profile = profile
super.init(nibName: nil, bundle: nil)
tabManager.addDelegate(self)
}
convenience init(tabManager: TabManager, profile: Profile, tabTrayDelegate: TabTrayDelegate) {
self.init(tabManager: tabManager, profile: profile)
self.delegate = tabTrayDelegate
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
self.tabManager.removeDelegate(self)
}
func SELDynamicFontChanged(_ notification: Notification) {
guard notification.name == NotificationDynamicFontChanged else { return }
self.collectionView.reloadData()
}
@objc func onTappedBackground(_ gesture: UITapGestureRecognizer) {
dismiss(animated: true, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
// TODO: centralize timing
UIView.animate(withDuration: 0.2, animations: {
self.viewsToAnimate.forEach { $0.alpha = 1.0 }
})
let tabs = WeakList<Browser>()
getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.forEach {
tabs.insert($0)
}
guard let selectedTab = tabManager.selectedTab else { return }
let selectedIndex = tabs.index(of: selectedTab) ?? 0
self.collectionView.scrollToItem(at: IndexPath(item: selectedIndex, section: 0), at: UICollectionViewScrollPosition.centeredVertically, animated: false)
}
// MARK: View Controller Callbacks
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = Strings.Tabs_Tray
let flowLayout = TabTrayCollectionViewLayout()
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout)
collectionView.dataSource = tabDataSource
collectionView.delegate = tabLayoutDelegate
collectionView.register(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier)
collectionView.backgroundColor = UIColor.clear
// Background view created for tapping background closure
collectionView.backgroundView = UIView()
collectionView.backgroundView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(TabTrayController.onTappedBackground(_:))))
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture(gesture:)))
longPressGesture.minimumPressDuration = 0.2
collectionView.addGestureRecognizer(longPressGesture)
viewsToAnimate = [blurBackdropView, collectionView, addTabButton, togglePrivateMode, doneButton]
viewsToAnimate.forEach {
$0.alpha = 0.0
view.addSubview($0)
}
makeConstraints()
if profile.prefs.boolForKey(kPrefKeyPrivateBrowsingAlwaysOn) ?? false {
togglePrivateMode.isHidden = true
}
view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView)
emptyPrivateTabsView.alpha = privateTabsAreEmpty() ? 1 : 0
emptyPrivateTabsView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
// Make sure buttons are all setup before this, to allow
// privateMode setter to setup final visuals
let selectedTabIsPrivate = tabManager.selectedTab?.isPrivate ?? false
privateMode = PrivateBrowsing.singleton.isOn || selectedTabIsPrivate
doneButton.setTitleColor(privateMode ? BraveUX.GreyG : BraveUX.GreyG, for: .normal)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELappWillResignActiveNotification), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELappDidBecomeActiveNotification), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
}
func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case UIGestureRecognizerState.began:
guard let selectedIndexPath = self.collectionView.indexPathForItem(at: gesture.location(in: self.collectionView)) else {
break
}
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case UIGestureRecognizerState.changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case UIGestureRecognizerState.ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Update the trait collection we reference in our layout delegate
tabLayoutDelegate.traitCollection = traitCollection
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// Used to update the glow effect on the selected tab
// and update screenshot framing/positioning
// Must be scheduled on next runloop
DispatchQueue.main.async {
self.collectionView.reloadData()
}
coordinator.animate(alongsideTransition: { _ in
self.collectionView.collectionViewLayout.invalidateLayout()
}, completion: nil)
}
fileprivate func makeConstraints() {
if UIDevice.current.userInterfaceIdiom == .phone {
doneButton.snp.makeConstraints { make in
if #available(iOS 11.0, *) {
make.right.equalTo(self.view.safeAreaLayoutGuide.snp.right).offset(-30)
} else {
make.right.equalTo(self.view).offset(-30)
}
make.centerY.equalTo(self.addTabButton.snp.centerY)
}
togglePrivateMode.snp.makeConstraints { make in
if #available(iOS 11.0, *) {
make.left.equalTo(self.view.safeAreaLayoutGuide.snp.left).offset(30)
} else {
make.left.equalTo(30)
}
make.centerY.equalTo(self.addTabButton.snp.centerY)
}
addTabButton.snp.makeConstraints { make in
if #available(iOS 11.0, *) {
make.bottom.equalTo(self.view).inset(getApp().window?.safeAreaInsets.bottom ?? 0)
} else {
make.bottom.equalTo(self.view)
}
make.centerX.equalTo(self.view)
make.size.equalTo(UIConstants.ToolbarHeight)
}
collectionView.snp.makeConstraints { make in
make.bottom.equalTo(addTabButton.snp.top)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
if #available(iOS 11.0, *) {
make.left.equalTo(self.view.safeAreaLayoutGuide.snp.left)
make.right.equalTo(self.view.safeAreaLayoutGuide.snp.right)
} else {
make.left.right.equalTo(self.view)
}
}
blurBackdropView.snp.makeConstraints { (make) in
make.edges.equalTo(view)
}
}
else {
doneButton.isHidden = true
togglePrivateMode.snp.makeConstraints { make in
make.right.equalTo(addTabButton.snp.left).offset(-10)
make.centerY.equalTo(self.addTabButton.snp.centerY)
}
addTabButton.snp.makeConstraints { make in
make.trailing.equalTo(self.view)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
make.size.equalTo(UIConstants.ToolbarHeight)
}
collectionView.snp.makeConstraints { make in
make.top.equalTo(addTabButton.snp.bottom)
make.left.right.bottom.equalTo(self.view)
}
blurBackdropView.snp.makeConstraints { (make) in
make.edges.equalTo(view)
}
}
}
// View we display when there are no private tabs created
fileprivate func newEmptyPrivateTabsView() -> UIView {
let emptyView = UIView()
emptyView.backgroundColor = BraveUX.GreyI
return emptyView
}
// MARK: Selectors
func SELdidTapDoneButton() {
self.dismiss(animated: true, completion: nil)
}
func SELdidClickAddTab() {
openNewTab()
}
func SELdidTogglePrivateMode() {
let fromView: UIView
if privateTabsAreEmpty() {
fromView = emptyPrivateTabsView
} else {
let snapshot = collectionView.snapshotView(afterScreenUpdates: false)
snapshot!.frame = collectionView.frame
view.insertSubview(snapshot!, aboveSubview: collectionView)
fromView = snapshot!
}
privateMode = !privateMode
doneButton.setTitleColor(privateMode ? BraveUX.GreyG : BraveUX.GreyG, for: .normal)
if privateMode {
PrivateBrowsing.singleton.enter()
} else {
view.isUserInteractionEnabled = false
let activityView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityView.center = view.center
activityView.startAnimating()
self.view.addSubview(activityView)
PrivateBrowsing.singleton.exit().uponQueue(DispatchQueue.main) {
self.view.isUserInteractionEnabled = true
activityView.stopAnimating()
}
}
tabDataSource.updateData()
collectionView.layoutSubviews()
let scaleDownTransform = CGAffineTransform(scaleX: 0.9, y: 0.9)
let toView = privateTabsAreEmpty() ? emptyPrivateTabsView : collectionView
toView.transform = scaleDownTransform
toView.alpha = 0
UIView.animate(withDuration: 0.4, delay: 0, options: [], animations: { () -> Void in
fromView.alpha = 0
toView.transform = CGAffineTransform.identity
toView.alpha = 1
}) { finished in
if fromView != self.emptyPrivateTabsView {
fromView.removeFromSuperview()
}
if self.privateMode {
self.openNewTab()
}
}
}
fileprivate func privateTabsAreEmpty() -> Bool {
return privateMode && tabManager.tabs.privateTabs.count == 0
}
func changePrivacyMode(_ isPrivate: Bool) {
if isPrivate != privateMode {
guard let _ = collectionView else {
privateMode = isPrivate
return
}
SELdidTogglePrivateMode()
}
}
fileprivate func openNewTab(_ request: URLRequest? = nil) {
if privateMode {
emptyPrivateTabsView.isHidden = true
}
// We're only doing one update here, but using a batch update lets us delay selecting the tab
// until after its insert animation finishes.
self.collectionView.performBatchUpdates({ _ in
// TODO: This logic seems kind of finicky
var tab: Browser?
let id = TabMO.freshTab().syncUUID
tab = self.tabManager.addTab(request, id: id)
tab?.tabID = id
if let tab = tab {
self.tabManager.selectTab(tab)
}
}, completion: { finished in
if finished {
self.dismiss(animated: true, completion: {
let app = UIApplication.shared.delegate as! AppDelegate
app.browserViewController.urlBar.browserLocationViewDidTapLocation(app.browserViewController.urlBar.locationView)
})
}
})
}
}
// MARK: - App Notifications
extension TabTrayController {
func SELappWillResignActiveNotification() {
if privateMode {
collectionView.alpha = 0
}
}
func SELappDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: {
self.collectionView.alpha = 1
},
completion: nil)
}
}
extension TabTrayController: TabSelectionDelegate {
func didSelectTabAtIndex(_ index: Int) {
let tab = tabsToDisplay[index]
tabManager.selectTab(tab)
self.dismiss(animated: true, completion: nil)
}
}
extension TabTrayController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) {
dismiss(animated: animated, completion: { self.collectionView.reloadData() })
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Browser?) {
}
func tabManager(_ tabManager: TabManager, didCreateWebView tab: Browser, url: URL?, at: Int?) {
}
func tabManager(_ tabManager: TabManager, didAddTab tab: Browser) {
// Get the index of the added tab from it's set (private or normal)
guard let index = tabsToDisplay.index(of: tab) else { return }
tabDataSource.updateData()
self.collectionView?.performBatchUpdates({ _ in
self.collectionView.insertItems(at: [IndexPath(item: index, section: 0)])
}, completion: { finished in
if finished {
tabManager.selectTab(tab)
// don't pop the tab tray view controller if it is not in the foreground
if self.presentedViewController == nil {
self.dismiss(animated: true, completion: nil)
}
}
})
}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Browser) {
var removedIndex = -1
for i in 0..<tabDataSource.tabList.count() {
let tabRef = tabDataSource.tabList.at(i)
if tabRef == nil || getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.index(of: tabRef!) == nil {
removedIndex = i
break
}
}
tabDataSource.updateData()
if (removedIndex < 0) {
return
}
self.collectionView.deleteItems(at: [IndexPath(item: removedIndex, section: 0)])
if privateTabsAreEmpty() {
emptyPrivateTabsView.alpha = 1
}
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {
}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatus(for scrollView: UIScrollView) -> String? {
var visibleCells = collectionView.visibleCells as! [TabCell]
var bounds = collectionView.bounds
bounds = bounds.offsetBy(dx: collectionView.contentInset.left, dy: collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !$0.frame.intersection(bounds).isEmpty }
let cells = visibleCells.map { self.collectionView.indexPath(for: $0)! }
let indexPaths = cells.sorted { (a: IndexPath, b: IndexPath) -> Bool in
return a.section < b.section || (a.section == b.section && a.row < b.row)
}
if indexPaths.count == 0 {
return Strings.No_tabs
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItems(inSection: 0)
if (firstTab == lastTab) {
let format = Strings.Tab_xofx_template
return String(format: format, NSNumber(value: firstTab), NSNumber(value: tabCount))
} else {
let format = Strings.Tabs_xtoxofx_template
return String(format: format, NSNumber(value: firstTab), NSNumber(value: lastTab), NSNumber(value: tabCount))
}
}
}
fileprivate func removeTabUtil(_ tabManager: TabManager, tab: Browser) {
let isAlwaysPrivate = getApp().profile?.prefs.boolForKey(kPrefKeyPrivateBrowsingAlwaysOn) ?? false
let createIfNone = true
tabManager.removeTab(tab, createTabIfNoneLeft: createIfNone)
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(_ animator: SwipeAnimator, viewWillExitContainerBounds: UIView) {
let tabCell = animator.container as! TabCell
if let indexPath = collectionView.indexPath(for: tabCell) {
let tab = tabsToDisplay[indexPath.item]
removeTabUtil(tabManager, tab: tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, Strings.Closing_tab)
}
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(_ cell: TabCell) {
let indexPath = collectionView.indexPath(for: cell)!
let tab = tabsToDisplay[indexPath.item]
removeTabUtil(tabManager, tab: tab)
}
}
extension TabTrayController: SettingsDelegate {
func settingsOpenURLInNewTab(_ url: URL) {
let request = URLRequest(url: url)
openNewTab(request)
}
}
fileprivate class TabManagerDataSource: NSObject, UICollectionViewDataSource {
unowned var cellDelegate: TabCellDelegate & SwipeAnimatorDelegate
fileprivate var tabList = WeakList<Browser>()
init(cellDelegate: TabCellDelegate & SwipeAnimatorDelegate) {
self.cellDelegate = cellDelegate
super.init()
getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.forEach {
tabList.insert($0)
}
}
func updateData() {
tabList = WeakList<Browser>()
getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.forEach {
tabList.insert($0)
}
}
@objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let tabCell = collectionView.dequeueReusableCell(withReuseIdentifier: TabCell.Identifier, for: indexPath) as! TabCell
tabCell.animator.delegate = cellDelegate
tabCell.delegate = cellDelegate
guard let tab = tabList.at(indexPath.item) else {
assert(false)
return tabCell
}
let title = tab.displayTitle
tabCell.titleLbl.text = title
if !title.isEmpty {
tabCell.accessibilityLabel = title
} else {
tabCell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url)
}
tabCell.isAccessibilityElement = true
tabCell.accessibilityHint = Strings.Swipe_right_or_left_with_three_fingers_to_close_the_tab
tabCell.favicon.backgroundColor = BraveUX.TabTrayCellBackgroundColor
tab.screenshot(callback: { (image) in
tabCell.background.image = image
})
tabCell.placeholderFavicon.isHidden = tab.isScreenshotSet
if tab.isHomePanel {
tabCell.favicon.isHidden = true
} else {
// Fetching favicon
if let tabMO = TabMO.get(byId: tab.tabID, context: .workerThreadContext), let urlString = tabMO.url, let url = URL(string: urlString) {
weak var weakSelf = self
if ImageCache.shared.hasImage(url, type: .square) {
// no relationship - check cache for icon which may have been stored recently for url.
ImageCache.shared.image(url, type: .square, callback: { (image) in
postAsyncToMain {
tabCell.favicon.image = image
tabCell.placeholderFavicon.image = image
}
})
}
else {
// no relationship - attempt to resolove domain problem
let context = DataController.shared.mainThreadContext
if let domain = Domain.getOrCreateForUrl(url, context: context), let faviconMO = domain.favicon, let urlString = faviconMO.url, let faviconurl = URL(string: urlString) {
postAsyncToMain {
weakSelf?.setCellImage(tabCell, iconUrl: faviconurl, cacheWithUrl: url)
}
}
else {
// last resort - download the icon
downloadFaviconsAndUpdateForUrl(url, collectionView: collectionView, indexPath: indexPath)
}
}
}
}
// TODO: Move most view logic here instead of `init` or `prepareForReuse`
// If the current tab add heightlighting
if getApp().tabManager.selectedTab == tab {
tabCell.backgroundHolder.layer.borderColor = BraveUX.LightBlue.withAlphaComponent(0.75).cgColor
tabCell.backgroundHolder.layer.borderWidth = 1
tabCell.shadowView.layer.shadowRadius = 5
tabCell.shadowView.layer.shadowColor = BraveUX.LightBlue.cgColor
tabCell.shadowView.layer.shadowOpacity = 1.0
tabCell.shadowView.layer.shadowOffset = CGSize(width: 0, height: 0)
tabCell.shadowView.layer.shadowPath = UIBezierPath(roundedRect: tabCell.bounds, cornerRadius: tabCell.backgroundHolder.layer.cornerRadius).cgPath
tabCell.background.alpha = 1.0
} else {
tabCell.backgroundHolder.layer.borderWidth = 0
tabCell.shadowView.layer.shadowRadius = 2
tabCell.shadowView.layer.shadowColor = UIColor(white: 0.0, alpha: 0.15).cgColor
tabCell.shadowView.layer.shadowOpacity = 1.0
tabCell.shadowView.layer.shadowOffset = CGSize(width: 0, height: 0)
tabCell.shadowView.layer.shadowPath = UIBezierPath(roundedRect: tabCell.bounds, cornerRadius: tabCell.backgroundHolder.layer.cornerRadius).cgPath
tabCell.background.alpha = 0.7
}
return tabCell
}
fileprivate func downloadFaviconsAndUpdateForUrl(_ url: URL, collectionView: UICollectionView, indexPath: IndexPath) {
weak var weakSelf = self
FaviconFetcher.getForURL(url).uponQueue(DispatchQueue.main) { result in
guard let favicons = result.successValue, favicons.count > 0, let foundIconUrl = favicons.first?.url.asURL, let cell = collectionView.cellForItem(at: indexPath) as? TabCell else { return }
weakSelf?.setCellImage(cell, iconUrl: foundIconUrl, cacheWithUrl: url)
}
}
fileprivate func setCellImage(_ cell: TabCell, iconUrl: URL, cacheWithUrl: URL) {
ImageCache.shared.image(cacheWithUrl, type: .square, callback: { (image) in
if image != nil {
postAsyncToMain {
cell.placeholderFavicon.image = image
cell.favicon.image = image
}
}
else {
postAsyncToMain {
cell.placeholderFavicon.sd_setImage(with: iconUrl, completed: { (img, err, type, url) in
guard err == nil, let img = img else {
// avoid retrying to find an icon when none can be found, hack skips FaviconFetch
ImageCache.shared.cache(FaviconFetcher.defaultFavicon, url: cacheWithUrl, type: .square, callback: nil)
cell.placeholderFavicon.image = FaviconFetcher.defaultFavicon
return
}
ImageCache.shared.cache(img, url: cacheWithUrl, type: .square, callback: nil)
cell.favicon.image = img
})
}
}
})
}
// fileprivate func getImageColor(image: UIImage) -> UIColor? {
// let rgba = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4)
// let colorSpace = CGColorSpaceCreateDeviceRGB()
// let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
// let context: CGContext = CGContext(data: rgba, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: info.rawValue)!
//
// guard let newImage = image.cgImage else { return nil }
// context.draw(newImage, in: CGRect(x: 0, y: 0, width: 1, height: 1))
//
// // Has issues, often sets background to black. experimenting without box for now.
// let red = CGFloat(rgba[0]) / 255.0
// let green = CGFloat(rgba[1]) / 255.0
// let blue = CGFloat(rgba[2]) / 255.0
// let colorFill: UIColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
//
// return colorFill
// }
@objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabList.count()
}
@objc func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}
@objc func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard let tab = tabList.at(sourceIndexPath.row) else { return }
// Find original from/to index... we need to target the full list not partial.
guard let tabManager = getApp().tabManager else { return }
guard let from = tabManager.tabs.tabs.index(where: {$0 === tab}) else { return }
let toTab = tabList.at(destinationIndexPath.row)
guard let to = tabManager.tabs.tabs.index(where: {$0 === toTab}) else { return }
tabManager.move(tab: tab, from: from, to: to)
updateData()
NotificationCenter.default.post(name: kRearangeTabNotification, object: nil)
}
}
@objc protocol TabSelectionDelegate: class {
func didSelectTabAtIndex(_ index :Int)
}
fileprivate class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout {
weak var tabSelectionDelegate: TabSelectionDelegate?
fileprivate var traitCollection: UITraitCollection
fileprivate var profile: Profile
fileprivate var numberOfColumns: Int {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
init(profile: Profile, traitCollection: UITraitCollection) {
self.profile = profile
self.traitCollection = traitCollection
super.init()
}
fileprivate func cellHeightForCurrentDevice() -> CGFloat {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
let shortHeight = TabTrayControllerUX.TitleBoxHeight * (compactLayout ? 7 : 6)
if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.compact {
return rint(UIScreen.main.bounds.height / 3)
} else {
return TabTrayControllerUX.TitleBoxHeight * 8
}
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellWidth = floor((collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns))
return CGSize(width: cellWidth, height: self.cellHeightForCurrentDevice())
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
}
// There seems to be a bug with UIKit where when the UICollectionView changes its contentSize
// from > frame.size to <= frame.size: the contentSet animation doesn't properly happen and 'jumps' to the
// final state.
// This workaround forces the contentSize to always be larger than the frame size so the animation happens more
// smoothly. This also makes the tabs be able to 'bounce' when there are not enough to fill the screen, which I
// think is fine, but if needed we can disable user scrolling in this case.
fileprivate class TabTrayCollectionViewLayout: UICollectionViewFlowLayout {
fileprivate override var collectionViewContentSize : CGSize {
var calculatedSize = super.collectionViewContentSize
let collectionViewHeight = collectionView?.bounds.size.height ?? 0
if calculatedSize.height < collectionViewHeight && collectionViewHeight > 0 {
calculatedSize.height = collectionViewHeight + 1
}
return calculatedSize
}
}
struct EmptyPrivateTabsViewUX {
static let TitleColor = UIColor.white
static let TitleFont = UIFont.systemFont(ofSize: 22, weight: UIFontWeightMedium)
static let DescriptionColor = UIColor.white
static let DescriptionFont = UIFont.systemFont(ofSize: 17)
static let LearnMoreFont = UIFont.systemFont(ofSize: 15, weight: UIFontWeightMedium)
static let TextMargin: CGFloat = 18
static let LearnMoreMargin: CGFloat = 30
static let MaxDescriptionWidth: CGFloat = 250
}
|
mpl-2.0
|
e4dbc73b9900ea018e3d3756a4d39245
| 40.33395 | 200 | 0.657513 | 5.450354 | false | false | false | false |
ohwutup/ReactiveCocoa
|
ReactiveCocoaTests/UIKit/UISwitchSpec.swift
|
1
|
1614
|
import Quick
import Nimble
import ReactiveSwift
import ReactiveCocoa
import Result
class UISwitchSpec: QuickSpec {
override func spec() {
var toggle: UISwitch!
weak var _toggle: UISwitch?
beforeEach {
toggle = UISwitch(frame: .zero)
_toggle = toggle
}
afterEach {
toggle = nil
expect(_toggle).to(beNil())
}
it("should accept changes from bindings to its `isOn` state") {
toggle.isOn = false
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
toggle.reactive.isOn <~ SignalProducer(pipeSignal)
observer.send(value: true)
expect(toggle.isOn) == true
observer.send(value: false)
expect(toggle.isOn) == false
}
it("should emit user initiated changes to its `isOn` state") {
var latestValue: Bool?
toggle.reactive.isOnValues.observeValues { latestValue = $0 }
toggle.isOn = true
toggle.sendActions(for: .valueChanged)
expect(latestValue!) == true
}
it("should execute the `toggled` action upon receiving a `valueChanged` action message.") {
toggle.isOn = false
toggle.isEnabled = true
toggle.isUserInteractionEnabled = true
let isOn = MutableProperty(false)
let action = Action<Bool, Bool, NoError> { isOn in
return SignalProducer(value: isOn)
}
isOn <~ SignalProducer(action.values)
toggle.reactive.toggled = CocoaAction(action) { return $0.isOn }
expect(isOn.value) == false
toggle.isOn = true
toggle.sendActions(for: .valueChanged)
expect(isOn.value) == true
toggle.isOn = false
toggle.sendActions(for: .valueChanged)
expect(isOn.value) == false
}
}
}
|
mit
|
249fe6f627d5e33c9e1070433e5af444
| 22.391304 | 93 | 0.685254 | 3.676538 | false | false | false | false |
Yalantis/PixPic
|
PixPic/Classes/ViewModels/PostAdapter.swift
|
1
|
3063
|
//
// PostDataSource.swift
// PixPic
//
// Created by Jack Lapin on 17.01.16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import Foundation
public enum UpdateType {
case Reload, LoadMore
}
@objc protocol PostAdapterDelegate: class {
optional func showUserProfile(adapter: PostAdapter, user: User)
func showPlaceholderForEmptyDataSet(adapter: PostAdapter)
func postAdapterRequestedViewUpdate(adapter: PostAdapter)
func showSettingsMenu(adapter: PostAdapter, post: Post, index: Int, items: [AnyObject])
}
class PostAdapter: NSObject {
private var posts = [Post]() {
didSet {
delegate?.showPlaceholderForEmptyDataSet(self)
delegate?.postAdapterRequestedViewUpdate(self)
}
}
weak var delegate: PostAdapterDelegate?
private var locator: ServiceLocator
init(locator: ServiceLocator) {
self.locator = locator
}
var postQuantity: Int {
return posts.count
}
func update(withPosts posts: [Post], action: UpdateType) {
switch action {
case .Reload:
self.posts.removeAll()
default:
break
}
self.posts.appendContentsOf(posts)
}
func getPost(atIndexPath indexPath: NSIndexPath) -> Post {
let post = posts[indexPath.row]
return post
}
func getPostIndexPath(postId: String) -> NSIndexPath? {
for i in 0..<posts.count {
if posts[i].objectId == postId {
return NSIndexPath(forRow: i, inSection: 0)
}
}
return nil
}
func removePost(atIndex index: Int) {
posts.removeAtIndex(index)
}
}
extension PostAdapter: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postQuantity
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(
PostViewCell.id,
forIndexPath: indexPath
) as! PostViewCell
let post = getPost(atIndexPath: indexPath)
cell.configure(with: post, locator: locator)
cell.didSelectUser = { [weak self] cell in
guard let this = self else {
return
}
if let path = tableView.indexPathForCell(cell) {
let post = this.getPost(atIndexPath: path)
if let user = post.user {
this.delegate?.showUserProfile?(this, user: user)
}
}
}
cell.didSelectSettings = { [weak self] cell, items in
guard let this = self else {
return
}
if let path = tableView.indexPathForCell(cell) {
let post = this.getPost(atIndexPath: path)
this.delegate?.showSettingsMenu(this, post: post, index: path.row, items: items)
}
}
return cell
}
}
|
mit
|
b66ea236520ad90073ca1f3eec8a7efc
| 24.949153 | 109 | 0.599935 | 4.710769 | false | false | false | false |
wendru/simple-twitter-client
|
Twittah/User.swift
|
1
|
2536
|
//
// User.swift
// Twittah
//
// Created by Andrew Wen on 2/22/15.
// Copyright (c) 2015 wendru. All rights reserved.
//
import UIKit
var _currentUser: User?
let currentUserKey = "kCurrentUserKey"
let userDidLoginNotification = "userDidLoginNotification"
let userDidLogoutNotification = "userDidLogoutNotification"
class User: NSObject {
var name: String?
var screenname: String?
var profileImageUrl: String?
var profileBackgroundImageUrl: String?
var tagline: String?
var location: String?
var dictionary: NSDictionary
var followingsCount: Int?
var followersCount: Int?
var tweetsCount: Int?
init(dict: NSDictionary) {
self.dictionary = dict
name = dict["name"] as? String
screenname = dict["screen_name"] as? String
profileImageUrl = dict["profile_image_url"] as? String
profileBackgroundImageUrl = dict["profile_background_image_url"] as? String
location = dict["location"] as? String
tagline = dict["description"] as? String
followingsCount = dict["friends_count"] as? Int
followersCount = dict["followers_count"] as? Int
tweetsCount = dict["statuses_count"] as? Int
}
func logout() {
User.currentUser = nil
TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
NSNotificationCenter.defaultCenter().postNotificationName(userDidLogoutNotification, object: nil)
}
class var currentUser: User? {
get {
if _currentUser == nil {
var data = NSUserDefaults.standardUserDefaults().objectForKey(currentUserKey) as? NSData
if data != nil {
var dict = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSDictionary
_currentUser = User(dict: dict)
}
}
return _currentUser
} set(user) {
_currentUser = user
if _currentUser != nil {
var data = NSJSONSerialization.dataWithJSONObject(
user!.dictionary,
options: nil,
error: nil)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: currentUserKey)
} else {
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: currentUserKey)
}
NSUserDefaults.standardUserDefaults().synchronize()
}
}
}
|
gpl-2.0
|
f9de686729884ea56545b132c51a0377
| 32.368421 | 118 | 0.608044 | 5.261411 | false | false | false | false |
gregstula/gol-rvb
|
oop-gol/LifeGenSwift/GoLGrid.swift
|
3
|
4895
|
//
// GOLGridController.swift
// LifeGenSwift
//
// Created by Gregory D. Stula on 8/30/15.
// Copyright (c) 2015 Gregory D. Stula. All rights reserved.
//
import Foundation
import UIKit
final class GOLGrid {
// MARK: Properties
let rowMax:Int
let colMax:Int
var useColoredGOLCells:Bool = false
var generationCount = 0
private var cellsKnowTheirPosition:Bool = false
let cellGrid:LiteMatrix<GOLCell>
// Mark: Init
init (rowSize:Int, columnSize colSize:Int) {
rowMax = rowSize
colMax = colSize
cellGrid = LiteMatrix<GOLCell>(rows: rowSize, columns: colSize)
for i in 0 ..< rowMax {
for j in 0 ..< colMax {
cellGrid[i,j] = GOLCell()
}
}
}
// MARK: Neighbor counting
private func countNeighbors(cell:GOLCell) {
cell.numberOfNeighbors = 0
cell.resetNeighborColorCount()
// Prevents index out of bounds for special case of row/col = 0.
if cell.coordinates.row < 1 || cell.coordinates.col < 1 {
return
// Prevents index out of bounds for special case of *MAX - 1
} else if cell.coordinates.row > rowMax - 2 || cell.coordinates.col > colMax - 2 {
return
}
// Normal case
for rowOffset in (-1...1) {
for colOffset in (-1...1) {
if (rowOffset != 0 || colOffset != 0) {
if (neighborAliveAt(cell, rowOffset, colOffset)) {
cell.numberOfNeighbors += 1
countNeighborByColor(cell, rowOffset, colOffset);
}
}
}
}
}
// Helper Method for looking up alive status of Neighbors
func neighborAliveAt(cell:GOLCell, _ rowOffset:Int, _ colOffset:Int) -> Bool {
return cellGrid[cell.coordinates.row + rowOffset, cell.coordinates.col + colOffset].isAlive
}
// Helper method for counting color cells
private func countNeighborByColor(cell:GOLCell, _ rowOffset:Int, _ colOffset:Int) {
let neighbor = cellGrid[cell.coordinates.row + rowOffset, cell.coordinates.col + colOffset]
if neighbor.spawnColor == .blue {
cell.blueNeighbors += 1
} else if neighbor.spawnColor == .red {
cell.redNeighbors += 1
}
}
// Mark: Cell Methods
// Calculates the next action of a cell
func calculateNextAction(cell:GOLCell) {
countNeighbors(cell)
if cell.isAlive {
switch cell.numberOfNeighbors {
case 0..<2:
cell.nextAction = .Die
case 2...3:
cell.nextAction = .Idle
default:
cell.nextAction = .Die
}
} else {
if cell.numberOfNeighbors == 3 {
if cell.redNeighbors > cell.blueNeighbors {
cell.spawnColor = .red
} else if cell.redNeighbors < cell.blueNeighbors {
cell.spawnColor = .blue
}
cell.nextAction = .Spawn
}
}
}
// Adjusts the cell's Alive status based on a previously calculated action
func executeNextAction(cell:GOLCell) {
switch cell.nextAction {
case GOLCell.Action.Idle:
break
case GOLCell.Action.Spawn:
cell.isAlive = true
case GOLCell.Action.Die:
cell.isAlive = false
}
}
private func prepNextGeneration() {
// GOLCells should know where they are mapped on the matrix
if !self.cellsKnowTheirPosition {
for i in 0 ..< rowMax {
for j in 0 ..< colMax {
cellGrid[i,j].coordinates = (row:i, col:j)
}
}
cellsKnowTheirPosition = true
}
for cell in cellGrid {
calculateNextAction(cell)
}
}
private func executeNextGeneration() {
for cell in cellGrid {
executeNextAction(cell)
}
}
func prepareAndExecuteNextGeneration() {
self.prepNextGeneration()
self.executeNextGeneration()
generationCount += 1
}
func killAll() {
for cell in cellGrid {
cell.isAlive = false
}
}
}
// MARK: Console output
extension GOLGrid {
func printGridToConsole() {
for i in 0..<rowMax {
for j in 0..<colMax {
cellGrid[i, j].isAlive ? print(" \(cellGrid[i,j].numberOfNeighbors)", terminator: "") : print(" . ", terminator: "")
}
print("")
}
print("")
print("")
}
}
|
agpl-3.0
|
c143bdb46544af707814a5b50a93c315
| 26.2 | 132 | 0.522574 | 4.507366 | false | false | false | false |
mleiv/IBIncludedThing
|
ContainerViewStroyboardReferencesDemo/ContainerViewStroyboardReferencesDemo/Flow1Controller.swift
|
1
|
1207
|
//
// Flow1Controller.swift
// ContainerViewStoryboardReferenceDemo
//
// Created by Emily Ivie on 3/18/16.
// Copyright © 2016 urdnot. All rights reserved.
//
import UIKit
class Flow1Controller: UIViewController {
// do things in here that happen in the flow rather than the scene, like closing navigation stacks.
var sentValue: String?
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// embed segues
if let controller = segue.destinationViewController as? FirstController {
// nothing passed here
}
if let controller = segue.destinationViewController as? SecondController {
controller.sentValue = sentValue ?? ""
}
// existing flow segue
if let flowController = segue.destinationViewController as? Flow1Controller {
flowController.sentValue = sentValue
}
// new flow segue
if let navController = segue.destinationViewController as? UINavigationController {
if let flowController = navController.visibleViewController as? Flow2Controller {
flowController.sentValue = sentValue
}
}
}
}
|
mit
|
5a9cc7637fa4ce534d2619119633fa3f
| 34.5 | 103 | 0.668325 | 5.336283 | false | false | false | false |
mentalfaculty/impeller
|
Playgrounds/Brocolli with Separate Protocol.playground/Contents.swift
|
1
|
2531
|
//: Playground - noun: a place where people can play
import Cocoa
typealias UniqueIdentifier = String
protocol PropertyListable {
func propertyList() -> Any
}
extension String : PropertyListable {
func propertyList() -> Any {
return self
}
}
extension Int : PropertyListable {
func propertyList() -> Any {
return self
}
}
struct StorableProperty<T:PropertyListable> {
var value:T?
init(_ value:T) {
self.value = value
}
init(_ value:T? = nil) {
self.value = nil
}
}
prefix operator <-
prefix operator <-?
prefix func <- <T>(right: StorableProperty<T>) -> T {
return right.value!
}
prefix func <-? <T>(right: StorableProperty<T>) -> T? {
return right.value
}
prefix func <- <T>(right: T) -> StorableProperty<T> {
return StorableProperty<T>(right)
}
prefix func <-? <T>(right: T?) -> StorableProperty<T> {
return StorableProperty<T>(right)
}
protocol Storable {
var metadata: Metadata { get set }
func resolvedValue(forConflictWith newValue:Self) -> Self
}
extension Storable {
mutating func store(_ value: PropertyListable) {
}
func resolvedValue(forConflictWith newValue:Self) -> Self {
return self
}
}
struct Metadata {
var version: UInt64 = 0
var timestamp = Date.timeIntervalSinceReferenceDate
var uniqueIdentifier = UUID().uuidString
init() {}
}
struct Person : Storable {
var metadata = Metadata()
var name = StorableProperty("No Name")
var age = StorableProperty<Int>()
init() {}
}
var person = Person()
<-person.name
person.name = <-"Tom"
var s = <-person.name
person.age = <-?13
let i = <-?person.age
/*
class Store {
func save<T:Storable>(value:T) {
let storeValue:T = fetchValue(identifiedBy: value.metadata.uniqueIdentifier)
var resolvedValue:T!
if value.metadata.version == storeValue.metadata.version {
// Store unchanged, so just save the new value directly
resolvedValue = value
}
else {
resolvedValue = value.resolvedValue(forConflictWith: storeValue)
}
// Update metadata
resolvedValue.metadata.timestamp = Date.timeIntervalSinceReferenceDate
resolvedValue.metadata.version = storeValue.metadata.version + 1
// TODO: Save resolved value to disk
}
func fetchValue<T:Storable>(identifiedBy uniqueIdentifier:UniqueIdentifier) -> T {
return Person() as! T
}
}*/
|
mit
|
2f1fa622b884bcddbada9f67af2f5f06
| 21.39823 | 86 | 0.633347 | 4.108766 | false | false | false | false |
erhoffex/SwiftAnyPic
|
SwiftAnyPic/PAPPhotoDetailsFooterView.swift
|
6
|
1976
|
import UIKit
class PAPPhotoDetailsFooterView: UIView {
private var mainView: UIView!
var commentField: UITextField!
var hideDropShadow: Bool = false
// MARK:- NSObject
override init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
self.backgroundColor = UIColor.clearColor()
mainView = UIView(frame: CGRectMake(0.0, 0.0, 320.0, 51.0))
mainView.backgroundColor = UIColor.whiteColor()
self.addSubview(mainView)
let messageIcon = UIImageView(image: UIImage(named: "IconAddComment.png"))
messageIcon.frame = CGRectMake(20.0, 15.0, 22.0, 22.0)
mainView.addSubview(messageIcon)
let commentBox = UIImageView(image: UIImage(named: "TextFieldComment.png")!.resizableImageWithCapInsets(UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)))
commentBox.frame = CGRectMake(55.0, 8.0, 237.0, 34.0)
mainView.addSubview(commentBox)
commentField = UITextField(frame: CGRectMake(66.0, 8.0, 217.0, 34.0))
commentField.font = UIFont.systemFontOfSize(14.0)
commentField.placeholder = "Add a comment"
commentField.returnKeyType = UIReturnKeyType.Send
commentField.textColor = UIColor(red: 34.0/255.0, green: 34.0/255.0, blue: 34.0/255.0, alpha: 1.0)
commentField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
commentField.setValue(UIColor(red: 114.0/255.0, green: 114.0/255.0, blue: 114.0/255.0, alpha: 1.0), forKeyPath: "_placeholderLabel.textColor") // Are we allowed to modify private properties like this? -Héctor
mainView.addSubview(commentField)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- PAPPhotoDetailsFooterView
class func rectForView() -> CGRect {
return CGRectMake(0.0, 0.0, UIScreen.mainScreen().bounds.size.width, 69.0)
}
}
|
cc0-1.0
|
439ae6555c2dc78bada1e1ba91cf46fc
| 40.145833 | 216 | 0.668354 | 3.95 | false | false | false | false |
hugolundin/Template
|
Template/Template/Supporting Files/AppDelegate.swift
|
1
|
2757
|
//
// AppDelegate.swift
// Template
//
// Created by Hugo Lundin on 2017-08-10.
// Copyright © 2017 Hugo Lundin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let appDependencies = AppDependencies()
appDependencies.settings = Local()
appDependencies.todoist = Todoist()
appDependencies.csv = CSV()
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
for child in controller?.childViewControllers ?? [] {
if let destination = child as? MainViewController {
destination.dependencies = appDependencies
}
}
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = controller
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
15b20b4e8b468fcc81b0706c92512a40
| 46.517241 | 285 | 0.711176 | 5.76569 | false | false | false | false |
saagarjha/iina
|
iina/DraggingDetect.swift
|
1
|
7689
|
//
// DraggingDetect.swift
// iina
//
// Created by Yuze Jiang on 05/08/2017.
// Copyright © 2017 lhc. All rights reserved.
//
import Foundation
extension PlayerCore {
/**
Checks whether the path list contains playable file and performs early return if so. Don't use this method for a non-file URL.
- Parameters:
- paths: The list as an array of `String`.
- Returns: Whether the path list contains playable file.
*/
func hasPlayableFiles(in paths: [String]) -> Bool {
for path in paths {
if path.isDirectoryAsPath {
// is directory, enumerate its content
guard let dirEnumerator = FileManager.default.enumerator(atPath: path) else { return false }
while let fileName = dirEnumerator.nextObject() as? String {
// ignore hidden files
guard !fileName.hasPrefix(".") else { continue }
if Utility.playableFileExt.contains(fileName.lowercasedPathExtension) {
return true
}
}
} else {
// is file, check extension
if !Utility.blacklistExt.contains(path.lowercasedPathExtension) {
return true
}
}
}
return false
}
/**
Returns playable files contained in a URL list. Any non-file URL will be counted directly without further checking.
- Parameters:
- urls: The list as an array of `URL`.
- Returns: URLs of all playable files as an array of `URL`.
*/
func getPlayableFiles(in urls: [URL]) -> [URL] {
var playableFiles: [URL] = []
for url in urls {
if !url.isFileURL {
playableFiles.append(url)
continue
}
if url.hasDirectoryPath {
// is directory
// `enumerator(at:includingPropertiesForKeys:)` doesn't work :(
guard let dirEnumerator = FileManager.default.enumerator(atPath: url.path) else { return [] }
while let fileName = dirEnumerator.nextObject() as? String {
guard !fileName.hasPrefix(".") else { continue }
if Utility.playableFileExt.contains(fileName.lowercasedPathExtension) {
playableFiles.append(url.appendingPathComponent(fileName))
}
}
} else {
// is file
if !Utility.blacklistExt.contains(url.pathExtension.lowercased()) {
playableFiles.append(url)
}
}
}
return Array(Set(playableFiles)).sorted { url1, url2 in
let folder1 = url1.deletingLastPathComponent(), folder2 = url2.deletingLastPathComponent()
if folder1.absoluteString == folder2.absoluteString {
return url1.lastPathComponent.localizedStandardCompare(url2.lastPathComponent) == .orderedAscending
} else {
return folder1.absoluteString < folder2.absoluteString
}
}
}
/**
Checks whether a path list contains path to subtitle file.
- Parameters:
- paths: The list as an array of `String`.
- Returns: Whether the path list contains path to subtitle file.
*/
func hasSubtitleFile(in paths: [String]) -> Bool {
return paths.contains {
!$0.isDirectoryAsPath && Utility.supportedFileExt[.sub]!.contains($0.lowercasedPathExtension)
}
}
/**
Checks whether a URL is BD folder by checking the existence of "MovieObject.bdmv" and "index.bdmv".
- Parameters:
- url: The URL.
- Returns: Whether the URL is a BD folder.
*/
func isBDFolder(_ url: URL) -> Bool {
let bdmvFolder = url.appendingPathComponent("BDMV")
guard bdmvFolder.isExistingDirectory else { return false }
if let files = try? FileManager.default.contentsOfDirectory(atPath: bdmvFolder.path) {
return files.contains("MovieObject.bdmv") && files.contains("index.bdmv")
} else {
return false
}
}
/**
Get called for all drag-and-drop enabled window/views in their `draggingEntered(_:)`.
- Parameters:
- sender: The `NSDraggingInfo` object received in `draggingEntered(_:)`.
- isPlaylist: True when the caller is `PlaylistViewController`
- Returns: The `NSDragOperation`.
*/
func acceptFromPasteboard(_ sender: NSDraggingInfo, isPlaylist: Bool = false) -> NSDragOperation {
// ignore events from this window
// must check `mainWindow.loaded` otherwise window will be lazy-loaded unexpectedly
if mainWindow.loaded && (sender.draggingSource as? NSView)?.window === mainWindow.window {
return []
}
// get info
let pb = sender.draggingPasteboard
guard let types = pb.types else { return [] }
if types.contains(.nsFilenames) {
guard var paths = pb.propertyList(forType: .nsFilenames) as? [String] else { return [] }
paths = Utility.resolvePaths(paths)
// check 3d lut files
if paths.count == 1 && Utility.lut3dExt.contains(paths[0].lowercasedPathExtension) {
return .copy
}
if isPlaylist {
return hasPlayableFiles(in: paths) ? .copy : []
} else {
let theOnlyPathIsBDFolder = paths.count == 1 && isBDFolder(URL(fileURLWithPath: paths[0]))
return theOnlyPathIsBDFolder ||
hasPlayableFiles(in: paths) ||
hasSubtitleFile(in: paths) ? .copy : []
}
} else if types.contains(.nsURL) {
return .copy
} else if let droppedString = pb.string(forType: .string) {
return Regex.url.matches(droppedString) || Regex.filePath.matches(droppedString) ? .copy : []
}
return []
}
/**
Get called for all drag-and-drop enabled window/views in their `performDragOperation(_:)`.
- Parameters:
- sender: The `NSDraggingInfo` object received in `performDragOperation(_:)`.
- Returns: The result for `performDragOperation(_:)`.
*/
func openFromPasteboard(_ sender: NSDraggingInfo) -> Bool {
// get info
let pb = sender.draggingPasteboard
guard let types = pb.types else { return false }
if types.contains(.nsFilenames) {
guard var paths = pb.propertyList(forType: .nsFilenames) as? [String] else { return false }
paths = Utility.resolvePaths(paths)
// check 3d lut files
if paths.count == 1 && Utility.lut3dExt.contains(paths[0].lowercasedPathExtension) {
let result = addVideoFilter(MPVFilter(lavfiName: "lut3d", label: "iina_quickl3d", paramDict: [
"file": paths[0],
"interp": "nearest"
]))
if result {
sendOSD(.addFilter("3D LUT"))
}
return result
}
let urls = paths.map{ URL(fileURLWithPath: $0) }
// try open files
guard let loadedFileCount = openURLs(urls) else { return true }
if loadedFileCount == 0 {
// if no playable files, try add subtitle files
var loadedSubtitle = false
for url in urls {
if !url.hasDirectoryPath && Utility.supportedFileExt[.sub]!.contains(url.pathExtension.lowercased()) {
loadExternalSubFile(url)
loadedSubtitle = true
}
}
return loadedSubtitle
} else if loadedFileCount == 1 {
// loaded one file
info.shouldAutoLoadFiles = true
return true
} else {
// add multiple files to playlist
sendOSD(.addToPlaylist(loadedFileCount))
return true
}
} else if types.contains(.nsURL) {
guard let url = pb.propertyList(forType: .nsURL) as? [String] else { return false }
openURLString(url[0])
return true
} else if let droppedString = pb.string(forType: .string) {
if Regex.url.matches(droppedString) || Regex.filePath.matches(droppedString) {
openURLString(droppedString)
return true
} else {
Utility.showAlert("unsupported_url")
return false
}
}
return false
}
}
|
gpl-3.0
|
45948511ddaeb7d31711f4b6cd7304a6
| 33.78733 | 129 | 0.639048 | 4.307003 | false | false | false | false |
joshua7v/ResearchOL-iOS
|
ResearchOL/Class/Me/Controller/ROLProfileDetailController.swift
|
1
|
1266
|
//
// ROLProfileDetailController.swift
// ResearchOL
//
// Created by Joshua on 15/4/13.
// Copyright (c) 2015年 SigmaStudio. All rights reserved.
//
import UIKit
class ROLProfileDetailController: SESettingViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = SEColor(226, 226, 226)
self.setupGroup0()
self.hidesBottomBarWhenPushed = true
}
// MARK: - setup
// MARK: setup first group
func setupGroup0() {
var group = self.addGroup()
var nickName = SESettingArrowItem(title: "昵称:", destVcClass: UIViewController.classForCoder())
var name = SESettingArrowItem(title: "姓名:", destVcClass: UIViewController.classForCoder())
var identity = SESettingArrowItem(title: "身份证:", destVcClass: UIViewController.classForCoder())
var gender = SESettingArrowItem(title: "性别:", destVcClass: UIViewController.classForCoder())
var birth = SESettingArrowItem(title: "生日:", destVcClass: UIViewController.classForCoder())
var mail = SESettingArrowItem(title: "邮箱:", destVcClass: UIViewController.classForCoder())
group.items = [nickName, name, identity, gender, birth, mail]
}
}
|
mit
|
7fd788c243d2ff72dd1a730f426a5b8e
| 36.515152 | 103 | 0.681745 | 4.298611 | false | false | false | false |
brentdax/SQLKit
|
Sources/CorePostgreSQL/Int+Formatted.swift
|
1
|
1331
|
//
// Int+Formatted.swift
// LittlinkRouterPerfect
//
// Created by Brent Royal-Gordon on 12/2/16.
//
//
import Foundation
protocol NumericFormattable: ExpressibleByIntegerLiteral {
func formatted(digits: Int) -> String
}
extension Int: NumericFormattable {
func formatted(digits: Int) -> String {
let sign = self < 0 ? "-" : ""
let base = String(abs(self))
let extraCount = digits - base.characters.count
guard extraCount > 0 else {
return base
}
let extra = String(repeating: "0", count: extraCount)
return sign + extra + base
}
}
extension Decimal: NumericFormattable {
func formatted(digits: Int) -> String {
let sign = self < 0 ? "-" : ""
let base = String(describing: abs(self))
let wholeEndIndex = base.characters.index(of: ".") ?? base.endIndex
let extraCount = digits - base.characters.distance(from: base.startIndex, to: wholeEndIndex)
guard extraCount > 0 else {
return base
}
let extra = String(repeating: "0", count: extraCount)
return sign + extra + base
}
}
func f<Num: NumericFormattable>(_ number: Num, digits: Int = 2) -> String {
return number.formatted(digits: digits)
}
|
mit
|
26705f8963f6459e1c4a3bf3c614439b
| 24.596154 | 100 | 0.587528 | 4.198738 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV
|
PopcornTime/UI/iOS/Extensions/UIAlertAction+Extension.swift
|
1
|
1831
|
import Foundation
extension UIAlertAction {
private struct AssociatedKeys {
static var checkedKey = "UIAlertAction.checkedKey"
}
@nonobjc var isChecked: Bool {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.checkedKey) as? Bool ?? false
} set (checked) {
objc_setAssociatedObject(self, &AssociatedKeys.checkedKey, checked, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
imageView = imageView ?? UIImageView()
imageView?.image = checked ? UIImage(named: "Checkmark")?.withRenderingMode(.alwaysTemplate) : nil
}
}
@nonobjc var alertController: UIAlertController? {
get {
return perform(Selector(("_alertController"))).takeUnretainedValue() as? UIAlertController
} set(vc) {
perform(Selector(("_setAlertController:")), with: vc)
}
}
private var view: UIView? {
return alertController?.view.recursiveSubviews.filter({type(of: $0) == NSClassFromString("_UIInterfaceActionCustomViewRepresentationView")}).compactMap({$0.value(forKeyPath: "action.customContentView") as? UIView}).first(where: {$0.value(forKey: "action") as? UIAlertAction == self})
}
var imageView: UIImageView? {
get {
return view?.value(forKey: "_checkView") as? UIImageView
} set(new) {
view?.setValue(new, forKey: "_checkView")
guard let new = new, let view = view else { return }
view.addSubview(new)
new.translatesAutoresizingMaskIntoConstraints = false
new.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -15).isActive = true
new.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
}
}
|
gpl-3.0
|
5d2403fd0179b435d9607e08e2caca07
| 37.957447 | 291 | 0.628072 | 5.072022 | false | false | false | false |
SusanDoggie/Doggie
|
Sources/DoggieGraphics/Font/Decoder/SFNTFontFace/AATStateTable.swift
|
1
|
13802
|
//
// SFNTMORX.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.
//
protocol AATStateMachineEntryData: ByteDecodable {
static var size: Int { get }
}
protocol AATStateMachineContext {
associatedtype Machine: AATStateMachine where Machine.Context == Self
init(_ machine: Machine) throws
mutating func transform(_ index: Int, _ entry: Machine.Entry, _ buffer: inout [Int]) -> Bool
}
protocol AATStateMachine {
associatedtype EntryData: AATStateMachineEntryData
associatedtype Context: AATStateMachineContext where Context.Machine == Self
typealias Entry = AATStateMachineEntry<EntryData>
var stateHeader: AATStateTable<EntryData> { get }
func perform(glyphs: [Int]) -> [Int]
}
struct AATStateMachineEntry<EntryData: AATStateMachineEntryData>: ByteDecodable {
static var size: Int {
return 4 + EntryData.size
}
var newState: BEUInt16
var flags: BEUInt16
var data: EntryData
init(from data: inout Data) throws {
self.newState = try data.decode(BEUInt16.self)
self.flags = try data.decode(BEUInt16.self)
self.data = try data.decode(EntryData.self)
}
}
struct AATStateTable<EntryData: AATStateMachineEntryData>: ByteDecodable {
var nClasses: BEUInt32
var classTable: AATLookupTable
var stateArray: Data
var entryTable: Data
init(from data: inout Data) throws {
let copy = data
self.nClasses = try data.decode(BEUInt32.self)
let classTableOffset = try data.decode(BEUInt32.self)
let stateArrayOffset = try data.decode(BEUInt32.self)
let entryTableOffset = try data.decode(BEUInt32.self)
self.classTable = try AATLookupTable(copy.dropFirst(Int(classTableOffset)))
self.stateArray = copy.dropFirst(Int(stateArrayOffset))
self.entryTable = copy.dropFirst(Int(entryTableOffset))
}
}
protocol AATLookupTableFormat: ByteDecodable {
func search(glyph: UInt16) -> UInt16?
}
struct AATLookupTable {
var format: BEUInt16
var fsHeader: AATLookupTableFormat
init(_ data: Data) throws {
var data = data
self.format = try data.decode(BEUInt16.self)
switch format {
case 0: self.fsHeader = try data.decode(Format0.self)
case 2: self.fsHeader = try data.decode(Format2.self)
case 4: self.fsHeader = try data.decode(Format4.self)
case 6: self.fsHeader = try data.decode(Format6.self)
case 8: self.fsHeader = try data.decode(Format8.self)
default: throw FontCollection.Error.InvalidFormat("Invalid AAT lookup table format.")
}
}
func search(glyph: UInt16) -> UInt16? {
return fsHeader.search(glyph: glyph)
}
}
extension AATLookupTable {
struct BinSrchHeader: ByteDecodable {
var unitSize: BEUInt16
var nUnits: BEUInt16
var searchRange: BEUInt16
var entrySelector: BEUInt16
var rangeShift: BEUInt16
init(from data: inout Data) throws {
self.unitSize = try data.decode(BEUInt16.self)
self.nUnits = try data.decode(BEUInt16.self)
self.searchRange = try data.decode(BEUInt16.self)
self.entrySelector = try data.decode(BEUInt16.self)
self.rangeShift = try data.decode(BEUInt16.self)
}
}
struct Format0: AATLookupTableFormat {
var data: Data
init(from data: inout Data) throws {
self.data = data.popFirst(data.count)
}
func search(glyph: UInt16) -> UInt16? {
var _data = data.dropFirst(Int(glyph) << 1)
return try? UInt16(_data.decode(BEUInt16.self))
}
}
struct Format2: AATLookupTableFormat {
var binSrchHeader: BinSrchHeader
var data: Data
init(from data: inout Data) throws {
self.binSrchHeader = try data.decode(BinSrchHeader.self)
let size = Int(self.binSrchHeader.nUnits) * Int(self.binSrchHeader.unitSize)
self.data = data.popFirst(size)
guard self.data.count == size else { throw ByteDecodeError.endOfData }
}
func search(_ glyph: UInt16, _ range: Range<Int>) -> UInt16? {
var range = range
while !range.isEmpty {
let mid = (range.lowerBound + range.upperBound) >> 1
var _data = data.dropFirst(mid * Int(self.binSrchHeader.unitSize))
guard let last_glyph = try? UInt16(_data.decode(BEUInt16.self)) else { return nil }
guard let first_glyph = try? UInt16(_data.decode(BEUInt16.self)) else { return nil }
guard let value = try? UInt16(_data.decode(BEUInt16.self)) else { return nil }
if first_glyph <= last_glyph && first_glyph...last_glyph ~= glyph {
return value
}
range = glyph < first_glyph ? range.prefix(upTo: mid) : range.suffix(from: mid).dropFirst()
}
return nil
}
func search(glyph: UInt16) -> UInt16? {
return search(glyph, 0..<Int(self.binSrchHeader.nUnits))
}
}
struct Format4: AATLookupTableFormat {
var binSrchHeader: BinSrchHeader
var data: Data
init(from data: inout Data) throws {
self.binSrchHeader = try data.decode(BinSrchHeader.self)
let size = Int(self.binSrchHeader.nUnits) * Int(self.binSrchHeader.unitSize)
self.data = data.popFirst(data.count)
guard self.data.count >= size else { throw ByteDecodeError.endOfData }
}
func search(_ glyph: UInt16, _ range: Range<Int>) -> UInt16? {
var range = range
while !range.isEmpty {
let mid = (range.lowerBound + range.upperBound) >> 1
var _data = data.dropFirst(mid * Int(self.binSrchHeader.unitSize))
guard let last_glyph = try? UInt16(_data.decode(BEUInt16.self)) else { return nil }
guard let first_glyph = try? UInt16(_data.decode(BEUInt16.self)) else { return nil }
guard let offset = try? Int(_data.decode(BEUInt16.self)) else { return nil }
if first_glyph <= last_glyph && first_glyph...last_glyph ~= glyph {
guard offset >= 12 else { return nil }
var _data = data.dropFirst(offset - 12).dropFirst(Int(glyph - first_glyph) << 1)
return try? UInt16(_data.decode(BEUInt16.self))
}
range = glyph < first_glyph ? range.prefix(upTo: mid) : range.suffix(from: mid).dropFirst()
}
return nil
}
func search(glyph: UInt16) -> UInt16? {
return search(glyph, 0..<Int(self.binSrchHeader.nUnits))
}
}
struct Format6: AATLookupTableFormat {
var binSrchHeader: BinSrchHeader
var data: Data
init(from data: inout Data) throws {
self.binSrchHeader = try data.decode(BinSrchHeader.self)
let size = Int(self.binSrchHeader.nUnits) * Int(self.binSrchHeader.unitSize)
self.data = data.popFirst(size)
guard self.data.count == size else { throw ByteDecodeError.endOfData }
}
func search(_ glyph: UInt16, _ range: Range<Int>) -> UInt16? {
var range = range
while !range.isEmpty {
let mid = (range.lowerBound + range.upperBound) >> 1
var _data = data.dropFirst(mid * Int(self.binSrchHeader.unitSize))
guard let _glyph = try? UInt16(_data.decode(BEUInt16.self)) else { return nil }
guard let value = try? UInt16(_data.decode(BEUInt16.self)) else { return nil }
if _glyph == glyph {
return value
}
range = glyph < _glyph ? range.prefix(upTo: mid) : range.suffix(from: mid).dropFirst()
}
return nil
}
func search(glyph: UInt16) -> UInt16? {
return search(glyph, 0..<Int(self.binSrchHeader.nUnits))
}
}
struct Format8: AATLookupTableFormat {
var firstGlyph: BEUInt16
var glyphCount: BEUInt16
var data: Data
init(from data: inout Data) throws {
self.firstGlyph = try data.decode(BEUInt16.self)
self.glyphCount = try data.decode(BEUInt16.self)
let size = Int(glyphCount) << 1
self.data = data.popFirst(size)
guard self.data.count == size else { throw ByteDecodeError.endOfData }
}
func search(glyph: UInt16) -> UInt16? {
let index = Int(glyph) - Int(firstGlyph)
guard 0..<Int(glyphCount) ~= index else { return nil }
var _data = data.dropFirst((Int(glyph) - Int(firstGlyph)) << 1)
return try? UInt16(_data.decode(BEUInt16.self))
}
}
}
struct AATStateMachineState: RawRepresentable, Hashable, ExpressibleByIntegerLiteral {
var rawValue: UInt16
init(rawValue: UInt16) {
self.rawValue = rawValue
}
init(integerLiteral value: UInt16.IntegerLiteralType) {
self.init(rawValue: UInt16(integerLiteral: value))
}
static let startOfText: AATStateMachineState = 0
static let startOfLine: AATStateMachineState = 1
}
struct AATStateMachineClass: RawRepresentable, Hashable, ExpressibleByIntegerLiteral {
var rawValue: UInt16
init(rawValue: UInt16) {
self.rawValue = rawValue
}
init(integerLiteral value: UInt16.IntegerLiteralType) {
self.init(rawValue: UInt16(integerLiteral: value))
}
static let endOfText: AATStateMachineClass = 0
static let outOfBounds: AATStateMachineClass = 1
static let deletedGlyph: AATStateMachineClass = 2
static let endOfLine: AATStateMachineClass = 3
}
extension AATStateMachine {
var nClasses: UInt16 {
return UInt16(self.stateHeader.nClasses)
}
func classOf(glyph: Int) -> AATStateMachineClass {
guard let glyph = UInt16(exactly: glyph) else { return .outOfBounds }
guard let rawValue = self.stateHeader.classTable.search(glyph: glyph) else { return .outOfBounds }
return AATStateMachineClass(rawValue: rawValue)
}
func entry(_ state: AATStateMachineState, _ klass: AATStateMachineClass) -> Entry? {
guard 0..<nClasses ~= klass.rawValue else { return nil }
let stateIdx = Int(state.rawValue) * Int(nClasses) + Int(klass.rawValue)
var state = stateHeader.stateArray.dropFirst(stateIdx << 1)
guard let entryIdx = try? Int(state.decode(BEUInt16.self)) else { return nil }
var entry = stateHeader.entryTable.dropFirst(entryIdx * Entry.size)
return try? entry.decode(Entry.self)
}
func perform(glyphs: [Int]) -> [Int] {
var buffer = glyphs
var state = AATStateMachineState.startOfText
guard var context = try? Context(self) else { return glyphs }
for offset in (0...glyphs.count).reversed() {
var dont_advance = false
var counter = 0
repeat {
guard counter < 0xFF else { return glyphs } // break infinite loop
let index = buffer.index(buffer.endIndex, offsetBy: -offset)
let klass = offset != 0 ? self.classOf(glyph: buffer[index]): .endOfText
guard let entry = self.entry(state, klass) else { return glyphs }
guard context.transform(index, entry, &buffer) else { return glyphs }
dont_advance = entry.flags & 0x4000 != 0
state = AATStateMachineState(rawValue: UInt16(entry.newState))
counter += 1
} while dont_advance
}
return buffer
}
}
|
mit
|
4991d930e01a5b2d53e57703bcbbe613
| 33.941772 | 107 | 0.587668 | 4.32936 | false | false | false | false |
belatrix/iOSAllStars
|
AllStarsV2/AllStarsV2/BC/UserBC.swift
|
1
|
10233
|
//
// UserBC.swift
// AllStarsV2
//
// Created by Kenyi Rodriguez Vergara on 20/07/17.
// Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved.
//
import UIKit
import Firebase
class UserBC: NSObject {
class func uploadPhoto(_ photo: UIImage, withSuccessful success : @escaping User, withAlertInformation alertInformation : @escaping AlertInformation) {
let objSession = UserBC.getUserSession()
if objSession == nil || objSession!.session_token == "" {
alertInformation("app_name".localized, "token_invalid".localized)
}else {
UserWebModel.uploadPhoto(photo, toUserSession: objSession!, withSuccessful: { (objUser) in
UserBE.shareInstance = objUser
success(objUser)
}, withError: { (errorResponse) in
alertInformation("generic_title_problem".localized, errorResponse.message)
})
}
}
class func getUserInformationById(_ userId: Int, withSuccessful success : @escaping User, withAlertInformation alertInformation : @escaping AlertInformation) {
let objSession = UserBC.getUserSession()
if objSession == nil || objSession!.session_token == "" {
alertInformation("app_name".localized, "token_invalid".localized)
}else {
UserWebModel.getUserInformationById(userId, withSession: objSession!, withSuccessful: { (objUser) in
success(objUser)
}, withError: { (errorResponse) in
alertInformation("generic_title_problem".localized, errorResponse.message)
})
}
}
class func updateInfoToUser(_ user : UserBE, withImage image: UIImage?, withSuccessful success : @escaping User, withAlertInformation alertInformation : @escaping AlertInformation) {
let objSession = UserBC.getUserSession()
if image == nil{
alertInformation("app_name".localized, "select_image_profile".localized)
}else if objSession == nil || objSession!.session_token == "" {
alertInformation("app_name".localized, "token_invalid".localized)
}else if (user.user_first_name == nil || user.user_first_name == "") {
alertInformation("app_name".localized, "first_name_empty".localized)
}else if (user.user_last_name == nil || user.user_last_name == "") {
alertInformation("app_name".localized, "last_name_empty".localized)
}else if (user.user_skype_id == nil || user.user_skype_id == "") {
alertInformation("app_name".localized, "skype_is_empty".localized)
}else if (user.user_location == nil) {
alertInformation("app_name".localized, "location_empty".localized)
}else {
UserWebModel.updateUser(user, withSession: objSession!, withSuccessful: { (objUser) in
UserBC.deleteSession()
UserBC.saveSession(objSession!)
UserBE.shareInstance = objUser
success(objUser)
}, withError: { (errorResponse) in
alertInformation("generic_title_problem".localized, errorResponse.message)
})
}
}
class func resetUserPassword(withSession userSession: SessionBE, currentPassword : String?, newPassword : String?, repeatNewPassword : String?, withSuccessful success : @escaping UserSession, withAlertInformation alertInformation : @escaping AlertInformation) {
if userSession.session_token == "" {
alertInformation("app_name".localized, "token_invalid".localized)
return
}
if (currentPassword == nil || currentPassword == "") {
alertInformation("app_name".localized, "old_password_empty".localized)
return
}
if (newPassword == nil || repeatNewPassword == nil || newPassword == "" || repeatNewPassword == "") {
alertInformation("app_name".localized, "new_password_empty".localized)
return
}
if (newPassword != repeatNewPassword) {
alertInformation("app_name".localized, "new_password_match".localized)
return
}
if (newPassword!.count < Constants.MIN_PASSWORD_LENGTH) {
let message = String.init(format: "new_password_length".localized, Constants.MIN_PASSWORD_LENGTH)
alertInformation("app_name".localized, message)
return
}
UserWebModel.resetUserPassword(userSession, currentPassword: currentPassword!, newPassword: newPassword!, withSuccessful: { (objSession) in
objSession.session_token = userSession.session_token
objSession.session_password = newPassword!
objSession.session_pwd_reset_required = false
SessionBE.sharedInstance = objSession
success(objSession)
}) { (errorResponse) in
self.deleteSession()
alertInformation("generic_title_problem".localized, errorResponse.message)
}
}
class func registerDevice(withSuccessful success : @escaping Success, withAlertInformation alertInformation : @escaping AlertInformation){
let objSession = UserBC.getUserSession()
if objSession == nil || objSession!.session_token == "" {
alertInformation("app_name".localized, "token_invalid".localized)
}
UserWebModel.registerDevice("", toSession: objSession!, withSuccessful: { (isCorrect) in
success(isCorrect)
}) { (errorResponse) in
alertInformation("generic_title_problem".localized, errorResponse.message)
}
}
class func forgotPasswordToEmail(_ user_email: String?, withSuccessful success : @escaping Success, withAlertInformation alertInformation : @escaping AlertInformation) {
if (user_email == nil || user_email == "") {
alertInformation("app_name".localized, "email_is_empty".localized)
return
}
UserWebModel.forgotPasswordToEmail("\(user_email!)@\(AppInformationBC.sharedInstance.appInformation.appInformation_emailDomain)", withSuccessful: { (isCorrect) in
success(isCorrect)
}) { (errorResponse) in
alertInformation("generic_title_problem".localized, errorResponse.message)
}
}
class func createUserWithEmail(_ user_email: String?, withSuccessful success : @escaping Success, withAlertInformation alertInformation : @escaping AlertInformation) {
if (user_email == nil || user_email == "") {
alertInformation("app_name".localized, "email_is_empty".localized)
return
}
UserWebModel.createUserWithEmail("\(user_email!)@\(AppInformationBC.sharedInstance.appInformation.appInformation_emailDomain)", withSuccessful: { (isCorrect) in
success(isCorrect)
}) { (errorResponse) in
alertInformation("generic_title_problem".localized, errorResponse.message)
}
}
class func logInUsername(_ username: String?, withPassword password: String?, withSuccessful success : @escaping UserSession, sessionProfileIncomplete profileIcomplete: @escaping UserSession, sessionNeedResetPassword resetPassword: @escaping UserSession, withError error : @escaping AlertInformation){
if username == nil || username!.trim().isEmpty {
error("app_name".localized, "username_empty".localized)
}else if password == nil || password!.trim().isEmpty {
error("app_name".localized, "password_empty".localized)
}else{
UserWebModel.logInUsername(username!, withPassword: password!, withSuccessful: { (objSession) in
objSession.session_user = username!
objSession.session_password = password!
self.saveSession(objSession)
if objSession.session_state == SessionBE.SessionState.session_profileComplete {
UserBC.saveSession(objSession)
success(objSession)
}
else if objSession.session_state == SessionBE.SessionState.session_profileIncomplete {
profileIcomplete(objSession)
}
else {
resetPassword(objSession)
}
}, withError: { (errorResponse) in
error("generic_title_problem".localized, errorResponse.message)
})
}
}
public class func saveSession(_ objSession : SessionBE) -> Void {
CDMKeyChain.eliminarKeychain()
SessionBE.sharedInstance = objSession
CDMKeyChain.guardarDataEnKeychain(NSKeyedArchiver.archivedData(withRootObject: objSession), conCuenta: "Login", conServicio: "dataUser")
}
public class func getUserSession() -> SessionBE?{
if SessionBE.sharedInstance != nil {
return SessionBE.sharedInstance
}
if let dataUser = CDMKeyChain.dataDesdeKeychainConCuenta("Login", conServicio: "dataUser") {
let objUser = NSKeyedUnarchiver.unarchiveObject(with: dataUser) as? SessionBE
SessionBE.sharedInstance = objUser
return objUser
}
return nil
}
public class func deleteSession() -> Void{
SessionBE.sharedInstance = nil
CDMKeyChain.eliminarKeychain()
}
}
|
apache-2.0
|
bf53e90854d01d1b0f84774effbdbf39
| 36.617647 | 305 | 0.584539 | 5.266083 | false | false | false | false |
hikelee/hotel
|
Sources/Common/Models/BasicModel.swift
|
1
|
8754
|
import Fluent
import Vapor
import HTTP
import Foundation
public protocol RestModel : Model {
var id : Node? {get set}
var exists: Bool {get set}
func validate(isCreate: Bool) throws ->[String:String]
func makeNode(context: Context) throws -> Node
func makeLeafNode() throws -> Node
func makeNode() throws -> Node
}
public struct Join{
public var tableName:String
public var fields:[String]
public var joinField:String
}
public struct GridResult {
public var page:Int
public var total:Int
public var records:Int
public var rows:[Node]
public func makeNode() throws->Node {
return try Node(
node:[
"page": page,
"total": total,
"records": records,
"rows": rows.makeNode()
])
}
}
extension RestModel {
public static func prepare(_ database: Database) throws {}
public static func revert(_ database: Database) throws {}
public func makeLeafNode() throws ->Node {
return try makeNode()
}
public static func load(group:Group?,
pageSize:Int = 10,
page:Int = 1,
orderBy:String = "id",
sort:String = "desc",
joins:[Join] = [],
fields:[String] = ["*"]
) throws ->GridResult {
var params:[NodeRepresentable] = []
var index = 1
var whereClause = ""
if let group = group {
func filter(group:Group) ->String {
var index = index
var sql = ""
for rule in group.rules {
sql = sql + "\(group.groupOp) t0.\(rule.field) \(rule.sqlOp) $\(index) "
index = index + 1
params.append(rule.sqlParam)
}
for subGroup in group.groups {
sql = sql + filter(group:subGroup)
}
return sql
}
whereClause = filter(group:group)
}
log.info(params)
let countSql = "select count(1) as c from \(Self.entity) t0 where 1=1 \(whereClause) "
log.info(countSql)
let orderClause = "order by \(orderBy) \(sort) "
let records = try database?.driver.raw(countSql,params) [0]?.object?["c"]?.int ?? 0
let offset = (page-1)*pageSize
let limitClause = "limit \(pageSize) offset \(offset) "
var joinTableClause = ""
var joinFieldClause = " 1=1 "
var fieldsStatment = fields.map{"t0.\($0)"}.joined(separator:",")
if joins.count > 0 {
joinFieldClause = ""
var joinIndex = 1
for join in joins {
let alias = "t\(joinIndex)"
joinTableClause = "\(joinTableClause),\(join.tableName) \(alias) "
joinFieldClause = "\(joinFieldClause) t0.\(join.joinField) = \(alias).id "
for var field in join.fields {
var fieldAlais = field
let parts = field.split(by:",")
if parts.count == 2 {
field = parts[0]
fieldAlais = parts[1]
}
fieldsStatment = fieldsStatment + ",\(alias).\(field) as \(fieldAlais) "
}
joinIndex = joinIndex + 1
}
}
var sql = "select \(fieldsStatment) from \(Self.entity) t0 \(joinTableClause) "
sql = sql + "where " + joinFieldClause
sql = "\(sql) \(whereClause) \(orderClause) \(limitClause) "
log.info(sql)
let rows = try database?.driver.raw(sql,params).nodeArray ?? []
let total = records/pageSize + (records%pageSize > 0 ? 1:0)
return GridResult(
page: page,
total:total,
records:records,
rows:rows
)
}
public func makeNode(context: Context) throws -> Node {
return try makeNode()
}
public static func node(id: NodeRepresentable?) throws ->Node? {
return try load(id:id)?.makeNode()
}
public static func leafNode(id: NodeRepresentable?) throws ->Node? {
return try load(id:id)?.makeLeafNode()
}
public static func load(id: NodeRepresentable?) throws ->Self?{
if id == nil {return nil }
return try Self.find(id!)
}
public static func load(field:String, value: NodeRepresentable?) throws ->Self?{
if value == nil {return nil}
return try Self.query().filter(field, .equals, value!).first()
}
public static func loadCache(id: Node?) throws ->Node?{
if let id = id?.int {
return try Self.loadCache(id:id)
}
return nil
}
public static func loadCache(id: Int) throws ->Node?{
let key = "\(Self.entity)-\(id)"
if let node = Cache.cache[key]{
log.debug("loaded from cache:\(key)")
return node
}
if let model = try Self.load(id:id) {
let node = try model.makeNode()
Cache.cache[key] = node
log.debug("loaded from database:\(key)")
return node
}
return nil
}
public func didUpdate() {
if let id = self.id?.int,id>0 {
let key = "\(Self.entity)-\(id)"
Cache.cache.removeValue(forKey: key)
log.debug("cache removed:\(key)")
}
}
}
final class Cache {
static var cache:[String:Node] = [:]
}
extension RestModel {
public static func all(
_ field: String = "id",
_ direction: Sort.Direction = .descending)
throws ->[Self]{
return try Self.query().sort(field,direction).all()
}
public static func allNodes(
_ field: String = "id",
_ direction: Sort.Direction = .descending)
throws ->[Node]{
return try all(field,direction).map {try $0.makeLeafNode()}
}
public static func allNode(
_ field: String = "id",
_ direction: Sort.Direction = .descending)
throws ->Node{
return try allNodes(field,direction).makeNode()
}
}
extension RestModel {
public static func rawQueryCount(query :String,params:[Node]=[]) throws -> Int {
let tableName = entity
let sql = "select count(1) as c from \(tableName) \(query)"
log.info(sql)
log.info(params)
return try database?.driver.raw(sql,params) [0]?.object?["c"]?.int ?? 0
}
public static func rawQuery(sql :String, params:[Node]=[]) throws -> [Self]{
var array :[Self] = []
if let rows = try database?.driver.raw(sql,params),let nodeArray = rows.nodeArray {
try nodeArray.forEach{array.append(try Self(node:$0))}
}
return array
}
public static func rawQuery(query :String,params:[Node]=[]) throws -> [Self]{
let tableName = entity
let sql = "select * from \(tableName) \(query) "
log.info(sql)
var array :[Self] = []
if let rows = try database?.driver.raw(sql,params),let nodeArray = rows.nodeArray {
try nodeArray.forEach{array.append(try Self(node:$0))}
}
return array
}
public static func rawQueryToLeafNodes(query :String,params:[Node]=[]) throws -> [Node]{
return try rawQuery(query:query,params:params).map(){try $0.makeLeafNode()}
}
}
public protocol HotelBasedModel : RestModel {
var hotelId :Node? {get set}
var channelId :Node? {get set}
}
extension HotelBasedModel {
public static func all(hotelId:Int) throws ->[Self]{
let query = try Self.query()
if hotelId>0 {
try query.filter("hotel_id",hotelId)
}
return try query.sort("id",.descending).all()
}
public static func first(hotelId:Int) throws -> Self?{
let query = try Self.query()
if hotelId>0 {
try query.filter("hotel_id",hotelId)
}
return try query.first()
}
public static func firstNode(hotelId:Int) throws -> Node?{
return try first(hotelId:hotelId)?.makeNode()
}
public static func firstLeafNode(hotelId:Int) throws -> Node?{
return try first(hotelId:hotelId)?.makeNode()
}
public static func allNodes(hotelId:Int) throws ->[Node] {
return try all(hotelId:hotelId).map{try $0.makeNode()}
}
public static func allLeafNodes(hotelId:Int) throws ->[Node]{
return try all(hotelId:hotelId).map{try $0.makeLeafNode()}
}
public func makeLeafNode() throws -> Node {
let node = try makeNode()
//node["hotel"]=try Hotel.loadCache(id:hotelId)
return node
}
}
|
mit
|
2410b48dab34c2cf037cae133d24c7da
| 31.422222 | 94 | 0.549463 | 4.198561 | false | false | false | false |
msaveleva/SpriteKit-tDemo
|
SpriteKittDemo/GameScene.swift
|
1
|
6166
|
//
// GameScene.swift
// SpriteKittDemo
//
// Created by MariaSaveleva on 21/12/2016.
// Copyright © 2016 MariaSaveleva. All rights reserved.
//
import SpriteKit
import GameplayKit
#if os(macOS)
import AppKit
#endif
class GameScene: SKScene, SKPhysicsContactDelegate {
//allow double jump
private let kJumps = 2
private let kCityScrollingVelocity: CGFloat = 20.0 / 4
private let kMountainsVelocity: CGFloat = 5.0 / 4
private let kCloudsVelocity: CGFloat = 2.0 / 4
private var playerStartPoint = CGPoint.zero
private var skyGradient: SKSpriteNode?
private var player: Player?
private var ice: SKSpriteNode?
private var scrollingCityBackground: ScrollingBackground?
private var scrollingMountainsBackground: ScrollingBackground?
private var scrollingCloudsBackground: ScrollingBackground?
//UI
private var coinsCounter: CoinsCounter?
private var platformsGenerator: PlatformsGenerator?
private var platformsNode: SKSpriteNode?
private var jumps = 0
override func didMove(to view: SKView) {
physicsWorld.contactDelegate = self
skyGradient = childNode(withName: "skyGradient") as? SKSpriteNode
scrollingCloudsBackground = childNode(withName: "scrollingCloudsBackground") as? ScrollingBackground
if let _ = self.scrollingCloudsBackground {
configureCloudsBackground()
}
scrollingMountainsBackground = childNode(withName: "scrollingMountainsBackground") as? ScrollingBackground
if let _ = self.scrollingMountainsBackground {
configureMountainsBackground()
}
scrollingCityBackground = childNode(withName: "scrollingCityBackground") as? ScrollingBackground
if let _ = self.scrollingCityBackground {
configureCityBackground()
}
player = childNode(withName: "player") as? Player
if let player = self.player {
player.physicsBody?.categoryBitMask = kPlayerCategory
player.physicsBody?.contactTestBitMask = kIceCategory
player.run()
}
playerStartPoint = calculatePlayerStartPoint()
ice = childNode(withName: "ice") as? SKSpriteNode
if let ice = self.ice {
ice.physicsBody?.categoryBitMask = kIceCategory
ice.physicsBody?.contactTestBitMask = kPlayerCategory
}
platformsGenerator = PlatformsGenerator()
platformsNode = platformsGenerator?.configurePlatformsNode(size: self.size)
if let platformsNode = self.platformsNode {
addChild(platformsNode)
platformsNode.position = self.position
platformsNode.zPosition = 2
}
coinsCounter = childNode(withName: "CoinsCounter") as? CoinsCounter
if let coinsCounter = self.coinsCounter {
coinsCounter.configure()
}
}
override func update(_ currentTime: TimeInterval) {
scrollingCityBackground?.update(currentTime: currentTime)
scrollingMountainsBackground?.update(currentTime: currentTime)
scrollingCloudsBackground?.update(currentTime: currentTime)
platformsGenerator?.updatePlatform(velocity: kCityScrollingVelocity)
checkPlayerPosition()
}
//MARK: - Private methods
private func configureCityBackground() {
scrollingCityBackground?.velocity = kCityScrollingVelocity
scrollingCityBackground?.backgroundImagesNames = ["city01", "city02", "city03", "city04", "city05", "city06", "city07", "city08"]
scrollingCityBackground?.configureScrollingBackground()
}
private func configureMountainsBackground() {
scrollingMountainsBackground?.velocity = kMountainsVelocity
scrollingMountainsBackground?.backgroundImagesNames = ["mountains01", "mountains02", "mountains03", "mountains04", "mountains05", "mountains06", "mountains07", "mountains08"]
scrollingMountainsBackground?.configureScrollingBackground()
}
private func configureCloudsBackground() {
scrollingCloudsBackground?.velocity = kCloudsVelocity
scrollingCloudsBackground?.backgroundImagesNames = ["clouds01", "clouds02", "clouds03", "clouds04", "clouds05", "clouds06", "clouds07", "clouds08"]
scrollingCloudsBackground?.configureScrollingBackground()
}
private func checkPlayerPosition() {
guard let player = self.player else { return }
//Don't allow player to hide on left side
if player.position.x < -frame.width / 2 {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
player.position = self.playerStartPoint
})
}
}
private func calculatePlayerStartPoint() -> CGPoint {
let x = -frame.width / 2 + frame.width/4
let y = frame.height / 2 + frame.height/4
return CGPoint(x: x, y: y)
}
private func userInteraction() {
if jumps < kJumps {
player?.jump()
jumps += 1
player?.physicsBody?.applyImpulse(CGVector(dx: 0.0, dy: 200.0)) //impulse vs force?
}
}
//MARK: - SKPhysicsContactDelegate methods
func didBegin(_ contact: SKPhysicsContact) {
player?.inAir = false
player?.run()
jumps = 0
//coins
if contact.bodyB.node is Coin {
if let coin = contact.bodyB.node as? Coin {
coinsCounter?.increaseCounter()
coin.collected()
}
}
}
#if os(iOS)
//MARK: - Touch methods
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
userInteraction()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
}
#elseif os(macOS)
override func keyDown(with event: NSEvent) {
super.keyDown(with: event)
if event.keyCode == 49 { //space bar keyCode
userInteraction()
}
}
#endif
}
|
mit
|
62b4deb8d4960bf174be6a2b18123567
| 31.967914 | 182 | 0.661638 | 4.786491 | false | true | false | false |
agilewalker/SwiftyChardet
|
SwiftyChardet/chardistribution.swift
|
1
|
9430
|
/*
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Wu Hui Yuan - port to Swift
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
*/
class CharDistributionAnalysis {
let ENOUGH_DATA_THRESHOLD = 1024
let SURE_YES = 0.99
let SURE_NO = 0.01
let MINIMUM_DATA_THRESHOLD = 3
var _char_to_freq_order: [Int]
var _table_size: Int
var typical_distribution_ratio: Double
var _total_chars: Int
var _freq_chars: Int
var _done: Bool
init() {
// Mapping table to get frequency order from char order (get from
// GetOrder())
self._char_to_freq_order = []
self._table_size = 0 // Size of above table
// This is a constant value which varies from language to language,
// used in calculating confidence. See
// http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html
// for further detail.
self.typical_distribution_ratio = 0.0
self._done = false
self._total_chars = 0
self._freq_chars = 0
self.reset()
}
func reset() {
//"""reset analyser, clear any state"""
// If this flag is set to True, detection is done and conclusion has
// been made
self._done = false
self._total_chars = 0 // Total characters encountered
// The number of characters whose frequency order is less than 512
self._freq_chars = 0
}
func feed(_ char: Data, _ char_len: Int) {
//"""feed a character with known length"""
var order: Int
if char_len == 2 {
// we only care about 2-bytes character in our distribution analysis
order = self.getOrder(char)
} else {
order = -1
}
if order >= 0 {
self._total_chars += 1
// order is valid
if order < self._table_size {
if 512 > self._char_to_freq_order[order] {
self._freq_chars += 1
}
}
}
}
var confidence: Double {
//"""return confidence based on existing data"""
// if we didn't receive any character in our consideration range,
// return negative answer
if self._total_chars <= 0 || self._freq_chars <= self.MINIMUM_DATA_THRESHOLD {
return self.SURE_NO
}
if self._total_chars != self._freq_chars {
let r = (Double(self._freq_chars) / (Double(self._total_chars - self._freq_chars)
* self.typical_distribution_ratio))
if r < self.SURE_YES {
return r
}
}
// normalize confidence (we don't want to be 100% sure)
return self.SURE_YES
}
var gotEnoughData: Bool {
// It is not necessary to receive all data to draw conclusion.
// For charset detection, certain amount of data is enough
return self._total_chars > self.ENOUGH_DATA_THRESHOLD
}
func getOrder(_ str: Data) -> Int {
// We do not handle characters based on the original encoding string,
// but convert this encoding string to a number, here called order.
// This allows multiple encodings of a language to share one frequency
// table.
return -1
}
}
class EUCTWDistributionAnalysis: CharDistributionAnalysis {
override init() {
super.init()
self._char_to_freq_order = EUCTW_CHAR_TO_FREQ_ORDER
self._table_size = EUCTW_TABLE_SIZE
self.typical_distribution_ratio = EUCTW_TYPICAL_DISTRIBUTION_RATIO
}
override func getOrder(_ byte_str: Data) -> Int {
// for euc-TW encoding, we are interested
// first byte range: 0xc4 -- 0xfe
// second byte range: 0xa1 -- 0xfe
// no validation needed here. State machine has done that
let first_char = byte_str[0]
if first_char >= 0xC4 {
return 94 * Int(first_char - 0xC4) + Int(byte_str[1]) - 0xA1
} else {
return -1
}
}
}
class EUCKRDistributionAnalysis: CharDistributionAnalysis {
override init() {
super.init()
self._char_to_freq_order = EUCKR_CHAR_TO_FREQ_ORDER
self._table_size = EUCKR_TABLE_SIZE
self.typical_distribution_ratio = EUCKR_TYPICAL_DISTRIBUTION_RATIO
}
override func getOrder(_ byte_str: Data) -> Int {
// for euc-KR encoding, we are interested
// first byte range: 0xb0 -- 0xfe
// second byte range: 0xa1 -- 0xfe
// no validation needed here. State machine has done that
let first_char = byte_str[0]
if first_char >= 0xB0 {
return 94 * Int(first_char - 0xB0) + Int(byte_str[1]) - 0xA1
} else {
return -1
}
}
}
class GB2312DistributionAnalysis: CharDistributionAnalysis {
override init() {
super.init()
self._char_to_freq_order = GB2312_CHAR_TO_FREQ_ORDER
self._table_size = GB2312_TABLE_SIZE
self.typical_distribution_ratio = GB2312_TYPICAL_DISTRIBUTION_RATIO
}
override func getOrder(_ byte_str: Data) -> Int {
// for GB2312 encoding, we are interested
// first byte range: 0xb0 -- 0xfe
// second byte range: 0xa1 -- 0xfe
// no validation needed here. State machine has done that
let (first_char, second_char) = (byte_str[0], byte_str[1])
if (first_char >= 0xB0) && (second_char >= 0xA1) {
return 94 * Int(first_char - 0xB0) + Int(second_char) - 0xA1
} else {
return -1
}
}
}
class Big5DistributionAnalysis: CharDistributionAnalysis {
override init() {
super.init()
self._char_to_freq_order = BIG5_CHAR_TO_FREQ_ORDER
self._table_size = BIG5_TABLE_SIZE
self.typical_distribution_ratio = BIG5_TYPICAL_DISTRIBUTION_RATIO
}
override func getOrder(_ byte_str: Data) -> Int {
// for big5 encoding, we are interested
// first byte range: 0xa4 -- 0xfe
// second byte range: 0x40 -- 0x7e , 0xa1 -- 0xfe
// no validation needed here. State machine has done that
let (first_char, second_char) = (byte_str[0], byte_str[1])
if first_char >= 0xA4 {
if second_char >= 0xA1 {
return 157 * Int(first_char - 0xA4) + Int(second_char) - 0xA1 + 63
} else {
return 157 * Int(first_char - 0xA4) + Int(second_char) - 0x40
}
} else {
return -1
}
}
}
class SJISDistributionAnalysis: CharDistributionAnalysis {
override init() {
super.init()
self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER
self._table_size = JIS_TABLE_SIZE
self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO
}
override func getOrder(_ byte_str: Data) -> Int {
// for sjis encoding, we are interested
// first byte range: 0x81 -- 0x9f , 0xe0 -- 0xfe
// second byte range: 0x40 -- 0x7e, 0x81 -- oxfe
// no validation needed here. State machine has done that
let (first_char, second_char) = (byte_str[0], byte_str[1])
var order: Int
if (first_char >= 0x81) && (first_char <= 0x9F) {
order = 188 * Int(first_char - 0x81)
} else if (first_char >= 0xE0) && (first_char <= 0xEF) {
order = 188 * Int(first_char - 0xE0 + 31)
} else {
return -1
}
order = order + Int(second_char) - 0x40
if second_char > 0x7F {
order = -1
}
return order
}
}
class EUCJPDistributionAnalysis: CharDistributionAnalysis {
override init() {
super.init()
self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER
self._table_size = JIS_TABLE_SIZE
self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO
}
override func getOrder(_ byte_str: Data) -> Int {
// for euc-JP encoding, we are interested
// first byte range: 0xa0 -- 0xfe
// second byte range: 0xa1 -- 0xfe
// no validation needed here. State machine has done that
let char = byte_str[0]
if char >= 0xA0 {
return 94 * Int(char - 0xA1) + Int(byte_str[1]) - 0xa1
} else {
return -1
}
}
}
|
lgpl-2.1
|
fb6eb4173332a433e72b8bacf08df9b8
| 34.186567 | 93 | 0.585366 | 3.831776 | false | false | false | false |
coodly/ios-gambrinus
|
Packages/Sources/KioskCore/Persistence/Persistence+Mappings.swift
|
1
|
1322
|
/*
* Copyright 2016 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
import CoreData
extension NSManagedObjectContext {
internal func createMappings(from posts: [CloudPost]) {
let postIds = posts.compactMap({ $0.identifier })
let predicate = NSPredicate(format: "postId IN %@", postIds)
let locals: [Post] = fetch(predicate: predicate)
for post in posts {
guard let saved = locals.first(where: { $0.postId == post.identifier }) else {
continue
}
let beers = beersWith(rbIds: post.rateBeers ?? [])
saved.beers = Set(beers)
let untappd = self.untappd(with: post.untappd ?? [])
saved.untappd = Set(untappd)
}
}
}
|
apache-2.0
|
969b3c0136f29bdbb3413fb9741c8f01
| 33.789474 | 90 | 0.639939 | 4.292208 | false | false | false | false |
ctime95/AJMListApp
|
AJMFlowLayout.swift
|
1
|
3323
|
//
// AJMFlowLayout.swift
// AJMListApp
//
// Created by Angel Jesse Morales Karam Kairuz on 05/09/17.
// Copyright © 2017 TheKairuzBlog. All rights reserved.
//
import UIKit
class AJMFlowLayout: UICollectionViewFlowLayout {
var allAttributes = [IndexPath : UICollectionViewLayoutAttributes]()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
itemSize = CGSize(width: 300, height: 300)
}
override func prepare() {
super.prepare()
scrollDirection = .horizontal
collectionView?.decelerationRate = UIScrollViewDecelerationRateFast
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let array = super.layoutAttributesForElements(in: rect)!
setUpInitialPositionForLayoutAttributes(array)
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for (_, value) in allAttributes {
var posX = value.frame.origin.x + collectionView!.contentInset.left
var percent : CGFloat = 0
if collectionView!.contentOffset.x >= posX {
posX = collectionView!.contentOffset.x + collectionView!.contentInset.left
percent = min(abs(collectionView!.contentOffset.x / (posX + itemSize.width)), 1.0)
}
let attribute = UICollectionViewLayoutAttributes(forCellWith: value.indexPath)
attribute.frame = CGRect(x: posX, y: value.frame.origin.y, width: itemSize.width, height: itemSize.height)
addRotateEffect(attribute: attribute, percent: percent)
layoutAttributes.append(attribute)
}
return layoutAttributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if let value = allAttributes[indexPath] {
return value
}
return UICollectionViewLayoutAttributes()
}
//MARK :- HELPER FUNCTIONS
func setUpInitialPositionForLayoutAttributes(_ attributes : [UICollectionViewLayoutAttributes]) {
for attr in attributes {
if let _ = allAttributes[attr.indexPath] { } else {
let posY = (collectionView!.bounds.height - itemSize.height) / 2
attr.frame = CGRect(x: attr.frame.origin.x, y: posY, width: itemSize.width, height: itemSize.height)
allAttributes.updateValue(attr, forKey: attr.indexPath)
}
}
}
func addRotateEffect(attribute : UICollectionViewLayoutAttributes, percent : CGFloat) {
// create 3D effect
var transform = CATransform3DIdentity
transform.m34 = -1.0 / 500.0
transform = CATransform3DRotate(transform, CGFloat(M_PI_4) * percent, 0, 1, 0)
if attribute.indexPath.section != 0 {
if percent >= 0.5 {
attribute.alpha = 1
} else {
attribute.alpha = 0
}
}
attribute.transform3D = transform
}
}
|
mit
|
4085330212f4aa4075a10a9df0461eb6
| 32.897959 | 118 | 0.610777 | 5.401626 | false | false | false | false |
4taras4/totp-auth
|
TOTP/Extensions/AutoBlurManager.swift
|
1
|
2085
|
//
// AutoBlurManager.swift
// TOTP
//
// Created by Taras Markevych on 10.10.2020.
// Copyright © 2020 Taras Markevych. All rights reserved.
//
import Foundation
import UIKit
public class AutoBlurScreen {
private var newBlur: UIImageView?
public var blurStyle: UIBlurEffect.Style = .light
public var isAutoBlur: Bool = true
public init() {
NotificationCenter.default.addObserver(self,
selector: #selector(remoteBlur),
name: UIApplication.didBecomeActiveNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(addBlur),
name: UIApplication.willResignActiveNotification,
object: nil)
}
@objc private func addBlur() {
if isAutoBlur {
createBlurEffect()
}
}
@objc private func remoteBlur() {
if isAutoBlur {
removeBlurEffect()
}
}
public func createBlurEffect() {
newBlur = UIImageView(frame: UIManager.shared.window!.frame)
guard let newBlur = newBlur else { return }
let blurEffect = UIBlurEffect(style: self.blurStyle)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = UIManager.shared.window!.frame
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
newBlur.addSubview(blurEffectView)
if let top = UIApplication.topViewController()?.navigationController {
top.view.addSubview(newBlur)
}
}
public func removeBlurEffect() {
if let blur = newBlur {
let blurredEffectViews = blur.subviews.filter{ $0 is UIVisualEffectView }
blurredEffectViews.forEach { blurView in
blurView.removeFromSuperview()
}
newBlur = nil
}
}
}
|
mit
|
97721f7b0134ad3539f2180b4bce3862
| 32.079365 | 96 | 0.569578 | 5.587131 | false | false | false | false |
ArthurGuibert/LiveBusSwift
|
BusExtension/TodayViewController.swift
|
1
|
2852
|
//
// TodayViewController.swift
// BusExtension
//
// Created by Arthur GUIBERT on 01/02/2015.
// Copyright (c) 2015 Arthur GUIBERT. All rights reserved.
//
import UIKit
import NotificationCenter
import CoreLocation
class TodayViewController: UITableViewController, NCWidgetProviding {
var departures: [Departure]?
override func viewDidLoad() {
super.viewDidLoad()
// Regestering the custom cell we're going to use
var nib = UINib(nibName: "TodayDepartureCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "TodayCell")
// Do any additional setup after loading the view from its nib.
self.preferredContentSize = CGSizeMake(0, 218);
let userDefault = NSUserDefaults(suiteName: "group.com.slipcorp.LiveBus")
let name = userDefault?.stringForKey("favoriteStopName")
let code = userDefault?.stringForKey("favoriteStopCode")
if name != nil && code != nil {
let favorite = BusStop(code: code, name: name)
Departure.getDepartures(favorite, { (departures: Array<Departure>) -> Void in
self.departures = departures
if self.departures != nil {
self.departures!.sort({$0.departureTime < $1.departureTime})
}
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
completionHandler(NCUpdateResult.NewData)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let departure: Departure = departures![indexPath.row]
var cell = tableView.dequeueReusableCellWithIdentifier("TodayCell") as TodayDepartureCell
cell.lineLabel.text = departure.line
cell.directionLabel.text = departure.direction
let t = Int(departure.departureTime! / 60)
if t == 0 {
cell.timeLabel.text = "due"
} else {
cell.timeLabel.text = "\(t) min"
}
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if departures == nil {
return 0
}
return departures!.count
}
func widgetMarginInsetsForProposedMarginInsets
(defaultMarginInsets: UIEdgeInsets) -> (UIEdgeInsets) {
return UIEdgeInsetsZero
}
}
|
mit
|
becb3cca7ba0cbd719511ca8f041b75c
| 32.552941 | 118 | 0.611501 | 5.381132 | false | false | false | false |
practicalswift/swift
|
test/stmt/statements.swift
|
2
|
19310
|
// RUN: %target-typecheck-verify-swift
/* block comments */
/* /* nested too */ */
func markUsed<T>(_ t: T) {}
func f1(_ a: Int, _ y: Int) {}
func f2() {}
func f3() -> Int {}
func invalid_semi() {
; // expected-error {{';' statements are not allowed}} {{3-5=}}
}
func nested1(_ x: Int) {
var y : Int
func nested2(_ z: Int) -> Int {
return x+y+z
}
_ = nested2(1)
}
func funcdecl5(_ a: Int, y: Int) {
var x : Int
// a few statements
if (x != 0) {
if (x != 0 || f3() != 0) {
// while with and without a space after it.
while(true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}}
while (true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}}
}
}
// Assignment statement.
x = y
(x) = y
1 = x // expected-error {{cannot assign to a literal value}}
(1) = x // expected-error {{cannot assign to a literal value}}
"string" = "other" // expected-error {{cannot assign to a literal value}}
[1, 1, 1, 1] = [1, 1] // expected-error {{cannot assign to immutable expression of type '[Int]}}
1.0 = x // expected-error {{cannot assign to a literal value}}
nil = 1 // expected-error {{cannot assign to a literal value}}
(x:1).x = 1 // expected-error {{cannot assign to immutable expression of type 'Int'}}
var tup : (x:Int, y:Int)
tup.x = 1
_ = tup
let B : Bool
// if/then/else.
if (B) {
} else if (y == 2) {
}
// This diagnostic is terrible - rdar://12939553
if x {} // expected-error {{'Int' is not convertible to 'Bool'}}
if true {
if (B) {
} else {
}
}
if (B) {
f1(1,2)
} else {
f2()
}
if (B) {
if (B) {
f1(1,2)
} else {
f2()
}
} else {
f2()
}
// while statement.
while (B) {
}
// It's okay to leave out the spaces in these.
while(B) {}
if(B) {}
}
struct infloopbool {
var boolValue: infloopbool {
return self
}
}
func infloopbooltest() {
if (infloopbool()) {} // expected-error {{'infloopbool' is not convertible to 'Bool'}}
}
// test "builder" API style
extension Int {
static func builder() -> Int { }
var builderProp: Int { return 0 }
func builder2() {}
}
Int
.builder()
.builderProp
.builder2()
struct SomeGeneric<T> {
static func builder() -> SomeGeneric<T> { }
var builderProp: SomeGeneric<T> { return .builder() }
func builder2() {}
}
SomeGeneric<Int>
.builder()
.builderProp
.builder2()
break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}}
continue // expected-error {{'continue' is only allowed inside a loop}}
while true {
func f() {
break // expected-error {{'break' is only allowed inside a loop}}
continue // expected-error {{'continue' is only allowed inside a loop}}
}
// Labeled if
MyIf: if 1 != 2 {
break MyIf
continue MyIf // expected-error {{'continue' cannot be used with if statements}}
break // break the while
continue // continue the while.
}
}
// Labeled if
MyOtherIf: if 1 != 2 {
break MyOtherIf
continue MyOtherIf // expected-error {{'continue' cannot be used with if statements}}
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if}}
continue // expected-error {{'continue' is only allowed inside a loop}}
}
do {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
func tuple_assign() {
var a,b,c,d : Int
(a,b) = (1,2)
func f() -> (Int,Int) { return (1,2) }
((a,b), (c,d)) = (f(), f())
}
func missing_semicolons() {
var w = 321
func g() {}
g() w += 1 // expected-error{{consecutive statements}} {{6-6=;}}
var z = w"hello" // expected-error{{consecutive statements}} {{12-12=;}} expected-warning {{string literal is unused}}
class C {}class C2 {} // expected-error{{consecutive statements}} {{14-14=;}}
struct S {}struct S2 {} // expected-error{{consecutive statements}} {{14-14=;}}
func j() {}func k() {} // expected-error{{consecutive statements}} {{14-14=;}}
}
//===--- Return statement.
return 42 // expected-error {{return invalid outside of a func}}
return // expected-error {{return invalid outside of a func}}
func NonVoidReturn1() -> Int {
return // expected-error {{non-void function should return a value}}
}
func NonVoidReturn2() -> Int {
return + // expected-error {{unary operator cannot be separated from its operand}} {{11-1=}} expected-error {{expected expression in 'return' statement}}
}
func VoidReturn1() {
if true { return }
// Semicolon should be accepted -- rdar://11344875
return; // no-error
}
func VoidReturn2() {
return () // no-error
}
func VoidReturn3() {
return VoidReturn2() // no-error
}
//===--- If statement.
func IfStmt1() {
if 1 > 0 // expected-error {{expected '{' after 'if' condition}}
_ = 42
}
func IfStmt2() {
if 1 > 0 {
} else // expected-error {{expected '{' or 'if' after 'else'}}
_ = 42
}
func IfStmt3() {
if 1 > 0 {
} else 1 < 0 { // expected-error {{expected '{' or 'if' after 'else'; did you mean to write 'if'?}} {{9-9= if}}
_ = 42
} else {
}
}
//===--- While statement.
func WhileStmt1() {
while 1 > 0 // expected-error {{expected '{' after 'while' condition}}
_ = 42
}
//===-- Do statement.
func DoStmt() {
// This is just a 'do' statement now.
do {
}
}
func DoWhileStmt() {
do { // expected-error {{'do-while' statement is not allowed; use 'repeat-while' instead}} {{3-5=repeat}}
} while true
}
//===--- Repeat-while statement.
func RepeatWhileStmt1() {
repeat {} while true
repeat {} while false
repeat { break } while true
repeat { continue } while true
}
func RepeatWhileStmt2() {
repeat // expected-error {{expected '{' after 'repeat'}} expected-error {{expected 'while' after body of 'repeat' statement}}
}
func RepeatWhileStmt4() {
repeat {
} while + // expected-error {{unary operator cannot be separated from its operand}} {{12-1=}} expected-error {{expected expression in 'repeat-while' condition}}
}
func brokenSwitch(_ x: Int) -> Int {
switch x {
case .Blah(var rep): // expected-error{{pattern cannot match values of type 'Int'}}
return rep
}
}
func switchWithVarsNotMatchingTypes(_ x: Int, y: Int, z: String) -> Int {
switch (x,y,z) {
case (let a, 0, _), (0, let a, _): // OK
return a
case (let a, _, _), (_, _, let a): // expected-error {{pattern variable bound to type 'String', expected type 'Int'}}
// expected-warning@-1 {{case is already handled by previous patterns; consider removing it}}
return a
}
}
func breakContinue(_ x : Int) -> Int {
Outer:
for _ in 0...1000 {
Switch: // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
switch x {
case 42: break Outer
case 97: continue Outer
case 102: break Switch
case 13: continue
case 139: break // <rdar://problem/16563853> 'break' should be able to break out of switch statements
}
}
// <rdar://problem/16692437> shadowing loop labels should be an error
Loop: // expected-note {{previously declared here}}
for _ in 0...2 {
Loop: // expected-error {{label 'Loop' cannot be reused on an inner statement}}
for _ in 0...2 {
}
}
// <rdar://problem/16798323> Following a 'break' statement by another statement on a new line result in an error/fit-it
switch 5 {
case 5:
markUsed("before the break")
break
markUsed("after the break") // 'markUsed' is not a label for the break.
default:
markUsed("")
}
let x : Int? = 42
// <rdar://problem/16879701> Should be able to pattern match 'nil' against optionals
switch x { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.some(_)'}}
case .some(42): break
case nil: break
}
}
enum MyEnumWithCaseLabels {
case Case(one: String, two: Int)
}
func testMyEnumWithCaseLabels(_ a : MyEnumWithCaseLabels) {
// <rdar://problem/20135489> Enum case labels are ignored in "case let" statements
switch a {
case let .Case(one: _, two: x): break // ok
case let .Case(xxx: _, two: x): break // expected-error {{tuple pattern element label 'xxx' must be 'one'}}
// TODO: In principle, reordering like this could be supported.
case let .Case(two: _, one: x): break // expected-error {{tuple pattern element label}}
}
}
// "defer"
func test_defer(_ a : Int) {
defer { VoidReturn1() }
defer { breakContinue(1)+42 } // expected-warning {{result of operator '+' is unused}}
// Ok:
defer { while false { break } }
// Not ok.
while false { defer { break } } // expected-error {{'break' cannot transfer control out of a defer statement}}
// expected-warning@-1 {{'defer' statement before end of scope always executes immediately}}{{17-22=do}}
defer { return } // expected-error {{'return' cannot transfer control out of a defer statement}}
// expected-warning@-1 {{'defer' statement before end of scope always executes immediately}}{{3-8=do}}
}
class SomeTestClass {
var x = 42
func method() {
defer { x = 97 } // self. not required here!
// expected-warning@-1 {{'defer' statement before end of scope always executes immediately}}{{5-10=do}}
}
}
class SomeDerivedClass: SomeTestClass {
override init() {
defer {
super.init() // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
}
}
func test_guard(_ x : Int, y : Int??, cond : Bool) {
// These are all ok.
guard let a = y else {}
markUsed(a)
guard let b = y, cond else {}
guard case let c = x, cond else {}
guard case let Optional.some(d) = y else {}
guard x != 4, case _ = x else { }
guard let e, cond else {} // expected-error {{variable binding in a condition requires an initializer}}
guard case let f? : Int?, cond else {} // expected-error {{variable binding in a condition requires an initializer}}
guard let g = y else {
markUsed(g) // expected-error {{variable declared in 'guard' condition is not usable in its body}}
}
guard let h = y, cond {} // expected-error {{expected 'else' after 'guard' condition}} {{25-25=else }}
guard case _ = x else {} // expected-warning {{'guard' condition is always true, body is unreachable}}
// SR-7567
guard let outer = y else {
guard true else {
print(outer) // expected-error {{variable declared in 'guard' condition is not usable in its body}}
}
}
}
func test_is_as_patterns() {
switch 4 {
case is Int: break // expected-warning {{'is' test is always true}}
case _ as Int: break // expected-warning {{'as' test is always true}}
// expected-warning@-1 {{case is already handled by previous patterns; consider removing it}}
case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
}
// <rdar://problem/21387308> Fuzzing SourceKit: crash in Parser::parseStmtForEach(...)
func matching_pattern_recursion() {
switch 42 {
case { // expected-error {{expression pattern of type '() -> ()' cannot match values of type 'Int'}}
for i in zs {
}
}: break
}
}
// <rdar://problem/18776073> Swift's break operator in switch should be indicated in errors
func r18776073(_ a : Int?) {
switch a {
case nil: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{14-14= break}}
case _?: break
}
}
// <rdar://problem/22491782> unhelpful error message from "throw nil"
func testThrowNil() throws {
throw nil // expected-error {{cannot infer concrete Error for thrown 'nil' value}}
}
// rdar://problem/23684220
// Even if the condition fails to typecheck, save it in the AST anyway; the old
// condition may have contained a SequenceExpr.
func r23684220(_ b: Any) {
if let _ = b ?? b {} // expected-error {{initializer for conditional binding must have Optional type, not 'Any'}}
// expected-warning@-1 {{left side of nil coalescing operator '??' has non-optional type 'Any', so the right side is never used}}
}
// <rdar://problem/21080671> QoI: try/catch (instead of do/catch) creates silly diagnostics
func f21080671() {
try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}}
} catch { }
try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}}
f21080671()
} catch let x as Int {
} catch {
}
}
// <rdar://problem/24467411> QoI: Using "&& #available" should fixit to comma
// https://twitter.com/radexp/status/694561060230184960
func f(_ x : Int, y : Int) {
if x == y && #available(iOS 52, *) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}}
if #available(iOS 52, *) && x == y {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{27-30=,}}
// https://twitter.com/radexp/status/694790631881883648
if x == y && let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}}
if x == y&&let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-14=,}}
}
// <rdar://problem/25178926> QoI: Warn about cases where switch statement "ignores" where clause
enum Type {
case Foo
case Bar
}
func r25178926(_ a : Type) {
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Bar'}}
case .Foo, .Bar where 1 != 100:
// expected-warning @-1 {{'where' only applies to the second pattern match in this case}}
// expected-note @-2 {{disambiguate by adding a line break between them if this is desired}} {{14-14=\n }}
// expected-note @-3 {{duplicate the 'where' on both patterns to check both patterns}} {{12-12= where 1 != 100}}
break
}
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Bar'}}
case .Foo: break
case .Bar where 1 != 100: break
}
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Bar'}}
case .Foo, // no warn
.Bar where 1 != 100:
break
}
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Foo'}}
// expected-note@-2 {{missing case: '.Bar'}}
case .Foo where 1 != 100, .Bar where 1 != 100:
break
}
}
do {
guard 1 == 2 else {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
}
func fn(a: Int) {
guard a < 1 else {
break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}}
}
}
func fn(x: Int) {
if x >= 0 {
guard x < 1 else {
guard x < 2 else {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
return
}
}
}
func bad_if() {
if 1 {} // expected-error {{'Int' is not convertible to 'Bool'}}
if (x: false) {} // expected-error {{'(x: Bool)' is not convertible to 'Bool'}}
if (x: 1) {} // expected-error {{'(x: Int)' is not convertible to 'Bool'}}
}
// Typo correction for loop labels
for _ in [1] {
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
while true {
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
repeat {
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
} while true
outerLoop: for _ in [1] { // expected-note {{'outerLoop' declared here}}
break outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{9-18=outerLoop}}
}
outerLoop: for _ in [1] { // expected-note {{'outerLoop' declared here}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{12-21=outerLoop}}
}
outerLoop: while true { // expected-note {{'outerLoop' declared here}}
break outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{9-18=outerLoop}}
}
outerLoop: while true { // expected-note {{'outerLoop' declared here}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{12-21=outerLoop}}
}
outerLoop: repeat { // expected-note {{'outerLoop' declared here}}
break outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{9-18=outerLoop}}
} while true
outerLoop: repeat { // expected-note {{'outerLoop' declared here}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{12-21=outerLoop}}
} while true
outerLoop1: for _ in [1] { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}}
outerLoop2: for _ in [1] { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}}
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
}
outerLoop1: for _ in [1] { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}}
outerLoop2: for _ in [1] { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
}
outerLoop1: while true { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}}
outerLoop2: while true { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}}
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
}
outerLoop1: while true { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}}
outerLoop2: while true { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
}
outerLoop1: repeat { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}}
outerLoop2: repeat { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}}
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
} while true
} while true
outerLoop1: repeat { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}}
outerLoop2: repeat { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
} while true
} while true
// Errors in case syntax
class
case, // expected-error {{expected identifier in enum 'case' declaration}} expected-error {{expected pattern}}
case // expected-error {{expected identifier after comma in enum 'case' declaration}} expected-error {{expected identifier in enum 'case' declaration}} expected-error {{enum 'case' is not allowed outside of an enum}} expected-error {{expected pattern}}
// NOTE: EOF is important here to properly test a code path that used to crash the parser
|
apache-2.0
|
396b4e60bb224c1f3a32e2bc0fbe6a29
| 30.864686 | 253 | 0.638063 | 3.635166 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/CryptoAssets/Sources/BitcoinCashKit/Domain/Models/Coincore/BitcoinCashCryptoAccount.swift
|
1
|
8061
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BitcoinChainKit
import Combine
import DIKit
import Localization
import MoneyKit
import PlatformKit
import RxSwift
import ToolKit
import WalletPayloadKit
final class BitcoinCashCryptoAccount: BitcoinChainCryptoAccount {
let coinType: BitcoinChainCoin = .bitcoinCash
private(set) lazy var identifier: AnyHashable = "BitcoinCashCryptoAccount.\(xPub.address).\(xPub.derivationType)"
let label: String
let asset: CryptoCurrency = .bitcoinCash
let isDefault: Bool
let hdAccountIndex: Int
func createTransactionEngine() -> Any {
BitcoinOnChainTransactionEngineFactory<BitcoinCashToken>()
}
var pendingBalance: AnyPublisher<MoneyValue, Error> {
.just(.zero(currency: .bitcoinCash))
}
var balance: AnyPublisher<MoneyValue, Error> {
balanceService
.balance(for: xPub)
.map(\.moneyValue)
.eraseToAnyPublisher()
}
var actionableBalance: AnyPublisher<MoneyValue, Error> {
balance
}
var receiveAddress: AnyPublisher<ReceiveAddress, Error> {
nativeWalletEnabled()
.flatMap { [receiveAddressProvider, bridge, hdAccountIndex, xPub] isEnabled
-> AnyPublisher<String, Error> in
guard isEnabled else {
return bridge
.receiveAddress(forXPub: xPub.address)
.asPublisher()
.eraseToAnyPublisher()
}
return receiveAddressProvider
.receiveAddressProvider(UInt32(hdAccountIndex))
.map { $0.replacingOccurrences(of: "bitcoincash:", with: "") }
.eraseError()
.eraseToAnyPublisher()
}
.map { [label, onTxCompleted] address -> ReceiveAddress in
BitcoinChainReceiveAddress<BitcoinCashToken>(
address: address,
label: label,
onTxCompleted: onTxCompleted
)
}
.eraseToAnyPublisher()
}
var firstReceiveAddress: AnyPublisher<ReceiveAddress, Error> {
nativeWalletEnabled()
.flatMap { [receiveAddressProvider, bridge, hdAccountIndex, xPub] isEnabled
-> AnyPublisher<String, Error> in
guard isEnabled else {
return bridge
.firstReceiveAddress(forXPub: xPub.address)
.asPublisher()
.eraseToAnyPublisher()
}
return receiveAddressProvider
.firstReceiveAddressProvider(UInt32(hdAccountIndex))
.map { $0.replacingOccurrences(of: "bitcoincash:", with: "") }
.eraseError()
.eraseToAnyPublisher()
}
.map { [label, onTxCompleted] address -> ReceiveAddress in
BitcoinChainReceiveAddress<BitcoinCashToken>(
address: address,
label: label,
onTxCompleted: onTxCompleted
)
}
.eraseToAnyPublisher()
}
var activity: AnyPublisher<[ActivityItemEvent], Error> {
nonCustodialActivity.zip(swapActivity)
.map { nonCustodialActivity, swapActivity in
Self.reconcile(swapEvents: swapActivity, noncustodial: nonCustodialActivity)
}
.eraseError()
.eraseToAnyPublisher()
}
private var isInterestTransferAvailable: AnyPublisher<Bool, Never> {
guard asset.supports(product: .interestBalance) else {
return .just(false)
}
return isInterestWithdrawAndDepositEnabled
.zip(canPerformInterestTransfer)
.map { isEnabled, canPerform in
isEnabled && canPerform
}
.replaceError(with: false)
.eraseToAnyPublisher()
}
private var nonCustodialActivity: AnyPublisher<[TransactionalActivityItemEvent], Never> {
transactionsService
.transactions(publicKeys: [xPub])
.map { response in
response
.map(\.activityItemEvent)
}
.replaceError(with: [])
.eraseToAnyPublisher()
}
private var swapActivity: AnyPublisher<[SwapActivityItemEvent], Never> {
swapTransactionsService
.fetchActivity(cryptoCurrency: asset, directions: custodialDirections)
.replaceError(with: [])
.eraseToAnyPublisher()
}
private var isInterestWithdrawAndDepositEnabled: AnyPublisher<Bool, Never> {
featureFlagsService
.isEnabled(.interestWithdrawAndDeposit)
.replaceError(with: false)
.eraseToAnyPublisher()
}
let xPub: XPub
private let featureFlagsService: FeatureFlagsServiceAPI
private let balanceService: BalanceServiceAPI
private let priceService: PriceServiceAPI
private let bridge: BitcoinCashWalletBridgeAPI
private let transactionsService: BitcoinCashHistoricalTransactionServiceAPI
private let swapTransactionsService: SwapActivityServiceAPI
private let nativeWalletEnabled: () -> AnyPublisher<Bool, Never>
private let receiveAddressProvider: BitcoinChainReceiveAddressProviderAPI
init(
xPub: XPub,
label: String?,
isDefault: Bool,
hdAccountIndex: Int,
priceService: PriceServiceAPI = resolve(),
transactionsService: BitcoinCashHistoricalTransactionServiceAPI = resolve(),
swapTransactionsService: SwapActivityServiceAPI = resolve(),
balanceService: BalanceServiceAPI = resolve(tag: BitcoinChainCoin.bitcoinCash),
bridge: BitcoinCashWalletBridgeAPI = resolve(),
featureFlagsService: FeatureFlagsServiceAPI = resolve(),
nativeWalletEnabled: @escaping () -> AnyPublisher<Bool, Never> = { nativeWalletFlagEnabled() },
receiveAddressProvider: BitcoinChainReceiveAddressProviderAPI = resolve(
tag: BitcoinChainKit.BitcoinChainCoin.bitcoinCash
)
) {
self.xPub = xPub
self.label = label ?? CryptoCurrency.bitcoinCash.defaultWalletName
self.isDefault = isDefault
self.hdAccountIndex = hdAccountIndex
self.priceService = priceService
self.balanceService = balanceService
self.transactionsService = transactionsService
self.swapTransactionsService = swapTransactionsService
self.bridge = bridge
self.featureFlagsService = featureFlagsService
self.nativeWalletEnabled = nativeWalletEnabled
self.receiveAddressProvider = receiveAddressProvider
}
func can(perform action: AssetAction) -> AnyPublisher<Bool, Error> {
switch action {
case .receive,
.send,
.buy,
.linkToDebitCard,
.viewActivity:
return .just(true)
case .deposit,
.sign,
.withdraw,
.interestWithdraw:
return .just(false)
case .interestTransfer:
return isInterestTransferAvailable
.flatMap { [isFunded] isEnabled in
isEnabled ? isFunded : .just(false)
}
.eraseToAnyPublisher()
case .sell, .swap:
return hasPositiveDisplayableBalance
}
}
func balancePair(
fiatCurrency: FiatCurrency,
at time: PriceTime
) -> AnyPublisher<MoneyValuePair, Error> {
balancePair(
priceService: priceService,
fiatCurrency: fiatCurrency,
at: time
)
}
func updateLabel(_ newLabel: String) -> Completable {
bridge.update(accountIndex: hdAccountIndex, label: newLabel)
}
func invalidateAccountBalance() {
balanceService
.invalidateBalanceForWallet(xPub)
}
}
|
lgpl-3.0
|
675d97a3fa04faa9660e7f3b52e1ac65
| 34.663717 | 117 | 0.612655 | 5.570145 | false | false | false | false |
DrabWeb/Azusa
|
Source/Mio/Mio/Sources/Objects/MIStats.swift
|
1
|
1871
|
//
// MIStats.swift
// Azusa.Mio
//
// Created by Ushio on 2/11/17.
//
import Foundation
import Yui
/// Represents the stats of an MPD server
public class MIStats: CustomStringConvertible {
// MARK: - Properties
// MARK: Public Properties
public var albumCount : Int = 0;
public var artistCount : Int = 0;
public var songCount : Int = 0;
public var databasePlayTime : Int = 0;
public var mpdUptime : Int = 0;
public var mpdPlayTime : Int = 0;
public var lastMpdDatabaseUpdate : NSDate = NSDate();
public var description : String {
return "MIMPDStats: \(self.albumCount) albums, " +
"\(self.artistCount) artists, " +
"\(songCount) songs, " +
"database play time: \(MusicUtilities.displayTime(from: self.databasePlayTime)), " +
"MPD uptime: \(MusicUtilities.displayTime(from: self.mpdUptime)), " +
"MPD play time: \(MusicUtilities.displayTime(from: mpdPlayTime)), " +
"last database update was \(self.lastMpdDatabaseUpdate)";
}
// MARK: - Initialization and Deinitialization
public init(albumCount : Int, artistCount : Int, songCount : Int, databasePlayTime : Int, mpdUptime : Int, mpdPlayTime : Int, lastMpdDatabaseUpdate : NSDate) {
self.albumCount = albumCount;
self.artistCount = artistCount;
self.songCount = songCount;
self.databasePlayTime = databasePlayTime;
self.mpdUptime = mpdUptime;
self.mpdPlayTime = mpdPlayTime;
self.lastMpdDatabaseUpdate = lastMpdDatabaseUpdate;
}
public init() {
self.albumCount = 0;
self.artistCount = 0;
self.songCount = 0;
self.databasePlayTime = 0;
self.mpdUptime = 0;
self.mpdPlayTime = 0;
self.lastMpdDatabaseUpdate = NSDate();
}
}
|
gpl-3.0
|
f5234996a1c9f5498cf374e648274b8f
| 31.258621 | 163 | 0.623196 | 4.023656 | false | false | false | false |
springwong/SnapKitten
|
SnapKitten/Classes/Core/KittenItem.swift
|
1
|
785
|
//
// SnapKittenItem.swift
// SnapKitten
//
// Created by Spring Wong on 25/2/2017.
// Copyright © 2017 Spring Wong. All rights reserved.
//
import UIKit
internal final class KittenItem {
var view : UIView
var itemOffset : Int = 0
var sideStartPadding : Int = 0
var sideEndPadding : Int = 0
var priority : KittenPriority = .high
var weight : Float = 1
var ratio : Float?
var width : KittenDimension?
var height : KittenDimension?
var isFillParent : Bool = false
var alignment : KittenAlignment
var insertCondition : KittenInsertCondition?
var sideCompressionResistance : Int = 750
init(child : UIView, alignment : KittenAlignment){
self.view = child
self.alignment = alignment
}
}
|
mit
|
b78ddaf5a4e5945ff25ee8237a7bc205
| 22.058824 | 54 | 0.653061 | 4.284153 | false | false | false | false |
Jnosh/swift
|
test/IRGen/class_resilience.swift
|
3
|
14228
|
// RUN: rm -rf %t && mkdir %t
// RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -enable-class-resilience %s | %FileCheck %s
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -enable-class-resilience -O %s
// CHECK: %swift.type = type { [[INT:i32|i64]] }
// CHECK: @_T016class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvWvd = {{(protected )?}}global [[INT]] 0
// CHECK: @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32VvWvd = {{(protected )?}}global [[INT]] 0
// CHECK: @_T016class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvWvd = {{(protected )?}}global [[INT]] 0
// CHECK: @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvWvd = {{(protected )?}}global [[INT]] 0
// CHECK: @_T016class_resilience14ResilientChildC5fields5Int32VvWvd = {{(protected )?}}global [[INT]] {{12|16}}
// CHECK: @_T016class_resilience21ResilientGenericChildC5fields5Int32VvWvi = {{(protected )?}}global [[INT]] {{56|88}}
// CHECK: @_T016class_resilience28ClassWithMyResilientPropertyC1rAA0eF6StructVvWvd = {{(protected )?}}constant [[INT]] {{12|16}}
// CHECK: @_T016class_resilience28ClassWithMyResilientPropertyC5colors5Int32VvWvd = {{(protected )?}}constant [[INT]] {{16|20}}
// CHECK: @_T016class_resilience30ClassWithIndirectResilientEnumC1s14resilient_enum10FunnyShapeOvWvd = {{(protected )?}}constant [[INT]] {{12|16}}
// CHECK: @_T016class_resilience30ClassWithIndirectResilientEnumC5colors5Int32VvWvd = {{(protected )?}}constant [[INT]] {{16|24}}
import resilient_class
import resilient_struct
import resilient_enum
// Concrete class with resilient stored property
public class ClassWithResilientProperty {
public let p: Point
public let s: Size
public let color: Int32
public init(p: Point, s: Size, color: Int32) {
self.p = p
self.s = s
self.color = color
}
}
// Concrete class with non-fixed size stored property
public class ClassWithResilientlySizedProperty {
public let r: Rectangle
public let color: Int32
public init(r: Rectangle, color: Int32) {
self.r = r
self.color = color
}
}
// Concrete class with resilient stored property that
// is fixed-layout inside this resilience domain
public struct MyResilientStruct {
public let x: Int32
}
public class ClassWithMyResilientProperty {
public let r: MyResilientStruct
public let color: Int32
public init(r: MyResilientStruct, color: Int32) {
self.r = r
self.color = color
}
}
// Enums with indirect payloads are fixed-size
public class ClassWithIndirectResilientEnum {
public let s: FunnyShape
public let color: Int32
public init(s: FunnyShape, color: Int32) {
self.s = s
self.color = color
}
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientChild : ResilientOutsideParent {
public let field: Int32 = 0
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientGenericChild<T> : ResilientGenericOutsideParent<T> {
public let field: Int32 = 0
}
// Superclass is resilient and has a resilient value type payload,
// but everything is in one module
public class MyResilientParent {
public let s: MyResilientStruct = MyResilientStruct(x: 0)
}
public class MyResilientChild : MyResilientParent {
public let field: Int32 = 0
}
// ClassWithResilientProperty.color getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32Vfg(%T16class_resilience26ClassWithResilientPropertyC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32VvWvd
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience26ClassWithResilientPropertyC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: ret i32 [[FIELD_VALUE]]
// ClassWithResilientProperty metadata accessor
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_T016class_resilience26ClassWithResilientPropertyCMa()
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience26ClassWithResilientPropertyCML
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: call void @swift_once([[INT]]* @_T016class_resilience26ClassWithResilientPropertyCMa.once_token, i8* bitcast (void (i8*)* @initialize_metadata_ClassWithResilientProperty to i8*), i8* undef)
// CHECK-NEXT: [[METADATA:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience26ClassWithResilientPropertyCML
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: ret %swift.type* [[RESULT]]
// ClassWithResilientlySizedProperty.color getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32Vfg(%T16class_resilience33ClassWithResilientlySizedPropertyC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvWvd
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience33ClassWithResilientlySizedPropertyC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: ret i32 [[FIELD_VALUE]]
// ClassWithResilientlySizedProperty metadata accessor
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_T016class_resilience33ClassWithResilientlySizedPropertyCMa()
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience33ClassWithResilientlySizedPropertyCML
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: call void @swift_once([[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyCMa.once_token, i8* bitcast (void (i8*)* @initialize_metadata_ClassWithResilientlySizedProperty to i8*), i8* undef)
// CHECK-NEXT: [[METADATA:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience33ClassWithResilientlySizedPropertyCML
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: ret %swift.type* [[RESULT]]
// ClassWithIndirectResilientEnum.color getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience30ClassWithIndirectResilientEnumC5colors5Int32Vfg(%T16class_resilience30ClassWithIndirectResilientEnumC* swiftself)
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T16class_resilience30ClassWithIndirectResilientEnumC, %T16class_resilience30ClassWithIndirectResilientEnumC* %0, i32 0, i32 2
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: ret i32 [[FIELD_VALUE]]
// ResilientChild.field getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience14ResilientChildC5fields5Int32Vfg(%T16class_resilience14ResilientChildC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience14ResilientChildC5fields5Int32VvWvd
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience14ResilientChildC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: ret i32 [[FIELD_VALUE]]
// ResilientGenericChild.field getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience21ResilientGenericChildC5fields5Int32Vfg(%T16class_resilience21ResilientGenericChildC* swiftself)
// FIXME: we could eliminate the unnecessary isa load by lazily emitting
// metadata sources in EmitPolymorphicParameters
// CHECK: load %swift.type*
// CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds %T16class_resilience21ResilientGenericChildC, %T16class_resilience21ResilientGenericChildC* %0, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ADDR]]
// CHECK-NEXT: [[INDIRECT_OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience21ResilientGenericChildC5fields5Int32VvWvi
// CHECK-NEXT: [[ISA_ADDR:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[FIELD_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_ADDR]], [[INT]] [[INDIRECT_OFFSET]]
// CHECK-NEXT: [[FIELD_OFFSET_ADDR:%.*]] = bitcast i8* [[FIELD_OFFSET_TMP]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_ADDR:%.*]]
// CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T16class_resilience21ResilientGenericChildC* %0 to i8*
// CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Ts5Int32V*
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK-NEXT: ret i32 [[RESULT]]
// MyResilientChild.field getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience16MyResilientChildC5fields5Int32Vfg(%T16class_resilience16MyResilientChildC* swiftself)
// CHECK: [[FIELD_ADDR:%.*]] = getelementptr inbounds %T16class_resilience16MyResilientChildC, %T16class_resilience16MyResilientChildC* %0, i32 0, i32 2
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK-NEXT: ret i32 [[RESULT]]
// ClassWithResilientProperty metadata initialization function
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_ClassWithResilientProperty
// CHECK: [[SIZE_METADATA:%.*]] = call %swift.type* @_T016resilient_struct4SizeVMa()
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_initClassMetadata_UniversalStrategy(
// CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvWvd
// CHECK-native-NEXT: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{13|16}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32VvWvd
// CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @_T016class_resilience26ClassWithResilientPropertyCML release,
// CHECK: ret void
// ClassWithResilientlySizedProperty metadata initialization function
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_ClassWithResilientlySizedProperty
// CHECK: [[RECTANGLE_METADATA:%.*]] = call %swift.type* @_T016resilient_struct9RectangleVMa()
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_initClassMetadata_UniversalStrategy(
// CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{11|14}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvWvd
// CHECK-native-NEXT: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvWvd
// CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @_T016class_resilience33ClassWithResilientlySizedPropertyCML release,
// CHECK: ret void
|
apache-2.0
|
5b3745e037f391496ef38b96efbb0f31
| 53.51341 | 218 | 0.706213 | 3.73929 | false | false | false | false |
kysonyangs/ysbilibili
|
ysbilibili/Classes/Home/Live/Controller/YSStartLiveViewController.swift
|
1
|
7126
|
//
// HomeStartLiveViewController.swift
// zhnbilibili
//
// Created by 张辉男 on 17/1/23.
// Copyright © 2017年 zhn. All rights reserved.
//
import UIKit
class YSStartLiveViewController: UIViewController {
// MARK - 懒加载控件
lazy var session: LFLiveSession = {
let audioConfiguration = LFLiveAudioConfiguration.default()
let videoConfiguration = LFLiveVideoConfiguration.defaultConfiguration(for: LFLiveVideoQuality.low3, outputImageOrientation: UIInterfaceOrientation.portrait)
let session = LFLiveSession(audioConfiguration: audioConfiguration, videoConfiguration: videoConfiguration)
session?.delegate = self
session?.preView = self.view
session?.captureDevicePosition = AVCaptureDevicePosition.back
session?.beautyFace = true
return session!
}()
lazy var liveStartEndButton: UIButton = {
let liveStartEndButton = UIButton()
liveStartEndButton.ysCornerRadius = 25
liveStartEndButton.ysBorderColor = kNavBarColor
liveStartEndButton.ysBorderWidth = 1
liveStartEndButton.setTitle("开始直播", for: .normal)
liveStartEndButton.setTitleColor(kNavBarColor, for: .normal)
liveStartEndButton.addTarget(self, action: #selector(liveButtonAction), for: .touchUpInside)
return liveStartEndButton
}()
lazy var disMissButton: UIButton = {
let disMissButton = UIButton()
disMissButton.setImage(UIImage(named: "circle_buy_vip_close"), for: .normal)
disMissButton.addTarget(self, action: #selector(disMissAction), for: .touchUpInside)
return disMissButton
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.setStatusBarStyle(.default, animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.shared.setStatusBarStyle(.default, animated: false)
view.backgroundColor = UIColor.white
view.addSubview(liveStartEndButton)
liveStartEndButton.snp.makeConstraints { (make) in
make.left.equalTo(view).offset(50)
make.right.equalTo(view).offset(-50)
make.bottom.equalTo(view).offset(-30)
make.height.equalTo(50)
}
view.addSubview(disMissButton)
disMissButton.snp.makeConstraints { (make) in
make.top.left.equalTo(view).offset(30)
make.size.equalTo(CGSize(width: 30, height: 30))
}
}
}
//======================================================================
// MARK:- 私有方法
//======================================================================
extension YSStartLiveViewController {
fileprivate func requestAccessForVideo() -> Void {
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo);
switch status {
// 许可对话没有出现,发起授权许可
case AVAuthorizationStatus.notDetermined:
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted) in
if(granted){
DispatchQueue.main.async {
self.session.running = true
}
}
})
break;
// 已经开启授权,可继续
case AVAuthorizationStatus.authorized:
session.running = true;
break;
// 用户明确地拒绝授权,或者相机设备无法访问
case AVAuthorizationStatus.denied: break
case AVAuthorizationStatus.restricted:break;
}
}
fileprivate func requestAccessForAudio() -> Void {
let status = AVCaptureDevice.authorizationStatus(forMediaType:AVMediaTypeAudio)
switch status {
// 许可对话没有出现,发起授权许可
case AVAuthorizationStatus.notDetermined:
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeAudio, completionHandler: { (granted) in
})
break;
// 已经开启授权,可继续
case AVAuthorizationStatus.authorized:
break;
// 用户明确地拒绝授权,或者相机设备无法访问
case AVAuthorizationStatus.denied: break
case AVAuthorizationStatus.restricted:break;
}
}
fileprivate func startLive() {
let stream = LFLiveStreamInfo()
stream.url = "rtmp://192.168.0.103:1935/rtmplive/room"
requestAccessForAudio()
requestAccessForVideo()
session.startLive(stream)
}
fileprivate func stopLive() {
session.running = false
session.stopLive()
}
fileprivate func buttonStartType() {
liveStartEndButton.ysBorderColor = kNavBarColor
liveStartEndButton.setTitle("开始直播", for: .normal)
liveStartEndButton.setTitleColor(kNavBarColor, for: .normal)
}
fileprivate func buttonEndType() {
liveStartEndButton.ysBorderColor = UIColor.white
liveStartEndButton.setTitle("结束直播", for: .normal)
liveStartEndButton.setTitleColor(UIColor.white, for: .normal)
}
}
//======================================================================
// MARK:- LFLiveSessionDelegate
//======================================================================
extension YSStartLiveViewController: LFLiveSessionDelegate {
func liveSession(_ session: LFLiveSession?, debugInfo: LFLiveDebug?) {
print(debugInfo as Any)
}
func liveSession(_ session: LFLiveSession?, errorCode: LFLiveSocketErrorCode) {
print(errorCode)
}
func liveSession(_ session: LFLiveSession?, liveStateDidChange state: LFLiveState) {
switch state {
case LFLiveState.ready:
buttonStartType()
print("未连接")
break;
case LFLiveState.pending:
print("连接中")
break;
case LFLiveState.start:
buttonEndType()
print("已连接")
break;
case LFLiveState.error:
print("连接错误")
break;
case LFLiveState.stop:
buttonStartType()
print("未连接")
break;
default:
break;
}
}
}
//======================================================================
// MARK:- target action
//======================================================================
extension YSStartLiveViewController {
@objc func liveButtonAction() {
switch session.state {
case .ready:
startLive()
case .start:
stopLive()
default:
startLive()
}
}
@objc func disMissAction() {
_ = navigationController?.popViewController(animated: true)
}
}
|
mit
|
2632fde3169a74f628f7b13c860f5937
| 33.315 | 165 | 0.591869 | 5.167922 | false | false | false | false |
BruceFight/JHB_HUDView
|
JHB_HUDViewExample/ExampleTwoPart/ExampleDiyNDetailController.swift
|
1
|
62629
|
//
// ExampleDiyNDetailController.swift
// JHB_HUDViewExample
//
// Created by Leon_pan on 16/8/23.
// Copyright © 2016年 bruce. All rights reserved.
//
import UIKit
public enum diyImageType{
case diyImageTypeJustImage
case diyImageTypeImageArray
case diyImageTypeImageWithMsg
case diyImageTypeImageArrayWithMsg
}
class ExampleDiyNDetailController: JHB_HUDTopViewController,UITableViewDelegate,UITableViewDataSource {
var SCREEN_WIDTH = UIScreen.main.bounds.size.width
var SCREEN_HEIGHT = UIScreen.main.bounds.size.height
var tableView = UITableView.init()
var currentCoreType = NSInteger()
var currentImageType = NSInteger()
let multiStr = " 此生之路,我将走过;走过这一次,便再也无法重来。所有力所能及的善行,所有充盈于心的善意,我将毫不吝惜,即刻倾予。我将不再拖延,再不淡漠,只因此生之路,再也无法重来。"
// 声明一个数组,用来储存cell
var cellArr = NSMutableArray()
// 标示
var ID = "cell"
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Diy-Type-Details(DiyImgType)"
self.setTableView()
}
func setTableView() {
self.tableView = UITableView.init(frame:self.view.bounds)
self.tableView.delegate = self
self.tableView.dataSource = self
// 注册cell
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: ID)
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none
self.view.addSubview(self.tableView)
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ID, for: indexPath)
cell.textLabel?.numberOfLines = 0
if (indexPath as NSIndexPath).row == 0 {
cell.textLabel?.text = "1⃣️Diy-Type kDiyHUDTypeDefault"
}else if (indexPath as NSIndexPath).row == 1{
cell.textLabel?.text = "2⃣️Diy-Type kDiyHUDTypeRotateWithY"
}else if (indexPath as NSIndexPath).row == 2{
cell.textLabel?.text = "3⃣️Diy-Type kDiyHUDTypeRotateWithZ"
}else if (indexPath as NSIndexPath).row == 3{
cell.textLabel?.text = "4⃣️Diy-Type kDiyHUDTypeShakeWithX"
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (indexPath as NSIndexPath).row == 0 {
self.defaultType()
}else if (indexPath as NSIndexPath).row == 1{
self.RotateWithYType()
}else if (indexPath as NSIndexPath).row == 2{
self.RotateWithZType()
}else if (indexPath as NSIndexPath).row == 3{
self.hakeWithXType()
}
}
func defaultType() {
switch currentCoreType {
case HUDType.kHUDTypeDefaultly.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowImmediately.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowSlightly.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromBottomToTop.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromTopToBottom.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromLeftToRight.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromRightToLeft.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeScaleFromInsideToOutside.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeScaleFromOutsideToInside.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeDefault, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
default:
break
}
}
func RotateWithYType() {
switch currentCoreType {
case HUDType.kHUDTypeDefaultly.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowImmediately.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowSlightly.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromBottomToTop.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromTopToBottom.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromLeftToRight.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromRightToLeft.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeScaleFromInsideToOutside.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeScaleFromOutsideToInside.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithY, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
default:
break
}
}
func RotateWithZType() {
switch currentCoreType {
case HUDType.kHUDTypeDefaultly.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("TaiChi", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "TaiChi", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowImmediately.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("TaiChi", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "TaiChi", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowSlightly.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("TaiChi", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "TaiChi", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromBottomToTop.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("TaiChi", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "TaiChi", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromTopToBottom.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("TaiChi", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "TaiChi", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromLeftToRight.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("TaiChi", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "TaiChi", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromRightToLeft.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("TaiChi", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "TaiChi", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeScaleFromInsideToOutside.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("TaiChi", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "TaiChi", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeScaleFromOutsideToInside.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("TaiChi", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "TaiChi", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeRotateWithZ, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
default:
break
}
}
func hakeWithXType() {
switch currentCoreType {
case HUDType.kHUDTypeDefaultly.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeDefaultly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowImmediately.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowImmediately)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowSlightly.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowSlightly)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromBottomToTop.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromBottomToTop)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromTopToBottom.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromTopToBottom)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromLeftToRight.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromLeftToRight)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeShowFromRightToLeft.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeShowFromRightToLeft)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeScaleFromInsideToOutside.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeScaleFromInsideToOutside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
case HUDType.kHUDTypeScaleFromOutsideToInside.hashValue:
switch currentImageType {
case diyImageType.diyImageTypeJustImage.hashValue:
JHB_HUDView.showProgressOfDIYTypeWith("dropdown_anim_loading4", diySpeed: 0.65, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArray.hashValue:
JHB_HUDView.showProgressOfDIYTypeWithAnimation("dropdown_anim_loading", imgsNumber: 8, diySpeed: 0.6, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWith(multiStr as NSString, img: "dropdown_anim_loading4", diySpeed: 0.6, diyHudType: DiyHUDType.kDiyHUDTypeShakeWithX, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
case diyImageType.diyImageTypeImageArrayWithMsg.hashValue:
JHB_HUDView.showProgressMsgOfDIYTypeWithAnimation(multiStr as NSString, imgsName: "dropdown_anim_loading", imgsNumber: 8,diySpeed: 0.65, HudType: HUDType.kHUDTypeScaleFromOutsideToInside)
self.perform(#selector(hide), with: self, afterDelay: 3)
break
default:
break
}
break
default:
break
}
}
func hide() {
JHB_HUDView.hideProgressOfDIYType()
}
// 设置header 和 footer
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UILabel.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 60))
header.text = "这一堆HUDType效果类型中的每一种都可以作为实现自定义效果的基础效果显示类型哦~!😊"
header.sizeToFit()
header.numberOfLines = 0
header.textColor = UIColor.white
header.font = UIFont.systemFont(ofSize: 18)
header.textAlignment = NSTextAlignment.center
header.backgroundColor = UIColor.orange
return header
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footer = UILabel.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 60))
footer.text = "是的,点进去还有好多种选择~!😂"
footer.sizeToFit()
footer.numberOfLines = 0
footer.textColor = UIColor.white
footer.font = UIFont.systemFont(ofSize: 18)
footer.textAlignment = NSTextAlignment.center
footer.backgroundColor = UIColor.orange
return footer
}
// ❤️ 如果要展示header 或 footer 就必须要设置他们的高度值!
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 75
}
}
|
mit
|
aeb2f8342c3b4091177daf42ad5f5181
| 61.77621 | 222 | 0.662074 | 4.140834 | false | false | false | false |
josve05a/wikipedia-ios
|
Wikipedia/Code/UserHistoryFunnel.swift
|
2
|
7124
|
// https://meta.wikimedia.org/wiki/Schema:MobileWikiAppiOSUserHistory
private typealias ContentGroupKindAndLoggingCode = (kind: WMFContentGroupKind, loggingCode: String)
@objc final class UserHistoryFunnel: EventLoggingFunnel, EventLoggingStandardEventProviding {
private let targetCountries: Set<String> = Set<String>(arrayLiteral:
"US", "DE", "GB", "FR", "IT", "CA", "JP", "AU", "IN", "RU", "NL", "ES", "CH", "SE", "MX",
"CN", "BR", "AT", "BE", "UA", "NO", "DK", "PL", "HK", "KR", "SA", "CZ", "IR", "IE", "SG",
"NZ", "AE", "FI", "IL", "TH", "AR", "VN", "TW", "RO", "PH", "MY", "ID", "CL", "CO", "ZA",
"PT", "HU", "GR", "EG"
)
@objc public static let shared = UserHistoryFunnel()
private var isTarget: Bool {
guard let countryCode = Locale.current.regionCode?.uppercased() else {
return false
}
return targetCountries.contains(countryCode)
}
private override init() {
super.init(schema: "MobileWikiAppiOSUserHistory", version: 19074748)
}
private func event() -> Dictionary<String, Any> {
let userDefaults = UserDefaults.wmf
let fontSize = userDefaults.wmf_articleFontSizeMultiplier().intValue
let theme = userDefaults.themeAnalyticsName
let isFeedDisabled = userDefaults.defaultTabType != .explore
let isNewsNotificationEnabled = userDefaults.wmf_inTheNewsNotificationsEnabled()
let appOpensOnSearchTab = userDefaults.wmf_openAppOnSearchTab
var event: [String: Any] = ["primary_language": primaryLanguage(), "is_anon": isAnon, "measure_font_size": fontSize, "theme": theme, "feed_disabled": isFeedDisabled, "trend_notify": isNewsNotificationEnabled, "search_tab": appOpensOnSearchTab]
guard let dataStore = SessionSingleton.sharedInstance().dataStore else {
return event
}
let savedArticlesCount = dataStore.savedPageList.numberOfItems()
event["measure_readinglist_itemcount"] = savedArticlesCount
let isSyncEnabled = dataStore.readingListsController.isSyncEnabled
let isDefaultListEnabled = dataStore.readingListsController.isDefaultListEnabled
event["readinglist_sync"] = isSyncEnabled
event["readinglist_showdefault"] = isDefaultListEnabled
if let readingListCount = try? dataStore.viewContext.allReadingListsCount() {
event["measure_readinglist_listcount"] = readingListCount
}
event["feed_enabled_list"] = feedEnabledListPayload()
return wholeEvent(with: event)
}
private func feedEnabledListPayload() -> [String: Any] {
let contentGroupKindAndLoggingCodeFromNumber:(NSNumber) -> ContentGroupKindAndLoggingCode? = { kindNumber in
// The MobileWikiAppiOSUserHistory schema only specifies that we log certain card types for `feed_enabled_list`.
// If `userHistorySchemaCode` returns nil for a given WMFContentGroupKind we don't add an entry to `feed_enabled_list`.
guard let kind = WMFContentGroupKind(rawValue: kindNumber.int32Value), let loggingCode = kind.userHistorySchemaCode else {
return nil
}
return (kind: kind, loggingCode: loggingCode)
}
var feedEnabledList = [String: Any]()
WMFExploreFeedContentController.globalContentGroupKindNumbers().compactMap(contentGroupKindAndLoggingCodeFromNumber).forEach() {
feedEnabledList[$0.loggingCode] = $0.kind.isInFeed
}
WMFExploreFeedContentController.customizableContentGroupKindNumbers().compactMap(contentGroupKindAndLoggingCodeFromNumber).forEach() {
feedEnabledList[$0.loggingCode] = $0.kind.userHistorySchemaLanguageInfo
}
return feedEnabledList
}
override func logged(_ eventData: [AnyHashable: Any]) {
guard let eventData = eventData as? [String: Any] else {
return
}
EventLoggingService.shared?.lastLoggedSnapshot = eventData as NSCoding
UserDefaults.wmf.wmf_lastAppVersion = WikipediaAppUtils.appVersion()
}
private var latestSnapshot: Dictionary<String, Any>? {
return EventLoggingService.shared?.lastLoggedSnapshot as? Dictionary<String, Any>
}
@objc public func logSnapshot() {
guard EventLoggingService.shared?.isEnabled ?? false else {
return
}
guard isTarget else {
return
}
guard let lastAppVersion = UserDefaults.wmf.wmf_lastAppVersion else {
log(event())
return
}
guard let latestSnapshot = latestSnapshot else {
return
}
let newSnapshot = event()
guard !newSnapshot.wmf_isEqualTo(latestSnapshot, excluding: standardEvent.keys) || lastAppVersion != WikipediaAppUtils.appVersion() else {
// DDLogDebug("User History snapshots are identical; logging new User History snapshot aborted")
return
}
// DDLogDebug("User History snapshots are different; logging new User History snapshot")
log(event())
}
@objc public func logStartingSnapshot() {
guard latestSnapshot == nil else {
// DDLogDebug("Starting User History snapshot was already recorded; logging new User History snapshot aborted")
logSnapshot() // call standard log snapshot in case version changed, should be logged on session start
return
}
guard isTarget else {
return
}
log(event())
// DDLogDebug("Attempted to log starting User History snapshot")
}
}
private extension WMFContentGroupKind {
var offLanguageCodes: Set<String> {
let preferredLangCodes = MWKLanguageLinkController.sharedInstance().preferredLanguages.map{$0.languageCode}
return Set(preferredLangCodes).subtracting(languageCodes)
}
// codes define by: https://meta.wikimedia.org/wiki/Schema:MobileWikiAppiOSUserHistory
var userHistorySchemaCode: String? {
switch self {
case .featuredArticle:
return "fa"
case .topRead:
return "tr"
case .onThisDay:
return "od"
case .news:
return "ns"
case .relatedPages:
return "rp"
case .continueReading:
return "cr"
case .location:
return "pl"
case .random:
return "rd"
case .pictureOfTheDay:
return "pd"
default:
return nil
}
}
// "on" / "off" define by: https://meta.wikimedia.org/wiki/Schema:MobileWikiAppiOSUserHistory
var userHistorySchemaLanguageInfo: [String: [String]] {
var info = [String: [String]]()
if !languageCodes.isEmpty {
info["on"] = Array(languageCodes)
}
if !offLanguageCodes.isEmpty {
info["off"] = Array(offLanguageCodes)
}
return info
}
}
|
mit
|
bfb854fa1b5d90af56d2e87574a878de
| 39.248588 | 251 | 0.632931 | 4.730412 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial
|
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/ZoomAndPanAChart/DragAxisToScaleChartView.swift
|
1
|
3843
|
//******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: support@scichart.com
// Sales: sales@scichart.com
//
// DragAxisToScaleChartView.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
class DragAxisToScaleChartView: SingleChartLayout {
override func initExample() {
let xAxis = SCINumericAxis()
xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
xAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(3), max: SCIGeneric(6))
let rightYAxis = SCINumericAxis()
rightYAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
rightYAxis.axisId = "RightAxisId"
rightYAxis.axisAlignment = .right
rightYAxis.style.labelStyle.colorCode = 0xFF279B27
let leftYAxis = SCINumericAxis()
leftYAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
leftYAxis.axisId = "LeftAxisId"
leftYAxis.axisAlignment = .left
leftYAxis.style.labelStyle.colorCode = 0xFF4083B7
let fourierSeries = DataManager.getFourierSeries(withAmplitude: 1.0, phaseShift: 0.1, count: 5000)
let dampedSinewave = DataManager.getDampedSinewave(withPad: 1500, amplitude: 3.0, phase: 0.0, dampingFactor: 0.005, pointCount: 5000, freq: 10)
let mountainDataSeries = SCIXyDataSeries(xType: .double, yType: .double)
let lineDataSeries = SCIXyDataSeries(xType: .double, yType: .double)
mountainDataSeries.appendRangeX(fourierSeries!.xValues, y: fourierSeries!.yValues, count: fourierSeries!.size)
lineDataSeries.appendRangeX(dampedSinewave!.xValues, y: dampedSinewave!.yValues, count: dampedSinewave!.size)
let mountainSeries = SCIFastMountainRenderableSeries()
mountainSeries.dataSeries = mountainDataSeries
mountainSeries.areaStyle = SCISolidBrushStyle(colorCode: 0x771964FF)
mountainSeries.strokeStyle = SCISolidPenStyle(colorCode: 0xFF0944CF, withThickness: 2.0)
mountainSeries.yAxisId = "LeftAxisId"
let lineSeries = SCIFastLineRenderableSeries()
lineSeries.dataSeries = lineDataSeries
lineSeries.strokeStyle = SCISolidPenStyle(colorCode: 0xFF279B27, withThickness: 2.0)
lineSeries.yAxisId = "RightAxisId"
let leftYAxisDM = SCIYAxisDragModifier()
leftYAxisDM.axisId = "LeftAxisId"
let rightYAxisDM = SCIYAxisDragModifier()
rightYAxisDM.axisId = "RightAxisId"
SCIUpdateSuspender.usingWithSuspendable(surface) {
self.surface.xAxes.add(xAxis)
self.surface.yAxes.add(leftYAxis)
self.surface.yAxes.add(rightYAxis)
self.surface.renderableSeries.add(mountainSeries)
self.surface.renderableSeries.add(lineSeries)
self.surface.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIXAxisDragModifier(), leftYAxisDM, rightYAxisDM, SCIZoomExtentsModifier()])
mountainSeries.addAnimation(SCIWaveRenderableSeriesAnimation(duration: 3, curveAnimation: .easeInOut))
lineSeries.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeInOut))
}
}
}
|
mit
|
4a1dbed7abf835517f3ca79c814b6bb8
| 50.891892 | 163 | 0.673958 | 4.398625 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue
|
iOS/Venue/Models/Detail.swift
|
1
|
973
|
/*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import Foundation
import CoreData
/// Class to represent a Detail object
class Detail: NSObject {
let id: Int
let message: String
let image_name: String
override init() {
id = 0
message = ""
image_name = ""
super.init()
}
convenience init(managedDetail: NSManagedObject) {
guard let id = managedDetail.valueForKey("id") as? Int, let message = managedDetail.valueForKey("message") as? String, let image_name = managedDetail.valueForKey("image_name") as? String else {
self.init()
return
}
self.init(id: id,message: message,image_name: image_name)
}
internal init(id: Int, message: String, image_name: String) {
self.id = id
self.message = message
self.image_name = image_name
super.init()
}
}
|
epl-1.0
|
db137f49f3fa746a21a32a2606703c3d
| 24.605263 | 201 | 0.600823 | 4.281938 | false | false | false | false |
Vostro162/VaporTelegram
|
Sources/App/Array+Extensions.swift
|
1
|
784
|
//
// Array+Extensions.swift
// VaporTelegram
//
// Created by Marius Hartig on 13.05.17.
//
//
import Foundation
import Vapor
extension Array where Element == NodeRepresentable {
func elementsToNode() -> [Node] {
var nodeElements = [Node]()
for element in self {
guard let node = try? element.makeNode() else { continue }
nodeElements.append(node)
}
return nodeElements
}
static func elementsToNode(from arrays: [[NodeRepresentable]]) -> [Node] {
var nodes = [Node]()
for array in arrays {
guard let node = try? Node(node: array.elementsToNode()) else { continue }
nodes.append(node)
}
return nodes;
}
}
|
mit
|
3eae6729fb70dc9df35c253da88be491
| 21.4 | 86 | 0.553571 | 4.379888 | false | false | false | false |
Minitour/WWDC-Collaborators
|
Macintosh.playground/Sources/Interface/OSToolBar.swift
|
1
|
8472
|
import Foundation
import UIKit
public protocol OSToolBarDataSource {
/// The menu actions that will be displayed on the toolbar
///
/// - Parameter toolBar: The toolbar instance
/// - Returns: An array of MenuAction
func menuActions(_ toolBar: OSToolBar)->[MenuAction]
/// The menu which displays the OS actions. (mostly applications)
///
/// - Parameter toolBar: The toolbar instance.
/// - Returns: An array of MenuAction.
func osMenuActions(_ toolBar: OSToolBar)->[MenuAction]
}
public class OSToolBar: UIView{
/// The height of the tool bar
static let height: CGFloat = 20.0
/// The logo/icon that is displayed in the toolbar
open var osMenuLogo: UIImage{
set{
osMenuButton?.setImage(newValue, for: [])
}
get{
return (osMenuButton?.image(for: []))!
}
}
/// The primary menu button.
var osMenuButton: UIButton!
/// The stack the holds the other menus
var menuStackView: UIStackView!
/// The current dropdown menu that is displayed.
var currentDropDownMenu: MenuDropdownView?
/// The seperator view
var seperatorView: UIView!
/// The data source which is implemented by the OSWindow
open var dataSource: OSToolBarDataSource?
convenience public init(inWindow window: CGRect) {
let rect = CGRect(x: 0, y: 0, width: window.width, height: OSToolBar.height)
self.init(frame: rect)
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("Sorry m8 there is no coder here")
}
func setup(){
self.backgroundColor = .white
//setup os menu button
osMenuButton = UIButton(type: .custom)
osMenuButton.addTarget(self, action: #selector(didSelectOSMenu(sender:)), for: .touchUpInside)
osMenuButton.imageView?.contentMode = .scaleAspectFit
osMenuButton.imageEdgeInsets = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
addSubview(osMenuButton)
//setup action menus
menuStackView = UIStackView()
menuStackView.axis = .horizontal
menuStackView.alignment = .fill
menuStackView.distribution = .fill
menuStackView.spacing = 0
menuStackView.isLayoutMarginsRelativeArrangement = true
addSubview(menuStackView)
seperatorView = UIView()
seperatorView.backgroundColor = .black
addSubview(seperatorView)
}
public override func layoutSubviews() {
super.layoutSubviews()
let spacing: CGFloat = 10
osMenuButton.frame = CGRect(x: spacing, y: 0, width: 30, height: OSToolBar.height)
menuStackView.frame.origin.x = osMenuButton.bounds.width + spacing * 2
seperatorView.frame = CGRect(x: 0, y: frame.maxY, width: bounds.size.width, height: 1)
}
public override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
let spacing: CGFloat = 10
let size = self.bounds.size
menuStackView.frame = CGRect(x: osMenuButton.bounds.width + spacing, y: 0, width: size.width - size.width / 3, height: OSToolBar.height)
}
func didSelectOSMenu(sender: UIButton){
showMenuDropDown(sender: sender, isPrimary: true)
}
func didSelectItemMenu(sender: UIButton){
showMenuDropDown(sender: sender,isPrimary: false)
}
func showMenuDropDown(sender: UIButton,isPrimary primary: Bool){
let id = sender.tag
for view in menuStackView.arrangedSubviews{
(view as! UIButton).isSelected = false
}
if let current = currentDropDownMenu{
current.removeFromSuperview()
if current.tag == id{
currentDropDownMenu = nil
return
}
}
if primary{
let action = MenuAction(title: "", action: nil, subMenus: dataSource?.osMenuActions(self))
self.currentDropDownMenu = MenuDropdownView(action: action)
self.currentDropDownMenu?.delegate = self
self.currentDropDownMenu?.tag = id
let senderRect = sender.convert(sender.bounds, to: self.superview)
self.currentDropDownMenu?.frame.origin = senderRect.origin
self.currentDropDownMenu?.frame.origin.y = (currentDropDownMenu?.frame.origin.y)! + OSToolBar.height
self.superview?.insertSubview(self.currentDropDownMenu!, belowSubview: self)
}else{
if let action = dataSource?.menuActions(self)[id-1]{
if let _ = action.subMenus {
sender.isSelected = true
self.currentDropDownMenu = MenuDropdownView(action: action)
self.currentDropDownMenu?.delegate = self
self.currentDropDownMenu?.tag = id
let senderRect = sender.convert(sender.bounds, to: self.superview)
self.currentDropDownMenu?.frame.origin = senderRect.origin
self.currentDropDownMenu?.frame.origin.y = (currentDropDownMenu?.frame.origin.y)! + OSToolBar.height
self.superview?.insertSubview(self.currentDropDownMenu!, belowSubview: self)
}else if let funcAction = action.action{
funcAction()
}
}
}
}
/// Request from the tool bar to close all open menus.
open func requestCloseAllMenus(){
for view in menuStackView.arrangedSubviews{
(view as! UIButton).isSelected = false
}
if let current = currentDropDownMenu{
current.removeFromSuperview()
currentDropDownMenu = nil
}
}
/// Request from the tool bar to refresh it's menus (if needed)
open func requestApplicationMenuUpdate(){
if let buttonStack = self.menuStackView{
//remove old menu items
buttonStack.subviews.forEach { $0.removeFromSuperview()}
//add new items
if let actions = dataSource?.menuActions(self){
for i in 1...actions.count {
let button = createMenuButtonFrom(action: actions[i-1],index: i)
buttonStack.addArrangedSubview(button)
}
}
var stackWidth:CGFloat = 0
let spacing: CGFloat = 20
for arrangedView in buttonStack.arrangedSubviews {
let button = (arrangedView as! UIButton)
let buttonNeededWidth = Utils.widthForView(button.title(for: [])!, font: (button.titleLabel?.font)!, height: OSToolBar.height)
button.widthAnchor.constraint(equalToConstant: buttonNeededWidth + spacing).isActive = true
stackWidth += buttonNeededWidth
}
buttonStack.bounds.size.width = stackWidth + CGFloat(buttonStack.arrangedSubviews.count) * spacing
buttonStack.removeConstraints(buttonStack.constraints)
buttonStack.layoutIfNeeded()
}
}
func createMenuButtonFrom(action: MenuAction,index: Int)->UIButton{
let button = UIButton(type: .custom)
button.tag = index
button.titleLabel?.numberOfLines = 0
button.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
button.titleLabel?.textAlignment = .center
button.setTitle(action.title, for: [])
button.setTitleColor(.black, for: .normal)
button.setTitleColor(.white, for: .highlighted)
button.setTitleColor(.white, for: .selected)
button.setBackgroundImage(UIImage(color: .clear),for: [])
button.setBackgroundImage(UIImage(color: .black),for: .highlighted)
button.setBackgroundImage(UIImage(color: .black),for: .selected)
button.addTarget(self, action: #selector(didSelectItemMenu(sender:)), for: .touchUpInside)
button.titleLabel?.font = SystemSettings.normalSizeFont
return button
}
}
// MARK: - MenuDropDownDelegate
extension OSToolBar: MenuDropDownDelegate{
public func menuDropDown(_ menuDropDown: MenuDropdownView, didSelectActionAtIndex index: Int) {
requestCloseAllMenus()
}
}
|
mit
|
2fb02d1ee05e7db73b8e422a7f699797
| 37.334842 | 144 | 0.622521 | 4.966002 | false | false | false | false |
ChristianKienle/highway
|
Sources/HighwayCore/Context/Context.swift
|
1
|
1156
|
import Foundation
import ZFile
import Task
import Terminal
import SourceryAutoProtocols
public protocol ContextProtocol: AutoMockable {
/// sourcery:inline:Context.AutoGenerateProtocol
var fileSystem: FileSystemProtocol { get }
var executableProvider: ExecutableProviderProtocol { get }
var executor: TaskExecutorProtocol { get }
/// sourcery:end
}
open class Context: ContextProtocol, AutoGenerateProtocol {
// MARK: - Convenience
public init() throws {
self.fileSystem = FileSystem()
self.executableProvider = try SystemExecutableProvider()
self.executor = SystemExecutor(ui: Terminal.shared)
}
// MARK: - Init
public init(executableProvider: ExecutableProviderProtocol, executor: TaskExecutorProtocol, fileSystem: FileSystemProtocol) {
self.executableProvider = executableProvider
self.executor = executor
self.fileSystem = fileSystem
}
// MARK: - Properties
public let fileSystem: FileSystemProtocol
public let executableProvider: ExecutableProviderProtocol
public private(set) var executor: TaskExecutorProtocol
}
|
mit
|
ab52b08f55a38198b5a9716f000160cc
| 28.641026 | 129 | 0.725779 | 5.327189 | false | false | false | false |
sammyd/VT_InAppPurchase
|
projects/03_Receipts/003_ChallengeComplete/GreenGrocer/DataStoreIAP.swift
|
1
|
2366
|
/*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
private let ShoppingListCreditCountKey = "ShoppingListCreditCount"
extension DataStore {
private(set) var shoppingListCredits: Int {
get {
return readNumberShoppingListCredits()
}
set(newValue) {
writeNumberShoppingListCredits(newValue)
}
}
func purchaseNewShoppingLists(productID: String) {
guard let product = GreenGrocerPurchase(productId: productID) else { return }
var numberOfShoppingListsToAdd: Int
switch product {
case .NewShoppingLists_One:
numberOfShoppingListsToAdd = 1
case .NewShoppingLists_Five:
numberOfShoppingListsToAdd = 5
case .NewShoppingLists_Ten:
numberOfShoppingListsToAdd = 10
default:
numberOfShoppingListsToAdd = 0
}
shoppingListCredits += numberOfShoppingListsToAdd
}
func spendShoppingListCredit() {
shoppingListCredits -= 1
}
private func readNumberShoppingListCredits() -> Int {
return NSUserDefaults.standardUserDefaults().integerForKey(ShoppingListCreditCountKey)
}
private func writeNumberShoppingListCredits(number: Int) {
NSUserDefaults.standardUserDefaults().setInteger(number, forKey: ShoppingListCreditCountKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
|
mit
|
28c66f7c359e09073a29205ff74dece6
| 34.848485 | 96 | 0.757819 | 4.838446 | false | false | false | false |
ktakayama/SimpleRSSReader
|
Classes/controllers/EntryListViewController.swift
|
1
|
5280
|
//
// EntryListViewController.swift
// SimpleRSSReader
//
// Created by Kyosuke Takayama on 2016/03/14.
// Copyright © 2016年 aill inc. All rights reserved.
//
import UIKit
import SafariServices
import RealmSwift
import RealmResultsController
import UIAlertControllerExtension
import SwiftTask
class EntryListViewController: UITableViewController, RealmResultsControllerDefaultDelegate {
private var rrc: RealmResultsController<Entry, Entry>?
var feed: Feed? {
didSet {
self.title = feed?.title
let predicate = NSPredicate(format:"identifier BEGINSWITH %@", feed!.identifier)
let sort = [ SortDescriptor(property:"publicAt", ascending:false) ]
do {
let realm = try Realm()
let request = RealmRequest<Entry>(predicate:predicate, realm:realm, sortDescriptors:sort)
rrc = try RealmResultsController(request:request, sectionKeyPath:nil)
rrc?.delegate = self
rrc?.performFetch()
self.tableView.reloadData()
FeedManager.lastSelectedFeed = feed
if let ref = self.refreshControl {
ref.beginRefreshing()
let y = self.tableView.contentOffset.y - ref.frame.height
self.tableView.setContentOffset(CGPoint(x:0, y:y), animated:true)
self.performActionRefresh(ref)
}
} catch let error as NSError {
presentAlert(title:String(error.code), message:error.localizedDescription, actionTitles: [ "OK" ])
}
}
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
fatalError("init(nibName:bundle:) has not been implemented")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
if let feed = FeedManager.lastSelectedFeed {
self.feed = feed
} else {
performSegueWithIdentifier("feedListViewController", sender:self)
}
}
// MARK: - actions
@IBAction func performActionRefresh(sender: UIRefreshControl) {
if let f = self.feed {
FeedManager.fetchFeed(f).success { (_) in
sender.endRefreshing()
}.failure { [unowned self] (error: NSError?, isCancelled: Bool) -> Void in
sender.endRefreshing()
self.presentAlert(title:String(error?.code), message:error?.localizedDescription, actionTitles: [ "OK" ])
}
} else {
sender.endRefreshing()
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return rrc?.numberOfSections ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rrc?.numberOfObjectsAt(section) ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("entryCell", forIndexPath: indexPath) as! EntryListCellView
cell.entry = rrc?.objectAt(indexPath)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
guard let entry = rrc?.objectAt(indexPath) else { return }
if let linkURLString = entry.linkURL, url = NSURL(string:linkURLString) {
let safari = SFSafariViewController(URL:url)
safari.title = entry.title
safari.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(safari, animated:true)
}
if entry.unread == false { return }
do {
let realm = try Realm()
try realm.write {
if let e = realm.objectForPrimaryKey(Entry.self, key:entry.identifier) {
e.unread = false
e.notifyChange()
}
}
} catch let error as NSError {
presentAlert(title:String(error.code), message:error.localizedDescription, actionTitles: [ "OK" ])
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "feedListViewController" {
guard let viewController = segue.destinationViewController as? UINavigationController else {
return
}
viewController.popoverPresentationController?.delegate = self
if let feedListViewController = viewController.topViewController as? FeedListViewController {
feedListViewController.feedSelectionHandler = { [unowned self] feed in
self.feed = feed
viewController.dismissViewControllerAnimated(true) {}
}
}
}
}
}
extension EntryListViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
}
|
mit
|
9f107bd2dd704dd8392221730a4aba84
| 34.897959 | 127 | 0.627819 | 5.440206 | false | false | false | false |
iAmrSalman/Dots
|
Sources/UIImageExtension.swift
|
1
|
729
|
//
// UIImageExtension.swift
// Dots-iOS
//
// Created by Amr Salman on 8/4/18.
// Copyright © 2018 Dots. All rights reserved.
//
#if !os(macOS) && !os(watchOS)
import UIKit
public extension UIImageView {
func setImage(withURL url: String) {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
indicator.center = self.center
self.addSubview(indicator)
indicator.startAnimating()
Dots.defualt.request(url) { (dot: Dot) in
if dot.error == nil {
guard let data = dot.data else { return }
self.image = UIImage(data: data)
indicator.removeFromSuperview()
}
}
}
}
#endif
|
mit
|
03a9c86dad61aa7055806f2b673c0e04
| 25.962963 | 84 | 0.597527 | 4.183908 | false | false | false | false |
relayrides/objective-c-sdk
|
Pods/Mixpanel-swift/Mixpanel/InAppNotifications.swift
|
1
|
4080
|
//
// InAppNotifications.swift
// Mixpanel
//
// Created by Yarden Eitan on 8/9/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
import UIKit
protocol InAppNotificationsDelegate {
func notificationDidShow(_ notification: InAppNotification)
func notificationDidCTA(_ notification: InAppNotification, event: String)
}
enum InAppType: String {
case mini = "mini"
case takeover = "takeover"
}
class InAppNotifications: NotificationViewControllerDelegate {
var checkForNotificationOnActive = true
var showNotificationOnActive = true
var miniNotificationPresentationTime = 6.0
var shownNotifications = Set<Int>()
var inAppNotifications = [InAppNotification]()
var currentlyShowingNotification: InAppNotification?
var delegate: InAppNotificationsDelegate?
func showNotification( _ notification: InAppNotification) {
let notification = notification
if notification.image != nil {
DispatchQueue.main.async {
if self.currentlyShowingNotification != nil {
Logger.warn(message: "already showing an in-app notification")
} else {
var shownNotification = false
#if os(iOS)
if let notification = notification as? MiniNotification {
shownNotification = self.showMiniNotification(notification)
} else if let notification = notification as? TakeoverNotification {
shownNotification = self.showTakeoverNotification(notification)
}
if shownNotification {
self.markNotificationShown(notification: notification)
self.delegate?.notificationDidShow(notification)
}
#endif
}
}
} else {
inAppNotifications = inAppNotifications.filter { $0.ID != notification.ID }
}
}
func markNotificationShown(notification: InAppNotification) {
Logger.info(message: "marking notification as seen: \(notification.ID)")
currentlyShowingNotification = notification
shownNotifications.insert(notification.ID)
}
#if os(iOS)
func showMiniNotification(_ notification: MiniNotification) -> Bool {
let miniNotificationVC = MiniNotificationViewController(notification: notification)
miniNotificationVC.delegate = self
miniNotificationVC.show(animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + miniNotificationPresentationTime) {
self.notificationShouldDismiss(controller: miniNotificationVC, callToActionURL: nil)
}
return true
}
func showTakeoverNotification(_ notification: TakeoverNotification) -> Bool {
let takeoverNotificationVC = TakeoverNotificationViewController(notification: notification)
takeoverNotificationVC.delegate = self
takeoverNotificationVC.show(animated: true)
return true
}
#endif
@discardableResult
func notificationShouldDismiss(controller: BaseNotificationViewController, callToActionURL: URL?) -> Bool {
if currentlyShowingNotification?.ID != controller.notification.ID {
return false
}
let completionBlock = {
self.currentlyShowingNotification = nil
}
if let callToActionURL = callToActionURL {
controller.hide(animated: true) {
Logger.info(message: "opening CTA URL: \(callToActionURL)")
if !UIApplication.shared.openURL(callToActionURL) {
Logger.error(message: "Mixpanel failed to open given URL: \(callToActionURL)")
}
self.delegate?.notificationDidCTA(controller.notification, event: "$campaign_open")
completionBlock()
}
} else {
controller.hide(animated: true, completion: completionBlock)
}
return true
}
}
|
apache-2.0
|
539da0291ef3bf0c4b577bece47ae716
| 35.747748 | 111 | 0.645011 | 5.453209 | false | false | false | false |
xichen744/SPPage
|
Swift/Example/Example/ViewController.swift
|
1
|
2326
|
//
// ViewController.swift
// SPPage
//
// Created by GodDan on 2018/2/27.
// Copyright © 2018年 GodDan. All rights reserved.
//
import UIKit
class ViewController: SPCoverController {
var navTitle:String?
override func viewDidLoad() {
super.viewDidLoad()
self.minYPullUp = kNavigationAndStatusBarHeight
self.automaticallyAdjustsScrollViewInsets = false
self.navigationController?.isNavigationBarHidden = false
self.navigationItem.title = self.navTitle ?? "SPPage"
if (self.navTitle == nil) {
self.navigationController?.navigationBar.barTintColor = UIColor.red
}
// Do any additional setup after loading the view, typically from a nib.
}
override func title(index: NSInteger) -> String {
return "TAB" + String(index)
}
override func needMarkView() -> Bool {
return true
}
override func preferCoverView() -> UIView? {
let view = UIView.init(frame: self.preferCoverFrame())
view.backgroundColor = UIColor.black
return view
}
override func preferTabFrame(index: NSInteger) -> CGRect {
return CGRect.init(x: 0, y: 245, width: kScreenWidth, height: 40)
}
override func preferCoverFrame() -> CGRect {
return CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: kScreenWidth, height: 245))
}
override func controller(index: NSInteger) -> UIViewController {
let subVC = TestSubController()
if index == 0 {
subVC.view.backgroundColor = UIColor.green
} else if index == 1 {
subVC.view.backgroundColor = UIColor.orange
} else {
subVC.view.backgroundColor = UIColor.red
}
return subVC
}
override func preferPageFirstAtIndex() -> NSInteger {
return 0
}
override func isSubPageCanScrollForIndex(index: NSInteger) -> Bool {
return true
}
override func numberOfControllers() -> NSInteger {
return 8
}
override func isPreLoad() -> Bool {
return false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
09c7990b6ca452a8897f5068ae93d808
| 25.101124 | 101 | 0.616014 | 4.799587 | false | false | false | false |
scottrhoyt/Jolt
|
Tests/TestingObjects/Protocols/DoubleOperandTest.swift
|
1
|
1141
|
//
// DoubleOperandTest.swift
// Jolt
//
// Created by Scott Hoyt on 9/24/15.
// Copyright © 2015 Scott Hoyt. All rights reserved.
//
import XCTest
protocol DoubleOperandTest : SingleOperandTest {
func measureAndValidateMappedFunctionWithAccuracy(member: (OperandType, OperandType) -> (OperandType), mapped: ([OperandType], [OperandType]) -> ([OperandType]), lowerBound: OperandType?, upperBound: OperandType?, accuracy: OperandType)
}
extension DoubleOperandTest where Self : XCTestCase {
func measureAndValidateMappedFunctionWithAccuracy(member: (OperandType, OperandType) -> (OperandType), mapped: (([OperandType], [OperandType]) -> ([OperandType])), lowerBound: OperandType? = nil, upperBound: OperandType? = nil, accuracy: OperandType = OperandType.accuracy)
{
let values1 = rands(JoltTestCountMedium, lowerBound: lowerBound, upperBound: upperBound)
let values2 = rands(JoltTestCountMedium, lowerBound: lowerBound, upperBound: upperBound)
measureAndValidateMappedFunctionWithAccuracy(values1, source2: values2, member: member, mapped: mapped, accuracy: accuracy)
}
}
|
mit
|
ee4ed6d176587b6df83b52313473fc84
| 39.75 | 277 | 0.737719 | 4.367816 | false | true | false | false |
wireapp/wire-ios-sync-engine
|
Tests/Source/Integration/ConversationTests+Ephemeral.swift
|
1
|
9022
|
//
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
class ConversationTests_Ephemeral: ConversationTestsBase {
var obfuscationTimer: ZMMessageDestructionTimer? {
return userSession!.syncManagedObjectContext.zm_messageObfuscationTimer
}
var deletionTimer: ZMMessageDestructionTimer? {
return userSession!.managedObjectContext.zm_messageDeletionTimer
}
}
extension ConversationTests_Ephemeral {
func testThatItCreatesAndSendsAnEphemeralMessage() {
// given
XCTAssert(login())
let conversation = self.conversation(for: selfToUser1Conversation!)!
self.userSession?.perform {
_ = try! conversation.appendText(content: "Hello") as! ZMClientMessage
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
mockTransportSession?.resetReceivedRequests()
// when
conversation.setMessageDestructionTimeoutValue(.custom(100), for: .selfUser)
var message: ZMClientMessage!
self.userSession?.perform {
message = try! conversation.appendText(content: "Hello") as? ZMClientMessage
XCTAssertTrue(message.isEphemeral)
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
// then
XCTAssertEqual(mockTransportSession?.receivedRequests().count, 1)
XCTAssertEqual(message.deliveryState, ZMDeliveryState.sent)
XCTAssertTrue(message.isEphemeral)
XCTAssertEqual(obfuscationTimer?.runningTimersCount, 1)
XCTAssertEqual(deletionTimer?.runningTimersCount, 0)
}
func testThatItCreatesAndSendsAnEphemeralImageMessage() {
// given
XCTAssert(login())
let conversation = self.conversation(for: selfToUser1Conversation!)!
self.userSession?.perform {
_ = try! conversation.appendText(content: "Hello") as! ZMClientMessage
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
mockTransportSession?.resetReceivedRequests()
// when
conversation.setMessageDestructionTimeoutValue(.custom(100), for: .selfUser)
var message: ZMAssetClientMessage!
self.userSession?.perform {
message = try! conversation.appendImage(from: self.verySmallJPEGData()) as? ZMAssetClientMessage
XCTAssertTrue(message.isEphemeral)
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
// then
XCTAssertEqual(mockTransportSession?.receivedRequests().count, 2)
XCTAssertEqual(message.deliveryState, ZMDeliveryState.sent)
XCTAssertTrue(message.isEphemeral)
XCTAssertEqual(obfuscationTimer?.runningTimersCount, 1)
XCTAssertEqual(deletionTimer?.runningTimersCount, 0)
}
func testThatItDeletesAnEphemeralMessage() {
// given
XCTAssert(login())
let conversation = self.conversation(for: selfToUser1Conversation!)!
let messageCount = conversation.allMessages.count
// insert ephemeral message
conversation.setMessageDestructionTimeoutValue(.custom(0.1), for: .selfUser)
var ephemeral: ZMClientMessage!
self.userSession?.perform {
ephemeral = try! conversation.appendText(content: "Hello") as? ZMClientMessage
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
spinMainQueue(withTimeout: 0.5)
XCTAssertTrue(ephemeral.isObfuscated)
XCTAssertEqual(conversation.allMessages.count, messageCount+1)
// when
// other client deletes ephemeral message
let fromClient = user1?.clients.anyObject() as! MockUserClient
let toClient = selfUser?.clients.anyObject() as! MockUserClient
let deleteMessage = GenericMessage(content: MessageDelete(messageId: ephemeral.nonce!))
mockTransportSession?.performRemoteChanges { _ in
do {
self.selfToUser1Conversation?.encryptAndInsertData(from: fromClient, to: toClient, data: try deleteMessage.serializedData())
} catch {
XCTFail()
}
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
// then
XCTAssertNotEqual(ephemeral.visibleInConversation, conversation)
XCTAssertEqual(ephemeral.hiddenInConversation, conversation)
XCTAssertNil(ephemeral.sender)
XCTAssertEqual(conversation.allMessages.count, messageCount)
}
func remotelyInsertEphemeralMessage(conversation: MockConversation) {
let fromClient = user1?.clients.anyObject() as! MockUserClient
let toClient = selfUser?.clients.anyObject() as! MockUserClient
let genericMessage = GenericMessage(content: Text(content: "foo"), expiresAfterTimeInterval: 0.1)
XCTAssertEqual(genericMessage.ephemeral.expireAfterMillis, 100)
guard case .ephemeral? = genericMessage.content else {
return XCTFail()
}
mockTransportSession?.performRemoteChanges { _ in
do {
conversation.encryptAndInsertData(from: fromClient, to: toClient, data: try genericMessage.serializedData())
} catch {
XCTFail()
}
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
}
func testThatItSendsADeletionMessageForAnEphemeralMessageWhenTheTimerFinishes() {
// given
XCTAssert(login())
let conversation = self.conversation(for: selfToUser1Conversation!)!
let messageCount = conversation.allMessages.count
// the other user inserts an ephemeral message
remotelyInsertEphemeralMessage(conversation: selfToUser1Conversation!)
guard let ephemeral = conversation.lastMessage as? ZMClientMessage,
let genMessage = ephemeral.underlyingMessage,
case .ephemeral? = genMessage.content else {
return XCTFail()
}
XCTAssertEqual(genMessage.ephemeral.expireAfterMillis, 100)
XCTAssertEqual(conversation.allMessages.count, messageCount+1)
mockTransportSession?.resetReceivedRequests()
// when
// we start the destruction timer
self.userSession?.perform {
ephemeral.startDestructionIfNeeded()
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
spinMainQueue(withTimeout: 5.1) // We can't set isTesting and therefore have to wait 5sec at least :-/
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1)) // we have to wait until the request "made the roundtrip" to the backend
// then
XCTAssertEqual(mockTransportSession?.receivedRequests().count, 1)
XCTAssertEqual(conversation.allMessages.count, messageCount)
// the ephemeral message is hidden
XCTAssertNotEqual(ephemeral.visibleInConversation, conversation)
XCTAssertEqual(ephemeral.hiddenInConversation, conversation)
XCTAssertNil(ephemeral.sender)
guard (conversation.hiddenMessages.first(where: {
if let message = $0 as? ZMClientMessage,
let deleteMessage = message.underlyingMessage, deleteMessage.hasDeleted,
deleteMessage.deleted.messageID == ephemeral.nonce!.transportString() {
return true
} else {
return false
}
})) != nil
else {
return XCTFail()
}
}
func testThatItSendsANotificationThatTheMessageWasObfuscatedWhenTheTimerRunsOut() {
// given
XCTAssert(login())
let conversation = self.conversation(for: selfToUser1Conversation!)!
// when
conversation.setMessageDestructionTimeoutValue(.custom(1), for: .selfUser)
var ephemeral: ZMClientMessage!
self.userSession?.perform {
ephemeral = try! conversation.appendText(content: "Hello") as? ZMClientMessage
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
let messageObserver = MessageChangeObserver(message: ephemeral)!
spinMainQueue(withTimeout: 1.1)
// then
XCTAssertTrue(ephemeral.isObfuscated)
guard let messageChangeInfo = messageObserver.notifications.firstObject as? MessageChangeInfo else {
return XCTFail()
}
XCTAssertTrue(messageChangeInfo.isObfuscatedChanged)
}
}
|
gpl-3.0
|
75b1e52cb0d4a3777ae86a7416e9eb85
| 39.097778 | 140 | 0.684216 | 5.29771 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/UITestsFoundation/Screens/Login/LoginEpilogueScreen.swift
|
1
|
3803
|
import ScreenObject
import XCTest
public class LoginEpilogueScreen: ScreenObject {
private let loginEpilogueTableGetter: (XCUIApplication) -> XCUIElement = {
$0.tables["login-epilogue-table"]
}
var loginEpilogueTable: XCUIElement { loginEpilogueTableGetter(app) }
init(app: XCUIApplication = XCUIApplication()) throws {
try super.init(
expectedElementGetters: [loginEpilogueTableGetter],
app: app,
waitTimeout: 7
)
}
public func continueWithSelectedSite(title: String? = nil) throws -> MySiteScreen {
if let title = title {
let selectedSite = loginEpilogueTable.cells[title]
selectedSite.tap()
} else {
let firstSite = loginEpilogueTable.cells.element(boundBy: 2)
firstSite.tap()
}
try dismissQuickStartPromptIfNeeded()
try dismissOnboardingQuestionsPromptIfNeeded()
try dismissFeatureIntroductionIfNeeded()
return try MySiteScreen()
}
// Used by "Self-Hosted after WordPress.com login" test. When a site is added from the Sites List, the Sites List modal (MySitesScreen)
// remains active after the epilogue "done" button is tapped.
public func continueWithSelfHostedSiteAddedFromSitesList() throws -> MySitesScreen {
let firstSite = loginEpilogueTable.cells.element(boundBy: 2)
firstSite.tap()
try dismissQuickStartPromptIfNeeded()
try dismissOnboardingQuestionsPromptIfNeeded()
return try MySitesScreen()
}
public func verifyEpilogueDisplays(username: String? = nil, siteUrl: String) -> LoginEpilogueScreen {
if var expectedUsername = username {
expectedUsername = "@\(expectedUsername)"
let actualUsername = app.staticTexts["login-epilogue-username-label"].label
XCTAssertEqual(expectedUsername, actualUsername, "Username displayed is \(actualUsername) but should be \(expectedUsername)")
}
let expectedSiteUrl = getDisplayUrl(for: siteUrl)
let actualSiteUrl = app.staticTexts["siteUrl"].firstMatch.label
XCTAssertEqual(expectedSiteUrl, actualSiteUrl, "Site URL displayed is \(actualSiteUrl) but should be \(expectedSiteUrl)")
return self
}
private func getDisplayUrl(for siteUrl: String) -> String {
var displayUrl = siteUrl.replacingOccurrences(of: "http(s?)://", with: "", options: .regularExpression)
if displayUrl.hasSuffix("/") {
displayUrl = String(displayUrl.dropLast())
}
return displayUrl
}
private func dismissQuickStartPromptIfNeeded() throws {
try XCTContext.runActivity(named: "Dismiss quick start prompt if needed.") { _ in
guard QuickStartPromptScreen.isLoaded() else { return }
Logger.log(message: "Dismising quick start prompt...", event: .i)
_ = try QuickStartPromptScreen().selectNoThanks()
}
}
private func dismissOnboardingQuestionsPromptIfNeeded() throws {
try XCTContext.runActivity(named: "Dismiss onboarding questions prompt if needed.") { _ in
guard OnboardingQuestionsPromptScreen.isLoaded() else { return }
Logger.log(message: "Dismissing onboarding questions prompt...", event: .i)
_ = try OnboardingQuestionsPromptScreen().selectSkip()
}
}
private func dismissFeatureIntroductionIfNeeded() throws {
try XCTContext.runActivity(named: "Dismiss feature introduction screen if needed.") { _ in
guard FeatureIntroductionScreen.isLoaded() else { return }
Logger.log(message: "Dismissing feature introduction screen...", event: .i)
_ = try FeatureIntroductionScreen().dismiss()
}
}
}
|
gpl-2.0
|
4f9fb65bbac01a29ed99ad102d6a3a46
| 39.031579 | 139 | 0.669997 | 4.958279 | false | false | false | false |
grafiti-io/SwiftCharts
|
SwiftCharts/Views/ChartPointViewBarStacked.swift
|
1
|
5700
|
//
// ChartPointViewBarStacked.swift
// Examples
//
// Created by ischuetz on 15/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public struct TappedChartPointViewBarStacked {
public let barView: ChartPointViewBarStacked
public let stackFrame: (index: Int, view: UIView, viewFrameRelativeToBarSuperview: CGRect)
}
private class ChartBarStackFrameView: UIView {
var isSelected: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public typealias ChartPointViewBarStackedFrame = (rect: CGRect, color: UIColor)
open class ChartPointViewBarStacked: ChartPointViewBar {
fileprivate var stackViews: [(index: Int, view: ChartBarStackFrameView, targetFrame: CGRect)] = []
var stackFrameSelectionViewUpdater: ChartViewSelector?
var stackedTapHandler: ((TappedChartPointViewBarStacked) -> Void)? {
didSet {
if stackedTapHandler != nil && gestureRecognizers?.isEmpty ?? true {
enableTap()
}
}
}
public required init(p1: CGPoint, p2: CGPoint, width: CGFloat, bgColor: UIColor?, stackFrames: [ChartPointViewBarStackedFrame], settings: ChartBarViewSettings, stackFrameSelectionViewUpdater: ChartViewSelector? = nil) {
self.stackFrameSelectionViewUpdater = stackFrameSelectionViewUpdater
super.init(p1: p1, p2: p2, width: width, bgColor: bgColor, settings: settings)
for (index, stackFrame) in stackFrames.enumerated() {
let (targetFrame, firstFrame): (CGRect, CGRect) = {
if isHorizontal {
let initFrame = CGRect(x: 0, y: stackFrame.rect.origin.y, width: 0, height: stackFrame.rect.size.height)
return (stackFrame.rect, initFrame)
} else { // vertical
let initFrame = CGRect(x: stackFrame.rect.origin.x, y: self.frame.height, width: stackFrame.rect.size.width, height: 0)
return (stackFrame.rect, initFrame)
}
}()
let v = ChartBarStackFrameView(frame: firstFrame)
v.backgroundColor = stackFrame.color
if settings.cornerRadius > 0 {
let corners: UIRectCorner
if (stackFrames.count == 1) {
corners = UIRectCorner.allCorners
} else {
switch (index, isHorizontal) {
case (0, true):
corners = [.bottomLeft, .topLeft]
case (0, false):
corners = [.bottomLeft, .bottomRight]
case (stackFrames.count - 1, true):
corners = [.topRight, .bottomRight]
case (stackFrames.count - 1, false):
corners = [.topLeft, .topRight]
default:
corners = []
}
}
let bounds = CGRect(x: 0, y: 0, width: stackFrame.rect.width, height: stackFrame.rect.height)
let path = UIBezierPath(
roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: settings.cornerRadius, height: settings.cornerRadius)
)
if !corners.isEmpty {
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = path.cgPath
v.layer.mask = maskLayer
}
}
stackViews.append((index, v, targetFrame))
addSubview(v)
}
}
override func onTap(_ sender: UITapGestureRecognizer) {
let loc = sender.location(in: self)
guard let tappedStackFrame = (stackViews.filter{$0.view.frame.contains(loc)}.first) else {
print("Warn: no stacked frame found in stacked bar")
return
}
toggleSelection()
tappedStackFrame.view.isSelected = !tappedStackFrame.view.isSelected
let f = tappedStackFrame.view.frame.offsetBy(dx: frame.origin.x, dy: frame.origin.y)
stackFrameSelectionViewUpdater?.displaySelected(tappedStackFrame.view, selected: tappedStackFrame.view.isSelected)
stackedTapHandler?(TappedChartPointViewBarStacked(barView: self, stackFrame: (tappedStackFrame.index, tappedStackFrame.view, f)))
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public required init(p1: CGPoint, p2: CGPoint, width: CGFloat, bgColor: UIColor?, settings: ChartBarViewSettings) {
super.init(p1: p1, p2: p2, width: width, bgColor: bgColor, settings: settings)
}
override open func didMoveToSuperview() {
func targetState() {
frame = targetFrame
for stackFrame in stackViews {
stackFrame.view.frame = stackFrame.targetFrame
}
layoutIfNeeded()
}
if settings.animDuration =~ 0 {
targetState()
} else {
UIView.animate(withDuration: CFTimeInterval(settings.animDuration), delay: CFTimeInterval(settings.animDelay), options: .curveEaseOut, animations: {
targetState()
}, completion: nil)
}
}
}
|
apache-2.0
|
9f948c62ceb43c6bc33725f8adebd7b6
| 36.748344 | 223 | 0.570702 | 5.21978 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift
|
Solutions/Solutions/Easy/Easy_008_String_to_Integer_atoi.swift
|
1
|
2988
|
/*
https://oj.leetcode.com/problems/string-to-integer-atoi/
#8 String to Integer (atoi)
Level: easy
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
Inspired by @yuruofeifei at https://leetcode.com/discuss/8886/my-simple-solution
*/
struct Easy_008_String_to_Integer_atoi {
// t = O(N), s = O(1)
static func atoi(_ s: String) -> Int {
var sign: Int?
var base = 0
for char in s {
guard char != "+" else {
if let signUnwrapped = sign {
return base * signUnwrapped
} else {
sign = 1
continue
}
}
guard char != " " else {
continue
}
guard char != "-" else {
if let signUnwrapped = sign {
return base * signUnwrapped
} else {
sign = -1
continue
}
}
guard let intValue = Int(String(char)) else {
return base
}
if sign == nil {
sign = 1
}
guard base < Int.max / 10 || (base == Int.max / 10 && intValue <= Int.max % 10) else {
if sign == nil || sign! == 1 {
return Int.max
} else {
return Int.min
}
}
base = intValue + 10 * base
}
if sign == nil {
sign = 1
}
return base * sign!
}
}
|
mit
|
658b70cb8ae5ee779731263cc4fc1903
| 38.315789 | 294 | 0.592704 | 4.661466 | false | false | false | false |
Decybel07/L10n-swift
|
Example/Example iOS/Scenes/ChooseLanguage/ChooseLanguageTableViewController.swift
|
1
|
2148
|
//
// ChooseLanguageTableViewController.swift
// Example
//
// Created by Adrian Bobrowski on 15.08.2017.
//
//
import UIKit
import L10n_swift
final class ChooseLanguageTableViewController: UITableViewController {
private var items: [L10n] = L10n.supportedLanguages.map { L10n(language: $0) }
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self, selector: #selector(self.onLanguageChanged), name: .L10nLanguageChanged, object: nil
)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let row = self.items.firstIndex(where: { $0.language == L10n.shared.language }) {
self.tableView.selectRow(at: IndexPath(row: row, section: 0), animated: true, scrollPosition: .none)
}
}
// MARK: - @IBAction
@IBAction
private func onLanguageChanged() {
self.navigationController?.setViewControllers(
self.navigationController?.viewControllers.map {
if let storyboard = $0.storyboard, let identifier = $0.restorationIdentifier {
return storyboard.instantiateViewController(withIdentifier: identifier)
}
return $0
} ?? [],
animated: false
)
}
// MARK: - Table view data source
override func numberOfSections(in _: UITableView) -> Int {
return 1
}
override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return self.items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "language", for: indexPath)
let item = self.items[indexPath.row]
cell.textLabel?.text = item.l10n()
cell.detailTextLabel?.text = item.l10n(item)
return cell
}
override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
L10n.shared.language = self.items[indexPath.row].language
}
}
|
mit
|
45e1dff27a8a8e85e3ea5ac9ffc1803f
| 28.833333 | 112 | 0.643855 | 4.669565 | false | false | false | false |
cornerAnt/Digger
|
Sources/DiggerHelper.swift
|
1
|
1782
|
//
// DiggerHelper.swift
// Digger
//
// Created by ant on 2017/10/26.
// Copyright © 2017年 github.cornerant. All rights reserved.
//
import Foundation
// MARK:- result help
public enum Result<T> {
case failure(Error)
case success(T)
}
// MARK:- error help
public let DiggerErrorDomain = "com.github.cornerAnt.DiggerErrorDomain"
public enum DiggerError: Int {
case badURL = 9981
case fileIsExist = 9982
case fileInfoError = 9983
case invalidStatusCode = 9984
case diskOutOfSpace = 9985
case downloadCanceled = -999
}
// MARK:- error help
public enum LogLevel {
case high,low,none
}
public func diggerLog<T>(_ info: T, file: NSString = #file, method: String = #function, line: Int = #line){
switch DiggerManager.shared.logLevel {
case .none:
_ = ""
case .low:
print("***************DiggerLog****************")
print("\(info)" + "\n")
case .high:
print("***************DiggerLog****************")
print( "file : " + "\(file.lastPathComponent)" + "\n"
+ "method : " + "\(method)" + "\n"
+ "line : " + "[\(line)]:" + "\n"
+ "info : " + "\(info)"
)
}
}
// MARK:- url helper
public protocol DiggerURL {
func asURL() throws -> URL
}
extension String: DiggerURL {
public func asURL() throws -> URL {
guard let url = URL(string: self) else { throw NSError(domain: DiggerErrorDomain, code: DiggerError.badURL.rawValue, userInfo: ["url":self]) }
return url
}
}
extension URL: DiggerURL {
public func asURL() throws -> URL {
return self
}
}
|
mit
|
fe280d27096ac9bf8ad9d5b170c4daf1
| 19.686047 | 153 | 0.525014 | 3.737395 | false | false | false | false |
LYM-mg/DemoTest
|
其他功能/MGBookViews/MGBookViews/Camera/CameraToolBarView.swift
|
1
|
4472
|
//
// CameraToolBarView.swift
// MGBookViews
//
// Created by newunion on 2017/12/25.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
@objc protocol CameraToolBarViewDelegate: NSObjectProtocol {
@objc optional func cancel(_ toolBarView: CameraToolBarView,_ cancelBtn: UIButton)
@objc optional func retake(_ toolBarView: CameraToolBarView,_ retakeBtn: UIButton)
@objc optional func takePhoto(_ toolBarView: CameraToolBarView,_ takePhotoBtn: UIButton)
@objc optional func flash(_ toolBarView: CameraToolBarView,_ flashBtn: UIButton)
@objc optional func switchCamera(_ toolBarView: CameraToolBarView,_ switchCameraBtn: UIButton)
}
class CameraToolBarView: UIView {
//照相按钮
var photoBtn:UIButton!
//取消按钮/重拍
var cancelBtn:UIButton!
//保存按钮
var switchCameraBtn:UIButton!
var delegate: CameraToolBarViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setUpUI() {
self.cancelBtn = UIButton(type: .custom)
// cancelBtn.frame = CGRect(x: ((WIDTH / 2.0) - 30) / 2.0, y: (82 - 30) / 2.0, width: 50, height: 50)
cancelBtn.setTitle("取消", for: .normal)
cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
cancelBtn.addTarget(self, action: #selector(self.cancelAction), for: .touchUpInside)
cancelBtn.sizeToFit()
self.addSubview(cancelBtn)
self.photoBtn = UIButton(type: .custom)
photoBtn.setTitle("拍照", for: .normal)
photoBtn.setBackgroundImage(#imageLiteral(resourceName: "拍摄"), for: .normal)
// photoBtn.frame = CGRect(x: (WIDTH - 50) / 2.0, y: (82 - 50) / 2.0, width: 50, height: 50)
photoBtn.addTarget(self, action: #selector(self.takePhotoAction), for: .touchUpInside)
// photoBtn.setImage(UIImage(named: "cameraPhoto"), for: .normal)
self.addSubview(photoBtn)
self.switchCameraBtn = UIButton(type: .custom)
switchCameraBtn.setTitle("切换", for: .normal)
switchCameraBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
switchCameraBtn.addTarget(self, action: #selector(self.saveAction), for: .touchUpInside)
switchCameraBtn.sizeToFit()
self.addSubview(switchCameraBtn)
// 闪光灯
// let flashBtn = UIButton(type: .custom)
// flashBtn.frame = CGRect(x: ((WIDTH / 2.0) - 30) / 2.0 + (WIDTH / 2.0), y: (82 - 30) / 2.0, width: 60, height: 30)
// flashBtn.setTitle("闪光灯", for: .normal)
// lampBtn.setImage(UIImage(named: "openFlish"), for: .selected)
// lampBtn.setImage(UIImage(named: "closeFlish"), for: .normal)
// flashBtn.addTarget(self, action: #selector(self.flashButtonClick), for: .touchUpInside)
// self.addSubview(flashBtn)
cancelBtn.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(50)
make.centerY.equalToSuperview()
}
photoBtn.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalTo(CGSize(width: 50, height: 50))
}
switchCameraBtn.snp.makeConstraints { (make) in
make.right.equalToSuperview().offset(-50)
make.centerY.equalToSuperview()
}
}
//取消按钮 /重拍
func cancelAction(){
if delegate != nil,(delegate?.responds(to: #selector(CameraToolBarViewDelegate.cancel(_:_:))))! {
delegate!.cancel!(self, cancelBtn)
}
}
//保存按钮-保存到相册,使用照片
func saveAction(){
if delegate != nil,(delegate?.responds(to: #selector(CameraToolBarViewDelegate.switchCamera(_:_:))))! {
delegate!.switchCamera!(self, switchCameraBtn)
}
}
//照相按钮
func takePhotoAction() {
if delegate != nil,(delegate?.responds(to: #selector(CameraToolBarViewDelegate.takePhoto(_:_:))))! {
delegate!.takePhoto!(self, photoBtn)
}
}
//闪光灯按钮
func flashButtonClick() {
if delegate != nil,(delegate?.responds(to: #selector(CameraToolBarViewDelegate.flash(_:_:))))! {
// delegate!.flash(self, flash)
}
}
}
|
mit
|
c0d9d740270384d0a3b027e6f8cda4ad
| 37.201754 | 123 | 0.624569 | 4.108491 | false | false | false | false |
sjchmiela/call-of-beacons
|
ios/CallOfBeacons/CallOfBeacons/COBFlagBehavior.swift
|
1
|
1523
|
//
// COBFlagBehavior.swift
// CallOfBeacons
//
// Created by Stanisław Chmiela on 02.06.2016.
// Copyright © 2016 Stanisław Chmiela, Rafał Żelazko. All rights reserved.
//
import Foundation
class COBFlagBehavior: COBBeaconBehavior {
static func beaconIsInRange(beacon: COBBeacon, forGamerState gamerState: COBGamerState) -> COBGamerState {
// If the gamer is alive
if gamerState.healthPoints > 0 {
// Add to the score points based on the proximity.
if let proximity = beacon.proximity {
switch proximity {
case .Immediate:
gamerState.score += 10
case .Near:
gamerState.score += 5
case .Far:
gamerState.score += 2
default:
break
}
}
}
return gamerState
}
static func highlighted(beacon: COBBeacon, forGamerState gamerState: COBGamerState) -> Bool {
if let proximity = beacon.proximity where proximity != .Unknown && gamerState.isScoring {
return true
}
return false
}
static func pulseRadius(beacon: COBBeacon, forGamerState gamerState: COBGamerState?) -> CGFloat? {
if let gamerState = gamerState, let proximity = beacon.proximity where proximity != .Unknown && gamerState.isScoring {
return 15 * (4 - CGFloat(proximity.rawValue)) + 15
}
return nil
}
}
|
mit
|
9ce66d2b0937dc386b76b6ebc2c6f9c3
| 32.021739 | 126 | 0.578393 | 4.412791 | false | false | false | false |
myfreeweb/freepass
|
ios/Freepass/Freepass/FieldViewModel.swift
|
1
|
1925
|
import Foundation
import RxSwift
class FieldViewModel {
enum FieldType {
case Stored
case Derived
}
let dbag = DisposeBag()
let field_type: Variable<FieldType?> = Variable(nil)
let field_name = Variable("")
let derived_counter: Variable<UInt32> = Variable(0)
let derived_site_name = Variable("")
let derived_usage: Variable<DerivedUsage?> = Variable(nil)
let stored_data: Variable<[UInt8]?> = Variable(nil)
let stored_data_string = Variable("")
let stored_usage: Variable<StoredUsage?> = Variable(nil)
func init_stored_data_conversion() {
var updatingFromSelf = false
stored_data.asObservable().subscribeNext {
if updatingFromSelf { return }
let b = $0 ?? []
if let s = NSString(bytes: b, length: b.count, encoding: NSUTF8StringEncoding) as? String {
self.stored_data_string.value = s
}
}.addDisposableTo(dbag)
stored_data_string.asObservable().subscribeNext {
updatingFromSelf = true
self.stored_data.value = $0.utf8.map { $0 }
updatingFromSelf = false
}.addDisposableTo(dbag)
}
init(name: String, field: Field) {
init_stored_data_conversion()
field_name.value = name
switch field {
case .Derived(let counter, let site_name, let usage):
field_type.value = .Derived
derived_counter.value = counter
derived_site_name.value = site_name ?? ""
derived_usage.value = usage
case .Stored(data: let data, usage: let usage):
field_type.value = .Stored
stored_data.value = data
stored_usage.value = usage
}
}
func toField() -> (String, Field)? {
switch (field_name.value, field_type.value) {
case (let name, .Derived?):
return (name, .Derived(counter: derived_counter.value ?? 1, site_name: derived_site_name.value, usage: derived_usage.value ?? .Password(template: "Maximum")))
case (let name, .Stored?):
return (name, .Stored(data: stored_data.value ?? [], usage: stored_usage.value ?? .Password))
default: return nil
}
}
}
|
unlicense
|
d7fd8d51c4e19ffd83649e3885981e03
| 30.57377 | 161 | 0.692468 | 3.257191 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie
|
4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/FriendTrends-关注/Model/XMGRecommendCategory.swift
|
1
|
553
|
//
// XMGRecommendCategory.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/2/16.
// Copyright © 2016年 蒋进. All rights reserved.
//
import UIKit
class XMGRecommendCategory: NSObject {
/** 总数 */
var count: Int = 0
/** id */
var id: String = ""
/** 名字 */
var name: String = ""
/** 这个类别对应的用户数据 */
lazy var users:NSMutableArray? = NSMutableArray()
/** 总数 */
var total: NSNumber = 0
/** 当前页码 */
var currentPage: Int = 0
}
|
apache-2.0
|
bdbc974e9a0d462ad8059130b6f1284d
| 16.241379 | 53 | 0.542 | 3.448276 | false | false | false | false |
tectijuana/patrones
|
Bloque1SwiftArchivado/PracticasSwift/LopezValenzuelaMarcoAntonio/127-Practica.swift
|
1
|
597
|
//
// main.swift
// Patrones
//
// Created by Lopez Valenzuela Marco Antonio on 2/20/17.
// Copyright © 2017 Lopez Valenzuela Marco Antonio. All rights reserved.
//
import Foundation
func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
var arreglo=[Int]()
var contNeg : Int = 0
var contPos : Int = 0
for i in 0..<24{
arreglo.append(randomInt(min: -100, max:100))
if arreglo[i]>=0{
contPos+=1
}
else{
contNeg+=1
}
}
print("Positive numbers: \(contPos)")
print("Negative numbers: \(contNeg)")
|
gpl-3.0
|
2654a3d8713274968e47a6c4388589cf
| 16.529412 | 73 | 0.624161 | 2.994975 | false | false | false | false |
wisesascha/SPHWNetworking
|
Networking/Networking.swift
|
1
|
10371
|
//
// Networking.swift
// Networking
//
import Foundation
import CocoaAsyncSocket
import GZIP
enum NetworkingError: Error {
case invalidUrl
}
open class NetworkingRequest: NSObject, GCDAsyncSocketDelegate {
//MARK: - HTTP Messages -
var requestMessage: CFHTTPMessage?
var responseMessage: CFHTTPMessage?
//MARK: - External Objects -
var completionCB: (Response, CookieJar) -> ()?
var progressCB: (_ progress: Int) -> ()
var request: Request
var response: Response?
//MARK: - Internal Objects -
var socket: GCDAsyncSocket?
var url: URL
var bodyString: String = ""
var cookieStore: CookieJar?
var redirectCount: Int = 0
var completed: Bool = false
//MARK; - Setup Functions -
public init(request: Request, cookieStore: CookieJar, progressCB: @escaping (_ progress: Int) -> () = {progress in }, completion: @escaping (Response, CookieJar) -> ()) throws {
self.url = URL(string: request.url)!
self.completionCB = completion
self.progressCB = progressCB
self.request = request
self.cookieStore = cookieStore
super.init()
guard self.url.host != nil else {
throw NetworkingError.invalidUrl
}
}
open func run() {
responseMessage = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
requestMessage = CFHTTPMessageCreateRequest(kCFAllocatorDefault, request.rawMethod as CFString, CFURLCreateWithString(kCFAllocatorDefault, url.absoluteString as CFString!, nil), kCFHTTPVersion1_1).takeRetainedValue()
if(request.timeout != 0) {
Timer.scheduledTimer(timeInterval: request.timeout, target: self, selector: #selector(NetworkingRequest.timedOut(_:)), userInfo: nil, repeats: false)
}
response = Response()
if((url as NSURL).port != 443 && (url as NSURL).port != 80 && (url as NSURL).port != nil) {
CFHTTPMessageSetHeaderFieldValue(self.requestMessage!, "Host" as CFString, "\(url.host!):\((url as NSURL).port!)" as CFString?)
} else {
CFHTTPMessageSetHeaderFieldValue(self.requestMessage!, "Host" as CFString, url.host! as CFString?)
}
if(request.dataBody != nil) {
CFHTTPMessageSetBody(requestMessage!, request.dataBody! as NSData as CFData)
CFHTTPMessageSetHeaderFieldValue(self.requestMessage!, "Content-Length" as CFString, "\((request.dataBody!.count))" as CFString)
} else {
if(request.body.characters.count > 0) {
CFHTTPMessageSetBody(requestMessage!, request.body.data(using: String.Encoding.utf8)! as NSData as CFData)
let data = request.body.data(using: String.Encoding.utf8)
CFHTTPMessageSetHeaderFieldValue(self.requestMessage!, "Content-Length" as CFString, "\((data!.count))" as CFString? )
}
}
for header in request.headers {
CFHTTPMessageSetHeaderFieldValue(self.requestMessage!, header.key as CFString, header.value as CFString?)
}
if request.type == .JSON {
CFHTTPMessageSetHeaderFieldValue(self.requestMessage!, "Content-type" as CFString, "application/json" as CFString?)
}
let validCookies = cookieStore?.validCookies(self.url)
let headerFields = HTTPCookie.requestHeaderFields(with: validCookies!)
for (key, value): (String, String) in headerFields {
NSLog("\(key): \(value)")
CFHTTPMessageSetHeaderFieldValue(self.requestMessage!, key as CFString, value as CFString)
}
let queue = DispatchQueue(label: "com.networking.queue\(arc4random_uniform(1000))", attributes: [])
self.socket = GCDAsyncSocket(delegate: self, delegateQueue: queue, socketQueue: queue)
var host = url.host
var port: Int
if(self.url.scheme == "https") {
port = (url as NSURL).port?.intValue ?? 443
} else {
port = (url as NSURL).port?.intValue ?? 80
}
if(request.proxy != "") {
let proxyURL = URL(string: request.proxy)
host = proxyURL?.host
CFHTTPMessageSetHeaderFieldValue(self.requestMessage!, "Proxy-Connection" as CFString, "keep-alive" as CFString?)
if((proxyURL as NSURL?)?.port != nil) {
port = ((proxyURL as NSURL?)?.port?.intValue)!
}
}
if(request.interface == "") {
try! socket!.connect(toHost: host, onPort: UInt16(port), withTimeout: -1)
} else {
try! socket!.connect(toHost: host, onPort: UInt16(port), viaInterface: request.interface, withTimeout: -1)
}
if(self.url.scheme == "https") {
self.socket!.startTLS([ String(kCFStreamSSLPeerName): host!])
}
}
//MARK: - Socket Delegates -
open func socket(_ sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16) {
print("Connected to URL: \(self.url)")
if let data = CFHTTPMessageCopySerializedMessage(self.requestMessage!) {
let rData = data.takeRetainedValue()
var string = String(data: rData as Data, encoding: String.Encoding.utf8)
if(request.proxy == "") {
socket!.write(rData as Data, withTimeout: -1, tag: 0)
} else {
var array = string?.components(separatedBy: "\r\n")
array![0] = "\(request.rawMethod) \(url.absoluteString) HTTP/1.1"
string = array?.joined(separator: "\r\n")
}
self.progressCB(25)
socket!.readData(to: "\r\n\r\n".data(using: String.Encoding.ascii), withTimeout: -1, tag: 1)
}
}
open func socket(_ sock: GCDAsyncSocket!, didRead data: Data!, withTag tag: Int) {
data.withUnsafeBytes() { (bytes: UnsafePointer<UInt8>) -> Void in
if let string = String(data: data, encoding: String.Encoding.ascii) {
CFHTTPMessageAppendBytes(self.responseMessage!, bytes, data.count)
if(tag == 1) {
if let encoding = CFHTTPMessageCopyHeaderFieldValue(self.responseMessage!, "Transfer-Encoding" as CFString) {
if encoding.takeRetainedValue() as String == "chunked" {
socket?.readData(to: "\r\n".data(using: String.Encoding.ascii), withTimeout: -1, tag: 3)
NSLog("reading forward chunked")
}
} else if let length = (CFHTTPMessageCopyHeaderFieldValue(self.responseMessage!, "Content-Length" as CFString)) {
let intLength = UInt(length.takeRetainedValue() as String)
if(intLength == 0) {
self.requestFinished()
}
socket!.readData(toLength: intLength!, withTimeout: -1, tag: 2)
NSLog("reading forward length")
} else {
self.requestFinished()
}
self.progressCB(35)
}
if(tag == 2) {
self.response!.body += string
self.response!.dataBody.append(data)
self.requestFinished()
}
if(tag == 3) {
if let length = UInt(string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines), radix: 16) {
if(length != 0) {
socket!.readData(toLength: length, withTimeout: -1, tag: 4)
} else {
self.requestFinished()
}
}
}
let dataCar = "\r\n".data(using: String.Encoding.ascii)
if(tag == 4) {
self.response!.body += string
self.response!.dataBody.append(data)
socket?.readData(to: dataCar, withTimeout: -1, tag: 5)
}
if(tag == 5) {
socket?.readData(to: dataCar, withTimeout: -1, tag: 3)
self.progressCB(55)
}
}
}
}
open func socketDidDisconnect(_ sock: GCDAsyncSocket!, withError err: NSError!) {
NSLog("Disconnected")
if(completed == false) {
self.responseGenerator()
}
}
//MARK: - Handlers
func requestFinished() {
print("Finished: \(self.url)")
let statusCode = CFHTTPMessageGetResponseStatusCode(self.responseMessage!)
if statusCode == 301 || statusCode == 302 || statusCode == 307 || statusCode == 308 {
if let location = CFHTTPMessageCopyHeaderFieldValue(self.responseMessage!, "Location" as CFString)?.takeRetainedValue() {
if(redirectCount < self.request.maxRedirects) {
let oldUrl = url
self.url = URL(string: location as String, relativeTo: oldUrl)!
self.redirectCount += 1
self.responseMessage = nil
completed = true
self.run()
} else {
self.responseGenerator()
}
}
} else {
self.responseGenerator()
}
}
func responseGenerator() {
let statusCode = CFHTTPMessageGetResponseStatusCode(self.responseMessage!)
self.completed = true
response!.url = self.url.absoluteString
// response!.size = (self.response!.body.dataUsingEncoding(NSASCIIStringEncoding)?.length)!;
response!.statusCode = statusCode
response!.redirectCount = redirectCount
if let headerCFDict = CFHTTPMessageCopyAllHeaderFields(self.responseMessage!)?.takeRetainedValue() as NSDictionary? {
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerCFDict as! [String : String], for: self.url)
self.cookieStore?.addCookies(cookies)
for rawKey in headerCFDict.allKeys {
let key = rawKey as! String as String!
let value = (headerCFDict.value(forKey: key!) as! String)
response!.headers.append(KVPair(key: key!, value: value))
switch (key?.lowercased()) {
case "content-type"?:
if(value.lowercased().contains("application/json")) {
response!.type = Type.JSON
} else {
response!.type = Type.PlainText
}
default: break
}
}
}
completionCB(response!, cookieStore!)
self.progressCB(100)
}
func errorHandler(_ error: String) {
}
func timedOut(_ timer: Timer) {
self.completed = true
socket!.disconnect()
response!.body = "TIMEDOUT"
completionCB(response!, cookieStore!)
self.progressCB(100)
}
}
public enum Type: String {
case JSON, XML, URLEncoded = "URL Encoded", PlainText = "Plain Text", HTML
}
public enum FollowRedirect {
case all
case get
}
open class HttpAuth: NSObject {
open var username: String = ""
open var password: String = ""
public init(username: String, password: String) {
self.username = username
self.password = password
}
}
public enum Method: String {
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}
open class KVPair: NSObject {
open var key: String = ""
open var value: String = ""
public init(key: String, value: String) {
self.key = key
self.value = value
}
}
|
mit
|
a091e1d26856500f14d58cc7c26fb078
| 39.197674 | 221 | 0.649407 | 4.255642 | false | false | false | false |
kaji001/GnomesBook
|
GnomesBook/MainTableViewController.swift
|
1
|
5860
|
//
// MainTableViewController.swift
// GnomesBook
//
// Created by Mario Martinez on 19/6/16.
// Copyright © 2016 Brastlewark Town. All rights reserved.
//
import UIKit
class MainTableViewController: UITableViewController, UISearchBarDelegate {
let alphabet : Array<String> = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
var sections : Array<String>
var sectionsFiltered : Array<String>
var alphabeticalNames : Dictionary<String, [Gnome]>
var alphabeticalNamesFiltered : Dictionary<String, [Gnome]>
var searchActive : Bool = false
required init?(coder aDecoder: NSCoder) {
sections = alphabet
sectionsFiltered = alphabet
alphabeticalNames = AppManager.sharedInstance.alphabeticalDictionaryGnome
alphabeticalNamesFiltered = alphabeticalNames
super.init(coder:aDecoder)
}
override func viewWillAppear(animated: Bool) {
searchActive = false
reloadSections()
}
private func reloadSections() {
sections = alphabet
sectionsFiltered = alphabet
for section in alphabet {
if alphabeticalNamesFiltered[section] == nil {
sectionsFiltered.removeAtIndex(sectionsFiltered.indexOf(section)!)
}
if alphabeticalNames[section] == nil {
sections.removeAtIndex(sections.indexOf(section)!)
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return searchActive ? sectionsFiltered.count : sections.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
return searchActive ? self.sectionsFiltered[section] : self.sections[section]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let arraySection: [Gnome] = searchActive ? alphabeticalNamesFiltered[sectionsFiltered[section]]! : alphabeticalNames[sections[section]]!
return arraySection.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : MainTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("MainTableViewCell", forIndexPath: indexPath) as! MainTableViewCell
let gnomeItem = getGnomeTableView(indexPath)
cell.setNameText(gnomeItem.name + ", " + gnomeItem.surname)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let gnome : Gnome = getGnomeTableView(indexPath)
self.performSegueWithIdentifier("ProfileViewControllerSegue", sender: gnome)
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return tableView.sectionHeaderHeight
}
return 0
}
func getGnomeTableView(indexPath: NSIndexPath) -> Gnome {
let arrayNamesSection : [Gnome]
if searchActive {
arrayNamesSection = alphabeticalNamesFiltered[sectionsFiltered[indexPath.section]]! as [Gnome]
} else {
arrayNamesSection = alphabeticalNames[sections[indexPath.section]]! as [Gnome]
}
return arrayNamesSection[indexPath.row]
}
// MARK: - UISearchBarDelegate Delegate
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchActive = true
alphabeticalNamesFiltered = alphabeticalNames
sectionsFiltered = sections
}
func searchBarTextDidShoudEditing(searchBar: UISearchBar) {
searchActive = true
alphabeticalNamesFiltered = alphabeticalNames
sectionsFiltered = sections
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchActive = false
}
func searchBarTextDidShoudEndEditing(searchBar: UISearchBar) {
searchActive = false
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchActive = false
self.tableView.reloadData()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchActive = false
self.tableView.reloadData()
}
// MARK: - UISearchResultsUpdating Delegate
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
alphabeticalNamesFiltered = alphabeticalNames
sectionsFiltered = sections
if !searchString.isEmpty {
for (key, value) in alphabeticalNamesFiltered {
let array: [Gnome] = value.filter(){
return $0.fullName.uppercaseString.containsString(searchString.uppercaseString)
}
if array.count == 0 {
alphabeticalNamesFiltered.removeValueForKey(key)
} else {
alphabeticalNamesFiltered[key] = array
}
}
}
reloadSections()
self.tableView.reloadData()
return true
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ProfileViewControllerSegue" {
if let nextViewController : ProfileViewController = segue.destinationViewController as? ProfileViewController {
nextViewController.gnome = sender as! Gnome
}
}
}
}
|
gpl-3.0
|
03bac02a2e141b8fbb8d26fbea0885e7
| 32.678161 | 155 | 0.634921 | 5.633654 | false | false | false | false |
RevenueCat/purchases-ios
|
Sources/Logging/Strings/CodableStrings.swift
|
1
|
2662
|
//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// CodableStrings.swift
//
// Created by Juanpe Catalán on 29/8/21.
import Foundation
// swiftlint:disable identifier_name
enum CodableStrings {
case unexpectedValueError(type: Any.Type, value: Any)
case valueNotFoundError(value: Any.Type, context: DecodingError.Context)
case keyNotFoundError(key: CodingKey, context: DecodingError.Context)
case invalid_json_error(jsonData: [String: Any])
case encoding_error(_ error: Error)
case decoding_error(_ error: Error)
case corrupted_data_error(context: DecodingError.Context)
case typeMismatch(type: Any, context: DecodingError.Context)
}
extension CodableStrings: CustomStringConvertible {
var description: String {
switch self {
case let .unexpectedValueError(type, value):
return "Found unexpected value '\(value)' for type '\(type)'"
case let .valueNotFoundError(value, context):
let description = context.debugDescription
return "No value found for: \(value), codingPath: \(context.codingPath), description:\n\(description)"
case let .keyNotFoundError(key, context):
let description = context.debugDescription
return "Key '\(key)' not found, codingPath: \(context.codingPath), description:\n\(description)"
case let .invalid_json_error(jsonData):
return "The given json data was not valid: \n\(jsonData)"
case let .encoding_error(error):
return "Couldn't encode data into json. Error:\n\(error.localizedDescription)"
case let .decoding_error(error):
let underlyingErrorMessage: String
if let underlyingError = (error as NSError).userInfo[NSUnderlyingErrorKey] as? NSError {
underlyingErrorMessage = "\nUnderlying error: \(underlyingError.debugDescription)"
} else {
underlyingErrorMessage = ""
}
return "Couldn't decode data from json.\nError: \(error.localizedDescription)." + underlyingErrorMessage
case let .corrupted_data_error(context):
return "Couldn't decode data from json, it was corrupted: \(context)"
case let .typeMismatch(type, context):
let description = context.debugDescription
return "Type '\(type)' mismatch, codingPath:\(context.codingPath), description:\n\(description)"
}
}
}
|
mit
|
95a9088dcbab292cff860dd2a23c3a5b
| 41.238095 | 116 | 0.6708 | 4.726465 | false | false | false | false |
HabitRPG/habitrpg-ios
|
HabitRPG/Interactors/CalculateUserStatsInteractor.swift
|
1
|
5444
|
//
// CalculateUserStatsInteractor.swift
// Habitica
//
// Created by Phillip Thelen on 07.06.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import ReactiveSwift
struct CalculatedUserStats {
var totalStrength: Int = 0
var totalIntelligence: Int = 0
var totalConstitution: Int = 0
var totalPerception: Int = 0
var levelStat: Int = 0
var buffStrength: Int = 0
var buffIntelligence: Int = 0
var buffConstitution: Int = 0
var buffPerception: Int = 0
var allocatedStrength: Int = 0
var allocatedIntelligence: Int = 0
var allocatedConstitution: Int = 0
var allocatedPerception: Int = 0
var gearStrength: Int = 0
var gearIntelligence: Int = 0
var gearConstitution: Int = 0
var gearPerception: Int = 0
var gearBonusStrength: Int = 0
var gearBonusIntelligence: Int = 0
var gearBonusConstitution: Int = 0
var gearBonusPerception: Int = 0
var gearWithBonusStrength: Int = 0
var gearWithBonusIntelligence: Int = 0
var gearWithBonusConstitution: Int = 0
var gearWithBonusPerception: Int = 0
mutating func recalculateTotals() {
totalStrength = levelStat + buffStrength + allocatedStrength + gearStrength + gearBonusStrength
totalIntelligence = levelStat + buffIntelligence + allocatedIntelligence + gearIntelligence + gearBonusIntelligence
totalConstitution = levelStat + buffConstitution + allocatedConstitution + gearConstitution + gearBonusConstitution
totalPerception = levelStat + buffPerception + allocatedPerception + gearPerception + gearBonusPerception
}
}
class CalculateUserStatsInteractor: Interactor<(StatsProtocol, [GearProtocol]), CalculatedUserStats> {
private let userRepository = UserRepository()
override func configure(signal: Signal<(StatsProtocol, [GearProtocol]), NSError>) -> Signal<CalculatedUserStats, NSError> {
return signal.map({ (userStats, gear) in
var stats = CalculatedUserStats()
stats.levelStat = min(userStats.level / 2, 100)
stats.allocatedStrength = userStats.strength
stats.allocatedIntelligence = userStats.intelligence
stats.allocatedConstitution = userStats.constitution
stats.allocatedPerception = userStats.perception
if let buff = userStats.buffs {
stats.buffStrength = buff.strength
stats.buffIntelligence = buff.intelligence
stats.buffConstitution = buff.constitution
stats.buffPerception = buff.perception
}
var gearBonusStrength = 0.0
var gearBonusIntelligence = 0.0
var gearBonusConstitution = 0.0
var gearBonusPerception = 0.0
for row in gear {
stats.gearStrength += row.strength
stats.gearIntelligence += row.intelligence
stats.gearConstitution += row.constitution
stats.gearPerception += row.perception
var itemClass = row.habitClass
let itemSpecialClass = row.specialClass
let classBonus = 0.5
let userClassMatchesGearClass = itemClass == userStats.habitClass
let userClassMatchesGearSpecialClass = itemSpecialClass == userStats.habitClass
if !userClassMatchesGearClass && !userClassMatchesGearSpecialClass {
continue
}
if itemClass?.isEmpty ?? false || itemClass == "special" {
itemClass = itemSpecialClass
}
switch itemClass {
case "rogue"?:
gearBonusStrength += Double(row.strength) * classBonus
gearBonusPerception += Double(row.perception) * classBonus
case "healer"?:
gearBonusConstitution += Double(row.constitution) * classBonus
gearBonusIntelligence += Double(row.intelligence) * classBonus
case "warrior"?:
gearBonusStrength += Double(row.strength) * classBonus
gearBonusConstitution += Double(row.constitution) * classBonus
case "wizard"?:
gearBonusIntelligence += Double(row.intelligence) * classBonus
gearBonusPerception += Double(row.perception) * classBonus
default:
break
}
}
stats.gearBonusStrength = Int(gearBonusStrength)
stats.gearBonusIntelligence = Int(gearBonusIntelligence)
stats.gearBonusConstitution = Int(gearBonusConstitution)
stats.gearBonusPerception = Int(gearBonusPerception)
stats.gearWithBonusStrength = stats.gearStrength + stats.gearBonusStrength
stats.gearWithBonusIntelligence = stats.gearIntelligence + stats.gearBonusIntelligence
stats.gearWithBonusConstitution = stats.gearConstitution + stats.gearBonusConstitution
stats.gearWithBonusPerception = stats.gearPerception + stats.gearBonusPerception
stats.recalculateTotals()
return stats
})
}
}
|
gpl-3.0
|
c69d582d57ff34bdbe87534f8bf679ac
| 40.234848 | 127 | 0.623737 | 4.998163 | false | false | false | false |
exyte/Macaw
|
Source/model/geom2d/GeomUtils.swift
|
1
|
1496
|
import Foundation
// TODO need to replace this class with model methods
open class GeomUtils {
@available(*, deprecated)
open class func concat(t1: Transform, t2: Transform) -> Transform {
return t1.concat(with: t2)
}
open class func centerRotation(node: Node, place: Transform, angle: Double) -> Transform {
let center = GeomUtils.center(node: node)
return GeomUtils.anchorRotation(node: node, place: place, anchor: center, angle: angle)
}
open class func anchorRotation(node: Node, place: Transform, anchor: Point, angle: Double) -> Transform {
let move = Transform.move(dx: anchor.x, dy: anchor.y)
let asin = sin(angle); let acos = cos(angle)
let rotation = Transform(
m11: acos, m12: -asin,
m21: asin, m22: acos,
dx: 0.0, dy: 0.0
)
let t1 = move.concat(with: rotation)
let t2 = t1.concat(with: move.invert()!)
let result = place.concat(with: t2)
return result
}
open class func centerScale(node: Node, sx: Double, sy: Double) -> Transform {
let center = GeomUtils.center(node: node)
return Transform.move(dx: center.x * (1.0 - sx), dy: center.y * (1.0 - sy)).scale(sx: sx, sy: sy)
}
open class func center(node: Node) -> Point {
guard let bounds = node.bounds else {
return Point()
}
return Point(x: bounds.x + bounds.w / 2.0, y: bounds.y + bounds.h / 2.0)
}
}
|
mit
|
043638cb23916d1622c3dac27bbdb6af
| 31.521739 | 109 | 0.597594 | 3.596154 | false | false | false | false |
Liqiankun/DLSwift
|
Swift/Swift函数.playground/Contents.swift
|
1
|
2706
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
func sayHello(name:String?) -> String{
return "Hello" + (name ?? "Cuest")
}
var name : String? = nil
sayHello(name)
func printHello() -> Void {
print("Hello")
}
//找到数组中的最大值
func findMaxAndMin(numbers:[Int]) -> (max:Int,min:Int)? {
if numbers.isEmpty {
return nil
}
var max = numbers[0]
var min = numbers[0]
for number in numbers{
min = min < number ? min : number
max = max > number ? max : number
}
return (max,min)
}
var numbers : [Int] = [123,12,35,78,43,67,45]
numbers = numbers ?? []
findMaxAndMin(numbers)
//多个参数
//withGreetingName是外部参数名
//name是内部参数名
func sayHelloTo(greeting:String,withGreetingName name:String) -> Void {
print("\(greeting) \(name)")
}
sayHelloTo("Hello", withGreetingName:"David")
//_ numberTwo调用的时候可以不显示参数名
func mutiply(numberOne:Int,_ numberTwo:Int) -> Int {
return numberOne * numberTwo
}
mutiply(2, 3)
//默认参数
func helloTo(greeting:String,withGreetingName name:String ,punctuation:String = "!") -> Void {
print("\(greeting) \(name)\(punctuation)")
}
//可变参数
func mean(numbers:Double...) ->Double{
var sum:Double = 0
for number in numbers{
sum += number
}
return sum / Double(numbers.count)
}
mean(12,34,12)
func toBinary(inout number: Int) -> String {
var res = ""
repeat{
res = String(number%2) + res
number /= 2
} while number != 0
return res
}
var number12 : Int = 12
toBinary(&number12)
func changeArray(inout arr:[Int],by number:Int){
for index in 0..<arr.count{
arr[index] = number
}
}
var arrayA:[Int] = [1,2,3]
changeArray(&arrayA, by: 2)
//函数类型
let change = changeArray //let change:(inout arr:[Int],by number:Int) = changeArray
var sortArray : [Int] = []
for _ in 0...1000{
sortArray.append(random()%1000)
}
sortArray.sort() //sortArray不改变
sortArray.sortInPlace()
func bigFirst(a:Int,b:Int) -> Bool {
return a > b;
}
//函数参数
sortArray.sort(bigFirst)
/**---------------------------函数式编程----------------------------*/
func changeScores(inout scores:[Int],by changeScore:(Int) ->Int) {
for (index,score) in scores.enumerate() {
scores[index] = changeScore(score)
}
}
func changeScore(number:Int) ->Int {
return Int(Double(number) / 150.0 * 100.0)
}
changeScores(&sortArray, by: changeScore)
//sortArray.map()
//sortArray.filter()
//sortArray.reduce()
//数组元素相加
sortArray.reduce(0, combine: +)
|
mit
|
8df7ce8b59dd5d8bdc5fcd54e1353a34
| 16.248322 | 94 | 0.614397 | 3.196517 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/Components/Announcements/Record/AnnouncementRecord+Key.swift
|
1
|
2359
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import PlatformKit
extension AnnouncementRecord {
/// A key used to register this Announcement history
/// All keys must be prefixed by `"announcement-"`
public enum Key {
case applePay
case assetRename(code: String)
case backupFunds
case buyBitcoin
case claimFreeCryptoDomain
case majorProductBlocked
case newAsset(code: String)
case resubmitDocuments
case resubmitDocumentsAfterRecovery
case sddUsersFirstBuy
case simpleBuyKYCIncomplete
case transferBitcoin
case twoFA
case verifyEmail
case verifyIdentity
case viewNFTWaitlist
case walletConnect
var string: String {
let prefix = "announcement-"
let key: String
switch self {
case .applePay:
key = "apple-pay"
case .assetRename(let code):
key = "cache-asset-rename-\(code)"
case .backupFunds:
key = "cache-backup-funds"
case .buyBitcoin:
key = "cache-buy-btc"
case .claimFreeCryptoDomain:
key = "claim-free-crypto-domain"
case .majorProductBlocked:
key = "cache-major-product-blocked"
case .newAsset(let code):
key = "cache-new-asset-\(code)"
case .resubmitDocuments:
key = "cache-resubmit-documents"
case .resubmitDocumentsAfterRecovery:
key = "cache-resubmit-documents-after-recovery"
case .sddUsersFirstBuy:
key = "cache-sdd-users-buy"
case .simpleBuyKYCIncomplete:
key = "simple-buy-kyc-incomplete"
case .transferBitcoin:
key = "cache-transfer-btc"
case .twoFA:
key = "cache-2fa"
case .verifyEmail:
key = "cache-email-verification"
case .verifyIdentity:
key = "cache-identity-verification"
case .viewNFTWaitlist:
key = "view-nft-waitlist"
case .walletConnect:
key = "wallet-connect"
}
return prefix + key
}
}
}
|
lgpl-3.0
|
807d9fd099508566ebf88d8d617949b4
| 31.30137 | 63 | 0.54877 | 4.892116 | false | false | false | false |
pdcgomes/RendezVous
|
RendezVous/ChangeReportStandardOutputRenderer.swift
|
1
|
6298
|
//
// StandardOutputChangeReportRenderer.swift
// RendezVous
//
// Created by Pedro Gomes on 15/09/2015.
// Copyright © 2015 Pedro Gomes. All rights reserved.
//
import Foundation
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public enum ChangeReportOutputStyle {
case Default;
case Colorized;
}
typealias ColorizeFunction = (String, AnsiColorCode, AnsiColorCode -> String)
typealias Color = ColorizeFunction -> ColorizeFunction
//func colorize(string: String, foreground: AnsiColorCode = .Default, background: AnsiColorCode = .Default) -> ColorizeFunction {
// return {
// a: string, f: foreground,
// b: background in {
// string.colorize(foreground, background: background, mode: .Default)
// }
// }
//
//// return func(string: String, foreground: AnsiColorCode = .Default, background: AnsiColorCode = .Default) -> String {
//// return string.colorize(foreground, background: background, mode: .Default)
//// }
//}
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
struct ChangeReportStandardOutputRenderer : ChangeReportRenderer {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
func render(changes: [String : [Change]], errors: [String: ErrorType]? = nil, groupBy: ChangeReportGroupingStyle = .NoGrouping) {
render(changes, errors: errors, groupBy: groupBy, style: .Default)
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
func render(changes: [String : [Change]], errors: [String: ErrorType]? = nil, groupBy: ChangeReportGroupingStyle = .NoGrouping, style: ChangeReportOutputStyle) {
var renderFunction: ([String: [Change]] -> Void)
switch (groupBy, style) {
case (.NoGrouping, .Default): renderFunction = renderNoGrouping
case (.NoGrouping, .Colorized): renderFunction = renderNoGroupingColorized
case (.GroupByChangeType, .Default): renderFunction = renderGroupByChangeType
case (.GroupByChangeType, .Colorized): renderFunction = renderGroupByChangeTypeColorized
}
renderFunction(changes)
if errors != nil {
renderErrors(errors!)
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
private func renderErrors(errors: [String: ErrorType]) {
for (file, error) in errors {
print("--> error: \(file), \(error)")
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
private func renderNoGrouping(changes: [String: [Change]]) {
for (file, changeList) in changes {
print("--> updated \(file) ...")
for change in changeList {
print(" --> \(change.type): \(change.key)")
}
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
private func renderNoGroupingColorized(changes: [String: [Change]]) {
for (file, changeList) in changes {
print("--> updated " + file.green.bold + " ...")
for change in changeList {
print(" --> " + "\(change.type)".white.bold + ": " + change.key.green.bold)
}
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
private func renderGroupByChangeType(changes: [String: [Change]]) {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
func extractChangesByType(type: Change.ChangeType, changeList: [Change]) -> [Change] {
return changeList.filter { $0.type == type }
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
func reportChanges(kind: String, changeList: [Change]) {
guard changeList.count > 0 else { return }
print(" --> \(kind):")
for change in changeList {
print(" --> \(change.type): \(change.key)")
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
for (file, changeList) in changes {
let createdList = extractChangesByType(.Created, changeList: changeList)
let deletedList = extractChangesByType(.Deleted, changeList: changeList)
let updatedList = extractChangesByType(.Changed, changeList: changeList)
let changeCount = (createdList.count + deletedList.count + updatedList.count)
guard changeCount > 0 else { continue }
print("--> updated \(file) ...")
reportChanges("created", changeList: createdList)
reportChanges("updated", changeList: updatedList)
reportChanges("deleted", changeList: deletedList)
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
private func renderGroupByChangeTypeColorized(changes: [String: [Change]]) {
}
}
|
mit
|
e5bc8d32dd192404076e1a939e9b21bf
| 43.034965 | 165 | 0.395268 | 6.412424 | false | false | false | false |
megavolt605/CNLUIKitTools
|
CNLUIKitTools/CNLUIT+UINavigationBar.swift
|
1
|
1056
|
//
// CNLUIT+UINavigationBar.swift
// CNLUIKitTools
//
// Created by Igor Smirnov on 11/11/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import UIKit
public extension UINavigationBar {
public func hideBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(self)
navigationBarImageView!.isHidden = true
}
public func showBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(self)
navigationBarImageView!.isHidden = false
}
fileprivate func hairlineImageViewInNavigationBar(_ view: UIView) -> UIImageView? {
if view.isKind(of: UIImageView.self) && view.bounds.height <= 1.0 {
return view as? UIImageView
}
let subviews = (view.subviews as [UIView])
for subview: UIView in subviews {
if let imageView = hairlineImageViewInNavigationBar(subview) {
return imageView
}
}
return nil
}
}
|
mit
|
0d084d2a9ae86a5638b05f02873efd24
| 26.763158 | 87 | 0.637915 | 5.02381 | false | false | false | false |
xxxAIRINxxx/Cmg
|
Sources/ColorEffect.swift
|
1
|
8539
|
//
// ColorEffect.swift
// Cmg
//
// Created by xxxAIRINxxx on 2016/02/20.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
public struct ColorCrossPolynomial: Filterable, FilterInputCollectionType,
InputRedCoefficientsAvailable, InputGreenCoefficientsAvailable, InputBlueCoefficientsAvailable {
public let filter: CIFilter = CIFilter(name: "CIColorCrossPolynomial")!
public let inputRedCoefficients: VectorInput
public let inputGreenCoefficients: VectorInput
public let inputBlueCoefficients: VectorInput
public init() {
self.inputRedCoefficients = VectorInput(.other(count: 10), self.filter, "inputRedCoefficients")
self.inputGreenCoefficients = VectorInput(.other(count: 10), self.filter, "inputGreenCoefficients")
self.inputBlueCoefficients = VectorInput(.other(count: 10), self.filter, "inputBlueCoefficients")
}
public func inputs() -> [FilterInputable] {
return [
self.inputRedCoefficients,
self.inputGreenCoefficients,
self.inputBlueCoefficients
]
}
}
public struct ColorCube: Filterable, InputCubeDimensionAvailable {
public let filter: CIFilter = CIFilter(name: "CIColorCube")!
public let inputCubeDimension: ScalarInput
public var cubeData: Data
public init(inputCubeData: Data) {
self.inputCubeDimension = ScalarInput(filter: self.filter, key: "inputCubeDimension")
self.cubeData = inputCubeData
}
public func sliders() -> [Slider] {
return self.inputCubeDimension.sliders()
}
public func setupFilter() {
self.inputCubeDimension.setInput(self.filter)
self.filter.setValue(self.cubeData, forKey: "inputCubeData")
}
}
public struct ColorCubeWithColorSpace: Filterable, InputCubeDimensionAvailable {
public let filter: CIFilter = CIFilter(name: "CIColorCubeWithColorSpace")!
public let inputCubeDimension: ScalarInput
public var cubeData: Data
public var colorSpace: CGColorSpace
public init(inputCubeData: Data, inputColorSpace: CGColorSpace) {
self.inputCubeDimension = ScalarInput(filter: self.filter, key: "inputCubeDimension")
self.cubeData = inputCubeData
self.colorSpace = inputColorSpace
}
public func sliders() -> [Slider] {
return self.inputCubeDimension.sliders()
}
public func setupFilter() {
self.inputCubeDimension.setInput(self.filter)
self.filter.setValue(self.cubeData, forKey: "inputCubeData")
self.filter.setValue(self.colorSpace, forKey: "inputColorSpace")
}
}
public struct ColorInvert: Filterable {
public let filter: CIFilter = CIFilter(name: "CIColorInvert")!
public init() {}
}
public struct ColorMap: Filterable, FilterInputCollectionType,
InputImageAvailable {
public let filter: CIFilter = CIFilter(name: "CIColorMap")!
public let inputImage: ImageInput
public init(uiImage: UIImage) {
self.inputImage = ImageInput(image: CIImage(cgImage: uiImage.cgImage!), key: "inputGradientImage")
}
public init(ciImage: CIImage) {
self.inputImage = ImageInput(image: ciImage, key: "inputGradientImage")
}
public func inputs() -> [FilterInputable] {
return [
self.inputImage
]
}
}
public struct ColorMonochrome: Filterable, FilterInputCollectionType,
InputIntensityAvailable, InputColorAvailable {
public let filter: CIFilter = CIFilter(name: "CIColorMonochrome")!
public let inputIntensity: ScalarInput
public let inputColor: ColorInput
public init() {
self.inputIntensity = ScalarInput(filter: self.filter, key: kCIInputIntensityKey)
self.inputColor = ColorInput(filter: self.filter, key: kCIInputColorKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputIntensity,
self.inputColor
]
}
}
public struct ColorPosterize: Filterable, FilterInputCollectionType,
InputLevelsAvailable {
public let filter: CIFilter = CIFilter(name: "CIColorPosterize")!
public let inputLevels: ScalarInput
public init() {
self.inputLevels = ScalarInput(filter: self.filter, key: "inputLevels")
}
public func inputs() -> [FilterInputable] {
return [
self.inputLevels
]
}
}
public struct FalseColor: Filterable, FilterInputCollectionType,
InputColor0Available, InputColor1Available {
public let filter: CIFilter = CIFilter(name: "CIFalseColor")!
public let inputColor0: ColorInput
public let inputColor1: ColorInput
public init() {
self.inputColor0 = ColorInput(filter: self.filter, key: "inputColor0")
self.inputColor1 = ColorInput(filter: self.filter, key: "inputColor1")
}
public func inputs() -> [FilterInputable] {
return [
self.inputColor0,
self.inputColor1
]
}
}
public struct MaskToAlpha: Filterable {
public let filter: CIFilter = CIFilter(name: "CIMaskToAlpha")!
public init() {}
}
public struct MaximumComponent: Filterable {
public let filter: CIFilter = CIFilter(name: "CIMaximumComponent")!
public init() {}
}
public struct MinimumComponent: Filterable {
public let filter: CIFilter = CIFilter(name: "CIMinimumComponent")!
public init() {}
}
public struct PhotoEffectChrome: Filterable {
public let filter: CIFilter = CIFilter(name: "CIPhotoEffectChrome")!
public init() {}
}
public struct PhotoEffectFade: Filterable {
public let filter: CIFilter = CIFilter(name: "CIPhotoEffectFade")!
public init() {}
}
public struct PhotoEffectInstant: Filterable {
public let filter: CIFilter = CIFilter(name: "CIPhotoEffectInstant")!
public init() {}
}
public struct PhotoEffectMono: Filterable {
public let filter: CIFilter = CIFilter(name: "CIPhotoEffectMono")!
public init() {}
}
public struct PhotoEffectNoir: Filterable {
public let filter: CIFilter = CIFilter(name: "CIPhotoEffectNoir")!
public init() {}
}
public struct PhotoEffectProcess: Filterable {
public let filter: CIFilter = CIFilter(name: "CIPhotoEffectProcess")!
public init() {}
}
public struct PhotoEffectTonal: Filterable {
public let filter: CIFilter = CIFilter(name: "CIPhotoEffectTonal")!
public init() {}
}
public struct PhotoEffectTransfer: Filterable {
public let filter: CIFilter = CIFilter(name: "CIPhotoEffectTransfer")!
public init() {}
}
public struct SepiaTone: Filterable, FilterInputCollectionType,
InputIntensityAvailable {
public let filter: CIFilter = CIFilter(name: "CISepiaTone")!
public let inputIntensity: ScalarInput
public init() {
self.inputIntensity = ScalarInput(filter: self.filter, key: kCIInputIntensityKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputIntensity
]
}
}
public struct Vignette: Filterable, FilterInputCollectionType,
InputRadiusAvailable, InputIntensityAvailable {
public let filter: CIFilter = CIFilter(name: "CIVignette")!
public let inputRadius: ScalarInput
public let inputIntensity: ScalarInput
public init() {
self.inputRadius = ScalarInput(filter: self.filter, key: kCIInputRadiusKey)
self.inputIntensity = ScalarInput(filter: self.filter, key: kCIInputIntensityKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputRadius,
self.inputIntensity
]
}
}
public struct VignetteEffect: Filterable, FilterInputCollectionType,
InputIntensityAvailable, InputCenterAvailable {
public let filter: CIFilter = CIFilter(name: "CIVignetteEffect")!
public let inputIntensity: ScalarInput
public let inputCenter: VectorInput
public init(imageSize: CGSize) {
self.inputIntensity = ScalarInput(filter: self.filter, key: kCIInputIntensityKey)
self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputIntensity,
self.inputCenter
]
}
}
|
mit
|
235853edc5f7fde29d46354d2834c404
| 26.720779 | 120 | 0.675568 | 4.785874 | false | false | false | false |
enabledhq/Selfie-Bot
|
Selfie-Bot/Views/Decorative/GradientView.swift
|
1
|
881
|
//
// GradientView.swift
// BrewArt
//
// Created by Simeon on 25/02/2015.
// Copyright (c) 2015 Enabled. All rights reserved.
//
import UIKit
class GradientView: UIView
{
init(gradient: PXPGradientColor, frame: CGRect)
{
self.gradient = gradient
super.init(frame: frame)
isUserInteractionEnabled = false
backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
var gradient: PXPGradientColor? {
didSet {
setNeedsDisplay()
}
}
var angle: Double = 0.0 {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect)
{
if let gradient = gradient
{
gradient.draw(inRect: rect, angle: angle)
}
}
}
|
mit
|
f00daf61269df5b20375ef8a192ad2af
| 17.354167 | 59 | 0.549376 | 4.318627 | false | false | false | false |
ivlevAstef/DITranquillity
|
Tests/DITranquillityTest/DITranquillityTests_Extensions.swift
|
1
|
4804
|
//
// DITranquillityTests_Extensions.swift
// DITranquillity
//
// Created by Alexander Ivlev on 17/08/2018.
// Copyright © 2018 Alexander Ivlev. All rights reserved.
//
import XCTest
import DITranquillity
private protocol Tag { }
private protocol MyProtocol {
func empty()
}
private class Class: MyProtocol
{
let p1: Int
let p2: String
let p3: Double
var p4: [Int] = []
var p5: [String] = []
internal init(p1: Int, p2: String, p3: Double) {
self.p1 = p1
self.p2 = p2
self.p3 = p3
}
func empty() { }
}
private class DepthClass: MyProtocol
{
let c: Class
internal init(c: Class) {
self.c = c
}
func empty() { }
}
private class OptionalClass: MyProtocol
{
let p1: Int?
let p2: String?
let p3: Double?
internal init(p1: Int?, p2: String?, p3: Double?) {
self.p1 = p1
self.p2 = p2
self.p3 = p3
}
func empty() { }
}
class DITranquillityTests_Extensions: XCTestCase {
func test01_Arguments() {
let container = DIContainer()
container.register{ "injection" as String }
container.register{ Class(p1: arg($0), p2: $1, p3: arg($2)) }
.injection{ $0.p4 = arg($1) }
.injection(\.p5) { arg($0) }
let obj: Class = container.resolve(args: 111, 22.2, [1,2,3,4,5], ["H","e","l","l","o"])
XCTAssertEqual(obj.p1, 111)
XCTAssertEqual(obj.p2, "injection")
XCTAssertEqual(obj.p3, 22.2)
XCTAssertEqual(obj.p4.count, 5)
XCTAssertEqual(obj.p5.joined(), "Hello")
}
func test02_DepthArguments() {
let container = DIContainer()
container.register{ 111 as Int }
container.register{ Class(p1: $0, p2: arg($1), p3: arg($2)) }
.injection{ $0.p4 = arg($1) }
.injection(\.p5) { arg($0) }
container.register(DepthClass.init)
let obj: DepthClass = container.resolve(
arguments: AnyArguments(for: Class.self, args: "injection", 22.2, [1,2,3,4,5], ["H","e","l","l","o"]))
XCTAssertEqual(obj.c.p1, 111)
XCTAssertEqual(obj.c.p2, "injection")
XCTAssertEqual(obj.c.p3, 22.2)
XCTAssertEqual(obj.c.p4.count, 5)
XCTAssertEqual(obj.c.p5.joined(), "Hello")
}
func test03_OptionalArguments() {
let container = DIContainer()
container.register{ OptionalClass(p1: arg($0), p2: $1, p3: arg($2)) }
let obj: OptionalClass = container.resolve(args: nil, 22.2)
XCTAssertNil(obj.p1)
XCTAssertNil(obj.p2)
XCTAssertEqual(obj.p3, 22.2)
}
func test04_NotSetOptionalArguments() {
let container = DIContainer()
container.register{ OptionalClass(p1: arg($0), p2: $1, p3: arg($2)) }
let obj: OptionalClass = *container
XCTAssertNil(obj.p1)
XCTAssertNil(obj.p2)
XCTAssertNil(obj.p3)
}
func test05_ProtocolArguments() {
let container = DIContainer()
container.register{ Class(p1: arg($0), p2: arg($1), p3: arg($2)) }
.as(MyProtocol.self)
var arguments = AnyArguments()
arguments.addArgs(for: MyProtocol.self, args: 11, "test", 15.0)
let obj: Class = container.resolve(arguments: arguments)
XCTAssertEqual(obj.p1, 11)
XCTAssertEqual(obj.p2, "test")
XCTAssertEqual(obj.p3, 15.0)
}
func test06_OptionalClass() {
let container = DIContainer()
container.register{ OptionalClass(p1: arg($0), p2: $1, p3: arg($2)) }
let obj: OptionalClass? = container.resolve(args: nil, 22.2)
XCTAssertNil(obj?.p1)
XCTAssertNil(obj?.p2)
XCTAssertEqual(obj?.p3, 22.2)
}
func test06_ManyClass() {
let container = DIContainer()
container.register{ OptionalClass(p1: arg($0), p2: $1, p3: arg($2)) }
let obj: [OptionalClass] = many(container.resolve(args: nil, 22.2))
XCTAssertEqual(obj.count, 1)
XCTAssertNil(obj.first?.p1)
XCTAssertNil(obj.first?.p2)
XCTAssertEqual(obj.first?.p3, 22.2)
}
func test06_TagClass() {
let container = DIContainer()
container.register{ Class(p1: arg($0), p2: arg($1), p3: arg($2)) }
.as(MyProtocol.self, tag: Tag.self)
var arguments = AnyArguments()
arguments.addArgs(for: MyProtocol.self, args: 11, "test", 15.0)
let obj: MyProtocol? = by(tag: Tag.self, on: container.resolve(arguments: arguments))
XCTAssertEqual((obj as? Class)?.p1, 11)
XCTAssertEqual((obj as? Class)?.p2, "test")
XCTAssertEqual((obj as? Class)?.p3, 15.0)
}
func test06_NameClass() {
let container = DIContainer()
container.register{ Class(p1: arg($0), p2: arg($1), p3: arg($2)) }
.as(MyProtocol.self, name: "name")
var arguments = AnyArguments()
arguments.addArgs(for: MyProtocol.self, args: 11, "test", 15.0)
let obj: MyProtocol? = container.resolve(name: "name", arguments: arguments)
XCTAssertEqual((obj as? Class)?.p1, 11)
XCTAssertEqual((obj as? Class)?.p2, "test")
XCTAssertEqual((obj as? Class)?.p3, 15.0)
}
}
|
mit
|
2672ea75a98dac55b1c8f086724007a4
| 23.505102 | 108 | 0.634187 | 3.106727 | false | true | false | false |
wrutkowski/Lucid-Weather-Clock
|
Pods/Charts/Charts/Classes/Data/Implementations/Standard/LineChartDataSet.swift
|
6
|
5475
|
//
// LineChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// 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
open class LineChartDataSet: LineRadarChartDataSet, ILineChartDataSet
{
@objc(LineChartMode)
public enum Mode: Int
{
case linear
case stepped
case cubicBezier
case horizontalBezier
}
private func initialize()
{
// default color
circleColors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
}
public required init()
{
super.init()
initialize()
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
initialize()
}
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// The drawing mode for this line dataset
///
/// **default**: Linear
open var mode: Mode = Mode.linear
private var _cubicIntensity = CGFloat(0.2)
/// Intensity for cubic lines (min = 0.05, max = 1)
///
/// **default**: 0.2
open var cubicIntensity: CGFloat
{
get
{
return _cubicIntensity
}
set
{
_cubicIntensity = newValue
if (_cubicIntensity > 1.0)
{
_cubicIntensity = 1.0
}
if (_cubicIntensity < 0.05)
{
_cubicIntensity = 0.05
}
}
}
@available(*, deprecated:1.0, message:"Use `mode` instead.")
open var drawCubicEnabled: Bool
{
get
{
return mode == .cubicBezier
}
set
{
mode = newValue ? LineChartDataSet.Mode.cubicBezier : LineChartDataSet.Mode.linear
}
}
@available(*, deprecated:1.0, message:"Use `mode` instead.")
open var drawSteppedEnabled: Bool
{
get
{
return mode == .stepped
}
set
{
mode = newValue ? LineChartDataSet.Mode.stepped : LineChartDataSet.Mode.linear
}
}
/// The radius of the drawn circles.
open var circleRadius = CGFloat(8.0)
/// The hole radius of the drawn circles
open var circleHoleRadius = CGFloat(4.0)
open var circleColors = [NSUIColor]()
/// - returns: the color at the given index of the DataSet's circle-color array.
/// Performs a IndexOutOfBounds check by modulus.
open func getCircleColor(_ index: Int) -> NSUIColor?
{
let size = circleColors.count
let index = index % size
if (index >= size)
{
return nil
}
return circleColors[index]
}
/// Sets the one and ONLY color that should be used for this DataSet.
/// Internally, this recreates the colors array and adds the specified color.
open func setCircleColor(_ color: NSUIColor)
{
circleColors.removeAll(keepingCapacity: false)
circleColors.append(color)
}
/// Resets the circle-colors array and creates a new one
open func resetCircleColors(_ index: Int)
{
circleColors.removeAll(keepingCapacity: false)
}
/// If true, drawing circles is enabled
open var drawCirclesEnabled = true
/// The color of the inner circle (the circle-hole).
open var circleHoleColor: NSUIColor? = NSUIColor.white
/// True if drawing circles for this DataSet is enabled, false if not
open var drawCircleHoleEnabled = true
/// This is how much (in pixels) into the dash pattern are we starting from.
open var lineDashPhase = CGFloat(0.0)
/// This is the actual dash pattern.
/// I.e. [2, 3] will paint [-- -- ]
/// [1, 3, 4, 2] will paint [- ---- - ---- ]
open var lineDashLengths: [CGFloat]?
/// Line cap type, default is CGLineCap.Butt
open var lineCapType = CGLineCap.butt
/// formatter for customizing the position of the fill-line
private var _fillFormatter: ChartFillFormatter = ChartDefaultFillFormatter()
/// Sets a custom FillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic.
open var fillFormatter: ChartFillFormatter?
{
get
{
return _fillFormatter
}
set
{
if newValue == nil
{
_fillFormatter = ChartDefaultFillFormatter()
}
else
{
_fillFormatter = newValue!
}
}
}
// MARK: NSCopying
open override func copyWithZone(_ zone: NSZone?) -> Any
{
let copy = super.copyWithZone(zone) as! LineChartDataSet
copy.circleColors = circleColors
copy.circleRadius = circleRadius
copy.cubicIntensity = cubicIntensity
copy.lineDashPhase = lineDashPhase
copy.lineDashLengths = lineDashLengths
copy.lineCapType = lineCapType
copy.drawCirclesEnabled = drawCirclesEnabled
copy.drawCircleHoleEnabled = drawCircleHoleEnabled
copy.mode = mode
return copy
}
}
|
mit
|
79e38d64317a1b6dec4a67e5ad845cf5
| 26.238806 | 154 | 0.581187 | 4.888393 | false | false | false | false |
jdommes/inquire
|
Sources/Validation.swift
|
2
|
1774
|
//
// Validation.swift
// Inquire
//
// Created by Wesley Cope on 1/14/16.
// Copyright © 2016 Wess Cope. All rights reserved.
//
import Foundation
/// ValidationBlock: Block used to validate string values.
public typealias ValidationBlock = (AnyObject) -> Bool
/**
# Valdation
Class used for loading and executing validations for form field values.
*/
open class Validation {
fileprivate func validateWithPattern(_ value:String, pattern:String) -> Bool {
if value.characters.count < 0 {
return false
}
do {
let regex = try NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
let matches = regex.matches(in: value, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, value.characters.count))
return matches.count > 0 ? true : false
}
catch {
print("Invalid pattern: \(pattern)")
return false
}
}
/**
## Validate
Takes a value and a rule to use to validate the value and return if it's valid or note.
- returns: Bool
- Parameter value:String
- Parameter rule:ValidationRule
*/
open func validate(_ value:String?, rule:ValidationRule) -> Bool {
var isValid = true
guard let text = value else {
return false
}
if let block = rule.block {
isValid = block(text as AnyObject)
}
if let pattern = rule.pattern {
isValid = validateWithPattern(text, pattern: pattern)
}
return isValid
}
}
/// Global validator to use with fields who have no forms.
internal let GlobalValidation:Validation = Validation()
|
mit
|
f5e089d5ecff22847d3ca897377a7c60
| 26.703125 | 156 | 0.605753 | 4.753351 | false | false | false | false |
elliottminns/blackfire
|
Sources/Blackfire/HttpStatus.swift
|
2
|
2409
|
import Foundation
enum HTTPStatus {
case `continue`
case ok
case created
case accepted
case nonAuthoritativeInformation
case noContent
case resetContent
case partialContent
case movedPermanently
case found
case badRequest
case unauthorized
case paymentRequired
case forbidden
case notFound
case internalServerError
case notImplemented
case badGateway
case serviceUnavailable
case gatewayTimeout
case unknown(Int)
}
fileprivate let map: [Int: HTTPStatus] = [
100: .continue,
200: .ok, 201: .created, 202: .accepted, 203: .nonAuthoritativeInformation,
204: .noContent, 205: .resetContent, 206: .partialContent,
301: .movedPermanently, 302: .found,
400: .badRequest, 401: .unauthorized, 402: .paymentRequired,
403: .forbidden, 404: .notFound,
500: .internalServerError, 501: .notImplemented, 502: .badGateway,
503: .serviceUnavailable, 504: .gatewayTimeout
]
extension HTTPStatus {
init(status: Int) {
self = map[status] ?? .unknown(status)
}
var stringValue: String {
let value: String
switch self {
case .ok: value = "200 OK"
case .`continue`: value = "100 Continue"
case .created: value = "201 Created"
case .accepted: value = "202 Accepted"
case .nonAuthoritativeInformation: value = "203 Non Authoritative Information"
case .noContent: value = "204 No Content"
case .resetContent: value = "205 Reset Content"
case .partialContent: value = "206 Partial Content"
case .movedPermanently: value = "301 Moved Permanently"
case .found: value = "302 Found"
case .badRequest: value = "400 Bad Request"
case .unauthorized: value = "401 Unauthorized"
case .paymentRequired: value = "402 Payment Required"
case .forbidden: value = "403 Forbidden"
case .notFound: value = "404 Not Found"
case .internalServerError: value = "500 Internal Server Error"
case .notImplemented: value = "501 Not Implemented"
case .badGateway: value = "502 Bad Gateway"
case .serviceUnavailable: value = "503 Service Unavailable"
case .gatewayTimeout: value = "504 Gateway Timeout"
case .unknown(let status): value = "\(status)"
}
return value
}
}
|
apache-2.0
|
8f7c98bfcd66ad1296d7f408b79aa79f
| 30.285714 | 86 | 0.64176 | 4.511236 | false | false | false | false |
luowei/PaintCodeSamples
|
ButtonView/ButtonView/MyStyleKit.swift
|
1
|
16535
|
//
// MyStyleKit.swift
// ButtonView
//
// Created by luowei on 2016/10/17.
// Copyright (c) 2016 wodedata. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import UIKit
public class MyStyleKit : NSObject {
//// Cache
private struct Cache {
static let normalColor: UIColor = UIColor(red: 0.023, green: 0.648, blue: 0.023, alpha: 1.000)
}
//// Colors
public class var normalColor: UIColor { return Cache.normalColor }
//// Drawing Methods
public class func drawMyCustomButton(frame: CGRect = CGRect(x: 11, y: 8, width: 113, height: 52), btnText: String = "确 定", presse: Bool = true) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Color Declarations
let normalFillColor = MyStyleKit.normalColor.colorWithHue(0.2)
let normalInnerColor = MyStyleKit.normalColor.colorWithBrightness(0.4)
let pressedColor = MyStyleKit.normalColor.colorWithHue(0.1)
let pressedFillColor = MyStyleKit.normalColor.colorWithSaturation(0.2)
let pressedInnerColor = MyStyleKit.normalColor.colorWithBrightness(0.3)
//// Subframes
let normal: CGRect = CGRect(x: frame.minX + 8, y: frame.minY + 7, width: frame.width - 16, height: frame.height - 13)
let pressed: CGRect = CGRect(x: frame.minX + 8, y: frame.minY + 7, width: frame.width - 16, height: frame.height - 13)
//// Normal
//// Normal Rectangle Drawing
let normalRectanglePath = UIBezierPath(roundedRect: CGRect(x: normal.minX + floor(normal.width * 0.00000 + 0.5), y: normal.minY + floor(normal.height * 0.00000 + 0.5), width: floor(normal.width * 1.00000 + 0.5) - floor(normal.width * 0.00000 + 0.5), height: floor(normal.height * 1.00000 + 0.5) - floor(normal.height * 0.00000 + 0.5)), cornerRadius: 5)
normalFillColor.setFill()
normalRectanglePath.fill()
MyStyleKit.normalColor.setStroke()
normalRectanglePath.lineWidth = 2
normalRectanglePath.stroke()
//// Normal Oval Drawing
let normalOvalPath = UIBezierPath(ovalInRect: CGRect(x: normal.minX + floor(normal.width * 0.03093 + 0.5), y: normal.minY + floor(normal.height * 0.11538) + 0.5, width: floor(normal.width * 0.26804 + 0.5) - floor(normal.width * 0.03093 + 0.5), height: floor(normal.height * 0.88462) - floor(normal.height * 0.11538)))
normalInnerColor.setStroke()
normalOvalPath.lineWidth = 2
normalOvalPath.stroke()
//// Normal Star Drawing
let normalStarPath = UIBezierPath()
normalStarPath.moveToPoint(CGPoint(x: normal.minX + 0.15212 * normal.width, y: normal.minY + 0.19223 * normal.height))
normalStarPath.addLineToPoint(CGPoint(x: normal.minX + 0.17224 * normal.width, y: normal.minY + 0.40288 * normal.height))
normalStarPath.addLineToPoint(CGPoint(x: normal.minX + 0.23582 * normal.width, y: normal.minY + 0.40497 * normal.height))
normalStarPath.addLineToPoint(CGPoint(x: normal.minX + 0.18733 * normal.width, y: normal.minY + 0.54872 * normal.height))
normalStarPath.addLineToPoint(CGPoint(x: normal.minX + 0.20385 * normal.width, y: normal.minY + 0.74918 * normal.height))
normalStarPath.addLineToPoint(CGPoint(x: normal.minX + 0.15715 * normal.width, y: normal.minY + 0.64594 * normal.height))
normalStarPath.addLineToPoint(CGPoint(x: normal.minX + 0.10184 * normal.width, y: normal.minY + 0.75936 * normal.height))
normalStarPath.addLineToPoint(CGPoint(x: normal.minX + 0.11692 * normal.width, y: normal.minY + 0.54872 * normal.height))
normalStarPath.addLineToPoint(CGPoint(x: normal.minX + 0.06843 * normal.width, y: normal.minY + 0.40497 * normal.height))
normalStarPath.addLineToPoint(CGPoint(x: normal.minX + 0.13201 * normal.width, y: normal.minY + 0.40288 * normal.height))
normalStarPath.addLineToPoint(CGPoint(x: normal.minX + 0.15212 * normal.width, y: normal.minY + 0.19223 * normal.height))
normalStarPath.closePath()
normalInnerColor.setStroke()
normalStarPath.lineWidth = 1
normalStarPath.stroke()
//// Normal Text Drawing
let normalTextRect = CGRect(x: normal.minX + floor(normal.width * 0.29897 + 0.5), y: normal.minY + floor(normal.height * 0.25641 + 0.5), width: floor(normal.width * 0.96907 + 0.5) - floor(normal.width * 0.29897 + 0.5), height: floor(normal.height * 0.76923 + 0.5) - floor(normal.height * 0.25641 + 0.5))
let normalTextStyle = NSMutableParagraphStyle()
normalTextStyle.alignment = .Center
let normalTextFontAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(UIFont.labelFontSize()), NSForegroundColorAttributeName: normalInnerColor, NSParagraphStyleAttributeName: normalTextStyle]
let normalTextTextHeight: CGFloat = NSString(string: btnText).boundingRectWithSize(CGSize(width: normalTextRect.width, height: CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: normalTextFontAttributes, context: nil).size.height
CGContextSaveGState(context!)
CGContextClipToRect(context!, normalTextRect)
NSString(string: btnText).drawInRect(CGRect(x: normalTextRect.minX, y: normalTextRect.minY + (normalTextRect.height - normalTextTextHeight) / 2, width: normalTextRect.width, height: normalTextTextHeight), withAttributes: normalTextFontAttributes)
CGContextRestoreGState(context!)
//// Pressed
if (presse) {
//// Pressed Rectangle Drawing
let pressedRectanglePath = UIBezierPath(roundedRect: CGRect(x: pressed.minX + floor(pressed.width * 0.00000 + 0.5), y: pressed.minY + floor(pressed.height * 0.00000 + 0.5), width: floor(pressed.width * 1.00000 + 0.5) - floor(pressed.width * 0.00000 + 0.5), height: floor(pressed.height * 1.00000 + 0.5) - floor(pressed.height * 0.00000 + 0.5)), cornerRadius: 5)
pressedFillColor.setFill()
pressedRectanglePath.fill()
pressedColor.setStroke()
pressedRectanglePath.lineWidth = 2
pressedRectanglePath.stroke()
//// Pressed Oval Drawing
let pressedOvalPath = UIBezierPath(ovalInRect: CGRect(x: pressed.minX + floor(pressed.width * 0.03093 + 0.5), y: pressed.minY + floor(pressed.height * 0.11538) + 0.5, width: floor(pressed.width * 0.26804 + 0.5) - floor(pressed.width * 0.03093 + 0.5), height: floor(pressed.height * 0.88462) - floor(pressed.height * 0.11538)))
pressedInnerColor.setStroke()
pressedOvalPath.lineWidth = 2
pressedOvalPath.stroke()
//// Pressed Star Drawing
let pressedStarPath = UIBezierPath()
pressedStarPath.moveToPoint(CGPoint(x: pressed.minX + 0.15212 * pressed.width, y: pressed.minY + 0.19223 * pressed.height))
pressedStarPath.addLineToPoint(CGPoint(x: pressed.minX + 0.17224 * pressed.width, y: pressed.minY + 0.40288 * pressed.height))
pressedStarPath.addLineToPoint(CGPoint(x: pressed.minX + 0.23582 * pressed.width, y: pressed.minY + 0.40497 * pressed.height))
pressedStarPath.addLineToPoint(CGPoint(x: pressed.minX + 0.18733 * pressed.width, y: pressed.minY + 0.54872 * pressed.height))
pressedStarPath.addLineToPoint(CGPoint(x: pressed.minX + 0.20385 * pressed.width, y: pressed.minY + 0.74918 * pressed.height))
pressedStarPath.addLineToPoint(CGPoint(x: pressed.minX + 0.15715 * pressed.width, y: pressed.minY + 0.64594 * pressed.height))
pressedStarPath.addLineToPoint(CGPoint(x: pressed.minX + 0.10184 * pressed.width, y: pressed.minY + 0.75936 * pressed.height))
pressedStarPath.addLineToPoint(CGPoint(x: pressed.minX + 0.11692 * pressed.width, y: pressed.minY + 0.54872 * pressed.height))
pressedStarPath.addLineToPoint(CGPoint(x: pressed.minX + 0.06843 * pressed.width, y: pressed.minY + 0.40497 * pressed.height))
pressedStarPath.addLineToPoint(CGPoint(x: pressed.minX + 0.13201 * pressed.width, y: pressed.minY + 0.40288 * pressed.height))
pressedStarPath.addLineToPoint(CGPoint(x: pressed.minX + 0.15212 * pressed.width, y: pressed.minY + 0.19223 * pressed.height))
pressedStarPath.closePath()
pressedInnerColor.setStroke()
pressedStarPath.lineWidth = 1
pressedStarPath.stroke()
//// Pressed Text Drawing
let pressedTextRect = CGRect(x: pressed.minX + floor(pressed.width * 0.29897 + 0.5), y: pressed.minY + floor(pressed.height * 0.25641 + 0.5), width: floor(pressed.width * 0.96907 + 0.5) - floor(pressed.width * 0.29897 + 0.5), height: floor(pressed.height * 0.76923 + 0.5) - floor(pressed.height * 0.25641 + 0.5))
let pressedTextStyle = NSMutableParagraphStyle()
pressedTextStyle.alignment = .Center
let pressedTextFontAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(UIFont.labelFontSize()), NSForegroundColorAttributeName: pressedInnerColor, NSParagraphStyleAttributeName: pressedTextStyle]
let pressedTextTextHeight: CGFloat = NSString(string: btnText).boundingRectWithSize(CGSize(width: pressedTextRect.width, height: CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: pressedTextFontAttributes, context: nil).size.height
CGContextSaveGState(context!)
CGContextClipToRect(context!, pressedTextRect)
NSString(string: btnText).drawInRect(CGRect(x: pressedTextRect.minX, y: pressedTextRect.minY + (pressedTextRect.height - pressedTextTextHeight) / 2, width: pressedTextRect.width, height: pressedTextTextHeight), withAttributes: pressedTextFontAttributes)
CGContextRestoreGState(context!)
}
}
public class func drawBubbleButton(frame: CGRect = CGRect(x: 14, y: 10, width: 94, height: 51)) {
//// Color Declarations
let normalFillColor = MyStyleKit.normalColor.colorWithHue(0.2)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPoint(x: frame.maxX - 11.35, y: frame.minY + 7.33))
bezierPath.addLineToPoint(CGPoint(x: frame.maxX - 11.16, y: frame.minY + 7.37))
bezierPath.addCurveToPoint(CGPoint(x: frame.maxX - 8.37, y: frame.minY + 10.16), controlPoint1: CGPoint(x: frame.maxX - 9.86, y: frame.minY + 7.85), controlPoint2: CGPoint(x: frame.maxX - 8.85, y: frame.minY + 8.86))
bezierPath.addCurveToPoint(CGPoint(x: frame.maxX - 8, y: frame.minY + 14.64), controlPoint1: CGPoint(x: frame.maxX - 8, y: frame.minY + 11.34), controlPoint2: CGPoint(x: frame.maxX - 8, y: frame.minY + 12.44))
bezierPath.addLineToPoint(CGPoint(x: frame.maxX - 8, y: frame.maxY - 21.64))
bezierPath.addCurveToPoint(CGPoint(x: frame.maxX - 8.33, y: frame.maxY - 17.35), controlPoint1: CGPoint(x: frame.maxX - 8, y: frame.maxY - 19.44), controlPoint2: CGPoint(x: frame.maxX - 8, y: frame.maxY - 18.34))
bezierPath.addLineToPoint(CGPoint(x: frame.maxX - 8.37, y: frame.maxY - 17.16))
bezierPath.addCurveToPoint(CGPoint(x: frame.maxX - 11.16, y: frame.maxY - 14.37), controlPoint1: CGPoint(x: frame.maxX - 8.85, y: frame.maxY - 15.86), controlPoint2: CGPoint(x: frame.maxX - 9.86, y: frame.maxY - 14.85))
bezierPath.addCurveToPoint(CGPoint(x: frame.maxX - 15.64, y: frame.maxY - 14), controlPoint1: CGPoint(x: frame.maxX - 12.34, y: frame.maxY - 14), controlPoint2: CGPoint(x: frame.maxX - 13.44, y: frame.maxY - 14))
bezierPath.addLineToPoint(CGPoint(x: frame.minX + 0.56900 * frame.width, y: frame.maxY - 14))
bezierPath.addCurveToPoint(CGPoint(x: frame.minX + 0.50650 * frame.width, y: frame.maxY - 7), controlPoint1: CGPoint(x: frame.minX + 0.53883 * frame.width, y: frame.maxY - 10.62), controlPoint2: CGPoint(x: frame.minX + 0.50650 * frame.width, y: frame.maxY - 7))
bezierPath.addCurveToPoint(CGPoint(x: frame.minX + 0.44400 * frame.width, y: frame.maxY - 14), controlPoint1: CGPoint(x: frame.minX + 0.50650 * frame.width, y: frame.maxY - 7), controlPoint2: CGPoint(x: frame.minX + 0.47417 * frame.width, y: frame.maxY - 10.62))
bezierPath.addLineToPoint(CGPoint(x: frame.minX + 15.64, y: frame.maxY - 14))
bezierPath.addCurveToPoint(CGPoint(x: frame.minX + 11.35, y: frame.maxY - 14.33), controlPoint1: CGPoint(x: frame.minX + 13.44, y: frame.maxY - 14), controlPoint2: CGPoint(x: frame.minX + 12.34, y: frame.maxY - 14))
bezierPath.addLineToPoint(CGPoint(x: frame.minX + 11.16, y: frame.maxY - 14.37))
bezierPath.addCurveToPoint(CGPoint(x: frame.minX + 8.37, y: frame.maxY - 17.16), controlPoint1: CGPoint(x: frame.minX + 9.86, y: frame.maxY - 14.85), controlPoint2: CGPoint(x: frame.minX + 8.85, y: frame.maxY - 15.86))
bezierPath.addCurveToPoint(CGPoint(x: frame.minX + 8, y: frame.maxY - 21.64), controlPoint1: CGPoint(x: frame.minX + 8, y: frame.maxY - 18.34), controlPoint2: CGPoint(x: frame.minX + 8, y: frame.maxY - 19.44))
bezierPath.addLineToPoint(CGPoint(x: frame.minX + 8, y: frame.minY + 14.64))
bezierPath.addCurveToPoint(CGPoint(x: frame.minX + 8.33, y: frame.minY + 10.35), controlPoint1: CGPoint(x: frame.minX + 8, y: frame.minY + 12.44), controlPoint2: CGPoint(x: frame.minX + 8, y: frame.minY + 11.34))
bezierPath.addLineToPoint(CGPoint(x: frame.minX + 8.37, y: frame.minY + 10.16))
bezierPath.addCurveToPoint(CGPoint(x: frame.minX + 11.16, y: frame.minY + 7.37), controlPoint1: CGPoint(x: frame.minX + 8.85, y: frame.minY + 8.86), controlPoint2: CGPoint(x: frame.minX + 9.86, y: frame.minY + 7.85))
bezierPath.addCurveToPoint(CGPoint(x: frame.minX + 15.64, y: frame.minY + 7), controlPoint1: CGPoint(x: frame.minX + 12.34, y: frame.minY + 7), controlPoint2: CGPoint(x: frame.minX + 13.44, y: frame.minY + 7))
bezierPath.addLineToPoint(CGPoint(x: frame.maxX - 15.64, y: frame.minY + 7))
bezierPath.addCurveToPoint(CGPoint(x: frame.maxX - 11.35, y: frame.minY + 7.33), controlPoint1: CGPoint(x: frame.maxX - 13.44, y: frame.minY + 7), controlPoint2: CGPoint(x: frame.maxX - 12.34, y: frame.minY + 7))
bezierPath.closePath()
normalFillColor.setFill()
bezierPath.fill()
MyStyleKit.normalColor.setStroke()
bezierPath.lineWidth = 2
bezierPath.stroke()
}
}
extension UIColor {
func colorWithHue(newHue: CGFloat) -> UIColor {
var saturation: CGFloat = 1.0, brightness: CGFloat = 1.0, alpha: CGFloat = 1.0
self.getHue(nil, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return UIColor(hue: newHue, saturation: saturation, brightness: brightness, alpha: alpha)
}
func colorWithSaturation(newSaturation: CGFloat) -> UIColor {
var hue: CGFloat = 1.0, brightness: CGFloat = 1.0, alpha: CGFloat = 1.0
self.getHue(&hue, saturation: nil, brightness: &brightness, alpha: &alpha)
return UIColor(hue: hue, saturation: newSaturation, brightness: brightness, alpha: alpha)
}
func colorWithBrightness(newBrightness: CGFloat) -> UIColor {
var hue: CGFloat = 1.0, saturation: CGFloat = 1.0, alpha: CGFloat = 1.0
self.getHue(&hue, saturation: &saturation, brightness: nil, alpha: &alpha)
return UIColor(hue: hue, saturation: saturation, brightness: newBrightness, alpha: alpha)
}
func colorWithAlpha(newAlpha: CGFloat) -> UIColor {
var hue: CGFloat = 1.0, saturation: CGFloat = 1.0, brightness: CGFloat = 1.0
self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: nil)
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: newAlpha)
}
func colorWithHighlight(highlight: CGFloat) -> UIColor {
var red: CGFloat = 1.0, green: CGFloat = 1.0, blue: CGFloat = 1.0, alpha: CGFloat = 1.0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return UIColor(red: red * (1-highlight) + highlight, green: green * (1-highlight) + highlight, blue: blue * (1-highlight) + highlight, alpha: alpha * (1-highlight) + highlight)
}
func colorWithShadow(shadow: CGFloat) -> UIColor {
var red: CGFloat = 1.0, green: CGFloat = 1.0, blue: CGFloat = 1.0, alpha: CGFloat = 1.0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return UIColor(red: red * (1-shadow), green: green * (1-shadow), blue: blue * (1-shadow), alpha: alpha * (1-shadow) + shadow)
}
}
|
apache-2.0
|
a195bbaec7ffa2767bcc9209fa6e38b3
| 73.130045 | 373 | 0.679027 | 3.679279 | false | false | false | false |
moonagic/MagicOcean
|
MagicOcean/ViewControllers/Droplet/DropletDetail.swift
|
1
|
7201
|
//
// DropletDetail.swift
// MagicOcean
//
// Created by Wu Hengmin on 16/6/13.
// Copyright © 2016年 Wu Hengmin. All rights reserved.
//
import UIKit
import MBProgressHUD
import SwiftyJSON
import Alamofire
@objc public protocol DropletDelegate {
func didSeleteDroplet()
}
class DropletDetail: UITableViewController {
var dropletData:DropletTemplate!
@IBOutlet weak var imageLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var memAndCPULabel: UILabel!
@IBOutlet weak var diskLabel: UILabel!
@IBOutlet weak var transferLabel: UILabel!
@IBOutlet weak var regionLabel: UILabel!
weak var delegate: DropletDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.title = dropletData.name
self.imageLabel.text = dropletData.image.distribution
// self.priceLabel.text = String(format: "$%.2f", Float(dropletData.size.price));
self.memAndCPULabel.text = "\(dropletData.size.memory)MB / \(dropletData.size.vcpus)vCPU"
self.transferLabel.text = "Transfer \(dropletData.size.transfer)TB"
self.regionLabel.text = dropletData.region.slug
self.diskLabel.text = "\(dropletData.size.disk)GB SSD"
}
@IBAction func actionPressed(sender: AnyObject) {
weak var weakSelf = self
let alertController = UIAlertController(title: "Actions", message: "Choose the action you want.", preferredStyle: .actionSheet)
// Reboot
let dateAction = UIAlertAction(title: "Reboot", style: .default) { (action:UIAlertAction!) in
print("you have pressed the Reboot button");
weakSelf!.dropletActions(type: "reboot")
}
alertController.addAction(dateAction)
// Power Off
if dropletData?.status == "off" {
let powerAction = UIAlertAction(title: "Power On", style: .destructive) { (action:UIAlertAction!) in
print("you have pressed the Power On button");
weakSelf!.dropletActions(type: "power_on")
}
alertController.addAction(powerAction)
} else if dropletData?.status == "active" {
let powerAction = UIAlertAction(title: "Power Off", style: .default) { (action:UIAlertAction!) in
print("you have pressed the Power Off button");
weakSelf!.dropletActions(type: "power_off")
}
alertController.addAction(powerAction)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction!) in
print("you have pressed the cancel button");
}
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion:nil)
}
func dropletActions(type: String) {
let Headers = [
"Content-Type": "application/json",
"Authorization": "Bearer "+Account.sharedInstance.Access_Token
]
let parameters = [
"type": type
]
let hud:MBProgressHUD = MBProgressHUD.init(view: self.view.window!)
self.view.window?.addSubview(hud)
hud.mode = MBProgressHUDMode.indeterminate
hud.show(animated: true)
hud.removeFromSuperViewOnHide = true
weak var weakSelf = self
print(BASE_URL+URL_DROPLETS+"/\(dropletData.id)/"+URL_ACTIONS)
Alamofire.request(BASE_URL+URL_DROPLETS+"/\(dropletData.id)/"+URL_ACTIONS, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: Headers).responseJSON { response in
if let _ = weakSelf {
DispatchQueue.main.async {
hud.hide(animated: true)
}
let dic = response.result.value as! NSDictionary
print("response=\(dic)")
}
}
}
@IBAction func powerCyclePressed(sender: AnyObject) {
weak var weakSelf = self
let alertController = UIAlertController(title: "Warnnig", message: "This action will not undo!", preferredStyle: .actionSheet)
let dateAction = UIAlertAction(title: "Power Cycle", style: .destructive) { (action:UIAlertAction!) in
weakSelf!.dropletActions(type: "power_cycle")
}
alertController.addAction(dateAction)
let cancellAction = UIAlertAction(title: "Cancell", style: .cancel) { (action:UIAlertAction!) in
}
alertController.addAction(cancellAction)
self.present(alertController, animated: true, completion:nil)
}
@IBAction func deletePressed(sender: AnyObject) {
weak var weakSelf = self
let alertController = UIAlertController(title: "Warnnig", message: "This action will not undo!", preferredStyle: .actionSheet)
// Reboot
let dateAction = UIAlertAction(title: "Delete", style: .destructive) { (action:UIAlertAction!) in
weakSelf!.deleteDroplet()
}
alertController.addAction(dateAction)
let cancellAction = UIAlertAction(title: "Cancell", style: .cancel) { (action:UIAlertAction!) in
}
alertController.addAction(cancellAction)
self.present(alertController, animated: true, completion:nil)
}
func deleteDroplet() {
// curl -X DELETE -H "Content-Type: application/json" -H "Authorization: Bearer b7d03a6947b217efb6f3ec3bd3504582" "https://api.digitalocean.com/v2/droplets/3164494"
let Headers = [
"Content-Type": "application/json",
"Authorization": "Bearer "+Account.sharedInstance.Access_Token
]
let hud:MBProgressHUD = MBProgressHUD(view: self.view.window!)
self.view.window?.addSubview(hud)
hud.mode = MBProgressHUDMode.indeterminate
hud.show(animated: true)
hud.removeFromSuperViewOnHide = true
weak var weakSelf = self
Alamofire.request(BASE_URL+URL_DROPLETS+"/\(dropletData.id)/", method: .delete, parameters: nil, encoding: URLEncoding.default, headers: Headers).responseJSON { response in
DispatchQueue.main.async {
hud.hide(animated: true)
}
if let strongSelf = weakSelf {
if response.response?.statusCode == 204 {
DispatchQueue.main.async {
strongSelf.delegate?.didSeleteDroplet()
strongSelf.navigationController?.popViewController(animated: true)
}
} else if response.response?.statusCode == 442 {
let dic = response.result.value as! NSDictionary
print("response=\(dic)")
if let message = dic.value(forKey: "message") {
makeTextToast(message: message as! String, view: strongSelf.view.window!)
}
}
}
}
}
}
|
mit
|
da982c4c602113c88cebdf7bf087c399
| 37.698925 | 198 | 0.608919 | 4.779548 | false | false | false | false |
IAskWind/IAWExtensionTool
|
IAWExtensionTool/IAWExtensionTool/Classes/Base/Controller/IAW_TabBarController.swift
|
1
|
4594
|
//
// IAWTabBarController.swift
// CtkApp
//
// Created by winston on 16/12/9.
// Copyright © 2016年 winston. All rights reserved.
//
import UIKit
//import SlideMenuControllerSwift
open class IAW_TabBarController: UITabBarController {
//第一个参数chindviewcontroller,第二个参数title,第三个imageName,第4个是否有侧边栏
var childVcArray:[(String,String,String,Bool)]?
var navBarTintColor:UIColor?
var navBarTitleFontSize:CGFloat?
var navBarTitleColor:UIColor?
override open func viewDidLoad() {
super.viewDidLoad()
// tabBar.tintColor = UIColor(red: 245 / 255, green: 80 / 255, blue: 83 / 255, alpha: 1.0)
}
public convenience init(childVcArray: [(String,String,String,Bool)],tabBarTintColor:UIColor,navBarTintColor:UIColor,navBarTitleFontSize:CGFloat = 15,navBarTitleColor:UIColor = UIColor.white) {
self.init(nibName: nil, bundle: nil)
self.navBarTintColor = navBarTintColor
self.navBarTitleFontSize = navBarTitleFontSize
self.navBarTitleColor = navBarTitleColor
tabBar.tintColor = tabBarTintColor
self.childVcArray = childVcArray
self.addChildViewControllers()
}
/**
# 添加子控制器
*/
public func addChildViewControllers() {
for childVc in childVcArray! {
addChildViewController(childControllerName: childVc.0, title: childVc.1, imageName: childVc.2,isLeftBarBtn:childVc.3)
}
// addChildViewController(childControllerName: String(describing: IAWMainAllViewController.self), title: CtkTabBarItem.Main.rawValue, imageName: "TabBar_home_23x23_")
// addChildViewController(childControllerName: String(describing: IAWUploadViewController.self), title: CtkTabBarItem.Upload.rawValue, imageName: "camera_23x23_")
// addChildViewController(childControllerName: String(describing: IAWMeViewController.self), title: CtkTabBarItem.Me.rawValue, imageName: "TabBar_me_boy_23x23_")
}
/**
# 初始化子控制器
- parameter childControllerName: 需要初始化的控制器
- parameter title: 标题
- parameter imageName: 图片名称
*/
private func addChildViewController(childControllerName: String, title: String, imageName: String,isLeftBarBtn:Bool) {
// 动态获取命名空间
let ns = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
// 将字符串转化为类,默认情况下命名空间就是项目名称,但是命名空间可以修改
let cls: AnyClass? = NSClassFromString(ns + "." + childControllerName)
let vcClass = cls as! UIViewController.Type
let vc = vcClass.init()
// 设置对应的数据
vc.tabBarItem.image = UIImage(named: imageName)
vc.tabBarItem.selectedImage = UIImage(named: imageName + "selected")
vc.title = title
// 给每个控制器包装一个导航控制器
let nav = IAW_NavigationController(navBarTintColor: navBarTintColor!,navBarTitleFontSize: navBarTitleFontSize!,navBarTitleColor: navBarTitleColor!)
if isLeftBarBtn {
IAW_SlideMenuTool.addLeftBarItem(target: vc)
}
nav.addChild(vc)
addChild(nav)
}
// override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
// if item.title! == CtkTabBarItem.Upload.rawValue{
// if let upload = self.childViewControllers[1].childViewControllers[0] as? IAWUploadViewController{
// upload.loadTips()
// }
// }
//
//
// }
}
extension IAW_TabBarController : SlideMenuControllerDelegate {
public func leftWillOpen() {
print("SlideMenuControllerDelegate: leftWillOpen")
}
public func leftDidOpen() {
print("SlideMenuControllerDelegate: leftDidOpen")
}
public func leftWillClose() {
print("SlideMenuControllerDelegate: leftWillClose")
}
public func leftDidClose() {
print("SlideMenuControllerDelegate: leftDidClose")
}
public func rightWillOpen() {
print("SlideMenuControllerDelegate: rightWillOpen")
}
public func rightDidOpen() {
print("SlideMenuControllerDelegate: rightDidOpen")
}
public func rightWillClose() {
print("SlideMenuControllerDelegate: rightWillClose")
}
public func rightDidClose() {
print("SlideMenuControllerDelegate: rightDidClose")
}
}
|
mit
|
01941d75aec3c5b7567255d2d76982ad
| 34.455285 | 196 | 0.664985 | 4.714595 | false | false | false | false |
embassem/NetworkService
|
NetworkService/Sources/Core/NetworkService.swift
|
1
|
6885
|
//
// NetworkAbstraction.swift
// Guest-iOS
//
// Created by Bassem on 8/17/17.
// Copyright © 2017 Ibtikar. All rights reserved.
//
//TODO: List
// - Cancelable
// hock to response to check on failure
import Foundation
import Alamofire
import Moya
import ObjectMapper
import SwiftyJSON
import Moya_ObjectMapper
import enum Result.Result
//============================================================================
//============================================================================
//MARK: -Protocal
public protocol ProviderProtocal {
associatedtype Target:TargetType;
// associatedtype ProviderTargetType:MoyaProvider<APITarget>
var providerBaseUrl :String{get set}
init(baseUrl: String , plugins : [PluginType] ,headers:[[String: String]] )
mutating func changeBaseUrl()
func getprovider() -> MoyaProvider<Target>
}
//============================================================================
//============================================================================
//MARK: - typealias
public typealias networkResult = Result<Mappable?, MoyaError>
public typealias NetworkResponse = (_ result: networkResult , _ json:JSON? , _ response: Moya.Response? , _ type:NetworkResponseType ) -> Void;
//============================================================================
//============================================================================
//MARK: - enum
public enum NetworkResponseType{
case object
case array
case image
case string
}
//============================================================================
//============================================================================
//MARK: - TypeProvider
public class TypeProvider<T:TargetType , M:Mappable> {
var genaricModelType:M
var target:T
init(moyaTarget:T,genaricModelType:M) {
self.genaricModelType = genaricModelType;
self.target = moyaTarget;
}
}
//============================================================================
//============================================================================
//MARK: - NetworkAbstractionService
public class NetworkService: NSObject {
public static let shared: NetworkService = {
let instance = NetworkService()
return instance
}()
public class func config(providers :[Any] ) {
NetworkService.providers = providers;
}
private static var providers :[Any] = []
func reAuthAllPoint(){
}
public func request<E:TargetType, T:Mappable>(endPoint: E,modelType:T.Type,responseType:NetworkResponseType = .object, delegate: @escaping NetworkResponse) where E:TargetType {
let targetproviders = NetworkService.providers.flatMap{ $0 as? MoyaProvider<E> }
if let provider = targetproviders.first {
provider.request(endPoint) { moyaResult in
self.responseHandeler(moyaResult, modelType: modelType,responseType, delegate: delegate)
}
}else {
delegate(Result.failure(MoyaError.underlying(NSError(domain: "", code: -999), nil)), nil, nil, responseType);
}
}
private func responseHandeler <T:Mappable>(_ result: Result<Moya.Response, Moya.MoyaError> , modelType: T.Type, _ responseType:NetworkResponseType , delegate: @escaping NetworkResponse ) where T: Mappable {
switch result {
case let .success(response):
self.successHandler(modelType, response: response, delegate: delegate)
break
case let .failure(error):
self.failureHandler(modelType, error: error, response: nil, delegate: delegate)
}
}
private func successHandler<T:Mappable> (_ modelType: T.Type , response: Moya.Response , _ type:NetworkResponseType = .object, delegate: @escaping NetworkResponse){
var json: JSON? = nil;
var model: Mappable? = nil;
do {
json = JSON(data: response.data);
switch type {
case .object:
model = try response.mapObject(GenaricModel<T>.self)
break;
case .array:
model = try response.mapObject(GenaricModel<T>.self)
// model = try response.mapArray(GenaricArray<modelType.Type>.self);
// model = try response.mapArray(GenaricModel<T>.self);
break;
default :
fatalError(" requesting to map Network response to type not implemented ")
break;
}
} catch let parseError {
debugPrint(parseError.localizedDescription)
// delegate(.failure(parseError), json, response, type)
}
// delegate(json, model, response);
delegate(.success(model), json, response, type)
}
private func failureHandler<T:Mappable> (_ modelType: T.Type ,error: MoyaError ,response: Moya.Response? , _ type:NetworkResponseType = .object, delegate: @escaping NetworkResponse) where T: Mappable {
var json: JSON? = nil;
var model: Mappable? = nil;
do {
if let data = response?.data {
json = JSON(data: data);
}
model = try response?.mapObject(GenaricModel<T>.self);
} catch let parseError {
debugPrint(parseError.localizedDescription)
// delegate(.failure(parseError), json, response, type)
}
delegate( Result<Mappable?, MoyaError>.failure(error), json, response, type)
}
}
// MARK: - Provider setup
public func JSONResponseDataFormatter(_ data: Data) -> Data {
do {
let dataAsJSON = try JSONSerialization.jsonObject(with: data)
let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
return prettyData
} catch {
return data // fallback to original data if it can't be serialized.
}
}
// MARK: - Provider support
public extension String {
var urlEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
}
|
mit
|
0e730f2458611c20ca7287f15f2ed3bc
| 25.274809 | 212 | 0.498402 | 5.5072 | false | false | false | false |
honghaoz/CrackingTheCodingInterview
|
Swift/LeetCode/记忆题 - 只需要记住最优解/242_Valid Anagram.swift
|
1
|
1565
|
// 242_Valid Anagram
// https://leetcode.com/problems/valid-anagram/
//
// Created by Honghao Zhang on 10/13/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given two strings s and t , write a function to determine if t is an anagram of s.
//
//Example 1:
//
//Input: s = "anagram", t = "nagaram"
//Output: true
//Example 2:
//
//Input: s = "rat", t = "car"
//Output: false
//Note:
//You may assume the string contains only lowercase alphabets.
//
//Follow up:
//What if the inputs contain unicode characters? How would you adapt your solution to such case?
//
import Foundation
class Num242 {
// MARK: - Use char table to count
// Use char in s to increment the count
// Use char in t to decrement the count
// Then check if the count is all zero
// If during the iteration, count is below zero, can early return
// O(n)
// O(1) // this is because the table is fixed size, regardless of the input size
func isAnagram(_ s: String, _ t: String) -> Bool {
let alphabeta = "abcdefghijklmnopqrstuvwxyz"
var table: [Character: Int] = [:]
for c in alphabeta {
table[c] = 0
}
for c in s {
table[c] = table[c]! + 1
}
for c in t {
table[c] = table[c]! - 1
if table[c]! < 0 {
return false
}
}
for c in alphabeta {
if table[c] != 0 {
return false
}
}
return true
}
// MARK: - Sort and compare
// O(n logn)
// O(1)
func isAnagram_sort(_ s: String, _ t: String) -> Bool {
return s.sorted() == t.sorted()
}
}
|
mit
|
fe866229ca435a58f252336437aaa59d
| 22.343284 | 96 | 0.60422 | 3.385281 | false | false | false | false |
yunuserenguzel/road-game
|
Generator/Generator/MapGenerator.swift
|
1
|
2316
|
//
// MapGenerator.swift
// Generator
//
// Created by Yunus Güzel on 25/10/2016.
// Copyright © 2016 yeg. All rights reserved.
//
import Foundation
public class MapGenerator {
let size: Int
let limit: Int
let passiveCellCount: Int
public init(size: Int, limit: Int, passiveCellCount: Int) {
self.size = size
self.limit = limit
self.passiveCellCount = passiveCellCount
}
public func generateMaps() -> [Map] {
var maps: [Map] = []
repeat {
if let map: Map = generateMap(), !maps.contains(map) {
maps.append(map)
}
} while(maps.count < limit)
return maps
}
func generateMap() -> Map? {
let helper = MapGeneratorHelper(map: Map(size: size), passiveCellCount: passiveCellCount)
return helper.execute()
}
public func generateMap() -> [(Int,Int)] {
let map: Map! = generateMap()
return map.cells.flatMap {
$0.flatMap {
return $0.cellType == .passive ? ($0.point.x, $0.point.y) : nil
}
}
}
}
class MapGeneratorHelper {
var map: Map
let passiveCellCount: Int
init(map: Map, passiveCellCount: Int) {
self.map = map.copy
self.passiveCellCount = passiveCellCount
}
func execute() -> Map? {
let cell: Cell! = map.cells.shuffled().first?.shuffled().first
if executeAStep(cell: cell) {
return Map(size: map.size, passiveCellPoints: map.unconnectedPoints)
}
return nil
}
func executeAStep(cell: Cell) -> Bool {
for direction in Direction.all.shuffled() {
guard let nextCell = self.map.cell(nextToCell: cell, atDirection: direction) else { continue }
guard cell.connect(toCell: nextCell) else { continue }
if map.unconnectedPoints.count == passiveCellCount,
nextCell.connection.count == 2 {
return true
}
if map.unconnectedPoints.count >= passiveCellCount {
if executeAStep(cell: nextCell) {
return true
}
}
cell.disconnect(fromCell: nextCell)
}
return false
}
}
|
mit
|
f782f8bc999f83ced0bfb5196bd116bf
| 26.223529 | 106 | 0.550994 | 4.184448 | false | false | false | false |
zjjzmw1/robot
|
robot/robot/CodeFragment/Category/NSDate+JCDate.swift
|
1
|
7317
|
//
// NSDate+JCDate.swift
// JCSwiftKitDemo
//
// Created by molin.JC on 2017/1/4.
// Copyright © 2017年 molin. All rights reserved.
//
import Foundation
private let kNSDATE_MINUTE_SEC = 60; // 一分 = 60秒
private let kNSDATE_HOURS_SEC = 3600; // 一小时 = 60分 = 3600秒
private let kNSDATE_DAY_SEC = 86400; // 一天 = 24小时 = 86400秒
private let kNSDATE_WEEK_SEC = 604800; // 一周 = 7天 = 604800秒
enum dateFormatStyle: String {
case Style1 = "yyyy-MM-dd"
}
extension NSDate {
class func formatterWithStyle(withStyle style: dateFormatStyle) -> DateFormatter {
let formatter = DateFormatter()
formatter.locale = NSLocale.current
formatter.dateFormat = style.rawValue
return formatter
}
/**
根据时间戳返回日期
- parameter stamp: 时间戳字符串
- returns: 日期
*/
class func dateWithTimeStamp(stamp: String) -> NSDate? {
if let interval = TimeInterval(stamp) {
return NSDate(timeIntervalSince1970: interval / 1000.0)
}
return nil
}
/**
根据日期返回字符串格式
- returns: 日期字符串
*/
func string(withStyle style: dateFormatStyle) -> String? {
switch style {
case .Style1:
let formatter = NSDate.formatterWithStyle(withStyle: style)
return formatter.string(from: self as Date)
}
}
private func dateFormat() -> Date {
let formatter = NSDate.formatterWithStyle(withStyle: .Style1)
let dateStr = formatter.string(from: self as Date)
return formatter.date(from: dateStr)!
}
var yearSwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.year, from: self as Date);
}
}
var monthSwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.month, from: self as Date);
}
}
var daySwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.day, from: self as Date);
}
}
var hourSwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.hour, from: self as Date);
}
}
var minuteSwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.minute, from: self as Date);
}
}
var secondSwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.second, from: self as Date);
}
}
var nanosecondSwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.nanosecond, from: self as Date);
}
}
var weekdaySwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.weekday, from: self as Date);
}
}
var weekdayOrdinalSwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.weekdayOrdinal, from: self as Date);
}
}
var weekOfMonthSwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.weekOfMonth, from: self as Date);
}
}
var weekOfYearSwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.weekOfYear, from: self as Date);
}
}
var yearForWeekOfYearSwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.yearForWeekOfYear, from: self as Date);
}
}
var quarterSwift: NSInteger {
get {
return NSCalendar.current.component(Calendar.Component.quarter, from: self as Date);
}
}
/// 闰月
var isLeapMonthSwift: Bool {
get {
return DateComponents.init().isLeapMonth!;
}
}
/// 闰年
var isLeapYearSwift: Bool {
get {
let year = self.year;
return ((year % 400 == 0) || (year % 100 == 0) || (year % 4 == 0));
}
}
/// 今天
var isTodaySwift: Bool {
get {
if (fabs(self.timeIntervalSinceNow) >= Double(kNSDATE_DAY_SEC)) {
return false;
}
return NSDate.init().day == self.day;
}
}
}
extension NSDate {
class func dateWithString(stringDate: String) -> NSDate? {
return NSDate.dateWithString(stringDate: stringDate, format: "yyyy-MM-dd HH:mm:ss");
}
class func dateWithString(stringDate: String, format: String) -> NSDate? {
let formatter = DateFormatter.init();
formatter.locale = NSLocale.current;
formatter.dateFormat = format;
return formatter.date(from: stringDate) as NSDate?;
}
func string() -> String {
return self.stringWithFormat(format: "yyyy-MM-dd HH:mm:ss");
}
func stringWithFormat(format: String) -> String {
let formatter = DateFormatter.init();
formatter.locale = NSLocale.current;
formatter.dateFormat = format;
return formatter.string(from: self as Date);
}
/// 明天
class func dateTomorrow() -> NSDate {
return NSDate.dateWithDaysFromNow(days: 1);
}
/// 后几天
class func dateWithDaysFromNow(days: NSInteger) -> NSDate {
return NSDate.init().dateByAdding(days: days);
}
/// 昨天
class func dateYesterday() -> NSDate {
return NSDate.dateWithDaysBeforeNow(days: 1);
}
/// 前几天
class func dateWithDaysBeforeNow(days: NSInteger) -> NSDate {
return NSDate.init().dateByAdding(days: -(days));
}
/// 当前小时后hours个小时
class func dateWithHoursFromNow(hours: NSInteger) -> NSDate {
return NSDate.dateByAddingTimeInterval(ti: TimeInterval(kNSDATE_HOURS_SEC * hours));
}
/// 当前小时前hours个小时
class func dateWithHoursBeforeNow(hours: NSInteger) -> NSDate {
return NSDate.dateByAddingTimeInterval(ti: TimeInterval(-kNSDATE_HOURS_SEC * hours));
}
/// 当前分钟后minutes个分钟
class func dateWithMinutesFromNow(minutes: NSInteger) -> NSDate {
return NSDate.dateByAddingTimeInterval(ti: TimeInterval(kNSDATE_MINUTE_SEC * minutes));
}
/// 当前分钟前minutes个分钟
class func dateWithMinutesBeforeNow(minutes: NSInteger) -> NSDate {
return NSDate.dateByAddingTimeInterval(ti: TimeInterval(-kNSDATE_MINUTE_SEC * minutes));
}
/// 追加天数,生成新的NSDate
func dateByAdding(days: NSInteger) -> NSDate {
var dateComponents = DateComponents.init();
dateComponents.day = days;
let date = NSCalendar.current.date(byAdding: dateComponents, to: (self as Date?)!);
return (date as NSDate?)!;
}
/// 追加秒数,生成新的NSDate
class func dateByAddingTimeInterval(ti: TimeInterval) -> NSDate {
let aTimeInterval = NSDate.init().timeIntervalSinceReferenceDate + ti;
let date = NSDate.init(timeIntervalSinceReferenceDate: aTimeInterval);
return date;
}
}
|
mit
|
28d1f70704bb75805c57079b2ecdcf1f
| 28.02459 | 106 | 0.602796 | 4.429018 | false | false | false | false |
zjjzmw1/speedxSwift
|
speedxSwift/speedxSwift/ClubVC.swift
|
1
|
1037
|
//
// Shoping_VC.swift
// LBTabBar
//
// Created by chenlei_mac on 15/8/25.
// Copyright (c) 2015年 Bison. All rights reserved.
//
import UIKit
class ClubVC: BaseViewController {
let BaiduURL = kHOME_TOPIC_LIST_URL
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "俱乐部"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//网络请求
self.reloadData()
}
func reloadData(){
// http://api.map.baidu.com/telematics/v3/weather?location=嘉兴&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ
// let url = "http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=yourkey"
// RequestBaseManager .baseRequestJson(.GET, urlString: url) { (isSuccessed, code, jsonValue) in
// print("isSuccessed====\(isSuccessed)")
// print("code====\(code)")
// print("jsonValue====\(jsonValue)")
// }
}
}
|
mit
|
8a9ab9cc00d73103f6af47eecc4c4c72
| 24.325 | 108 | 0.59921 | 3.433898 | false | false | false | false |
sacrelee/iOSDev
|
Notes/Swift/Coding.playground/Pages/Inheritance.xcplaygroundpage/Contents.swift
|
1
|
1552
|
/// 继承 Inheritance
// 继承自其它类,称之为子类,被继承的类称之为父类或者超类
/// 一个基类
// 不继承自其他类称之为基类
class Animal{ // 动物基类
var speed = 0.0
var name:String{
return "Animal"
}
func description()->String{ return "Name:\(name), Speed:\(speed)"}
func eat(){}
}
/// 子类生成
class Felidae:Animal{ // 猫科动物类继承自Animal类
var numberOfLegs = 4
var hasTail = true
}
let f = Felidae()
f.speed = 15
print("\(f.description())")
class Cat:Felidae { // 猫类继承自猫科动物类
var houseAnimal = true
}
let c = Cat()
c.speed = 10
print("\(c.description())")
/// 重写
// 重写方法 父类方法前加override
// 重写属性 不可以将读写属性重写为只读类型
class Dog:Animal{
var speedLevel = 0
override var name:String{ // 重写属性
return "Dog"
}
override func eat() { // 重写方法
print("Dog like eat Bone")
}
override var speed:Double{ // 重写属性观察器,
didSet{
speedLevel = Int(( speed - 10 )) / 10 + 1
}
}
}
let aDog = Dog()
aDog.eat() // 打印Dog like eat Bone
aDog.speed = 40
print("Speed Level:\(aDog.speedLevel)")
print("\(aDog.name)") // 现在name为Dog
/// 禁止重写
// 在想要禁止重写的类型前加final
// 比如:final var, final func, final subscript, 如果试图重写这些,将会报错
// 在final class 表示这个类不能被继承
|
apache-2.0
|
698d8f800860ad57cf2bf310ea044b0e
| 15 | 70 | 0.587171 | 2.902148 | false | false | false | false |
DanielAsher/Few.swift
|
Few-Mac/Image.swift
|
4
|
1255
|
//
// Image.swift
// Few
//
// Created by Josh Abernathy on 3/3/15.
// Copyright (c) 2015 Josh Abernathy. All rights reserved.
//
import Foundation
import AppKit
public class Image: Element {
public var image: NSImage?
public var scaling: NSImageScaling
public init(_ image: NSImage?, scaling: NSImageScaling = .ImageScaleProportionallyUpOrDown) {
self.image = image
self.scaling = scaling
let size = image?.size ?? CGSize(width: Node.Undefined, height: Node.Undefined)
super.init(frame: CGRect(origin: CGPointZero, size: size))
}
// MARK: Element
public override func applyDiff(old: Element, realizedSelf: RealizedElement?) {
super.applyDiff(old, realizedSelf: realizedSelf)
if let view = realizedSelf?.view as? NSImageView {
if view.imageScaling != scaling {
view.imageScaling = scaling
}
if view.image != image {
view.image = image
realizedSelf?.markNeedsLayout()
}
}
}
public override func createView() -> ViewType {
let view = NSImageView(frame: CGRectZero)
view.image = image
view.editable = false
view.allowsCutCopyPaste = false
view.animates = true
view.imageFrameStyle = .None
view.imageScaling = scaling
view.alphaValue = alpha
view.hidden = hidden
return view
}
}
|
mit
|
64cd192461bd2aee80778d54b81413a9
| 22.679245 | 94 | 0.70996 | 3.535211 | false | false | false | false |
yaslab/ZeroFormatter.swift
|
Sources/ZeroFormattable.swift
|
1
|
3923
|
//
// ZeroFormattable.swift
// ZeroFormatter
//
// Created by Yasuhiro Hatta on 2016/11/24.
// Copyright © 2016 yaslab. All rights reserved.
//
import Foundation
public func _fixedSize(_ types: [Formattable.Type]) -> Int? {
var size = 0
for type in types {
guard let length = type.length else {
return nil
}
size += length
}
return size
}
// MARK: - Basic Protocol
public protocol Formattable {
static var length: Int? { get }
}
public protocol Serializable: Formattable {
static func serialize(_ bytes: NSMutableData, _ offset: Int, _ value: Self) -> Int
static func serialize(_ bytes: NSMutableData, _ offset: Int, _ value: Self?) -> Int
static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Self
static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Self?
}
// MARK: - Primitive Protocol
public protocol PrimitiveSerializable: Serializable {}
// MARK: - Object Protocol
public protocol ObjectSerializable: Serializable {
static func serialize(_ value: Self, _ builder: ObjectBuilder)
static func deserialize(_ extractor: ObjectExtractor) -> Self
}
public extension ObjectSerializable {
public static func serialize(_ bytes: NSMutableData, _ offset: Int, _ value: Self) -> Int {
let builder = ObjectBuilder(bytes)
serialize(value, builder)
let length = builder.build()
return length
}
public static func serialize(_ bytes: NSMutableData, _ offset: Int, _ value: Self?) -> Int {
if let value = value {
return serialize(bytes, -1, value)
} else {
return BinaryUtility.serialize(bytes, -1) // byteSize
}
}
}
public extension ObjectSerializable {
public static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Self {
let value: Self? = deserialize(bytes, offset, &byteSize)
if value == nil {
preconditionFailure()
}
return value!
}
public static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Self? {
let extractor = ObjectExtractor(bytes, offset)
if extractor.byteSize < 0 {
return nil
}
let value = deserialize(extractor)
byteSize += extractor.byteSize
return value
}
}
// MARK: - Struct Protocol
public protocol StructSerializable: Serializable {
static func serialize(_ value: Self, _ builder: StructBuilder)
static func deserialize(_ extractor: StructExtractor) -> Self
}
public extension StructSerializable {
public static func serialize(_ bytes: NSMutableData, _ offset: Int, _ value: Self) -> Int {
let builder = StructBuilder(bytes)
serialize(value, builder)
let length = builder.byteSize
return length
}
public static func serialize(_ bytes: NSMutableData, _ offset: Int, _ value: Self?) -> Int {
if let value = value {
return serialize(bytes, -1, value)
} else {
return BinaryUtility.serialize(bytes, -1) // byteSize
}
}
}
public extension StructSerializable {
public static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Self {
let value: Self? = deserialize(bytes, offset, &byteSize)
if value == nil {
preconditionFailure()
}
return value!
}
public static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Self? {
let extractor = StructExtractor(bytes, offset)
if extractor.byteSize < 0 {
byteSize += extractor.byteSize
return nil
}
let value = deserialize(extractor)
byteSize += extractor.byteSize
return value
}
}
|
mit
|
f9e877fa730bb14b1d230f741cec19f9
| 26.426573 | 100 | 0.614482 | 4.528868 | false | false | false | false |
rajatvig/pact-demo-client
|
Sources/Models/TodoItem.swift
|
1
|
791
|
import Foundation
import SwiftyJSON
public struct TodoItem: CustomStringConvertible, Equatable {
public let title: String
public let completed: Bool
public let order: Int?
public let url: URL?
public init(_ jsonData: JSON) {
self.title = jsonData["title"].stringValue
self.completed = jsonData["completed"].boolValue
self.order = jsonData["order"].int
self.url = URL.init(string: jsonData["url"].stringValue)
}
public var description: String {
return "title=\(self.title),completed=\(self.completed),order=\(self.order),url=\(self.url)"
}
}
public func == (lhs: TodoItem, rhs: TodoItem) -> Bool {
return lhs.url == rhs.url && lhs.title == rhs.title && lhs.order == rhs.order && lhs.completed == rhs.completed
}
|
mit
|
27a3754c2cb422e6d881f2fc22ea5bfb
| 31.958333 | 115 | 0.65866 | 4.163158 | false | false | false | false |
tmukammel/iOSKickStart
|
iOSKickStart/Classes/TextField.swift
|
1
|
2938
|
//
// TextField.swift
// BeWithFriends
//
// Created by Twaha Mukammel on 9/4/16.
// Copyright © 2016 Twaha Mukammel. All rights reserved.
//
import UIKit
@IBDesignable
open class TextField: UITextField, UITextFieldDelegate {
}
@IBDesignable
open class CodeInputTextField: TextField {
private var codeLength: Int?
private var codePlaceHolder: Character?
@IBInspectable public var codeLengthAndChar: String {
set {
if (newValue.count >= 3) {
codeLength = nil
codePlaceHolder = nil
let data = newValue.components(separatedBy: ",")
guard data.count == 2 else {
return
}
codeLength = Int(data[0])
codePlaceHolder = data[1].first;
if let length = codeLength, length > 0, let placeholder = codePlaceHolder {
text = String(repeating: String(describing: placeholder), count: length)
}
}
}
get {
return ""
}
}
/// Brings cursor position to begning of text
///
/// - Returns: should begin editing
open func observeCodeInputDidBegin() {
selectedTextRange = textRange(from: beginningOfDocument, to: beginningOfDocument)
}
/// Code input and placeholder replacement. Call this method from textfield shouldChangeCharactersIn range: delegate method.
///
/// - Parameters:
/// - range: The range of characters to be replaced.
/// - string: The replacement string.
/// - Returns: should change character.
open func observeCodeInput(shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// print("Location: \(range.location), Length: \(range.length), String: \(string)");
guard let length = codeLength, let code = codePlaceHolder,
range.location + string.count <= length else {
return false
}
switch range.length {
case 0:
text = (text! as NSString).replacingCharacters(in: NSMakeRange(range.location, string.count), with: string)
if let position = position(from: beginningOfDocument, offset: range.location + string.count) {
selectedTextRange = textRange(from: position, to: position)
}
default:
text = (text! as NSString).replacingCharacters(in: NSMakeRange(range.location, range.length), with: String(repeating: String(describing: code), count: range.length))
if let position = position(from: beginningOfDocument, offset: range.location) {
selectedTextRange = textRange(from: position, to: position)
}
}
return false
}
}
|
mit
|
d039b5135b7166faf8e297b40f657084
| 32 | 177 | 0.574736 | 5.125654 | false | false | false | false |
wikimedia/wikipedia-ios
|
Wikipedia/Code/DiffToolbarView.swift
|
1
|
6770
|
import UIKit
protocol DiffToolbarViewDelegate: AnyObject {
func tappedPrevious()
func tappedNext()
func tappedShare(_ sender: UIBarButtonItem)
func tappedThankButton()
var isLoggedIn: Bool { get }
}
class DiffToolbarView: UIView {
var parentViewState: DiffContainerViewModel.State? {
didSet {
apply(theme: theme)
}
}
private var theme: Theme = .standard
@IBOutlet private var toolbar: UIToolbar!
@IBOutlet var contentView: UIView!
lazy var previousButton: IconBarButtonItem = {
let item = IconBarButtonItem(iconName: "chevron-down", target: self, action: #selector(tappedPrevious(_:)), for: .touchUpInside)
item.accessibilityLabel = WMFLocalizedString("action-previous-revision-accessibility", value: "Previous Revision", comment: "Accessibility title for the 'Previous Revision' action button when viewing a single revision diff.")
item.customView?.widthAnchor.constraint(equalToConstant: 38).isActive = true
return item
}()
lazy var nextButton: IconBarButtonItem = {
let item = IconBarButtonItem(iconName: "chevron-up", target: self, action: #selector(tappedNext(_:)), for: .touchUpInside)
item.accessibilityLabel = WMFLocalizedString("action-next-revision-accessibility", value: "Next Revision", comment: "Accessibility title for the 'Next Revision' action button when viewing a single revision diff.")
item.customView?.widthAnchor.constraint(equalToConstant: 38).isActive = true
return item
}()
lazy var shareButton: IconBarButtonItem = {
let item = IconBarButtonItem(iconName: "share", target: self, action: #selector(tappedShare(_:)), for: .touchUpInside)
item.accessibilityLabel = CommonStrings.accessibilityShareTitle
return item
}()
lazy var thankButton: IconBarButtonItem = {
let item = IconBarButtonItem(iconName: "diff-smile", target: self, action: #selector(tappedThank(_:)), for: .touchUpInside , iconInsets: UIEdgeInsets(top: 5.0, left: 0, bottom: -5.0, right: 0))
item.accessibilityLabel = WMFLocalizedString("action-thank-user-accessibility", value: "Thank User", comment: "Accessibility title for the 'Thank User' action button when viewing a single revision diff.")
return item
}()
weak var delegate: DiffToolbarViewDelegate?
var isThankSelected = false {
didSet {
let imageName = isThankSelected ? "diff-smile-filled" : "diff-smile"
if let button = thankButton.customView as? UIButton {
button.setImage(UIImage(named: imageName), for: .normal)
}
}
}
var toolbarHeight: CGFloat {
return toolbar.frame.height
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
Bundle.main.loadNibNamed(DiffToolbarView.wmf_nibName(), owner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
setItems()
}
@objc func tappedPrevious(_ sender: UIBarButtonItem) {
delegate?.tappedPrevious()
}
@objc func tappedNext(_ sender: UIBarButtonItem) {
delegate?.tappedNext()
}
@objc func tappedShare(_ sender: UIBarButtonItem) {
delegate?.tappedShare(shareButton)
}
@objc func tappedThank(_ sender: UIBarButtonItem) {
delegate?.tappedThankButton()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
setItems()
}
private func setItems() {
let trailingMarginSpacing = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
switch (traitCollection.horizontalSizeClass, traitCollection.verticalSizeClass) {
case (.regular, .regular):
trailingMarginSpacing.width = 58
default:
trailingMarginSpacing.width = 24
}
let leadingMarginSpacing = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
switch (traitCollection.horizontalSizeClass, traitCollection.verticalSizeClass) {
case (.regular, .regular):
leadingMarginSpacing.width = 42
default:
leadingMarginSpacing.width = 0
}
let largeFixedSize = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
largeFixedSize.width = 30
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbar.items = [leadingMarginSpacing, nextButton, previousButton, spacer, thankButton, largeFixedSize, shareButton, trailingMarginSpacing]
}
func setPreviousButtonState(isEnabled: Bool) {
previousButton.isEnabled = isEnabled
}
func setNextButtonState(isEnabled: Bool) {
nextButton.isEnabled = isEnabled
}
func setThankButtonState(isEnabled: Bool) {
thankButton.isEnabled = isEnabled
}
func setShareButtonState(isEnabled: Bool) {
shareButton.isEnabled = isEnabled
}
}
extension DiffToolbarView: Themeable {
func apply(theme: Theme) {
self.theme = theme
toolbar.isTranslucent = false
toolbar.backgroundColor = theme.colors.chromeBackground
toolbar.barTintColor = theme.colors.chromeBackground
contentView.backgroundColor = theme.colors.chromeBackground
// avoid toolbar disappearing when empty/error states are shown
if theme == Theme.black {
switch parentViewState {
case .error, .empty:
toolbar.backgroundColor = theme.colors.paperBackground
toolbar.barTintColor = theme.colors.paperBackground
contentView.backgroundColor = theme.colors.paperBackground
default:
break
}
}
previousButton.apply(theme: theme)
nextButton.apply(theme: theme)
shareButton.apply(theme: theme)
thankButton.apply(theme: theme)
if let delegate = delegate,
!delegate.isLoggedIn {
if let button = thankButton.customView as? UIButton {
button.tintColor = theme.colors.disabledLink
}
}
shareButton.tintColor = theme.colors.link
}
}
|
mit
|
52efded496784611b50429109d339152
| 35.594595 | 233 | 0.64904 | 5.29734 | false | false | false | false |
Pluto-tv/jsonjam
|
Example/Pods/JSONHelper/JSONHelper/Deserialization.swift
|
1
|
3011
|
//
// Copyright © 2016 Baris Sencan. All rights reserved.
//
import Foundation
/// TODOC
public protocol Deserializable {
/// TODOC
init(dictionary: [String : AnyObject])
}
// MARK: - Helper Methods
private func dataStringToObject(_ dataString: String) -> Any? {
guard let data: Data = dataString.data(using: String.Encoding.utf8) else { return nil }
var jsonObject: Any?
do {
jsonObject = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0))
} catch {}
return jsonObject
}
// MARK: - Basic Deserialization
public func <-- <D: Deserializable, T>(lhs: inout D?, rhs: T?) -> D? {
let cleanedValue = JSONHelper.convertToNilIfNull(rhs)
if let jsonObject = cleanedValue as? NSDictionary as? [String : AnyObject] {
lhs = D(dictionary: jsonObject)
} else if let string = cleanedValue as? String {
lhs <-- dataStringToObject(string)
} else {
lhs = nil
}
return lhs
}
public func <-- <D: Deserializable, T>(lhs: inout D, rhs: T?) -> D {
var newValue: D?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
// MARK: - Array Deserialization
public func <-- <D: Deserializable, T>(lhs: inout [D]?, rhs: [T]?) -> [D]? {
guard let rhs = rhs else { return nil }
lhs = [D]()
for element in rhs {
var convertedElement: D?
convertedElement <-- element
if let convertedElement = convertedElement {
lhs?.append(convertedElement)
}
}
return lhs
}
public func <-- <D: Deserializable, T>(lhs: inout [D], rhs: [T]?) -> [D] {
var newValue: [D]?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
public func <-- <D: Deserializable, T>(lhs: inout [D]?, rhs: T?) -> [D]? {
guard let rhs = rhs else { return nil }
if let elements = rhs as? NSArray as? [AnyObject] {
return lhs <-- elements
}
return nil
}
public func <-- <D: Deserializable, T>(lhs: inout [D], rhs: T?) -> [D] {
var newValue: [D]?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
// MARK: - Dictionary Deserialization
public func <-- <T, D: Deserializable, U>(lhs: inout [T : D]?, rhs: [T : U]?) -> [T : D]? {
guard let rhs = rhs else {
lhs = nil
return lhs
}
lhs = [T : D]()
for (key, value) in rhs {
var convertedValue: D?
convertedValue <-- value
if let convertedValue = convertedValue {
lhs?[key] = convertedValue
}
}
return lhs
}
public func <-- <T, D: Deserializable, U>(lhs: inout [T : D], rhs: [T : U]?) -> [T : D] {
var newValue: [T : D]?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
public func <-- <T, D: Deserializable, U>(lhs: inout [T : D]?, rhs: U?) -> [T : D]? {
guard let rhs = rhs else {
lhs = nil
return lhs
}
if let elements = rhs as? NSDictionary as? [T : AnyObject] {
return lhs <-- elements
}
return nil
}
public func <-- <T, D: Deserializable, U>(lhs: inout [T : D], rhs: U?) -> [T : D] {
var newValue: [T : D]?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
|
mit
|
34eafc614bacfb3f3703e690fa65d1fc
| 21.132353 | 117 | 0.60598 | 3.504075 | false | false | false | false |
Obisoft2017/BeautyTeamiOS
|
BeautyTeam/BeautyTeam/RadioStationTaskCell.swift
|
1
|
2746
|
//
// RadioStationTaskCell.swift
// BeautyTeam
//
// Created by Carl Lee on 4/24/16.
// Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved.
//
import UIKit
import FontAwesome_swift
class RadioStationTaskCell: UITableViewCell, CustomPresentCellProtocol {
var titleLabel: UILabel?
var timeImageView: UIImageView?
var timeLabel: UILabel?
var emergencyLabel: UILabel?
var locationImageView: UIImageView?
var locationLabel: UILabel?
required init(reuseIdentifier: String) {
super.init(style: .Default, reuseIdentifier: reuseIdentifier)
let fontAwesomeSize = CGSize(width: 12, height: 12)
self.titleLabel = UILabel(frame: CGRectMake(10, 10, 300, 20))
self.titleLabel?.font = UIFont.systemFontOfSize(20)
// 74 144 226
self.timeImageView = UIImageView(frame: CGRectMake(10, 40, 12, 12))
self.timeImageView?.image = UIImage.fontAwesomeIconWithName(.ClockO, textColor: UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 1), size: fontAwesomeSize)
self.timeLabel = UILabel(frame: CGRectMake(30, 40, 300, 12))
self.timeLabel?.font = UIFont.systemFontOfSize(12)
// 208 2 27
self.emergencyLabel = UILabel(frame: CGRectMake(310, 40, 100, 12))
self.emergencyLabel?.font = UIFont.boldSystemFontOfSize(12)
// 0 0 0
self.locationImageView = UIImageView(frame: CGRectMake(10, 70, 12, 12))
self.locationImageView?.image = UIImage.fontAwesomeIconWithName(.LocationArrow, textColor: UIColor.blackColor(), size: fontAwesomeSize)
self.locationLabel = UILabel(frame: CGRectMake(30, 70, 300, 12))
self.locationLabel?.font = UIFont.systemFontOfSize(12)
}
func assignValue(title: String, time: NSDate, location: String) {
self.titleLabel?.text = title
let timeStr = ObiBeautyTeam.ObiDateFormatter().stringFromDate(time)
let timeAttrStr = NSMutableAttributedString(string: timeStr)
timeAttrStr.setAttributes([
NSForegroundColorAttributeName: UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 1)
], range: NSMakeRange(0, timeStr.characters.count))
self.timeLabel?.attributedText = timeAttrStr
self.locationLabel?.text = location
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
apache-2.0
|
122d14c2cce242a187b5cef085d7991e
| 36.60274 | 173 | 0.667395 | 4.427419 | false | false | false | false |
chipsandtea/Ecology
|
Ecology/SchoolSelectionViewController.swift
|
1
|
4250
|
//
// SchoolSelectionViewController.swift
// Ecology
//
// Created by Christopher Hsiao on 2/10/15.
// Copyright (c) 2015 Chips&Tea. All rights reserved.
//
import UIKit
class SchoolSelectionViewController: UIViewController, UIPickerViewDelegate{
@IBOutlet weak var schoolPicker: UIPickerView!
@IBOutlet weak var schoolField: UITextField!
var contents = [String]()
var dict = [String : String]()
var isSearch = false
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setNavigationBarHidden(true, animated: true)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(false);
navigationController?.setNavigationBarHidden(true, animated: true)
}
@IBAction func doSearch(sender: AnyObject) {
contents = [String]()
dict = [String : String]()
if(!self.isSearch)
{
get(schoolField.text)
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int{
return contents.count
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
//cData().setObject(self.dict[contents[row]]!, forKey: "id")
}
func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String!{
return contents[row]
}
func get(search : String) {
self.isSearch = true
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
/* Create session, and optionally set a NSURLSessionDelegate. */
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
/* Create the Request:
My API (2) (POST http://oneillseaodyssey.org/testing.php)
*/
var getUrl = search.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil)
var URL = NSURL(string: "http://oneillseaodyssey.org/search.php?search=\(getUrl)")
let request = NSMutableURLRequest(URL: URL!)
request.HTTPMethod = "GET"
/* Start a new Task */
let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as NSHTTPURLResponse).statusCode
let json = JSON(data: data)
dispatch_async(dispatch_get_main_queue(), {
for (key: String, subJson: JSON) in json {
self.contents.append(subJson["school"].stringValue + " - " + subJson["teacher"].stringValue)
self.dict[subJson["school"].stringValue + " - " + subJson["teacher"].stringValue] = subJson["id"].stringValue
}
self.schoolPicker.reloadAllComponents()
})
}
else {
println("URL Session Task Failed: %@", error.localizedDescription);
}
self.isSearch = false
})
task.resume()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var DestVC: GroupNameViewController = segue.destinationViewController as GroupNameViewController
//DestVC.school = "Placeholder School"
//println(self.schoolPicker.selectedRowInComponent(0))
if(!self.contents.isEmpty) {
DestVC.school = self.contents[self.schoolPicker.selectedRowInComponent(0)]
DestVC.school = self.contents[self.schoolPicker.selectedRowInComponent(0)]
sharedData().setObject(self.dict[contents[self.schoolPicker.selectedRowInComponent(0)]]!, forKey: "school_id")
}
}
}
|
gpl-3.0
|
3d3c6e31d07ff56c594d3d858294074c
| 32.730159 | 147 | 0.625176 | 5.065554 | false | false | false | false |
Donny8028/Swift-Animation
|
TabBarSwitch/TabBarSwitch/FriendReadViewController.swift
|
1
|
3396
|
//
// FriendReadViewController.swift
// TabBarSwitch
//
// Created by 賢瑭 何 on 2016/5/29.
// Copyright © 2016年 Donny. All rights reserved.
//
import UIKit
class FriendReadViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var data = [
article(avatarImage: "allen", sharedName: "Allen Wang", actionType: "Read Later", articleTitle: "Giphy Cam Lets You Create And Share Homemade Gifs", articleCoverImage: "giphy", articleSource: "TheNextWeb", articleTime: "5min • 13:20"),
article(avatarImage: "Daniel Hooper", sharedName: "Daniel Hooper", actionType: "Shared on Twitter", articleTitle: "Principle. The Sketch of Prototyping Tools", articleCoverImage: "my workflow flow", articleSource: "SketchTalk", articleTime: "3min • 12:57"),
article(avatarImage: "davidbeckham", sharedName: "David Beckham", actionType: "Shared on Facebook", articleTitle: "Ohlala, An Uber For Escorts, Launches Its ‘Paid Dating’ Service In NYC", articleCoverImage: "Ohlala", articleSource: "TechCrunch", articleTime: "1min • 12:59"),
article(avatarImage: "bruce", sharedName: "Bruce Fan", actionType: "Shared on Weibo", articleTitle: "Lonely Planet’s new mobile app helps you explore major cities like a pro", articleCoverImage: "Lonely Planet", articleSource: "36Kr", articleTime: "5min • 11:21"),
]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .None
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as? FriendReadTableViewCell
let info = data[indexPath.row]
cell?.profileView.image = UIImage(named: info.avatarImage)
cell?.friendName.text = info.sharedName
cell?.newsCaption.text = info.articleTitle
cell?.newsThumbnail.image = UIImage(named: info.articleCoverImage)
cell?.timeStamp.text = info.articleTime
cell?.pressName.text = info.articleSource
return cell!
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
let cells = tableView.visibleCells
for cell in cells {
cell.transform = CGAffineTransformMakeTranslation(0, view.bounds.height)
}
var index = 0.0
for cell in cells {
UIView.animateWithDuration(0.8, delay: (0.1) * index, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .CurveEaseOut, animations: {
cell.transform = CGAffineTransformIdentity
index += 1
}, completion: { _ in
index = 0.0
})
}
}
}
|
mit
|
f6877f4bb3a5c5c48caa90bc877fe74d
| 43.381579 | 285 | 0.665876 | 4.607923 | false | false | false | false |
donileo/RMessage
|
Sources/RMessage/RMessage.swift
|
1
|
5312
|
//
// RMessage.swift
// RMessage
//
// Created by Adonis Peralta on 8/2/18.
// Copyright © 2018 None. All rights reserved.
//
import Foundation
import HexColors
import UIKit
public class RMessage: UIView, RMessageAnimatorDelegate {
private(set) var spec: RMessageSpec
@IBOutlet private(set) var containerView: UIView!
@IBOutlet private(set) var contentView: UIView!
private(set) var leftView: UIView?
private(set) var rightView: UIView?
private(set) var backgroundView: UIView?
@IBOutlet private(set) var titleLabel: UILabel!
@IBOutlet private(set) var bodyLabel: UILabel!
@IBOutlet private var titleBodyVerticalSpacingConstraint: NSLayoutConstraint!
@IBOutlet private var titleLabelLeadingConstraint: NSLayoutConstraint!
@IBOutlet private var titleLabelTrailingConstraint: NSLayoutConstraint!
@IBOutlet private var bodyLabelLeadingConstraint: NSLayoutConstraint!
@IBOutlet private var bodyLabelTrailingConstraint: NSLayoutConstraint!
@IBOutlet private var contentViewTrailingConstraint: NSLayoutConstraint!
private var messageSpecIconImageViewSet = false
private var messageSpecBackgroundImageViewSet = false
// MARK: Instance Methods
init?(
spec: RMessageSpec, title: String, body: String?, leftView: UIView? = nil, rightView: UIView? = nil,
backgroundView: UIView? = nil
) {
self.spec = spec
self.leftView = leftView
self.rightView = rightView
self.backgroundView = backgroundView
super.init(frame: CGRect.zero)
loadNib()
titleLabel.text = title
bodyLabel.text = body
accessibilityIdentifier = String(describing: type(of: self))
setupComponents(withMessageSpec: spec)
setupDesign(withMessageSpec: spec, titleLabel: titleLabel, bodyLabel: bodyLabel)
}
public required init?(coder aDecoder: NSCoder) {
spec = DefaultRMessageSpec()
super.init(coder: aDecoder)
}
private func loadNib() {
Bundle(for: RMessage.self).loadNibNamed(String(describing: RMessage.self), owner: self, options: nil)
addSubview(containerView)
containerView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
containerView.topAnchor.constraint(equalTo: topAnchor),
containerView.bottomAnchor.constraint(equalTo: bottomAnchor),
containerView.leadingAnchor.constraint(equalTo: leadingAnchor),
containerView.trailingAnchor.constraint(equalTo: trailingAnchor)
])
}
private func setupComponents(withMessageSpec spec: RMessageSpec) {
if let image = spec.iconImage, leftView == nil {
leftView = iconImageView(withImage: image, imageTintColor: spec.iconImageTintColor, superview: self)
}
// Let any left view passed in programmatically override any icon image view initiated via a message spec
if let leftView = leftView {
setup(leftView: leftView, inSuperview: self)
}
if let rightView = rightView {
setup(rightView: rightView, inSuperview: self)
}
if let backgroundImage = spec.backgroundImage, backgroundView == nil {
backgroundView = backgroundImageView(withImage: backgroundImage, superview: self)
}
// Let any background view passed in programmatically override any background image view initiated
// via a message spec
if let backgroundView = backgroundView {
setup(backgroundView: backgroundView, inSuperview: self)
}
if spec.blurBackground {
setupBlurBackgroundView(inSuperview: self)
}
}
func setupLabelConstraintsToSizeToFit() {
assert(superview != nil, "RMessage instance must have a superview by this point!")
guard spec.titleBodyLabelsSizeToFit else {
return
}
NSLayoutConstraint.deactivate(
[
contentViewTrailingConstraint,
titleLabelLeadingConstraint, titleLabelTrailingConstraint,
bodyLabelLeadingConstraint, bodyLabelTrailingConstraint,
].compactMap { $0 }
)
titleLabelLeadingConstraint = titleLabel.leadingAnchor.constraint(greaterThanOrEqualTo: contentView.leadingAnchor)
titleLabelTrailingConstraint = titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: contentView.trailingAnchor)
bodyLabelLeadingConstraint = bodyLabel.leadingAnchor.constraint(greaterThanOrEqualTo: contentView.leadingAnchor)
bodyLabelTrailingConstraint = bodyLabel.trailingAnchor.constraint(lessThanOrEqualTo: contentView.trailingAnchor)
NSLayoutConstraint.activate(
[
titleLabelLeadingConstraint, titleLabelTrailingConstraint,
bodyLabelLeadingConstraint, bodyLabelTrailingConstraint,
]
)
}
// MARK: - Respond to Layout Changes
public override func layoutSubviews() {
super.layoutSubviews()
if titleLabel.text == nil || bodyLabel.text == nil { titleBodyVerticalSpacingConstraint.constant = 0 }
if let leftView = leftView, messageSpecIconImageViewSet, spec.iconImageRelativeCornerRadius > 0 {
leftView.layer.cornerRadius = spec.iconImageRelativeCornerRadius * leftView.bounds.size.width
}
if spec.cornerRadius >= 0 { layer.cornerRadius = spec.cornerRadius }
guard let superview = superview else { return }
setPreferredLayoutWidth(
forTitleLabel: titleLabel, bodyLabel: bodyLabel, inSuperview: superview,
sizingToFit: spec.titleBodyLabelsSizeToFit
)
}
}
|
mit
|
d7438bd802890a0b01d37c9d1a59b75e
| 32.613924 | 118 | 0.749953 | 5.217092 | false | false | false | false |
MatthiasHoldorf/swift-core-data-architecture
|
swift-core-data-architecture/swift-core-data-architecture/ViewController.swift
|
1
|
1007
|
//
// ViewController.swift
// swift-core-data-architecture
//
// Created by Matthias Holdorf on 20/11/15.
// Copyright © 2015 Matthias Holdorf. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let person = BLLContext.userService.createUser()
person.age = 25
person.firstName = "Matthias"
person.lastName = "Holdorf"
print(person)
let person1 = BLLContext.userService.createUser()
person1.age = 28
person1.firstName = "G"
person1.lastName = "Nasir"
let usersSortedByFirstName = BLLContext.userService.getAllUsersSortedByFirstName();
print("Users sorted by first name: ", usersSortedByFirstName.description)
let usersSortedByLastName = BLLContext.userService.getAllUsersSortedByLastName();
print("Users sorted by last name: ", usersSortedByLastName.description)
}
}
|
mit
|
d18a902857f6a6be536d2ae0be3737d2
| 28.617647 | 91 | 0.662028 | 4.511211 | false | false | false | false |
bitjammer/swift
|
test/ClangImporter/enum-error.swift
|
2
|
4309
|
// REQUIRES: OS=macosx
// RUN: %target-swift-frontend -DVALUE -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=VALUE
// RUN: %target-swift-frontend -DEMPTYCATCH -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=EMPTYCATCH
// RUN: %target-swift-frontend -DASQEXPR -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=ASQEXPR
// RUN: %target-swift-frontend -DASBANGEXPR -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=ASBANGEXPR
// RUN: %target-swift-frontend -DCATCHIS -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=CATCHIS
// RUN: %target-swift-frontend -DCATCHAS -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=CATCHAS
// RUN: %target-swift-frontend -DGENERICONLY -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=GENERICONLY
// RUN: %target-swift-frontend -emit-sil %s -import-objc-header %S/Inputs/enum-error.h -verify
// RUN: echo '#include "enum-error.h"' > %t.m
// RUN: %target-swift-ide-test -source-filename %s -print-header -header-to-print %S/Inputs/enum-error.h -import-objc-header %S/Inputs/enum-error.h -print-regular-comments --cc-args %target-cc-options -fsyntax-only %t.m -I %S/Inputs > %t.txt
// RUN: %FileCheck -check-prefix=HEADER %s < %t.txt
import Foundation
func testDropCode(other: OtherError) -> OtherError.Code {
return other.code
}
func testError() {
let testErrorNSError = NSError(domain: TestErrorDomain,
code: Int(TestError.TENone.rawValue),
userInfo: nil)
// Below are a number of test cases to make sure that various pattern and cast
// expression forms are sufficient in pulling in the _NSBridgedError
// conformance.
#if VALUE
// VALUE: TestError: _BridgedStoredNSError
let terr = getErr(); terr
#elseif EMPTYCATCH
// EMPTYCATCH: TestError: _BridgedStoredNSError
do {
throw TestError(.TENone)
} catch {}
#elseif ASQEXPR
// ASQEXPR: sil_witness_table shared [fragile] TestError: _BridgedStoredNSError module __ObjC
let wasTestError = testErrorNSError as? TestError; wasTestError
#elseif ASBANGEXPR
// ASBANGEXPR: sil_witness_table shared [fragile] TestError: _BridgedStoredNSError module __ObjC
let terr2 = testErrorNSError as! TestError; terr2
#elseif ISEXPR
// ISEXPR: sil_witness_table shared [fragile] TestError: _BridgedStoredNSError module __ObjC
if (testErrorNSError is TestError) {
print("true")
} else {
print("false")
}
#elseif CATCHIS
// CATCHIS: sil_witness_table shared [fragile] TestError: _BridgedStoredNSError module __ObjC
do {
throw TestError(.TETwo)
} catch is TestError {
} catch {}
#elseif CATCHAS
// CATCHAS: sil_witness_table shared [fragile] TestError: _BridgedStoredNSError module __ObjC
do {
throw TestError(.TETwo)
} catch let err as TestError {
err
} catch {}
#elseif GENERICONLY
// GENERICONLY: TestError: _BridgedStoredNSError
func dyncast<T, U>(_ x: T) -> U {
return x as! U
}
let _ : TestError = dyncast(testErrorNSError)
#else
// CHECK: sil_witness_table shared [fragile] TestError: _BridgedStoredNSError module __ObjC
let terr = getErr()
switch (terr) { case .TENone, .TEOne, .TETwo: break } // ok
switch (terr) { case .TENone, .TEOne: break }
// expected-error@-1 {{switch must be exhaustive, consider adding missing cases}}
let _ = TestError.Code(rawValue: 2)!
do {
throw TestError(.TEOne)
} catch is TestError {
} catch {}
#endif
}
// HEADER: struct TestError : _BridgedStoredNSError {
// HEADER: let _nsError: NSError
// HEADER: init(_nsError: NSError)
// HEADER: static var _nsErrorDomain: String { get }
// HEADER: enum Code : Int32, _ErrorCodeProtocol {
// HEADER: init?(rawValue: Int32)
// HEADER: var rawValue: Int32 { get }
// HEADER: typealias _ErrorType = TestError
// HEADER: case TENone
// HEADER: case TEOne
// HEADER: case TETwo
// HEADER: }
// HEADER: static var TENone: TestError.Code { get }
// HEADER: static var TEOne: TestError.Code { get }
// HEADER: static var TETwo: TestError.Code { get }
// HEADER: }
// HEADER: func getErr() -> TestError.Code
|
apache-2.0
|
72ef04c741a210d665aac1266d9c80ee
| 36.798246 | 241 | 0.695985 | 3.345497 | false | true | false | false |
richarddan/Flying-Swift
|
test-swift/ObjccBlog/models/BlogPost.swift
|
3
|
442
|
//
// BlogPost.swift
// test-swift
//
// Created by Su Wei on 14-7-16.
// Copyright (c) 2014年 OBJCC.COM. All rights reserved.
//
import Foundation
class BlogPost : NSObject {
init(title:String, img_url:String, post_url:String) {
self.title = title;
self.img_url = img_url;
self.post_url = post_url;
}
var title: String = "";
var img_url: String = "";
var post_url: String = "";
}
|
apache-2.0
|
e056d94933fea71e61b71ada37328873
| 18.173913 | 57 | 0.575 | 3.120567 | false | false | false | false |
materik/stubborn
|
Stubborn/Body/Body.swift
|
1
|
2325
|
extension Stubborn {
public class Body {
public typealias Key = String
public typealias Value = Any
public typealias InternalBody = [Key: Value]
internal private(set) var body: InternalBody
var data: Data {
guard let data = try? JSONSerialization.data(withJSONObject: self.body, options: []) else {
fatalError("Couldn't parse data")
}
return data
}
public required init(dictionaryLiteral elements: (Key, Value)...) {
var body: InternalBody = [:]
for (key, value) in elements {
body[key] = value
}
self.body = body
}
init() {
self.body = [:]
}
init(_ body: InternalBody) {
self.body = body
}
init(_ elements: [(Key, Value)]) {
var body: InternalBody = [:]
for (key, value) in elements {
body[key] = value
}
self.body = body
}
init?(_ body: InternalBody?) {
guard let body = body else {
return nil
}
self.body = body
}
func contains(_ body: Body) -> Bool {
for (key, that) in body.body {
guard let this = self.body[key], this == that else {
return false
}
}
return true
}
}
}
extension Stubborn.Body: ExpressibleByDictionaryLiteral {}
extension Stubborn.Body: Collection {
public typealias Index = DictionaryIndex<Key, Value>
public var startIndex: Index {
return self.body.startIndex
}
public var endIndex: Index {
return self.body.endIndex
}
public func index(after index: Index) -> Index {
return self.body.index(after: index)
}
public subscript(index: Index) -> (key: Key, value: Value) {
return self.body[index]
}
public subscript(index: Key) -> Value? {
return self.body[index]
}
}
fileprivate func == (lhs: Any, rhs: Any) -> Bool {
return String(describing: lhs) == String(describing: rhs)
}
|
mit
|
a0926e7d2e1aae20fccf5ad42c2d94a4
| 23.734043 | 103 | 0.487742 | 4.884454 | false | false | false | false |
malaonline/iOS
|
mala-ios/Common/Network/MAAPI.swift
|
1
|
9113
|
//
// MAAPI.swift
// mala-ios
//
// Created by 王新宇 on 15/03/2017.
// Copyright © 2017 Mala Online. All rights reserved.
//
import Foundation
import Moya
import Result
internal enum MAAPI {
// account
case sendSMS(phone: String)
case verifySMS(phone: String, code: String)
case userProtocolHTML()
// profile
case profileInfo(id: Int)
case parentInfo(id: Int)
case uploadAvatar(data: Data, profileId: Int)
case saveStudentName(name: String, parentId: Int)
case saveSchoolName(name: String, parentId: Int)
case userCoupons(onlyValid: Bool)
case getOrderList(page: Int)
case userNewMessageCount()
case userCollection(page: Int)
case addCollection(id: Int)
case removeCollection(id: Int)
// teacher
case loadTeachers(condition: JSON?, page: Int)
case loadTags()
case loadTeacherDetail(id: Int)
case evaluationStatus(subjectId: Int)
case getTeacherAvailableTime(teacherId: Int, schoolId: Int)
case getTeacherGradePrice(teacherId: Int, schoolId: Int)
case getConcreteTimeslots(id: Int, hours: Int, timeSlots: [Int])
// live-course
case getLiveClasses(schoolId: Int?, page: Int)
case getLiveClassDetail(id: Int)
// schedule&comment
case getStudentSchedule(onlyPassed: Bool)
case getCourseInfo(id: Int)
case createComment(comment: CommentModel)
case getCommentInfo(id: Int)
// payment&order
case createOrder(order: JSON)
case getChargeToken(channel: MalaPaymentChannel, id: Int)
case getOrderInfo(id: Int)
case cancelOrder(id: Int)
// study report
case userStudyReportOverview()
case userSubjectReport(id: Int)
// region
case loadRegions()
case getSchools(regionId: Int?, teacherId: Int?)
// exercise record
case exerciseMistakes(subject: Int?, page: Int)
}
extension MAAPI: TargetType {
public var baseURL: URL { return MABaseURL }
public var path: String {
switch self {
case .sendSMS, .verifySMS:
return "/sms"
case .profileInfo(let id), .uploadAvatar(_, let id):
return "/profiles/\(id)"
case .parentInfo(let id), .saveStudentName(_, let id), .saveSchoolName(_, let id):
return "/parents/\(id)"
case .userCoupons:
return "/coupons"
case .evaluationStatus(let id):
return "/subject/\(id)/record"
case .getStudentSchedule:
return "/timeslots"
case .getOrderList:
return "/orders"
case .userNewMessageCount:
return "/my_center"
case .userCollection, .addCollection:
return "/favorites"
case .removeCollection(let id):
return "/favorites/\(id)"
case .loadTeachers:
return "/teachers"
case .loadTeacherDetail(let id):
return "/teachers/\(id)"
case .getTeacherAvailableTime(let teacherId, _):
return "teachers/\(teacherId)/weeklytimeslots"
case .getTeacherGradePrice(let teacherId, let schoolId):
return "teacher/\(teacherId)/school/\(schoolId)/prices"
case .getLiveClasses:
return "/liveclasses"
case .getLiveClassDetail(let id):
return "/liveclasses/\(id)"
case .getCourseInfo(let id):
return "timeslots/\(id)"
case .getConcreteTimeslots:
return "concrete/timeslots"
case .createComment:
return "comments"
case .getCommentInfo(let id):
return "comments/\(id)"
case .createOrder:
return "/orders"
case .getChargeToken(_, let id):
return "/orders/\(id)"
case .getOrderInfo(let id), .cancelOrder(let id):
return "/orders/\(id)"
case .userProtocolHTML:
return "/policy"
case .userStudyReportOverview:
return "/study_report"
case .userSubjectReport(let id):
return "/study_report/\(id)"
case .loadRegions:
return "/regions"
case .getSchools:
return "/schools"
case .loadTags:
return "/tags"
case .exerciseMistakes:
return "/exercise"
}
}
public var method: Moya.Method {
switch self {
case .sendSMS, .verifySMS, .addCollection, .createComment, .createOrder:
return .post
case .uploadAvatar, .saveStudentName, .saveSchoolName, .getChargeToken:
return .patch
case .removeCollection, .cancelOrder:
return .delete
default:
return .get
}
}
public var parameters: [String : Any]? {
switch self {
case .sendSMS(let phone):
return ["action": "send", "phone": phone]
case .verifySMS(let phone, let code):
return ["action": "verify", "phone": phone, "code": code]
case .saveStudentName(let name, _):
return ["student_name": name]
case .saveSchoolName(let name, _):
return ["student_school_name": name]
case .userCoupons(let onlyValid):
return ["only_valid": String(onlyValid)]
case .getStudentSchedule(let onlyPassed):
return ["for_review": String(onlyPassed)]
case .getOrderList(let page), .userCollection(let page):
return ["page": page]
case .addCollection(let id):
return ["teacher": id]
case .loadTeachers(let condition, let page):
var params = condition ?? JSON()
params["page"] = page
if let city = MalaCurrentCity {
params["region"] = city.id
}
if let school = MalaCurrentSchool {
params["school"] = school.id
}
return params
case .getTeacherAvailableTime(_, let schoolId):
return ["school_id": schoolId]
case .getLiveClasses(let id, let page):
if let id = id {
return ["school": id, "page": page]
}else {
return ["page": page]
}
case .getConcreteTimeslots(let id, let hours, let timeSlots):
return [
"teacher": id,
"hours": hours,
"weekly_time_slots": timeSlots.map { String($0) }.joined(separator: " ")
]
case .createComment(let comment):
return [
"timeslot": comment.timeslot,
"score": comment.score,
"content": comment.content
]
case .createOrder(let order):
return order
case .getChargeToken(let channel, _):
return [
"action": PaymentMethod.Pay.rawValue,
"channel": channel.rawValue
]
case .getSchools(let regionId, let teacherId):
var params = JSON()
if let id = regionId {
params["region"] = id
} else if let region = MalaCurrentCity {
params["region"] = region.id
}
if let teacherId = teacherId {
params["teacher"] = teacherId
}
return params
case .exerciseMistakes(let subject, let page):
if let id = subject {
return ["subject": id, "page": page]
}else {
return ["page": page]
}
default:
return nil
}
}
public var parameterEncoding: ParameterEncoding {
switch self {
case .sendSMS, .verifySMS, .saveStudentName, .saveSchoolName, .addCollection, .createOrder, .getChargeToken:
return JSONEncoding.default
default:
return URLEncoding.default
}
}
public var sampleData: Data {
return "".data(using: String.Encoding.utf8)!
}
public var task: Task {
switch self {
case .uploadAvatar(let imageData, _):
return .upload(UploadType.multipart([MultipartFormData(provider: .data(imageData), name: "avatar", fileName: "avatar.jpg", mimeType: "image/jpeg")]))
default:
return .request
}
}
}
extension MAAPI: AccessTokenAuthorizable {
public var shouldAuthorize: Bool {
switch self {
case .sendSMS, .verifySMS, .getLiveClasses:
return false
case .loadTeacherDetail:
return MalaUserDefaults.isLogined ? true : false
default:
return true
}
}
}
extension MAAPI: HUDController {
public var shouldShowHUD: Bool {
switch self {
case .sendSMS, .verifySMS, .loadTeacherDetail, .evaluationStatus, .getTeacherAvailableTime, .getTeacherGradePrice, .getConcreteTimeslots,
.getLiveClassDetail, .getCourseInfo, .createComment, .getCommentInfo, .createOrder, .getChargeToken, .getOrderInfo,
.cancelOrder:
return true
default:
return false
}
}
}
|
mit
|
b898b17ad6add0b3f4618d315949fcb4
| 32.477941 | 161 | 0.571382 | 4.448461 | false | false | false | false |
sharplet/five-day-plan
|
Sources/FiveDayPlan/ViewModels/PlanDayDetailViewModel.swift
|
1
|
1699
|
import CoreData
struct PlanDayDetailViewModel {
let title: String
let provider: ScriptureProvider
let fetchController: NSFetchedResultsController<PlanChapter>
let store: Store
init(day: PlanDay, provider: ScriptureProvider = YouVersionScriptureProvider(), store: Store) {
self.title = day.name
self.provider = provider
self.fetchController = store.planDayController(for: day)
self.store = store
}
func performFetch() throws {
try fetchController.performFetch()
}
var numberOfSections: Int {
return fetchController.sections?.count ?? 0
}
func numberOfChapters(in section: Int) -> Int {
return fetchController.sections?[section].numberOfObjects ?? 0
}
subscript(indexPath: IndexPath) -> PlanChapter {
return fetchController.object(at: indexPath)
}
func openChapter(at indexPath: IndexPath, completionHandler: @escaping (Error?) -> Void) {
let chapter = Scripture.Chapter(self[indexPath])
provider.open(chapter) { success in
if success || TargetEnvironment.isSimulator {
self.markAsRead(at: indexPath, completionHandler: completionHandler)
} else {
completionHandler(nil)
}
}
}
private func markAsRead(at indexPath: IndexPath, completionHandler: @escaping (Error?) -> Void) {
let objectID: NSManagedObjectID
do {
let chapter = self[indexPath]
guard !chapter.isRead else { completionHandler(nil); return }
objectID = self[indexPath].objectID
}
store.performBackgroundTask(failingWith: completionHandler) { context in
let chapter = PlanChapter.fetch(by: objectID, in: context)
chapter.isRead = true
try context.save()
}
}
}
|
mit
|
e5d049bd0e17bf8f42ebfd32843ae8b9
| 28.293103 | 99 | 0.704532 | 4.530667 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.