repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
phimage/Natalie | Sources/natalie/Storyboard.swift | 1 | 1515 | //
// Storyboard.swift
// Natalie
//
// Created by Marcin Krzyzanowski on 07/08/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
class Storyboard: XMLObject {
let version: String
lazy var os: OS = {
guard let targetRuntime = self.xml["document"].element?.attribute(by: "targetRuntime")?.text else {
return OS.iOS
}
return OS(targetRuntime: targetRuntime)
}()
lazy var initialViewControllerClass: String? = {
if let initialViewControllerId = self.xml["document"].element?.attribute(by: "initialViewController")?.text,
let xmlVC = self.searchById(id: initialViewControllerId) {
let vc = ViewController(xml: xmlVC)
if let customClassName = vc.customClass {
return customClassName
}
if let controllerType = self.os.controllerType(for: vc.name) {
return controllerType
}
}
return nil
}()
lazy var scenes: [Scene] = {
guard let scenes = self.searchAll(root: self.xml, attributeKey: "sceneID") else {
return []
}
return scenes.map { Scene(xml: $0) }
}()
lazy var customModules: Set<String> = Set(self.scenes.filter { $0.customModule != nil && $0.customModuleProvider == nil }.map { $0.customModule! })
override init(xml: XMLIndexer) {
self.version = xml["document"].element!.attribute(by: "version")!.text
super.init(xml: xml)
}
}
| mit | 757c08b2a17b1adf08da9288e47ab3a3 | 29.28 | 151 | 0.601057 | 4.301136 | false | false | false | false |
yaoxinghuo/SwiftHash | SwiftHash/FileDropView.swift | 1 | 1811 | //
// FileDropView.swift
// Hashing Utility
//
// @author Terry E-mail: yaoxinghuo at 126 dot com
// @date 2015-3-30 11:26
// @description
//
import Foundation
import Cocoa
class FileDropView : NSView {
var delegate : FileDropViewDelegate?;
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
NSColor.white.set();
NSRectFill(dirtyRect);
}
override func awakeFromNib() {
register(forDraggedTypes: [NSFilenamesPboardType]);
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
return NSDragOperation.copy;
// let sourceDragMask = sender.draggingSourceOperationMask()
// let pboard = sender.draggingPasteboard()!
//
// if pboard.availableTypeFromArray([NSFilenamesPboardType]) == NSFilenamesPboardType {
// if sourceDragMask.rawValue & NSDragOperation.Generic.rawValue != 0 {
// return NSDragOperation.Generic
// }
// }
// return NSDragOperation.None
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
var pboard:NSPasteboard! = sender.draggingPasteboard()
if pboard != nil {
pboard = sender.draggingPasteboard()
if pboard.types!.contains(NSFilenamesPboardType) {
var files:[String] = pboard.propertyList(forType: NSFilenamesPboardType) as! [String]
if(files.count > 0) {
if(delegate != nil) {
delegate!.fileDropView(didDroppedFile: files[0]);
}
}
}
return true
}
return false
}
}
protocol FileDropViewDelegate {
func fileDropView(didDroppedFile filePath: String);
}
| apache-2.0 | 50c4ee802f058d73920aed1af0033bfb | 29.183333 | 101 | 0.600221 | 4.842246 | false | false | false | false |
urbanthings/urbanthings-sdk-apple | UrbanThingsAPI/Public/Response/MonitoredStopCall.swift | 1 | 2356 | //
// MonitoredStopCall.swift
// UrbanThingsAPI
//
// Created by Mark Woollard on 26/04/2016.
// Copyright © 2016 UrbanThings. All rights reserved.
//
import Foundation
/// Defines how arrival at stop is displayed
@objc public enum MonitoredStopCallDisplayFormat:Int {
/// Display time until arrival at stop
case Time = 0
/// Display distance from stop
case Distance = 1
}
/// `MonitoredStopCall` contains realtime information for a timetabled call at a transit stop.
public protocol MonitoredStopCall : StopCall {
/// The real time estimate of when this vehicle is expected to arrive at the stop.
var expectedArrivalTime:Date? { get }
/// The real time estimate of when this vehicle is expected to depart from the stop.
var expectedDepartureTime:Date? { get }
/// The real time estimate of the distance from the stop, along the route, that the vehicle is presently located at.
var distanceMetres:Int? { get }
/// A value to aid presentation; this indicates whether a time based or distance based display is most appropriate.
var masterDisplayFormat:MonitoredStopCallDisplayFormat { get }
/// Any additional Real Time information for this vehicle - the delay field is not relevant in this context.
var vehicleRTI:VehicleRTI { get }
/// A label representing the platform at which the vehicle is expected to call when it arrives at this stop if applicable.
var platform:String? { get }
/// A flag to indicate if the vehicle's trip has been cancelled. If this is set to TRUE any conflicting real time information should be discarded.
var isCancelled:Bool { get }
}
extension MonitoredStopCallDisplayFormat : JSONInitialization {
public init(required:Any?) throws {
guard let rawValue = required as? Int else {
throw UTAPIError(expected: Int.self, not: required, file:#file, function:#function, line:#line)
}
guard let value = MonitoredStopCallDisplayFormat(rawValue:rawValue) else {
throw UTAPIError(enumType: MonitoredStopCallDisplayFormat.self, invalidRawValue: rawValue, file:#file, function:#function, line:#line)
}
self = value
}
public init?(optional:Any?) throws {
guard optional != nil else {
return nil
}
try self.init(required: optional)
}
}
| apache-2.0 | ee2cbb0b991f25744909d510ca34fc98 | 41.818182 | 150 | 0.706157 | 4.460227 | false | false | false | false |
TLOpenSpring/TLTabBarSpring | Example/TLTabBarSpring/CustomController1.swift | 1 | 760 | //
// CustomController1.swift
// TLTabBarSpring
//
// Created by Andrew on 16/5/30.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import UIKit
class CustomController1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
initView()
}
func initView() -> Void {
let rect = CGRect(x: 100, y: 100, width: 200, height: 40)
let btn = UIButton(frame: rect)
btn.center=self.view.center
btn.setTitle("首页", for: UIControlState())
btn.setTitleColor(UIColor.red, for: UIControlState())
btn.titleLabel?.font=UIFont.boldSystemFont(ofSize: 28)
self.view.addSubview(btn)
}
}
| mit | 0ee80d56a90378d900a7341d4bbcd7ba | 24.1 | 65 | 0.620186 | 4.048387 | false | false | false | false |
feighter09/Cloud9 | Pods/Bond/Bond/Bond+Operators.swift | 14 | 2854 | //
// Bond+Operators.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// MARK: Operators
infix operator ->> { associativity left precedence 105 }
infix operator ->| { associativity left precedence 105 }
infix operator <->> { associativity left precedence 100 }
// MARK: Bind and fire
public func ->> <T>(left: Dynamic<T>, right: Bond<T>) {
left.bindTo(right)
}
public func ->> <T>(left: Dynamic<T>, right: Dynamic<T>) {
left ->> right.valueBond
}
public func ->> <T: Dynamical, U where T.DynamicType == U>(left: T, right: Bond<U>) {
left.designatedDynamic ->> right
}
public func ->> <T: Dynamical, U: Bondable where T.DynamicType == U.BondType>(left: T, right: U) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> <T, U: Bondable where U.BondType == T>(left: Dynamic<T>, right: U) {
left ->> right.designatedBond
}
// MARK: Bind only
public func ->| <T>(left: Dynamic<T>, right: Bond<T>) {
right.bind(left, fire: false)
}
public func ->| <T>(left: Dynamic<T>, right: T -> Void) -> Bond<T> {
let bond = Bond<T>(right)
bond.bind(left, fire: false)
return bond
}
public func ->| <T: Dynamical, U where T.DynamicType == U>(left: T, right: Bond<U>) {
left.designatedDynamic ->| right
}
public func ->| <T: Dynamical, U: Bondable where T.DynamicType == U.BondType>(left: T, right: U) {
left.designatedDynamic ->| right.designatedBond
}
public func ->| <T, U: Bondable where U.BondType == T>(left: Dynamic<T>, right: U) {
left ->| right.designatedBond
}
// MARK: Two way bind
public func <->> <T>(left: Dynamic<T>, right: Dynamic<T>) {
left.bindTo(right.valueBond, fire: true, strongly: true)
right.bindTo(left.valueBond, fire: false, strongly: false)
}
| lgpl-3.0 | c45e5a4d2edce7f86b0717c7d2c78b87 | 31.431818 | 98 | 0.691661 | 3.608091 | false | false | false | false |
yangboz/SwiftTutorials | CookieCrunch/CookieCrunch/Cookie.swift | 1 | 1451 | //
// Cookie.swift
// CookieCrunch
//
// Created by Matthijs on 19-06-14.
// Copyright (c) 2014 Razeware LLC. All rights reserved.
//
import SpriteKit
class Cookie: Printable, Hashable {
var column: Int
var row: Int
let cookieType: CookieType
var sprite: SKSpriteNode?
init(column: Int, row: Int, cookieType: CookieType) {
self.column = column
self.row = row
self.cookieType = cookieType
}
var description: String {
return "type:\(cookieType) square:(\(column),\(row))"
}
var hashValue: Int {
return row*10 + column
}
}
enum CookieType: Int, Printable {
case Unknown = 0, Croissant, Cupcake, Danish, Donut, Macaroon, SugarCookie
var spriteName: String {
let spriteNames = [
"Croissant",
"Cupcake",
"Danish",
"Donut",
"Macaroon",
"SugarCookie"]
return spriteNames[toRaw() - 1]
}
var highlightedSpriteName: String {
let highlightedSpriteNames = [
"Croissant-Highlighted",
"Cupcake-Highlighted",
"Danish-Highlighted",
"Donut-Highlighted",
"Macaroon-Highlighted",
"SugarCookie-Highlighted"]
return highlightedSpriteNames[toRaw() - 1]
}
static func random() -> CookieType {
return CookieType.fromRaw(Int(arc4random_uniform(6)) + 1)!
}
var description: String {
return spriteName
}
}
func ==(lhs: Cookie, rhs: Cookie) -> Bool {
return lhs.column == rhs.column && lhs.row == rhs.row
}
| mit | e86a3e706ab41d7eac745e302905237d | 19.728571 | 76 | 0.640937 | 3.636591 | false | false | false | false |
Isahkaren/Mememe | Mememe/Mememe/MemeDetailsViewController.swift | 1 | 1092 | //
// MemeDetailsViewController.swift
// Mememe
//
// Created by Isabela Karen de Oliveira Gomes on 08/12/16.
// Copyright © 2016 Isabela Karen de Oliveira Gomes. All rights reserved.
//
import UIKit
class MemeDetailsViewController: UIViewController {
class func newInstanceFromStoryboard() -> MemeDetailsViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MemeDetailsViewController") as! MemeDetailsViewController
return vc
}
@IBOutlet weak var imgDetails: UIImageView!
@IBOutlet weak var lblTextTop: UILabel!
@IBOutlet weak var lblTextBottom: UILabel!
var details: ImageSalve!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.imgDetails!.image = details.imageMeme
self.lblTextTop.text = details.textTop
self.lblTextBottom.text = details.textBottom
}
}
| mit | b83412ca4fd144dcd65f795938d71b18 | 25.609756 | 128 | 0.679193 | 4.892377 | false | false | false | false |
crazypoo/PTools | Pods/CollectionViewPagingLayout/Lib/CollectionViewPagingLayout.swift | 1 | 14603 | //
// CollectionViewPagingLayout.swift
// CollectionViewPagingLayout
//
// Created by Amir Khorsandi on 12/23/19.
// Copyright © 2019 Amir Khorsandi. All rights reserved.
//
import UIKit
public protocol CollectionViewPagingLayoutDelegate: AnyObject {
/// Calls when the current page changes
///
/// - Parameter layout: a reference to the layout class
/// - Parameter currentPage: the new current page index
func onCurrentPageChanged(layout: CollectionViewPagingLayout, currentPage: Int)
}
public extension CollectionViewPagingLayoutDelegate {
func onCurrentPageChanged(layout: CollectionViewPagingLayout, currentPage: Int) {}
}
public class CollectionViewPagingLayout: UICollectionViewLayout {
// MARK: Properties
/// Number of visible items at the same time
///
/// nil = no limit
public var numberOfVisibleItems: Int?
/// Constants that indicate the direction of scrolling for the layout.
public var scrollDirection: UICollectionView.ScrollDirection = .horizontal
/// See `ZPositionHandler` for details
public var zPositionHandler: ZPositionHandler = .both
/// Set `alpha` to zero when the cell is not loaded yet by collection view, enabling this prevents showing a cell before applying transforms but may cause flashing when you reload the data
public var transparentAttributeWhenCellNotLoaded: Bool = false
/// The animator for setting `contentOffset`
///
/// See `ViewAnimator` for details
public var defaultAnimator: ViewAnimator?
public private(set) var isAnimating: Bool = false
public weak var delegate: CollectionViewPagingLayoutDelegate?
override public var collectionViewContentSize: CGSize {
getContentSize()
}
/// Current page index
///
/// Use `setCurrentPage` to change it
public private(set) var currentPage: Int = 0 {
didSet {
delegate?.onCurrentPageChanged(layout: self, currentPage: currentPage)
}
}
private var currentScrollOffset: CGFloat {
let visibleRect = self.visibleRect
return scrollDirection == .horizontal ? (visibleRect.minX / max(visibleRect.width, 1)) : (visibleRect.minY / max(visibleRect.height, 1))
}
private var visibleRect: CGRect {
collectionView.map { CGRect(origin: $0.contentOffset, size: $0.bounds.size) } ?? .zero
}
private var numberOfItems: Int {
guard let numberOfSections = collectionView?.numberOfSections, numberOfSections > 0 else {
return 0
}
return (0..<numberOfSections)
.compactMap { collectionView?.numberOfItems(inSection: $0) }
.reduce(0, +)
}
private var currentPageCache: Int?
private var attributesCache: [(page: Int, attributes: UICollectionViewLayoutAttributes)]?
private var boundsObservation: NSKeyValueObservation?
private var lastBounds: CGRect?
private var currentViewAnimatorCancelable: ViewAnimatorCancelable?
private var originalIsUserInteractionEnabled: Bool?
private var contentOffsetObservation: NSKeyValueObservation?
// MARK: Public functions
public func setCurrentPage(_ page: Int,
animated: Bool = true,
animator: ViewAnimator? = nil,
completion: (() -> Void)? = nil) {
safelySetCurrentPage(page, animated: animated, animator: animator, completion: completion)
}
public func setCurrentPage(_ page: Int,
animated: Bool = true,
completion: (() -> Void)? = nil) {
safelySetCurrentPage(page, animated: animated, animator: defaultAnimator, completion: completion)
}
public func goToNextPage(animated: Bool = true,
animator: ViewAnimator? = nil,
completion: (() -> Void)? = nil) {
setCurrentPage(currentPage + 1, animated: animated, animator: animator, completion: completion)
}
public func goToPreviousPage(animated: Bool = true,
animator: ViewAnimator? = nil,
completion: (() -> Void)? = nil) {
setCurrentPage(currentPage - 1, animated: animated, animator: animator, completion: completion)
}
/// Calls `invalidateLayout` wrapped in `performBatchUpdates`
/// - Parameter invalidateOffset: change offset and revert it immediately
/// this fixes the zIndex issue more: https://stackoverflow.com/questions/12659301/uicollectionview-setlayoutanimated-not-preserving-zindex
public func invalidateLayoutInBatchUpdate(invalidateOffset: Bool = false) {
DispatchQueue.main.async { [weak self] in
if invalidateOffset,
let collectionView = self?.collectionView,
self?.isAnimating == false {
let original = collectionView.contentOffset
collectionView.contentOffset = .init(x: original.x + 1, y: original.y + 1)
collectionView.contentOffset = original
}
self?.collectionView?.performBatchUpdates({ [weak self] in
self?.invalidateLayout()
})
}
}
// MARK: UICollectionViewLayout
override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
if newBounds.size != visibleRect.size {
currentPageCache = currentPage
}
return true
}
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let currentScrollOffset = self.currentScrollOffset
let numberOfItems = self.numberOfItems
let attributesCount = numberOfVisibleItems ?? numberOfItems
let visibleRangeMid = attributesCount / 2
let currentPageIndex = Int(round(currentScrollOffset))
var initialStartIndex = currentPageIndex - visibleRangeMid
var initialEndIndex = currentPageIndex + visibleRangeMid
if attributesCount % 2 != 0 {
if currentPageIndex < visibleRangeMid {
initialStartIndex -= 1
} else {
initialEndIndex += 1
}
}
let startIndexOutOfBounds = max(0, -initialStartIndex)
let endIndexOutOfBounds = max(0, initialEndIndex - numberOfItems)
let startIndex = max(0, initialStartIndex - endIndexOutOfBounds)
let endIndex = min(numberOfItems, initialEndIndex + startIndexOutOfBounds)
var attributesArray: [(page: Int, attributes: UICollectionViewLayoutAttributes)] = []
var section = 0
var numberOfItemsInSection = collectionView?.numberOfItems(inSection: section) ?? 0
var numberOfItemsInPrevSections = 0
for index in startIndex..<endIndex {
var item = index - numberOfItemsInPrevSections
while item >= numberOfItemsInSection {
numberOfItemsInPrevSections += numberOfItemsInSection
section += 1
numberOfItemsInSection = collectionView?.numberOfItems(inSection: section) ?? 0
item = index - numberOfItemsInPrevSections
}
let cellAttributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: item, section: section))
let pageIndex = CGFloat(index)
let progress = pageIndex - currentScrollOffset
var zIndex = Int(-abs(round(progress)))
let cell = collectionView?.cellForItem(at: cellAttributes.indexPath)
if let cell = cell as? TransformableView {
cell.transform(progress: progress)
zIndex = cell.zPosition(progress: progress)
}
if cell == nil || cell is TransformableView {
cellAttributes.frame = visibleRect
if cell == nil, transparentAttributeWhenCellNotLoaded {
cellAttributes.alpha = 0
}
} else {
cellAttributes.frame = CGRect(origin: CGPoint(x: pageIndex * visibleRect.width, y: 0),
size: visibleRect.size)
}
// In some cases attribute.zIndex doesn't work so this is the work-around
if let cell = cell, [ZPositionHandler.both, .cellLayer].contains(zPositionHandler) {
cell.layer.zPosition = CGFloat(zIndex)
}
if [ZPositionHandler.both, .layoutAttribute].contains(zPositionHandler) {
cellAttributes.zIndex = zIndex
}
attributesArray.append((page: Int(pageIndex), attributes: cellAttributes))
}
attributesCache = attributesArray
addBoundsObserverIfNeeded()
return attributesArray.map(\.attributes)
}
override public func invalidateLayout() {
super.invalidateLayout()
if let page = currentPageCache {
setCurrentPage(page, animated: false)
currentPageCache = nil
} else {
updateCurrentPageIfNeeded()
}
}
// MARK: Private functions
private func updateCurrentPageIfNeeded() {
var currentPage: Int = 0
if let collectionView = collectionView {
let contentOffset = collectionView.contentOffset
let pageSize = scrollDirection == .horizontal ? collectionView.frame.width : collectionView.frame.height
let offset = scrollDirection == .horizontal ?
(contentOffset.x + collectionView.contentInset.left) :
(contentOffset.y + collectionView.contentInset.top)
if pageSize > 0 {
currentPage = Int(round(offset / pageSize))
}
}
if currentPage != self.currentPage, !isAnimating {
self.currentPage = currentPage
}
}
private func getContentSize() -> CGSize {
var safeAreaLeftRight: CGFloat = 0
var safeAreaTopBottom: CGFloat = 0
if #available(iOS 11, *) {
safeAreaLeftRight = (collectionView?.safeAreaInsets.left ?? 0) + (collectionView?.safeAreaInsets.right ?? 0)
safeAreaTopBottom = (collectionView?.safeAreaInsets.top ?? 0) + (collectionView?.safeAreaInsets.bottom ?? 0)
}
if scrollDirection == .horizontal {
return CGSize(width: CGFloat(numberOfItems) * visibleRect.width, height: visibleRect.height - safeAreaTopBottom)
} else {
return CGSize(width: visibleRect.width - safeAreaLeftRight, height: CGFloat(numberOfItems) * visibleRect.height)
}
}
private func safelySetCurrentPage(_ page: Int, animated: Bool, animator: ViewAnimator?, completion: (() -> Void)? = nil) {
if isAnimating {
currentViewAnimatorCancelable?.cancel()
isAnimating = false
if let isEnabled = originalIsUserInteractionEnabled {
collectionView?.isUserInteractionEnabled = isEnabled
}
}
let pageSize = scrollDirection == .horizontal ? visibleRect.width : visibleRect.height
let contentSize = scrollDirection == .horizontal ? collectionViewContentSize.width : collectionViewContentSize.height
let maxPossibleOffset = contentSize - pageSize
var offset = Double(pageSize) * Double(page)
offset = max(0, offset)
offset = min(offset, Double(maxPossibleOffset))
let contentOffset: CGPoint = scrollDirection == .horizontal ? CGPoint(x: offset, y: 0) : CGPoint(x: 0, y: offset)
if animated {
isAnimating = true
}
if animated, let animator = animator {
setContentOffset(with: animator, offset: contentOffset, completion: completion)
} else {
contentOffsetObservation = collectionView?.observe(\.contentOffset, options: [.new]) { [weak self] _, _ in
if self?.collectionView?.contentOffset == contentOffset {
self?.contentOffsetObservation = nil
DispatchQueue.main.async { [weak self] in
self?.invalidateLayoutInBatchUpdate()
self?.collectionView?.setContentOffset(contentOffset, animated: false)
self?.isAnimating = false
completion?()
}
}
}
collectionView?.setContentOffset(contentOffset, animated: animated)
}
// this is necessary when we want to set the current page without animation
if !animated, page != currentPage {
invalidateLayoutInBatchUpdate()
}
}
private func setContentOffset(with animator: ViewAnimator, offset: CGPoint, completion: (() -> Void)? = nil) {
guard let start = collectionView?.contentOffset else { return }
let x = offset.x - start.x
let y = offset.y - start.y
originalIsUserInteractionEnabled = collectionView?.isUserInteractionEnabled ?? true
collectionView?.isUserInteractionEnabled = false
currentViewAnimatorCancelable = animator.animate { [weak self] progress, finished in
guard let collectionView = self?.collectionView else { return }
collectionView.contentOffset = CGPoint(x: start.x + x * CGFloat(progress),
y: start.y + y * CGFloat(progress))
if finished {
self?.currentViewAnimatorCancelable = nil
self?.isAnimating = false
self?.collectionView?.isUserInteractionEnabled = self?.originalIsUserInteractionEnabled ?? true
self?.originalIsUserInteractionEnabled = nil
self?.collectionView?.delegate?.scrollViewDidEndScrollingAnimation?(collectionView)
self?.invalidateLayoutInBatchUpdate()
completion?()
}
}
}
}
extension CollectionViewPagingLayout {
private func addBoundsObserverIfNeeded() {
guard boundsObservation == nil else { return }
boundsObservation = collectionView?.observe(\.bounds, options: [.old, .new, .initial, .prior]) { [weak self] collectionView, _ in
guard collectionView.bounds.size != self?.lastBounds?.size else { return }
self?.lastBounds = collectionView.bounds
self?.invalidateLayoutInBatchUpdate(invalidateOffset: true)
}
}
}
| mit | 1a7a38fe37f3415f686cfa20965faa37 | 42.073746 | 192 | 0.627996 | 5.681712 | false | false | false | false |
sanjmhj/SMPopOver | popover/AppDelegate.swift | 1 | 6097 | //
// AppDelegate.swift
// popover
//
// Created by Sanjay Maharjan on 4/25/16.
// Copyright © 2016 Sanjay Maharjan. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.leapfrog.popover" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("popover", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 396ac81dde5d3ff1ae6f62beb33e9d76 | 53.918919 | 291 | 0.719652 | 5.889855 | false | false | false | false |
Sherlouk/monzo-vapor | Sources/Transaction.swift | 1 | 8008 | import Foundation
import JSON
public final class Transaction {
public enum DeclineReason: CustomStringConvertible {
case insufficientFunds
case cardInactive
case cardBlocked
case other
case unknown(String) // Future Proofing
init?(rawValue: String?) {
guard let rawValue = rawValue else { return nil }
switch rawValue {
case "INSUFFICIENT_FUNDS": self = .insufficientFunds
case "CARD_INACTIVE": self = .cardInactive
case "CARD_BLOCKED": self = .cardBlocked
case "OTHER": self = .other
default: self = .unknown(rawValue)
}
}
public var description: String {
switch self {
case .insufficientFunds: return "INSUFFICIENT_FUNDS"
case .cardInactive: return "CARD_INACTIVE"
case .cardBlocked: return "CARD_BLOCKED"
case .other: return "OTHER"
case .unknown(let string): return string
}
}
}
public enum Category: CustomStringConvertible {
case monzo // Topups
case general
case eatingOut
case expenses
case transport
case cash
case bills
case entertainment
case shopping
case holidays
case groceries
case other(String) // Future Proofing
init(rawValue: String) {
switch rawValue {
case "monzo", "mondo": self = .monzo
case "general": self = .general
case "eating_out": self = .eatingOut
case "expenses": self = .expenses
case "transport": self = .transport
case "cash": self = .cash
case "bills": self = .bills
case "entertainment": self = .entertainment
case "shopping": self = .shopping
case "holidays": self = .holidays
case "groceries": self = .groceries
default: self = .other(rawValue)
}
}
public var description: String {
switch self {
case .monzo: return "mondo"
case .general: return "general"
case .eatingOut: return "eating_out"
case .expenses: return "expenses"
case .transport: return "transport"
case .cash: return "cash"
case .bills: return "bills"
case .entertainment: return "entertainment"
case .shopping: return "shopping"
case .holidays: return "holidays"
case .groceries: return "groceries"
case .other(let string): return string
}
}
}
let account: Account
public let id: String
public let description: String
/// How much the transaction was for, this will often be a negative value for monies spent
public let amount: Amount
private let isLoad: Bool
/// Whether the transaction is an account topup
public var isTopup: Bool { return amount.amount > 0 && isLoad }
/// Whether the transaction is a refund
///
/// A transaction is treated as a refund, if the amount is positive and it's not a topup.
/// This includes transactions such as refunds, reversals or chargebacks
public var isRefund: Bool { return amount.amount > 0 && !isLoad }
/// Why, if at all, the transaction was declined
public let declineReason: DeclineReason?
/// Whether or not the transaction was declined. See `declineReason`.
public var declined: Bool { return declineReason != nil }
/// When the transaction was first created
public let created: Date
/// When the transaction was settled.
///
/// If nil, the transaction has been authorised but not completed
public let settled: Date?
/// User defined notes on the transaction
public let notes: String
/// Metadata is per-client and will not be shared with other clients
private(set) public var metadata: [String: String?]
/// Category for this transaction
public let category: Category
/// The ID of the merchant, fallback if merchant info isn't expanded
public let merchantId: String?
/// Information about the merchant
///
/// Will only be available if opted in when requesting transactions
public let merchant: Merchant?
init(account: Account, json: JSON) throws {
self.account = account
self.declineReason = DeclineReason(rawValue: try? json.value(forKey: "decline_reason"))
self.id = try json.value(forKey: "id")
self.description = try json.value(forKey: "description")
self.amount = try Amount(json.value(forKey: "amount"), currency: json.value(forKey: "currency"))
self.isLoad = try json.value(forKey: "is_load")
self.created = try json.value(forKey: "created")
self.notes = try json.value(forKey: "notes")
self.settled = try? json.value(forKey: "settled")
self.category = .init(rawValue: try json.value(forKey: "category"))
if let merchant = json["merchant"]?.string {
self.merchantId = merchant
self.merchant = nil
} else if let merchant: Merchant = try? Merchant(json: json["merchant"]) {
self.merchantId = merchant.id
self.merchant = merchant
} else {
self.merchantId = nil
self.merchant = nil
}
self.metadata = [String: String?]()
json["metadata"]?.object?.forEach {
self.metadata[$0.key] = $0.value.string
}
}
// MARK: - Metadata
/// Add an annotation on this key, if the value is nil then the key will be removed
public func setMetadata(_ value: String?, forKey key: String) throws {
metadata.updateValue(value, forKey: key)
try account.user.client.provider.deliver(.updateTransaction(self), user: account.user)
if value == nil {
metadata.removeValue(forKey: key)
}
}
/// Remove an annotation on this transaction
public func removeMetadata(forKey key: String) throws {
try setMetadata(nil, forKey: key)
}
// MARK: - Refresh
func refresh() {
// Update all values by making a new network request for the ID (the only constant)
// let rawTransaction = try account.user.client.provider.request(.transaction(account, id))
}
// MARK: - Attachments
public func registerAttachment(url: URL) throws -> Attachment {
let rawAttachment = try account.user.client.provider.request(.registerAttachment(self, url))
return try Attachment(transaction: self, json: rawAttachment)
}
public func deregisterAttachment(_ attachment: Attachment) throws {
try account.user.client.provider.deliver(.deregisterAttachment(attachment))
}
}
extension Transaction: CustomDebugStringConvertible {
public var debugDescription: String {
return "Transaction(\(id))"
}
}
extension Array where Element: Transaction {
mutating func loadMore(merchantInfo: Bool = true, limit: Int? = nil) throws -> Bool {
let transactions = sorted(by: { $0.created.timeIntervalSince1970 < $1.created.timeIntervalSince1970 })
guard let latest = transactions.last else { return false }
var options: [PaginationOptions] = [
.since(latest.id)
]
if let limit = limit {
options.append(.limit(limit))
}
let newTransactions = try latest.account.transactions(merchantInfo: merchantInfo, options: options)
guard let elements = newTransactions as? [Element], newTransactions.count > 0 else { return false }
append(contentsOf: elements)
return true
}
}
| mit | 82fc56ce752cae894cdeddeee07b3065 | 34.433628 | 110 | 0.598277 | 4.800959 | false | false | false | false |
gnachman/iTerm2 | sources/MarkCache.swift | 2 | 2309 | //
// MarkCache.swift
// iTerm2SharedARC
//
// Created by George Nachman on 1/27/22.
//
import Foundation
@objc(iTermMarkCacheReading)
protocol MarkCacheReading: AnyObject {
@objc
subscript(line: Int) -> iTermMarkProtocol? {
get
}
}
@objc(iTermMarkCache)
class MarkCache: NSObject, NSCopying, MarkCacheReading {
private var dict = [Int: iTermMarkProtocol]()
@objc private(set) var dirty = false
@objc lazy var sanitizingAdapter: MarkCache = {
return MarkCacheSanitizingAdapter(self)
}()
@objc
override init() {
super.init()
}
private init(dict: [Int: iTermMarkProtocol]) {
self.dict = dict.mapValues({ value in
value.doppelganger() as! iTermMarkProtocol
})
}
@objc(remove:)
func remove(line: Int) {
dirty = true
dict.removeValue(forKey: line)
}
@objc
func removeAll() {
dirty = true
dict = [:]
}
@objc
func copy(with zone: NSZone? = nil) -> Any {
dirty = false
return MarkCache(dict: dict)
}
@objc
subscript(line: Int) -> iTermMarkProtocol? {
get {
return dict[line]
}
set {
dirty = true
if let newValue = newValue {
dict[line] = newValue
} else {
dict.removeValue(forKey: line)
}
}
}
}
fileprivate class MarkCacheSanitizingAdapter: MarkCache {
private weak var source: MarkCache?
init(_ source: MarkCache) {
self.source = source
}
@objc(remove:)
override func remove(line: Int) {
fatalError()
}
@objc
override func removeAll() {
fatalError()
}
@objc
override func copy(with zone: NSZone? = nil) -> Any {
fatalError()
}
@objc
override subscript(line: Int) -> iTermMarkProtocol? {
get {
guard let source = source else {
return nil
}
let maybeMark: iTermMarkProtocol? = source[line]
guard let downcast = maybeMark as? iTermMark else {
return maybeMark
}
return downcast.doppelganger() as iTermMarkProtocol
}
set {
fatalError()
}
}
}
| gpl-2.0 | 2c3cd4c62255ae9979fa2c0c0820b562 | 20.183486 | 63 | 0.546124 | 4.182971 | false | false | false | false |
6ag/BaoKanIOS | BaoKanIOS/Classes/Module/Photo/Controller/JFPhotoViewController.swift | 1 | 7192 | //
// JFPhotoViewController.swift
// BaoKanIOS
//
// Created by jianfeng on 15/12/20.
// Copyright © 2015年 六阿哥. All rights reserved.
//
import UIKit
import SnapKit
class JFPhotoViewController: UIViewController {
/// 顶部标签按钮区域
@IBOutlet weak var topScrollView: UIScrollView!
/// 内容区域
@IBOutlet weak var contentScrollView: UIScrollView!
/// 标签按钮旁的加号按钮
@IBOutlet weak var addButton: UIButton!
// 顶部标签数组
fileprivate var topTitles: [[String : String]]?
// MARK: - 视图生命周期
override func viewDidLoad() {
super.viewDidLoad()
// 准备视图
prepareUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
}
// MARK: - 各种自定义方法
/**
准备视图
*/
fileprivate func prepareUI() {
// 添加内容
addContent()
}
/**
添加顶部标题栏和控制器
*/
fileprivate func addContent() {
self.topTitles = [
[
"classid" : "322",
"classname" : "图话网文"
],
[
"classid" : "434",
"classname": "精品封面"
],
[
"classid" : "366",
"classname": "游戏图库"
],
[
"classid" : "338",
"classname": "娱乐八卦"
],
[
"classid" : "354",
"classname": "社会百态"
],
[
"classid" : "357",
"classname": "旅游视野"
],
[
"classid" : "433",
"classname": "军事图秀"
]
]
// 布局用的左边距
var leftMargin: CGFloat = 0
for i in 0..<topTitles!.count {
let label = JFTopLabel()
label.text = topTitles![i]["classname"]
label.tag = i
label.scale = i == 0 ? 1.0 : 0.0
label.isUserInteractionEnabled = true
topScrollView.addSubview(label)
// 利用layout来自适应各种长度的label
label.snp.makeConstraints({ (make) in
make.left.equalTo(leftMargin + 15)
make.centerY.equalTo(topScrollView)
})
// 更新布局和左边距
topScrollView.layoutIfNeeded()
leftMargin = label.frame.maxX
// 添加标签点击手势
label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTappedTopLabel(_:))))
// 添加控制器
let photoVc = JFPhotoTableViewController()
addChildViewController(photoVc)
// 默认控制器
if i == 0 {
photoVc.classid = Int(topTitles![0]["classid"]!)
photoVc.view.frame = contentScrollView.bounds
contentScrollView.addSubview(photoVc.view)
}
}
// 内容区域滚动范围
contentScrollView.contentSize = CGSize(width: CGFloat(childViewControllers.count) * SCREEN_WIDTH, height: 0)
contentScrollView.isPagingEnabled = true
let lastLabel = topScrollView.subviews.last as! JFTopLabel
// 设置顶部标签区域滚动范围
topScrollView.contentSize = CGSize(width: leftMargin + lastLabel.frame.width, height: 0)
}
/**
顶部标签的点击事件
*/
@objc fileprivate func didTappedTopLabel(_ gesture: UITapGestureRecognizer) {
let titleLabel = gesture.view as! JFTopLabel
contentScrollView.setContentOffset(CGPoint(x: CGFloat(titleLabel.tag) * contentScrollView.frame.size.width, y: contentScrollView.contentOffset.y), animated: true)
}
}
// MARK: - scrollView代理方法
extension JFPhotoViewController: UIScrollViewDelegate {
// 滚动结束后触发 代码导致
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
// 滚动标题栏
let titleLabel = topScrollView.subviews[index]
var offsetX = titleLabel.center.x - topScrollView.frame.size.width * 0.5
let offsetMax = topScrollView.contentSize.width - topScrollView.frame.size.width
if offsetX < 0 {
offsetX = 0
} else if (offsetX > offsetMax) {
offsetX = offsetMax
}
// 滚动顶部标题
topScrollView.setContentOffset(CGPoint(x: offsetX, y: topScrollView.contentOffset.y), animated: true)
// 恢复其他label缩放
for i in 0..<topTitles!.count {
if i != index {
let topLabel = topScrollView.subviews[i] as! JFTopLabel
topLabel.scale = 0.0
}
}
}
// 滚动结束 手势导致
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollViewDidEndScrollingAnimation(scrollView)
}
// 正在滚动
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let value = abs(scrollView.contentOffset.x / scrollView.frame.width)
let leftIndex = Int(value)
let rightIndex = leftIndex + 1
let scaleRight = value - CGFloat(leftIndex)
let scaleLeft = 1 - scaleRight
let labelLeft = topScrollView.subviews[leftIndex] as! JFTopLabel
labelLeft.scale = CGFloat(scaleLeft)
if rightIndex < topScrollView.subviews.count {
let labelRight = topScrollView.subviews[rightIndex] as! JFTopLabel
labelRight.scale = CGFloat(scaleRight)
}
// 计算子控制器数组角标
var index = (value - CGFloat(Int(value))) > 0 ? Int(value) + 1 : Int(value)
// 控制器角标范围
if index > childViewControllers.count - 1 {
index = childViewControllers.count - 1
} else if index < 0 {
index = 0
}
// 获取需要展示的控制器
let photoVc = childViewControllers[index] as! JFPhotoTableViewController
// 如果已经展示则直接返回
if photoVc.view.superview != nil {
return
}
contentScrollView.addSubview(photoVc.view)
photoVc.view.frame = CGRect(x: CGFloat(index) * SCREEN_WIDTH, y: 0, width: SCREEN_WIDTH, height: contentScrollView.frame.height)
// 传递分类数据
photoVc.classid = Int(topTitles![index]["classid"]!)
}
}
| apache-2.0 | 8e1d3c10168afed35a9297f785a225a3 | 28.808036 | 170 | 0.543508 | 4.820939 | false | false | false | false |
huangboju/HYAlertController | HYAlertControllerDemo/ViewController.swift | 1 | 27435 | //
// ViewController.swift
// HYAlertControllerDemo
//
// Created by work on 2016/11/17.
// Copyright © 2016年 hyyy. All rights reserved.
//
import UIKit
struct Constant {
static let ScreenWidth: CGFloat = UIScreen.main.bounds.width
static let ScreenHeight: CGFloat = UIScreen.main.bounds.height
static let cellIdentifier: String = "cell"
static let cellHeight: CGFloat = 44
}
class ViewController: UIViewController {
lazy var tableView: UITableView = {
let tableView = UITableView(frame: CGRect(x: 0,
y: 0,
width: Constant.ScreenWidth,
height: Constant.ScreenHeight),
style: .plain)
tableView.backgroundColor = UIColor.white
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.cellIdentifier)
return tableView
}()
lazy var dataArray: [[String]] = [
[
"Alert style without title and message",
"Alert style with title",
"Alert style with message",
"Alert style with title and message",
"Alert style without action",
"Alert style with image action",
],
[
"Sheet style without title and message",
"Sheet style with title",
"Sheet style with message",
"Sheet style with title and message",
"Sheet style without action",
"Sheet style with image action",
],
[
"Share style with one line",
"Share style with multi line",
"Share style with title",
"Share style with message",
"Share style with title and message",
],
]
}
// MARK: - LifeCycle
extension ViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
title = "HYAlertControllerDemo"
tableView.dataSource = self
tableView.delegate = self
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func numberOfSections(in _: UITableView) -> Int {
return dataArray.count
}
func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: Constant.cellIdentifier)!
let rowArray: Array = dataArray[indexPath.section]
cell.textLabel?.text = rowArray[indexPath.row]
return cell
}
}
// MARK: - UITableViewDelegate
extension ViewController: UITableViewDelegate {
func tableView(_: UITableView, heightForHeaderInSection _: Int) -> CGFloat {
return 10
}
func tableView(_: UITableView, heightForFooterInSection _: Int) -> CGFloat {
return 0.1
}
func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
return Constant.cellHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let str = "show" + dataArray[indexPath.section][indexPath.row].camelcaseStr
print(str, "🍀")
perform(Selector(str))
}
}
extension String {
var camelcaseStr: String {
let source = self
if source.characters.contains(" ") {
let first = source.substring(to: source.index(source.startIndex, offsetBy: 1))
let cammel = source.capitalized.replacingOccurrences(of: " ", with: "")
let rest = String(cammel.characters.dropFirst())
return "\(first)\(rest)"
} else {
let first = source.lowercased().substring(to: source.index(source.startIndex, offsetBy: 1))
let rest = String(source.characters.dropFirst())
return "\(first)\(rest)"
}
}
}
// MARK: - AlertDemo
extension ViewController {
func showAlertStyleWithoutTitleAndMessage() {
let alertVC = HYAlertController(title: nil, message: nil, style: .alert)
let oneAction = HYAlertAction(title: "One Action", style: .normal, handler: { action in
print(action.title as Any)
})
let twoAction = HYAlertAction(title: "Two Action", style: .normal, handler: { action in
print(action.title as Any)
})
let threeAction = HYAlertAction(title: "Three Action", style: .destructive, handler: { action in
print(action.title as Any)
})
let cancelAction = HYAlertAction(title: "Cancel Action", style: .cancel, handler: { action in
print(action.title as Any)
})
alertVC.add(oneAction)
alertVC.add(twoAction)
alertVC.add(threeAction)
alertVC.add(cancelAction)
present(alertVC, animated: true, completion: nil)
}
func showAlertStyleWithTitle() {
let alertVC = HYAlertController(title: "Title", message: nil, style: .alert)
let oneAction = HYAlertAction(title: "One Action", style: .normal, handler: { action in
print(action.title as Any)
})
let twoAction = HYAlertAction(title: "Two Action", style: .normal, handler: { action in
print(action.title as Any)
})
let threeAction = HYAlertAction(title: "Three Action", style: .destructive, handler: { action in
print(action.title as Any)
})
let cancelAction = HYAlertAction(title: "Cancel Action", style: .cancel, handler: { action in
print(action.title as Any)
})
alertVC.add(oneAction)
alertVC.add(twoAction)
alertVC.add(threeAction)
alertVC.add(cancelAction)
present(alertVC, animated: true, completion: nil)
}
func showAlertStyleWithMessage() {
let alertVC = HYAlertController(title: nil, message: "Here you can describe the details of its title, and you can write here what you want to express.", style: .alert)
let oneAction = HYAlertAction(title: "One Action", style: .normal, handler: { action in
print(action.title as Any)
})
let twoAction = HYAlertAction(title: "Two Action", style: .normal, handler: { action in
print(action.title as Any)
})
let threeAction = HYAlertAction(title: "Three Action", style: .destructive, handler: { action in
print(action.title as Any)
})
let cancelAction = HYAlertAction(title: "Cancel Action", style: .cancel, handler: { action in
print(action.title as Any)
})
alertVC.add(oneAction)
alertVC.add(twoAction)
alertVC.add(threeAction)
alertVC.add(cancelAction)
present(alertVC, animated: true, completion: nil)
}
func showAlertStyleWithTitleAndMessage() {
let alertVC = HYAlertController(title: "Title", message: "Here you can describe the details of its title, and you can write here what you want to express.", style: .alert)
let oneAction = HYAlertAction(title: "One Action", style: .normal, handler: { action in
print(action.title as Any)
})
let twoAction = HYAlertAction(title: "Two Action", style: .normal, handler: { action in
print(action.title as Any)
})
let threeAction = HYAlertAction(title: "Three Action", style: .destructive, handler: { action in
print(action.title as Any)
})
let cancelAction = HYAlertAction(title: "Cancel Action", style: .cancel, handler: { action in
print(action.title as Any)
})
alertVC.add(oneAction)
alertVC.add(twoAction)
alertVC.add(threeAction)
alertVC.add(cancelAction)
present(alertVC, animated: true, completion: nil)
}
func showAlertStyleWithoutAction() {
let alertVC = HYAlertController(title: "Title", message: "Here you can describe the details of its title, and you can write here what you want to express.", style: .alert)
present(alertVC, animated: true, completion: nil)
}
func showAlertStyleWithImageAction() {
let alertVC = HYAlertController(title: "Title", message: "Here you can describe the details of its title, and you can write here what you want to express.", style: .alert)
let oneAction = HYAlertAction(title: "Facebook Action", image: UIImage(named: "facebook")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let twoAction = HYAlertAction(title: "Twitter Action", image: UIImage(named: "twitter")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let threeAction = HYAlertAction(title: "Snapchat Action", image: UIImage(named: "snapchat")!, style: .normal, handler: {
action in
print(action.title as Any)
})
alertVC.add(oneAction)
alertVC.add(twoAction)
alertVC.add(threeAction)
present(alertVC, animated: true, completion: nil)
}
}
// MARK: - SheetDemo
extension ViewController {
func showSheetStyleWithoutTitleAndMessage() {
let alertVC = HYAlertController(title: nil, message: nil, style: .actionSheet)
let oneAction = HYAlertAction(title: "One Action", style: .normal, handler: { action in
print(action.title as Any)
})
let twoAction = HYAlertAction(title: "Two Action", style: .normal, handler: { action in
print(action.title as Any)
})
let threeAction = HYAlertAction(title: "Three Action", style: .destructive, handler: { action in
print(action.title as Any)
})
let cancelAction = HYAlertAction(title: "Cancel Action", style: .cancel, handler: { action in
print(action.title as Any)
})
alertVC.add(oneAction)
alertVC.add(twoAction)
alertVC.add(threeAction)
alertVC.add(cancelAction)
present(alertVC, animated: true, completion: nil)
}
func showSheetStyleWithTitle() {
let alertVC: HYAlertController = HYAlertController(title: "Title", message: nil, style: .actionSheet)
let oneAction = HYAlertAction(title: "One Action", style: .normal, handler: { action in
print(action.title as Any)
})
let twoAction = HYAlertAction(title: "Two Action", style: .normal, handler: { action in
print(action.title as Any)
})
let threeAction = HYAlertAction(title: "Three Action", style: .destructive, handler: { action in
print(action.title as Any)
})
let cancelAction = HYAlertAction(title: "Cancel Action", style: .cancel, handler: { action in
print(action.title as Any)
})
alertVC.add(oneAction)
alertVC.add(twoAction)
alertVC.add(threeAction)
alertVC.add(cancelAction)
present(alertVC, animated: true, completion: nil)
}
func showSheetStyleWithMessage() {
let alertVC: HYAlertController = HYAlertController(title: nil, message: "Here you can describe the details of its title, and you can write here what you want to express.", style: .actionSheet)
let oneAction = HYAlertAction(title: "One Action", style: .normal, handler: { action in
print(action.title as Any)
})
let twoAction = HYAlertAction(title: "Two Action", style: .normal, handler: { action in
print(action.title as Any)
})
let threeAction = HYAlertAction(title: "Three Action", style: .destructive, handler: { action in
print(action.title as Any)
})
let cancelAction = HYAlertAction(title: "Cancel Action", style: .cancel, handler: { action in
print(action.title as Any)
})
alertVC.add(oneAction)
alertVC.add(twoAction)
alertVC.add(threeAction)
alertVC.add(cancelAction)
present(alertVC, animated: true, completion: nil)
}
func showSheetStyleWithTitleAndMessage() {
let alertVC = HYAlertController(title: "Title", message: "Here you can describe the details of its title, and you can write here what you want to express.", style: .actionSheet)
let oneAction = HYAlertAction(title: "One Action", style: .normal, handler: { action in
print(action.title as Any)
})
let twoAction = HYAlertAction(title: "Two Action", style: .normal, handler: { action in
print(action.title as Any)
})
let threeAction = HYAlertAction(title: "Three Action", style: .destructive, handler: { action in
print(action.title as Any)
})
let cancelAction = HYAlertAction(title: "Cancel Action", style: .cancel, handler: { action in
print(action.title as Any)
})
alertVC.add(oneAction)
alertVC.add(twoAction)
alertVC.add(threeAction)
alertVC.add(cancelAction)
present(alertVC, animated: true, completion: nil)
}
func showSheetStyleWithoutAction() {
let alertVC: HYAlertController = HYAlertController(title: "Title", message: "Here you can describe the details of its title, and you can write here what you want to express.", style: .actionSheet)
present(alertVC, animated: true, completion: nil)
}
func showSheetStyleWithImageAction() {
let alertVC: HYAlertController = HYAlertController(title: "Title", message: "Here you can describe the details of its title, and you can write here what you want to express.", style: .actionSheet)
let oneAction = HYAlertAction(title: "Facebook Action", image: UIImage(named: "facebook")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let twoAction = HYAlertAction(title: "Twitter Action", image: UIImage(named: "twitter")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let threeAction = HYAlertAction(title: "Snapchat Action", image: UIImage(named: "snapchat")!, style: .normal, handler: {
action in
print(action.title as Any)
})
alertVC.add(oneAction)
alertVC.add(twoAction)
alertVC.add(threeAction)
present(alertVC, animated: true, completion: nil)
}
}
// MARK: - ShareDemo
extension ViewController {
func showShareStyleWithOneLine() {
let alertVC: HYAlertController = HYAlertController(title: nil, message: nil, style: .shareSheet)
let oneAction = HYAlertAction(title: "Facebook", image: UIImage(named: "facebook")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let twoAction = HYAlertAction(title: "Twitter", image: UIImage(named: "twitter")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let threeAction = HYAlertAction(title: "Snapchat", image: UIImage(named: "snapchat")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let fourAction = HYAlertAction(title: "Instagram", image: UIImage(named: "instagram")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let fiveAction = HYAlertAction(title: "Pinterest", image: UIImage(named: "pinterest")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let sixAction = HYAlertAction(title: "Line", image: UIImage(named: "line")!, style: .normal, handler: {
action in
print(action.title as Any)
})
alertVC.addShare([oneAction, twoAction, threeAction, fourAction, fiveAction, sixAction])
present(alertVC, animated: true, completion: nil)
}
func showShareStyleWithMultiLine() {
let alertVC: HYAlertController = HYAlertController(title: nil, message: nil, style: .shareSheet)
let facebookAction = HYAlertAction(title: "Facebook", image: UIImage(named: "facebook")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let twitterAction = HYAlertAction(title: "Twitter", image: UIImage(named: "twitter")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let snapchatAction = HYAlertAction(title: "Snapchat", image: UIImage(named: "snapchat")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let instagramAction = HYAlertAction(title: "Instagram", image: UIImage(named: "instagram")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let pinterestAction = HYAlertAction(title: "Pinterest", image: UIImage(named: "pinterest")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let lineAction = HYAlertAction(title: "Line", image: UIImage(named: "line")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let wechatAction = HYAlertAction(title: "Wechat", image: UIImage(named: "wechat")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let momentAction = HYAlertAction(title: "Moment", image: UIImage(named: "wechat_moment")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let qqAction = HYAlertAction(title: "QQ", image: UIImage(named: "qq")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let qzoneAction = HYAlertAction(title: "Qzone", image: UIImage(named: "qzone")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let sinaAction = HYAlertAction(title: "Sina", image: UIImage(named: "sina")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let alipayAction = HYAlertAction(title: "Alipay", image: UIImage(named: "alipay")!, style: .normal, handler: {
action in
print(action.title as Any)
})
alertVC.addShare([facebookAction, twitterAction, snapchatAction, instagramAction, pinterestAction, lineAction])
alertVC.addShare([wechatAction, momentAction, qqAction, qzoneAction, sinaAction, alipayAction])
present(alertVC, animated: true, completion: nil)
}
func showShareStyleWithTitle() {
let alertVC: HYAlertController = HYAlertController(title: "Title", message: nil, style: .shareSheet)
let facebookAction = HYAlertAction(title: "Facebook", image: UIImage(named: "facebook")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let twitterAction = HYAlertAction(title: "Twitter", image: UIImage(named: "twitter")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let snapchatAction = HYAlertAction(title: "Snapchat", image: UIImage(named: "snapchat")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let instagramAction = HYAlertAction(title: "Instagram", image: UIImage(named: "instagram")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let pinterestAction = HYAlertAction(title: "Pinterest", image: UIImage(named: "pinterest")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let lineAction = HYAlertAction(title: "Line", image: UIImage(named: "line")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let wechatAction = HYAlertAction(title: "Wechat", image: UIImage(named: "wechat")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let momentAction = HYAlertAction(title: "Moment", image: UIImage(named: "wechat_moment")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let qqAction = HYAlertAction(title: "QQ", image: UIImage(named: "qq")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let qzoneAction = HYAlertAction(title: "Qzone", image: UIImage(named: "qzone")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let sinaAction = HYAlertAction(title: "Sina", image: UIImage(named: "sina")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let alipayAction = HYAlertAction(title: "Alipay", image: UIImage(named: "alipay")!, style: .normal, handler: {
action in
print(action.title as Any)
})
alertVC.addShare([facebookAction, twitterAction, snapchatAction, instagramAction, pinterestAction, lineAction])
alertVC.addShare([wechatAction, momentAction, qqAction, qzoneAction, sinaAction, alipayAction])
present(alertVC, animated: true, completion: nil)
}
func showShareStyleWithMessage() {
let alertVC: HYAlertController = HYAlertController(title: nil, message: "Here you can describe the details of its title, and you can write here what you want to express.", style: .shareSheet)
let facebookAction = HYAlertAction(title: "Facebook", image: UIImage(named: "facebook")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let twitterAction = HYAlertAction(title: "Twitter", image: UIImage(named: "twitter")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let snapchatAction = HYAlertAction(title: "Snapchat", image: UIImage(named: "snapchat")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let instagramAction = HYAlertAction(title: "Instagram", image: UIImage(named: "instagram")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let pinterestAction = HYAlertAction(title: "Pinterest", image: UIImage(named: "pinterest")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let lineAction = HYAlertAction(title: "Line", image: UIImage(named: "line")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let wechatAction = HYAlertAction(title: "Wechat", image: UIImage(named: "wechat")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let momentAction = HYAlertAction(title: "Moment", image: UIImage(named: "wechat_moment")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let qqAction = HYAlertAction(title: "QQ", image: UIImage(named: "qq")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let qzoneAction = HYAlertAction(title: "Qzone", image: UIImage(named: "qzone")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let sinaAction = HYAlertAction(title: "Sina", image: UIImage(named: "sina")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let alipayAction = HYAlertAction(title: "Alipay", image: UIImage(named: "alipay")!, style: .normal, handler: {
action in
print(action.title as Any)
})
alertVC.addShare([facebookAction, twitterAction, snapchatAction, instagramAction, pinterestAction, lineAction])
alertVC.addShare([wechatAction, momentAction, qqAction, qzoneAction, sinaAction, alipayAction])
present(alertVC, animated: true, completion: nil)
}
func showShareStyleWithTitleAndMessage() {
let alertVC = HYAlertController(title: "Title", message: "Here you can describe the details of its title, and you can write here what you want to express.", style: .shareSheet)
let facebookAction = HYAlertAction(title: "Facebook", image: UIImage(named: "facebook")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let twitterAction = HYAlertAction(title: "Twitter", image: UIImage(named: "twitter")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let snapchatAction = HYAlertAction(title: "Snapchat", image: UIImage(named: "snapchat")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let instagramAction = HYAlertAction(title: "Instagram", image: UIImage(named: "instagram")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let pinterestAction = HYAlertAction(title: "Pinterest", image: UIImage(named: "pinterest")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let lineAction = HYAlertAction(title: "Line", image: UIImage(named: "line")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let wechatAction = HYAlertAction(title: "Wechat", image: UIImage(named: "wechat")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let momentAction = HYAlertAction(title: "Moment", image: UIImage(named: "wechat_moment")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let qqAction = HYAlertAction(title: "QQ", image: UIImage(named: "qq")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let qzoneAction = HYAlertAction(title: "Qzone", image: UIImage(named: "qzone")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let sinaAction = HYAlertAction(title: "Sina", image: UIImage(named: "sina")!, style: .normal, handler: {
action in
print(action.title as Any)
})
let alipayAction = HYAlertAction(title: "Alipay", image: UIImage(named: "alipay")!, style: .normal, handler: {
action in
print(action.title as Any)
})
alertVC.addShare([facebookAction, twitterAction, snapchatAction, instagramAction, pinterestAction, lineAction])
alertVC.addShare([wechatAction, momentAction, qqAction, qzoneAction, sinaAction, alipayAction])
present(alertVC, animated: true, completion: nil)
}
}
| mit | 25f23bf9b0774316de489ce05c2458ed | 43.527597 | 204 | 0.614641 | 4.444823 | false | false | false | false |
papierschiff/swift-search-tree | Sources/SplayTree/SplayTree.swift | 1 | 12319 | //
// SplayTree.swift
// See /LICENSE for license information
// Short description: An implementation of a Splay tree
//
import Foundation
public protocol OrderStatisticTree {
associatedtype ValueType
func select(index: Int) -> ValueType?
func rank(value: ValueType) -> Int
}
/// Enum for the possible rotations in a splay tree
private enum SplayRotation {
case left
case right
case leftLeft
case rightRight
case leftRight
case rightLeft
}
/// SplayTree: An implementation of a Splay tree
/// - Note: Based on the splay tree idea from 1985 by Daniel Dominic Sleator
/// and Robert Endre Tarjan
/// - SeeAlso: [Paper](https://www.cs.cmu.edu/~sleator/papers/self-adjusting.pdf),
/// [ACM](http://dl.acm.org/citation.cfm?id=3835)
public struct SplayTree<Key: Comparable, Value> {
public typealias Element = (Key, Value)
internal var treeRoot: SplayNode<Key, Value>?
public var values: [Value] {
guard let safeRoot = treeRoot else {
return []
}
return safeRoot.values
}
public init() {
}
public subscript(atKey: Key) -> Value? {
get {
// root has no node
guard let safeRoot = treeRoot else {
return nil
}
return safeRoot.search(key: atKey)?.value
}
mutating set {
guard let safeNewValue = newValue else {
return
}
let newNode = SplayNode(key: atKey, value: safeNewValue)
guard let safeRoot = treeRoot else {
treeRoot = newNode
return
}
treeRoot = safeRoot.insert(node: newNode)
}
}
/// idea: rotate the node with 'forKey' to the root and than split and
/// concat the new trees
@discardableResult
public mutating func removeValue(forKey: Key) -> Value? {
guard let safeRoot = treeRoot else {
return nil
}
let searchedNode = safeRoot.search(key: forKey)
guard let nodeToDelete = searchedNode else {
// key doesn't exist
return nil
}
// nodeToDelete is root of the tree
if let safeLeft = nodeToDelete.left, let safeRight = nodeToDelete.right {
// node has two childs
safeLeft.parent = nil
safeRight.parent = nil
treeRoot = safeLeft.concatenate(with: safeRight)
} else if let safeLeft = nodeToDelete.left {
// only left exist -> left will be new root
safeLeft.parent = nil
treeRoot = safeLeft
} else if let safeRight = nodeToDelete.right {
// only right exist -> right will be new root
safeRight.parent = nil
treeRoot = safeRight
} else {
// no sub-trees)
treeRoot = nil
}
// update prev / next connections
if let safeNext = nodeToDelete.next {
safeNext.prev = nodeToDelete.prev
}
if let safePrev = nodeToDelete.prev {
safePrev.next = nodeToDelete.next
}
nodeToDelete.parent = nil
nodeToDelete.left = nil
nodeToDelete.right = nil
nodeToDelete.prev = nil
nodeToDelete.next = nil
return nodeToDelete.value
}
}
/// The important methods / logic for a Splay tree
/// - Complexity:
/// - concat: O(log n) amortized
/// - split: O(log n) amortized
/// - Note: There are 3 possibilities to use a Splay tree:
/// - "Normal" tree (with keys) is saved at one place (SplayTree)
/// - Tree with indexes as keys (SplayTreeCounted)
/// - Tree is not saved at one place (SplayNode)
/// Other nodes in the tree
extension SplayNodeProtocol {
var root: Self {
var root: Self? = self
while let temp = root!.parent {
root = temp
}
root!.splay()
return root!
}
var first: Self {
var first: Self? = self.root
while let temp = first!.left {
first = temp
}
first!.splay()
return first!
}
var last: Self {
var last: Self? = self.root
while let temp = last!.right {
last = temp
}
last!.splay()
return last!
}
// perhaps it is patter to rotate to the root and than traverse from top to
// bottom?
var values: [Self.ValueType] {
var firstNode: Self? = self.first
var list: [Self.ValueType] = [firstNode!.value]
while firstNode!.next != nil {
firstNode = firstNode!.next
list.append(firstNode!.value)
}
return list
}
}
// split and concatenate
extension SplayNodeProtocol {
/// concatenates the tree of node with other (noder is the first, other the last part)
/// - TODO: should we check first, if they are in the same tree?
/// - returns: the root of the new tree
@discardableResult
func concatenate(with: Self) -> Self {
//print("Type: \(node.dynamicType) - \(other.dynamicType)")
// returns the last element and automatic splays to the root
let lastNode: Self = self.last
// returns the first element and automatic splays to the root
let firstNode: Self = with.first//first(of: other)
lastNode.right = firstNode
// connect prev / next
lastNode.next = firstNode
firstNode.prev = lastNode
return lastNode
}
/// split the tree in two trees: one containing all elements less than or
/// equal to index and the other containing all elements greater than index
/// - returns: a node of the other tree of `node`: \
/// `before == true: self.prev` \
/// `before == false: self.next`
func split(before: Bool) -> Self? {
if self.isSingle {
return nil
}
self.splay()
// now left tree + root holds all elements <= self
// in right tree are all elements > self
/// TODO, fall abhandeln, wo left bzw. right nil ist
if before {
// split the left tree
let tempLeft: Self? = self.left
if tempLeft == nil {
return nil
}
self.left = nil
tempLeft!.parent = nil
// split prev / next
self.prev = nil
tempLeft!.last.next = nil
return tempLeft!.last
} else {
// split the right tree
let tempRight: Self? = self.right
if tempRight == nil {
return nil
}
self.right = nil
tempRight!.parent = nil
// split prev / next
self.next = nil
tempRight!.first.prev = nil
return tempRight!.first
}
}
}
extension SplayNodeProtocol {
func makeRoot() {
self.splay()
}
/// we don't habe to return the node, because after splay the node is the root
/// but it's easier to use
/// - returns: the root of the tree (`node`)
fileprivate func splay() {
// rotate the tree until node is root
while !self.isRoot {
if self.parent!.isRoot {
self.rotate(direction: self.isLeft ? .right: .left)
self.parent = nil
} else if self.parent!.isLeft && self.isLeft {
self.rotate(direction: .rightRight)
} else if self.parent!.isRight && self.isRight {
self.rotate(direction: .leftLeft)
} else if self.isLeft {
self.rotate(direction: .rightLeft)
} else if self.isRight {
self.rotate(direction: .leftRight)
}
}
}
/// rotates the tree
fileprivate func rotate(direction: SplayRotation) {
let parent: Self = self.parent!
if !self.parent!.isRoot {
let parentParent: Self = self.parent!.parent!
if parentParent.isRoot {
self.parent = nil
} else {
if parentParent.isLeft {
parentParent.parent!.left = self
} else {
parentParent.parent!.right = self
}
}
switch direction {
case .leftLeft:
parentParent.right = parent.left
parent.left = parentParent
case .rightRight:
parentParent.left = parent.right
parent.right = parentParent
case .leftRight:
parentParent.left = self.right
self.right = parentParent
case .rightLeft:
parentParent.right = self.left
self.left = parentParent
default: ()
}
}
switch direction {
case .leftLeft, .leftRight, .left:
parent.right = self.left
self.left = parent
case .rightRight, .rightLeft, .right:
parent.left = self.right
self.right = parent
}
}
}
/// tree-methods
/// * insert node in the tree
/// * search for key in the tree
extension SplayNodeKeyProtocol {
/// TODO: can this be shorter?
fileprivate func insert(node: Self) -> Self {
let safeRoot = self.root
var current: Self? = safeRoot
var parent: Self? = nil
var oldNext: Self? = nil
var oldPrev: Self? = nil
var isReplace: Bool = false
while let temp = current {
if temp.key == node.key {
// replace the subtrees of the new node
node.left = current!.left
node.right = current!.right
oldNext = current!.next
oldPrev = current!.prev
isReplace = true
break
}
parent = current
if node.key < temp.key {
current = temp.left
} else if node.key > temp.key {
current = temp.right
}
}
if isReplace == false {
if let safeParent = parent , safeParent.key < node.key {
oldNext = safeParent.next
oldPrev = safeParent
} else if let safeParent = parent , safeParent.key > node.key {
oldNext = safeParent
oldPrev = safeParent.prev
}
}
// connect with parent
node.parent = parent
if let safeParent = parent , safeParent.key < node.key {
safeParent.right = node
} else if let safeParent = parent , safeParent.key > node.key {
safeParent.left = node
}
// connect to the right
if let safeNext = oldNext {
node.next = safeNext
safeNext.prev = node
}
// connect to the left
if let safePev = oldPrev {
node.prev = safePev
safePev.next = node
}
node.splay()
return node
}
/// searchs in the tree for a node with the key 'key'
/// returns the found node if it exist, the found node is the new root
/// if the node doesn't exist, this method will return nil
func search(key: Self.KeyType) -> Self? {
let safeRoot = self.root
var current: Self? = safeRoot
while let temp = current {
if temp.key == key {
break
}
if key < temp.key {
current = temp.left
} else {
current = temp.right
}
}
guard let safeCurrent = current else {
// key doesn't exist
return nil
}
safeCurrent.makeRoot()
return safeCurrent
}
}
| bsd-2-clause | 5d1798be578d0d06dc78a0e01fad014d | 27.985882 | 90 | 0.515383 | 4.727168 | false | false | false | false |
ayushn21/SwiftLogger | SwiftLoggerTests/SwiftLoggerTests.swift | 1 | 768 | //
// SwiftLoggerTests.swift
// SwiftLogger
//
// Created by Ayush Newatia on 30/09/2015.
// Copyright © 2015 Ayush Newatia. All rights reserved.
//
import XCTest
@testable import SwiftLogger
class SwiftLoggerTests: XCTestCase {
func testSettingTheLogLevel() {
XCTAssertTrue(SwiftLogger.logLevel == .debug,
"The default log level should be debug")
SwiftLogger.logLevel = .verbose
XCTAssertTrue(SwiftLogger.logLevel == .verbose,
"The log level should correctly change to verbose")
}
func testSettingTheDateFormat() {
SwiftLogger.dateFormat = "HH:mm"
XCTAssertTrue(SwiftLogger.dateFormat == "HH:mm",
"The date format should be set to the new value")
}
}
| mit | 4c4a9fead48b7f817b933978a0ca23c5 | 25.448276 | 63 | 0.653194 | 4.168478 | false | true | false | false |
dhanvi/firefox-ios | Client/Frontend/Browser/BrowserLocationView.swift | 2 | 11911 | /* 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 Shared
import SnapKit
protocol BrowserLocationViewDelegate {
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView)
func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView)
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView)
/// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) -> Bool
func browserLocationViewLocationAccessibilityActions(browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]?
}
struct BrowserLocationViewUX {
static let HostFontColor = UIColor.blackColor()
static let BaseURLFontColor = UIColor.grayColor()
static let BaseURLPitch = 0.75
static let HostPitch = 1.0
static let LocationContentInset = 8
}
class BrowserLocationView: UIView {
var delegate: BrowserLocationViewDelegate?
var longPressRecognizer: UILongPressGestureRecognizer!
var tapRecognizer: UITapGestureRecognizer!
dynamic var baseURLFontColor: UIColor = BrowserLocationViewUX.BaseURLFontColor {
didSet { updateTextWithURL() }
}
dynamic var hostFontColor: UIColor = BrowserLocationViewUX.HostFontColor {
didSet { updateTextWithURL() }
}
var url: NSURL? {
didSet {
let wasHidden = lockImageView.hidden
lockImageView.hidden = url?.scheme != "https"
if wasHidden != lockImageView.hidden {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
}
updateTextWithURL()
setNeedsUpdateConstraints()
}
}
var readerModeState: ReaderModeState {
get {
return readerModeButton.readerModeState
}
set (newReaderModeState) {
if newReaderModeState != self.readerModeButton.readerModeState {
let wasHidden = readerModeButton.hidden
self.readerModeButton.readerModeState = newReaderModeState
readerModeButton.hidden = (newReaderModeState == ReaderModeState.Unavailable)
if wasHidden != readerModeButton.hidden {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
}
UIView.animateWithDuration(0.1, animations: { () -> Void in
if newReaderModeState == ReaderModeState.Unavailable {
self.readerModeButton.alpha = 0.0
} else {
self.readerModeButton.alpha = 1.0
}
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
})
}
}
}
lazy var placeholder: NSAttributedString = {
let placeholderText = NSLocalizedString("Search or enter address", comment: "The text shown in the URL bar on about:home")
return NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.grayColor()])
}()
lazy var urlTextField: UITextField = {
let urlTextField = DisplayTextField()
self.longPressRecognizer.delegate = self
urlTextField.addGestureRecognizer(self.longPressRecognizer)
self.tapRecognizer.delegate = self
urlTextField.addGestureRecognizer(self.tapRecognizer)
// Prevent the field from compressing the toolbar buttons on the 4S in landscape.
urlTextField.setContentCompressionResistancePriority(250, forAxis: UILayoutConstraintAxis.Horizontal)
urlTextField.attributedPlaceholder = self.placeholder
urlTextField.accessibilityIdentifier = "url"
urlTextField.accessibilityActionsSource = self
urlTextField.font = UIConstants.DefaultMediumFont
return urlTextField
}()
private lazy var lockImageView: UIImageView = {
let lockImageView = UIImageView(image: UIImage(named: "lock_verified.png"))
lockImageView.hidden = true
lockImageView.isAccessibilityElement = true
lockImageView.contentMode = UIViewContentMode.Center
lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "Accessibility label for the lock icon, which is only present if the connection is secure")
return lockImageView
}()
private lazy var readerModeButton: ReaderModeButton = {
let readerModeButton = ReaderModeButton(frame: CGRectZero)
readerModeButton.hidden = true
readerModeButton.addTarget(self, action: "SELtapReaderModeButton", forControlEvents: .TouchUpInside)
readerModeButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "SELlongPressReaderModeButton:"))
readerModeButton.isAccessibilityElement = true
readerModeButton.accessibilityLabel = NSLocalizedString("Reader View", comment: "Accessibility label for the Reader View button")
readerModeButton.accessibilityCustomActions = [UIAccessibilityCustomAction(name: NSLocalizedString("Add to Reading List", comment: "Accessibility label for action adding current page to reading list."), target: self, selector: "SELreaderModeCustomAction")]
return readerModeButton
}()
override init(frame: CGRect) {
super.init(frame: frame)
longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "SELlongPressLocation:")
tapRecognizer = UITapGestureRecognizer(target: self, action: "SELtapLocation:")
self.backgroundColor = UIColor.whiteColor()
addSubview(urlTextField)
addSubview(lockImageView)
addSubview(readerModeButton)
lockImageView.snp_makeConstraints { make in
make.leading.centerY.equalTo(self)
make.width.equalTo(self.lockImageView.intrinsicContentSize().width + CGFloat(BrowserLocationViewUX.LocationContentInset * 2))
}
readerModeButton.snp_makeConstraints { make in
make.trailing.centerY.equalTo(self)
make.width.equalTo(self.readerModeButton.intrinsicContentSize().width + CGFloat(BrowserLocationViewUX.LocationContentInset * 2))
}
}
override var accessibilityElements: [AnyObject]! {
get {
return [lockImageView, urlTextField, readerModeButton].filter { !$0.hidden }
}
set {
super.accessibilityElements = newValue
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
urlTextField.snp_remakeConstraints { make in
make.top.bottom.equalTo(self)
if lockImageView.hidden {
make.leading.equalTo(self).offset(BrowserLocationViewUX.LocationContentInset)
} else {
make.leading.equalTo(self.lockImageView.snp_trailing)
}
if readerModeButton.hidden {
make.trailing.equalTo(self).offset(-BrowserLocationViewUX.LocationContentInset)
} else {
make.trailing.equalTo(self.readerModeButton.snp_leading)
}
}
super.updateConstraints()
}
func SELtapReaderModeButton() {
delegate?.browserLocationViewDidTapReaderMode(self)
}
func SELlongPressReaderModeButton(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
delegate?.browserLocationViewDidLongPressReaderMode(self)
}
}
func SELlongPressLocation(recognizer: UITapGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
delegate?.browserLocationViewDidLongPressLocation(self)
}
}
func SELtapLocation(recognizer: UITapGestureRecognizer) {
delegate?.browserLocationViewDidTapLocation(self)
}
func SELreaderModeCustomAction() -> Bool {
return delegate?.browserLocationViewDidLongPressReaderMode(self) ?? false
}
private func updateTextWithURL() {
if let httplessURL = url?.absoluteStringWithoutHTTPScheme(), let baseDomain = url?.baseDomain() {
// Highlight the base domain of the current URL.
let attributedString = NSMutableAttributedString(string: httplessURL)
let nsRange = NSMakeRange(0, httplessURL.characters.count)
attributedString.addAttribute(NSForegroundColorAttributeName, value: baseURLFontColor, range: nsRange)
attributedString.colorSubstring(baseDomain, withColor: hostFontColor)
attributedString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(double: BrowserLocationViewUX.BaseURLPitch), range: nsRange)
attributedString.pitchSubstring(baseDomain, withPitch: BrowserLocationViewUX.HostPitch)
urlTextField.attributedText = attributedString
} else {
// If we're unable to highlight the domain, just use the URL as is.
urlTextField.text = url?.absoluteString
}
}
}
extension BrowserLocationView: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// If the longPressRecognizer is active, fail all other recognizers to avoid conflicts.
return gestureRecognizer == longPressRecognizer
}
}
extension BrowserLocationView: AccessibilityActionsSource {
func accessibilityCustomActionsForView(view: UIView) -> [UIAccessibilityCustomAction]? {
if view === urlTextField {
return delegate?.browserLocationViewLocationAccessibilityActions(self)
}
return nil
}
}
private class ReaderModeButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setImage(UIImage(named: "reader.png"), forState: UIControlState.Normal)
setImage(UIImage(named: "reader_active.png"), forState: UIControlState.Selected)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var _readerModeState: ReaderModeState = ReaderModeState.Unavailable
var readerModeState: ReaderModeState {
get {
return _readerModeState;
}
set (newReaderModeState) {
_readerModeState = newReaderModeState
switch _readerModeState {
case .Available:
self.enabled = true
self.selected = false
case .Unavailable:
self.enabled = false
self.selected = false
case .Active:
self.enabled = true
self.selected = true
}
}
}
}
private class DisplayTextField: UITextField {
weak var accessibilityActionsSource: AccessibilityActionsSource?
override var accessibilityCustomActions: [UIAccessibilityCustomAction]? {
get {
return accessibilityActionsSource?.accessibilityCustomActionsForView(self)
}
set {
super.accessibilityCustomActions = newValue
}
}
private override func canBecomeFirstResponder() -> Bool {
return false
}
}
| mpl-2.0 | 44edd6c5ba28bb76dc55a405a6bb9487 | 40.646853 | 264 | 0.691126 | 6.152376 | false | false | false | false |
exponent/exponent | packages/expo-modules-core/ios/Swift/EventListener.swift | 2 | 1677 | /**
Represents a listener for the specific event.
*/
internal struct EventListener: AnyDefinition {
let name: EventName
let call: (Any?, Any?) throws -> Void
/**
Listener initializer for events without sender and payload.
*/
init(_ name: EventName, _ listener: @escaping () -> Void) {
self.name = name
self.call = { _, _ in listener() }
}
/**
Listener initializer for events with no payload.
*/
init<Sender>(_ name: EventName, _ listener: @escaping (Sender) -> Void) {
self.name = name
self.call = { sender, _ in
guard let sender = sender as? Sender else {
throw InvalidSenderTypeException((eventName: name, senderType: Sender.self))
}
listener(sender)
}
}
/**
Listener initializer for events that specify the payload.
*/
init<Sender, PayloadType>(_ name: EventName, _ listener: @escaping (Sender, PayloadType?) -> Void) {
self.name = name
self.call = { sender, payload in
guard let sender = sender as? Sender else {
throw InvalidSenderTypeException((eventName: name, senderType: Sender.self))
}
listener(sender, payload as? PayloadType)
}
}
}
class InvalidSenderTypeException: GenericException<(eventName: EventName, senderType: Any.Type)> {
override var reason: String {
"Sender for event '\(param.eventName)' must be of type \(param.senderType)"
}
}
public enum EventName: Equatable {
case custom(_ name: String)
// MARK: Module lifecycle
case moduleCreate
case moduleDestroy
case appContextDestroys
// MARK: App (UIApplication) lifecycle
case appEntersForeground
case appBecomesActive
case appEntersBackground
}
| bsd-3-clause | 56ae97abe7fd868b156b4d1a91049972 | 25.619048 | 102 | 0.670841 | 4.110294 | false | false | false | false |
wupingzj/YangRepoApple | QiuTuiJian/QiuTuiJian/BusinessPerson.swift | 1 | 1003 | //
// Mobile.swift
// QiuTuiJian
//
// Created by Ping on 27/07/2014.
// Copyright (c) 2014 Yang Ltd. All rights reserved.
//
// BusinessPerson
import Foundation
import CoreData
public class BusinessPerson: Person {
@NSManaged
public var anonymous: Bool
@NSManaged
public var businessEntity: BusinessEntity
public override func awakeFromInsert() {
super.awakeFromInsert()
self.uuid = NSUUID().UUIDString
self.createdDate = NSDate()
}
public class func createEntity() -> BusinessPerson {
let ctx: NSManagedObjectContext = DataService.sharedInstance.ctx
let ed: NSEntityDescription = NSEntityDescription.entityForName("BusinessPerson", inManagedObjectContext: ctx)!
let newEntity = BusinessPerson(entity: ed, insertIntoManagedObjectContext: ctx)
return newEntity
}
public func getNormalizedName() -> String {
return self.firstName + " " + self.lastName
}
} | gpl-2.0 | a87a96c4685e7998cff34f7080a25825 | 25.421053 | 119 | 0.667996 | 4.965347 | false | false | false | false |
leo-lp/LPIM | LPIM/Classes/SessionList/LPSessionListViewController.swift | 1 | 11975 | //
// LPSessionListViewController.swift
// LPIM
//
// Created by lipeng on 2017/6/19.
// Copyright © 2017年 lipeng. All rights reserved.
//
import UIKit
import NIMSDK
private let kSessionListTitle: String = "LPIM"
class LPSessionListViewController: LPKSessionListViewController {
lazy var emptyTipLabel: UILabel = {
let lbl = UILabel()
lbl.text = "还没有会话,在通讯录中找个人聊聊吧"
lbl.sizeToFit()
return lbl
}()
lazy fileprivate var titleLabel: UILabel = {
let lbl = UILabel(frame: .zero)
lbl.text = kSessionListTitle
lbl.font = UIFont.boldSystemFont(ofSize: 15.0)
lbl.sizeToFit()
return lbl
}()
lazy fileprivate var header: LPListHeader = {
let header = LPListHeader(frame: CGRect(x: 0, y: 0, width: self.view.lp_width, height: 0))
header.autoresizingMask = .flexibleWidth
return header
}()
lazy fileprivate var supportsForceTouch: Bool = false
lazy fileprivate var previews: [Int: UIViewControllerPreviewing] = [:]
deinit {
NIMSDK.shared().subscribeManager.remove(self)
log.warning("release memory.")
}
override func viewDidLoad() {
super.viewDidLoad()
autoRemoveRemoteSession = LPBundleSetting.shared.autoRemoveRemoteSession()
if #available(iOS 9.0, *) {
supportsForceTouch = traitCollection.forceTouchCapability == UIForceTouchCapability.available
} else {
supportsForceTouch = false
}
NIMSDK.shared().subscribeManager.add(self)
header.delegate = self
view.addSubview(header)
emptyTipLabel.isHidden = recentSessions.count != 0
view.addSubview(emptyTipLabel)
let uid = NIMSDK.shared().loginManager.currentAccount()
navigationItem.titleView = titleView(uid)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
titleLabel.sizeToFit()
titleLabel.lp_centerX = (navigationItem.titleView?.lp_width ?? view.lp_width) / 2.0
tableView.lp_top = header.lp_height
tableView.lp_height = view.lp_height - tableView.lp_top
header.lp_bottom = tableView.lp_top + tableView.contentInset.top
emptyTipLabel.lp_centerX = view.lp_width / 2.0
emptyTipLabel.lp_centerY = tableView.lp_height / 2.0
}
override func refresh(_ reload: Bool) {
super.refresh(reload)
emptyTipLabel.isHidden = recentSessions.count != 0
}
override func selectedRecent(at indexPath: IndexPath, recent: NIMRecentSession) {
// NTESSessionViewController *vc = [[NTESSessionViewController alloc] initWithSession:recent.session];
// [self.navigationController pushViewController:vc animated:YES];
}
override func selectedAvatar(at indexPath: IndexPath, recent: NIMRecentSession) {
// if (recent.session.sessionType == NIMSessionTypeP2P) {
// NTESPersonalCardViewController *vc = [[NTESPersonalCardViewController alloc] initWithUserId:recent.session.sessionId];
// [self.navigationController pushViewController:vc animated:YES];
// }
}
override func deleteRecent(at indexPath: IndexPath, recent: NIMRecentSession) {
super.deleteRecent(at: indexPath, recent: recent)
}
override func nameForRecentSession(_ recent: NIMRecentSession) -> String? {
if let session = recent.session, session.sessionId == NIMSDK.shared().loginManager.currentAccount() {
return "我的电脑"
}
return super.nameForRecentSession(recent)
}
override func contentForRecentSession(_ recent: NIMRecentSession) -> NSAttributedString {
var content: NSAttributedString
if let lastMsg = recent.lastMessage, lastMsg.messageType == .custom {
var text = "[未知消息]"
if let object = lastMsg.messageObject as? NIMCustomObject {
if object.attachment is LPSnapchatAttachment {
text = "[阅后即焚]"
} else if object.attachment is LPJanKenPonAttachment {
text = "[猜拳]"
} else if object.attachment is LPChartletAttachment {
text = "[贴图]"
} else if object.attachment is LPWhiteboardAttachment {
text = "[白板]"
} else {
text = "[未知消息]"
}
}
if recent.session?.sessionType == .P2P, let from = lastMsg.from {
if let nickName = LPSessionUtil.showNick(from, session: lastMsg.session), nickName.characters.count > 0 {
text = nickName.appendingFormat(" : %@", text)
} else {
text = ""
}
}
content = NSAttributedString(string: text)
} else {
content = super.contentForRecentSession(recent)
}
let attContent = NSMutableAttributedString(attributedString: content)
checkNeedAtTip(recent, content: attContent)
checkOnlineState(recent, content: attContent)
return attContent
}
}
extension LPSessionListViewController: NIMEventSubscribeManagerDelegate, UIViewControllerPreviewingDelegate, LPListHeaderDelegate {
// MARK: - NIMLoginManagerDelegate
override func onLogin(_ step: NIMLoginStep) {
super.onLogin(step)
switch step {
case .linkFailed:
titleLabel.text = kSessionListTitle + "(未连接)"
case .linking:
titleLabel.text = kSessionListTitle + "(连接中)"
case .linkOK, .syncOK:
titleLabel.text = kSessionListTitle
case .syncing:
titleLabel.text = kSessionListTitle + "(同步数据)"
default:
break
}
titleLabel.sizeToFit()
titleLabel.lp_centerX = (navigationItem.titleView?.lp_width ?? view.lp_width) / 2.0
header.refresh(with: .netStauts, value: step)
view.setNeedsLayout()
}
override func onMultiLoginClientsChanged() {
super.onMultiLoginClientsChanged()
header.refresh(with: .loginClients, value: [NIMSDK.shared().loginManager.currentLoginClients()])
view.setNeedsLayout()
}
// MARK: - NIMEventSubscribeManagerDelegate
func onRecvSubscribeEvents(_ events: [Any]) {
var ids: [String] = []
for event in events {
if let event = event as? NIMSubscribeEvent, let id = event.from {
ids.append(id)
}
}
var indexPaths: [IndexPath] = []
if let visibleIndexPaths = tableView.indexPathsForVisibleRows{
for indexPath in visibleIndexPaths where recentSessions.count > indexPath.row {
let recent = recentSessions[indexPath.row]
if let session = recent.session, session.sessionType == .P2P {
let from = session.sessionId
if ids.contains(from) {
indexPaths.append(indexPath)
}
}
}
}
tableView.reloadRows(at: indexPaths, with: .none)
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if #available(iOS 9.0, *) {
if supportsForceTouch {
let preview = registerForPreviewing(with: self, sourceView: cell)
previews[indexPath.row] = preview
}
} else {
// Fallback on earlier versions
}
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if #available(iOS 9.0, *) {
if supportsForceTouch, let preview = previews[indexPath.row] {
unregisterForPreviewing(withContext: preview)
previews.removeValue(forKey: indexPath.row)
}
} else {
// Fallback on earlier versions
}
}
// MARK: - UIViewControllerPreviewingDelegate
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
if #available(iOS 9.0, *) {
if previewingContext.sourceView is UITableViewCell, let touchCell = previewingContext.sourceView as? UITableViewCell {
guard let indexPath = tableView.indexPath(for: touchCell) else { return nil }
let recent = recentSessions[indexPath.row]
// NTESSessionPeekNavigationViewController *nav = [NTESSessionPeekNavigationViewController instance:recent.session];
// return nav;
}
} else {
// Fallback on earlier versions
}
return nil
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
if #available(iOS 9.0, *) {
if previewingContext.sourceView is UITableViewCell, let touchCell = previewingContext.sourceView as? UITableViewCell {
guard let indexPath = tableView.indexPath(for: touchCell) else { return }
let recent = recentSessions[indexPath.row]
// NTESSessionViewController *vc = [[NTESSessionViewController alloc] initWithSession:recent.session];
// [self.navigationController showViewController:vc sender:nil];
}
} else {
// Fallback on earlier versions
}
}
// MARK: - LPListHeaderDelegate
func didSelectRowType(_ type: LPListHeaderType) {
/// 多人登录
switch type {
case .loginClients:
// NTESClientsTableViewController *vc = [[NTESClientsTableViewController alloc] initWithNibName:nil bundle:nil];
// [self.navigationController pushViewController:vc animated:YES];
break
default:
break
}
}
}
// MARK: -
// MARK: - Private
extension LPSessionListViewController {
fileprivate func titleView(_ uid: String) -> UIView {
let subLabel = UILabel(frame: .zero)
subLabel.textColor = UIColor.gray
subLabel.font = UIFont.systemFont(ofSize: 12.0)
subLabel.text = uid
subLabel.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin]
subLabel.sizeToFit()
let titleView = UIView()
titleView.lp_width = subLabel.lp_width
titleView.lp_height = titleLabel.lp_height + subLabel.lp_height
subLabel.lp_bottom = titleView.lp_height
titleView.addSubview(titleLabel)
titleView.addSubview(subLabel)
return titleView
}
fileprivate func checkNeedAtTip(_ recent: NIMRecentSession, content: NSMutableAttributedString) {
if LPSessionUtil.recentSessionIsAtMark(recent) {
let atTip = NSAttributedString(string: "[有人@你] ", attributes: [NSForegroundColorAttributeName : UIColor.red])
content.insert(atTip, at: 0)
}
}
fileprivate func checkOnlineState(_ recent: NIMRecentSession, content: NSMutableAttributedString) {
if let session = recent.session, session.sessionType == .P2P {
let state = LPSessionUtil.onlineState(session.sessionId, detail: false)
if state.characters.count > 0 {
let format = "[\(state)] "
let atTip = NSAttributedString(string: format, attributes: nil)
content.insert(atTip, at: 0)
}
}
}
}
| mit | fb042c86a65ac250b4d263821e2072c3 | 37.506494 | 143 | 0.608853 | 4.96442 | false | false | false | false |
i-schuetz/SwiftCharts | SwiftCharts/Axis/ChartAxisYHighLayerDefault.swift | 3 | 3125 | //
// ChartAxisYHighLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/// A ChartAxisLayer for high Y axes
class ChartAxisYHighLayerDefault: ChartAxisYLayerDefault {
override var low: Bool {return false}
/// The start point of the axis line.
override var lineP1: CGPoint {
return CGPoint(x: origin.x, y: axis.firstVisibleScreen)
}
/// The end point of the axis line.
override var lineP2: CGPoint {
return CGPoint(x: end.x, y: axis.lastVisibleScreen)
}
override func updateInternal() {
guard let chart = chart else {return}
super.updateInternal()
if lastFrame.width != frame.width {
// Move drawers by delta
let delta = frame.width - lastFrame.width
offset -= delta
initDrawers()
if canChangeFrameSize {
chart.notifyAxisInnerFrameChange(yHigh: ChartAxisLayerWithFrameDelta(layer: self, delta: delta))
}
}
}
override func handleAxisInnerFrameChange(_ xLow: ChartAxisLayerWithFrameDelta?, yLow: ChartAxisLayerWithFrameDelta?, xHigh: ChartAxisLayerWithFrameDelta?, yHigh: ChartAxisLayerWithFrameDelta?) {
super.handleAxisInnerFrameChange(xLow, yLow: yLow, xHigh: xHigh, yHigh: yHigh)
// Handle resizing of other high y axes
if let yHigh = yHigh , yHigh.layer.frame.maxX > frame.maxX {
offset = offset - yHigh.delta
initDrawers()
}
}
override func initDrawers() {
lineDrawer = generateLineDrawer(offset: 0)
let labelsOffset = settings.labelsToAxisSpacingY + settings.axisStrokeWidth
labelDrawers = generateLabelDrawers(offset: labelsOffset)
let axisTitleLabelsOffset = labelsOffset + labelsMaxWidth + settings.axisTitleLabelsToLabelsSpacing
axisTitleLabelDrawers = generateAxisTitleLabelsDrawers(offset: axisTitleLabelsOffset)
}
override func generateLineDrawer(offset: CGFloat) -> ChartLineDrawer {
let halfStrokeWidth = settings.axisStrokeWidth / 2 // we want that the stroke begins at the beginning of the frame, not in the middle of it
let x = origin.x + offset + halfStrokeWidth
let p1 = CGPoint(x: x, y: axis.firstVisibleScreen)
let p2 = CGPoint(x: x, y: axis.lastVisibleScreen)
return ChartLineDrawer(p1: p1, p2: p2, color: settings.lineColor, strokeWidth: settings.axisStrokeWidth)
}
override func labelsX(offset: CGFloat, labelWidth: CGFloat, textAlignment: ChartLabelTextAlignment) -> CGFloat {
var labelsX: CGFloat
switch textAlignment {
case .left, .default:
labelsX = origin.x + offset
case .right:
labelsX = origin.x + offset + labelsMaxWidth - labelWidth
}
return labelsX
}
override func axisLineX(offset: CGFloat) -> CGFloat {
return self.offset + offset + settings.axisStrokeWidth / 2
}
}
| apache-2.0 | 9c6734c5f3d894915f257f1e263e37fe | 35.764706 | 198 | 0.6512 | 4.706325 | false | false | false | false |
hq7781/MoneyBook | Pods/ChartsRealm/ChartsRealm/Classes/Data/RealmRadarDataSet.swift | 2 | 3443 | //
// RealmRadarDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
import Charts
import Realm
import RealmSwift
import Realm.Dynamic
open class RealmRadarDataSet: RealmLineRadarDataSet, IRadarChartDataSet
{
open override func initialize()
{
self.valueFont = NSUIFont.systemFont(ofSize: 13.0)
}
public required init()
{
super.init()
}
public init(results: RLMResults<RLMObject>?, yValueField: String, label: String?)
{
super.init(results: results, xValueField: nil, yValueField: yValueField, label: label)
}
public convenience init(results: Results<Object>?, yValueField: String, label: String?)
{
var converted: RLMResults<RLMObject>?
if results != nil
{
converted = ObjectiveCSupport.convert(object: results!)
}
self.init(results: converted, yValueField: yValueField, label: label)
}
public convenience init(results: RLMResults<RLMObject>?, yValueField: String)
{
self.init(results: results, yValueField: yValueField, label: "DataSet")
}
public convenience init(results: Results<Object>?, yValueField: String)
{
var converted: RLMResults<RLMObject>?
if results != nil
{
converted = ObjectiveCSupport.convert(object: results!)
}
self.init(results: converted, yValueField: yValueField)
}
public init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, label: String?)
{
super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, label: label)
}
public convenience init(realm: Realm?, modelName: String, resultsWhere: String, yValueField: String, label: String?)
{
var converted: RLMRealm?
if realm != nil
{
converted = ObjectiveCSupport.convert(object: realm!)
}
self.init(realm: converted, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, label: label)
}
// MARK: - Data functions and accessors
internal override func buildEntryFromResultObject(_ object: RLMObject, x: Double) -> ChartDataEntry
{
return RadarChartDataEntry(value: object[_yValueField!] as! Double)
}
// MARK: - Styling functions and accessors
/// flag indicating whether highlight circle should be drawn or not
/// **default**: false
open var drawHighlightCircleEnabled: Bool = false
/// - returns: `true` if highlight circle should be drawn, `false` ifnot
open var isDrawHighlightCircleEnabled: Bool { return drawHighlightCircleEnabled }
open var highlightCircleFillColor: NSUIColor? = NSUIColor.white
/// The stroke color for highlight circle.
/// If `nil`, the color of the dataset is taken.
open var highlightCircleStrokeColor: NSUIColor?
open var highlightCircleStrokeAlpha: CGFloat = 0.3
open var highlightCircleInnerRadius: CGFloat = 3.0
open var highlightCircleOuterRadius: CGFloat = 4.0
open var highlightCircleStrokeWidth: CGFloat = 2.0
}
| mit | e811c0dcf38f274ba11e59f8d8a887c7 | 30.018018 | 140 | 0.660471 | 4.997097 | false | false | false | false |
carabina/away | Example/Tests/Tests.swift | 2 | 3447 | // https://github.com/Quick/Quick
import Quick
import Nimble
import CoreLocation
import Away
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("Away class methods") {
let location = CLLocation(latitude: 11.008914, longitude: -74.810864)
describe("buildLocation"){
let distanceCases = [ 0.01, 1.0, 3.0, 9.0.Km, 99.99.Km, 0.1.Km, 1.miles ]
it("contains a method called buildLocation that returns a CLLocation") {
expect(Away.buildLocation(3, from: location)).to(beAnInstanceOf(CLLocation))
}
it("receives a from parameter"){
expect(Away.buildLocation(3, from: location)).to(beAnInstanceOf(CLLocation))
}
it("returns a CLLocation that is N meters away from base location"){
for distance in distanceCases {
var resultLocation = Away.buildLocation(distance, from: location)
expect(resultLocation.distanceFromLocation(location)) >= distance
}
}
it("changes the latitude insignificantly if we dont pass the bearing degrees"){
for distance in distanceCases {
var resultLocation = Away.buildLocation(distance, from: location)
let difference = abs(resultLocation.coordinate.latitude - location.coordinate.latitude)
expect(difference) < 0.002
}
}
it("accepts an optional parameter for the bearing"){
for bearing in 0...360 {
var resultLocation = Away.buildLocation(100, from: location, bearing: Double(bearing))
var distanceDifference = resultLocation.distanceFromLocation(location) - 100
expect(distanceDifference) < 0.2
}
}
}
describe("buildTrip"){
let result = Away.buildTrip(3.Km, from: location, locations: 3)
it("contains a method called buildTrip that returns CLLocation") {
expect(result[0]).to(equal(location))
}
it("distance between first and last location should be passed distance"){
let difference = location.distanceFromLocation(result.last!)
expect(difference) >= 3.Km
}
it("it should contain the same number of elements passed"){
expect(result.count).to(equal(3))
}
it("locations should be separated by the same distance [distance/locations]"){
let first = result.first!
let second = result[1]
let last = result.last!
var firstDistance = second.distanceFromLocation(first)
var secondDistance = last.distanceFromLocation(second)
let difference = abs(firstDistance - secondDistance)
expect(difference) < 5
}
it("throws an exeption if you call the method and require only one location"){
expect(Away.buildTrip(3.Km, from: location, locations: 1)).to(raiseException())
}
}
}
}
}
| mit | 54f5182bb763806580b1b936ce7335d9 | 40.53012 | 111 | 0.536989 | 5.369159 | false | false | false | false |
gottesmm/swift | test/SILGen/partial_apply_protocol.swift | 2 | 14267 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s
protocol Clonable {
func clone() -> Self
func maybeClone() -> Self?
func cloneMetatype() -> Self.Type
func getCloneFn() -> () -> Self
func genericClone<T>(t: T) -> Self
func genericGetCloneFn<T>(t: T) -> () -> Self
}
//===----------------------------------------------------------------------===//
// Partial apply of methods returning Self-derived types
//===----------------------------------------------------------------------===//
// CHECK-LABEL: sil hidden @_T022partial_apply_protocol12testClonableyAA0E0_p1c_tF : $@convention(thin) (@in Clonable) -> ()
func testClonable(c: Clonable) {
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable
let _: () -> Clonable = c.clone
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xSgIxr_22partial_apply_protocol8Clonable_pSgIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable>
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable>
let _: () -> Clonable? = c.maybeClone
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xXMTIxd_22partial_apply_protocol8Clonable_pXmTIxd_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @thick τ_0_0.Type) -> @thick Clonable.Type
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @thick τ_0_0.Type) -> @thick Clonable.Type
let _: () -> Clonable.Type = c.cloneMetatype
// CHECK: [[METHOD_FN:%.*]] = witness_method $@opened("{{.*}}") Clonable, #Clonable.getCloneFn!1, {{.*}} : $*@opened("{{.*}}") Clonable : $@convention(witness_method) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_owned () -> @out τ_0_0
// CHECK: [[RESULT:%.*]] = apply [[METHOD_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_owned () -> @out τ_0_0
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>([[RESULT]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable
let _: () -> Clonable = c.getCloneFn()
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_Ixo_22partial_apply_protocol8Clonable_pIxr_Ixo_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @owned @callee_owned () -> @out τ_0_0) -> @owned @callee_owned () -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @owned @callee_owned () -> @out τ_0_0) -> @owned @callee_owned () -> @out Clonable
let _: () -> () -> Clonable = c.getCloneFn
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable
// CHECK: bb0(%0 : $*Clonable, %1 : $@callee_owned () -> @out τ_0_0):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $τ_0_0
// CHECK-NEXT: apply %1([[INNER_RESULT]])
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_addr %0
// CHECK-NEXT: copy_addr [take] [[INNER_RESULT]] to [initialization] [[OUTER_RESULT]]
// CHECK-NEXT: [[EMPTY:%.*]] = tuple ()
// CHECK-NEXT: dealloc_stack [[INNER_RESULT]]
// CHECK-NEXT: return [[EMPTY]]
// FIXME: This is horribly inefficient, too much alloc_stack / copy_addr!
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xSgIxr_22partial_apply_protocol8Clonable_pSgIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable>
// CHECK: bb0(%0 : $*Optional<Clonable>, %1 : $@callee_owned () -> @out Optional<τ_0_0>):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $Optional<τ_0_0>
// CHECK-NEXT: apply %1([[INNER_RESULT]])
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = alloc_stack $Optional<Clonable>
// CHECK: [[IS_SOME:%.*]] = select_enum_addr [[INNER_RESULT]]
// CHECK-NEXT: cond_br [[IS_SOME]], bb1, bb2
// CHECK: bb1:
// CHECK-NEXT: [[INNER_RESULT_ADDR:%.*]] = unchecked_take_enum_data_addr [[INNER_RESULT]]
// CHECK-NEXT: [[SOME_PAYLOAD:%.*]] = alloc_stack $Clonable
// CHECK-NEXT: [[SOME_PAYLOAD_ADDR:%.*]] = init_existential_addr [[SOME_PAYLOAD]]
// CHECK-NEXT: copy_addr [take] [[INNER_RESULT_ADDR]] to [initialization] [[SOME_PAYLOAD_ADDR]]
// CHECK-NEXT: [[OUTER_RESULT_ADDR:%.*]] = init_enum_data_addr [[OUTER_RESULT]]
// CHECK-NEXT: copy_addr [take] [[SOME_PAYLOAD]] to [initialization] [[OUTER_RESULT_ADDR]]
// CHECK-NEXT: inject_enum_addr [[OUTER_RESULT]]
// CHECK-NEXT: dealloc_stack [[SOME_PAYLOAD]]
// CHECK-NEXT: br bb3
// CHECK: bb2:
// CHECK-NEXT: inject_enum_addr [[OUTER_RESULT]]
// CHECK-NEXT: br bb3
// CHECK: bb3:
// CHECK-NEXT: copy_addr [take] [[OUTER_RESULT]] to [initialization] %0
// CHECK-NEXT: [[EMPTY:%.*]] = tuple ()
// CHECK-NEXT: dealloc_stack [[OUTER_RESULT]]
// CHECK-NEXT: dealloc_stack [[INNER_RESULT]]
// CHECK-NEXT: return [[EMPTY]]
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xXMTIxd_22partial_apply_protocol8Clonable_pXmTIxd_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @thick τ_0_0.Type) -> @thick Clonable.Type
// CHECK: bb0(%0 : $@callee_owned () -> @thick τ_0_0.Type):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = apply %0()
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_metatype [[INNER_RESULT]]
// CHECK-NEXT: return [[OUTER_RESULT]]
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xIxr_Ixo_22partial_apply_protocol8Clonable_pIxr_Ixo_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @owned @callee_owned () -> @out τ_0_0) -> @owned @callee_owned () -> @out Clonable
// CHECK: bb0(%0 : $@callee_owned () -> @owned @callee_owned () -> @out τ_0_0):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = apply %0()
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = partial_apply [[THUNK_FN]]<τ_0_0>([[INNER_RESULT]])
// CHECK-NEXT: return [[OUTER_RESULT]]
//===----------------------------------------------------------------------===//
// Partial apply of methods returning Self-derived types from generic context
//
// Make sure the thunk only has the context generic parameters if needed!
//===----------------------------------------------------------------------===//
// CHECK-LABEL: sil hidden @_T022partial_apply_protocol28testClonableInGenericContextyAA0E0_p1c_x1ttlF : $@convention(thin) <T> (@in Clonable, @in T) -> ()
func testClonableInGenericContext<T>(c: Clonable, t: T) {
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable
let _: () -> Clonable = c.clone
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xSgIxr_22partial_apply_protocol8Clonable_pSgIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable>
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable>
let _: () -> Clonable? = c.maybeClone
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xXMTIxd_22partial_apply_protocol8Clonable_pXmTIxd_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @thick τ_0_0.Type) -> @thick Clonable.Type
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @thick τ_0_0.Type) -> @thick Clonable.Type
let _: () -> Clonable.Type = c.cloneMetatype
// CHECK: [[METHOD_FN:%.*]] = witness_method $@opened("{{.*}}") Clonable, #Clonable.getCloneFn!1, {{.*}} : $*@opened("{{.*}}") Clonable : $@convention(witness_method) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_owned () -> @out τ_0_0
// CHECK: [[RESULT:%.*]] = apply [[METHOD_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_owned () -> @out τ_0_0
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>([[RESULT]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable
let _: () -> Clonable = c.getCloneFn()
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_Ixo_22partial_apply_protocol8Clonable_pIxr_Ixo_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @owned @callee_owned () -> @out τ_0_0) -> @owned @callee_owned () -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @owned @callee_owned () -> @out τ_0_0) -> @owned @callee_owned () -> @out Clonable
let _: () -> () -> Clonable = c.getCloneFn
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xqd__Ixir_x22partial_apply_protocol8Clonable_pIxir_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @out τ_1_0) -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<T, @opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @out τ_1_0) -> @out Clonable
let _: (T) -> Clonable = c.genericClone
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xqd__Ixr_Ixio_x22partial_apply_protocol8Clonable_pIxr_Ixio_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @owned @callee_owned () -> @out τ_1_0) -> @owned @callee_owned () -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<T, @opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @owned @callee_owned () -> @out τ_1_0) -> @owned @callee_owned () -> @out Clonable
let _: (T) -> () -> Clonable = c.genericGetCloneFn
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xqd__Ixir_x22partial_apply_protocol8Clonable_pIxir_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @out τ_1_0) -> @out Clonable
// CHECK: bb0(%0 : $*Clonable, %1 : $*τ_0_0, %2 : $@callee_owned (@in τ_0_0) -> @out τ_1_0):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $τ_1_0
// CHECK-NEXT: apply %2([[INNER_RESULT]], %1)
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_addr %0
// CHECK-NEXT: copy_addr [take] [[INNER_RESULT]] to [initialization] [[OUTER_RESULT]]
// CHECK-NEXT: [[EMPTY:%.*]] = tuple ()
// CHECK-NEXT: dealloc_stack [[INNER_RESULT]]
// CHECK-NEXT: return [[EMPTY]]
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xqd__Ixr_Ixio_x22partial_apply_protocol8Clonable_pIxr_Ixio_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @owned @callee_owned () -> @out τ_1_0) -> @owned @callee_owned () -> @out Clonable
// CHECK: bb0(%0 : $*τ_0_0, %1 : $@callee_owned (@in τ_0_0) -> @owned @callee_owned () -> @out τ_1_0):
// CHECK-NEXT: apply %1(%0)
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0qd__Ixr_22partial_apply_protocol8Clonable_pIxr_AaBRd__r__lTR
// CHECK-NEXT: [[RESULT:%.*]] = partial_apply [[THUNK_FN]]<τ_0_0, τ_1_0>(%2)
// CHECK-NEXT: return [[RESULT]]
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0qd__Ixr_22partial_apply_protocol8Clonable_pIxr_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@owned @callee_owned () -> @out τ_1_0) -> @out Clonable {
// CHECK: bb0(%0 : $*Clonable, %1 : $@callee_owned () -> @out τ_1_0):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $τ_1_0
// CHECK-NEXT: apply %1([[INNER_RESULT]])
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_addr %0
// CHECK-NEXT: copy_addr [take] [[INNER_RESULT]] to [initialization] [[OUTER_RESULT]]
// CHECK-NEXT: [[EMPTY:%.*]] = tuple ()
// CHECK-NEXT: dealloc_stack [[INNER_RESULT:%.*]]
// CHECK-NEXT: return [[EMPTY]]
| apache-2.0 | 919ee38f7f324ce05828719c1d8ed7d5 | 88.373418 | 329 | 0.597196 | 3.043975 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | Classes/InteractiveNotifications/MMNotificationCategory.swift | 1 | 4524 | //
// MMInteractiveCategory.swift
//
// Created by okoroleva on 21.07.17.
//
//
import UserNotifications
@objcMembers
public final class MMNotificationCategory: NSObject {
///The category identifier passed in a `MM_MTMessage` object
public let identifier: String
///Actions in the order to be displayed for available contexts.
/// - remark: If there are more than four action objects in the array, the notification displays only the first four. When displaying banner notifications, the system displays only the first two actions.
public let actions: [MMNotificationAction]
///Options indicating how to handle notifications associated with category.
public let options: [MMNotificationCategoryOptions]
///The intent identifier strings, which defined in Intents framework, that you want to associate with notifications of this category.
/// - remark: Intent identifier may be useful for SiriKit support.
public let intentIdentifiers: [String]
///Initializes the `MMNotificationCategory`
/// - parameter identifier: category identifier. "mm_" prefix is reserved for Mobile Messaging ids and cannot be used as a prefix.
/// - parameter actions: Actions in the order to be displayed for available contexts.
/// - parameter options: Options indicating how to handle notifications associated with category. Supported only for iOS 10+.
/// - parameter intentIdentifiers: The intent identifier strings, which defined in Intents framework, that you want to associate with notifications of this category. Supported only for iOS 10+.
public init?(identifier: String, actions: [MMNotificationAction], options: [MMNotificationCategoryOptions]?, intentIdentifiers: [String]?) {
guard !identifier.hasPrefix(NotificationCategoryConstants.categoryNamePrefix) else {
return nil
}
self.identifier = identifier
self.actions = actions
self.options = options ?? []
self.intentIdentifiers = intentIdentifiers ?? []
}
public init?(dictionary: [String: Any]) {
guard let actions = (dictionary[NotificationCategoryConstants.actions] as? [[String: Any]])?.compactMap(MMNotificationAction.makeAction), !actions.isEmpty, let identifier = dictionary[NotificationCategoryConstants.identifier] as? String else
{
return nil
}
self.actions = actions
self.identifier = identifier
self.options = []
self.intentIdentifiers = []
}
var unUserNotificationCategory: UNNotificationCategory {
var categoryOptions: UNNotificationCategoryOptions = []
categoryOptions.insert(.customDismissAction)
if options.contains(.allowInCarPlay) {
categoryOptions.insert(.allowInCarPlay)
}
return UNNotificationCategory(identifier: identifier, actions: actions.map{$0.unUserNotificationAction}, intentIdentifiers: intentIdentifiers, options: categoryOptions)
}
public override var hash: Int {
return identifier.hashValue
}
public override func isEqual(_ object: Any?) -> Bool {
guard let obj = object as? MMNotificationCategory else {
return false
}
return identifier == obj.identifier
}
}
@objcMembers
public final class MMNotificationCategoryOptions : NSObject {
let rawValue: Int
init(rawValue: Int) {
self.rawValue = rawValue
}
public init(options: [MMNotificationCategoryOptions]) {
self.rawValue = options.reduce(0) { (total, option) -> Int in
return total | option.rawValue
}
}
public func contains(options: MMNotificationCategoryOptions) -> Bool {
return rawValue & options.rawValue != 0
}
// Whether notifications of this category should be allowed in CarPlay
/// - remark: This option is available only for iOS 10+
public static let allowInCarPlay = MMNotificationCategoryOptions(rawValue: 1 << 0)
}
extension Set where Element: MMNotificationCategory {
var unNotificationCategories: Set<UNNotificationCategory>? {
return Set<UNNotificationCategory>(self.map{ $0.unUserNotificationCategory })
}
}
struct NotificationCategories {
static let path: String? = MobileMessaging.resourceBundle.path(forResource: NotificationCategoryConstants.plistName, ofType: "plist")
static var predefinedCategories: Set<MMNotificationCategory>? {
if let path = path, let categories = NSArray(contentsOfFile: path) as? [[String: Any]] {
return Set(categories.compactMap(MMNotificationCategory.init))
} else {
return nil
}
}
}
struct NotificationCategoryConstants {
static let categoryNamePrefix = "mm_"
static let identifier = "identifier"
static let actions = "actions"
static let plistName = "PredefinedNotificationCategories"
}
| apache-2.0 | 36d5b6d3dcb3b5855f2601af1220b559 | 36.7 | 243 | 0.766799 | 4.379477 | false | false | false | false |
acchou/RxGmail | Example/RxGmail/Global.swift | 1 | 2007 | import GoogleAPIClientForREST
import RxGmail
var global = Global()
struct Global {
var gmailService: GTLRGmailService
var rxGmail: RxGmail
var labelViewModel: LabelViewModelType
var labelDetailViewModel: LabelDetailViewModelType
var messagesViewModel: MessagesViewModelType
var threadsViewModel: ThreadsViewModelType
var threadMessagesViewModel: ThreadMessagesViewModelType
var messageViewModel: MessageViewModelType
}
extension Global {
init(gmailService: GTLRGmailService? = nil,
rxGmail: RxGmail? = nil,
labelViewModel: LabelViewModelType? = nil,
labelDetailViewModel: LabelDetailViewModelType? = nil,
messagesViewModel: MessagesViewModelType? = nil,
threadsViewModel: ThreadsViewModelType? = nil,
threadMessagesViewModel: ThreadMessagesViewModelType? = nil,
messageViewModel: MessageViewModelType? = nil) {
let gmailService = gmailService ?? GTLRGmailService()
let rxGmail = rxGmail ?? RxGmail(gmailService: gmailService)
let labelViewModel = labelViewModel ?? LabelViewModel(rxGmail: rxGmail)
let labelDetailViewModel = labelDetailViewModel ?? LabelDetailViewModel(rxGmail: rxGmail)
let messagesViewModel = messagesViewModel ?? MessagesViewModel(rxGmail: rxGmail)
let threadsViewModel = threadsViewModel ?? ThreadsViewModel(rxGmail: rxGmail)
let threadMessagesViewModel = threadMessagesViewModel ?? ThreadMessagesViewModel(rxGmail: rxGmail)
let messageViewModel = messageViewModel ?? MessageViewModel(rxGmail: rxGmail)
self.init (
gmailService: gmailService,
rxGmail: rxGmail,
labelViewModel: labelViewModel,
labelDetailViewModel: labelDetailViewModel,
messagesViewModel: messagesViewModel,
threadsViewModel: threadsViewModel,
threadMessagesViewModel: threadMessagesViewModel,
messageViewModel: messageViewModel
)
}
}
| mit | 5a059d1bca61c0abc43e81f196e67898 | 41.702128 | 106 | 0.727454 | 5.226563 | false | false | false | false |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 26 - iOS 8 Visual Effects/Grimm-Starter/Grimm/StoryView (Ray Wenderlich's conflicted copy 2014-10-28).swift | 1 | 4768 |
/*
* Copyright (c) 2014 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 UIKit
class StoryView: UIView, ThemeAdopting {
override func awakeFromNib() {
setup()
}
var story: Story? {
didSet {
titleLabel.text = story!.title
contentLabel.text = story!.content
setNeedsUpdateConstraints()
}
}
private let titleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.opaque = true
label.setTranslatesAutoresizingMaskIntoConstraints(false)
return label
}()
private var contentLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.opaque = true
label.setTranslatesAutoresizingMaskIntoConstraints(false)
return label
}()
private var separatorView: UIView = {
let view = UIView()
view.opaque = true
view.setTranslatesAutoresizingMaskIntoConstraints(false)
return view
}()
func reloadTheme() {
let theme = Theme.sharedInstance
backgroundColor = theme.textBackgroundColor
titleLabel.backgroundColor = theme.textBackgroundColor
titleLabel.font = theme.preferredFontForTextStyle(UIFontTextStyleHeadline)
titleLabel.textColor = theme.textColor
titleLabel.textAlignment = theme.titleAlignment == TitleAlignment.Center ? NSTextAlignment.Center : NSTextAlignment.Left
contentLabel.backgroundColor = theme.textBackgroundColor
contentLabel.font = theme.preferredFontForTextStyle(UIFontTextStyleBody)
contentLabel.textColor = theme.textColor
separatorView.backgroundColor = theme.separatorColor
}
private func setup() {
addSubview(titleLabel)
addSubview(separatorView)
addSubview(contentLabel)
var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(
item: titleLabel,
attribute: .Top,
relatedBy: .Equal,
toItem: self,
attribute: .Top,
multiplier: 1,
constant: 20))
constraints.append(NSLayoutConstraint(
item: titleLabel,
attribute: .Height,
relatedBy: .GreaterThanOrEqual,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: 20))
constraints.append(NSLayoutConstraint(
item: separatorView,
attribute: .Top,
relatedBy: .Equal,
toItem: titleLabel,
attribute: .Bottom,
multiplier: 1,
constant: 20))
constraints.append(NSLayoutConstraint(
item: separatorView,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: 0.5))
constraints.append(NSLayoutConstraint(
item: contentLabel,
attribute: .Top,
relatedBy: .Equal,
toItem: separatorView,
attribute: .Bottom,
multiplier: 1,
constant: 20))
constraints.append(NSLayoutConstraint(
item: self,
attribute: .Bottom,
relatedBy: .Equal,
toItem: contentLabel,
attribute: .Bottom,
multiplier: 1,
constant: 15))
constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[titleLabel]-15-|", options: .convertFromNilLiteral(), metrics: nil, views: ["titleLabel": titleLabel]) as [NSLayoutConstraint]
constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[separatorView]-15-|", options: .convertFromNilLiteral(), metrics: nil, views: ["separatorView": separatorView]) as [NSLayoutConstraint]
constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[contentLabel]-15-|", options: .convertFromNilLiteral(), metrics: nil, views: ["contentLabel": contentLabel]) as [NSLayoutConstraint]
addConstraints(constraints)
reloadTheme()
}
}
| mit | 3a1007701ac385f5fea378ba94dcd879 | 32.342657 | 210 | 0.705327 | 5.06695 | false | false | false | false |
rambler-digital-solutions/rambler-it-ios | Carthage/Checkouts/rides-ios-sdk/source/UberRides/Model/Vehicle.swift | 1 | 2358 | //
// Vehicle.swift
// UberRides
//
// Copyright © 2016 Uber Technologies, Inc. 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.
// MARK: Vehicle
/**
* Contains information for an Uber driver's car.
*/
@objc(UBSDKVehicle) public class Vehicle: NSObject, Codable {
/// The license plate number of the vehicle.
@objc public private(set) var licensePlate: String
/// The vehicle make or brand.
@objc public private(set) var make: String
/// The vehicle model or type.
@objc public private(set) var model: String
/// The URL to a stock photo of the vehicle
@objc public private(set) var pictureURL: URL?
enum CodingKeys: String, CodingKey {
case make = "make"
case model = "model"
case licensePlate = "license_plate"
case pictureURL = "picture_url"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
licensePlate = try container.decode(String.self, forKey: .licensePlate)
make = try container.decode(String.self, forKey: .make)
model = try container.decode(String.self, forKey: .model)
pictureURL = try container.decodeIfPresent(URL.self, forKey: .pictureURL)
}
}
| mit | bd86a56412b7117c9705b9372649033b | 39.637931 | 81 | 0.699618 | 4.356747 | false | false | false | false |
rtoal/polyglot | swift/string_counting.swift | 2 | 156 | // Swift understands grapheme clusters and encodings
let s = "\u{1f1f1}\u{1f1e7}"
assert(s.count == 1)
assert(s.utf16.count == 4)
assert(s.utf8.count == 8)
| mit | 2699628569bd2cc92a5d8948aa020e7c | 30.2 | 52 | 0.692308 | 2.516129 | false | false | false | false |
tripleCC/GanHuoCode | GanHuo/Controllers/HomePage/TPCDetailViewController.swift | 1 | 7276 | //
// TPCDetailViewController.swift
// WKCC
//
// Created by tripleCC on 15/11/18.
// Copyright © 2015年 tripleCC. All rights reserved.
//
import UIKit
import Kingfisher
class TPCDetailViewController: TPCViewController {
let navigationBarHideKey = "TPCDetailViewNavigationBarHideKey"
let reuseIdentifier = "TPCDetailCell"
let reuseHeaderIdentifier = "TPCDetailHeader"
var technicalDict: TPCTechnicalDictionary?
var categories: [String]? {
didSet {
categories = categories?.sort{ $0 < $1 }
}
}
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.backgroundColor = UIColor.clearColor()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = TPCConfiguration.detailCellHeight
tableView.sectionFooterHeight = 0
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.registerClass(TPCDetailHeaderView.self, forHeaderFooterViewReuseIdentifier: reuseHeaderIdentifier)
tableView.contentInset = UIEdgeInsets(top: TPCConfiguration.detailHeaderImageViewHeight, left: 0, bottom: 0, right: 0)
}
}
private lazy var headerImageView: UIImageView = {
let headerImageView = UIImageView()
headerImageView.frame = CGRect(x: 0, y: 0, width: TPCScreenWidth, height: TPCConfiguration.detailHeaderImageViewHeight)
headerImageView.clipsToBounds = true
headerImageView.contentMode = UIViewContentMode.ScaleAspectFill
headerImageView.alpha = CGFloat(TPCConfiguration.imageAlpha)
return headerImageView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupNav()
view.insertSubview(headerImageView, belowSubview: tableView)
debugPrint(technicalDict)
if let technicals = technicalDict?["福利"] where technicals.count > 1 {
technicals.forEach{ debugPrint("\($0.url)") }
}
if let technical = technicalDict?["福利"]?.first {
headerImageView.kf_setImageWithURL(NSURL(string: technical.url!)!)
}
registerObserverForApplicationDidEnterBackground()
registerObserverForApplicationDidEnterForeground()
}
private func setupNav() {
navigationBarBackgroundView.removeFromSuperview()
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "all"), style: .Done, target: self, action: #selector(TPCDetailViewController.showAllImages))
}
func showAllImages() {
if let technicals = technicalDict?["福利"] {
let pageScrollView = TPCPageScrollView(frame: view.bounds)
pageScrollView.backgroundColor = UIColor.blackColor()
pageScrollView.viewDisappearAction = { [unowned self] in
self.prepareForPageDisappear()
}
pageScrollView.imageURLStrings = technicals.flatMap{ $0.url }
pageScrollView.alpha = 0
view.addSubview(pageScrollView)
UIView.animateWithDuration(0.5) { () -> Void in
self.prepareForPageAppear()
pageScrollView.alpha = 1
}
}
}
func prepareForPageAppear() {
// view.alpha = 0
headerImageView.alpha = 0
tableView.alpha = 0
adjustBarToHidenPosition()
}
func prepareForPageDisappear() {
// view.alpha = 1
headerImageView.alpha = CGFloat(TPCConfiguration.imageAlpha)
tableView.alpha = 1
adjustBarToOriginPosition()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
override func applicationDidEnterBackground(notification: NSNotification) {
NSUserDefaults.standardUserDefaults().setBool(navigationBarFrame!.origin.y == TPCStatusBarHeight, forKey: navigationBarHideKey)
debugPrint(#function, navigationBarFrame!.origin.y == TPCStatusBarHeight)
}
override func applicationDidEnterForeground(notification: NSNotification) {
debugPrint(#function)
if !NSUserDefaults.standardUserDefaults().boolForKey(navigationBarHideKey) {
dispatchSeconds(0.5, action: {
self.adjustBarToHidenPosition()
})
}
}
deinit {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: navigationBarHideKey)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "DetailVc2BrowserVc" {
if let broswerVc = segue.destinationViewController as? TPCBroswerViewController {
if let row = sender?.row,
let section = sender?.section,
let category = categories?[section] {
broswerVc.technical = technicalDict?[category]?[row]
}
}
}
}
}
extension TPCDetailViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return categories?.count ?? 0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard categories?[section] != nil else { return 0 }
return technicalDict?[categories![section]]?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as! TPCDetailViewCell
if let catagory = categories?[indexPath.section] {
cell.technical = technicalDict?[catagory]?[indexPath.row]
}
return cell
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(reuseHeaderIdentifier) as! TPCDetailHeaderView
header.title = categories?[section]
return header
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return TPCConfiguration.detailSectionHeaderHeight
}
}
extension TPCDetailViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("DetailVc2BrowserVc", sender: indexPath)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.contentOffset.y < 0 {
if abs(scrollView.contentOffset.y) < scrollView.contentInset.top {
headerImageView.transform = CGAffineTransformMakeTranslation(0, -(scrollView.contentOffset.y + scrollView.contentInset.top) * 0.5)
} else {
let scale = (abs(scrollView.contentOffset.y + scrollView.contentInset.top) + TPCConfiguration.detailHeaderImageViewHeight) / TPCConfiguration.detailHeaderImageViewHeight
headerImageView.transform = CGAffineTransformMakeScale(scale, scale)
headerImageView.frame.origin.y = 0
}
}
}
}
| mit | ba4fedb56d2ab594f501209d18a06d05 | 38.677596 | 185 | 0.665335 | 5.546982 | false | false | false | false |
wangyuanou/LZRequest | LZRequest/Data+Request.swift | 1 | 1389 | //
// Data+Request.swift
// LZRequest
//
// Created by 王渊鸥 on 2016/10/21.
// Copyright © 2016年 王渊鸥. All rights reserved.
//
import Foundation
extension Data {
static let HTTP_BOUNDRY = "_REQUEST_APPLICATION_"
static func parameters(_ boundry:String = HTTP_BOUNDRY) -> LZData {
return LZData(source: NSMutableData(), boundry: boundry)
}
static func setting(_ action:(LZData)->()) -> Data {
let data = Data.parameters()
return data.setting(action)
}
}
extension NSMutableData {
func set(_ key:String, value:String, boundry:String) {
let leadString = "\n--\(boundry)"
+ "\nContent-Disposition:form-data;name=\"\(key)\"\n"
+ "\n\(value)"
if let data = (leadString as NSString).data(using: String.Encoding.utf8.rawValue) {
self.append(data)
}
}
func set(_ file:String, data:Data, boundry:String) {
let leadString = "\n--\(boundry)"
+ "\nContent-Disposition:form-data;name=\"file\";filename=\"\(file)\""
+ "\nContent-Type:application/octet-stream"
+ "\nContent-Transfer-Encoding:binary\n\n"
if let lead = (leadString as NSString).data(using: String.Encoding.utf8.rawValue) {
self.append(lead)
}
self.append(data)
}
func closeBoundry(_ boundry:String) {
let endString = "\n--\(boundry)--"
if let data = (endString as NSString).data(using: String.Encoding.utf8.rawValue) {
self.append(data)
}
}
}
| mit | 23c48f607f8c2261590033de0ec38352 | 23.981818 | 85 | 0.663755 | 3.180556 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document2.playgroundchapter/Pages/Exercise3.playgroundpage/Sources/Setup.swift | 1 | 1830 | //
// Setup.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import Foundation
//let world = GridWorld(columns: 5, rows: 5)
let world: GridWorld = loadGridWorld(named: "2.5")
let actor = Actor()
public func playgroundPrologue() {
world.place(actor, facing: north, at: Coordinate(column: 1, row: 1))
placeItems()
// Must be called in `playgroundPrologue()` to update with the current page contents.
registerAssessment(world, assessment: assessmentPoint)
//// ----
// Any items added or removed after this call will be animated.
finalizeWorldBuilding(for: world)
//// ----
}
// Called from LiveView.swift to initially set the LiveView.
public func presentWorld() {
setUpLiveViewWith(world)
}
// MARK: Epilogue
public func playgroundEpilogue() {
sendCommands(for: world)
}
func placeItems() {
let gems = [
Coordinate(column: 0, row: 1),
Coordinate(column: 1, row: 0),
Coordinate(column: 1, row: 2),
Coordinate(column: 2, row: 1),
]
world.placeGems(at: gems)
}
func placeFloor() {
let obstacles = world.coordinates(inColumns: [0,4], intersectingRows: 0...4)
let obstacles2 = world.coordinates(inColumns: 0...4, intersectingRows: [0,4])
world.removeNodes(at: obstacles)
world.removeNodes(at: obstacles2)
world.placeWater(at: obstacles)
world.placeWater(at: obstacles2)
world.place(Stair(), facing: south, at: Coordinate(column: 2, row: 3))
world.place(Stair(), facing: north, at: Coordinate(column: 2, row: 1))
world.place(Stair(), facing: east, at: Coordinate(column: 1, row: 2))
world.place(Stair(), facing: west, at: Coordinate(column: 3, row: 2))
}
| mit | 17ba3d1b0821e9229348375ec4ddb2d3 | 26.313433 | 89 | 0.618579 | 3.78882 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/00424-no-stacktrace.random.swift | 1 | 2655 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
return d<A"\()
import CoreData
return "
case b in x in a {
typealias B<I : B? = {
self] in
let g = compose(g: c> [B) -> ("""
}
case b {
let c: NSObject {
protocol a {
import Foundation
return $0
protocol A : Array) {
self.E == .c> U.dynamicType)
return nil
}
return b
}
}
return d
return true
return [B
let t: P {
func f("")-> Int = { x }
typealias R
}
import Foundation
}
extension NSSet {
}
static let h = [T>: NSManagedObject {
}
let g = { c>()
typealias h> {
convenience init() -> T
var c>Bool)
}
func g(t: C {
var e: String = {
init()
}
}
class d: NSObject {
}
}
self.B
func b<T>(t: T]((t: NSObject {
self] {
protocol c = {
func a(object1: P {
typealias R
convenience init("\() {
class C<T
var e)
}
var e: AnyObject.R
extension NSSet {
let c: Array) -> [B<T] {
import CoreData
var e: A.d.Type) {
class C) -> {
}
protocol P {
print(object2: T
}
}
class C
}
}
typealias e : Int -> : d where T) -> {
let a {
struct D : A {
}
}
import Foundation
let d<H : A? = nil
self.B? {
private let d<T, f: NSManagedObject {
class func f: B<C> : C> Self {
typealias F>(n: NSObject {
}
protocol P {
class A : e, f: AnyObject, AnyObject) -> Int = A"\(n: d = { c) {
typealias F = compose()(f)
class C<f : Int -> {
import Foundation
}
}
class A : A: T>>(false)
}
let g = D>)
import Foundation
struct D : Int -> T>())
import Foundation
let c(AnyObject, b = .init()
print(t: A {
f = b: U.E == {
if true {
}
case b = e: P {
private class A {
return nil
func g<T) {
convenience init()
if c == f<T! {
return self.b = ""
if c = b<T where A: e, object1, f<T] in
override init(n: P {
}
func f(t: A((c: A : A> Int = b> {
}
}
d: Int
}
return d.Type) {
struct S {
[T>()
}
import Foundation
}
class A : T>? {
var b {
self.E
struct B
}
protocol c {
typealias e = 0
func b
struct c {
convenience init(x)
import Foundation
}
typealias R = b
typealias e : B<A? = 0
}
class C) ->) -> Int {
}
return { x }
}
typealias R
}
protocol P {
let c: B("A.e where A.c()(f<T where T>(g<T! {
var b<H : P> {
let f = {
e : T] in
}
}
class A {
}
}
class func b.e == { c(x: e: Int
let v: P {
}
}
class func a(self)
let d<T>) {
}
print(c: B? = B<c> Self {
let c = {
}
self.R
}
class A {
struct c == e: A>>()
let c(n: Array) -> T -> {
}
return $0
}
private class A : U : (x: P> T where H) {
if true {
let c
| apache-2.0 | 060ea0b2de7a8498a2f175f4b07242d7 | 13.668508 | 79 | 0.60678 | 2.562741 | false | false | false | false |
adrfer/swift | stdlib/public/core/CocoaArray.swift | 2 | 2648 | //===--- CocoaArray.swift - A subset of the NSArray interface -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// To implement bridging, the core standard library needs to interact
// a little bit with Cocoa. Because we want to keep the core
// decoupled from the Foundation module, we can't use NSArray
// directly. We _can_, however, use an @objc protocol with a
// compatible API. That's _NSArrayCoreType.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
/// A wrapper around any `_NSArrayCoreType` that gives it
/// `CollectionType` conformance. Why not make
/// `_NSArrayCoreType` conform directly? It's a class, and I
/// don't want to pay for the dynamic dispatch overhead.
internal struct _CocoaArrayWrapper : CollectionType {
var startIndex: Int {
return 0
}
var endIndex: Int {
return buffer.count
}
subscript(i: Int) -> AnyObject {
return buffer.objectAtIndex(i)
}
/// Returns a pointer to the first element in the given subRange if
/// the subRange is stored contiguously. Otherwise, return `nil`.
///
/// - Note: This method should only be used as an optimization; it
/// is sometimes conservative and may return `nil` even when
/// contiguous storage exists, e.g., if array doesn't have a smart
/// implementation of countByEnumeratingWithState.
func contiguousStorage(
subRange: Range<Int>
) -> UnsafeMutablePointer<AnyObject>
{
var enumerationState = _makeSwiftNSFastEnumerationState()
// This function currently returns nil unless the first
// subRange.endIndex items are stored contiguously. This is an
// acceptable conservative behavior, but could potentially be
// optimized for other cases.
let contiguousCount = withUnsafeMutablePointer(&enumerationState) {
self.buffer.countByEnumeratingWithState($0, objects: nil, count: 0)
}
return contiguousCount >= subRange.endIndex
? unsafeBitCast(
enumerationState.itemsPtr, UnsafeMutablePointer<AnyObject>.self
) + subRange.startIndex
: nil
}
@_transparent
init(_ buffer: _NSArrayCoreType) {
self.buffer = buffer
}
var buffer: _NSArrayCoreType
}
#endif
| apache-2.0 | fc5ded1b9613e4955df2ab48685da6d0 | 33.842105 | 80 | 0.66503 | 4.728571 | false | false | false | false |
KrishMunot/swift | benchmark/single-source/RangeAssignment.swift | 3 | 916 | //===--- RangeAssignment.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
@inline(never)
public func run_RangeAssignment(_ scale: Int) {
let range = 100..<200
var vector = [Double](repeating: 0.0 , count: 5000)
let alfa = 1.0
let N = 500*scale
for _ in 1...N {
vector[range] = ArraySlice(vector[range].map { $0 + alfa })
}
CheckResults(vector[100] == Double(N),
"IncorrectResults in RangeAssignment: \(vector[100]) != \(N).")
}
| apache-2.0 | 6b7ec5d893ad0f6393d2c8183926a8ef | 32.925926 | 80 | 0.584061 | 4.144796 | false | false | false | false |
KrishMunot/swift | benchmark/single-source/PopFrontGeneric.swift | 3 | 1949 | //===--- PopFrontGeneric.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
let reps = 1
let arrayCount = 1024
// This test case exposes rdar://17440222 which caused rdar://17974483 (popFront
// being really slow).
func _arrayReplace<B: _ArrayBufferProtocol, C: Collection
where C.Iterator.Element == B.Element, B.Index == Int
>(
_ target: inout B, _ subRange: Range<Int>, _ newValues: C
) {
_precondition(
subRange.startIndex >= 0,
"Array replace: subRange start is negative")
_precondition(
subRange.endIndex <= target.endIndex,
"Array replace: subRange extends past the end")
let oldCount = target.count
let eraseCount = subRange.count
let insertCount = numericCast(newValues.count) as Int
let growth = insertCount - eraseCount
if target.requestUniqueMutableBackingBuffer(minimumCapacity: oldCount + growth) != nil {
target.replace(subRange: subRange, with: insertCount, elementsOf: newValues)
}
else {
_preconditionFailure("Should not get here?")
}
}
@inline(never)
public func run_PopFrontArrayGeneric(_ N: Int) {
let orig = Array(repeating: 1, count: arrayCount)
var a = [Int]()
for _ in 1...20*N {
for _ in 1...reps {
var result = 0
a.append(contentsOf: orig)
while a.count != 0 {
result += a[0]
_arrayReplace(&a._buffer, 0..<1, EmptyCollection())
}
CheckResults(result == arrayCount, "IncorrectResults in StringInterpolation: \(result) != \(arrayCount)")
}
}
}
| apache-2.0 | a7c1f3cca600bb09c359d9890b078231 | 29.936508 | 111 | 0.639302 | 4.209503 | false | false | false | false |
auth0/Lock.iOS-OSX | Lock/Routes.swift | 2 | 3290 | // RouteHistory.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
struct Routes {
var current: Route {
return self.history.first ?? .root
}
private(set) var history: [Route] = []
mutating func back() -> Route {
self.history.removeLast(1)
return self.current
}
mutating func go(_ route: Route) {
self.history.append(route)
}
mutating func reset() {
self.history = []
}
}
enum Route: Equatable {
case root
case forgotPassword
case multifactor
case multifactorWithToken(String)
case enterpriseActiveAuth(connection: EnterpriseConnection, domain: String)
case unrecoverableError(error: UnrecoverableError)
case passwordless(screen: PasswordlessScreen, connection: PasswordlessConnection)
func title(withStyle style: Style) -> String? {
switch self {
case .forgotPassword:
return "Reset Password".i18n(key: "com.auth0.lock.forgot.title", comment: "Forgot Password title")
case .multifactor, .multifactorWithToken:
return "Two Step Verification".i18n(key: "com.auth0.lock.multifactor.title", comment: "Multifactor title")
case .root, .unrecoverableError, .enterpriseActiveAuth, .passwordless:
return style.hideTitle ? nil : style.title
}
}
}
func == (lhs: Route, rhs: Route) -> Bool {
switch((lhs, rhs)) {
case (.root, .root), (.forgotPassword, .forgotPassword), (.multifactor, .multifactor):
return true
case (.enterpriseActiveAuth(let lhsConnection, let lhsDomain), .enterpriseActiveAuth(let rhsConnection, let rhsDomain)):
return lhsConnection.name == rhsConnection.name && lhsDomain == rhsDomain
case (.unrecoverableError(let lhsError), .unrecoverableError(let rhsError)):
return lhsError == rhsError
case (.multifactorWithToken(let lhsToken), .multifactorWithToken(let rhsToken)):
return lhsToken == rhsToken
case (.passwordless(let lhsScreen, let lhsConnection), .passwordless(let rhsScreen, let rhsConnection)):
return lhsScreen == rhsScreen && lhsConnection.name == rhsConnection.name
default:
return false
}
}
| mit | 1b4575d254b63c5b9fbcf8878c20da37 | 38.638554 | 124 | 0.704559 | 4.433962 | false | false | false | false |
mojidabckuu/content | Content/Classes/CollectionView/CollectionViewDelegate.swift | 1 | 11937 | //
// CollectionViewDelegate.swift
// Contents
//
// Created by Vlad Gorbenko on 9/5/16.
// Copyright © 2016 Vlad Gorbenko. All rights reserved.
//
import UIKit
extension UICollectionView: Scrollable {}
open class CollectionDelegate<Model: Equatable, View: ViewDelegate, Cell: ContentCell>: BaseDelegate<Model, View, Cell>, UICollectionViewDelegate, UICollectionViewDataSource where View: UIView {
open var collectionView: UICollectionView { return self.content.view as! UICollectionView }
open override var selectedItem: Model? {
set {
self.select(model: newValue)
}
get {
guard let indexPath = self.collectionView.indexPathsForSelectedItems?.first else { return nil }
return self.content.relation[indexPath.row]
}
}
open override var selectedItems: [Model]? {
set {
self.select(models: newValue)
}
get { return self.collectionView.indexPathsForSelectedItems?.map { self.content.relation[$0.row] } }
}
open override var visibleItem: Model? {
set {
self.scroll(to: newValue)
}
get {
guard let indexPath = self.collectionView.indexPathsForVisibleItems.first else { return nil }
return self.content.relation[indexPath.row]
}
}
open override var visibleItems: [Model]? {
set {
self.scroll(to: newValue)
}
get { return self.collectionView.indexPathsForVisibleItems.map { self.content.relation[$0.row] } }
}
//MARK: - Lifecycle
public override init() {
super.init()
}
override init(content: Content<Model, View, Cell>) {
super.init(content: content)
}
// Select
open override func select(model: Model?, animated: Bool = false, scrollPosition: ContentScrollPosition = .none) {
guard let model = model else { return }
if let index = self.content.relation.index(of: model) {
let indexPath = IndexPath(item: index, section: 0)
let defaultScroll = scrollPosition == .none ? self.none : scrollPosition
self.collectionView.selectItem(at: indexPath, animated: animated, scrollPosition: scrollPosition.collectionScroll)
}
}
open override func select(models: [Model]?, animated: Bool = false, scrollPosition: ContentScrollPosition = .none) {
guard let models = models else { return }
for (i, model) in models.enumerated() {
self.select(model: model, animated: animated, scrollPosition: i == 0 ? scrollPosition : self.none)
}
}
//Scroll
open override func scroll(to model: Model?, at: ContentScrollPosition = .middle, animated: Bool = true) {
guard let model = model else { return }
if let index = self.content.relation.index(of: model) {
let indexPath = IndexPath(row: index, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: at.collectionScroll, animated: animated)
}
}
/** Scrolls to first item only */
open override func scroll(to models: [Model]?, at: ContentScrollPosition = .middle, animated: Bool = true) {
guard let model = models?.first else { return }
self.scroll(to: model, at: at, animated: animated)
}
open override func deselect(model: Model?, animated: Bool = false) {
guard let model = model else { return }
if let index = self.content.relation.index(of: model) {
let indexPath = IndexPath(row: index, section: 0)
self.collectionView.deselectItem(at: indexPath, animated: animated)
}
}
open override func deselect(models: [Model]?, animated: Bool = false) {
guard let models = models else { return }
for (i, model) in models.enumerated() {
self.deselect(model: model, animated: animated)
}
}
// Insert
open override func insert(_ models: [Model], index: Int = 0, animated: Bool = true, completion: Completion?) {
if animated {
let collectionView = self.collectionView
self.collectionView.performBatchUpdates({
self.content.relation.insert(contentsOf: models, at: index)
let indexPaths = self.indexPaths(models)
collectionView.insertItems(at: indexPaths)
}, completion: { finished in
completion?()
})
} else {
self.content.relation.insert(contentsOf: models, at: index)
var obs: NSKeyValueObservation? = nil
obs = self.collectionView.observe(\.contentSize, options: [.new], changeHandler: { (view, value) in
completion?()
obs = nil
})
self.reload()
}
}
//Move
open override func move(from: Int, to: Int) {
let sourceIndexPath = IndexPath(row: from, section: 0)
let destinationPath = IndexPath(row: to, section: 0)
self.collectionView.moveItem(at: sourceIndexPath, to: destinationPath)
}
//Delete
open override func delete(_ models: [Model]) {
var indexes = models
.flatMap { self.content.relation.index(of: $0) }
.map {IndexPath(row: $0, section: 0)}
let collectionView = self.collectionView
let content: Content<Model, View, Cell> = self.content
self.collectionView.performBatchUpdates({
indexes.forEach { content.relation.remove(at: $0.row) }
collectionView.deleteItems(at: indexes)
}, completion: nil)
}
open override func update(_ block: () -> (), completion: (() -> ())? = nil) {
self.collectionView.performBatchUpdates(block, completion: { finished in
completion?()
})
}
//Reload
open override func reload(_ models: [Model], animated: Bool) {
let indexes = self.indexPaths(models)
let collectionView = self.collectionView
// if animated {
collectionView.performBatchUpdates({
collectionView.reloadItems(at: indexes)
}, completion: nil)
// } else {
// collectionView.reloadItems(at: indexes)
// }
}
// Registration
override open func registerCell(_ reuseIdentifier: String, nib: UINib) {
self.collectionView.register(nib, forCellWithReuseIdentifier: reuseIdentifier)
}
open override func registerCell(_ reuseIdentifier: String, cell: AnyClass?) {
self.collectionView.register(cell, forCellWithReuseIdentifier: reuseIdentifier)
}
//MARK: - UICollectionView delegate
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! Cell
self.content.actions.onSelect?(self.content, self.content.relation[indexPath.row], cell)
if self.content.configuration.autoDeselect {
self.collectionView.deselectItem(at: indexPath, animated: true)
}
}
open func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? Cell {
self.content.actions.onDeselect?(self.content, self.content.relation[indexPath.row], cell)
}
}
open func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true;
}
//MARK: - UICollectionView data
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1;
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.content.relation.count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return self.collectionView(collectionView, cellForItemAt: indexPath, with: Cell.identifier)
}
//TODO: It is a workaround to achieve different rows for dequeue.
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath, with identifier: String) -> UICollectionViewCell {
let item = self.content.relation[indexPath.row]
let id = self.content.callbacks.onDequeueBlock?(item)?.identifier ?? identifier
let collectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: id, for: indexPath)
if var cell = collectionViewCell as? Cell {
cell.raiser = self.content
self.content.callbacks.onCellSetupBlock?(item, cell)
}
return collectionViewCell
}
open func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let item = self.content.relation[indexPath.row]
if var cell = cell as? Cell {
cell.raiser = self.content
self.content.callbacks.onCellDisplay?(item, cell)
}
}
open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return UICollectionReusableView()
}
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageWidth = scrollView.frame.width
let page = Int(scrollView.contentOffset.x / pageWidth)
self.content.callbacks.onItemChanged?(self.content, self.content.relation[page], page)
}
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.content.scrollCallbacks.onDidScroll?(self.content)
}
public func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
return true
}
open override func scrollToBottom() {
let bounds = self.collectionView.bounds
let origin = CGPoint(x: 0, y: self.collectionView.contentSize.height - bounds.size.height)
let rect = CGRect(origin: origin, size: bounds.size)
self.collectionView.scrollRectToVisible(rect, animated: true)
}
//MARK: - Utils
private var none : ContentScrollPosition {
let position: ContentScrollPosition = (self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.scrollDirection == .vertical ? .left : .top
return position
}
private var middle : ContentScrollPosition {
let position: ContentScrollPosition = (self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.scrollDirection == .vertical ? .centeredVertically : .centeredHorizontally
return position
}
override open func indexPath(_ cell: Cell) -> IndexPath? {
if let collectionViewCell = cell as? UICollectionViewCell {
return self.collectionView.indexPath(for: collectionViewCell)
}
return nil
}
}
open class CollectionFlowDelegate<Model: Equatable, View: ViewDelegate, Cell: ContentCell>: CollectionDelegate<Model, View, Cell>, UICollectionViewDelegateFlowLayout where View: UIView {
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if let size = self.content.callbacks.onLayout?(self.content, self.content.relation[indexPath.row]) ?? self.content.configuration.size {
return size
}
return collectionView.bounds.size
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return (collectionViewLayout as? UICollectionViewFlowLayout)?.sectionInset ?? .zero
}
}
| mit | 8f2688687ed4b42cbc62f2ed658f1e3e | 40.58885 | 195 | 0.654658 | 5.081311 | false | false | false | false |
fastai/course-v3 | nbs/swift/Imagenette/Sources/imagenette/main.swift | 1 | 1066 | import TensorFlow
import Path
import Foundation
import FastaiNotebook_11_imagenette
let path = downloadImagenette(sz:"-160")
let il = ItemList(fromFolder: path, extensions: ["jpeg", "jpg"])
let sd = SplitData(il) {grandParentSplitter(fName: $0, valid: "val")}
var procLabel = CategoryProcessor()
let sld = makeLabeledData(sd, fromFunc: parentLabeler, procLabel: &procLabel)
let rawData = sld.toDataBunch(itemToTensor: pathsToTensor, labelToTensor: intsToTensor, bs: 128)
let data = transformData(rawData) { openAndResize(fname: $0, size: 128) }
func modelInit() -> XResNet { return xresnet18(cOut: 10) }
let optFunc: (XResNet) -> StatefulOptimizer<XResNet> = adamOpt(lr: 1e-3, mom: 0.9, beta: 0.99, wd: 1e-2, eps: 1e-6)
let learner = Learner(data: data, lossFunc: softmaxCrossEntropy, optFunc: optFunc, modelInit: modelInit)
let recorder = learner.makeDefaultDelegates(metrics: [accuracy])
learner.addDelegate(learner.makeNormalize(mean: imagenetStats.mean, std: imagenetStats.std))
learner.addOneCycleDelegates(1e-3, pctStart: 0.5)
time { try! learner.fit(5) }
| apache-2.0 | 0782dcdb42e08d189e44300d31762d5a | 47.454545 | 115 | 0.75985 | 2.977654 | false | false | false | false |
ppamorim/iOS-Example | iOS-Example/ViewController/MapViewController.swift | 1 | 1415 | //
// Created by Pedro Paulo Amorim on 10/03/2015.
// Copyright (c) 2015 Pedro Paulo Amorim. 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.
//
import UIKit
import PureLayout
import MapKit
class MapViewController : UIViewController {
var didUpdateViews = false
let mapView : MKMapView = {
let mapView = MKMapView.newAutoLayoutView()
mapView.mapType = .Standard
return mapView
}()
override func loadView() {
super.loadView()
self.view.addSubview(mapView)
self.view.setNeedsUpdateConstraints()
}
override func updateViewConstraints() {
if(!didUpdateViews) {
mapView.autoMatchDimension(.Width, toDimension: .Width, ofView: self.view)
mapView.autoMatchDimension(.Height, toDimension: .Height, ofView: self.view)
didUpdateViews = true;
}
super.updateViewConstraints()
}
} | apache-2.0 | b2c0363cc4f5c76e50bfe594d53f4599 | 31.181818 | 82 | 0.728622 | 4.564516 | false | false | false | false |
luzefeng/Kanna | Source/libxml/libxmlParserOption.swift | 1 | 6007 | /**@file libxmlParserOption.swift
Kanna
Copyright (c) 2015 Atsushi Kiwaki (@_tid_)
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.
*/
/*
Libxml2HTMLParserOptions
*/
public struct Libxml2HTMLParserOptions : RawOptionSetType {
typealias RawValue = UInt
private var value: UInt = 0
init(_ value: UInt) { self.value = value }
private init(_ opt: htmlParserOption) { self.value = UInt(opt.value) }
public init(rawValue value: UInt) { self.value = value }
public init(nilLiteral: ()) { self.value = 0 }
public static var allZeros: Libxml2HTMLParserOptions { return self(0) }
static func fromMask(raw: UInt) -> Libxml2HTMLParserOptions { return self(raw) }
public var rawValue: UInt { return self.value }
static var STRICT: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(0) }
static var RECOVER: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_RECOVER) }
static var NODEFDTD: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NODEFDTD) }
static var NOERROR: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOERROR) }
static var NOWARNING: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOWARNING) }
static var PEDANTIC: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_PEDANTIC) }
static var NOBLANKS: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOBLANKS) }
static var NONET: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NONET) }
static var NOIMPLIED: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOIMPLIED) }
static var COMPACT: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_COMPACT) }
static var IGNORE_ENC: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_IGNORE_ENC) }
}
/*
Libxml2XMLParserOptions
*/
public struct Libxml2XMLParserOptions: RawOptionSetType {
typealias RawValue = UInt
private var value: UInt = 0
init(_ value: UInt) { self.value = value }
private init(_ opt: xmlParserOption) { self.value = UInt(opt.value) }
public init(rawValue value: UInt) { self.value = value }
public init(nilLiteral: ()) { self.value = 0 }
public static var allZeros: Libxml2XMLParserOptions { return self(0) }
static func fromMask(raw: UInt) -> Libxml2XMLParserOptions { return self(raw) }
public var rawValue: UInt { return self.value }
static var STRICT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(0) }
static var RECOVER: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_RECOVER) }
static var NOENT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOENT) }
static var DTDLOAD: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_DTDLOAD) }
static var DTDATTR: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_DTDATTR) }
static var DTDVALID: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_DTDVALID) }
static var NOERROR: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOERROR) }
static var NOWARNING: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOWARNING) }
static var PEDANTIC: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_PEDANTIC) }
static var NOBLANKS: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOBLANKS) }
static var SAX1: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_SAX1) }
static var XINCLUDE: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_XINCLUDE) }
static var NONET: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NONET) }
static var NODICT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NODICT) }
static var NSCLEAN: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NSCLEAN) }
static var NOCDATA: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOCDATA) }
static var NOXINCNODE: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOXINCNODE) }
static var COMPACT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_COMPACT) }
static var OLD10: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_OLD10) }
static var NOBASEFIX: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOBASEFIX) }
static var HUGE: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_HUGE) }
static var OLDSAX: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_OLDSAX) }
static var IGNORE_ENC: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_IGNORE_ENC) }
static var BIG_LINES: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_BIG_LINES) }
}
| mit | ae0b82616aeea26729edb53a6a3d1a9b | 65.010989 | 110 | 0.773764 | 3.801899 | false | false | false | false |
radex/swift-compiler-crashes | crashes-fuzzing/23156-clang-astcontext-getobjcencodingformethoddecl.swift | 11 | 1983 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
enum S<T where k.E == f {
{
protocol P {
class func f: P {
class A<
{
{
class B<T where f, g: a {
{
let t: P
class func b<T where I : e
struct B
{
class func g: T.C() {
struct Q<T where f<T where k.g == d:Any).g =b: P
typealias e where f
class
{
println() {
private let t: B
{false?protocol c,
println(object1: P {
"
{
class B<f: a {
{
{
private let a = {
class b: P
{
class A<T where h.E == e?
( {
{
class b<I : e?protocol P {
protocol c,
typealias e == {
class B<T where h.g == "
let t: P
class A {
let t: Array<T where I :A, b =
{
var d = [Void{
{
println(object1: P {
case c,
class A<T
{
let start = Int
class B<T.E == e:a
let t: T) {
"
protocol c
{
struct B<T where g: A<T.E == "
{
class B<T where g: B<I : a {
class b
class func f, g: a {
class b: e where H.E =
func f
}
}
{
struct c{
class A
class b
Void{
println("
func f: Array<I : e where k.h : A? {
}
protocol A {
var A : Array<T where h.E == d: e == e?
}
var b
class a {
{
class func < {
}
class b<I : e where k.c = e
struct B<T where g<T where f: P
let a = Int
class B<T where g: d : A
{
func f: e: e, AnyObject
}
{
func f<T where I.f : Array<T where f: A, d = "\(object1: T.B : A, d = e
var d = f : A<T where k.g == d<T where g: A? {
class A : P
{
struct B<I : Any {
va d<I : e : e, AnyObject, d {
{
{
class b<d = d> : Array<T where f: A, d : P {
class b<T where h.C() {
struct c,
{
enum S<I : T>
}
var d = d<T where g: Array<T where g: e
class b<T {
{
{
( {
( {
let d: P {
{
class b<T where g: e
class B
let a = {
{
class B
{
println() {
class a {
class a = a
"
class A : e where h.c : Array<T where g: d : e, b == Int
var b : Array<T where I.E =
enum S<T) -> : Array<T where h.E == {
class a = {
class B<T where g: Array<T where k.C() {
{
func f: Array<T where g: C {
let t: Array<T) {
{
{
var d = "
struct B<T where I.h : a = e?
va d> :
| mit | 2e364d3190907d9f2e66e82e3193663d | 13.580882 | 87 | 0.580938 | 2.27931 | false | false | false | false |
manavgabhawala/CookieManager | Cookie Manager/MainViewController.swift | 1 | 10011 | //
// MainViewController.swift
// Cookie Manager
//
// Created by Manav Gabhawala on 22/07/15.
// Copyright © 2015 Manav Gabhawala. All rights reserved.
//
// The MIT License (MIT)
// Copyright (c) 2015 Manav Gabhawala
//
// 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 Cocoa
class MainViewController: NSViewController
{
@IBOutlet var tableView: NSTableView!
@IBOutlet var sourceList: NSTableView!
@IBOutlet var splitView: NSView!
var store : CookieStore!
var selectedCookies = [HTTPCookie]()
var highlightedCookies = [HTTPCookie]()
var searchDomains : [HTTPCookieDomain]?
@IBOutlet var toolbar: NSToolbar!
@IBOutlet var cookieDomainsStatus: NSTextField!
@IBOutlet var cookiesStatus: NSTextField!
@IBOutlet var cookiesProgress: NSProgressIndicator!
override func viewDidLoad()
{
super.viewDidLoad()
// Do view setup here.
store = CookieStore(delegate: self)
tableView.setDataSource(self)
tableView.setDelegate(self)
sourceList.setDataSource(self)
sourceList.setDelegate(self)
cookiesProgress.doubleValue = 0.0
}
override func viewDidAppear()
{
super.viewDidAppear()
view.window?.toolbar = toolbar
for item in toolbar.items
{
if item.action == "removeCookie:"
{
item.enabled = false
}
}
}
}
// MARK: - Safari Cookie reader
extension MainViewController : CookieStoreDelegate
{
func updateLabels()
{
dispatch_async(dispatch_get_main_queue(), {
let cookieDomainCount = self.sourceList.selectedRowIndexes.count
let domainWord = cookieDomainCount == 1 ? "domain" : "domains"
self.cookieDomainsStatus.stringValue = "\(cookieDomainCount) cookie \(domainWord) out of \(self.store.domainCount)"
let cookieCount = self.selectedCookies.count
let cookieWord = cookieCount == 1 ? "cookie" : "cookies"
self.cookiesStatus.stringValue = "Displaying \(cookieCount) \(cookieWord) out of \(self.store.cookieCount)"
})
}
func startedParsingCookies()
{
dispatch_async(dispatch_get_main_queue(), {
self.cookiesProgress.alphaValue = 1.0
self.cookiesProgress.doubleValue = 0.0
})
}
func finishedParsingCookies()
{
dispatch_async(dispatch_get_main_queue(), {
self.updateLabels()
self.cookiesProgress.alphaValue = 0.0
self.sourceList.reloadData()
})
}
func stoppedTrackingCookiesForBrowser(browser: Browser)
{
// TODO: Show error.
}
func madeProgress(progress: Double)
{
dispatch_async(dispatch_get_main_queue(), {
self.cookiesProgress.doubleValue = progress * self.cookiesProgress.maxValue
})
}
func updatedCookies()
{
dispatch_async(dispatch_get_main_queue(), {
self.updateLabels()
self.sourceList.reloadData()
})
}
func fullUpdate()
{
dispatch_async(dispatch_get_main_queue(), {
let selectedIndices = self.sourceList.selectedRowIndexes
self.sourceList.reloadData()
self.updateLabels()
self.selectedCookies.removeAll(keepCapacity: true)
self.sourceList.selectRowIndexes(selectedIndices, byExtendingSelection: false)
for index in self.sourceList.selectedRowIndexes
{
guard index >= 0 && index < (self.searchDomains?.count ?? self.store.domainCount)
else
{
continue
}
let domain = (self.searchDomains?[index] ?? self.store.domainAtIndex(index))
domain?.cookies.map { self.selectedCookies.append($0) }
}
self.tableView.reloadData()
})
}
}
// MARK: - Table View
extension MainViewController : NSTableViewDataSource, NSTableViewDelegate
{
func numberOfRowsInTableView(tableView: NSTableView) -> Int
{
guard tableView !== sourceList
else
{
return store.domainCount
}
return selectedCookies.count
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView?
{
guard tableView !== sourceList
else
{
guard row < (searchDomains?.count ?? store.domainCount)
else { return nil }
let cell = tableView.makeViewWithIdentifier("cell", owner: self) as? NSTableCellView
cell?.textField?.stringValue = searchDomains?[row].domain ?? store.domainAtIndex(row)?.domain ?? ""
return cell
}
guard let id = tableColumn?.identifier
else
{
return nil
}
let view = tableView.makeViewWithIdentifier("\(id)_cell", owner: self) as? NSTableCellView
let cookie = selectedCookies[row]
switch id
{
case "browser":
view?.imageView?.image = cookie.browser.image
break
case "domain":
view?.textField?.stringValue = cookie.domain
break
case "name":
view?.textField?.stringValue = cookie.name
break
case "value":
view?.textField?.stringValue = cookie.value
break
case "path":
view?.textField?.stringValue = cookie.path
break
case "expires":
view?.textField?.stringValue = cookie.expiryDate?.descriptionWithLocale(NSLocale.currentLocale()) ?? "Session"
break
case "version":
view?.textField?.stringValue = cookie.versionDescription
break
case "secure":
view?.textField?.stringValue = cookie.secure ? "✓" : "✗"
break
case "http":
view?.textField?.stringValue = cookie.HTTPOnly ? "✓" : "✗"
break
case "comment":
view?.textField?.stringValue = cookie.comment ?? ""
break
default:
return nil
}
return view
}
func tableViewSelectionDidChange(notification: NSNotification)
{
defer
{
for item in toolbar.items
{
if item.action == "removeCookie:"
{
dispatch_async(dispatch_get_main_queue(), {
item.enabled = self.highlightedCookies.count > 0
})
}
}
}
highlightedCookies.removeAll(keepCapacity: true)
guard notification.object === sourceList
else
{
for index in tableView.selectedRowIndexes
{
guard index >= 0 && index < selectedCookies.count
else
{
continue
}
highlightedCookies.append(selectedCookies[index])
}
return
}
selectedCookies.removeAll(keepCapacity: true)
for index in sourceList.selectedRowIndexes
{
guard index >= 0 && index < (searchDomains?.count ?? store.domainCount)
else
{
continue
}
let domain = (searchDomains?[index] ?? store.domainAtIndex(index))
domain?.cookies.map { selectedCookies.append($0) }
}
tableView.reloadData()
updateLabels()
}
func tableView(tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor])
{
let newDescriptors = tableView.sortDescriptors
for descriptor in newDescriptors.reverse()
{
let order = descriptor.ascending ? NSComparisonResult.OrderedAscending : NSComparisonResult.OrderedDescending
guard let key = descriptor.key
else
{
continue
}
switch key
{
case "browser":
selectedCookies.sortInPlace { $0.browser.compare($1.browser) == order }
break
case "domain":
selectedCookies.sortInPlace { $0.domain.localizedCaseInsensitiveCompare($1.domain) == order }
break
case "name":
selectedCookies.sortInPlace { $0.name.localizedCaseInsensitiveCompare($1.name) == order }
break
case "value":
selectedCookies.sortInPlace { $0.value.localizedCaseInsensitiveCompare($1.value) == order }
break
case "path":
selectedCookies.sortInPlace { $0.path.localizedCaseInsensitiveCompare($1.path) == order }
break
case "expires":
selectedCookies.sortInPlace
{
guard $0.expiryDate != nil
else
{
return order == .OrderedDescending
}
guard $1.expiryDate != nil
else
{
return order == .OrderedAscending
}
return $0.expiryDate!.compare($1.expiryDate!) == order
}
break
case "version":
selectedCookies.sortInPlace { NSNumber(integer: $0.version).compare(NSNumber(integer: $1.version)) == order }
break
case "secure":
selectedCookies.sortInPlace { NSNumber(bool: $0.secure).compare(NSNumber(bool: $1.secure)) == order }
break
case "http":
selectedCookies.sortInPlace { NSNumber(bool: $0.HTTPOnly).compare(NSNumber(bool: $1.HTTPOnly)) == order }
break
case "comment":
selectedCookies.sortInPlace { ($0.comment ?? "").localizedCaseInsensitiveCompare(($1.comment ?? "")) == order }
break
default:
continue
}
}
tableView.reloadData()
}
}
// MARK: - Toolbar Actions
extension MainViewController : NSToolbarDelegate
{
@IBAction func addCookie(sender: NSToolbarItem)
{
}
@IBAction func search(sender: NSSearchField)
{
defer
{
selectedCookies = []
sourceList.reloadData()
tableView.reloadData()
}
let str = sender.stringValue
guard !str.isEmpty
else
{
searchDomains = nil
return
}
searchDomains = store.searchUsingString(str)
}
@IBAction func removeCookie(sender: NSToolbarItem)
{
highlightedCookies.removeAll(keepCapacity: true)
for index in tableView.selectedRowIndexes
{
guard index >= 0 && index < selectedCookies.count
else { continue }
highlightedCookies.append(selectedCookies[index])
}
do
{
try store.deleteCookies(highlightedCookies)
}
catch
{
// TODO: Show error
}
highlightedCookies.removeAll()
}
}
| mit | 878b27e0cb73799c0ffc0fb3e99be1d1 | 25.959569 | 118 | 0.705059 | 3.77719 | false | false | false | false |
PrazAs/ArithmeticSolver | ArithmeticSolver/ViewControllers/ArithmeticSolver/ArithmeticSolverViewController.swift | 1 | 2425 | //
// ViewController.swift
// ArithmeticSolver
//
// Created by Justin Makaila on 6/12/15.
// Copyright (c) 2015 Tabtor. All rights reserved.
//
import UIKit
import ReactiveCocoa
import TableAdapter
class ArithmeticSolverViewController: UIViewController {
let viewModel = ArithmeticSolverViewModel()
@IBOutlet
private var expressionTextField: UITextField!
@IBOutlet
private var solveButton: UIButton!
@IBOutlet
private var stepsTableView: UITableView!
private let tableViewDataSource = TableViewDataSource()
private let stepsTableViewSection = TableViewSection()
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
}
// MARK: - Private API
// MARK: Setup
private extension ArithmeticSolverViewController {
func setup() {
setupTableView()
setupSignals()
}
func setupSignals() {
// Bind `expressionTextField` text signal to `viewModel.expression`
RAC(viewModel, "expression") <~ expressionTextField.rac_textSignal()
/**
When `solveButton` receives a touch up inside event,
solve the expression, and update the table view.
*/
solveButton
.rac_signalForControlEvents(.TouchUpInside)
.flattenMap { _ in
return self.viewModel.solveExpressionSignal()
}
.subscribeNextAs { (solution: Solution) in
self.stepsTableViewSection.objects = solution.steps
self.tableViewDataSource.reloadSections()
}
}
func setupTableView() {
let stepCellIdentifier = "StepCell"
let stepCellNib = UINib(nibName: "StepCell", bundle: nil)
stepsTableView.estimatedRowHeight = 50
stepsTableView.registerNib(stepCellNib, forCellReuseIdentifier: stepCellIdentifier)
tableViewDataSource.tableView = stepsTableView
stepsTableViewSection.cellIdentifier = { _, _ in return stepCellIdentifier }
stepsTableViewSection.cellConfiguration = { cell, item, indexPath in
if let cell = cell as? StepCell, operation = item as? Operation {
let viewModel = StepCellViewModel(operation: operation)
cell.bindWithViewModel(viewModel)
}
}
tableViewDataSource.addSection(stepsTableViewSection)
}
}
| apache-2.0 | e5c3adac22f5bd6bdfb7b8ba16c2c03d | 28.573171 | 91 | 0.644536 | 5.400891 | false | false | false | false |
WalterCreazyBear/Swifter30 | BlueLib/BlueLib/ViewController.swift | 1 | 7905 | //
// ViewController.swift
// BlueLib
//
// Created by 熊伟 on 2017/7/1.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: - Private Variables
fileprivate var allAlbums = [Album]()
fileprivate var currentAlbumData : (titles:[String], values:[String])?
fileprivate var currentAlbumIndex = 0
// use a stack to push and pop operation for the undo option
fileprivate var undoStack: [(Album, Int)] = []
lazy var toolbar : UIToolbar = {
let view : UIToolbar = UIToolbar.init(frame: CGRect.init(x: 0, y: UIScreen.main.bounds.height-40, width: UIScreen.main.bounds.width, height: 40))
let undoButton = UIBarButtonItem(barButtonSystemItem: .undo, target: self, action:#selector(ViewController.undoAction))
undoButton.isEnabled = false;
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target:nil, action:nil)
let trashButton = UIBarButtonItem(barButtonSystemItem: .trash, target:self, action:#selector(ViewController.deleteAlbum))
let toolbarButtonItems = [undoButton, space, trashButton]
view.setItems(toolbarButtonItems, animated: true)
return view
}()
lazy var scroller : HorizontalScroller = {
let view : HorizontalScroller = HorizontalScroller.init(frame: CGRect.init(x: 0, y: 24, width: UIScreen.main.bounds.width, height: 120))
view.delegate = self
return view
}()
lazy var tableView : UITableView = {
let tableView = UITableView.init(frame: CGRect.init(x: 0, y: 144, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-120))
tableView.dataSource = self
tableView.backgroundColor = UIColor.white
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(toolbar)
view.addSubview(tableView)
view.addSubview(scroller)
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.saveCurrentState), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
setupData()
setupUI()
setupComponents()
showDataForAlbum(currentAlbumIndex)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func setupUI() {
navigationController?.navigationBar.isTranslucent = false
}
func setupData() {
currentAlbumIndex = 0
allAlbums = LibraryAPI.sharedInstance.getAlbums()
}
func setupComponents() {
tableView.backgroundView = nil
loadPreviousState()
scroller.delegate = self
reloadScroller()
}
// MARK: - Memento Pattern
func saveCurrentState() {
// When the user leaves the app and then comes back again, he wants it to be in the exact same state
// he left it. In order to do this we need to save the currently displayed album.
// Since it's only one piece of information we can use NSUserDefaults.
UserDefaults.standard.set(currentAlbumIndex, forKey: "currentAlbumIndex")
LibraryAPI.sharedInstance.saveAlbums()
}
func loadPreviousState() {
currentAlbumIndex = UserDefaults.standard.integer(forKey: "currentAlbumIndex")
showDataForAlbum(currentAlbumIndex)
}
// MARK: - Scroller Related
func reloadScroller() {
allAlbums = LibraryAPI.sharedInstance.getAlbums()
if currentAlbumIndex < 0 {
currentAlbumIndex = 0
} else if currentAlbumIndex >= allAlbums.count {
currentAlbumIndex = allAlbums.count - 1
}
scroller.reload()
showDataForAlbum(currentAlbumIndex)
}
func showDataForAlbum(_ index: Int) {
if index < allAlbums.count && index > -1 {
let album = allAlbums[index]
currentAlbumData = album.ae_tableRepresentation()
} else {
currentAlbumData = nil
}
tableView.reloadData()
}
func deleteAlbum() {
// get album
let deletedAlbum : Album = allAlbums[currentAlbumIndex]
// add to stack
let undoAction = (deletedAlbum, currentAlbumIndex)
undoStack.insert(undoAction, at: 0)
// use library API to delete the album
LibraryAPI.sharedInstance.deleteAlbum(currentAlbumIndex)
reloadScroller()
// enable the undo button
let barButtonItems = toolbar.items! as [UIBarButtonItem]
let undoButton : UIBarButtonItem = barButtonItems[0]
undoButton.isEnabled = true
// disable trashbutton when no albums left
if (allAlbums.count == 0) {
let trashButton : UIBarButtonItem = barButtonItems[2]
trashButton.isEnabled = false
}
}
func undoAction() {
let barButtonItems = toolbar.items! as [UIBarButtonItem]
// pop to undo the last one
if undoStack.count > 0 {
let (deletedAlbum, index) = undoStack.remove(at: 0)
addAlbumAtIndex(deletedAlbum, index: index)
}
// disable undo button when no albums left
if undoStack.count == 0 {
let undoButton : UIBarButtonItem = barButtonItems[0]
undoButton.isEnabled = false
}
// enable the trashButton as there must be at least one album there
let trashButton : UIBarButtonItem = barButtonItems[2]
trashButton.isEnabled = true
}
func addAlbumAtIndex(_ album: Album,index: Int) {
LibraryAPI.sharedInstance.addAlbum(album, index: index)
currentAlbumIndex = index
reloadScroller()
}
}
// MARK: - HorizontalScroller
extension ViewController: HorizontalScrollerDelegate {
func numberOfViewsForHorizontalScroller(_ scroller: HorizontalScroller) -> Int {
return allAlbums.count
}
func horizontalScrollerViewAtIndex(_ scroller: HorizontalScroller, index: Int) -> UIView {
let album = allAlbums[index]
let albumView = AlbumView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), albumCover: album.coverUrl)
if currentAlbumIndex == index {
albumView.highlightAlbum(true)
} else {
albumView.highlightAlbum(false)
}
return albumView
}
func horizontalScrollerClickedViewAtIndex(_ scroller: HorizontalScroller, index: Int) {
let previousAlbumView = scroller.viewAtIndex(currentAlbumIndex) as! AlbumView
previousAlbumView.highlightAlbum(false)
currentAlbumIndex = index
let albumView = scroller.viewAtIndex(currentAlbumIndex) as! AlbumView
albumView.highlightAlbum(true)
showDataForAlbum(currentAlbumIndex)
}
func initialViewIndex(_ scroller: HorizontalScroller) -> Int {
return currentAlbumIndex
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let albumData = currentAlbumData {
return albumData.titles.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = UITableViewCell.init(style: .value1, reuseIdentifier: "cellid")
if let albumData = currentAlbumData {
cell.textLabel?.text = albumData.titles[(indexPath as NSIndexPath).row]
cell.detailTextLabel?.text = albumData.values[(indexPath as NSIndexPath).row]
}
return cell
}
}
| mit | 35ba471451d5ff7c431e317aed1699f9 | 32.752137 | 177 | 0.639276 | 4.939337 | false | false | false | false |
MBKwon/SwiftTimer | TestSwift/TestSwift/Timer State/TimerReset.swift | 1 | 1307 | //
// TimerReset.swift
// TestSwift
//
// Created by MB KWON on 2014. 7. 28..
// Copyright (c) 2014년 UANGEL Corp. All rights reserved.
//
import Foundation
import UIKit
class TimerReset : NSObject, TimerProtocol {
weak var timerController: TimerViewController?
init(timerController: TimerViewController!) {
if timerController {
self.timerController = timerController
self.timerController!.stateLabel!.text = "Reset State"
self.timerController!.timeLabel!.text = "00.00"
self.timerController!.runningTime = 0.0
self.timerController!.stoppedTime = 0.0
self.timerController!.startBtn!.setTitle("Start", forState: UIControlState.Normal)
self.timerController!.resetBtn!.setTitle("Reset", forState: UIControlState.Normal)
self.timerController!.resetBtn!.enabled = false
self.timerController!.logBtn!.enabled = true
}
}
func touchUpStartBtn() {
NSRunLoop.mainRunLoop().addTimer(timerController?.stopWatchTimer, forMode: NSDefaultRunLoopMode)
self.timerController!.timerDelegate = TimerRunning(timerController: self.timerController);
}
func touchUpResetBtn() {
// do not anything.
}
}
| mit | 12dc3b6f670370f0a1bfb7c54f92fe80 | 31.625 | 104 | 0.651341 | 4.677419 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/peeking-iterator.swift | 2 | 2362 | /**
* https://leetcode.com/problems/peeking-iterator/
*
*
*/
// Date: Mon Feb 8 09:39:51 PST 2021
// Swift IndexingIterator refernence:
// https://developer.apple.com/documentation/swift/indexingiterator
class PeekingIterator {
var list: IndexingIterator<Array<Int>>
var peekElement: Int?
init(_ arr: IndexingIterator<Array<Int>>) {
self.list = arr
peekElement = self.list.next()
}
func next() -> Int {
guard let element = self.peekElement else { fatalError() }
self.peekElement = self.list.next()
return element
}
func peek() -> Int {
return self.peekElement!
}
func hasNext() -> Bool {
return self.peekElement != nil
}
}
/**
* Your PeekingIterator object will be instantiated and called as such:
* let obj = PeekingIterator(arr)
* let ret_1: Int = obj.next()
* let ret_2: Int = obj.peek()
* let ret_3: Bool = obj.hasNext()
*//**
* https://leetcode.com/problems/peeking-iterator/
*
*
*/
// Date: Mon Feb 8 09:48:18 PST 2021
// Swift IndexingIterator refernence:
// https://developer.apple.com/documentation/swift/indexingiterator
class PeekingIterator {
var list: PeekingIteratorGeneric<Array<Int>>
init(_ arr: IndexingIterator<Array<Int>>) {
self.list = PeekingIteratorGeneric(arr)
}
func next() -> Int {
return self.list.next()
}
func peek() -> Int {
return self.list.peek()
}
func hasNext() -> Bool {
return self.list.hasNext()
}
}
class PeekingIteratorGeneric<T: Collection> {
var elements: IndexingIterator<T>
var nextElement: T.Element?
init(_ arr: IndexingIterator<T>) {
self.elements = arr
self.nextElement = self.elements.next()
}
func next() -> T.Element {
guard let element = self.nextElement else { fatalError() }
self.nextElement = self.elements.next()
return element
}
func peek() -> T.Element {
guard let element = self.nextElement else { fatalError() }
return element
}
func hasNext() -> Bool {
return self.nextElement != nil
}
}
/**
* Your PeekingIterator object will be instantiated and called as such:
* let obj = PeekingIterator(arr)
* let ret_1: Int = obj.next()
* let ret_2: Int = obj.peek()
* let ret_3: Bool = obj.hasNext()
*/ | mit | 4159f70513a60b67872d7497f4bd457b | 23.112245 | 71 | 0.618967 | 3.797428 | false | false | false | false |
openHPI/xikolo-ios | iOS/Views/CertificateCell.swift | 1 | 3756 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Common
import UIKit
class CertificateCell: UICollectionViewCell {
@IBOutlet private weak var descriptionLabel: UILabel!
@IBOutlet private weak var shadowView: UIView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var statusLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.shadowView.layer.roundCorners(for: .default, masksToBounds: false)
self.shadowView.addDefaultPointerInteraction()
}
func configure(_ name: String, explanation: String?, url: URL?, stateOfCertificate: String) {
self.titleLabel.text = name
self.descriptionLabel.text = explanation
self.statusLabel.text = stateOfCertificate
let achieved = url != nil
self.isUserInteractionEnabled = achieved
let cardColor = achieved ? Brand.default.colors.primary : ColorCompatibility.systemGray3
self.shadowView.backgroundColor = cardColor
self.titleLabel.backgroundColor = cardColor
self.statusLabel.backgroundColor = cardColor
let textColor = achieved ? UIColor.white : ColorCompatibility.label
self.titleLabel.textColor = textColor
self.statusLabel.textColor = textColor
}
}
extension CertificateCell {
static func minimalWidth(for traitCollection: UITraitCollection) -> CGFloat { // swiftlint:disable:this cyclomatic_complexity
switch traitCollection.preferredContentSizeCategory {
case .extraSmall:
return 270
case .small:
return 280
case .medium:
return 290
case .extraLarge:
return 310
case .extraExtraLarge:
return 320
case .extraExtraExtraLarge:
return 330
// Accessibility sizes
case .accessibilityMedium:
return 370
case .accessibilityLarge:
return 390
case .accessibilityExtraLarge:
return 410
case .accessibilityExtraExtraLarge:
return 430
case .accessibilityExtraExtraExtraLarge:
return 450
default: // large
return 300
}
}
}
extension CertificateCell {
static var cardInset: CGFloat {
return 14
}
static func height(for certificate: Course.Certificate, forWidth width: CGFloat, delegate: CertificateCellDelegate) -> CGFloat {
let cardMargin = Self.cardInset
let cardPadding: CGFloat = 16
let cardWidth = width - 2 * cardMargin
let textWidth = cardWidth - 2 * cardPadding
let titleHeight = delegate.maximalHeightForTitle(withWidth: textWidth)
let statusHeight = delegate.maximalHeightForStatus(withWidth: textWidth)
let explanationHeight = certificate.explanation?.height(forTextStyle: .footnote, boundingWidth: cardWidth) ?? 0
var height = cardMargin
height += 2 * cardPadding
height += 8
height += 8
height += titleHeight
height += statusHeight
height += explanationHeight
height += 5
return height
}
static func heightForTitle(_ title: String, withWidth width: CGFloat) -> CGFloat {
return title.height(forTextStyle: .headline, boundingWidth: width)
}
static func heightForStatus(_ status: String, withWidth width: CGFloat) -> CGFloat {
return status.height(forTextStyle: .subheadline, boundingWidth: width)
}
}
protocol CertificateCellDelegate: AnyObject {
func maximalHeightForTitle(withWidth width: CGFloat) -> CGFloat
func maximalHeightForStatus(withWidth width: CGFloat) -> CGFloat
}
| gpl-3.0 | 7c3a52c42c503335507b99ef68e25f01 | 30.291667 | 132 | 0.667909 | 5.318697 | false | false | false | false |
cotkjaer/Silverback | Silverback/FloatAnimator.swift | 1 | 1011 | //
// FloatAnimator.swift
// Silverback
//
// Created by Christian Otkjær on 04/11/15.
// Copyright © 2015 Christian Otkjær. All rights reserved.
//
public class FloatAnimator
{
private let StepSize : Float = 1.0/30.0
private var tasks = Array<Task>()
var setter : ((Float) -> ())!
var getter : (() -> Float)!
public init(setter: Float -> () = { _ in }, getter: () -> Float = { return 0 })
{
self.getter = getter
self.setter = setter
}
public func animateFloat(to: Float, duration: Double)
{
tasks.forEach { $0.unschedule() }
tasks.removeAll(keepCapacity: true)
let T = Float(max(0.1, duration))
let from = getter()
//liniear easing function
let f = { (t: Float) -> Float in return (from * (T - t) + to * t) / T }
T.stride(to: 0, by: -StepSize).forEach { let v = f($0); self.tasks.append(Task(delay: Double($0), closure: { self.setter(v) })) }
}
}
| mit | 6756ac5b005e0619ba71c13685997d48 | 26.243243 | 137 | 0.544643 | 3.6 | false | false | false | false |
mayfield/strava-sauce | safari/Sauce for Strava™/Shared (App)/ViewController.swift | 1 | 2159 | //
// ViewController.swift
// Shared (App)
//
import WebKit
#if os(iOS)
import UIKit
typealias PlatformViewController = UIViewController
#elseif os(macOS)
import Cocoa
import SafariServices
typealias PlatformViewController = NSViewController
#endif
let extensionBundleIdentifier = "io.saucellc.sauce4strava.Extension"
class ViewController: PlatformViewController, WKNavigationDelegate, WKScriptMessageHandler {
@IBOutlet var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.webView.navigationDelegate = self
#if os(iOS)
self.webView.scrollView.isScrollEnabled = false
#endif
self.webView.configuration.userContentController.add(self, name: "controller")
self.webView.loadFileURL(Bundle.main.url(forResource: "Main", withExtension: "html")!, allowingReadAccessTo: Bundle.main.resourceURL!)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
#if os(iOS)
webView.evaluateJavaScript("show('ios')")
#elseif os(macOS)
webView.evaluateJavaScript("show('mac')")
SFSafariExtensionManager.getStateOfSafariExtension(withIdentifier: extensionBundleIdentifier) { (state, error) in
guard let state = state, error == nil else {
// Insert code to inform the user that something went wrong.
return
}
DispatchQueue.main.async {
webView.evaluateJavaScript("show('mac', \(state.isEnabled)")
}
}
#endif
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
#if os(macOS)
if (message.body as! String != "open-preferences") {
return;
}
SFSafariApplication.showPreferencesForExtension(withIdentifier: extensionBundleIdentifier) { error in
guard error == nil else {
// Insert code to inform the user that something went wrong.
return
}
DispatchQueue.main.async {
NSApplication.shared.terminate(nil)
}
}
#endif
}
}
| mit | f688982dda4c3b9db0c930d3869e842c | 27.786667 | 142 | 0.666512 | 4.974654 | false | false | false | false |
brunodlz/Transaction | ExampleWithStoryboard/ExampleWithStoryboard/ViewController.swift | 1 | 1200 | import UIKit
import Transaction
enum Segue: String {
case First
case Second
}
class ViewController: UIViewController {
let animation = Transaction()
override func viewDidLoad() {
super.viewDidLoad()
showFirstSegue()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Segue.First.rawValue {
animation.startOn(current: self,
destination: segue.destination,
animation: .transitionFlipFromRight)
}
else if segue.identifier == Segue.Second.rawValue {
animation.startOn(current: self,
destination: segue.destination,
animation: .transitionFlipFromLeft)
}
}
func showFirstSegue() {
performSegue(withIdentifier: Segue.First.rawValue,
sender: nil)
}
func showSecondSegue() {
performSegue(withIdentifier: Segue.Second.rawValue,
sender: nil)
}
}
| mit | 0e71a0830b696e2e7dda6142cabc878a | 25.086957 | 71 | 0.565833 | 5.660377 | false | false | false | false |
apozdeyev/ReactiveEureka | Example/Tests/RowSignalSpec.swift | 1 | 1238 | import Quick
import Nimble
import UIKit
import Eureka
import ReactiveCocoa
import ReactiveSwift
import Result
@testable import ReactiveEureka
@testable import ReactiveEureka_Example
class RowSignalSpec: QuickSpec {
var vc: TapsCountVC!
override func spec() {
beforeEach {
self.vc = TapsCountVC.load()
}
describe("Row value signal") {
it("Row value changing events are emitted when the user text in row's cell is chamged") {
let tapsCountRow = self.vc.form.rowBy(tag: TapsCountVC.RowTag.TapsCount) as! TextRow
let buttonRow = self.vc.form.rowBy(tag: TapsCountVC.RowTag.Button) as! ButtonRow
let tapsCount = MutableProperty<Int>(0)
tapsCount <~ tapsCountRow.reactive.values.map { Int($0!)! }
expect(tapsCount.value) == 0
buttonRow.didSelect()
expect(tapsCount.value) == 1
buttonRow.didSelect()
expect(tapsCount.value) == 2
}
it("Signal of row value changing events sends completed event when the row is released") {
var tapsCountRow:TextRow? = TextRow()
var counter = 0
tapsCountRow!.reactive.values.observeCompleted {
counter += 1
}
expect(counter) == 0
tapsCountRow = nil
expect(counter) == 1
}
}
}
}
| mit | 1dec072845c83daa58c03a2377fd13b8 | 23.76 | 93 | 0.684168 | 3.609329 | false | false | false | false |
pekoto/fightydot | FightyDot/FightyDot/MillView.swift | 1 | 2591 | //
// MillImageView.swift
// FightyDot
//
// Created by Graham McRobbie on 07/02/2017.
// Copyright © 2017 Graham McRobbie. All rights reserved.
//
import UIKit
class MillView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setColourEmpty()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setColourEmpty()
}
func animate(to newColour: UIColor, completion: (() -> ())?) {
let constraintId = getConstraintId()
let animationDirection = getAnimationDirection()
self.updateConstraintWith(id: constraintId, to: Constants.Constraints.activeMillThickness)
self.changeColour(to: newColour, direction: animationDirection) {
completion?()
}
}
func reset() {
let constraintId = getConstraintId()
var animationDirection = getAnimationDirection()
animationDirection.reverse()
self.updateConstraintWith(id: constraintId, to: Constants.Constraints.defaultMillThickness)
self.changeColour(to: Constants.Colours.emptyMillColour, direction: animationDirection)
}
// MARK: - Private functions
// Used to normalize colour space (required when comparing colours)
private func setColourEmpty() {
self.backgroundColor = Constants.Colours.emptyMillColour
}
// Vertical views change their width, horizontal views change their height
private func getConstraintId() -> String {
if(isVerticalMill()) {
return Constants.Constraints.widthId
} else {
return Constants.Constraints.heightId
}
}
private func getAnimationDirection() -> AnimationDirection {
if(isVerticalMill()) {
if(isTopMillHalf()) {
return .Up
} else {
return.Down
}
} else {
if(isLeftMillHalf()) {
return .Left
} else {
return .Right
}
}
}
private func isTopMillHalf() -> Bool {
return (self.tag % 2) == 0
}
private func isLeftMillHalf() -> Bool {
return (self.tag % 2) == 0
}
private func isVerticalMill() -> Bool {
return getParentId() >= Constants.GameplayNumbers.verticalMillStartIndex
}
// A single mill is made of two images.
// So to get the parent ID of the images, we just divide by 2.
private func getParentId() -> Int {
return self.tag/2
}
}
| mit | 3ecc9daf90b3dc1e4b1e6881ce2aef5d | 27.461538 | 99 | 0.594981 | 4.683544 | false | false | false | false |
arvedviehweger/swift | test/decl/protocol/special/coding/class_codable_inheritance.swift | 1 | 2591 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
class SimpleClass : Codable {
var x: Int = 1
var y: Double = .pi
static var z: String = "foo"
}
// The synthesized CodingKeys type should not be accessible from outside the
// class.
let _ = SimpleClass.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
// Classes which inherit from classes that are codable should synthesize Codable
// conformance as well.
class SimpleChildClass : SimpleClass {
var w: Bool = true
// NOTE: These tests will fail in the future as Codable classes are updated
// to derive Codable conformance instead of inheriting their
// superclass's. Classes currently inherit their parent's Codable
// conformance and we never get the chance to derive a CodingKeys
// type, nor overridden methods.
// These lines have to be within the SimpleChildClass type because
// CodingKeys should be private.
func foo() {
// They should receive a synthesized CodingKeys enum.
// NOTE: This expected error will need to be removed in the future.
let _ = SimpleChildClass.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
// The enum should have a case for each of the vars.
// NOTE: This expectedxerror will need to be removed in the future.
let _ = SimpleChildClass.CodingKeys.w // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
// Inherited vars should not be part of the CodingKeys enum.
// NOTE: This expected error will need to be updated in the future.
// Should be `type 'SimpleClass.CodingKeys' has no member 'x'`
let _ = SimpleChildClass.CodingKeys.x // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
// NOTE: This expected error will need to be updated in the future.
// Should be `type 'SimpleClass.CodingKeys' has no member 'y'`
let _ = SimpleChildClass.CodingKeys.y // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
}
}
// These are wrapped in a dummy function to avoid binding a global variable.
func foo() {
// They should receive synthesized init(from:) and an encode(to:).
let _ = SimpleChildClass.init(from:)
let _ = SimpleChildClass.encode(to:)
// The synthesized CodingKeys type should not be accessible from outside the
// class.
let _ = SimpleChildClass.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
}
| apache-2.0 | db317fc45aa9d7d950387ea9be4e0cfe | 46.109091 | 129 | 0.717484 | 4.42906 | false | false | false | false |
BPForEveryone/BloodPressureForEveryone | BPApp/Shared/BloodPressureMeasurement.swift | 1 | 1896 | //
// BloodPressureMeasurement.swift
// BPApp
//
// Created by MiningMarsh on 9/27/17.
// Copyright © 2017 BlackstoneBuilds. All rights reserved.
//
import Foundation
import os.log
public class BloodPressureMeasurement: NSObject, NSCoding {
var systolic: Int
var diastolic: Int
var measurementDate: Date
// The properties to save for a patients, make sure this reflects with the properties patients have.
struct PropertyKey {
static let systolic = "systolic"
static let diastolic = "diastolic"
static let measurementDate = "measurementDate"
}
// Create a new blood pressure reading
init?(systolic: Int, diastolic: Int, measurementDate: Date) {
self.systolic = systolic
self.diastolic = diastolic
self.measurementDate = measurementDate
}
// Encoder used to store a patient.
public func encode(with encoder: NSCoder) {
encoder.encode(systolic, forKey: PropertyKey.systolic)
encoder.encode(diastolic, forKey: PropertyKey.diastolic)
encoder.encode(measurementDate, forKey: PropertyKey.measurementDate)
}
public required convenience init?(coder decoder: NSCoder) {
let systolic = decoder.decodeInteger(forKey: PropertyKey.systolic)
let diastolic = decoder.decodeInteger(forKey: PropertyKey.diastolic)
// Date is required.
guard let measurementDate = decoder.decodeObject(forKey: PropertyKey.measurementDate) as? Date else {
os_log("Unable to decode the measurement date for a BloodPressureMeasurement object.", log: OSLog.default, type: .debug)
return nil
}
// Initialize with decoded values.
self.init(
systolic: systolic,
diastolic: diastolic,
measurementDate: measurementDate
)
}
}
| mit | d24966d4d55d9d576871fcd47535b345 | 31.672414 | 132 | 0.661214 | 4.7733 | false | false | false | false |
segmentio/analytics-swift | Sources/Segment/Plugins/Logger/LogTarget.swift | 1 | 8810 | //
// LogTarget.swift
// LogTarget
//
// Created by Cody Garvin on 8/19/21.
//
import Foundation
// MARK: - Logging Types
/// The foundation for building out a special logger. If logs need to be directed to a certain area, this is the
/// interface to start off with. For instance a console logger, a networking logger or offline storage logger
/// would all start off with LogTarget.
public protocol LogTarget {
/// Implement this method to process logging messages. This is where the logic for the target will be
/// added. Feel free to add your own data queueing and offline storage.
/// - important: Use the Segment Network stack for Segment library compatibility and simplicity.
func parseLog(_ log: LogMessage)
/// Optional method to implement. This helps respond to potential queueing events being flushed out.
/// Perhaps responding to backgrounding or networking events, this gives a chance to empty a queue
/// or pump a firehose of logs.
func flush()
}
/// Used for analytics.log() types. This lets the system know what to filter on and how to set priorities.
public enum LogFilterKind: Int {
case error = 0 // Not Verbose (fail cases | non-recoverable errors)
case warning // Semi-verbose (deprecations | potential issues)
case debug // Verbose (everything of interest)
func toString() -> String {
switch (self) {
case .error:
return "ERROR"
case .warning:
return "Warning"
case .debug:
return "Debug"
}
}
}
/// The Segment logging system has three types of logs: log, metric and history. When adding a target that
/// responds to logs, it is possible to adhere to 1 to many. In other words, a LoggingType can be .log &
/// .history. This is used to tell which targets logs are directed to.
public struct LoggingType: Hashable {
public enum LogDestination {
case log
case metric
case history
}
/// Convenience .log logging type
static let log = LoggingType(types: [.log])
/// Convenience .metric logging type
static let metric = LoggingType(types: [.metric])
/// Convenience .history logging type
static let history = LoggingType(types: [.history])
/// Designated initializer for LoggingType. Add all the destinations this LoggingType should support.
/// - Parameter types: The LoggingDestination(s) that this LoggingType will support.
public init(types: [LogDestination]) {
// TODO: Failable scenario if types empty
self.allTypes = types
}
// - Private Properties and Methods
private let allTypes: [LogDestination]
/// Convience method to find if the LoggingType supports a particular destination.
/// - Parameter destination: The particular destination being tested for conformance.
/// - Returns: If the destination exists in this LoggingType `true` or `false` will be returned.
internal func contains(_ destination: LogDestination) -> Bool {
return allTypes.contains(destination)
}
}
/// The interface to the message being returned to `LogTarget` -> `parseLog()`.
public protocol LogMessage {
var kind: LogFilterKind { get }
var title: String? { get }
var message: String { get }
var event: RawEvent? { get }
var function: String? { get }
var line: Int? { get }
var logType: LoggingType.LogDestination { get }
var dateTime: Date { get }
}
public enum MetricType: Int {
case counter = 0 // Not Verbose
case gauge // Semi-verbose
func toString() -> String {
var typeString = "Gauge"
if self == .counter {
typeString = "Counter"
}
return typeString
}
static func fromString(_ string: String) -> Self {
var returnType = Self.counter
if string == "Gauge" {
returnType = .gauge
}
return returnType
}
}
// MARK: - Public Logging API
extension Analytics {
/// The public logging method for capturing all general types of log messages related to Segment.
/// - Parameters:
/// - message: The main message of the log to be captured.
/// - kind: Usually .error, .warning or .debug, in order of serverity. This helps filter logs based on
/// this added metadata.
/// - function: The name of the function the log came from. This will be captured automatically.
/// - line: The line number in the function the log came from. This will be captured automatically.
public func log(message: String, kind: LogFilterKind? = nil, function: String = #function, line: Int = #line) {
apply { plugin in
// Check if we should send off the event
if SegmentLog.loggingEnabled == false {
return
}
if let loggerPlugin = plugin as? SegmentLog {
var filterKind = loggerPlugin.filterKind
if let logKind = kind {
filterKind = logKind
}
let log = LogFactory.buildLog(destination: .log, title: "", message: message, kind: filterKind, function: function, line: line)
loggerPlugin.log(log, destination: .log)
}
}
}
/// The public logging method for capturing metrics related to Segment or other libraries.
/// - Parameters:
/// - type: Metric type, usually .counter or .gauge. Select the one that makes sense for the metric.
/// - name: The title of the metric to track.
/// - value: The value associated with the metric. This would be an incrementing counter or time
/// or pressure gauge.
/// - tags: Any tags that should be associated with the metric. Any extra metadata that may help.
public func metric(_ type: MetricType, name: String, value: Double, tags: [String]? = nil) {
apply { plugin in
// Check if we should send off the event
if SegmentLog.loggingEnabled == false {
return
}
if let loggerPlugin = plugin as? SegmentLog {
let log = LogFactory.buildLog(destination: .metric, title: type.toString(), message: name, value: value, tags: tags)
loggerPlugin.log(log, destination: .metric)
}
}
}
/// Used to track the history of events as the event data travels through the Segment Event Timeline. As
/// plugins manipulate the data at the `before`, `enrichment`, `destination`,
/// `destination timeline`, and `after` states, an event can be tracked. Starting with the first one
/// - Parameters:
/// - event: The timeline event that is to be processed.
/// - sender: Where the event came from.
/// - function: The name of the function the log came from. This will be captured automatically.
/// - line: The line number in the function the log came from. This will be captured automatically.
public func history(event: RawEvent, sender: AnyObject, function: String = #function, line: Int = #line) {
apply { plugin in
// Check if we should send off the event
if SegmentLog.loggingEnabled == false {
return
}
if let loggerPlugin = plugin as? SegmentLog {
let log = LogFactory.buildLog(destination: .history, title: event.toString(), message: "", function: function, line: line, event: event, sender: sender)
loggerPlugin.log(log, destination: .metric)
}
}
}
}
extension Analytics {
/// Add a logging target to the system. These `targets` can handle logs in various ways. Consider
/// sending logs to the console, the OS and a web service. Three targets can handle these scenarios.
/// - Parameters:
/// - target: A `LogTarget` that has logic to parse and handle log messages.
/// - type: The type consists of `log`, `metric` or `history`. These correspond to the
/// public API on Analytics.
public func add(target: LogTarget, type: LoggingType) {
apply { (potentialLogger) in
if let logger = potentialLogger as? SegmentLog {
do {
try logger.add(target: target, for: type)
} catch {
Self.segmentLog(message: "Could not add target: \(error.localizedDescription)", kind: .error)
}
}
}
}
public func logFlush() {
apply { (potentialLogger) in
if let logger = potentialLogger as? SegmentLog {
logger.flush()
}
}
}
}
| mit | 895f802178ac7380c084bfae5f7f272d | 39.045455 | 168 | 0.61941 | 4.68119 | false | false | false | false |
ifLab/WeCenterMobile-iOS | WeCenterMobile/Model/DataObject/Topic.swift | 3 | 9817 | //
// Topic.swift
// WeCenterMobile
//
// Created by Darren Liu on 14/10/7.
// Copyright (c) 2014年 ifLab. All rights reserved.
//
import AFNetworking
import CoreData
import UIKit
enum TopicObjectListType: String {
case Month = "month"
case Week = "weeek"
case All = "all"
case Focus = "focus"
}
class Topic: DataObject {
@NSManaged var focusCount: NSNumber?
@NSManaged var imageURI: String?
@NSManaged var introduction: String?
@NSManaged var title: String?
@NSManaged var articles: Set<Article>
@NSManaged var questions: Set<Question>
@NSManaged var users: Set<User>
@NSManaged var imageData: NSData?
var focused: Bool? = nil
var imageURL: String? {
get {
return (imageURI == nil) ? nil : NetworkManager.defaultManager!.website + NetworkManager.defaultManager!.paths["Topic Image"]! + imageURI!
}
set {
if let replacedString = newValue?.stringByReplacingOccurrencesOfString(NetworkManager.defaultManager!.website + NetworkManager.defaultManager!.paths["Topic Image"]!, withString: "") {
if replacedString != newValue {
imageURI = replacedString
} else {
imageURI = nil
}
} else {
imageURI = nil
}
}
}
var image: UIImage? {
get {
return (imageData == nil) ? nil : UIImage(data: imageData!)
}
set {
imageData = newValue == nil ? nil : UIImagePNGRepresentation(newValue!)
}
}
class func fetch(ID ID: NSNumber, success: ((Topic) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.GET("Topic Detail",
parameters: [
"id": ID
],
success: {
data in
let topic = Topic.cachedObjectWithID(ID)
topic.title = data["topic_title"] as? String
topic.introduction = data["topic_description"] as? String
topic.imageURI = data["topic_pic"] as? String
topic.focusCount = Int(msr_object: data["focus_count"]!!)
topic.focused = Int(msr_object: data["has_focus"]) == 1
_ = try? DataManager.defaultManager.saveChanges()
success?(topic)
},
failure: failure)
}
class func fetchHotTopic(page page: Int, count: Int, type: TopicObjectListType, success: (([Topic]) -> Void)?, failure: ((NSError) -> Void)?) {
var parameters: [String: AnyObject] = [
"page": page,
"count": count
]
if type.rawValue != "all" {
parameters["day"] = type.rawValue
}
NetworkManager.defaultManager!.GET("Hot Topic List",
parameters: parameters,
success: {
data in
if Int(msr_object: data["total_rows"]) > 0 {
var topics = [Topic]()
for object in data["rows"] as! [[String: AnyObject]] {
let topic = Topic.cachedObjectWithID(Int(msr_object: object["topic_id"]!)!)
topic.title = object["topic_title"] as? String
topic.introduction = object["topic_description"] as? String
topic.imageURI = object["topic_pic"] as? String
topic.focusCount = Int(msr_object: object["focus_count"]!)!
topics.append(topic)
}
_ = try? DataManager.defaultManager.saveChanges()
success?(topics)
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
func toggleFocus(userID userID: NSNumber, success: (() -> Void)?, failure: ((NSError) -> Void)?) {
if focused != nil {
if focused! {
cancleFocus(userID: userID, success: success, failure: failure)
} else {
focus(userID: userID, success: success, failure: failure)
}
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
}
func cancleFocus(userID userID: NSNumber, success: (() -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.POST("Focus Topic",
parameters: [
"uid": userID,
"topic_id": id,
"type": "cancel"
],
success: {
[weak self] data in
if let self_ = self {
self_.focused = false
_ = try? DataManager.defaultManager.saveChanges()
success?()
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
func focus(userID userID: NSNumber, success: (() -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.POST("Focus Topic",
parameters: [
"uid": userID,
"topic_id": id,
"type": "focus"
],
success: {
[weak self] data in
if let self_ = self {
self_.focused = true
_ = try? DataManager.defaultManager.saveChanges()
success?()
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
func fetchOutstandingAnswers(success success: (([Answer]) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.GET("Topic Outstanding Answer List",
parameters: [
"topic_id": id,
"page": 1
],
success: {
[weak self] data in
if let self_ = self {
if Int(msr_object: data["total_rows"]!!) > 0 {
var answers = [Answer]()
for value in data["rows"] as! [NSDictionary] {
let questionValue = value["question_info"] as! NSDictionary
let questionID = questionValue["question_id"] as! NSNumber
let question = Question.cachedObjectWithID(questionID)
self_.questions.insert(question)
question.title = questionValue["question_content"] as? String
let answerValue = value["answer_info"] as! NSDictionary
let answerID = answerValue["answer_id"] as! NSNumber
let answer = Answer.cachedObjectWithID(answerID)
question.answers.insert(answer)
answer.body = answerValue["answer_content"] as? String
answer.agreementCount = answerValue["agree_count"] as? NSNumber
let userValue = value["user_info"] as! NSDictionary
let userID = userValue["uid"] as! NSNumber
answer.user = User.cachedObjectWithID(userID)
answer.user!.avatarURL = userValue["avatar_file"] as? String
answers.append(answer)
}
_ = try? DataManager.defaultManager.saveChanges()
success?(answers)
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
private let imageView = UIImageView()
func fetchImage(success success: (() -> Void)?, failure: ((NSError) -> Void)?) {
if imageURL != nil {
let request = NSMutableURLRequest(URL: NSURL(string: imageURL!)!)
request.addValue("image/*", forHTTPHeaderField:"Accept")
imageView.setImageWithURLRequest(request,
placeholderImage: nil,
success: {
[weak self] request, response, image in
if self?.image == nil || response != nil {
self?.image = image
}
_ = try? DataManager.defaultManager.saveChanges()
success?()
},
failure: {
request, response, error in
failure?(error)
return
})
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
}
}
| gpl-2.0 | dcf9ff75836e872e55fa87cdfbc321e8 | 42.048246 | 196 | 0.519205 | 5.413679 | false | false | false | false |
davidbutz/ChristmasFamDuels | iOS/Boat Aware/SegueFromRight.swift | 1 | 1116 | //
// SegueFromRight.swift
// Boat Aware
//
// Created by Adam Douglass on 3/11/16.
// Copyright © 2016 Thrive Engineering. All rights reserved.
//
import UIKit
import QuartzCore
class SegueFromRight: UIStoryboardSegue {
override func perform()
{
let src = self.sourceViewController
let dst = self.destinationViewController
src.view.superview?.insertSubview(dst.view, aboveSubview: src.view)
src.view.transform = CGAffineTransformMakeTranslation(0, 0)
dst.view.transform = CGAffineTransformMakeTranslation(src.view.frame.size.width, 0)
UIView.animateWithDuration(0.25,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: {
dst.view.transform = CGAffineTransformMakeTranslation(0, 0)
src.view.transform = CGAffineTransformMakeTranslation(-1 * src.view.frame.size.width, 0)
},
completion: { finished in
src.presentViewController(dst, animated: false, completion: nil)
}
)
}
} | mit | b33a476908df489512060114b8c6cb25 | 30 | 104 | 0.634081 | 4.806034 | false | false | false | false |
apple/swift-corelibs-foundation | Sources/Foundation/NSSpecialValue.swift | 1 | 4878 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
internal protocol NSSpecialValueCoding {
static func objCType() -> String
init(bytes value: UnsafeRawPointer)
func encodeWithCoder(_ aCoder: NSCoder)
init?(coder aDecoder: NSCoder)
func getValue(_ value: UnsafeMutableRawPointer)
// Ideally we would make NSSpecialValue a generic class and specialise it for
// NSPoint, etc, but then we couldn't implement NSValue.init?(coder:) because
// it's not yet possible to specialise classes with a type determined at runtime.
//
// Nor can we make NSSpecialValueCoding conform to Equatable because it has associated
// type requirements.
//
// So in order to implement equality and hash we have the hack below.
func isEqual(_ value: Any) -> Bool
func hash(into hasher: inout Hasher)
var description: String { get }
}
internal class NSSpecialValue : NSValue {
// Originally these were functions in NSSpecialValueCoding but it's probably
// more convenient to keep it as a table here as nothing else really needs to
// know about them
private static let _specialTypes : Dictionary<Int, NSSpecialValueCoding.Type> = [
1 : NSPoint.self,
2 : NSSize.self,
3 : NSRect.self,
4 : NSRange.self,
12 : NSEdgeInsets.self
]
private static func _typeFromFlags(_ flags: Int) -> NSSpecialValueCoding.Type? {
return _specialTypes[flags]
}
private static func _flagsFromType(_ type: NSSpecialValueCoding.Type) -> Int {
for (F, T) in _specialTypes {
if T == type {
return F
}
}
return 0
}
private static func _objCTypeFromType(_ type: NSSpecialValueCoding.Type) -> String? {
for (_, T) in _specialTypes {
if T == type {
return T.objCType()
}
}
return nil
}
internal static func _typeFromObjCType(_ type: UnsafePointer<Int8>) -> NSSpecialValueCoding.Type? {
let objCType = String(cString: type)
for (_, T) in _specialTypes {
if T.objCType() == objCType {
return T
}
}
return nil
}
internal var _value : NSSpecialValueCoding
init(_ value: NSSpecialValueCoding) {
self._value = value
}
required init(bytes value: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) {
guard let specialType = NSSpecialValue._typeFromObjCType(type) else {
NSUnsupported()
}
self._value = specialType.init(bytes: value)
}
override func getValue(_ value: UnsafeMutableRawPointer) {
self._value.getValue(value)
}
convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let specialFlags = aDecoder.decodeInteger(forKey: "NS.special")
guard let specialType = NSSpecialValue._typeFromFlags(specialFlags) else {
return nil
}
guard let specialValue = specialType.init(coder: aDecoder) else {
return nil
}
self.init(specialValue)
}
override func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(NSSpecialValue._flagsFromType(type(of: _value)), forKey: "NS.special")
_value.encodeWithCoder(aCoder)
}
override var objCType : UnsafePointer<Int8> {
let typeName = NSSpecialValue._objCTypeFromType(type(of: _value))
return typeName!._bridgeToObjectiveC().utf8String! // leaky
}
override var classForCoder: AnyClass {
// for some day when we support class clusters
return NSValue.self
}
override var description : String {
let desc = _value.description
if desc.isEmpty {
return super.description
}
return desc
}
override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as NSSpecialValue:
return _value.isEqual(other._value)
case let other as NSObject:
return self === other
default:
return false
}
}
override var hash: Int {
var hasher = Hasher()
_value.hash(into: &hasher)
return hasher.finalize()
}
}
| apache-2.0 | 78a25af32df1eeb85622f58cc36294c0 | 31.092105 | 103 | 0.615416 | 4.699422 | false | false | false | false |
rockwotj/shiloh-ranch | ios/shiloh_ranch/shiloh_ranch/CategoriesUpdater.swift | 1 | 1867 | //
// CategoriesUpdater.swift
// Shiloh Ranch
//
// Created by Tyler Rockwood on 6/13/15.
// Copyright (c) 2015 Shiloh Ranch Cowboy Church. All rights reserved.
//
import Foundation
class CategoriesUpdater : Updater {
override func getSyncQuery() -> GTLQuery? {
return GTLQueryShilohranch.queryForUpdateCategoriesWithMilliseconds(getLastSyncTime())
}
override func update(pageToken : String? = nil) {
let service = getApiService()
let query = GTLQueryShilohranch.queryForCategories() as GTLQueryShilohranch
query.pageToken = pageToken
service.executeQuery(query) { (ticket, response, error) -> Void in
if error != nil {
showErrorDialog(error)
} else {
let categoryCollection = response as! GTLShilohranchCategoryCollection
let categories = categoryCollection.items() as! [GTLShilohranchCategory]
if pageToken == nil && !categories.isEmpty {
let lastSync = convertDateToUnixTime(categories[0].timeAdded)
if lastSync > 0 {
println("Setting last SyncTime for Categories to be \(lastSync)")
self.setLastSyncTime(lastSync)
}
}
for category in categories {
println("Got Category named: \(category.title)")
self.save(category)
}
if let nextPageToken = categoryCollection.nextPageToken {
self.update(pageToken: nextPageToken)
}
}
}
}
func save(entity : GTLShilohranchCategory) {
let database = getDatabase()
database.insert(entity)
}
override func getModelType() -> String! {
return "Category"
}
} | mit | 4fbd62f0270ddc0f45454a8549ac03c9 | 34.245283 | 94 | 0.576861 | 4.811856 | false | false | false | false |
Lietmotiv/Swift4096 | swift-2048/Views/GameboardView.swift | 1 | 8195 | //
// GameboardView.swift
// swift-2048
//
// Created by Austin Zheng on 6/3/14.
// Copyright (c) 2014 Austin Zheng. All rights reserved.
//
import UIKit
class GameboardView : UIView {
var dimension: Int
var tileWidth: CGFloat
var tilePadding: CGFloat
var cornerRadius: CGFloat
var tiles: Dictionary<NSIndexPath, TileView>
let provider = AppearanceProvider()
let tilePopStartScale: CGFloat = 0.1
let tilePopMaxScale: CGFloat = 1.1
let tilePopDelay: NSTimeInterval = 0.05
let tileExpandTime: NSTimeInterval = 0.18
let tileContractTime: NSTimeInterval = 0.08
let tileMergeStartScale: CGFloat = 1.0
let tileMergeExpandTime: NSTimeInterval = 0.08
let tileMergeContractTime: NSTimeInterval = 0.08
let perSquareSlideDuration: NSTimeInterval = 0.08
init(dimension d: Int, tileWidth width: CGFloat, tilePadding padding: CGFloat, cornerRadius radius: CGFloat, backgroundColor: UIColor, foregroundColor: UIColor) {
assert(d > 0)
dimension = d
tileWidth = width
tilePadding = padding
cornerRadius = radius
tiles = Dictionary()
let sideLength = padding + CGFloat(dimension)*(width + padding)
super.init(frame: CGRectMake(0, 0, sideLength, sideLength))
layer.cornerRadius = radius
setupBackground(backgroundColor: backgroundColor, tileColor: foregroundColor)
}
/// Reset the gameboard.
func reset() {
for (key, tile) in tiles {
tile.removeFromSuperview()
}
tiles.removeAll(keepCapacity: true)
}
/// Return whether a given position is valid. Used for bounds checking.
func positionIsValid(pos: (Int, Int)) -> Bool {
let (x, y) = pos
return (x >= 0 && x < dimension && y >= 0 && y < dimension)
}
func setupBackground(backgroundColor bgColor: UIColor, tileColor: UIColor) {
backgroundColor = bgColor
var xCursor = tilePadding
var yCursor: CGFloat
let bgRadius = (cornerRadius >= 2) ? cornerRadius - 2 : 0
for i in 0...dimension-1 {
yCursor = tilePadding
for j in 0...dimension-1 {
// Draw each tile
let background = UIView(frame: CGRectMake(xCursor, yCursor, tileWidth, tileWidth))
background.layer.cornerRadius = bgRadius
background.backgroundColor = tileColor
addSubview(background)
yCursor += tilePadding + tileWidth
}
xCursor += tilePadding + tileWidth
}
}
/// Update the gameboard by inserting a tile in a given location. The tile will be inserted with a 'pop' animation.
func insertTile(pos: (Int, Int), value: Int) {
assert(positionIsValid(pos))
let (row, col) = pos
let x = tilePadding + CGFloat(col)*(tileWidth + tilePadding)
let y = tilePadding + CGFloat(row)*(tileWidth + tilePadding)
let r = (cornerRadius >= 2) ? cornerRadius - 2 : 0
let tile = TileView(position: CGPointMake(x, y), width: tileWidth, value: value, radius: r, delegate: provider)
tile.layer.setAffineTransform(CGAffineTransformMakeScale(tilePopStartScale, tilePopStartScale))
addSubview(tile)
bringSubviewToFront(tile)
tiles[NSIndexPath(forRow: row, inSection: col)] = tile
// Add to board
UIView.animateWithDuration(tileExpandTime, delay: tilePopDelay, options: UIViewAnimationOptions.TransitionNone,
animations: { () -> Void in
// Make the tile 'pop'
tile.layer.setAffineTransform(CGAffineTransformMakeScale(self.tilePopMaxScale, self.tilePopMaxScale))
},
completion: { (finished: Bool) -> Void in
// Shrink the tile after it 'pops'
UIView.animateWithDuration(self.tileContractTime, animations: { () -> Void in
tile.layer.setAffineTransform(CGAffineTransformIdentity)
})
})
}
/// Update the gameboard by moving a single tile from one location to another. If the move is going to collapse two
/// tiles into a new tile, the tile will 'pop' after moving to its new location.
func moveOneTile(from: (Int, Int), to: (Int, Int), value: Int) {
assert(positionIsValid(from) && positionIsValid(to))
let (fromRow, fromCol) = from
let (toRow, toCol) = to
let fromKey = NSIndexPath(forRow: fromRow, inSection: fromCol)
let toKey = NSIndexPath(forRow: toRow, inSection: toCol)
// Get the tiles
assert(tiles[fromKey] != nil)
let tile = tiles[fromKey]!
let endTile = tiles[toKey]
// Make the frame
var finalFrame = tile.frame
finalFrame.origin.x = tilePadding + CGFloat(toCol)*(tileWidth + tilePadding)
finalFrame.origin.y = tilePadding + CGFloat(toRow)*(tileWidth + tilePadding)
// Update board state
tiles.removeValueForKey(fromKey)
tiles[toKey] = tile
// Animate
let shouldPop = endTile != nil
UIView.animateWithDuration(perSquareSlideDuration,
delay: 0.0,
options: UIViewAnimationOptions.BeginFromCurrentState,
animations: { () -> Void in
// Slide tile
tile.frame = finalFrame
},
completion: { (finished: Bool) -> Void in
tile.value = value
endTile?.removeFromSuperview()
if !shouldPop || !finished {
return
}
tile.layer.setAffineTransform(CGAffineTransformMakeScale(self.tileMergeStartScale, self.tileMergeStartScale))
// Pop tile
UIView.animateWithDuration(self.tileMergeExpandTime,
animations: { () -> Void in
tile.layer.setAffineTransform(CGAffineTransformMakeScale(self.tilePopMaxScale, self.tilePopMaxScale))
},
completion: { (finished: Bool) -> () in
// Contract tile to original size
UIView.animateWithDuration(self.tileMergeContractTime,
animations: { () -> Void in
tile.layer.setAffineTransform(CGAffineTransformIdentity)
})
})
})
}
/// Update the gameboard by moving two tiles from their original locations to a common destination. This action always
/// represents tile collapse, and the combined tile 'pops' after both tiles move into position.
func moveTwoTiles(from: ((Int, Int), (Int, Int)), to: (Int, Int), value: Int) {
assert(positionIsValid(from.0) && positionIsValid(from.1) && positionIsValid(to))
let (fromRowA, fromColA) = from.0
let (fromRowB, fromColB) = from.1
let (toRow, toCol) = to
let fromKeyA = NSIndexPath(forRow: fromRowA, inSection: fromColA)
let fromKeyB = NSIndexPath(forRow: fromRowB, inSection: fromColB)
let toKey = NSIndexPath(forRow: toRow, inSection: toCol)
assert(tiles[fromKeyA] != nil)
assert(tiles[fromKeyB] != nil)
let tileA = tiles[fromKeyA]!
let tileB = tiles[fromKeyB]!
// Make the frame
var finalFrame = tileA.frame
finalFrame.origin.x = tilePadding + CGFloat(toCol)*(tileWidth + tilePadding)
finalFrame.origin.y = tilePadding + CGFloat(toRow)*(tileWidth + tilePadding)
// Update the state
let oldTile = tiles[toKey] // TODO: make sure this doesn't cause issues
oldTile?.removeFromSuperview()
tiles.removeValueForKey(fromKeyA)
tiles.removeValueForKey(fromKeyB)
tiles[toKey] = tileA
UIView.animateWithDuration(perSquareSlideDuration,
delay: 0.0,
options: UIViewAnimationOptions.BeginFromCurrentState,
animations: { () -> Void in
// Slide tiles
tileA.frame = finalFrame
tileB.frame = finalFrame
},
completion: { (finished: Bool) -> Void in
tileA.value = value
tileB.removeFromSuperview()
if !finished {
return
}
tileA.layer.setAffineTransform(CGAffineTransformMakeScale(self.tileMergeStartScale, self.tileMergeStartScale))
// Pop tile
UIView.animateWithDuration(self.tileMergeExpandTime,
animations: { () -> Void in
tileA.layer.setAffineTransform(CGAffineTransformMakeScale(self.tilePopMaxScale, self.tilePopMaxScale))
},
completion: { (finished: Bool) -> Void in
// Contract tile to original size
UIView.animateWithDuration(self.tileMergeContractTime,
animations: { () -> Void in
tileA.layer.setAffineTransform(CGAffineTransformIdentity)
})
})
})
}
} | mit | c70af262b2d6719de85c49a8f78da64d | 36.59633 | 164 | 0.670653 | 4.315429 | false | false | false | false |
legendecas/Rocket.Chat.iOS | Rocket.ChatTests/Helpers/UploadHelperSpec.swift | 1 | 2292 | //
// UploadHelperSpec.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 14/08/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import XCTest
@testable import Rocket_Chat
class UploadHelperSpec: XCTestCase {
func testFileUploadObject() {
let name = "foo.png"
let mimetype = "image/png"
guard
let image = UIImage(named: "Logo"),
let data = UIImagePNGRepresentation(image),
let file = UploadHelper.file(for: data, name: name, mimeType: mimetype) else {
return XCTAssertTrue(false, "File wasn't created successfuly")
}
XCTAssert(file.name == name, "file name is equal to name")
XCTAssert(file.type == mimetype, "file type is equal to mimetype")
XCTAssert(file.data == data, "file data is equal to data")
XCTAssert(file.size == (data as NSData).length, "file data is equal to data")
}
func testFileMimetype() {
let files: [String: String] = [
"filename.png": "image/png",
"filename.jpg": "image/jpeg",
"filename.jpeg": "image/jpeg",
"filename.pdf": "application/pdf",
"filename.mp4": "video/mp4"
]
for file in files.keys {
if let localURL = DownloadManager.localFileURLFor(file) {
let mimetype = UploadHelper.mimeTypeFor(localURL)
XCTAssert(mimetype == files[file], "\(file) mimetype (\(mimetype)) respects the extension")
} else {
XCTAssertTrue(false, "file url is invalid")
}
}
}
func testFileSize() {
guard
let image = UIImage(named: "Logo"),
let data = UIImagePNGRepresentation(image) else {
return XCTAssertTrue(false, "File data isn't valid")
}
XCTAssert(UploadHelper.sizeFor(data) == (data as NSData).length, "file data is equal to data")
}
func testFileName() {
let filename = "filename.png"
guard let localURL = DownloadManager.localFileURLFor(filename) else {
return XCTAssertTrue(false, "file url is invalid")
}
XCTAssert(filename == UploadHelper.nameFor(localURL), "filename keeps the same after URL")
}
}
| mit | 5e8c57d9cc43ae22313a352ce71c5300 | 31.728571 | 107 | 0.592318 | 4.388889 | false | true | false | false |
touchopia/Codementor-Swift-201 | SourceCode/Background-Starter/BackgroundChooser/BackgroundViewController.swift | 1 | 939 | //
// ViewController.swift
// BackgroundChooser
//
// Created by Phil Wright on 10/1/15.
// Copyright © 2015 Touchopia LLC. All rights reserved.
//
import UIKit
class BackgroundViewController: UIViewController {
var backgroundImageString : String = ""
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func chooseBackground(sender: UIButton) {
print("chooseBackground")
switch(sender.tag) {
case 1: backgroundImageString = "blueBackground"
case 2: backgroundImageString = "cityBackground"
case 3: backgroundImageString = "greenBackground"
case 4: backgroundImageString = "funBackground"
case 5: backgroundImageString = "castleBackground"
default: backgroundImageString = "redBackground"
}
self.performSegueWithIdentifier(kExitIdentifier, sender: self)
}
}
| mit | e3f8fc88c64baa91e9d71b4d3d4ec9aa | 25.055556 | 70 | 0.644989 | 5.016043 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeImage/AwesomeImage/Classes/Extensions/UIImageExtensions.swift | 1 | 1247 | //
// UIImageExtensions.swift
// AwesomeImage
//
// Created by Evandro Harrison Hoffmann on 4/5/18.
//
import Foundation
import AwesomeLoading
import Kingfisher
extension UIImage {
public static func image(_ named: String) -> UIImage? {
return UIImage(named: named, in: AwesomeImage.bundle, compatibleWith: nil)
}
public static func loadImage(_ urlString: String?, completion:@escaping (_ image: UIImage?) -> Void) {
guard let urlString = urlString, let url = URL(string: urlString) else {
return
}
ImageDownloader.default.downloadImage(with: url, options: [], progressBlock: nil) {
(image, _, _, _) in
completion(image)
}
/*if let url = url {
let awesomeRequester = AwesomeImageRequester()
_ = awesomeRequester.performRequest(url, shouldCache: true, completion: { (data, errorData, responseType) in
DispatchQueue.main.async {
if let data = data {
completion(UIImage(data: data))
} else {
completion(nil)
}
}
})
}*/
}
}
| mit | da43f05235900dd58573b8289d86d844 | 28 | 120 | 0.539695 | 5.008032 | false | false | false | false |
ludoded/ReceiptBot | ReceiptBot/Helper/Formatter/NumberFormaters.swift | 1 | 939 | //
// NumberFormaters.swift
// ReceiptBot
//
// Created by Haik Ampardjian on 4/5/17.
// Copyright © 2017 receiptbot. All rights reserved.
//
import Foundation
struct NumberFormaters {
static var pieFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.maximumFractionDigits = 1
formatter.multiplier = NSNumber(floatLiteral: 1)
formatter.percentSymbol = " %"
return formatter
}
static var lineFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}
static var grossFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.allowsFloats = true
formatter.maximumFractionDigits = 2
return formatter
}
}
| lgpl-3.0 | 2eb68c19de465e1f2087c448d50613a6 | 24.351351 | 56 | 0.642857 | 5.48538 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/CrossSigning/CrossSigningService.swift | 1 | 2400 | /*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
@objcMembers
final class CrossSigningService: NSObject {
private var authenticatedSessionFactory: AuthenticatedSessionViewControllerFactory?
private var supportSetupKeyVerificationByUser: [String: Bool] = [:] // Cached server response
@discardableResult
func canSetupCrossSigning(for session: MXSession, success: @escaping ((Bool) -> Void), failure: @escaping ((Error) -> Void)) -> MXHTTPOperation? {
guard let crossSigning = session.crypto?.crossSigning, crossSigning.state == .notBootstrapped else {
// Cross-signing already setup
success(false)
return nil
}
let userId: String = session.myUserId
if let supportSetupKeyVerification = self.supportSetupKeyVerificationByUser[userId] {
// Return cached response
success(supportSetupKeyVerification)
return nil
}
let authenticatedSessionFactory = AuthenticatedSessionViewControllerFactory(session: session)
self.authenticatedSessionFactory = authenticatedSessionFactory
let path = "\(kMXAPIPrefixPathUnstable)/keys/device_signing/upload"
return authenticatedSessionFactory.hasSupport(forPath: path, httpMethod: "POST", success: { [weak self] succeeded in
guard let self = self else {
return
}
self.authenticatedSessionFactory = nil
self.supportSetupKeyVerificationByUser[userId] = succeeded
success(succeeded)
}, failure: { [weak self] error in
guard let self = self else {
return
}
self.authenticatedSessionFactory = nil
failure(error)
})
}
}
| apache-2.0 | bd9774b9fd0d613f2e9f71037663fcb8 | 37.095238 | 150 | 0.660417 | 5.357143 | false | false | false | false |
ludoded/ReceiptBot | ReceiptBot/Scene/Auth/EmailPasswordViewController.swift | 1 | 1702 | //
// EmailPasswordViewController.swift
// ReceiptBot
//
// Created by Haik Ampardjian on 4/9/17.
// Copyright © 2017 receiptbot. All rights reserved.
//
import UIKit
import Material
import RxCocoa
import RxSwift
class EmailPasswordViewController: SignBaseViewController {
var disposeBag = DisposeBag()
@IBOutlet weak var loginButton: Button!
@IBOutlet weak var recoveryButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setupValidators()
}
private func setupValidators() {
let emailValid = textFields![0].rx.text.orEmpty
.map{ RebotValidator.validate(email: $0) }
.shareReplay(1)
let passwordValid = textFields![1].rx.text.orEmpty
.map{ RebotValidator.validate(password: $0) }
.shareReplay(1)
let emailError = textFields![0].rx.text.orEmpty
.map{ RebotValidator.emailError(text: $0) }
.shareReplay(1)
let passwordError = textFields![1].rx.text.orEmpty
.map{ RebotValidator.passwordError(text: $0) }
.shareReplay(1)
let everythingValid = Observable.combineLatest(emailValid, passwordValid) { $0 && $1 }
emailError
.bind(to: textFields![0].rx.isErrorRevealed)
.disposed(by: disposeBag)
emailValid
.bind(to: recoveryButton.rx.isEnabled)
.disposed(by: disposeBag)
passwordError
.bind(to: textFields![1].rx.isErrorRevealed)
.disposed(by: disposeBag)
everythingValid
.bind(to: loginButton.rx.isEnabled)
.disposed(by: disposeBag)
}
}
| lgpl-3.0 | e517ab0a18bdb2888364e07f9c52daa2 | 29.927273 | 94 | 0.613169 | 4.441253 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Kingfisher/Sources/General/KingfisherManager.swift | 3 | 20655 | //
// KingfisherManager.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// 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
/// The downloading progress block type.
/// The parameter value is the `receivedSize` of current response.
/// The second parameter is the total expected data length from response's "Content-Length" header.
/// If the expected length is not available, this block will not be called.
public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> Void)
/// Represents the result of a Kingfisher retrieving image task.
public struct RetrieveImageResult {
/// Gets the image object of this result.
public let image: KFCrossPlatformImage
/// Gets the cache source of the image. It indicates from which layer of cache this image is retrieved.
/// If the image is just downloaded from network, `.none` will be returned.
public let cacheType: CacheType
/// The `Source` from which the retrieve task begins.
public let source: Source
}
/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache,
/// to provide a set of convenience methods to use Kingfisher for tasks.
/// You can use this class to retrieve an image via a specified URL from web or cache.
public class KingfisherManager {
/// Represents a shared manager used across Kingfisher.
/// Use this instance for getting or storing images with Kingfisher.
public static let shared = KingfisherManager()
// Mark: Public Properties
/// The `ImageCache` used by this manager. It is `ImageCache.default` by default.
/// If a cache is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be
/// used instead.
public var cache: ImageCache
/// The `ImageDownloader` used by this manager. It is `ImageDownloader.default` by default.
/// If a downloader is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be
/// used instead.
public var downloader: ImageDownloader
/// Default options used by the manager. This option will be used in
/// Kingfisher manager related methods, as well as all view extension methods.
/// You can also passing other options for each image task by sending an `options` parameter
/// to Kingfisher's APIs. The per image options will overwrite the default ones,
/// if the option exists in both.
public var defaultOptions = KingfisherOptionsInfo.empty
// Use `defaultOptions` to overwrite the `downloader` and `cache`.
private var currentDefaultOptions: KingfisherOptionsInfo {
return [.downloader(downloader), .targetCache(cache)] + defaultOptions
}
private let processingQueue: CallbackQueue
private convenience init() {
self.init(downloader: .default, cache: .default)
}
/// Creates an image setting manager with specified downloader and cache.
///
/// - Parameters:
/// - downloader: The image downloader used to download images.
/// - cache: The image cache which stores memory and disk images.
public init(downloader: ImageDownloader, cache: ImageCache) {
self.downloader = downloader
self.cache = cache
let processQueueName = "com.onevcat.Kingfisher.KingfisherManager.processQueue.\(UUID().uuidString)"
processingQueue = .dispatch(DispatchQueue(label: processQueueName))
}
// Mark: Getting Images
/// Gets an image from a given resource.
///
/// - Parameters:
/// - resource: The `Resource` object defines data information like key or URL.
/// - options: Options to use when creating the animated image.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called. `progressBlock` is always called in
/// main queue.
/// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked
/// from the `options.callbackQueue`. If not specified, the main queue will be used.
/// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource,
/// the started `DownloadTask` is returned. Otherwise, `nil` is returned.
///
/// - Note:
/// This method will first check whether the requested `resource` is already in cache or not. If cached,
/// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it
/// will download the `resource`, store it in cache, then call `completionHandler`.
///
@discardableResult
public func retrieveImage(
with resource: Resource,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
{
let source = Source.network(resource)
return retrieveImage(
with: source, options: options, progressBlock: progressBlock, completionHandler: completionHandler
)
}
/// Gets an image from a given resource.
///
/// - Parameters:
/// - source: The `Source` object defines data information from network or a data provider.
/// - options: Options to use when creating the animated image.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called. `progressBlock` is always called in
/// main queue.
/// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked
/// from the `options.callbackQueue`. If not specified, the main queue will be used.
/// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource,
/// the started `DownloadTask` is returned. Otherwise, `nil` is returned.
///
/// - Note:
/// This method will first check whether the requested `source` is already in cache or not. If cached,
/// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it
/// will try to load the `source`, store it in cache, then call `completionHandler`.
///
public func retrieveImage(
with source: Source,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
{
let options = currentDefaultOptions + (options ?? .empty)
var info = KingfisherParsedOptionsInfo(options)
if let block = progressBlock {
info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
return retrieveImage(
with: source,
options: info,
completionHandler: completionHandler)
}
func retrieveImage(
with source: Source,
options: KingfisherParsedOptionsInfo,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
{
if options.forceRefresh {
return loadAndCacheImage(
source: source,
options: options,
completionHandler: completionHandler)?.value
} else {
let loadedFromCache = retrieveImageFromCache(
source: source,
options: options,
completionHandler: completionHandler)
if loadedFromCache {
return nil
}
if options.onlyFromCache {
let error = KingfisherError.cacheError(reason: .imageNotExisting(key: source.cacheKey))
completionHandler?(.failure(error))
return nil
}
return loadAndCacheImage(
source: source,
options: options,
completionHandler: completionHandler)?.value
}
}
func provideImage(
provider: ImageDataProvider,
options: KingfisherParsedOptionsInfo,
completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)?)
{
guard let completionHandler = completionHandler else { return }
provider.data { result in
switch result {
case .success(let data):
(options.processingQueue ?? self.processingQueue).execute {
let processor = options.processor
let processingItem = ImageProcessItem.data(data)
guard let image = processor.process(item: processingItem, options: options) else {
options.callbackQueue.execute {
let error = KingfisherError.processorError(
reason: .processingFailed(processor: processor, item: processingItem))
completionHandler(.failure(error))
}
return
}
options.callbackQueue.execute {
let result = ImageLoadingResult(image: image, url: nil, originalData: data)
completionHandler(.success(result))
}
}
case .failure(let error):
options.callbackQueue.execute {
let error = KingfisherError.imageSettingError(
reason: .dataProviderError(provider: provider, error: error))
completionHandler(.failure(error))
}
}
}
}
@discardableResult
func loadAndCacheImage(
source: Source,
options: KingfisherParsedOptionsInfo,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask.WrappedTask?
{
func cacheImage(_ result: Result<ImageLoadingResult, KingfisherError>)
{
switch result {
case .success(let value):
// Add image to cache.
let targetCache = options.targetCache ?? self.cache
targetCache.store(
value.image,
original: value.originalData,
forKey: source.cacheKey,
options: options,
toDisk: !options.cacheMemoryOnly)
{
_ in
if options.waitForCache {
let result = RetrieveImageResult(image: value.image, cacheType: .none, source: source)
completionHandler?(.success(result))
}
}
// Add original image to cache if necessary.
let needToCacheOriginalImage = options.cacheOriginalImage &&
options.processor != DefaultImageProcessor.default
if needToCacheOriginalImage {
let originalCache = options.originalCache ?? targetCache
originalCache.storeToDisk(
value.originalData,
forKey: source.cacheKey,
processorIdentifier: DefaultImageProcessor.default.identifier,
expiration: options.diskCacheExpiration)
}
if !options.waitForCache {
let result = RetrieveImageResult(image: value.image, cacheType: .none, source: source)
completionHandler?(.success(result))
}
case .failure(let error):
completionHandler?(.failure(error))
}
}
switch source {
case .network(let resource):
let downloader = options.downloader ?? self.downloader
guard let task = downloader.downloadImage(
with: resource.downloadURL,
options: options,
completionHandler: cacheImage) else {
return nil
}
return .download(task)
case .provider(let provider):
provideImage(provider: provider, options: options, completionHandler: cacheImage)
return .dataProviding
}
}
/// Retrieves image from memory or disk cache.
///
/// - Parameters:
/// - source: The target source from which to get image.
/// - key: The key to use when caching the image.
/// - url: Image request URL. This is not used when retrieving image from cache. It is just used for
/// `RetrieveImageResult` callback compatibility.
/// - options: Options on how to get the image from image cache.
/// - completionHandler: Called when the image retrieving finishes, either with succeeded
/// `RetrieveImageResult` or an error.
/// - Returns: `true` if the requested image or the original image before being processed is existing in cache.
/// Otherwise, this method returns `false`.
///
/// - Note:
/// The image retrieving could happen in either memory cache or disk cache. The `.processor` option in
/// `options` will be considered when searching in the cache. If no processed image is found, Kingfisher
/// will try to check whether an original version of that image is existing or not. If there is already an
/// original, Kingfisher retrieves it from cache and processes it. Then, the processed image will be store
/// back to cache for later use.
func retrieveImageFromCache(
source: Source,
options: KingfisherParsedOptionsInfo,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> Bool
{
// 1. Check whether the image was already in target cache. If so, just get it.
let targetCache = options.targetCache ?? cache
let key = source.cacheKey
let targetImageCached = targetCache.imageCachedType(
forKey: key, processorIdentifier: options.processor.identifier)
let validCache = targetImageCached.cached &&
(options.fromMemoryCacheOrRefresh == false || targetImageCached == .memory)
if validCache {
targetCache.retrieveImage(forKey: key, options: options) { result in
guard let completionHandler = completionHandler else { return }
options.callbackQueue.execute {
result.match(
onSuccess: { cacheResult in
let value: Result<RetrieveImageResult, KingfisherError>
if let image = cacheResult.image {
value = result.map {
RetrieveImageResult(image: image, cacheType: $0.cacheType, source: source)
}
} else {
value = .failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))
}
completionHandler(value)
},
onFailure: { _ in
completionHandler(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))))
}
)
}
}
return true
}
// 2. Check whether the original image exists. If so, get it, process it, save to storage and return.
let originalCache = options.originalCache ?? targetCache
// No need to store the same file in the same cache again.
if originalCache === targetCache && options.processor == DefaultImageProcessor.default {
return false
}
// Check whether the unprocessed image existing or not.
let originalImageCached = originalCache.imageCachedType(
forKey: key, processorIdentifier: DefaultImageProcessor.default.identifier).cached
if originalImageCached {
// Now we are ready to get found the original image from cache. We need the unprocessed image, so remove
// any processor from options first.
var optionsWithoutProcessor = options
optionsWithoutProcessor.processor = DefaultImageProcessor.default
originalCache.retrieveImage(forKey: key, options: optionsWithoutProcessor) { result in
result.match(
onSuccess: { cacheResult in
guard let image = cacheResult.image else {
return
}
let processor = options.processor
(options.processingQueue ?? self.processingQueue).execute {
let item = ImageProcessItem.image(image)
guard let processedImage = processor.process(item: item, options: options) else {
let error = KingfisherError.processorError(
reason: .processingFailed(processor: processor, item: item))
options.callbackQueue.execute { completionHandler?(.failure(error)) }
return
}
var cacheOptions = options
cacheOptions.callbackQueue = .untouch
targetCache.store(
processedImage,
forKey: key,
options: cacheOptions,
toDisk: !options.cacheMemoryOnly)
{
_ in
if options.waitForCache {
let value = RetrieveImageResult(
image: processedImage, cacheType: .none, source: source)
options.callbackQueue.execute { completionHandler?(.success(value)) }
}
}
if !options.waitForCache {
let value = RetrieveImageResult(image: processedImage, cacheType: .none, source: source)
options.callbackQueue.execute { completionHandler?(.success(value)) }
}
}
},
onFailure: { _ in
// This should not happen actually, since we already confirmed `originalImageCached` is `true`.
// Just in case...
options.callbackQueue.execute {
completionHandler?(
.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))
)
}
}
)
}
return true
}
return false
}
}
| mit | a7440a850de8e553962f77333b21de20 | 46.702079 | 120 | 0.590027 | 5.834746 | false | false | false | false |
naokits/bluemix-swift-demo-ios | Pods/BMSPush/Source/BMSPushUrlBuilder.swift | 1 | 5783 | /*
* Copyright 2015 IBM Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import BMSCore
internal class BMSPushUrlBuilder: NSObject {
internal let FORWARDSLASH = "/";
internal let IMFPUSH = "imfpush";
internal let V1 = "v1";
internal let APPS = "apps";
internal let AMPERSAND = "&";
internal let QUESTIONMARK = "?";
internal let SUBZONE = "subzone";
internal let EQUALTO = "=";
internal let SUBSCRIPTIONS = "subscriptions";
internal let TAGS = "tags";
internal let DEVICES = "devices";
internal let TAGNAME = "tagName";
internal let DEVICEID = "deviceId";
internal let defaultProtocol = "https";
internal final var pwUrl_ = String()
internal final var reWritedomain = String()
init(applicationID:String) {
if(!BMSPushClient.overrideServerHost.isEmpty){
pwUrl_ += BMSPushClient.overrideServerHost
}
else {
pwUrl_ += defaultProtocol
pwUrl_ += "://"
if BMSClient.sharedInstance.bluemixRegion?.containsString("stage1-test") == true || BMSClient.sharedInstance.bluemixRegion?.containsString("stage1-dev") == true {
//pwUrl_ += "mobile"
let url = NSURL(string: BMSClient.sharedInstance.bluemixAppRoute!)
print(url?.host);
let appName = url?.host?.componentsSeparatedByString(".").first
pwUrl_ += appName!
pwUrl_ += ".stage1.mybluemix.net"
if BMSClient.sharedInstance.bluemixRegion?.containsString("stage1-test") == true {
reWritedomain = "stage1-test.ng.bluemix.net"
}
else{
reWritedomain = "stage1-dev.ng.bluemix.net"
}
}
else{
pwUrl_ += IMFPUSH
pwUrl_ += BMSClient.sharedInstance.bluemixRegion!
reWritedomain = ""
}
}
pwUrl_ += FORWARDSLASH
pwUrl_ += IMFPUSH
pwUrl_ += FORWARDSLASH
pwUrl_ += V1
pwUrl_ += FORWARDSLASH
pwUrl_ += APPS
pwUrl_ += FORWARDSLASH
pwUrl_ += applicationID
pwUrl_ += FORWARDSLASH
}
func addHeader() -> [String: String] {
if reWritedomain.isEmpty {
return [IMFPUSH_CONTENT_TYPE_KEY:IMFPUSH_CONTENT_TYPE_JSON]
}
else{
return [IMFPUSH_CONTENT_TYPE_KEY:IMFPUSH_CONTENT_TYPE_JSON, IMFPUSH_X_REWRITE_DOMAIN:reWritedomain]
}
}
func getSubscribedDevicesUrl(devID:String) -> String {
var deviceIdUrl:String = getDevicesUrl()
deviceIdUrl += FORWARDSLASH
deviceIdUrl += devID
return deviceIdUrl
}
func getDevicesUrl() -> String {
return getCollectionUrl(DEVICES)
}
func getTagsUrl() -> String {
return getCollectionUrl(TAGS)
}
func getSubscriptionsUrl() -> String {
return getCollectionUrl(SUBSCRIPTIONS)
}
func getAvailableSubscriptionsUrl(deviceId : String) -> String {
var subscriptionURL = getCollectionUrl(SUBSCRIPTIONS)
subscriptionURL += QUESTIONMARK
subscriptionURL += "deviceId=\(deviceId)"
return subscriptionURL;
}
func getUnSubscribetagsUrl() -> String {
var unSubscriptionURL = getCollectionUrl(SUBSCRIPTIONS)
unSubscriptionURL += QUESTIONMARK
unSubscriptionURL += FORWARDSLASH
unSubscriptionURL += IMFPUSH_ACTION_DELETE
return unSubscriptionURL
}
func getUnregisterUrl (deviceId : String) -> String {
var deviceUnregisterUrl:String = getDevicesUrl()
deviceUnregisterUrl += FORWARDSLASH
deviceUnregisterUrl += deviceId
return deviceUnregisterUrl
}
internal func getCollectionUrl (collectionName:String) -> String {
var collectionUrl:String = pwUrl_
collectionUrl += collectionName
return collectionUrl
}
// internal func retrieveAppName () -> String {
//
// let url = NSURL(string: BMSClient.sharedInstance.bluemixAppRoute!)
//
// print(url?.host);
////
//// if(!url){
//// [NSException raise:@"InvalidURLException" format:@"Invalid applicationRoute: %@", applicationRoute];
//// }
////
//// NSString *newBaasUrl = nil;
//// NSString *newRewriteDomain = nil;
//// NSString *regionInDomain = @"ng";
////
//// // Determine whether a port should be added.
//// NSNumber * port = url.port;
//// if(port){
//// newBaasUrl = [NSString stringWithFormat:@"%@://%@:%@", url.scheme, url.host, port];
//// }else{
//// newBaasUrl = [NSString stringWithFormat:@"%@://%@", url.scheme, url.host];
//// }
// }
}
| mit | db80c5725f45e559438a1c233056170d | 31.502825 | 174 | 0.559534 | 5.201627 | false | false | false | false |
alberttra/A-Framework | Pod/Classes/AFramework.swift | 1 | 755 | //
// AFramework.swift
// Pods
//
// Created by Albert Tra on 31/01/16.
//
//
import Foundation
public class AFramework {
public static let sharedInstance = AFramework()
public var bundleServices = BundleServices()
public var colorKit = ColorKit()
public var compassServices = CompassServices()
public var coreLocationServices = CoreLocationServices()
public var dateTimeServices = DateTimeServices()
/**
Provice infomation about hosted hardware
:Author: Albert Tra
*/
public var hardwareServies = HardwareServices()
public var logger = Logger()
public var mapServices = MapServices()
public var networkServices = NetworkServices()
} | mit | d4d19489477211ddab69561dd7504ef1 | 19.432432 | 60 | 0.654305 | 4.934641 | false | false | false | false |
coach-plus/ios | CoachPlus/ui/CoachPlusViewController.swift | 1 | 4033 | //
// CoachPlusViewController.swift
// CoachPlus
//
// Created by Maurice Breit on 16.04.17.
// Copyright © 2017 Mathandoro GbR. All rights reserved.
//
import UIKit
import RxSwift
import PromiseKit
import MBProgressHUD
class CoachPlusViewController: UIViewController, ErrorHandlerDelegate {
var loaded = false
var membership:Membership?
var previousVC: CoachPlusViewController?
var heroId:String = ""
var errorHandler: ErrorHandler?
public let disposeBag = DisposeBag()
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
self.errorHandler = ErrorHandler(delegate: self)
setNeedsStatusBarAppearanceUpdate()
self.isHeroEnabled = true
if (self.membership == nil) {
self.membership = MembershipManager.shared.getPreviouslySelectedMembership()
}
self.view.backgroundColor = UIColor.defaultBackground
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationManager.shared.setCurrentVc(currentVc: self)
self.setupNavBarDelegate()
self.disableDrawer()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func setupNavBarDelegate() {
if let navbar = self.navigationController?.navigationBar as? CoachPlusNavigationBar {
navbar.coachPlusNavigationBarDelegate = self as? CoachPlusNavigationBarDelegate
}
}
func pushToEventDetail(currentVC: CoachPlusViewController, event:Event) {
let targetVc = UIStoryboard(name: "EventDetail", bundle: nil).instantiateInitialViewController() as! EventDetailViewController
targetVc.event = event
targetVc.heroId = "event\(event.id)"
targetVc.isHeroEnabled = true
targetVc.previousVC = currentVC
self.navigationController?.pushViewController(targetVc, animated: true)
}
func setLeftBarButton(type:CoachPlusNavigationBar.BarButtonType) {
if let navbar = self.navigationController?.navigationBar as? CoachPlusNavigationBar {
navbar.leftBarButtonType = type
navbar.setLeftBarButton(item: self.navigationItem)
}
}
func setRightBarButton(type:CoachPlusNavigationBar.BarButtonType) {
if let navbar = self.navigationController?.navigationBar as? CoachPlusNavigationBar {
navbar.rightBarButtonType = type
navbar.setRightBarButton(item: self.navigationItem)
}
}
func setNavbarTitle() {
if (self.membership != nil) {
self.navigationItem.titleView = nil
self.setNavbarTitle(title: self.membership?.team?.name)
} else {
self.setCoachPlusLogo()
}
}
func setNavbarTitle(title: String?) {
if (title != nil) {
self.navigationItem.title = title
}
}
func setCoachPlusLogo() {
let topItem = self.navigationItem
let img = UIImageView(image: UIImage(named: "LogoWhite"))
img.contentMode = .scaleAspectFit
let title = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 45))
img.frame = title.bounds
title.addSubview(img)
topItem.titleView = title
}
func loadData<T>(text: String?, promise: Promise<T>) -> Promise<T> {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.detailsLabel.text = text?.localize()
return Promise { p in
promise.done({ result in
p.fulfill(result)
}).ensure({
hud.hide(animated: true)
})
.catch({err in
self.errorHandler?.handleError(error: err)
p.reject(err)
})
}
}
}
| mit | 848975eb765b59f3ab1910aa41d51135 | 29.545455 | 134 | 0.62252 | 5.136306 | false | false | false | false |
Arror/AttributesBuilder | Sample/Sample/ViewController.swift | 1 | 1585 | import UIKit
import AttributesBuilder
class ViewController: UIViewController {
@IBOutlet weak var contentLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let linkStr = "https://github.com/Arror"
let content = """
CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects.
✨+✨+✨ Github: \(linkStr)
"""
let whole = AttributesBuilder {
$0.color(.gray)
$0.font(.systemFont(ofSize: 14.0))
$0.paragraphStyle { style in
style.lineSpacing = 12.0
}
}
let link = AttributesBuilder {
$0.color(.blue)
$0.link(URL(string: linkStr)!)
}
let special = whole.copy {
$0.color(.red)
$0.font(.systemFont(ofSize: 24.0))
}
let mark = AttributesBuilder {
$0.font(.boldSystemFont(ofSize: 30.0))
}
let specialRange1 = content.startIndex..<(content.index(after: content.startIndex))
let specialRange2 = content.index(content.startIndex, offsetBy: 10)..<content.index(content.startIndex, offsetBy: 12)
self.contentLabel.attributedText = content
.rs.rendered(by: whole)
.rs.rendered(by: special, ranges: specialRange1, specialRange2)
.rs.rendered(by: link, ranges: content.range(of: linkStr)!)
.rs.rendered(by: mark, regexPattern: "✨")
}
}
| mit | 261e68051942dba9c18501d8773ffb6c | 28.754717 | 125 | 0.5409 | 4.531609 | false | false | false | false |
aestesis/Aether | Sources/Aether/3D/Box.swift | 1 | 15908 | //
// Box.swift
// Alib
//
// Created by renan jegouzo on 08/06/2017.
// Copyright © 2017 aestesis. All rights reserved.
//
import Foundation
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct Attenuation {
public var constant:Double
public var linear:Double
public var quadratic:Double
public init(constant:Double=0,linear:Double=0,quadratic:Double=0) {
self.constant = constant
self.linear = linear
self.quadratic = quadratic
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct Rot3 {
public var phi:Double
public var theta:Double
public init(phi:Double=0,theta:Double=0) {
self.phi = phi
self.theta = theta
}
public func lerp(to:Rot3,coef:Double) -> Rot3 {
return Rot3(phi:Rot3.lerpModulo(a:self.phi,b:to.phi,coef:coef),theta:Rot3.lerpModulo(a:self.theta,b:to.theta,coef:coef))
}
public var modulo : Rot3 {
return Rot3(phi:Rot3.modulo(self.phi),theta:Rot3.modulo(self.theta))
}
public var matrix : Mat4 {
return Mat4.rotZ(phi)*Mat4.rotX(theta) // TODO: not sure, need to be tested...
}
public static var random : Rot3 {
return Rot3(phi:ß.rnd*ß.π*2,theta:ß.rnd*ß.π*2)
}
static let pi2 = ß.π*2
static func modulo(_ a:Double) -> Double {
return ß.modulo(a,Rot3.pi2)
}
static func lerpModulo(a:Double,b:Double,coef:Double) -> Double {
let ma = Rot3.modulo(a)
let mb = Rot3.modulo(b)
let sub = mb - ß.π*2
let sup = mb + ß.π*2
let dif = abs(mb-ma)
if ma-sub<dif {
return Rot3.modulo(sub*coef + ma*(1-coef))
} else if sup-ma<dif {
return Rot3.modulo(sup*coef + ma*(1-coef))
}
return mb*coef + ma*(1-coef)
}
}
public func ==(a: Rot3, b: Rot3) -> Bool {
return a.phi == b.phi && a.theta == b.theta
}
public func !=(a: Rot3, b: Rot3) -> Bool {
return a.phi != b.phi || a.theta != b.theta
}
public prefix func - (v: Rot3) -> Rot3 {
return Rot3(phi:-v.phi,theta:-v.theta)
}
public func +(a:Rot3,b:Rot3)->Rot3 {
return Rot3(phi:a.phi+b.phi,theta:a.theta+b.theta)
}
public func -(a:Rot3,b:Rot3)->Rot3 {
return Rot3(phi:a.phi-b.phi,theta:a.theta-b.theta)
}
public func +(a:Rot3,b:Double)->Rot3 {
return Rot3(phi:a.phi+b,theta:a.theta+b)
}
public func -(a:Rot3,b:Double)->Rot3 {
return Rot3(phi:a.phi-b,theta:a.theta-b)
}
public func *(a:Rot3,b:Rot3)->Rot3 {
return Rot3(phi:a.phi*b.phi,theta:a.theta*b.theta)
}
public func *(a:Rot3,b:Double)->Rot3 {
return Rot3(phi:a.phi*b,theta:a.theta*b)
}
public func /(a:Rot3,b:Rot3)->Rot3 {
return Rot3(phi:a.phi/b.phi,theta:a.theta/b.theta)
}
public func /(a:Rot3,b:Double)->Rot3 {
return Rot3(phi:a.phi/b,theta:a.theta/b)
}
public func +=(a:inout Rot3,b:Rot3) {
a = a + b
}
public func -=(a:inout Rot3,b:Rot3) {
a = a - b
}
public func +=(a:inout Rot3,b:Double) {
a = a + b
}
public func -=(a:inout Rot3,b:Double) {
a = a - b
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// http://www.sedris.org/wg8home/Documents/WG80485.pdf
public struct Euler { // Tait–Bryan angles
public var pitch:Double
public var roll:Double
public var yaw:Double
public var matrix : Mat4 {
let cp = cos(pitch)
let sp = sin(pitch)
let cr = cos(roll)
let sr = sin(roll)
let cy = cos(yaw)
let sy = sin(yaw)
return Mat4(r0:Vec4(x:cp*cy,y:cp*sy,z:-sp),
r1:Vec4(x:sr*sp*cy,y:sr*sp*sy,z:cp*sr),
r2:Vec4(x:cr*sp*cy,y:cr*sp*sy,z:cp*cr),
r3:Vec4(w:1))
// aka -> return Mat4.rotZ(yaw)*Mat4.rotY(pitch)*Mat4.rotX(roll)
}
public init(pitch:Double=0,roll:Double=0,yaw:Double=0) {
self.pitch = pitch
self.roll = roll
self.yaw = yaw
}
public init(_ q:Quaternion) {
let ysqr = q.y * q.y
// roll (x-axis)
let t0 = 2.0 * (q.w * q.x + q.y * q.z)
let t1 = 1.0 - 2.0 * (q.x * q.x + ysqr)
roll = atan2(t0,t1)
// pitch (y-axis)
var t2 = 2.0 * (q.w * q.y - q.z * q.x)
t2 = ((t2 > 1.0) ? 1.0 : t2)
t2 = ((t2 < -1.0) ? -1.0 : t2)
pitch = asin(t2)
// yaw (z-axis)
let t3 = 2.0 * (q.w * q.z + q.x * q.y)
let t4 = 1.0 - 2.0 * (ysqr + q.z * q.z)
yaw = atan2(t3,t4)
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// https://github.com/mono/opentk/blob/master/Source/OpenTK/Math/Quaternion.cs
public struct Quaternion {
var q:Vec4
public var x: Double {
get { return q.x }
set(x){ q.x=x }
}
public var y: Double {
get { return q.y }
set(y){ q.y=y }
}
public var z: Double {
get { return q.z }
set(z){ q.z=z }
}
public var w: Double {
get { return q.w }
set(w){ q.w=w }
}
public var xyz:Vec3 {
get { return q.xyz }
set(xyz) { q.xyz=xyz }
}
public var axisAngle : Vec4 {
var q=self.q
if(abs(q.w)>1) {
q=q.normalized
}
var r=Vec4.zero
r.w = 2.0 * acos(q.w)
let den = sqrt(1-q.w*q.w)
if den>0.0001 {
r.xyz = q.xyz/den
} else {
r.xyz = Vec3(x:1)
}
return r
}
public var conjugated : Quaternion {
return Quaternion(xyz:-q.xyz,w:q.w)
}
public var lenght : Double {
return q.length
}
public func lerp(to:Quaternion,coef:Double) -> Quaternion { // TODO: verify if OK
var q1 = self
var q2 = to
if self.lenght == 0 {
if to.lenght == 0 {
return Quaternion.identity
}
return to
} else if to.lenght == 0 {
return self
}
var cosHalfAngle = q1.w*q2.w+Vec3.dot(q1.xyz,q2.xyz)
if cosHalfAngle >= 1 || cosHalfAngle <= -1 {
return self
} else if cosHalfAngle<0 {
q2 = -q2
cosHalfAngle = -cosHalfAngle
}
if cosHalfAngle<0.99 {
let halfAngle = acos(cosHalfAngle)
let sinHalfAngle=sin(halfAngle)
let oneOverSinHalfAngle=1/sinHalfAngle
let a = sin(halfAngle*(1-coef))*oneOverSinHalfAngle
let b = sin(halfAngle*coef)*oneOverSinHalfAngle
let q = q1 * a + q2 * b
if q.lenght>0 {
return q.normalized
}
return Quaternion.identity
}
let q = q1 * (1-coef) + q2 * coef
if q.lenght>0 {
return q.normalized
}
return Quaternion.identity
}
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/
public var matrix : Mat4 {
return Mat4(r0: Vec4(x:1-2*y*y-2*z*z,
y:2*x*y-2*z*w,
z:2*x*z+2*y*w),
r1: Vec4(x:2*x*y+2*z*w,
y:1-2*x*x-2*z*z,
z:2*y*z-2*x*w),
r2: Vec4(x:2*x*z-2*y*w,
y:2*y*z+2*x*w,
z:1-2*x*x-2*y*y),
r3: Vec4(w:1))
}
public var normalized : Quaternion {
return Quaternion(q.normalized)
}
public init(_ v:Vec4) {
self.q=v
}
public init(x:Double=0,y:Double=0,z:Double=0,w:Double=0) {
q=Vec4(x:x,y:y,z:z,w:w)
}
public init(_ xyz:Vec3,_ w:Double) {
q = Vec4(xyz:xyz,w:w)
}
public init(xyz:Vec3,w:Double) {
q = Vec4(xyz:xyz,w:w)
}
public init(axis:Vec3,angle:Double) {
if axis.length > 0 {
let a = angle*0.5
self.q = Vec4(xyz:axis.normalized*sin(a),w:cos(a)).normalized
} else {
self.q = Quaternion.identity.q
}
}
public init(_ e:Euler) {
let cy = cos(e.yaw*0.5)
let sy = sin(e.yaw*0.5)
let cr = cos(e.roll*0.5)
let sr = sin(e.roll*0.5)
let cp = cos(e.pitch*0.5)
let sp = sin(e.pitch*0.5)
q=Vec4(x:cy * sr * cp - sy * cr * sp,
y:cy * cr * sp + sy * sr * cp,
z:sy * cr * cp - cy * sr * sp,
w:cy * cr * cp + sy * sr * sp)
}
public static var identity : Quaternion {
return Quaternion(xyz:.zero,w:1)
}
}
public func ==(a: Quaternion, b: Quaternion) -> Bool {
return a.x==b.x&&a.y==b.y&&a.z==b.z&&a.w==b.w
}
public func !=(a: Quaternion, b: Quaternion) -> Bool {
return a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w
}
public prefix func - (v: Quaternion) -> Quaternion {
return Quaternion(x:-v.x,y:-v.y,z:-v.z,w:-v.w)
}
public func +(a:Quaternion,b:Quaternion)->Quaternion {
return Quaternion(x:a.x+b.x,y:a.y+b.y,z:a.z+b.z,w:a.w+b.w)
}
public func -(a:Quaternion,b:Quaternion)->Quaternion {
return Quaternion(x:a.x-b.x,y:a.y-b.y,z:a.z-b.z,w:a.w-b.w)
}
public func *(q:Quaternion,r:Quaternion)->Quaternion {
return Quaternion(x:r.x*q.x-r.y*q.y-r.z*q.z-r.w*q.w,
y:r.x*q.y+r.y*q.x-r.z*q.w+r.w*q.z,
z:r.x*q.z+r.y*q.w+r.z*q.x-r.w*q.y,
w:r.x*q.w-r.y*q.z+r.z*q.y+r.w*q.x)
}
public func *(a:Quaternion,b:Double)->Quaternion {
return Quaternion(x:a.x*b,y:a.y*b,z:a.z*b,w:a.w*b)
}
public func /(q:Quaternion,r:Quaternion)->Quaternion {
let m = q*r
let d = r.x*r.x+r.y*r.y+r.z*r.z+r.w*r.w
return Quaternion(x:m.x/d,y:m.y/d,z:m.z/d,w:m.w/d)
}
public func /(a:Quaternion,b:Double)->Quaternion {
return Quaternion(x:a.x/b,y:a.y/b,z:a.z/b,w:a.w/b)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct Sphere {
public var center:Vec3
public var radius:Double
public init(bounding box:Box) {
self.center = box.origin.lerp(vector:box.opposite,coef:0.5)
self.radius = (box.opposite-box.origin).length*0.5
}
public init(center:Vec3=Vec3.zero,radius:Double=1) {
self.center = center
self.radius = radius
}
public static var unity : Sphere {
return Sphere()
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct Cylinder {
public var center:Vec3
public var direction:Vec3
public var radius:Double
public init(center:Vec3=Vec3.zero,direction:Vec3=Vec3(y:1),radius:Double=1) {
self.center = center
self.direction = direction
self.radius = radius
}
public init(base:Vec3,direction:Vec3=Vec3(y:1),radius:Double=1) {
self.center = base + direction * 0.5
self.direction = direction
self.radius = radius
}
public static var unity : Cylinder {
return Cylinder()
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct Box {
public var origin : Vec3
public var size: Vec3
public var x: Double {
get { return origin.x }
set(x){ origin.x=x }
}
public var y: Double {
get { return origin.y }
set(y){ origin.y=y }
}
public var z: Double {
get { return origin.z }
set(z){ origin.z=z }
}
public var w: Double {
get { return size.x }
set(width){ size.x=width }
}
public var h: Double {
get { return size.y }
set(height){ size.y=height }
}
public var d: Double {
get { return size.z }
set(depth){ size.z=depth }
}
public var width: Double {
get { return size.x }
set(width){ size.x=width }
}
public var height: Double {
get { return size.y }
set(height){ size.y=height }
}
public var depth: Double {
get { return size.z }
set(depth){ size.z=depth }
}
public var left: Double {
get { return x }
set(l) { w+=x-l; x=l }
}
public var right: Double {
get { return x+width }
set(r) { width=r-x }
}
public var top: Double {
get { return y }
set(t) { h+=y-t; y=t }
}
public var bottom: Double {
get { return y+h }
set(b) { h=b-y }
}
public var front: Double {
get { return z }
set(t) { d+=z-t; z=t }
}
public var back: Double {
get { return z+d }
set(t) { depth=t-z }
}
public var opposite : Vec3 {
return origin+size
}
public var center : Vec3 {
return origin + size * 0.5
}
public func point(_ px:Double,_ py:Double,_ pz:Double) -> Vec3 {
return Vec3(x:x+width*px,y:y+height*py,z:z+depth*pz)
}
public var diagonale : Double {
return sqrt(width*width+height*height+depth*depth)
}
public var random : Vec3 {
return Vec3(x:x+width*ß.rnd,y:y+height*ß.rnd,z:z+depth*ß.rnd)
}
public func union(_ r:Box) -> Box {
if self == Box.zero {
return r
} else if r == Box.zero {
return self
} else {
var rr = Box.zero
rr.left = min(self.left,r.left)
rr.right = max(self.right,r.right)
rr.top = min(self.top,r.top)
rr.bottom = max(self.bottom,r.bottom)
rr.front = min(self.front,r.front)
rr.back = max(self.back,r.back)
return rr
}
}
public func union(_ o:Vec3,_ s:Vec3=Vec3.zero) -> Box {
return self.union(Box(o:o,s:s))
}
public func wrap(_ p:Vec3) -> Vec3 {
return Vec3(x:ß.modulo(p.x-left,width)+left,y:ß.modulo(p.y-top,height)+top,z:ß.modulo(p.z-front,depth)+front)
}
public init(origin:Vec3,size:Vec3) {
self.origin=origin
self.size=size
}
public init(o:Vec3,s:Vec3) {
self.origin=o
self.size=s
}
public init(x:Double=0,y:Double=0,z:Double=0,w:Double=0,h:Double=0,d:Double=0)
{
origin=Vec3(x:x,y:y,z:z)
size=Vec3(x:w,y:h,z:d)
}
public init(center:Vec3,size:Vec3)
{
self.origin=center-size*0.5
self.size=size
}
public static var zero: Box {
return Box(o:Vec3.zero,s:Vec3.zero)
}
public static var infinity: Box {
return Box(o:-Vec3.infinity,s:Vec3.infinity)
}
public static var unity: Box {
return Box(o:Vec3.zero,s:Vec3(x:1,y:1,z:1))
}
}
public func ==(lhs: Box, rhs: Box) -> Bool {
return (lhs.origin==rhs.origin)&&(lhs.size==rhs.size)
}
public func !=(lhs: Box, rhs: Box) -> Bool {
return (lhs.origin != rhs.origin)||(lhs.size != rhs.size)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
| apache-2.0 | b0751a1f0c20a3eff637b532d74eae0c | 31.420408 | 128 | 0.472051 | 3.172125 | false | false | false | false |
Keenan144/SpaceKase | SpaceKase/File.swift | 1 | 1653 | //
// File.swift
// SpaceKase
//
// Created by Keenan Sturtevant on 6/21/16.
// Copyright © 2016 Keenan Sturtevant. All rights reserved.
//
import Foundation
import SpriteKit
class Health: SKSpriteNode {
class func spawn() -> SKSpriteNode {
let healthColor = UIColor.greenColor()
let healthSize = CGSize(width: 20, height: 20)
let health = SKSpriteNode(color: healthColor, size: healthSize)
health.texture = SKTexture(imageNamed: "Health")
health.physicsBody = SKPhysicsBody(rectangleOfSize: healthSize)
health.physicsBody?.dynamic = true
health.physicsBody?.usesPreciseCollisionDetection = true
health.physicsBody?.affectedByGravity = false
health.physicsBody?.velocity.dy = -300
health.name = "Health"
print("HEALTH: spawn")
return health
}
class func showHealth(label: SKLabelNode) -> SKLabelNode {
label.removeFromParent()
label.text = "Health: \(SpaceShip.shipHealth())"
switch (SpaceShip.shipHealth()) {
case _ where (SpaceShip.shipHealth() > 80):
label.fontColor = UIColor.greenColor()
case _ where (SpaceShip.shipHealth() > 60):
label.fontColor = UIColor.yellowColor()
case _ where (SpaceShip.shipHealth() > 40):
label.fontColor = UIColor.orangeColor()
case _ where (SpaceShip.shipHealth() > 20):
label.fontColor = UIColor.redColor()
default:
label.fontColor = UIColor.grayColor()
}
print("HEALTH: showHealth")
return label
}
}
| mit | aeb226a080c816c3f1b7aa1c4a94b9bf | 31.392157 | 71 | 0.614407 | 4.550964 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceKit/Sources/EurofurenceKit/EurofurencePersistentContainer.swift | 1 | 2681 | import CoreData
import EurofurenceWebAPI
import Logging
class EurofurencePersistentContainer: NSPersistentContainer {
private let logger = Logger(label: "EurofurencePersistentContainer")
private let api: EurofurenceAPI
private let keychain: Keychain
private let properties: EurofurenceModelProperties
private let calendar: EventCalendar
init(
api: EurofurenceAPI,
keychain: Keychain,
properties: EurofurenceModelProperties,
calendar: EventCalendar
) {
self.api = api
self.keychain = keychain
self.properties = properties
self.calendar = calendar
super.init(name: "Eurofurence", managedObjectModel: .eurofurenceModel)
viewContext.automaticallyMergesChangesFromParent = true
configureUserInfo(for: viewContext)
}
override func newBackgroundContext() -> NSManagedObjectContext {
let backgroundContext = super.newBackgroundContext()
configureUserInfo(for: backgroundContext)
return backgroundContext
}
private func configureUserInfo(for managedObjectContext: NSManagedObjectContext) {
managedObjectContext.persistentContainer = self
managedObjectContext.eurofurenceAPI = api
managedObjectContext.keychain = keychain
managedObjectContext.properties = properties
managedObjectContext.eventsCalendar = calendar
}
}
// MARK: - Attaching Persistent Stores
extension EurofurencePersistentContainer {
func attachPersistentStore(properties: EurofurenceModelProperties) {
let modelDirectory = properties.persistentStoreDirectory
let persistentStoreURL = modelDirectory.appendingPathComponent("database.sqlite")
let persistentStoreDescription = NSPersistentStoreDescription(url: persistentStoreURL)
persistentStoreDescription.type = NSSQLiteStoreType
persistentStoreDescriptions = [persistentStoreDescription]
loadPersistentStores()
}
func attachMemoryStore() {
let persistentStoreDescription = NSPersistentStoreDescription()
persistentStoreDescription.type = NSInMemoryStoreType
persistentStoreDescriptions = [persistentStoreDescription]
loadPersistentStores()
}
private func loadPersistentStores() {
loadPersistentStores { [logger] _, error in
if let error = error {
logger.error(
"Failed to attach persistent store",
metadata: ["Error": .string(String(describing: error))]
)
}
}
}
}
| mit | c95ac9519f10e27e86534541699b0e8d | 32.5125 | 94 | 0.685938 | 6.669154 | false | false | false | false |
ManueGE/Actions | actions/actions/NotificationCenter+Actions.swift | 1 | 9855 | //
// NotificationCenter+Actions.swift
// actions
//
// Created by Manu on 6/7/16.
// Copyright © 2016 manuege. All rights reserved.
//
import Foundation
private protocol NotificationCenterAction: Action {
var notificationName: NSNotification.Name? { get }
var notificationObject: AnyObject? { get }
}
private class NotificationCenterVoidAction: VoidAction, NotificationCenterAction {
fileprivate let notificationName: NSNotification.Name?
fileprivate let notificationObject: AnyObject?
fileprivate init(name: NSNotification.Name?, object: AnyObject?, action: @escaping () -> Void) {
self.notificationName = name
self.notificationObject = object
super.init(action: action)
}
}
private class NotificationCenterParametizedAction: ParametizedAction<NSNotification>, NotificationCenterAction {
fileprivate let notificationName: NSNotification.Name?
fileprivate let notificationObject: AnyObject?
fileprivate init(name: NSNotification.Name?, object: AnyObject?, action: @escaping (NSNotification) -> Void) {
self.notificationName = name
self.notificationObject = object;
super.init(action: action)
}
}
/// Observe notifications with closures instead of a pair of observer/selector
extension NotificationCenter {
// MARK: Add observers
/**
Adds an entry to the receiver’s dispatch table with a closure and optional criteria: notification name and sender.
The observation lives until it is manually stopped,, so be sure to invoke `stopObserving(_)` when the observation is not longer needed
- parameter name: The name of the notification for which to register the observer; that is, only notifications with this name are delivered to the observer.
If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.
- parameter object: The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer. Default is `nil`.
- parameter action: The closure which will be called when a notification with the criteria is sent
- returns: The action that has been added to the receiver. You can catch this value to stop observing it by calling `stopObserving(_)`.
*/
@discardableResult
public func observe(_ name: NSNotification.Name?, object: AnyObject? = nil, action: @escaping () -> Void) -> Action {
let action = NotificationCenterVoidAction(name: name, object: object, action: action)
addObserver(action, selector: action.selector, name: name, object: object)
retainAction(action, self)
return action
}
/**
Adds an entry to the receiver’s dispatch table with a closure and optional criteria: notification name and sender.
The observation lives until it is manually stopped, so be sure to invoke `stopObserving(_)` when the observation is not longer needed
- parameter name: The name of the notification for which to register the observer; that is, only notifications with this name are delivered to the observer.
If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.
- parameter object: The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer. Default is `nil`.
- parameter action: The closure which will be called when a notification with the criteria is sent
- returns: The action that has been added to the receiver. You can catch this value to stop observing it by calling `stopObserving(_)`.
*/
@discardableResult
@nonobjc
public func observe(_ name: NSNotification.Name?, object: AnyObject? = nil, action: @escaping (NSNotification) -> Void) -> Action {
let action = NotificationCenterParametizedAction(name: name, object: object, action: action)
addObserver(action, selector: action.selector, name: name, object: object)
retainAction(action, self)
return action
}
/**
Adds an entry to the receiver’s dispatch table with a closure and optional criteria: notification name and sender.
The observation lives while the `observer` is not deallocated. In case you need stop the observation before the òbserver` is deallocated, you can do it by invoking `stopObserving(_)`.
- note: Due to internal implementation, the defaul method `removeObserver` not take any effect on obervations registered using this method.
- parameter observer: Object registering as an observer. This value must not be nil.
If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.
- parameter name: The name of the notification for which to register the observer; that is, only notifications with this name are delivered to the observer.
If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.
- parameter object: The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer. Default is `nil`.
- parameter action: The closure which will be called when a notification with the criteria is sent
- returns: The action that has been added to the receiver. You can catch this value to stop observing it by calling `stopObserving(_)`.
*/
@discardableResult
public func add(observer: NSObject, name: NSNotification.Name?, object: AnyObject? = nil, action: @escaping () -> Void) -> Action {
let action = NotificationCenterVoidAction(name: name, object: object, action: action)
addObserver(action, selector: action.selector, name: name, object: object)
retainAction(action, observer)
return action
}
/**
Adds an entry to the receiver’s dispatch table with a closure and optional criteria: notification name and sender.
The observation lives while the `observer` is not deallocated. In case you need stop the observation before the òbserver` is deallocated, you can do it by invoking `stopObserving(_)`.
- note: Due to internal implementation, the defaul method `removeObserver` not take any effect on obervations registered using this method.
- parameter observer: Object registering as an observer. This value must not be nil.
If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.
- parameter name: The name of the notification for which to register the observer; that is, only notifications with this name are delivered to the observer.
If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.
- parameter object: The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer. Default is `nil`.
- parameter action: The closure which will be called when a notification with the criteria is sent
- returns: The action that has been added to the receiver. You can catch this value to stop observing it by calling `stopObserving(_)`.
*/
@discardableResult
@nonobjc
public func add(observer: NSObject, name: NSNotification.Name?, object: AnyObject? = nil, action: @escaping (NSNotification) -> Void) -> Action {
let action = NotificationCenterParametizedAction(name: name, object: object, action: action)
addObserver(action, selector: action.selector, name: name, object: object)
retainAction(action, observer)
return action
}
// MARK: Remove observers
/**
Stop observing the given action.
- parameter action: The action which won't be observed anymore
*/
public func stopObserving(action: Action) {
NotificationCenter.default.removeObserver(action)
releaseAction(action, self)
}
/**
Removes all the entries specifying a given observer from the receiver’s dispatch table.
Be sure to invoke this method (or stopObserver(_:name:object:)) before observer or any object specified in add(observer:name:action:) is deallocated.
You should not use this method to remove all observers from an object that is going to be long-lived, because your code may not be the only code adding observers that involve the object.
- parameter observer: Object unregistered as observer.
- parameter name: The name of the notification for which to unregister the observer; if nil, notifications with any name will be stopped.
- parameter object: The object whose notifications the observer wants to stop; if nil, notifications from any object will be stopped.
*/
public func stopObserver(_ observer: NSObject, name: NSNotification.Name? = nil, object: AnyObject? = nil) {
for (_, value) in observer.actions {
guard let action = value as? NotificationCenterAction else {
continue
}
var matches: Bool
switch (name, object) {
case (nil, nil):
matches = true
case let (.some(name), nil):
matches = (name == action.notificationName)
case let (nil, .some(object)):
matches = (object === object)
case let (.some(name), .some(object)):
matches = (object === object) && (name == action.notificationName)
}
if matches {
stopObserving(action: action)
}
}
}
}
| mit | 2d57b8275f8747b947bae4f4e08ae105 | 59.604938 | 191 | 0.71043 | 4.976178 | false | false | false | false |
Laptopmini/SwiftyArtik | Source/ScenesAPI.swift | 1 | 7754 | //
// ScenesAPI.swift
// SwiftyArtik
//
// Created by Paul-Valentin Mini on 12/11/17.
// Copyright © 2017 Paul-Valentin Mini. All rights reserved.
//
import Foundation
import PromiseKit
import Alamofire
open class ScenesAPI {
/// Create a Scene.
///
/// - Parameters:
/// - name: The name of the scene.
/// - actions: The scene's actions definition.
/// - uid: (Optional) The User's ID, required if using an `ApplicationToken`.
/// - Returns: A `Promise<Scene>`
open class func create(name: String, description: String? = nil, actions: [[String:Any]], uid: String? = nil) -> Promise<Scene> {
let promise = Promise<Scene>.pending()
let path = SwiftyArtikSettings.basePath + "/scenes"
let parameters = APIHelpers.removeNilParameters([
"name": name,
"description": description,
"actions": actions,
"uid": uid
])
APIHelpers.makeRequest(url: path, method: .post, parameters: parameters, encoding: JSONEncoding.default).then { response -> Void in
if let data = response["data"] as? [String:Any], let instance = Scene(JSON: data) {
promise.fulfill(instance)
} else {
promise.reject(ArtikError.json(reason: .unexpectedFormat))
}
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
/// Update a Scene.
///
/// - Parameters:
/// - id: The scene's ID.
/// - name: (Optional) The scene's new name.
/// - actions: (Optional) The scene's new actions definition.
/// - uid: (Optional) The User's ID, required if using an `ApplicationToken`.
/// - Returns: A `Promise<Scene>`
open class func update(id: String, name: String? = nil, description: String? = nil, actions: [[String:Any]]? = nil, uid: String? = nil) -> Promise<Scene> {
let promise = Promise<Scene>.pending()
let path = SwiftyArtikSettings.basePath + "/scenes"
var parameters = APIHelpers.removeNilParameters([
"name": name,
"description": description,
"actions": actions
])
if parameters.count > 0 {
if let uid = uid {
parameters["uid"] = uid
}
APIHelpers.makeRequest(url: path, method: .put, parameters: parameters, encoding: JSONEncoding.default).then { response -> Void in
if let data = response["data"] as? [String:Any], let instance = Scene(JSON: data) {
promise.fulfill(instance)
} else {
promise.reject(ArtikError.json(reason: .unexpectedFormat))
}
}.catch { error -> Void in
promise.reject(error)
}
} else {
self.get(id: id).then { scene -> Void in
promise.fulfill(scene)
}.catch { error -> Void in
promise.reject(error)
}
}
return promise.promise
}
/// Get a Scene
///
/// - Parameter id: The scene's ID.
/// - Returns: A `Promise<Scene>`
open class func get(id: String) -> Promise<Scene> {
let promise = Promise<Scene>.pending()
let path = SwiftyArtikSettings.basePath + "/scenes/\(id)"
APIHelpers.makeRequest(url: path, method: .get, parameters: nil, encoding: URLEncoding.default).then { response -> Void in
if let data = response["data"] as? [String:Any], let instance = Scene(JSON: data) {
promise.fulfill(instance)
} else {
promise.reject(ArtikError.json(reason: .unexpectedFormat))
}
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
/// Get a User's Scenes.
///
/// - Parameters:
/// - uid: The User's ID.
/// - count: The count of results, max `100`.
/// - offset: The offset for pagination, default `0`.
/// - Returns: A `Promise<Page<Scene>>`
open class func get(uid: String, count: Int, offset: Int = 0) -> Promise<Page<Scene>> {
let promise = Promise<Page<Scene>>.pending()
let path = SwiftyArtikSettings.basePath + "/users/\(uid)/scenes"
let parameters = [
"count": count,
"offset": offset
]
APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in
if let total = response["total"] as? Int64, let offset = response["offset"] as? Int64, let count = response["count"] as? Int64, let scenes = (response["data"] as? [String:Any])?["scenes"] as? [[String:Any]] {
let page = Page<Scene>(offset: offset, total: total)
if scenes.count != Int(count) {
promise.reject(ArtikError.json(reason: .countAndContentDoNotMatch))
return
}
for item in scenes {
if let scene = Scene(JSON: item) {
page.data.append(scene)
} else {
promise.reject(ArtikError.json(reason: .invalidItem))
return
}
}
promise.fulfill(page)
} else {
promise.reject(ArtikError.json(reason: .unexpectedFormat))
}
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
/// Get all of a User's Scenes using recursive requests.
/// WARNING: May strongly impact your rate limit and quota.
///
/// - Parameter uid: The User's id.
/// - Returns: A `Promise<Page<Scene>>`
open class func get(uid: String) -> Promise<Page<Scene>> {
return self.getRecursive(Page<Scene>(), uid: uid)
}
/// Remove a Scene.
///
/// - Parameter id: The scene's ID.
/// - Returns: A `Promise<Void>`
open class func remove(id: String) -> Promise<Void> {
return DevicesAPI.delete(id: id)
}
/// Activate a Scene.
///
/// - Parameter id: The scene's ID.
/// - Returns: A `Promise<Void>`
open class func activate(id: String) -> Promise<Void> {
let promise = Promise<Void>.pending()
let path = SwiftyArtikSettings.basePath + "/scenes/\(id)"
APIHelpers.makeRequest(url: path, method: .post, parameters: nil, encoding: JSONEncoding.default).then { _ -> Void in
promise.fulfill(())
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
// MARK: - Private Methods
private class func getRecursive(_ container: Page<Scene>, uid: String, offset: Int = 0) -> Promise<Page<Scene>> {
let promise = Promise<Page<Scene>>.pending()
self.get(uid: uid, count: 100, offset: offset).then { result -> Void in
container.data.append(contentsOf: result.data)
container.total = result.total
if container.total > Int64(container.data.count) {
self.getRecursive(container, uid: uid, offset: Int(result.offset) + result.data.count).then { result -> Void in
promise.fulfill(result)
}.catch { error -> Void in
promise.reject(error)
}
} else {
promise.fulfill(container)
}
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
}
| mit | 1cb4e6fcc5be7a7f080e78512c7a6e2b | 37.381188 | 220 | 0.541855 | 4.362971 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/Chat/CellNodes/ChatSectionDateCellNode.swift | 1 | 2118 | //
// ChatSectionDateCellNode.swift
// Yep
//
// Created by NIX on 16/7/5.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import RealmSwift
import AsyncDisplayKit
class ChatSectionDateCellNode: ASCellNode {
private static let topPadding: CGFloat = 0
private static let bottomPadding: CGFloat = 5
private static var verticalPadding: CGFloat {
return topPadding + bottomPadding
}
private static let textAttributes = [
NSForegroundColorAttributeName: UIColor.darkGrayColor(),
NSFontAttributeName: UIFont.systemFontOfSize(12),
]
private lazy var textNode: ASTextNode = {
let node = ASTextNode()
node.layerBacked = true
return node
}()
override init() {
super.init()
selectionStyle = .None
addSubnode(textNode)
}
func configure(withMessage message: Message) {
let text = message.sectionDateString
textNode.attributedText = NSAttributedString(string: text, attributes: ChatSectionDateCellNode.textAttributes)
}
func configure(withText text: String) {
textNode.attributedText = NSAttributedString(string: text, attributes: ChatSectionDateCellNode.textAttributes)
}
override func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize {
let textMaxWidth = constrainedSize.width - (15 + 15)
textNode.measure(CGSize(width: textMaxWidth, height: CGFloat.max))
let height = max(20, textNode.calculatedSize.height)
return CGSize(width: constrainedSize.width, height: height + ChatSectionDateCellNode.verticalPadding)
}
override func layout() {
super.layout()
let x = (calculatedSize.width - textNode.calculatedSize.width) / 2
let containerHeight = calculatedSize.height - ChatSectionDateCellNode.verticalPadding
let y = (containerHeight - textNode.calculatedSize.height) / 2 + ChatSectionDateCellNode.topPadding
let origin = CGPoint(x: x, y: y)
textNode.frame = CGRect(origin: origin, size: textNode.calculatedSize)
}
}
| mit | 82812a2647df977b0531c101469b8ff4 | 28.788732 | 118 | 0.695981 | 4.895833 | false | false | false | false |
coderLHQ/DYZB | DYZB/DYZB/class/home/ViewC/HomeViewController.swift | 1 | 4144 | //
// HomeViewController.swift
// DYZB
//
// Created by lhq on 2017/5/17.
// Copyright © 2017年 LhqHelianthus. All rights reserved.
//
import UIKit
private let KTitleViewH : CGFloat = 40
class HomeViewController: UIViewController {
//懒加载属性
fileprivate lazy var pageTitleView: PageTitleView={[weak self] in
let titleFrame = CGRect (x: 0, y: kStatuBarH+kNavigationBarH, width: kScreenW, height: KTitleViewH)
let titles = ["推荐","游戏","娱乐","趣玩"]
let titleView = PageTitleView (frame: titleFrame, titles: titles)
titleView.delegate = self
return titleView
}()
fileprivate lazy var pageContentView : PageContentView = {[weak self] in
//1.设置内容frame
let contentH = kScreenH-kNavigationBarH-kStatuBarH-KTitleViewH
let contentFrame = CGRect (x: 0, y: kNavigationBarH+kStatuBarH+KTitleViewH, width: kScreenW, height: contentH)
//2.确定所有的子控制器
var childVCs=[UIViewController]()
for _ in 0..<4 {
let vc = UIViewController()
vc.view.backgroundColor = UIColor (r: CGFloat(arc4random_uniform(100)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)), a: 1)
childVCs.append(vc)
}
let contentView = PageContentView (frame: contentFrame, childVcs: childVCs, parentViewController: self)
contentView.delegate=self
return contentView
}()
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setupUI()
// Do any additional setup after loading the view.
}
}
//设置UI界面
extension HomeViewController{
fileprivate func setupUI(){
//0.不需要调整scrollView的内边距
automaticallyAdjustsScrollViewInsets = false
//1.设置导航栏
setupNavigationBar()
//2.添加titleView
view.addSubview(pageTitleView)
//3.添加contentView
pageContentView.backgroundColor=UIColor.orange
view.addSubview(pageContentView)
}
fileprivate func setupNavigationBar(){
//设置左侧item
let btn = UIButton()
btn.setImage(UIImage (named: "logo"), for: .normal)
btn.sizeToFit()
navigationItem.leftBarButtonItem = UIBarButtonItem (customView: btn)
//2.设置右侧的Items
let histpryBtn = UIButton()
histpryBtn.setImage(UIImage (named: "image_my_history"), for: UIControlState.normal)
histpryBtn.setImage(UIImage (named: "image_my_history_click"), for: UIControlState.highlighted)
histpryBtn.sizeToFit()
let historyItem = UIBarButtonItem (customView: histpryBtn)
let searchBtn = UIButton()
searchBtn.setImage(UIImage (named: "btn_search"), for: UIControlState.normal)
searchBtn.setImage(UIImage (named: "btn_search_clicked"), for: UIControlState.highlighted)
searchBtn.sizeToFit()
let searchItem = UIBarButtonItem (customView: searchBtn)
let qrcondeBtn = UIButton()
qrcondeBtn.setImage(UIImage (named: "Image_scan"), for: UIControlState.normal)
qrcondeBtn.setImage(UIImage (named: "Image_scan_click"), for: UIControlState.highlighted)
qrcondeBtn.sizeToFit()
let qrcondeImem = UIBarButtonItem (customView: qrcondeBtn)
navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcondeImem]
}
}
//
extension HomeViewController : PageTitleViewDelegate{
func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) {
pageContentView.setCurrentIndex(currentIndex: index)
}
}
//遵守pagecontentViewdelegate
extension HomeViewController : PageContentViewDelegate{
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setPageTitleWithPrgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| mit | c55c0e28fa18020bdbaf7726c4a62392 | 31.909836 | 170 | 0.654296 | 4.802632 | false | false | false | false |
brave/browser-ios | brave/src/data/History.swift | 1 | 5072 | /* 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 CoreData
import Shared
private func getDate(_ dayOffset: Int) -> Date {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let nowComponents = calendar.dateComponents([Calendar.Component.year, Calendar.Component.month, Calendar.Component.day], from: Date())
let today = calendar.date(from: nowComponents)!
return (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.day, value: dayOffset, to: today, options: [])!
}
private var ignoredSchemes = ["about"]
public func isIgnoredURL(_ url: URL) -> Bool {
guard let scheme = url.scheme else { return false }
if let _ = ignoredSchemes.index(of: scheme) {
return true
}
if url.host == "localhost" {
return true
}
return false
}
public func isIgnoredURL(_ url: String) -> Bool {
if let url = URL(string: url) {
return isIgnoredURL(url)
}
return false
}
public final class History: NSManagedObject, WebsitePresentable, CRUD {
@NSManaged public var title: String?
@NSManaged public var url: String?
@NSManaged public var visitedOn: Date?
@NSManaged public var syncUUID: UUID?
@NSManaged public var domain: Domain?
@NSManaged public var sectionIdentifier: String?
static let Today = getDate(0)
static let Yesterday = getDate(-1)
static let ThisWeek = getDate(-7)
static let ThisMonth = getDate(-31)
// Currently required, because not `syncable`
static func entity(_ context: NSManagedObjectContext) -> NSEntityDescription {
return NSEntityDescription.entity(forEntityName: "History", in: context)!
}
public class func add(_ title: String, url: URL) {
let context = DataController.newBackgroundContext()
context.perform {
var item = History.getExisting(url, context: context)
if item == nil {
item = History(entity: History.entity(context), insertInto: context)
item!.domain = Domain.getOrCreateForUrl(url, context: context)
item!.url = url.absoluteString
}
item?.title = title
item?.domain?.visits += 1
item?.visitedOn = Date()
item?.sectionIdentifier = Strings.Today
DataController.save(context: context)
}
}
public class func frc() -> NSFetchedResultsController<NSFetchRequestResult> {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
let context = DataController.viewContext
fetchRequest.entity = History.entity(context)
fetchRequest.fetchBatchSize = 20
fetchRequest.fetchLimit = 200
fetchRequest.sortDescriptors = [NSSortDescriptor(key:"visitedOn", ascending: false)]
fetchRequest.predicate = NSPredicate(format: "visitedOn >= %@", History.ThisMonth as CVarArg)
return NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:context, sectionNameKeyPath: "sectionIdentifier", cacheName: nil)
}
public override func awakeFromFetch() {
if sectionIdentifier != nil {
return
}
if visitedOn?.compare(History.Today) == ComparisonResult.orderedDescending {
sectionIdentifier = Strings.Today
} else if visitedOn?.compare(History.Yesterday) == ComparisonResult.orderedDescending {
sectionIdentifier = Strings.Yesterday
} else if visitedOn?.compare(History.ThisWeek) == ComparisonResult.orderedDescending {
sectionIdentifier = Strings.Last_week
} else {
sectionIdentifier = Strings.Last_month
}
}
class func getExisting(_ url: URL, context: NSManagedObjectContext) -> History? {
let urlKeyPath = #keyPath(History.url)
let predicate = NSPredicate(format: "\(urlKeyPath) == %@", url.absoluteString)
return first(where: predicate, context: context)
}
class func frecencyQuery(_ context: NSManagedObjectContext, containing:String? = nil) -> [History] {
let urlKeyPath = #keyPath(History.url)
let visitedOnKeyPath = #keyPath(History.visitedOn)
var predicate = NSPredicate(format: "\(visitedOnKeyPath) > %@", History.ThisWeek as CVarArg)
if let query = containing {
predicate = NSPredicate(format: predicate.predicateFormat + " AND \(urlKeyPath) CONTAINS %@", query)
}
return all(where: predicate, fetchLimit: 100) ?? []
}
public class func deleteAll(_ completionOnMain: @escaping () -> Void) {
let context = DataController.newBackgroundContext()
// No save, save in Domain
History.deleteAll(context: context, includesPropertyValues: false, save: false)
Domain.deleteNonBookmarkedAndClearSiteVisits(context: context) {
completionOnMain()
}
}
}
| mpl-2.0 | 751a7f3d0c8b8e35a279dee914047f91 | 36.850746 | 198 | 0.659306 | 4.914729 | false | false | false | false |
ncalexan/mentat | sdks/swift/Mentat/Mentat/Core/TypedValue.swift | 3 | 5365 | /* Copyright 2018 Mozilla
*
* 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 MentatStore
/**
A wrapper around Mentat's `TypedValue` Rust object. This class wraps a raw pointer to a Rust `TypedValue`
struct and provides accessors to the values according to expected result type.
As the FFI functions for fetching values are consuming, this class keeps a copy of the result internally after
fetching so that the value can be referenced several times.
Also, due to the consuming nature of the FFI layer, this class also manages it's raw pointer, nilling it after calling the
FFI conversion function so that the underlying base class can manage cleanup.
*/
open class TypedValue: OptionalRustObject {
private var value: Any?
/**
The `ValueType` for this `TypedValue`.
- Returns: The `ValueType` for this `TypedValue`.
*/
var valueType: ValueType {
return typed_value_value_type(self.raw!)
}
private func isConsumed() -> Bool {
return self.raw == nil
}
/**
This value as a `Int64`. This function will panic if the `ValueType` of this `TypedValue`
is not a `Long`
- Returns: the value of this `TypedValue` as a `Int64`
*/
open func asLong() -> Int64 {
defer {
self.raw = nil
}
if !self.isConsumed() {
self.value = typed_value_into_long(self.raw!)
}
return self.value as! Int64
}
/**
This value as an `Entid`. This function will panic if the `ValueType` of this `TypedValue`
is not a `Ref`
- Returns: the value of this `TypedValue` as an `Entid`
*/
open func asEntid() -> Entid {
defer {
self.raw = nil
}
if !self.isConsumed() {
self.value = typed_value_into_entid(self.raw!)
}
return self.value as! Entid
}
/**
This value as a keyword `String`. This function will panic if the `ValueType` of this `TypedValue`
is not a `Keyword`
- Returns: the value of this `TypedValue` as a keyword `String`
*/
open func asKeyword() -> String {
defer {
self.raw = nil
}
if !self.isConsumed() {
self.value = String(destroyingRustString: typed_value_into_kw(self.raw!))
}
return self.value as! String
}
/**
This value as a `Bool`. This function will panic if the `ValueType` of this `TypedValue`
is not a `Boolean`
- Returns: the value of this `TypedValue` as a `Bool`
*/
open func asBool() -> Bool {
defer {
self.raw = nil
}
if !self.isConsumed() {
let v = typed_value_into_boolean(self.raw!)
self.value = v > 0
}
return self.value as! Bool
}
/**
This value as a `Double`. This function will panic if the `ValueType` of this `TypedValue`
is not a `Double`
- Returns: the value of this `TypedValue` as a `Double`
*/
open func asDouble() -> Double {
defer {
self.raw = nil
}
if !self.isConsumed() {
self.value = typed_value_into_double(self.raw!)
}
return self.value as! Double
}
/**
This value as a `Date`. This function will panic if the `ValueType` of this `TypedValue`
is not a `Instant`
- Returns: the value of this `TypedValue` as a `Date`
*/
open func asDate() -> Date {
defer {
self.raw = nil
}
if !self.isConsumed() {
let timestamp = typed_value_into_timestamp(self.raw!)
self.value = Date(timeIntervalSince1970: TimeInterval(timestamp))
}
return self.value as! Date
}
/**
This value as a `String`. This function will panic if the `ValueType` of this `TypedValue`
is not a `String`
- Returns: the value of this `TypedValue` as a `String`
*/
open func asString() -> String {
defer {
self.raw = nil
}
if !self.isConsumed() {
self.value = String(destroyingRustString: typed_value_into_string(self.raw!));
}
return self.value as! String
}
/**
This value as a `UUID`. This function will panic if the `ValueType` of this `TypedValue`
is not a `Uuid`
- Returns: the value of this `TypedValue` as a `UUID?`. If the `UUID` is not valid then this function returns nil.
*/
open func asUUID() -> UUID? {
defer {
self.raw = nil
}
if !self.isConsumed() {
let bytes = typed_value_into_uuid(self.raw!);
self.value = UUID(destroyingRustUUID: bytes);
}
return self.value as! UUID?
}
override open func cleanup(pointer: OpaquePointer) {
typed_value_destroy(pointer)
}
}
| apache-2.0 | 796548a3e6dbf7aa6d4d2739c899c30d | 28.640884 | 123 | 0.601678 | 4.067475 | false | false | false | false |
sparklit/adbutler-ios-sdk | AdButler/AdButler/PlacementResponseOperation.swift | 1 | 1136 | //
// PlacementResponseOperation.swift
// AdButler
//
// Created by Ryuichi Saito on 11/11/16.
// Copyright © 2016 AdButler. All rights reserved.
//
import Foundation
class PlacementResponseOperation: AsynchronousOperation {
let _responseCollector: ResponseCollector
init(responseCollector: ResponseCollector) {
_responseCollector = responseCollector
}
override func main() {
defer {
finish()
}
let responses = _responseCollector.responses
var placements = [Placement]()
for response in responses {
if case let .success(_, eachPlacements) = response {
// we aggregate all successful responses
placements.append(contentsOf: eachPlacements)
} else {
// for unsuccessful requests, we just return the first failure
_responseCollector.complete(response)
return
}
}
let status: ResponseStatus = placements.isEmpty ? .noAds : .success
_responseCollector.complete(.success(status, placements))
}
}
| apache-2.0 | 10e67a31c8f84d35932ab0a067d5a08c | 28.868421 | 78 | 0.613216 | 5.182648 | false | false | false | false |
Tobiaswk/XLForm | Examples/Swift/SwiftExample/PredicateExamples/PredicateFormViewController.swift | 4 | 5014 | //
// PredicateFormViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
class PredicateFormViewController : XLFormViewController {
fileprivate struct Tags {
static let Text = "text"
static let Integer = "integer"
static let Switch = "switch"
static let Date = "date"
static let Account = "account"
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initializeForm()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeForm()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Predicates example")
section = XLFormSectionDescriptor()
section.title = "Independent rows"
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.Text, rowType: XLFormRowDescriptorTypeAccount, title:"Text")
row.cellConfigAtConfigure["textField.placeholder"] = "Type disable"
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.Integer, rowType: XLFormRowDescriptorTypeInteger, title:"Integer")
row.hidden = NSPredicate(format: "$\(Tags.Switch).value==0")
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.Switch, rowType: XLFormRowDescriptorTypeBooleanSwitch, title:"Boolean")
row.value = true
section.addFormRow(row)
form.addFormSection(section)
section = XLFormSectionDescriptor()
section.title = "Dependent section"
section.footerTitle = "Type disable in the textfield, a number between 18 and 60 in the integer field or use the switch to disable the last row. By doing all three the last section will hide.\nThe integer field hides when the boolean switch is set to 0."
form.addFormSection(section)
// Predicate Disabling
row = XLFormRowDescriptor(tag: Tags.Date, rowType: XLFormRowDescriptorTypeDateInline, title:"Disabled")
row.value = Date()
section.addFormRow(row)
row.disabled = NSPredicate(format: "$\(Tags.Text).value contains[c] 'disable' OR ($\(Tags.Integer).value between {18, 60}) OR ($\(Tags.Switch).value == 0)")
section.hidden = NSPredicate(format: "($\(Tags.Text).value contains[c] 'disable') AND ($\(Tags.Integer).value between {18, 60}) AND ($\(Tags.Switch).value == 0)")
section = XLFormSectionDescriptor()
section.title = "More predicates..."
section.footerTitle = "This row hides when the row of the previous section is disabled and the textfield in the first section contains \"out\"\n\nPredicateFormViewController.swift"
form.addFormSection(section)
row = XLFormRowDescriptor(tag: "thirds", rowType:XLFormRowDescriptorTypeAccount, title:"Account")
section.addFormRow(row)
row.hidden = NSPredicate(format: "$\(Tags.Date).isDisabled == 1 AND $\(Tags.Text).value contains[c] 'Out'")
row.onChangeBlock = { [weak self] oldValue, newValue, _ in
let noValue = "No Value"
let message = "Old value: \(oldValue ?? noValue), New value: \(newValue ?? noValue)"
let alertView = UIAlertController(title: "Account Field changed", message: message, preferredStyle: .actionSheet)
alertView.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self?.navigationController?.present(alertView, animated: true, completion: nil)
}
self.form = form
}
}
| mit | 3f9c35a566cb93f3d56c45044318fa7f | 40.438017 | 262 | 0.668728 | 4.925344 | false | false | false | false |
TySchultz/TSIntro | Example/TSIntro/Intro/TSIntroViewController.swift | 1 | 1967 | //
// TSIntroViewController.swift
//
//
// Created by Ty Schultz on 4/7/16.
//
//
import UIKit
class TSIntroViewController: UIViewController, UIScrollViewDelegate {
var scroll : TSIntroScrollView!
override func viewDidLoad() {
super.viewDidLoad()
//Initialize the scrollview
scroll = TSIntroScrollView(frame: self.view.frame)
scroll.introViewController = self
scroll.delegate = self
self.view.addSubview(scroll)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Calls the scrollview to add a new page to the contentView
func addPage(title : String, image : UIImage, content : String){
scroll.addPage(title, image: image, content: content)
}
//Closes the tutorial view and goes back to the viewcontroller which called the tutorial
func dismissTutorial() {
self.dismissViewControllerAnimated(true, completion: nil)
}
/**
Controls how the pages move their contents
When scrolling the images move at different rates then the descriptions below
**/
func scrollViewDidScroll(scrollView: UIScrollView) {
var count = 0
let width = self.view.frame.width
let scrollSpeed : CGFloat = 1.0// change to 2 to slow down the scrolling
for page in scroll.pages{
//Creates the same offset for each page so scrolling is consistent
let offset = (scroll.contentOffset.x - (CGFloat(count) * width)) / scrollSpeed
print (offset)
page.moveContent(offset)
count += 1
}
//Keep the skip, left, and right buttons on screen
scroll.moveElements(scroll.contentOffset.x)
}
}
| mit | 0c4a1c3d06cb32be83bc3120e1f870b0 | 30.222222 | 92 | 0.621759 | 4.979747 | false | false | false | false |
yaobanglin/viossvc | viossvc/Scenes/Chat/ChatInteractionViewController.swift | 1 | 12422 | //
// ChatInteractionViewController.swift
// viossvc
//
// Created by abx’s mac on 2016/12/1.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
import XCGLogger
private let sectionHeaderHeight : CGFloat = 50.0
class ChatInteractionViewController: BaseCustomListTableViewController,InputBarViewProcotol,ChatSessionProtocol, SendLocationMessageDelegate{
let showTime = 300
@IBOutlet weak var inputBar: InputBarView!
@IBOutlet weak var inputBarHeight: NSLayoutConstraint!
@IBOutlet weak var inputBarBottom: NSLayoutConstraint!
var chatUid:Int = 0
var chatName = ""
override func viewDidLoad() {
super.viewDidLoad()
MobClick.event(AppConst.Event.order_chat)
inputBar.registeredDelegate(self)
self.title = chatName
ChatSessionHelper.shared.openChatSession(self)
updateUserInfo()
didRequest()
settingTableView()
}
func settingTableView() {
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
tableView.registerClass(ChatLocationMeCell.self)
tableView.registerClass(ChatLocationAnotherCell.self)
tableView.registerClass(ChatSectionView.classForCoder(), forHeaderFooterViewReuseIdentifier: "ChatSectionView")
tableView.tableHeaderView = UIView(frame:CGRectMake(0,0,0,0.5))
}
override func autoRefreshLoad() -> Bool {
return false
}
private func updateUserInfo() {
if chatUid != 0 {
AppAPIHelper.userAPI().getUserInfo(chatUid, complete: { [weak self](model) in
let userInfo = model as? UserInfoModel
if userInfo != nil {
self?.title = userInfo!.nickname
ChatSessionHelper.shared.didReqeustUserInfoComplete(userInfo!)
}
}, error:nil)
}
}
func receiveMsg(chatMsgModel: ChatMsgModel) {
guard chatMsgModel.from_uid == chatUid || chatMsgModel.from_uid == CurrentUserHelper.shared.userInfo.uid else {return}
dataSource?.append(chatMsgModel)
tableView.reloadData()
tableViewScrolToBottom()
}
func sessionUid() -> Int {
return chatUid
}
override func didRequest() {
let pageSize = 20
let offset = dataSource == nil ? 0 : dataSource!.count
var array = ChatMsgHepler.shared.findHistoryMsg(chatUid, offset: offset , pageSize: pageSize) as [AnyObject]
if array.count < pageSize {
removeRefreshControl()
}
if dataSource != nil {
array.appendContentsOf(dataSource!)
}
didRequestComplete(array)
if offset == 0 {
// _tableViewScrolToBottom(false)
self.performSelector(#selector(self.tableViewScrolToBottom), withObject: nil, afterDelay: 0.1)
}
}
override func isCalculateCellHeight() -> Bool {
return true
}
override func tableView(tableView: UITableView, cellDataForRowAtIndexPath indexPath: NSIndexPath) -> AnyObject? {
var datas:[AnyObject]? = dataSource;
return (datas != nil && datas!.count > indexPath.section ) ? datas![indexPath.section] : nil;
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return dataSource == nil ? 0 : dataSource!.count
}
override func tableView(tableView: UITableView, cellIdentifierForRowAtIndexPath indexPath: NSIndexPath) -> String? {
let model = self.tableView(tableView, cellDataForRowAtIndexPath: indexPath) as! ChatMsgModel
if model.msg_type == ChatMsgType.Text.rawValue {
return model.from_uid == CurrentUserHelper.shared.uid ? "ChatWithISayCell" : "ChatWithAnotherSayCell"
} else if model.msg_type == ChatMsgType.Location.rawValue {
return model.from_uid == CurrentUserHelper.shared.uid ? "ChatLocationMeCell" : "ChatLocationAnotherCell"
}
return model.from_uid == CurrentUserHelper.shared.uid ? "ChatWithISayCell" : "ChatWithAnotherSayCell"
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return isTimeToShow(section) ? sectionHeaderHeight : 0.1
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.1
}
// func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// view.backgroundColor = UIColor.clearColor()
// }
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var headerView : ChatSectionView?
if isTimeToShow(section) {
let model = self.tableView(tableView, cellDataForRowAtIndexPath: NSIndexPath.init(forRow: 0, inSection: section)) as! ChatMsgModel
headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier("ChatSectionView") as? ChatSectionView
headerView?.update(model)
}
return headerView
}
func isTimeToShow(index : Int) -> Bool {
var isShow = false
if dataSource != nil {
if index == 0 {
isShow = true
}else {
let currentModel = dataSource![index] as! ChatMsgModel
let beforeModel = dataSource![index - 1] as! ChatMsgModel
isShow = currentModel.msg_time - beforeModel.msg_time >= showTime
}
}
return isShow
}
func inputBarDidKeyboardHide(inputBar inputBar: InputBarView, userInfo: [NSObject : AnyObject]?) {
let duration = userInfo![UIKeyboardAnimationDurationUserInfoKey]?.doubleValue
let rawValue = (userInfo![UIKeyboardAnimationCurveUserInfoKey]?.integerValue)! << 16
let curve = UIViewAnimationOptions.init(rawValue: UInt(rawValue))
UIView.animateWithDuration(duration!, delay: 0, options: curve, animations: {
[weak self]() in
self!.inputBarChangeHeight(-1)
}, completion: nil)
}
func inputBarDidKeyboardShow(inputBar inputBar: InputBarView, userInfo: [NSObject : AnyObject]?) {
let height = CGRectGetHeight(userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue())
if (height > 0) {
let heightTime = userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
UIView.animateWithDuration(heightTime, animations: {
[weak self]() in
self!.inputBarChangeHeight(height)
})
}
}
func sendLocation(poiModel: POIInfoModel?) {
let msgString = ChatMsgHepler.shared.modelToString(poiModel!)
ChatMsgHepler.shared.sendMsg(chatUid, msg: msgString, type: ChatMsgType.Location.rawValue)
}
func inputBarShowGetLocationPage() {
let getLocationVC = GetLocationInfoViewController()
getLocationVC.delegate = self
navigationController?.pushViewController(getLocationVC, animated: true)
}
func inputBarDidSendMessage(inputBar inputBar: InputBarView, message: String) {
if !message.isEmpty {
ChatMsgHepler.shared.sendMsg(chatUid, msg: message)
}
}
func inputBarDidChangeHeight(inputBar inputBar: InputBarView, height: CGFloat) {
inputBarHeight.constant = height;
self.view.layoutIfNeeded()
_tableViewScrolToBottom(true)
}
func inputBarChangeHeight(height : CGFloat) {
inputBarBottom.constant = height
self.view.layoutIfNeeded()
if height > 0 {
_tableViewScrolToBottom(false)
}
}
func tableViewScrolToBottom() {
if dataSource?.count > 0 {
tableView.scrollToRowAtIndexPath(NSIndexPath.init(forRow: 0, inSection: dataSource!.count - 1), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
}
}
func _tableViewScrolToBottom(animated : Bool? = true){
if dataSource?.count > 0 {
tableView.scrollToRowAtIndexPath(NSIndexPath.init(forRow: 0, inSection: dataSource!.count - 1), atScrollPosition: UITableViewScrollPosition.Top, animated: animated!)
}
}
func tableView(tableView: UITableView!, rowAtIndexPath indexPath: NSIndexPath!, didAction action: Int, data: AnyObject!) {
if UInt(action) == AppConst.Action.ShowLocation.rawValue {
let showDetailVC = ShowLocationDetailViewController()
let msgModel = dataSource![indexPath.section] as! ChatMsgModel
let poiModel = ChatMsgHepler.shared.stringToModel(msgModel.content)
showDetailVC.poiModel = poiModel
navigationController?.pushViewController(showDetailVC, animated: true)
}
}
deinit {
ChatSessionHelper.shared.closeChatSession()
}
}
class ChatSectionView: UITableViewHeaderFooterView,OEZUpdateProtocol {
// var label : UILabel = UILabel()
let layerLeft : CALayer = CALayer()
let layerRight : CALayer = CALayer()
let stringLabel = UILabel.init()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
let color = AppConst.Color.C3
layerLeft.backgroundColor = color.CGColor
layerRight.backgroundColor = color.CGColor
self.layer.addSublayer(layerLeft)
self.layer.addSublayer(layerRight)
stringLabel.textAlignment = .Center
stringLabel.font = UIFont.SIZE(11)
stringLabel.textColor = color
stringLabel.frame = CGRectMake(0, 0, UIScreen.width(), sectionHeaderHeight)
self.addSubview(stringLabel)
}
func update(data: AnyObject!) {
let model = data as! ChatMsgModel
let string = model.formatMsgTime() as NSString
stringLabel.text = string as String
let strWidth = string.sizeWithAttributes([NSFontAttributeName : UIFont.SIZE(11)]).width
let width = UIScreen.width() - 50 - strWidth
let layerWidth = width > 120 ? 60 : (width - 20) / 2.0
let startX = (UIScreen.width() - strWidth - 50 - 2 * layerWidth) / 2.0
layerLeft.frame = CGRectMake(startX, (sectionHeaderHeight - 0.5) / 2.0, layerWidth, 0.5)
layerRight.frame = CGRectMake(startX + layerWidth + strWidth + 50, (sectionHeaderHeight - 0.5) / 2.0, layerWidth, 0.5)
}
// init(frame: CGRect,model: ChatMsgModel) {
// super.init(reuseIdentifier: "ChatSectionView")
//
// let label = detailTextLabel!
//// self.addSubview(label)
// label.textAlignment = .Center
// label.font = UIFont.SIZE(11)
// label.textColor = AppConst.Color.C3
// let string = model.formatMsgTime() as NSString
//
// label.text = string as String
//
// let strWidth = string.sizeWithAttributes([NSFontAttributeName : UIFont.SIZE(11)]).width
// let width = UIScreen.width() - 50 - strWidth
// let layerWidth = width > 120 ? 60 : (width - 20) / 2.0
//
// let layer1 = CALayer()
// layer1.backgroundColor = AppConst.Color.C3.CGColor
//
// let startX = (UIScreen.width() - strWidth - 50 - 2 * layerWidth) / 2.0
// layer1.frame = CGRectMake(startX, (frame.height - 0.5) / 2.0, layerWidth, 0.5)
//
// let layer2 = CALayer()
// layer2.backgroundColor = AppConst.Color.C3.CGColor
//
// layer2.frame = CGRectMake(startX + layerWidth + strWidth + 50, (frame.height - 0.5) / 2.0, layerWidth, 0.5)
//
// self.layer.addSublayer(layer1)
// self.layer.addSublayer(layer2)
//
//
// }
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 57986c0d175221a808c670250f785af3 | 34.275568 | 177 | 0.624225 | 4.848497 | false | false | false | false |
ryan-boder/path-of-least-resistance | Test/PathFinderTest.swift | 1 | 3447 | import XCTest
@testable import PathOfLeastResistance
class PathFinderTest: XCTestCase {
var out: PathFinder!
override func setUp() {
super.setUp()
out = PathFinder()
}
func testWhenEmptyInputReturnNil() {
let (success, resistance, path) = out.find([])
XCTAssertFalse(success)
XCTAssertEqual(0, resistance)
XCTAssertEqual([], path)
}
func testWhenSingleRowSingleColumnInput() {
let (success, resistance, path) = out.find([[4]])
XCTAssertTrue(success)
XCTAssertEqual(4, resistance)
XCTAssertEqual([1], path)
}
func testWhenSingleRowSingleColumnInput2() {
let (success, resistance, path) = out.find([[8]])
XCTAssertTrue(success)
XCTAssertEqual(8, resistance)
XCTAssertEqual([1], path)
}
func testWhenSingleRowMultipleColumnInput() {
let (success, resistance, path) = out.find([[1,2,3,4]])
XCTAssertTrue(success)
XCTAssertEqual(10, resistance)
XCTAssertEqual([1,1,1,1], path)
}
func test2RowInput1() {
let (success, resistance, path) = out.find([[1,2],[3,4]])
XCTAssertTrue(success)
XCTAssertEqual(3, resistance)
XCTAssertEqual([1,1], path)
}
func test2RowInput2() {
let (success, resistance, path) = out.find([[3,4],[1,2]])
XCTAssertTrue(success)
XCTAssertEqual(3, resistance)
XCTAssertEqual([2,2], path)
}
func test2RowInput3() {
let (success, resistance, path) = out.find([[1,4],[3,2]])
XCTAssertTrue(success)
XCTAssertEqual(3, resistance)
XCTAssertEqual([1,2], path)
}
func test2RowInput4() {
let (success, resistance, path) = out.find([[1,2,1,2,1],[2,1,2,1,2]])
XCTAssertTrue(success)
XCTAssertEqual(5, resistance)
XCTAssertEqual([1,2,1,2,1], path)
}
func test3RowInput1() {
let (success, resistance, path) = out.find([[1,2,3,2,1],[2,1,2,1,2],[4,4,1,4,4]])
XCTAssertTrue(success)
XCTAssertEqual(5, resistance)
XCTAssertEqual([1,2,3,2,1], path)
}
func testResistanceTooHigh1() {
let (success, resistance, path) = out.find([[10,10,10,10,11]])
XCTAssertFalse(success)
XCTAssertEqual(40, resistance)
XCTAssertEqual([1,1,1,1], path)
}
func testGivenExample1() {
let (success, resistance, path) = out.find([
[3,4,1,2,8,6],
[6,1,8,2,7,4],
[5,9,3,9,9,5],
[8,4,1,3,2,6],
[3,7,2,8,6,4]
])
XCTAssertTrue(success)
XCTAssertEqual(16, resistance)
XCTAssertEqual([1,2,3,4,4,5], path)
}
func testGivenExample2() {
let (success, resistance, path) = out.find([
[3,4,1,2,8,6],
[6,1,8,2,7,4],
[5,9,3,9,9,5],
[8,4,1,3,2,6],
[3,7,2,1,2,3]
])
XCTAssertTrue(success)
XCTAssertEqual(11, resistance)
XCTAssertEqual([1,2,1,5,4,5], path)
}
func testGivenExample3() {
let (success, resistance, path) = out.find([
[19,10,19,10,19],
[21,23,20,19,12],
[20,12,20,11,10]
])
XCTAssertFalse(success)
XCTAssertEqual(48, resistance)
XCTAssertEqual([1,1,1], path)
}
}
| apache-2.0 | 385d82f4c262e4c60e8d8706ebda6f64 | 27.725 | 89 | 0.543371 | 3.510183 | false | true | false | false |
tardieu/swift | test/DebugInfo/typearg.swift | 10 | 1668 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
protocol AProtocol {
func f() -> String
}
class AClass : AProtocol {
func f() -> String { return "A" }
}
// CHECK: define hidden void @{{.*}}aFunction
// CHECK: call void @llvm.dbg.declare(metadata %swift.type** %{{.*}}, metadata ![[TYPEARG:.*]], metadata !{{[0-9]+}}),
// CHECK: ![[TYPEARG]] = !DILocalVariable(name: "$swift.type.T"
// CHECK-SAME: type: ![[SWIFTMETATYPE:[^,)]+]]
// CHECK-SAME: flags: DIFlagArtificial
// CHECK: ![[SWIFTMETATYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$swift.type",
// CHECK-SAME: baseType: ![[VOIDPTR:[0-9]+]]
// CHECK: ![[VOIDPTR]] = !DIDerivedType(tag: DW_TAG_pointer_type, name: "_TtBp", baseType: null
func aFunction<T : AProtocol>(_ x: T) {
print("I am in aFunction: \(x.f())")
}
aFunction(AClass())
// Verify that we also emit a swift.type for a generic self.
class Foo<Bar> {
func one() {
}
func two<Baz>(_ x: Baz) {
// TODO: leave breadcrumbs for how to dynamically derive T in the debugger
// CHECK- FIXME: !DILocalVariable(name: "$swift.type.Bar"
// CHECK: !DILocalVariable(name: "$swift.type.Baz"
}
}
// Verify that the backend doesn't elide the debug intrinsics.
// RUN: %target-swift-frontend %s -c -g -o %t.o
// RUN: %llvm-dwarfdump %t.o | %FileCheck %s --check-prefix=CHECK-LLVM
// CHECK-LLVM-DAG: .debug_str[{{.*}}] = "x"
// CHECK-LLVM-DAG: .debug_str[{{.*}}] = "$swift.type.T"
// CHECK- FIXME -LLVM-DAG: .debug_str[{{.*}}] = "$swift.type.Bar"
// CHECK-LLVM-DAG: .debug_str[{{.*}}] = "$swift.type.Baz"
| apache-2.0 | e42a1ab96b2577b844963711b1de148d | 38.714286 | 119 | 0.582134 | 3.201536 | false | false | false | false |
wyp767363905/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBSpecialCell.swift | 1 | 4716 | //
// CBSpecialCell.swift
// TestKitchen
//
// Created by qianfeng on 16/8/19.
// Copyright © 2016年 1606. All rights reserved.
//
import UIKit
class CBSpecialCell: UITableViewCell {
//显示数据
var model: CBRecommendWidgetListModel?{
didSet {
showData()
}
}
func showData(){
//类型图片
if model?.widget_data?.count > 0 {
let imageModel = model?.widget_data![0]
if imageModel?.type == "image" {
//获取类型按钮
let subView = contentView.viewWithTag(100)
if subView?.isKindOfClass(UIButton.self) == true {
let sceneBtn = subView as! UIButton
let url = NSURL(string: (imageModel?.content)!)
let dImage = UIImage(named: "sdefaultImage")
sceneBtn.kf_setBackgroundImageWithURL(url, forState: .Normal, placeholderImage: dImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
//类型名字
if model?.widget_data?.count > 1 {
let nameModel = model?.widget_data![1]
if nameModel?.type == "text" {
//获取名字的lab
let subView = contentView.viewWithTag(101)
if subView?.isKindOfClass(UILabel.self) == true {
let nameLabel = subView as! UILabel
nameLabel.text = (nameModel?.content)!
}
}
}
//多少道菜
if model?.widget_data?.count > 2 {
let numModel = model?.widget_data![2]
if numModel?.type == "text" {
//获取label
let subView = contentView.viewWithTag(102)
if subView?.isKindOfClass(UILabel.self) == true {
let numLabel = subView as! UILabel
numLabel.text = (numModel?.content)!
}
}
}
//列举菜例的图片显示
for i in 0..<4 {
//图片数据在数组中的序号
let index = i*2+3
if model?.widget_data?.count > index {
let imageModel = model?.widget_data![index]
if imageModel?.type == "image" {
//获取按钮视图
let subView = contentView.viewWithTag(200+i)
if subView?.isKindOfClass(UIButton.self) == true {
let btn = subView as! UIButton
let url = NSURL(string: (imageModel?.content)!)
btn.kf_setBackgroundImageWithURL(url, forState: .Normal, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
}
//描述文字
let subView = contentView.viewWithTag(400)
if subView?.isKindOfClass(UILabel.self) == true {
let descLabel = subView as! UILabel
descLabel.text = (model?.desc)!
}
}
//进入类型的界面
@IBAction func clickSceneBtn(sender: UIButton) {
}
@IBAction func clickDetailBtn(sender: UIButton) {
}
@IBAction func clickPlayBtn(sender: UIButton) {
}
//创建cell的方法
class func createSpecialCellFor(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withListModel listModel: CBRecommendWidgetListModel) -> CBSpecialCell {
let cellId = "specialCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBSpecialCell
if nil == cell {
cell = NSBundle.mainBundle().loadNibNamed("CBSpecialCell", owner: nil, options: nil).last as? CBSpecialCell
}
cell?.model = listModel
return cell!
}
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
}
}
| mit | d6083ad63c2661b3e0caa8a1769450f0 | 28.681818 | 193 | 0.476263 | 5.507229 | false | false | false | false |
mrandi/laives | laives/AppDelegate.swift | 1 | 1780 | //
// AppDelegate.swift
// laives
//
// Created by Michele Randi on 03/05/16.
// Copyright © 2016 Michele Randi. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
var pasteBoard = NSPasteboard.generalPasteboard()
@IBOutlet weak var laivesCB: NSMenu!
func applicationDidFinishLaunching(aNotification: NSNotification) {
pasteBoard.clearContents()
let icon = NSImage(named: "statusIcon")
icon?.template = true
statusItem.image = icon
statusItem.toolTip = "Laives Clipboard Manager"
pasteBoard.writeObjects(["wowow","test"])
var i = 0
while i <= pasteBoard.pasteboardItems!.count-1 {
print(pasteBoard.pasteboardItems![i].stringForType("public.utf8-plain-text")!)
let nsmi = NSMenuItem()
nsmi.title = pasteBoard.pasteboardItems![i].stringForType("public.utf8-plain-text")!
nsmi.action = #selector(AppDelegate.paste(_:))
laivesCB.addItem(nsmi)
i = i + 1
}
let q = NSMenuItem()
q.title = "Quit"
q.action = #selector(AppDelegate.quit(_:))
laivesCB.addItem(q)
statusItem.menu = laivesCB
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
@IBAction func paste(sender: NSMenuItem) {
print("paste me")
}
@IBAction func quit(sender: AnyObject?) {
NSApplication.sharedApplication().terminate(self)
}
}
| mit | ad13cfbbff40476c00e743c5b4e672a8 | 25.552239 | 96 | 0.598089 | 4.847411 | false | false | false | false |
rene-dohan/CS-IOS | Renetik/Renetik/Classes/Core/Extensions/UIKit/UIDevice+CSExtension.swift | 1 | 1886 | public enum DisplayType {
case unknown
case iphone4
case iphone5
case iphone6
case iphone6plus
case iPadNonRetina
case iPad
case iPadProBig
static let iphone7 = iphone6
static let iphone7plus = iphone6plus
}
public extension UIDevice {
public class func set(orientation: UIDeviceOrientation) {
UIDevice.current.setValue(orientation.rawValue, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()
UIDevice.current.setValue(UIDeviceOrientation.unknown.rawValue, forKey: "orientation")
}
public class var isPhone: Bool { UIDevice.current.userInterfaceIdiom == .phone }
public class var isTablet: Bool { UIDevice.current.userInterfaceIdiom == .pad }
public class var isCarPlay: Bool { UIDevice.current.userInterfaceIdiom == .carPlay }
public class var isTV: Bool { UIDevice.current.userInterfaceIdiom == .tv }
@nonobjc class var typeIsLike: DisplayType {
if isPhone && UIScreen.maxLength < 568 {
return .iphone4
}
else if isPhone && UIScreen.maxLength == 568 {
return .iphone5
}
else if isPhone && UIScreen.maxLength == 667 {
return .iphone6
}
else if isPhone && UIScreen.maxLength == 736 {
return .iphone6plus
}
else if isTablet && !UIScreen.isRetina {
return .iPadNonRetina
}
else if isTablet && UIScreen.isRetina && UIScreen.maxLength == 1024 {
return .iPad
}
else if isTablet && UIScreen.maxLength == 1366 {
return .iPadProBig
}
return .unknown
}
public class var systemVersionInt: Int { Int(UIDevice.current.systemVersion)! }
public class var isIOS10: Bool { systemVersionInt >= 10 }
public class var isIOS11: Bool { systemVersionInt >= 11 }
}
| mit | cecdf04566750a62badbd0e3267d6685 | 32.678571 | 94 | 0.646872 | 4.811224 | false | false | false | false |
gregomni/swift | test/AutoDiff/SILOptimizer/semantic_member_accessors_sil.swift | 10 | 5765 | // RUN: %target-swift-frontend -emit-sil -Xllvm -sil-print-after=differentiation %s -module-name null -o /dev/null 2>&1 | %FileCheck %s
// Test differentiation of semantic member accessors:
// - Stored property accessors.
// - Property wrapper wrapped value accessors.
// TODO(TF-1254): Support forward-mode differentiation and test generated differentials.
import _Differentiation
@propertyWrapper
struct Wrapper<Value> {
var wrappedValue: Value
}
struct Struct: Differentiable {
@Wrapper @Wrapper var x: Float = 10
var y: Float = 10
}
struct Generic<T> {
@Wrapper @Wrapper var x: T
var y: T
}
extension Generic: Differentiable where T: Differentiable {}
func trigger<T: Differentiable>(_ x: T.Type) {
let _: @differentiable(reverse) (Struct) -> Float = { $0.x }
let _: @differentiable(reverse) (inout Struct, Float) -> Void = { $0.x = $1 }
let _: @differentiable(reverse) (Generic<T>) -> T = { $0.x }
let _: @differentiable(reverse) (inout Generic<T>, T) -> Void = { $0.x = $1 }
}
// CHECK-LABEL: // differentiability witness for Generic.x.setter
// CHECK-NEXT: sil_differentiability_witness private [reverse] [parameters 0 1] [results 0] <τ_0_0 where τ_0_0 : Differentiable> @$s4null7GenericV1xxvs : $@convention(method) <T> (@in T, @inout Generic<T>) -> () {
// CHECK-LABEL: // differentiability witness for Generic.x.getter
// CHECK-NEXT: sil_differentiability_witness private [reverse] [parameters 0] [results 0] <τ_0_0 where τ_0_0 : Differentiable> @$s4null7GenericV1xxvg : $@convention(method) <T> (@in_guaranteed Generic<T>) -> @out T {
// CHECK-LABEL: // differentiability witness for Struct.x.setter
// CHECK-NEXT: sil_differentiability_witness private [reverse] [parameters 0 1] [results 0] @$s4null6StructV1xSfvs : $@convention(method) (Float, @inout Struct) -> () {
// CHECK-LABEL: // differentiability witness for Struct.x.getter
// CHECK-NEXT: sil_differentiability_witness private [reverse] [parameters 0] [results 0] @$s4null6StructV1xSfvg : $@convention(method) (Struct) -> Float {
// CHECK-LABEL: sil private [ossa] @$s4null7GenericV1xxvs16_Differentiation14DifferentiableRzlTJpSSpSr
// CHECK: bb0([[ADJ_X_RESULT:%.*]] : $*τ_0_0.TangentVector, [[ADJ_SELF:%.*]] : $*Generic<τ_0_0>.TangentVector, {{.*}} : {{.*}}):
// CHECK: [[ADJ_X_TMP:%.*]] = alloc_stack $τ_0_0.TangentVector
// CHECK: [[ZERO_FN:%.*]] = witness_method $τ_0_0.TangentVector, #AdditiveArithmetic.zero!getter
// CHECK: apply [[ZERO_FN]]<τ_0_0.TangentVector>([[ADJ_X_TMP]], {{.*}})
// CHECK: [[ADJ_X:%.*]] = struct_element_addr [[ADJ_SELF]] : $*Generic<τ_0_0>.TangentVector, #Generic.TangentVector.x
// CHECK: [[ZERO_FN:%.*]] = witness_method $τ_0_0.TangentVector, #AdditiveArithmetic."+="
// CHECK: apply [[ZERO_FN]]<τ_0_0.TangentVector>([[ADJ_X_TMP]], [[ADJ_X]], {{.*}})
// CHECK: destroy_addr [[ADJ_X]] : $*τ_0_0.TangentVector
// CHECK: [[ZERO_FN:%.*]] = witness_method $τ_0_0.TangentVector, #AdditiveArithmetic.zero!getter
// CHECK: apply [[ZERO_FN]]<τ_0_0.TangentVector>([[ADJ_X]], {{.*}})
// CHECK: copy_addr [take] [[ADJ_X_TMP]] to [initialization] [[ADJ_X_RESULT]] : $*τ_0_0.TangentVector
// CHECK: dealloc_stack [[ADJ_X_TMP]] : $*τ_0_0.TangentVector
// CHECK: return {{.*}} : $()
// CHECK: }
// CHECK-LABEL: sil private [ossa] @$s4null7GenericV1xxvg16_Differentiation14DifferentiableRzlTJpSpSr
// CHECK: bb0([[ADJ_SELF_RESULT:%.*]] : $*Generic<τ_0_0>.TangentVector, [[SEED:%.*]] : $*τ_0_0.TangentVector, {{.*}} : ${{.*}}):
// CHECK: [[ADJ_SELF_TMP:%.*]] = alloc_stack $Generic<τ_0_0>.TangentVector
// CHECK: [[SEED_COPY:%.*]] = alloc_stack $τ_0_0.TangentVector
// CHECK: copy_addr [[SEED]] to [initialization] [[SEED_COPY]] : $*τ_0_0.TangentVector
// CHECK: [[ADJ_X:%.*]] = struct_element_addr [[ADJ_SELF_TMP]] : $*Generic<τ_0_0>.TangentVector, #Generic.TangentVector.x
// CHECK: copy_addr [take] [[SEED_COPY]] to [initialization] [[ADJ_X]] : $*τ_0_0.TangentVector
// CHECK: [[ADJ_Y:%.*]] = struct_element_addr [[ADJ_SELF_TMP]] : $*Generic<τ_0_0>.TangentVector, #Generic.TangentVector.y
// CHECK: [[ZERO_FN:%.*]] = witness_method $τ_0_0.TangentVector, #AdditiveArithmetic.zero!getter
// CHECK: apply [[ZERO_FN]]<τ_0_0.TangentVector>([[ADJ_Y]], {{.*}})
// CHECK: copy_addr [take] [[ADJ_SELF_TMP]] to [initialization] [[ADJ_SELF_RESULT]] : $*Generic<τ_0_0>.TangentVector
// CHECK: dealloc_stack [[SEED_COPY]] : $*τ_0_0.TangentVector
// CHECK: dealloc_stack [[ADJ_SELF_TMP]] : $*Generic<τ_0_0>.TangentVector
// CHECK: return {{.*}} : $()
// CHECK: }
// CHECK-LABEL: sil private [ossa] @$s4null6StructV1xSfvsTJpSSpSr
// CHECK: bb0([[ADJ_SELF:%.*]] : $*Struct.TangentVector, {{.*}} : $_AD__$s4null6StructV1xSfvs_bb0__PB__src_0_wrt_0_1):
// CHECK: [[ADJ_X_ADDR:%.*]] = struct_element_addr [[ADJ_SELF]] : $*Struct.TangentVector, #Struct.TangentVector.x
// CHECK: [[ADJ_X:%.*]] = load [trivial] [[ADJ_X_ADDR]] : $*Float
// CHECK: [[ZERO_FN:%.*]] = witness_method $Float, #AdditiveArithmetic.zero!getter
// CHECK: apply [[ZERO_FN]]<Float>([[ADJ_X_ADDR]], {{.*}})
// CHECK: return [[ADJ_X]] : $Float
// CHECK: }
// CHECK-LABEL: sil private [ossa] @$s4null6StructV1xSfvgTJpSpSr
// CHECK: bb0([[ADJ_X:%.*]] : $Float, {{.*}} : $_AD__$s4null6StructV1xSfvg_bb0__PB__src_0_wrt_0):
// CHECK: [[ADJ_Y_ADDR:%.*]] = alloc_stack $Float
// CHECK: [[ZERO_FN:%.*]] = witness_method $Float, #AdditiveArithmetic.zero!getter
// CHECK: apply [[ZERO_FN]]<Float>([[ADJ_Y_ADDR]], {{.*}})
// CHECK: [[ADJ_Y:%.*]] = load [trivial] [[ADJ_Y_ADDR]] : $*Float
// CHECK: dealloc_stack [[ADJ_Y_ADDR]] : $*Float
// CHECK: [[ADJ_SELF:%.*]] = struct $Struct.TangentVector ([[ADJ_X]] : $Float, [[ADJ_Y]] : $Float)
// CHECK: return [[ADJ_SELF]] : $Struct.TangentVector
// CHECK: }
| apache-2.0 | 0c7bc95fa85ebd49b76971a1529e5881 | 58.123711 | 216 | 0.644638 | 3.113464 | false | false | false | false |
mitsuyoshi-yamazaki/SwarmChemistry | SwarmChemistry/Recipe.swift | 1 | 4666 | //
// Recipe.swift
// SwarmChemistry
//
// Created by mitsuyoshi.yamazaki on 2017/08/10.
// Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved.
//
import Foundation
// MARK: - Recipe
public struct Recipe {
public let name: String
public let genomes: [GenomeInfo]
}
public extension Recipe {
/**
Expecting:
Recipe Name
41 * (249.84, 4.85, 28.73, 0.34, 0.45, 14.44, 0.09, 0.82)
26 * (277.87, 15.02, 35.48, 0.68, 0.05, 82.96, 0.46, 0.9)
...
*/
init?(_ recipeText: String, name: String? = nil) {
func isGenome(_ line: String) -> Bool {
if let (genomeText, _) = Recipe.parseLine(line) {
if Recipe.parseGenome(from: genomeText) != nil {
return true
}
}
return false
}
let lineSeparator = "\n"
let components = recipeText.components(separatedBy: lineSeparator)
guard let firstLine = components.first else {
return nil
}
if isGenome(firstLine) {
self.init(recipeText, givenName: name ?? "Untitled")
} else {
let genomeText = components.dropFirst().joined(separator: lineSeparator)
self.init(genomeText, givenName: firstLine)
}
}
private init?(_ recipeText: String, givenName: String) {
guard recipeText.isEmpty == false else {
return nil
}
let result = recipeText
.trimmingCharacters(in: .whitespacesAndNewlines)
.components(separatedBy: "\n")
.map { line -> (genomeText: String, count: Int)? in
Recipe.parseLine(line)
}
.map { value -> GenomeInfo? in
guard let value = value else {
return nil
}
guard let genome = Recipe.parseGenome(from: value.genomeText) else {
return nil
}
return GenomeInfo(count: value.count, area: nil, genome: genome)
}
guard let genome = result as? [GenomeInfo] else {
return nil
}
self.init(name: givenName, genomes: genome)
}
private static func parseLine(_ text: String) -> (genomeText: String, count: Int)? {
let components = text
.replacingOccurrences(of: " ", with: "")
.components(separatedBy: "*")
guard
let count = Int(components.first ?? ""),
let genomeText = components.dropFirst().first
else {
return nil
}
return (genomeText: genomeText, count: count)
}
private static func parseGenome(from text: String) -> Parameters? {
let components = text
.replacingOccurrences(of: " ", with: "") // Can't just use CharacterSet?
.replacingOccurrences(of: "(", with: "")
.replacingOccurrences(of: ")", with: "")
.components(separatedBy: ",")
guard let values = components.map({ Value($0) }) as? [Value] else {
Log.debug("Parse genome parameters failed: \"\(text)\"")
return nil
}
return Parameters(values)
}
}
// MARK: - Accessor
public extension Recipe {
static func none() -> Recipe {
return self.init(name: "None", genomes: [])
}
static func random(numberOfGenomes: Int) -> Recipe {
let genomes = (0..<numberOfGenomes)
.map { _ in GenomeInfo(count: 10, area: nil, genome: Parameters.random) }
let random = self.init(name: "Random", genomes: genomes)
Log.debug(random.description)
return random
}
static func random(numberOfGenomes: Int, fieldSize: Vector2.Rect) -> Recipe {
let genomes = (0..<numberOfGenomes)
.map { _ in GenomeInfo.random(in: fieldSize) }
let random = self.init(name: "Random", genomes: genomes)
Log.debug(random.description)
return random
}
}
// MARK: - Operator override
public extension Recipe {
static func + (recipe: Recipe, genome: GenomeInfo) -> Recipe {
let name = "Expanded \(recipe.name)"
let genomes = recipe.genomes + [genome]
return Recipe(name: name, genomes: genomes)
}
}
// MARK: - CustomStringConvertible
extension Recipe: CustomStringConvertible {
public var description: String { // TODO: Needs test
let hasInitialArea = genomes.allSatisfy { $0.area != nil }
let genomesText = genomes
.map { (hasInitialArea ? "\($0.area?.description ?? "")\n" : "") + "\($0.count) * \($0.genome)" }
.joined(separator: "\n")
return "\(name)\n\(genomesText)"
}
}
// MARK: - GenomeInfo
public extension Recipe {
struct GenomeInfo {
let count: Int
let area: Vector2.Rect?
let genome: Parameters
}
}
public extension Recipe.GenomeInfo {
static func random(`in` fieldSize: Vector2.Rect) -> Recipe.GenomeInfo {
let count = Int.random(in: 0..<999)
let area: Vector2.Rect = fieldSize.random()
return Recipe.GenomeInfo(count: count, area: area, genome: .random)
}
}
| mit | a7b133f579cb776b28e8783207c1839f | 26.122093 | 103 | 0.626367 | 3.655956 | false | false | false | false |
nohana/NohanaImagePicker | NohanaImagePicker/PhotoAuthorizationLimitedCell.swift | 1 | 3975 | /*
* Copyright (C) 2022 nohana, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
protocol PhotoAuthorizationLimitedCellDeletate {
func didSelectAddPhotoButton(_ cell: PhotoAuthorizationLimitedCell)
func didSelectAuthorizeAllPhotoButton(_ cell: PhotoAuthorizationLimitedCell)
}
class PhotoAuthorizationLimitedCell: UICollectionViewCell {
static var defaultReusableId: String {
String(describing: self)
}
var delegate: PhotoAuthorizationLimitedCellDeletate?
@IBOutlet weak private var containerView: UIStackView!
@IBOutlet weak private var attentionLabel: UILabel!
@IBOutlet weak private var addPhotoButton: UIButton! {
didSet {
self.addPhotoButton.layer.cornerRadius = 6
self.addPhotoButton.layer.borderColor = UIColor(red: 187/255, green: 187/255, blue: 187/255, alpha: 1).cgColor
self.addPhotoButton.layer.borderWidth = 1
}
}
@IBOutlet weak private var authorizeAllPhotoButton: UIButton! {
didSet {
self.authorizeAllPhotoButton.layer.cornerRadius = 6
self.authorizeAllPhotoButton.layer.borderColor = UIColor(red: 187/255, green: 187/255, blue: 187/255, alpha: 1).cgColor
self.authorizeAllPhotoButton.layer.borderWidth = 1
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
@IBAction func tappedAddPhotoButton(_ sender: UIButton) {
delegate?.didSelectAddPhotoButton(self)
}
@IBAction func tappedAuthorizeAllPhotoButton(_ sender: UIButton) {
delegate?.didSelectAuthorizeAllPhotoButton(self)
}
func update(_ isHidden: Bool, nohanaImagePickerController: NohanaImagePickerController) {
containerView.isHidden = isHidden
attentionLabel.text = NSLocalizedString(
"albumlist.menu.description",
tableName: "NohanaImagePicker",
bundle: nohanaImagePickerController.assetBundle,
comment: ""
)
addPhotoButton.setTitle(
NSLocalizedString(
"albumlist.menu.addPhoto.title",
tableName: "NohanaImagePicker",
bundle: nohanaImagePickerController.assetBundle,
comment: ""
),
for: .normal
)
authorizeAllPhotoButton.setTitle(
NSLocalizedString(
"albumlist.menu.authorizeAllPhoto.title",
tableName: "NohanaImagePicker",
bundle: nohanaImagePickerController.assetBundle,
comment: ""
),
for: .normal
)
}
func isHiddenCell(_ isHidden: Bool) {
containerView.isHidden = isHidden
}
static func cellSize(_ nohanaImagePickerController: NohanaImagePickerController) -> CGSize {
let descriptionLabel = UILabel()
descriptionLabel.numberOfLines = 0
descriptionLabel.font = .systemFont(ofSize: 13.5)
descriptionLabel.text = NSLocalizedString("albumlist.menu.description", tableName: "NohanaImagePicker", bundle: nohanaImagePickerController.assetBundle, comment: "")
let maxSize: CGSize = .init(width: UIScreen.main.bounds.width - 28, height: .infinity)
let height: CGFloat = descriptionLabel.sizeThatFits(maxSize).height + 44 * 2 + 10 + 16 * 3
return .init(width: UIScreen.main.bounds.width, height: height)
}
}
| apache-2.0 | 17d6d9efbef0b3ec0c873bea60f705f2 | 36.5 | 173 | 0.671195 | 4.794934 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Utility/Kanvas/KanvasCameraCustomUI.swift | 1 | 9834 | import Foundation
import Kanvas
/// Contains custom colors and fonts for the KanvasCamera framework
public class KanvasCustomUI {
public static let shared = KanvasCustomUI()
private static let brightBlue = UIColor.muriel(color: MurielColor(name: .blue)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightPurple = UIColor.muriel(color: MurielColor(name: .purple)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightPink = UIColor.muriel(color: MurielColor(name: .pink)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightYellow = UIColor.muriel(color: MurielColor(name: .yellow)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightGreen = UIColor.muriel(color: MurielColor(name: .green)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightRed = UIColor.muriel(color: MurielColor(name: .red)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightOrange = UIColor.muriel(color: MurielColor(name: .orange)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let white = UIColor.white
static private var firstPrimary: UIColor {
return KanvasCustomUI.primaryColors.first ?? UIColor.blue
}
static private var lastPrimary: UIColor {
return KanvasCustomUI.primaryColors.last ?? UIColor.green
}
private let pickerColors: [UIColor] = [KanvasCustomUI.firstPrimary] + KanvasCustomUI.primaryColors + [KanvasCustomUI.lastPrimary]
private let segmentColors: [UIColor] = KanvasCustomUI.primaryColors + KanvasCustomUI.primaryColors + [KanvasCustomUI.firstPrimary]
static private let primaryColors: [UIColor] = [.blue,
.purple,
.magenta,
.red,
.yellow,
.green]
private let backgroundColorCollection: [UIColor] = KanvasCustomUI.primaryColors
private let mangaColor: UIColor = brightPink
private let toonColor: UIColor = brightOrange
private let selectedColor = brightBlue // ColorPickerController:29
private let black25 = UIColor(white: 0, alpha: 0.25)
func cameraColors() -> KanvasColors {
let firstPrimary = KanvasCustomUI.primaryColors.first ?? .blue
return KanvasColors(
drawingDefaultColor: firstPrimary,
colorPickerColors: pickerColors,
selectedPickerColor: selectedColor,
timeSegmentColors: segmentColors,
backgroundColors: backgroundColorCollection,
strokeColor: firstPrimary,
sliderActiveColor: firstPrimary,
sliderOuterCircleColor: firstPrimary,
trimBackgroundColor: firstPrimary,
trashColor: Self.brightRed,
tooltipBackgroundColor: .systemRed,
closeButtonColor: black25,
cameraConfirmationColor: firstPrimary,
primaryButtonBackgroundColor: Self.brightRed,
permissionsButtonColor: Self.brightBlue,
permissionsButtonAcceptedBackgroundColor: UIColor.muriel(color: MurielColor(name: .green, shade: .shade20)),
overlayColor: UIColor.muriel(color: MurielColor.gray),
filterColors: [
.manga: mangaColor,
.toon: toonColor,
])
}
private static let cameraPermissions = KanvasFonts.CameraPermissions(titleFont: UIFont.systemFont(ofSize: 26, weight: .medium), descriptionFont: UIFont.systemFont(ofSize: 16), buttonFont: UIFont.systemFont(ofSize: 16, weight: .medium))
private static let drawer = KanvasFonts.Drawer(textSelectedFont: UIFont.systemFont(ofSize: 14, weight: .medium), textUnselectedFont: UIFont.systemFont(ofSize: 14))
func cameraFonts() -> KanvasFonts {
let paddingAdjustment: (UIFont) -> KanvasFonts.Padding? = { font in
if font == UIFont.systemFont(ofSize: font.pointSize) {
return KanvasFonts.Padding(topMargin: 8.0,
leftMargin: 5.7,
extraVerticalPadding: 0.125 * font.pointSize,
extraHorizontalPadding: 0)
}
else {
return nil
}
}
let editorFonts: [UIFont] = [.libreBaskerville(fontSize: 20), .nunitoBold(fontSize: 24), .pacifico(fontSize: 24), .shrikhand(fontSize: 22), .spaceMonoBold(fontSize: 20), .oswaldUpper(fontSize: 22)]
return KanvasFonts(permissions: Self.cameraPermissions,
drawer: Self.drawer,
editorFonts: editorFonts,
optionSelectorCellFont: UIFont.systemFont(ofSize: 16, weight: .medium),
mediaClipsFont: UIFont.systemFont(ofSize: 9.5),
mediaClipsSmallFont: UIFont.systemFont(ofSize: 8),
modeButtonFont: UIFont.systemFont(ofSize: 18.5),
speedLabelFont: UIFont.systemFont(ofSize: 16, weight: .medium),
timeIndicatorFont: UIFont.systemFont(ofSize: 16, weight: .medium),
colorSelectorTooltipFont:
UIFont.systemFont(ofSize: 14),
modeSelectorTooltipFont: UIFont.systemFont(ofSize: 15),
postLabelFont: UIFont.systemFont(ofSize: 14, weight: .medium),
gifMakerRevertButtonFont: UIFont.systemFont(ofSize: 15, weight: .bold),
paddingAdjustment: paddingAdjustment
)
}
func cameraImages() -> KanvasImages {
return KanvasImages(confirmImage: UIImage(named: "stories-confirm-button"), editorConfirmImage: UIImage(named: "stories-confirm-button"), nextImage: UIImage(named: "stories-next-button"))
}
}
enum CustomKanvasFonts: CaseIterable {
case libreBaskerville
case nunitoBold
case pacifico
case oswaldUpper
case shrikhand
case spaceMonoBold
struct Shadow {
let radius: CGFloat
let offset: CGPoint
let color: UIColor
}
var name: String {
switch self {
case .libreBaskerville:
return "LibreBaskerville-Regular"
case .nunitoBold:
return "Nunito-Bold"
case .pacifico:
return "Pacifico-Regular"
case .oswaldUpper:
return "Oswald-Regular"
case .shrikhand:
return "Shrikhand-Regular"
case .spaceMonoBold:
return "SpaceMono-Bold"
}
}
var size: Int {
switch self {
case .libreBaskerville:
return 20
case .nunitoBold:
return 24
case .pacifico:
return 24
case .oswaldUpper:
return 22
case .shrikhand:
return 22
case .spaceMonoBold:
return 20
}
}
var shadow: Shadow? {
switch self {
case .libreBaskerville:
return nil
case .nunitoBold:
return Shadow(radius: 1, offset: CGPoint(x: 0, y: 2), color: UIColor.black.withAlphaComponent(75))
case .pacifico:
return Shadow(radius: 5, offset: .zero, color: UIColor.white.withAlphaComponent(50))
case .oswaldUpper:
return nil
case .shrikhand:
return Shadow(radius: 1, offset: CGPoint(x: 1, y: 2), color: UIColor.black.withAlphaComponent(75))
case .spaceMonoBold:
return nil
}
}
}
extension UIFont {
static func libreBaskerville(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "LibreBaskerville-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
static func nunitoBold(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "Nunito-Bold", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
static func pacifico(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "Pacifico-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
static func oswaldUpper(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "Oswald-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
static func shrikhand(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "Shrikhand-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
static func spaceMonoBold(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "SpaceMono-Bold", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
@objc func fontByAddingSymbolicTrait(_ trait: UIFontDescriptor.SymbolicTraits) -> UIFont {
let modifiedTraits = fontDescriptor.symbolicTraits.union(trait)
guard let modifiedDescriptor = fontDescriptor.withSymbolicTraits(modifiedTraits) else {
assertionFailure("Unable to created modified font descriptor by adding a symbolic trait.")
return self
}
return UIFont(descriptor: modifiedDescriptor, size: pointSize)
}
}
| gpl-2.0 | 3eaba9129d81303c8819b5050984c521 | 44.527778 | 239 | 0.630364 | 4.696275 | false | false | false | false |
adrfer/swift | test/1_stdlib/ErrorHandling.swift | 2 | 8076 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
//
// Tests for error handling in standard library APIs.
//
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
var NoisyCount = 0
class Noisy {
init() { NoisyCount += 1 }
deinit { NoisyCount -= 1 }
}
enum SillyError: ErrorType { case JazzHands }
var ErrorHandlingTests = TestSuite("ErrorHandling")
ErrorHandlingTests.test("ErrorHandling/withUnsafeMutableBufferPointer restores array on throw") {
var x = [1, 2, 3]
do {
// Check that the array buffer is restored when an error is thrown
// inside withUnsafeMutableBufferPointer
try x.withUnsafeMutableBufferPointer { p in
p[0] = 4
p[1] = 5
p[2] = 6
// FIXME: Seems to have recently regressed
// Buffer should be swapped out of the original array.
// expectEqual(x, [])
throw SillyError.JazzHands
}
expectUnreachable()
} catch {}
// Mutated buffer should be restored to the array.
expectEqual(x, [4, 5, 6])
}
ErrorHandlingTests.test("ErrorHandling/withUnsafeBufferPointer extends lifetime") {
let initialCount = NoisyCount
do {
let x = [Noisy(), Noisy(), Noisy()]
let countBeforeWithUBP = NoisyCount
do {
// Don't use x anywhere in this test after this point.
try x.withUnsafeBufferPointer { p in
expectEqual(NoisyCount, countBeforeWithUBP)
throw SillyError.JazzHands
}
expectUnreachable()
} catch {}
}
expectEqual(NoisyCount, initialCount)
}
ErrorHandlingTests.test("ErrorHandling/Optional.map and .flatMap") {
var x: Int? = 222
do {
let y: String? = try x.map {(n: Int) -> String in
throw SillyError.JazzHands
return "\(n)"
}
expectUnreachable()
} catch {}
do {
let y: String? = try x.flatMap {(n: Int) -> String? in
throw SillyError.JazzHands
return .Some("\(n)")
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/withCString extends lifetime") {
do {
let x = "ad astra per aspera"
do {
// Don't use x anywhere in this test after this point.
try x.withCString { p in
expectEqual(p[0], Int8(("a" as UnicodeScalar).value))
expectEqual(p[1], Int8(("d" as UnicodeScalar).value))
throw SillyError.JazzHands
}
expectUnreachable()
} catch {}
}
// TODO: Some way to check string was deallocated?
}
ErrorHandlingTests.test("ErrorHandling/indexOf") {
do {
let _: Int? = try [1, 2, 3].indexOf {
throw SillyError.JazzHands
return $0 == $0
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/split") {
do {
let _: [String.CharacterView] = try "foo".characters.split { _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
do {
let _: [AnySequence<Character>]
= try AnySequence("foo".characters).split { _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/forEach") {
var loopCount = 0
do {
try [1, 2, 3].forEach {
loopCount += 1
if $0 == 2 {
throw SillyError.JazzHands
}
}
expectUnreachable()
} catch {}
expectEqual(loopCount, 2)
}
ErrorHandlingTests.test("ErrorHandling/Optional flatMap") {
var loopCount = 0
do {
let _: [Int] = try [1, 2, 3].flatMap {
loopCount += 1
if $0 == 2 {
throw SillyError.JazzHands
}
return .Some($0)
}
expectUnreachable()
} catch {}
expectEqual(loopCount, 2)
}
ErrorHandlingTests.test("ErrorHandling/Array flatMap") {
var loopCount = 0
do {
let _: [Int] = try [1, 2, 3].flatMap {(x) -> [Int] in
loopCount += 1
if x == 2 {
throw SillyError.JazzHands
}
return Array(count: x, repeatedValue: x)
}
expectUnreachable()
} catch {}
expectEqual(loopCount, 2)
}
ErrorHandlingTests.test("ErrorHandling/minElement") {
do {
let _: Int? = try [1, 2, 3].minElement { _, _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
do {
let _: Int? = try [1, 2, 3].maxElement { _, _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/startsWith") {
do {
let x: Bool = try [1, 2, 3].startsWith([1, 2]) { _, _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/elementsEqual") {
do {
let x: Bool = try [1, 2, 3].elementsEqual([1, 2, 3]) { _, _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/lexicographicalCompare") {
do {
let x: Bool = try [1, 2, 3].lexicographicalCompare([0, 2, 3]) { _, _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/contains") {
do {
let x: Bool = try [1, 2, 3].contains { _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/reduce") {
var loopCount = 0
do {
let x: Int = try [1, 2, 3, 4, 5].reduce(0, combine: {
(x: Int, y: Int) -> Int
in
loopCount += 1
var total = x + y
if total > 5 {
throw SillyError.JazzHands
}
return total
})
expectUnreachable()
} catch {}
expectEqual(loopCount, 3)
}
func explosiveBoolean() throws -> Bool {
throw SillyError.JazzHands
}
func explosiveInt() throws -> Int {
throw SillyError.JazzHands
}
ErrorHandlingTests.test("ErrorHandling/operators") {
do {
if try true && explosiveBoolean() {
expectUnreachable()
}
expectUnreachable()
} catch {}
do {
if try false || explosiveBoolean() {
expectUnreachable()
}
expectUnreachable()
} catch {}
do {
if try nil ?? explosiveInt() == 0 {
expectUnreachable()
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/Sequence map") {
let initialCount = NoisyCount
let sequence = AnySequence([1, 2, 3])
for throwAtCount in 0...3 {
var loopCount = 0
do {
let result: [Noisy] = try sequence.map { _ in
if loopCount == throwAtCount {
throw SillyError.JazzHands
}
loopCount += 1
return Noisy()
}
expectEqual(NoisyCount, initialCount + 3)
expectEqual(result.count, 3)
} catch {}
expectEqual(NoisyCount, initialCount)
}
}
ErrorHandlingTests.test("ErrorHandling/Sequence filter") {
let initialCount = NoisyCount
for condition in [true, false] {
for throwAtCount in 0...3 {
let sequence = [Noisy(), Noisy(), Noisy()]
var loopCount = 0
do {
let result: [Noisy] = try sequence.filter { _ in
if loopCount == throwAtCount {
throw SillyError.JazzHands
}
loopCount += 1
return condition
}
expectEqual(NoisyCount, initialCount + sequence.count)
expectEqual(result.count, condition ? 3 : 0)
} catch {}
}
expectEqual(NoisyCount, initialCount)
}
}
ErrorHandlingTests.test("ErrorHandling/Collection map") {
let initialCount = NoisyCount
let collection = [1, 2, 3]
for throwAtCount in 0...3 {
var loopCount = 0
do {
let result: [Noisy] = try collection.map { _ in
if loopCount == throwAtCount {
throw SillyError.JazzHands
}
loopCount += 1
return Noisy()
}
expectEqual(NoisyCount, initialCount + 3)
expectEqual(result.count, 3)
} catch {}
expectEqual(NoisyCount, initialCount)
}
}
runAllTests()
| apache-2.0 | c2b09048ad16e70233c0c738ef79c303 | 22.074286 | 97 | 0.61788 | 3.984213 | false | true | false | false |
Clean-Swift/CleanStore | CleanStore/Scenes/ShowOrder/ShowOrderPresenter.swift | 1 | 1467 | //
// ShowOrderPresenter.swift
// CleanStore
//
// Created by Raymond Law on 2/12/19.
// Copyright (c) 2019 Clean Swift LLC. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol ShowOrderPresentationLogic
{
func presentOrder(response: ShowOrder.GetOrder.Response)
}
class ShowOrderPresenter: ShowOrderPresentationLogic
{
weak var viewController: ShowOrderDisplayLogic?
let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
return dateFormatter
}()
let currencyFormatter: NumberFormatter = {
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
return currencyFormatter
}()
// MARK: - Get order
func presentOrder(response: ShowOrder.GetOrder.Response)
{
let order = response.order
let date = dateFormatter.string(from: order.date)
let total = currencyFormatter.string(from: order.total)!
let displayedOrder = ShowOrder.GetOrder.ViewModel.DisplayedOrder(id: order.id!, date: date, email: order.email, name: "\(order.firstName) \(order.lastName)", total: total)
let viewModel = ShowOrder.GetOrder.ViewModel(displayedOrder: displayedOrder)
viewController?.displayOrder(viewModel: viewModel)
}
}
| mit | 310f09fcfaa105b1bc21c015ff4187de | 28.34 | 175 | 0.732788 | 4.327434 | false | false | false | false |
ahayman/RxStream | RxStream/Streams/Progression.swift | 1 | 32931 | //
// Progression.swift
// RxStream iOS
//
// Created by Aaron Hayman on 9/25/17.
// Copyright © 2017 Aaron Hayman. All rights reserved.
//
import Foundation
/**
A ProgressEvent represents the current progress for a task.
*/
public struct ProgressEvent<T> {
// The title should be a user friendly, short stream describing the task.
public let title: String
// The unit should describe the progress units. Example: 'mb', '%', etc
public let unit: String
// The current progress.
public var current: T
// The total expected progress.
public let total: T
/**
A Progress Event should be initialized with:
- parameters:
- title: A short description of the progress
- unit: The name of the unit describing the progress
- current: The current progress
- total: The total expected units
*/
public init(title: String, unit: String, current: T, total: T) {
self.title = title
self.unit = unit
self.current = current
self.total = total
}
}
/// Use to detect the presence of a Progression stream down stream and pass it a progress event.
protocol ProgressStream {
func processProgressEvent<Unit>(_ event: ProgressEvent<Unit>)
}
extension Progression: ProgressStream { }
/// Progression streams are cancelable.
extension Progression: Cancelable { }
/**
A Progression stream is a type of Future that allows the client to observe the progress of the task while waiting for the task to complete.
The most obvious and common use case for this is to update a Progression Indicator in the UI while waiting for something to complete/download/process/etc.
At it's core, the Progression stream replaces the standard two handler function signature with a single return value. For example, this:
func downloadImage(at url: URL, progressHandler: ((Progression) -> Void)?, completion: (URL) -> Void)
can be replaced with:
func downloadImage(at url: URL) -> Progression<Double, URL>
The client can then choose to observe the progress on their own terms:
downloadImage(at: someURL)
.onProgress{ p in self.updateUIWith(progress: p) }
.on{ url in self.handleDownloadedImage(at: url) }
Warning: Unless the Stream is cancelled, the task should _always_ return a result. Otherwise, both the task and the stream will be leaked in memory.
*/
public class Progression<ProgressUnit, T> : Future<T> {
/**
When creating a Progression stream, you'll need to pass in the task closure that both updates the progress _and_ submits the final value when completed.
The closure takes two arguments:
- parameter cancelled: a reference Boolean value that indicates whether the task has been cancelled.
If possible, the task should cancel and clean up. Any further attempts to call the handler will be ignored.
- parameter resultHandler: This is an embedded closure that takes either a ProgressEvent or a Result.
If a progress event is passed in, the stream will be updated with the current progress. If a Result is passed in,
the stream will complete with the Result and terminate.
*/
public typealias ProgressTask = (_ cancelled: Box<Bool>, _ result: @escaping (Either<ProgressEvent<ProgressUnit>, Result<T>>) -> Void) -> Void
/**
The progress mapper should map a progress event to the this streams ProgressUnit type.
In order to work with Swift's type system, the argument type is `Any` to get around the type system.
However, since this is only assigned from within this module, it should always be consistent if I've done everything correctly.
*/
internal var progressMapper: ((Any) -> ProgressEvent<ProgressUnit>?)?
/// On handler for progress events. Since we're not using the standard "piping" in the Stream, we've gotta keep an explicit reference.
internal var onHandler: ((ProgressEvent<ProgressUnit>) -> Void)?
/// Satisfied the Cancelable protocol to allow a stream to be cancelled.
weak var cancelParent: Cancelable?
/**
The task associated with this stream.
Note: The task is strongly referenced and within that is a closure that strongly references this class.
This created a memory lock on the stream so long as the task is active.
*/
private var task: ProgressTask?
/// We keep a separate cancelled variable here so we can pass it into the task as an inout reference.
private var cancelled = Box(false)
// MARK: Initializers
/**
Allows for the creation of a `Progression` that already has a value filled.
- note: Since the Progression is completed before being returned, there will be no chance for progress updates.
*/
public class func completed<U, T>(_ value: T) -> Progression<U, T> {
let progression = Progression<U, T>(op: "CompletedValue")
progression.process(event: .next(value))
return progression
}
/**
Allows for the creation of a `Progression` that already has a error filled.
- note: Since the Progression is completed before being returned, there will be no chance for progress updates.
*/
public class func completed<U, T>(_ error: Error) -> Progression<U, T> {
let progression = Progression<U, T>(op: "CompletedError")
progression.process(event: .error(error))
return progression
}
/**
Initialize a Progression with a Task. The task should be use to:
- Pass updates regarding the progress of the task.
- Monitor the cancelled boolean status and clean up if the flag is marked `true`
- Pass the Result when the task has completed or encountered an error.
Note: The task will be called immediately on instantiation.
- parameter task: A ProgressTask used to perform the task, update progress, and return the Result.
- return: A new Progression Stream
*/
public init(task: @escaping ProgressTask) {
super.init(op: "Task")
var complete = false
self.task = task
task(cancelled) { result in
guard complete == false && self.isActive else { return }
switch result {
case .left(let progress):
self.processProgressEvent(progress)
case .right(.success(let data)):
complete = true
self.process(event: .next(data))
case .right(.failure(let error)):
complete = true
self.process(event: .terminate(reason: .error(error)))
}
}
}
/// Internal init for creating down streams for operations
override init(op: String) {
task = nil
super.init(op: op)
}
// MARK: Overrides
/// If we have a handler or mapper, then those should use the dispatcher and the stream op should only be a passthrough.
override func shouldDispatch<U>(event: Event<U>) -> Bool {
return onHandler == nil && progressMapper == nil
}
/// If we have a handler or mapper, then those should use the throttle and the stream op should only be a passthrough.
override func shouldThrottle<U>(event: Event<U>) -> Bool {
return onHandler == nil && progressMapper == nil
}
/// We need to handle cancelled and terminate events properly to ensure we release the lock and mark the stream cancelled for the task.
override func preProcess<U>(event: Event<U>) -> Event<U>? {
// Terminations are always processed.
switch event {
case .terminate(.cancelled): cancelled.value = true; fallthrough
case .terminate, .error: self.task = nil
default: break
}
return super.preProcess(event: event)
}
/// Used to detect when we should remove the task to release the memory lock
override func postProcess<U>(event: Event<U>, producedSignal signal: OpSignal<T>) {
switch signal {
case .push, .error, .cancel: self.task = nil
default: break
}
super.postProcess(event: event, producedSignal: signal)
}
// MARK: Cancellation
/// Part of the Cancelable protocol, we either cancel the task or pass the cancellation to the parent.
func cancelTask() {
guard isActive else { return }
guard task == nil else { return process(event: .terminate(reason: .cancelled)) }
guard let parent = cancelParent else { return process(event: .terminate(reason: .cancelled)) }
parent.cancelTask()
}
/**
This will cancel the stream. It will travel up stream until it reaches the task that is performing the operation.
A flag is passed into that task, indicating that the stream has been cancelled. While the stream itself is guaranteed
to be cancelled (an no further events propagated), the task itself may or may not cancel, depending on whether it is watching
that flag.
*/
public func cancel() {
cancelTask()
}
// MARK: Processing
/**
Despite it's length, all of the work is done primarily in the `work` closure, where we map the progress event, call the handler,
and pass the event downstream. Pretty much everything else iterates the variations needed to use dispatch and throttle.
*/
func processProgressEvent<Unit>(_ event: ProgressEvent<Unit>) {
/// Convenience function to map a progress event or return the current event if it's type signature matches this instance.
func mapProgressEvent<U>(_ event: ProgressEvent<U>) -> ProgressEvent<ProgressUnit>? {
return progressMapper?(event) ?? event as? ProgressEvent<ProgressUnit>
}
let work = {
guard let pEvent = mapProgressEvent(event) else { return }
self.onHandler?(pEvent)
for stream in self.downStreams.oMap({ $0.stream as? ProgressStream }) {
stream.processProgressEvent(pEvent)
}
}
switch (self.throttle, self.dispatch) {
case let (.some(throttle), .some(dispatch)):
throttle.process { signal in
switch signal {
case .cancel: return
case let .perform(completion):
dispatch.execute {
work()
completion()
}
}
}
case let (.some(throttle), .none):
throttle.process { signal in
switch signal {
case .cancel: return
case let .perform(completion):
work()
completion()
}
}
case let (.none, .some(dispatch)):
dispatch.execute(work)
case (.none, .none):
work()
}
}
// MARK: Progress Operations
/**
## Branching
Attache a simple handler to observe when new Progression Events are emitted.
- parameter handler: The handler takes a ProgressEvent and returns `Void`. A new event will be emitted whenever the progress is updated from the task.
- returns: A new Progression Stream of the same type.
- warning: There is no guarantee the handler will be called on the main thread unless you specify the appropriate dispatch. This is an important
consideration if you are attempting to update a UI from the handler.
*/
@discardableResult public func onProgress(_ handler: @escaping (ProgressEvent<ProgressUnit>) -> Void) -> Progression<ProgressUnit, T> {
let stream = append(stream: Progression<ProgressUnit, T>(op: "onProgress")) { (event, completion) in completion(event.signal) }
stream.onHandler = handler
return stream
}
/**
## Branching
This will map the progress events of this stream to a new progress event type.
It does not map the final emitted value of the stream.
- parameter mapper: Handler should take a progress event and map it to the new type.
- returns: a new Progression Stream with the new ProgressEvent type.
*/
@discardableResult public func mapProgress<U>(_ mapper: @escaping (ProgressEvent<ProgressUnit>) -> ProgressEvent<U>) -> Progression<U, T> {
let stream = append(stream: Progression<U, T>(op: "onProgress")) { (event: Event<T>, completion: @escaping (OpSignal<T>) -> Void) in completion(event.signal) }
stream.progressMapper = { event in
guard let event = event as? ProgressEvent<ProgressUnit> else { return nil }
return mapper(event)
}
return stream
}
/**
## Branching
Merge another Progression stream into this one, emitting the completed values from each string as a single tuple.
Requires that you also map the progress events of each stream into a new progress event. In most situations,
the progress emitted from the mapper should be _additive_, that is, taking the current progress and totals
of each event and adding them together to produce a total of both. Of course, you are able to do whatever
is appropriate for the situation.
- parameter stream: The stream to combine into this one.
- parameter progressMapper: Maps the progress of one or both streams into a new progress event.
- returns: A new Progression Stream
*/
@discardableResult public func combineProgress<U, R, P>(
stream: Progression<R, U>,
progressMapper mapper: @escaping (EitherAnd<ProgressEvent<ProgressUnit>, ProgressEvent<R>>)
-> ProgressEvent<P>) -> Progression<P, (T, U)>
{
let combined = appendCombine(stream: stream, intoStream: Progression<P, (T, U)>(op: "combine(stream: \(stream))"), latest: true)
var left: ProgressEvent<ProgressUnit>? = nil
var right: ProgressEvent<R>? = nil
self.onHandler = { left = $0 }
stream.onHandler = { right = $0 }
combined.progressMapper = { event in
switch (event, left, right) {
case let (left as ProgressEvent<ProgressUnit>, _, .some(right)): return mapper(.both(left, right))
case let (right as ProgressEvent<R>, .some(left), _): return mapper(.both(left, right))
case let (left as ProgressEvent<ProgressUnit>, _, .none): return mapper(.left(left))
case let (right as ProgressEvent<R>, .none, _): return mapper(.right(right))
default: return nil
}
}
return combined
}
// MARK: Operations
// MARK:
/**
## Branching
Attach a simple observation handler to the stream to observe new values.
- parameter handler: The handler used to observe new values.
- parameter value: The next value in the stream
- returns: A new Progression stream
*/
@discardableResult public override func on(_ handler: @escaping (_ value: T) -> Void) -> Progression<ProgressUnit, T> {
return appendOn(stream: Progression<ProgressUnit, T>(op: "on"), handler: handler)
}
/**
## Branching
This will call the handler when the stream receives any error.
- parameter handler: Handler will be called when an error is received.
- parameter error: The error thrown by the stream
- note: The behavior of this operation is slightly different from other streams in that an error is _always_ reported, whether it is terminating or not. Other streams only report non-terminating errors.
- returns: a new Progression stream
*/
@discardableResult public override func onError(_ handler: @escaping (_ error: Error) -> Void) -> Progression<ProgressUnit, T> {
return append(stream: Progression<ProgressUnit, T>(op: "onError")) { (next, completion) in
switch next {
case .error(let error): handler(error)
case .terminate(.error(let error)): handler(error)
default: break
}
completion(next.signal)
}
}
/**
## Branching
Attach an observation handler to observe termination events for the stream.
- parameter handler: The handler used to observe the stream's termination.
- returns: A new Progression Stream
*/
@discardableResult public override func onTerminate(_ handler: @escaping (Termination) -> Void) -> Progression<ProgressUnit, T> {
return appendOnTerminate(stream: Progression<ProgressUnit, T>(op: "onTerminate"), handler: handler)
}
/**
## Branching
Map values in the current stream to new values returned in a new stream.
- note: The mapper returns an optional type. If the mapper returns `nil`, nothing will be passed down the stream, but the stream will continue to remain active.
- parameter mapper: The handler to map the current type to a new type.
- parameter value: The current value in the stream
- returns: A new Progression Stream
*/
@discardableResult public override func map<U>(_ mapper: @escaping (_ value: T) -> U?) -> Progression<ProgressUnit, U> {
return appendMap(stream: Progression<ProgressUnit, U>(op: "map<\(String(describing: T.self))>"), withMapper: mapper)
}
/**
## Branching
Map values in the current stream to new values returned in a new stream.
The mapper returns a result type that can return an error or the mapped value.
- parameter mapper: The handler to map the current value either to a new value or an error.
- parameter value: The current value in the stream
- returns: A new Progression Stream
*/
@discardableResult public override func resultMap<U>(_ mapper: @escaping (_ value: T) -> Result<U>) -> Progression<ProgressUnit, U> {
return appendMap(stream: Progression<ProgressUnit, U>(op: "resultMap<\(String(describing: T.self))>"), withMapper: mapper)
}
/**
## Branching
Map values _asynchronously_ to either a new value, or else an error.
The handler should take the current value along with a completion handler.
Once ready, the completion handler should be called with:
- New Value: New values will be passed down stream
- Error: An error will be passed down stream. If you wish the error to terminate, add `onError` down stream and return a termination for it.
- `nil`: Passing `nil` into will complete the handler but pass nothing down stream.
- warning: The completion handler must _always_ be called, even if it's called with `nil`. Failing to call the completion handler will block the stream, prevent it from being terminated, and will result in memory leakage.
- parameter mapper: The mapper takes a value and a comletion handler.
- parameter value: The current value in the stream
- parameter completion: The completion handler; takes an optional Result type passed in. _Must always be called only once_.
- returns: A new Progression Stream
*/
@discardableResult public override func asyncMap<U>(_ mapper: @escaping (_ value: T, _ completion: @escaping (Result<U>?) -> Void) -> Void) -> Progression<ProgressUnit, U> {
return appendMap(stream: Progression<ProgressUnit, U>(op: "asyncMap<\(String(describing: T.self))>"), withMapper: mapper)
}
/**
## Branching
Map values to an array of values that are emitted sequentially in a new stream.
- parameter mapper: The mapper should take a value and map it to an array of new values. The array of values will be emitted sequentially in the returned stream.
- parameter value: The next value in the stream.
- note: Because a future can only return 1 value, using flatmap will instead return a Hot Stream that emits the mapped values and then terminates.
- returns: A new Hot Stream
*/
@discardableResult public override func flatMap<U>(_ mapper: @escaping (_ value: T) -> [U]) -> Hot<U> {
return appendFlatMap(stream: Hot<U>(op: "flatMap<\(String(describing: T.self))>"), withFlatMapper: mapper)
}
/**
## Branching
Filter out values if the handler returns `false`.
- parameter include: Handler to determine whether the value should filtered out (`false`) or included in the stream (`true`)
- parameter value: The next value to be emitted by the stream.
- returns: A new Progression Stream
*/
@discardableResult public override func filter(include: @escaping (_ value: T) -> Bool) -> Progression<ProgressUnit, T> {
return appendFilter(stream: Progression<ProgressUnit, T>(op: "filter"), include: include)
}
/**
## Branching
Append a stamp to each item emitted from the stream. The Stamp and the value will be emitted as a tuple.
- parameter stamper: Takes a value emitted from the stream and returns a stamp for that value.
- parameter value: The next value for the stream.
- returns: A new Progression Stream
*/
@discardableResult public override func stamp<U>(_ stamper: @escaping (_ value: T) -> U) -> Progression<ProgressUnit, (value: T, stamp: U)> {
return appendStamp(stream: Progression<ProgressUnit, (value: T, stamp: U)>(op: "stamp"), stamper: stamper)
}
/**
## Branching
Append a timestamp to each value and return both as a tuple.
- returns: A new Progression Stream
*/
@discardableResult public override func timeStamp() -> Progression<ProgressUnit, (value: T, stamp: Date)> {
return stamp{ _ in return Date() }
}
/**
## Branching
This will delay the values emitted from the stream by the time specified.
- warning: The stream cannot terminate until all events are terminated.
- parameter delay: The time, in seconds, to delay emitting events from the stream.
- returns: A new Progression Stream
*/
@discardableResult public override func delay(_ delay: TimeInterval) -> Progression<ProgressUnit, T> {
return appendDelay(stream: Progression<ProgressUnit, T>(op: "delay(\(delay))"), delay: delay)
}
/**
## Branching
Emit provided values immediately before the first value received by the stream.
- note: These values are only emitted when the stream receives its first value. If the stream receives no values, these values won't be emitted.
- note: Since a Progression can only emit 1 item, flatten will return a hot stream instead, emit the flattened values and then terminate.
- parameter with: The values to emit before the first value
- returns: A new Progression Stream
*/
@discardableResult public override func start(with: [T]) -> Hot<T> {
return appendStart(stream: Hot<T>(op: "start(with: \(with.count) values)"), startWith: with)
}
/**
## Branching
Emit provided values after the last item, right before the stream terminates.
These values will be the last values emitted by the stream.
- parameter concat: The values to emit before the stream terminates.
- note: Since a Progression can only emit 1 item, flatten will return a hot stream instead, emit the flattened values and then terminate.
- returns: A new Progression Stream
*/
@discardableResult public override func concat(_ concat: [T]) -> Hot<T> {
return appendConcat(stream: Hot<T>(op: "concat(\(concat.count) values)"), concat: concat)
}
/**
## Branching
Define a default value to emit if the stream terminates without emitting anything.
- parameter value: The default value to emit.
- returns: A new Progression Stream
*/
@discardableResult public override func defaultValue(_ value: T) -> Progression<ProgressUnit, T> {
return appendDefault(stream: Progression<ProgressUnit, T>(op: "defaultValue(\(value))"), value: value)
}
// MARK: Combining operators
/**
## Branching
Merge a separate stream into this one, returning a new stream that emits values from both streams sequentially as an Either
- parameter stream: The stream to merge into this one.
- returns: A new Progression Stream
*/
@discardableResult public override func merge<U>(_ stream: Stream<U>) -> Progression<ProgressUnit, Either<T, U>> {
return appendMerge(stream: stream, intoStream: Progression<ProgressUnit, Either<T, U>>(op: "merge(stream:\(stream))"))
}
/**
## Branching
Merge into this stream a separate stream with the same type, returning a new stream that emits values from both streams sequentially.
- parameter stream: The stream to merge into this one.
- returns: A new Progression Stream
*/
@discardableResult public override func merge(_ stream: Stream<T>) -> Progression<ProgressUnit, T> {
return appendMerge(stream: stream, intoStream: Progression<ProgressUnit, T>(op: "merge(stream:\(stream))"))
}
/**
## Branching
Merge another stream into this one, _zipping_ the values from each stream into a tuple that's emitted from a new stream.
- note: Zipping combines a stream of two values by their _index_.
In order to do this, the new stream keeps a buffer of values emitted by either stream if one stream emits more values than the other.
In order to prevent unconstrained memory growth, you can specify the maximum size of the buffer.
If you do not specify a buffer, the buffer will continue to grow if one stream continues to emit values more than another.
- parameter stream: The stream to zip into this one
- parameter buffer: _(Optional)_, **Default:** `nil`. The maximum size of the buffer. If `nil`, then no maximum is set (the buffer can grow indefinitely).
- returns: A new Progression Stream
*/
@discardableResult public override func zip<U>(_ stream: Stream<U>, buffer: Int? = nil) -> Progression<ProgressUnit, (T, U)> {
return appendZip(stream: stream, intoStream: Progression<ProgressUnit, (T, U)>(op: "zip(stream: \(stream), buffer: \(buffer ?? -1))"), buffer: buffer)
}
/**
## Branching
Merge another stream into this one, emitting the values as a tuple.
If one stream emits more values than another, the latest value in that other stream will be emitted multiple times, thus enumerating each combination.
- parameter stream: The stream to combine into this one.
- returns: A new Progression Stream
*/
@discardableResult public override func combine<U>(stream: Stream<U>) -> Progression<ProgressUnit, (T, U)> {
return appendCombine(stream: stream, intoStream: Progression<ProgressUnit, (T, U)>(op: "combine(stream: \(stream))"), latest: true)
}
// MARK: Lifetime operators
/**
## Branching
Emit values from stream until the handler returns `false`, and then terminate the stream with the provided termination.
- parameter then: **Default:** `.cancelled`. When the handler returns `false`, then terminate the stream with this termination.
- parameter handler: Takes the next value and returns `false` to terminate the stream or `true` to remain active.
- parameter value: The current value being passed down the stream.
- warning: Be aware that terminations propagate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- returns: A new Hot Stream
*/
@discardableResult public override func doWhile(then: Termination = .cancelled, handler: @escaping (_ value: T) -> Bool) -> Progression<ProgressUnit, T> {
return appendWhile(stream: Progression<ProgressUnit, T>(op: "doWhile(then: \(then))"), handler: handler, then: then)
}
/**
## Branching
Emit values from stream until the handler returns `true`, and then terminate the stream with the provided termination.
- note: This is the inverse of `doWhile`, in that the stream remains active _until_ it returns `true` whereas `doWhile` remains active until the handler return `false`.
- parameter then: **Default:** `.cancelled`. When the handler returns `true`, then terminate the stream with this termination.
- parameter handler: Takes the next value and returns `true` to terminate the stream or `false` to remain active.
- parameter value: The current value being passed down the stream.
- warning: Be aware that terminations propagate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- returns: A new Hot Stream
*/
@discardableResult public override func until(then: Termination = .cancelled, handler: @escaping (T) -> Bool) -> Progression<ProgressUnit, T> {
return appendUntil(stream: Progression<ProgressUnit, T>(op: "until(then: \(then)"), handler: handler, then: then)
}
/**
## Branching
Emit values from stream until the handler returns a `Termination`, at which the point the stream will Terminate.
- parameter handler: Takes the next value and returns a `Termination` to terminate the stream or `nil` to continue as normal.
- parameter value: The current value being passed down the stream.
- warning: Be aware that terminations propagate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- returns: A new Hot Stream
*/
@discardableResult public override func until(_ handler: @escaping (_ value: T) -> Termination?) -> Progression<ProgressUnit, T> {
return appendUntil(stream: Progression<ProgressUnit, T>(op: "until"), handler: handler)
}
/**
## Branching
Keep a weak reference to an object, emitting both the object and the current value as a tuple.
Terminate the stream on the next event that finds object `nil`.
- parameter object: The object to keep a week reference. The stream will terminate on the next even where the object is `nil`.
- parameter then: The termination to apply after the reference has been found `nil`.
- warning: Be aware that terminations propagate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- warning: This stream will return a stream that _cannot_ be replayed. This prevents the stream of retaining the object and extending its lifetime.
- returns: A new Hot Stream
*/
@discardableResult public override func using<U: AnyObject>(_ object: U, then: Termination = .cancelled) -> Progression<ProgressUnit, (U, T)> {
return appendUsing(stream: Progression<ProgressUnit, (U, T)>(op: "using(\(object), then: \(then))"), object: object, then: then).canReplay(false)
}
/**
## Branching
Tie the lifetime of the stream to that of the object.
Terminate the stream on the next event that finds object `nil`.
- parameter object: The object to keep a week reference. The stream will terminate on the next even where the object is `nil`.
- parameter then: The termination to apply after the reference has been found `nil`.
- warning: Be aware that terminations propagate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- warning: This stream will return a stream that _cannot_ be replayed. This prevents the stream of retaining the object and extending its lifetime.
- returns: A new Progression Stream
*/
@discardableResult public override func lifeOf<U: AnyObject>(_ object: U, then: Termination = .cancelled) -> Progression<ProgressUnit, T> {
return appendLifeOf(stream: Progression<ProgressUnit, T>(op: "lifeOf(\(object), then: \(then))"), object: object, then: then)
}
}
/**
A ProgressionInput is a subclass of Progression that allows you to update and complete the progression outside the class with standard functions.
Normally, a Progression is created by passing in a Task that provides the progression with all the updates and data needed to complete the stream and
update the progress. This works well when the task the Progression represents is easily contained. However, in many cases, the task isn't easily contained,
especially when using a delegate pattern, and updates need to be passed in from outside the class. In those cases, use a Progression Input, pass in
progress updates using `updateProgress(to:_)`, and complete the progression by using the `complete(_:_)` function.
- warning: A standard Progression will lock itself in memory until the task is completed. However, a ProgressionInput has no such lock, so it's
important to keep a reference to the stream until the progression is completed or else it will be dropped from memory.
*/
public class ProgressionInput<ProgressUnit, T> : Progression<ProgressUnit, T> {
/**
Initialization of a Progression Input requires no parameters, but may require type information.
After initializing, the Progression should be completed by calling the `complete` func with a value or an error.
The Progression's progress can be updated by using the `updateProgress(to: _)` function.
*/
public init() {
super.init(op: "Input")
}
/**
This will complete the Progression with the provided value.
After passing this value, no other values, errors or progression updates can be passed in.
- parameter value: The value to complete the progression with.
*/
public func complete(_ value: T) {
self.process(event: .next(value))
}
/**
Update the progress of the progression stream.
- parameter progress: A Progress Event that represents the current progress of the progression stream.
*/
public func updateProgress(to progress: ProgressEvent<ProgressUnit>) {
self.processProgressEvent(progress)
}
/**
This will complete the future with the provided error.
After passing this error, no other values or errors can be passed in.
- parameter error: The error to complete the future with.
*/
public func complete(_ error: Error) {
self.process(event: .terminate(reason: .error(error)))
}
deinit {
self.process(event: .terminate(reason: .cancelled))
}
}
| mit | ca14e22d2f987d0997a587307310ae97 | 41.326478 | 225 | 0.709475 | 4.343754 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/01669-void.swift | 11 | 576 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
import Foundation
protocol b : C: (s: String {
func a(a: AnyObject, let b in c == "
protocol b : A {
typealias B : c, B>() {
var _ = g: A, Any, let v: d == d.init()"
protocol A : A(a)
| apache-2.0 | 4d7663d954c4e992d5e33e83d48215cd | 37.4 | 78 | 0.696181 | 3.428571 | false | false | false | false |
santosli/100-Days-of-Swift-3 | Project 28/Project 28/SLTableViewController.swift | 1 | 3072 | //
// SLTableViewController.swift
// Project 28
//
// Created by Santos on 05/01/2017.
// Copyright © 2017 santos. All rights reserved.
//
import UIKit
class SLTableViewController: UITableViewController {
@IBOutlet weak var collectionView: UICollectionView!
let imageCount = 6;
let movieData = ["Mr. Donkey", "Tony and Susan", "The Day Will Come", "The Shawshank Redemption", "Léon", "Farewell My Concubine", "Forrest Gump", "La vita è bella", "Spirited Away", "Schindler's List", "Titanic","Inception", "WALL·E", "3 Idiots", "Les choristes", "Hachi: A Dog's Tale", "The Godfather", "Gone with the Wind", "The Truman Show", "Nuovo Cinema Paradiso"]
override func viewDidLoad() {
super.viewDidLoad()
//init navigationItem
navigationItem.title = "Movies"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Genres", style: .plain, target: self, action: nil)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: nil)
collectionView.delegate = self
collectionView.dataSource = self
//set UICollectionViewFlowLayout
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let width = UIScreen.main.bounds.width
layout.itemSize = CGSize(width: width, height: 154)
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = .horizontal
collectionView?.collectionViewLayout = layout
collectionView.reloadData()
}
}
// MARK: - Table view data source
extension SLTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return movieData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "movieTable", for: indexPath)
cell.textLabel?.text = movieData[indexPath.row]
return cell
}
}
extension SLTableViewController : UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! SLImageCollectionViewCell
cell.imageView.image = UIImage(named: String(indexPath.row) + ".jpg")
return cell
}
}
| apache-2.0 | fbb032e18a6e1fc12cd4bb542a09ed48 | 36.876543 | 374 | 0.687093 | 4.988618 | false | false | false | false |
alokc83/rayW-SwiftSeries | RW-SwiftSeries-fucntions-Chellenge7.playground/Contents.swift | 1 | 790 | //: Playground - noun: a place where people can play
import UIKit
func count(#targetNumber:Int) -> (){
for n in 0 ... targetNumber{
println(n)
}
}
count(targetNumber: 10)
func countTo(#targetNum:Int, by:Int = 5) ->(){
for var n = 0; n < targetNum; n += by{
println(n)
}
}
countTo(targetNum: 20)
// chellenge 7
//3,5 wintin 1000
func projEuler(#firstInt:Int, #secondInt:Int, withIn:Int = 100) -> (Int){
var sum = 0
for num in 0..<withIn{
let multipleOfFirstInt = num%firstInt == 0
let multipleOfSecondInt = num%secondInt == 0
if multipleOfFirstInt || multipleOfSecondInt{
sum = sum + num
}
}
return sum
}
var returnVal = projEuler(firstInt: 3, secondInt: 5, withIn: 1000)
println(returnVal)
| mit | ebd329729ff57d373e36e57fc5ecbd9f | 20.351351 | 73 | 0.608861 | 3.22449 | false | false | false | false |
optimizely/swift-sdk | Tests/OptimizelyTests-DataModel/UserAttributeTests.swift | 1 | 8284 | //
// Copyright 2019, 2021, Optimizely, Inc. and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
// MARK: - Sample Data
class UserAttributeTests: XCTestCase {
let modelType = UserAttribute.self
static var sampleData: [String: Any] = ["name": "geo",
"type": "custom_attribute",
"match": "exact",
"value": 30]
}
// MARK: - Decode
extension UserAttributeTests {
func testDecodeSuccessWithJSONValid() {
let json: [String: Any] = ["name": "geo", "type": "custom_attribute", "match": "exact", "value": 30]
// JSONEncoder not happy with [String: Any]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
let model = try! JSONDecoder().decode(modelType, from: jsonData)
XCTAssert(model.name == "geo")
XCTAssert(model.typeSupported == .customAttribute)
XCTAssert(model.matchSupported == .exact)
// integer can be parsed as int or double (we catch as double first)
XCTAssert(model.value == .double(30.0))
}
func testDecodeSuccessWithJSONValid2() {
let json: [String: Any] = ["name": "geo", "type": "custom_attribute", "match": "gt", "value": 30.5]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
let model = try! JSONDecoder().decode(modelType, from: jsonData)
XCTAssert(model.name == "geo")
XCTAssert(model.typeSupported == .customAttribute)
XCTAssert(model.matchSupported == .gt)
XCTAssert(model.value == .double(30.5))
}
func testDecodeSuccessWithJSONValid3() {
let json: [String: Any] = ["name": "geo", "type": "custom_attribute", "match": "exists", "value": true]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
let model = try! JSONDecoder().decode(modelType, from: jsonData)
XCTAssert(model.name == "geo")
XCTAssert(model.typeSupported == .customAttribute)
XCTAssert(model.matchSupported == .exists)
XCTAssert(model.value == .bool(true))
}
func testDecodeSuccessWithJSONValid4() {
let json: [String: Any] = ["name": "geo", "type": "custom_attribute", "match": "substring", "value": "us"]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
let model = try! JSONDecoder().decode(modelType, from: jsonData)
XCTAssert(model.name == "geo")
XCTAssert(model.typeSupported == .customAttribute)
XCTAssert(model.matchSupported == .substring)
XCTAssert(model.value == .string("us"))
}
func testDecodeSuccessWithMissingMatch() {
let json: [String: Any] = ["name": "geo", "type": "custom_attribute", "value": "us"]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
let model = try! JSONDecoder().decode(modelType, from: jsonData)
XCTAssert(model.name == "geo")
XCTAssert(model.typeSupported == .customAttribute)
XCTAssert(model.value == .string("us"))
}
func testDecodeSuccessWithMissingName() {
let json: [String: Any] = ["type": "custom_attribute", "match": "exact", "value": "us"]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
let model = try! JSONDecoder().decode(modelType, from: jsonData)
XCTAssert(model.typeSupported == .customAttribute)
XCTAssert(model.matchSupported == .exact)
XCTAssert(model.value == .string("us"))
}
func testDecodeSuccessWithMissingType() {
let json: [String: Any] = ["name": "geo", "match": "exact", "value": "us"]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
let model = try! JSONDecoder().decode(modelType, from: jsonData)
XCTAssert(model.name == "geo")
XCTAssert(model.matchSupported == .exact)
XCTAssert(model.value == .string("us"))
}
func testDecodeSuccessWithMissingValue() {
let json: [String: Any] = ["name": "geo", "type": "custom_attribute", "match": "exact"]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
let model = try! JSONDecoder().decode(modelType, from: jsonData)
XCTAssert(model.name == "geo")
XCTAssert(model.typeSupported == .customAttribute)
XCTAssert(model.matchSupported == .exact)
}
func testDecodeSuccessWithWrongValueType() {
let json: [String: Any] = ["name": "geo", "type": "custom_attribute", "match": "exact", "value": ["a1", "a2"]]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
let model = try! JSONDecoder().decode(modelType, from: jsonData)
XCTAssert(model.name == "geo")
XCTAssert(model.typeSupported == .customAttribute)
XCTAssert(model.matchSupported == .exact)
XCTAssert(model.value == .others)
}
// MARK: - Forward Compatibility
func testDecodeSuccessWithInvalidType() {
let json: [String: Any] = ["name": "geo", "type": "invalid", "match": "exact", "value": 10]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
let model = try! JSONDecoder().decode(modelType, from: jsonData)
XCTAssert(model.name == "geo")
XCTAssertNil(model.typeSupported)
XCTAssert(model.matchSupported == .exact)
}
func testDecodeSuccessWithInvalidMatch() {
let json: [String: Any] = ["name": "geo", "type": "custom_attribute", "match": "invalid", "value": 10]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
let model = try! JSONDecoder().decode(modelType, from: jsonData)
XCTAssert(model.name == "geo")
XCTAssert(model.typeSupported == .customAttribute)
XCTAssertNil(model.matchSupported)
}
}
// MARK: - Encode
extension UserAttributeTests {
func testEncodeJSON() {
let modelGiven = modelType.init(name: "geo", type: "custom_attribute", match: "exact", value: .string("us"))
XCTAssert(OTUtils.isEqualWithEncodeThenDecode(modelGiven))
}
}
// MARK: - Others
extension UserAttributeTests {
func testDecodeFailureWithInvalidData() {
let jsonInvalid: [String: Any] = ["name": true, "type": 123]
let jsonDataInvalid = try! JSONSerialization.data(withJSONObject: jsonInvalid, options: [])
var tmpError: Error?
do {
_ = try JSONDecoder().decode(modelType, from: jsonDataInvalid)
} catch {
tmpError = error
}
XCTAssertTrue(tmpError != nil)
}
func testEvaluateWithMissingName() {
let json: [String: Any] = ["type":"custom_attribute", "match":"exact", "value":"us"]
let model: UserAttribute = try! OTUtils.model(from: json)
var tmpError: Error?
do {
_ = try model.evaluate(user: OTUtils.user(attributes: ["country": "us"]))
} catch {
tmpError = error
}
XCTAssertTrue(tmpError != nil)
}
func testEvaluateWithInvalidMatch() {
let json: [String: Any] = ["name":"geo", "type":"custom_attribute", "match":"invalid", "value": 10]
let model: UserAttribute = try! OTUtils.model(from: json)
var tmpError: Error?
do {
_ = try model.evaluate(user: OTUtils.user(attributes: ["name": "geo"]))
} catch {
tmpError = error
}
XCTAssertTrue(tmpError != nil)
}
}
| apache-2.0 | 4210cf58146c4eb9a4108184f93b1c44 | 39.213592 | 118 | 0.614317 | 4.278926 | false | true | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.