repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
robconrad/fledger-common | refs/heads/master | FledgerCommon/LoginViewHelper.swift | mit | 1 | //
// LoginViewControllerUtils.swift
// FledgerCommon
//
// Created by Robert Conrad on 8/16/15.
// Copyright (c) 2015 Robert Conrad. All rights reserved.
//
import Foundation
public protocol LoginViewHelperDataSource {
func getEmail() -> String
func getPassword() -> String
}
public protocol LoginViewHelperDelegate {
func notifyEmailValidity(valid: Bool)
func notifyPasswordValidity(valid: Bool)
func notifyLoginResult(valid: Bool)
}
public class LoginViewHelper {
private let dataSource: LoginViewHelperDataSource
private let delegate: LoginViewHelperDelegate
public required init(_ dataSource: LoginViewHelperDataSource, _ delegate: LoginViewHelperDelegate) {
self.dataSource = dataSource
self.delegate = delegate
}
public func loginFromCache() {
if ParseSvc().isLoggedIn() {
handleSuccess()
}
}
public func login() {
if !validateFields() {
return
}
ParseSvc().login(dataSource.getEmail(), dataSource.getPassword(), { success in
if success {
self.handleSuccess()
}
else {
self.delegate.notifyLoginResult(false)
}
})
}
public func signup() {
if !validateFields() {
return
}
ParseSvc().signup(dataSource.getEmail(), dataSource.getPassword(), { success in
if success {
self.handleSuccess()
}
else {
self.delegate.notifyEmailValidity(false)
}
})
}
public func validateFields() -> Bool {
var valid = true
delegate.notifyEmailValidity(true)
if dataSource.getEmail().characters.count < 5 {
delegate.notifyEmailValidity(false)
valid = false
}
delegate.notifyPasswordValidity(true)
if dataSource.getPassword().characters.count < 3 {
delegate.notifyPasswordValidity(false)
valid = false
}
return valid
}
private func handleSuccess() {
// services can't be registered until a User is logged in
ServiceBootstrap.register()
delegate.notifyLoginResult(true)
}
} | 28b4de44de674945f1d83fc7b4a13c74 | 23.43299 | 104 | 0.576192 | false | false | false | false |
Codility-BMSTU/Codility | refs/heads/master | Codility/Codility/OBMyCardBalanceResponse.swift | apache-2.0 | 1 | //
// OBMyCardBalanceResponse.swift
// Codility
//
// Created by Кирилл Володин on 16.09.17.
// Copyright © 2017 Кирилл Володин. All rights reserved.
//
import Foundation
import SwiftyJSON
class OBMyCardBalanceResponse {
var card: OBMyCard!
var json: JSON!
var errorCode: String = ""
var errorDescription: String = ""
init(json: JSON) {
self.json = json
self.errorCode = json["ErrorCode"].string ?? ""
self.errorDescription = json["ErrorDescription"].string ?? ""
let card = OBMyCard()
card.id = json["CardId"].int! // временная строчка
for item in json["CardBalance"].arrayValue {
let newBalance = OBCardBalance()
newBalance.value = item["Value"].int ?? 0
newBalance.cur = item["Cur"].string ?? ""
card.balances.append(newBalance)
}
self.card = card
}
}
| 78ae573501d08f2b6f55c1bd23c440a7 | 23.435897 | 69 | 0.570829 | false | false | false | false |
GenerallyHelpfulSoftware/Scalar2D | refs/heads/master | Styling/Sources/GraphicStyle.swift | mit | 1 | //
// GraphicStyle.swift
// Scalar2D
//
// Created by Glenn Howes on 8/27/16.
// Copyright © 2016-2019 Generally Helpful Software. All rights reserved.
//
//
//
// The MIT License (MIT)
// Copyright (c) 2016-2019 Generally Helpful Software
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
import Foundation
import Scalar2D_Colour
import Scalar2D_FontDescription
#if os(iOS) || os(tvOS) || os(OSX) || os(watchOS)
import CoreGraphics
public typealias NativeDimension = CGFloat
#else
public typealias NativeDimension = Double
#endif
extension String
{
public var asStyleUnit : StyleUnit?
{
switch self.lowercased()
{
case "px":
return .pixel
case "%":
return .percent
case "em":
return .em
case "pt":
return .point
case "cm":
return .centimeter
default:
return nil
}
}
}
public struct UnitDimension : Equatable
{
public let dimension: NativeDimension
public let unit : StyleUnit
public init(dimension: NativeDimension, unit: StyleUnit)
{
self.dimension = dimension
self.unit = unit
}
}
public enum StyleProperty
{
case string(String)
case unitNumber(UnitDimension)
case number(Double)
case colour(Colour, NativeColour?)
case boolean(Bool)
// half of any graphics library is dealing with drawing text
case fontStyle(FontStyle)
case fontVariant(FontVariant)
case fontFamilies([FontFamily])
case fontWeight(FontWeight)
case fontStretch(FontStretch)
case fontDecorations(Set<TextDecoration>)
case distance(Distance)
case fontSize(FontSize)
// stroke properties
case lineCap(LineCap)
case lineJoin(LineJoin)
// view properties
case border([BorderRecord])
case cornerRadius(CornerRadius)
indirect case array([StyleProperty])
indirect case dimensionArray([UnitDimension])
// remember to update Equatable extension below if you add another case
}
public struct PropertyKey : RawRepresentable
{
public let rawValue : String
public init?(rawValue: String)
{
self.rawValue = rawValue
}
}
extension PropertyKey : Hashable
{
}
public struct GraphicStyle
{
public let key: PropertyKey
public let value: StyleProperty
public let important: Bool
public init(key: PropertyKey, value: StyleProperty, important: Bool = false)
{
self.key = key
self.value = value
self.important = important
}
public init(key: PropertyKey, value: String, important: Bool = false)
{
self.init(key: key, value: StyleProperty.string(value), important: important)
}
/**
convenient alternate init for creating a graphic style from a constant # style colour description
**/
public init(key: PropertyKey, hexColour: String, important: Bool = false)
{
let colour = try! HexColourParser().deserializeString(source: hexColour)!
self.init(key: key, value: StyleProperty.colour(colour, colour.nativeColour), important: important)
}
/**
convenient alternate init for creating a graphic style from a constant named web colour description
**/
public init(key: PropertyKey, webColour: String, important: Bool = false)
{
let colour = try! WebColourParser().deserializeString(source: webColour)!
self.init(key: key, value: StyleProperty.colour(colour, colour.nativeColour), important: important)
}
}
/**
Such a context will be able to resolve an inherited property (for example by looking up the style chain)
**/
public protocol StyleContext
{
func resolve(property : GraphicStyle) -> StyleProperty?
func points(fromUnit unit: StyleUnit) -> NativeDimension?
var hairlineWidth : NativeDimension {get}
}
public extension StyleContext
{
// default implementation
func resolve(property : GraphicStyle) -> StyleProperty?
{
return property.value
}
// default implementation
func points(value: NativeDimension, fromUnit unit: StyleUnit) -> NativeDimension?
{
switch unit
{
case .point:
return value
default:
return nil
}
}
}
extension StyleProperty : Equatable
{
public static func == (lhs: StyleProperty, rhs: StyleProperty) -> Bool {
switch(lhs, rhs)
{
case (.string(let lhsString), .string(let rhsString)):
return lhsString == rhsString
case (.unitNumber(let lhsDimension), .unitNumber(let rhsDimension)):
return lhsDimension == rhsDimension
case (.number(let lhsNumber), .number(let rhsNumber)):
return lhsNumber == rhsNumber
case (.colour(let lhsColour, let lhsNative), .colour(let rhsColour, let rhsNative)):
return lhsColour == rhsColour && lhsNative == rhsNative
case (.boolean(let lhsBool), .boolean(let rhsBool)):
return lhsBool == rhsBool
case (.array(let lhsArray), .array(let rhsArray)):
return lhsArray == rhsArray
case (.fontStyle(let lhsStyle), .fontStyle(let rhsStyle)):
return lhsStyle == rhsStyle
case (.fontVariant(let lhsVariant), .fontVariant(let rhsVariant)):
return lhsVariant == rhsVariant
case (.fontFamilies(let lhsFamilies), .fontFamilies(let rhsFamilies)):
return lhsFamilies == rhsFamilies
case (.fontWeight(let lhsWeight), .fontWeight(let rhsWeight)):
return lhsWeight == rhsWeight
case (.fontDecorations(let lhsDecorations), .fontDecorations(let rhsDecorations)):
return lhsDecorations == rhsDecorations
case (.distance(let lhsHeight), .distance(let rhsHeight)):
return lhsHeight == rhsHeight
case (.fontSize(let lhsSize), .fontSize(let rhsSize)):
return lhsSize == rhsSize
case (.fontStretch(let lhsStretch), .fontStretch(let rhsStretch)):
return lhsStretch == rhsStretch
case (.lineCap(let lhsCap), .lineCap(let rhsCap)):
return lhsCap == rhsCap
case (.lineJoin(let lhsJoin), .lineJoin(let rhsJoin)):
return lhsJoin == rhsJoin
case (.dimensionArray(let lhsArray), .dimensionArray(let rhsArray)):
return lhsArray == rhsArray
case (.border(let lhsTypes), .border(let rhsTypes)):
return lhsTypes == rhsTypes
case (.cornerRadius(let lhsCorner), .cornerRadius(let rhsCorner)):
return lhsCorner == rhsCorner
default:
return false
}
}
}
extension GraphicStyle : Equatable
{
public static func == (lhs: GraphicStyle, rhs: GraphicStyle) -> Bool {
return lhs.important == rhs.important && lhs.key == rhs.key && lhs.value == rhs.value
}
}
public extension FontDescription
{
init(properties : [StyleProperty])
{
var fontSize : FontSize? = nil
var families : [FontFamily]? = nil
var weight : FontWeight? = nil
var stretch : FontStretch? = nil
var decorations : Set<TextDecoration>? = nil
var style : FontStyle? = nil
var variant : FontVariant? = nil
var lineHeight : Distance? = nil
for aProperty in properties
{
switch aProperty
{
case .fontDecorations(let newDecorations):
if let oldDecorations = decorations
{
decorations = oldDecorations.union(newDecorations)
}
else
{
decorations = newDecorations
}
case .fontFamilies(let newFamilies):
families = newFamilies
case .fontSize(let newSize):
fontSize = newSize
case .fontStretch(let newStretch):
stretch = newStretch
case .fontStyle(let newStyle):
style = newStyle
case .distance(let newLineHeight):
lineHeight = newLineHeight
case .fontVariant(let newVariant):
variant = newVariant
case .fontWeight(let newWeight):
weight = newWeight
default:
break
}
}
self.init(families: families ?? [.inherit],
size: fontSize ?? .inherit,
weight: weight ?? .inherit,
stretch: stretch ?? .inherit,
decorations: decorations ?? [.inherit],
style: style ?? .inherit,
variant: variant ?? .inherit,
lineHeight: lineHeight ?? .inherit)
}
}
| c4d67f3754ae84fc13619980f8612d6f | 31.816129 | 108 | 0.607097 | false | false | false | false |
rnystrom/GitHawk | refs/heads/master | Classes/Milestones/MilestoneViewModel.swift | mit | 1 | //
// MilestoneViewModel.swift
// Freetime
//
// Created by Ryan Nystrom on 6/3/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
struct MilestoneViewModel: ListSwiftDiffable {
let title: String
let due: String
let selected: Bool
// MARK: ListSwiftDiffable
var identifier: String {
return title
}
func isEqual(to value: ListSwiftDiffable) -> Bool {
guard let value = value as? MilestoneViewModel else { return false }
return due == value.due
&& selected == value.selected
}
}
| 7ed71fcb70495caf22f83bec040aa841 | 19.586207 | 76 | 0.656616 | false | false | false | false |
hironytic/Eventitic | refs/heads/master | Sources/Eventitic/EventSource.swift | mit | 1 | //
// EventSource.swift
// Eventitic
//
// Copyright (c) 2016-2018 Hironori Ichimiya <[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
private class UnlistenPool<T> {
var listeners: [Listener<T>] = []
}
///
/// This class represents a source of events.
///
public class EventSource<T> {
private var listeners: [Listener<T>]
private var unlistenPools: [UnlistenPool<T>]
///
/// Initializes an event source.
///
public init() {
listeners = []
unlistenPools = []
}
///
/// Begins listening to events.
///
/// - Parameter handler: A closure which handles events.
/// - Returns: A listener object.
///
public func listen(_ handler: @escaping (T) -> Void) -> Listener<T> {
let listener = Listener(eventSource: self, handler: handler)
listeners.append(listener)
return listener
}
func unlisten(_ listener: Listener<T>) {
if let pool = unlistenPools.last {
pool.listeners.append(listener)
} else {
if let index = listeners.firstIndex(of: listener) {
listeners.remove(at: index)
}
}
}
///
/// Dispaches an event to its listeners.
///
/// - Parameter value: An event value.
///
public func fire(_ value: T) {
unlistenPools.append(UnlistenPool<T>())
listeners.forEach { listener in
listener.handleEvent(value)
}
let pool = unlistenPools.removeLast()
if pool.listeners.count > 0 {
listeners = listeners.filter { !pool.listeners.contains($0) }
}
}
}
| 4921158de9a1f338d323097e7e2fd8f2 | 30.436782 | 80 | 0.64351 | false | false | false | false |
guidomb/Portal | refs/heads/master | Portal/View/Components/NavigationBar.swift | mit | 1 | //
// NavigationBar.swift
// PortalView
//
// Created by Guido Marucci Blas on 1/27/17.
//
//
import Foundation
public enum NavigationBarTitle<MessageType> {
case text(String)
case image(Image)
case component(Component<MessageType>)
}
public enum NavigationBarButton<MessageType> {
case textButton(title: String, onTap: MessageType)
case imageButton(icon: Image, onTap: MessageType)
}
public struct NavigationBarProperties<MessageType> {
public var title: NavigationBarTitle<MessageType>?
public var backButtonTitle: String?
public var onBack: MessageType?
public var leftButtonItems: [NavigationBarButton<MessageType>]?
public var rightButtonItems: [NavigationBarButton<MessageType>]?
fileprivate init(
title: NavigationBarTitle<MessageType>? = .none,
backButtonTitle: String? = .none,
onBack: MessageType? = .none,
leftButtonItems: [NavigationBarButton<MessageType>]? = .none,
rightButtonItems: [NavigationBarButton<MessageType>]? = .none) {
self.title = title
self.backButtonTitle = backButtonTitle
self.onBack = onBack
self.leftButtonItems = leftButtonItems
self.rightButtonItems = rightButtonItems
}
}
public struct NavigationBar<MessageType> {
public let properties: NavigationBarProperties<MessageType>
public let style: StyleSheet<NavigationBarStyleSheet>
fileprivate init(properties: NavigationBarProperties<MessageType>, style: StyleSheet<NavigationBarStyleSheet>) {
self.properties = properties
self.style = style
}
}
public func navigationBar<MessageType>(
properties: NavigationBarProperties<MessageType>,
style: StyleSheet<NavigationBarStyleSheet> = navigationBarStyleSheet()) -> NavigationBar<MessageType> {
return NavigationBar(properties: properties, style: style)
}
public func navigationBar<MessageType>(
title: String,
onBack: MessageType,
style: StyleSheet<NavigationBarStyleSheet> = navigationBarStyleSheet()) -> NavigationBar<MessageType> {
return NavigationBar(
properties: properties {
$0.title = .text(title)
$0.onBack = onBack
},
style: style
)
}
public func navigationBar<MessageType>(
title: Image,
onBack: MessageType,
style: StyleSheet<NavigationBarStyleSheet> = navigationBarStyleSheet()) -> NavigationBar<MessageType> {
return NavigationBar(
properties: properties {
$0.title = .image(title)
$0.onBack = onBack
},
style: style
)
}
public func properties<MessageType>(
configure: (inout NavigationBarProperties<MessageType>) -> Void) -> NavigationBarProperties<MessageType> {
var properties = NavigationBarProperties<MessageType>()
configure(&properties)
return properties
}
// MARK: - Style sheet
public let defaultNavigationBarTitleFontSize: UInt = 17
public struct NavigationBarStyleSheet {
public static let `default` = StyleSheet<NavigationBarStyleSheet>(component: NavigationBarStyleSheet())
public var tintColor: Color
public var titleTextColor: Color
public var titleTextFont: Font
public var titleTextSize: UInt
public var isTranslucent: Bool
public var statusBarStyle: StatusBarStyle
public var separatorHidden: Bool
fileprivate init(
tintColor: Color = .black,
titleTextColor: Color = .black,
titleTextFont: Font = defaultFont,
titleTextSize: UInt = defaultNavigationBarTitleFontSize,
isTranslucent: Bool = true,
statusBarStyle: StatusBarStyle = .`default`,
separatorHidden: Bool = false) {
self.tintColor = tintColor
self.titleTextFont = titleTextFont
self.titleTextColor = titleTextColor
self.titleTextSize = titleTextSize
self.isTranslucent = isTranslucent
self.statusBarStyle = statusBarStyle
self.separatorHidden = separatorHidden
}
}
public func navigationBarStyleSheet(
configure: (inout BaseStyleSheet, inout NavigationBarStyleSheet) -> Void = { _, _ in }
) -> StyleSheet<NavigationBarStyleSheet> {
var base = BaseStyleSheet()
var component = NavigationBarStyleSheet()
configure(&base, &component)
return StyleSheet(component: component, base: base)
}
| c90e13743ca01a7c72e546db1bede61a | 29.908451 | 116 | 0.698337 | false | false | false | false |
rheinfabrik/Dobby | refs/heads/master | Dobby/Stub.swift | apache-2.0 | 2 | /// A matcher-based behavior with closure-based handling.
fileprivate struct Behavior<Interaction, ReturnValue> {
/// The matcher of this behavior.
fileprivate let matcher: Matcher<Interaction>
/// The handler of this behavior.
fileprivate let handler: (Interaction) -> ReturnValue
/// Initializes a new behavior with the given matcher and handler.
fileprivate init<M: MatcherConvertible>(matcher: M, handler: @escaping (Interaction) -> ReturnValue) where M.ValueType == Interaction {
self.matcher = matcher.matcher()
self.handler = handler
}
}
/// A stub error.
public enum StubError<Interaction, ReturnValue>: Error {
/// The associated interaction was unexpected.
case unexpectedInteraction(Interaction)
}
/// A stub that, when invoked, returns a value based on the set up behavior, or,
/// if an interaction is unexpected, throws an error.
public final class Stub<Interaction, ReturnValue> {
/// The current (next) identifier for behaviors.
private var currentIdentifier: UInt = 0
/// The behaviors of this stub.
private var behaviors: [(identifier: UInt, behavior: Behavior<Interaction, ReturnValue>)] = []
/// Initializes a new stub.
public init() {
}
/// Modifies the behavior of this stub, forwarding invocations to the given
/// function and returning its return value if the given matcher does match
/// an interaction.
///
/// Returns a disposable that, when disposed, removes this behavior.
@discardableResult
public func on<M: MatcherConvertible>(_ matcher: M, invoke handler: @escaping (Interaction) -> ReturnValue) -> Disposable where M.ValueType == Interaction {
currentIdentifier += 1
let identifier = currentIdentifier
let behavior = Behavior(matcher: matcher, handler: handler)
behaviors.append((identifier: identifier, behavior: behavior))
return Disposable { [weak self] in
let index = self?.behaviors.index { otherIdentifier, _ in
return otherIdentifier == identifier
}
if let index = index {
self?.behaviors.remove(at: index)
}
}
}
/// Modifies the behavior of this stub, returning the given value upon
/// invocation if the given matcher does match an interaction.
///
/// Returns a disposable that, when disposed, removes this behavior.
///
/// - SeeAlso: `Stub.on<M>(matcher: M, invoke: Interaction -> ReturnValue) -> Disposable`
@discardableResult
public func on<M: MatcherConvertible>(_ matcher: M, return value: ReturnValue) -> Disposable where M.ValueType == Interaction {
return on(matcher) { _ in value }
}
/// Invokes this stub, returning a value based on the set up behavior, or,
/// if the given interaction is unexpected, throwing an error.
///
/// Behavior is matched in order, i.e., the function associated with the
/// first matcher that matches the given interaction is invoked.
///
/// - Throws: `StubError.unexpectedInteraction(Interaction)` if the given
/// interaction is unexpected.
@discardableResult
public func invoke(_ interaction: Interaction) throws -> ReturnValue {
for (_, behavior) in behaviors {
if behavior.matcher.matches(interaction) {
return behavior.handler(interaction)
}
}
throw StubError<Interaction, ReturnValue>.unexpectedInteraction(interaction)
}
}
| 4e55f5902bc85621b00e556e91344bd4 | 38.707865 | 160 | 0.667516 | false | false | false | false |
Tomikes/eidolon | refs/heads/master | Kiosk/Help/HelpViewController.swift | mit | 5 | import UIKit
import ORStackView
import Artsy_UILabels
import Artsy_UIButtons
import Swift_RAC_Macros
import ReactiveCocoa
class HelpViewController: UIViewController {
var positionConstraints: [NSLayoutConstraint]?
var dismissTapGestureRecognizer: UITapGestureRecognizer?
private let stackView = ORTagBasedAutoStackView()
private var buyersPremiumButton: UIButton!
private let sideMargin: Float = 90.0
private let topMargin: Float = 45.0
private let headerMargin: Float = 25.0
private let inbetweenMargin: Float = 10.0
var showBuyersPremiumCommand = { () -> RACCommand in
appDelegate().showBuyersPremiumCommand()
}
var registerToBidCommand = { (enabledSignal: RACSignal) -> RACCommand in
appDelegate().registerToBidCommand(enabledSignal)
}
var requestBidderDetailsCommand = { (enabledSignal: RACSignal) -> RACCommand in
appDelegate().requestBidderDetailsCommand(enabledSignal)
}
var showPrivacyPolicyCommand = { () -> RACCommand in
appDelegate().showPrivacyPolicyCommand()
}
var showConditionsOfSaleCommand = { () -> RACCommand in
appDelegate().showConditionsOfSaleCommand()
}
lazy var hasBuyersPremiumSignal: RACSignal = {
RACObserve(appDelegate().appViewController, "sale.buyersPremium").notNil()
}()
class var width: Float {
get {
return 415.0
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Configure view
view.backgroundColor = .whiteColor()
addSubviews()
}
}
private extension HelpViewController {
enum SubviewTag: Int {
case AssistanceLabel = 0
case StuckLabel, StuckExplainLabel
case BidLabel, BidExplainLabel
case RegisterButton
case BidderDetailsLabel, BidderDetailsExplainLabel, BidderDetailsButton
case ConditionsOfSaleButton, BuyersPremiumButton, PrivacyPolicyButton
}
func addSubviews() {
// Configure subviews
let assistanceLabel = ARSerifLabel()
assistanceLabel.font = assistanceLabel.font.fontWithSize(35)
assistanceLabel.text = "Assistance"
assistanceLabel.tag = SubviewTag.AssistanceLabel.rawValue
let stuckLabel = titleLabel(.StuckLabel, title: "Stuck in the process?")
let stuckExplainLabel = wrappingSerifLabel(.StuckExplainLabel, text: "Find the nearest Artsy representative and they will assist you.")
let bidLabel = titleLabel(.BidLabel, title: "How do I place a bid?")
let bidExplainLabel = wrappingSerifLabel(.BidExplainLabel, text: "Enter the amount you would like to bid. You will confirm this bid in the next step. Enter your mobile number or bidder number and PIN that you received when you registered.")
bidExplainLabel.makeSubstringsBold(["mobile number", "bidder number", "PIN"])
let registerButton = blackButton(.RegisterButton, title: "Register")
registerButton.rac_command = registerToBidCommand(reachabilityManager.reachSignal)
let bidderDetailsLabel = titleLabel(.BidderDetailsLabel, title: "What Are Bidder Details?")
let bidderDetailsExplainLabel = wrappingSerifLabel(.BidderDetailsExplainLabel, text: "The bidder number is how you can identify yourself to bid and see your place in bid history. The PIN is a four digit number that authenticates your bid.")
bidderDetailsExplainLabel.makeSubstringsBold(["bidder number", "PIN"])
let sendDetailsButton = blackButton(.BidderDetailsButton, title: "Send me my details")
sendDetailsButton.rac_command = requestBidderDetailsCommand(reachabilityManager.reachSignal)
let conditionsButton = serifButton(.ConditionsOfSaleButton, title: "Conditions of Sale")
conditionsButton.rac_command = showConditionsOfSaleCommand()
buyersPremiumButton = serifButton(.BuyersPremiumButton, title: "Buyers Premium")
buyersPremiumButton.rac_command = showBuyersPremiumCommand()
let privacyButton = serifButton(.PrivacyPolicyButton, title: "Privacy Policy")
privacyButton.rac_command = showPrivacyPolicyCommand()
// Add subviews
view.addSubview(stackView)
stackView.alignTop("0", leading: "0", bottom: nil, trailing: "0", toView: view)
stackView.addSubview(assistanceLabel, withTopMargin: "\(topMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(stuckLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(stuckExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(bidLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(bidExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(registerButton, withTopMargin: "20", sideMargin: "\(sideMargin)")
stackView.addSubview(bidderDetailsLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(bidderDetailsExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(sendDetailsButton, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(conditionsButton, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(privacyButton, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(self.sideMargin)")
hasBuyersPremiumSignal.subscribeNext { [weak self] in
let hasBuyersPremium = $0 as! Bool
if hasBuyersPremium {
self?.stackView.addSubview(self!.buyersPremiumButton, withTopMargin: "\(self!.inbetweenMargin)", sideMargin: "\(self!.sideMargin)")
} else {
self?.stackView.removeSubview(self!.buyersPremiumButton)
}
}
}
func blackButton(tag: SubviewTag, title: String) -> ARBlackFlatButton {
let button = ARBlackFlatButton()
button.setTitle(title, forState: .Normal)
button.tag = tag.rawValue
return button
}
func serifButton(tag: SubviewTag, title: String) -> ARUnderlineButton {
let button = ARUnderlineButton()
button.setTitle(title, forState: .Normal)
button.setTitleColor(.artsyHeavyGrey(), forState: .Normal)
button.titleLabel?.font = UIFont.serifFontWithSize(18)
button.contentHorizontalAlignment = .Left
button.tag = tag.rawValue
return button
}
func wrappingSerifLabel(tag: SubviewTag, text: String) -> UILabel {
let label = ARSerifLabel()
label.font = label.font.fontWithSize(18)
label.lineBreakMode = .ByWordWrapping
label.preferredMaxLayoutWidth = CGFloat(HelpViewController.width - sideMargin)
label.tag = tag.rawValue
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
label.attributedText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName: paragraphStyle])
return label
}
func titleLabel(tag: SubviewTag, title: String) -> ARSerifLabel {
let label = ARSerifLabel()
label.font = label.font.fontWithSize(24)
label.text = title
label.tag = tag.rawValue
return label
}
}
| e8b2bf37583c2b285640f0fca03918f2 | 42.571429 | 248 | 0.680262 | false | false | false | false |
guidomb/Portal | refs/heads/master | Portal/Middlewares/TimeLogger.swift | mit | 1 | //
// TimeLogger.swift
// Portal
//
// Created by Guido Marucci Blas on 4/12/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import Foundation
public final class TimeLogger<StateType, MessageType, CommandType>: MiddlewareProtocol {
public typealias Transition = (StateType, CommandType?)?
public typealias NextMiddleware = (StateType, MessageType, CommandType?) -> Transition
public typealias Logger = (String) -> Void
public var log: Logger
public var isEnabled: Bool = true
public init(log: @escaping Logger = { print($0) }) {
self.log = log
}
public func call(
state: StateType,
message: MessageType,
command: CommandType?,
next: NextMiddleware) -> Transition {
let timestamp = Date.timeIntervalSinceReferenceDate
let result = next(state, message, command)
let dispatchTime = ((Date.timeIntervalSinceReferenceDate - timestamp) * 100000).rounded() / 100
if isEnabled {
log("Dispatch time \(dispatchTime)ms")
}
return result
}
}
| ecc331403cebef729f97585ae9143722 | 26.902439 | 103 | 0.628497 | false | false | false | false |
Lee-junha/tvOS-controller | refs/heads/master | tvOS-controller/PlayersViewController.swift | mit | 1 | //
// PlayersViewController.swift
// tvOS-controller
//
// Created by Lauren Brown on 16/11/2015.
// Copyright © 2015 Fluid Pixel Limited. All rights reserved.
//
import UIKit
import SceneKit
class PlayersViewController: UIViewController, TVCTVSessionDelegate {
@IBOutlet weak var CarView1: SCNView!
@IBOutlet weak var CarView2: SCNView!
@IBOutlet weak var CarView3: SCNView!
@IBOutlet weak var CarView4: SCNView!
var players = [GameObject]()
var numberOfPlayers = 0
let MAX_NUMBER_OF_PLAYERS = 4
var carScene = SCNScene()
//ready confirmation
@IBOutlet weak var ready1: UILabel!
@IBOutlet weak var Ready2: UILabel!
@IBOutlet weak var Ready3: UILabel!
@IBOutlet weak var Ready4: UILabel!
//lights
var lightNode1 = SCNNode()
var lightNode2 = SCNNode()
var lightNode3 = SCNNode()
var lightNode4 = SCNNode()
// cameras
let cameraNode1 = SCNNode()
let cameraNode2 = SCNNode()
let cameraNode3 = SCNNode()
let cameraNode4 = SCNNode()
//array to neaten things up
var PlayerViews = [SCNView!]()
let remote = TVCTVSession()
@IBOutlet weak var Player1ColourLabel: UILabel!
@IBOutlet weak var PlayerNumberLabel: UILabel!
@IBOutlet weak var StatusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
prepareScenes()
self.remote.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "StartGame" {
if let vc = segue.destination as? ViewController {
vc.gameObjects = players
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func prepareScenes() {
//prepare all at the start and only light them up when a player joins
//
CarView1.scene = SCNScene()
CarView2.scene = SCNScene()
CarView3.scene = SCNScene()
CarView4.scene = SCNScene()
PlayerViews = [CarView1, CarView2, CarView3, CarView4]
//setup cameras
let camera = SCNCamera()
cameraNode1.camera = camera
cameraNode2.camera = camera
cameraNode3.camera = camera
cameraNode4.camera = camera
cameraNode1.position = SCNVector3(10, 5, 10)
cameraNode2.position = SCNVector3(10, 5, 10)
cameraNode3.position = SCNVector3(10, 5, 10)
cameraNode4.position = SCNVector3(10, 5, 10)
let light = SCNLight()
light.type = SCNLight.LightType.spot
lightNode1.light = light
lightNode2.light = light
lightNode3.light = light
lightNode4.light = light
lightNode1.position = SCNVector3(0, 50, 0)
lightNode2.position = SCNVector3(0, 50, 0)
lightNode3.position = SCNVector3(0, 50, 0)
lightNode4.position = SCNVector3(0, 50, 0)
// //add camera and light to views
// CarView1.scene!.rootNode.addChildNode(cameraNode1)
// CarView2.scene!.rootNode.addChildNode(cameraNode2)
// CarView3.scene!.rootNode.addChildNode(cameraNode3)
// CarView4.scene!.rootNode.addChildNode(cameraNode4)
}
func addNewPlayer(_ device : String) {
numberOfPlayers = numberOfPlayers + 1
var newPlayer = GameObject()
newPlayer.playerID = device
newPlayer.ID = numberOfPlayers
newPlayer.colourID = numberOfPlayers
PlayerNumberLabel.text = "\(numberOfPlayers)/\(MAX_NUMBER_OF_PLAYERS)"
if numberOfPlayers == MAX_NUMBER_OF_PLAYERS {
StatusLabel.text = "All Players Ready!"
}
switch numberOfPlayers {
case 1:
AddPlayerToScreen(CarView1, lightNode: lightNode1, cameraNode: cameraNode1)
break
case 2:
AddPlayerToScreen(CarView2, lightNode: lightNode2, cameraNode: cameraNode2)
break
case 3:
AddPlayerToScreen(CarView3, lightNode: lightNode3, cameraNode: cameraNode3)
break
case 4:
AddPlayerToScreen(CarView4, lightNode: lightNode4, cameraNode: cameraNode4)
break
default:
break
}
players.append(newPlayer)
}
func AddPlayerToScreen(_ view : SCNView, lightNode : SCNNode, cameraNode : SCNNode) {
if let carScene : SCNScene = SCNScene(named: "gameAssets.scnassets/rc_car.dae") {
if let node = carScene.rootNode.childNode(withName: "rccarBody", recursively: false) {
node.position = SCNVector3Make(0, 0, 0)
node.rotation = SCNVector4Make(0, 1, 0, Float(M_PI))
node.physicsBody = SCNPhysicsBody.static()
node.name = "Car"
let action = SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 0.5, z: 0, duration: 0.5))
node.runAction(action)
let constraint = SCNLookAtConstraint(target: node)
lightNode.constraints = [constraint]
cameraNode.rotation = SCNVector4(0, 1, 0, 0.7)
view.scene?.rootNode.addChildNode(node)
view.scene?.rootNode.addChildNode(lightNode)
view.scene?.rootNode.addChildNode(cameraNode)
}
}
}
func removePlayerFromScreen() {
}
func changePlayerColour(_ i : Int, playerFromDevice: String) {
numberOfPlayers = numberOfPlayers + 1
for j in 0 ..< numberOfPlayers {
if players[j].playerID == playerFromDevice {
if let node = PlayerViews[j].scene!.rootNode.childNode(withName: "Car", recursively: false) {
players[j].colourID = (players[j].colourID + i) % 9
node.geometry?.materials[0].diffuse.contents = players[j].GetColour(players[j].colourID)
}
}
}
}
func playerIsReady(_ playerFromDevice : String) {
numberOfPlayers = numberOfPlayers + 1
for j in 0 ..< numberOfPlayers {
if players[j].playerID == playerFromDevice {
switch j {
case 0:
ready1.isHidden = !ready1.isHidden
break
case 1:
Ready2.isHidden = !Ready2.isHidden
break
case 2:
Ready3.isHidden = !Ready3.isHidden
break
case 3:
Ready4.isHidden = !Ready4.isHidden
break
default:
break
}
}
}
}
func deviceDidConnect(_ device: String) {
print("Player joined!")
addNewPlayer(device)
}
func deviceDidDisconnect(_ device: String) {
print("Player left! :(")
// numberOfPlayers -= 1
//
// //remove player from list
// var count = players.count
// count = count + 1
// for i in 0 ..< count {
// if players[i].playerID == device {
// players.remove(at: i)
// }
// }
}
internal func didReceiveMessage(_ message: [String : Any], fromDevice: String, replyHandler: ([String : Any]) -> Void) {
print("received message with reply handler")
if message.keys.first! == "Colour" {
changePlayerColour(message.values.first as! Int, playerFromDevice: fromDevice)
} else if message.keys.first == "Ready" {
playerIsReady(fromDevice)
}
//join game
//addNewPlayer(fromDevice)
}
internal func didReceiveMessage(_ message: [String : Any], fromDevice: String) {
print("received message")
//join game
//addNewPlayer(fromDevice)
}
}
| 980437d9c90ffe004a1024f38f3a7044 | 31.299625 | 124 | 0.570733 | false | false | false | false |
dreamsxin/swift | refs/heads/master | test/Serialization/Inputs/def_class.swift | apache-2.0 | 3 | public class Empty {}
@swift3_migration(renamed: "DosInts", message: "because I can")
public class TwoInts {
public var x, y : Int
required public init(a : Int, b : Int) {
x = a
y = b
}
}
public class ComputedProperty {
@swift3_migration(renamed: "theValue", message: "because I can")
public var value : Int {
get {
var result = 0
return result
}
set(newVal) {
// completely ignore it!
}
}
@swift3_migration(message: "something else")
public var readOnly : Int {
return 42
}
public init() {}
}
// Generics
public class Pair<A, B> {
public var first : A
public var second : B
public init(a : A, b : B) {
first = a
second = b
}
}
public class GenericCtor<U> {
public init<T>(_ t : T) {}
public func doSomething<T>(_ t : T) {}
}
// Protocols
public protocol Resettable {
func reset()
}
public extension Resettable {
final func doReset() { self.reset() }
}
public class ResettableIntWrapper : Resettable {
public var value : Int
public init() { value = 0 }
public func reset() {
var zero = 0
value = zero
}
}
public protocol Computable {
func compute()
}
public typealias Cacheable = protocol<Resettable, Computable>
public protocol SpecialResettable : Resettable, Computable {}
public protocol PairLike {
associatedtype FirstType
associatedtype SecondType
func getFirst() -> FirstType
func getSecond() -> SecondType
}
public extension PairLike where FirstType : Cacheable {
final func cacheFirst() { }
}
public protocol ClassProto : class {}
@objc public protocol ObjCProtoWithOptional {
@objc optional func optionalMethod()
@objc optional var optionalVar: Int { get }
@objc optional subscript (i: Int) -> Int { get }
}
public class OptionalImplementer : ObjCProtoWithOptional {
public func unrelated() {}
public init() {}
}
// Inheritance
public class StillEmpty : Empty, Resettable {
public func reset() {}
public override init() {}
}
public class BoolPair<T> : Pair<Bool, Bool>, PairLike {
public init() { super.init(a: false, b: false) }
public func bothTrue() -> Bool {
return first && second
}
public func getFirst() -> Bool { return first }
public func getSecond() -> Bool { return second }
}
public class SpecialPair<A> : Pair<Int, Int>, Computable {
public func compute() {}
}
public class OtherPair<A, B> : PairLike {
public var first : A
public var second : B
public init(a : A, b : B) {
first = a
second = b
}
public typealias FirstType = Bool
public typealias SecondType = Bool
public func getFirst() -> Bool { return true }
public func getSecond() -> Bool { return true }
}
public class OtherBoolPair<T> : OtherPair<Bool, Bool> {
}
public class RequiresPairLike<P : PairLike> { }
public func getReqPairLike() -> RequiresPairLike<OtherBoolPair<Bool>> {
return RequiresPairLike<OtherBoolPair<Bool>>()
}
// Subscripts
public class ReadonlySimpleSubscript {
public subscript(x : Int) -> Bool {
return true
}
public init() {}
}
public class ComplexSubscript {
public subscript(x : Int, y : Bool) -> Int {
set(newValue) {
// do nothing!
}
get {
return 0
}
}
public init() {}
}
// Destructor
public class Resource {
public init() { }
deinit {}
}
// Ownership
public class ResourceSharer {
// FIXME: Cannot perform in-class initialization here
public unowned var alwaysPresent : Resource
public weak var maybePresent : Resource?
public init (res: Resource) {
self.alwaysPresent = res
self.maybePresent = nil
}
}
| d18b9a81c63b1f44cc17f6899c8e8a61 | 18.164894 | 72 | 0.659173 | false | false | false | false |
CatchChat/Yep | refs/heads/master | Yep/Views/SkillHomeHeaderView/SkillHomeHeaderView.swift | mit | 1 | //
// SkillHomeHeaderView.swift
// Yep
//
// Created by kevinzhow on 15/5/6.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import Kingfisher
final class SkillHomeHeaderView: UIView {
var skillCategory: SkillCellSkill.Category = .Art
var skillCoverURLString: String? {
willSet {
// if let coverURLString = newValue, URL = NSURL(string: coverURLString) {
// headerImageView.kf_setImageWithURL(URL, placeholderImage: skillCategory.gradientImage)
//
// } else {
// headerImageView.image = skillCategory.gradientImage
// }
}
}
lazy var headerImageView: UIImageView = {
let tempImageView = UIImageView(frame: CGRectZero)
tempImageView.contentMode = .ScaleAspectFill
tempImageView.clipsToBounds = true
tempImageView.backgroundColor = UIColor.whiteColor()
return tempImageView;
}()
lazy var masterButton: SkillHomeSectionButton = {
let button = createSkillHomeButtonWithText(SkillSet.Master.name, width: 100, height: YepConfig.skillHomeHeaderButtonHeight)
return button
}()
lazy var learningButton: SkillHomeSectionButton = {
let button = createSkillHomeButtonWithText(SkillSet.Learning.name, width: 100, height: YepConfig.skillHomeHeaderButtonHeight)
return button
}()
var changeCoverAction: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
addSubview(headerImageView)
addSubview(masterButton)
addSubview(learningButton)
backgroundColor = UIColor.lightGrayColor()
headerImageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(SkillHomeHeaderView.tap))
headerImageView.addGestureRecognizer(tap)
}
func tap() {
changeCoverAction?()
}
override func layoutSubviews() {
super.layoutSubviews()
headerImageView.frame = self.bounds
masterButton.frame = CGRectMake(0, self.frame.height - YepConfig.skillHomeHeaderButtonHeight, self.frame.size.width/2.0, YepConfig.skillHomeHeaderButtonHeight)
masterButton.updateHightLightBounce()
learningButton.frame = CGRectMake(masterButton.frame.size.width, self.frame.height - YepConfig.skillHomeHeaderButtonHeight, self.frame.size.width/2.0, YepConfig.skillHomeHeaderButtonHeight)
learningButton.updateHightLightBounce()
}
}
| 9d2cfe638a87458f93b69782ae31a91f | 29.144444 | 197 | 0.670107 | false | true | false | false |
jpsim/SourceKitten | refs/heads/main | Source/SourceKittenFramework/String+SourceKitten.swift | mit | 1 | import Foundation
/**
* For "wall of asterisk" comment blocks, such as this one.
*/
private let commentLinePrefixCharacterSet: CharacterSet = {
var characterSet = CharacterSet.whitespacesAndNewlines
characterSet.insert(charactersIn: "*")
return characterSet
}()
// swiftlint:disable:next line_length
// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/swift/grammar/line-break
private let newlinesCharacterSet = CharacterSet(charactersIn: "\u{000A}\u{000D}")
extension String {
internal var isFile: Bool {
var isDirectory: ObjCBool = false
let exists = FileManager.default.fileExists(atPath: self, isDirectory: &isDirectory)
return exists && !isDirectory.boolValue
}
/**
Returns true if self is an Objective-C header file.
*/
public func isObjectiveCHeaderFile() -> Bool {
return ["h", "hpp", "hh"].contains(bridge().pathExtension)
}
/// A version of the string with backslash escapes removed.
public var unescaped: String {
struct UnescapingSequence: Sequence, IteratorProtocol {
var iterator: String.Iterator
mutating func next() -> Character? {
guard let char = iterator.next() else { return nil }
guard char == "\\" else { return char }
return iterator.next()
}
}
return String(UnescapingSequence(iterator: makeIterator()))
}
/**
Returns true if self is a Swift file.
*/
public func isSwiftFile() -> Bool {
return bridge().pathExtension == "swift"
}
/**
Returns the body of the comment if the string is a comment.
- parameter range: Range to restrict the search for a comment body.
*/
public func commentBody(range: NSRange? = nil) -> String? {
let nsString = bridge()
let patterns: [(pattern: String, options: NSRegularExpression.Options)] = [
("^\\s*\\/\\*\\*\\s*(.*?)\\*\\/", [.anchorsMatchLines, .dotMatchesLineSeparators]), // multi: ^\s*\/\*\*\s*(.*?)\*\/
("^\\s*\\/\\/\\/(.+)?", .anchorsMatchLines) // single: ^\s*\/\/\/(.+)?
// swiftlint:disable:previous comma
]
let range = range ?? NSRange(location: 0, length: nsString.length)
for pattern in patterns {
let regex = try! NSRegularExpression(pattern: pattern.pattern, options: pattern.options) // Safe to force try
let matches = regex.matches(in: self, options: [], range: range)
let bodyParts = matches.flatMap { match -> [String] in
let numberOfRanges = match.numberOfRanges
if numberOfRanges < 1 {
return []
}
return (1..<numberOfRanges).map { rangeIndex in
let range = match.range(at: rangeIndex)
if range.location == NSNotFound {
return "" // empty capture group, return empty string
}
var lineStart = 0
var lineEnd = nsString.length
let indexRange = NSRange(location: range.location, length: 0)
nsString.getLineStart(&lineStart, end: &lineEnd, contentsEnd: nil, for: indexRange)
let leadingWhitespaceCountToAdd = nsString.substring(with: NSRange(location: lineStart, length: lineEnd - lineStart))
.countOfLeadingCharacters(in: .whitespacesAndNewlines)
let leadingWhitespaceToAdd = String(repeating: " ", count: leadingWhitespaceCountToAdd)
let bodySubstring = nsString.substring(with: range)
if bodySubstring.contains("@name") {
return "" // appledoc directive, return empty string
}
return leadingWhitespaceToAdd + bodySubstring
}
}
if !bodyParts.isEmpty {
return bodyParts.joined(separator: "\n").bridge()
.trimmingTrailingCharacters(in: .whitespacesAndNewlines)
.removingCommonLeadingWhitespaceFromLines()
}
}
return nil
}
/**
Returns the number of contiguous characters at the start of `self` belonging to `characterSet`.
- parameter characterSet: Character set to check for membership.
*/
public func countOfLeadingCharacters(in characterSet: CharacterSet) -> Int {
let characterSet = characterSet.bridge()
var count = 0
for char in utf16 {
if !characterSet.characterIsMember(char) {
break
}
count += 1
}
return count
}
/**
Returns a copy of `self` with the trailing contiguous characters belonging to `characterSet`
removed.
- parameter characterSet: Character set to check for membership.
*/
public func trimmingTrailingCharacters(in characterSet: CharacterSet) -> String {
guard !isEmpty else {
return ""
}
var unicodeScalars = self.bridge().unicodeScalars
while let scalar = unicodeScalars.last {
if !characterSet.contains(scalar) {
return String(unicodeScalars)
}
unicodeScalars.removeLast()
}
return ""
}
/// Returns a copy of `self` with the leading whitespace common in each line removed.
public func removingCommonLeadingWhitespaceFromLines() -> String {
var minLeadingCharacters = Int.max
let lineComponents = components(separatedBy: newlinesCharacterSet)
for line in lineComponents {
let lineLeadingWhitespace = line.countOfLeadingCharacters(in: .whitespacesAndNewlines)
let lineLeadingCharacters = line.countOfLeadingCharacters(in: commentLinePrefixCharacterSet)
// Is this prefix smaller than our last and not entirely whitespace?
if lineLeadingCharacters < minLeadingCharacters && lineLeadingWhitespace != line.count {
minLeadingCharacters = lineLeadingCharacters
}
}
return lineComponents.map { line in
if line.count >= minLeadingCharacters {
return String(line[line.index(line.startIndex, offsetBy: minLeadingCharacters)...])
}
return line
}.joined(separator: "\n")
}
internal func capitalizingFirstLetter() -> String {
return String(prefix(1)).capitalized + String(dropFirst())
}
}
extension NSString {
/**
Returns self represented as an absolute path.
- parameter rootDirectory: Absolute parent path if not already an absolute path.
*/
public func absolutePathRepresentation(rootDirectory: String = FileManager.default.currentDirectoryPath) -> String {
if isAbsolutePath { return bridge() }
#if os(Linux)
return NSURL(fileURLWithPath: NSURL.fileURL(withPathComponents: [rootDirectory, bridge()])!.path).standardizingPath!.path
#else
return NSString.path(withComponents: [rootDirectory, bridge()]).bridge().standardizingPath
#endif
}
}
extension Array where Element == String {
/// Return the full list of compiler arguments, replacing any response files with their contents.
var expandingResponseFiles: [String] {
return flatMap { arg -> [String] in
guard arg.starts(with: "@") else {
return [arg]
}
let responseFile = String(arg.dropFirst())
return (try? String(contentsOf: URL(fileURLWithPath: responseFile))).flatMap {
$0.trimmingCharacters(in: .newlines)
.components(separatedBy: "\n")
.map { $0.unescaped }
.expandingResponseFiles
} ?? [arg]
}
}
}
extension String {
/// Returns a copy of the string by trimming whitespace and the opening curly brace (`{`).
internal func trimmingWhitespaceAndOpeningCurlyBrace() -> String? {
var unwantedSet = CharacterSet.whitespacesAndNewlines
unwantedSet.insert(charactersIn: "{")
return trimmingCharacters(in: unwantedSet)
}
/// Returns the byte offset of the section of the string following the last dot ".", or 0 if no dots.
internal func byteOffsetOfInnerTypeName() -> ByteCount {
return range(of: ".", options: .backwards).map { range in
return ByteCount(self[...range.lowerBound].lengthOfBytes(using: .utf8))
} ?? 0
}
}
| 9136164524f832c253e2db16dc667096 | 39.170507 | 163 | 0.606975 | false | false | false | false |
stephentyrone/swift | refs/heads/master | test/Parse/switch.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int,Int), y: (Int,Int)) -> Bool {
return true
}
func parseError1(x: Int) {
switch func {} // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}} expected-error {{expected identifier in function declaration}} expected-error {{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{15-15=do }}
}
func parseError2(x: Int) {
switch x // expected-error {{expected '{' after 'switch' subject expression}}
}
func parseError3(x: Int) {
switch x {
case // expected-error {{expected pattern}} expected-error {{expected ':' after 'case'}}
}
}
func parseError4(x: Int) {
switch x {
case var z where // expected-error {{expected expression for 'where' guard of 'case'}} expected-error {{expected ':' after 'case'}}
}
}
func parseError5(x: Int) {
switch x {
case let z // expected-error {{expected ':' after 'case'}} expected-warning {{immutable value 'z' was never used}} {{12-13=_}}
}
}
func parseError6(x: Int) {
switch x {
default // expected-error {{expected ':' after 'default'}}
}
}
var x: Int
switch x {} // expected-error {{'switch' statement body must have at least one 'case' or 'default' block}}
switch x {
case 0:
x = 0
// Multiple patterns per case
case 1, 2, 3:
x = 0
// 'where' guard
case _ where x % 2 == 0:
x = 1
x = 2
x = 3
case _ where x % 2 == 0,
_ where x % 3 == 0:
x = 1
case 10,
_ where x % 3 == 0:
x = 1
case _ where x % 2 == 0,
20:
x = 1
case var y where y % 2 == 0:
x = y + 1
case _ where 0: // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
x = 0
default:
x = 1
}
// Multiple cases per case block
switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}}
case 1:
x = 0
}
switch x {
case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}}
default:
x = 0
}
switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
case 0:
x = 0
case 1: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}}
}
switch x {
case 0:
x = 0
default: // expected-error {{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}}
}
switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
case 0:
; // expected-error {{';' statements are not allowed}} {{3-5=}}
case 1:
x = 0
}
switch x {
x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}}
default:
x = 0
case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}}
x = 0
case 1:
x = 0
}
switch x {
default:
x = 0
default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}}
x = 0
}
switch x { // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}}
x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}}
}
switch x { // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}}
x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}}
x = 2
}
switch x {
default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}}
case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}}
x = 0
}
switch x {
default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}}
default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}}
x = 0
}
switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
default where x == 0: // expected-error{{'default' cannot be used with a 'where' guard expression}}
x = 0
}
switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}}
}
switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}}
case 1:
x = 0
}
switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
case 0:
x = 0
case 1: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}}
}
case 0: // expected-error{{'case' label can only appear inside a 'switch' statement}}
var y = 0
default: // expected-error{{'default' label can only appear inside a 'switch' statement}}
var z = 1
fallthrough // expected-error{{'fallthrough' is only allowed inside a switch}}
switch x {
case 0:
fallthrough
case 1:
fallthrough
default:
fallthrough // expected-error{{'fallthrough' without a following 'case' or 'default' block}}
}
// Fallthrough can transfer control anywhere within a case and can appear
// multiple times in the same case.
switch x {
case 0:
if true { fallthrough }
if false { fallthrough }
x += 1
default:
x += 1
}
// Cases cannot contain 'var' bindings if there are multiple matching patterns
// attached to a block. They may however contain other non-binding patterns.
var t = (1, 2)
switch t {
case (var a, 2), (1, _): // expected-error {{'a' must be bound in every pattern}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
()
case (_, 2), (var a, _): // expected-error {{'a' must be bound in every pattern}}
()
case (var a, 2), (1, var b): // expected-error {{'a' must be bound in every pattern}} expected-error {{'b' must be bound in every pattern}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
()
case (var a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
case (1, _):
()
case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}}
case (1, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
()
case (var a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
case (1, var b): // expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}}
()
case (1, let b): // let bindings expected-warning {{immutable value 'b' was never used; consider replacing with '_' or removing it}}
()
case (_, 2), (let a, _): // expected-error {{'a' must be bound in every pattern}} expected-warning {{case is already handled by previous patterns; consider removing it}}
()
// OK
case (_, 2), (1, _):
()
case (_, var a), (_, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
// expected-warning@-1 {{case is already handled by previous patterns; consider removing it}}
// expected-warning@-2 {{case is already handled by previous patterns; consider removing it}}
()
case (var a, var b), (var b, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}}
// expected-warning@-1 {{case is already handled by previous patterns; consider removing it}}
// expected-warning@-2 {{case is already handled by previous patterns; consider removing it}}
()
case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}}
case (1, _):
()
}
func patternVarUsedInAnotherPattern(x: Int) {
switch x {
case let a, // expected-error {{'a' must be bound in every pattern}}
a:
break
}
}
// Fallthroughs can only transfer control into a case label with bindings if the previous case binds a superset of those vars.
switch t {
case (1, 2):
fallthrough // expected-error {{'fallthrough' from a case which doesn't bind variable 'a'}} expected-error {{'fallthrough' from a case which doesn't bind variable 'b'}}
case (var a, var b): // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
t = (b, a)
}
switch t { // specifically notice on next line that we shouldn't complain that a is unused - just never mutated
case (var a, let b): // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
t = (b, b)
fallthrough // ok - notice that subset of bound variables falling through is fine
case (2, let a):
t = (a, a)
}
func patternVarDiffType(x: Int, y: Double) {
switch (x, y) {
case (1, let a): // expected-error {{pattern variable bound to type 'Double', fallthrough case bound to type 'Int'}}
fallthrough
case (let a, _):
break
}
}
func patternVarDiffMutability(x: Int, y: Double) {
switch x {
case let a where a < 5, var a where a > 10: // expected-error {{'var' pattern binding must match previous 'let' pattern binding}}{{27-30=let}}
break
default:
break
}
switch (x, y) {
// Would be nice to have a fixit in the following line if we detect that all bindings in the same pattern have the same problem.
case let (a, b) where a < 5, var (a, b) where a > 10: // expected-error 2{{'var' pattern binding must match previous 'let' pattern binding}}{{none}}
break
case (let a, var b) where a < 5, (let a, let b) where a > 10: // expected-error {{'let' pattern binding must match previous 'var' pattern binding}}{{44-47=var}}
break
case (let a, let b) where a < 5, (var a, let b) where a > 10, (let a, var b) where a == 8:
// expected-error@-1 {{'var' pattern binding must match previous 'let' pattern binding}}{{37-40=let}}
// expected-error@-2 {{'var' pattern binding must match previous 'let' pattern binding}}{{73-76=let}}
break
default:
break
}
}
func test_label(x : Int) {
Gronk: // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
switch x {
case 42: return
}
}
func enumElementSyntaxOnTuple() {
switch (1, 1) {
case .Bar: // expected-error {{value of tuple type '(Int, Int)' has no member 'Bar'}}
break
default:
break
}
}
// sr-176
enum Whatever { case Thing }
func f0(values: [Whatever]) { // expected-note {{'values' declared here}}
switch value { // expected-error {{cannot find 'value' in scope; did you mean 'values'?}}
case .Thing: // Ok. Don't emit diagnostics about enum case not found in type <<error type>>.
break
}
}
// sr-720
enum Whichever {
case Thing
static let title = "title"
static let alias: Whichever = .Thing
}
func f1(x: String, y: Whichever) {
switch x {
case Whichever.title: // Ok. Don't emit diagnostics for static member of enum.
break
case Whichever.buzz: // expected-error {{type 'Whichever' has no member 'buzz'}}
break
case Whichever.alias: // expected-error {{expression pattern of type 'Whichever' cannot match values of type 'String'}}
// expected-note@-1 {{overloads for '~=' exist with these partially matching parameter lists: (Substring, String)}}
break
default:
break
}
switch y {
case Whichever.Thing: // Ok.
break
case Whichever.alias: // Ok. Don't emit diagnostics for static member of enum.
break
case Whichever.title: // expected-error {{expression pattern of type 'String' cannot match values of type 'Whichever'}}
break
}
}
switch Whatever.Thing {
case .Thing: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}}
@unknown case _:
x = 0
}
switch Whatever.Thing {
case .Thing: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}}
@unknown default:
x = 0
}
switch Whatever.Thing {
case .Thing:
x = 0
@unknown case _: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}}
}
switch Whatever.Thing {
case .Thing:
x = 0
@unknown default: // expected-error {{'default' label in a 'switch' should have at least one executable statement}} {{18-18= break}}
}
switch Whatever.Thing {
@unknown default:
x = 0
default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}}
x = 0
case .Thing:
x = 0
}
switch Whatever.Thing {
default:
x = 0
@unknown case _: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} expected-error {{'@unknown' can only be applied to the last case in a switch}}
x = 0
case .Thing:
x = 0
}
switch Whatever.Thing {
default:
x = 0
@unknown default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}}
x = 0
case .Thing:
x = 0
}
switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}}
@unknown default where x == 0: // expected-error{{'default' cannot be used with a 'where' guard expression}}
x = 0
}
switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}}
@unknown case _:
fallthrough // expected-error{{'fallthrough' without a following 'case' or 'default' block}}
}
switch Whatever.Thing {
@unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}}
fallthrough
case .Thing:
break
}
switch Whatever.Thing {
@unknown default:
fallthrough
case .Thing: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}}
break
}
switch Whatever.Thing {
@unknown case _, _: // expected-error {{'@unknown' cannot be applied to multiple patterns}}
break
}
switch Whatever.Thing {
@unknown case _, _, _: // expected-error {{'@unknown' cannot be applied to multiple patterns}}
break
}
switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}}
@unknown case let value: // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}}
_ = value
}
switch (Whatever.Thing, Whatever.Thing) { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '(_, _)'}}
@unknown case (_, _): // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}}
break
}
switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}}
@unknown case is Whatever: // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}}
// expected-warning@-1 {{'is' test is always true}}
break
}
switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}}
@unknown case .Thing: // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}}
break
}
switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}}
@unknown case (_): // okay
break
}
switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}}
@unknown case _ where x == 0: // expected-error {{'where' cannot be used with '@unknown'}}
break
}
switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}}
@unknown default where x == 0: // expected-error {{'default' cannot be used with a 'where' guard expression}}
break
}
switch Whatever.Thing {
case .Thing:
x = 0
#if true
@unknown case _:
x = 0
#endif
}
switch x {
case 0:
break
@garbage case _: // expected-error {{unknown attribute 'garbage'}}
break
}
switch x {
case 0:
break
@garbage @moreGarbage default: // expected-error {{unknown attribute 'garbage'}} expected-error {{unknown attribute 'moreGarbage'}}
break
}
@unknown let _ = 1 // expected-error {{unknown attribute 'unknown'}}
switch x {
case _:
@unknown let _ = 1 // expected-error {{unknown attribute 'unknown'}}
}
switch Whatever.Thing {
case .Thing:
break
@unknown(garbage) case _: // expected-error {{unexpected '(' in attribute 'unknown'}}
break
}
switch Whatever.Thing {
case .Thing:
break
@unknown // expected-note {{attribute already specified here}}
@unknown // expected-error {{duplicate attribute}}
case _:
break
}
switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note {{add missing case: '.Thing'}}
@unknown @garbage(foobar) // expected-error {{unknown attribute 'garbage'}}
case _:
break
}
switch x { // expected-error {{switch must be exhaustive}}
case 1:
break
@unknown case _: // expected-note {{remove '@unknown' to handle remaining values}} {{1-10=}}
break
}
switch x { // expected-error {{switch must be exhaustive}}
@unknown case _: // expected-note {{remove '@unknown' to handle remaining values}} {{1-10=}}
break
}
switch x { // expected-error {{switch must be exhaustive}}
@unknown default: // expected-note {{remove '@unknown' to handle remaining values}} {{1-10=}}
break
}
switch Whatever.Thing {
case .Thing:
break
@unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}}
break
@unknown case _:
break
}
switch Whatever.Thing {
case .Thing:
break
@unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}}
break
@unknown default:
break
}
switch Whatever.Thing {
case .Thing:
break
@unknown default:
break
@unknown default: // expected-error {{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}}
break
}
switch Whatever.Thing {
@unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}}
break
@unknown case _:
break
}
switch Whatever.Thing {
@unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}}
break
@unknown default:
break
}
switch Whatever.Thing {
@unknown default:
break
@unknown default: // expected-error {{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}}
break
}
switch x {
@unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}}
break
@unknown case _:
break
}
switch x {
@unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}}
break
@unknown default:
break
}
switch x {
@unknown default:
break
@unknown default: // expected-error {{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}}
break
}
func testReturnBeforeUnknownDefault() {
switch x { // expected-error {{switch must be exhaustive}}
case 1:
return
@unknown default: // expected-note {{remove '@unknown' to handle remaining values}}
break
}
}
func testReturnBeforeIncompleteUnknownDefault() {
switch x { // expected-error {{switch must be exhaustive}}
case 1:
return
@unknown default // expected-error {{expected ':' after 'default'}}
// expected-note@-1 {{remove '@unknown' to handle remaining values}}
}
}
func testReturnBeforeIncompleteUnknownDefault2() {
switch x { // expected-error {{switch must be exhaustive}} expected-note {{do you want to add a default clause?}}
case 1:
return
@unknown // expected-error {{unknown attribute 'unknown'}}
} // expected-error {{expected declaration}}
}
func testIncompleteArrayLiteral() {
switch x { // expected-error {{switch must be exhaustive}}
case 1:
_ = [1 // expected-error {{expected ']' in container literal expression}} expected-note {{to match this opening '['}}
@unknown default: // expected-note {{remove '@unknown' to handle remaining values}}
()
}
}
| 22d2108401a09ab194fbdebef071f14a | 31.23493 | 326 | 0.676016 | false | false | false | false |
jihun-kang/ios_a2big_sdk | refs/heads/master | A2bigSDK/GIFAnimatable.swift | apache-2.0 | 1 | import UIKit
/// The protocol that view classes need to conform to to enable animated GIF support.
public protocol GIFAnimatable: class {
/// Responsible for managing the animation frames.
var animator: Animator? { get set }
/// Notifies the instance that it needs display.
var layer: CALayer { get }
/// View frame used for resizing the frames.
var frame: CGRect { get set }
/// Content mode used for resizing the frames.
var contentMode: UIViewContentMode { get set }
}
/// A single-property protocol that animatable classes can optionally conform to.
public protocol ImageContainer {
/// Used for displaying the animation frames.
var image: UIImage? { get set }
}
extension GIFAnimatable where Self: ImageContainer {
/// Returns the intrinsic content size based on the size of the image.
public var intrinsicContentSize: CGSize {
return image?.size ?? CGSize.zero
}
}
extension GIFAnimatable {
/// Returns the active frame if available.
public var activeFrame: UIImage? {
return animator?.activeFrame()
}
/// Total frame count of the GIF.
public var frameCount: Int {
return animator?.frameCount ?? 0
}
/// Introspect whether the instance is animating.
public var isAnimatingGIF: Bool {
return animator?.isAnimating ?? false
}
/// Prepare for animation and start animating immediately.
///
/// - parameter imageName: The file name of the GIF in the main bundle.
public func animate(withGIFNamed imageName: String) {
animator?.animate(withGIFNamed: imageName, size: frame.size, contentMode: contentMode)
}
/// Prepare for animation and start animating immediately.
///
/// - parameter imageData: GIF image data.
public func animate(withGIFData imageData: Data) {
animator?.animate(withGIFData: imageData, size: frame.size, contentMode: contentMode)
}
/// Prepares the animator instance for animation.
///
/// - parameter imageName: The file name of the GIF in the main bundle.
public func prepareForAnimation(withGIFNamed imageName: String) {
animator?.prepareForAnimation(withGIFNamed: imageName, size: frame.size, contentMode: contentMode)
}
/// Prepare for animation and start animating immediately.
///
/// - parameter imageData: GIF image data.
public func prepareForAnimation(withGIFData imageData: Data) {
if var imageContainer = self as? ImageContainer {
imageContainer.image = UIImage(data: imageData)
}
animator?.prepareForAnimation(withGIFData: imageData, size: frame.size, contentMode: contentMode)
}
/// Stop animating and free up GIF data from memory.
public func prepareForReuse() {
animator?.prepareForReuse()
}
/// Start animating GIF.
public func startAnimatingGIF() {
animator?.startAnimating()
}
/// Stop animating GIF.
public func stopAnimatingGIF() {
animator?.stopAnimating()
}
/// Whether the frame images should be resized or not. The default is `false`, which means that the frame images retain their original size.
///
/// - parameter resize: Boolean value indicating whether individual frames should be resized.
public func setShouldResizeFrames(_ resize: Bool) {
animator?.shouldResizeFrames = resize
}
/// Sets the number of frames that should be buffered. Default is 50. A high number will result in more memory usage and less CPU load, and vice versa.
///
/// - parameter frames: The number of frames to buffer.
public func setFrameBufferCount(_ frames: Int) {
animator?.frameBufferCount = frames
}
/// Updates the image with a new frame if necessary.
public func updateImageIfNeeded() {
if var imageContainer = self as? ImageContainer {
imageContainer.image = activeFrame ?? imageContainer.image
} else {
layer.contents = activeFrame?.cgImage
}
}
}
extension GIFAnimatable {
/// Calls setNeedsDisplay on the layer whenever the animator has a new frame. Should *not* be called directly.
func animatorHasNewFrame() {
layer.setNeedsDisplay()
}
}
| 5204808a49192b3a03210c4a4dacef82 | 31.232 | 153 | 0.719037 | false | false | false | false |
huangboju/QMUI.swift | refs/heads/master | QMUI.swift/Demo/Modules/Demos/UIKit/QDSearchViewController.swift | mit | 1 | //
// QDSearchViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/19.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDSearchViewController: QDCommonTableViewController {
private let keywords = ["Helps", "Maintain", "Liver", "Health", "Function", "Supports", "Healthy", "Fat", "Metabolism", "Nuturally"]
private var searchResultsKeywords: [String] = []
private lazy var mySearchController: QMUISearchController = {
// QMUISearchController 有两种使用方式,一种是独立使用,一种是集成到 QMUICommonTableViewController 里使用。为了展示它的使用方式,这里使用第一种,不理会 QMUICommonTableViewController 内部自带的 QMUISearchController
let mySearchController = QMUISearchController(contentsViewController: self)
mySearchController.searchResultsDelegate = self
mySearchController.launchView = QDRecentSearchView() // launchView 会自动布局,无需处理 frame
mySearchController.searchBar?.qmui_usedAsTableHeaderView = true // 以 tableHeaderView 的方式使用 searchBar 的话,将其置为 YES,以辅助兼容一些系统 bug
return mySearchController
}()
override init(style: UITableView.Style) {
super.init(style: style)
// 这个属性默认就是 false,这里依然写出来只是为了提醒 QMUICommonTableViewController 默认就集成了 QMUISearchController,如果你的界面本身就是 QMUICommonTableViewController 的子类,则也可以直接通过将这个属性改为 true 来创建 QMUISearchController
shouldShowSearchBar = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableHeaderView = mySearchController.searchBar
}
}
extension QDSearchViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection _: Int) -> Int {
if tableView == self.tableView {
return keywords.count
}
return searchResultsKeywords.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "cell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if cell == nil {
cell = QMUITableViewCell(tableView: self.tableView, reuseIdentifier: identifier)
}
if tableView == self.tableView {
cell?.textLabel?.text = keywords[indexPath.row]
} else {
let keyword = searchResultsKeywords[indexPath.row]
let attributedString = NSMutableAttributedString(string: keyword, attributes: [NSAttributedString.Key.foregroundColor: UIColorBlack])
if let string = mySearchController.searchBar?.text, let range = keyword.range(of: string), let color = QDThemeManager.shared.currentTheme?.themeTintColor {
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange(range, in: string))
}
cell?.textLabel?.attributedText = attributedString
}
(cell as? QMUITableViewCell)?.updateCellAppearance(indexPath)
return cell ?? UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension QDSearchViewController {
override func searchController(_ searchController: QMUISearchController, updateResultsFor searchString: String?) {
searchResultsKeywords.removeAll()
for key in keywords {
if searchString != nil && key.contains(searchString!) {
searchResultsKeywords.append(key)
}
}
searchController.tableView?.reloadData()
if searchResultsKeywords.count == 0 {
searchController.showEmptyViewWith(text: "没有匹配结果", detailText: nil, buttonTitle: nil, buttonAction: nil)
} else {
searchController.hideEmptyView()
}
}
func willPresent(_ searchController: QMUISearchController) {
QMUIHelper.renderStatusBarStyleDark()
}
func willDismiss(_: QMUISearchController) {
var oldStatusbarLight = false
oldStatusbarLight = shouldSetStatusBarStyleLight
if oldStatusbarLight {
QMUIHelper.renderStatusBarStyleLight()
} else {
QMUIHelper.renderStatusBarStyleDark()
}
}
}
class QDRecentSearchView: UIView {
private lazy var titleLabel: QMUILabel = {
let label = QMUILabel(with: UIFontMake(14), textColor: UIColorGray2)
label.text = "最近搜索"
label.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
label.sizeToFit()
label.qmui_borderPosition = .bottom
return label
}()
private lazy var floatLayoutView: QMUIFloatLayoutView = {
let floatLayoutView = QMUIFloatLayoutView()
floatLayoutView.padding = .zero
floatLayoutView.itemMargins = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)
floatLayoutView.minimumItemSize = CGSize(width: 69, height: 29)
return floatLayoutView
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColorWhite
addSubview(titleLabel)
addSubview(floatLayoutView)
let suggestions = ["Helps", "Maintain", "Liver", "Health", "Function", "Supports", "Healthy", "Fat"]
suggestions.forEach {
let button = QMUIGhostButton(ghostType: .gray)
button.setTitle($0, for: .normal)
button.titleLabel?.font = UIFontMake(14)
button.contentEdgeInsets = UIEdgeInsets(top: 6, left: 20, bottom: 6, right: 20)
floatLayoutView.addSubview(button)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let padding = UIEdgeInsets(top: 26, left: 26, bottom: 26, right: 26).concat(insets: qmui_safeAreaInsets)
let titleLabelMarginTop: CGFloat = 20
titleLabel.frame = CGRect(x: padding.left, y: padding.top, width: bounds.width - padding.horizontalValue, height: titleLabel.frame.height)
let minY = titleLabel.frame.maxY + titleLabelMarginTop
floatLayoutView.frame = CGRect(x: padding.left, y: minY, width: bounds.width - padding.horizontalValue, height: bounds.height - minY)
}
}
| 3c9d0358fdd6fba6e32c0aefb12f7519 | 39.223602 | 188 | 0.669549 | false | false | false | false |
iCasa/js-xlsx | refs/heads/master | demos/altjs/SJSPlayground.swift | apache-2.0 | 3 | /* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
/* This only works in a playground, see SheetJSCore.swift for standalone use */
import JavaScriptCore;
import PlaygroundSupport;
/* build path variable for the library */
let shared_dir = PlaygroundSupport.playgroundSharedDataDirectory;
let lib_path = shared_dir.appendingPathComponent("xlsx.full.min.js");
/* prepare JS context */
var context:JSContext! = JSContext();
var src = "var global = (function(){ return this; }).call(null);";
context.evaluateScript(src);
/* load library */
var lib = try? String(contentsOf: lib_path);
context.evaluateScript(lib);
let XLSX: JSValue! = context.objectForKeyedSubscript("XLSX");
/* to verify the library was loaded, get the version string */
let XLSXversion: JSValue! = XLSX.objectForKeyedSubscript("version")
var version = XLSXversion.toString();
/* parse sheetjs.xls */
let file_path = shared_dir.appendingPathComponent("sheetjs.xls");
let data:String! = try String(contentsOf: file_path, encoding:String.Encoding.isoLatin1);
context.setObject(data, forKeyedSubscript:"payload" as (NSCopying & NSObjectProtocol)!);
src = "var wb = XLSX.read(payload, {type:'binary'});";
context.evaluateScript(src);
/* write to sheetjs.xlsx */
let out_path = shared_dir.appendingPathComponent("sheetjs.xlsx");
src = "var out = XLSX.write(wb, {type:'binary', bookType:'xlsx'})";
context.evaluateScript(src);
let outvalue: JSValue! = context.objectForKeyedSubscript("out");
var out:String! = outvalue.toString();
try? out.write(to: out_path, atomically: false, encoding: String.Encoding.isoLatin1);
| ca0ec9c26c80175a98f46b64d19723db | 42.081081 | 89 | 0.74404 | false | false | false | false |
haranicle/RealmRelationsSample | refs/heads/master | Carthage/Checkouts/realm-cocoa/Realm/Tests/Swift/SwiftObjectInterfaceTests.swift | mit | 2 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm
import Foundation
class OuterClass {
class InnerClass {
}
}
class SwiftStringObjectSubclass : SwiftStringObject {
var stringCol2 = ""
}
class SwiftSelfRefrencingSubclass: SwiftStringObject {
dynamic var objects = RLMArray(objectClassName: SwiftSelfRefrencingSubclass.className())
}
class SwiftDefaultObject: RLMObject {
dynamic var intCol = 1
dynamic var boolCol = true
override class func defaultPropertyValues() -> [NSObject : AnyObject]! {
return ["intCol": 2]
}
}
class SwiftObjectInterfaceTests: SwiftTestCase {
// Swift models
func testSwiftObject() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let obj = SwiftObject()
realm.addObject(obj)
obj.boolCol = true
obj.intCol = 1234
obj.floatCol = 1.1
obj.doubleCol = 2.2
obj.stringCol = "abcd"
obj.binaryCol = "abcd".dataUsingEncoding(NSUTF8StringEncoding)
obj.dateCol = NSDate(timeIntervalSince1970: 123)
obj.objectCol = SwiftBoolObject()
obj.objectCol.boolCol = true
obj.arrayCol.addObject(obj.objectCol)
realm.commitWriteTransaction()
let data = NSString(string: "abcd").dataUsingEncoding(NSUTF8StringEncoding)
let firstObj = SwiftObject.allObjectsInRealm(realm).firstObject() as SwiftObject
XCTAssertEqual(firstObj.boolCol, true, "should be true")
XCTAssertEqual(firstObj.intCol, 1234, "should be 1234")
XCTAssertEqual(firstObj.floatCol, Float(1.1), "should be 1.1")
XCTAssertEqual(firstObj.doubleCol, 2.2, "should be 2.2")
XCTAssertEqual(firstObj.stringCol, "abcd", "should be abcd")
XCTAssertEqual(firstObj.binaryCol!, data!)
XCTAssertEqual(firstObj.dateCol, NSDate(timeIntervalSince1970: 123), "should be epoch + 123")
XCTAssertEqual(firstObj.objectCol.boolCol, true, "should be true")
XCTAssertEqual(obj.arrayCol.count, UInt(1), "array count should be 1")
XCTAssertEqual((obj.arrayCol.firstObject() as? SwiftBoolObject)!.boolCol, true, "should be true")
}
func testDefaultValueSwiftObject() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
realm.addObject(SwiftObject())
realm.commitWriteTransaction()
let data = NSString(string: "a").dataUsingEncoding(NSUTF8StringEncoding)
let firstObj = SwiftObject.allObjectsInRealm(realm).firstObject() as SwiftObject
XCTAssertEqual(firstObj.boolCol, false, "should be false")
XCTAssertEqual(firstObj.intCol, 123, "should be 123")
XCTAssertEqual(firstObj.floatCol, Float(1.23), "should be 1.23")
XCTAssertEqual(firstObj.doubleCol, 12.3, "should be 12.3")
XCTAssertEqual(firstObj.stringCol, "a", "should be a")
XCTAssertEqual(firstObj.binaryCol!, data!)
XCTAssertEqual(firstObj.dateCol, NSDate(timeIntervalSince1970: 1), "should be epoch + 1")
XCTAssertEqual(firstObj.objectCol.boolCol, false, "should be false")
XCTAssertEqual(firstObj.arrayCol.count, UInt(0), "array count should be zero")
}
func testMergedDefaultValuesSwiftObject() {
let realm = self.realmWithTestPath()
realm.beginWriteTransaction()
SwiftDefaultObject.createInRealm(realm, withObject: NSDictionary())
realm.commitWriteTransaction()
let object = SwiftDefaultObject.allObjectsInRealm(realm).firstObject() as SwiftDefaultObject
XCTAssertEqual(object.intCol, 2, "defaultPropertyValues should override native property default value")
XCTAssertEqual(object.boolCol, true, "native property default value should be used if defaultPropertyValues doesn't contain that key")
}
func testSubclass() {
// test className methods
XCTAssertEqual("SwiftStringObject", SwiftStringObject.className())
XCTAssertEqual("SwiftStringObjectSubclass", SwiftStringObjectSubclass.className())
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
SwiftStringObject.createInDefaultRealmWithObject(["string"])
let obj = SwiftStringObjectSubclass.createInDefaultRealmWithObject(["string", "string2"])
realm.commitWriteTransaction()
// ensure creation in proper table
XCTAssertEqual(UInt(1), SwiftStringObjectSubclass.allObjects().count)
XCTAssertEqual(UInt(1), SwiftStringObject.allObjects().count)
realm.transactionWithBlock { () -> Void in
// create self referencing subclass
var sub = SwiftSelfRefrencingSubclass.createInDefaultRealmWithObject(["string", []])
var sub2 = SwiftSelfRefrencingSubclass()
sub.objects.addObject(sub2)
}
}
func testOptionalSwiftProperties() {
let realm = realmWithTestPath()
realm.transactionWithBlock { realm.addObject(SwiftOptionalObject()) }
let firstObj = SwiftOptionalObject.allObjectsInRealm(realm).firstObject() as SwiftOptionalObject
XCTAssertNil(firstObj.optObjectCol)
realm.transactionWithBlock {
firstObj.optObjectCol = SwiftBoolObject()
firstObj.optObjectCol!.boolCol = true
}
XCTAssertTrue(firstObj.optObjectCol!.boolCol)
}
func testSwiftClassNameIsDemangled() {
XCTAssertEqual(SwiftObject.className()!, "SwiftObject", "Calling className() on Swift class should return demangled name")
}
// Objective-C models
// Note: Swift doesn't support custom accessor names
// so we test to make sure models with custom accessors can still be accessed
func testCustomAccessors() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let ca = CustomAccessorsObject.createInRealm(realm, withObject: ["name", 2])
XCTAssertEqual(ca.name!, "name", "name property should be name.")
ca.age = 99
XCTAssertEqual(ca.age, Int32(99), "age property should be 99")
realm.commitWriteTransaction()
}
func testClassExtension() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let bObject = BaseClassStringObject()
bObject.intCol = 1
bObject.stringCol = "stringVal"
realm.addObject(bObject)
realm.commitWriteTransaction()
let objectFromRealm = BaseClassStringObject.allObjectsInRealm(realm)[0] as BaseClassStringObject
XCTAssertEqual(objectFromRealm.intCol, Int32(1), "Should be 1")
XCTAssertEqual(objectFromRealm.stringCol!, "stringVal", "Should be stringVal")
}
func testCreateOrUpdate() {
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithObject(["string", 1])
let objects = SwiftPrimaryStringObject.allObjects();
XCTAssertEqual(objects.count, UInt(1), "Should have 1 object");
XCTAssertEqual((objects[0] as SwiftPrimaryStringObject).intCol, 1, "Value should be 1");
SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithObject(["stringCol": "string2", "intCol": 2])
XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects")
SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithObject(["string", 3])
XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects")
XCTAssertEqual((objects[0] as SwiftPrimaryStringObject).intCol, 3, "Value should be 3");
realm.commitWriteTransaction()
}
// if this fails (and you haven't changed the test module name), the checks
// for swift class names and the demangling logic need to be updated
func testNSStringFromClassDemangledTopLevelClassNames() {
#if os(iOS)
XCTAssertEqual(NSStringFromClass(OuterClass), "iOS_Tests.OuterClass")
#else
XCTAssertEqual(NSStringFromClass(OuterClass), "OSX_Tests.OuterClass")
#endif
}
// if this fails (and you haven't changed the test module name), the prefix
// check in RLMSchema initialization needs to be updated
func testNestedClassNameMangling() {
#if os(iOS)
XCTAssertEqual(NSStringFromClass(OuterClass.InnerClass.self), "_TtCC9iOS_Tests10OuterClass10InnerClass")
#else
XCTAssertEqual(NSStringFromClass(OuterClass.InnerClass.self), "_TtCC9OSX_Tests10OuterClass10InnerClass")
#endif
}
}
| c6835c42d631ffbf8ed1c7d4dad8bdc2 | 39.631111 | 142 | 0.691096 | false | true | false | false |
b-andris/Authenticate | refs/heads/master | Authenticate/LockViewController.swift | mit | 1 | //
// ViewController.swift
// Authenticate
//
// Created by Benjamin Andris Suter-Dörig on 09/05/15.
// Copyright (c) 2015 Benjamin Andris Suter-Dörig. All rights reserved.
//
import UIKit
import LocalAuthentication
import Dispatch
import CoreImage
@objc public protocol LockViewControllerDelegate {
func lockViewControllerAuthentication(_ controller: LockViewController, didSucced success: Bool)
func lockViewControllerDidSetup(_ controller: LockViewController, code: String)
}
private enum CodeValidationResult {
case ok
case tooShort
case wrong
}
@objc public enum LockScreenMode: Int {
case setup
case authenticate
}
private class Keypad: UIView {
var enterPrompt = "Enter PIN" {
didSet {
updateTextField()
}
}
var wrongCodeMessage = "Wrong PIN" {
didSet {
updateTextField()
}
}
var callback: (String) -> (CodeValidationResult) = {code -> CodeValidationResult in return .wrong}
var timeUnits = ["Sec", "Min", "Hours", "Days", "Months", "Years"]
var wait: UInt = 0 {
didSet {
if wait > 0 {
for button in digitButtons {
button.isEnabled = false
}
deleteButton.isEnabled = false
if wait < 60 {
textField.placeholder = "\(wait) \(timeUnits[0])"
} else if wait < 60 * 60 {
textField.placeholder = "\(wait / 60) \(timeUnits[1])"
} else if wait < 60 * 60 * 24 {
textField.placeholder = "\(wait / 60 / 60) \(timeUnits[2])"
} else if wait < 60 * 60 * 24 * 30 {
textField.placeholder = "\(wait / 60 / 60 / 24) \(timeUnits[3])"
} else if wait < 60 * 60 * 24 * 365 {
textField.placeholder = "\(wait / 60 / 60 / 24 / 30) \(timeUnits[4])"
} else {
textField.placeholder = "\(wait / 60 / 60 / 24 / 365) \(timeUnits[5])"
}
textField.text = ""
} else {
for button in digitButtons {
button.isEnabled = true
}
deleteButton.isEnabled = true
updateTextField()
}
}
}
private var digitButtons: [UIButton] = []
private let deleteButton = UIButton(type: .system) as UIButton
private var enteredCode = ""
private let textField = UITextField()
private var showWrongPINMessage = false
init() {
super.init(frame: CGRect.zero)
let chars = ["⓪", "①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⌫"]
for i in 0 ... 9 {
digitButtons.append(UIButton(type: .system) as UIButton)
digitButtons[i].setTitle(chars[i], for: UIControlState())
digitButtons[i].tag = i
digitButtons[i].addTarget(self, action: #selector(Keypad.digitButtonPressed(_:)), for: .touchUpInside)
addSubview(digitButtons[i])
}
deleteButton.setTitle(chars[10], for: UIControlState())
deleteButton.addTarget(self, action: #selector(Keypad.deleteButtonPressed(_:)), for: .touchUpInside)
addSubview(textField)
textField.isUserInteractionEnabled = false
textField.textAlignment = .center
updateTextField()
addSubview(deleteButton)
layout()
}
@IBAction func digitButtonPressed(_ button: UIButton) {
enteredCode += "\(button.tag)"
if callback(enteredCode) == .wrong {
enteredCode = ""
showWrongPINMessage = true
} else {
showWrongPINMessage = false
}
updateTextField()
}
@IBAction func deleteButtonPressed(_ button: UIButton) {
if enteredCode.count > 0 {
let index = enteredCode.index(enteredCode.endIndex, offsetBy: -1)
enteredCode = String(enteredCode[..<index])
updateTextField()
}
}
func reset() {
enteredCode = ""
showWrongPINMessage = false
updateTextField()
}
private func updateTextField() {
if wait > 0 {
return
}
if showWrongPINMessage {
textField.placeholder = wrongCodeMessage
} else {
textField.placeholder = enterPrompt
}
var code = ""
for _ in 0 ..< enteredCode.count {
code += " ●"
}
textField.text = code
}
private func layout() {
let elementWidth = bounds.width / 3
let elementHeight = bounds.height / 5
textField.frame = CGRect(x: 0, y: 0, width: bounds.width, height: elementHeight)
textField.font = UIFont.systemFont(ofSize: min(elementWidth, elementHeight) * 0.5)
for i in 1 ... 9 {
digitButtons[i].frame = CGRect(x: (CGFloat(i) + 2).truncatingRemainder(dividingBy: 3) * elementWidth, y: floor((CGFloat(i) + 2) / 3) * elementHeight, width: elementWidth, height: elementHeight)
digitButtons[i].titleLabel?.font = UIFont.systemFont(ofSize: min(elementWidth, elementHeight) * 0.9)
}
digitButtons[0].frame = CGRect(x: elementWidth, y: 4 * elementHeight, width: elementWidth, height: elementHeight)
digitButtons[0].titleLabel?.font = UIFont.systemFont(ofSize: min(elementWidth, elementHeight) * 0.9)
deleteButton.frame = CGRect(x: 2 * elementWidth, y: 4 * elementHeight, width: elementWidth, height: elementHeight)
deleteButton.titleLabel?.font = UIFont.systemFont(ofSize: min(elementWidth, elementHeight) * 0.5)
}
override func layoutSubviews() {
layout()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
}
public class LockViewController: UIViewController, UIViewControllerTransitioningDelegate {
private var keypad: Keypad = Keypad()
private var isVerifying = false
private var isUpdatingWait = false
private var waitTime = 0.16
private var background = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.light))
private var upBackground = UIView()
private var downBackground = UIView()
private var rightBackground = UIView()
private var leftBackground = UIView()
private var wait: UInt {
get {
return keypad.wait
}
set(wait) {
keypad.wait = wait
if (!isUpdatingWait) {
updateWait()
}
}
}
@objc public var code: String = "0000"
@objc public var reason: String = "Unlock " + (Bundle.main.infoDictionary!["CFBundleName"] as! String)
@objc public var allowsTouchID = true
@objc public var mode = LockScreenMode.authenticate
@objc public var codeLength = 4
@objc public var remainingAttempts = -1
@objc public var maxWait: UInt = 30
@objc public var delegate: LockViewControllerDelegate?
@objc public var wrongCodeMessage: String {
get {
return keypad.wrongCodeMessage
}
set(wrongCodeMessage) {
keypad.wrongCodeMessage = wrongCodeMessage
}
}
@objc public var enterPrompt = "Enter PIN" {
didSet {
if !isVerifying {
keypad.enterPrompt = enterPrompt
}
}
}
@objc public var verifyPrompt = "Verify" {
didSet {
if isVerifying {
keypad.enterPrompt = verifyPrompt
}
}
}
@objc public var timeUnits: [String] {
get {
return keypad.timeUnits
}
set(timeUnits) {
keypad.timeUnits = timeUnits
}
}
private func updateWait() {
if wait > 0 {
isUpdatingWait = true
weak var weakSelf = self
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
if let strongSelf = weakSelf {
strongSelf.wait -= 1
strongSelf.updateWait()
}
}
} else {
isUpdatingWait = false
}
}
private func validate(code: String) -> CodeValidationResult {
if mode == .authenticate {
if code.count < self.code.count {
return .tooShort
} else if code == self.code {
if let del = delegate {
del.lockViewControllerAuthentication(self, didSucced: true)
} else {
dismiss(animated: true, completion: nil)
}
return .ok
} else {
if remainingAttempts > 0 {
remainingAttempts -= 1
}
if remainingAttempts == 0 {
if let del = delegate {
del.lockViewControllerAuthentication(self, didSucced: false)
} else {
dismiss(animated: true, completion: nil)
}
return .wrong
}
if maxWait > 0 {
waitTime *= 2
if UInt(waitTime) > maxWait {
wait = maxWait
} else {
wait = UInt(waitTime)
}
}
return .wrong
}
} else {
if code.count < codeLength {
return .tooShort
} else if isVerifying && code == self.code {
if let del = delegate {
del.lockViewControllerDidSetup(self, code: code)
} else {
dismiss(animated: true, completion: nil)
}
return .ok
} else if isVerifying {
isVerifying = false
keypad.enterPrompt = enterPrompt
return .wrong
} else {
isVerifying = true
self.code = code
keypad.enterPrompt = verifyPrompt
keypad.reset()
return .ok
}
}
}
init() {
super.init(nibName: nil, bundle: nil)
transitioningDelegate = self
modalPresentationStyle = .custom
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
transitioningDelegate = self
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
keypad.callback = validate(code:)
let context = LAContext()
if allowsTouchID && mode == .authenticate {
context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error:nil)
weak var weakSelf = self
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason, reply: { (success, error) ->Void in
if success {
if let strongSelf = weakSelf {
if let del = strongSelf.delegate {
del.lockViewControllerAuthentication(self, didSucced: true)
} else {
strongSelf.dismiss(animated: true, completion: nil)
}
}
}
})
}
view.addSubview(background)
view.addSubview(keypad)
leftBackground.backgroundColor = UIColor.black
rightBackground.backgroundColor = UIColor.black
upBackground.backgroundColor = UIColor.black
downBackground.backgroundColor = UIColor.black
view.addSubview(leftBackground)
view.addSubview(rightBackground)
view.addSubview(upBackground)
view.addSubview(downBackground)
setupView(view.bounds.size)
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
setupView(size)
}
private func setupView(_ size: CGSize) {
let elementSize = min(min(size.width / 3, size.height / 5), 100)
keypad.frame = CGRect(x: 0, y: 0, width: 3 * elementSize, height: 5 * elementSize)
keypad.center = CGPoint(x: size.width / 2, y: size.height / 2)
background.frame.size = size
let maxSize = max(size.width, size.height)
leftBackground.frame = CGRect(x: -maxSize, y: -maxSize, width: maxSize, height: 3 * maxSize)
rightBackground.frame = CGRect(x: size.width, y: -maxSize, width: maxSize, height: 3 * maxSize)
upBackground.frame = CGRect(x: -maxSize, y: -maxSize, width: 3 * maxSize, height: maxSize)
downBackground.frame = CGRect(x: -maxSize, y: size.height, width: 3 * maxSize, height: maxSize)
}
open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PresentController()
}
open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return DismissController()
}
}
private class PresentController: NSObject, UIViewControllerAnimatedTransitioning {
@objc func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
@objc func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let vc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
transitionContext.containerView.addSubview(vc.view)
vc.view.alpha = 0
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
vc.view.alpha = 1
}, completion: { (finished) -> Void in transitionContext.completeTransition(finished)})
}
}
private class DismissController: NSObject, UIViewControllerAnimatedTransitioning {
@objc func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
@objc func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let vc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
vc.view.alpha = 1
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
vc.view.alpha = 0
}, completion: { (finished) -> Void in
vc.view.removeFromSuperview()
transitionContext.completeTransition(finished)
})
}
}
| 46c0af05f8a4ed8fb868a25f698db76e | 28.820639 | 196 | 0.70075 | false | false | false | false |
aptyr/-github-iOS | refs/heads/master | #github-ios/models/AccessToken.swift | apache-2.0 | 1 | //
// AccessToken.swift
// #github-ios
//
// Created by Artur on 09/03/2017.
// Copyright © 2017 Artur Matusiak. All rights reserved.
//
import Foundation
final class AccessToken: HTTPRequestResult {
private(set) var accessTokenKey: String?
private(set) var scope: String?
private(set) var tokenType: String?
private var params: [String : String]?
init(withDictionary params: [String : String]) {
self.params = params
self.accessTokenKey = params["access_token"]
self.scope = params["scope"]
self.tokenType = params["token_type"]
}
convenience init(withString params: String){
self.init(withDictionary: params.dictionary)
}
convenience init(withApiData data: Data) throws {
let params = try JSONSerialization.jsonObject(with: data, options: []) as! [String: String]
self.init(withDictionary: params)
}
}
| 15c1d70da8777230de32a9c6e5aa70f1 | 25.222222 | 99 | 0.64089 | false | false | false | false |
MattLewin/Interview-Prep | refs/heads/master | Data Structures.playground/Pages/Binary Heap.xcplaygroundpage/Contents.swift | unlicense | 1 | //: [Previous](@previous)
import Foundation
class MinHeap {
private(set) var heap: [Int]
private(set) var elementCount = 0
init(size: Int = 3) {
heap = Array<Int>(repeatElement(Int.max, count: size))
}
private func resizeHeap() {
var newHeap = Array<Int>(repeatElement(Int.max, count: (2 * heap.count)))
newHeap[0..<heap.count] = heap[...]
heap = newHeap
}
private func swap(_ index1: Int, _ index2: Int) {
let temp = heap[index1]
heap[index1] = heap[index2]
heap[index2] = temp
}
private func bubbleUp(_ index: Int) {
var currentIndex = index
var parentIndex = currentIndex / 2
while parentIndex > 0 &&
(heap[parentIndex] > heap[currentIndex]) {
swap(parentIndex, currentIndex)
currentIndex = parentIndex
parentIndex = currentIndex / 2
}
}
private func bubbleDown(_ index: Int) {
var currentIndex = index
var leftIndex = currentIndex * 2
var rightIndex = leftIndex + 1
while currentIndex <= elementCount {
if leftIndex <= elementCount &&
(heap[currentIndex] > heap[leftIndex]) {
swap(currentIndex, leftIndex)
currentIndex = leftIndex
}
else if rightIndex < elementCount &&
(heap[currentIndex] > heap[rightIndex]) {
swap(currentIndex, rightIndex)
currentIndex = rightIndex
}
else {
break
}
leftIndex = currentIndex * 2
rightIndex = leftIndex + 1
}
}
public func insert(_ element: Int) {
elementCount += 1
if elementCount >= heap.count {
resizeHeap()
}
heap[elementCount] = element
bubbleUp(elementCount)
}
public func removeMin() -> Int {
let retVal = heap[1]
heap[1] = heap[elementCount]
heap[elementCount] = Int.max
elementCount -= 1
bubbleDown(1)
return retVal
}
}
let minHeap = MinHeap()
minHeap.insert(4)
minHeap.insert(50)
minHeap.insert(7)
minHeap.insert(55)
minHeap.insert(90)
minHeap.insert(87)
minHeap.insert(2)
minHeap.removeMin()
minHeap
//: [Next](@next)
| dfb408f608445358a769526114f0b094 | 23.684211 | 81 | 0.549254 | false | false | false | false |
Pstoppani/swipe | refs/heads/master | core/SwipeList.swift | mit | 4 | //
// SwipeList.swift
//
// Created by Pete Stoppani on 5/26/16.
//
import Foundation
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
class SwipeList: SwipeView, UITableViewDelegate, UITableViewDataSource {
let TAG = "SWList"
private var items = [[String:Any]]()
private var itemHeights = [CGFloat]()
private var defaultItemHeight: CGFloat = 40
private let scale:CGSize
private var screenDimension = CGSize(width: 0, height: 0)
weak var delegate:SwipeElementDelegate!
var tableView: UITableView
init(parent: SwipeNode, info: [String:Any], scale: CGSize, frame: CGRect, screenDimension: CGSize, delegate:SwipeElementDelegate) {
self.scale = scale
self.screenDimension = screenDimension
self.delegate = delegate
self.tableView = UITableView(frame: frame, style: .plain)
super.init(parent: parent, info: info)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
#if !os(tvOS)
self.tableView.separatorStyle = .none
#endif
self.tableView.allowsSelection = true
self.tableView.backgroundColor = UIColor.clear
if let value = info["itemH"] as? CGFloat {
defaultItemHeight = value
} else if let value = info["itemH"] as? String {
defaultItemHeight = SwipeParser.parsePercent(value, full: screenDimension.height, defaultValue: defaultItemHeight)
}
if let itemsInfo = info["items"] as? [[String:Any]] {
items = itemsInfo
for _ in items {
itemHeights.append(defaultItemHeight)
}
}
if let scrollEnabled = self.info["scrollEnabled"] as? Bool {
self.tableView.isScrollEnabled = scrollEnabled
}
self.tableView.reloadData()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
if let selectedIndex = self.info["selectedItem"] as? Int {
self.tableView.selectRow(at: IndexPath(row: selectedIndex, section: 0), animated: true, scrollPosition: .middle)
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// UITableViewDataDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return itemHeights[indexPath.row]
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let actions = parent!.eventHandler.actionsFor("rowSelected") {
parent!.execute(self, actions: actions)
}
}
// UITableViewDataSource
var cellIndexPath: IndexPath?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let subviewTag = 999
self.cellIndexPath = indexPath
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
if let subView = cell.contentView.viewWithTag(subviewTag) {
subView.removeFromSuperview()
}
var cellError: String?
let item = self.items[indexPath.row]
if let itemH = item["h"] as? CGFloat {
self.itemHeights[indexPath.row] = itemH
}
let itemHeight = self.itemHeights[indexPath.row]
if let elementsInfo = item["elements"] as? [[String:Any]] {
for elementInfo in elementsInfo {
let element = SwipeElement(info: elementInfo, scale:self.scale, parent:self, delegate:self.delegate!)
if let subview = element.loadViewInternal(CGSize(width: self.tableView.bounds.size.width, height: itemHeight), screenDimension: self.screenDimension) {
subview.tag = subviewTag
cell.contentView.addSubview(subview)
children.append(element)
} else {
cellError = "can't load"
}
}
} else {
cellError = "no elements"
}
if cellError != nil {
let v = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: itemHeight))
let l = UILabel(frame: CGRect(x:0, y:0, width: v.bounds.size.width, height: v.bounds.size.height))
v.addSubview(l)
cell.contentView.addSubview(v)
l.text = "row \(indexPath.row) error " + cellError!
}
cell.selectionStyle = .none
self.cellIndexPath = nil
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
// SwipeView
override func appendList(_ originator: SwipeNode, info: [String:Any]) {
if let itemsInfoArray = info["items"] as? [[String:Any]] {
var itemInfos = [[String:Any]]()
for itemInfo in itemsInfoArray {
if let _ = itemInfo["data"] as? [String:Any] {
var eval = originator.evaluate(itemInfo)
// if 'data' is a JSON string, use it, otherwise, use the info as is
if let dataStr = eval["data"] as? String, let data = dataStr.data(using: .utf8) {
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [String:Any] else {
// 'data' is a plain String
itemInfos.append(eval)
break
}
// 'data' is a JSON string so use the JSON object
if (json["elements"] as? [[String:Any]]) != nil {
// 'data' is a redefinition of the item
itemInfos.append(json)
} else {
// 'data' is just data
eval["data"] = json
itemInfos.append(eval)
}
} catch {
// 'data' is a plain String
itemInfos.append(eval)
}
} else {
// 'data' is a 'valueOf' JSON object
itemInfos.append(eval)
}
} else {
itemInfos.append(itemInfo)
}
}
var urls = [URL:String]()
for itemInfo in itemInfos {
if let elementsInfo = itemInfo["elements"] as? [[String:Any]] {
let scaleDummy = CGSize(width: 0.1, height: 0.1)
for e in elementsInfo {
let element = SwipeElement(info: e, scale:scaleDummy, parent:self, delegate:self.delegate!)
for (url, prefix) in element.resourceURLs {
urls[url] = prefix
}
}
}
}
self.delegate.addedResourceURLs(urls) {
for itemInfo in itemInfos {
self.items.append(itemInfo)
self.itemHeights.append(self.defaultItemHeight)
}
self.tableView.reloadData()
self.tableView.scrollToRow(at: IndexPath(row: self.items.count - 1, section: 0), at: .bottom, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
self.tableView.scrollToRow(at: IndexPath(row: self.items.count - 1, section: 0), at: .bottom, animated: true)
}
}
}
}
override func appendList(_ originator: SwipeNode, name: String, up: Bool, info: [String:Any]) -> Bool {
if (name == "*" || self.name.caseInsensitiveCompare(name) == .orderedSame) {
appendList(originator, info: info)
return true
}
var node: SwipeNode? = self
if up {
while node?.parent != nil {
if let viewNode = node?.parent as? SwipeView {
for c in viewNode.children {
if let e = c as? SwipeElement {
if e.name.caseInsensitiveCompare(name) == .orderedSame {
e.appendList(originator, info: info)
return true
}
}
}
node = node?.parent
} else {
return false
}
}
} else {
for c in children {
if let e = c as? SwipeElement {
if e.updateElement(originator, name:name, up:up, info:info) {
return true
}
}
}
}
return false
}
// SwipeNode
override func getPropertyValue(_ originator: SwipeNode, property: String) -> Any? {
switch (property) {
case "selectedItem":
if let indexPath = self.tableView.indexPathForSelectedRow {
return "\(indexPath.row)"
} else {
return "none"
}
default:
return nil
}
}
override func getPropertiesValue(_ originator: SwipeNode, info: [String:Any]) -> Any? {
let prop = info.keys.first!
switch (prop) {
case "items":
if let indexPath = self.cellIndexPath {
var item = items[indexPath.row]
if let itemStr = info["items"] as? String {
// ie "property":{"items":"data"}}
if let val = item[itemStr] as? String {
// ie "data":String
return val
} else if let valInfo = item[itemStr] as? [String:Any] {
// ie "data":{...}
return originator.evaluate(valInfo)
}
}
// ie "property":{"items":{"data":{...}}}
var path = info["items"] as! [String:Any]
var property = path.keys.first!
while (true) {
if let next = path[property] as? String {
if let sub = item[property] as? [String:Any] {
return sub[next]
} else {
return nil
}
} else if let next = path[property] as? [String:Any] {
if let sub = item[property] as? [String:Any] {
path = next
property = path.keys.first!
item = sub
} else {
return nil
}
} else {
return nil
}
}
// loop on properties in info until get to a String
} else {
print("no cellIndexPath")
}
break;
default:
return nil
}
return nil
}
}
| 8b6d233377517b955881b1114af25cd9 | 37.511475 | 167 | 0.486719 | false | false | false | false |
ahoppen/swift | refs/heads/main | SwiftCompilerSources/Sources/Basic/SourceLoc.swift | apache-2.0 | 1 | //===--- SourceLoc.swift - SourceLoc bridging utilities ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public struct SourceLoc {
/// Points into a source file.
let locationInFile: UnsafePointer<UInt8>
public init?(locationInFile: UnsafePointer<UInt8>?) {
guard let locationInFile = locationInFile else {
return nil
}
self.locationInFile = locationInFile
}
public init?(bridged: BridgedSourceLoc) {
guard let locationInFile = bridged.pointer else {
return nil
}
self.init(locationInFile: locationInFile)
}
public var bridged: BridgedSourceLoc {
.init(pointer: locationInFile)
}
}
extension SourceLoc {
public func advanced(by n: Int) -> SourceLoc {
SourceLoc(locationInFile: locationInFile.advanced(by: n))!
}
}
extension Optional where Wrapped == SourceLoc {
public var bridged: BridgedSourceLoc {
self?.bridged ?? .init(pointer: nil)
}
}
public struct CharSourceRange {
private let start: SourceLoc
private let byteLength: Int
public init(start: SourceLoc, byteLength: Int) {
self.start = start
self.byteLength = byteLength
}
public init?(bridged: BridgedCharSourceRange) {
guard let start = SourceLoc(bridged: bridged.start) else {
return nil
}
self.init(start: start, byteLength: bridged.byteLength)
}
public var bridged: BridgedCharSourceRange {
.init(start: start.bridged, byteLength: byteLength)
}
}
extension Optional where Wrapped == CharSourceRange {
public var bridged: BridgedCharSourceRange {
self?.bridged ?? .init(start: .init(pointer: nil), byteLength: 0)
}
}
| 392ec45ed791d2228a46d12709affcff | 26.671233 | 80 | 0.675248 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/RoundCornersSelectionTableViewCell.swift | apache-2.0 | 3 | //
// RoundCornersSelectionTableViewCell.swift
// SwiftEntryKit_Example
//
// Created by Daniel Huri on 4/25/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
import SwiftEntryKit
class RoundCornersSelectionTableViewCell: SelectionTableViewCell {
override func configure(attributesWrapper: EntryAttributeWrapper) {
super.configure(attributesWrapper: attributesWrapper)
titleValue = "Round Corners"
descriptionValue = "The entry's corners can be rounded in one of the following manner"
insertSegments(by: ["None", "Top", "Bottom", "All"])
selectSegment()
}
private func selectSegment() {
switch attributesWrapper.attributes.roundCorners {
case .none:
segmentedControl.selectedSegmentIndex = 0
case .top(radius: _):
segmentedControl.selectedSegmentIndex = 1
case .bottom(radius: _):
segmentedControl.selectedSegmentIndex = 2
case .all(radius: _):
segmentedControl.selectedSegmentIndex = 3
}
}
@objc override func segmentChanged() {
switch segmentedControl.selectedSegmentIndex {
case 0:
attributesWrapper.attributes.roundCorners = .none
case 1:
attributesWrapper.attributes.roundCorners = .top(radius: 10)
case 2:
attributesWrapper.attributes.roundCorners = .bottom(radius: 10)
case 3:
attributesWrapper.attributes.roundCorners = .all(radius: 10)
default:
break
}
}
}
| f488fa5b4bd2726dbf5cfd780a3883ae | 31.55102 | 94 | 0.647022 | false | false | false | false |
ldt25290/MyInstaMap | refs/heads/master | Climate Control App/Pods/AlamofireImage/Source/UIImage+AlamofireImage.swift | mit | 3 | //
// UIImage+AlamofireImage.swift
//
// Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if os(iOS) || os(tvOS) || os(watchOS)
import CoreGraphics
import Foundation
import UIKit
// MARK: Initialization
private let lock = NSLock()
extension UIImage {
/// Initializes and returns the image object with the specified data in a thread-safe manner.
///
/// It has been reported that there are thread-safety issues when initializing large amounts of images
/// simultaneously. In the event of these issues occurring, this method can be used in place of
/// the `init?(data:)` method.
///
/// - parameter data: The data object containing the image data.
///
/// - returns: An initialized `UIImage` object, or `nil` if the method failed.
public static func af_threadSafeImage(with data: Data) -> UIImage? {
lock.lock()
let image = UIImage(data: data)
lock.unlock()
return image
}
/// Initializes and returns the image object with the specified data and scale in a thread-safe manner.
///
/// It has been reported that there are thread-safety issues when initializing large amounts of images
/// simultaneously. In the event of these issues occurring, this method can be used in place of
/// the `init?(data:scale:)` method.
///
/// - parameter data: The data object containing the image data.
/// - parameter scale: The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0
/// results in an image whose size matches the pixel-based dimensions of the image. Applying a
/// different scale factor changes the size of the image as reported by the size property.
///
/// - returns: An initialized `UIImage` object, or `nil` if the method failed.
public static func af_threadSafeImage(with data: Data, scale: CGFloat) -> UIImage? {
lock.lock()
let image = UIImage(data: data, scale: scale)
lock.unlock()
return image
}
}
// MARK: - Inflation
extension UIImage {
private struct AssociatedKey {
static var inflated = "af_UIImage.Inflated"
}
/// Returns whether the image is inflated.
public var af_inflated: Bool {
get {
if let inflated = objc_getAssociatedObject(self, &AssociatedKey.inflated) as? Bool {
return inflated
} else {
return false
}
}
set {
objc_setAssociatedObject(self, &AssociatedKey.inflated, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Inflates the underlying compressed image data to be backed by an uncompressed bitmap representation.
///
/// Inflating compressed image formats (such as PNG or JPEG) can significantly improve drawing performance as it
/// allows a bitmap representation to be constructed in the background rather than on the main thread.
public func af_inflate() {
guard !af_inflated else { return }
af_inflated = true
_ = cgImage?.dataProvider?.data
}
}
// MARK: - Alpha
extension UIImage {
/// Returns whether the image contains an alpha component.
public var af_containsAlphaComponent: Bool {
let alphaInfo = cgImage?.alphaInfo
return (
alphaInfo == .first ||
alphaInfo == .last ||
alphaInfo == .premultipliedFirst ||
alphaInfo == .premultipliedLast
)
}
/// Returns whether the image is opaque.
public var af_isOpaque: Bool { return !af_containsAlphaComponent }
}
// MARK: - Scaling
extension UIImage {
/// Returns a new version of the image scaled to the specified size.
///
/// - parameter size: The size to use when scaling the new image.
///
/// - returns: A new image object.
public func af_imageScaled(to size: CGSize) -> UIImage {
assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height")
UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0)
draw(in: CGRect(origin: .zero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
return scaledImage
}
/// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fit within
/// a specified size.
///
/// The resulting image contains an alpha component used to pad the width or height with the necessary transparent
/// pixels to fit the specified size. In high performance critical situations, this may not be the optimal approach.
/// To maintain an opaque image, you could compute the `scaledSize` manually, then use the `af_imageScaledToSize`
/// method in conjunction with a `.Center` content mode to achieve the same visual result.
///
/// - parameter size: The size to use when scaling the new image.
///
/// - returns: A new image object.
public func af_imageAspectScaled(toFit size: CGSize) -> UIImage {
assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height")
let imageAspectRatio = self.size.width / self.size.height
let canvasAspectRatio = size.width / size.height
var resizeFactor: CGFloat
if imageAspectRatio > canvasAspectRatio {
resizeFactor = size.width / self.size.width
} else {
resizeFactor = size.height / self.size.height
}
let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor)
let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
draw(in: CGRect(origin: origin, size: scaledSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
return scaledImage
}
/// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fill a
/// specified size. Any pixels that fall outside the specified size are clipped.
///
/// - parameter size: The size to use when scaling the new image.
///
/// - returns: A new image object.
public func af_imageAspectScaled(toFill size: CGSize) -> UIImage {
assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height")
let imageAspectRatio = self.size.width / self.size.height
let canvasAspectRatio = size.width / size.height
var resizeFactor: CGFloat
if imageAspectRatio > canvasAspectRatio {
resizeFactor = size.height / self.size.height
} else {
resizeFactor = size.width / self.size.width
}
let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor)
let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0)
UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0)
draw(in: CGRect(origin: origin, size: scaledSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
return scaledImage
}
}
// MARK: - Rounded Corners
extension UIImage {
/// Returns a new version of the image with the corners rounded to the specified radius.
///
/// - parameter radius: The radius to use when rounding the new image.
/// - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the
/// image has the same resolution for all screen scales such as @1x, @2x and
/// @3x (i.e. single image from web server). Set to `false` for images loaded
/// from an asset catalog with varying resolutions for each screen scale.
/// `false` by default.
///
/// - returns: A new image object.
public func af_imageRounded(withCornerRadius radius: CGFloat, divideRadiusByImageScale: Bool = false) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let scaledRadius = divideRadiusByImageScale ? radius / scale : radius
let clippingPath = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: size), cornerRadius: scaledRadius)
clippingPath.addClip()
draw(in: CGRect(origin: CGPoint.zero, size: size))
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return roundedImage
}
/// Returns a new version of the image rounded into a circle.
///
/// - returns: A new image object.
public func af_imageRoundedIntoCircle() -> UIImage {
let radius = min(size.width, size.height) / 2.0
var squareImage = self
if size.width != size.height {
let squareDimension = min(size.width, size.height)
let squareSize = CGSize(width: squareDimension, height: squareDimension)
squareImage = af_imageAspectScaled(toFill: squareSize)
}
UIGraphicsBeginImageContextWithOptions(squareImage.size, false, 0.0)
let clippingPath = UIBezierPath(
roundedRect: CGRect(origin: CGPoint.zero, size: squareImage.size),
cornerRadius: radius
)
clippingPath.addClip()
squareImage.draw(in: CGRect(origin: CGPoint.zero, size: squareImage.size))
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return roundedImage
}
}
#endif
#if os(iOS) || os(tvOS)
import CoreImage
// MARK: - Core Image Filters
@available(iOS 9.0, *)
extension UIImage {
/// Returns a new version of the image using a CoreImage filter with the specified name and parameters.
///
/// - parameter name: The name of the CoreImage filter to use on the new image.
/// - parameter parameters: The parameters to apply to the CoreImage filter.
///
/// - returns: A new image object, or `nil` if the filter failed for any reason.
public func af_imageFiltered(withCoreImageFilter name: String, parameters: [String: Any]? = nil) -> UIImage? {
var image: CoreImage.CIImage? = ciImage
if image == nil, let CGImage = self.cgImage {
image = CoreImage.CIImage(cgImage: CGImage)
}
guard let coreImage = image else { return nil }
let context = CIContext(options: [kCIContextPriorityRequestLow: true])
var parameters: [String: Any] = parameters ?? [:]
parameters[kCIInputImageKey] = coreImage
guard let filter = CIFilter(name: name, withInputParameters: parameters) else { return nil }
guard let outputImage = filter.outputImage else { return nil }
let cgImageRef = context.createCGImage(outputImage, from: outputImage.extent)
return UIImage(cgImage: cgImageRef!, scale: scale, orientation: imageOrientation)
}
}
#endif
| 33deefcabcbf75879a57904ee8d0fd12 | 38.536508 | 122 | 0.660591 | false | false | false | false |
904388172/-TV | refs/heads/master | DouYuTV/DouYuTV/Classes/Home/View/MenuView.swift | mit | 1 | //
// MenuView.swift
// DouYuTV
//
// Created by GS on 2017/10/26.
// Copyright © 2017年 Demo. All rights reserved.
//
import UIKit
private let kMenuCellID = "kMenuCellID"
class MenuView: UIView {
//MARK: - 定义属性
var groups: [AnchorGroup]? {
didSet {
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
//MARK: - 从xib中加载出来
override func awakeFromNib() {
super.awakeFromNib()
//xib方式注册cell
collectionView.register(UINib(nibName: "CollectionMenuCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
//必须在这个方法里面布局
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
// 行间距
layout.minimumLineSpacing = 0
//item之间的间距
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
}
}
//MARK: - 从xib中快速创建的类方法
extension MenuView {
class func menuView() -> MenuView {
return Bundle.main.loadNibNamed("MenuView", owner: nil, options: nil)?.first as! MenuView
}
}
//MARK: - UICollectionView dataSource
extension MenuView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groups == nil {
return 0
}
let pageNum = (groups!.count - 1) / 8 + 1
if pageNum <= 1 {
pageControl.isHidden = true
} else {
//只显示两个
// pageNum = 2
//显示多个
pageControl.numberOfPages = pageNum
}
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! CollectionMenuCell
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
//像里面的cell传递数据
private func setupCellDataWithCell(cell: CollectionMenuCell, indexPath: IndexPath) {
//0页:0~7
//1页:8~15
//2页:16~23
//1.取出起始位置,终点位置
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
//2.判断越界问题
if endIndex > (groups?.count)! - 1 {
endIndex = (groups?.count)! - 1
}
//3.取出数据,赋值给cell
cell.groups = Array(groups![startIndex...endIndex])
}
}
//MARK: - UICollectionView Delegate
extension MenuView: UICollectionViewDelegate {
//监听滚动
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//计算pageControl的currentIndex
pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
}
}
| 0cbdf4fa74b2e0e4050939229ae562f5 | 24.878049 | 126 | 0.612001 | false | false | false | false |
kamawshuang/iOS---Animation | refs/heads/master | 3D动画(八)/3Dstart/3DSlideMenu/3DSlideMenu/MenuButton.swift | apache-2.0 | 2 | ////
//// MenuButton.swift
//// 3DSlideMenu
////
//// Created by 51Testing on 15/12/9.
//// Copyright © 2015年 HHW. All rights reserved.
////
////
//import UIKit
//
//
////自定义按钮
//class MenuButton: UIView {
//
// var imageView: UIImageView!
// var tapHandler: (()->())?
//
// //当视图移动完成后调用
// override func didMoveToSuperview() {
// frame = CGRect(x: 0.0, y: 0.0, width: 20.0, height: 20.0)
// imageView = UIImageView(image: UIImage(named: "menu.png"))
// imageView.userInteractionEnabled = true
// imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("didTap")))
// addSubview(imageView)
// }
//
// func didTap() {
// tapHandler?()
// }
//
//}
import UIKit
class MenuButton: UIView {
var imageView: UIImageView!
var tapHandler: (()->())?
override func didMoveToSuperview() {
frame = CGRect(x: 0.0, y: 0.0, width: 20.0, height: 20.0)
imageView = UIImageView(image:UIImage(named:"menu.png"))
imageView.userInteractionEnabled = true
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("didTap")))
addSubview(imageView)
}
func didTap() {
tapHandler?()
}
} | 3983cb6727d5347daefd33b5935c690a | 23.415094 | 106 | 0.589327 | false | false | false | false |
HeMet/DLife | refs/heads/master | MVVMKit/MVVMKit/DataBindings/Adapters/Utils/CellViewBindingManager.swift | mit | 1 | //
// CellViewBindingManager.swift
// MVVMKit
//
// Created by Евгений Губин on 15.07.15.
// Copyright (c) 2015 SimbirSoft. All rights reserved.
//
import UIKit
public class CellViewBindingManager {
typealias Binding = (AnyObject, NSIndexPath) -> UITableViewCell
public typealias BindingCallback = (UITableViewCell, NSIndexPath) -> ()
unowned(unsafe) var tableView: UITableView
var bindings: [String:Binding] = [:]
public var onWillBind: BindingCallback?
public var onDidBind: BindingCallback?
public init(tableView: UITableView) {
self.tableView = tableView
}
public func register<V: UITableViewCell where V: BindableCellView>(viewType: V.Type) {
if tableView.dequeueReusableCellWithIdentifier(V.CellIdentifier) == nil {
tableView.registerClass(V.self, forCellReuseIdentifier: V.CellIdentifier)
}
registerBinding(viewType)
}
public func register<V: UITableViewCell where V: BindableCellView, V: NibSource>(viewType: V.Type) {
if tableView.dequeueReusableCellWithIdentifier(V.CellIdentifier) == nil {
let nib = UINib(nibName: V.NibIdentifier, bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: V.CellIdentifier)
}
registerBinding(viewType)
}
func registerBinding<V: BindableCellView where V: UITableViewCell>(viewType: V.Type) {
let typeName = nameOfType(V.ViewModelType.self)
bindings[typeName] = { [unowned self] viewModel, indexPath in
let view = self.tableView.dequeueReusableCellWithIdentifier(V.CellIdentifier, forIndexPath: indexPath) as! V
view.viewModel = viewModel as! V.ViewModelType
self.onWillBind?(view, indexPath)
view.bindToViewModel()
self.onDidBind?(view, indexPath)
return view
}
}
public func unregister<V: ViewForViewModel>(viewType: V.Type) {
let typeName = nameOfType(V.ViewModelType.self)
bindings[typeName] = nil
}
func bindViewModel(viewModel: AnyObject, indexPath: NSIndexPath) -> UITableViewCell {
let typeName = nameOfType(viewModel)
if let binding = bindings[typeName] {
return binding(viewModel, indexPath)
}
fatalError("Unknown view model type")
}
func nameOfType(obj: AnyObject) -> String {
return "\(obj.dynamicType)"
}
func nameOfType<T>(type: T.Type) -> String {
return "\(type)"
}
deinit {
println("deinit bindings manager")
}
} | 09eb312a35c2eee041e3ba827ab99669 | 31.609756 | 120 | 0.638982 | false | false | false | false |
wangjwchn/MetalAcc | refs/heads/master | MetalAcc/AccImage.swift | mit | 1 | //
// AccImage.swift
// MetalAcc
//
// Created by 王佳玮 on 16/4/19.
// Copyright © 2016年 wangjwchn. All rights reserved.
//
import MetalKit
import ImageIO
public class AccImage{
private var commandQueue:MTLCommandQueue
private var textures = [MTLTexture]()
public var filter:AccImageFilter?
init(){
self.commandQueue = MTLCreateSystemDefaultDevice()!.newCommandQueue()
}
public func Input(image:UIImage){
let texture = image.toMTLTexture()
if(textures.isEmpty==true){
textures.append(texture.sameSizeEmptyTexture())//outTexture
}
textures.append(texture)
}
public func AddProcessor(filter:AccImageFilter){
self.filter = filter
}
public func Processing(){
self.commandQueue.addAccCommand((self.filter!.pipelineState!), textures: textures, factors: self.filter!.getFactors())
}
public func Output()->UIImage{
let image = textures[0].toImage()
return image
}
}
| eb09ae86771f7e1e071325c25f67edfa | 24.45 | 126 | 0.649312 | false | false | false | false |
snazzware/HexMatch | refs/heads/master | HexMatch/Scenes/LevelScene.swift | gpl-3.0 | 2 | //
// LevelScene.swift
// HexMatch
//
// Created by Josh McKee on 1/28/16.
// Copyright © 2016 Josh McKee. All rights reserved.
//
import SpriteKit
import SNZSpriteKitUI
class LevelScene: SNZScene {
var checkboxMobilePieces: SNZCheckButtonWidget?
var checkboxEnemyPieces: SNZCheckButtonWidget?
var checkboxSoundEffects: SNZCheckButtonWidget?
override func didMove(to view: SKView) {
super.didMove(to: view)
self.updateGui()
}
func updateGui() {
self.removeAllChildren()
self.widgets.removeAll()
// Set background
self.backgroundColor = UIColor(red: 0x69/255, green: 0x65/255, blue: 0x6f/255, alpha: 1.0)
// Create primary header
let header = SNZSceneHeaderWidget()
header.caption = "Menu"
self.addWidget(header)
// Add copyright
let copyrightLabel = SKLabelNode(fontNamed: "Avenir-Black")
copyrightLabel.text = "Mergel ©2016 Josh M. McKee"
copyrightLabel.fontColor = UIColor.white
copyrightLabel.fontSize = 12
copyrightLabel.horizontalAlignmentMode = .center
copyrightLabel.verticalAlignmentMode = .center
copyrightLabel.position = CGPoint(x: self.size.width / 2, y: 8)
copyrightLabel.ignoreTouches = true
self.addChild(copyrightLabel)
var verticalOffset:CGFloat = self.frame.height - 60
// Create and position option buttons
let horizontalOffset:CGFloat = self.frame.width < 500 ? 20 : 300
verticalOffset = self.frame.width < 500 ? verticalOffset - 60 : self.frame.height - 120
self.checkboxSoundEffects = MergelCheckButtonWidget(parentNode: self)
self.checkboxSoundEffects!.isChecked = GameState.instance!.getIntForKey("enable_sound_effects", 1) == 1
self.checkboxSoundEffects!.caption = "Sound Effects"
self.checkboxSoundEffects!.position = CGPoint(x: horizontalOffset,y: verticalOffset)
self.addWidget(self.checkboxSoundEffects!)
/*self.checkboxMobilePieces = MergelCheckButtonWidget(parentNode: self)
self.checkboxMobilePieces!.isChecked = GameState.instance!.getIntForKey("include_mobile_pieces", 1) == 1
self.checkboxMobilePieces!.caption = "Moving Shapes"
self.checkboxMobilePieces!.position = CGPointMake(horizontalOffset,verticalOffset)
self.addWidget(self.checkboxMobilePieces!)*/
verticalOffset -= 120
/*self.checkboxEnemyPieces = MergelCheckButtonWidget(parentNode: self)
self.checkboxEnemyPieces!.isChecked = GameState.instance!.getIntForKey("include_enemy_pieces", 1) == 1
self.checkboxEnemyPieces!.caption = "Vanilla Gel"
self.checkboxEnemyPieces!.position = CGPointMake(horizontalOffset,verticalOffset)
self.addWidget(self.checkboxEnemyPieces!)*/
// Add the New Game button
let newGameButton = MergelButtonWidget(parentNode: self)
newGameButton.position = CGPoint(x: horizontalOffset,y: verticalOffset)
newGameButton.caption = "New Game"
newGameButton.bind("tap",{
self.view?.presentScene(SceneHelper.instance.newGameScene, transition: SKTransition.push(with: SKTransitionDirection.up, duration: 0.4))
});
self.addWidget(newGameButton)
verticalOffset -= 60
// Add the Help button
let helpButton = MergelButtonWidget(parentNode: self)
helpButton.position = CGPoint(x: horizontalOffset,y: verticalOffset)
helpButton.caption = "How to Play"
helpButton.bind("tap",{
UIApplication.shared.openURL(URL(string:"https://github.com/snazzware/Mergel/blob/master/HELP.md")!)
});
self.addWidget(helpButton)
verticalOffset -= 60
// Add the About button
let aboutButton = MergelButtonWidget(parentNode: self)
aboutButton.position = CGPoint(x: horizontalOffset,y: verticalOffset)
aboutButton.caption = "About Mergel"
aboutButton.bind("tap",{
UIApplication.shared.openURL(URL(string:"https://github.com/snazzware/Mergel/blob/master/ABOUT.md")!)
});
self.addWidget(aboutButton)
verticalOffset -= 60
// Add the Issues button
let issuesButton = MergelButtonWidget(parentNode: self)
issuesButton.position = CGPoint(x: horizontalOffset,y: verticalOffset)
issuesButton.caption = "Bugs & Requests"
issuesButton.bind("tap",{
UIApplication.shared.openURL(URL(string:"https://github.com/snazzware/Mergel/issues")!)
});
self.addWidget(issuesButton)
// Add the close button
let closeButton = MergelButtonWidget(parentNode: self)
closeButton.anchorPoint = CGPoint(x: 0,y: 0)
closeButton.caption = "Back"
closeButton.bind("tap",{
self.captureSettings()
self.close()
});
self.addWidget(closeButton)
// Render the widgets
self.renderWidgets()
}
func captureSettings() {
//GameState.instance!.setIntForKey("include_mobile_pieces", self.checkboxMobilePieces!.isChecked ? 1 : 0 )
//GameState.instance!.setIntForKey("include_enemy_pieces", self.checkboxEnemyPieces!.isChecked ? 1 : 0 )
GameState.instance!.setIntForKey("enable_sound_effects", self.checkboxSoundEffects!.isChecked ? 1 : 0 )
if (GameState.instance!.getIntForKey("enable_sound_effects", 1) == 1) {
SoundHelper.instance.enableSoundEffects()
} else {
SoundHelper.instance.disableSoundEffects()
}
}
func close() {
self.view?.presentScene(SceneHelper.instance.gameScene, transition: SKTransition.push(with: SKTransitionDirection.down, duration: 0.4))
}
}
| 04967a82deca02952450fe88ebffef07 | 39.739726 | 148 | 0.652824 | false | false | false | false |
Sorix/CloudCore | refs/heads/master | Source/Classes/Setup Operation/SubscribeOperation.swift | mit | 1 | //
// SubscribeOperation.swift
// CloudCore
//
// Created by Vasily Ulianov on 12/12/2017.
// Copyright © 2017 Vasily Ulianov. All rights reserved.
//
import Foundation
import CloudKit
#if !os(watchOS)
@available(watchOS, unavailable)
class SubscribeOperation: AsynchronousOperation {
var errorBlock: ErrorBlock?
private let queue = OperationQueue()
override func main() {
super.main()
let container = CloudCore.config.container
// Subscribe operation
let subcribeToPrivate = self.makeRecordZoneSubscriptionOperation(for: container.privateCloudDatabase, id: CloudCore.config.subscriptionIDForPrivateDB)
// Fetch subscriptions and cancel subscription operation if subscription is already exists
let fetchPrivateSubscriptions = makeFetchSubscriptionOperation(for: container.privateCloudDatabase,
searchForSubscriptionID: CloudCore.config.subscriptionIDForPrivateDB,
operationToCancelIfSubcriptionExists: subcribeToPrivate)
subcribeToPrivate.addDependency(fetchPrivateSubscriptions)
// Finish operation
let finishOperation = BlockOperation {
self.state = .finished
}
finishOperation.addDependency(subcribeToPrivate)
finishOperation.addDependency(fetchPrivateSubscriptions)
queue.addOperations([subcribeToPrivate, fetchPrivateSubscriptions, finishOperation], waitUntilFinished: false)
}
private func makeRecordZoneSubscriptionOperation(for database: CKDatabase, id: String) -> CKModifySubscriptionsOperation {
let notificationInfo = CKNotificationInfo()
notificationInfo.shouldSendContentAvailable = true
let subscription = CKRecordZoneSubscription(zoneID: CloudCore.config.zoneID, subscriptionID: id)
subscription.notificationInfo = notificationInfo
let operation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: [])
operation.modifySubscriptionsCompletionBlock = {
if let error = $2 {
// Cancellation is not an error
if case CKError.operationCancelled = error { return }
self.errorBlock?(error)
}
}
operation.database = database
return operation
}
private func makeFetchSubscriptionOperation(for database: CKDatabase, searchForSubscriptionID subscriptionID: String, operationToCancelIfSubcriptionExists operationToCancel: CKModifySubscriptionsOperation) -> CKFetchSubscriptionsOperation {
let fetchSubscriptions = CKFetchSubscriptionsOperation(subscriptionIDs: [subscriptionID])
fetchSubscriptions.database = database
fetchSubscriptions.fetchSubscriptionCompletionBlock = { subscriptions, error in
// If no errors = subscription is found and we don't need to subscribe again
if error == nil {
operationToCancel.cancel()
}
}
return fetchSubscriptions
}
}
#endif
| a9639a9a3cc2260d5eb2755b0556dec6 | 33.493827 | 241 | 0.78418 | false | false | false | false |
garygriswold/Bible.js | refs/heads/master | OBSOLETE/YourBible/plugins/com-shortsands-utility/src/ios/Utility/Sqlite3.swift | mit | 1 | //
// Sqlite3.swift
// Utility
//
// Created by Gary Griswold on 4/19/2019.
// Copyright © 2018 ShortSands. All rights reserved.
//
// Documentation of the sqlite3 C interface
// https://www.sqlite.org/cintro.html
//
import Foundation
import SQLite3
public enum Sqlite3Error: Error {
case databaseNotOpenError(name: String)
case directoryCreateError(name: String, srcError: Error)
case databaseNotFound(name: String)
case databaseNotInBundle(name: String)
case databaseCopyError(name: String, srcError: Error)
case databaseOpenError(name: String, sqliteError: String)
case databaseColBindError(value: Any)
case statementPrepareFailed(sql: String, sqliteError: String)
case statementExecuteFailed(sql: String, sqliteError: String)
}
public class Sqlite3 {
private static var openDatabases = Dictionary<String, Sqlite3>()
public static func findDB(dbname: String) throws -> Sqlite3 {
if let openDB: Sqlite3 = openDatabases[dbname] {
return openDB
} else {
throw Sqlite3Error.databaseNotOpenError(name: dbname)
}
}
public static func openDB(dbname: String, copyIfAbsent: Bool) throws -> Sqlite3 {
if let openDB: Sqlite3 = openDatabases[dbname] {
return openDB
} else {
let newDB = Sqlite3()
try newDB.open(dbname: dbname, copyIfAbsent: copyIfAbsent)
openDatabases[dbname] = newDB
return newDB
}
}
public static func closeDB(dbname: String) {
if let openDB: Sqlite3 = openDatabases[dbname] {
openDB.close()
openDatabases.removeValue(forKey: dbname)
}
}
public static func listDB() throws -> [String] {
var results = [String]()
let db = Sqlite3()
let files = try FileManager.default.contentsOfDirectory(atPath: db.databaseDir.path)
for file in files {
if file.hasSuffix(".db") {
results.append(file)
}
}
return results
}
public static func deleteDB(dbname: String) throws {
let db = Sqlite3()
let fullPath: URL = db.databaseDir.appendingPathComponent(dbname)
try FileManager.default.removeItem(at: fullPath)
}
private var databaseDir: URL
private var database: OpaquePointer?
public init() {
print("****** Init Sqlite3 ******")
let homeDir: URL = URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)
let libDir: URL = homeDir.appendingPathComponent("Library")
let dbDir: URL = libDir.appendingPathComponent("LocalDatabase")
self.databaseDir = dbDir
self.database = nil
}
// Could introduce alternate init that introduces different databaseDir
deinit {
print("****** Deinit Sqlite3 ******")
}
public var isOpen: Bool {
get {
return self.database != nil
}
}
public func open(dbname: String, copyIfAbsent: Bool) throws {
self.database = nil
let fullPath = try self.ensureDatabase(dbname: dbname, copyIfAbsent: copyIfAbsent)
var db: OpaquePointer? = nil
let result = sqlite3_open(fullPath.path, &db)
if result == SQLITE_OK {
print("Successfully opened connection to database at \(fullPath)")
self.database = db!
} else {
print("SQLITE Result Code = \(result)")
let openMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.databaseOpenError(name: dbname, sqliteError: openMsg)
}
}
/** This open method is used by command line or other programs that open the database at a
* specified path, not in the bundle.
*/
public func openLocal(dbname: String) throws {
self.database = nil
var db: OpaquePointer? = nil
let result = sqlite3_open(dbname, &db)
if result == SQLITE_OK {
print("Successfully opened connection to database at \(dbname)")
self.database = db!
} else {
print("SQLITE Result Code = \(result)")
let openMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.databaseOpenError(name: dbname, sqliteError: openMsg)
}
}
private func ensureDatabase(dbname: String, copyIfAbsent: Bool) throws -> URL {
let fullPath: URL = self.databaseDir.appendingPathComponent(dbname)
print("Opening Database at \(fullPath.path)")
if FileManager.default.isReadableFile(atPath: fullPath.path) {
return fullPath
} else if !copyIfAbsent {
try self.ensureDirectory()
return fullPath
} else {
print("Copy Bundle at \(dbname)")
try self.ensureDirectory()
let parts = dbname.split(separator: ".")
let name = String(parts[0])
let ext = String(parts[1])
let bundle = Bundle.main
print("bundle \(bundle.bundlePath)")
var bundlePath = bundle.url(forResource: name, withExtension: ext, subdirectory: "www")
if bundlePath == nil {
// This option is here only because I have not been able to get databases in www in my projects
bundlePath = bundle.url(forResource: name, withExtension: ext)
}
if bundlePath != nil {
do {
try FileManager.default.copyItem(at: bundlePath!, to: fullPath)
return fullPath
} catch let err {
throw Sqlite3Error.databaseCopyError(name: dbname, srcError: err)
}
} else {
throw Sqlite3Error.databaseNotInBundle(name: dbname)
}
}
}
private func ensureDirectory() throws {
let file = FileManager.default
if !file.fileExists(atPath: self.databaseDir.path) {
do {
try file.createDirectory(at: self.databaseDir, withIntermediateDirectories: true, attributes: nil)
} catch let err {
throw Sqlite3Error.directoryCreateError(name: self.databaseDir.path, srcError: err)
}
}
}
public func close() {
if database != nil {
sqlite3_close(database)
database = nil
}
}
/**
* This is the single statement execute
*/
public func executeV1(sql: String, values: [Any?]) throws -> Int {
if database != nil {
var statement: OpaquePointer? = nil
let prepareOut = sqlite3_prepare_v2(database, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
if prepareOut == SQLITE_OK {
try self.bindStatement(statement: statement!, values: values)
let stepOut = sqlite3_step(statement)
if stepOut == SQLITE_DONE {
let rowCount = Int(sqlite3_changes(database))
return rowCount
} else {
let execMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementExecuteFailed(sql: sql, sqliteError: execMsg)
}
} else {
let prepareMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementPrepareFailed(sql: sql, sqliteError: prepareMsg)
}
} else {
throw Sqlite3Error.databaseNotFound(name: "unknown")
}
}
/*
* This method executes an array of values against one prepared statement
*/
public func bulkExecuteV1(sql: String, values: [[Any?]]) throws -> Int {
var totalRowCount = 0
if database != nil {
var statement: OpaquePointer? = nil
let prepareOut = sqlite3_prepare_v2(database, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
if prepareOut == SQLITE_OK {
for row: [Any?] in values {
try self.bindStatement(statement: statement!, values: row)
if sqlite3_step(statement) == SQLITE_DONE {
let rowCount = Int(sqlite3_changes(database))
totalRowCount += rowCount
sqlite3_reset(statement);
} else {
let execMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementExecuteFailed(sql: sql, sqliteError: execMsg)
}
}
return totalRowCount
} else {
let prepareMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementPrepareFailed(sql: sql, sqliteError: prepareMsg)
}
} else {
throw Sqlite3Error.databaseNotFound(name: "unknown")
}
}
/**
* This one is written to conform to the query interface of the cordova sqlite plugin. It returns
* a JSON array that can be serialized and sent back to Javascript. It supports both String and Int
* results, because that is what are used in the current databases.
*/
public func queryJS(sql: String, values: [Any?]) throws -> Data {
let results: [Dictionary<String,Any?>] = try self.queryV0(sql: sql, values: values)
var message: Data
do {
message = try JSONSerialization.data(withJSONObject: results)
} catch let jsonError {
print("ERROR while converting resultSet to JSON \(jsonError)")
let errorMessage = "{\"Error\": \"Sqlite3.queryJS \(jsonError.localizedDescription)\"}"
message = errorMessage.data(using: String.Encoding.utf8)!
}
return message
}
/**
* This returns a classic sql result set as an array of dictionaries. It is probably not a good choice
* if a large number of rows are returned. It returns types: String, Int, Double, and nil because JSON
* will accept these types.
*/
public func queryV0(sql: String, values: [Any?]) throws -> [Dictionary<String,Any?>] {
if database != nil {
var resultSet = [Dictionary<String,Any?>]()
var statement: OpaquePointer? = nil
let prepareOut = sqlite3_prepare_v2(database, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
if prepareOut == SQLITE_OK {
try self.bindStatement(statement: statement!, values: values)
let colCount = Int(sqlite3_column_count(statement))
while (sqlite3_step(statement) == SQLITE_ROW) {
var row = Dictionary<String, Any?>()
for i in 0..<colCount {
let col = Int32(i)
let name = String(cString: sqlite3_column_name(statement, col))
let type: Int32 = sqlite3_column_type(statement, col)
switch type {
case 1: // INT
row[name] = Int(sqlite3_column_int(statement, col))
break
case 2: // Double
row[name] = sqlite3_column_double(statement, col)
break
case 3: // TEXT
row[name] = String(cString: sqlite3_column_text(statement, col))
break
case 5: // NULL
row[name] = nil
break
default:
row[name] = String(cString: sqlite3_column_text(statement, col))
break
}
}
resultSet.append(row)
}
return resultSet
} else {
let prepareMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementPrepareFailed(sql: sql, sqliteError: prepareMsg)
}
} else {
throw Sqlite3Error.databaseNotFound(name: "unknown")
}
}
/**
* This execute accepts only strings on the understanding that sqlite will convert data into the type
* that is correct based on the affinity of the type in the database.
*
* Also, this query method returns a resultset that is an array of an array of Strings.
*/
public func queryV1(sql: String, values: [Any?]) throws -> [[String?]] {
if database != nil {
var resultSet: [[String?]] = []
var statement: OpaquePointer? = nil
let prepareOut = sqlite3_prepare_v2(database, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
if prepareOut == SQLITE_OK {
try self.bindStatement(statement: statement!, values: values)
let colCount = Int(sqlite3_column_count(statement))
while (sqlite3_step(statement) == SQLITE_ROW) {
var row: [String?] = [String?] (repeating: nil, count: colCount)
for i in 0..<colCount {
if let cValue = sqlite3_column_text(statement, Int32(i)) {
row[i] = String(cString: cValue)
} else {
row[i] = nil
}
}
resultSet.append(row)
}
return resultSet
} else {
let prepareMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementPrepareFailed(sql: sql, sqliteError: prepareMsg)
}
} else {
throw Sqlite3Error.databaseNotFound(name: "unknown")
}
}
private func bindStatement(statement: OpaquePointer, values: [Any?]) throws {
for i in 0..<values.count {
let col = Int32(i + 1)
let value = values[i];
if value is String {
sqlite3_bind_text(statement, col, (value as! NSString).utf8String, -1, nil)
} else if value is Int {
sqlite3_bind_int(statement, col, Int32(value as! Int))
} else if value is Double {
sqlite3_bind_double(statement, col, (value as! Double))
} else if value == nil {
sqlite3_bind_null(statement, col)
} else {
throw Sqlite3Error.databaseColBindError(value: value!)
}
}
}
public static func errorDescription(error: Error) -> String {
if error is Sqlite3Error {
switch error {
case Sqlite3Error.databaseNotOpenError(let name) :
return "DatabaseNotOpen: \(name)"
case Sqlite3Error.directoryCreateError(let name, let srcError) :
return "DirectoryCreateError \(srcError) at \(name)"
case Sqlite3Error.databaseNotFound(let name) :
return "DatabaseNotFound: \(name)"
case Sqlite3Error.databaseNotInBundle(let name) :
return "DatabaseNotInBundle: \(name)"
case Sqlite3Error.databaseCopyError(let name, let srcError) :
return "DatabaseCopyError: \(srcError.localizedDescription) \(name)"
case Sqlite3Error.databaseOpenError(let name, let sqliteError) :
return "SqliteOpenError: \(sqliteError) on database: \(name)"
case Sqlite3Error.databaseColBindError(let value) :
return "DatabaseBindError: value: \(value)"
case Sqlite3Error.statementPrepareFailed(let sql, let sqliteError) :
return "StatementPrepareFailed: \(sqliteError) on stmt: \(sql)"
case Sqlite3Error.statementExecuteFailed(let sql, let sqliteError) :
return "StatementExecuteFailed: \(sqliteError) on stmt: \(sql)"
default:
return "Unknown Sqlite3Error"
}
} else {
return "Unknown Error Type"
}
}
}
/*
One person's recommendation to make sqlite threadsafe.
+(sqlite3*) getInstance {
if (instance == NULL) {
sqlite3_shutdown();
sqlite3_config(SQLITE_CONFIG_SERIALIZED);
sqlite3_initialize();
NSLog(@"isThreadSafe %d", sqlite3_threadsafe());
const char *path = [@"./path/to/db/db.sqlite" cStringUsingEncoding:NSUTF8StringEncoding];
if (sqlite3_open_v2(path, &database, SQLITE_OPEN_READWRITE|SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) {
NSLog(@"Database opening failed!");
}
}
return instance;
}
*/
| d4785a1d93eb32c3a63c8fc617d1a9e7 | 39.929612 | 114 | 0.565736 | false | false | false | false |
necrowman/CRLAlamofireFuture | refs/heads/master | Examples/SimpleIOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleIOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Tests/CRLAlamofireFuture/SimpleTest.swift | mit | 18 | //
// CRLAlamofireFuture_iOSTests.swift
// CRLAlamofireFuture iOSTests
//
// Created by Ruslan Yupyn on 7/4/16.
//
//
import XCTest
import Alamofire
import Future
import CRLAlamofireFuture
class CRLAlamofireFuture_iOSTests: XCTestCase {
let correctURLBase = "https://raw.githubusercontent.com/necrowman/CRLAlomofireFeature/master/"
let uncorrectURLBase = "https://raw.githubusercontent12.com/necrowman/CRLAlomofireFeature/master/"
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
//MARK: - responseString() -> Future<String> testing
func testSimpleString() {
let asyncExpectation = expectationWithDescription("AlamofireResponseString")
let urlString = "\(correctURLBase)simpleTestURL.txt"
let future = Alamofire.request(.GET, urlString).responseString()
future.onSuccess { value in
print("RESULT VALUE -> ", value)
XCTAssertEqual(value, "Test String")
asyncExpectation.fulfill()
}
future.onFailure { error in
print("ERROR VALUE -> ", error)
XCTFail("Whoops, error \(error)")
asyncExpectation.fulfill()
}
self.waitForExpectationsWithTimeout(5) { error in
XCTAssertNil(error)
}
}
func testExample() {
XCTAssertEqual(CRLAlamofireFuture.instance.frameworkFunctionExample(), "This is test framework function example")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| b3ea06b2418edf2b91938a3e7231a60e | 31.016393 | 121 | 0.645161 | false | true | false | false |
Xiomara7/Apps | refs/heads/master | Apps/AppDetailsController.swift | mit | 1 | //
// AppDetailsController.swift
// Apps
//
// Created by Xiomara on 2/14/17.
// Copyright © 2017 Xiomara. All rights reserved.
//
import UIKit
class AppDetailsController: UIViewController {
var appShown: App!
@IBOutlet weak var circle: UIImageView!
@IBOutlet weak var appImageView: UIImageView!
@IBOutlet weak var appSummary: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
appImageView.layer.borderColor = UIColor.white.cgColor
appImageView.layer.borderWidth = 1.0
appImageView.layer.cornerRadius = 15.0
appImageView.layer.masksToBounds = true
UIView.animate(withDuration: 1.5, animations: {
let scaleTransform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.circle.transform = scaleTransform
self.circle.frame.origin.y = 64.0
self.appImageView.setImageWith(URL(string: self.appShown.imageURL)!)
self.appImageView.center = self.circle.center
}, completion: { (finished: Bool) in
self.appSummary.isHidden = false
self.appSummary.text = self.appShown.summary
})
}
@IBAction func onCloseButton(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
| f74b8455efae30cbc8d77cbc99ad08d9 | 29.627907 | 80 | 0.634017 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/SwiftUI/Mac/Get-It-master/Get It/DownloadButton.swift | mit | 1 | //
// BlueButton.swift
// Get It
//
// Created by Kevin De Koninck on 29/01/2017.
// Copyright © 2017 Kevin De Koninck. All rights reserved.
//
import Cocoa
class DownloadButton: NSButton {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
self.layer?.backgroundColor = blueColor.cgColor
self.layer?.cornerRadius = 15.0
self.layer?.masksToBounds = true
}
override func awakeFromNib() {
super.awakeFromNib()
//text
let style = NSMutableParagraphStyle()
style.alignment = .center
self.attributedTitle = NSAttributedString(string: "Download", attributes: [ NSAttributedString.Key.foregroundColor : NSColor.white,
NSAttributedString.Key.paragraphStyle : style,
NSAttributedString.Key.font: NSFont(name: "Arial", size: 18)!])
}
}
| 054ea9210a80bc211b6eb74c21fe07e4 | 32.193548 | 147 | 0.549077 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/BackgroundStyleSelectionTableViewCell.swift | apache-2.0 | 3 | //
// ScreenBackgroundStyleSelectionTableViewCell.swift
// SwiftEntryKit_Example
//
// Created by Daniel Huri on 4/25/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
import SwiftEntryKit
class BackgroundStyleSelectionTableViewCell: SelectionTableViewCell {
private var focus: Focus = .entry
private var backgroundStyle: EKAttributes.BackgroundStyle {
get {
switch focus {
case .entry:
return attributesWrapper.attributes.entryBackground
case .screen:
return attributesWrapper.attributes.screenBackground
}
}
set {
switch focus {
case .entry:
attributesWrapper.attributes.entryBackground = newValue
case .screen:
attributesWrapper.attributes.screenBackground = newValue
}
}
}
func configure(attributesWrapper: EntryAttributeWrapper, focus: Focus) {
self.focus = focus
configure(attributesWrapper: attributesWrapper)
}
override func configure(attributesWrapper: EntryAttributeWrapper) {
super.configure(attributesWrapper: attributesWrapper)
titleValue = "\(focus.rawValue.capitalized) Background Style"
descriptionValue = "The style of the \(focus.rawValue)'s background can be one of the following options"
insertSegments(by: ["Clear", "Blur", "Gradient", "Color"])
selectSegment()
}
private func selectSegment() {
switch backgroundStyle {
case .clear:
segmentedControl.selectedSegmentIndex = 0
case .visualEffect(style: _):
segmentedControl.selectedSegmentIndex = 1
case .gradient(gradient: _):
segmentedControl.selectedSegmentIndex = 2
case .color(color: _):
segmentedControl.selectedSegmentIndex = 3
default:
// TODO: Image isn't handled yet
break
}
}
@objc override func segmentChanged() {
switch segmentedControl.selectedSegmentIndex {
case 0:
backgroundStyle = .clear
case 1:
backgroundStyle = .visualEffect(style: .light)
case 2:
let gradient = EKAttributes.BackgroundStyle.Gradient(colors: [EKColor.BlueGray.c100, EKColor.BlueGray.c300], startPoint: .zero, endPoint: CGPoint(x: 1, y: 1))
backgroundStyle = .gradient(gradient: gradient)
case 3:
let color: UIColor
switch focus {
case .entry:
color = .amber
case .screen:
color = UIColor.black.withAlphaComponent(0.5)
}
backgroundStyle = .color(color: color)
default:
break
}
}
}
| 7a38d398d215a6338f6a37a307ffd939 | 31.443182 | 170 | 0.602102 | false | false | false | false |
git-hushuai/MOMO | refs/heads/master | MMHSMeterialProject/UINavigationController/BusinessFile/简历库Item/TKOptimizeResumeBaseController.swift | mit | 1 | //
// TKOptimizeResumeBaseController.swift
// MMHSMeterialProject
//
// Created by hushuaike on 16/4/12.
// Copyright © 2016年 hushuaike. All rights reserved.
//
import UIKit
class TKOptimizeResumeBaseController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var TKTableView = UITableView.init(frame: CGRectZero, style: UITableViewStyle.Plain);
var dataSourceLists = NSMutableArray();
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = RGBA(0xf3, g: 0xf3, b: 0xf3, a: 1.0);
self.setUpUI();
self.performSelectorInBackground(Selector.init("loadLocalOptimizeResumeBaseInfo"), withObject: self);
}
func loadLocalOptimizeResumeBaseInfo(){
// 将本地数据取出
let dbCacheModel = TKResumeDataCacheTool();
let nowDate = NSDate.init();
let timeInterval = nowDate.timeIntervalSince1970;
let timeIntervalStr = String.init(format: "%i", Int(timeInterval) - 1);
let localResumeLists = dbCacheModel.loadLocalAllResumeInfoWithResumeCateInfo("简历库优选", timeStampInfo: timeIntervalStr);
print("localoptimizebaseResume lists info :\(localResumeLists)");
let itemModelLists : NSArray = TKJobItemModel.parses(arr: localResumeLists) as! [TKJobItemModel];
print("optimizebasefirst item Model lists:\(itemModelLists)");
self.dataSourceLists.removeAllObjects();
self.dataSourceLists.addObjectsFromArray(itemModelLists as [AnyObject]);
self.TKTableView.reloadData();
}
func setUpUI(){
self.view.addSubview(self.TKTableView);
self.TKTableView.sd_layout().spaceToSuperView(UIEdgeInsetsMake(0, 0, 50, 0));
self.TKTableView.tableFooterView = UIView.init();
self.TKTableView.separatorStyle = .None;
self.TKTableView.backgroundColor = RGBA(0xf3, g: 0xf3, b: 0xf3, a: 1.0);
self.TKTableView.delegate = self;
self.TKTableView.dataSource = self;
self.TKTableView.registerClass(ClassFromString("TKOptimizeCell"), forCellReuseIdentifier: "TKOptimizeCell");
let loadingView = DGElasticPullToRefreshLoadingViewCircle()
loadingView.tintColor = UIColor(red: 78/255.0, green: 221/255.0, blue: 200/255.0, alpha: 1.0)
self.TKTableView.dg_addPullToRefreshWithActionHandler({ [weak self] () -> Void in
self?.loadNewResumeItemInfo();
}, loadingView: loadingView)
self.TKTableView.dg_setPullToRefreshFillColor(UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0))
self.TKTableView.dg_setPullToRefreshBackgroundColor(RGBA(0xf3, g: 0xf3, b: 0xf3, a: 1.0));
self.TKTableView.addFootRefresh(self, action: "loadMoreResumeItemInfo")
}
// MARK: 加载最新数据
func loadNewResumeItemInfo(){
self.pullRequestLoadingResumeInfoWithParam(true);
}
// MARK: 加载历史数据
func loadMoreResumeItemInfo(){
self.pullRequestLoadingResumeInfoWithParam(false);
}
// MARK: 发起网络请求
func pullRequestLoadingResumeInfoWithParam(isfresh:Bool){
let reqDict = NSMutableDictionary();
if isfresh == true{
reqDict.setValue("0", forKey: "lastTime")
}else{
if self.dataSourceLists.count > 0{
let resuemModel = self.dataSourceLists.lastObject as! TKJobItemModel;
reqDict.setValue(resuemModel.ts, forKey: "lastTime")
}else{
// reqDict.setValue("0", forKey: "lastTime");
}
}
GNNetworkCenter.userLoadResumeItemBaseInfoWithReqObject(reqDict, andFunName: KAppUserLoadResumeBaseInfoFunc) { (response : YWResponse!) -> Void in
print("resume base info :response:\(response)---data:\(response.data)");
if (Int(response.retCode) == ERROR_NOERROR){
let responseDict:Dictionary<String,AnyObject> = response.data as! Dictionary;
let keyValueArr = responseDict.keys;
if keyValueArr.contains("data") == true{
let itemArr : NSArray = responseDict["data"]! as! NSArray;
print("order job item array :\(itemArr)");
if itemArr.count > 0{
if isfresh==true{self.clearLocalResumeInfo();}
let itemModel : NSArray = TKJobItemModel.parses(arr: itemArr) as! [TKJobItemModel];
for i in 0...(itemModel.count-1){
let dict = itemModel[i] as! TKJobItemModel;
dict.cellItemInfo = "简历库优选";
print("dict cell item info :\(dict)");
let dbItem = TKResumeDataCacheTool();
// 先判断本地是否有该条记录
let job_id = String.init(format: "%@", dict.id);
let cellItemCateInfo = dict.cellItemInfo;
let queryData = dbItem.checkResumeItemIsAlreadySaveInLocal(job_id, resumeItemInfo: cellItemCateInfo);
print("queryData inf0 :\(queryData)");
if(queryData.count > 0){
print("本地已经有该条记录");
}else{
// 本地没有该条数据需要缓存
dbItem.setDBItemInfoWithResumeModel(dict);
dbItem.save();
}
}
// 展示数据
print("item model info:\(itemModel)");
self.showItemInfoWithArray(itemModel,isfresh:isfresh);
}
}else{
print("数据加载出错");
let errorInfo = response.msg;
SVProgressHUD.showErrorWithStatus(String.init(format: "%@", errorInfo));
dispatch_after(UInt64(1.5), dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.dismiss();
});
self.stopWithParamIsFresh(isfresh);
}
}else{
self.stopWithParamIsFresh(isfresh);
}
}
}
func showItemInfoWithArray(itemArr : NSArray,isfresh:Bool){
if isfresh == true{
print("current THREADinfo:\(NSThread.currentThread())");
self.dataSourceLists.removeAllObjects();
self.dataSourceLists.addObjectsFromArray(itemArr as [AnyObject]);
print("self dataSourceList info:\(self.dataSourceLists)");
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.reloadData();
self.TKTableView.tableHeadStopRefreshing();
self.TKTableView.dg_stopLoading();
})
}else{
self.dataSourceLists.addObjectsFromArray(itemArr as [AnyObject]);
if itemArr.count >= 20{
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.tableFootStopRefreshing();
self.TKTableView.reloadData();
})
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.tableFootShowNomore();
self.TKTableView.reloadData();
});
})
}
}
}
//MARK: 将本地数据清空
func clearLocalResumeInfo(){
let cityInfo = self.getUserSelectCityName();
let deleDBModel = TKResumeDataCacheTool();
deleDBModel.clearTableResumeInfoWithParms("简历库优选", cityCateInfo: cityInfo)
// 加载数据成功之后将本地数据清空
}
// MARK: 返回用户选择的城市信息
func getUserSelectCityName()->String{
var cityInfo = NSUserDefaults.standardUserDefaults().stringForKey("kUserDidSelectCityInfoKey");
if( cityInfo == nil) {
cityInfo = "广州";
}
return cityInfo as String!;
}
// MARK: 停止刷新
func stopWithParamIsFresh(isfresh:Bool){
if isfresh == true{
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.dg_stopLoading();
self.TKTableView.tableHeadStopRefreshing();
})
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.tableFootShowNomore();
self.TKTableView.reloadData();
});
})
}
}
// MARK: rgb color
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat)->UIColor {
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) }
// MARK: tableview delegate 和 datasource 方法
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
print("dataSourceList count :\(self.dataSourceLists.count)");
self.TKTableView.foot?.hidden = self.dataSourceLists.count > 0 ? false : true;
self.TKTableView.foot?.userInteractionEnabled = self.dataSourceLists.count > 0 ? true : false;
return self.dataSourceLists.count;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10.0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headView = UIView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 10.0));
headView.backgroundColor = UIColor.clearColor();
return headView;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TKOptimizeCell") as? TKOptimizeCell;
let resumeModel = self.dataSourceLists.objectAtIndex(indexPath.section);
cell!.resumeModel = resumeModel as? TKJobItemModel;
cell!.sd_tableView = tableView;
cell!.sd_indexPath = indexPath;
return cell!;
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let resumeModel = self.dataSourceLists.objectAtIndex(indexPath.section);
return self.TKTableView.cellHeightForIndexPath(indexPath,model: resumeModel, keyPath:"resumeModel", cellClass: ClassFromString("TKOptimizeCell"), contentViewWidth:UIScreen.mainScreen().bounds.size.width);
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true);
print("indexPath info:\(indexPath)");
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| b34792e934a61c26cf1796af999406f2 | 39.456835 | 212 | 0.611897 | false | false | false | false |
mrchenhao/VPNOn | refs/heads/develop | VPNOnKit/VPNManager.swift | mit | 1 | //
// VPNManager.swift
// VPNOn
//
// Created by Lex Tang on 12/5/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import Foundation
import NetworkExtension
import CoreData
let kAppGroupIdentifier = "group.VPNOn"
final public class VPNManager
{
lazy var _manager: NEVPNManager = {
return NEVPNManager.sharedManager()!
}()
lazy var _defaults: NSUserDefaults = {
return NSUserDefaults(suiteName: kAppGroupIdentifier)!
}()
public var status: NEVPNStatus {
get {
return _manager.connection.status
}
}
public class var sharedManager : VPNManager
{
struct Static
{
static let sharedInstance : VPNManager = {
let instance = VPNManager()
instance._manager.loadFromPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
println("Failed to load preferences: \(err.localizedDescription)")
}
}
instance._manager.localizedDescription = "VPN On"
instance._manager.enabled = true
return instance
}()
}
return Static.sharedInstance
}
public func connectIPSec(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) {
// TODO: Add a tailing closure for callback.
let p = NEVPNProtocolIPSec()
p.authenticationMethod = NEVPNIKEAuthenticationMethod.None
p.useExtendedAuthentication = true
p.serverAddress = server
p.disconnectOnSleep = !alwaysOn
_manager.localizedDescription = "VPN On - \(title)"
if let grp = group {
p.localIdentifier = grp
} else {
p.localIdentifier = "VPN"
}
if let username = account {
p.username = username
}
if let password = passwordRef {
p.passwordReference = password
}
if let secret = secretRef {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret
p.sharedSecretReference = secret
}
if let certficiateData = certificate {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate
p.identityData = certficiateData
}
_manager.enabled = true
_manager.`protocol` = p
configOnDemand()
_manager.saveToPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
println("Failed to save profile: \(err.localizedDescription)")
} else {
var connectError : NSError?
self._manager.connection.startVPNTunnelAndReturnError(&connectError)
if let connectErr = connectError {
// println("Failed to start tunnel: \(connectErr.localizedDescription)")
} else {
// println("VPN tunnel started.")
}
}
}
}
public func connectIKEv2(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) {
let p = NEVPNProtocolIKEv2()
p.authenticationMethod = NEVPNIKEAuthenticationMethod.None
p.useExtendedAuthentication = true
p.serverAddress = server
p.remoteIdentifier = server
p.disconnectOnSleep = !alwaysOn
p.deadPeerDetectionRate = NEVPNIKEv2DeadPeerDetectionRate.Medium
// TODO: Add an option into config page
_manager.localizedDescription = "VPN On - \(title)"
if let grp = group {
p.localIdentifier = grp
} else {
p.localIdentifier = "VPN"
}
if let username = account {
p.username = username
}
if let password = passwordRef {
p.passwordReference = password
}
if let secret = secretRef {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret
p.sharedSecretReference = secret
}
if let certficiateData = certificate {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate
p.serverCertificateCommonName = server
p.serverCertificateIssuerCommonName = server
p.identityData = certficiateData
}
_manager.enabled = true
_manager.`protocol` = p
configOnDemand()
_manager.saveToPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
println("Failed to save profile: \(err.localizedDescription)")
} else {
var connectError : NSError?
if self._manager.connection.startVPNTunnelAndReturnError(&connectError) {
if let connectErr = connectError {
println("Failed to start IKEv2 tunnel: \(connectErr.localizedDescription)")
} else {
println("IKEv2 tunnel started.")
}
} else {
println("Failed to connect: \(connectError?.localizedDescription)")
}
}
}
}
public func configOnDemand() {
if onDemandDomainsArray.count > 0 && onDemand {
let connectionRule = NEEvaluateConnectionRule(
matchDomains: onDemandDomainsArray,
andAction: NEEvaluateConnectionRuleAction.ConnectIfNeeded
)
let ruleEvaluateConnection = NEOnDemandRuleEvaluateConnection()
ruleEvaluateConnection.connectionRules = [connectionRule]
_manager.onDemandRules = [ruleEvaluateConnection]
_manager.onDemandEnabled = true
} else {
_manager.onDemandRules = [AnyObject]()
_manager.onDemandEnabled = false
}
}
public func disconnect() {
_manager.connection.stopVPNTunnel()
}
public func removeProfile() {
_manager.removeFromPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
}
}
}
| 3c67878edf38fd43529eb874b48e9f74 | 32.025 | 182 | 0.56109 | false | false | false | false |
netguru/inbbbox-ios | refs/heads/develop | Inbbbox/Source Files/ViewModels/LikesViewModel.swift | gpl-3.0 | 1 | //
// LikesViewModel.swift
// Inbbbox
//
// Created by Aleksander Popko on 29.02.2016.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import PromiseKit
class LikesViewModel: SimpleShotsViewModel {
weak var delegate: BaseCollectionViewViewModelDelegate?
let title = Localized("LikesViewModel.Title", comment:"Title of Likes screen")
var shots = [ShotType]()
fileprivate let shotsProvider = ShotsProvider()
fileprivate var userMode: UserMode
var itemsCount: Int {
return shots.count
}
init() {
userMode = UserStorage.isUserSignedIn ? .loggedUser : .demoUser
}
func downloadInitialItems() {
firstly {
shotsProvider.provideMyLikedShots()
}.then { shots -> Void in
if let shots = shots?.map({ $0.shot }), shots != self.shots || shots.count == 0 {
self.shots = shots
self.delegate?.viewModelDidLoadInitialItems()
}
}.catch { error in
self.delegate?.viewModelDidFailToLoadInitialItems(error)
}
}
func downloadItemsForNextPage() {
guard UserStorage.isUserSignedIn else {
return
}
firstly {
shotsProvider.nextPageForLikedShots()
}.then { shots -> Void in
if let shots = shots?.map({ $0.shot }), shots.count > 0 {
let indexes = shots.enumerated().map { index, _ in
return index + self.shots.count
}
self.shots.append(contentsOf: shots)
let indexPaths = indexes.map {
IndexPath(row:($0), section: 0)
}
self.delegate?.viewModel(self, didLoadItemsAtIndexPaths: indexPaths)
}
}.catch { error in
self.notifyDelegateAboutFailure(error)
}
}
func downloadItem(at index: Int) { /* empty */ }
func emptyCollectionDescriptionAttributes() -> EmptyCollectionViewDescription {
let description = EmptyCollectionViewDescription(
firstLocalizedString: Localized("LikesCollectionView.EmptyData.FirstLocalizedString",
comment: "LikesCollectionView, empty data set view"),
attachmentImageName: "ic-like-emptystate",
imageOffset: CGPoint(x: 0, y: -2),
lastLocalizedString: Localized("LikesCollectionView.EmptyData.LastLocalizedString",
comment: "LikesCollectionView, empty data set view")
)
return description
}
func shotCollectionViewCellViewData(_ indexPath: IndexPath) -> (shotImage: ShotImageType, animated: Bool) {
let shotImage = shots[indexPath.row].shotImage
let animated = shots[indexPath.row].animated
return (shotImage, animated)
}
func clearViewModelIfNeeded() {
let currentUserMode = UserStorage.isUserSignedIn ? UserMode.loggedUser : .demoUser
if userMode != currentUserMode {
shots = []
userMode = currentUserMode
delegate?.viewModelDidLoadInitialItems()
}
}
}
| 86e371623a2f35a893ea9928bdf3c8ea | 33.163043 | 111 | 0.610881 | false | false | false | false |
alecgorge/AGAudioPlayer | refs/heads/master | AGAudioPlayer/UI/AGAudioPlayerViewController.swift | mit | 1 | //
// AGAudioPlayerViewController.swift
// AGAudioPlayer
//
// Created by Alec Gorge on 1/19/17.
// Copyright © 2017 Alec Gorge. All rights reserved.
//
import UIKit
import QuartzCore
import MediaPlayer
import Interpolate
import MarqueeLabel
import NapySlider
public struct AGAudioPlayerColors {
let main: UIColor
let accent: UIColor
let accentWeak: UIColor
let barNothing: UIColor
let barDownloads: UIColor
let barPlaybackElapsed: UIColor
let scrubberHandle: UIColor
public init() {
let main = UIColor(red:0.149, green:0.608, blue:0.737, alpha:1)
let accent = UIColor.white
self.init(main: main, accent: accent)
}
public init(main: UIColor, accent: UIColor) {
self.main = main
self.accent = accent
accentWeak = accent.withAlphaComponent(0.7)
barNothing = accent.withAlphaComponent(0.3)
barDownloads = accent.withAlphaComponent(0.4)
barPlaybackElapsed = accent
scrubberHandle = accent
}
}
@objc public class AGAudioPlayerViewController: UIViewController {
@IBOutlet var uiPanGestureClose: VerticalPanDirectionGestureRecognizer!
@IBOutlet var uiPanGestureOpen: VerticalPanDirectionGestureRecognizer!
@IBOutlet weak var uiTable: UITableView!
@IBOutlet weak var uiHeaderView: UIView!
@IBOutlet weak var uiFooterView: UIView!
@IBOutlet weak var uiProgressDownload: UIView!
@IBOutlet weak var uiProgressDownloadCompleted: UIView!
@IBOutlet weak var uiScrubber: ScrubberBar!
@IBOutlet weak var uiProgressDownloadCompletedContraint: NSLayoutConstraint!
@IBOutlet weak var uiLabelTitle: MarqueeLabel!
@IBOutlet weak var uiLabelSubtitle: MarqueeLabel!
@IBOutlet weak var uiLabelElapsed: UILabel!
@IBOutlet weak var uiLabelDuration: UILabel!
@IBOutlet weak var uiButtonShuffle: UIButton!
@IBOutlet weak var uiButtonPrevious: UIButton!
@IBOutlet weak var uiButtonPlay: UIButton!
@IBOutlet weak var uiButtonPause: UIButton!
@IBOutlet weak var uiButtonNext: UIButton!
@IBOutlet weak var uiButtonLoop: UIButton!
@IBOutlet weak var uiButtonDots: UIButton!
@IBOutlet weak var uiButtonPlus: UIButton!
@IBOutlet weak var uiSliderVolume: MPVolumeView!
@IBOutlet weak var uiSpinnerBuffering: UIActivityIndicatorView!
@IBOutlet weak var uiButtonStack: UIStackView!
@IBOutlet weak var uiWrapperEq: UIView!
@IBOutlet weak var uiSliderEqBass: NapySlider!
@IBOutlet weak var uiConstraintTopTitleSpace: NSLayoutConstraint!
@IBOutlet weak var uiConstraintSpaceBetweenPlayers: NSLayoutConstraint!
@IBOutlet weak var uiConstraintBottomBarHeight: NSLayoutConstraint!
// mini player
@IBOutlet weak var uiMiniPlayerContainerView: UIView!
public var barHeight : CGFloat {
get {
if let c = uiMiniPlayerContainerView {
let extra: CGFloat = UIApplication.shared.keyWindow!.rootViewController!.view.safeAreaInsets.bottom
return c.bounds.height + extra
}
return 64.0
}
}
@IBOutlet weak var uiMiniPlayerTopOffsetConstraint: NSLayoutConstraint!
@IBOutlet weak var uiMiniProgressDownloadCompletedView: UIView!
@IBOutlet weak var uiMiniProgressDownloadCompletedConstraint: NSLayoutConstraint!
@IBOutlet weak var uiMiniProgressPlayback: UIProgressView!
@IBOutlet weak var uiMiniButtonPlay: UIButton!
@IBOutlet weak var uiMiniButtonPause: UIButton!
@IBOutlet weak var uiMiniLabelTitle: MarqueeLabel!
@IBOutlet weak var uiMiniLabelSubtitle: MarqueeLabel!
@IBOutlet weak var uiMiniButtonStack: UIStackView!
@IBOutlet public weak var uiMiniButtonDots: UIButton!
@IBOutlet weak var uiMiniButtonPlus: UIButton!
@IBOutlet weak var uiMiniSpinnerBuffering: UIActivityIndicatorView!
// end mini player
public var presentationDelegate: AGAudioPlayerViewControllerPresentationDelegate? = nil
public var cellDataSource: AGAudioPlayerViewControllerCellDataSource? = nil
public var delegate: AGAudioPlayerViewControllerDelegate? = nil
public var shouldPublishToNowPlayingCenter: Bool = true
var remoteCommandManager : RemoteCommandManager? = nil
var dismissInteractor: DismissInteractor = DismissInteractor()
var openInteractor: OpenInteractor = OpenInteractor()
// colors
var colors = AGAudioPlayerColors()
// constants
let SectionQueue = 0
// bouncy header
var headerInterpolate: Interpolate?
var interpolateBlock: ((_ scale: Double) -> Void)?
// swipe to dismiss
static let defaultTransitionDelegate = AGAudioPlayerViewControllerTransitioningDelegate()
// non-jumpy seeking
var isCurrentlyScrubbing = false
// for delegate notifications
var lastSeenProgress: Float? = nil
let player: AGAudioPlayer
@objc required public init(player: AGAudioPlayer) {
self.player = player
let bundle = Bundle(path: Bundle(for: AGAudioPlayerViewController.self).path(forResource: "AGAudioPlayer", ofType: "bundle")!)
super.init(nibName: String(describing: AGAudioPlayerViewController.self), bundle: bundle)
self.transitioningDelegate = AGAudioPlayerViewController.defaultTransitionDelegate
setupPlayer()
dismissInteractor.viewController = self
openInteractor.viewController = self
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
uiMiniButtonStack.removeArrangedSubview(uiMiniButtonPlus)
uiMiniButtonPlus.isHidden = true
uiButtonPlus.alpha = 0.0
setupTable()
setupStretchyHeader()
setupColors()
setupPlayerUiActions()
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewWillAppear_StretchyHeader()
viewWillAppear_Table()
updateUI()
uiSliderVolume.isHidden = false
}
public override func viewDidDisappear(_ animated: Bool) {
uiSliderVolume.isHidden = true
}
}
extension AGAudioPlayerViewController : UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
let pt = touch.location(in: uiHeaderView)
return uiHeaderView.frame.contains(pt);
}
}
extension AGAudioPlayerViewController : AGAudioPlayerDelegate {
func setupPlayer() {
player.delegate = self
player.prepareAudioSession()
publishToNowPlayingCenter()
}
public func audioPlayerAudioSessionSetUp(_ audioPlayer: AGAudioPlayer) {
remoteCommandManager = RemoteCommandManager(player: audioPlayer)
remoteCommandManager?.activatePlaybackCommands(true)
}
func updateUI() {
updatePlayPauseButtons()
updateShuffleLoopButtons()
updateNonTimeLabels()
updateTimeLabels()
updatePlaybackProgress()
updatePreviousNextButtons()
}
func updatePlayPauseButtons() {
guard uiButtonPause != nil, uiButtonPlay != nil,
uiMiniButtonPause != nil, uiMiniButtonPlay != nil,
uiSpinnerBuffering != nil, uiMiniSpinnerBuffering != nil else {
return
}
if player.isBuffering {
uiButtonPause.isHidden = true
uiButtonPlay.isHidden = true
uiMiniButtonPause.isHidden = true
uiMiniButtonPlay.isHidden = true
uiMiniSpinnerBuffering.isHidden = false
uiSpinnerBuffering.isHidden = false
return
}
uiMiniSpinnerBuffering.isHidden = true
uiSpinnerBuffering.isHidden = true
uiButtonPause.isHidden = !player.isPlaying && !player.isBuffering
uiButtonPlay.isHidden = player.isPlaying
uiMiniButtonPause.isHidden = uiButtonPause.isHidden
uiMiniButtonPlay.isHidden = uiButtonPlay.isHidden
}
func updatePreviousNextButtons() {
guard uiButtonPrevious != nil, uiButtonNext != nil else {
return
}
uiButtonPrevious.isEnabled = !player.isPlayingFirstItem
uiButtonNext.isEnabled = !player.isPlayingLastItem
}
func updateShuffleLoopButtons() {
guard uiButtonShuffle != nil, uiButtonLoop != nil else {
return
}
uiButtonLoop.alpha = player.loopItem ? 1.0 : 0.7
uiButtonShuffle.alpha = player.shuffle ? 1.0 : 0.7
}
func updateNonTimeLabels() {
guard uiLabelTitle != nil, uiLabelSubtitle != nil, uiMiniLabelTitle != nil, uiLabelSubtitle != nil else {
return
}
if let cur = player.currentItem {
uiLabelTitle.text = cur.displayText
uiLabelSubtitle.text = cur.displaySubtext
uiMiniLabelTitle.text = cur.displayText
uiMiniLabelSubtitle.text = cur.displaySubtext
}
else {
uiLabelTitle.text = " "
uiLabelSubtitle.text = " "
uiMiniLabelTitle.text = " "
uiMiniLabelSubtitle.text = " "
}
}
func updateTimeLabels() {
guard uiLabelElapsed != nil, uiLabelDuration != nil else {
return
}
if player.duration == 0.0 {
uiLabelElapsed.text = " "
uiLabelDuration.text = " "
}
else {
uiLabelElapsed.text = player.elapsed.formatted()
uiLabelDuration.text = player.duration.formatted()
}
}
func updatePlaybackProgress() {
guard uiScrubber != nil, uiMiniProgressPlayback != nil else {
return
}
if !isCurrentlyScrubbing {
let floatProgress = Float(player.percentElapsed)
uiScrubber.setProgress(progress: floatProgress)
uiMiniProgressPlayback.progress = floatProgress
updateTimeLabels()
// send this delegate once when it goes past 50%
if let lastProgress = lastSeenProgress, lastProgress < 0.5, floatProgress >= 0.5, let item = player.currentItem {
delegate?.audioPlayerViewController(self, passedHalfWayFor: item)
}
lastSeenProgress = floatProgress
}
}
func updateDownloadProgress(pct: Double) {
guard uiProgressDownloadCompletedContraint != nil, uiMiniProgressDownloadCompletedConstraint != nil else {
return
}
var p = pct
if p > 0.98 {
p = 1.0
}
uiProgressDownloadCompletedContraint = uiProgressDownloadCompletedContraint.setMultiplier(multiplier: CGFloat(p))
uiProgressDownload.layoutIfNeeded()
uiMiniProgressDownloadCompletedConstraint = uiMiniProgressDownloadCompletedConstraint.setMultiplier(multiplier: CGFloat(p))
uiMiniPlayerContainerView.layoutIfNeeded()
uiMiniProgressDownloadCompletedView.isHidden = p == 0.0
}
public func audioPlayer(_ audioPlayer: AGAudioPlayer, uiNeedsRedrawFor reason: AGAudioPlayerRedrawReason) {
publishToNowPlayingCenter()
switch reason {
case .buffering, .playing:
updatePlayPauseButtons()
delegate?.audioPlayerViewController(self, trackChangedState: player.currentItem)
uiTable.reloadData()
case .stopped:
uiLabelTitle.text = ""
uiLabelSubtitle.text = ""
uiMiniLabelTitle.text = ""
uiMiniLabelSubtitle.text = ""
fallthrough
case .paused, .error:
updatePlayPauseButtons()
delegate?.audioPlayerViewController(self, trackChangedState: player.currentItem)
uiTable.reloadData()
case .trackChanged:
updatePreviousNextButtons()
updateNonTimeLabels()
updateTimeLabels()
uiTable.reloadData()
delegate?.audioPlayerViewController(self, changedTrackTo: player.currentItem)
case .queueChanged:
uiTable.reloadData()
default:
break
}
self.scrollQueueToPlayingTrack()
}
public func audioPlayer(_ audioPlayer: AGAudioPlayer, errorRaised error: Error, for url: URL) {
print("CRAP")
print(error)
print(url)
publishToNowPlayingCenter()
}
public func audioPlayer(_ audioPlayer: AGAudioPlayer, downloadedBytesForActiveTrack downloadedBytes: UInt64, totalBytes: UInt64) {
guard uiProgressDownloadCompleted != nil else {
return
}
let progress = Double(downloadedBytes) / Double(totalBytes)
updateDownloadProgress(pct: progress)
}
public func audioPlayer(_ audioPlayer: AGAudioPlayer, progressChanged elapsed: TimeInterval, withTotalDuration totalDuration: TimeInterval) {
updatePlaybackProgress()
publishToNowPlayingCenter()
}
public func publishToNowPlayingCenter() {
guard shouldPublishToNowPlayingCenter else {
return
}
var nowPlayingInfo : [String : Any]? = nil
if let item = player.currentItem {
nowPlayingInfo = [
MPMediaItemPropertyMediaType : NSNumber(value: MPMediaType.music.rawValue),
MPMediaItemPropertyTitle : item.title,
MPMediaItemPropertyAlbumArtist : item.artist,
MPMediaItemPropertyArtist : item.artist,
MPMediaItemPropertyAlbumTitle : item.album,
MPMediaItemPropertyPlaybackDuration : NSNumber(value: item.duration),
MPMediaItemPropertyAlbumTrackNumber : NSNumber(value: item.trackNumber),
// MPNowPlayingInfoPropertyDefaultPlaybackRate : NSNumber(value: 1.0),
MPNowPlayingInfoPropertyElapsedPlaybackTime : NSNumber(value: player.elapsed),
MPNowPlayingInfoPropertyPlaybackProgress : NSNumber(value: Float(player.percentElapsed)),
MPNowPlayingInfoPropertyPlaybackQueueCount : NSNumber(value: player.queue.count),
MPNowPlayingInfoPropertyPlaybackQueueIndex : NSNumber(value: player.currentIndex),
MPNowPlayingInfoPropertyPlaybackRate : NSNumber(value: player.isPlaying ? 1.0 : 0.0)
]
if let albumArt = item.albumArt {
nowPlayingInfo![MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: albumArt.size, requestHandler: { (_) -> UIImage in
return albumArt
})
}
}
//print("Updating now playing info to \(nowPlayingInfo)")
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
}
extension AGAudioPlayerViewController : ScrubberBarDelegate {
func setupPlayerUiActions() {
uiScrubber.delegate = self
uiLabelTitle.isUserInteractionEnabled = true
uiLabelSubtitle.isUserInteractionEnabled = true
uiMiniLabelTitle.isUserInteractionEnabled = true
uiMiniLabelSubtitle.isUserInteractionEnabled = true
updateDownloadProgress(pct: 0.0)
updatePlaybackProgress()
/*
Assign in XIB as per MarqueeLabel docs
uiLabelTitle.scrollRate = 25
uiLabelTitle.trailingBuffer = 32
uiLabelTitle.animationDelay = 5
uiLabelSubtitle.scrollRate = 25
uiLabelSubtitle.trailingBuffer = 24
uiLabelSubtitle.animationDelay = 5
uiMiniLabelTitle.scrollRate = 16
uiMiniLabelTitle.trailingBuffer = 24
uiMiniLabelTitle.animationDelay = 5
uiMiniLabelSubtitle.scrollRate = 16
uiMiniLabelSubtitle.trailingBuffer = 16
uiMiniLabelSubtitle.animationDelay = 5
*/
}
public func scrubberBar(bar: ScrubberBar, didScrubToProgress: Float, finished: Bool) {
isCurrentlyScrubbing = !finished
if let elapsed = uiLabelElapsed, let mp = uiMiniProgressPlayback {
elapsed.text = TimeInterval(player.duration * Double(didScrubToProgress)).formatted()
mp.progress = didScrubToProgress
}
if finished {
player.seek(toPercent: CGFloat(didScrubToProgress))
}
}
@IBAction func uiActionToggleShuffle(_ sender: UIButton) {
player.shuffle = !player.shuffle
updateShuffleLoopButtons()
uiTable.reloadData()
updatePreviousNextButtons()
}
@IBAction func uiActionToggleLoop(_ sender: UIButton) {
player.loopItem = !player.loopItem
updateShuffleLoopButtons()
}
@IBAction func uiActionPrevious(_ sender: UIButton) {
player.backward()
}
@IBAction func uiActionPlay(_ sender: UIButton) {
player.resume()
}
@IBAction func uiActionPause(_ sender: UIButton) {
player.pause()
}
@IBAction func uiActionNext(_ sender: UIButton) {
player.forward()
}
@IBAction func uiActionDots(_ sender: UIButton) {
if let item = self.player.currentItem {
delegate?.audioPlayerViewController(self, pressedDotsForAudioItem: item)
}
}
@IBAction func uiActionPlus(_ sender: UIButton) {
if let item = self.player.currentItem {
delegate?.audioPlayerViewController(self, pressedPlusForAudioItem: item)
}
}
@IBAction func uiOpenFullUi(_ sender: UIButton) {
self.presentationDelegate?.fullPlayerRequested()
}
}
public protocol AGAudioPlayerViewControllerPresentationDelegate {
func fullPlayerRequested()
func fullPlayerDismissRequested(fromProgress: CGFloat)
func fullPlayerStartedDismissing()
func fullPlayerDismissUpdatedProgress(_ progress: CGFloat)
func fullPlayerDismissCancelled(fromProgress: CGFloat)
func fullPlayerOpenUpdatedProgress(_ progress: CGFloat)
func fullPlayerOpenCancelled(fromProgress: CGFloat)
func fullPlayerOpenRequested(fromProgress: CGFloat)
}
public protocol AGAudioPlayerViewControllerCellDataSource {
func cell(inTableView tableView: UITableView, basedOnCell cell: UITableViewCell, atIndexPath: IndexPath, forPlaybackItem playbackItem: AGAudioItem, isCurrentlyPlaying: Bool) -> UITableViewCell
func heightForCell(inTableView tableView: UITableView, atIndexPath: IndexPath, forPlaybackItem playbackItem: AGAudioItem, isCurrentlyPlaying: Bool) -> CGFloat
}
public protocol AGAudioPlayerViewControllerDelegate {
func audioPlayerViewController(_ agAudio: AGAudioPlayerViewController, trackChangedState audioItem: AGAudioItem?)
func audioPlayerViewController(_ agAudio: AGAudioPlayerViewController, changedTrackTo audioItem: AGAudioItem?)
func audioPlayerViewController(_ agAudio: AGAudioPlayerViewController, passedHalfWayFor audioItem: AGAudioItem)
func audioPlayerViewController(_ agAudio: AGAudioPlayerViewController, pressedDotsForAudioItem audioItem: AGAudioItem)
func audioPlayerViewController(_ agAudio: AGAudioPlayerViewController, pressedPlusForAudioItem audioItem: AGAudioItem)
}
extension AGAudioPlayerViewController {
public func switchToMiniPlayer(animated: Bool) {
view.layoutIfNeeded()
UIView.animate(withDuration: 0.3) {
self.switchToMiniPlayerProgress(1.0)
}
}
public func switchToFullPlayer(animated: Bool) {
view.layoutIfNeeded()
UIView.animate(withDuration: 0.3) {
self.switchToMiniPlayerProgress(0.0)
}
self.scrollQueueToPlayingTrack()
}
public func switchToMiniPlayerProgress(_ progress: CGFloat) {
let maxHeight = self.uiMiniPlayerContainerView.frame.height
self.uiMiniPlayerTopOffsetConstraint.constant = -1.0 * maxHeight * (1.0 - progress)
self.view.layoutIfNeeded()
}
}
extension AGAudioPlayerViewController {
@IBAction func handlePanToClose(_ sender: UIPanGestureRecognizer) {
let percentThreshold:CGFloat = 0.3
let inView = uiHeaderView
// convert y-position to downward pull progress (percentage)
let translation = sender.translation(in: inView)
let verticalMovement = translation.y / view.bounds.height
let downwardMovement = fmaxf(Float(verticalMovement), 0.0)
let downwardMovementPercent = fminf(downwardMovement, 1.0)
let progress = CGFloat(downwardMovementPercent)
let interactor = dismissInteractor
switch sender.state {
case .began:
uiScrubber.scrubbingEnabled = false
interactor.hasStarted = true
case .changed:
interactor.shouldFinish = progress > percentThreshold
interactor.update(progress)
case .cancelled:
uiScrubber.scrubbingEnabled = true
interactor.hasStarted = false
interactor.cancel(progress)
case .ended:
uiScrubber.scrubbingEnabled = true
interactor.hasStarted = false
if interactor.shouldFinish {
interactor.finish(progress)
}
else {
interactor.cancel(progress)
}
default:
break
}
}
@IBAction func handlePanToOpen(_ sender: UIPanGestureRecognizer) {
let percentThreshold:CGFloat = 0.15
let inView = uiMiniPlayerContainerView
// convert y-position to downward pull progress (percentage)
let translation = sender.translation(in: inView)
let verticalMovement = (-1.0 * translation.y) / view.bounds.height
let upwardMovement = fmaxf(Float(verticalMovement), 0.0)
let upwardMovementPercent = fminf(upwardMovement, 1.0)
let progress = CGFloat(upwardMovementPercent)
let interactor = openInteractor
switch sender.state {
case .began:
interactor.hasStarted = true
case .changed:
interactor.shouldFinish = progress > percentThreshold
interactor.update(progress)
case .cancelled:
interactor.hasStarted = false
interactor.cancel(progress)
case .ended:
interactor.hasStarted = false
if interactor.shouldFinish {
interactor.finish(progress)
}
else {
interactor.cancel(progress)
}
default:
break
}
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive press: UIPress) -> Bool {
return !isCurrentlyScrubbing
}
@IBAction func handleChevronTapped(_ sender: UIButton) {
dismissInteractor.finish(1.0)
}
}
class DismissInteractor {
var hasStarted = false
var shouldFinish = false
var viewController: AGAudioPlayerViewController? = nil
var delegate: AGAudioPlayerViewControllerPresentationDelegate? {
get {
return viewController?.presentationDelegate
}
}
public func update(_ progress: CGFloat) {
delegate?.fullPlayerDismissUpdatedProgress(progress)
}
// restore
public func cancel(_ progress: CGFloat) {
delegate?.fullPlayerDismissCancelled(fromProgress: progress)
}
// dismiss
public func finish(_ progress: CGFloat) {
delegate?.fullPlayerDismissRequested(fromProgress: progress)
}
}
class OpenInteractor : DismissInteractor {
public override func update(_ progress: CGFloat) {
delegate?.fullPlayerOpenUpdatedProgress(progress)
}
// restore
public override func cancel(_ progress: CGFloat) {
delegate?.fullPlayerOpenCancelled(fromProgress: progress)
}
// dismiss
public override func finish(_ progress: CGFloat) {
delegate?.fullPlayerOpenRequested(fromProgress: progress)
}
}
extension AGAudioPlayerViewController {
func setupStretchyHeader() {
let blk = { [weak self] (fontScale: Double) in
if let s = self {
s.uiHeaderView.transform = CGAffineTransform(scaleX: CGFloat(fontScale), y: CGFloat(fontScale))
let h = s.uiHeaderView.bounds.height * CGFloat(fontScale)
s.uiTable.scrollIndicatorInsets = UIEdgeInsets.init(top: h, left: 0, bottom: 0, right: 0)
}
}
headerInterpolate = Interpolate(from: 1.0, to: 1.3, function: BasicInterpolation.easeOut, apply: blk)
interpolateBlock = blk
let insets = UIApplication.shared.keyWindow!.rootViewController!.view.safeAreaInsets
self.uiConstraintSpaceBetweenPlayers.constant = insets.top
self.view.layoutIfNeeded()
self.uiConstraintBottomBarHeight.constant += insets.bottom * 2
self.uiFooterView.layoutIfNeeded()
}
func viewWillAppear_StretchyHeader() {
interpolateBlock?(1.0)
let h = self.uiHeaderView.bounds.height
self.uiTable.contentInset = UIEdgeInsets.init(top: h, left: 0, bottom: 0, right: 0)
self.uiTable.contentOffset = CGPoint(x: 0, y: -h)
self.scrollQueueToPlayingTrack()
}
func scrollViewDidScroll_StretchyHeader(_ scrollView: UIScrollView) {
let y = scrollView.contentOffset.y + uiHeaderView.bounds.height
let base = view.safeAreaInsets.top
let np = CGFloat(abs(y).clamped(lower: CGFloat(base + 0), upper: CGFloat(base + 150))) / CGFloat(base + 150)
if y < 0 && headerInterpolate?.progress != np {
// headerInterpolate?.progress = np
}
}
}
extension AGAudioPlayerViewController {
func setupColors() {
applyColors(colors)
}
public func applyColors(_ colors: AGAudioPlayerColors) {
self.colors = colors
view.backgroundColor = colors.main
uiMiniPlayerContainerView.backgroundColor = colors.main
uiMiniLabelTitle.textColor = colors.accent
uiMiniLabelSubtitle.textColor = colors.accent
uiHeaderView.backgroundColor = colors.main
uiFooterView.backgroundColor = colors.main
uiLabelTitle.textColor = colors.accent
uiLabelSubtitle.textColor = colors.accent
uiLabelElapsed.textColor = colors.accentWeak
uiLabelDuration.textColor = colors.accentWeak
uiProgressDownload.backgroundColor = colors.barNothing
uiProgressDownloadCompleted.backgroundColor = colors.barDownloads
uiScrubber.elapsedColor = colors.barPlaybackElapsed
uiScrubber.dragIndicatorColor = colors.scrubberHandle
uiWrapperEq.isHidden = true
uiWrapperEq.backgroundColor = colors.main.darkenByPercentage(0.05)
uiSliderVolume.tintColor = colors.accent
/*
view.layer.masksToBounds = true
view.layer.cornerRadius = 4
*/
uiSliderEqBass.tintColor = colors.barPlaybackElapsed
uiSliderEqBass.sliderUnselectedColor = colors.barDownloads
}
public override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension AGAudioPlayerViewController {
func setupTable() {
uiTable.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// uiTable.backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: uiHeaderView.bounds.size.height + 44 * 2))
// uiTable.backgroundView?.backgroundColor = ColorMain
uiTable.allowsSelection = true
uiTable.allowsSelectionDuringEditing = true
uiTable.allowsMultipleSelectionDuringEditing = false
uiTable.setEditing(true, animated: false)
uiTable.reloadData()
}
func viewWillAppear_Table() {
}
public func tableReloadData() {
if let t = uiTable {
t.reloadData()
}
}
}
extension AGAudioPlayerViewController : UITableViewDelegate {
/*
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
dismissInteractor.hasStarted = true
}
*/
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollViewDidScroll_StretchyHeader(scrollView)
// let progress = (scrollView.contentOffset.y - scrollView.contentOffset.y) / view.frame.size.height
//
// dismissInteractor.update(progress)
}
// public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// dismissInteractor.hasStarted = false
//
// let progress = (scrollView.contentOffset.y - scrollView.contentOffset.y) / view.frame.size.height
//
// if progress > 0.1 {
// dismissInteractor.finish(progress)
// }
// else {
// dismissInteractor.cancel(progress)
// }
// }
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
player.currentIndex = indexPath.row
}
public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
print("\(indexPath) deselected")
}
public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return indexPath.section == SectionQueue
}
public func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if sourceIndexPath != destinationIndexPath {
player.queue.moveItem(at: sourceIndexPath.row, to: destinationIndexPath.row)
tableView.reloadData()
}
}
public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
}
extension AGAudioPlayerViewController : UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return player.queue.count
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Queue"
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
guard indexPath.row < player.queue.count else {
cell.textLabel?.text = "Error"
return cell
}
let q = player.queue.properQueue(forShuffleEnabled: player.shuffle)
let item = q[indexPath.row]
let currentlyPlaying = item.playbackGUID == player.currentItem?.playbackGUID
if let d = cellDataSource {
return d.cell(inTableView: tableView, basedOnCell: cell, atIndexPath: indexPath, forPlaybackItem: item, isCurrentlyPlaying: currentlyPlaying)
}
cell.textLabel?.text = (currentlyPlaying ? "* " : "") + item.title
return cell
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard indexPath.row < player.queue.count else {
return UITableView.automaticDimension
}
let q = player.queue.properQueue(forShuffleEnabled: player.shuffle)
let item = q[indexPath.row]
let currentlyPlaying = item.playbackGUID == player.currentItem?.playbackGUID
if let d = cellDataSource {
return d.heightForCell(inTableView: tableView, atIndexPath: indexPath, forPlaybackItem: item, isCurrentlyPlaying: currentlyPlaying)
}
return UITableView.automaticDimension
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tableView.performBatchUpdates({
player.queue.removeItem(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}, completion: nil)
}
}
fileprivate func scrollQueueToPlayingTrack() {
var itemRow = -1
let q = player.queue.properQueue(forShuffleEnabled: player.shuffle)
var curItemIndex = 0
for item in q {
if item.playbackGUID == player.currentItem?.playbackGUID {
itemRow = curItemIndex
break
}
curItemIndex += 1
}
if itemRow > -1 && itemRow < uiTable.numberOfRows(inSection: 0) {
uiTable.scrollToRow(at: IndexPath(row: max(0, itemRow-1), section: 0), at: .top, animated: true)
}
}
}
| bf5eeee1d27993b5bbcf2c109d8d5c99 | 33.455927 | 196 | 0.645378 | false | false | false | false |
moyazi/SwiftDayList | refs/heads/master | SwiftDayList/Days/Day7/Day7MainViewController.swift | mit | 1 | //
// Day7MainViewController.swift
// SwiftDayList
//
// Created by leoo on 2017/6/28.
// Copyright © 2017年 Het. All rights reserved.
//
import UIKit
import CoreLocation
class Day7MainViewController: UIViewController ,CLLocationManagerDelegate{
@IBOutlet weak var locationLB: UILabel!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "CLLocation"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Private Func
@IBAction func myLocationButtonDidTouch(_ sender: UIButton) {
self.locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.locationLB.text = "Error while updating location " + error.localizedDescription
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
self.locationLB.text = "Reverse geocoder failed with error" + error!.localizedDescription
return
}
if placemarks!.count > 0 {
let pm = placemarks![0]
self.displayLocationInfo(pm)
} else {
self.locationLB.text = "Problem with the data received from geocoder"
}
})
}
func displayLocationInfo(_ placemark: CLPlacemark?) {
if let containsPlacemark = placemark {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
self.locationLB.text = postalCode! + " " + locality!
self.locationLB.text?.append("\n" + administrativeArea! + ", " + country!)
}
}
}
| 9f907439c94b67303d368e0ee0d32f1b | 37.144928 | 126 | 0.647796 | false | false | false | false |
rlisle/Patriot-iOS | refs/heads/master | Patriot/ConfigViewController.swift | bsd-3-clause | 1 | //
// ConfigViewController.swift
// Patriot
//
// Created by Ron Lisle on 5/29/17.
// Copyright © 2017 Ron Lisle. All rights reserved.
//
import UIKit
class ConfigViewController: UITableViewController
{
@IBOutlet weak var particleUser: UITextField!
@IBOutlet weak var particlePassword: UITextField!
@IBOutlet weak var loginStatus: UILabel!
let settings = Settings(store: UserDefaultsSettingsStore())
fileprivate let swipeInteractionController = InteractiveTransition()
var screenEdgeRecognizer: UIScreenEdgePanGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
print("config viewDidLoad")
screenEdgeRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleUnwindRecognizer))
screenEdgeRecognizer.edges = .right
view.addGestureRecognizer(screenEdgeRecognizer)
}
override func viewDidAppear(_ animated: Bool)
{
registerForNotifications()
initializeDisplayValues()
}
override func viewWillDisappear(_ animated: Bool)
{
unregisterForNotifications()
}
func registerForNotifications()
{
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(self.textFieldDidChange),
name: NSNotification.Name.UITextFieldTextDidChange,
object: nil)
}
func initializeDisplayValues()
{
particleUser.text = settings.particleUser
particlePassword.text = settings.particlePassword
}
func unregisterForNotifications()
{
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self)
}
@objc func handleUnwindRecognizer(_ recognizer: UIScreenEdgePanGestureRecognizer)
{
if recognizer.state == .began
{
let transition: CATransition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionReveal
transition.subtype = kCATransitionFromRight
view.window!.layer.add(transition, forKey: nil)
dismiss(animated: false, completion: nil)
}
}
@objc func textFieldDidChange(sender : AnyObject) {
guard let notification = sender as? NSNotification,
let textFieldChanged = notification.object as? UITextField else
{
return
}
if let textString = textFieldChanged.text
{
print("text changed = \(textString)")
switch textFieldChanged
{
case self.particleUser:
userDidChange(string: textString)
break
case self.particlePassword:
passwordDidChange(string: textString)
break
default:
print("unknown text field")
break
}
}
}
fileprivate func userDidChange(string: String)
{
print("User changed")
settings.particleUser = string
loginIfDataIsValid()
}
fileprivate func passwordDidChange(string: String)
{
print("Password changed")
settings.particlePassword = string
loginIfDataIsValid()
}
fileprivate func loginIfDataIsValid()
{
print("particle login")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let appFactory = appDelegate.appFactory!
appFactory.loginToParticle()
}
}
| 4439661596c45ceb845f0c2821200d45 | 28.183206 | 120 | 0.617316 | false | false | false | false |
urbn/URBNValidator | refs/heads/master | Pod/Classes/ObjC/URBNLengthRulesCompat.swift | mit | 1 |
//
// URBNLengthRulesCompat.swift
// URBNValidator
//
// Created by Nick DiStefano on 12/21/15.
//
//
import Foundation
@objc open class URBNCompatMinLengthRule: URBNCompatRequirementRule {
public init(minLength: Int, inclusive: Bool = false, localizationKey: String? = nil) {
super.init()
backingRule = URBNMinLengthRule(minLength: minLength, inclusive: inclusive, localizationKey: localizationKey)
}
}
@objc open class URBNCompatMaxLengthRule: URBNCompatRequirementRule {
public init(maxLength: Int, inclusive: Bool = false, localizationKey: String? = nil) {
super.init()
backingRule = URBNMaxLengthRule(maxLength: maxLength, inclusive: inclusive, localizationKey: localizationKey)
}
}
| f644cae0f7f2086f4d0ee1639e45000e | 29.958333 | 117 | 0.728129 | false | false | false | false |
silence0201/Swift-Study | refs/heads/master | AdvancedSwift/协议/Indices/Indices - Stacks.playgroundpage/Contents.swift | mit | 1 | /*:
#### Stacks
This list is a stack, with consing as push, and unwrapping the next element as
pop. As we've mentioned before, arrays are also stacks. Let's define a common
protocol for stacks, as we did with queues:
*/
//#-editable-code
/// A LIFO stack type with constant-time push and pop operations
protocol Stack {
/// The type of element held stored in the stack
associatedtype Element
/// Pushes `x` onto the top of `self`
/// - Complexity: Amortized O(1).
mutating func push(_: Element)
/// Removes the topmost element of `self` and returns it,
/// or `nil` if `self` is empty.
/// - Complexity: O(1)
mutating func pop() -> Element?
}
//#-end-editable-code
/*:
We've been a bit more proscriptive in the documentation comments about what it
means to conform to `Stack`, including giving some minimum performance
guarantees.
`Array` can be made to conform to `Stack`, like this:
*/
//#-editable-code
extension Array: Stack {
mutating func push(_ x: Element) { append(x) }
mutating func pop() -> Element? { return popLast() }
}
//#-end-editable-code
/*:
So can `List`:
*/
//#-hidden-code
/// A simple linked list enum
enum List<Element> {
case end
indirect case node(Element, next: List<Element>)
}
//#-end-hidden-code
//#-hidden-code
extension List {
/// Return a new list by prepending a node with value `x` to the
/// front of a list.
func cons(_ x: Element) -> List {
return .node(x, next: self)
}
}
//#-end-hidden-code
//#-hidden-code
extension List: ExpressibleByArrayLiteral {
init(arrayLiteral elements: Element...) {
self = elements.reversed().reduce(.end) { partialList, element in
partialList.cons(element)
}
}
}
//#-end-hidden-code
//#-editable-code
extension List: Stack {
mutating func push(_ x: Element) {
self = self.cons(x)
}
mutating func pop() -> Element? {
switch self {
case .end: return nil
case let .node(x, next: xs):
self = xs
return x
}
}
}
//#-end-editable-code
/*:
But didn't we just say that the list had to be immutable for the persistence to
work? How can it have mutating methods?
These mutating methods don't change the list. Instead, they just change the part
of the list the variables refer to:
*/
//#-editable-code
var stack: List<Int> = [3,2,1]
var a = stack
var b = stack
a.pop()
a.pop()
a.pop()
stack.pop()
stack.push(4)
b.pop()
b.pop()
b.pop()
stack.pop()
stack.pop()
stack.pop()
//#-end-editable-code
/*:
This shows us the difference between values and variables. The nodes of the list
are values; they can't change. A node of three and a reference to the next node
can't become some other value; it'll be that value forever, just like the number
three can't change. It just is. Just because these values in question are
structures with references to each other doesn't make them less value-like.
A variable `a`, on the other hand, can change the value it holds. It can be set
to hold a value of an indirect reference to any of the nodes, or to the value
`end`. But changing `a` doesn't change these nodes; it just changes which node
`a` refers to.
This is what these mutating methods on structs do — they take an implicit
`inout` argument of `self`, and they can change the value `self` holds. This
doesn't change the list, but rather which part of the list the variable
currently represents. In this sense, through `indirect`, the variables have
become iterators into the list:

You can, of course, declare your variables with `let` instead of `var`, in which
case the variables will be constant (i.e. you can't change the value they hold
once they're set). But `let` is about the variables, not the values. Values are
constant by definition.
Now this is all just a logical model of how things work. In reality, the nodes
are actually places in memory that point to each other. And they take up space,
which we want back if it's no longer needed. Swift uses automated reference
counting (ARC) to manage this and frees the memory for the nodes that are no
longer used:

We'll discuss `inout` in more detail in the chapter on functions, and we'll
cover mutating methods as well as ARC in the structs and classes chapter.
*/
| dc60a0296d88235276c0999223e8c3be | 26.591195 | 80 | 0.692956 | false | false | false | false |
Jauzee/showroom | refs/heads/master | Showroom/ViewControllers/SearchViewController/WordReader.swift | gpl-3.0 | 1 | //
// WordReader.swift
// RAMReelExample
//
// Created by Mikhail Stepkin on 01.02.16.
// Copyright © 2016 Ramotion. All rights reserved.
//
import Foundation
public final class WordReader {
fileprivate(set) public var words: [String] = []
init (filepath: String) throws {
let fileManager = FileManager.default
guard fileManager.fileExists(atPath: filepath) else {
throw AnError.fileDoesntExist(filepath)
}
guard fileManager.isReadableFile(atPath: filepath) else {
throw AnError.fileIsNotReadable(filepath)
}
let contents = try String(contentsOfFile: filepath)
guard !contents.isEmpty else {
throw AnError.fileIsEmpty(filepath)
}
let words = contents.characters.split(separator: "\n")
self.words = words.map(String.init)
}
enum AnError: Error {
case fileDoesntExist(String)
case fileIsNotReadable(String)
case fileIsEmpty(String)
}
}
| 532e73fb1a27f5c1e8977a62c66ab2c6 | 24.357143 | 65 | 0.608451 | false | false | false | false |
tnantoka/AppBoard | refs/heads/master | AppBoard/Models/Software.swift | mit | 1 | //
// Software.swift
// AppBoard
//
// Created by Tatsuya Tobioka on 3/13/16.
// Copyright © 2016 Tatsuya Tobioka. All rights reserved.
//
import UIKit
import Himotoki
struct Software: Decodable {
let name: String
let description: String
let iconURL: NSURL?
let viewURL: NSURL?
let releaseDate: NSDate?
let thumbnail: UIImage?
static func decode(e: Extractor) throws -> Software {
return try Software(
name: e.value("trackName"),
description: e.value("description"),
iconURL: e.valueOptional("artworkUrl512").flatMap { NSURL(string: $0) },
viewURL: e.valueOptional("trackViewUrl").flatMap { NSURL(string: $0) },
releaseDate: e.valueOptional("releaseDate").flatMap { parseDate($0) },
thumbnail: e.valueOptional("artworkUrl60").flatMap { NSURL(string: $0) }.flatMap { NSData(contentsOfURL: $0) }.flatMap { UIImage(data: $0) }
)
}
static func parseDate(string: String) -> NSDate? {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter.dateFromString(string)
}
var app: App {
let app = App()
app.name = name
app.desc = description
app.icon = iconURL?.absoluteString ?? ""
app.url = viewURL?.absoluteString ?? ""
app.releasedAt = releaseDate ?? NSDate()
return app
}
}
| f156ef0b78e085acc27657ee9e6a2e6b | 30.456522 | 152 | 0.609537 | false | false | false | false |
jum/Charts | refs/heads/master | Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift | apache-2.0 | 2 | //
// BarChartRenderer.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
open class BarChartRenderer: BarLineScatterCandleBubbleRenderer
{
/// A nested array of elements ordered logically (i.e not in visual/drawing order) for use with VoiceOver
///
/// Its use is apparent when there are multiple data sets, since we want to read bars in left to right order,
/// irrespective of dataset. However, drawing is done per dataset, so using this array and then flattening it prevents us from needing to
/// re-render for the sake of accessibility.
///
/// In practise, its structure is:
///
/// ````
/// [
/// [dataset1 element1, dataset2 element1],
/// [dataset1 element2, dataset2 element2],
/// [dataset1 element3, dataset2 element3]
/// ...
/// ]
/// ````
/// This is done to provide numerical inference across datasets to a screenreader user, in the same way that a sighted individual
/// uses a multi-dataset bar chart.
///
/// The ````internal```` specifier is to allow subclasses (HorizontalBar) to populate the same array
internal lazy var accessibilityOrderedElements: [[NSUIAccessibilityElement]] = accessibilityCreateEmptyOrderedElements()
private class Buffer
{
var rects = [CGRect]()
}
@objc open weak var dataProvider: BarChartDataProvider?
@objc public init(dataProvider: BarChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
// [CGRect] per dataset
private var _buffers = [Buffer]()
open override func initBuffers()
{
if let barData = dataProvider?.barData
{
// Matche buffers count to dataset count
if _buffers.count != barData.dataSetCount
{
while _buffers.count < barData.dataSetCount
{
_buffers.append(Buffer())
}
while _buffers.count > barData.dataSetCount
{
_buffers.removeLast()
}
}
for i in stride(from: 0, to: barData.dataSetCount, by: 1)
{
let set = barData.dataSets[i] as! IBarChartDataSet
let size = set.entryCount * (set.isStacked ? set.stackSize : 1)
if _buffers[i].rects.count != size
{
_buffers[i].rects = [CGRect](repeating: CGRect(), count: size)
}
}
}
else
{
_buffers.removeAll()
}
}
private func prepareBuffer(dataSet: IBarChartDataSet, index: Int)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
let barWidthHalf = barData.barWidth / 2.0
let buffer = _buffers[index]
var bufferIndex = 0
let containsStacks = dataSet.isStacked
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
let phaseY = animator.phaseY
var barRect = CGRect()
var x: Double
var y: Double
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
let vals = e.yValues
x = e.x
y = e.y
if !containsStacks || vals == nil
{
let left = CGFloat(x - barWidthHalf)
let right = CGFloat(x + barWidthHalf)
var top = isInverted
? (y <= 0.0 ? CGFloat(y) : 0)
: (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted
? (y >= 0.0 ? CGFloat(y) : 0)
: (y <= 0.0 ? CGFloat(y) : 0)
/* When drawing each bar, the renderer actually draws each bar from 0 to the required value.
* This drawn bar is then clipped to the visible chart rect in BarLineChartViewBase's draw(rect:) using clipDataToContent.
* While this works fine when calculating the bar rects for drawing, it causes the accessibilityFrames to be oversized in some cases.
* This offset attempts to undo that unnecessary drawing when calculating barRects
*
* +---------------------------------------------------------------+---------------------------------------------------------------+
* | Situation 1: (!inverted && y >= 0) | Situation 3: (inverted && y >= 0) |
* | | |
* | y -> +--+ <- top | 0 -> ---+--+---+--+------ <- top |
* | |//| } topOffset = y - max | | | |//| } topOffset = min |
* | max -> +---------+--+----+ <- top - topOffset | min -> +--+--+---+--+----+ <- top + topOffset |
* | | +--+ |//| | | | | | |//| | |
* | | | | |//| | | | +--+ |//| | |
* | | | | |//| | | | |//| | |
* | min -> +--+--+---+--+----+ <- bottom + bottomOffset | max -> +---------+--+----+ <- bottom - bottomOffset |
* | | | |//| } bottomOffset = min | |//| } bottomOffset = y - max |
* | 0 -> ---+--+---+--+----- <- bottom | y -> +--+ <- bottom |
* | | |
* +---------------------------------------------------------------+---------------------------------------------------------------+
* | Situation 2: (!inverted && y < 0) | Situation 4: (inverted && y < 0) |
* | | |
* | 0 -> ---+--+---+--+----- <- top | y -> +--+ <- top |
* | | | |//| } topOffset = -max | |//| } topOffset = min - y |
* | max -> +--+--+---+--+----+ <- top - topOffset | min -> +---------+--+----+ <- top + topOffset |
* | | | | |//| | | | +--+ |//| | |
* | | +--+ |//| | | | | | |//| | |
* | | |//| | | | | | |//| | |
* | min -> +---------+--+----+ <- bottom + bottomOffset | max -> +--+--+---+--+----+ <- bottom - bottomOffset |
* | |//| } bottomOffset = min - y | | | |//| } bottomOffset = -max |
* | y -> +--+ <- bottom | 0 -> ---+--+---+--+------- <- bottom |
* | | |
* +---------------------------------------------------------------+---------------------------------------------------------------+
*/
var topOffset: CGFloat = 0.0
var bottomOffset: CGFloat = 0.0
if let offsetView = dataProvider as? BarChartView
{
let offsetAxis = offsetView.getAxis(dataSet.axisDependency)
if y >= 0
{
// situation 1
if offsetAxis.axisMaximum < y
{
topOffset = CGFloat(y - offsetAxis.axisMaximum)
}
if offsetAxis.axisMinimum > 0
{
bottomOffset = CGFloat(offsetAxis.axisMinimum)
}
}
else // y < 0
{
//situation 2
if offsetAxis.axisMaximum < 0
{
topOffset = CGFloat(offsetAxis.axisMaximum * -1)
}
if offsetAxis.axisMinimum > y
{
bottomOffset = CGFloat(offsetAxis.axisMinimum - y)
}
}
if isInverted
{
// situation 3 and 4
// exchange topOffset/bottomOffset based on 1 and 2
// see diagram above
(topOffset, bottomOffset) = (bottomOffset, topOffset)
}
}
//apply offset
top = isInverted ? top + topOffset : top - topOffset
bottom = isInverted ? bottom - bottomOffset : bottom + bottomOffset
// multiply the height of the rect with the phase
// explicitly add 0 + topOffset to indicate this is changed after adding accessibility support (#3650, #3520)
if top > 0 + topOffset
{
top *= CGFloat(phaseY)
}
else
{
bottom *= CGFloat(phaseY)
}
barRect.origin.x = left
barRect.origin.y = top
barRect.size.width = right - left
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
else
{
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// fill the stack
for k in 0 ..< vals!.count
{
let value = vals![k]
if value == 0.0 && (posY == 0.0 || negY == 0.0)
{
// Take care of the situation of a 0.0 value, which overlaps a non-zero bar
y = value
yStart = y
}
else if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let left = CGFloat(x - barWidthHalf)
let right = CGFloat(x + barWidthHalf)
var top = isInverted
? (y <= yStart ? CGFloat(y) : CGFloat(yStart))
: (y >= yStart ? CGFloat(y) : CGFloat(yStart))
var bottom = isInverted
? (y >= yStart ? CGFloat(y) : CGFloat(yStart))
: (y <= yStart ? CGFloat(y) : CGFloat(yStart))
// multiply the height of the rect with the phase
top *= CGFloat(phaseY)
bottom *= CGFloat(phaseY)
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
}
}
}
open override func drawData(context: CGContext)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
// If we redraw the data, remove and repopulate accessible elements to update label values and frames
accessibleChartElements.removeAll()
accessibilityOrderedElements = accessibilityCreateEmptyOrderedElements()
// Make the chart header the first element in the accessible elements array
if let chart = dataProvider as? BarChartView {
let element = createAccessibleHeader(usingChart: chart,
andData: barData,
withDefaultDescription: "Bar Chart")
accessibleChartElements.append(element)
}
// Populate logically ordered nested elements into accessibilityOrderedElements in drawDataSet()
for i in 0 ..< barData.dataSetCount
{
guard let set = barData.getDataSetByIndex(i) else { continue }
if set.isVisible
{
if !(set is IBarChartDataSet)
{
fatalError("Datasets for BarChartRenderer must conform to IBarChartDataset")
}
drawDataSet(context: context, dataSet: set as! IBarChartDataSet, index: i)
}
}
// Merge nested ordered arrays into the single accessibleChartElements.
accessibleChartElements.append(contentsOf: accessibilityOrderedElements.flatMap { $0 } )
accessibilityPostLayoutChangedNotification()
}
private var _barShadowRectBuffer: CGRect = CGRect()
@objc open func drawDataSet(context: CGContext, dataSet: IBarChartDataSet, index: Int)
{
guard let dataProvider = dataProvider else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
prepareBuffer(dataSet: dataSet, index: index)
trans.rectValuesToPixel(&_buffers[index].rects)
let borderWidth = dataSet.barBorderWidth
let borderColor = dataSet.barBorderColor
let drawBorder = borderWidth > 0.0
context.saveGState()
// draw the bar shadow before the values
if dataProvider.isDrawBarShadowEnabled
{
guard let barData = dataProvider.barData else { return }
let barWidth = barData.barWidth
let barWidthHalf = barWidth / 2.0
var x: Double = 0.0
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
x = e.x
_barShadowRectBuffer.origin.x = CGFloat(x - barWidthHalf)
_barShadowRectBuffer.size.width = CGFloat(barWidth)
trans.rectValueToPixel(&_barShadowRectBuffer)
if !viewPortHandler.isInBoundsLeft(_barShadowRectBuffer.origin.x + _barShadowRectBuffer.size.width)
{
continue
}
if !viewPortHandler.isInBoundsRight(_barShadowRectBuffer.origin.x)
{
break
}
_barShadowRectBuffer.origin.y = viewPortHandler.contentTop
_barShadowRectBuffer.size.height = viewPortHandler.contentHeight
context.setFillColor(dataSet.barShadowColor.cgColor)
context.fill(_barShadowRectBuffer)
}
}
let buffer = _buffers[index]
// draw the bar shadow before the values
if dataProvider.isDrawBarShadowEnabled
{
for j in stride(from: 0, to: buffer.rects.count, by: 1)
{
let barRect = buffer.rects[j]
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
context.setFillColor(dataSet.barShadowColor.cgColor)
context.fill(barRect)
}
}
let isSingleColor = dataSet.colors.count == 1
if isSingleColor
{
context.setFillColor(dataSet.color(atIndex: 0).cgColor)
}
// In case the chart is stacked, we need to accomodate individual bars within accessibilityOrdereredElements
let isStacked = dataSet.isStacked
let stackSize = isStacked ? dataSet.stackSize : 1
for j in stride(from: 0, to: buffer.rects.count, by: 1)
{
let barRect = buffer.rects[j]
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
if !isSingleColor
{
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
context.setFillColor(dataSet.color(atIndex: j).cgColor)
}
context.fill(barRect)
if drawBorder
{
context.setStrokeColor(borderColor.cgColor)
context.setLineWidth(borderWidth)
context.stroke(barRect)
}
// Create and append the corresponding accessibility element to accessibilityOrderedElements
if let chart = dataProvider as? BarChartView
{
let element = createAccessibleElement(withIndex: j,
container: chart,
dataSet: dataSet,
dataSetIndex: index,
stackSize: stackSize)
{ (element) in
element.accessibilityFrame = barRect
}
accessibilityOrderedElements[j/stackSize].append(element)
}
}
context.restoreGState()
}
open func prepareBarHighlight(
x: Double,
y1: Double,
y2: Double,
barWidthHalf: Double,
trans: Transformer,
rect: inout CGRect)
{
let left = x - barWidthHalf
let right = x + barWidthHalf
let top = y1
let bottom = y2
rect.origin.x = CGFloat(left)
rect.origin.y = CGFloat(top)
rect.size.width = CGFloat(right - left)
rect.size.height = CGFloat(bottom - top)
trans.rectValueToPixel(&rect, phaseY: animator.phaseY )
}
open override func drawValues(context: CGContext)
{
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
var dataSets = barData.dataSets
let valueOffsetPlus: CGFloat = 4.5
var posOffset: CGFloat
var negOffset: CGFloat
let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled
for dataSetIndex in 0 ..< barData.dataSetCount
{
guard let
dataSet = dataSets[dataSetIndex] as? IBarChartDataSet,
shouldDrawValues(forDataSet: dataSet)
else { continue }
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
// calculate the correct offset depending on the draw position of the value
let valueFont = dataSet.valueFont
let valueTextHeight = valueFont.lineHeight
posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus)
negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus))
if isInverted
{
posOffset = -posOffset - valueTextHeight
negOffset = -negOffset - valueTextHeight
}
let buffer = _buffers[dataSetIndex]
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
let iconsOffset = dataSet.iconsOffset
// if only single values are drawn (sum)
if !dataSet.isStacked
{
for j in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let rect = buffer.rects[j]
let x = rect.origin.x + rect.size.width / 2.0
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(rect.origin.y)
|| !viewPortHandler.isInBoundsLeft(x)
{
continue
}
let val = e.y
if dataSet.isDrawValuesEnabled
{
drawValue(
context: context,
value: formatter.stringForValue(
val,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: val >= 0.0
? (rect.origin.y + posOffset)
: (rect.origin.y + rect.size.height + negOffset),
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(j))
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
var px = x
var py = val >= 0.0
? (rect.origin.y + posOffset)
: (rect.origin.y + rect.size.height + negOffset)
px += iconsOffset.x
py += iconsOffset.y
ChartUtils.drawImage(
context: context,
image: icon,
x: px,
y: py,
size: icon.size)
}
}
}
else
{
// if we have stacks
var bufferIndex = 0
for index in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(index) as? BarChartDataEntry else { continue }
let vals = e.yValues
let rect = buffer.rects[bufferIndex]
let x = rect.origin.x + rect.size.width / 2.0
// we still draw stacked bars, but there is one non-stacked in between
if vals == nil
{
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(rect.origin.y)
|| !viewPortHandler.isInBoundsLeft(x)
{
continue
}
if dataSet.isDrawValuesEnabled
{
drawValue(
context: context,
value: formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: rect.origin.y +
(e.y >= 0 ? posOffset : negOffset),
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(index))
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
var px = x
var py = rect.origin.y +
(e.y >= 0 ? posOffset : negOffset)
px += iconsOffset.x
py += iconsOffset.y
ChartUtils.drawImage(
context: context,
image: icon,
x: px,
y: py,
size: icon.size)
}
}
else
{
// draw stack values
let vals = vals!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for k in 0 ..< vals.count
{
let value = vals[k]
var y: Double
if value == 0.0 && (posY == 0.0 || negY == 0.0)
{
// Take care of the situation of a 0.0 value, which overlaps a non-zero bar
y = value
}
else if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: 0.0, y: CGFloat(y * phaseY)))
}
trans.pointValuesToPixel(&transformed)
for k in 0 ..< transformed.count
{
let val = vals[k]
let drawBelow = (val == 0.0 && negY == 0.0 && posY > 0.0) || val < 0.0
let y = transformed[k].y + (drawBelow ? negOffset : posOffset)
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x)
{
continue
}
if dataSet.isDrawValuesEnabled
{
drawValue(
context: context,
value: formatter.stringForValue(
vals[k],
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: y,
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(index))
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
ChartUtils.drawImage(
context: context,
image: icon,
x: x + iconsOffset.x,
y: y + iconsOffset.y,
size: icon.size)
}
}
}
bufferIndex = vals == nil ? (bufferIndex + 1) : (bufferIndex + vals!.count)
}
}
}
}
}
/// Draws a value at the specified x and y position.
@objc open func drawValue(context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: NSUIFont, align: NSTextAlignment, color: NSUIColor)
{
ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: color])
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
context.saveGState()
var barRect = CGRect()
for high in indices
{
guard
let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet,
set.isHighlightEnabled
else { continue }
if let e = set.entryForXValue(high.x, closestToY: high.y) as? BarChartDataEntry
{
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
context.setFillColor(set.highlightColor.cgColor)
context.setAlpha(set.highlightAlpha)
let isStack = high.stackIndex >= 0 && e.isStacked
let y1: Double
let y2: Double
if isStack
{
if dataProvider.isHighlightFullBarEnabled
{
y1 = e.positiveSum
y2 = -e.negativeSum
}
else
{
let range = e.ranges?[high.stackIndex]
y1 = range?.from ?? 0.0
y2 = range?.to ?? 0.0
}
}
else
{
y1 = e.y
y2 = 0.0
}
prepareBarHighlight(x: e.x, y1: y1, y2: y2, barWidthHalf: barData.barWidth / 2.0, trans: trans, rect: &barRect)
setHighlightDrawPos(highlight: high, barRect: barRect)
context.fill(barRect)
}
}
context.restoreGState()
}
/// Sets the drawing position of the highlight object based on the given bar-rect.
internal func setHighlightDrawPos(highlight high: Highlight, barRect: CGRect)
{
high.setDraw(x: barRect.midX, y: barRect.origin.y)
}
/// Creates a nested array of empty subarrays each of which will be populated with NSUIAccessibilityElements.
/// This is marked internal to support HorizontalBarChartRenderer as well.
internal func accessibilityCreateEmptyOrderedElements() -> [[NSUIAccessibilityElement]]
{
guard let chart = dataProvider as? BarChartView else { return [] }
// Unlike Bubble & Line charts, here we use the maximum entry count to account for stacked bars
let maxEntryCount = chart.data?.maxEntryCountSet?.entryCount ?? 0
return Array(repeating: [NSUIAccessibilityElement](),
count: maxEntryCount)
}
/// Creates an NSUIAccessibleElement representing the smallest meaningful bar of the chart
/// i.e. in case of a stacked chart, this returns each stack, not the combined bar.
/// Note that it is marked internal to support subclass modification in the HorizontalBarChart.
internal func createAccessibleElement(withIndex idx: Int,
container: BarChartView,
dataSet: IBarChartDataSet,
dataSetIndex: Int,
stackSize: Int,
modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement
{
let element = NSUIAccessibilityElement(accessibilityContainer: container)
let xAxis = container.xAxis
guard let e = dataSet.entryForIndex(idx/stackSize) as? BarChartDataEntry else { return element }
guard let dataProvider = dataProvider else { return element }
// NOTE: The formatter can cause issues when the x-axis labels are consecutive ints.
// i.e. due to the Double conversion, if there are more than one data set that are grouped,
// there is the possibility of some labels being rounded up. A floor() might fix this, but seems to be a brute force solution.
let label = xAxis.valueFormatter?.stringForValue(e.x, axis: xAxis) ?? "\(e.x)"
var elementValueText = dataSet.valueFormatter?.stringForValue(
e.y,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler) ?? "\(e.y)"
if dataSet.isStacked, let vals = e.yValues
{
let labelCount = min(dataSet.colors.count, stackSize)
let stackLabel: String?
if (dataSet.stackLabels.count > 0 && labelCount > 0) {
let labelIndex = idx % labelCount
stackLabel = dataSet.stackLabels.indices.contains(labelIndex) ? dataSet.stackLabels[labelIndex] : nil
} else {
stackLabel = nil
}
elementValueText = dataSet.valueFormatter?.stringForValue(
vals[idx % stackSize],
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler) ?? "\(e.y)"
if let stackLabel = stackLabel {
elementValueText = stackLabel + " \(elementValueText)"
} else {
elementValueText = "\(elementValueText)"
}
}
let dataSetCount = dataProvider.barData?.dataSetCount ?? -1
let doesContainMultipleDataSets = dataSetCount > 1
element.accessibilityLabel = "\(doesContainMultipleDataSets ? (dataSet.label ?? "") + ", " : "") \(label): \(elementValueText)"
modifier(element)
return element
}
}
| 325d2d9233c740b99f6f1f01cca8c768 | 42.589026 | 202 | 0.404573 | false | false | false | false |
TheBrewery/Hikes | refs/heads/master | WorldHeritage/Components/TBLocationManager.swift | mit | 1 |
import CoreLocation
import UIKit
extension CLLocationCoordinate2D {
func coordinatesSeparatedByComma() -> String {
return "\(self.latitude),\(self.longitude)"
}
}
enum TBLocationServicesStatus {
case Authorized
case Unauthorized
case Disabled
}
class TBLocationManager: CLLocationManager, CLLocationManagerDelegate {
private static let sharedInstance = TBLocationManager()
private var didChangeAuthorizationStatus: ((CLAuthorizationStatus) -> ())?
private var didUpdateLocations: ((CLLocation?, NSError?) -> ())?
private override init() {
super.init()
desiredAccuracy = kCLLocationAccuracyNearestTenMeters
distanceFilter = 500
delegate = self
}
class func unauthorizedAlertController() -> UIViewController {
let appName = NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String
let title = "Allow \"\(appName)\" to access your location while you use the app?"
let message = NSBundle.mainBundle().infoDictionary!["NSLocationWhenInUseUsageDescription"] as! String
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Don't Allow", style: .Default, handler: nil))
alertController.addAction(UIAlertAction(title: "Allow", style: .Default, handler: { (action) in ()
let url = NSURL(string: UIApplicationOpenSettingsURLString)!
UIApplication.sharedApplication().openURL(url)
}))
return alertController
}
class func disabledAlertController() -> UIViewController {
let title = "Location Services is disabled"
let message = NSBundle.mainBundle().infoDictionary!["NSLocationWhenInUseUsageDescription"] as! String
let alertController = UIAlertController(title: title, message: message + " Please turn on Location Services in the Privacy section of your device settings.", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "No Thanks", style: .Default, handler: nil))
alertController.addAction(UIAlertAction(title: "Go to Settings", style: .Default, handler: { (action) in ()
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}))
return alertController
}
class var currentLocation: CLLocation? {
return sharedInstance.location
}
class var isAvailable: Bool {
return isEnabled && isAuthorized
}
class var isAuthorized: Bool {
return authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse
}
class var isEnabled: Bool {
return locationServicesEnabled()
}
class func authorize(completion: ((CLAuthorizationStatus) -> ())? = nil) {
sharedInstance.didChangeAuthorizationStatus = completion
sharedInstance.requestWhenInUseAuthorization()
}
class func updateLocation() {
sharedInstance.startUpdatingLocation()
}
class func getGeolocation(completion: ((CLLocation?, NSError?) -> ())?) {
guard let location = sharedInstance.location else {
sharedInstance.didUpdateLocations = completion
updateLocation()
return
}
completion?(location, nil)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
stopUpdatingLocation()
didUpdateLocations?(locations.first, nil)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
stopUpdatingLocation()
didUpdateLocations?(nil, error)
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
didChangeAuthorizationStatus?(status)
}
}
| 23251d7356cf82855bc61f8a0632719e | 36.475728 | 189 | 0.698187 | false | false | false | false |
h-n-y/BigNerdRanch-SwiftProgramming | refs/heads/master | chapter-24/silver-challenge/CyclicalAssets/Person.swift | mit | 1 | //
// Person.swift
// CyclicalAssets
//
// Created by Hans Yelek on 1/28/16.
// Copyright © 2016 Hans Yelek. All rights reserved.
//
import Foundation
class Person: CustomStringConvertible {
let name: String
let accountant = Accountant()
var assets = [Asset]()
var description: String {
return "Person(\(name))"
}
init(name: String) {
self.name = name
accountant.netWorthChangedHandler = {
[weak self]( netWorth ) in
self?.netWorthDidChange(netWorth)
return
}
}
deinit {
print("\(self) is being deallocated")
}
func takeOwnershipOfAsset(asset: Asset) {
// SILVER CHALLENGE
//
// prevent asset from being assigned to a second owner if
// it is already owned
guard asset.owner == nil else {
print("Cannot take ownership - asset is already owned!")
return
}
asset.owner = self
assets.append(asset)
accountant.gainedNewAsset(asset)
}
func netWorthDidChange(netWorth: Double) {
print("The net worth of \(self) is now \(netWorth)")
}
}
| 415159b982181035bc98095964e697e3 | 21.87037 | 68 | 0.550607 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Concurrency/actor_keypath_isolation.swift | apache-2.0 | 10 | // RUN: %target-typecheck-verify-swift -disable-availability-checking -warn-concurrency
// REQUIRES: concurrency
class Box { // expected-note 3{{class 'Box' does not conform to the 'Sendable' protocol}}
let size : Int = 0
}
actor Door {
let immutable : Int = 0
let letBox : Box? = nil
let letDict : [Int : Box] = [:]
let immutableNeighbor : Door? = nil
var mutableNeighbor : Door? = nil
var varDict : [Int : Box] = [:]
var mutable : Int = 0
var varBox : Box = Box()
var getOnlyInt : Int {
get { 0 }
}
@MainActor var globActor_mutable : Int = 0
@MainActor let globActor_immutable : Int = 0
@MainActor(unsafe) var unsafeGlobActor_mutable : Int = 0
@MainActor(unsafe) let unsafeGlobActor_immutable : Int = 0
subscript(byIndex: Int) -> Int { 0 }
@MainActor subscript(byName: String) -> Int { 0 }
nonisolated subscript(byIEEE754: Double) -> Int { 0 }
}
func attemptAccess<T, V>(_ t : T, _ f : (T) -> V) -> V {
return f(t)
}
func tryKeyPathsMisc(d : Door) {
// as a func
_ = attemptAccess(d, \Door.mutable) // expected-error {{cannot form key path to actor-isolated property 'mutable'}}
_ = attemptAccess(d, \Door.immutable)
_ = attemptAccess(d, \Door.immutableNeighbor?.immutableNeighbor)
// in combination with other key paths
_ = (\Door.letBox).appending(path: // expected-warning {{cannot form key path that accesses non-sendable type 'Box?'}}
\Box?.?.size)
_ = (\Door.varBox).appending(path: // expected-error {{cannot form key path to actor-isolated property 'varBox'}}
\Box.size)
}
func tryKeyPathsFromAsync() async {
_ = \Door.unsafeGlobActor_immutable
_ = \Door.unsafeGlobActor_mutable // okay for now
}
func tryNonSendable() {
_ = \Door.letDict[0] // expected-warning {{cannot form key path that accesses non-sendable type '[Int : Box]'}}
_ = \Door.varDict[0] // expected-error {{cannot form key path to actor-isolated property 'varDict'}}
_ = \Door.letBox!.size // expected-warning {{cannot form key path that accesses non-sendable type 'Box?'}}
}
func tryKeypaths() {
_ = \Door.unsafeGlobActor_immutable
_ = \Door.unsafeGlobActor_mutable // okay for now
_ = \Door.immutable
_ = \Door.globActor_immutable
_ = \Door.[4.2]
_ = \Door.immutableNeighbor?.immutableNeighbor?.immutableNeighbor
_ = \Door.varBox // expected-error{{cannot form key path to actor-isolated property 'varBox'}}
_ = \Door.mutable // expected-error{{cannot form key path to actor-isolated property 'mutable'}}
_ = \Door.getOnlyInt // expected-error{{cannot form key path to actor-isolated property 'getOnlyInt'}}
_ = \Door.mutableNeighbor?.mutableNeighbor?.mutableNeighbor // expected-error 3 {{cannot form key path to actor-isolated property 'mutableNeighbor'}}
let _ : PartialKeyPath<Door> = \.mutable // expected-error{{cannot form key path to actor-isolated property 'mutable'}}
let _ : AnyKeyPath = \Door.mutable // expected-error{{cannot form key path to actor-isolated property 'mutable'}}
_ = \Door.globActor_mutable // okay for now
_ = \Door.[0] // expected-error{{cannot form key path to actor-isolated subscript 'subscript(_:)'}}
_ = \Door.["hello"] // okay for now
}
| 5521455df8f0e6863ccd1cb70d11fa84 | 37.517241 | 153 | 0.645777 | false | false | false | false |
tomboates/BrilliantSDK | refs/heads/master | Pod/Classes/CommentsViewController.swift | mit | 1 | //
// CommentsViewController.swift
// Pods
//
// Created by Phillip Connaughton on 1/24/16.
//
//
import Foundation
protocol CommentsViewControllerDelegate: class{
func closePressed(_ state: SurveyViewControllerState)
func submitFeedbackPressed()
func doNotSubmitFeedbackPressed()
}
class CommentsViewController: UIViewController
{
@IBOutlet var closeButton: UIButton!
@IBOutlet var comments: UITextView!
@IBOutlet var noThanksButton: UIButton!
@IBOutlet var submitButton: UIButton!
@IBOutlet var commentDescriptionLabel: UILabel!
@IBOutlet var doneButton: UIBarButtonItem!
@IBOutlet var keyboardToolbar: UIToolbar!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
internal weak var delegate : CommentsViewControllerDelegate?
override func viewDidLoad() {
let image = UIImage(named: "brilliant-icon-close", in:Brilliant.imageBundle(), compatibleWith: nil)
self.closeButton.setImage(image, for: UIControlState())
self.closeButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 25, right: 25)
self.commentDescriptionLabel.textColor = Brilliant.sharedInstance().mainLabelColor()
self.commentDescriptionLabel.font = Brilliant.sharedInstance().mainLabelFont()
self.comments.layer.cornerRadius = 4;
self.comments.inputAccessoryView = self.keyboardToolbar
self.comments.font = Brilliant.sharedInstance().commentBoxFont()
let npsNumber: Int! = Brilliant.sharedInstance().completedSurvey?.npsRating!
if(npsNumber >= 7)
{
self.commentDescriptionLabel.text = Brilliant.sharedInstance().positiveFeedbackText(npsNumber)
}
else
{
self.commentDescriptionLabel.text = Brilliant.sharedInstance().negativeFeedbackText(npsNumber)
}
Brilliant.sharedInstance().styleButton(self.submitButton)
self.noThanksButton.tintColor = Brilliant.sharedInstance().noThanksButtonColor()
self.submitButton.titleLabel?.font = Brilliant.sharedInstance().submitButtonFont()
self.noThanksButton.titleLabel?.font = Brilliant.sharedInstance().submitButtonFont()
NotificationCenter.default.addObserver(self, selector: #selector(adjustForKeyboard), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(adjustForKeyboard), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func adjustForKeyboard(_ notification: Notification) {
var userInfo = (notification as NSNotification).userInfo!
let keyboardScreenEndFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, to: view.window)
self.view.translatesAutoresizingMaskIntoConstraints = true
let screenHeight = UIScreen.main.bounds.height
let height = self.comments.frame.height + self.comments.frame.origin.y
let diffHeight = CGFloat(screenHeight) - height
var moveHeight : CGFloat? = 0
if (diffHeight < keyboardViewEndFrame.height) {
moveHeight = diffHeight - keyboardViewEndFrame.height
}
var offset : CGFloat? = 0
if comments.frame.origin.y < abs(moveHeight!) {
offset = abs(moveHeight!) - comments.frame.origin.y - 5
}
if notification.name == NSNotification.Name.UIKeyboardWillHide {
UIView.animate(withDuration: 1.0, animations: {
self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
})
} else {
UIView.animate(withDuration: 1.0, animations: {
self.view.frame = CGRect(x: 0, y: moveHeight! + offset! - 5, width: self.view.frame.width, height: self.view.frame.height)
})
}
}
func textFieldValue(_ notification: Notification){
if comments.text.isEmpty {
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.noThanksButton.alpha = 1
self.submitButton.alpha = 0
}, completion: nil)
} else {
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.noThanksButton.alpha = 0
self.submitButton.alpha = 1
}, completion: nil)
}
}
func textView(_ textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
if comments.text.isEmpty {
textView.resignFirstResponder()
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.noThanksButton.alpha = 1
self.submitButton.alpha = 0
}, completion: nil)
return false
} else {
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.noThanksButton.alpha = 0
self.submitButton.alpha = 1
}, completion: nil)
}
textView.resignFirstResponder()
return false
}
return true
}
func textFieldDidReturn(_ textField: UITextField!) {
textField.resignFirstResponder()
// Execute additional code
}
func keyboardWasShown(_ notification: Notification)
{
//Need to calculate keyboard exact size due to Apple suggestions
// npsView.scrollEnabled = true
// let info : NSDictionary = notification.userInfo!
// var keyboardSize : CGRect = ((info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue())!
// keyboardSize = comments.convertRect(keyboardSize, toView: nil)
// let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0)
//
// npsView.contentInset = contentInsets
// npsView.scrollIndicatorInsets = contentInsets
//
// var aRect : CGRect = self.view.frame
// aRect.size.height -= (keyboardSize.height + 100)
// var fieldOrigin : CGPoint = comments.frame.origin;
// fieldOrigin.y -= npsView.contentOffset.y;
// fieldOrigin = comments.convertPoint(fieldOrigin, toView: self.view.superview)
// originalOffset = npsView.contentOffset;
//
// if (!CGRectContainsPoint(aRect, fieldOrigin))
// {
// npsView.scrollRectToVisible(comments.frame, animated: true)
// }
}
func keyboardWillBeHidden(_ notification: Notification)
{
//Once keyboard disappears, restore original positions
// let info : NSDictionary = notification.userInfo!
// let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
// let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
// npsView.contentInset = contentInsets
// npsView.scrollIndicatorInsets = contentInsets
// npsView.setContentOffset(originalOffset, animated: true)
// self.view.endEditing(true)
// npsView.scrollEnabled = false
}
@IBAction func submitPressed(_ sender: AnyObject) {
Brilliant.sharedInstance().completedSurvey!.comment = self.comments.text
self.delegate?.submitFeedbackPressed()
}
@IBAction func noThanksPressed(_ sender: AnyObject) {
self.delegate?.doNotSubmitFeedbackPressed()
}
@IBAction func closePressed(_ sender: AnyObject) {
self.delegate?.closePressed(.commentScreen)
}
@IBAction func keyboardDoneClicked(_ sender: AnyObject) {
self.comments.resignFirstResponder()
}
}
| 7c77d44a003a8ffee28111b7cd01c57a | 39.910448 | 151 | 0.640399 | false | false | false | false |
heptorsj/Design-Patterns-Swftly | refs/heads/master | Builder.swift | gpl-3.0 | 1 | // Builder Desing Pattern
/*
Separate the construction of a complex object from
its representation so that the same construction
process can create different representations.
*/
// We need:
// A Director, A Builder , A Client and Product
// Example: A Burger Fast Food Restaurant
// We define tipes for project
enum Burger { // A burger can be one of these
case chessBurger
case chickernBurger
case beefBurger
}
enum Drink { // A coke can be one ot these
case cocaCola
case pepsiCola
}
enum Complement { // Second item of package
case frenchFries
case wings
}
enum Toy{ // Two types of toys
case forBoy
case forGirl
}
// Structure of a generic package
class BurgerPackage{
var burger: Burger = Burger.chessBurger
var drink: Drink = Drink.pepsiCola
var complement:Complement = Complement.frenchFries
var toy: Toy = Toy.forGirl
}
// Build abstract protocol to create all of possible packages
protocol builderBurgers{
var customerPackage: BurgerPackage {get} // Creates a new packages
// Now the functions that creates all the variations
func setBurger(burger:Burger)-> Burger
func setDrink(drink:Drink)-> Drink
func setComplement(complement:Complement)-> Complement
func setToy(toy:Toy)-> Toy
}
// Define concrete package Builder
class PackageMaker : builderBurgers {
var customerPackage: BurgerPackage
// functions that makes custome packages
func setBurger(burger:Burger) -> Burger {
switch burger {
case .chickernBurger:
customerPackage.burger = Burger.chickernBurger
return Burger.chickernBurger
case .beefBurger:
customerPackage.burger = Burger.beefBurger
return Burger.beefBurger
default:
return Burger.chessBurger
}
}
func setDrink(drink: Drink)-> Drink {
switch drink {
case .cocaCola:
customerPackage.drink = Drink.cocaCola
return Drink.cocaCola
default:
return Drink.pepsiCola
}
}
func setComplement(complement:Complement)-> Complement {
switch complement {
case .wings:
customerPackage.complement = Complement.wings
return Complement.wings
default:
return Complement.frenchFries
}
}
func setToy(toy:Toy)->Toy{
switch toy {
case .forBoy:
customerPackage.toy = Toy.forBoy
return Toy.forBoy
default:
return Toy.forGirl
}
}
init(burger:Burger,drink:Drink,complement:Complement,toy:Toy){
self.customerPackage = BurgerPackage()
setBurger(burger:burger)
setDrink(drink:drink)
setComplement(complement:complement)
setToy(toy:toy)
}
}
// Now make some packages
let client = PackageMaker(burger:Burger.beefBurger,drink:Drink.pepsiCola,complement:Complement.wings,toy:Toy.forBoy)
print("Burger: \(client.customerPackage.burger)")
print("Drink: \(client.customerPackage.drink)")
print("Complement: \(client.customerPackage.complement)")
print("Toy: \(client.customerPackage.toy)")
| 8aeeed10a98029a0b69837c8d7c48fe7 | 26.570093 | 118 | 0.718644 | false | false | false | false |
Joachimdj/JobResume | refs/heads/develop | Apps/Forum17/2017/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift | apache-2.0 | 6 | //
// ImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2017 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.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
// MARK: - Extension methods.
/**
* Set image to use from web.
*/
extension Kingfisher where Base: ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
If `resource` is `nil`, the `placeholder` image will be set and
`completionHandler` will be called with both `error` and `image` being `nil`.
*/
@discardableResult
public func setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
guard let resource = resource else {
base.image = placeholder
setWebURL(nil)
completionHandler?(nil, nil, .none, nil)
return .empty
}
var options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo)
if !options.keepCurrentImageWhileLoading || base.image == nil {
base.image = placeholder
}
let maybeIndicator = indicator
maybeIndicator?.startAnimatingView()
setWebURL(resource.downloadURL)
if base.shouldPreloadAllAnimation() {
options.append(.preloadAllAnimationData)
}
let task = KingfisherManager.shared.retrieveImage(
with: resource,
options: options,
progressBlock: { receivedSize, totalSize in
guard resource.downloadURL == self.webURL else {
return
}
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: {[weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
maybeIndicator?.stopAnimatingView()
guard let strongBase = base, imageURL == self.webURL else {
completionHandler?(image, error, cacheType, imageURL)
return
}
self.setImageTask(nil)
guard let image = image else {
completionHandler?(nil, error, cacheType, imageURL)
return
}
guard let transitionItem = options.lastMatchIgnoringAssociatedValue(.transition(.none)),
case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else
{
strongBase.image = image
completionHandler?(image, error, cacheType, imageURL)
return
}
#if !os(macOS)
UIView.transition(with: strongBase, duration: 0.0, options: [],
animations: { maybeIndicator?.stopAnimatingView() },
completion: { _ in
UIView.transition(with: strongBase, duration: transition.duration,
options: [transition.animationOptions, .allowUserInteraction],
animations: {
// Set image property in the animation.
transition.animations?(strongBase, image)
},
completion: { finished in
transition.completion?(finished)
completionHandler?(image, error, cacheType, imageURL)
})
})
#endif
}
})
setImageTask(task)
return task
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func cancelDownloadTask() {
imageTask?.cancel()
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var indicatorKey: Void?
private var indicatorTypeKey: Void?
private var imageTaskKey: Void?
extension Kingfisher where Base: ImageView {
/// Get the image URL binded to this image view.
public var webURL: URL? {
return objc_getAssociatedObject(base, &lastURLKey) as? URL
}
fileprivate func setWebURL(_ url: URL?) {
objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
public var indicatorType: IndicatorType {
get {
let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value
return indicator ?? .none
}
set {
switch newValue {
case .none:
indicator = nil
case .activity:
indicator = ActivityIndicator()
case .image(let data):
indicator = ImageIndicator(imageData: data)
case .custom(let anIndicator):
indicator = anIndicator
}
objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `indicatorType` is `.none`.
public fileprivate(set) var indicator: Indicator? {
get {
return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value
}
set {
// Remove previous
if let previousIndicator = indicator {
previousIndicator.view.removeFromSuperview()
}
// Add new
if var newIndicator = newValue {
// Set default indicator frame if the view's frame not set.
if newIndicator.view.frame != .zero {
newIndicator.view.frame = base.frame
}
newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY)
newIndicator.view.isHidden = true
base.addSubview(newIndicator.view)
}
// Save in associated object
objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
}
fileprivate func setImageTask(_ task: RetrieveImageTask?) {
objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Deprecated. Only for back compatibility.
/**
* Set image to use from web. Deprecated. Use `kf` namespacing instead.
*/
extension ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage")
@discardableResult
public func kf_setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask")
public func kf_cancelDownloadTask() { kf.cancelDownloadTask() }
/// Get the image URL binded to this image view.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL")
public var kf_webURL: URL? { return kf.webURL }
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType")
public var kf_indicatorType: IndicatorType {
get { return kf.indicatorType }
set { kf.indicatorType = newValue }
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator")
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `kf_indicatorType` is `.none`.
public private(set) var kf_indicator: Indicator? {
get { return kf.indicator }
set { kf.indicator = newValue }
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask")
fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask")
fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL")
fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) }
func shouldPreloadAllAnimation() -> Bool { return true }
@available(*, deprecated, renamed: "shouldPreloadAllAnimation")
func shouldPreloadAllGIF() -> Bool { return true }
}
| 22eeea0d1b59926c4d1861a950701a62 | 44.906667 | 173 | 0.601873 | false | false | false | false |
AllenConquest/emonIOS | refs/heads/master | emonIOSTests/FeedSpec.swift | gpl-2.0 | 1 | //
// FeedSpec.swift
// emonIOS
//
// Created by Allen Conquest on 25/07/2015.
// Copyright (c) 2015 Allen Conquest. All rights reserved.
//
import Quick
import Nimble
import emonIOS
import SwiftyJSON
class FeedSpec: QuickSpec {
override func spec() {
// var feed: Feed!
//
// beforeEach() {
// feed = Feed()
// feed.id = 1
// feed.userid = 2
// feed.name = "Test"
// }
//
// describe("intial state") {
// it("has id") {
// expect(feed.id).to(beGreaterThanOrEqualTo(1))
// }
// it("has userid") {
// expect(feed.userid).to(beGreaterThanOrEqualTo(1))
// }
// it("has name") {
// expect(feed.name).to(equal("Test"))
// }
//
// }
it("can be encode and decoded") {
let json = JSON(["id":"101","userid":"202","name":"fred","datatype":"1","tag":"","public":"0","size":"12345","engine":"5","server":"1","time":"123","value":"123.456"])
let test = Feed(item: json)
NSKeyedArchiver.archiveRootObject(test, toFile: "/feed/data")
let y = NSKeyedUnarchiver.unarchiveObjectWithFile("/feed/data") as? Feed
print (y)
}
}
}
| 31cec87107d3bc5ac3e9803af2bf4772 | 26.8125 | 179 | 0.481648 | false | true | false | false |
Piwigo/Piwigo-Mobile | refs/heads/master | piwigoKit/Network/NetworkUtilities.swift | mit | 1 | //
// NetworkUtilities.swift
// piwigoKit
//
// Created by Eddy Lelièvre-Berna on 08/06/2021.
// Copyright © 2021 Piwigo.org. All rights reserved.
//
import Foundation
public class NetworkUtilities: NSObject {
// MARK: - UTF-8 encoding on 3 and 4 bytes
public class
func utf8mb4String(from string: String?) -> String {
// Return empty string if nothing provided
guard let strToConvert = string, strToConvert.isEmpty == false else {
return ""
}
// Convert string to UTF-8 encoding
let serverEncoding = String.Encoding(rawValue: NetworkVars.stringEncoding )
if let strData = strToConvert.data(using: serverEncoding, allowLossyConversion: true) {
return String(data: strData, encoding: .utf8) ?? strToConvert
}
return ""
}
// Piwigo supports the 3-byte UTF-8, not the standard UTF-8 (4 bytes)
// See https://github.com/Piwigo/Piwigo-Mobile/issues/429, https://github.com/Piwigo/Piwigo/issues/750
public class
func utf8mb3String(from string: String?) -> String {
// Return empty string is nothing provided
guard let strToFilter = string, strToFilter.isEmpty == false else {
return ""
}
// Replace characters encoded on 4 bytes
var utf8mb3String = ""
for char in strToFilter {
if char.utf8.count > 3 {
// 4-byte char => Not handled by Piwigo Server
utf8mb3String.append("\u{FFFD}") // Use the Unicode replacement character
} else {
// Up to 3-byte char
utf8mb3String.append(char)
}
}
return utf8mb3String
}
// MARK: - Clean URLs of Images
public class
func encodedImageURL(_ originalURL:String?) -> String? {
// Return nil if originalURL is nil and a placeholder will be used
guard let okURL = originalURL else { return nil }
// TEMPORARY PATCH for case where $conf['original_url_protection'] = 'images';
/// See https://github.com/Piwigo/Piwigo-Mobile/issues/503
var serverURL: NSURL? = NSURL(string: okURL.replacingOccurrences(of: "&part=", with: "&part="))
// Servers may return incorrect URLs
// See https://tools.ietf.org/html/rfc3986#section-2
if serverURL == nil {
// URL not RFC compliant!
var leftURL = okURL
// Remove protocol header
if okURL.hasPrefix("http://") { leftURL.removeFirst(7) }
if okURL.hasPrefix("https://") { leftURL.removeFirst(8) }
// Retrieve authority
guard let endAuthority = leftURL.firstIndex(of: "/") else {
// No path, incomplete URL —> return image.jpg but should never happen
return "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)/image.jpg"
}
let authority = String(leftURL.prefix(upTo: endAuthority))
leftURL.removeFirst(authority.count)
// The Piwigo server may not be in the root e.g. example.com/piwigo/…
// So we remove the path to avoid a duplicate if necessary
if let loginURL = URL(string: "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)"),
loginURL.path.count > 0, leftURL.hasPrefix(loginURL.path) {
leftURL.removeFirst(loginURL.path.count)
}
// Retrieve path
if let endQuery = leftURL.firstIndex(of: "?") {
// URL contains a query
let query = (String(leftURL.prefix(upTo: endQuery)) + "?").replacingOccurrences(of: "??", with: "?")
guard let newQuery = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
// Could not apply percent encoding —> return image.jpg but should never happen
return "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)/image.jpg"
}
leftURL.removeFirst(query.count)
guard let newPath = leftURL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
// Could not apply percent encoding —> return image.jpg but should never happen
return "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)/image.jpg"
}
serverURL = NSURL(string: "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)\(newQuery)\(newPath)")
} else {
// No query -> remaining string is a path
let newPath = String(leftURL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)
serverURL = NSURL(string: "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)\(newPath)")
}
// Last check
if serverURL == nil {
// Could not apply percent encoding —> return image.jpg but should never happen
return "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)/image.jpg"
}
}
// Servers may return image URLs different from those used to login (e.g. wrong server settings)
// We only keep the path+query because we only accept to download images from the same server.
guard var cleanPath = serverURL?.path else {
return "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)/image.jpg"
}
if let paramStr = serverURL?.parameterString {
cleanPath.append(paramStr)
}
if let query = serverURL?.query {
cleanPath.append("?" + query)
}
if let fragment = serverURL?.fragment {
cleanPath.append("#" + fragment)
}
// The Piwigo server may not be in the root e.g. example.com/piwigo/…
// So we remove the path to avoid a duplicate if necessary
if let loginURL = URL(string: "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)"),
loginURL.path.count > 0, cleanPath.hasPrefix(loginURL.path) {
cleanPath.removeFirst(loginURL.path.count)
}
// Remove the .php?, i? prefixes if any
var prefix = ""
if let pos = cleanPath.range(of: "?") {
// The path contains .php? or i?
prefix = String(cleanPath.prefix(upTo: pos.upperBound))
cleanPath.removeFirst(prefix.count)
}
// Path may not be encoded
if let decodedPath = cleanPath.removingPercentEncoding, cleanPath == decodedPath,
let test = cleanPath.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) {
cleanPath = test
}
// Compile final URL using the one provided at login
let encodedImageURL = "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)\(prefix)\(cleanPath)"
#if DEBUG
if encodedImageURL != originalURL {
print("=> originalURL:\(String(describing: originalURL))")
print(" encodedURL:\(encodedImageURL)")
print(" path=\(String(describing: serverURL?.path)), parameterString=\(String(describing: serverURL?.parameterString)), query:\(String(describing: serverURL?.query)), fragment:\(String(describing: serverURL?.fragment))")
}
#endif
return encodedImageURL;
}
}
// MARK: - RFC 3986 allowed characters
extension CharacterSet {
/// Creates a CharacterSet from RFC 3986 allowed characters.
///
/// https://datatracker.ietf.org/doc/html/rfc3986/#section-2.2
/// Section 2.2 states that the following characters are "reserved" characters.
///
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
///
/// https://datatracker.ietf.org/doc/html/rfc3986/#section-3.4
/// Section 3.4 states that the "?" and "/" characters should not be escaped to allow
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
/// should be percent-escaped in the query string.
///
public static let pwgURLQueryAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@"
let subDelimitersToEncode = "!$&'()*+,;="
let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters)
}()
}
| 5bb7d6efad916cebf039c6b602adf930 | 44.700535 | 235 | 0.604844 | false | false | false | false |
apple/swift-nio | refs/heads/main | Tests/NIOPosixTests/EventLoopFutureTest.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import Dispatch
@testable import NIOCore
import NIOEmbedded
import NIOPosix
enum EventLoopFutureTestError : Error {
case example
}
class EventLoopFutureTest : XCTestCase {
func testFutureFulfilledIfHasResult() throws {
let eventLoop = EmbeddedEventLoop()
let f = EventLoopFuture(eventLoop: eventLoop, value: 5)
XCTAssertTrue(f.isFulfilled)
}
func testFutureFulfilledIfHasError() throws {
let eventLoop = EmbeddedEventLoop()
let f = EventLoopFuture<Void>(eventLoop: eventLoop, error: EventLoopFutureTestError.example)
XCTAssertTrue(f.isFulfilled)
}
func testFoldWithMultipleEventLoops() throws {
let nThreads = 3
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: nThreads)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
}
let eventLoop0 = eventLoopGroup.next()
let eventLoop1 = eventLoopGroup.next()
let eventLoop2 = eventLoopGroup.next()
XCTAssert(eventLoop0 !== eventLoop1)
XCTAssert(eventLoop1 !== eventLoop2)
XCTAssert(eventLoop0 !== eventLoop2)
let f0: EventLoopFuture<[Int]> = eventLoop0.submit { [0] }
let f1s: [EventLoopFuture<Int>] = (1...4).map { id in eventLoop1.submit { id } }
let f2s: [EventLoopFuture<Int>] = (5...8).map { id in eventLoop2.submit { id } }
var fN = f0.fold(f1s) { (f1Value: [Int], f2Value: Int) -> EventLoopFuture<[Int]> in
XCTAssert(eventLoop0.inEventLoop)
return eventLoop1.makeSucceededFuture(f1Value + [f2Value])
}
fN = fN.fold(f2s) { (f1Value: [Int], f2Value: Int) -> EventLoopFuture<[Int]> in
XCTAssert(eventLoop0.inEventLoop)
return eventLoop2.makeSucceededFuture(f1Value + [f2Value])
}
let allValues = try fN.wait()
XCTAssert(fN.eventLoop === f0.eventLoop)
XCTAssert(fN.isFulfilled)
XCTAssertEqual(allValues, [0, 1, 2, 3, 4, 5, 6, 7, 8])
}
func testFoldWithSuccessAndAllSuccesses() throws {
let eventLoop = EmbeddedEventLoop()
let secondEventLoop = EmbeddedEventLoop()
let f0 = eventLoop.makeSucceededFuture([0])
let futures: [EventLoopFuture<Int>] = (1...5).map { (id: Int) in secondEventLoop.makeSucceededFuture(id) }
let fN = f0.fold(futures) { (f1Value: [Int], f2Value: Int) -> EventLoopFuture<[Int]> in
XCTAssert(eventLoop.inEventLoop)
return secondEventLoop.makeSucceededFuture(f1Value + [f2Value])
}
let allValues = try fN.wait()
XCTAssert(fN.eventLoop === f0.eventLoop)
XCTAssert(fN.isFulfilled)
XCTAssertEqual(allValues, [0, 1, 2, 3, 4, 5])
}
func testFoldWithSuccessAndOneFailure() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let secondEventLoop = EmbeddedEventLoop()
let f0: EventLoopFuture<Int> = eventLoop.makeSucceededFuture(0)
let promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in secondEventLoop.makePromise() }
var futures = promises.map { $0.futureResult }
let failedFuture: EventLoopFuture<Int> = secondEventLoop.makeFailedFuture(E())
futures.insert(failedFuture, at: futures.startIndex)
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return secondEventLoop.makeSucceededFuture(f1Value + f2Value)
}
_ = promises.map { $0.succeed(0) }
XCTAssert(fN.isFulfilled)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testFoldWithSuccessAndEmptyFutureList() throws {
let eventLoop = EmbeddedEventLoop()
let f0 = eventLoop.makeSucceededFuture(0)
let futures: [EventLoopFuture<Int>] = []
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return eventLoop.makeSucceededFuture(f1Value + f2Value)
}
let summationResult = try fN.wait()
XCTAssert(fN.isFulfilled)
XCTAssertEqual(summationResult, 0)
}
func testFoldWithFailureAndEmptyFutureList() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let f0: EventLoopFuture<Int> = eventLoop.makeFailedFuture(E())
let futures: [EventLoopFuture<Int>] = []
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return eventLoop.makeSucceededFuture(f1Value + f2Value)
}
XCTAssert(fN.isFulfilled)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testFoldWithFailureAndAllSuccesses() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let secondEventLoop = EmbeddedEventLoop()
let f0: EventLoopFuture<Int> = eventLoop.makeFailedFuture(E())
let promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in secondEventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return secondEventLoop.makeSucceededFuture(f1Value + f2Value)
}
_ = promises.map { $0.succeed(1) }
XCTAssert(fN.isFulfilled)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testFoldWithFailureAndAllUnfulfilled() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let secondEventLoop = EmbeddedEventLoop()
let f0: EventLoopFuture<Int> = eventLoop.makeFailedFuture(E())
let promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in secondEventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return secondEventLoop.makeSucceededFuture(f1Value + f2Value)
}
XCTAssert(fN.isFulfilled)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testFoldWithFailureAndAllFailures() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let secondEventLoop = EmbeddedEventLoop()
let f0: EventLoopFuture<Int> = eventLoop.makeFailedFuture(E())
let futures: [EventLoopFuture<Int>] = (0..<100).map { (_: Int) in secondEventLoop.makeFailedFuture(E()) }
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return secondEventLoop.makeSucceededFuture(f1Value + f2Value)
}
XCTAssert(fN.isFulfilled)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testAndAllWithEmptyFutureList() throws {
let eventLoop = EmbeddedEventLoop()
let futures: [EventLoopFuture<Void>] = []
let fN = EventLoopFuture.andAllSucceed(futures, on: eventLoop)
XCTAssert(fN.isFulfilled)
}
func testAndAllWithAllSuccesses() throws {
let eventLoop = EmbeddedEventLoop()
let promises: [EventLoopPromise<Void>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN = EventLoopFuture.andAllSucceed(futures, on: eventLoop)
_ = promises.map { $0.succeed(()) }
() = try fN.wait()
}
func testAndAllWithAllFailures() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let promises: [EventLoopPromise<Void>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN = EventLoopFuture.andAllSucceed(futures, on: eventLoop)
_ = promises.map { $0.fail(E()) }
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testAndAllWithOneFailure() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
var promises: [EventLoopPromise<Void>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
_ = promises.map { $0.succeed(()) }
let failedPromise = eventLoop.makePromise(of: Void.self)
failedPromise.fail(E())
promises.append(failedPromise)
let futures = promises.map { $0.futureResult }
let fN = EventLoopFuture.andAllSucceed(futures, on: eventLoop)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testReduceWithAllSuccesses() throws {
let eventLoop = EmbeddedEventLoop()
let promises: [EventLoopPromise<Int>] = (0..<5).map { (_: Int) in eventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN: EventLoopFuture<[Int]> = EventLoopFuture<[Int]>.reduce(into: [], futures, on: eventLoop) {
$0.append($1)
}
for i in 1...5 {
promises[i - 1].succeed((i))
}
let results = try fN.wait()
XCTAssertEqual(results, [1, 2, 3, 4, 5])
XCTAssert(fN.eventLoop === eventLoop)
}
func testReduceWithOnlyInitialValue() throws {
let eventLoop = EmbeddedEventLoop()
let futures: [EventLoopFuture<Int>] = []
let fN: EventLoopFuture<[Int]> = EventLoopFuture<[Int]>.reduce(into: [], futures, on: eventLoop) {
$0.append($1)
}
let results = try fN.wait()
XCTAssertEqual(results, [])
XCTAssert(fN.eventLoop === eventLoop)
}
func testReduceWithAllFailures() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN: EventLoopFuture<Int> = EventLoopFuture<Int>.reduce(0, futures, on: eventLoop, +)
_ = promises.map { $0.fail(E()) }
XCTAssert(fN.eventLoop === eventLoop)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testReduceWithOneFailure() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
var promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
_ = promises.map { $0.succeed((1)) }
let failedPromise = eventLoop.makePromise(of: Int.self)
failedPromise.fail(E())
promises.append(failedPromise)
let futures = promises.map { $0.futureResult }
let fN: EventLoopFuture<Int> = EventLoopFuture<Int>.reduce(0, futures, on: eventLoop, +)
XCTAssert(fN.eventLoop === eventLoop)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testReduceWhichDoesFailFast() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
var promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
let failedPromise = eventLoop.makePromise(of: Int.self)
promises.insert(failedPromise, at: promises.startIndex)
let futures = promises.map { $0.futureResult }
let fN: EventLoopFuture<Int> = EventLoopFuture<Int>.reduce(0, futures, on: eventLoop, +)
failedPromise.fail(E())
XCTAssertTrue(fN.isFulfilled)
XCTAssert(fN.eventLoop === eventLoop)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testReduceIntoWithAllSuccesses() throws {
let eventLoop = EmbeddedEventLoop()
let futures: [EventLoopFuture<Int>] = [1, 2, 2, 3, 3, 3].map { (id: Int) in eventLoop.makeSucceededFuture(id) }
let fN: EventLoopFuture<[Int: Int]> = EventLoopFuture<[Int: Int]>.reduce(into: [:], futures, on: eventLoop) { (freqs, elem) in
if let value = freqs[elem] {
freqs[elem] = value + 1
} else {
freqs[elem] = 1
}
}
let results = try fN.wait()
XCTAssertEqual(results, [1: 1, 2: 2, 3: 3])
XCTAssert(fN.eventLoop === eventLoop)
}
func testReduceIntoWithEmptyFutureList() throws {
let eventLoop = EmbeddedEventLoop()
let futures: [EventLoopFuture<Int>] = []
let fN: EventLoopFuture<[Int: Int]> = EventLoopFuture<[Int: Int]>.reduce(into: [:], futures, on: eventLoop) { (freqs, elem) in
if let value = freqs[elem] {
freqs[elem] = value + 1
} else {
freqs[elem] = 1
}
}
let results = try fN.wait()
XCTAssert(results.isEmpty)
XCTAssert(fN.eventLoop === eventLoop)
}
func testReduceIntoWithAllFailure() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let futures: [EventLoopFuture<Int>] = [1, 2, 2, 3, 3, 3].map { (id: Int) in eventLoop.makeFailedFuture(E()) }
let fN: EventLoopFuture<[Int: Int]> = EventLoopFuture<[Int: Int]>.reduce(into: [:], futures, on: eventLoop) { (freqs, elem) in
if let value = freqs[elem] {
freqs[elem] = value + 1
} else {
freqs[elem] = 1
}
}
XCTAssert(fN.isFulfilled)
XCTAssert(fN.eventLoop === eventLoop)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testReduceIntoWithMultipleEventLoops() throws {
let nThreads = 3
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: nThreads)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
}
let eventLoop0 = eventLoopGroup.next()
let eventLoop1 = eventLoopGroup.next()
let eventLoop2 = eventLoopGroup.next()
XCTAssert(eventLoop0 !== eventLoop1)
XCTAssert(eventLoop1 !== eventLoop2)
XCTAssert(eventLoop0 !== eventLoop2)
let f0: EventLoopFuture<[Int:Int]> = eventLoop0.submit { [:] }
let f1s: [EventLoopFuture<Int>] = (1...4).map { id in eventLoop1.submit { id / 2 } }
let f2s: [EventLoopFuture<Int>] = (5...8).map { id in eventLoop2.submit { id / 2 } }
let fN = EventLoopFuture<[Int:Int]>.reduce(into: [:], f1s + f2s, on: eventLoop0) { (freqs, elem) in
XCTAssert(eventLoop0.inEventLoop)
if let value = freqs[elem] {
freqs[elem] = value + 1
} else {
freqs[elem] = 1
}
}
let allValues = try fN.wait()
XCTAssert(fN.eventLoop === f0.eventLoop)
XCTAssert(fN.isFulfilled)
XCTAssertEqual(allValues, [0: 1, 1: 2, 2: 2, 3: 2, 4: 1])
}
func testThenThrowingWhichDoesNotThrow() {
let eventLoop = EmbeddedEventLoop()
var ran = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.map {
$0.count
}.flatMapThrowing {
1 + $0
}.whenSuccess {
ran = true
XCTAssertEqual($0, 6)
}
p.succeed("hello")
XCTAssertTrue(ran)
}
func testThenThrowingWhichDoesThrow() {
enum DummyError: Error, Equatable {
case dummyError
}
let eventLoop = EmbeddedEventLoop()
var ran = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.map {
$0.count
}.flatMapThrowing { (x: Int) throws -> Int in
XCTAssertEqual(5, x)
throw DummyError.dummyError
}.map { (x: Int) -> Int in
XCTFail("shouldn't have been called")
return x
}.whenFailure {
ran = true
XCTAssertEqual(.some(DummyError.dummyError), $0 as? DummyError)
}
p.succeed("hello")
XCTAssertTrue(ran)
}
func testflatMapErrorThrowingWhichDoesNotThrow() {
enum DummyError: Error, Equatable {
case dummyError
}
let eventLoop = EmbeddedEventLoop()
var ran = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.map {
$0.count
}.flatMapErrorThrowing {
XCTAssertEqual(.some(DummyError.dummyError), $0 as? DummyError)
return 5
}.flatMapErrorThrowing { (_: Error) in
XCTFail("shouldn't have been called")
return 5
}.whenSuccess {
ran = true
XCTAssertEqual($0, 5)
}
p.fail(DummyError.dummyError)
XCTAssertTrue(ran)
}
func testflatMapErrorThrowingWhichDoesThrow() {
enum DummyError: Error, Equatable {
case dummyError1
case dummyError2
}
let eventLoop = EmbeddedEventLoop()
var ran = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.map {
$0.count
}.flatMapErrorThrowing { (x: Error) throws -> Int in
XCTAssertEqual(.some(DummyError.dummyError1), x as? DummyError)
throw DummyError.dummyError2
}.map { (x: Int) -> Int in
XCTFail("shouldn't have been called")
return x
}.whenFailure {
ran = true
XCTAssertEqual(.some(DummyError.dummyError2), $0 as? DummyError)
}
p.fail(DummyError.dummyError1)
XCTAssertTrue(ran)
}
func testOrderOfFutureCompletion() throws {
let eventLoop = EmbeddedEventLoop()
var state = 0
let p: EventLoopPromise<Void> = EventLoopPromise(eventLoop: eventLoop, file: #filePath, line: #line)
p.futureResult.map {
XCTAssertEqual(state, 0)
state += 1
}.map {
XCTAssertEqual(state, 1)
state += 1
}.whenSuccess {
XCTAssertEqual(state, 2)
state += 1
}
p.succeed(())
XCTAssertTrue(p.futureResult.isFulfilled)
XCTAssertEqual(state, 3)
}
func testEventLoopHoppingInThen() throws {
let n = 20
let elg = MultiThreadedEventLoopGroup(numberOfThreads: n)
var prev: EventLoopFuture<Int> = elg.next().makeSucceededFuture(0)
(1..<20).forEach { (i: Int) in
let p = elg.next().makePromise(of: Int.self)
prev.flatMap { (i2: Int) -> EventLoopFuture<Int> in
XCTAssertEqual(i - 1, i2)
p.succeed(i)
return p.futureResult
}.whenSuccess { i2 in
XCTAssertEqual(i, i2)
}
prev = p.futureResult
}
XCTAssertEqual(n-1, try prev.wait())
XCTAssertNoThrow(try elg.syncShutdownGracefully())
}
func testEventLoopHoppingInThenWithFailures() throws {
enum DummyError: Error {
case dummy
}
let n = 20
let elg = MultiThreadedEventLoopGroup(numberOfThreads: n)
var prev: EventLoopFuture<Int> = elg.next().makeSucceededFuture(0)
(1..<n).forEach { (i: Int) in
let p = elg.next().makePromise(of: Int.self)
prev.flatMap { (i2: Int) -> EventLoopFuture<Int> in
XCTAssertEqual(i - 1, i2)
if i == n/2 {
p.fail(DummyError.dummy)
} else {
p.succeed(i)
}
return p.futureResult
}.flatMapError { error in
p.fail(error)
return p.futureResult
}.whenSuccess { i2 in
XCTAssertEqual(i, i2)
}
prev = p.futureResult
}
XCTAssertThrowsError(try prev.wait()) { error in
XCTAssertNotNil(error as? DummyError)
}
XCTAssertNoThrow(try elg.syncShutdownGracefully())
}
func testEventLoopHoppingAndAll() throws {
let n = 20
let elg = MultiThreadedEventLoopGroup(numberOfThreads: n)
let ps = (0..<n).map { (_: Int) -> EventLoopPromise<Void> in
elg.next().makePromise()
}
let allOfEm = EventLoopFuture.andAllSucceed(ps.map { $0.futureResult }, on: elg.next())
ps.reversed().forEach { p in
DispatchQueue.global().async {
p.succeed(())
}
}
try allOfEm.wait()
XCTAssertNoThrow(try elg.syncShutdownGracefully())
}
func testEventLoopHoppingAndAllWithFailures() throws {
enum DummyError: Error { case dummy }
let n = 20
let fireBackEl = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let elg = MultiThreadedEventLoopGroup(numberOfThreads: n)
let ps = (0..<n).map { (_: Int) -> EventLoopPromise<Void> in
elg.next().makePromise()
}
let allOfEm = EventLoopFuture.andAllSucceed(ps.map { $0.futureResult }, on: fireBackEl.next())
ps.reversed().enumerated().forEach { idx, p in
DispatchQueue.global().async {
if idx == n / 2 {
p.fail(DummyError.dummy)
} else {
p.succeed(())
}
}
}
XCTAssertThrowsError(try allOfEm.wait()) { error in
XCTAssertNotNil(error as? DummyError)
}
XCTAssertNoThrow(try elg.syncShutdownGracefully())
XCTAssertNoThrow(try fireBackEl.syncShutdownGracefully())
}
func testFutureInVariousScenarios() throws {
enum DummyError: Error { case dummy0; case dummy1 }
let elg = MultiThreadedEventLoopGroup(numberOfThreads: 2)
let el1 = elg.next()
let el2 = elg.next()
precondition(el1 !== el2)
let q1 = DispatchQueue(label: "q1")
let q2 = DispatchQueue(label: "q2")
// this determines which promise is fulfilled first (and (true, true) meaning they race)
for whoGoesFirst in [(false, true), (true, false), (true, true)] {
// this determines what EventLoops the Promises are created on
for eventLoops in [(el1, el1), (el1, el2), (el2, el1), (el2, el2)] {
// this determines if the promises fail or succeed
for whoSucceeds in [(false, false), (false, true), (true, false), (true, true)] {
let p0 = eventLoops.0.makePromise(of: Int.self)
let p1 = eventLoops.1.makePromise(of: String.self)
let fAll = p0.futureResult.and(p1.futureResult)
// preheat both queues so we have a better chance of racing
let sem1 = DispatchSemaphore(value: 0)
let sem2 = DispatchSemaphore(value: 0)
let g = DispatchGroup()
q1.async(group: g) {
sem2.signal()
sem1.wait()
}
q2.async(group: g) {
sem1.signal()
sem2.wait()
}
g.wait()
if whoGoesFirst.0 {
q1.async {
if whoSucceeds.0 {
p0.succeed(7)
} else {
p0.fail(DummyError.dummy0)
}
if !whoGoesFirst.1 {
q2.asyncAfter(deadline: .now() + 0.1) {
if whoSucceeds.1 {
p1.succeed("hello")
} else {
p1.fail(DummyError.dummy1)
}
}
}
}
}
if whoGoesFirst.1 {
q2.async {
if whoSucceeds.1 {
p1.succeed("hello")
} else {
p1.fail(DummyError.dummy1)
}
if !whoGoesFirst.0 {
q1.asyncAfter(deadline: .now() + 0.1) {
if whoSucceeds.0 {
p0.succeed(7)
} else {
p0.fail(DummyError.dummy0)
}
}
}
}
}
do {
let result = try fAll.wait()
if !whoSucceeds.0 || !whoSucceeds.1 {
XCTFail("unexpected success")
} else {
XCTAssert((7, "hello") == result)
}
} catch let e as DummyError {
switch e {
case .dummy0:
XCTAssertFalse(whoSucceeds.0)
case .dummy1:
XCTAssertFalse(whoSucceeds.1)
}
} catch {
XCTFail("unexpected error: \(error)")
}
}
}
}
XCTAssertNoThrow(try elg.syncShutdownGracefully())
}
func testLoopHoppingHelperSuccess() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let loop1 = group.next()
let loop2 = group.next()
XCTAssertFalse(loop1 === loop2)
let succeedingPromise = loop1.makePromise(of: Void.self)
let succeedingFuture = succeedingPromise.futureResult.map {
XCTAssertTrue(loop1.inEventLoop)
}.hop(to: loop2).map {
XCTAssertTrue(loop2.inEventLoop)
}
succeedingPromise.succeed(())
XCTAssertNoThrow(try succeedingFuture.wait())
}
func testLoopHoppingHelperFailure() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let loop1 = group.next()
let loop2 = group.next()
XCTAssertFalse(loop1 === loop2)
let failingPromise = loop2.makePromise(of: Void.self)
let failingFuture = failingPromise.futureResult.flatMapErrorThrowing { error in
XCTAssertEqual(error as? EventLoopFutureTestError, EventLoopFutureTestError.example)
XCTAssertTrue(loop2.inEventLoop)
throw error
}.hop(to: loop1).recover { error in
XCTAssertEqual(error as? EventLoopFutureTestError, EventLoopFutureTestError.example)
XCTAssertTrue(loop1.inEventLoop)
}
failingPromise.fail(EventLoopFutureTestError.example)
XCTAssertNoThrow(try failingFuture.wait())
}
func testLoopHoppingHelperNoHopping() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let loop1 = group.next()
let loop2 = group.next()
XCTAssertFalse(loop1 === loop2)
let noHoppingPromise = loop1.makePromise(of: Void.self)
let noHoppingFuture = noHoppingPromise.futureResult.hop(to: loop1)
XCTAssertTrue(noHoppingFuture === noHoppingPromise.futureResult)
noHoppingPromise.succeed(())
}
func testFlatMapResultHappyPath() {
let el = EmbeddedEventLoop()
defer {
XCTAssertNoThrow(try el.syncShutdownGracefully())
}
let p = el.makePromise(of: Int.self)
let f = p.futureResult.flatMapResult { (_: Int) in
return Result<String, Never>.success("hello world")
}
p.succeed(1)
XCTAssertNoThrow(XCTAssertEqual("hello world", try f.wait()))
}
func testFlatMapResultFailurePath() {
struct DummyError: Error {}
let el = EmbeddedEventLoop()
defer {
XCTAssertNoThrow(try el.syncShutdownGracefully())
}
let p = el.makePromise(of: Int.self)
let f = p.futureResult.flatMapResult { (_: Int) in
return Result<Int, Error>.failure(DummyError())
}
p.succeed(1)
XCTAssertThrowsError(try f.wait()) { error in
XCTAssert(type(of: error) == DummyError.self)
}
}
func testWhenAllSucceedFailsImmediately() {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Int]>?) {
let promises = [group.next().makePromise(of: Int.self),
group.next().makePromise(of: Int.self)]
let futures = promises.map { $0.futureResult }
let futureResult: EventLoopFuture<[Int]>
if let promise = promise {
futureResult = promise.futureResult
EventLoopFuture.whenAllSucceed(futures, promise: promise)
} else {
futureResult = EventLoopFuture.whenAllSucceed(futures, on: group.next())
}
promises[0].fail(EventLoopFutureTestError.example)
XCTAssertThrowsError(try futureResult.wait()) { error in
XCTAssert(type(of: error) == EventLoopFutureTestError.self)
}
}
doTest(promise: nil)
doTest(promise: group.next().makePromise())
}
func testWhenAllSucceedResolvesAfterFutures() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 6)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Int]>?) throws {
let promises = (0..<5).map { _ in group.next().makePromise(of: Int.self) }
let futures = promises.map { $0.futureResult }
var succeeded = false
var completedPromises = false
let mainFuture: EventLoopFuture<[Int]>
if let promise = promise {
mainFuture = promise.futureResult
EventLoopFuture.whenAllSucceed(futures, promise: promise)
} else {
mainFuture = EventLoopFuture.whenAllSucceed(futures, on: group.next())
}
mainFuture.whenSuccess { _ in
XCTAssertTrue(completedPromises)
XCTAssertFalse(succeeded)
succeeded = true
}
// Should be false, as none of the promises have completed yet
XCTAssertFalse(succeeded)
// complete the first four promises
for (index, promise) in promises.dropLast().enumerated() {
promise.succeed(index)
}
// Should still be false, as one promise hasn't completed yet
XCTAssertFalse(succeeded)
// Complete the last promise
completedPromises = true
promises.last!.succeed(4)
let results = try assertNoThrowWithValue(mainFuture.wait())
XCTAssertEqual(results, [0, 1, 2, 3, 4])
}
XCTAssertNoThrow(try doTest(promise: nil))
XCTAssertNoThrow(try doTest(promise: group.next().makePromise()))
}
func testWhenAllSucceedIsIndependentOfFulfillmentOrder() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 6)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Int]>?) throws {
let expected = Array(0..<1000)
let promises = expected.map { _ in group.next().makePromise(of: Int.self) }
let futures = promises.map { $0.futureResult }
var succeeded = false
var completedPromises = false
let mainFuture: EventLoopFuture<[Int]>
if let promise = promise {
mainFuture = promise.futureResult
EventLoopFuture.whenAllSucceed(futures, promise: promise)
} else {
mainFuture = EventLoopFuture.whenAllSucceed(futures, on: group.next())
}
mainFuture.whenSuccess { _ in
XCTAssertTrue(completedPromises)
XCTAssertFalse(succeeded)
succeeded = true
}
for index in expected.reversed() {
if index == 0 {
completedPromises = true
}
promises[index].succeed(index)
}
let results = try assertNoThrowWithValue(mainFuture.wait())
XCTAssertEqual(results, expected)
}
XCTAssertNoThrow(try doTest(promise: nil))
XCTAssertNoThrow(try doTest(promise: group.next().makePromise()))
}
func testWhenAllCompleteResultsWithFailuresStillSucceed() {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Result<Bool, Error>]>?) {
let futures: [EventLoopFuture<Bool>] = [
group.next().makeFailedFuture(EventLoopFutureTestError.example),
group.next().makeSucceededFuture(true)
]
let future: EventLoopFuture<[Result<Bool, Error>]>
if let promise = promise {
future = promise.futureResult
EventLoopFuture.whenAllComplete(futures, promise: promise)
} else {
future = EventLoopFuture.whenAllComplete(futures, on: group.next())
}
XCTAssertNoThrow(try future.wait())
}
doTest(promise: nil)
doTest(promise: group.next().makePromise())
}
func testWhenAllCompleteResults() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Result<Int, Error>]>?) throws {
let futures: [EventLoopFuture<Int>] = [
group.next().makeSucceededFuture(3),
group.next().makeFailedFuture(EventLoopFutureTestError.example),
group.next().makeSucceededFuture(10),
group.next().makeFailedFuture(EventLoopFutureTestError.example),
group.next().makeSucceededFuture(5)
]
let future: EventLoopFuture<[Result<Int, Error>]>
if let promise = promise {
future = promise.futureResult
EventLoopFuture.whenAllComplete(futures, promise: promise)
} else {
future = EventLoopFuture.whenAllComplete(futures, on: group.next())
}
let results = try assertNoThrowWithValue(future.wait())
XCTAssertEqual(try results[0].get(), 3)
XCTAssertThrowsError(try results[1].get())
XCTAssertEqual(try results[2].get(), 10)
XCTAssertThrowsError(try results[3].get())
XCTAssertEqual(try results[4].get(), 5)
}
XCTAssertNoThrow(try doTest(promise: nil))
XCTAssertNoThrow(try doTest(promise: group.next().makePromise()))
}
func testWhenAllCompleteResolvesAfterFutures() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 6)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Result<Int, Error>]>?) throws {
let promises = (0..<5).map { _ in group.next().makePromise(of: Int.self) }
let futures = promises.map { $0.futureResult }
var succeeded = false
var completedPromises = false
let mainFuture: EventLoopFuture<[Result<Int, Error>]>
if let promise = promise {
mainFuture = promise.futureResult
EventLoopFuture.whenAllComplete(futures, promise: promise)
} else {
mainFuture = EventLoopFuture.whenAllComplete(futures, on: group.next())
}
mainFuture.whenSuccess { _ in
XCTAssertTrue(completedPromises)
XCTAssertFalse(succeeded)
succeeded = true
}
// Should be false, as none of the promises have completed yet
XCTAssertFalse(succeeded)
// complete the first four promises
for (index, promise) in promises.dropLast().enumerated() {
promise.succeed(index)
}
// Should still be false, as one promise hasn't completed yet
XCTAssertFalse(succeeded)
// Complete the last promise
completedPromises = true
promises.last!.succeed(4)
let results = try assertNoThrowWithValue(mainFuture.wait().map { try $0.get() })
XCTAssertEqual(results, [0, 1, 2, 3, 4])
}
XCTAssertNoThrow(try doTest(promise: nil))
XCTAssertNoThrow(try doTest(promise: group.next().makePromise()))
}
struct DatabaseError: Error {}
struct Database {
let query: () -> EventLoopFuture<[String]>
var closed = false
init(query: @escaping () -> EventLoopFuture<[String]>) {
self.query = query
}
func runQuery() -> EventLoopFuture<[String]> {
return query()
}
mutating func close() {
self.closed = true
}
}
func testAlways() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
var db = Database { loop.makeSucceededFuture(["Item 1", "Item 2", "Item 3"]) }
XCTAssertFalse(db.closed)
let _ = try assertNoThrowWithValue(db.runQuery().always { result in
assertSuccess(result)
db.close()
}.map { $0.map { $0.uppercased() }}.wait())
XCTAssertTrue(db.closed)
}
func testAlwaysWithFailingPromise() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
var db = Database { loop.makeFailedFuture(DatabaseError()) }
XCTAssertFalse(db.closed)
let _ = try XCTAssertThrowsError(db.runQuery().always { result in
assertFailure(result)
db.close()
}.map { $0.map { $0.uppercased() }}.wait()) { XCTAssertTrue($0 is DatabaseError) }
XCTAssertTrue(db.closed)
}
func testPromiseCompletedWithSuccessfulFuture() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
let future = loop.makeSucceededFuture("yay")
let promise = loop.makePromise(of: String.self)
promise.completeWith(future)
XCTAssertEqual(try promise.futureResult.wait(), "yay")
}
func testPromiseCompletedWithFailedFuture() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
let future: EventLoopFuture<EventLoopFutureTestError> = loop.makeFailedFuture(EventLoopFutureTestError.example)
let promise = loop.makePromise(of: EventLoopFutureTestError.self)
promise.completeWith(future)
XCTAssertThrowsError(try promise.futureResult.wait()) { error in
XCTAssert(type(of: error) == EventLoopFutureTestError.self)
}
}
func testPromiseCompletedWithSuccessfulResult() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
let promise = loop.makePromise(of: Void.self)
let result: Result<Void, Error> = .success(())
promise.completeWith(result)
XCTAssertNoThrow(try promise.futureResult.wait())
}
func testPromiseCompletedWithFailedResult() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
let promise = loop.makePromise(of: Void.self)
let result: Result<Void, Error> = .failure(EventLoopFutureTestError.example)
promise.completeWith(result)
XCTAssertThrowsError(try promise.futureResult.wait()) { error in
XCTAssert(type(of: error) == EventLoopFutureTestError.self)
}
}
func testAndAllCompleteWithZeroFutures() {
let eventLoop = EmbeddedEventLoop()
let done = DispatchWorkItem {}
EventLoopFuture<Void>.andAllComplete([], on: eventLoop).whenComplete { (result: Result<Void, Error>) in
_ = result.mapError { error -> Error in
XCTFail("unexpected error \(error)")
return error
}
done.perform()
}
done.wait()
}
func testAndAllSucceedWithZeroFutures() {
let eventLoop = EmbeddedEventLoop()
let done = DispatchWorkItem {}
EventLoopFuture<Void>.andAllSucceed([], on: eventLoop).whenComplete { result in
_ = result.mapError { error -> Error in
XCTFail("unexpected error \(error)")
return error
}
done.perform()
}
done.wait()
}
func testAndAllCompleteWithPreSucceededFutures() {
let eventLoop = EmbeddedEventLoop()
let succeeded = eventLoop.makeSucceededFuture(())
for i in 0..<10 {
XCTAssertNoThrow(try EventLoopFuture<Void>.andAllComplete(Array(repeating: succeeded, count: i),
on: eventLoop).wait())
}
}
func testAndAllCompleteWithPreFailedFutures() {
struct Dummy: Error {}
let eventLoop = EmbeddedEventLoop()
let failed: EventLoopFuture<Void> = eventLoop.makeFailedFuture(Dummy())
for i in 0..<10 {
XCTAssertNoThrow(try EventLoopFuture<Void>.andAllComplete(Array(repeating: failed, count: i),
on: eventLoop).wait())
}
}
func testAndAllCompleteWithMixOfPreSuccededAndNotYetCompletedFutures() {
struct Dummy: Error {}
let eventLoop = EmbeddedEventLoop()
let succeeded = eventLoop.makeSucceededFuture(())
let incompletes = [eventLoop.makePromise(of: Void.self), eventLoop.makePromise(of: Void.self),
eventLoop.makePromise(of: Void.self), eventLoop.makePromise(of: Void.self),
eventLoop.makePromise(of: Void.self)]
var futures: [EventLoopFuture<Void>] = []
for i in 0..<10 {
if i % 2 == 0 {
futures.append(succeeded)
} else {
futures.append(incompletes[i/2].futureResult)
}
}
let overall = EventLoopFuture<Void>.andAllComplete(futures, on: eventLoop)
XCTAssertFalse(overall.isFulfilled)
for (idx, incomplete) in incompletes.enumerated() {
XCTAssertFalse(overall.isFulfilled)
if idx % 2 == 0 {
incomplete.succeed(())
} else {
incomplete.fail(Dummy())
}
}
XCTAssertNoThrow(try overall.wait())
}
func testWhenAllCompleteWithMixOfPreSuccededAndNotYetCompletedFutures() {
struct Dummy: Error {}
let eventLoop = EmbeddedEventLoop()
let succeeded = eventLoop.makeSucceededFuture(())
let incompletes = [eventLoop.makePromise(of: Void.self), eventLoop.makePromise(of: Void.self),
eventLoop.makePromise(of: Void.self), eventLoop.makePromise(of: Void.self),
eventLoop.makePromise(of: Void.self)]
var futures: [EventLoopFuture<Void>] = []
for i in 0..<10 {
if i % 2 == 0 {
futures.append(succeeded)
} else {
futures.append(incompletes[i/2].futureResult)
}
}
let overall = EventLoopFuture<Void>.whenAllComplete(futures, on: eventLoop)
XCTAssertFalse(overall.isFulfilled)
for (idx, incomplete) in incompletes.enumerated() {
XCTAssertFalse(overall.isFulfilled)
if idx % 2 == 0 {
incomplete.succeed(())
} else {
incomplete.fail(Dummy())
}
}
let expected: [Result<Void, Error>] = [.success(()), .success(()),
.success(()), .failure(Dummy()),
.success(()), .success(()),
.success(()), .failure(Dummy()),
.success(()), .success(())]
func assertIsEqual(_ expecteds: [Result<Void, Error>], _ actuals: [Result<Void, Error>]) {
XCTAssertEqual(expecteds.count, actuals.count, "counts not equal")
for i in expecteds.indices {
let expected = expecteds[i]
let actual = actuals[i]
switch (expected, actual) {
case (.success(()), .success(())):
()
case (.failure(let le), .failure(let re)):
XCTAssert(le is Dummy)
XCTAssert(re is Dummy)
default:
XCTFail("\(expecteds) and \(actuals) not equal")
}
}
}
XCTAssertNoThrow(assertIsEqual(expected, try overall.wait()))
}
func testRepeatedTaskOffEventLoopGroupFuture() throws {
let elg1: EventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try elg1.syncShutdownGracefully())
}
let elg2: EventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try elg2.syncShutdownGracefully())
}
let exitPromise: EventLoopPromise<Void> = elg1.next().makePromise()
var callNumber = 0
_ = elg1.next().scheduleRepeatedAsyncTask(initialDelay: .nanoseconds(0), delay: .nanoseconds(0)) { task in
struct Dummy: Error {}
callNumber += 1
switch callNumber {
case 1:
return elg2.next().makeSucceededFuture(())
case 2:
task.cancel(promise: exitPromise)
return elg2.next().makeFailedFuture(Dummy())
default:
XCTFail("shouldn't be called \(callNumber)")
return elg2.next().makeFailedFuture(Dummy())
}
}
try exitPromise.futureResult.wait()
}
func testEventLoopFutureOrErrorNoThrow() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(42)
promise.completeWith(result)
XCTAssertEqual(try promise.futureResult.unwrap(orError: EventLoopFutureTestError.example).wait(), 42)
}
func testEventLoopFutureOrThrows() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(nil)
promise.completeWith(result)
XCTAssertThrowsError(try _ = promise.futureResult.unwrap(orError: EventLoopFutureTestError.example).wait()) { (error) -> Void in
XCTAssertEqual(error as! EventLoopFutureTestError, EventLoopFutureTestError.example)
}
}
func testEventLoopFutureOrNoReplacement() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(42)
promise.completeWith(result)
XCTAssertEqual(try! promise.futureResult.unwrap(orReplace: 41).wait(), 42)
}
func testEventLoopFutureOrReplacement() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(nil)
promise.completeWith(result)
XCTAssertEqual(try! promise.futureResult.unwrap(orReplace: 42).wait(), 42)
}
func testEventLoopFutureOrNoElse() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(42)
promise.completeWith(result)
XCTAssertEqual(try! promise.futureResult.unwrap(orElse: { 41 } ).wait(), 42)
}
func testEventLoopFutureOrElse() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(4)
promise.completeWith(result)
let x = 2
XCTAssertEqual(try! promise.futureResult.unwrap(orElse: { x * 2 } ).wait(), 4)
}
func testFlatBlockingMapOnto() {
let eventLoop = EmbeddedEventLoop()
let p = eventLoop.makePromise(of: String.self)
let sem = DispatchSemaphore(value: 0)
var blockingRan = false
var nonBlockingRan = false
p.futureResult.map {
$0.count
}.flatMapBlocking(onto: DispatchQueue.global()) { value -> Int in
sem.wait() // Block in chained EventLoopFuture
blockingRan = true
return 1 + value
}.whenSuccess {
XCTAssertEqual($0, 6)
XCTAssertTrue(blockingRan)
XCTAssertTrue(nonBlockingRan)
}
p.succeed("hello")
let p2 = eventLoop.makePromise(of: Bool.self)
p2.futureResult.whenSuccess { _ in
nonBlockingRan = true
}
p2.succeed(true)
sem.signal()
}
func testWhenSuccessBlocking() {
let eventLoop = EmbeddedEventLoop()
let sem = DispatchSemaphore(value: 0)
var nonBlockingRan = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.whenSuccessBlocking(onto: DispatchQueue.global()) {
sem.wait() // Block in callback
XCTAssertEqual($0, "hello")
XCTAssertTrue(nonBlockingRan)
}
p.succeed("hello")
let p2 = eventLoop.makePromise(of: Bool.self)
p2.futureResult.whenSuccess { _ in
nonBlockingRan = true
}
p2.succeed(true)
sem.signal()
}
func testWhenFailureBlocking() {
let eventLoop = EmbeddedEventLoop()
let sem = DispatchSemaphore(value: 0)
var nonBlockingRan = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.whenFailureBlocking (onto: DispatchQueue.global()) { err in
sem.wait() // Block in callback
XCTAssertEqual(err as! EventLoopFutureTestError, EventLoopFutureTestError.example)
XCTAssertTrue(nonBlockingRan)
}
p.fail(EventLoopFutureTestError.example)
let p2 = eventLoop.makePromise(of: Bool.self)
p2.futureResult.whenSuccess { _ in
nonBlockingRan = true
}
p2.succeed(true)
sem.signal()
}
func testWhenCompleteBlockingSuccess() {
let eventLoop = EmbeddedEventLoop()
let sem = DispatchSemaphore(value: 0)
var nonBlockingRan = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.whenCompleteBlocking (onto: DispatchQueue.global()) { _ in
sem.wait() // Block in callback
XCTAssertTrue(nonBlockingRan)
}
p.succeed("hello")
let p2 = eventLoop.makePromise(of: Bool.self)
p2.futureResult.whenSuccess { _ in
nonBlockingRan = true
}
p2.succeed(true)
sem.signal()
}
func testWhenCompleteBlockingFailure() {
let eventLoop = EmbeddedEventLoop()
let sem = DispatchSemaphore(value: 0)
var nonBlockingRan = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.whenCompleteBlocking (onto: DispatchQueue.global()) { _ in
sem.wait() // Block in callback
XCTAssertTrue(nonBlockingRan)
}
p.fail(EventLoopFutureTestError.example)
let p2 = eventLoop.makePromise(of: Bool.self)
p2.futureResult.whenSuccess { _ in
nonBlockingRan = true
}
p2.succeed(true)
sem.signal()
}
func testFlatMapWithEL() {
let el = EmbeddedEventLoop()
XCTAssertEqual(2,
try el.makeSucceededFuture(1).flatMapWithEventLoop { one, el2 in
XCTAssert(el === el2)
return el2.makeSucceededFuture(one + 1)
}.wait())
}
func testFlatMapErrorWithEL() {
let el = EmbeddedEventLoop()
struct E: Error {}
XCTAssertEqual(1,
try el.makeFailedFuture(E()).flatMapErrorWithEventLoop { error, el2 in
XCTAssert(error is E)
return el2.makeSucceededFuture(1)
}.wait())
}
func testFoldWithEL() {
let el = EmbeddedEventLoop()
let futures = (1...10).map { el.makeSucceededFuture($0) }
var calls = 0
let all = el.makeSucceededFuture(0).foldWithEventLoop(futures) { l, r, el2 in
calls += 1
XCTAssert(el === el2)
XCTAssertEqual(calls, r)
return el2.makeSucceededFuture(l + r)
}
XCTAssertEqual((1...10).reduce(0, +), try all.wait())
}
}
| 86841dc9c034ea629727a15f002131af | 35.594396 | 136 | 0.570212 | false | true | false | false |
valitovaza/IntervalReminder | refs/heads/master | IntervalReminderTests/AppDelegateTests.swift | mit | 1 | import XCTest
@testable import IntervalReminder
class AppDelegateTests: XCTestCase {
// MARK: - Test variables
private var sut: AppDelegate!
// MARK: - Set up and tear down
override func setUp() {
super.setUp()
sut = AppDelegate()
}
override func tearDown() {
sut = nil
super.tearDown()
}
// MARK: - Tests
func testHasConfigurator() {
XCTAssertNotNil(sut.configurator)
}
func testTheAppWasConfiguredInApplicationDidFinishLaunching() {
let mock = MockConfigurator()
sut.configurator = mock
sut.applicationDidFinishLaunching(Notification(name: NSNotification.Name.NSApplicationDidFinishLaunching))
XCTAssertTrue(mock.configureWasInvoked)
}
}
extension AppDelegateTests {
class MockConfigurator: Configurator{
var configureWasInvoked = false
func configure() {
configureWasInvoked = true
}
}
}
| 288bc53f7e712d5dfd914fc2fd88034e | 26.571429 | 114 | 0.65285 | false | true | false | false |
ivygulch/IVGRouter | refs/heads/master | IVGRouterTests/tests/router/RouterHistorySpec.swift | mit | 1 | //
// RouterHistorySpec.swift
// IVGRouter
//
// Created by Douglas Sjoquist on 7/24/16.
// Copyright © 2016 Ivy Gulch LLC. All rights reserved.
//
import UIKit
import Quick
import Nimble
@testable import IVGRouter
class RouterHistorySpec: QuickSpec {
override func spec() {
describe("Router") {
let mockRouteHistoryItemA = RouteHistoryItem(routeSequence: RouteSequence(source: ["A"]), title: "title A")
let mockRouteHistoryItemB = RouteHistoryItem(routeSequence: RouteSequence(source: ["B"]), title: "title B")
let mockRouteHistoryItemC = RouteHistoryItem(routeSequence: RouteSequence(source: ["C"]), title: "title C")
let mockRouteHistoryItemD = RouteHistoryItem(routeSequence: RouteSequence(source: ["D"]), title: "title D")
let mockRouteHistoryItemE = RouteHistoryItem(routeSequence: RouteSequence(source: ["E"]), title: "title E")
var routerHistory: RouterHistory!
beforeEach {
routerHistory = RouterHistory(historySize: 10)
}
context("when initialized") {
it("should return nil for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem).to(beNil())
}
}
context("after moving forward one step") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
}
it("should return nil for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem).to(beNil())
}
}
context("after moving forward two steps") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemB, ignoreDuplicates: false)
}
it("should return A for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem as? RouteHistoryItem).to(equal(mockRouteHistoryItemA))
}
}
context("after moving forward two steps, then back one") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemB, ignoreDuplicates: false)
routerHistory.moveBackward()
}
it("should return nil for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem).to(beNil())
}
}
context("after moving forward three steps, then back one") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemB, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemC, ignoreDuplicates: false)
routerHistory.moveBackward()
}
it("should return A for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem as? RouteHistoryItem).to(equal(mockRouteHistoryItemA))
}
}
context("after moving forward four steps, then back two, then forward with same as before") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemB, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemC, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemD, ignoreDuplicates: false)
routerHistory.moveBackward()
routerHistory.moveBackward()
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemC, ignoreDuplicates: false)
}
it("should return B for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem as? RouteHistoryItem).to(equal(mockRouteHistoryItemB))
}
}
context("after moving forward four steps, then back two, then forward with different from before") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemB, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemC, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemD, ignoreDuplicates: false)
routerHistory.moveBackward()
routerHistory.moveBackward()
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemE, ignoreDuplicates: false)
}
it("should return B for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem as? RouteHistoryItem).to(equal(mockRouteHistoryItemB))
}
}
}
}
}
| 07775f395aaafe89fd6efa38693b0778 | 40.886364 | 120 | 0.623802 | false | false | false | false |
wireapp/wire-ios-data-model | refs/heads/develop | Source/Utilis/CryptoBox.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireCryptobox
extension NSManagedObjectContext {
fileprivate static let ZMUserClientKeysStoreKey = "ZMUserClientKeysStore"
@objc(setupUserKeyStoreInAccountDirectory:applicationContainer:)
public func setupUserKeyStore(accountDirectory: URL, applicationContainer: URL) {
if !self.zm_isSyncContext {
fatal("Can't initiliazie crypto box on non-sync context")
}
let newKeyStore = UserClientKeysStore(accountDirectory: accountDirectory, applicationContainer: applicationContainer)
self.userInfo[NSManagedObjectContext.ZMUserClientKeysStoreKey] = newKeyStore
}
/// Returns the cryptobox instance associated with this managed object context
@objc public var zm_cryptKeyStore: UserClientKeysStore! {
if !self.zm_isSyncContext {
fatal("Can't access key store: Currently not on sync context")
}
let keyStore = self.userInfo.object(forKey: NSManagedObjectContext.ZMUserClientKeysStoreKey)
if let keyStore = keyStore as? UserClientKeysStore {
return keyStore
} else {
fatal("Can't access key store: not keystore found.")
}
}
@objc public func zm_tearDownCryptKeyStore() {
self.userInfo.removeObject(forKey: NSManagedObjectContext.ZMUserClientKeysStoreKey)
}
}
public extension FileManager {
@objc static let keyStoreFolderPrefix = "otr"
/// Returns the URL for the keyStore
@objc(keyStoreURLForAccountInDirectory:createParentIfNeeded:)
static func keyStoreURL(accountDirectory: URL, createParentIfNeeded: Bool) -> URL {
if createParentIfNeeded {
FileManager.default.createAndProtectDirectory(at: accountDirectory)
}
let keyStoreDirectory = accountDirectory.appendingPathComponent(FileManager.keyStoreFolderPrefix)
return keyStoreDirectory
}
}
public enum UserClientKeyStoreError: Error {
case canNotGeneratePreKeys
case preKeysCountNeedsToBePositive
}
/// A storage for cryptographic keys material
@objc(UserClientKeysStore) @objcMembers
open class UserClientKeysStore: NSObject {
/// Maximum possible ID for prekey
public static let MaxPreKeyID: UInt16 = UInt16.max-1
public var encryptionContext: EncryptionContext
/// Fallback prekeys (when no other prekey is available, this will always work)
fileprivate var internalLastPreKey: String?
/// Folder where the material is stored (managed by Cryptobox)
public private(set) var cryptoboxDirectory: URL
public private(set) var applicationContainer: URL
/// Loads new key store (if not present) or load an existing one
public init(accountDirectory: URL, applicationContainer: URL) {
self.cryptoboxDirectory = FileManager.keyStoreURL(accountDirectory: accountDirectory, createParentIfNeeded: true)
self.applicationContainer = applicationContainer
self.encryptionContext = UserClientKeysStore.setupContext(in: self.cryptoboxDirectory)!
}
private static func setupContext(in directory: URL) -> EncryptionContext? {
FileManager.default.createAndProtectDirectory(at: directory)
return EncryptionContext(path: directory)
}
open func deleteAndCreateNewBox() {
_ = try? FileManager.default.removeItem(at: cryptoboxDirectory)
self.encryptionContext = UserClientKeysStore.setupContext(in: cryptoboxDirectory)!
self.internalLastPreKey = nil
}
open func lastPreKey() throws -> String {
var error: NSError?
if internalLastPreKey == nil {
encryptionContext.perform({ [weak self] (sessionsDirectory) in
guard let strongSelf = self else { return }
do {
strongSelf.internalLastPreKey = try sessionsDirectory.generateLastPrekey()
} catch let anError as NSError {
error = anError
}
})
}
if let error = error {
throw error
}
return internalLastPreKey!
}
open func generateMoreKeys(_ count: UInt16 = 1, start: UInt16 = 0) throws -> [(id: UInt16, prekey: String)] {
if count > 0 {
var error: Error?
var newPreKeys : [(id: UInt16, prekey: String)] = []
let range = preKeysRange(count, start: start)
encryptionContext.perform({(sessionsDirectory) in
do {
newPreKeys = try sessionsDirectory.generatePrekeys(range)
if newPreKeys.count == 0 {
error = UserClientKeyStoreError.canNotGeneratePreKeys
}
}
catch let anError as NSError {
error = anError
}
})
if let error = error {
throw error
}
return newPreKeys
}
throw UserClientKeyStoreError.preKeysCountNeedsToBePositive
}
fileprivate func preKeysRange(_ count: UInt16, start: UInt16) -> CountableRange<UInt16> {
if start >= UserClientKeysStore.MaxPreKeyID-count {
return 0 ..< count
}
return start ..< (start + count)
}
}
| 0a7b9f6f954027d00d3a5a864bd60881 | 36.2375 | 125 | 0.670023 | false | false | false | false |
mmrmmlrr/ModelsTreeKit | refs/heads/master | ModelsTreeKit/Classes/UIKit/CollectionViewAdapter.swift | mit | 1 | //
// CollectionViewAdapter.swift
// ModelsTreeKit
//
// Created by aleksey on 06.12.15.
// Copyright © 2015 aleksey chernish. All rights reserved.
//
import Foundation
import UIKit
public class CollectionViewAdapter <ObjectType>: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
typealias DataSourceType = ObjectsDataSource<ObjectType>
typealias UpdateAction = (Void) -> Void
public var nibNameForObjectMatching: ((ObjectType, IndexPath) -> String)!
public var typeForSupplementaryViewOfKindMatching: ((String, IndexPath) -> UICollectionReusableView.Type)?
public var userInfoForCellSizeMatching: ((IndexPath) -> [String: AnyObject]?) = { _ in return nil }
public let didSelectCell = Pipe<(UICollectionViewCell, IndexPath, ObjectType)>()
public let willDisplayCell = Pipe<(UICollectionViewCell, IndexPath)>()
public let willCalculateSize = Pipe<(UICollectionViewCell, IndexPath)>()
public let didEndDisplayingCell = Pipe<(UICollectionViewCell, IndexPath)>()
public let willSetObject = Pipe<(UICollectionViewCell, IndexPath)>()
public let didSetObject = Pipe<(UICollectionViewCell, IndexPath)>()
public let didScroll = Pipe<UICollectionView>()
public let didEndDecelerating = Pipe<UICollectionView>()
public let didEndDragging = Pipe<UICollectionView>()
public let willEndDragging = Pipe<(UICollectionView, CGPoint, UnsafeMutablePointer<CGPoint>)>()
public let willDisplaySupplementaryView = Pipe<(UICollectionReusableView, String, IndexPath)>()
public let didEndDisplayingSupplementaryView = Pipe<(UICollectionReusableView, String, IndexPath)>()
public var checkedIndexPaths = [IndexPath]() {
didSet {
collectionView.indexPathsForVisibleItems.forEach {
if var checkable = collectionView.cellForItem(at: $0) as? Checkable {
checkable.checked = checkedIndexPaths.contains($0)
}
}
}
}
private weak var collectionView: UICollectionView!
private var dataSource: ObjectsDataSource<ObjectType>!
private var instances = [String: UICollectionViewCell]()
private var identifiersForIndexPaths = [IndexPath: String]()
private var mappings: [String: (ObjectType, UICollectionViewCell, IndexPath) -> Void] = [:]
private var updateActions = [UpdateAction]()
public init(dataSource: ObjectsDataSource<ObjectType>, collectionView: UICollectionView) {
super.init()
self.collectionView = collectionView
collectionView.dataSource = self
collectionView.delegate = self
self.dataSource = dataSource
dataSource.beginUpdatesSignal.subscribeNext { [weak self] in
self?.updateActions.removeAll()
}.putInto(pool)
dataSource.endUpdatesSignal.subscribeNext { [weak self] in
guard let strongSelf = self else { return }
strongSelf.updateActions.forEach { $0() }
}.putInto(pool)
dataSource.reloadDataSignal.subscribeNext { [weak self] in
guard let strongSelf = self else { return }
UIView.animate(withDuration: 0.1, animations: {
strongSelf.collectionView.alpha = 0},
completion: { completed in
strongSelf.collectionView.reloadData()
UIView.animate(withDuration: 0.2, animations: {
strongSelf.collectionView.alpha = 1
})
})
}.putInto(pool)
dataSource.didChangeObjectSignal.subscribeNext { [weak self] object, changeType, fromIndexPath, toIndexPath in
guard let strongSelf = self else {
return
}
switch changeType {
case .Insertion:
if let toIndexPath = toIndexPath {
strongSelf.updateActions.append() { [weak strongSelf] in
strongSelf?.collectionView.insertItems(at: [toIndexPath])
}
}
case .Deletion:
strongSelf.updateActions.append() { [weak strongSelf] in
if let fromIndexPath = fromIndexPath {
strongSelf?.collectionView.deleteItems(at: [fromIndexPath])
}
}
case .Update:
strongSelf.updateActions.append() { [weak strongSelf] in
if let indexPath = toIndexPath {
strongSelf?.collectionView.reloadItems(at: [indexPath])
}
}
case .Move:
strongSelf.updateActions.append() { [weak strongSelf] in
if let fromIndexPath = fromIndexPath, let toIndexPath = toIndexPath {
strongSelf?.collectionView.moveItem(at: fromIndexPath, to: toIndexPath)
}
}
}
}.putInto(pool)
dataSource.didChangeSectionSignal.subscribeNext { [weak self] changeType, fromIndex, toIndex in
guard let strongSelf = self else { return }
switch changeType {
case .Insertion:
strongSelf.updateActions.append() { [weak strongSelf] in
if let toIndex = toIndex {
strongSelf?.collectionView.insertSections(IndexSet(integer: toIndex))
}
}
case .Deletion:
if let fromIndex = fromIndex {
strongSelf.updateActions.append() { [weak strongSelf] in
strongSelf?.collectionView.deleteSections(IndexSet(integer: fromIndex))
}
}
default:
break
}
}.putInto(pool)
}
public func registerCellClass<U: ObjectConsuming>(_ cellClass: U.Type) where U.ObjectType == ObjectType {
let identifier = String(describing: cellClass)
let nib = UINib(nibName: identifier, bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: identifier)
instances[identifier] = nib.instantiate(withOwner: self, options: nil).last as? UICollectionViewCell
mappings[identifier] = { object, cell, _ in
if let consumer = cell as? U {
consumer.applyObject(object)
}
}
}
//UICollectionViewDataSource
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSource.numberOfSections()
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.numberOfObjectsInSection(section)
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let object = dataSource.objectAtIndexPath(indexPath)!;
let identifier = nibNameForObjectMatching(object, indexPath)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
identifiersForIndexPaths[indexPath] = identifier
willSetObject.sendNext((cell, indexPath))
let mapping = mappings[identifier]!
mapping(object, cell, indexPath)
didSetObject.sendNext((cell, indexPath))
return cell
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if var checkable = cell as? Checkable {
checkable.checked = checkedIndexPaths.contains(indexPath)
}
willDisplayCell.sendNext((cell, indexPath))
}
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let identifier = String(describing: typeForSupplementaryViewOfKindMatching!(kind, indexPath))
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier, for: indexPath)
return view
}
public func collectiolnView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
didEndDisplayingCell.sendNext((cell, indexPath))
}
public func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
willDisplaySupplementaryView.sendNext((view, elementKind, indexPath))
}
public func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) {
didEndDisplayingSupplementaryView.sendNext((view, elementKind, indexPath))
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let identifier = nibNameForObjectMatching(dataSource.objectAtIndexPath(indexPath)!, indexPath)
if let cell = instances[identifier] as? SizeCalculatingCell {
willCalculateSize.sendNext((instances[identifier]!, indexPath))
return cell.size(forObject: dataSource.objectAtIndexPath(indexPath), userInfo: userInfoForCellSizeMatching(indexPath))
}
if let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout {
return flowLayout.itemSize
}
return CGSize.zero;
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
didScroll.sendNext(collectionView)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
didEndDecelerating.sendNext(collectionView)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
didEndDragging.sendNext(collectionView)
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
willEndDragging.sendNext((collectionView, velocity, targetContentOffset))
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
didSelectCell.sendNext((
collectionView.cellForItem(at: indexPath)!,
indexPath,
dataSource.objectAtIndexPath(indexPath)!)
)
}
}
| 351e008764cc64ab1e18d258793030ce | 43.995885 | 197 | 0.647704 | false | false | false | false |
zerozheng/ZZQRCode | refs/heads/master | QRCode/ScanVC.swift | mit | 1 | //
// ScanVC.swift
// QRCode
//
// Created by zero on 17/2/7.
// Copyright © 2017年 zero. All rights reserved.
//
import UIKit
@objc protocol ScanVCDelegate: NSObjectProtocol {
func scanVC(vc:ScanVC, didFoundResult result: String)
}
class ScanVC: UIViewController {
weak var delegate: ScanVCDelegate?
var qrScaner: QRScaner?
override func viewDidLoad() {
super.viewDidLoad()
let qrScanView: QRScanView = QRScanView(frame: self.view.bounds)
self.qrScaner = QRScaner(view: qrScanView, didFoundResultHandle: { [unowned self] (string) in
let _ = self.navigationController?.popViewController(animated: true)
if let delegate = self.delegate, delegate.responds(to: #selector(ScanVCDelegate.scanVC(vc:didFoundResult:))) {
delegate.scanVC(vc: self, didFoundResult: string)
}
})
if let qrScaner = self.qrScaner {
self.view.addSubview(qrScanView)
qrScaner.startScanning()
}
}
}
| ecb129cd977b025b6ea8f25114c726e5 | 24.880952 | 122 | 0.610856 | false | false | false | false |
mcgraw/dojo-pop-animation | refs/heads/master | dojo-pop-animation/XMCSpringViewController.swift | mit | 1 | //
// XMCSpringViewController.swift
// dojo-pop-animation
//
// Created by David McGraw on 1/14/15.
// Copyright (c) 2015 David McGraw. All rights reserved.
//
import UIKit
class XMCSpringViewController: UIViewController {
@IBOutlet weak var ballView: UIView!
@IBOutlet weak var ballCenterYConstraint: NSLayoutConstraint!
var bounciness: CGFloat = 8.0
var atTop = false
override func viewDidLoad() {
super.viewDidLoad()
ballView.layer.cornerRadius = ballView.frame.size.width/2
ballView.layer.masksToBounds = true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
@IBAction func toggleActionPressed(sender: AnyObject) {
if atTop {
animateBottom()
} else {
animateTop()
}
atTop = !atTop
}
@IBAction func valueSlideChanged(sender: AnyObject) {
let slider = sender as UISlider
bounciness = CGFloat(slider.value)
}
func animateTop() {
let spring = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant)
spring.toValue = 200
spring.springBounciness = bounciness
spring.springSpeed = 8
ballCenterYConstraint.pop_addAnimation(spring, forKey: "moveUp")
}
func animateBottom() {
let spring = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant)
spring.toValue = -200
spring.springBounciness = bounciness
spring.springSpeed = 8
ballCenterYConstraint.pop_addAnimation(spring, forKey: "moveDown")
}
}
| 47474a04c95ce8eeaa5e9f04094b066c | 25.629032 | 84 | 0.644458 | false | false | false | false |
debugsquad/nubecero | refs/heads/master | nubecero/View/Store/VStoreCellNotAvailable.swift | mit | 1 | import UIKit
class VStoreCellNotAvailable:VStoreCell
{
override init(frame:CGRect)
{
super.init(frame:frame)
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
let label:UILabel = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.isUserInteractionEnabled = false
label.textAlignment = NSTextAlignment.center
label.font = UIFont.regular(size:14)
label.textColor = UIColor(white:0.5, alpha:1)
label.text = NSLocalizedString("VStoreCellNotAvailable_label", comment:"")
addSubview(label)
let views:[String:UIView] = [
"label":label]
let metrics:[String:CGFloat] = [:]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[label]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[label]-0-|",
options:[],
metrics:metrics,
views:views))
}
required init?(coder:NSCoder)
{
fatalError()
}
}
| 96aeba54b14639ea6f68dd3abd2a6b58 | 28 | 82 | 0.584565 | false | false | false | false |
samodom/TestSwagger | refs/heads/master | TestSwagger/Spying/SpyCoselectors.swift | mit | 1 | //
// SpyCoselectors.swift
// TestSwagger
//
// Created by Sam Odom on 2/19/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import FoundationSwagger
/// Convenience type used to create method surrogates for spying.
public struct SpyCoselectors {
let methodType: MethodType
let original: Selector
let spy: Selector
/// Creates a new spy co-selector.
/// - parameter methodType: The method type of the methods implemented by the selectors.
/// - parameter original: The selector of the original method defined by the root
/// spyable class that is spied upon.
/// - parameter spy: The selector of the spy method defined for the purposes of spying
/// on calls to the original method
public init(methodType: MethodType,
original: Selector,
spy: Selector) {
self.methodType = methodType
self.original = original
self.spy = spy
}
}
extension SpyCoselectors: Equatable {}
public func ==(lhs: SpyCoselectors, rhs: SpyCoselectors) -> Bool {
return lhs.methodType == rhs.methodType &&
lhs.original == rhs.original &&
lhs.spy == rhs.spy
}
extension SpyCoselectors: Hashable {
public var hashValue: Int {
return original.hashValue + spy.hashValue
}
}
| 7f0bb6d11f45fc578816474d1929f1b4 | 25.392157 | 92 | 0.64636 | false | false | false | false |
alienorb/Vectorized | refs/heads/master | Vectorized/Core/SVGGraphic.swift | mit | 1 | //---------------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Created by Austin Fitzpatrick on 3/19/15 (the "SwiftVG" project)
// Modified by Brian Christensen <[email protected]>
//
// Copyright (c) 2015 Seedling
// Copyright (c) 2016 Alien Orb Software LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//---------------------------------------------------------------------------------------
import Foundation
#if os(OSX)
import AppKit
#else
import UIKit
#endif
/// An SVGGraphic is used by a SVGView to display an SVG to the screen.
public class SVGGraphic: SVGGroup {
private(set) var size: CGSize //the size of the SVG's at "100%"
/// initializes an SVGGraphic with a list of drawables and a size
///
/// :param: drawables The list of drawables at the root level - can be nested
/// :param: size The size of the vector image at "100%"
/// :returns: An SVGGraphic ready for display in an SVGView
public init(drawables: [SVGDrawable], size: CGSize) {
self.size = size
super.init(drawables: drawables)
}
/// initializes an SVGGraphic with the contents of another SVGGraphic
///
/// :param: graphic another vector image to take the contents of
/// :returns: an SVGGraphic ready for display in an SVGView
public init(graphic: SVGGraphic) {
self.size = graphic.size
super.init(drawables: graphic.drawables)
}
/// Initializes an SVGGraphic with the contents of the file at the
/// given path
///
/// :param: path A file path to the SVG file
/// :returns: an SVGGraphic ready for display in an SVGView
public convenience init?(path: String) {
do {
if let parser = SVGParser(path: path) {
let (drawables, size) = try parser.coreParse()
self.init(drawables: drawables, size: size)
return
}
} catch {
print("The SVG parser encountered an error: \(error)")
return nil
}
return nil
}
/// Initializes an SVGGraphic with the data provided (should be an XML String)
///
/// :param: path A file path to the SVG file
/// :returns: an SVGGraphic ready for display in an SVGView
public convenience init?(data: NSData) {
do {
let (drawables, size) = try SVGParser(data: data).coreParse()
self.init(drawables: drawables, size: size)
} catch {
print("The SVG parser encountered an error: \(error)")
return nil
}
}
/// Optionally initialies an SVGGraphic with the given name in the main bundle
///
/// :param: name The name of the vector image file (without the .svg extension)
/// :returns: an SVGGraphic ready for display in an SVGView or nil if no svg exists
/// at the given path
public convenience init?(named name: String) {
if let path = NSBundle.mainBundle().pathForResource(name, ofType: "svg"), parser = SVGParser(path: path) {
do {
let graphic = try parser.parse()
self.init(graphic: graphic)
} catch {
print("The SVG parser encountered an error: \(error)")
return nil
}
return
}
return nil
}
/// Renders the vector image to a raster UIImage
///
/// :param: size the size of the UIImage to be returned
/// :param: contentMode the contentMode to use for rendering, some values may effect the output size
/// :returns: a UIImage containing a raster representation of the SVGGraphic
public func renderToImage(size size: CGSize, contentMode: SVGContentMode = .ScaleToFill) -> SVGImage {
let targetSize = sizeWithTargetSize(size, contentMode: contentMode)
let scale = scaleWithTargetSize(size, contentMode: contentMode)
let image: SVGImage
#if os(OSX)
let representation = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(targetSize.width), pixelsHigh: Int(targetSize.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)
image = NSImage(size: targetSize)
image.addRepresentation(representation!)
image.lockFocus()
#else
UIGraphicsBeginImageContext(targetSize)
#endif
let context = SVGGraphicsGetCurrentContext()
CGContextScaleCTM(context, scale.width, scale.height)
draw()
#if os(OSX)
image.unlockFocus()
#else
image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
#endif
return image
}
/// Returns the size of the vector image when scaled to fit in the size parameter using
/// the given content mode
///
/// :param: size The size to render at
/// :param: contentMode the contentMode to use for rendering
/// :returns: the size to render at
internal func sizeWithTargetSize(size: CGSize, contentMode: SVGContentMode) -> CGSize {
let targetSize = self.size
let bounds = size
switch contentMode {
case .ScaleAspectFit:
let scaleFactor = min(bounds.width / targetSize.width, bounds.height / targetSize.height)
let scale = CGSizeMake(scaleFactor, scaleFactor)
return CGSize(width: targetSize.width * scale.width, height: targetSize.height * scale.height)
case .ScaleAspectFill:
let scaleFactor = max(bounds.width / targetSize.width, bounds.height / targetSize.height)
let scale = CGSizeMake(scaleFactor, scaleFactor)
return CGSize(width: targetSize.width * scale.width, height: targetSize.height * scale.height)
case .ScaleToFill:
return size
case .Center:
return size
default:
return size
}
}
/// Returns the size of the translation to apply when rendering the SVG at the given size with the given contentMode
///
/// :param: size The size to render at
/// :param: contentMode the contentMode to use for rendering
/// :returns: the translation to apply when rendering
internal func translationWithTargetSize(size: CGSize, contentMode: SVGContentMode) -> CGPoint {
let targetSize = self.size
let bounds = size
var newSize: CGSize
switch contentMode {
case .ScaleAspectFit:
let scaleFactor = min(bounds.width / targetSize.width, bounds.height / targetSize.height)
let scale = CGSizeMake(scaleFactor, scaleFactor)
newSize = CGSize(width: targetSize.width * scale.width, height: targetSize.height * scale.height)
let xTranslation = (bounds.width - newSize.width) / 2.0
let yTranslation = (bounds.height - newSize.height) / 2.0
return CGPoint(x: xTranslation, y: yTranslation)
case .ScaleAspectFill:
let scaleFactor = max(bounds.width / targetSize.width, bounds.height / targetSize.height)
let scale = CGSizeMake(scaleFactor, scaleFactor)
newSize = CGSize(width: targetSize.width * scale.width, height: targetSize.height * scale.height)
let xTranslation = (bounds.width - newSize.width) / 2.0
let yTranslation = (bounds.height - newSize.height) / 2.0
return CGPoint(x: xTranslation, y: yTranslation)
case .ScaleToFill:
newSize = size
//??? WTF
//let scaleFactor = CGSize(width: bounds.width / targetSize.width, height: bounds.height / targetSize.height)
return CGPointZero
case .Center:
newSize = targetSize
let xTranslation = (bounds.width - newSize.width) / 2.0
let yTranslation = (bounds.height - newSize.height) / 2.0
return CGPoint(x: xTranslation, y: yTranslation)
default:
return CGPointZero
}
}
/// Returns the scale of the translation to apply when rendering the SVG at the given size with the given contentMode
///
/// :param: size The size to render at
/// :param: contentMode the contentMode to use for rendering
/// :returns: the scale to apply to the context when rendering
internal func scaleWithTargetSize(size: CGSize, contentMode: SVGContentMode) -> CGSize {
let targetSize = self.size
let bounds = size
switch contentMode {
case .ScaleAspectFit:
let scaleFactor = min(bounds.width / targetSize.width, bounds.height / targetSize.height)
return CGSizeMake(scaleFactor, scaleFactor)
case .ScaleAspectFill:
let scaleFactor = max(bounds.width / targetSize.width, bounds.height / targetSize.height)
return CGSizeMake(scaleFactor, scaleFactor)
case .ScaleToFill:
return CGSize(width:bounds.width / targetSize.width, height: bounds.height / targetSize.height)
case .Center:
return CGSize(width: 1, height: 1)
default:
return CGSize(width: 1, height: 1)
}
}
}
| f55e19b89a740687c187d8aac968fea4 | 33.63197 | 280 | 0.704272 | false | false | false | false |
Alexiuce/Tip-for-day | refs/heads/develop | Demo/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift | apache-2.0 | 22 | //
// UICollectionView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
// Items
extension Reactive where Base: UICollectionView {
/**
Binds sequences of elements to collection view items.
- parameter source: Observable sequence of items.
- parameter cellFactory: Transform between sequence elements and view cells.
- returns: Disposable object that can be used to unbind.
Example
let items = Observable.just([
1,
2,
3
])
items
.bind(to: collectionView.rx.items) { (collectionView, row, element) in
let indexPath = IndexPath(row: row, section: 0)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell
cell.value?.text = "\(element) @ \(row)"
return cell
}
.disposed(by: disposeBag)
*/
public func items<S: Sequence, O: ObservableType>
(_ source: O)
-> (_ cellFactory: @escaping (UICollectionView, Int, S.Iterator.Element) -> UICollectionViewCell)
-> Disposable where O.E == S {
return { cellFactory in
let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S>(cellFactory: cellFactory)
return self.items(dataSource: dataSource)(source)
}
}
/**
Binds sequences of elements to collection view items.
- parameter cellIdentifier: Identifier used to dequeue cells.
- parameter source: Observable sequence of items.
- parameter configureCell: Transform between sequence elements and view cells.
- parameter cellType: Type of table view cell.
- returns: Disposable object that can be used to unbind.
Example
let items = Observable.just([
1,
2,
3
])
items
.bind(to: collectionView.rx.items(cellIdentifier: "Cell", cellType: NumberCell.self)) { (row, element, cell) in
cell.value?.text = "\(element) @ \(row)"
}
.disposed(by: disposeBag)
*/
public func items<S: Sequence, Cell: UICollectionViewCell, O : ObservableType>
(cellIdentifier: String, cellType: Cell.Type = Cell.self)
-> (_ source: O)
-> (_ configureCell: @escaping (Int, S.Iterator.Element, Cell) -> Void)
-> Disposable where O.E == S {
return { source in
return { configureCell in
let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S> { (cv, i, item) in
let indexPath = IndexPath(item: i, section: 0)
let cell = cv.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! Cell
configureCell(i, item, cell)
return cell
}
return self.items(dataSource: dataSource)(source)
}
}
}
/**
Binds sequences of elements to collection view items using a custom reactive data used to perform the transformation.
- parameter dataSource: Data source used to transform elements to view cells.
- parameter source: Observable sequence of items.
- returns: Disposable object that can be used to unbind.
Example
let dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel<String, Double>>()
let items = Observable.just([
SectionModel(model: "First section", items: [
1.0,
2.0,
3.0
]),
SectionModel(model: "Second section", items: [
1.0,
2.0,
3.0
]),
SectionModel(model: "Third section", items: [
1.0,
2.0,
3.0
])
])
dataSource.configureCell = { (dataSource, cv, indexPath, element) in
let cell = cv.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell
cell.value?.text = "\(element) @ row \(indexPath.row)"
return cell
}
items
.bind(to: collectionView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
*/
public func items<
DataSource: RxCollectionViewDataSourceType & UICollectionViewDataSource,
O: ObservableType>
(dataSource: DataSource)
-> (_ source: O)
-> Disposable where DataSource.Element == O.E
{
return { source in
// This is called for sideeffects only, and to make sure delegate proxy is in place when
// data source is being bound.
// This is needed because theoretically the data source subscription itself might
// call `self.rx.delegate`. If that happens, it might cause weird side effects since
// setting data source will set delegate, and UICollectionView might get into a weird state.
// Therefore it's better to set delegate proxy first, just to be sure.
_ = self.delegate
// Strong reference is needed because data source is in use until result subscription is disposed
return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource, retainDataSource: true) { [weak collectionView = self.base] (_: RxCollectionViewDataSourceProxy, event) -> Void in
guard let collectionView = collectionView else {
return
}
dataSource.collectionView(collectionView, observedEvent: event)
}
}
}
}
extension UICollectionView {
/// Factory method that enables subclasses to implement their own `delegate`.
///
/// - returns: Instance of delegate proxy that wraps `delegate`.
public override func createRxDelegateProxy() -> RxScrollViewDelegateProxy {
return RxCollectionViewDelegateProxy(parentObject: self)
}
/// Factory method that enables subclasses to implement their own `rx.dataSource`.
///
/// - returns: Instance of delegate proxy that wraps `dataSource`.
public func createRxDataSourceProxy() -> RxCollectionViewDataSourceProxy {
return RxCollectionViewDataSourceProxy(parentObject: self)
}
}
extension Reactive where Base: UICollectionView {
/// Reactive wrapper for `dataSource`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var dataSource: DelegateProxy {
return RxCollectionViewDataSourceProxy.proxyForObject(base)
}
/// Installs data source as forwarding delegate on `rx.dataSource`.
/// Data source won't be retained.
///
/// It enables using normal delegate mechanism with reactive delegate mechanism.
///
/// - parameter dataSource: Data source object.
/// - returns: Disposable object that can be used to unbind the data source.
public func setDataSource(_ dataSource: UICollectionViewDataSource)
-> Disposable {
return RxCollectionViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base)
}
/// Reactive wrapper for `delegate` message `collectionView:didSelectItemAtIndexPath:`.
public var itemSelected: ControlEvent<IndexPath> {
let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didSelectItemAt:)))
.map { a in
return a[1] as! IndexPath
}
return ControlEvent(events: source)
}
/// Reactive wrapper for `delegate` message `collectionView:didSelectItemAtIndexPath:`.
public var itemDeselected: ControlEvent<IndexPath> {
let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didDeselectItemAt:)))
.map { a in
return a[1] as! IndexPath
}
return ControlEvent(events: source)
}
/// Reactive wrapper for `delegate` message `collectionView:didSelectItemAtIndexPath:`.
///
/// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
/// or any other data source conforming to `SectionedViewDataSourceType` protocol.
///
/// ```
/// collectionView.rx.modelSelected(MyModel.self)
/// .map { ...
/// ```
public func modelSelected<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = itemSelected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/// Reactive wrapper for `delegate` message `collectionView:didSelectItemAtIndexPath:`.
///
/// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
/// or any other data source conforming to `SectionedViewDataSourceType` protocol.
///
/// ```
/// collectionView.rx.modelDeselected(MyModel.self)
/// .map { ...
/// ```
public func modelDeselected<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = itemDeselected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/// Synchronous helper method for retrieving a model at indexPath through a reactive data source
public func model<T>(at indexPath: IndexPath) throws -> T {
let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.itemsWith*` methods was used.")
let element = try dataSource.model(at: indexPath)
return element as! T
}
}
#endif
#if os(tvOS)
extension Reactive where Base: UICollectionView {
/// Reactive wrapper for `delegate` message `collectionView:didUpdateFocusInContext:withAnimationCoordinator:`.
public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> {
let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didUpdateFocusIn:with:)))
.map { a -> (context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in
let context = a[1] as! UICollectionViewFocusUpdateContext
let animationCoordinator = a[2] as! UIFocusAnimationCoordinator
return (context: context, animationCoordinator: animationCoordinator)
}
return ControlEvent(events: source)
}
}
#endif
| 998be96811c79621931f84903a3cf0f0 | 38.003425 | 210 | 0.629555 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | refs/heads/master | source/Core/Classes/RSEnhancedTextScaleAnswerFormat.swift | apache-2.0 | 1 | //
// RSEnhancedTextScaleAnswerFormat.swift
// Pods
//
// Created by James Kizer on 8/6/17.
//
//
import UIKit
import ResearchKit
open class RSEnhancedTextScaleAnswerFormat: ORKTextScaleAnswerFormat {
public let maxValueLabel: String?
public let minValueLabel: String?
public let maximumValueDescription: String?
public let neutralValueDescription: String?
public let minimumValueDescription: String?
public let valueLabelHeight: Int?
public init(
textChoices: [ORKTextChoice],
defaultIndex: Int,
vertical: Bool,
maxValueLabel: String?,
minValueLabel: String?,
maximumValueDescription: String?,
neutralValueDescription: String?,
minimumValueDescription: String?,
valueLabelHeight: Int?
) {
self.maxValueLabel = maxValueLabel
self.minValueLabel = minValueLabel
self.maximumValueDescription = maximumValueDescription
self.neutralValueDescription = neutralValueDescription
self.minimumValueDescription = minimumValueDescription
self.valueLabelHeight = valueLabelHeight
super.init(textChoices: textChoices, defaultIndex: defaultIndex, vertical: vertical)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 5c857572df097e4b6dff889402a36bcc | 28.913043 | 92 | 0.694041 | false | false | false | false |
nickplee/A-E-S-T-H-E-T-I-C-A-M | refs/heads/master | Aestheticam/Sources/Other Sources/ImageDownloader.swift | mit | 1 | //
// ImageDownloader.swift
// A E S T H E T I C A M
//
// Created by Nick Lee on 5/21/16.
// Copyright © 2016 Nick Lee. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireImage
import RealmSwift
import RandomKit
final class ImageDownloader {
// MARK: Singleton
static let sharedInstance = ImageDownloader()
// MARK: Private Properties
private static let saveQueue = DispatchQueue(label: "com.nicholasleedesigns.aestheticam.save", attributes: [])
// MARK: Initialiaztion
private init() {}
// MARK: DB
private class func ImageRealm() throws -> Realm {
let folder = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] as NSString
let realmPath = folder.appendingPathComponent("data.realm")
var realmURL = URL(fileURLWithPath: realmPath)
var config = Realm.Configuration()
config.fileURL = realmURL
let realm = try Realm(configuration: config)
defer {
do {
var values = URLResourceValues()
values.isExcludedFromBackup = true
try realmURL.setResourceValues(values)
}
catch {}
}
return realm
}
// MARK: Download
func download() {
guard Globals.needsDownload else {
return
}
let url = Globals.apiURL
request(url).responseJSON { result in
guard let v = result.result.value as? [String: AnyObject], let images = v["images"] as? [String] else {
return
}
let urls = images.flatMap(URL.init(string:))
self.getImages(urls)
Globals.lastDownloadDate = Date()
}
}
private func getImages(_ urls: [URL]) {
let requests = urls.map({ request($0) })
requests.forEach {
$0.responseImage { result in
guard let image = result.result.value else {
return
}
ImageDownloader.saveQueue.async {
let realm = try! type(of: self).ImageRealm()
guard let data = UIImagePNGRepresentation(image) else {
return
}
do {
let urlString = result.request!.url!.absoluteString
let pred = NSPredicate(format: "%K = %@", argumentArray: ["url", urlString])
guard realm.objects(Image.self).filter(pred).first == nil else {
return
}
try realm.write {
let img = Image()
img.data = data
img.url = urlString
realm.add(img)
}
}
catch {}
}
}
}
}
// MARK: Random
func getRandomImage() -> UIImage? {
guard let realm = try? type(of: self).ImageRealm(), let entry = realm.objects(Image.self).random else {
return nil
}
return UIImage(data: entry.data)
}
}
| 080cbd64a708e97caf779d964cf83727 | 28.042017 | 115 | 0.481771 | false | false | false | false |
hilen/TSWeChat | refs/heads/master | TSWeChat/Classes/CoreModule/Models/TSModelTransformer.swift | mit | 1 | //
// TSModelTransformer.swift
// TSWeChat
//
// Created by Hilen on 2/22/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import ObjectMapper
//转换器:把 1423094023323 微秒时间转换成 几天前,几小时前
let TransformerTimestampToTimeAgo = TransformOf<String, NSNumber>(fromJSON: { (value: AnyObject?) -> String? in
guard let value = value else {
return ""
}
let seconds = Double(value as! NSNumber)/1000
let timeInterval: TimeInterval = TimeInterval(seconds)
let date = Date(timeIntervalSince1970: timeInterval)
let string = Date.messageAgoSinceDate(date)
return string
}, toJSON: { (value: String?) -> NSNumber? in
return nil
})
//把字符串转换为 Float
let TransformerStringToFloat = TransformOf<Float, String>(fromJSON: { (value: String?) -> Float? in
guard let value = value else {
return 0
}
let intValue: Float? = Float(value)
return intValue
}, toJSON: { (value: Float?) -> String? in
// transform value from Int? to String?
if let value = value {
return String(value)
}
return nil
})
//把字符串转换为 Int
let TransformerStringToInt = TransformOf<Int, String>(fromJSON: { (value: String?) -> Int? in
guard let value = value else {
return 0
}
let intValue: Int? = Int(value)
return intValue
}, toJSON: { (value: Int?) -> String? in
// transform value from Int? to String?
if let value = value {
return String(value)
}
return nil
})
//把字符串转换为 CGFloat
let TransformerStringToCGFloat = TransformOf<CGFloat, String>(fromJSON: { (value: String?) -> CGFloat? in
guard let value = value else {
return nil
}
let intValue: CGFloat? = CGFloat(Int(value)!)
return intValue
}, toJSON: { (value: CGFloat?) -> String? in
if let value = value {
return String(describing: value)
}
return nil
})
//数组的坐标转换为 CLLocation
let TransformerArrayToLocation = TransformOf<CLLocation, [Double]>(fromJSON: { (value: [Double]?) -> CLLocation? in
if let coordList = value, coordList.count == 2 {
return CLLocation(latitude: coordList[1], longitude: coordList[0])
}
return nil
}, toJSON: { (value: CLLocation?) -> [Double]? in
if let location = value {
return [Double(location.coordinate.longitude), Double(location.coordinate.latitude)]
}
return nil
})
| 077372ae3d4c74db1bb4fd46d088d12d | 27.823529 | 115 | 0.628571 | false | false | false | false |
200895045/NSDate-TimeAgo | refs/heads/final | NSDate+Extension.swift | isc | 12 | //
// NSDate+Extension.swift
// Tasty
//
// Created by Vitaliy Kuzmenko on 17/10/14.
// http://github.com/vitkuzmenko
// Copyright (c) 2014 Vitaliy Kuz'menko. All rights reserved.
//
import Foundation
let kMinute = 60
let kDay = kMinute * 24
let kWeek = kDay * 7
let kMonth = kDay * 31
let kYear = kDay * 365
func NSDateTimeAgoLocalizedStrings(key: String) -> String {
let resourcePath = NSBundle.mainBundle().resourcePath
let path = resourcePath?.stringByAppendingPathComponent("NSDateTimeAgo.bundle")
let bundle = NSBundle(path: path!)
return NSLocalizedString(key, tableName: "NSDateTimeAgo", bundle: bundle!, comment: "")
}
extension NSDate {
// shows 1 or two letter abbreviation for units.
// does not include 'ago' text ... just {value}{unit-abbreviation}
// does not include interim summary options such as 'Just now'
var timeAgoSimple: String {
let now = NSDate()
let deltaSeconds = Int(fabs(timeIntervalSinceDate(now)))
let deltaMinutes = deltaSeconds / 60
var value: Int!
if deltaSeconds < kMinute {
// Seconds
return stringFromFormat("%%d%@s", withValue: deltaSeconds)
} else if deltaMinutes < kMinute {
// Minutes
return stringFromFormat("%%d%@m", withValue: deltaMinutes)
} else if deltaMinutes < kDay {
// Hours
value = Int(floor(Float(deltaMinutes / kMinute)))
return stringFromFormat("%%d%@h", withValue: value)
} else if deltaMinutes < kWeek {
// Days
value = Int(floor(Float(deltaMinutes / kDay)))
return stringFromFormat("%%d%@d", withValue: value)
} else if deltaMinutes < kMonth {
// Weeks
value = Int(floor(Float(deltaMinutes / kWeek)))
return stringFromFormat("%%d%@w", withValue: value)
} else if deltaMinutes < kYear {
// Month
value = Int(floor(Float(deltaMinutes / kMonth)))
return stringFromFormat("%%d%@mo", withValue: value)
}
// Years
value = Int(floor(Float(deltaMinutes / kYear)))
return stringFromFormat("%%d%@yr", withValue: value)
}
var timeAgo: String {
let now = NSDate()
let deltaSeconds = Int(fabs(timeIntervalSinceDate(now)))
let deltaMinutes = deltaSeconds / 60
var value: Int!
if deltaSeconds < 5 {
// Just Now
return NSDateTimeAgoLocalizedStrings("Just now")
} else if deltaSeconds < kMinute {
// Seconds Ago
return stringFromFormat("%%d %@seconds ago", withValue: deltaSeconds)
} else if deltaSeconds < 120 {
// A Minute Ago
return NSDateTimeAgoLocalizedStrings("A minute ago")
} else if deltaMinutes < kMinute {
// Minutes Ago
return stringFromFormat("%%d %@minutes ago", withValue: deltaMinutes)
} else if deltaMinutes < 120 {
// An Hour Ago
return NSDateTimeAgoLocalizedStrings("An hour ago")
} else if deltaMinutes < kDay {
// Hours Ago
value = Int(floor(Float(deltaMinutes / kMinute)))
return stringFromFormat("%%d %@hours ago", withValue: value)
} else if deltaMinutes < (kDay * 2) {
// Yesterday
return NSDateTimeAgoLocalizedStrings("Yesterday")
} else if deltaMinutes < kWeek {
// Days Ago
value = Int(floor(Float(deltaMinutes / kDay)))
return stringFromFormat("%%d %@days ago", withValue: value)
} else if deltaMinutes < (kWeek * 2) {
// Last Week
return NSDateTimeAgoLocalizedStrings("Last week")
} else if deltaMinutes < kMonth {
// Weeks Ago
value = Int(floor(Float(deltaMinutes / kWeek)))
return stringFromFormat("%%d %@weeks ago", withValue: value)
} else if deltaMinutes < (kDay * 61) {
// Last month
return NSDateTimeAgoLocalizedStrings("Last month")
} else if deltaMinutes < kYear {
// Month Ago
value = Int(floor(Float(deltaMinutes / kMonth)))
return stringFromFormat("%%d %@months ago", withValue: value)
} else if deltaMinutes < (kDay * (kYear * 2)) {
// Last Year
return NSDateTimeAgoLocalizedStrings("Last Year")
}
// Years Ago
value = Int(floor(Float(deltaMinutes / kYear)))
return stringFromFormat("%%d %@years ago", withValue: value)
}
func stringFromFormat(format: String, withValue value: Int) -> String {
let localeFormat = String(format: format, getLocaleFormatUnderscoresWithValue(Double(value)))
return String(format: NSDateTimeAgoLocalizedStrings(localeFormat), value)
}
func getLocaleFormatUnderscoresWithValue(value: Double) -> String {
let localeCode = NSLocale.preferredLanguages().first as String
if localeCode == "ru" {
let XY = Int(floor(value)) % 100
let Y = Int(floor(value)) % 10
if Y == 0 || Y > 4 || (XY > 10 && XY < 15) {
return ""
}
if Y > 1 && Y < 5 && (XY < 10 || XY > 20) {
return "_"
}
if Y == 1 && XY != 11 {
return "__"
}
}
return ""
}
}
| de3d7ba22627d57af6b5bd863a81cf32 | 34.1625 | 101 | 0.557057 | false | false | false | false |
rasmusth/BluetoothKit | refs/heads/master | Example/Vendor/CryptoSwift/Sources/CryptoSwift/MD5.swift | mit | 1 | //
// MD5.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 06/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
public final class MD5: DigestType {
static let blockSize:Int = 64
static let digestLength:Int = 16 // 128 / 8
fileprivate static let hashInitialValue:Array<UInt32> = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
fileprivate var accumulated = Array<UInt8>()
fileprivate var accumulatedLength: Int = 0
fileprivate var accumulatedHash:Array<UInt32> = MD5.hashInitialValue
/** specifies the per-round shift amounts */
private let s: Array<UInt32> = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let k: Array<UInt32> = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,
0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,
0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,
0x6b901122,0xfd987193,0xa679438e,0x49b40821,
0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,
0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8,
0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,
0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,
0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,
0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,
0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05,
0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,
0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,
0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,
0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,
0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391]
public init() {
}
func calculate(for bytes: Array<UInt8>) -> Array<UInt8> {
do {
return try self.update(withBytes: bytes, isLast: true)
} catch {
fatalError()
}
}
// mutating currentHash in place is way faster than returning new result
fileprivate func process<C: Collection>(block chunk: C, currentHash: inout Array<UInt32>) where C.Iterator.Element == UInt8, C.Index == Int {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M = chunk.toUInt32Array()
assert(M.count == 16, "Invalid array")
// Initialize hash value for this chunk:
var A:UInt32 = currentHash[0]
var B:UInt32 = currentHash[1]
var C:UInt32 = currentHash[2]
var D:UInt32 = currentHash[3]
var dTemp:UInt32 = 0
// Main loop
for j in 0..<k.count {
var g = 0
var F:UInt32 = 0
switch (j) {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft(A &+ F &+ k[j] &+ M[g], by: s[j])
A = dTemp
}
currentHash[0] = currentHash[0] &+ A
currentHash[1] = currentHash[1] &+ B
currentHash[2] = currentHash[2] &+ C
currentHash[3] = currentHash[3] &+ D
}
}
extension MD5: Updatable {
public func update<T: Sequence>(withBytes bytes: T, isLast: Bool = false) throws -> Array<UInt8> where T.Iterator.Element == UInt8 {
let prevAccumulatedLength = self.accumulated.count
self.accumulated += bytes
self.accumulatedLength += self.accumulated.count - prevAccumulatedLength //avoid Array(bytes).count
if isLast {
// Step 1. Append padding
self.accumulated = bitPadding(to: self.accumulated, blockSize: MD5.blockSize, allowance: 64 / 8)
// Step 2. Append Length a 64-bit representation of lengthInBits
let lengthInBits = self.accumulatedLength * 8
let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b
self.accumulated += lengthBytes.reversed()
}
for chunk in BytesSequence(chunkSize: MD5.blockSize, data: self.accumulated) {
if (isLast || self.accumulated.count >= MD5.blockSize) {
self.process(block: chunk, currentHash: &self.accumulatedHash)
self.accumulated.removeFirst(chunk.count)
}
}
// output current hash
var result = Array<UInt8>()
result.reserveCapacity(MD5.digestLength)
for hElement in self.accumulatedHash {
let hLE = hElement.littleEndian
result += [UInt8(hLE & 0xff), UInt8((hLE >> 8) & 0xff), UInt8((hLE >> 16) & 0xff), UInt8((hLE >> 24) & 0xff)]
}
// reset hash value for instance
if isLast {
self.accumulatedHash = MD5.hashInitialValue
}
return result
}
}
| 303b70d36cf057c65ff62b47397e990b | 37.02027 | 145 | 0.543807 | false | false | false | false |
vespax/GoMap-keyboard | refs/heads/master | Keyboard/Custom Views/Buttons/KeyButton.swift | apache-2.0 | 1 | //
// KeyButton.swift
// ELDeveloperKeyboard
//
// Created by Eric Lin on 2014-07-02.
// Copyright (c) 2014 Eric Lin. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
/**
KeyButton is a UIButton subclass with keyboard button styling.
*/
class KeyButton: UIButton {
// MARK: Constructors
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel?.font = UIFont(name: "HelveticaNeue", size: 20.0)
titleLabel?.textAlignment = .center
setTitleColor(UIColor(white: 1.0/255, alpha: 1.0), for: UIControlState())
titleLabel?.sizeToFit()
let gradient = CAGradientLayer()
gradient.frame = bounds
let gradientColors: [AnyObject] = [UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0).cgColor, UIColor(red: 254.0/255, green: 254.0/255, blue: 254.0/255, alpha: 1.0).cgColor]
gradient.colors = gradientColors // Declaration broken into two lines to prevent 'unable to bridge to Objective C' error.
//setBackgroundImage(gradient.UIImageFromCALayer(), forState: .Normal)
setBackgroundImage(UIImage.fromColor(UIColor.white), for:UIControlState() )
let selectedGradient = CAGradientLayer()
selectedGradient.frame = bounds
let selectedGradientColors: [AnyObject] = [UIColor(red: 1.0, green: 1.0/255, blue: 1.0/255, alpha: 1.0).cgColor, UIColor(red: 200.0/255, green: 210.0/255, blue: 214.0/255, alpha: 1.0).cgColor]
selectedGradient.colors = selectedGradientColors // Declaration broken into two lines to prevent 'unable to bridge to Objective C' error.
setBackgroundImage(selectedGradient.UIImageFromCALayer(), for: .selected)
layer.masksToBounds = true
layer.cornerRadius = 3.0
contentVerticalAlignment = .center
contentHorizontalAlignment = .center
contentEdgeInsets = UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| f9d5553b6d9f201faeb755c50d82a112 | 39.480769 | 200 | 0.663658 | false | false | false | false |
danielpi/Swift-Playgrounds | refs/heads/master | Swift-Playgrounds/The Swift Programming Language/LanguageGuide/01-TheBasics.playground/Contents.swift | mit | 1 | // The Basics Chapter of “The Swift Programming Language.” iBooks. https://itun.es/au/jEUH0.l
//: # The Basics
//: ## Constants and Variables
//: ### Declaring Constants and Variables
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
var x = 0.0, y = 0.0, z = 0.0
//: ### Type Annotations
var welcomeMessage: String
welcomeMessage = "Hello"
var red, green, blue: Double
//: ### Naming Constants and Variables
let π = 3.14159
let 你好 = "你好世界"
let 🐶🐮 = "dogcow"
var friendlyWelcome = "Hello!"
friendlyWelcome = "Bonjour!"
let languageName = "Swift"
//languageName = "Swift++" // Compile time error
//: Printing Constants and Variables
print(friendlyWelcome)
print(π, 你好, 🐶🐮, separator: ", ", terminator: "")
print("The current value of friendlyWelcome is \(friendlyWelcome)")
//: ## Comments
// this is a comment
/* this is also a comment,
but written over multiple lines*/
/* this is the start of the first multiline comment
/* this is the second, nested multiline comment */
this is the end of the first multiline comment */
//: ## Semicolons
let cat = "🐱"; print(cat)
//: ## Integers
//: ### Integer Bounds
let minValue = UInt8.min
let maxValue = UInt8.max
//: ## Floating-Point Numbers
var w = [1, 1.2]
//: ## Type Safety and Type Inference
var meaningOfLife = 42
// inferred to be of type Int
// meaningOfLife = 35.0 //Type Error
let pi = 3.14159
let anotherPi = 3 + 0.14159
//: ## Numeric Literals
let descimalInteger = 17
let binaryInteger = 0b10001
let octalInteger = 0o21
let hexadecimalInteger = 0x11
//let hexFloat = 0x1234.0x5678
1.25e2
1.25e-2
0xFp2
0x8p4
let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecialDouble = 0xC.3p0
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1
//: ## Numeric Conversion
//: ### Integer Conversion
//let cannotBeNegative: UInt8 = -1
//let tooBig: Int8 = Int8.max + 1
let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)
//: ### Integer and Floating Point Conversion
let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi2 = Double(three) + pointOneFourOneFiveNine
let integerPi = Int(pi)
// Floats are always truncated when cast to Integers
let integerFourPointSeven = Int(4.75)
let integerNegativeThreePointNine = Int(-3.9)
// Literals can be cross type combined because they have no type until they are evaluated
3 + 0.14159
//: ## Type Aliases
// Type aliases are useful when you want to refer to an existing type by a name that is contextually more appropriate, such as when working with data of a specific size from an external source:
typealias AudioSample = UInt16
var macAmplitudeFound = AudioSample.min
//: ## Booleans
let orangesAreOrange = true
let turnipsAreDelicious = false
if turnipsAreDelicious {
print("Mmm, tasty turnips!")
} else {
print("Eww, turnips are horrible.")
}
// Non-Bool types can't be used for flow control
let i = 1
/*
if i {
}
*/
if i == 1 {
}
//: ## Tuples
let http404Error = (404, "Not Found")
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
print("The status message is \(statusMessage)")
// use _ if you don't want to decompose one of the values of a tuple
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// You can access the values of the tuple using index numbers
print("The status code is \(http404Error.0)")
print("The status message is \(http404Error.1)")
// You can name the elements of a tuple when it is defined
let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode)")
print("The status message is \(http200Status.description)")
// “Tuples are useful for temporary groups of related values. They are not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple. For more information”
//: ## Optionals
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be ot type "Int?" (optional Int)
// nil
var serverResponseCode: Int? = 404
serverResponseCode = nil
var surveyAnswer: String?
// surveyAnswer is automatically set to nil
// If statements and forced Unwrapping
if convertedNumber != nil {
print("convertedNumber contains some integer value.")
}
if convertedNumber != nil {
print("convertedNumber has an integer value of \(convertedNumber!)")
}
//: ### Optional Binding
if let actualNumber = Int(possibleNumber) {
print("\'\(possibleNumber)\' has a value of \(actualNumber)")
} else {
print("\'\(possibleNumber)\' could not be converted to an Int")
}
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
if let firstNumber = Int("4") {
if let secondNumber = Int("42") {
if firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
}
}
//: ### Implicitly Unwrapped Optionals
//: Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization
let possibleString: String? = "An optional string."
let forcedString: String = possibleString!
let assumedString: String! = "An implicitly unwrapped optional string"
let implicitString: String = assumedString
if assumedString != nil {
print(assumedString)
}
if let definiteString = assumedString {
print(definiteString)
}
//: Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.
//: ## Error Handling
//: In contrast to optionals, which can use the presence or absence of a value to signify success or failure of a function, error handling allows you to determine the underlying cause of failure and if necessary propagate the error to another part of your program.
func canThrowError() throws {
// This function may or may not throw an error.
}
do {
try canThrowError()
// no error was thrown
} catch {
// an error was thrown
}
enum SandwichError: Error {
case OutOfCleanDishes
case MissingIngredients([String])
}
func makeASandwich() throws {
throw SandwichError.MissingIngredients(["butter","ham","bread"])
}
func eatASandwich() {
print("yum yum yum")
}
func washDishes() {
print("Wash the dishes")
}
func buyGroceries(ingredients: [String]) {
ingredients.forEach{ i in print(i) }
}
do {
try makeASandwich()
eatASandwich()
} catch SandwichError.OutOfCleanDishes {
washDishes()
} catch SandwichError.MissingIngredients(let ingredients) {
buyGroceries(ingredients: ingredients)
} catch {
print("Why did I fail")
}
//: ## Assertions and Preconditions
//: ### Debugging with Assertions
//: Use an assertion whenever a condition has the potential to be false, but must definitely be true in order for your code to continue execution.
let age = -3
//assert(age >= 0, "A person's age cannot be less than zero")
// Left this out as it stops the REPL from continuing
//: ### Enforcing Preconditions
var index = -3
precondition(index > 0, "Index must be greater than zero.")
| e2eb173e9f708861042b4cf25f1c8c7a | 26.806569 | 296 | 0.720173 | false | false | false | false |
box/box-ios-sdk | refs/heads/main | Tests/Modules/SearchModuleSpecs.swift | apache-2.0 | 1 | //
// SearchModuleSpecs
// BoxSDK
//
// Created by Matt Willer on 5/3/2019.
// Copyright © 2019 Box. All rights reserved.
//
@testable import BoxSDK
import Nimble
import OHHTTPStubs
import Quick
class SearchModuleSpecs: QuickSpec {
var client: BoxClient!
override func spec() {
describe("SearchModule") {
beforeEach {
self.client = BoxSDK.getClient(token: "asdf")
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
context("query()") {
it("should make request with simple search query when only query is provided") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["query": "test"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let iterator = self.client.search.query(query: "test")
iterator.next { result in
switch result {
case let .success(page):
let item = page.entries[0]
guard case let .file(file) = item else {
fail("Expected test item to be a file")
done()
return
}
expect(file).toNot(beNil())
expect(file.id).to(equal("11111"))
expect(file.name).to(equal("test file.txt"))
expect(file.description).to(equal(""))
expect(file.size).to(equal(16))
case let .failure(error):
fail("Expected search request to succeed, but it failed: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with greater than relation") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"global\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"date\":{\"gt\":\"2019-07-24T12:00:00Z\"}}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "date", fieldValue: "2019-07-24T12:00:00Z", scope: MetadataScope.global, relation: MetadataFilterBound.greaterThan)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with less than relation") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"enterprise\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"date\":{\"lt\":\"2019-07-24T12:00:00Z\"}}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "date", fieldValue: "2019-07-24T12:00:00Z", scope: MetadataScope.enterprise, relation: MetadataFilterBound.lessThan)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with enterprise scope.") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"enterprise\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"documentType\":\"dataSheet\"}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "documentType", fieldValue: "dataSheet", scope: MetadataScope.enterprise)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with global scope.") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"global\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"documentType\":\"dataSheet\"}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "documentType", fieldValue: "dataSheet", scope: MetadataScope.global)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with query parameters populated when optional parameters are provided") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams([
"query": "test",
"scope": "user_content",
"file_extensions": "pdf,docx",
"created_at_range": "2019-05-15T21:52:15Z,2019-05-15T21:53:00Z",
"updated_at_range": "2019-05-15T21:53:27Z,2019-05-15T21:53:44Z",
"size_range": "1024,4096",
"owner_user_ids": "11111,22222",
"ancestor_folder_ids": "33333,44444",
"content_types": "name,description,comments,file_content,tags",
"type": "file",
"trash_content": "non_trashed_only"
])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let iterator = self.client.search.query(
query: "test",
scope: .user,
fileExtensions: ["pdf", "docx"],
createdAfter: Date(timeIntervalSince1970: 1_557_957_135), // 2019-05-15T21:52:15Z
createdBefore: Date(timeIntervalSince1970: 1_557_957_180), // 2019-05-15T21:53:00Z
updatedAfter: Date(timeIntervalSince1970: 1_557_957_207), // 2019-05-15T21:53:27Z
updatedBefore: Date(timeIntervalSince1970: 1_557_957_224), // 2019-05-15T21:53:44Z
sizeAtLeast: 1024,
sizeAtMost: 4096,
ownerUserIDs: ["11111", "22222"],
ancestorFolderIDs: ["33333", "44444"],
searchIn: [.name, .description, .comments, .fileContents, .tags],
itemType: .file,
searchTrash: false
)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Expected request to succeed, but instead got \(error)")
}
done()
}
}
}
}
context("queryWithSharedLinks()") {
it("should make request with simple search query and shared links query parameter when only query is provided") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams([
"query": "test",
"created_at_range": "2019-05-15T21:52:15Z,2019-05-15T21:53:00Z",
"updated_at_range": "2019-05-15T21:53:27Z,2019-05-15T21:53:44Z",
"size_range": "1024,4096",
"include_recent_shared_links": "true"
])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("SearchResult200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let iterator = self.client.search.queryWithSharedLinks(
query: "test",
createdAfter: Date(timeIntervalSince1970: 1_557_957_135), // 2019-05-15T21:52:15Z
createdBefore: Date(timeIntervalSince1970: 1_557_957_180), // 2019-05-15T21:53:00Z
updatedAfter: Date(timeIntervalSince1970: 1_557_957_207), // 2019-05-15T21:53:27Z
updatedBefore: Date(timeIntervalSince1970: 1_557_957_224), // 2019-05-15T21:53:44Z
sizeAtLeast: 1024,
sizeAtMost: 4096
)
iterator.next { result in
switch result {
case let .success(page):
let searchResult = page.entries[0]
let item = searchResult.item
guard case let .file(file) = item else {
fail("Expected test item to be a file")
done()
return
}
expect(file).toNot(beNil())
expect(file.id).to(equal("11111"))
expect(file.name).to(equal("test file.txt"))
expect(file.description).to(equal(""))
expect(file.size).to(equal(16))
expect(searchResult.accessibleViaSharedLink?.absoluteString).to(equal("https://www.box.com/s/vspke7y05sb214wjokpk"))
case let .failure(error):
fail("Expected search request to succeed, but it failed: \(error)")
}
done()
}
}
}
}
context("SearchScope") {
describe("init()") {
it("should correctly create an enum value from it's string representation") {
expect(SearchScope.user).to(equal(SearchScope(SearchScope.user.description)))
expect(SearchScope.enterprise).to(equal(SearchScope(SearchScope.enterprise.description)))
expect(SearchScope.customValue("custom value")).to(equal(SearchScope("custom value")))
}
}
}
context("SearchContentType") {
describe("init()") {
it("should correctly create an enum value from it's string representation") {
expect(SearchContentType.name).to(equal(SearchContentType(SearchContentType.name.description)))
expect(SearchContentType.description).to(equal(SearchContentType(SearchContentType.description.description)))
expect(SearchContentType.fileContents).to(equal(SearchContentType(SearchContentType.fileContents.description)))
expect(SearchContentType.comments).to(equal(SearchContentType(SearchContentType.comments.description)))
expect(SearchContentType.tags).to(equal(SearchContentType(SearchContentType.tags.description)))
expect(SearchContentType.customValue("custom value")).to(equal(SearchContentType("custom value")))
}
}
}
context("SearchItemType") {
describe("init()") {
it("should correctly create an enum value from it's string representation") {
expect(SearchItemType.file).to(equal(SearchItemType(SearchItemType.file.description)))
expect(SearchItemType.folder).to(equal(SearchItemType(SearchItemType.folder.description)))
expect(SearchItemType.webLink).to(equal(SearchItemType(SearchItemType.webLink.description)))
expect(SearchItemType.customValue("custom value")).to(equal(SearchItemType("custom value")))
}
}
}
}
}
}
| 0a6652163b9858e6c0ae14a3959a4751 | 50.93617 | 209 | 0.43536 | false | false | false | false |
grpc/grpc-swift | refs/heads/main | Sources/GRPC/Compression/MessageEncoding.swift | apache-2.0 | 1 | /*
* Copyright 2020, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// Whether compression should be enabled for the message.
public struct Compression: Hashable, GRPCSendable {
@usableFromInline
internal enum _Wrapped: Hashable, GRPCSendable {
case enabled
case disabled
case deferToCallDefault
}
@usableFromInline
internal var _wrapped: _Wrapped
private init(_ wrapped: _Wrapped) {
self._wrapped = wrapped
}
/// Enable compression. Note that this will be ignored if compression has not been enabled or is
/// not supported on the call.
public static let enabled = Compression(.enabled)
/// Disable compression.
public static let disabled = Compression(.disabled)
/// Defer to the call (the ``CallOptions`` for the client, and the context for the server) to
/// determine whether compression should be used for the message.
public static let deferToCallDefault = Compression(.deferToCallDefault)
}
extension Compression {
@inlinable
internal func isEnabled(callDefault: Bool) -> Bool {
switch self._wrapped {
case .enabled:
return callDefault
case .disabled:
return false
case .deferToCallDefault:
return callDefault
}
}
}
/// Whether compression is enabled or disabled for a client.
public enum ClientMessageEncoding: GRPCSendable {
/// Compression is enabled with the given configuration.
case enabled(Configuration)
/// Compression is disabled.
case disabled
}
extension ClientMessageEncoding {
internal var enabledForRequests: Bool {
switch self {
case let .enabled(configuration):
return configuration.outbound != nil
case .disabled:
return false
}
}
}
extension ClientMessageEncoding {
public struct Configuration: GRPCSendable {
public init(
forRequests outbound: CompressionAlgorithm?,
acceptableForResponses inbound: [CompressionAlgorithm] = CompressionAlgorithm.all,
decompressionLimit: DecompressionLimit
) {
self.outbound = outbound
self.inbound = inbound
self.decompressionLimit = decompressionLimit
}
/// The compression algorithm used for outbound messages.
public var outbound: CompressionAlgorithm?
/// The set of compression algorithms advertised to the remote peer that they may use.
public var inbound: [CompressionAlgorithm]
/// The decompression limit acceptable for responses. RPCs which receive a message whose
/// decompressed size exceeds the limit will be cancelled.
public var decompressionLimit: DecompressionLimit
/// Accept all supported compression on responses, do not compress requests.
public static func responsesOnly(
acceptable: [CompressionAlgorithm] = CompressionAlgorithm.all,
decompressionLimit: DecompressionLimit
) -> Configuration {
return Configuration(
forRequests: .identity,
acceptableForResponses: acceptable,
decompressionLimit: decompressionLimit
)
}
internal var acceptEncodingHeader: String {
return self.inbound.map { $0.name }.joined(separator: ",")
}
}
}
/// Whether compression is enabled or disabled on the server.
public enum ServerMessageEncoding {
/// Compression is supported with this configuration.
case enabled(Configuration)
/// Compression is not enabled. However, 'identity' compression is still supported.
case disabled
@usableFromInline
internal var isEnabled: Bool {
switch self {
case .enabled:
return true
case .disabled:
return false
}
}
}
extension ServerMessageEncoding {
public struct Configuration {
/// The set of compression algorithms advertised that we will accept from clients for requests.
/// Note that clients may send us messages compressed with algorithms not included in this list;
/// if we support it then we still accept the message.
///
/// All cases of `CompressionAlgorithm` are supported.
public var enabledAlgorithms: [CompressionAlgorithm]
/// The decompression limit acceptable for requests. RPCs which receive a message whose
/// decompressed size exceeds the limit will be cancelled.
public var decompressionLimit: DecompressionLimit
/// Create a configuration for server message encoding.
///
/// - Parameters:
/// - enabledAlgorithms: The list of algorithms which are enabled.
/// - decompressionLimit: Decompression limit acceptable for requests.
public init(
enabledAlgorithms: [CompressionAlgorithm] = CompressionAlgorithm.all,
decompressionLimit: DecompressionLimit
) {
self.enabledAlgorithms = enabledAlgorithms
self.decompressionLimit = decompressionLimit
}
}
}
| cb0f1f4ed553377ca3af0334f31e9753 | 31.555556 | 100 | 0.723929 | false | true | false | false |
IBM-Swift/BluePic | refs/heads/master | BluePic-iOS/Pods/BMSPush/Source/BMSPushUtils.swift | apache-2.0 | 1 | /*
* Copyright 2016 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
// MARK: - Swift 3
#if swift(>=3.0)
/**
Utils class for `BMSPush`
*/
internal class BMSPushUtils: NSObject {
static var loggerMessage:String = ""
class func saveValueToNSUserDefaults (value:String, key:String) {
UserDefaults.standard.set(value, forKey: key)
UserDefaults.standard.synchronize()
loggerMessage = ("Saving value to NSUserDefaults with Key: \(key) and Value: \(value)")
self.sendLoggerData()
}
class func getValueToNSUserDefaults (key:String) -> String {
var value = ""
if(UserDefaults.standard.value(forKey: key) != nil){
value = UserDefaults.standard.value(forKey: key) as! String
}
loggerMessage = ("Getting value for NSUserDefaults Key: \(key) and Value: \(value)")
self.sendLoggerData()
return value
}
class func getPushSettingValue() -> Bool {
var pushEnabled = false
if ((UIDevice.current.systemVersion as NSString).floatValue >= 8.0) {
if (UIApplication.shared.isRegisteredForRemoteNotifications) {
pushEnabled = true
}
else {
pushEnabled = false
}
} else {
let grantedSettings = UIApplication.shared.currentUserNotificationSettings
if grantedSettings!.types.rawValue & UIUserNotificationType.alert.rawValue != 0 {
// Alert permission granted
pushEnabled = true
}
else{
pushEnabled = false
}
}
return pushEnabled;
}
class func sendLoggerData () {
let devId = BMSPushClient.sharedInstance.getDeviceID()
let testLogger = Logger.logger(name:devId)
Logger.logLevelFilter = LogLevel.debug
testLogger.debug(message: loggerMessage)
Logger.logLevelFilter = LogLevel.info
testLogger.info(message: loggerMessage)
}
}
/**************************************************************************************************/
// MARK: - Swift 2
#else
/**
Utils class for `BMSPush`
*/
internal class BMSPushUtils: NSObject {
static var loggerMessage:String = ""
class func saveValueToNSUserDefaults (value:String, key:String) {
NSUserDefaults.standardUserDefaults().setObject(value, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
loggerMessage = ("Saving value to NSUserDefaults with Key: \(key) and Value: \(value)")
self.sendLoggerData()
}
class func getValueToNSUserDefaults (key:String) -> String{
var value = ""
if(NSUserDefaults.standardUserDefaults().valueForKey(key) != nil) {
value = NSUserDefaults.standardUserDefaults().stringForKey(key)!
}
loggerMessage = ("Getting value for NSUserDefaults Key: \(key) and Value: \(value)")
self.sendLoggerData()
return value ;
}
class func getPushSettingValue() -> Bool {
var pushEnabled = false
if ((UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8.0) {
if (UIApplication.sharedApplication().isRegisteredForRemoteNotifications()) {
pushEnabled = true
}
else {
pushEnabled = false
}
} else {
let grantedSettings = UIApplication.sharedApplication().currentUserNotificationSettings()
if grantedSettings!.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 {
// Alert permission granted
pushEnabled = true
}
else{
pushEnabled = false
}
}
return pushEnabled;
}
class func sendLoggerData () {
let devId = BMSPushClient.sharedInstance.getDeviceID()
let testLogger = Logger.logger(name: devId)
Logger.logLevelFilter = LogLevel.debug
testLogger.debug(message: loggerMessage)
Logger.logLevelFilter = LogLevel.info
testLogger.info(message: loggerMessage)
}
}
#endif
| 3937b989e457871a952ca2d7f55abe82 | 28.497041 | 101 | 0.581143 | false | false | false | false |
VadimPavlov/Swifty | refs/heads/master | Sources/Swifty/Common/Foundation/Dictionary.swift | mit | 1 | //
// Collection.swift
// Created by Vadim Pavlov on 4/27/16.
import Foundation
public extension Dictionary {
init(_ pairs: [Element]) {
self.init()
for (k, v) in pairs {
self[k] = v
}
}
func mapPairs<OutKey: Hashable, OutValue>(_ transform: (Element) throws -> (OutKey, OutValue)) rethrows -> [OutKey: OutValue] {
return Dictionary<OutKey, OutValue>(try map(transform))
}
func mapKeys<OutKey: Hashable>(_ transform: @escaping (Key) -> OutKey) -> [OutKey : Value] {
return self.mapPairs { (transform($0), $1) }
}
func mapValues<OutValue>(_ transform: (Value) -> OutValue) -> [Key : OutValue] {
return self.mapPairs { ($0, transform($1)) }
}
func filterPairs(_ includeElement: (Element) throws -> Bool) rethrows -> [Key: Value] {
return Dictionary(try filter(includeElement))
}
}
public extension Dictionary where Value: Equatable {
func allKeys(forValue val: Value) -> [Key] {
return self.filter { $1 == val }.map { $0.0 }
}
}
// MARK: - Combining operators
public extension Dictionary {
static func +=(lhs: inout [Key: Value], rhs: [Key: Value]) {
rhs.forEach({ lhs[$0] = $1})
}
static func +(lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
var combined = lhs
combined += rhs
return combined
}
}
| d01c3d7721c6c4eb4c969d0f57ccc453 | 27.02 | 131 | 0.581014 | false | false | false | false |
erikmartens/NearbyWeather | refs/heads/develop | NearbyWeather/Commons/Extensions/MKMapView+Focus.swift | mit | 1 | //
// MKMapView+Focus.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 05.03.22.
// Copyright © 2022 Erik Maximilian Martens. All rights reserved.
//
import MapKit.MKMapView
extension MKMapView {
func focus(onCoordinate coordinate: CLLocationCoordinate2D?, latitudinalMeters: CLLocationDistance = 1500, longitudinalMeters: CLLocationDistance = 1500, animated: Bool = false) {
guard let coordinate = coordinate else {
return
}
let region = MKCoordinateRegion(center: coordinate, latitudinalMeters: latitudinalMeters, longitudinalMeters: longitudinalMeters)
setRegion(region, animated: animated)
}
}
| e9b891aaaa0a23ef0bf48bd5879163af | 33.105263 | 181 | 0.757716 | false | false | false | false |
safx/TypetalkApp | refs/heads/master | TypetalkApp/OSX/ViewControllers/EditTopicViewController.swift | mit | 1 | //
// EditTopicViewController.swift
// TypetalkApp
//
// Created by Safx Developer on 2015/02/22.
// Copyright (c) 2015年 Safx Developers. All rights reserved.
//
import Cocoa
import TypetalkKit
import RxSwift
class EditTopicViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
let viewModel = EditTopicViewModel()
@IBOutlet weak var topicNameLabel: NSTextField!
@IBOutlet weak var teamListBox: NSComboBox!
@IBOutlet weak var idLabel: NSTextField!
@IBOutlet weak var createdLabel: NSTextField!
@IBOutlet weak var updatedLabel: NSTextField!
@IBOutlet weak var lastPostedLabel: NSTextField!
@IBOutlet weak var acceptButton: NSButton!
@IBOutlet weak var membersTableView: NSTableView!
@IBOutlet weak var invitesTableView: NSTableView!
private let disposeBag = DisposeBag()
var topic: Topic? = nil {
didSet {
self.viewModel.fetch(topic!)
}
}
override func viewDidLoad() {
super.viewDidLoad()
membersTableView.setDelegate(self)
membersTableView.setDataSource(self)
invitesTableView.setDelegate(self)
invitesTableView.setDataSource(self)
teamListBox.editable = false
acceptButton.enabled = false
precondition(topic != nil)
self.topicNameLabel.stringValue = topic!.name
self.idLabel.stringValue = "\(topic!.id)"
self.createdLabel.stringValue = topic!.createdAt.humanReadableTimeInterval
self.updatedLabel.stringValue = topic!.updatedAt.humanReadableTimeInterval
if let posted = topic!.lastPostedAt {
self.lastPostedLabel.stringValue = posted.humanReadableTimeInterval
}
Observable.combineLatest(viewModel.teamListIndex.asObservable(), viewModel.teamList.asObservable()) { ($0, $1) }
.filter { !$0.1.isEmpty }
.subscribeOn(MainScheduler.instance)
.subscribeNext { (index, teams) -> () in
self.teamListBox.removeAllItems()
self.teamListBox.addItemsWithObjectValues(teams.map { $0.description } )
self.teamListBox.selectItemAtIndex(index)
self.acceptButton.enabled = true
}
.addDisposableTo(disposeBag)
Observable.combineLatest(viewModel.teamList.asObservable(), teamListBox.rx_selectionSignal()) { ($0, $1) }
.filter { teams, idx in teams.count > 0 && (0..<teams.count).contains(idx) }
.map { teams, idx in TeamID(teams[idx].id) }
.bindTo(viewModel.teamId)
.addDisposableTo(disposeBag)
topicNameLabel
.rx_text
.throttle(0.05, scheduler: MainScheduler.instance)
.bindTo(viewModel.topicName)
.addDisposableTo(disposeBag)
viewModel.accounts
.asObservable()
.subscribeOn(MainScheduler.instance)
.subscribeNext { [weak self] _ in
self?.membersTableView.reloadData()
()
}
.addDisposableTo(disposeBag)
viewModel.invites
.asObservable()
.subscribeOn(MainScheduler.instance)
.subscribeNext { [weak self] _ in
self?.invitesTableView.reloadData()
()
}
.addDisposableTo(disposeBag)
}
@IBAction func deleteTopic(sender: AnyObject) {
let alert = NSAlert()
alert.addButtonWithTitle("Delete")
alert.addButtonWithTitle("Cancel")
let bs = alert.buttons as [NSButton]
bs[0].keyEquivalent = "\033"
bs[1].keyEquivalent = "\r"
alert.messageText = "Remove “\(topic!.name)”"
alert.informativeText = "WARNING: All messages in this topic will be removed permanently."
alert.alertStyle = .WarningAlertStyle
if let key = NSApp.keyWindow {
alert.beginSheetModalForWindow(key) { [weak self] res in
if res == NSAlertFirstButtonReturn {
if let s = self {
s.viewModel.deleteTopic()
s.presentingViewController?.dismissViewController(s)
}
}
}
}
}
@IBAction func exit(sender: NSButton) {
presentingViewController?.dismissViewController(self)
}
@IBAction func accept(sender: AnyObject) {
viewModel.updateTopic()
presentingViewController?.dismissViewController(self)
}
// MARK: - NSTableViewDataSource
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if tableView == membersTableView {
return viewModel.accounts.value.count
} else if tableView == invitesTableView {
return viewModel.invites.value.count
}
return 0
}
func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
if let i = tableColumn?.identifier {
if tableView == membersTableView && 0 <= row && row < viewModel.accounts.value.count {
let account = viewModel.accounts.value[row]
if i == "image" { return NSImage(contentsOfURL: account.imageUrl) }
if i == "name" { return account.name }
if i == "date" { return account.createdAt.humanReadableTimeInterval }
}
else if tableView == invitesTableView && 0 <= row && row < viewModel.invites.value.count {
let invite = viewModel.invites.value[row]
if i == "image" {
if let a = invite.account {
return NSImage(contentsOfURL: a.imageUrl)
}
}
if i == "name" { return invite.account?.name ?? "" }
if i == "status" { return invite.status }
if i == "date" { return invite.createdAt?.humanReadableTimeInterval ?? "" }
}
}
return nil
}
// MARK: - NSTableViewDelegate
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 20
}
}
| 7f06457ebbb07cfe779d21fcf276c793 | 35.52071 | 123 | 0.604018 | false | false | false | false |
IAskWind/IAWExtensionTool | refs/heads/master | Demo/roadtrip/Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift | mit | 4 | //
// NSButton+Kingfisher.swift
// Kingfisher
//
// Created by Jie Zhang on 14/04/2016.
//
// 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.
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
extension KingfisherWrapper where Base: NSButton {
// MARK: Setting Image
/// Sets an image to the button with a source.
///
/// - Parameters:
/// - source: The `Source` object contains information about how to get the image.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested source.
/// Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
base.image = placeholder
mutatingSelf.taskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
if !options.keepCurrentImageWhileLoading {
base.image = placeholder
}
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.taskIdentifier = issuedIdentifier
if let block = progressBlock {
options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
if let provider = ImageProgressiveProvider(options, refresh: { image in
self.base.image = image
}) {
options.onDataReceived = (options.onDataReceived ?? []) + [provider]
}
options.onDataReceived?.forEach {
$0.onShouldApply = { issuedIdentifier == self.taskIdentifier }
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
guard issuedIdentifier == self.taskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.imageTask = nil
mutatingSelf.taskIdentifier = nil
switch result {
case .success(let value):
self.base.image = value.image
completionHandler?(result)
case .failure:
if let image = options.onFailureImage {
self.base.image = image
}
completionHandler?(result)
}
}
}
)
mutatingSelf.imageTask = task
return task
}
/// Sets an image to the button with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the resource.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: resource?.convertToSource(),
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
// MARK: Cancelling Downloading Task
/// Cancels the image download task of the button if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelImageDownloadTask() {
imageTask?.cancel()
}
// MARK: Setting Alternate Image
@discardableResult
public func setAlternateImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
base.alternateImage = placeholder
mutatingSelf.alternateTaskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
if !options.keepCurrentImageWhileLoading {
base.alternateImage = placeholder
}
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.alternateTaskIdentifier = issuedIdentifier
if let block = progressBlock {
options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
if let provider = ImageProgressiveProvider(options, refresh: { image in
self.base.alternateImage = image
}) {
options.onDataReceived = (options.onDataReceived ?? []) + [provider]
}
options.onDataReceived?.forEach {
$0.onShouldApply = { issuedIdentifier == self.alternateTaskIdentifier }
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
downloadTaskUpdated: { mutatingSelf.alternateImageTask = $0 },
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
guard issuedIdentifier == self.alternateTaskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.alternateImageTask = nil
mutatingSelf.alternateTaskIdentifier = nil
switch result {
case .success(let value):
self.base.alternateImage = value.image
completionHandler?(result)
case .failure:
if let image = options.onFailureImage {
self.base.alternateImage = image
}
completionHandler?(result)
}
}
}
)
mutatingSelf.alternateImageTask = task
return task
}
/// Sets an alternate image to the button with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the resource.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setAlternateImage(
with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setAlternateImage(
with: resource?.convertToSource(),
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
// MARK: Cancelling Alternate Image Downloading Task
/// Cancels the alternate image download task of the button if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelAlternateImageDownloadTask() {
alternateImageTask?.cancel()
}
}
// MARK: - Associated Object
private var taskIdentifierKey: Void?
private var imageTaskKey: Void?
private var alternateTaskIdentifierKey: Void?
private var alternateImageTaskKey: Void?
extension KingfisherWrapper where Base: NSButton {
// MARK: Properties
public private(set) var taskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &taskIdentifierKey, box)
}
}
private var imageTask: DownloadTask? {
get { return getAssociatedObject(base, &imageTaskKey) }
set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
}
public private(set) var alternateTaskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &alternateTaskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &alternateTaskIdentifierKey, box)
}
}
private var alternateImageTask: DownloadTask? {
get { return getAssociatedObject(base, &alternateImageTaskKey) }
set { setRetainedAssociatedObject(base, &alternateImageTaskKey, newValue)}
}
}
extension KingfisherWrapper where Base: NSButton {
/// Gets the image URL bound to this button.
@available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.")
public private(set) var webURL: URL? {
get { return nil }
set { }
}
/// Gets the image URL bound to this button.
@available(*, deprecated, message: "Use `alternateTaskIdentifier` instead to identify a setting task.")
public private(set) var alternateWebURL: URL? {
get { return nil }
set { }
}
}
#endif
| 8791261a85e94c0467a39fc83b726390 | 40.966197 | 119 | 0.614646 | false | false | false | false |
ushios/SwifTumb | refs/heads/master | Sources/SwifTumb/OAuthSwiftAdapter.swift | mit | 1 | //
// OAuthSwiftAdapter.swift
// SwifTumb
//
// Created by Ushio Shugo on 2016/12/11.
//
//
import Foundation
import OAuthSwift
open class OAuthSwiftAdapter: OAuth1Swift, SwifTumbOAuthAdapter {
public init(
consumerKey: String,
consumerSecret: String,
oauthToken: String,
oauthTokenSecret: String
) {
super.init(
consumerKey: consumerKey,
consumerSecret: consumerSecret,
requestTokenUrl: SwifTumb.RequestTokenUrl,
authorizeUrl: SwifTumb.AuthorizeUrl,
accessTokenUrl: SwifTumb.AccessTokenUrl
)
self.client.credential.oauthToken = oauthToken
self.client.credential.oauthTokenSecret = oauthTokenSecret
}
convenience init (consumerKey: String, consumerSecret: String) {
self.init(
consumerKey: consumerKey,
consumerSecret: consumerSecret,
oauthToken: "",
oauthTokenSecret: ""
)
}
public func request(
_ urlString: String,
method: SwifTumbHttpRequest.Method,
parameters: SwifTumb.Parameters = [:],
headers: SwifTumb.Headers? = nil,
body: Data? = nil,
checkTokenExpiration: Bool = true,
success: SwifTumbHttpRequest.SuccessHandler?,
failure: SwifTumbHttpRequest.FailureHandler?
) -> SwifTumbRequestHandle? {
let handle: OAuthSwiftRequestHandle? = self.client.request(
urlString,
method: self.method(method: method),
parameters: parameters,
headers: headers,
body:body,
checkTokenExpiration: checkTokenExpiration,
success: { (response: OAuthSwiftResponse) in
if success != nil {
// print("response data:", String(data: response.data, encoding: .utf8))
let resp = try! SwifTumbResponseMapper.Response(
data: response.data
)
success!(resp)
}
},
failure: { (err: OAuthSwiftError) in
if failure != nil {
failure!(OAuthSwiftAdapterError(err.description))
}
}
)
return OAuthSwiftAdapterRequestHandle(handle: handle)
}
private func method(method: SwifTumbHttpRequest.Method) -> OAuthSwiftHTTPRequest.Method {
switch method {
case SwifTumbHttpRequest.Method.GET:
return OAuthSwiftHTTPRequest.Method.GET
case SwifTumbHttpRequest.Method.POST:
return OAuthSwiftHTTPRequest.Method.POST
case SwifTumbHttpRequest.Method.PUT:
return OAuthSwiftHTTPRequest.Method.PUT
case SwifTumbHttpRequest.Method.DELETE:
return OAuthSwiftHTTPRequest.Method.DELETE
case SwifTumbHttpRequest.Method.PATCH:
return OAuthSwiftHTTPRequest.Method.PATCH
case SwifTumbHttpRequest.Method.HEAD:
return OAuthSwiftHTTPRequest.Method.HEAD
}
}
}
open class OAuthSwiftAdapterError: SwifTumbError {
private var rawMessage: String
init(_ message: String) {
self.rawMessage = message
}
open func message() -> String {
return self.rawMessage
}
}
open class OAuthSwiftAdapterRequestHandle: SwifTumbRequestHandle {
var handle: OAuthSwiftRequestHandle
init? (handle: OAuthSwiftRequestHandle?) {
if handle == nil {
return nil
}
self.handle = handle!
}
open func cancel() {
self.handle.cancel()
}
}
| 4eb2fcff251a89214351e935eb3758c0 | 29.213115 | 93 | 0.595225 | false | false | false | false |
claudetech/cordova-plugin-media-lister | refs/heads/master | src/ios/MediaLister.swift | mit | 1 | import Foundation
import AssetsLibrary
import MobileCoreServices
// TODO: Rewrite in ObjC or Photo
@objc(HWPMediaLister) public class MediaLister: CDVPlugin{
let library = ALAssetsLibrary()
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
var command: CDVInvokedUrlCommand!
var option: [String: AnyObject] = [:]
var result:[[String: AnyObject]] = []
var success: Bool!
public func readLibrary(command: CDVInvokedUrlCommand){
dispatch_async(dispatch_get_global_queue(priority, 0)){
self.result = []
self.command = command
let temp = command.arguments[0] as! [String: AnyObject]
self.option = self.initailizeOption(temp)
self.loadMedia(self.option)
}
}
public func startLoad(thumbnail: Bool = true, limit: Int = 20, mediaTypes: [String] = ["image"], offset:Int = 0) -> [[String: AnyObject]]{
option = ["thumbnail": thumbnail, "limit":limit , "mediaTypes": mediaTypes, "offset": offset]
loadMedia(option)
return result
}
private func initailizeOption(option:[String: AnyObject]) -> [String: AnyObject]{
var tempOption = option
if tempOption["offset"] == nil{
tempOption["offset"] = 0
}
if tempOption["limit"] == nil{
tempOption["limit"] = 20
}
if tempOption["thumbnail"] == nil{
tempOption["thumbnail"] = true
}
if tempOption["mediaTypes"] == nil{
tempOption["mdeiaTypes"] = ["image"]
}
return tempOption
}
private func sendResult(){
dispatch_async(dispatch_get_main_queue()){
var pluginResult: CDVPluginResult! = nil
if self.success == true {
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsArray: self.result)
} else {
pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR)
}
self.commandDelegate?.sendPluginResult(pluginResult, callbackId: self.command.callbackId)
}
}
private func loadMedia(option: [String: AnyObject]){
success = false
library.enumerateGroupsWithTypes(ALAssetsGroupSavedPhotos,usingBlock: {
(group: ALAssetsGroup!, stop: UnsafeMutablePointer) in
if group == nil{
return
}
self.success = true
if let filter = self.getFilter(option["mediaTypes"] as! [String]){
group.setAssetsFilter(filter)
} else {
return
}
let num = group.numberOfAssets()
let indexSet = self.getIndexSet(num, limit: option["limit"] as! Int, offset: option["offset"] as! Int)
if indexSet == nil{
return
}
group.enumerateAssetsAtIndexes(indexSet!, options: NSEnumerationOptions.Reverse){
(asset:ALAsset!, id:Int , stop: UnsafeMutablePointer) in
if asset != nil{
self.result.append(self.setDictionary(asset, id: id, option:option))
}
}
self.sendResult()
}, failureBlock:{
(myerror: NSError!) -> Void in
print("error occurred: \(myerror.localizedDescription)")
}
)
}
// TODO: Add data of Location etc.
private func setDictionary(asset: ALAsset, id: Int, option: [String: AnyObject]) -> [String: AnyObject]{
var data: [String: AnyObject] = [:]
data["id"] = id
data["mediaType"] = setType(asset)
let date: NSDate = asset.valueForProperty(ALAssetPropertyDate) as! NSDate
data["dateAdded"] = date.timeIntervalSince1970
data["path"] = asset.valueForProperty(ALAssetPropertyAssetURL).absoluteString
let rep = asset.defaultRepresentation()
data["size"] = Int(rep.size())
data["orientation"] = rep.metadata()["Orientation"]
data["title"] = rep.filename()
data["height"] = rep.dimensions().height
data["wigth"] = rep.dimensions().width
data["mimeType"] = UTTypeCopyPreferredTagWithClass(rep.UTI(), kUTTagClassMIMEType)!.takeUnretainedValue()
if (option["thumbnail"] as! Bool) {
data["thumbnailPath"] = saveThumbnail(asset, id: id)
}
return data
}
private func saveThumbnail(asset: ALAsset, id: Int) -> NSString{
let thumbnail = asset.thumbnail().takeUnretainedValue()
let image = UIImage(CGImage: thumbnail)
let imageData = UIImageJPEGRepresentation(image, 0.8)
let cacheDirPath: NSString = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as NSString
let filePath = cacheDirPath.stringByAppendingPathComponent("\(id).jpeg")
if imageData!.writeToFile(filePath, atomically: true){
return filePath
} else {
print("error occured: Cannot save thumbnail image")
return ""
}
}
private func setType(asset:ALAsset) -> String{
let type = asset.valueForProperty(ALAssetPropertyType) as! String
if type == ALAssetTypePhoto{
return "image"
} else if type == ALAssetTypeVideo {
return "video"
}
return ""
}
// TODO: Add music and playlist and audio
private func getFilter(mediaTypes: [String]) -> ALAssetsFilter?{
if mediaTypes.contains("image"){
if mediaTypes.contains("video"){
return ALAssetsFilter.allAssets()
} else {
return ALAssetsFilter.allPhotos()
}
} else if mediaTypes.contains("video"){
return ALAssetsFilter.allVideos()
}
return nil
}
private func getIndexSet(max: Int, limit:Int, offset: Int) -> NSIndexSet?{
if offset >= max{
return nil
} else if offset + limit > max{
return NSIndexSet(indexesInRange: NSMakeRange(0, max - offset))
} else {
return NSIndexSet(indexesInRange: NSMakeRange(max - offset - limit, limit))
}
}
} | 6ea9ac8842d7ff444e6117b9f7b2a270 | 36.710059 | 142 | 0.574074 | false | false | false | false |
zhaobin19918183/zhaobinCode | refs/heads/master | HTK/HTK/Common/PDChart/PDPieChart/PDPieChart.swift | gpl-3.0 | 1 | //
// PDPieChart.swift
// Swift_iPhone_demo
//
// Created by Pandara on 14-7-7.
// Copyright (c) 2014年 Pandara. All rights reserved.
//
import UIKit
import QuartzCore
struct PieDataItem {
var description: String?
var color: UIColor?
var percentage: CGFloat!
}
let lightGreen: UIColor = UIColor(red: 69.0 / 255, green: 212.0 / 255, blue: 103.0 / 255, alpha: 1.0)
let middleGreen: UIColor = UIColor(red: 66.0 / 255, green: 187.0 / 255, blue: 102.0 / 255, alpha: 1.0)
let deepGreen: UIColor = UIColor(red: 64.0 / 255, green: 164.0 / 255, blue: 102.0 / 255, alpha: 1.0)
class PDPieChartDataItem {
//optional
var animationDur: CGFloat = 1.0
var clockWise: Bool = true
var chartStartAngle: CGFloat = CGFloat(-M_PI / 2)
var pieTipFontSize: CGFloat = 20.0
var pieTipTextColor: UIColor = UIColor.white
var pieMargin: CGFloat = 0
//required
var pieWidth: CGFloat!
var dataArray: [PieDataItem]!
init() {
}
}
class PDPieChart: PDChart {
var dataItem: PDPieChartDataItem!
init(frame: CGRect, dataItem: PDPieChartDataItem) {
super.init(frame: frame)
self.dataItem = dataItem
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func getShapeLayerWithARCPath(_ color: UIColor?, lineWidth: CGFloat, center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockWise: Bool) -> CAShapeLayer {
//layer
let pathLayer: CAShapeLayer = CAShapeLayer()
pathLayer.lineCap = kCALineCapButt
pathLayer.fillColor = UIColor.clear.cgColor
if (color != nil) {
pathLayer.strokeColor = color!.cgColor
}
pathLayer.lineWidth = self.dataItem.pieWidth
pathLayer.strokeStart = 0.0
pathLayer.strokeEnd = 1.0
pathLayer.backgroundColor = UIColor.clear.cgColor
//path
let path: UIBezierPath = UIBezierPath()
path.lineWidth = lineWidth
path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: self.dataItem.clockWise)
path.stroke()
pathLayer.path = path.cgPath
return pathLayer
}
override func strokeChart() {
var pieCenterPointArray: [CGPoint] = []
let radius: CGFloat = self.frame.size.width / 2 - self.dataItem.pieMargin - self.dataItem.pieWidth / 2
let center: CGPoint = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
let chartLayer: CAShapeLayer = CAShapeLayer()
chartLayer.backgroundColor = UIColor.clear.cgColor
self.layer.addSublayer(chartLayer)
UIGraphicsBeginImageContext(self.frame.size)
//每一段饼
var totalPercentage: CGFloat = 0.0
for i in 0 ..< self.dataItem.dataArray.count {
//data
let dataItem: PieDataItem = self.dataItem.dataArray[i]
let startAngle: CGFloat = CGFloat(M_PI * 2.0) * totalPercentage + self.dataItem.chartStartAngle
let endAngle: CGFloat = startAngle + dataItem.percentage * CGFloat(M_PI * 2)
//pie center point
// var sign: Int = self.dataItem.clockWise ? -1 : 1
let angle: Float = Float(dataItem.percentage) * Float(M_PI) * Float(2.0) / 2.0 + Float(totalPercentage) * Float(M_PI * 2.0)
let pieCenterPointX: CGFloat = center.x + radius * CGFloat(sinf(angle))
let pieCenterPointY: CGFloat = center.y - radius * CGFloat(cosf(angle))
let pieCenterPoint: CGPoint = CGPoint(x: pieCenterPointX, y: pieCenterPointY)
pieCenterPointArray.append(pieCenterPoint)
totalPercentage += dataItem.percentage
//arc path layer
let pathLayer = self.getShapeLayerWithARCPath(dataItem.color, lineWidth: self.dataItem.pieWidth, center: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockWise: true)
chartLayer.addSublayer(pathLayer)
}
//mask
let maskCenter: CGPoint = CGPoint(x: self.frame.size.width / 2.0, y: self.frame.size.height / 2)
let maskRadius: CGFloat = self.frame.size.width / 2 - self.dataItem.pieMargin - self.dataItem.pieWidth / 2
let maskStartAngle: CGFloat = -CGFloat(M_PI) / 2
let maskEndAngle: CGFloat = CGFloat(M_PI) * 2 - CGFloat(M_PI) / 2
let maskLayer: CAShapeLayer = self.getShapeLayerWithARCPath(UIColor.white, lineWidth: self.dataItem.pieWidth, center: maskCenter, radius: maskRadius, startAngle: maskStartAngle, endAngle: maskEndAngle, clockWise: true)
maskLayer.strokeStart = 0.0
maskLayer.strokeEnd = 1.0
let animation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = CFTimeInterval(self.dataItem.animationDur)
animation.fromValue = 0.0
animation.toValue = 1.0
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.isRemovedOnCompletion = true
maskLayer.add(animation, forKey: "maskAnimation")
self.layer.mask = maskLayer
UIGraphicsEndImageContext()
//pie tip
for i in 0 ..< pieCenterPointArray.count {
let dataItem: PieDataItem = self.dataItem.dataArray[i]
let pieTipLabel: UILabel = UILabel()
pieTipLabel.backgroundColor = UIColor.clear;
pieTipLabel.font = UIFont.systemFont(ofSize: self.dataItem.pieTipFontSize)
pieTipLabel.textColor = self.dataItem.pieTipTextColor
if (dataItem.description != nil) {
pieTipLabel.text = dataItem.description
} else {
pieTipLabel.text = "\(dataItem.percentage * 100)%"
}
pieTipLabel.sizeToFit()
pieTipLabel.alpha = 0.0
pieTipLabel.center = pieCenterPointArray[i]
UIView.animate(withDuration: 0.5, delay: TimeInterval(self.dataItem.animationDur), options: UIViewAnimationOptions(), animations:{
() -> Void in
pieTipLabel.alpha = 1.0
}, completion: {
(completion: Bool) -> Void in
return
})
self.addSubview(pieTipLabel)
}
}
override func draw(_ rect: CGRect)
{
super.draw(rect)
}
}
| 519228e9fd76422f35418634a42a9d0d | 35.815642 | 226 | 0.620941 | false | false | false | false |
peferron/algo | refs/heads/master | EPI/Strings/Convert from Roman to decimal/swift/main.swift | mit | 1 | let romanValues: [Character: Int] = [
"M": 1000,
"D": 500,
"C": 100,
"L": 50,
"X": 10,
"V": 5,
"I": 1,
]
public func toInt(roman: String) -> Int {
var max = 0
var sum = 0
for character in roman.reversed() {
let value = romanValues[character]!
if value < max {
sum -= value
} else {
sum += value
max = value
}
}
return sum
// Alternative below, that takes 25s to compile with Swift 3.1. Can be made faster by splitting
// the chain into pieces, but hopefully it'll be fixed in a future version of the compiler.
// return roman
// .reversed()
// .map { romanValues[$0]! }
// .reduce((sum: 0, max: 0)) { (acc, value) in
// value < acc.max ? (acc.sum - value, acc.max) : (acc.sum + value, value)
// }
// .sum
}
| 0b93ac4b1ba27050bba9763152ee467b | 23.75 | 99 | 0.497194 | false | false | false | false |
Johnykutty/SwiftLint | refs/heads/master | Source/SwiftLintFramework/Rules/LegacyConstantRuleExamples.swift | mit | 2 | //
// LegacyConstantRuleExamples.swift
// SwiftLint
//
// Created by Aaron McTavish on 01/16/17.
// Copyright © 2017 Realm. All rights reserved.
//
import Foundation
internal struct LegacyConstantRuleExamples {
static let swift2NonTriggeringExamples = commonNonTriggeringExamples
static let swift3NonTriggeringExamples = commonNonTriggeringExamples + ["CGFloat.pi", "Float.pi"]
static let swift2TriggeringExamples = commonTriggeringExamples
static let swift3TriggeringExamples = commonTriggeringExamples + ["↓CGFloat(M_PI)", "↓Float(M_PI)"]
static let swift2Corrections = commonCorrections
static let swift3Corrections: [String: String] = {
var corrections = commonCorrections
["↓CGFloat(M_PI)": "CGFloat.pi",
"↓Float(M_PI)": "Float.pi",
"↓CGFloat(M_PI)\n↓Float(M_PI)\n": "CGFloat.pi\nFloat.pi\n"].forEach { key, value in
corrections[key] = value
}
return corrections
}()
static let swift2Patterns = commonPatterns
static let swift3Patterns: [String: String] = {
var patterns = commonPatterns
["CGFloat\\(M_PI\\)": "CGFloat.pi",
"Float\\(M_PI\\)": "Float.pi"].forEach { key, value in
patterns[key] = value
}
return patterns
}()
private static let commonNonTriggeringExamples = [
"CGRect.infinite",
"CGPoint.zero",
"CGRect.zero",
"CGSize.zero",
"NSPoint.zero",
"NSRect.zero",
"NSSize.zero",
"CGRect.null"
]
private static let commonTriggeringExamples = [
"↓CGRectInfinite",
"↓CGPointZero",
"↓CGRectZero",
"↓CGSizeZero",
"↓NSZeroPoint",
"↓NSZeroRect",
"↓NSZeroSize",
"↓CGRectNull"
]
private static let commonCorrections = [
"↓CGRectInfinite": "CGRect.infinite",
"↓CGPointZero": "CGPoint.zero",
"↓CGRectZero": "CGRect.zero",
"↓CGSizeZero": "CGSize.zero",
"↓NSZeroPoint": "NSPoint.zero",
"↓NSZeroRect": "NSRect.zero",
"↓NSZeroSize": "NSSize.zero",
"↓CGRectNull": "CGRect.null",
"↓CGRectInfinite\n↓CGRectNull\n": "CGRect.infinite\nCGRect.null\n"
]
private static let commonPatterns = [
"CGRectInfinite": "CGRect.infinite",
"CGPointZero": "CGPoint.zero",
"CGRectZero": "CGRect.zero",
"CGSizeZero": "CGSize.zero",
"NSZeroPoint": "NSPoint.zero",
"NSZeroRect": "NSRect.zero",
"NSZeroSize": "NSSize.zero",
"CGRectNull": "CGRect.null"
]
}
| a1561f5c368430acffdd27a70aa3c44c | 28.191011 | 103 | 0.602002 | false | false | false | false |
JeanetteMueller/fyydAPI | refs/heads/master | fyydAPI/Classes/FyydCuration.swift | mit | 1 | //
// FyydCuration.swift
// Podcat 2
//
// Created by Jeanette Müller on 10.04.17.
// Copyright © 2017 Jeanette Müller. All rights reserved.
//
import Foundation
public class FyydCuration {
private let data:[String:Any]
public var fyydId:Int32{
get{
if let value = data["id"] as? Int32{
return value
}
return -1
}
}
public var title:String?{
get{
if let value = data["title"] as? String{
return value
}
return nil
}
}
public var desciption:String?{
get{
if let value = data["desciption"] as? String{
return value
}
return nil
}
}
public var layoutImageURL: String?{
get{
if let value = data["layoutImageURL"] as? String{
return value
}
return nil
}
}
public var thumbImageURL: String?{
get{
if let value = data["thumbImageURL"] as? String{
return value
}
return nil
}
}
public var microImageURL: String?{
get{
if let value = data["microImageURL"] as? String{
return value
}
return nil
}
}
public var isPublic: Bool{
get{
if let pub = data["public"] as? Int{
return pub == 1
}
return false
}
}
public var url: String{
get{
if let url = data["url"] as? String{
return url
}
return ""
}
}
public var xmlURL: String{
get{
if let url = data["xmlURL"] as? String{
return url
}
return ""
}
}
public init(_ data:[String:Any]){
self.data = data
}
}
| 46ebf08700e9f5ffe5b6b7cbbffe398c | 19.70297 | 61 | 0.412243 | false | false | false | false |
nevyn/SPAsync | refs/heads/master | Swift/Task.swift | mit | 1 | //
// Task.swift
// SPAsync
//
// Created by Joachim Bengtsson on 2014-08-14.
// Copyright (c) 2014 ThirdCog. All rights reserved.
//
import Foundation
public class Task<T> : Cancellable, Equatable
{
// MARK: Public interface: Callbacks
public func addCallback(callback: (T -> Void)) -> Self
{
return addCallback(on:dispatch_get_main_queue(), callback: callback)
}
public func addCallback(on queue: dispatch_queue_t, callback: (T -> Void)) -> Self
{
synchronized(self.callbackLock) {
if self.isCompleted {
if self.completedError == nil {
dispatch_async(queue) {
callback(self.completedValue!)
}
}
} else {
self.callbacks.append(TaskCallbackHolder(on: queue, callback: callback))
}
}
return self
}
public func addErrorCallback(callback: (NSError! -> Void)) -> Self
{
return addErrorCallback(on:dispatch_get_main_queue(), callback:callback)
}
public func addErrorCallback(on queue: dispatch_queue_t, callback: (NSError! -> Void)) -> Self
{
synchronized(self.callbackLock) {
if self.isCompleted {
if self.completedError != nil {
dispatch_async(queue) {
callback(self.completedError!)
}
}
} else {
self.errbacks.append(TaskCallbackHolder(on: queue, callback: callback))
}
}
return self
}
public func addFinallyCallback(callback: (Bool -> Void)) -> Self
{
return addFinallyCallback(on:dispatch_get_main_queue(), callback:callback)
}
public func addFinallyCallback(on queue: dispatch_queue_t, callback: (Bool -> Void)) -> Self
{
synchronized(self.callbackLock) {
if(self.isCompleted) {
dispatch_async(queue, { () -> Void in
callback(self.isCancelled)
})
} else {
self.finallys.append(TaskCallbackHolder(on: queue, callback: callback))
}
}
return self
}
// MARK: Public interface: Advanced callbacks
public func then<T2>(worker: (T -> T2)) -> Task<T2>
{
return then(on:dispatch_get_main_queue(), worker: worker)
}
public func then<T2>(on queue:dispatch_queue_t, worker: (T -> T2)) -> Task<T2>
{
let source = TaskCompletionSource<T2>();
let then = source.task;
self.childTasks.append(then)
self.addCallback(on: queue, callback: { (value: T) -> Void in
let result = worker(value)
source.completeWithValue(result)
})
self.addErrorCallback(on: queue, callback: { (error: NSError!) -> Void in
source.failWithError(error)
})
return then
}
public func then<T2>(chainer: (T -> Task<T2>)) -> Task<T2>
{
return then(on:dispatch_get_main_queue(), chainer: chainer)
}
public func then<T2>(on queue:dispatch_queue_t, chainer: (T -> Task<T2>)) -> Task<T2>
{
let source = TaskCompletionSource<T2>();
let chain = source.task;
self.childTasks.append(chain)
self.addCallback(on: queue, callback: { (value: T) -> Void in
let workToBeProvided : Task<T2> = chainer(value)
chain.childTasks.append(workToBeProvided)
source.completeWithTask(workToBeProvided)
})
self.addErrorCallback(on: queue, callback: { (error: NSError!) -> Void in
source.failWithError(error)
})
return chain;
}
/// Transforms Task<Task<T2>> into a Task<T2> asynchronously
// dunno how to do this with static typing...
/*public func chain<T2>() -> Task<T2>
{
return self.then<T.T>({(value: Task<T2>) -> T2 in
return value
})
}*/
// MARK: Public interface: Cancellation
public func cancel()
{
var shouldCancel = false
synchronized(callbackLock) { () -> Void in
shouldCancel = !self.isCancelled
self.isCancelled = true
}
if shouldCancel {
self.source!.cancel()
// break any circular references between source<> task by removing
// callbacks and errbacks which might reference the source
synchronized(callbackLock) {
self.callbacks.removeAll()
self.errbacks.removeAll()
for holder in self.finallys {
dispatch_async(holder.callbackQueue, { () -> Void in
holder.callback(true)
})
}
self.finallys.removeAll()
}
}
for child in childTasks {
child.cancel()
}
}
public private(set) var isCancelled = false
// MARK: Public interface: construction
class func performWork(on queue:dispatch_queue_t, work: Void -> T) -> Task<T>
{
let source = TaskCompletionSource<T>()
dispatch_async(queue) {
let value = work()
source.completeWithValue(value)
}
return source.task
}
class func fetchWork(on queue:dispatch_queue_t, work: Void -> Task<T>) -> Task<T>
{
let source = TaskCompletionSource<T>()
dispatch_async(queue) {
let value = work()
source.completeWithTask(value)
}
return source.task
}
class func delay(interval: NSTimeInterval, value : T) -> Task<T>
{
let source = TaskCompletionSource<T>()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
source.completeWithValue(value)
}
return source.task
}
class func completedTask(value: T) -> Task<T>
{
let source = TaskCompletionSource<T>()
source.completeWithValue(value)
return source.task
}
class func failedTask(error: NSError!) -> Task<T>
{
let source = TaskCompletionSource<T>()
source.failWithError(error)
return source.task
}
// MARK: Public interface: other convenience
class func awaitAll(tasks: [Task]) -> Task<[Any]>
{
let source = TaskCompletionSource<[Any]>()
if tasks.count == 0 {
source.completeWithValue([])
return source.task;
}
var values : [Any] = []
var remainingTasks : [Task] = tasks
var i : Int = 0
for task in tasks {
source.task.childTasks.append(task)
weak var weakTask = task
values.append(NSNull())
task.addCallback(on: dispatch_get_main_queue(), callback: { (value: Any) -> Void in
values[i] = value
remainingTasks.removeAtIndex(find(remainingTasks, weakTask!)!)
if remainingTasks.count == 0 {
source.completeWithValue(values)
}
}).addErrorCallback(on: dispatch_get_main_queue(), callback: { (error: NSError!) -> Void in
if remainingTasks.count == 0 {
// ?? how could this happen?
return
}
remainingTasks.removeAtIndex(find(remainingTasks, weakTask!)!)
source.failWithError(error)
for task in remainingTasks {
task.cancel()
}
remainingTasks.removeAll()
values.removeAll()
}).addFinallyCallback(on: dispatch_get_main_queue(), callback: { (canceled: Bool) -> Void in
if canceled {
source.task.cancel()
}
})
i++;
}
return source.task;
}
// MARK: Private implementation
var callbacks : [TaskCallbackHolder<T -> Void>] = []
var errbacks : [TaskCallbackHolder<NSError! -> Void>] = []
var finallys : [TaskCallbackHolder<Bool -> Void>] = []
var callbackLock : NSLock = NSLock()
var isCompleted = false
var completedValue : T? = nil
var completedError : NSError? = nil
weak var source : TaskCompletionSource<T>?
var childTasks : [Cancellable] = []
internal init()
{
// temp
}
internal init(source: TaskCompletionSource<T>)
{
self.source = source
}
func completeWithValue(value: T)
{
assert(self.isCompleted == false, "Can't complete a task twice")
if self.isCompleted {
return
}
if self.isCancelled {
return
}
synchronized(callbackLock) {
self.isCompleted = true
self.completedValue = value
let copiedCallbacks = self.callbacks
let copiedFinallys = self.finallys
for holder in copiedCallbacks {
dispatch_async(holder.callbackQueue) {
if !self.isCancelled {
holder.callback(value)
}
}
}
for holder in copiedFinallys {
dispatch_async(holder.callbackQueue) {
holder.callback(self.isCancelled)
}
}
self.callbacks.removeAll()
self.errbacks.removeAll()
self.finallys.removeAll()
}
}
func failWithError(error: NSError!)
{
assert(self.isCompleted == false, "Can't complete a task twice")
if self.isCompleted {
return
}
if self.isCancelled {
return
}
synchronized(callbackLock) {
self.isCompleted = true
self.completedError = error
let copiedErrbacks = self.errbacks
let copiedFinallys = self.finallys
for holder in copiedErrbacks {
dispatch_async(holder.callbackQueue) {
if !self.isCancelled {
holder.callback(error)
}
}
}
for holder in copiedFinallys {
dispatch_async(holder.callbackQueue) {
holder.callback(self.isCancelled)
}
}
self.callbacks.removeAll()
self.errbacks.removeAll()
self.finallys.removeAll()
}
}
}
public func ==<T>(lhs: Task<T>, rhs: Task<T>) -> Bool
{
return lhs === rhs
}
// MARK:
public class TaskCompletionSource<T> : NSObject {
public override init()
{
}
public let task = Task<T>()
private var cancellationHandlers : [(() -> Void)] = []
/** Signal successful completion of the task to all callbacks */
public func completeWithValue(value: T)
{
self.task.completeWithValue(value)
}
/** Signal failed completion of the task to all errbacks */
public func failWithError(error: NSError!)
{
self.task.failWithError(error)
}
/** Signal completion for this source's task based on another task. */
public func completeWithTask(task: Task<T>)
{
task.addCallback(on:dispatch_get_global_queue(0, 0), callback: {
(v: T) -> Void in
self.task.completeWithValue(v)
}).addErrorCallback(on:dispatch_get_global_queue(0, 0), callback: {
(e: NSError!) -> Void in
self.task.failWithError(e)
})
}
/** If the task is cancelled, your registered handlers will be called. If you'd rather
poll, you can ask task.cancelled. */
public func onCancellation(callback: () -> Void)
{
synchronized(self) {
self.cancellationHandlers.append(callback)
}
}
func cancel() {
var handlers: [()->()] = []
synchronized(self) { () -> Void in
handlers = self.cancellationHandlers
}
for callback in handlers {
callback()
}
}
}
protocol Cancellable {
func cancel() -> Void
}
class TaskCallbackHolder<T>
{
init(on queue:dispatch_queue_t, callback: T) {
callbackQueue = queue
self.callback = callback
}
var callbackQueue : dispatch_queue_t
var callback : T
}
func synchronized(on: AnyObject, closure: () -> Void) {
objc_sync_enter(on)
closure()
objc_sync_exit(on)
}
func synchronized(on: NSLock, closure: () -> Void) {
on.lock()
closure()
on.unlock()
}
func synchronized<T>(on: NSLock, closure: () -> T) -> T {
on.lock()
let r = closure()
on.unlock()
return r
} | 1f24475013928f12040ac855ac14da7c | 22.068282 | 133 | 0.664343 | false | false | false | false |
Yoseob/Trevi | refs/heads/master | Trevi/Utility/Json.swift | apache-2.0 | 1 | //
// Json.swift
// Trevi
//
// Created by LeeYoseob on 2015. 12. 9..
// Copyright © 2015년 LeeYoseob. All rights reserved.
//
import Foundation
public enum JSON {
case Array( [JSON] )
case Dictionary( [Swift.String:JSON] )
case String( Swift.String )
case Number( Float )
case Null
}
extension JSON {
public var string: Swift.String? {
switch self {
case .String(let s):
return s
default:
return nil
}
}
public var int: Int? {
switch self {
case .Number(let d):
return Int ( d )
default:
return nil
}
}
public var float: Float? {
switch self {
case .Number(let d):
return d
default:
return nil
}
}
public var bool: Bool? {
switch self {
case .Number(let d):
return (d != 0)
default:
return nil
}
}
public var isNull: Bool {
switch self {
case Null:
return true
default:
return false
}
}
public func wrap ( json: AnyObject ) -> JSON {
if let str = json as? Swift.String {
return .String ( str )
}
if let num = json as? NSNumber {
return .Number ( num.floatValue )
}
if let dictionary = json as? [Swift.String:AnyObject] {
return .Dictionary ( internalConvertDictionary ( dictionary ) )
}
if let array = json as? [AnyObject] {
return .Array ( internalConvertArray ( array ) )
}
assert ( json is NSNull, "Unsupported Type" )
return .Null
}
private func internalConvertDictionary ( dic: [Swift.String:AnyObject] ) -> [Swift.String:JSON]! {
// var newDictionary = [:]
// for (k,v) in dic{
// switch v{
// case let arr as [AnyObject]:
// var newarr = internalConvertArray(arr)
//
// print(arr)
// case let dic as [Swift.String: AnyObject]:
// internalConvertDictionary(dic)
// default:
// wrap(v)
// break
//
// }
// }
return nil;
}
private func internalConvertArray ( arr: [AnyObject] ) -> [JSON]! {
return nil
}
}
| 79d058c401097790420d174d85947c56 | 21.345794 | 102 | 0.488499 | false | false | false | false |
tellowkrinkle/Sword | refs/heads/master | Sources/Sword/Gateway/GatewayHandler.swift | mit | 1 | //
// GatewayHandler.swift
// Sword
//
// Created by Alejandro Alonso
// Copyright © 2017 Alejandro Alonso. All rights reserved.
//
import Foundation
/// Gateway Handler
extension Shard {
/**
Handles all gateway events (except op: 0)
- parameter payload: Payload sent with event
*/
func handleGateway(_ payload: Payload) {
guard let op = OP(rawValue: payload.op) else {
self.sword.log("Received unknown gateway\nOP: \(payload.op)\nData: \(payload.d)")
return
}
switch op {
/// OP: 1
case .heartbeat:
let heartbeat = Payload(
op: .heartbeat,
data: self.lastSeq ?? NSNull()
).encode()
self.send(heartbeat)
/// OP: 11
case .heartbeatACK:
self.heartbeat?.received = true
/// OP: 10
case .hello:
self.heartbeat = Heartbeat(self.session!, "heartbeat.shard.\(self.id)", interval: (payload.d as! [String: Any])["heartbeat_interval"] as! Int)
self.heartbeat?.received = true
self.heartbeat?.send()
guard !self.isReconnecting else {
self.isReconnecting = false
var data: [String: Any] = ["token": self.sword.token, "session_id": self.sessionId!, "seq": NSNull()]
if let lastSeq = self.lastSeq {
data["seq"] = lastSeq
}
let payload = Payload(
op: .resume,
data: data
).encode()
self.send(payload)
return
}
self.identify()
/// OP: 9
case .invalidSession:
self.isReconnecting = false
self.reconnect()
/// OP: 7
case .reconnect:
self.isReconnecting = true
self.reconnect()
/// Others~~~
default:
break
}
}
}
| 9a9d3f862fc866cd1ddad12017ea8834 | 20.170732 | 148 | 0.567396 | false | false | false | false |
JamieScanlon/AugmentKit | refs/heads/master | AugmentKit/AKCore/Anchors/AugmentedSurfaceAnchor.swift | mit | 1 | //
// AugmentedSurfaceAnchor.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2018 JamieScanlon
//
// 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 ARKit
import Foundation
import MetalKit
import simd
/**
A generic implementation of `AKAugmentedSurfaceAnchor` that renders a `MDLTexture` on a simple plane with a given extent
*/
open class AugmentedSurfaceAnchor: AKAugmentedSurfaceAnchor {
/**
A type string. Always returns "AugmentedSurface"
*/
public static var type: String {
return "AugmentedSurface"
}
/**
The location in the ARWorld
*/
public var worldLocation: AKWorldLocation
/**
The heading in the ARWorld. Defaults to `NorthHeading()`
*/
public var heading: AKHeading = NorthHeading()
/**
The `MDLAsset` associated with the entity.
*/
public var asset: MDLAsset
/**
A unique, per-instance identifier
*/
public var identifier: UUID?
/**
An array of `AKEffect` objects that are applied by the renderer
*/
public var effects: [AnyEffect<Any>]?
/**
Specified a perfered renderer to use when rendering this enitity. Most will use the standard PBR renderer but some entities may prefer a simpiler renderer when they are not trying to achieve the look of real-world objects. Defaults to `ShaderPreference.pbr`
*/
public var shaderPreference: ShaderPreference = .pbr
/**
Indicates whether this geometry participates in the generation of augmented shadows. Since this is an augmented geometry, it does generate shadows.
*/
public var generatesShadows: Bool = true
/**
If `true`, the current base color texture of the entity has changed since the last time it was rendered and the pixel data needs to be updated. This flag can be used to achieve dynamically updated textures for rendered objects.
*/
public var needsColorTextureUpdate: Bool = false
/// If `true` the underlying mesh for this geometry has changed and the renderer needs to update. This can be used to achieve dynamically generated geometries that change over time.
public var needsMeshUpdate: Bool = false
/**
An `ARAnchor` that will be tracked in the AR world by `ARKit`
*/
public var arAnchor: ARAnchor?
/**
Initialize a new object with a `MDLTexture` and an extent representing the size at a `AKWorldLocation` and AKHeading using a `MTKMeshBufferAllocator` for allocating the geometry
- Parameters:.
- withTexture: The `MDLTexture` containing the image texture
- extent: The size of the geometry in meters
- at: The location of the anchor
- heading: The heading for the anchor
- withAllocator: A `MTKMeshBufferAllocator` with wich to create the plane geometry
*/
public init(withTexture texture: MDLTexture, extent: SIMD3<Float>, at location: AKWorldLocation, heading: AKHeading? = nil, withAllocator metalAllocator: MTKMeshBufferAllocator? = nil) {
self.texture = texture
self.extent = extent
self.metalAllocator = metalAllocator
self.asset = MDLAsset(bufferAllocator: metalAllocator)
self.worldLocation = location
if let heading = heading {
self.heading = heading
}
}
/**
Sets a new `arAnchor`
- Parameters:
- _: An `ARAnchor`
*/
public func setARAnchor(_ arAnchor: ARAnchor) {
self.arAnchor = arAnchor
if identifier == nil {
identifier = arAnchor.identifier
}
worldLocation.transform = arAnchor.transform
let mesh = MDLMesh(planeWithExtent: extent, segments: SIMD2<UInt32>(1, 1), geometryType: .triangles, allocator: metalAllocator)
let scatteringFunction = MDLScatteringFunction()
let material = MDLMaterial(name: "Default AugmentedSurfaceAnchor baseMaterial", scatteringFunction: scatteringFunction)
let textureSampler = MDLTextureSampler()
textureSampler.texture = texture
let property = MDLMaterialProperty(name: "baseColor", semantic: MDLMaterialSemantic.baseColor, textureSampler: textureSampler)
material.setProperty(property)
for submesh in mesh.submeshes! {
if let submesh = submesh as? MDLSubmesh {
submesh.material = material
}
}
asset.add(mesh)
}
// MARK: Private
private var texture: MDLTexture
private var extent: SIMD3<Float>
private var metalAllocator: MTKMeshBufferAllocator?
}
/// :nodoc:
extension AugmentedSurfaceAnchor: CustomDebugStringConvertible, CustomStringConvertible {
/// :nodoc:
public var description: String {
return debugDescription
}
/// :nodoc:
public var debugDescription: String {
let myDescription = "<AugmentedSurfaceAnchor: \(Unmanaged.passUnretained(self).toOpaque())> worldLocation: \(worldLocation), identifier:\(identifier?.uuidString ?? "None"), effects: \(effects?.debugDescription ?? "None"), arAnchor: \(arAnchor?.debugDescription ?? "None"), asset: \(asset)"
return myDescription
}
}
| 2f95df1d1aa6f3c0ccca29c58ef3feca | 39.584416 | 297 | 0.6904 | false | false | false | false |
cdtschange/SwiftMKit | refs/heads/master | SwiftMKit/Data/Local/Cache/CachePool.swift | mit | 1 | //
// CachePool.swift
// SwiftMKitDemo
//
// Created by Mao on 4/26/16.
// Copyright © 2016 cdts. All rights reserved.
//
import Foundation
import PINCache
import CocoaLumberjack
public struct CachePoolConstant {
// 取手机剩余空间 DefaultCapacity = MIN(剩余空间, 100M)
static let DefaultCapacity: Int64 = 100*1024*1024 // 默认缓存池空间 100M
static let DefaultCachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! + "/"
static let MimeType4Image = "image"
}
@objc(CacheModel)private class CacheModel : NSObject, NSCoding, CacheModelProtocol {
var key: String = ""
var name: String = ""
var filePath: URL?
var size: Int64 = 0
var mimeType: String = ""
var createTime: TimeInterval = 0
var lastVisitTime: TimeInterval = 0
var expireTime: TimeInterval = 0
@objc func encode(with aCoder: NSCoder){
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.key, forKey: "key")
aCoder.encode(self.filePath, forKey: "filePath")
aCoder.encode(self.createTime, forKey: "createTime")
aCoder.encode(self.size, forKey: "size")
aCoder.encode(self.mimeType, forKey: "mimeType")
}
@objc required init(coder aDecoder: NSCoder) {
super.init()
self.name = aDecoder.decodeObject(forKey: "name") as! String
self.key = aDecoder.decodeObject(forKey: "key") as! String
self.filePath = aDecoder.decodeObject(forKey: "filePath") as? URL
self.createTime = aDecoder.decodeObject(forKey: "createTime") as! TimeInterval
self.size = aDecoder.decodeInt64(forKey: "size")
self.mimeType = aDecoder.decodeObject(forKey: "mimeType") as! String
}
override init() {
super.init()
}
override var description: String {
return "\(key) \(name) \(createTime) \(size)"
}
}
/// 缓存池:用于存储文件
open class CachePool: CachePoolProtocol {
let fileManager = FileManager.default
var cache: PINCache?
open var namespace: String = "CachePool"
open var capacity: Int64 = CachePoolConstant.DefaultCapacity
open var size: Int64 {
// 遍历配置文件
// 取出缓存字典
let cachedDict = (cache?.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
var cachedSize: Int64 = 0
for value in cachedDict.values {
cachedSize += value.size
}
return cachedSize
}
open var basePath: URL?
init() {
cache = PINCache(name: "Config", rootPath: cachePath())
createFolder(forName: namespace, baseUrl: baseCacheUrl())
}
init(namespace: String?) {
self.namespace = namespace ?? self.namespace
cache = PINCache(name: "Config", rootPath: cachePath())
createFolder(forName: self.namespace, baseUrl: baseCacheUrl())
}
open func addCache(_ data: Data, name: String?) -> String {
return addCache(data, name: name, mimeType: nil)
}
open func addCache(_ image: UIImage, name: String?) -> String {
let data = UIImagePNGRepresentation(image)
return self.addCache(data!, name: name, mimeType: CachePoolConstant.MimeType4Image)
}
open func addCache(_ filePath: URL, name: String?) -> String {
// 拷贝文件
// 生成目标路径
let timestamp = Date().timeIntervalSince1970
let nameTime = ( name ?? "" ) + "\(timestamp)"
let encryptName = nameTime.md5
let dir = self.cachePath()
let destFilePath:String = dir + encryptName
try! fileManager.copyItem(atPath: filePath.path, toPath: destFilePath)
DDLogInfo("filePath: \(filePath.path)")
DDLogInfo("destFilePath: \(destFilePath)")
// 获取文件信息
if let attrs = self.getFileAttributes(withFilePath: destFilePath) {
DDLogInfo("file info:\(attrs)")
// 更新配置文件
let num = attrs[FileAttributeKey.size] as? NSNumber ?? 0
let size = num.int64Value
return self.updateConfig(forName: name, timestamp:timestamp, size: size)
}
// TODO: 返回值需要思考一下
return encryptName
}
open func getCache(forKey key: String) -> AnyObject? {
let dir = self.cachePath()
let filePath:String = dir + key
DDLogInfo("objectForName filePath:" + filePath)
let cachedDict = (cache!.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
if let obj = cachedDict[key] {
if obj.mimeType == CachePoolConstant.MimeType4Image {
if let data = fileManager.contents(atPath: filePath) {
return UIImage(data: data)
} else {
return nil
}
}
return fileManager.contents(atPath: filePath) as AnyObject?
}
return fileManager.contents(atPath: filePath) as AnyObject?
}
open func all() -> [CacheModelProtocol]? {
let cachedDict = (cache!.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
var cacheModelList:[CacheModelProtocol] = []
for obj in cachedDict.values {
cacheModelList.append(obj)
}
return cacheModelList
}
open func removeCache(forKey key: String) -> Bool {
var cachedDict = (cache!.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
if let obj = cachedDict[key] {
print(obj)
// 从沙河中删除
let filePathStr = cachePath() + obj.key
if fileManager.fileExists(atPath: filePathStr) {
try! fileManager.removeItem(atPath: filePathStr)
}
// 从配置文件中删除
cachedDict.removeValue(forKey: key)
cacheDict = cachedDict
return true
}
return false
}
@discardableResult
open func clear() -> Bool {
let cachepath = cachePath()
if fileManager.fileExists(atPath: cachepath) {
let fileArray:[AnyObject]? = fileManager.subpaths(atPath: cachepath) as [AnyObject]?
for fn in fileArray!{
let subpath = cachepath + "/\(fn)";
var flag: ObjCBool = false
if fileManager.fileExists(atPath: subpath, isDirectory: &flag) {
if flag.boolValue {
// 是文件夹
continue
} else {
try! fileManager.removeItem(atPath: subpath)
}
}
// if fileManager.fileExistsAtPath(subpath) {
// try! fileManager.removeItemAtPath(subpath)
// }
}
// try! fileManager.removeItemAtPath(cachepath)
// try! fileManager.createDirectoryAtPath(cachepath, withIntermediateDirectories: true, attributes: nil)
// 清空缓存配置文件
cacheDict?.removeAll()
// 重新生成配置文件
cache = PINCache(name: "Config", rootPath: cachePath())
createFolder(forName: namespace, baseUrl: baseCacheUrl())
return true
}
return size == 0
}
// 缓存相关
let cacheDictKey = "CacheModels"
fileprivate var cacheDict: Dictionary<String, CacheModel>? {
get {
return cache!.object(forKey: cacheDictKey) as? Dictionary<String, CacheModel>
}
set {
if let value = newValue {
cache!.setObject(value as NSCoding, forKey: cacheDictKey)
} else {
cache!.removeObject(forKey: cacheDictKey)
}
}
}
}
extension CachePool {
fileprivate func addCache(_ data: Data, name: String?, mimeType: String?) -> String {
// 更新配置文件
let timestamp = Date().timeIntervalSince1970
let encryptName = self.updateConfig(forName: name, timestamp:timestamp, size: Int64(data.count), mimeType: mimeType)
// 保存对象到沙盒
let dir = self.cachePath()
let filePath:String = dir + encryptName
let _ = Async.background {
if (try? data.write(to: URL(fileURLWithPath: filePath), options: [.atomic])) != nil {
DDLogDebug("文件写入成功:\(filePath)")
} else {
DDLogDebug("文件写入失败!")
}
}
return encryptName
}
/// 存储文件之前,判断是否有足够的空间存储
///
/// :param: size 即将存储的文件大小
fileprivate func preparePool(forSize size: Int64) -> Bool {
// 比较 设备剩余可用空间 & 文件大小
var leftCapacity = capacity - self.size
leftCapacity = min(UIDevice.freeDiskSpaceInBytes, leftCapacity) // 取出最小可用空间
DDLogVerbose("可用空间:\(leftCapacity), 文件大小:\(size), 正常保存")
if leftCapacity < size {
// 读取配置文件,删除已过期、即将过期、最近未访问的文件,直至可以保存为止
DDLogInfo("需要删除文件后保存")
leftCapacity = self.cleanDisk(leftCapacity: leftCapacity, size: size)
}
return size <= leftCapacity
}
/// 更新配置文件
///
/// :param: name 文件名
/// :param: size 文件大小
///
/// :returns: 加密后的文件名
fileprivate func updateConfig(forName name: String?, timestamp: TimeInterval, size: Int64) -> String {
return updateConfig(forName: name, timestamp: timestamp, size: size, mimeType: nil)
}
fileprivate func updateConfig(forName name: String?, timestamp: TimeInterval, size: Int64, mimeType: String?) -> String {
// 核心方法:判断是否有足够的空间存储
if !(self.preparePool(forSize: size)) {
return ""
}
let cacheObj = CacheModel()
// 已缓存的字典
var cachedDict = (cache!.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
let nameTime = (name ?? "") + "\(timestamp)"
let encryptName = nameTime.md5
cacheObj.name = name ?? ""
cacheObj.key = encryptName
cacheObj.createTime = timestamp
cacheObj.mimeType = (mimeType ?? "")
cacheObj.size = size
cacheObj.filePath = URL(fileURLWithPath: (cachePath() + encryptName))
cachedDict[encryptName] = cacheObj
// 同步到PINCache
cacheDict = cachedDict
return encryptName
}
/// 创建文件夹
fileprivate func createFolder(forName name: String, baseUrl: URL) {
let folder = baseUrl.appendingPathComponent(name, isDirectory: true)
let exist = fileManager.fileExists(atPath: folder.path)
if !exist {
try! fileManager.createDirectory(at: folder, withIntermediateDirectories: true, attributes: nil)
DDLogVerbose("缓存文件夹:" + folder.path)
}
}
/// 获取文件属性
///
/// :param: filePath 文件路径
fileprivate func getFileAttributes(withFilePath filePath: String) -> [FileAttributeKey: Any]? {
let attributes = try? fileManager.attributesOfItem(atPath: filePath)
return attributes
}
fileprivate func cachePath() -> String {
let baseStr = ((basePath) != nil) ? basePath!.path : CachePoolConstant.DefaultCachePath
return baseStr + "/" + namespace + "/"
}
fileprivate func baseCacheUrl() -> URL {
let baseUrl = ((basePath) != nil) ? basePath! : URL(fileURLWithPath: CachePoolConstant.DefaultCachePath)
self.basePath = baseUrl
return baseUrl
}
/// 设备剩余空间不足时,删除本地缓存文件
///
/// :param: leftCapacity 剩余空间
/// :param: size 至少需要的空间
fileprivate func cleanDisk(leftCapacity lastSize: Int64, size: Int64) -> Int64 {
var leftCapacity = lastSize
// 遍历配置文件
// 取出缓存字典
var cachedDict = (cache!.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
DDLogVerbose("排序前:\(cachedDict)")
// 升序,最新的数据在最下面(目的:删除日期最小的旧数据)
let sortedList = cachedDict.sorted { $0.1.createTime < $1.1.createTime }
DDLogVerbose("=========================================================")
DDLogVerbose("排序后:\(sortedList)")
// obj 是一个元组类型
for (key, model) in sortedList {
// 从沙河中删除
let filePathStr = cachePath() + key
if fileManager.fileExists(atPath: filePathStr) {
try! fileManager.removeItem(atPath: filePathStr)
}
// 从配置文件中删除
cachedDict.removeValue(forKey: key)
cacheDict = cachedDict
// 更新剩余空间大小
leftCapacity += model.size
DDLogVerbose("remove=\(key), save=\(model.size) byte lastSize=\(leftCapacity) size=\(size)")
if leftCapacity > size {
break
}
}
return leftCapacity
}
}
| 37fb058fc99892d1a792f82f49660496 | 36.002941 | 125 | 0.585883 | false | false | false | false |
DSanzh/GuideMe-iOS | refs/heads/master | Pods/EasyPeasy/EasyPeasy/Item.swift | mit | 1 | // The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
var easy_attributesReference: Int = 0
/**
Typealias of a tuple grouping an array of `NSLayoutConstraints`
to activate and another array of `NSLayoutConstraints` to
deactivate
*/
typealias ActivationGroup = ([NSLayoutConstraint], [NSLayoutConstraint])
/**
Protocol enclosing the objects a constraint will apply to
*/
public protocol Item: NSObjectProtocol {
/// Array of constraints installed in the current `Item`
var constraints: [NSLayoutConstraint] { get }
/// Owning `UIView` for the current `Item`. The concept varies
/// depending on the class conforming the protocol
var owningView: View? { get }
}
public extension Item {
/// Access to **EasyPeasy** `layout`, `reload` and `clear`operations
public var easy: EasyPeasy {
return EasyPeasy(item: self)
}
/**
This method will trigger the recreation of the constraints
created using *EasyPeasy* for the current view. `Condition`
closures will be evaluated again
*/
@available(iOS, deprecated: 1.5.1, message: "Use easy.reload() instead")
public func easy_reload() {
self.reload()
}
/**
Clears all the constraints applied with EasyPeasy to the
current `UIView`
*/
@available(iOS, deprecated: 1.5.1, message: "Use easy.clear() instead")
public func easy_clear() {
self.clear()
}
}
/**
Internal extension that handles the storage and application
of `Attributes` in an `Item`
*/
extension Item {
/**
This method will trigger the recreation of the constraints
created using *EasyPeasy* for the current view. `Condition`
closures will be evaluated again
*/
func reload() {
var activateConstraints: [NSLayoutConstraint] = []
var deactivateConstraints: [NSLayoutConstraint] = []
for node in self.nodes.values {
let activationGroup = node.reload()
activateConstraints.append(contentsOf: activationGroup.0)
deactivateConstraints.append(contentsOf: activationGroup.1)
}
// Activate/deactivate the resulting `NSLayoutConstraints`
NSLayoutConstraint.deactivate(deactivateConstraints)
NSLayoutConstraint.activate(activateConstraints)
}
/**
Clears all the constraints applied with EasyPeasy to the
current `UIView`
*/
func clear() {
var deactivateConstraints: [NSLayoutConstraint] = []
for node in self.nodes.values {
deactivateConstraints.append(contentsOf: node.clear())
}
self.nodes = [:]
// Deactivate the resulting `NSLayoutConstraints`
NSLayoutConstraint.deactivate(deactivateConstraints)
}
}
/**
Internal extension that handles the storage and application
of `Attributes` in an `Item`
*/
extension Item {
/// Dictionary persisting the `Nodes` related with this `Item`
var nodes: [String:Node] {
get {
if let nodes = objc_getAssociatedObject(self, &easy_attributesReference) as? [String:Node] {
return nodes
}
let nodes: [String:Node] = [:]
let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
objc_setAssociatedObject(self, &easy_attributesReference, nodes, policy)
return nodes
}
set {
let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
objc_setAssociatedObject(self, &easy_attributesReference, newValue, policy)
}
}
/**
Applies the `Attributes` within the passed array to the current `Item`
- parameter attributes: Array of `Attributes` to apply into the `Item`
- returns the resulting `NSLayoutConstraints`
*/
func apply(attributes: [Attribute]) -> [NSLayoutConstraint] {
// Before doing anything ensure that this item has translates autoresizing
// mask into constraints disabled
self.disableAutoresizingToConstraints()
var layoutConstraints: [NSLayoutConstraint] = []
var activateConstraints: [NSLayoutConstraint] = []
var deactivateConstraints: [NSLayoutConstraint] = []
for attribute in attributes {
if let compoundAttribute = attribute as? CompoundAttribute {
layoutConstraints.append(contentsOf: self.apply(attributes: compoundAttribute.attributes))
continue
}
if let activationGroup = self.apply(attribute: attribute) {
layoutConstraints.append(contentsOf: activationGroup.0)
activateConstraints.append(contentsOf: activationGroup.0)
deactivateConstraints.append(contentsOf: activationGroup.1)
}
}
// Activate/deactivate the `NSLayoutConstraints` returned by the different `Nodes`
NSLayoutConstraint.deactivate(deactivateConstraints)
NSLayoutConstraint.activate(activateConstraints)
return layoutConstraints
}
func apply(attribute: Attribute) -> ActivationGroup? {
// Creates the `NSLayoutConstraint` of the `Attribute` holding
// a reference to it from the `Attribute` objects
attribute.createConstraints(for: self)
// Checks the node correspoding to the `Attribute` and creates it
// in case it doesn't exist
let node = self.nodes[attribute.signature] ?? Node()
// Set node
self.nodes[attribute.signature] = node
// Add the `Attribute` to the node and return the `NSLayoutConstraints`
// to be activated/deactivated
return node.add(attribute: attribute)
}
/**
Sets `translatesAutoresizingMaskIntoConstraints` to `false` if the
current `Item` implements it
*/
private func disableAutoresizingToConstraints() {
#if os(iOS) || os(tvOS)
(self as? UIView)?.translatesAutoresizingMaskIntoConstraints = false
#else
(self as? NSView)?.translatesAutoresizingMaskIntoConstraints = false
#endif
}
}
| 7a322a640e0c5c55470f8a575b41acd2 | 33.762626 | 106 | 0.645068 | false | false | false | false |
8bytes/drift-sdk-ios | refs/heads/master | Drift/Birdsong/Response.swift | mit | 2 | //
// Response.swift
// Pods
//
// Created by Simon Manning on 23/06/2016.
//
//
import Foundation
class Response {
let ref: String
let topic: String
let event: String
let payload: Socket.Payload
init?(data: Data) {
do {
guard let jsonObject = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? Socket.Payload else { return nil }
ref = jsonObject["ref"] as? String ?? ""
if let topic = jsonObject["topic"] as? String,
let event = jsonObject["event"] as? String,
let payload = jsonObject["payload"] as? Socket.Payload {
self.topic = topic
self.event = event
self.payload = payload
}
else {
return nil
}
}
catch {
return nil
}
}
}
| ee9f2e2a29d08cbf96296e5c47a216f4 | 23.736842 | 163 | 0.509574 | false | false | false | false |
rohan-panchal/Scaffold | refs/heads/master | Scaffold/Classes/Foundation/SCAFFoundation.swift | mit | 1 | //
// SCAFFoundation.swift
// Pods
//
// Created by Rohan Panchal on 9/26/16.
//
//
import Foundation
public struct Platform {
public static var iPhone: Bool {
return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone
}
public static var iPad: Bool {
return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad
}
public static var iOS: Bool {
return TARGET_OS_IOS != 0
}
public static var TVOS: Bool {
return TARGET_OS_TV != 0
}
public static var WatchOS: Bool {
return TARGET_OS_WATCH != 0
}
public static var Simulator: Bool {
return TARGET_OS_SIMULATOR != 0
}
}
| 5e11afb1a5fb762cbaac873c7593bc60 | 17.631579 | 70 | 0.583333 | false | false | false | false |
marcelvoss/WWDC15-Scholarship | refs/heads/master | Marcel Voss/Marcel Voss/MapViewer.swift | unlicense | 1 | //
// MapViewer.swift
// Marcel Voss
//
// Created by Marcel Voß on 18.04.15.
// Copyright (c) 2015 Marcel Voß. All rights reserved.
//
import UIKit
import MapKit
class MapViewer: UIView {
var mapView : MKMapView?
var effectView = UIVisualEffectView()
var aWindow : UIWindow?
var closeButton = UIButton()
var constraintY : NSLayoutConstraint?
init() {
super.init(frame: UIScreen.mainScreen().bounds)
aWindow = UIApplication.sharedApplication().keyWindow!
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func show() {
self.setupViews()
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.effectView.alpha = 1
self.closeButton.alpha = 1
})
UIView.animateWithDuration(0.4, delay: 0.4, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: nil, animations: { () -> Void in
self.constraintY!.constant = 0
self.layoutIfNeeded()
}) { (finished) -> Void in
}
}
func hide() {
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.effectView.alpha = 0
self.closeButton.alpha = 0
}) { (finished) -> Void in
self.mapView!.delegate = nil;
self.mapView!.removeFromSuperview();
self.mapView = nil;
self.effectView.removeFromSuperview()
self.removeFromSuperview()
}
UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: nil, animations: { () -> Void in
self.constraintY!.constant = self.frame.size.height
self.layoutIfNeeded()
}) { (finished) -> Void in
self.mapView?.removeFromSuperview()
}
}
func setupViews () {
aWindow?.addSubview(self)
let blur = UIBlurEffect(style: UIBlurEffectStyle.Dark)
effectView = UIVisualEffectView(effect: blur)
effectView.frame = self.frame
effectView.alpha = 0
self.addSubview(effectView)
closeButton.alpha = 0
closeButton.setTranslatesAutoresizingMaskIntoConstraints(false)
closeButton.addTarget(self, action: "hide", forControlEvents: UIControlEvents.TouchUpInside)
closeButton.setImage(UIImage(named: "CloseIcon"), forState: UIControlState.Normal)
self.addSubview(closeButton)
self.addConstraint(NSLayoutConstraint(item: closeButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -20))
self.addConstraint(NSLayoutConstraint(item: closeButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 20))
// Map
mapView?.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(mapView!)
self.addConstraint(NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
constraintY = NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: self.frame.size.height)
self.addConstraint(constraintY!)
self.addConstraint(NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
var tap = UITapGestureRecognizer(target: self, action: "hide")
effectView.addGestureRecognizer(tap)
self.layoutIfNeeded()
}
}
| 96c463a1ff2818953cbc099f818cb438 | 39.67619 | 232 | 0.65137 | false | false | false | false |
codeservis/UICollectionviewsample | refs/heads/master | MultiDirectionCollectionView/CustomCollectionViewLayout.swift | gpl-3.0 | 1 | //
// CustomCollectionViewLayout.swift
// MultiDirectionCollectionView
//
// Created by Kyle Andrews on 4/20/15.
// Copyright (c) 2015 Credera. All rights reserved.
//
import UIKit
class CustomCollectionViewLayout: UICollectionViewLayout {
// Used for calculating each cells CGRect on screen.
// CGRect will define the Origin and Size of the cell.
let CELL_HEIGHT = 40.0
let CELL_WIDTH = 120.0
let STATUS_BAR = UIApplication.sharedApplication().statusBarFrame.height
// Dictionary to hold the UICollectionViewLayoutAttributes for
// each cell. The layout attribtues will define the cell's size
// and position (x, y, and z index). I have found this process
// to be one of the heavier parts of the layout. I recommend
// holding onto this data after it has been calculated in either
// a dictionary or data store of some kind for a smooth performance.
var cellAttrsDictionary = Dictionary<NSIndexPath, UICollectionViewLayoutAttributes>()
// Defines the size of the area the user can move around in
// within the collection view.
var contentSize = CGSize.zero
// Used to determine if a data source update has occured.
// Note: The data source would be responsible for updating
// this value if an update was performed.
var dataSourceDidUpdate = true
override func collectionViewContentSize() -> CGSize {
return self.contentSize
}
override func prepareLayout() {
// Only update header cells.
if !dataSourceDidUpdate {
// Determine current content offsets.
let xOffset = collectionView!.contentOffset.x
let yOffset = collectionView!.contentOffset.y
if collectionView?.numberOfSections() > 0 {
for section in 0...collectionView!.numberOfSections()-1 {
// Confirm the section has items.
if collectionView?.numberOfItemsInSection(section) > 0 {
// Update all items in the first row.
if section == 0 {
for item in 0...collectionView!.numberOfItemsInSection(section)-1 {
// Build indexPath to get attributes from dictionary.
let indexPath = NSIndexPath(forItem: item, inSection: section)
// Update y-position to follow user.
if let attrs = cellAttrsDictionary[indexPath] {
var frame = attrs.frame
// Also update x-position for corner cell.
if item == 0 {
frame.origin.x = xOffset
}
frame.origin.y = yOffset
attrs.frame = frame
}
}
// For all other sections, we only need to update
// the x-position for the fist item.
} else {
// Build indexPath to get attributes from dictionary.
let indexPath = NSIndexPath(forItem: 0, inSection: section)
// Update y-position to follow user.
if let attrs = cellAttrsDictionary[indexPath] {
var frame = attrs.frame
frame.origin.x = xOffset
attrs.frame = frame
}
}
}
}
}
// Do not run attribute generation code
// unless data source has been updated.
return
}
// Acknowledge data source change, and disable for next time.
dataSourceDidUpdate = false
// Cycle through each section of the data source.
if collectionView?.numberOfSections() > 0 {
for section in 0...collectionView!.numberOfSections()-1 {
// Cycle through each item in the section.
if collectionView?.numberOfItemsInSection(section) > 0 {
for item in 0...collectionView!.numberOfItemsInSection(section)-1 {
// Build the UICollectionVieLayoutAttributes for the cell.
let cellIndex = NSIndexPath(forItem: item, inSection: section)
let xPos = Double(item) * CELL_WIDTH
let yPos = Double(section) * CELL_HEIGHT
let cellAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: cellIndex)
cellAttributes.frame = CGRect(x: xPos, y: yPos, width: CELL_WIDTH, height: CELL_HEIGHT)
// Determine zIndex based on cell type.
if section == 0 && item == 0 {
cellAttributes.zIndex = 4
} else if section == 0 {
cellAttributes.zIndex = 3
} else if item == 0 {
cellAttributes.zIndex = 2
} else {
cellAttributes.zIndex = 1
}
// Save the attributes.
cellAttrsDictionary[cellIndex] = cellAttributes
}
}
}
}
// Update content size.
let contentWidth = Double(collectionView!.numberOfItemsInSection(0)) * CELL_WIDTH
let contentHeight = Double(collectionView!.numberOfSections()) * CELL_HEIGHT
self.contentSize = CGSize(width: contentWidth, height: contentHeight)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
// Create an array to hold all elements found in our current view.
var attributesInRect = [UICollectionViewLayoutAttributes]()
// Check each element to see if it should be returned.
for cellAttributes in cellAttrsDictionary.values.elements {
if CGRectIntersectsRect(rect, cellAttributes.frame) {
attributesInRect.append(cellAttributes)
}
}
// Return list of elements.
return attributesInRect
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
return cellAttrsDictionary[indexPath]!
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
| 6297023d18ca18988cfbf5db562d51eb | 41.386364 | 115 | 0.497319 | false | false | false | false |
DrabWeb/Akedo | refs/heads/master | Akedo/Akedo/Objects/AKPomf.swift | gpl-3.0 | 1 | //
// AKPomf.swift
// Akedo
//
// Created by Seth on 2016-09-04.
//
import Cocoa
import Alamofire
import SwiftyJSON
/// Represents a pomf clone the user can upload to
class AKPomf: NSObject {
// MARK: - Properties
/// The name of this pomf clone
var name : String = "";
/// The URL to this pomf clone(E.g. https://mixtape.moe/)
var url : String = "";
/// The max file size for uploading(in MB)
var maxFileSize : Int = 0;
/// For some pomf hosts they use a subdomain for uploaded files(E.g. pomf.cat, uses a.pomf.cat for uploads), this variable is the "a." in that example, optional
var uploadUrlPrefix : String = "";
// MARK: - Functions
/// Uploads the file(s) at the given path(s) to this pomf clone and calls the completion handler with the URL(s), and if the upload was successful
/// Uploads the given files to this pomf host
///
/// - Parameters:
/// - filePaths: The paths of the files to upload
/// - completionHandler: The completion handler for when the operation finishes, passed the URLs of the uploaded files and if it the upload was successful
func upload(files : [String], completionHandler : @escaping ((([String], Bool)) -> ())) {
/// The URLs to the uploaded files
var urls : [String] = [];
/// Was the upload successful?
var successful : Bool = false;
print("AKPomf: Uploading \"\(files)\" to \(self.name)(\(self.url + "upload.php"))");
// Make the upload request
Alamofire.upload(
multipartFormData: { multipartFormData in
// For every file to upload...
for(_, currentFilePath) in files.enumerated() {
// Append the current file path to the `files[]` multipart data
multipartFormData.append(URL(fileURLWithPath: currentFilePath), withName: "files[]");
}
},
to: self.url + "upload.php",
encodingCompletion: { encodingResult in
switch encodingResult {
// If the encode was a success...
case .success(let upload, _, _):
upload.responseJSON { (responseData) -> Void in
/// The string of JSON that will be returned when the POST request finishes
let responseJsonString : NSString = NSString(data: responseData.data!, encoding: String.Encoding.utf8.rawValue)!;
// If the the response data isnt nil...
if let dataFromResponseJsonString = responseJsonString.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false) {
/// The JSON from the response string
let responseJson = JSON(data: dataFromResponseJsonString);
// For every uploaded file...
for(_, currentFileData) in responseJson["files"] {
/// The current file URL
var currentUrl : String = currentFileData["url"].stringValue.replacingOccurrences(of: "\\", with: "");
// If the URL doesnt have a ://...
if(!currentUrl.contains("://")) {
// Fix up the URL
/// The prefix of this pomf clones URL(Either http:// or https://)
let urlPrefix : String = (self.url.substring(to: self.url.range(of: "://")!.lowerBound)) + "://";
// Set currentUrl to `urlPrefix + uploadUrlPrefix + self.url` without `prefix + currentUrl`
currentUrl = urlPrefix + (self.uploadUrlPrefix + self.url.replacingOccurrences(of: urlPrefix, with: "")) + currentUrl;
}
// Add the current file's URL to `urls`
urls.append(currentUrl);
}
// Set `successful`
successful = responseJson["success"].boolValue;
// Call the completion handler
completionHandler((urls, successful));
}
}
// If the encode was a failure...
case .failure(let encodingError):
print("AKPomf(\(self.name)): Error encoding \"\(files)\", \(encodingError)");
// Post the notification saying the file failed to encode
/// The notification to say the file encoding failed
let fileEncodingFailedNotification : NSUserNotification = NSUserNotification();
// Setup the notification
fileEncodingFailedNotification.title = "Akedo";
fileEncodingFailedNotification.informativeText = "Failed to encode \(files.count) file\((files.count == 1) ? "" : "s") for \(self.name)";
// Deliver the notification
NSUserNotificationCenter.default.deliver(fileEncodingFailedNotification);
}
}
)
}
// Init with a name, URL and max file size
init(name: String, url : String, maxFileSize : Int) {
self.name = name;
self.url = url;
self.maxFileSize = maxFileSize;
}
// Init with a name, URL, max file size and URL prefix
init(name: String, url : String, maxFileSize : Int, uploadUrlPrefix : String) {
self.name = name;
self.url = url;
self.maxFileSize = maxFileSize;
self.uploadUrlPrefix = uploadUrlPrefix;
}
}
| 55e66d5fbd7cbd8db268048156d5dfda | 47.906977 | 164 | 0.492788 | false | false | false | false |
KeithPiTsui/Pavers | refs/heads/swift5 | Pavers/Sources/UI/Styles/lenses/UIAccessibilityLenses.swift | mit | 1 | // swiftlint:disable type_name
import PaversFRP
import UIKit
// UIAccessibility
public extension LensHolder where Object: KSObjectProtocol {
var isAccessibilityElement: Lens<Object, Bool> {
return Lens(
view: { $0.isAccessibilityElement },
set: { $1.isAccessibilityElement = $0; return $1 }
)
}
var accessibilityElementsHidden: Lens<Object, Bool> {
return Lens(
view: { $0.accessibilityElementsHidden },
set: { $1.accessibilityElementsHidden = $0; return $1 }
)
}
var accessibilityHint: Lens<Object, String?> {
return Lens(
view: { $0.accessibilityHint },
set: { $1.accessibilityHint = $0; return $1 }
)
}
var accessibilityLabel: Lens<Object, String?> {
return Lens(
view: { $0.accessibilityLabel },
set: { $1.accessibilityLabel = $0; return $1 }
)
}
var accessibilityTraits: Lens<Object, UIAccessibilityTraits> {
return Lens(
view: { $0.accessibilityTraits },
set: { $1.accessibilityTraits = $0; return $1 }
)
}
var accessibilityValue: Lens<Object, String?> {
return Lens(
view: { $0.accessibilityValue },
set: { $1.accessibilityValue = $0; return $1 }
)
}
var shouldGroupAccessibilityChildren: Lens<Object, Bool> {
return Lens(
view: { $0.shouldGroupAccessibilityChildren },
set: { $1.shouldGroupAccessibilityChildren = $0; return $1 }
)
}
var accessibilityNavigationStyle: Lens<Object, UIAccessibilityNavigationStyle> {
return Lens(
view: { $0.accessibilityNavigationStyle },
set: { $1.accessibilityNavigationStyle = $0; return $1 }
)
}
}
// UIAccessibilityContainer
public extension LensHolder where Object: NSObject {
var accessibilityElements: Lens<Object, [Any]?> {
return Lens(
view: { $0.accessibilityElements },
set: { $1.accessibilityElements = $0; return $1 }
)
}
}
| 7a08879f7bda85ef8cf1c34c37af9973 | 25.430556 | 82 | 0.648975 | false | false | false | false |
ludagoo/Perfect | refs/heads/master | PerfectLib/WebSocketHandler.swift | agpl-3.0 | 2 | //
// WebSocketHandler.swift
// PerfectLib
//
// Created by Kyle Jessup on 2016-01-06.
// Copyright © 2016 PerfectlySoft. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
#if os(Linux)
import SwiftGlibc
import LinuxBridge
private let UINT16_MAX = UInt(0xFFFF)
#endif
private let smallPayloadSize = 126
/// This class represents the communications channel for a WebSocket session.
public class WebSocket {
/// The various types of WebSocket messages.
public enum OpcodeType: UInt8 {
case Continuation = 0x0, Text = 0x1, Binary = 0x2, Close = 0x8, Ping = 0x9, Pong = 0xA, Invalid
}
private struct Frame {
let fin: Bool
let rsv1: Bool
let rsv2: Bool
let rsv3: Bool
let opCode: OpcodeType
let bytesPayload: [UInt8]
var stringPayload: String? {
return UTF8Encoding.encode(self.bytesPayload)
}
}
private let connection: WebConnection
/// The read timeout, in seconds. By default this is -1, which means no timeout.
public var readTimeoutSeconds: Double = -1.0
private var socket: NetTCP { return self.connection.connection }
/// Indicates if the socket is still likely connected or if it has been closed.
public var isConnected: Bool { return self.socket.fd.isValid }
private var nextIsContinuation = false
private let readBuffer = Bytes()
init(connection: WebConnection) {
self.connection = connection
}
/// Close the connection.
public func close() {
if self.socket.fd.isValid {
self.sendMessage(.Close, bytes: [UInt8](), final: true) {
self.socket.close()
}
}
}
private func clearFrame() {
let position = self.readBuffer.position
self.readBuffer.data.removeFirst(position)
self.readBuffer.position = 0
}
private func fillFrame() -> Frame? {
guard self.readBuffer.availableExportBytes >= 2 else {
return nil
}
// we know we potentially have a valid frame here
// for to be resetting the position if we don't have a valid frame yet
let oldPosition = self.readBuffer.position
let byte1 = self.readBuffer.export8Bits()
let byte2 = self.readBuffer.export8Bits()
let fin = (byte1 & 0x80) != 0
let rsv1 = (byte1 & 0x40) != 0
let rsv2 = (byte1 & 0x20) != 0
let rsv3 = (byte1 & 0x10) != 0
let opcode = OpcodeType(rawValue: byte1 & 0xF) ?? .Invalid
let maskBit = (byte2 & 0x80) != 0
guard maskBit else {
self.close()
return nil
}
var unmaskedLength = Int(byte2 ^ 0x80)
if unmaskedLength == smallPayloadSize {
if self.readBuffer.availableExportBytes >= 2 {
unmaskedLength = Int(ntohs(self.readBuffer.export16Bits()))
}
} else if unmaskedLength > smallPayloadSize {
if self.readBuffer.availableExportBytes >= 8 {
unmaskedLength = Int(ntohll(self.readBuffer.export64Bits()))
}
} // else small payload
if self.readBuffer.availableExportBytes >= 4 {
let maskingKey = self.readBuffer.exportBytes(4)
if self.readBuffer.availableExportBytes >= unmaskedLength {
var exported = self.readBuffer.exportBytes(unmaskedLength)
for i in 0..<exported.count {
exported[i] = exported[i] ^ maskingKey[i % 4]
}
self.clearFrame()
return Frame(fin: fin, rsv1: rsv1, rsv2: rsv2, rsv3: rsv3, opCode: opcode, bytesPayload: exported)
}
}
self.readBuffer.position = oldPosition
return nil
}
func fillBuffer(demand: Int, completion: (Bool) -> ()) {
self.socket.readBytesFully(demand, timeoutSeconds: self.readTimeoutSeconds) {
[weak self] (b:[UInt8]?) -> () in
if let b = b {
self?.readBuffer.data.appendContentsOf(b)
}
completion(b != nil)
}
}
func fillBufferSome(suggestion: Int, completion: () -> ()) {
self.socket.readSomeBytes(suggestion) {
[weak self] (b:[UInt8]?) -> () in
if let b = b {
self?.readBuffer.data.appendContentsOf(b)
}
completion()
}
}
private func readFrame(completion: (Frame?) -> ()) {
if let frame = self.fillFrame() {
switch frame.opCode {
// check for and handle ping/pong
case .Ping:
self.sendMessage(.Pong, bytes: frame.bytesPayload, final: true) {
self.readFrame(completion)
}
return
// check for and handle close
case .Close:
self.close()
return completion(nil)
default:
return completion(frame)
}
}
self.fillBuffer(1) {
b in
guard b != false else {
return completion(nil)
}
self.fillBufferSome(1024 * 32) { // some arbitrary read-ahead amount
self.readFrame(completion)
}
}
}
/// Read string data from the client.
public func readStringMessage(continuation: (String?, opcode: OpcodeType, final: Bool) -> ()) {
self.readFrame {
frame in
continuation(frame?.stringPayload, opcode: frame?.opCode ?? .Invalid, final: frame?.fin ?? true)
}
}
/// Read binary data from the client.
public func readBytesMessage(continuation: ([UInt8]?, opcode: OpcodeType, final: Bool) -> ()) {
self.readFrame {
frame in
continuation(frame?.bytesPayload, opcode: frame?.opCode ?? .Invalid, final: frame?.fin ?? true)
}
}
/// Send binary data to thew client.
public func sendBinaryMessage(bytes: [UInt8], final: Bool, completion: () -> ()) {
self.sendMessage(.Binary, bytes: bytes, final: final, completion: completion)
}
/// Send string data to the client.
public func sendStringMessage(string: String, final: Bool, completion: () -> ()) {
self.sendMessage(.Text, bytes: UTF8Encoding.decode(string), final: final, completion: completion)
}
/// Send a "pong" message to the client.
public func sendPong(completion: () -> ()) {
self.sendMessage(.Pong, bytes: [UInt8](), final: true, completion: completion)
}
/// Send a "ping" message to the client.
/// Expect a "pong" message to follow.
public func sendPing(completion: () -> ()) {
self.sendMessage(.Ping, bytes: [UInt8](), final: true, completion: completion)
}
private func sendMessage(opcode: OpcodeType, bytes: [UInt8], final: Bool, completion: () -> ()) {
let sendBuffer = Bytes()
let byte1 = UInt8(final ? 0x80 : 0x0) | (self.nextIsContinuation ? 0 : opcode.rawValue)
self.nextIsContinuation = !final
sendBuffer.import8Bits(byte1)
let payloadSize = bytes.count
if payloadSize < smallPayloadSize {
let byte2 = UInt8(payloadSize)
sendBuffer.import8Bits(byte2)
} else if payloadSize <= Int(UINT16_MAX) {
sendBuffer.import8Bits(UInt8(smallPayloadSize))
.import16Bits(htons(UInt16(payloadSize)))
} else {
sendBuffer.import8Bits(UInt8(1+smallPayloadSize))
.import64Bits(htonll(UInt64(payloadSize)))
}
sendBuffer.importBytes(bytes)
self.socket.writeBytes(sendBuffer.data) {
_ in
completion()
}
}
}
/// The protocol that all WebSocket handlers must implement.
public protocol WebSocketSessionHandler {
/// Optionally indicate the name of the protocol the handler implements.
/// If this has a valid, the protocol name will be validated against what the client is requesting.
var socketProtocol: String? { get }
/// This function is called once the WebSocket session has been initiated.
func handleSession(request: WebRequest, socket: WebSocket)
}
private let acceptableProtocolVersions = [13]
private let webSocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
/// This request handler accepts WebSocket requests from client.
/// It will initialize the session and then deliver it to the `WebSocketSessionHandler`.
public class WebSocketHandler : RequestHandler {
public typealias HandlerProducer = (request: WebRequest, protocols: [String]) -> WebSocketSessionHandler?
private let handlerProducer: HandlerProducer
public init(handlerProducer: HandlerProducer) {
self.handlerProducer = handlerProducer
}
public func handleRequest(request: WebRequest, response: WebResponse) {
guard let upgrade = request.header("Upgrade"),
connection = request.header("Connection"),
secWebSocketKey = request.header("Sec-WebSocket-Key"),
secWebSocketVersion = request.header("Sec-WebSocket-Version")
where upgrade.lowercaseString == "websocket" && connection.lowercaseString == "upgrade" else {
response.setStatus(400, message: "Bad Request")
response.requestCompletedCallback()
return
}
guard acceptableProtocolVersions.contains(Int(secWebSocketVersion) ?? 0) else {
response.setStatus(400, message: "Bad Request")
response.addHeader("Sec-WebSocket-Version", value: "\(acceptableProtocolVersions[0])")
response.appendBodyString("WebSocket protocol version \(secWebSocketVersion) not supported. Supported protocol versions are: \(acceptableProtocolVersions.map { String($0) }.joinWithSeparator(","))")
response.requestCompletedCallback()
return
}
let secWebSocketProtocol = request.header("Sec-WebSocket-Protocol") ?? ""
let protocolList = secWebSocketProtocol.characters.split(",").flatMap {
i -> String? in
var s = String(i)
while s.characters.count > 0 && s.characters[s.characters.startIndex] == " " {
s.removeAtIndex(s.startIndex)
}
return s.characters.count > 0 ? s : nil
}
guard let handler = self.handlerProducer(request: request, protocols: protocolList) else {
response.setStatus(400, message: "Bad Request")
response.appendBodyString("WebSocket protocols not supported.")
response.requestCompletedCallback()
return
}
response.requestCompletedCallback = {} // this is no longer a normal request, eligible for keep-alive
response.setStatus(101, message: "Switching Protocols")
response.addHeader("Upgrade", value: "websocket")
response.addHeader("Connection", value: "Upgrade")
response.addHeader("Sec-WebSocket-Accept", value: self.base64((secWebSocketKey + webSocketGUID).utf8.sha1))
if let chosenProtocol = handler.socketProtocol {
response.addHeader("Sec-WebSocket-Protocol", value: chosenProtocol)
}
for (key, value) in response.headersArray {
response.connection.writeHeaderLine(key + ": " + value)
}
response.connection.writeBodyBytes([UInt8]())
handler.handleSession(request, socket: WebSocket(connection: response.connection))
}
private func base64(a: [UInt8]) -> String {
let bio = BIO_push(BIO_new(BIO_f_base64()), BIO_new(BIO_s_mem()))
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL)
BIO_write(bio, a, Int32(a.count))
BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, nil)
var mem = UnsafeMutablePointer<BUF_MEM>()
BIO_ctrl(bio, BIO_C_GET_BUF_MEM_PTR, 0, &mem)
BIO_ctrl(bio, BIO_CTRL_SET_CLOSE, Int(BIO_NOCLOSE), nil)
BIO_free_all(bio)
let txt = UnsafeMutablePointer<UInt8>(mem.memory.data)
let ret = UTF8Encoding.encode(GenerateFromPointer(from: txt, count: mem.memory.length))
free(mem.memory.data)
return ret
}
}
import OpenSSL
extension String.UTF8View {
var sha1: [UInt8] {
let bytes = UnsafeMutablePointer<UInt8>.alloc(Int(SHA_DIGEST_LENGTH))
defer { bytes.destroy() ; bytes.dealloc(Int(SHA_DIGEST_LENGTH)) }
SHA1(Array<UInt8>(self), (self.count), bytes)
var r = [UInt8]()
for idx in 0..<Int(SHA_DIGEST_LENGTH) {
r.append(bytes[idx])
}
return r
}
}
| 29e1325113e224b88d834440210b97b3 | 29.861619 | 201 | 0.710575 | false | false | false | false |
Monnoroch/Cuckoo | refs/heads/master | Generator/Tests/SourceFiles/Expected/NoHeader.swift | mit | 1 | import Cuckoo
import Foundation
class MockEmptyClass: EmptyClass, Cuckoo.Mock {
typealias MocksType = EmptyClass
typealias Stubbing = __StubbingProxy_EmptyClass
typealias Verification = __VerificationProxy_EmptyClass
let manager = Cuckoo.MockManager()
private var observed: EmptyClass?
func spy(on victim: EmptyClass) -> Self {
observed = victim
return self
}
struct __StubbingProxy_EmptyClass: Cuckoo.StubbingProxy {
private let manager: Cuckoo.MockManager
init(manager: Cuckoo.MockManager) {
self.manager = manager
}
}
struct __VerificationProxy_EmptyClass: Cuckoo.VerificationProxy {
private let manager: Cuckoo.MockManager
private let callMatcher: Cuckoo.CallMatcher
private let sourceLocation: Cuckoo.SourceLocation
init(manager: Cuckoo.MockManager, callMatcher: Cuckoo.CallMatcher, sourceLocation: Cuckoo.SourceLocation) {
self.manager = manager
self.callMatcher = callMatcher
self.sourceLocation = sourceLocation
}
}
}
class EmptyClassStub: EmptyClass {
}
| a40d3753b3f6613bed7958a143f109eb | 28.4 | 115 | 0.668367 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.