repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bigL055/SPKit | Sources/UIImage/UIImage.swift | 1 | 10599 | //
// SPKit
//
// Copyright (c) 2017 linhay - https:// github.com/linhay
//
// 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
import UIKit
#if canImport(UIKit)
import CoreMedia
public extension UIImage{
/// from CMSampleBuffer
///
/// must import CoreMedia
/// from: https://stackoverflow.com/questions/15726761/make-an-uiimage-from-a-cmsamplebuffer
///
/// - Parameter sampleBuffer: CMSampleBuffer
public convenience init?(sampleBuffer: CMSampleBuffer) {
// Get a CMSampleBuffer's Core Video image buffer for the media data
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil }
// Lock the base address of the pixel buffer
CVPixelBufferLockBaseAddress(imageBuffer, .readOnly)
// Get the number of bytes per row for the pixel buffer
let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
// Get the number of bytes per row for the pixel buffer
let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
// Get the pixel buffer width and height
let width = CVPixelBufferGetWidth(imageBuffer)
let height = CVPixelBufferGetHeight(imageBuffer)
// Create a device-dependent RGB color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
// Create a bitmap graphics context with the sample buffer data
var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Little.rawValue
bitmapInfo |= CGImageAlphaInfo.premultipliedFirst.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
//let bitmapInfo: UInt32 = CGBitmapInfo.alphaInfoMask.rawValue
// Create a Quartz image from the pixel data in the bitmap graphics context
guard let context = CGContext(data: baseAddress,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo),
let quartzImage = context.makeImage() else { return nil }
// Unlock the pixel buffer
CVPixelBufferUnlockBaseAddress(imageBuffer, .readOnly)
// Create an image object from the Quartz image
self.init(cgImage: quartzImage)
}
}
#endif
// MARK: - ๅๅงๅ
public extension UIImage{
/// ่ทๅๆๅฎ้ข่ฒ็ๅพ็
///
/// - Parameters:
/// - color: UIColor
/// - size: ๅพ็ๅคงๅฐ
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
if size.width <= 0 || size.height <= 0 { return nil }
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
context.setFillColor(color.cgColor)
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImg = image?.cgImage else { return nil }
self.init(cgImage: cgImg)
}
}
// MARK: - UIImage
public extension SPExtension where Base: UIImage{
/// ๅพ็ๅฐบๅฏธ: Bytes
public var sizeAsBytes: Int
{ return base.jpegData(compressionQuality: 1)?.count ?? 0 }
/// ๅพ็ๅฐบๅฏธ: KB
public var sizeAsKB: Int {
let sizeAsBytes = self.sizeAsBytes
return sizeAsBytes != 0 ? sizeAsBytes / 1024: 0 }
/// ๅพ็ๅฐบๅฏธ: MB
public var sizeAsMB: Int {
let sizeAsKB = self.sizeAsKB
return sizeAsBytes != 0 ? sizeAsKB / 1024: 0 }
}
// MARK: - UIImage
public extension SPExtension where Base: UIImage{
/// ่ฟๅไธๅผ ๆฒกๆ่ขซๆธฒๆๅพ็
public var original: UIImage { return base.withRenderingMode(.alwaysOriginal) }
/// ่ฟๅไธๅผ ๅฏ่ขซๆธฒๆๅพ็
public var template: UIImage { return base.withRenderingMode(.alwaysTemplate) }
}
public extension SPExtension where Base: UIImage{
/// ไฟฎๆนๅ่ฒ็ณปๅพ็้ข่ฒ
///
/// - Parameter color: ้ข่ฒ
/// - Returns: ๆฐๅพ
public func setTint(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(base.size, false, 1)
defer { UIGraphicsEndImageContext() }
color.setFill()
let bounds = CGRect(x: 0, y: 0, width: base.size.width, height: base.size.height)
UIRectFill(bounds)
base.draw(in: bounds, blendMode: .overlay, alpha: 1)
base.draw(in: bounds, blendMode: .destinationIn, alpha: 1)
return UIGraphicsGetImageFromCurrentImageContext() ?? base
}
}
// MARK: - UIImage ๅพ็ๅค็
public extension SPExtension where Base: UIImage{
/// ่ฃๅชๅฏนๅบๅบๅ
///
/// - Parameter bound: ่ฃๅชๅบๅ
/// - Returns: ๆฐๅพ
public func crop(bound: CGRect) -> UIImage {
let scaledBounds = CGRect(x: bound.origin.x * base.scale,
y: bound.origin.y * base.scale,
width: bound.size.width * base.scale,
height: bound.size.height * base.scale)
guard let cgImage = base.cgImage?.cropping(to: scaledBounds) else { return base }
return UIImage(cgImage: cgImage, scale: base.scale, orientation: .up)
}
/// ่ฟๅๅๅฝขๅพ็
public func rounded() -> UIImage {
return base.sp.rounded(radius: base.size.height * 0.5,
corners: .allCorners,
borderWidth: 0,
borderColor: nil,
borderLineJoin: .miter)
}
/// ๅพๅๅค็: ่ฃๅ
/// - Parameters:
/// - radius: ๅ่งๅคงๅฐ
/// - corners: ๅ่งๅบๅ
/// - borderWidth: ๆ่พนๅคงๅฐ
/// - borderColor: ๆ่พน้ข่ฒ
/// - borderLineJoin: ๆ่พน็ฑปๅ
/// - Returns: ๆฐๅพ
public func rounded(radius: CGFloat,
corners: UIRectCorner = .allCorners,
borderWidth: CGFloat = 0,
borderColor: UIColor? = nil,
borderLineJoin: CGLineJoin = .miter) -> UIImage {
var corners = corners
if corners != UIRectCorner.allCorners {
var rawValue: UInt = 0
if (corners.rawValue & UIRectCorner.topLeft.rawValue) != 0
{ rawValue = rawValue | UIRectCorner.bottomLeft.rawValue }
if (corners.rawValue & UIRectCorner.topRight.rawValue) != 0
{ rawValue = rawValue | UIRectCorner.bottomRight.rawValue }
if (corners.rawValue & UIRectCorner.bottomLeft.rawValue) != 0
{ rawValue = rawValue | UIRectCorner.topLeft.rawValue }
if (corners.rawValue & UIRectCorner.bottomRight.rawValue) != 0
{ rawValue = rawValue | UIRectCorner.topRight.rawValue }
corners = UIRectCorner(rawValue: rawValue)
}
UIGraphicsBeginImageContextWithOptions(base.size, false, base.scale)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return base }
let rect = CGRect(x: 0, y: 0, width: base.size.width, height: base.size.height)
context.scaleBy(x: 1, y: -1)
context.translateBy(x: 0, y: -rect.height)
let minSize = min(base.size.width, base.size.height)
if borderWidth < minSize * 0.5{
let path = UIBezierPath(roundedRect: rect.insetBy(dx: borderWidth, dy: borderWidth),
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: borderWidth))
path.close()
context.saveGState()
path.addClip()
guard let cgImage = base.cgImage else { return base }
context.draw(cgImage, in: rect)
context.restoreGState()
}
if (borderColor != nil && borderWidth < minSize / 2 && borderWidth > 0) {
let strokeInset = (floor(borderWidth * base.scale) + 0.5) / base.scale
let strokeRect = rect.insetBy(dx: strokeInset, dy: strokeInset)
let strokeRadius = radius > base.scale / 2 ? CGFloat(radius - base.scale / 2): 0
let path = UIBezierPath(roundedRect: strokeRect, byRoundingCorners: corners, cornerRadii: CGSize(width: strokeRadius, height: borderWidth))
path.close()
path.lineWidth = borderWidth
path.lineJoinStyle = borderLineJoin
borderColor?.setStroke()
path.stroke()
}
let image = UIGraphicsGetImageFromCurrentImageContext()
return image ?? base
}
/// ็ผฉๆพ่ณๆๅฎ้ซๅบฆ
///
/// - Parameters:
/// - toWidth: ้ซๅบฆ
/// - opaque: ้ๆๅผๅ
ณ๏ผๅฆๆๅพๅฝขๅฎๅ
จไธ็จ้ๆ๏ผ่ฎพ็ฝฎไธบYESไปฅไผๅไฝๅพ็ๅญๅจ
/// - Returns: ๆฐ็ๅพ็
public func scaled(toHeight: CGFloat, opaque: Bool = false) -> UIImage? {
let scale = toHeight / base.size.height
let newWidth = base.size.width * scale
UIGraphicsBeginImageContextWithOptions(CGSize(width: newWidth, height: toHeight), opaque, 0)
base.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: toHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// ็ผฉๆพ่ณๆๅฎๅฎฝๅบฆ
///
/// - Parameters:
/// - toWidth: ๅฎฝๅบฆ
/// - opaque: ้ๆๅผๅ
ณ๏ผๅฆๆๅพๅฝขๅฎๅ
จไธ็จ้ๆ๏ผ่ฎพ็ฝฎไธบYESไปฅไผๅไฝๅพ็ๅญๅจ
/// - Returns: ๆฐ็ๅพ็
public func scaled(toWidth: CGFloat, opaque: Bool = false) -> UIImage? {
let scale = toWidth / base.size.width
let newHeight = base.size.height * scale
UIGraphicsBeginImageContextWithOptions(CGSize(width: toWidth, height: newHeight), opaque, 0)
base.draw(in: CGRect(x: 0, y: 0, width: toWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
| apache-2.0 | f08457325e3171f4a5d92639a02589f4 | 37.402256 | 145 | 0.661772 | 4.435519 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeLocalization/AwesomeLocalization/Classes/Views/UIButton+AL.swift | 1 | 2043 | //
// UIView+Localized.swift
// AwesomeLocalization
//
// Created by Evandro Harrison Hoffmann on 10/4/17.
//
import UIKit
@IBDesignable
extension UIButton {
// MARK: - Associations
private static let localizedTextAssociation = ObjectAssociation<NSObject>()
private static let customLocalizationFileAssociation = ObjectAssociation<NSObject>()
private static let isAttributedLocalizationAssociation = ObjectAssociation<NSObject>()
// MARK: - Inspectables
@IBInspectable
public var localizedText: String {
get {
return UIButton.localizedTextAssociation[self] as? String ?? ""
}
set (localizedText) {
UIButton.localizedTextAssociation[self] = localizedText as NSObject
updateLocalization()
}
}
@IBInspectable
public var customLocalizationFile: String? {
get {
return UIButton.customLocalizationFileAssociation[self] as? String
}
set (localizationTable) {
UIButton.customLocalizationFileAssociation[self] = localizationTable as NSObject?
updateLocalization()
}
}
@IBInspectable
public var isAttributedLocalization: Bool {
get {
return UIButton.isAttributedLocalizationAssociation[self] as? Bool ?? false
}
set (isLocalizationAttributed) {
UIButton.isAttributedLocalizationAssociation[self] = isLocalizationAttributed as NSObject
updateLocalization()
}
}
// MARK: - Localization
public func updateLocalization() {
if isAttributedLocalization, let attributedText = localizedText.localizedAttributed(tableName: customLocalizationFile, font: titleLabel?.font, fontColor: titleColor(for: .normal), alignment: titleLabel?.textAlignment) {
setAttributedTitle(attributedText, for: .normal)
} else {
setTitle(localizedText.localized(tableName: customLocalizationFile), for: .normal)
}
}
}
| mit | 4e4da4416e592439b394c68ab4fab0d3 | 30.921875 | 228 | 0.665688 | 5.390501 | false | false | false | false |
jamy0801/LGWeChatKit | LGWeChatKit/LGChatKit/conversion/view/LGChatTextCell.swift | 1 | 3154 | //
// LGChatMessageCell.swift
// LGChatViewController
//
// Created by jamy on 10/11/15.
// Copyright ยฉ 2015 jamy. All rights reserved.
//
import UIKit
class LGChatTextCell: LGChatBaseCell {
let messageLabel: UILabel
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
messageLabel = UILabel(frame: CGRectZero)
messageLabel.userInteractionEnabled = false
messageLabel.numberOfLines = 0
messageLabel.font = messageFont
super.init(style: .Default, reuseIdentifier: reuseIdentifier)
selectionStyle = .None
backgroundImageView.addSubview(messageLabel)
messageLabel.translatesAutoresizingMaskIntoConstraints = false
backgroundImageView.addConstraint(NSLayoutConstraint(item: backgroundImageView, attribute: .Width, relatedBy: .Equal, toItem: messageLabel, attribute: .Width, multiplier: 1, constant: 30))
backgroundImageView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterX, relatedBy: .Equal, toItem: backgroundImageView, attribute: .CenterX, multiplier: 1, constant: 0))
backgroundImageView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: backgroundImageView, attribute: .CenterY, multiplier: 1, constant: -5))
messageLabel.preferredMaxLayoutWidth = 210
backgroundImageView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Height, relatedBy: .Equal, toItem: backgroundImageView, attribute: .Height, multiplier: 1, constant: -30))
contentView.addConstraint(NSLayoutConstraint(item: backgroundImageView, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: -5))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setMessage(message: Message) {
super.setMessage(message)
let message = message as! textMessage
messageLabel.text = message.text
//indicatorView.hidden = false
if message.incoming != (tag == receiveTag) {
if message.incoming {
tag = receiveTag
backgroundImageView.image = backgroundImage.incoming
backgroundImageView.highlightedImage = backgroundImage.incomingHighlighed
messageLabel.textColor = UIColor.blackColor()
} else {
tag = sendTag
backgroundImageView.image = backgroundImage.outgoing
backgroundImageView.highlightedImage = backgroundImage.outgoingHighlighed
messageLabel.textColor = UIColor.whiteColor()
}
let messageConstraint : NSLayoutConstraint = backgroundImageView.constraints[1]
messageConstraint.constant = -messageConstraint.constant
}
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
backgroundImageView.highlighted = selected
}
}
| mit | bb8e3769c778f4ad42d56df12a77d54b | 42.191781 | 200 | 0.684428 | 5.650538 | false | false | false | false |
swiftix/swift.old | test/SILPasses/specialize_unconditional_checked_cast.swift | 1 | 15757 | // RUN: %target-swift-frontend -emit-sil -o - -O -disable-func-sig-opts %s | FileCheck %s
//////////////////
// Declarations //
//////////////////
public class C {}
public class D : C {}
public class E {}
var b : UInt8 = 0
var c = C()
var d = D()
var e = E()
var f : UInt64 = 0
var o : AnyObject = c
////////////////////////////
// Archetype To Archetype //
////////////////////////////
@inline(never)
public func ArchetypeToArchetype<T1, T2>(t t: T1, t2: T2) -> T2 {
return t as! T2
}
ArchetypeToArchetype(t: b, t2: b)
ArchetypeToArchetype(t: c, t2: c)
ArchetypeToArchetype(t: b, t2: c)
ArchetypeToArchetype(t: c, t2: b)
ArchetypeToArchetype(t: c, t2: d)
ArchetypeToArchetype(t: d, t2: c)
ArchetypeToArchetype(t: c, t2: e)
ArchetypeToArchetype(t: b, t2: f)
// x -> y where x and y are unrelated non classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_Vs6UInt64___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@out UInt64, @in UInt8, @in UInt64) -> () {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x and y are unrelated classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_CS_1E___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@out E, @in C, @in E) -> () {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// y -> x where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D_CS_1C___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@out C, @in D, @in C) -> () {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: upcast {{%[0-9]+}} : $D to $C
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_CS_1D___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@out D, @in C, @in D) -> () {
// CHECK: unconditional_checked_cast_addr take_always C in %1 : $*C to D in
// y -> x where x is not a class but y is.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_Vs5UInt8___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@out UInt8, @in C, @in UInt8) -> () {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x is not a class but y is.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@out C, @in UInt8, @in C) -> () {
// CHECK-NOT: unconditional_checked_cast_addr
// CHECK-NOT: unconditional_checked_cast_addr
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast_addr
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_S0____TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@out C, @in C, @in C) -> () {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_S____TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@out UInt8, @in UInt8, @in UInt8) -> () {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
///////////////////////////
// Archetype To Concrete //
///////////////////////////
@inline(never)
public func ArchetypeToConcreteConvertUInt8<T>(t t: T) -> UInt8 {
return t as! UInt8
}
ArchetypeToConcreteConvertUInt8(t: b)
ArchetypeToConcreteConvertUInt8(t: c)
ArchetypeToConcreteConvertUInt8(t: f)
// x -> y where x,y are not classes and x is a different type from y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs6UInt64___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{.*}} : $@convention(thin) (@in UInt64) -> UInt8 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where y is a class but x is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{.*}} : $@convention(thin) (@in C) -> UInt8 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{.*}} : $@convention(thin) (@in UInt8) -> UInt8 {
// CHECK: bb0
// CHECK-NEXT: debug_value_addr
// CHECK-NEXT: load
// CHECK-NEXT: return
@inline(never)
public func ArchetypeToConcreteConvertC<T>(t t: T) -> C {
return t as! C
}
ArchetypeToConcreteConvertC(t: c)
ArchetypeToConcreteConvertC(t: b)
ArchetypeToConcreteConvertC(t: d)
ArchetypeToConcreteConvertC(t: e)
// x -> y where x,y are classes, but x is unrelated to y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1E___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{.*}} : $@convention(thin) (@in E) -> @owned C {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are classes and x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{.*}} : $@convention(thin) (@in D) -> @owned C {
// CHECK: bb0
// CHECK-NEXT: debug_value_addr
// CHECK-NEXT: load
// CHECK-NEXT: upcast
// CHECK-NEXT: return
// x -> y where x is a class but y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{.*}} : $@convention(thin) (@in UInt8) -> @owned C {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{.*}} : $@convention(thin) (@in C) -> @owned C {
// CHECK: bb0
// CHECK-NEXT: debug_value_addr
// CHECK-NEXT: load
// CHECK-NEXT: return
@inline(never)
public func ArchetypeToConcreteConvertD<T>(t t: T) -> D {
return t as! D
}
ArchetypeToConcreteConvertD(t: c)
// x -> y where x,y are classes and x is a sub class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertD{{.*}} : $@convention(thin) (@in C) -> @owned D {
// CHECK: bb0
// CHECK-NEXT: debug_value_addr
// CHECK-NEXT: alloc_stack
// CHECK-NEXT: unconditional_checked_cast_addr take_always
// CHECK-NEXT: load
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: return
@inline(never)
public func ArchetypeToConcreteConvertE<T>(t t: T) -> E {
return t as! E
}
ArchetypeToConcreteConvertE(t: c)
// x -> y where x,y are classes, but y is unrelated to x. The idea is
// to make sure that the fact that y is concrete does not affect the
// result.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertE{{.*}} : $@convention(thin) (@in C) -> @owned E {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
///////////////////////////
// Concrete to Archetype //
///////////////////////////
@inline(never)
public func ConcreteToArchetypeConvertUInt8<T>(t t: UInt8, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertUInt8(t: b, t2: b)
ConcreteToArchetypeConvertUInt8(t: b, t2: c)
ConcreteToArchetypeConvertUInt8(t: b, t2: f)
// x -> y where x,y are different non class types.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs6UInt64___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (@out UInt64, UInt8, @in UInt64) -> () {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x is not a class but y is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (@out C, UInt8, @in C) -> () {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (@out UInt8, UInt8, @in UInt8) -> () {
// CHECK: bb0
// CHECK-NEXT: debug_value
// CHECK-NEXT: store
// CHECK-NEXT: tuple
// CHECK-NEXT: return
@inline(never)
public func ConcreteToArchetypeConvertC<T>(t t: C, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertC(t: c, t2: c)
ConcreteToArchetypeConvertC(t: c, t2: b)
ConcreteToArchetypeConvertC(t: c, t2: d)
ConcreteToArchetypeConvertC(t: c, t2: e)
// x -> y where x and y are unrelated classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1E___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@out E, @owned C, @in E) -> () {
// CHECK: bb0
// CHECK-NEXT: debug_value
// CHECK-NEXT: strong_retain
// CHECK-NEXT: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@out D, @owned C, @in D) -> () {
// CHECK: bb0
// CHECK-NEXT: debug_value
// CHECK-NEXT: debug_value_addr
// CHECK-NEXT: alloc_stack
// CHECK-NEXT: store
// CHECK-NEXT: strong_retain
// CHECK-NEXT: unconditional_checked_cast_addr take_always
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: load
// CHECK-NEXT: strong_release
// CHECK-NEXT: strong_release
// CHECK-NEXT: tuple
// CHECK-NEXT: return
// x -> y where x is a class but y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@out UInt8, @owned C, @in UInt8) -> () {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@out C, @owned C, @in C) -> () {
// CHECK: bb0
// CHECK-NEXT: debug_value
// CHECK-NEXT: debug_value_addr
// CHECK-NEXT: store
// CHECK-NEXT: load
// CHECK-NEXT: strong_release
// CHECK-NEXT: tuple
// CHECK-NEXT: return
@inline(never)
public func ConcreteToArchetypeConvertD<T>(t t: D, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertD(t: d, t2: c)
// x -> y where x is a subclass of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertD{{.*}} : $@convention(thin) (@out C, @owned D, @in C) -> () {
// CHECK: bb0
// CHECK-NEXT: debug_value
// CHECK-NEXT: debug_value_addr
// CHECK-NEXT: upcast
// CHECK-NEXT: store
// CHECK-NEXT: load
// CHECK-NEXT: strong_release
// CHECK-NEXT: tuple
// CHECK-NEXT: return
////////////////////////
// Super To Archetype //
////////////////////////
@inline(never)
public func SuperToArchetypeC<T>(c c : C, t : T) -> T {
return c as! T
}
SuperToArchetypeC(c: c, t: c)
SuperToArchetypeC(c: c, t: d)
SuperToArchetypeC(c: c, t: b)
// x -> y where x is a class and y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@out UInt8, @owned C, @in UInt8) -> () {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@out D, @owned C, @in D) -> () {
// CHECK: bb0
// CHECK: unconditional_checked_cast_addr take_always C in
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@out C, @owned C, @in C) -> () {
// CHECK: bb0
// CHECK-NEXT: debug_value
// CHECK-NEXT: debug_value_addr
// CHECK-NEXT: store
// CHECK-NEXT: load
// CHECK-NEXT: strong_release
// CHECK-NEXT: tuple
// CHECK-NEXT: return
@inline(never)
public func SuperToArchetypeD<T>(d d : D, t : T) -> T {
return d as! T
}
SuperToArchetypeD(d: d, t: c)
SuperToArchetypeD(d: d, t: d)
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast17SuperToArchetypeD{{.*}} : $@convention(thin) (@out D, @owned D, @in D) -> () {
// CHECK: bb0
// CHECK-NEXT: debug_value
// CHECK-NEXT: debug_value_addr
// CHECK-NEXT: store
// CHECK-NEXT: load
// CHECK-NEXT: strong_release
// CHECK-NEXT: tuple
// CHECK-NEXT: return
// *NOTE* The frontend is smart enough to turn this into an upcast. When this
// test is converted to SIL, this should be fixed appropriately.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast17SuperToArchetypeD{{.*}} : $@convention(thin) (@out C, @owned D, @in C) -> () {
// CHECK-NOT: unconditional_checked_cast super_to_archetype
// CHECK: upcast
// CHECK-NOT: unconditional_checked_cast super_to_archetype
//////////////////////////////
// Existential To Archetype //
//////////////////////////////
@inline(never)
public func ExistentialToArchetype<T>(o o : AnyObject, t : T) -> T {
return o as! T
}
// AnyObject -> AnyObject
// CHECK-LABEL: sil shared [noinline] @_TTSg5Ps9AnyObject____TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@out AnyObject, @owned AnyObject, @in AnyObject) -> () {
// CHECK: bb0
// CHECK-NEXT: debug_value
// CHECK-NEXT: debug_value_addr
// CHECK-NEXT: store
// CHECK-NEXT: load
// CHECK-NEXT: strong_release
// CHECK-NEXT: tuple
// CHECK-NEXT: return
// AnyObject -> Non Class (should always fail)
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@out UInt8, @owned AnyObject, @in UInt8) -> () {
// CHECK: builtin "int_trap"()
// CHECK: unreachable
// CHECK-NEXT: }
// AnyObject -> Class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@out C, @owned AnyObject, @in C) -> () {
// CHECK: unconditional_checked_cast_addr take_always AnyObject in {{%.*}} : $*AnyObject to C
ExistentialToArchetype(o: o, t: c)
ExistentialToArchetype(o: o, t: b)
ExistentialToArchetype(o: o, t: o)
| apache-2.0 | 58041680edd693a3c2d4336cc788b2a3 | 39.506427 | 228 | 0.69696 | 3.384962 | false | false | false | false |
shu223/ARKit-Sampler | common/SceneKitUtils.swift | 3 | 1148 | //
// SceneKitUtils.swift
//
// Created by Shuichi Tsutsumi on 2017/09/04.
// Copyright ยฉ 2017 Shuichi Tsutsumi. All rights reserved.
//
import SceneKit
func + (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.x + right.x, left.y + right.y, left.z + right.z)
}
func += (left: inout SCNVector3, right: SCNVector3) {
left = left + right
}
func - (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z)
}
func * (vector: SCNVector3, scalar: Float) -> SCNVector3 {
return SCNVector3Make(vector.x * scalar, vector.y * scalar, vector.z * scalar)
}
func / (left: SCNVector3, right: Float) -> SCNVector3 {
return SCNVector3Make(left.x / right, left.y / right, left.z / right)
}
func /= (left: inout SCNVector3, right: Float) {
left = left / right
}
extension SCNVector3 {
func length() -> Float {
return sqrtf(x * x + y * y + z * z)
}
}
extension matrix_float4x4 {
func position() -> SCNVector3 {
let mat = SCNMatrix4(self)
return SCNVector3(mat.m41, mat.m42, mat.m43)
}
}
| mit | b918a50341f33dea9ba709a96c4b0d67 | 23.934783 | 82 | 0.643418 | 3.125341 | false | false | false | false |
PravinNagargoje/CustomCalendar | CustomCalendar/CalendarViewController.swift | 1 | 9383 | //
// ViewController.swift
// CustomCalendar
//
// Created by APPLE-HOME on 21/09/17.
// Copyright ยฉ 2017 Encureit system's pvt.ltd. All rights reserved.
//
import UIKit
import JTAppleCalendar
protocol getDateDelegate {
func selectedDate(date: String, selected: Date)
}
class CalendarViewController: UIViewController {
let preDateSelectable: Bool = false
var delegate: getDateDelegate!
let outsideMonthColor = UIColor(hex: 0x584a66)
let monthColor = UIColor.white
let selectedMonthColor = UIColor(hex: 0x3a294b)
let currentDateSelectedViewColor = UIColor(hex: 0x4e3f5d)
var selected = Date()
@IBOutlet weak var calendarView: JTAppleCalendarView!
@IBOutlet weak var monthLabel: UILabel!
@IBOutlet weak var yearView: UIView!
@IBOutlet weak var selectedDate: UILabel!
@IBOutlet weak var dateView: UIView!
@IBOutlet weak var stackView: UIStackView!
@IBOutlet weak var topStackView: UIStackView!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var doneButton: UIButton!
let formatter = DateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupCalendarView()
setupTopStackView()
setupLabels()
setupButtons()
}
func setupTopStackView() {
topStackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
topStackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
topStackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
topStackView.widthAnchor.constraint(equalToConstant: 315),
topStackView.heightAnchor.constraint(equalToConstant: 433)
])
}
func setupButtons() {
doneButton.translatesAutoresizingMaskIntoConstraints = false
cancelButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
doneButton.bottomAnchor.constraint(equalTo: self.topStackView.bottomAnchor, constant: -8),
doneButton.trailingAnchor.constraint(equalTo: self.topStackView.trailingAnchor, constant: -24),
cancelButton.bottomAnchor.constraint(equalTo: self.topStackView.bottomAnchor, constant: -8),
cancelButton.trailingAnchor.constraint(equalTo: self.doneButton.leadingAnchor, constant: -24)
])
}
func setupLabels() {
monthLabel.translatesAutoresizingMaskIntoConstraints = false
yearView.translatesAutoresizingMaskIntoConstraints = false
dateView.translatesAutoresizingMaskIntoConstraints = false
selectedDate.translatesAutoresizingMaskIntoConstraints = false
dateView.translatesAutoresizingMaskIntoConstraints = false
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
yearView.topAnchor.constraint(equalTo: self.topStackView.topAnchor),
yearView.heightAnchor.constraint(equalToConstant: 50),
yearView.widthAnchor.constraint(equalTo: topStackView.widthAnchor, multiplier: 0),
monthLabel.centerYAnchor.constraint(equalTo: self.yearView.centerYAnchor),
monthLabel.centerXAnchor.constraint(equalTo: self.yearView.centerXAnchor),
dateView.topAnchor.constraint(equalTo: self.yearView.bottomAnchor, constant: 8),
dateView.widthAnchor.constraint(equalTo: topStackView.widthAnchor, multiplier: 0),
selectedDate.centerYAnchor.constraint(equalTo: self.dateView.centerYAnchor),
selectedDate.centerXAnchor.constraint(equalTo: self.dateView.centerXAnchor),
stackView.topAnchor.constraint(equalTo: self.dateView.bottomAnchor, constant: 16),
stackView.widthAnchor.constraint(equalTo: topStackView.widthAnchor, multiplier: 0)
])
}
func setupCalendarView() {
// Setup calendar spacing
calendarView.minimumLineSpacing = 0
calendarView.minimumInteritemSpacing = 0
// Setup labels
calendarView.scrollToDate(selected, animateScroll: false)
calendarView.selectDates([selected])
calendarView.visibleDates { (visibleDates) in
self.setupViewsOfCalendar(from: visibleDates)
}
}
func setupViewsOfCalendar(from visibleDates: DateSegmentInfo) {
let date = visibleDates.monthDates.first!.date
formatter.dateFormat = "yyyy"
let year = formatter.string(from: date)
formatter.dateFormat = "MMMM"
let month = formatter.string(from: date)
monthLabel.text = "\(month), \(year)"
}
func setDate(date: Date) {
let formatters = DateFormatter()
formatters.dateFormat = "dd MMM yyyy"
self.selected = date
selectedDate.text = formatters.string(from: date)
}
func handleCellTextColor(view: JTAppleCell?, cellState: CellState) {
guard let validCell = view as? CustomCell else { return }
if cellState.isSelected {
validCell.dateLabel.textColor = UIColor.darkGray
} else {
if cellState.dateBelongsTo == .thisMonth {
validCell.dateLabel.textColor = monthColor
} else {
validCell.dateLabel.textColor = outsideMonthColor
}
}
}
@IBAction func cancelClicked(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func doneClicked(_ sender: Any) {
self.delegate?.selectedDate(date: selectedDate.text!, selected: self.selected)
self.dismiss(animated: true, completion: nil)
}
func handleCellSelected(view: JTAppleCell?, cellState: CellState, date: Date) {
guard let validCell = view as? CustomCell else { return }
if cellState.dateBelongsTo != .thisMonth {
validCell.dateLabel.text = ""
validCell.isUserInteractionEnabled = false
validCell.selectedView.isHidden = true
} else if date.isSmaller(to: Date()) && !preDateSelectable {
validCell.dateLabel.text = "-"
validCell.isUserInteractionEnabled = false
validCell.selectedView.isHidden = true
} else {
validCell.isUserInteractionEnabled = true
if cellState.isSelected {
view?.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
UIView.animate(
withDuration: 0.5,
delay: 0, usingSpringWithDamping: 0.3,
initialSpringVelocity: 0.1,
options: UIViewAnimationOptions.beginFromCurrentState,
animations: {
view?.transform = CGAffineTransform(scaleX: 1, y: 1)
},
completion: { _ in
})
validCell.selectedView.isHidden = false
} else {
validCell.selectedView.isHidden = true
}
validCell.dateLabel.text = cellState.text
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension CalendarViewController: JTAppleCalendarViewDataSource {
func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
formatter.dateFormat = "yyyy MM dd"
formatter.timeZone = Calendar.current.timeZone
formatter.locale = Calendar.current.locale
let startDate = Date()
let endDate = formatter.date(from: "2050 12 31")
let parameters = ConfigurationParameters(startDate: startDate, endDate: endDate!)
return parameters
}
}
extension CalendarViewController: JTAppleCalendarViewDelegate {
// Display Cell
func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell {
let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.dateLabel.text = cellState.text
handleCellSelected(view: cell, cellState: cellState, date: date)
handleCellTextColor(view: cell, cellState: cellState)
return cell
}
func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
handleCellSelected(view: cell, cellState: cellState, date: date)
handleCellTextColor(view: cell, cellState: cellState)
setDate(date: date)
}
func calendar(_ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
handleCellSelected(view: cell, cellState: cellState, date: date)
handleCellTextColor(view: cell, cellState: cellState)
}
func calendar(_ calendar: JTAppleCalendarView, didScrollToDateSegmentWith visibleDates: DateSegmentInfo) {
setupViewsOfCalendar(from: visibleDates)
}
}
| mit | 8fdf3ebadd58b790b086dc121ba3f33d | 37.293878 | 137 | 0.654018 | 5.423121 | false | false | false | false |
nikHowlett/Attend-O | attendo1/Assignment.swift | 1 | 6974 | //
// Assignment.swift
// T-Squared for Georgia Tech
//
// Created by Cal on 9/12/15.
// Copyright ยฉ 2015 Cal Stephens. All rights reserved.
//
import Foundation
import Kanna
class Assignment {
let name: String
let link: String
let rawDueDateString: String
let dueDate: NSDate?
let completed: Bool
let owningClass: Class
var message: String?
var attachments: [Attachment]?
var submissions: [Attachment]?
var usesInlineText = false
var feedback: String?
init(name: String, link: String, dueDate: String, completed: Bool, inClass owningClass: Class) {
self.owningClass = owningClass
self.name = name
self.link = link
self.rawDueDateString = dueDate
self.completed = completed
self.dueDate = dueDate.dateWithTSquareFormat()
}
func loadMessage(attempt attempt: Int = 0) {
message = nil
attachments = nil
submissions = nil
feedback = nil
if let page = HttpClient.contentsOfPage(self.link) {
if !page.toHTML!.containsString("<div class=\"textPanel\">") {
if attempt > 10 {
self.message = "Could not load message for assignment."
}
self.loadMessage(attempt: attempt + 1)
}
else {
//load attachments if present
//split into submissions and attachments
let html = page.toHTML!
let splits: [String]
if html.containsString("<h5>Submitted Attachments</h5>") {
splits = page.toHTML!.componentsSeparatedByString("<h5>Submitted Attachments</h5>")
}
else if html.containsString("id=\"addSubmissionForm\"") {
splits = page.toHTML!.componentsSeparatedByString("id=\"addSubmissionForm\"")
}
else if html.containsString("Original submission text") {
splits = page.toHTML!.componentsSeparatedByString("Original submission text")
}
else if html.containsString("instructor\'s comments") {
splits = page.toHTML!.componentsSeparatedByString("instructor\'s comments")
}
else {
splits = [page.toHTML!]
}
let attachmentsPage = HTML(html: splits[0], encoding: NSUTF8StringEncoding)!
let submissionsPage: HTMLDocument? = splits.count != 1 ? HTML(html: splits[1], encoding: NSUTF8StringEncoding)! : nil
//load main message
var message: String = ""
for divTag in attachmentsPage.css("div") {
if divTag["class"] != "textPanel" { continue }
var text = divTag.textWithLineBreaks
if text.hasPrefix("ย Assignment Instructions") {
text = (text as NSString).substringFromIndex(24)
}
message += text
}
if message == "" {
message = "No message content."
}
message = message.withNoTrailingWhitespace()
message = (message as NSString).stringByReplacingOccurrencesOfString("<o:p>", withString: "")
message = (message as NSString).stringByReplacingOccurrencesOfString("</o:p>", withString: "")
self.message = message
//load attachments
for link in attachmentsPage.css("a, link") {
let linkURL = link["href"] ?? ""
if linkURL.containsString("/attachment/") {
let attachment = Attachment(link: linkURL, fileName: link.text?.cleansed() ?? "Attached file")
if self.attachments == nil { self.attachments = [] }
self.attachments!.append(attachment)
}
}
//load submissions
if let submissionsPage = submissionsPage {
//load submission attachments
for link in submissionsPage.css("a, link") {
let linkURL = link["href"] ?? ""
if linkURL.containsString("/attachment/") {
let attachment = Attachment(link: linkURL, fileName: link.text?.cleansed() ?? "Attached file")
if self.submissions == nil { self.submissions = [] }
self.submissions!.append(attachment)
}
}
var submittedString: String?
//load submitted text
if html.containsString("Original submission text") {
for div in submissionsPage.css("div") {
if div["class"] != "textPanel" { continue }
submittedString = div.toHTML!
var trimmedText = submittedString?.stringByReplacingOccurrencesOfString("<div class=\"textPanel\">", withString: "")
trimmedText = trimmedText?.stringByReplacingOccurrencesOfString("</div>", withString: "")
var title = "Submitted Text"
let links = linksInText(trimmedText!)
if links.count == 1 && trimmedText!.cleansed() == links[0].text {
title = websiteForLink(links[0].text)
}
let submittedText = Attachment(fileName: title, rawText: trimmedText!)
if self.submissions == nil { self.submissions = [] }
self.submissions!.append(submittedText)
self.usesInlineText = true
break
}
}
//load submission comments
var feedback: String = ""
for divTag in submissionsPage.css("div") {
if divTag["class"] != "textPanel" { continue }
if divTag.toHTML! == (submittedString ?? "") { continue }
feedback += divTag.textWithLineBreaks
}
if feedback != "" {
self.feedback = feedback.withNoTrailingWhitespace()
}
}
}
}
}
}
| mit | 192bccc24d6d5c4cdd39dd91c59e9b79 | 41.773006 | 144 | 0.472605 | 6 | false | false | false | false |
abertelrud/swift-package-manager | Tests/PackageLoadingTests/ToolsVersionParserTests.swift | 2 | 58282 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import PackageModel
import PackageLoading
import SPMTestSupport
import TSCBasic
import XCTest
class ToolsVersionParserTests: XCTestCase {
func parse(_ content: String, _ body: ((ToolsVersion) -> Void)? = nil) throws {
let toolsVersion = try ToolsVersionParser.parse(utf8String: content)
body?(toolsVersion)
}
/// Verifies correct parsing for valid version specifications, and that the parser isn't confused by contents following the version specification.
func testValidVersions() throws {
let manifestsSnippetWithValidVersionSpecification = [
// No spacing surrounding the label for Swift โฅ 5.4:
"//swift-tools-version:5.4.0" : (5, 4, 0, "5.4.0"),
"//swift-tools-version:5.4-dev" : (5, 4, 0, "5.4.0"),
"//swift-tools-version:5.8.0" : (5, 8, 0, "5.8.0"),
"//swift-tools-version:5.8.0-dev.al+sha.x" : (5, 8, 0, "5.8.0"),
"//swift-tools-version:6.1.2" : (6, 1, 2, "6.1.2"),
"//swift-tools-version:6.1.2;" : (6, 1, 2, "6.1.2"),
"//swift-tools-vErsion:6.1.2;;;;;" : (6, 1, 2, "6.1.2"),
"//swift-tools-version:6.1.2;x;x;x;x;x;" : (6, 1, 2, "6.1.2"),
"//swift-toolS-version:5.5.2;hello" : (5, 5, 2, "5.5.2"),
"//sWiFt-tOoLs-vErSiOn:5.5.2\nkkk\n" : (5, 5, 2, "5.5.2"),
// No spacing before, and 1 space (U+0020) after the label for Swift โฅ 5.4:
"//swift-tools-version: 5.4.0" : (5, 4, 0, "5.4.0"),
"//swift-tools-version: 5.4-dev" : (5, 4, 0, "5.4.0"),
"//swift-tools-version: 5.8.0" : (5, 8, 0, "5.8.0"),
"//swift-tools-version: 5.8.0-dev.al+sha.x" : (5, 8, 0, "5.8.0"),
"//swift-tools-version: 6.1.2" : (6, 1, 2, "6.1.2"),
"//swift-tools-version: 6.1.2;" : (6, 1, 2, "6.1.2"),
"//swift-tools-vErsion: 6.1.2;;;;;" : (6, 1, 2, "6.1.2"),
"//swift-tools-version: 6.1.2;x;x;x;x;x;" : (6, 1, 2, "6.1.2"),
"//swift-toolS-version: 5.5.2;hello" : (5, 5, 2, "5.5.2"),
"//sWiFt-tOoLs-vErSiOn: 5.5.2\nkkk\n" : (5, 5, 2, "5.5.2"),
// 1 space (U+0020) before, and no spacing after the label:
"// swift-tools-version:3.1" : (3, 1, 0, "3.1.0"),
"// swift-tools-version:3.1-dev" : (3, 1, 0, "3.1.0"),
"// swift-tools-version:5.8.0" : (5, 8, 0, "5.8.0"),
"// swift-tools-version:5.8.0-dev.al+sha.x" : (5, 8, 0, "5.8.0"),
"// swift-tools-version:3.1.2" : (3, 1, 2, "3.1.2"),
"// swift-tools-version:3.1.2;" : (3, 1, 2, "3.1.2"),
"// swift-tools-vErsion:3.1.2;;;;;" : (3, 1, 2, "3.1.2"),
"// swift-tools-version:3.1.2;x;x;x;x;x;" : (3, 1, 2, "3.1.2"),
"// swift-toolS-version:3.5.2;hello" : (3, 5, 2, "3.5.2"),
"// sWiFt-tOoLs-vErSiOn:3.5.2\nkkk\n" : (3, 5, 2, "3.5.2"),
// leading line feeds (U+000A) before the specification, and 1 space (U+0020) before and no space after the label for Swift โฅ 5.4:
"\n// swift-tools-version:6.1" : (6, 1, 0, "6.1.0"),
"\n\n// swift-tools-version:6.2-dev" : (6, 2, 0, "6.2.0"),
"\n\n\n// swift-tools-version:5.8.0" : (5, 8, 0, "5.8.0"),
"\n\n\n\n// swift-tools-version:6.8.0-dev.al+sha.x" : (6, 8, 0, "6.8.0"),
"\n\n\n\n\n// swift-tools-version:7.1.2" : (7, 1, 2, "7.1.2"),
"\n\n\n\n\n\n// swift-tools-version:8.1.2;" : (8, 1, 2, "8.1.2"),
"\n\n\n\n\n\n\n// swift-tools-vErsion:9.1.2;;;;;" : (9, 1, 2, "9.1.2"),
"\n\n\n\n\n\n\n\n// swift-tools-version:6.1.2;x;x;x;x;x;" : (6, 1, 2, "6.1.2"),
"\n\n\n\n\n\n\n\n\n// swift-toolS-version:5.5.2;hello" : (5, 5, 2, "5.5.2"),
"\n\n\n\n\n\n\n\n\n\n// sWiFt-tOoLs-vErSiOn:6.5.2\nkkk\n" : (6, 5, 2, "6.5.2"),
// An assortment of horizontal whitespace characters surrounding the label for Swift โฅ 5.4:
"//swift-tools-version:\u{2002}\u{202F}\u{3000}\u{A0}\u{1680}\t\u{2000}\u{2001}5.4.0" : (5, 4, 0, "5.4.0"),
"//\u{2001}swift-tools-version:\u{2002}\u{202F}\u{3000}\u{A0}\u{1680}\t\u{2000}5.4-dev" : (5, 4, 0, "5.4.0"),
"//\t\u{2000}\u{2001}swift-tools-version:\u{2002}\u{202F}\u{3000}\u{A0}\u{1680}5.8.0" : (5, 8, 0, "5.8.0"),
"//\u{1680}\t\u{2000}\u{2001}swift-tools-version:\u{2002}\u{202F}\u{3000}\u{A0}5.8.0-dev.al+sha.x" : (5, 8, 0, "5.8.0"),
"//\u{A0}\u{1680}\t\u{2000}\u{2001}swift-tools-version:\u{2002}\u{202F}\u{3000}6.1.2" : (6, 1, 2, "6.1.2"),
"//\u{3000}\u{A0}\u{1680}\t\u{2000}\u{2001}swift-tools-version:\u{2002}\u{202F}6.1.2;" : (6, 1, 2, "6.1.2"),
"//\u{202F}\u{3000}\u{A0}\u{1680}\t\u{2000}\u{2001}swift-tools-vErsion:\u{2002}6.1.2;;;;;" : (6, 1, 2, "6.1.2"),
"//\u{2002}\u{202F}\u{3000}\u{A0}\u{1680}\t\u{2000}\u{2001}swift-tools-version:6.1.2;x;x;x;x;x;" : (6, 1, 2, "6.1.2"),
"//\u{2000}\u{2002}\u{202F}\u{3000}\t\u{2001}swift-toolS-version:\u{A0}\u{1680}5.5.2;hello" : (5, 5, 2, "5.5.2"),
"//\u{2000}\u{2001}\u{2002}\u{202F}\u{3000}\tsWiFt-tOoLs-vErSiOn:\u{A0}\u{1680}5.5.2\nkkk\n" : (5, 5, 2, "5.5.2"),
// Some leading whitespace characters, and no spacing surrounding the label for Swift โฅ 5.4:
"\u{A} //swift-tools-version:5.4.0" : (5, 4, 0, "5.4.0"),
"\u{B}\t\u{A}//swift-tools-version:5.4-dev" : (5, 4, 0, "5.4.0"),
"\u{3000}\u{A0}\u{C}//swift-tools-version:5.8.0" : (5, 8, 0, "5.8.0"),
"\u{2002}\u{D}\u{2001}//swift-tools-version:5.8.0-dev.al+sha.x" : (5, 8, 0, "5.8.0"),
"\u{D}\u{A}\u{A0}\u{1680}//swift-tools-version:6.1.2" : (6, 1, 2, "6.1.2"),
" \u{85}//swift-tools-version:6.1.2;" : (6, 1, 2, "6.1.2"),
"\u{2028}//swift-tools-vErsion:6.1.2;;;;;" : (6, 1, 2, "6.1.2"),
"\u{202F}\u{2029}//swift-tools-version:6.1.2;x;x;x;x;x;" : (6, 1, 2, "6.1.2"),
"\u{A}\u{B}\u{C}\u{D}\u{A}\u{D}\u{85}\u{202F}\u{2029}\u{2001}\u{2002}\u{205F}\u{85}\u{2028}//swift-toolS-version:5.5.2;hello" : (5, 5, 2, "5.5.2"),
"\u{B} \u{200A}\u{D}\u{A}\t\u{85}\u{85}\u{A}\u{2028}\u{2009}\u{2001}\u{C}//sWiFt-tOoLs-vErSiOn:5.5.2\nkkk\n" : (5, 5, 2, "5.5.2"),
// Some leading whitespace characters, and an assortment of horizontal whitespace characters surrounding the label for Swift โฅ 5.4:
"\u{2002}\u{202F}\u{A}//\u{A0}\u{1680}\t\u{2004}\u{2001} \u{2002}swift-tools-version:\u{3000}5.4.0" : (5, 4, 0, "5.4.0"),
"\u{B}//\u{A0}\u{1680}\t\u{2000}\u{2001} \u{2002}swift-tools-version:\u{202F}\u{3000}5.4-dev" : (5, 4, 0, "5.4.0"),
"\u{C}//\u{A0}\u{1680}\t\u{2000}\u{2001} swift-tools-version:\u{2002}\u{202F}\u{3000}5.8.0" : (5, 8, 0, "5.8.0"),
"\u{D}//\u{A0}\u{1680}\t\u{2005} \u{202F}\u{3000}swift-tools-version:\u{2001}5.8.0-dev.al+sha.x" : (5, 8, 0, "5.8.0"),
"\u{D}\u{A}//\u{A0}\u{2001} \u{2002}\u{202F}\u{3000}swift-tools-version:\u{1680}\t\u{2000}6.1.2" : (6, 1, 2, "6.1.2"),
"\u{85}//\u{2000}\u{2001} \u{2006}\u{202F}\u{3000}swift-tools-version:\u{A0}\u{1680}\t6.1.2;" : (6, 1, 2, "6.1.2"),
"\u{2028}//\u{2001} \u{2002}\u{2007}\u{3000}swift-tools-vErsion:\u{A0}\u{1680}\t\u{2000}6.1.2;;;;;" : (6, 1, 2, "6.1.2"),
"\u{2029}//\u{202F}\u{3000}swift-tools-version:\u{A0}\u{1680}\t\u{2000}\u{2001} \u{2002}6.1.2;x;x;x;x;x;" : (6, 1, 2, "6.1.2"),
"\u{A}\u{D}\u{85}\u{202F}\u{2029}\u{A}\u{2028}//\u{2000}\u{2001}\u{9}swift-toolS-version:\u{A0}\u{1680}\t\u{2000}\u{2009} \u{2002}\u{202F}5.5.2;hello" : (5, 5, 2, "5.5.2"),
"\u{D}\u{A}\t\u{85}\u{85}\u{A}\u{2028}\u{2029}//\u{2001}\u{2002}\u{202F}sWiFt-tOoLs-vErSiOn:\u{1680}\t\u{2000}\u{200A} \u{2002}\u{202F}5.5.2\nkkk\n" : (5, 5, 2, "5.5.2"),
]
for (snippet, result) in manifestsSnippetWithValidVersionSpecification {
try self.parse(snippet) { toolsVersion in
XCTAssertEqual(toolsVersion.major, result.0)
XCTAssertEqual(toolsVersion.minor, result.1)
XCTAssertEqual(toolsVersion.patch, result.2)
XCTAssertEqual(toolsVersion.description, result.3)
}
}
do {
let stream = BufferedOutputByteStream()
stream <<< "// swift-tools-version:3.1.0\n\n\n\n\n"
stream <<< "let package = .."
try self.parse(stream.bytes.validDescription!) { toolsVersion in
XCTAssertEqual(toolsVersion.description, "3.1.0")
}
}
do {
let stream = BufferedOutputByteStream()
stream <<< "// swift-tools-version:3.1.0\n"
stream <<< "// swift-tools-version:4.1.0\n\n\n\n"
stream <<< "let package = .."
try self.parse(stream.bytes.validDescription!) { toolsVersion in
XCTAssertEqual(toolsVersion.description, "3.1.0")
}
}
}
/// Verifies that if a manifest appears empty to SwiftPM, a distinct error is thrown.
func testEmptyManifest() throws {
let fs = InMemoryFileSystem()
let packageRoot = AbsolutePath(path: "/lorem/ipsum/dolor")
try fs.createDirectory(packageRoot, recursive: true)
let manifestPath = packageRoot.appending(component: "Package.swift")
try fs.writeFileContents(manifestPath, bytes: "")
XCTAssertThrowsError(
try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: fs),
"empty manifest '/lorem/ipsum/dolor/Package.swift'") { error in
guard let error = error as? ManifestParseError, case .emptyManifest(let errorPath) = error else {
XCTFail("'ManifestParseError.emptyManifest' should've been thrown, but a different error is thrown")
return
}
guard errorPath == manifestPath else {
XCTFail("error is in '\(manifestPath)', but '\(errorPath)' is given for the error message")
return
}
XCTAssertEqual(error.description, "'/lorem/ipsum/dolor/Package.swift' is empty")
}
}
/// Verifies that the correct error is thrown for each non-empty manifest missing its Swift tools version specification.
func testMissingSpecifications() throws {
/// Leading snippets of manifest files that don't have Swift tools version specifications.
let manifestSnippetsWithoutSpecification = [
"\n",
"\n\r\r\n",
"ni",
"\rimport PackageDescription",
"let package = Package(\n",
]
for manifestSnippet in manifestSnippetsWithoutSpecification {
XCTAssertThrowsError(
try self.parse(manifestSnippet),
"a 'ToolsVersionLoader.Error' should've been thrown, because the Swift tools version specification is missing from the manifest snippet"
) { error in
guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.commentMarker(.isMissing)) = error else {
XCTFail("'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.commentMarker(.isMissing))' should've been thrown, but a different error is thrown")
return
}
XCTAssertEqual(
error.description,
"the manifest is missing a Swift tools version specification; consider prepending to the manifest '// swift-tools-version:\(ToolsVersion.current < .v5_4 ? "" : " ")\(ToolsVersion.current.major).\(ToolsVersion.current.minor)\(ToolsVersion.current.patch == 0 ? "" : ".\(ToolsVersion.current.patch)")' to specify the current Swift toolchain version as the lowest Swift version supported by the project; if such a specification already exists, consider moving it to the top of the manifest, or prepending it with '//' to help Swift Package Manager find it"
)
}
}
}
/// Verifies that the correct error is thrown for each Swift tools version specification missing its comment marker.
func testMissingSpecificationCommentMarkers() throws {
let manifestSnippetsWithoutSpecificationCommentMarker = [
" swift-tools-version:4.0",
// Missing comment markers are diagnosed before missing Labels.
" 4.2",
// Missing comment markers are diagnosed before missing version specifiers.
" swift-tools-version:",
" ",
// Missing comment markers are diagnosed before misspelt labels.
" Swift toolchain version 5.1",
" shiny-tools-version",
// Missing comment markers are diagnosed before misspelt version specifiers.
" swift-tools-version:0",
" The Answer to the Ultimate Question of Life, the Universe, and Everything is 42",
" 9999999",
// Missing comment markers are diagnosed before backward-compatibility checks.
"\n\n\nswift-tools-version:3.1\r",
"\r\n\r\ncontrafibularity",
"\n\r\t3.14",
]
for manifestSnippet in manifestSnippetsWithoutSpecificationCommentMarker {
XCTAssertThrowsError(
try self.parse(manifestSnippet),
"a 'ToolsVersionLoader.Error' should've been thrown, because the comment marker is missing from the Swift tools version specification"
) { error in
guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.commentMarker(.isMissing)) = error else {
XCTFail("'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.commentMarker(.isMissing))' should've been thrown, but a different error is thrown")
return
}
XCTAssertEqual(
error.description,
"the manifest is missing a Swift tools version specification; consider prepending to the manifest '// swift-tools-version:\(ToolsVersion.current < .v5_4 ? "" : " ")\(ToolsVersion.current.major).\(ToolsVersion.current.minor)\(ToolsVersion.current.patch == 0 ? "" : ".\(ToolsVersion.current.patch)")' to specify the current Swift toolchain version as the lowest Swift version supported by the project; if such a specification already exists, consider moving it to the top of the manifest, or prepending it with '//' to help Swift Package Manager find it"
)
}
}
}
/// Verifies that the correct error is thrown for each Swift tools version specification missing its label.
func testMissingSpecificationLabels() throws {
let manifestSnippetsWithoutSpecificationLabel = [
"// 5.3",
// Missing labels are diagnosed before missing version specifiers.
"// ",
// Missing labels are diagnosed before misspelt comment markers.
"/// ",
"/* ",
// Missing labels are diagnosed before misspelt version specifiers.
"// 6 ร 9 = 42",
"/// 99 little bugs in the code",
// Missing labels are diagnosed before backward-compatibility checks.
"\r\n// ",
"//",
"\n\r///\t2.1\r",
]
for manifestSnippet in manifestSnippetsWithoutSpecificationLabel {
XCTAssertThrowsError(
try self.parse(manifestSnippet),
"a 'ToolsVersionLoader.Error' should've been thrown, because the label is missing from the Swift tools version specification"
) { error in
guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.label(.isMissing)) = error else {
XCTFail("'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.label(.isMissing))' should've been thrown, but a different error is thrown")
return
}
XCTAssertEqual(
error.description,
"the Swift tools version specification is missing a label; consider inserting 'swift-tools-version:' between the comment marker and the version specifier"
)
}
}
}
/// Verifies that the correct error is thrown for each Swift tools version specification missing its version specifier.
func testMissingVersionSpecifiers() throws {
let manifestSnippetsWithoutVersionSpecifier = [
"// swift-tools-version:",
// Missing version specifiers are diagnosed before misspelt comment markers.
"/// swift-tools-version:",
"/* swift-tools-version:",
// Missing version specifiers are diagnosed before misspelt labels.
"// swallow tools version:",
"/// We are the knights who say 'Ni!'",
// Missing version specifiers are diagnosed before backward-compatibility checks.
"\r\n//\tswift-tools-version:",
"\n\r///The swifts hung in the sky in much the same way that bricks don't.\u{85}",
]
for manifestSnippet in manifestSnippetsWithoutVersionSpecifier {
XCTAssertThrowsError(
try self.parse(manifestSnippet),
"a 'ToolsVersionLoader.Error' should've been thrown, because the version specifier is missing from the Swift tools version specification"
) { error in
guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.versionSpecifier(.isMissing)) = error else {
XCTFail("'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.versionSpecifier(.isMissing))' should've been thrown, but a different error is thrown")
return
}
XCTAssertEqual(
error.description,
"the Swift tools version specification is possibly missing a version specifier; consider using '// swift-tools-version:\(ToolsVersion.current < .v5_4 ? "" : " ")\(ToolsVersion.current.major).\(ToolsVersion.current.minor)\(ToolsVersion.current.patch == 0 ? "" : ".\(ToolsVersion.current.patch)")' to specify the current Swift toolchain version as the lowest Swift version supported by the project"
)
}
}
}
/// Verifies that the correct error is thrown for each misspelt comment marker in Swift tools version specification.
func testMisspeltSpecificationCommentMarkers() throws {
let manifestSnippetsWithMisspeltSpecificationCommentMarker = [
"/// swift-tools-version:4.0",
"/** swift-tools-version:4.1",
// Misspelt comment markers are diagnosed before misspelt labels.
"//// Shiny toolchain version 4.2",
// Misspelt comment markers are diagnosed before misspelt version specifiers.
"/* swift-tools-version:43",
"/** Swift version 4.4 **/",
// Misspelt comment markers are diagnosed before backward-compatibility checks.
"\r\r\r*/swift-tools-version:4.5",
"\n\n\n/*/*\t\tSwift5\r",
]
for manifestSnippet in manifestSnippetsWithMisspeltSpecificationCommentMarker {
XCTAssertThrowsError(
try self.parse(manifestSnippet),
"a 'ToolsVersionLoader.Error' should've been thrown, because the comment marker is misspelt in the Swift tools version specification"
) { error in
guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.commentMarker(.isMisspelt(let misspeltCommentMarker))) = error else {
XCTFail("'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.commentMarker(.isMisspelt))' should've been thrown, but a different error is thrown")
return
}
XCTAssertEqual(
error.description,
"the comment marker '\(misspeltCommentMarker)' is misspelt for the Swift tools version specification; consider replacing it with '//'"
)
}
}
}
/// Verifies that the correct error is thrown for each misspelt label in Swift tools version specification.
func testMisspeltSpecificationLabels() throws {
let manifestSnippetsWithMisspeltSpecificationLabel = [
"// fast-tools-version:3.0",
// Misspelt labels are diagnosed before misspelt version specifiers.
"// rapid-tools-version:3",
"// swift-too1s-version:3.0",
// Misspelt labels are diagnosed before backward-compatibility checks.
"\n\r//\t\u{A0}prompt-t00ls-version:3.0.0.0\r\n",
]
for manifestSnippet in manifestSnippetsWithMisspeltSpecificationLabel {
XCTAssertThrowsError(
try self.parse(manifestSnippet),
"a 'ToolsVersionLoader.Error' should've been thrown, because the label is misspelt in the Swift tools version specification"
) { error in
guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.label(.isMisspelt(let misspeltLabel))) = error else {
XCTFail("'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.label(.isMisspelt))' should've been thrown, but a different error is thrown")
return
}
XCTAssertEqual(
error.description,
"the Swift tools version specification's label '\(misspeltLabel)' is misspelt; consider replacing it with 'swift-tools-version:'"
)
}
}
}
/// Verifies that the correct error is thrown for each misspelt version specifier in Swift tools version specification.
func testMisspeltVersionSpecifiers() throws {
let manifestSnippetsWithMisspeltVersionSpecifier = [
"// swift-tools-version:5ยฒ",
"// swift-tools-version:5โฃ๏ธ.2โฃ๏ธ",
"// swift-tools-version:5 รท 2 = 2.5",
// If the label starts with exactly "swift-tools-version:" (case-insensitive), then all its misspellings are treated as the version specifier's.
"// swift-tools-version::5.2",
"// Swift-tOOls-versIon:-2.5",
// Misspelt version specifiers are diagnosed before backward-compatibility checks.
"\u{A}\u{B}\u{C}\u{D}//\u{3000}swift-tools-version:ไบ.ไบ\u{2028}",
]
for manifestSnippet in manifestSnippetsWithMisspeltVersionSpecifier {
XCTAssertThrowsError(
try self.parse(manifestSnippet),
"a 'ToolsVersionLoader.Error' should've been thrown, because the version specifier is misspelt in the Swift tools version specification"
) { error in
guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.versionSpecifier(.isMisspelt(let misspeltVersionSpecifier))) = error else {
XCTFail("'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.versionSpecifier(.isMisspelt))' should've been thrown, but a different error is thrown")
return
}
XCTAssertEqual(
error.description,
"the Swift tools version '\(misspeltVersionSpecifier)' is misspelt or otherwise invalid; consider replacing it with '\(ToolsVersion.current.specification())' to specify the current Swift toolchain version as the lowest Swift version supported by the project"
)
}
}
}
/// Verifies that a correct error is thrown, if the manifest is valid for Swift tools version โฅ 5.4, but invalid for version < 5.4.
func testBackwardIncompatibilityPre5_4() throws {
// The order of tests in this function:
// 1. Test backward-incompatible leading whitespace for Swift < 5.4.
// 2. Test that backward-incompatible leading whitespace is diagnosed before backward-incompatible spacings.
// 3. Test spacings before the label.
// 4. Test that backward-incompatible spacings before the label are diagnosed before those after the label.
// 5. Test spacings after the label.
// MARK: 1 leading u+000D
let manifestSnippetWith1LeadingCarriageReturn = [
"\u{D}//swift-tools-version:3.1" : "3.1.0",
"\u{D}//swift-tools-version:3.1-dev" : "3.1.0",
"\u{D}//swift-tools-version:5.3" : "5.3.0",
"\u{D}//swift-tools-version:5.3.0" : "5.3.0",
"\u{D}//swift-tools-version:5.3-dev" : "5.3.0",
"\u{D}//swift-tools-version:4.8.0" : "4.8.0",
"\u{D}//swift-tools-version:4.8.0-dev.al+sha.x" : "4.8.0",
"\u{D}//swift-tools-version:3.1.2" : "3.1.2",
"\u{D}//swift-tools-version:3.1.2;" : "3.1.2",
"\u{D}//swift-tools-vErsion:3.1.2;;;;;" : "3.1.2",
"\u{D}//swift-tools-version:3.1.2;x;x;x;x;x;" : "3.1.2",
"\u{D}//swift-toolS-version:3.5.2;hello" : "3.5.2",
"\u{D}//sWiFt-tOoLs-vErSiOn:3.5.2\nkkk\n" : "3.5.2",
]
for (specification, toolsVersionString) in manifestSnippetWith1LeadingCarriageReturn {
XCTAssertThrowsError(
try self.parse(specification),
"a 'ToolsVersionLoader.Error' should've been thrown, because the manifest starts with a U+000D, and the specified version \(toolsVersionString) (< 5.4) supports only leading line feeds (U+000A)."
) { error in
guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.leadingWhitespace, _) = error else {
XCTFail("'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.leadingWhitespace, _)' should've been thrown, but a different error is thrown.")
return
}
XCTAssertEqual(
error.description,
"leading whitespace sequence [U+000D] in manifest is supported by only Swift โฅ 5.4; the specified version \(toolsVersionString) supports only line feeds (U+000A) preceding the Swift tools version specification; consider moving the Swift tools version specification to the first line of the manifest"
)
}
}
// MARK: 1 U+0020
let manifestSnippetWith1LeadingSpace = [
"\u{20}//swift-tools-version:3.1" : "3.1.0",
"\u{20}//swift-tools-version:3.1-dev" : "3.1.0",
"\u{20}//swift-tools-version:5.3" : "5.3.0",
"\u{20}//swift-tools-version:5.3.0" : "5.3.0",
"\u{20}//swift-tools-version:5.3-dev" : "5.3.0",
"\u{20}//swift-tools-version:4.8.0" : "4.8.0",
"\u{20}//swift-tools-version:4.8.0-dev.al+sha.x" : "4.8.0",
"\u{20}//swift-tools-version:3.1.2" : "3.1.2",
"\u{20}//swift-tools-version:3.1.2;" : "3.1.2",
"\u{20}//swift-tools-vErsion:3.1.2;;;;;" : "3.1.2",
"\u{20}//swift-tools-version:3.1.2;x;x;x;x;x;" : "3.1.2",
"\u{20}//swift-toolS-version:3.5.2;hello" : "3.5.2",
"\u{20}//sWiFt-tOoLs-vErSiOn:3.5.2\nkkk\n" : "3.5.2",
]
for (specification, toolsVersionString) in manifestSnippetWith1LeadingSpace {
XCTAssertThrowsError(
try self.parse(specification),
"a 'ToolsVersionLoader.Error' should've been thrown, because the manifest starts with a U+0020, and the specified version \(toolsVersionString) (< 5.4) supports only leading line feeds (U+000A)."
) { error in
guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.leadingWhitespace, _) = error else {
XCTFail("'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.leadingWhitespace, _)' should've been thrown, but a different error is thrown.")
return
}
XCTAssertEqual(
error.description,
"leading whitespace sequence [U+0020] in manifest is supported by only Swift โฅ 5.4; the specified version \(toolsVersionString) supports only line feeds (U+000A) preceding the Swift tools version specification; consider moving the Swift tools version specification to the first line of the manifest"
)
}
}
// MARK: An assortment of leading whitespace characters
let manifestSnippetWithAnAssortmentOfLeadingWhitespaceCharacters = [
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-tools-version:3.1" : "3.1.0",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-tools-version:3.1-dev" : "3.1.0",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-tools-version:5.3" : "5.3.0",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-tools-version:5.3.0" : "5.3.0",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-tools-version:5.3-dev" : "5.3.0",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-tools-version:4.8.0" : "4.8.0",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-tools-version:4.8.0-dev.al+sha.x" : "4.8.0",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-tools-version:3.1.2" : "3.1.2",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-tools-version:3.1.2;" : "3.1.2",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-tools-vErsion:3.1.2;;;;;" : "3.1.2",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-tools-version:3.1.2;x;x;x;x;x;" : "3.1.2",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//swift-toolS-version:3.5.2;hello" : "3.5.2",
"\u{A}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}\u{D}\u{D}\u{A}\u{85}\u{2001}\u{2028}\u{2002}\u{202F}\u{2029}\u{3000}//sWiFt-tOoLs-vErSiOn:3.5.2\nkkk\n" : "3.5.2",
]
for (specification, toolsVersionString) in manifestSnippetWithAnAssortmentOfLeadingWhitespaceCharacters {
XCTAssertThrowsError(
try self.parse(specification),
"a 'ToolsVersionLoader.Error' should've been thrown, because the manifest starts with an assortment of whitespace characters, and the specified version \(toolsVersionString) (< 5.4) supports only leading line feeds (U+000A)."
) { error in
guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.leadingWhitespace, _) = error else {
XCTFail("'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.leadingWhitespace, _)' should've been thrown, but a different error is thrown.")
return
}
XCTAssertEqual(
error.description,
"leading whitespace sequence [U+000A, U+00A0, U+000B, U+1680, U+000C, U+0009, U+2000, U+000D, U+000D, U+000A, U+0085, U+2001, U+2028, U+2002, U+202F, U+2029, U+3000] in manifest is supported by only Swift โฅ 5.4; the specified version \(toolsVersionString) supports only line feeds (U+000A) preceding the Swift tools version specification; consider moving the Swift tools version specification to the first line of the manifest"
)
}
}
// MARK: An assortment of leading whitespace characters and an assortment of horizontal whitespace characters surrounding the label
let manifestSnippetWithAnAssortmentOfLeadingWhitespaceCharactersAndAnAssortmentOfWhitespacesSurroundingLabel = [
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}3.1" : "3.1.0",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}3.1-dev" : "3.1.0",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}5.3" : "5.3.0",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}5.3.0" : "5.3.0",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}5.3-dev" : "5.3.0",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}4.8.0" : "4.8.0",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}4.8.0-dev.al+sha.x" : "4.8.0",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}3.1.2" : "3.1.2",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}3.1.2;" : "3.1.2",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-vErsion:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}3.1.2;;;;;" : "3.1.2",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}3.1.2;x;x;x;x;x;" : "3.1.2",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-toolS-version:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}3.5.2;hello" : "3.5.2",
"\u{D}\u{202F}\u{2029}\u{85}\u{2001}\u{2028}\u{3000}\u{A}\u{D}\u{A}\u{2002}\u{A0}\u{B}\u{1680}\u{C}\t\u{2000}//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}sWiFt-tOoLs-vErSiOn:\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}3.5.2\nkkk\n" : "3.5.2",
]
// Backward-incompatible leading whitespace is diagnosed before backward-incompatible spacings surrounding the label.
// So the errors thrown here should be about invalid leading whitespace, although both the leading whitespace and the spacings here are backward-incompatible.
for (specification, toolsVersionString) in manifestSnippetWithAnAssortmentOfLeadingWhitespaceCharactersAndAnAssortmentOfWhitespacesSurroundingLabel {
XCTAssertThrowsError(
try self.parse(specification),
"a 'ToolsVersionLoader.Error' should've been thrown, because the manifest starts with an assortment of whitespace characters, and the specified version \(toolsVersionString) (< 5.4) supports only leading line feeds (U+000A)."
) { error in
guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.leadingWhitespace, _) = error else {
XCTFail("'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.leadingWhitespace, _)' should've been thrown, but a different error is thrown.")
return
}
XCTAssertEqual(
error.description,
"leading whitespace sequence [U+000D, U+202F, U+2029, U+0085, U+2001, U+2028, U+3000, U+000A, U+000D, U+000A, U+2002, U+00A0, U+000B, U+1680, U+000C, U+0009, U+2000] in manifest is supported by only Swift โฅ 5.4; the specified version \(toolsVersionString) supports only line feeds (U+000A) preceding the Swift tools version specification; consider moving the Swift tools version specification to the first line of the manifest"
)
}
}
// MARK: No spacing surrounding the label
let specificationsWithZeroSpacing = [
"//swift-tools-version:3.1" : "3.1.0",
"//swift-tools-version:3.1-dev" : "3.1.0",
"//swift-tools-version:5.3" : "5.3.0",
"//swift-tools-version:5.3.0" : "5.3.0",
"//swift-tools-version:5.3-dev" : "5.3.0",
"//swift-tools-version:4.8.0" : "4.8.0",
"//swift-tools-version:4.8.0-dev.al+sha.x" : "4.8.0",
"//swift-tools-version:3.1.2" : "3.1.2",
"//swift-tools-version:3.1.2;" : "3.1.2",
"//swift-tools-vErsion:3.1.2;;;;;" : "3.1.2",
"//swift-tools-version:3.1.2;x;x;x;x;x;" : "3.1.2",
"//swift-toolS-version:3.5.2;hello" : "3.5.2",
"//sWiFt-tOoLs-vErSiOn:3.5.2\nkkk\n" : "3.5.2",
]
for (specification, toolsVersionString) in specificationsWithZeroSpacing {
XCTAssertThrowsError(
try self.parse(specification),
"a 'ToolsVersionLoader.Error' should've been thrown, because there is no spacing between '//' and 'swift-tools-version', and the specified version \(toolsVersionString) (< 5.4) supports exactly 1 space (U+0020) there"
) { error in
guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _) = error else {
XCTFail("'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _)' should've been thrown, but a different error is thrown.")
return
}
XCTAssertEqual(
error.description,
"zero spacing between '//' and 'swift-tools-version' is supported by only Swift โฅ 5.4; consider replacing the sequence with a single space (U+0020) for Swift \(toolsVersionString)"
)
}
}
// MARK: An assortment of horizontal whitespace characters before the label
let specificationsWithAnAssortmentOfWhitespacesBeforeLabel = [
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:3.1" : "3.1.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:3.1-dev" : "3.1.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:5.3" : "5.3.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:5.3.0" : "5.3.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:5.3-dev" : "5.3.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:4.8.0" : "4.8.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:4.8.0-dev.al+sha.x" : "4.8.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:3.1.2" : "3.1.2",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:3.1.2;" : "3.1.2",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-vErsion:3.1.2;;;;;" : "3.1.2",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-tools-version:3.1.2;x;x;x;x;x;" : "3.1.2",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}swift-toolS-version:3.5.2;hello" : "3.5.2",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}sWiFt-tOoLs-vErSiOn:3.5.2\nkkk\n" : "3.5.2",
]
for (specification, toolsVersionString) in specificationsWithAnAssortmentOfWhitespacesBeforeLabel {
XCTAssertThrowsError(
try self.parse(specification),
"a 'ToolsVersionLoader.Error' should've been thrown, because the spacing between '//' and 'swift-tools-version' is an assortment of horizontal whitespace characters, and the specified version \(toolsVersionString) (< 5.4) supports exactly 1 space (U+0020) there."
) { error in
guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _) = error else {
XCTFail("'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _)' should've been thrown, but a different error is thrown.")
return
}
XCTAssertEqual(
error.description,
"horizontal whitespace sequence [U+0009, U+0020, U+00A0, U+1680, U+2000, U+2001, U+2002, U+2003, U+2004, U+2005, U+2006, U+2007, U+2008, U+2009, U+200A, U+202F, U+205F, U+3000] between '//' and 'swift-tools-version' is supported by only Swift โฅ 5.4; consider replacing the sequence with a single space (U+0020) for Swift \(toolsVersionString)"
)
}
}
// MARK: An assortment of horizontal whitespace characters surrounding the label
let specificationsWithAnAssortmentOfWhitespacesBeforeAndAfterLabel = [
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-tools-version:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1" : "3.1.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-tools-version:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1-dev" : "3.1.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-tools-version:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}5.3" : "5.3.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-tools-version:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}5.3.0" : "5.3.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-tools-version:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}5.3-dev" : "5.3.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-tools-version:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}4.8.0" : "4.8.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-tools-version:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}4.8.0-dev.al+sha.x" : "4.8.0",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-tools-version:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1.2" : "3.1.2",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-tools-version:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1.2;" : "3.1.2",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-tools-vErsion:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1.2;;;;;" : "3.1.2",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-tools-version:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1.2;x;x;x;x;x;" : "3.1.2",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}swift-toolS-version:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.5.2;hello" : "3.5.2",
"//\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}sWiFt-tOoLs-vErSiOn:\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.5.2\nkkk\n" : "3.5.2",
]
// Backward-incompatible spacings after the comment marker is diagnosed before backward-incompatible spacings after the label.
// So the errors thrown here should be about invalid spacing after comment marker, although both the spacings here are backward-incompatible.
for (specification, toolsVersionString) in specificationsWithAnAssortmentOfWhitespacesBeforeAndAfterLabel {
XCTAssertThrowsError(
try self.parse(specification),
"a 'ToolsVersionLoader.Error' should've been thrown, because the spacing between '//' and 'swift-tools-version' is an assortment of horizontal whitespace characters, and the specified version \(toolsVersionString) (< 5.4) supports exactly 1 space (U+0020) there."
) { error in
guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _) = error else {
XCTFail("'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _)' should've been thrown, but a different error is thrown.")
return
}
XCTAssertEqual(
error.description,
"horizontal whitespace sequence [U+0009, U+0020, U+00A0, U+1680, U+2000, U+2001, U+2002, U+2003, U+2004] between '//' and 'swift-tools-version' is supported by only Swift โฅ 5.4; consider replacing the sequence with a single space (U+0020) for Swift \(toolsVersionString)"
)
}
}
// MARK: 1 U+0020 before the label and an assortment of horizontal whitespace characters after the label
let specificationsWithAnAssortmentOfWhitespacesAfterLabel = [
"// swift-tools-version:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1" : "3.1.0",
"// swift-tools-version:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1-dev" : "3.1.0",
"// swift-tools-version:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}5.3" : "5.3.0",
"// swift-tools-version:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}5.3.0" : "5.3.0",
"// swift-tools-version:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}5.3-dev" : "5.3.0",
"// swift-tools-version:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}4.8.0" : "4.8.0",
"// swift-tools-version:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}4.8.0-dev.al+sha.x" : "4.8.0",
"// swift-tools-version:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1.2" : "3.1.2",
"// swift-tools-version:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1.2;" : "3.1.2",
"// swift-tools-vErsion:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1.2;;;;;" : "3.1.2",
"// swift-tools-version:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.1.2;x;x;x;x;x;" : "3.1.2",
"// swift-toolS-version:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.5.2;hello" : "3.5.2",
"// sWiFt-tOoLs-vErSiOn:\u{9}\u{20}\u{A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}3.5.2\nkkk\n" : "3.5.2",
]
for (specification, toolsVersionString) in specificationsWithAnAssortmentOfWhitespacesAfterLabel {
XCTAssertThrowsError(
try self.parse(specification),
"a 'ToolsVersionLoader.Error' should've been thrown, because the spacing between 'swift-tools-version' and the version specifier is an assortment of horizontal whitespace characters, and the specified version \(toolsVersionString) (< 5.4) supports no spacing there."
) { error in
guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.spacingAfterLabel, _) = error else {
XCTFail("'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.spacingAfterLabel, _)' should've been thrown, but a different error is thrown.")
return
}
XCTAssertEqual(
error.description,
"horizontal whitespace sequence [U+0009, U+0020, U+00A0, U+1680, U+2000, U+2001, U+2002, U+2003, U+2004, U+2005, U+2006, U+2007, U+2008, U+2009, U+200A, U+202F, U+205F, U+3000] immediately preceding the version specifier is supported by only Swift โฅ 5.4; consider removing the sequence for Swift \(toolsVersionString)"
)
}
}
}
func testVersionSpecificManifest() throws {
let fs = InMemoryFileSystem()
let root = AbsolutePath(path: "/pkg")
try fs.createDirectory(root, recursive: true)
/// Loads the tools version of root pkg.
func parse(_ body: (ToolsVersion) -> Void) throws {
let manifestPath = try ManifestLoader.findManifest(packagePath: root, fileSystem: fs, currentToolsVersion: .current)
body(try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: fs))
}
// Test default manifest.
try fs.writeFileContents(root.appending(component: "Package.swift"), bytes: "// swift-tools-version:3.1.1\n")
try parse { version in
XCTAssertEqual(version.description, "3.1.1")
}
// Test version specific manifests.
let keys = ToolsVersion.current.versionSpecificKeys
// In case the count ever changes, we will need to modify this test.
XCTAssertEqual(keys.count, 3)
// Test the last key.
try fs.writeFileContents(root.appending(component: "Package\(keys[2]).swift"), bytes: "// swift-tools-version:3.4.1\n")
try parse { version in
XCTAssertEqual(version.description, "3.4.1")
}
// Test the second last key.
try fs.writeFileContents(root.appending(component: "Package\(keys[1]).swift"), bytes: "// swift-tools-version:3.4.0\n")
try parse { version in
XCTAssertEqual(version.description, "3.4.0")
}
// Test the first key.
try fs.writeFileContents(root.appending(component: "Package\(keys[0]).swift"), bytes: "// swift-tools-version:3.4.5\n")
try parse { version in
XCTAssertEqual(version.description, "3.4.5")
}
}
func testVersionSpecificManifestFallbacks() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/pkg/foo"
)
let root = AbsolutePath(path: "/pkg")
func parse(currentToolsVersion: ToolsVersion, _ body: (ToolsVersion) -> Void) throws {
let manifestPath = try ManifestLoader.findManifest(packagePath: root, fileSystem: fs, currentToolsVersion: currentToolsVersion)
body(try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: fs))
}
try fs.writeFileContents(root.appending(component: "Package.swift"), bytes: "// swift-tools-version:1.0.0\n")
try fs.writeFileContents(root.appending(component: "[email protected]"), bytes: "// swift-tools-version:3.4.5\n")
try fs.writeFileContents(root.appending(component: "[email protected]"), bytes: "// swift-tools-version:3.4.6\n")
try fs.writeFileContents(root.appending(component: "[email protected]"), bytes: "// swift-tools-version:3.4.7\n")
try fs.writeFileContents(root.appending(component: "[email protected]"), bytes: "// swift-tools-version:3.4.8\n")
try parse(currentToolsVersion: ToolsVersion(version: "15.1.1")) { version in
XCTAssertEqual(version.description, "3.4.6")
}
try parse(currentToolsVersion: ToolsVersion(version: "15.2.5")) { version in
XCTAssertEqual(version.description, "3.4.7")
}
try parse(currentToolsVersion: ToolsVersion(version: "3.0.0")) { version in
XCTAssertEqual(version.description, "1.0.0")
}
try parse(currentToolsVersion: ToolsVersion(version: "15.3.0")) { version in
XCTAssertEqual(version.description, "3.4.8")
}
}
}
| apache-2.0 | 5b8eec9ee52ec88820b7b60da00bbdee | 76.135099 | 572 | 0.572952 | 3.121958 | false | false | false | false |
wrutkowski/Lucid-Weather-Clock | Pods/Charts/Charts/Classes/Animation/ChartAnimator.swift | 6 | 12913 | //
// ChartAnimator.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
@objc
public protocol ChartAnimatorDelegate
{
/// Called when the Animator has stepped.
func chartAnimatorUpdated(_ chartAnimator: ChartAnimator)
/// Called when the Animator has stopped.
func chartAnimatorStopped(_ chartAnimator: ChartAnimator)
}
open class ChartAnimator: NSObject
{
open weak var delegate: ChartAnimatorDelegate?
open var updateBlock: (() -> Void)?
open var stopBlock: (() -> Void)?
/// the phase that is animated and influences the drawn values on the x-axis
open var phaseX: CGFloat = 1.0
/// the phase that is animated and influences the drawn values on the y-axis
open var phaseY: CGFloat = 1.0
private var _startTimeX: TimeInterval = 0.0
private var _startTimeY: TimeInterval = 0.0
private var _displayLink: NSUIDisplayLink!
private var _durationX: TimeInterval = 0.0
private var _durationY: TimeInterval = 0.0
private var _endTimeX: TimeInterval = 0.0
private var _endTimeY: TimeInterval = 0.0
private var _endTime: TimeInterval = 0.0
private var _enabledX: Bool = false
private var _enabledY: Bool = false
private var _easingX: ChartEasingFunctionBlock?
private var _easingY: ChartEasingFunctionBlock?
public override init()
{
super.init()
}
deinit
{
stop()
}
open func stop()
{
if (_displayLink != nil)
{
_displayLink.remove(from: RunLoop.main, forMode: RunLoopMode.commonModes)
_displayLink = nil
_enabledX = false
_enabledY = false
// If we stopped an animation in the middle, we do not want to leave it like this
if phaseX != 1.0 || phaseY != 1.0
{
phaseX = 1.0
phaseY = 1.0
if (delegate != nil)
{
delegate!.chartAnimatorUpdated(self)
}
if (updateBlock != nil)
{
updateBlock!()
}
}
if (delegate != nil)
{
delegate!.chartAnimatorStopped(self)
}
if (stopBlock != nil)
{
stopBlock?()
}
}
}
private func updateAnimationPhases(_ currentTime: TimeInterval)
{
if (_enabledX)
{
let elapsedTime: TimeInterval = currentTime - _startTimeX
let duration: TimeInterval = _durationX
var elapsed: TimeInterval = elapsedTime
if (elapsed > duration)
{
elapsed = duration
}
if (_easingX != nil)
{
phaseX = _easingX!(elapsed, duration)
}
else
{
phaseX = CGFloat(elapsed / duration)
}
}
if (_enabledY)
{
let elapsedTime: TimeInterval = currentTime - _startTimeY
let duration: TimeInterval = _durationY
var elapsed: TimeInterval = elapsedTime
if (elapsed > duration)
{
elapsed = duration
}
if (_easingY != nil)
{
phaseY = _easingY!(elapsed, duration)
}
else
{
phaseY = CGFloat(elapsed / duration)
}
}
}
@objc private func animationLoop()
{
let currentTime: TimeInterval = CACurrentMediaTime()
updateAnimationPhases(currentTime)
if (delegate != nil)
{
delegate!.chartAnimatorUpdated(self)
}
if (updateBlock != nil)
{
updateBlock!()
}
if (currentTime >= _endTime)
{
stop()
}
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingX: an easing function for the animation on the x axis
/// - parameter easingY: an easing function for the animation on the y axis
open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?)
{
stop()
_startTimeX = CACurrentMediaTime()
_startTimeY = _startTimeX
_durationX = xAxisDuration
_durationY = yAxisDuration
_endTimeX = _startTimeX + xAxisDuration
_endTimeY = _startTimeY + yAxisDuration
_endTime = _endTimeX > _endTimeY ? _endTimeX : _endTimeY
_enabledX = xAxisDuration > 0.0
_enabledY = yAxisDuration > 0.0
_easingX = easingX
_easingY = easingY
// Take care of the first frame if rendering is already scheduled...
updateAnimationPhases(_startTimeX)
if (_enabledX || _enabledY)
{
_displayLink = NSUIDisplayLink(target: self, selector: #selector(ChartAnimator.animationLoop))
_displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOptionX: the easing function for the animation on the x axis
/// - parameter easingOptionY: the easing function for the animation on the y axis
open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption)
{
animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingFunctionFromOption(easingOptionX), easingY: easingFunctionFromOption(easingOptionY))
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?)
{
animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easing, easingY: easing)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOption: ChartEasingOption)
{
animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easingFunctionFromOption(easingOption))
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval)
{
animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: .easeInOutSine)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easing: an easing function for the animation
open func animate(xAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?)
{
_startTimeX = CACurrentMediaTime()
_durationX = xAxisDuration
_endTimeX = _startTimeX + xAxisDuration
_endTime = _endTimeX > _endTimeY ? _endTimeX : _endTimeY
_enabledX = xAxisDuration > 0.0
_easingX = easing
// Take care of the first frame if rendering is already scheduled...
updateAnimationPhases(_startTimeX)
if (_enabledX || _enabledY)
{
if _displayLink === nil
{
_displayLink = NSUIDisplayLink(target: self, selector: #selector(ChartAnimator.animationLoop))
_displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
}
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easingOption: the easing function for the animation
open func animate(xAxisDuration: TimeInterval, easingOption: ChartEasingOption)
{
animate(xAxisDuration: xAxisDuration, easing: easingFunctionFromOption(easingOption))
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
open func animate(xAxisDuration: TimeInterval)
{
animate(xAxisDuration: xAxisDuration, easingOption: .easeInOutSine)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
open func animate(yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?)
{
_startTimeY = CACurrentMediaTime()
_durationY = yAxisDuration
_endTimeY = _startTimeY + yAxisDuration
_endTime = _endTimeX > _endTimeY ? _endTimeX : _endTimeY
_enabledY = yAxisDuration > 0.0
_easingY = easing
// Take care of the first frame if rendering is already scheduled...
updateAnimationPhases(_startTimeY)
if (_enabledX || _enabledY)
{
if _displayLink === nil
{
_displayLink = NSUIDisplayLink(target: self, selector: #selector(ChartAnimator.animationLoop))
_displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
}
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
open func animate(yAxisDuration: TimeInterval, easingOption: ChartEasingOption)
{
animate(yAxisDuration: yAxisDuration, easing: easingFunctionFromOption(easingOption))
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
open func animate(yAxisDuration: TimeInterval)
{
animate(yAxisDuration: yAxisDuration, easingOption: .easeInOutSine)
}
}
| mit | 4932709281c192eb71ece9c54b184807 | 38.130303 | 175 | 0.625881 | 5.311806 | false | false | false | false |
tjw/swift | test/SILGen/global_resilience.swift | 2 | 3494 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-sil-ownership -enable-resilience -emit-module-path=%t/resilient_global.swiftmodule -module-name=resilient_global %S/../Inputs/resilient_global.swift
// RUN: %target-swift-frontend -I %t -emit-silgen -enable-resilience -enable-sil-ownership -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-frontend -I %t -emit-sil -O -enable-resilience -parse-as-library %s | %FileCheck --check-prefix=CHECK-OPT %s
import resilient_global
public struct MyEmptyStruct {}
// CHECK-LABEL: sil_global @$S17global_resilience13myEmptyGlobalAA02MyD6StructVvp : $MyEmptyStruct
public var myEmptyGlobal = MyEmptyStruct()
// CHECK-LABEL: sil_global @$S17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvp : $MyEmptyStruct
@_fixed_layout public var myFixedLayoutGlobal = MyEmptyStruct()
// Mutable addressor for resilient global
// CHECK-LABEL: sil hidden [global_init] @$S17global_resilience13myEmptyGlobalAA02MyD6StructVvau : $@convention(thin) () -> Builtin.RawPointer
// CHECK: global_addr @$S17global_resilience13myEmptyGlobalAA02MyD6StructVv
// CHECK: return
// Synthesized getter and setter for our resilient global variable
// CHECK-LABEL: sil @$S17global_resilience13myEmptyGlobalAA02MyD6StructVvg
// CHECK: function_ref @$S17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
// CHECK-LABEL: sil @$S17global_resilience13myEmptyGlobalAA02MyD6StructVvs
// CHECK: function_ref @$S17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
// Mutable addressor for fixed-layout global
// CHECK-LABEL: sil [global_init] @$S17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvau
// CHECK: global_addr @$S17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK: return
// CHECK-OPT-LABEL: sil private @globalinit_{{.*}}_func0
// CHECK-OPT: alloc_global @$S17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK-OPT: return
// CHECK-OPT-LABEL: sil [global_init] @$S17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvau
// CHECK-OPT: global_addr @$S17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvp
// CHECK-OPT: function_ref @globalinit_{{.*}}_func0
// CHECK-OPT: return
// Accessing resilient global from our resilience domain --
// call the addressor directly
// CHECK-LABEL: sil @$S17global_resilience16getMyEmptyGlobalAA0dE6StructVyF
// CHECK: function_ref @$S17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
public func getMyEmptyGlobal() -> MyEmptyStruct {
return myEmptyGlobal
}
// Accessing resilient global from a different resilience domain --
// access it with accessors
// CHECK-LABEL: sil @$S17global_resilience14getEmptyGlobal010resilient_A00D15ResilientStructVyF
// CHECK: function_ref @$S16resilient_global11emptyGlobalAA20EmptyResilientStructVvg
// CHECK: return
public func getEmptyGlobal() -> EmptyResilientStruct {
return emptyGlobal
}
// Accessing fixed-layout global from a different resilience domain --
// call the addressor directly
// CHECK-LABEL: sil @$S17global_resilience20getFixedLayoutGlobal010resilient_A020EmptyResilientStructVyF
// CHECK: function_ref @$S16resilient_global17fixedLayoutGlobalAA20EmptyResilientStructVvau
// CHECK: return
public func getFixedLayoutGlobal() -> EmptyResilientStruct {
return fixedLayoutGlobal
}
| apache-2.0 | f187bdb8b8498afa58c1d0d68e97b033 | 44.376623 | 200 | 0.771895 | 4.149644 | false | false | false | false |
zapdroid/RXWeather | Weather/Weather.swift | 1 | 2693 | //
// Weather.swift
// Weather
//
// Created by Boran ASLAN on 12/05/2017.
// Copyright ยฉ 2017 Boran ASLAN. All rights reserved.
//
import Foundation
struct Weather {
var cityId: Int16 = 0
var cityName: String = ""
var temperature: Double = 0
var weatherCondition: String = ""
var humidity: Double = 0
var precipitationProbability: Double = 0
var windSpeed: Double = 0
var windDeg: Double = 0
var icon: String = ""
var lat: Double = 0
var lon: Double = 0
}
extension Weather {
struct Key {
static let cityId = "id"
static let cityName = "name"
// main
static let mainKey = "main"
static let temperature = "temp"
static let humidity = "humidity"
// rain
static let rainKey = "rain"
static let precipitation = "3h"
// wind
static let windKey = "wind"
static let windSpeed = "speed"
static let windDeg = "deg"
// weather[0]
static let weatherKey = "weather"
static let icon = "icon"
static let weatherCondition = "main"
}
init?(json: [String: Any]) {
if let cityId = json["id"] as? Int16 {
self.cityId = cityId
}
if let cityNameString = json[Key.cityName] as? String {
cityName = cityNameString
}
if let main = json[Key.mainKey] as? [String: AnyObject] {
if let temperatureValue = main[Key.temperature] as? Double {
temperature = temperatureValue
}
if let humidityValue = main[Key.humidity] as? Double {
humidity = humidityValue
}
}
if let rain = json[Key.rainKey] as? [String: AnyObject] {
if let precipitationValue = rain[Key.precipitation] as? Double {
precipitationProbability = precipitationValue
}
}
if let wind = json[Key.windKey] as? [String: AnyObject] {
if let windSpeedValue = wind[Key.windSpeed] as? Double {
windSpeed = windSpeedValue
}
if let windDegValue = wind[Key.windDeg] as? Double {
windDeg = windDegValue
}
}
if let weather = json[Key.weatherKey] as? [[String: AnyObject]] {
if let weatherConditionValue = weather[0][Key.weatherCondition] as? String {
weatherCondition = weatherConditionValue
}
if let icon = weather[0]["icon"] as? String, let iconId = weather[0]["id"] as? Int {
self.icon = WeatherIcon(condition: iconId, iconString: icon).iconText
}
}
}
}
| mit | eaad464186d4a2b39bc9c1a021d14e0c | 27.336842 | 96 | 0.556835 | 4.384365 | false | false | false | false |
Acidburn0zzz/firefox-ios | WidgetKit/OpenTabs/SimpleTab.swift | 1 | 2930 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
fileprivate let userDefaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)!
struct SimpleTab: Hashable, Codable {
var title: String?
var url: URL?
let lastUsedTime: Timestamp? // From Session Data
var faviconURL: String?
var isPrivate: Bool = false
var uuid: String = ""
var imageKey: String {
return url?.baseDomain ?? ""
}
}
extension SimpleTab {
static func getSimpleTabs() -> [String: SimpleTab] {
if let tbs = userDefaults.object(forKey: PrefsKeys.WidgetKitSimpleTabKey) as? Data {
do {
let jsonDecoder = JSONDecoder()
let tabs = try jsonDecoder.decode([String: SimpleTab].self, from: tbs)
return tabs
}
catch {
print("Error occured")
}
}
return [String: SimpleTab]()
}
static func saveSimpleTab(tabs:[String: SimpleTab]?) {
guard let tabs = tabs, !tabs.isEmpty else {
userDefaults.removeObject(forKey: PrefsKeys.WidgetKitSimpleTabKey)
return
}
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(tabs) {
userDefaults.set(encoded, forKey: PrefsKeys.WidgetKitSimpleTabKey)
}
}
static func convertToSimpleTabs(_ tabs: [SavedTab]) -> [String: SimpleTab] {
var simpleTabs: [String: SimpleTab] = [:]
for tab in tabs {
var url:URL?
// Set URL
if tab.url != nil {
url = tab.url
// Check if session data urls have something
} else if tab.sessionData?.urls != nil {
url = tab.sessionData?.urls.last
}
// Ignore `internal about` urls which corresponds to Home
if url != nil, url!.absoluteString.starts(with: "internal://local/about/") {
continue
}
// Set Title
var title = tab.title ?? ""
// There is no title then use the base url Ex https://www.mozilla.org/ will be short displayed as `mozilla`
if title.isEmpty {
title = url?.shortDisplayString ?? ""
}
// Key for simple tabs dictionary is tab UUID which is used to select proper tab when we send UUID to NavigationRouter class handle widget url
let uuidVal = tab.UUID ?? ""
let value = SimpleTab(title: title, url: url, lastUsedTime: tab.sessionData?.lastUsedTime ?? 0, faviconURL: tab.faviconURL, isPrivate: tab.isPrivate, uuid: uuidVal)
simpleTabs[uuidVal] = value
}
return simpleTabs
}
}
| mpl-2.0 | 87a139cc61052336f9d57b2fa6a195fc | 35.625 | 176 | 0.576451 | 4.665605 | false | false | false | false |
joemcbride/outlander-osx | src/Outlander/SimpleDiff.swift | 1 | 3644 | //
// simplediff.swift
// simplediff
//
// Created by Matthias Hochgatterer on 31/03/15.
// Copyright (c) 2015 Matthias Hochgatterer. All rights reserved.
//
import Foundation
enum OperationType {
case Insert, Delete, Noop
var description: String {
get {
switch self {
case .Insert: return "+"
case .Delete: return "-"
case .Noop: return "="
}
}
}
}
/// Operation describes an operation (insertion, deletion, or noop) of elements.
struct Operation<T> {
let type: OperationType
let elements: [T]
var elementsString: String {
return elements.map { "\($0)" }.joinWithSeparator("")
}
var description: String {
get {
switch type {
case .Insert:
return "[+\(elementsString)]"
case .Delete:
return "[-\(elementsString)]"
default:
return "\(elementsString)"
}
}
}
}
/// diff finds the difference between two lists.
/// This algorithm a shameless copy of simplediff https://github.com/paulgb/simplediff
///
/// - parameter before: Old list of elements.
/// - parameter after: New list of elements
/// - returns: A list of operation (insert, delete, noop) to transform the list *before* to the list *after*.
func diff<T where T: Equatable, T: Hashable>(before: [T], after: [T]) -> [Operation<T>] {
// Create map of indices for every element
var beforeIndices = [T: [Int]]()
for (index, elem) in before.enumerate() {
var indices = beforeIndices.indexForKey(elem) != nil ? beforeIndices[elem]! : [Int]()
indices.append(index)
beforeIndices[elem] = indices
}
var beforeStart = 0
var afterStart = 0
var maxOverlayLength = 0
var overlay = [Int: Int]() // remembers *overlayLength* of previous element
for (index, elem) in after.enumerate() {
var _overlay = [Int: Int]()
// Element must be in *before* list
if let elemIndices = beforeIndices[elem] {
// Iterate over element indices in *before*
for elemIndex in elemIndices {
var overlayLength = 1
if let previousSub = overlay[elemIndex - 1] {
overlayLength += previousSub
}
_overlay[elemIndex] = overlayLength
if overlayLength > maxOverlayLength { // longest overlay?
maxOverlayLength = overlayLength
beforeStart = elemIndex - overlayLength + 1
afterStart = index - overlayLength + 1
}
}
}
overlay = _overlay
}
var operations = [Operation<T>]()
if maxOverlayLength == 0 {
// No overlay; remove before and add after elements
if before.count > 0 {
operations.append(Operation(type: .Delete, elements: before))
}
if after.count > 0 {
operations.append(Operation(type: .Insert, elements: after))
}
} else {
// Recursive call with elements before overlay
operations += diff(Array(before[0..<beforeStart]), after: Array(after[0..<afterStart]))
// Noop for longest overlay
operations.append(Operation(type: .Noop, elements: Array(after[afterStart..<afterStart+maxOverlayLength])))
// Recursive call with elements after overlay
operations += diff(Array(before[beforeStart+maxOverlayLength..<before.count]), after: Array(after[afterStart+maxOverlayLength..<after.count]))
}
return operations
}
| mit | f96cc79e5546b5724440c8c587b11254 | 33.377358 | 150 | 0.582876 | 4.630241 | false | false | false | false |
venticake/RetricaImglyKit-iOS | RetricaImglyKit/Classes/Frontend/Stores/StickerStore.swift | 1 | 3451 | // This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
import Foundation
/**
The `JSONStore` provides methods to retrieve JSON data from any URL.
*/
@available(iOS 8, *)
@objc(IMGLYStickerStoreProtocol) public protocol StickerStoreProtocol {
/**
Retrieves StickerInfoRecord data, from the JSON located at the specified URL.
- parameter url: A valid URL.
- parameter completionBlock: A completion block.
*/
func get(url: NSURL, completionBlock: ([StickerInfoRecord]?, NSError?) -> Void)
}
/**
The `JSONStore` class provides methods to retrieve JSON data from any URL.
It also caches the data due to efficiency, and performs a sanity check.
*/
@available(iOS 8, *)
@objc(IMGLYStickerStore) public class StickerStore: NSObject, StickerStoreProtocol {
/// A shared instance for convenience.
public static let sharedStore = StickerStore()
/// The json parser to use.
public var jsonParser: JSONStickerParserProtocol = JSONStickerParser()
/// This store is used to retrieve the JSON data.
public var jsonStore: JSONStoreProtocol = JSONStore()
private var store: [NSURL : [StickerInfoRecord]] = [ : ]
/**
Retrieves StickerInfoRecord data, from the JSON located at the specified URL.
- parameter url: A valid URL.
- parameter completionBlock: A completion block.
*/
public func get(url: NSURL, completionBlock: ([StickerInfoRecord]?, NSError?) -> Void) {
if let record = store[url] {
completionBlock(record, nil)
} else {
jsonStore.get(url, completionBlock: { (dict, error) -> Void in
if let dict = dict {
do {
try self.store[url] = self.jsonParser.parseJSON(dict)
} catch JSONParserError.IllegalStickerHash {
completionBlock(nil, NSError(info: Localize("Illegal sticker hash")))
} catch JSONParserError.IllegalImageRecord(let recordName) {
completionBlock(nil, NSError(info: Localize("Illegal image record") + " .Tag: \(recordName)"))
} catch JSONParserError.IllegalImageRatio(let recordName) {
completionBlock(nil, NSError(info: Localize("Illegal image ratio" ) + " .Tag: \(recordName)"))
} catch JSONParserError.StickerNodeNoDictionary {
completionBlock(nil, NSError(info: Localize("Sticker node not holding a dictionaty")))
} catch JSONParserError.StickerArrayNotFound {
completionBlock(nil, NSError(info: Localize("Sticker node not found, or not holding an array")))
} catch {
completionBlock(nil, NSError(info: Localize("Unknown error")))
}
completionBlock(self.store[url], nil)
} else {
completionBlock(nil, error)
}
})
}
}
}
| mit | 6b54d7eeffd475f5f5e268bd636f206d | 43.24359 | 120 | 0.628513 | 4.95122 | false | false | false | false |
xedin/swift | benchmark/single-source/ArrayOfGenericPOD.swift | 20 | 2784 | //===--- ArrayOfGenericPOD.swift ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This benchmark tests creation and destruction of arrays of enum and
// generic type bound to trivial types. It should take the same time as
// ArrayOfPOD. (In practice, it takes a little longer to construct
// the optional arrays).
//
// For comparison, we always create three arrays of 200,000 words.
// An integer enum takes two words.
import TestsUtils
public let ArrayOfGenericPOD = [
BenchmarkInfo(
// Renamed benchmark to "2" when IUO test was removed, which
// effectively changed what we're benchmarking here.
name: "ArrayOfGenericPOD2",
runFunction: run_ArrayOfGenericPOD,
tags: [.validation, .api, .Array]),
// Initialize an array of generic POD from a slice.
// This takes a unique path through stdlib customization points.
BenchmarkInfo(
name: "ArrayInitFromSlice",
runFunction: run_initFromSlice,
tags: [.validation, .api, .Array], setUpFunction: createArrayOfPOD)
]
class RefArray<T> {
var array: [T]
init(_ i:T) {
array = [T](repeating: i, count: 100000)
}
}
// Check the performance of destroying an array of enums (optional) where the
// enum has a single payload of trivial type. Destroying the
// elements should be a nop.
@inline(never)
func genEnumArray() {
blackHole(RefArray<Int?>(3))
// should be a nop
}
// Check the performance of destroying an array of structs where the
// struct has multiple fields of trivial type. Destroying the
// elements should be a nop.
struct S<T> {
var x: T
var y: T
}
@inline(never)
func genStructArray() {
blackHole(RefArray<S<Int>>(S(x:3, y:4)))
// should be a nop
}
@inline(never)
public func run_ArrayOfGenericPOD(_ N: Int) {
for _ in 0..<N {
genEnumArray()
genStructArray()
}
}
// --- ArrayInitFromSlice
let globalArray = Array<UInt8>(repeating: 0, count: 4096)
func createArrayOfPOD() {
blackHole(globalArray)
}
@inline(never)
@_optimize(none)
func copyElements<S: Sequence>(_ contents: S) -> [UInt8]
where S.Iterator.Element == UInt8
{
return [UInt8](contents)
}
@inline(never)
public func run_initFromSlice(_ N: Int) {
for _ in 0..<N {
for _ in 0..<1000 {
// Slice off at least one element so the array buffer can't be reused.
blackHole(copyElements(globalArray[0..<4095]))
}
}
}
| apache-2.0 | 1ddaf0b93eafe133624a3788d7dd5af6 | 26.564356 | 80 | 0.665589 | 3.829436 | false | false | false | false |
sjf0213/DingShan | DingshanSwift/DingshanSwift/GalleryViewController.swift | 1 | 11131 | //
// GalleryViewController.swift
// DingshanSwift
//
// Created by song jufeng on 15/7/14.
// Copyright (c) 2015ๅนด song jufeng. All rights reserved.
//
import Foundation
let gallery_gap:CGFloat = 10.0
let load_delay:Double = 1.0
class GalleryViewController:DSViewController,UICollectionViewDataSource, UICollectionViewDelegate,CHTCollectionViewDelegateWaterfallLayout
{
var seg:KASegmentControl?
var menuView = GalleryMenuView()
var mainCollection:UICollectionView?
var currentPage:NSInteger = 0
var dataList = NSMutableArray()
var singleConfig:[AnyObject]?
var multiConfig:[AnyObject]?
var configCache:[NSObject:AnyObject]?
var indicatorTop:UzysRadialProgressActivityIndicator?
var indicatorBottom:UzysRadialProgressActivityIndicator?
override func loadView(){
super.loadView()
self.view.backgroundColor = NAVI_COLOR
self.backBtnHidden = true
// ่ฏปๅ่ๅ้
็ฝฎ
if let configAll = MainConfig.sharedInstance.rootDic?["GalleryMenu"] as? [NSObject:AnyObject]{
multiConfig = configAll["Multi"] as? [AnyObject]
singleConfig = configAll["Single"] as? [AnyObject]
}
// ๅๅงๅๅๆขๆ้ฎ
seg = KASegmentControl(frame: CGRectMake((self.topView.frame.size.width - 140)*0.5, 27, 140, 30),
withItems: ["ๅฅๅพ", "ๅๅพ"],
withLightedColor: THEME_COLOR)
self.topView.addSubview(seg!)
seg?.tapSegmentItemHandler = {(selectedIndex)->Void in
self.changeBySegIndex(selectedIndex)
}
// ๅๅงๅ่ๅ
menuView.frame = CGRectMake(0, self.topView.frame.size.height, self.view.bounds.size.width, 40)
self.view.addSubview(menuView)
let layout = CHTCollectionViewWaterfallLayout()
layout.sectionInset = UIEdgeInsetsMake(gallery_gap, gallery_gap, gallery_gap, gallery_gap);
layout.columnCount = 2;
layout.minimumColumnSpacing = gallery_gap;
layout.minimumInteritemSpacing = gallery_gap;
mainCollection = UICollectionView(frame: CGRect(x: 0,
y: self.topView.bounds.size.height + self.menuView.bounds.size.height,
width: self.view.bounds.size.width,
height: self.view.bounds.size.height - self.topView.bounds.size.height - self.menuView.bounds.size.height - MAIN_TAB_H), collectionViewLayout: layout)
mainCollection?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
mainCollection?.backgroundColor = UIColor.whiteColor()
mainCollection?.dataSource = self;
mainCollection?.delegate = self;
mainCollection?.registerClass(GalleryViewCell.classForCoder(), forCellWithReuseIdentifier: GalleryViewCellIdentifier)
mainCollection?.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
mainCollection?.alwaysBounceVertical = true
mainCollection?.addPullToRefreshActionHandler({ [weak self] () -> Void in
self?.currentPage = 0
self?.dataList.removeAllObjects()
self?.mainCollection?.reloadData()
self?.startRequest(self?.configCache)
print("A_DONE------- self.frame = (\(self?.indicatorTop?.frame.origin.x), \(self?.indicatorTop?.frame.origin.y), \(self?.indicatorTop?.frame.size.width), \(self?.indicatorTop?.frame.size.height)")
})
mainCollection?.addPullToLoadMoreActionHandler({ [weak self] () -> Void in
self?.startRequest(self?.configCache)
print("B_DONE------- self.frame = (\(self?.indicatorBottom?.frame.origin.x), \(self?.indicatorBottom?.frame.origin.y), \(self?.indicatorBottom?.frame.size.width), \(self?.indicatorBottom?.frame.size.height)")
})
self.view.addSubview(mainCollection!)
self.view.bringSubviewToFront(menuView)
menuView.tapItemHandler = {[weak self](config:[NSObject:AnyObject]) -> Void in
print("-----------Changed ! ! !userSelectConfig = \(config)")
self?.configCache = config
self?.currentPage = 0
self?.dataList.removeAllObjects()
self?.mainCollection?.reloadData()
self?.startRequest(config)
}
}
deinit {
//
}
override func viewDidLoad() {
seg?.selectedSegmentIndex = 0;
}
override func viewDidAppear(animated: Bool) {
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default
}
// ๅๆขๅฅๅพไธๅๅพ
func changeBySegIndex(index:Int)->Void{
self.currentPage = 0
self.dataList.removeAllObjects()
self.mainCollection?.reloadData()
if 0 == index{
menuView.menuConfig = multiConfig!
}
if (1 == index){
menuView.menuConfig = singleConfig!
}
mainCollection?.triggerPullToRefresh()
}
func onTapBtn(sender:UIButton) {
print(sender, terminator: "")
let detail = DetailController()
self.navigationController?.pushViewController(detail, animated: true)
}
func startRequest(config:[NSObject:AnyObject]?){
var iid = "0"// ๅไธไธ้กต็ๆๅไธๅผ ๅพ็imageid
if(self.dataList.count > 0){
if let item = self.dataList.lastObject as? ImageInfoData{
iid = String(item.imageId)
}
}
var parameter:[NSObject:AnyObject] = [ "iid" : iid,
"psize" : "30",
"json" : "1"]
if config != nil{
for one in config! {
parameter[one.0] = String(one.1)
}
}
// print("Multi = = = = = = =parameter = \(parameter)", terminator: "")
var type = ""
if 0 == seg?.selectedSegmentIndex{
type = "multi"
}else if 1 == seg?.selectedSegmentIndex{
type = "single"
}
let url = ServerApi.gallery_get_galary_list(type, dic:parameter)
if (self.currentPage == 0){
self.mainCollection?.showLoadMoreEnd(false)
}
// print("\n---$$$---url = \(url)", terminator: "")
AFDSClient.sharedInstance.GET(url, parameters: nil,
success: {[weak self](task, JSON) -> Void in
// print("\n responseJSON- - - - -data = \(JSON)")
// ไธๆๅทๆฐๆถๅๆธ
็ฉบๆงๆฐๆฎ๏ผ่ฏทๆฑๅคฑ่ดฅไนๆธ
็ฉบ๏ผ
if (self?.currentPage == 0 && self?.dataList.count > 0){
self?.dataList.removeAllObjects()
}
self?.currentPage++
// ๅฆๆ่ฏทๆฑๆฐๆฎๆๆ
if let dic = JSON as? [NSObject:AnyObject]{
// print("\n responseJSON- - - - -data:", dic)
self?.processRequestResult(dic)
}
}, failure: {[weak self]( task, error) -> Void in
print("\n failure: TIP --- e:\(error)")
let delayInSeconds = 2.0;
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue(), {() -> Void in
self?.mainCollection?.showLoadMoreEnd(true)
})
})
}
func processRequestResult(result:[NSObject:AnyObject]){
if (200 == result["c"]?.integerValue){
if let v = result["v"] as? [NSObject:AnyObject]{
if let list = v["image_list"] as? [AnyObject]{
for item in list{
if let data = item as? [NSObject:AnyObject]{
let data = ImageInfoData(dic: data)
self.dataList.addObject(data)
}
}
// ๆญฃๅธธๆต็จ
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(load_delay * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue(), {() -> Void in
self.mainCollection?.reloadData()// ๅคฑ่ดฅๆถๅๆธ
็ฉบๆฐๆฎๅไน่ฆ้ๆฐๅ ่ฝฝ
// ๆงไปถๅคไฝ
self.mainCollection?.stopRefreshAnimation()
self.mainCollection?.stopLoadMoreAnimation()
})
}else{// ๆๅไธ้กตๆฒกๆๆดๅคๆฐๆฎไบ
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(load_delay * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue(), {() -> Void in
self.mainCollection?.showLoadMoreEnd(true)
})
}
}
}else{
print("\n---===---Error: processRequestResult = \(result)")
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(load_delay * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue(), {() -> Void in
self.mainCollection?.showLoadMoreEnd(true)
})
}
}
// MARK: UICollectionViewDelegate
func collectionView (collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
var sz = CGSize(width: 100.0, height: 100.0)
if let data = self.dataList.objectAtIndex(indexPath.row) as? ImageInfoData{
sz = CGSize(width: data.width, height: data.height)
}
return sz
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return self.dataList.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier(GalleryViewCellIdentifier, forIndexPath: indexPath) as? GalleryViewCell{
cell.clearData()
if let item = self.dataList.objectAtIndex(indexPath.row) as? ImageInfoData{
cell.loadCellData(item)
}
return cell
}else{
return UICollectionViewCell()
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
if let imgData = dataList[indexPath.row] as? ImageInfoData{
let detail = GalleryDetailController()
self.navigationController?.pushViewController(detail, animated: true)
detail.navigationItem.title = imgData.desc;
if 0 == seg?.selectedSegmentIndex{// ๅคๅพ
detail.loadDetailTitle(imgData.desc)
detail.startRequest(imgData.imageId)
}else if 1 == seg?.selectedSegmentIndex{
detail.loadImageData(imgData)
}
}
}
} | mit | 6109d5f45836fce8534559d2ad03bc2b | 42 | 220 | 0.583463 | 4.83444 | false | true | false | false |
AaronBratcher/ALBNoSQLDB | ALBNoSQLDB/ALBNoSQLDBTests/DBResultsTests.swift | 1 | 1744 | //
// DBResultsTests.swift
// ALBNoSQLDBTests
//
// Created by Aaron Bratcher on 5/9/20.
// Copyright ยฉ 2020 Aaron Bratcher. All rights reserved.
//
import XCTest
@testable import ALBNoSQLDB
class DBResultsTests: XCTestCase {
lazy var db: ALBNoSQLDB = {
return dbForTestClass(className: String(describing: type(of: self)))
}()
override func setUpWithError() throws {
super.setUp()
db.dropAllTables()
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
db.close()
removeDB(for: String(describing: type(of: self)))
}
func testDBResults() throws {
let date = Date()
let keys = ["1", "2", "3"]
var transaction = Transaction(key: keys[0], date: date, accountKey: "A1", notes: TransactionValue.notes, amount: TransactionValue.amount, purchaseOrders: TransactionValue.purchaseOrders, isNew: TransactionValue.isNew)
transaction.save(to: db)
transaction = Transaction(key: keys[1], date: date, accountKey: "A2", notes: TransactionValue.notes, amount: TransactionValue.amount, purchaseOrders: TransactionValue.purchaseOrders, isNew: TransactionValue.isNew)
transaction.save(to: db)
transaction = Transaction(key: keys[2], date: date, accountKey: "A3", notes: TransactionValue.notes, amount: TransactionValue.amount, purchaseOrders: TransactionValue.purchaseOrders, isNew: TransactionValue.isNew)
transaction.save(to: db)
let transactions = DBResults<Transaction>(db: db, keys: keys)
XCTAssertEqual(transactions.count, 3)
XCTAssertEqual(transactions[0]?.accountKey, "A1")
XCTAssertEqual(transactions[1]?.accountKey, "A2")
XCTAssertEqual(transactions[2]?.accountKey, "A3")
}
}
| mit | 50c05681bcf2ce40e51728a6e24ac1f5 | 33.86 | 219 | 0.743546 | 3.58642 | false | true | false | false |
15221758864/TestKitchen_1606 | TestKitchen/TestKitchen/classes/common/UILabel+Util.swift | 1 | 712 | //
// UILabel+Util.swift
// TestKitchen
//
// Created by Ronie on 16/8/15.
// Copyright ยฉ 2016ๅนด Ronie. All rights reserved.
//
import UIKit
extension UILabel{
class func createLabel(text: String?, font: UIFont?, textAlignment: NSTextAlignment?, textColor: UIColor?)-> UILabel {
let label = UILabel()
if let labelText = text {
label.text = labelText
}
if let labelFont = font {
label.font = labelFont
}
if let labelAlign = textAlignment {
label.textAlignment = labelAlign
}
if let labeltextColor = textColor {
label.textColor = labeltextColor
}
return label
}
}
| mit | 7027a5202af1989dac13ac9bf7dd8875 | 22.633333 | 122 | 0.5811 | 4.574194 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/FasterStarsView.swift | 1 | 3811 | //
// FasterStarsView.swift
// Telegram
//
// Created by Mike Renoir on 14.06.2022.
// Copyright ยฉ 2022 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SceneKit
final class FasterStarsView: NSView, PremiumDecorationProtocol {
private let sceneView: SCNView
private var particles: SCNNode?
override init(frame: CGRect) {
self.sceneView = SCNView(frame: CGRect(origin: .zero, size: frame.size))
self.sceneView.backgroundColor = .clear
if let url = Bundle.main.url(forResource: "lightspeed", withExtension: "scn") {
self.sceneView.scene = try? SCNScene(url: url, options: nil)
}
super.init(frame: frame)
wantsLayer = true
self.layer?.opacity = 0.0
self.addSubview(self.sceneView)
self.particles = self.sceneView.scene?.rootNode.childNode(withName: "particles", recursively: false)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
self.particles = nil
}
func setVisible(_ visible: Bool) {
if visible, let particles = self.particles, particles.parent == nil {
self.sceneView.scene?.rootNode.addChildNode(particles)
}
self._change(opacity: visible ? 0.4 : 0.0, animated: true, completion: { [weak self] finished in
if let strongSelf = self, finished && !visible && strongSelf.particles?.parent != nil {
strongSelf.particles?.removeFromParentNode()
}
})
}
private var playing = false
func startAnimation() {
guard !self.playing, let scene = self.sceneView.scene, let node = scene.rootNode.childNode(withName: "particles", recursively: false), let particles = node.particleSystems?.first else {
return
}
self.playing = true
let speedAnimation = CABasicAnimation(keyPath: "speedFactor")
speedAnimation.fromValue = 1.0
speedAnimation.toValue = 1.8
speedAnimation.duration = 0.8
speedAnimation.fillMode = .forwards
particles.addAnimation(speedAnimation, forKey: "speedFactor")
particles.speedFactor = 3.0
let stretchAnimation = CABasicAnimation(keyPath: "stretchFactor")
stretchAnimation.fromValue = 0.05
stretchAnimation.toValue = 0.3
stretchAnimation.duration = 0.8
stretchAnimation.fillMode = .forwards
particles.addAnimation(stretchAnimation, forKey: "stretchFactor")
particles.stretchFactor = 0.3
}
func resetAnimation() {
guard self.playing, let scene = self.sceneView.scene, let node = scene.rootNode.childNode(withName: "particles", recursively: false), let particles = node.particleSystems?.first else {
return
}
self.playing = false
let speedAnimation = CABasicAnimation(keyPath: "speedFactor")
speedAnimation.fromValue = 3.0
speedAnimation.toValue = 1.0
speedAnimation.duration = 0.35
speedAnimation.fillMode = .forwards
particles.addAnimation(speedAnimation, forKey: "speedFactor")
particles.speedFactor = 1.0
let stretchAnimation = CABasicAnimation(keyPath: "stretchFactor")
stretchAnimation.fromValue = 0.3
stretchAnimation.toValue = 0.05
stretchAnimation.duration = 0.35
stretchAnimation.fillMode = .forwards
particles.addAnimation(stretchAnimation, forKey: "stretchFactor")
particles.stretchFactor = 0.05
}
override func layout() {
super.layout()
self.sceneView.frame = CGRect(origin: .zero, size: frame.size)
}
}
| gpl-2.0 | f7534fbfae5c04ecb963caa424f10b89 | 33.324324 | 193 | 0.632808 | 4.562874 | false | false | false | false |
DallasMcNeil/LIFX-Master | LIFX Master/AppDelegate.swift | 1 | 13690 | //
// AppDelegate.swift
// LIFX Master
//
// Created by Dallas McNeil on 15/11/2015.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, LFXLightObserver, LFXLightCollectionObserver, NSMenuDelegate {
/// Status item that represents the menu bar item
let statusItem:NSStatusItem = NSStatusBar.system().statusItem(withLength: 24)
/// Menu of the status itme
let menu:NSMenu = NSMenu()
/// Light submenu, displays all light information
var lightMenu:NSMenu = NSMenu()
/// Effects submenu, displays all effects
let effectMenu:NSMenu = NSMenu()
/// Colour submenu, displays HSB colour sliders
let colourMenu:NSMenu = NSMenu()
/// All lights on the local network
var lights:[LFXLight] = []
/// Represents the labels of light menu items with a tick
var selectedLights:[String:Bool] = [:]
/// All lights that are approved to be used by the user
var approvedLights:[LFXLight] = []
/// The last highlights menu item
var selectedItem:NSMenuItem?
/// The on/off state of all lights
var toggleState = false
/// A set of closures that form the effects available to the user
var effects:[(Int,AppDelegate)->()] = [
{(time:Int,delegate:AppDelegate) in
delegate.setAllLights(LFXHSBKColor(hue: 0, saturation: 0 , brightness: 1), duration: 0.5)
},
{(time:Int,delegate:AppDelegate) in
delegate.setAllLights(LFXHSBKColor(hue: CGFloat(time)*36, saturation: 1, brightness: 1), duration: 1)
},
{(time:Int,delegate:AppDelegate) in
delegate.setAllLights(LFXHSBKColor(hue: CGFloat(arc4random_uniform(360)), saturation: CGFloat(arc4random_uniform(256))/256, brightness: CGFloat(arc4random_uniform(256))/256), duration: 1)
},
{(time:Int,delegate:AppDelegate) in
delegate.setAllLights(LFXHSBKColor(hue:(CGFloat(sin(Double(time*5)/(180*M_PI)))*3600), saturation: 1, brightness: 1), duration: 0.2)
},
{(time:Int,delegate:AppDelegate) in
delegate.setAllLights(LFXHSBKColor(hue:CGFloat(time/2), saturation: 1, brightness: 1), duration: 1)
},
{(time:Int,delegate:AppDelegate) in
if time%2 == 0 {
delegate.setAllLights(LFXHSBKColor(hue:0, saturation: 1, brightness: 1), duration: 0)
} else {
delegate.setAllLights(LFXHSBKColor(hue:120, saturation: 1, brightness: 1), duration: 0)
}
},
{(time:Int,delegate:AppDelegate) in
if time%4 == 0 {
delegate.setAllLights(LFXHSBKColor(hue:0, saturation: 1, brightness: 1), duration: 0)
} else if time%4 == 1 {
delegate.setAllLights(LFXHSBKColor(hue:120, saturation: 1, brightness: 1), duration: 0)
} else if time%4 == 2 {
delegate.setAllLights(LFXHSBKColor(hue:50, saturation: 1, brightness: 1), duration: 0)
} else if time%4 == 3 {
delegate.setAllLights(LFXHSBKColor(hue:240, saturation: 1, brightness: 1), duration: 0)
}
}
]
/// The corresponding name of the effect displayed to the user
var effectNames:[String] = ["Standard","Rainbow","Random","Varying Rainbow","Slow Rainbow","Christmas 1","Christmas 2"]
/// The corresponding update time of each effect
var updateTimings:[TimeInterval] = [1,1,1,0.2,1,1,1]
/*
CREATING ADDITIONAL EFFECTS
Effects are managed by a closure system where each effect is updated periodically and sets the colour of the lights
All closure recieve the current time of the lights (An Int value 0 or greater which is increased by 1 every time the lights are updated) and a reference to the AppDelegate to access lighting methods and approved lights
All closures are placed in an array
The update time periods are in another array and correspond to the same index in the effects array
The name of each effect is in another array and corresponds to the same index in the effects array
To add your own effects, simply add to the arrays your effect closure, update time and effect name
Here is a template for the closures array
{(time:Int,delegate:AppDelegate) in
*YOUR CODE GOES HERE*
}
e.g adding a new effect
// effect changes lights
effects += {(time:Int,delegate:AppDelegate) in
delegate.setAllLights(LFXHSBKColor(hue: 0.66, saturation: 1, brightness: 1), duration: 0)
}
// display name for light
effectName += "Blue"
// time to update
updateTimings += 1
*/
/// A timer that manages the update of light effects
var timer:Timer = Timer()
/// The current effect option being used
var effectOption:Int = 0
/// The current effects time
var effectCount:Int = 0
/// Hue slider in colour menu
let sliderH = NSSlider(frame: NSRect(x: 0, y: 0, width: 24, height: 120))
/// Saturation slider in colour menu
let sliderS = NSSlider(frame: NSRect(x: 24, y: 0, width: 24, height: 120))
/// Brightness slider in colour menu
let sliderB = NSSlider(frame: NSRect(x: 48, y: 0, width: 24, height: 120))
/// The colour of the lights determined by the HSB sliders
let lightColour = LFXHSBKColor(hue: 0, saturation: 1, brightness: 0)
func applicationDidFinishLaunching(_ aNotification: Notification) {
LFXClient.shared().localNetworkContext.allLightsCollection.add(self)
let title = NSMenuItem(title: "LIFX Master", action: nil, keyEquivalent: "")
title.isEnabled = false
let lights = NSMenuItem(title: "Lights", action: nil, keyEquivalent: "")
let quit = NSMenuItem(title: "Quit", action: #selector(AppDelegate.quit), keyEquivalent: "")
statusItem.image = NSImage(named: "MenuLogo")
let effects = NSMenuItem(title: "Effects", action: nil, keyEquivalent: "")
for name in effectNames {
let item = NSMenuItem(title: name, action: #selector(AppDelegate.setEffect), keyEquivalent: "")
effectMenu.addItem(item)
}
let toggle = NSMenuItem(title: "Lights On", action: nil, keyEquivalent: "")
toggle.isEnabled = false
let colour = NSMenuItem(title: "Colour", action: nil, keyEquivalent: "")
colour.submenu = colourMenu
let slidersView = NSView(frame: NSRect(x: 0, y: 0, width: 72, height: 120))
slidersView.addSubview(sliderH)
slidersView.addSubview(sliderS)
slidersView.addSubview(sliderB)
let colourItem = NSMenuItem(title: "", action: nil, keyEquivalent: "")
colourItem.view = slidersView
colourMenu.addItem(withTitle: "HSB", action: nil, keyEquivalent: "")
colourMenu.addItem(colourItem)
sliderH.maxValue = 360.0
sliderH.minValue = 0.0
sliderS.maxValue = 1.0
sliderS.minValue = 0.0
sliderB.maxValue = 1.0
sliderB.minValue = 0.0
sliderH.target = self
sliderS.target = self
sliderB.target = self
sliderH.action = #selector(AppDelegate.updateLightColour(_:))
sliderS.action = #selector(AppDelegate.updateLightColour(_:))
sliderB.action = #selector(AppDelegate.updateLightColour(_:))
menu.addItem(title)
menu.addItem(NSMenuItem.separator())
menu.addItem(lights)
menu.addItem(NSMenuItem.separator())
menu.addItem(toggle)
menu.addItem(colour)
menu.addItem(effects)
menu.addItem(NSMenuItem.separator())
menu.addItem(quit)
lights.submenu = lightMenu
effects.submenu = effectMenu
effectMenu.delegate = self
let noLights = NSMenuItem(title: "No Lights", action: nil, keyEquivalent: "")
noLights.isEnabled = false
lightMenu.addItem(noLights)
statusItem.menu = menu
menu.delegate = self
lightMenu.delegate = self
}
/// Called if light is discovered on network
func lightCollection(_ lightCollection: LFXLightCollection!, didAdd light: LFXLight!) {
updateSelectedLights()
}
/// Called if light is removed from network
func lightCollection(_ lightCollection: LFXLightCollection!, didRemove light: LFXLight!) {
updateSelectedLights()
}
/// Updates which lights are selected in the lights menu
func updateSelectedLights() {
lights = LFXClient.shared().localNetworkContext.allLightsCollection.lights as! [LFXLight]
for light in lights {
if selectedLights[light.label()] == nil {
selectedLights[light.label()] = false
}
}
updateMenuLightOptions()
}
/// Updates menu lighting options as new lights are discovered on the network
func updateMenuLightOptions() {
lightMenu = NSMenu()
lightMenu.delegate = self
for light in lights {
let item = NSMenuItem(title: "\(light.label()!)", action: #selector(AppDelegate.lightPicked), keyEquivalent: "")
item.target = self
lightMenu.addItem(item)
item.isEnabled = true
}
menu.item(at: 2)!.submenu = lightMenu
if lights.isEmpty {
let noLights = NSMenuItem(title: "No Lights", action: nil, keyEquivalent: "")
noLights.isEnabled = false
lightMenu.addItem(noLights)
}
}
/// Called when a light is selected, approved or diapproved for use
func lightPicked() {
if selectedItem != nil {
if selectedItem!.state == NSOnState {
selectedItem!.state = NSOffState
selectedLights[selectedItem!.title] = false
} else {
selectedItem!.state = NSOnState
selectedLights[selectedItem!.title] = true
}
}
approvedLights.removeAll()
for light in lights {
if let approve = selectedLights[light.label()] {
if approve {
approvedLights.append(light)
}
}
}
if !approvedLights.isEmpty {
menu.item(at: 4)!.isEnabled = true
menu.item(at: 4)!.action = #selector(AppDelegate.toggleLights)
if approvedLights.count == 1 {
toggleState = approvedLights[0].powerState() == LFXPowerState.on
if !toggleState {
menu.item(at: 4)!.title = "Light On"
} else {
menu.item(at: 4)!.title = "Light Off"
}
}
} else {
menu.item(at: 4)!.isEnabled = false
menu.item(at: 4)!.action = nil
}
}
/// Delegate method called when item is highlited, updates selectedItem to last highlighted item
func menu(_ menu: NSMenu, willHighlight item: NSMenuItem?) {
if menu === lightMenu {
selectedItem = item
} else if menu === effectMenu {
selectedItem = item
}
}
/// Terminated application
func quit() {
NSApplication.shared().terminate(self)
}
/// Sets all approvedLights to colour over duration
func setAllLights(_ color:LFXHSBKColor, duration:TimeInterval) {
for light in approvedLights {
light.setColor(color, overDuration: duration)
}
}
/// Sets the current effect based on last selected menu item
func setEffect() {
if let option = effectMenu.items.index(of: selectedItem!) {
effectOption = option
setupTimingForOption(option)
}
}
/// Toggles lights on or off depending on toggle state
func toggleLights() {
for light in approvedLights {
if toggleState {
light.setPowerState(.off)
} else {
light.setPowerState(.on)
}
}
if toggleState {
menu.item(at: 4)!.title = "Light On"
toggleState = false
} else {
menu.item(at: 4)!.title = "Light Off"
toggleState = true
}
}
/// Sets timer for current effect option to update after a period of time
func setupTimingForOption(_ option:Int) {
effectCount = 0
effectOption = option
timer = Timer.scheduledTimer(timeInterval: updateTimings[effectOption], target: self, selector: #selector(AppDelegate.updateLightsEffect), userInfo: nil, repeats: true)
timer.fire()
}
/// Updates current lighting effect
func updateLightsEffect() {
effects[effectOption](effectCount,self)
effectCount += 1
}
/// Updates the colour of all approvedLights based on HSB slider values
func updateLightColour(_ sender:NSSlider) {
if sender === sliderH {
lightColour?.hue = CGFloat(sliderH.doubleValue)
} else if sender === sliderS {
lightColour?.saturation = CGFloat(sliderS.doubleValue)
} else if sender === sliderB {
lightColour?.brightness = CGFloat(sliderB.doubleValue)
}
for light in approvedLights {
light.setColor(lightColour)
}
}
}
| mit | e6d663fb18e97058b80cc62798f5f7c5 | 34.837696 | 223 | 0.598977 | 4.628127 | false | false | false | false |
weiss19ja/LocalizableUI | LocalizableUI Example/ExampleViewController.swift | 1 | 855 | //
// ExampleViewController.swift
// LocalizableUI Example
//
// Created by Philipp Weiร on 23.10.17.
// Copyright ยฉ 2017 Jan Weiร, Philipp Weiร. All rights reserved.
//
import UIKit
private enum Constants {
static let titleKey = "example-alert-title"
static let messagekey = "example-alert-message"
static let buttonKey = "example-alert-button"
}
class ExampleViewController: UITableViewController {
@IBAction func didSelectAlertButton(_ sender: Any) {
let alertController = UIAlertController(localizedTitle: Constants.titleKey, localizedMessage: Constants.messagekey, preferredStyle: .alert)
let action = UIAlertAction(localizedTitleKey: Constants.buttonKey, style: .cancel, handler: nil)
alertController.addAction(action)
present(alertController, animated: true, completion: nil)
}
}
| mit | 00dae2b391ce994ee39703442ad84153 | 28.344828 | 147 | 0.733255 | 4.386598 | false | false | false | false |
CSullivan102/LearnApp | LearnKit/SmallModalTransition/SmallModalPresentationController.swift | 1 | 2563 | //
// SmallModalPresentationController.swift
// Learn
//
// Created by Christopher Sullivan on 8/31/15.
// Copyright ยฉ 2015 Christopher Sullivan. All rights reserved.
//
import UIKit
public class SmallModalPresentationController: UIPresentationController {
private let dimmingView = UIView()
override init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
dimmingView.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
}
override public func presentationTransitionWillBegin() {
guard let containerView = containerView else {
return
}
dimmingView.frame = containerView.bounds
dimmingView.alpha = 0.0
containerView.insertSubview(dimmingView, atIndex: 0)
presentedViewController.transitionCoordinator()?.animateAlongsideTransition({
context in
self.dimmingView.alpha = 1.0
}, completion: nil)
}
override public func dismissalTransitionWillBegin() {
presentedViewController.transitionCoordinator()?.animateAlongsideTransition({
context in
self.dimmingView.alpha = 0.0
}, completion: {
context in
self.dimmingView.removeFromSuperview()
})
}
override public func frameOfPresentedViewInContainerView() -> CGRect {
guard let containerView = containerView else {
return CGRect(x: 0, y: 0, width: 0, height: 0)
}
let insetBounds = containerView.bounds.insetBy(dx: 30, dy: 30)
var modalHeight = insetBounds.height
if let presentedVC = presentedViewController as? UIViewControllerHeightRequestable {
modalHeight = presentedVC.preferredHeight()
}
let yCoord = containerView.bounds.height / 2 - modalHeight / 2
return CGRect(x: insetBounds.origin.x, y: yCoord, width: insetBounds.width, height: modalHeight)
}
override public func containerViewWillLayoutSubviews() {
guard let containerView = containerView, presentedView = presentedView() else {
return
}
dimmingView.frame = containerView.bounds
presentedView.frame = frameOfPresentedViewInContainerView()
}
}
public protocol UIViewControllerHeightRequestable: class {
func preferredHeight() -> CGFloat
}
| mit | ae29a8f90f05909a5ae28cd34c413793 | 33.16 | 120 | 0.663934 | 5.985981 | false | false | false | false |
vakoc/particle-swift | Sources/Products.swift | 1 | 24749 | // This source file is part of the vakoc.com open source project(s)
//
// Copyright ยฉ 2017 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See http://www.vakoc.com/LICENSE.txt for license information
import Foundation
/// A Particle Product
public struct Product {
/// The constants used to construct/parse from json
fileprivate enum DictionaryConstants: String {
case id
case platformId = "platform_id"
case name
case slug
case latestFirmwareVersion = "latest_firmware_version"
case description
case type
case hardwareVersion = "hardware_version"
case configId = "config_id"
case organization
case subscriptionId = "subscription_id"
case mbLimit = "mb_limit"
}
/// The market segment the product is geard to
///
/// - hobbyist: Hobbyists
/// - consumer: Consumers
/// - industrial: Industrial Uses
public enum ProductType: String {
case hobbyist = "Hobbyist"
case consumer = "Consumer"
case industrial = "Industrial"
}
/// Unique identifier for the product
public var id: Int
/// The device that is included in the product
public var platform: DeviceInformation.Product
/// The name of the product
public var name: String
/// The product slug
public var slug: String
/// The most recent firmware version, if availble
public var latestFirmwareVersion: String?
/// A description of the product
public var description: String
/// The type (marget segment) of the product
public var type: ProductType
/// The version of the hardware associated with the product
public var hardwareVersion: String
/// The product configuration identifier
public var configId: String
/// The organization that owns the product
public var organization: String
/// The product subscription identifier
public var subscriptionId: Int
/// Whether the product requires an activation code
public var requiresActivationCodes: Bool = false
/// The data limit imposed on the product
public var mbLimit: Int?
}
extension Product: Equatable {
public static func ==(lhs: Product, rhs: Product) -> Bool {
return lhs.id == rhs.id &&
lhs.name == rhs.name &&
lhs.platform == rhs.platform &&
lhs.latestFirmwareVersion == rhs.latestFirmwareVersion &&
lhs.description == rhs.description &&
lhs.type == rhs.type &&
lhs.hardwareVersion == rhs.hardwareVersion &&
lhs.configId == rhs.configId &&
lhs.organization == rhs.organization &&
lhs.subscriptionId == rhs.subscriptionId &&
lhs.subscriptionId == rhs.subscriptionId &&
lhs.requiresActivationCodes == rhs.requiresActivationCodes &&
lhs.mbLimit == rhs.mbLimit
}
}
extension Product: StringKeyedDictionaryConvertible {
/// Create a Product with a dictionary
///
/// The dictionary looks like the following
///
/// {
/// "id": 3699,
/// "platform_id": 6,
/// "name": "SampleProduct",
/// "slug": "sampleproduct-v101",
/// "latest_firmware_version": null,
/// "description": "A sample product",
/// "type": "Hobbyist",
/// "hardware_version": "v1.0.1",
/// "config_id": "58cc141a363e4e6f670d093a",
/// "organization": "58cc141a363e4e6f670d0938",
/// "subscription_id": 8573,
/// "mb_limit": null
/// }
public init?(with dictionary: [String : Any]) {
guard let productId = dictionary[DictionaryConstants.id.rawValue] as? Int,
let platformId = dictionary[DictionaryConstants.platformId.rawValue] as? Int, let platform = DeviceInformation.Product(rawValue: platformId),
let name = dictionary[DictionaryConstants.name.rawValue] as? String , !name.isEmpty,
let slug = dictionary[DictionaryConstants.slug.rawValue] as? String,
let type = dictionary[DictionaryConstants.type.rawValue] as? String, let productType = ProductType(rawValue: type),
let hardwareVersion = dictionary[DictionaryConstants.hardwareVersion.rawValue] as? String,
let configId = dictionary[DictionaryConstants.configId.rawValue] as? String,
let organization = dictionary[DictionaryConstants.organization.rawValue] as? String,
let subscriptionId = dictionary[DictionaryConstants.subscriptionId.rawValue] as? Int else {
warn("Failed to create a Product using the dictionary \(dictionary); the required properties were not found")
return nil;
}
self.id = productId
self.platform = platform
self.name = name
self.slug = slug
self.type = productType
self.latestFirmwareVersion = dictionary[DictionaryConstants.latestFirmwareVersion.rawValue] as? String
self.hardwareVersion = hardwareVersion
self.configId = configId
self.organization = organization
self.subscriptionId = subscriptionId
description = dictionary[DictionaryConstants.description.rawValue] as? String ?? ""
self.mbLimit = dictionary[DictionaryConstants.mbLimit.rawValue] as? Int
}
/// The product as a dictionary using keys compatible with the original web service
public var dictionary: [String : Any] {
get {
var ret = [String : Any]()
ret[DictionaryConstants.id.rawValue] = id
ret[DictionaryConstants.platformId.rawValue] = platform.rawValue
ret[DictionaryConstants.name.rawValue] = name
ret[DictionaryConstants.slug.rawValue] = slug
ret[DictionaryConstants.latestFirmwareVersion.rawValue] = latestFirmwareVersion
ret[DictionaryConstants.description.rawValue] = description
ret[DictionaryConstants.type.rawValue] = type.rawValue
ret[DictionaryConstants.hardwareVersion.rawValue] = hardwareVersion
ret[DictionaryConstants.configId.rawValue] = configId
ret[DictionaryConstants.organization.rawValue] = organization
ret[DictionaryConstants.subscriptionId.rawValue] = subscriptionId
if let mbLimit = mbLimit {
ret[DictionaryConstants.subscriptionId.rawValue] = mbLimit
}
return ret
}
}
}
/// A product team member
public struct ProductTeamMember {
/// The constants used to construct/parse from json
fileprivate enum DictionaryConstants: String {
case id = "_id"
case username
}
/// The unique identifier of the team memeber
public var id: String
/// Username of the team member
public var username: String
}
extension ProductTeamMember: StringKeyedDictionaryConvertible {
/// Create a Product with a dictionary
///
/// The dictionary looks like the following
///
/// [
/// {
/// "_id":"9980222caf8bad191600019b",
/// "username":"[email protected]"
/// },
/// ...
/// ]
public init?(with dictionary: [String : Any]) {
guard let id = dictionary[DictionaryConstants.id.rawValue] as? String,
let username = dictionary[DictionaryConstants.username.rawValue] as? String , !username.isEmpty else { return nil }
self.id = id
self.username = username
}
/// The dproduct as a dictionary using keys compatible with the original web service
public var dictionary: [String : Any] {
get {
var ret = [String : Any]()
ret[DictionaryConstants.id.rawValue] = id
ret[DictionaryConstants.username.rawValue] = username
return ret
}
}
}
extension ProductTeamMember: Equatable {
public static func ==(lhs: ProductTeamMember, rhs: ProductTeamMember) -> Bool {
return lhs.id == rhs.id && lhs.username == rhs.username
}
}
/// A product team invitation
public struct ProductTeamInvitation {
/// A product invitation
public struct Invite {
/// Unique organization identifier
public var organization: String
/// Product slug
public var slug: String
/// Product identifier
public var product: String
/// Product name
public var name: String
/// Invigation Originator
public var invitedBy: String
/// Invigation creation date
public var invitedOn: Date
}
/// The constants used to construct/parse from json
fileprivate enum DictionaryConstants: String {
case id = "_id"
case created = "created_at"
case updated = "updated_at"
case username
case organizationInvites = "orgInvites"
case organizations = "orgs"
case organization = "org"
case slug
case invitedBy
case invitedOn
case product
case name
}
/// The unique identifier of the team memeber
public var id: String
/// The creation date of the invitation
public var created: Date
/// The last modified date of the invitation
public var updated: Date
/// Username of the team member
public var username: String
/// Pending invitations to product teams
public var organizationInvites = [Invite]()
/// The product teams the to which user currently belongs. TODO: strongly type
var organizations = [[String : Any]]()
}
extension ProductTeamInvitation.Invite: Equatable {
public static func ==(lhs: ProductTeamInvitation.Invite, rhs: ProductTeamInvitation.Invite) -> Bool {
return lhs.organization == rhs.organization &&
lhs.slug == rhs.slug &&
lhs.product == rhs.product &&
lhs.name == rhs.name &&
lhs.invitedBy == rhs.invitedBy &&
lhs.invitedOn == rhs.invitedOn
}
}
extension ProductTeamInvitation: StringKeyedDictionaryConvertible {
/// Create a Product with a dictionary
///
/// The dictionary looks like the following
///
/// {
/// "_id":"12351fc561a46af606000abc",
/// "created_at":"2014-08-08T19:06:45.000Z",
/// "updated_at":"2017-03-14T22:38:40.028Z",
/// "username":"[email protected]",
/// "orgInvites": [
/// {
/// "org":"456bcd",
/// "slug":"my-product",
/// "product":"3333999",
/// "name":"My Product",
/// "invitedBy":"[email protected]",
/// "invitedOn":"2017-01-18T18:53:00.235Z"
/// }
/// ],
/// "orgs":[]
/// }
public init?(with dictionary: [String : Any]) {
guard let id = dictionary[DictionaryConstants.id.rawValue] as? String,
let createdString = dictionary[DictionaryConstants.created.rawValue] as? String, let created = createdString.dateWithISO8601String,
let updatedString = dictionary[DictionaryConstants.created.rawValue] as? String, let updated = updatedString.dateWithISO8601String,
let username = dictionary[DictionaryConstants.username.rawValue] as? String , !username.isEmpty else { return nil }
self.id = id
self.created = created
self.updated = updated
self.username = username
if let orgInvites = dictionary[DictionaryConstants.organizationInvites.rawValue] as? [[String : Any]] {
organizationInvites = orgInvites.compactMap {
guard let organization = $0[DictionaryConstants.organization.rawValue] as? String,
let slug = $0[DictionaryConstants.slug.rawValue] as? String,
let product = $0[DictionaryConstants.product.rawValue] as? String,
let name = $0[DictionaryConstants.name.rawValue] as? String,
let invitedBy = $0[DictionaryConstants.invitedBy.rawValue] as? String,
let invitedOnString = $0[DictionaryConstants.invitedOn.rawValue] as? String,
let invitedOn = invitedOnString.dateWithISO8601String else { return nil }
return Invite(organization: organization, slug: slug, product: product, name: name, invitedBy: invitedBy, invitedOn: invitedOn)
}
}
}
/// The dproduct as a dictionary using keys compatible with the original web service
public var dictionary: [String : Any] {
get {
var ret = [String : Any]()
ret[DictionaryConstants.id.rawValue] = id
ret[DictionaryConstants.created.rawValue] = created.ISO8601String
ret[DictionaryConstants.updated.rawValue] = updated.ISO8601String
ret[DictionaryConstants.username.rawValue] = username
let x: [[String : Any]] = organizationInvites.map {
var ret = [String : Any]()
ret[DictionaryConstants.organization.rawValue] = $0.organization
ret[DictionaryConstants.slug.rawValue] = $0.slug
ret[DictionaryConstants.product.rawValue] = $0.product
ret[DictionaryConstants.name.rawValue] = $0.name
ret[DictionaryConstants.invitedBy.rawValue] = $0.invitedBy
ret[DictionaryConstants.invitedOn.rawValue] = $0.invitedOn.ISO8601String
return ret
}
ret[DictionaryConstants.organizationInvites.rawValue] = x
// TODO: handle orgs
return ret
}
}
}
extension ProductTeamInvitation: Equatable {
public static func ==(lhs: ProductTeamInvitation, rhs: ProductTeamInvitation) -> Bool {
return lhs.id == rhs.id
&& lhs.created == rhs.created
&& lhs.updated == rhs.updated
&& lhs.username == rhs.username
&& lhs.organizationInvites == rhs.organizationInvites
// TODO: after strongly typing organizations add a check for equality
//&& lhs.organizations == rhs.organizations
}
}
// MARK: Products
extension ParticleCloud {
/// List the available products or an individual product
///
/// Reference API https://docs.particle.io/reference/api/#list-products
///
/// - Parameters:
/// - productIdOrSlug: The product id (or slug) to retrieve. If nil, all products will be retrieved
/// - completion: The asynchronous result containing an array of products or an error code
public func products(_ productIdOrSlug: String? = nil, completion: @escaping (Result<[Product]>) -> Void ) {
self.authenticate(false) { result in
switch result {
case .failure(let error):
return completion(.failure(error))
case .success(let accessToken):
var url = self.baseURL.appendingPathComponent("v1/products")
if let productIdOrSlug = productIdOrSlug {
url = url.appendingPathComponent("/\(productIdOrSlug)")
}
var request = URLRequest(url: url)
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
let task = self.urlSession.dataTask(with: request) { (data, response, error) in
trace("Listing products", request: request, data: data, response: response, error: error)
if let error = error {
return completion(.failure(ParticleError.productsListFailed(error)))
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let j = json {
if let products = j[productIdOrSlug == nil ? "products" : "product"] as? [[String : Any]] {
return completion(.success(products.compactMap({ return Product(with: $0)})))
} else {
return completion(.success([]))
}
} else {
let message = data != nil ? String(data: data!, encoding: String.Encoding.utf8) ?? "" : ""
warn("Failed to obtain product with response: \(String(describing: response)) and message body \(String(describing: message))")
return completion(.failure(ParticleError.productsListFailed(ParticleError.httpResponseParseFailed(message))))
}
}
task.resume()
}
}
}
/// List all team members that are part of a given product
///
/// Reference API https://docs.particle.io/reference/api/#list-team-members
///
/// - Parameters:
/// - productIdOrSlug: The product id (or slug) to retrieve
/// - completion: The asynchronous result containing an array of products or an error code
public func productTeamMembers(_ productIdOrSlug: String, completion: @escaping (Result<[ProductTeamMember]>) -> Void ) {
self.authenticate(false) { result in
switch result {
case .failure(let error):
return completion(.failure(error))
case .success(let accessToken):
let url = self.baseURL.appendingPathComponent("v1/products/\(productIdOrSlug)/team")
var request = URLRequest(url: url)
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
let task = self.urlSession.dataTask(with: request) { (data, response, error) in
trace("Retrieving product team members", request: request, data: data, response: response, error: error)
if let error = error {
return completion(.failure(ParticleError.productTeamMembersFailed(error)))
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [[String : Any]], let j = json {
return completion(.success(j.compactMap({ return ProductTeamMember(with: $0)})))
} else {
let message = data != nil ? String(data: data!, encoding: String.Encoding.utf8) ?? "" : ""
warn("Failed to obtain product team members with response: \(String(describing: response)) and message body \(String(describing: message))")
return completion(.failure(ParticleError.productTeamMembersFailed(ParticleError.httpResponseParseFailed(message))))
}
}
task.resume()
}
}
}
/// Invite a new member to a product team. Invitee will receive an email with a link to accept the invitation and join the team.
///
/// Reference API https://docs.particle.io/reference/api/#invite-team-member
///
/// - Parameters:
/// - productIdOrSlug: The product id (or slug) on which the invite is extended
/// - username: Username of the invitee. Must be a valid email associated with an Particle user
/// - completion: The asynchronous result containing details of the invited user or an error code
public func inviteTeamMember(_ productIdOrSlug: String, username: String, completion: @escaping (Result<ProductTeamInvitation>) -> Void ) {
self.authenticate(false) { result in
switch result {
case .failure(let error):
return completion(.failure(error))
case .success(let accessToken):
let url = self.baseURL.appendingPathComponent("v1/products/\(productIdOrSlug)/team")
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = ["username" : username].URLEncodedParameters?.data(using: String.Encoding.utf8)
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
let task = self.urlSession.dataTask(with: request) { (data, response, error) in
trace("Inviting team member", request: request, data: data, response: response, error: error)
if let error = error {
return completion(.failure(ParticleError.inviteTeamMemberFailed(error)))
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let j = json, let invite = ProductTeamInvitation(with: j) {
return completion(.success(invite))
} else {
let message = data != nil ? String(data: data!, encoding: String.Encoding.utf8) ?? "" : ""
warn("Failed to invite team member with response: \(String(describing: response)) and message body \(String(describing: message))")
return completion(.failure(ParticleError.inviteTeamMemberFailed(ParticleError.httpResponseParseFailed(message))))
}
}
task.resume()
}
}
}
/// Remove a current team member.
///
/// Reference API https://docs.particle.io/reference/api/#remove-team-member
///
/// - Parameters:
/// - productIdOrSlug: The product id (or slug) on which the team member is removed
/// - username: Username of the team member to be removed
/// - completion: The asynchronous result detailing the result of the member removal
public func removeTeamMember(_ productIdOrSlug: String, username: String, completion: @escaping (Result<Bool>) -> Void ) {
self.authenticate(false) { result in
switch result {
case .failure(let error):
return completion(.failure(error))
case .success(let accessToken):
guard let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
return completion(.failure(ParticleError.invalidUsername))
}
let url = self.baseURL.appendingPathComponent("v1/products/\(productIdOrSlug)/team/\(encodedUsername)")
var request = URLRequest(url: url)
request.httpMethod = "DELETE"
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
let task = self.urlSession.dataTask(with: request) { (data, response, error) in
trace("Remove team member", request: request, data: data, response: response, error: error)
if let error = error {
return completion(.failure(ParticleError.removeTeamMemberFailed(error)))
}
if let response = response as? HTTPURLResponse, response.statusCode == 204 {
return completion(.success(true))
} else {
let message = data != nil ? String(data: data!, encoding: String.Encoding.utf8) ?? "" : ""
warn("Failed to remove team member with response: \(String(describing: response)) and message body \(String(describing: message))")
return completion(.failure(ParticleError.removeTeamMemberFailed(ParticleError.httpResponseParseFailed(message))))
}
}
task.resume()
}
}
}
}
| apache-2.0 | 1eb7071606b8336074fdce5c00f0cffd | 41.160136 | 190 | 0.583158 | 5.058872 | false | false | false | false |
yanoooooo/DecoRecipe | DecoRecipe/DecoRecipe/ImageUtil.swift | 1 | 2095 | //
// DetectUtil.swift
// DecoRecipe
//
// Created by Yano on 2015/06/03.
// Copyright (c) 2015ๅนด Yano. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
class ImageUtil {
// sampleBufferใใUIImageใธๅคๆ
class func imageFromSampleBuffer(sampleBuffer: CMSampleBufferRef) -> UIImage {
let imageBuffer: CVImageBufferRef = CMSampleBufferGetImageBuffer(sampleBuffer)
// ใใผในใขใใฌในใใญใใฏ
CVPixelBufferLockBaseAddress(imageBuffer, 0)
// ็ปๅใใผใฟใฎๆ
ๅ ฑใๅๅพ
let baseAddress: UnsafeMutablePointer<Void> = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0)
let bytesPerRow: Int = CVPixelBufferGetBytesPerRow(imageBuffer)
let width: Int = CVPixelBufferGetWidth(imageBuffer)
let height: Int = CVPixelBufferGetHeight(imageBuffer)
// RGB่ฒ็ฉบ้ใไฝๆ
let colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceRGB()
// Bitmap graphic contextใไฝๆ
let bitsPerCompornent: Int = 8
var bitmapInfo = CGBitmapInfo((CGBitmapInfo.ByteOrder32Little.rawValue | CGImageAlphaInfo.PremultipliedFirst.rawValue) as UInt32)
let newContext: CGContextRef = CGBitmapContextCreate(baseAddress, width, height, bitsPerCompornent, bytesPerRow, colorSpace, bitmapInfo) as CGContextRef
// Quartz imageใไฝๆ
let imageRef: CGImageRef = CGBitmapContextCreateImage(newContext)
// UIImageใไฝๆ
let resultImage: UIImage = UIImage(CGImage: imageRef)!
return resultImage
}
//ใฌใคใใฉใคใณใฎๅ
ๅดใฎๅใๆใ
class func clipImg(srcImg: UIImage, rect: CGRect) -> UIImage{
var dstImg: UIImage = UIImage()
let clipRect = CGRectMake(
rect.origin.x+25, rect.origin.y-35,
rect.width, rect.height)
let clipRef = CGImageCreateWithImageInRect(srcImg.CGImage, clipRect)
dstImg = UIImage(CGImage: clipRef)!
return dstImg
}
}
| mit | f84faadfa6a22e434c58760dd24e6e1f | 33.754386 | 160 | 0.672892 | 4.683215 | false | false | false | false |
ilyahal/VKMusic | VkPlaylist/EditPlaylistMusicTableViewController.swift | 1 | 8203 | //
// EditPlaylistMusicTableViewController.swift
// VkPlaylist
//
// MIT License
//
// Copyright (c) 2016 Ilya Khalyapin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
/// ะะพะฝััะพะปะปะตั ัะพะดะตัะถะฐัะธะน ัะฐะฑะปะธัั ัะพ ัะฟะธัะบะพะผ ะฐัะดะธะพะทะฐะฟะธัะตะน ัะตะดะฐะบัะธััะตะผะพะณะพ ะฟะปะตะนะปะธััะฐ
class EditPlaylistMusicTableViewController: UITableViewController {
/// ะ ะตะดะฐะบัะธััะตะผัะน ะฟะปะตะนะปะธัั
var playlistToEdit: Playlist?
/// ะะฐััะธะฒ ััะตะบะพะฒ ะฟะปะตะนะปะธััะฐ
var tracks = [OfflineTrack]()
override func viewDidLoad() {
super.viewDidLoad()
if let playlistToEdit = playlistToEdit where playlistToEdit.tracks.count != 0 {
for trackInPlaylist in DataManager.sharedInstance.getTracksForPlaylist(playlistToEdit) {
tracks.append(trackInPlaylist.track)
}
}
// ะะฐััะพะผะธะทะฐัะธั tableView
tableView.tableFooterView = UIView() // ะงะธััะธะผ ะฟัััะพะต ะฟัะพัััะฐะฝััะฒะพ ะฟะพะด ัะฐะฑะปะธัะตะน
tableView.allowsSelectionDuringEditing = true // ะะพะทะผะพะถะฝะพ ะฒัะดะตะปะตะฝะธะต ััะตะตะบ ะฟัะธ ัะตะดะฐะบัะธัะพะฒะฐะฝะธะธ
tableView.editing = true
// ะ ะตะณะธัััะฐัะธั ััะตะตะบ
let cellNib = UINib(nibName: TableViewCellIdentifiers.offlineAudioCell, bundle: nil) // ะฏัะตะนะบะฐ ัะพ ัะบะฐัะตะฝะฝัะผ ััะตะบะพะผ
tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.offlineAudioCell)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == SegueIdentifiers.showAddPlaylistMusicViewControllerSegue {
let navigationController = segue.destinationViewController as! UINavigationController
let addPlaylistMusicViewController = navigationController.viewControllers.first as! AddPlaylistMusicViewController
addPlaylistMusicViewController.delegate = self
}
}
/// ะะฐะฝะพะฒะพ ะพััะธัะพะฒะฐัั ัะฐะฑะปะธัั
func reloadTableView() {
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
// MARK: ะะพะปััะตะฝะธะต ััะตะตะบ ะดะปั ัััะพะบ ัะฐะฑะปะธัั
/// ะฏัะตะนะบะฐ ะดะปั ัััะพะบะธ ั ะทะฐะณััะถะตะฝะฝัะผ ััะตะบะพะผ
func getCellForAddAudioForIndexPath(indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.addAudioCell, forIndexPath: indexPath)
return cell
}
// ะฏัะตะนะบะฐ ะดะปั ัััะพะบะธ ั ะทะฐะณััะถะตะฝะฝัะผ ััะตะบะพะผ
func getCellForOfflineAudioForIndexPath(indexPath: NSIndexPath) -> UITableViewCell {
let track = tracks[indexPath.row - 1]
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.offlineAudioCell, forIndexPath: indexPath) as! OfflineAudioCell
cell.configureForTrack(track)
cell.selectionStyle = .None
return cell
}
}
// MARK: UITableViewDataSource
private typealias _EditPlaylistMusicTableViewControllerDataSource = EditPlaylistMusicTableViewController
extension _EditPlaylistMusicTableViewControllerDataSource {
// ะะพะปััะตะฝะธะต ะบะพะปะธัะตััะฒะฐ ัััะพะบ ัะฐะฑะปะธัั
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tracks.count + 1
}
// ะะพะปััะตะฝะธะต ััะตะนะบะธ ะดะปั ัััะพะบะธ ัะฐะฑะปะธัั
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
return getCellForAddAudioForIndexPath(indexPath)
}
return getCellForOfflineAudioForIndexPath(indexPath)
}
// ะะพะทะผะพะถะฝะพ ะปะธ ัะตะดะฐะบัะธัะพะฒะฐัั ััะตะนะบั
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return indexPath.row != 0
}
// ะะฑัะฐะฑะพัะบะฐ ัะดะฐะปะตะฝะธั ััะตะนะบะธ
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
tracks.removeAtIndex(indexPath.row - 1)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
// ะะพะทะผะพะถะฝะพ ะปะธ ะฟะตัะตะผะตัะฐัั ััะตะนะบั
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return indexPath.row != 0
}
// ะะฑัะฐะฑะพัะบะฐ ะฟะพัะปะต ะฟะตัะตะผะตัะตะฝะธั ััะตะนะบะธ
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
let trackToMove = tracks[fromIndexPath.row - 1]
tracks.removeAtIndex(fromIndexPath.row - 1)
tracks.insert(trackToMove, atIndex: toIndexPath.row - 1)
}
// ะะฟัะตะดะตะปัะตััั ะบัะดะฐ ะฟะตัะตะผะตััะธัั ััะตะนะบั ั ัะบะทะฐะฝะฝะพะณะพ NSIndexPath ะฟัะธ ะฟะตัะตะผะตัะตะฝะธะธ ะฒ ัะบะฐะทะฐะฝะฝัะน NSIndexPath
override func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
if proposedDestinationIndexPath.row == 0 {
return sourceIndexPath
} else {
return proposedDestinationIndexPath
}
}
}
// MARK: UITableViewDelegate
private typealias _EditPlaylistMusicTableViewControllerDelegate = EditPlaylistMusicTableViewController
extension _EditPlaylistMusicTableViewControllerDelegate {
// ะััะพัะฐ ะบะฐะถะดะพะน ัััะพะบะธ
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return 53
}
return 62
}
// ะัะทัะฒะฐะตััั ะฟัะธ ัะฐะฟะต ะฟะพ ัััะพะบะต ัะฐะฑะปะธัั
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.row == 0 {
performSegueWithIdentifier(SegueIdentifiers.showAddPlaylistMusicViewControllerSegue, sender: nil)
}
}
}
// MARK: AddPlaylistMusicDelegate
extension EditPlaylistMusicTableViewController: AddPlaylistMusicDelegate {
// ะัะดะธะพะทะฐะฟะธัั ะฑัะปะฐ ะดะพะฑะฐะฒะปะตะฝะฐ ะฒ ะฟะปะตะนะปะธัั
func addPlaylistMusicDelegateAddTrack(track: OfflineTrack) {
tracks.append(track)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.tracks.count, inSection: 0)], withRowAnimation: .None)
})
}
} | mit | 8175a9646c560f0c92215eaa92a9c046 | 37.6 | 202 | 0.714058 | 5.098916 | false | false | false | false |
richeterre/SwiftGoal | Carthage/Checkouts/Argo/Argo Playground.playground/Pages/iTunes Example.xcplaygroundpage/Contents.swift | 21 | 1857 | /*:
**Note:** For **Argo** to be imported into the Playground, ensure that the **Argo-Mac** *scheme* is selected from the list of schemes.
* * *
*/
import Foundation
import Argo
import Curry
/*:
**Helper function** โ load JSON from a file
*/
func JSONFromFile(file: String) -> AnyObject? {
return NSBundle.mainBundle().pathForResource(file, ofType: "json")
.flatMap { NSData(contentsOfFile: $0) }
.flatMap(JSONObjectWithData)
}
func JSONObjectWithData(data: NSData) -> AnyObject? {
do { return try NSJSONSerialization.JSONObjectWithData(data, options: []) }
catch { return .None }
}
/*:
During JSON decoding, a **String** representation of a date needs to be converted to a **NSDate**.
To achieve this, a **NSDateFormatter** and a helper function will be used.
*/
let jsonDateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssz"
return dateFormatter
}()
let toNSDate: String -> Decoded<NSDate> = {
.fromOptional(jsonDateFormatter.dateFromString($0))
}
/*:
## Decoding selected entries from the iTunes store JSON format
An example JSON file (**tropos.json**) can be found in the **resources** folder.
*/
struct App {
let name: String
let formattedPrice: String
let averageUserRating: Float?
let releaseDate: NSDate
}
extension App: CustomStringConvertible {
var description: String {
return "name: \(name)\nprice: \(formattedPrice), rating: \(averageUserRating), released: \(releaseDate)"
}
}
extension App: Decodable {
static func decode(j: JSON) -> Decoded<App> {
return curry(self.init)
<^> j <| "trackName"
<*> j <| "formattedPrice"
<*> j <|? "averageUserRating"
<*> (j <| "releaseDate" >>- toNSDate)
}
}
/*:
* * *
*/
let app: App? = (JSONFromFile("tropos")?["results"].flatMap(decode))?.first
print(app!)
| mit | 5047c48aa067b32472caf89849354a06 | 26.686567 | 134 | 0.685175 | 3.880753 | false | false | false | false |
stvalentin/skmenunode | skmenunode/Classes/SKMenuNode.swift | 1 | 8214 | //
// SKMenuNode.swift
// skmenunode
//
// Created by Stanciu Valentin on 25/07/16.
// Copyright ยฉ 2016 CocoaPods. All rights reserved.
//
import Foundation
import SpriteKit
#if os(watchOS)
import WatchKit
// <rdar://problem/26756207> SKColor typealias does not seem to be exposed on watchOS SpriteKit
typealias SKColor = UIColor
#endif
@objc public protocol MenuNodeDelegate {
//func menuTargetTouched(index: Int)
@objc optional func menuTargetTouched(_ index: Int, section: String);
}
open class SKMenuImage {
}
open class SKMenuPOP {
}
public typealias callbackCompletion = (() -> Void);
struct MenuItem {
var item: AnyObject
let callback: callbackCompletion?
}
open class SKMenuNode: SKNode {
var delegate: MenuNodeDelegate?
var padding: Int = 50;
var xPos: Int = 0;
var yPos: Int = 0;
var defaultText: SKLabelNode?;
var items: Array<MenuItem>
var actions: Array<AnyObject>
var layoutType: SKMenuLayout;
var section: String = "default";
var _fontSize: Int = 28;
fileprivate var _backgroundButton: UIColor = UIColor.blue;
override public init () {
items = Array();
actions = Array();
layoutType = .horizontal;
super.init();
self.isUserInteractionEnabled = true;
}
convenience public init(delegate: MenuNodeDelegate) {
self.init();
self.delegate = delegate
}
convenience public init(delegate: MenuNodeDelegate, section: String) {
self.init();
self.section = section;
self.delegate = delegate
}
open func setBackgroundButton(color: UIColor) {
self._backgroundButton = color;
}
open func setLayout(_ layoutType: SKMenuLayout) {
self.layoutType = layoutType;
}
open func setPadding(_ padding: Int = 20) {
self.padding = padding;
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@discardableResult
open func addChainTarget(_ item: String, callback: callbackCompletion? = nil) -> AnyObject {
let node:SKLabelNode = SKLabelNode(fontNamed: "HelveticaNeue");
//let layer = SKSpriteNode.init(color: UIColor.blueColor(), size: CGSize(width: 175, height: 45));
let layer = SKShapeNode(rect: CGRect(x: 0, y: 0, width: 200, height: 45), cornerRadius: 12);
//ACTIVE /HOVER /DISABLED
layer.strokeColor = _backgroundButton;
layer.fillColor = _backgroundButton;
node.fontColor = UIColor.white;
node.fontSize = CGFloat(_fontSize);
node.text = item;
node.color = UIColor.white
//node.anchorPoint = CGPointMake(0.5, 0.5);
node.position = CGPoint(x: layer.frame.midX , y: layer.frame.midY);
node.name = "text";
node.horizontalAlignmentMode = .center;
node.verticalAlignmentMode = .center;
layer.position = self.getPosition(layer);
layer.addChild(node);
layer.isUserInteractionEnabled = false;
self.addChild(layer);
items.append(MenuItem(item: layer, callback: callback));
return self;
}
open func getContainer() -> SKSpriteNode
{
let size = self.calculateAccumulatedFrame();
let tempNode = SKSpriteNode(color: UIColor.clear,
size: CGSize(width: size.width, height: size.height));
self.position = CGPoint(x: -1 * size.midX, y: -1 * size.midY);
tempNode.addChild(self);
tempNode.position = CGPoint.zero; //CGPoint(x: -1 * size.midX, y: -1 * size.midY);
tempNode.anchorPoint = CGPoint(x: 0, y: 1);
return tempNode;
}
open func setFontSize(size: Int) {
self._fontSize = size;
}
open func addTarget(_ item: String) {
let node: SKLabelNode = SKLabelNode(fontNamed: "HelveticaNeue");
node.text = item
node.fontSize = 28;
node.position = self.getPosition(node);
node.verticalAlignmentMode = .center;
node.horizontalAlignmentMode = .left;
self.addChild(node);
items.append(MenuItem(item: node, callback: nil));
}
open func addTargetImage(_ item: SKSpriteNode, callback: callbackCompletion?) {
item.position = self.getPosition(item);
self.addChild(item);
items.append(MenuItem(item: item, callback: callback));
}
open func changeTargetLabelContent(_ index: Int, content: String) {
let node = items[index].item as! SKShapeNode;
node.children.forEach { (snode) in
let textNode = snode as! SKLabelNode;
textNode.text = content;
}
}
open func changeTargetContent(_ index: Int, content: String) {
let node = items[index].item as! SKLabelNode;
node.text = content;
/*
let node = items[index] as! SKSpriteNode;
node.enumerateChildNodesWithName("name") { (node, unsafePointer) in
let nodeText = node as! SKLabelNode;
nodeText.text = content;
}
*/
}
/**
* @TODO: Still al lot of pozitioning issues
*/
func getPosition(_ node: SKNode) -> CGPoint {
let padd = self.items.count != 0 ? self.padding: 5;
if (self.layoutType == .horizontal) {
if (self.items.count == 0) {
xPos = (Int(node.calculateAccumulatedFrame().width) + padd);
return CGPoint(x: padd, y: 0);
}
let xPosPrev = xPos + padd;
xPos += (Int(node.calculateAccumulatedFrame().width)) + padd;
return CGPoint(x: xPosPrev, y: yPos);
} else {
xPos = 0;
yPos -= (Int(node.frame.height) + padd);
}
return CGPoint(x: xPos, y: yPos);
}
open func addText(_ item: String) {
defaultText = SKLabelNode(fontNamed: "HelveticaNeue");
defaultText?.text = item
self.addChild(defaultText!);
items.append(MenuItem(item: defaultText!, callback: nil));
defaultText?.position = CGPoint(x: 0, y: xPos);
xPos -= (Int(defaultText!.frame.height) + self.padding);
}
func changeText(_ item: String) {
defaultText?.text = item;
}
func setPosition() {
}
func menuTargetTouched() {
//
}
func render() {
//
}
}
#if os(watchOS)
extension SKMenuNode {
@available(watchOSApplicationExtension 3.0, *)
@IBAction func handleSingleTap(tapGesture: WKTapGestureRecognizer) {
let location = tapGesture.locationInObject()
for index in 0...items.count-1 {
if (items[index].item.calculateAccumulatedFrame().contains(location)) {
if (items[index].callback != nil) {
items[index].callback!();
} else{
delegate?.menuTargetTouched(index, section: section);
}
}
}
}
}
#endif
#if os(iOS) || os(tvOS)
extension SKMenuNode {
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
//let touch:UITouch = touches.anyObject() as! UITouch
let touchLocation = touch.location(in: self)
for index in 0...items.count-1 {
if (items[index].item.calculateAccumulatedFrame().contains(touchLocation)) {
if (items[index].callback != nil) {
items[index].callback!();
} else{
delegate?.menuTargetTouched!(index, section: section);
}
}
}
}
}
}
#endif
public enum SKMenuLayout {
case horizontal, vertical;
}
| mit | d9b24ff4230b11b072ccae33b2786354 | 28.227758 | 106 | 0.562036 | 4.527563 | false | false | false | false |
bitjammer/swift | validation-test/compiler_crashers_fixed/01662-llvm-ondiskchainedhashtable-swift-modulefile-decltableinfo-find.swift | 65 | 1572 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
}
}
}
var d : P {
for c == [[T>)
struct d: e? = b: (z: String {
}
struct Q<B : 1]() -> (true }
}
}
}
b.h: a : Any, U) -> Any)
class A : AnyObject.count][1]](A
}
case .c : A> U) -> {
protocol c {
typealias A {
}
case C) {
func b, V>(true {
}
struct c<U) -> {
}
func a: A>? {
}
class A
typealias d
typealias f = {
var f = {
extension NSSet {
func f(A.E == i<T -> ([0.C<S {
enum A = [c<T> <S {
func c(c: U, B() -> {
init(A<c) -> (false)
init() { c: X.f = i<T where k.startIndex)!.e: a {
private class A {
let g = F
}
self, V, A {
func e: T, self.d where H.advance(_ = b: String {
class B = h: T>) {
}
}
protocol b {
init(")
typealias A {
e : A<T.d>: B<f == c) {
protocol d = c> {
}
}
() -> {
enum S<T] as Boolean, Any) {
class A<T where l..init(_ = b()
struct e where T> : end)
}
}
}
}
var e, g: b = Int) {
return NSData()
}
func b
func a""\() {
protocol c == "ab"
}
func a<T>()
init(T, x }
init <S : Boolean)
func g<U : Bool) {
enum a: NSObject {
func d: A where f, Any, y: [B, (A.Iterator.C(seq: AnyObject)
}
0] = ")
func i: A"].init()
typealias e = g("""))
i<T>(object1, e
class B == b("ab"""\(n: C<T where T: d = c() -> Any) ->)
func b.init()
class func c: c<f = { c, b =
| apache-2.0 | 28fe039804cac649f3b504ea9babc41c | 17.068966 | 79 | 0.571247 | 2.46395 | false | false | false | false |
carabina/Lantern | LanternModel/PageMapper.swift | 1 | 11404 | //
// PageMapper.swift
// Hoverlytics
//
// Created by Patrick Smith on 24/04/2015.
// Copyright (c) 2015 Burnt Caramel. All rights reserved.
//
import Foundation
let JUST_USE_FINAL_URLS = true
public struct MappableURL {
public let primaryURL: NSURL
public let localHost: String
}
extension MappableURL {
public init?(primaryURL: NSURL) {
if let primaryURL = conformURL(primaryURL)?.absoluteURL {
if let localHost = primaryURL.host {
self.primaryURL = primaryURL
self.localHost = localHost
return
}
}
return nil
}
}
public class PageMapper {
public let primaryURL: NSURL
public let crawlsFoundURLs: Bool
public let maximumDepth: UInt
let localHost: String
public internal(set) var additionalURLs = [NSURL]()
//var ignoresNoFollows = false
internal(set) var requestedURLsUnique = UniqueURLArray()
public internal(set) var loadedURLToPageInfo = [NSURL: PageInfo]()
public internal(set) var requestedURLToDestinationURL = [NSURL: NSURL]()
public internal(set) var requestedURLToResponseType = [NSURL: PageResponseType]()
public func hasFinishedRequestingURL(requestedURL: NSURL) -> Bool {
return requestedURLToResponseType[requestedURL] != nil
}
public internal(set) var externalURLs = Set<NSURL>()
internal(set) var requestedLocalPageURLsUnique = UniqueURLArray()
public var localPageURLsOrdered: [NSURL] {
return requestedLocalPageURLsUnique.orderedURLs
}
internal(set) var requestedImageURLsUnique = UniqueURLArray()
public var imageURLsOrdered: [NSURL] {
return requestedImageURLsUnique.orderedURLs
}
var requestedFeedURLsUnique = UniqueURLArray()
public var feedURLsOrdered: [NSURL] {
return requestedFeedURLsUnique.orderedURLs
}
var baseContentTypeToResponseTypeToURLCount = [BaseContentType: [PageResponseType: UInt]]()
var baseContentTypeToSummedByteCount = [BaseContentType: UInt]()
var baseContentTypeToMaximumByteCount = [BaseContentType: UInt]()
public var redirectedSourceURLToInfo = [NSURL: RequestRedirectionInfo]()
public var redirectedDestinationURLToInfo = [NSURL: RequestRedirectionInfo]()
private let infoRequestQueue: PageInfoRequestQueue
private enum State {
case Idle
case Crawling
case Paused
}
private var state: State = .Idle
public var isCrawling: Bool {
return state == .Crawling
}
public var paused: Bool {
return state == .Paused
}
var queuedURLsToRequestWhilePaused = [(NSURL, BaseContentType, UInt?)]()
public var didUpdateCallback: ((pageURL: NSURL) -> Void)?
private static let defaultMaximumDefault: UInt = 10
public init(mappableURL: MappableURL, crawlsFoundURLs: Bool = true, maximumDepth: UInt = defaultMaximumDefault) {
self.primaryURL = mappableURL.primaryURL
self.localHost = mappableURL.localHost
self.crawlsFoundURLs = crawlsFoundURLs
self.maximumDepth = maximumDepth
infoRequestQueue = PageInfoRequestQueue()
infoRequestQueue.willPerformHTTPRedirection = { [weak self] redirectionInfo in
if
let pageMapper = self,
let sourceURL = redirectionInfo.sourceRequest.URL,
let nextURL = redirectionInfo.nextRequest.URL
{
#if DEBUG
println("REDIRECT \(sourceURL) \(nextURL)")
#endif
pageMapper.redirectedSourceURLToInfo[sourceURL] = redirectionInfo
pageMapper.redirectedDestinationURLToInfo[nextURL] = redirectionInfo
}
}
}
public func addAdditionalURL(URL: NSURL) {
additionalURLs.append(URL)
if isCrawling {
retrieveInfoForPageWithURL(URL, expectedBaseContentType: .LocalHTMLPage, currentDepth: 0)
}
}
func clearLoadedInfo() {
requestedURLsUnique.removeAll()
loadedURLToPageInfo.removeAll()
requestedURLToDestinationURL.removeAll()
requestedURLToResponseType.removeAll()
requestedLocalPageURLsUnique.removeAll()
externalURLs.removeAll()
requestedImageURLsUnique.removeAll()
requestedFeedURLsUnique.removeAll()
redirectedSourceURLToInfo.removeAll()
redirectedDestinationURLToInfo.removeAll()
queuedURLsToRequestWhilePaused.removeAll()
baseContentTypeToResponseTypeToURLCount.removeAll()
baseContentTypeToSummedByteCount.removeAll()
}
public func reload() {
state = .Crawling
clearLoadedInfo()
retrieveInfoForPageWithURL(primaryURL, expectedBaseContentType: .LocalHTMLPage, currentDepth: 0)
for additionalURL in additionalURLs {
retrieveInfoForPageWithURL(additionalURL, expectedBaseContentType: .LocalHTMLPage, currentDepth: 0)
}
}
public func pageInfoForRequestedURL(URL: NSURL) -> PageInfo? {
if JUST_USE_FINAL_URLS {
if let URL = conformURL(URL) {
return loadedURLToPageInfo[URL]
}
}
else if let destinationURL = requestedURLToDestinationURL[URL] {
return loadedURLToPageInfo[destinationURL]
}
return nil
}
private func retrieveInfoForPageWithURL(pageURL: NSURL, expectedBaseContentType: BaseContentType, currentDepth: UInt?) {
if linkedURLLooksLikeFileDownload(pageURL) {
return
}
if !paused {
if let pageURL = requestedURLsUnique.insertReturningConformedURLIfNew(pageURL) {
let includeContent = !hasReachedMaximumByteLimitForBaseContentType(expectedBaseContentType)
infoRequestQueue.addRequestForURL(pageURL, expectedBaseContentType: expectedBaseContentType, includingContent: includeContent) { [weak self] (info, infoRequest) in
self?.didRetrieveInfo(info, forPageWithRequestedURL: pageURL, expectedBaseContentType: expectedBaseContentType, currentDepth: currentDepth)
}
}
}
else {
queuedURLsToRequestWhilePaused.append((pageURL, expectedBaseContentType, currentDepth))
}
}
public func priorityRequestContentIfNeededForURL(URL: NSURL, expectedBaseContentType: BaseContentType) {
if let
info = pageInfoForRequestedURL(URL),
contentInfo = info.contentInfo
{
return
}
infoRequestQueue.cancelRequestForURL(URL)
infoRequestQueue.addRequestForURL(URL, expectedBaseContentType: expectedBaseContentType, includingContent: true, highPriority: true) { [weak self] (info, infoRequest) in
self?.didRetrieveInfo(info, forPageWithRequestedURL: URL, expectedBaseContentType: expectedBaseContentType, currentDepth: nil)
}
}
private func didRetrieveInfo(pageInfo: PageInfo, forPageWithRequestedURL requestedPageURL: NSURL, expectedBaseContentType: BaseContentType, currentDepth: UInt?) {
let responseType = PageResponseType(statusCode: pageInfo.statusCode)
requestedURLToResponseType[requestedPageURL] = responseType
if responseType == .Redirects {
#if DEBUG
println("REDIRECT \(requestedPageURL) \(pageInfo.finalURL)")
#endif
}
if let finalURL = pageInfo.finalURL {
requestedURLToDestinationURL[requestedPageURL] = finalURL
loadedURLToPageInfo[finalURL] = pageInfo
let actualBaseContentType = pageInfo.baseContentType
baseContentTypeToResponseTypeToURLCount.updateValueForKey(actualBaseContentType) { responseTypeToURLCount in
var responseTypeToURLCount = responseTypeToURLCount ?? [PageResponseType: UInt]()
responseTypeToURLCount.updateValueForKey(responseType) { count in
return (count ?? 0) + 1
}
return responseTypeToURLCount
}
baseContentTypeToSummedByteCount.updateValueForKey(actualBaseContentType) { summedByteCount in
return (summedByteCount ?? 0) + UInt(pageInfo.byteCount ?? 0)
}
if hasReachedMaximumByteLimitForBaseContentType(actualBaseContentType) {
cancelPendingRequestsForBaseContentType(actualBaseContentType)
}
if JUST_USE_FINAL_URLS {
switch actualBaseContentType {
case .LocalHTMLPage:
requestedLocalPageURLsUnique.insertReturningConformedURLIfNew(finalURL)
case .Image:
requestedImageURLsUnique.insertReturningConformedURLIfNew(finalURL)
case .Feed:
requestedFeedURLsUnique.insertReturningConformedURLIfNew(finalURL)
case .Text:
fallthrough
default:
break
}
}
if let
childDepth = map(currentDepth, { $0 + 1 }),
contentInfo = pageInfo.contentInfo
where childDepth <= maximumDepth
{
let crawl = crawlsFoundURLs && isCrawling
for pageURL in contentInfo.externalPageURLs {
externalURLs.insert(pageURL)
}
for pageURL in contentInfo.localPageURLs {
if JUST_USE_FINAL_URLS {
if crawl {
retrieveInfoForPageWithURL(pageURL, expectedBaseContentType: .LocalHTMLPage, currentDepth: childDepth)
}
}
else if let pageURLPath = pageURL.relativePath where pageURLPath != "" {
if let pageURL = requestedLocalPageURLsUnique.insertReturningConformedURLIfNew(pageURL) {
if crawl {
retrieveInfoForPageWithURL(pageURL, expectedBaseContentType: .LocalHTMLPage, currentDepth: childDepth)
}
}
}
}
for imageURL in contentInfo.imageURLs {
if JUST_USE_FINAL_URLS {
if crawl {
retrieveInfoForPageWithURL(imageURL, expectedBaseContentType: .Image, currentDepth: childDepth)
}
}
else if let imageURL = requestedImageURLsUnique.insertReturningConformedURLIfNew(imageURL) {
if crawl {
retrieveInfoForPageWithURL(imageURL, expectedBaseContentType: .Image, currentDepth: childDepth)
}
}
}
for feedURL in contentInfo.feedURLs {
if JUST_USE_FINAL_URLS {
if crawl {
retrieveInfoForPageWithURL(feedURL, expectedBaseContentType: .Feed, currentDepth: childDepth)
}
}
else if let feedURL = requestedFeedURLsUnique.insertReturningConformedURLIfNew(feedURL) {
if crawl {
retrieveInfoForPageWithURL(feedURL, expectedBaseContentType: .Feed, currentDepth: childDepth)
}
}
}
}
}
self.didUpdateCallback?(pageURL: requestedPageURL)
}
func cancelPendingRequestsForBaseContentType(type: BaseContentType) {
infoRequestQueue.downgradePendingRequestsToNotIncludeContent { request in
return request.expectedBaseContentType == type
}
}
public func pauseCrawling() {
assert(crawlsFoundURLs, "Must have been initialized with crawlsFoundURLs = true")
if !paused {
state = .Paused
}
}
public func resumeCrawling() {
assert(crawlsFoundURLs, "Must have been initialized with crawlsFoundURLs = true")
state = .Crawling
for (pendingURL, baseContentType, currentDepth) in queuedURLsToRequestWhilePaused {
retrieveInfoForPageWithURL(pendingURL, expectedBaseContentType: baseContentType, currentDepth: currentDepth)
}
queuedURLsToRequestWhilePaused.removeAll()
}
public func cancel() {
state = .Idle
didUpdateCallback = nil
infoRequestQueue.cancelAll(clearAll: true)
}
public func summedByteCountForBaseContentType(type: BaseContentType) -> UInt {
return baseContentTypeToSummedByteCount[type] ?? 0
}
public func maximumByteCountForBaseContentType(type: BaseContentType) -> UInt? {
return baseContentTypeToMaximumByteCount[type]
}
public func setMaximumByteCount(maximumByteCount: UInt?, forBaseContentType type: BaseContentType) {
if let maximumByteCount = maximumByteCount {
baseContentTypeToMaximumByteCount[type] = maximumByteCount
}
else {
baseContentTypeToMaximumByteCount.removeValueForKey(type)
}
}
public func hasReachedMaximumByteLimitForBaseContentType(type: BaseContentType) -> Bool {
if let maximumByteCount = maximumByteCountForBaseContentType(type) {
return summedByteCountForBaseContentType(type) >= maximumByteCount
}
else {
return false
}
}
}
| apache-2.0 | 413d6d7f73f9829e9fd0325f1a3ec6ee | 29.410667 | 171 | 0.756577 | 3.925645 | false | false | false | false |
zhaobin19918183/zhaobinCode | ๅคง็ฅไปฃ็ /ManagerExtension/HelperManagerExtension.swift | 1 | 1109 | //
// HelperManagerExtension.swift
// Portal
//
// Created by Kilin on 16/3/29.
// Copyright ยฉ 2016ๅนด Eli Lilly and Company. All rights reserved.
//
import UIKit
extension HelperManager
{
static func getUnzipedAppPathWith(entity : Entity_App) -> String
{
let appNameWithoutExtension = String(entity.applicationCode!)
return PATH_FOLDER_APP + appNameWithoutExtension
}
static func getAppNameWithoutExtensionWith(entity : Entity_App) -> String
{
let appNameWithExtension = self.getAppNameWithExtensionWith(entity)
let seperators = appNameWithExtension.componentsSeparatedByString(".")
let appNameWithoutExtension = seperators.first!
return appNameWithoutExtension
}
static func getAppNameWithExtensionWith(entity : Entity_App) -> String
{
let package : String = entity.applicationPackage!
let sepratedPath : [String] = package.componentsSeparatedByString("/")
let name : String = sepratedPath.last! as String
return name
}
}
| gpl-3.0 | 5f731556f2972a6240a8eaf2e7ac6dd0 | 28.891892 | 91 | 0.663653 | 4.872247 | false | false | false | false |
NemProject/NEMiOSApp | NEMWallet/Application/Transaction/TransactionUnconfirmedTableViewCell.swift | 1 | 3595 | //
// TransactionUnconfirmedTableViewCell.swift
//
// This file is covered by the LICENSE file in the root of this project.
// Copyright (c) 2016 NEM
//
import UIKit
/// The table view cell that represents an unconfirmed multisig transaction.
final class TransactionUnconfirmedTableViewCell: UITableViewCell {
// MARK: - Cell Properties
var transferTransaction: TransferTransaction? {
didSet {
updateCellTransferTransaction()
}
}
var multisigAggregateModificationTransaction: MultisigAggregateModificationTransaction? {
didSet {
updateCellMultisigAggregateModificationTransaction()
}
}
weak var delegate: TransactionUnconfirmedViewController? = nil
// MARK: - Cell Outlets
@IBOutlet weak var senderHeadingLabel: UILabel!
@IBOutlet weak var senderValueLabel: UILabel!
@IBOutlet weak var recipientHeadingLabel: UILabel!
@IBOutlet weak var recipientValueLabel: UILabel!
@IBOutlet weak var messageHeadingLabel: UILabel?
@IBOutlet weak var messageValueLabel: UILabel?
@IBOutlet weak var amountValueLabel: UILabel?
@IBOutlet weak var confirmationButton: UIButton!
@IBOutlet weak var showChangesButton: UIButton?
// MARK: - Cell Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
updateCellAppearance()
}
// MARK: - Cell Helper Methods
/// Updates the table view cell with the provided title.
fileprivate func updateCellTransferTransaction() {
senderValueLabel.text = AccountManager.sharedInstance.generateAddress(forPublicKey: transferTransaction!.signer).accountTitle()
recipientValueLabel.text = transferTransaction!.recipient.accountTitle()
messageValueLabel!.text = transferTransaction!.message?.message ?? String()
amountValueLabel!.text = "\(transferTransaction!.amount / 1000000) XEM"
}
/// Updates the table view cell with the provided title.
fileprivate func updateCellMultisigAggregateModificationTransaction() {
senderValueLabel.text = AccountManager.sharedInstance.generateAddress(forPublicKey: multisigAggregateModificationTransaction!.signer).accountTitle()
recipientValueLabel.text = AccountManager.sharedInstance.generateAddress(forPublicKey: multisigAggregateModificationTransaction!.signer).accountTitle()
}
/// Updates the appearance of the table view cell.
fileprivate func updateCellAppearance() {
senderHeadingLabel.text = "\("FROM".localized()):"
recipientHeadingLabel.text = "\("TO".localized()):"
confirmationButton.setTitle("CONFIRM".localized(), for: UIControlState())
showChangesButton?.setTitle("SHOW_CHANGES".localized(), for: UIControlState())
senderValueLabel.text = ""
recipientValueLabel.text = ""
messageHeadingLabel?.text = "\("MESSAGE".localized()):"
messageValueLabel?.text = ""
amountValueLabel?.text = "0 XEM"
confirmationButton.layer.cornerRadius = 5
showChangesButton?.layer.cornerRadius = 5
layer.cornerRadius = 10
preservesSuperviewLayoutMargins = false
separatorInset = UIEdgeInsets.zero
layoutMargins = UIEdgeInsets.zero
}
@IBAction func confirmTransaction(_ sender: UIButton) {
delegate?.confirmTransaction(atIndex: tag)
}
@IBAction func showChanges(_ sender: UIButton) {
delegate?.showChanges(forTransactionAtIndex: tag)
}
}
| mit | 0fc250a7a183e6fe07c7e7d5c95e48f3 | 36.447917 | 159 | 0.694854 | 5.397898 | false | false | false | false |
hawkfalcon/Clients | Clients/ViewControllers/NewMileageViewController.swift | 1 | 490 | import UIKit
class NewMileageViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet var miles: UITextField!
@IBOutlet var date: UIDatePicker!
var mileage: Double!
var mileageDate: NSDate!
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
var mileAmount = 0.0
if let miles = Double(miles.text!) {
mileAmount = miles
}
mileage = mileAmount
mileageDate = date.date as NSDate
}
}
| mit | 570d438ec19393a3ad46f3d7263fa338 | 24.789474 | 76 | 0.657143 | 4.711538 | false | false | false | false |
kuzmir/kazimir-ios | kazimir-ios/TimeContext.swift | 1 | 1090 | //
// TimeContext.swift
// kazimir-ios
//
// Created by Krzysztof Cieplucha on 14/06/15.
// Copyright (c) 2015 Kazimir. All rights reserved.
//
enum TimeContext: Int {
case Old
case New
}
extension TimeContext {
static func getTimeContextForPlace(place: Place) -> TimeContext {
return place.present.boolValue ? TimeContext.New : TimeContext.Old
}
static func getTimeContextFromSegueIdentifier(segueIdentifier: String) -> TimeContext? {
switch segueIdentifier {
case TimeContext.Old.getSegueIdentifier():
return .Old
case TimeContext.New.getSegueIdentifier():
return .New
default:
return nil
}
}
func getSegueIdentifier() -> String {
return self == .Old ? "pushStreetViewControllerOld" : "pushStreetViewControllerNew"
}
func getImageName() -> String {
return self == .Old ? "button_flip_new" : "button_flip_old"
}
func getOppositeTimeContext() -> TimeContext {
return self == .Old ? .New : .Old
}
}
| apache-2.0 | 77add428b6f7ec15100ca7d1c84d3c77 | 24.348837 | 92 | 0.617431 | 4.176245 | false | false | false | false |
jeevanRao7/Swift_Playgrounds | Swift Playgrounds/Challenges/Famous Color.playground/Contents.swift | 1 | 1250 | /************************
Problem Statement:
Print Most repeated Colors in a given colors array.
************************/
import Foundation
//Input Array of colors
let inputArray = ["green", "red" , "green", "blue", "green", "black", "red", "blue", "blue", "gray", "purple", "white", "green", "red", "yellow", "red", "blue", "green"]
func getTopItemsArray(_ array:[String]) -> [String] {
var topArray = [String]()
var colorDictionary = [String:Int]()
//Step 1 : Form dictionary of items with its count
for color in array {
if let count = colorDictionary[color] {
colorDictionary[color] = count + 1
}
else{
//First time encoured a color, initialize value to '1'
colorDictionary[color] = 1
}
}
//Step 2 : Find the max value in the colors count dictionary
let highest = colorDictionary.values.max()
//Step 3 : Get the 'color' key having 'height' value
for (color, count) in colorDictionary {
if count == highest {
topArray.append(color)
}
}
return topArray
}
//Print array of colors most repeated.
print(getTopItemsArray(inputArray))
| mit | 008d7b60bfa7d5ac14b6d266ac750cca | 23.509804 | 169 | 0.5552 | 4.208754 | false | false | false | false |
cardstream/iOS-SDK | cardstream-ios-sdk/CryptoSwift-0.7.2/Sources/CryptoSwift/PKCS/PBKDF1.swift | 7 | 3289 | //
// PBKDF1.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyลผanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public extension PKCS5 {
/// A key derivation function.
///
/// PBKDF1 is recommended only for compatibility with existing
/// applications since the keys it produces may not be large enough for
/// some applications.
public struct PBKDF1 {
public enum Error: Swift.Error {
case invalidInput
case derivedKeyTooLong
}
public enum Variant {
case md5, sha1
var size: Int {
switch self {
case .md5:
return MD5.digestLength
case .sha1:
return SHA1.digestLength
}
}
fileprivate func calculateHash(_ bytes: Array<UInt8>) -> Array<UInt8>? {
switch self {
case .sha1:
return Digest.sha1(bytes)
case .md5:
return Digest.md5(bytes)
}
}
}
private let iterations: Int // c
private let variant: Variant
private let keyLength: Int
private let t1: Array<UInt8>
/// - parameters:
/// - salt: salt, an eight-bytes
/// - variant: hash variant
/// - iterations: iteration count, a positive integer
/// - keyLength: intended length of derived key
public init(password: Array<UInt8>, salt: Array<UInt8>, variant: Variant = .sha1, iterations: Int = 4096 /* c */, keyLength: Int? = nil /* dkLen */ ) throws {
precondition(iterations > 0)
precondition(salt.count == 8)
let keyLength = keyLength ?? variant.size
if keyLength > variant.size {
throw Error.derivedKeyTooLong
}
guard let t1 = variant.calculateHash(password + salt) else {
throw Error.invalidInput
}
self.iterations = iterations
self.variant = variant
self.keyLength = keyLength
self.t1 = t1
}
/// Apply the underlying hash function Hash for c iterations
public func calculate() -> Array<UInt8> {
var t = t1
for _ in 2...iterations {
t = variant.calculateHash(t)!
}
return Array(t[0..<self.keyLength])
}
}
}
| gpl-3.0 | d334200c2e608f377dba9b398484df04 | 34.73913 | 217 | 0.582421 | 4.849558 | false | false | false | false |
ontouchstart/swift3-playground | Drawing Sounds.playgroundbook/Contents/Sources/SpeechTweak.swift | 1 | 2257 | //
// SpeechTweak.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import AVFoundation
/**
An enum of different tweaks that can be applied to an instrument.
These can be pitch, speed, and volume.
*/
public enum SpeechTweakType {
case pitch, speed, volume
// The range that the particular tweak modifier can be between.
private var tweakRange: ClosedRange<Float> {
switch self {
case .pitch:
return 0.5 ... 2.0
case .speed:
return 0.1 ... 2.0
case .volume:
return 0.0 ... 1.0
}
}
}
/// This class provides effects to tweak how the speech sounds.
public struct SpeechTweak {
var type: SpeechTweakType
private var valueRange: ClosedRange<Int>
/// Create an speech tweak whose effect varies by the values (from 0 to 100). Depending on where you tap on the keyboard it will apply a different value within the range.
public init(type: SpeechTweakType, effectFrom startValue: Int, to endValue: Int) {
self.type = type
let firstValue = startValue.clamped(to: Constants.userValueRange)
let secondValue = endValue.clamped(to: Constants.userValueRange)
if firstValue < secondValue {
self.valueRange = firstValue...secondValue
} else {
self.valueRange = secondValue...firstValue
}
}
// When passed in a normalized value between 0 to 1, places it within the user's specified valueRange and then converts that to the actual value for the underlying speech tweak.
func tweakValue(fromNormalizedValue normalizedValue: CGFloat) -> Float {
let valueRangeCount = CGFloat(valueRange.count)
let normalizedValueInDefinedRange = ((normalizedValue * valueRangeCount) + CGFloat(valueRange.lowerBound)) / CGFloat(Constants.userValueRange.count)
return SpeechTweak.tweak(normalizedValue: normalizedValueInDefinedRange, forType: type)
}
static func tweak(normalizedValue: CGFloat, forType type: SpeechTweakType) -> Float {
let tweakRange = type.tweakRange
return (Float(normalizedValue) * (tweakRange.upperBound - tweakRange.lowerBound)) + tweakRange.lowerBound
}
}
| mit | 0aa7fb8d045597f265ee649728781639 | 35.403226 | 181 | 0.673903 | 4.606122 | false | false | false | false |
ejensen/cleartext-mac | Simpler/SimplerTextStorage.swift | 1 | 5025 | //
// SimpleTextStorage.swift
// Simpler
//
// Created by Morten Just Petersen on 11/29/15.
// Copyright ยฉ 2015 Morten Just Petersen. All rights reserved.
//
import Cocoa
protocol SimplerTextStorageDelegate {
func simplerTextStorageGotComplexWord()
func simplerTextStorageGotComplexWordAtRange(range:NSRange)
func simplerTextStorageShouldChangeAtts(atts:[String:AnyObject])
}
class SimplerTextStorage: NSTextStorage {
var backingStore = NSMutableAttributedString()
let checker = SimpleWords()
var simpleDelegate : SimplerTextStorageDelegate?
// var layoutManager : NSLayoutManager!
override var string: String {
return backingStore.string
}
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init?(pasteboardPropertyList propertyList: AnyObject, ofType type: String) {
fatalError("init(pasteboardPropertyList:ofType:) has not been implemented")
}
func selectionDidChange(range:NSRange){
// print("storage:selectionddichange")
}
override func processEditing() {
super.processEditing()
if editedRange.length > 0 && editedRange.location < backingStore.string.characters.count {
let token = tokenAtIndex(editedRange.location, inString: backingStore.string)
let word = NSString(string: backingStore.string).substringWithRange(token.range)
if (token.token == NSLinguisticTagWhitespace // check on spaces
|| token.token == NSLinguisticTagPunctuation) // check on punctuation like , and .
&& !word.characters.contains("'") { // but not on ' like in it's and don't
performReplacementsForRange(token.range)
}
}
}
func performReplacementsForRange(changedRange: NSRange) {
let index = changedRange.location-1
if index>=0 {
if let wordRange = wordRangeAtIndex(index, inString: string) {
lookForBadWords(wordRange)
}
}
}
func substringForRange(range:NSRange) -> String {
// print("storagee:substinrgforfrange")
return String(NSString(string: self.string).substringWithRange(range))
}
func lookForBadWords(range:NSRange){
let word = NSString(string: string).substringWithRange(range)
if word.characters.count == 0 { return }
// let timer = ParkBenchTimer()
if self.checker.isSimpleWord(word) { // could have sworn these should be the other way around. But actual response is king.
// processGoodWord(word, atRange: range)
} else {
processBadWord(word, atRange: range)
}
}
func processBadWord(word:String, atRange range:NSRange){
simpleDelegate?.simplerTextStorageGotComplexWord()
simpleDelegate?.simplerTextStorageGotComplexWordAtRange(range)
}
func processGoodWord(word:String, atRange range:NSRange){
}
override func attributesAtIndex(location: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject] {
return backingStore.attributesAtIndex(location, effectiveRange: range)
}
override func replaceCharactersInRange(range: NSRange, withString str: String) {
beginEditing()
backingStore.replaceCharactersInRange(range, withString: str)
edited(.EditedCharacters, range: range, changeInLength: (str as NSString).length - range.length)
endEditing()
}
override func setAttributes(attrs: [String : AnyObject]?, range: NSRange) {
beginEditing()
backingStore.setAttributes(attrs, range: range)
edited(.EditedAttributes, range: range, changeInLength: 0)
endEditing()
}
func tokenAtIndex(index:Int, inString str:NSString) -> (range:NSRange, token:String) {
let tokenType = NSLinguisticTagSchemeTokenType
let tagger = NSLinguisticTagger(tagSchemes: [tokenType], options: 0)
var r : NSRange = NSMakeRange(0, 0)
tagger.string = str as String
let tag = tagger.tagAtIndex(index, scheme: tokenType, tokenRange: &r, sentenceRange: nil)
return(range:r, token:tag!)
}
func wordRangeAtIndex(index:Int, inString str:NSString) -> NSRange? {
let options = (NSLinguisticTaggerOptions.OmitWhitespace.rawValue)
let tagger = NSLinguisticTagger(tagSchemes: [NSLinguisticTagSchemeTokenType],
options: Int(options))
var r : NSRange = NSMakeRange(0,0)
tagger.string = str as String
let tag = tagger.tagAtIndex(index, scheme: NSLinguisticTagSchemeTokenType, tokenRange: &r, sentenceRange: nil)
if tag == NSLinguisticTagWord {
return r
} else
{
return nil
}
}
}
| gpl-3.0 | 59d100c0fc3ec6682faf017c1d4b832a | 34.380282 | 131 | 0.646099 | 4.854106 | false | false | false | false |
carabina/Reachability.swift | Reachability.swift | 3 | 13460 | /*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import SystemConfiguration
import Foundation
public let ReachabilityChangedNotification = "ReachabilityChangedNotification"
public class Reachability: NSObject, Printable {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUnreachable = (Reachability) -> ()
public enum NetworkStatus: Printable {
case NotReachable, ReachableViaWiFi, ReachableViaWWAN
public var description: String {
switch self {
case .ReachableViaWWAN:
return "Cellular"
case .ReachableViaWiFi:
return "WiFi"
case .NotReachable:
return "No Connection"
}
}
}
// MARK: - *** Public properties ***
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
public var reachableOnWWAN: Bool
public var notificationCenter = NSNotificationCenter.defaultCenter()
public var currentReachabilityStatus: NetworkStatus {
if isReachable() {
if isReachableViaWiFi() {
return .ReachableViaWiFi
}
if isRunningOnDevice {
return .ReachableViaWWAN
}
}
return .NotReachable
}
public var currentReachabilityString: String {
return "\(currentReachabilityStatus)"
}
// MARK: - *** Initialisation methods ***
public required init(reachabilityRef: SCNetworkReachability) {
reachableOnWWAN = true
self.reachabilityRef = reachabilityRef
}
public convenience init(hostname: String) {
let ref = SCNetworkReachabilityCreateWithName(nil, (hostname as NSString).UTF8String).takeRetainedValue()
self.init(reachabilityRef: ref)
}
public class func reachabilityForInternetConnection() -> Reachability {
var zeroAddress = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let ref = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0)).takeRetainedValue()
}
return Reachability(reachabilityRef: ref)
}
public class func reachabilityForLocalWiFi() -> Reachability {
var localWifiAddress: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
localWifiAddress.sin_len = UInt8(sizeofValue(localWifiAddress))
localWifiAddress.sin_family = sa_family_t(AF_INET)
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
let address: Int64 = 0xA9FE0000
localWifiAddress.sin_addr.s_addr = in_addr_t(address.bigEndian)
let ref = withUnsafePointer(&localWifiAddress) {
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0)).takeRetainedValue()
}
return Reachability(reachabilityRef: ref)
}
// MARK: - *** Notifier methods ***
public func startNotifier() -> Bool {
reachabilityObject = self
let reachability = self.reachabilityRef!
previousReachabilityFlags = reachabilityFlags
if let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timer_queue) {
dispatch_source_set_timer(timer, dispatch_walltime(nil, 0), 500 * NSEC_PER_MSEC, 100 * NSEC_PER_MSEC)
dispatch_source_set_event_handler(timer, { [unowned self] in
self.timerFired()
})
dispatch_timer = timer
dispatch_resume(timer)
return true
} else {
return false
}
}
public func stopNotifier() {
reachabilityObject = nil
if let timer = dispatch_timer {
dispatch_source_cancel(timer)
dispatch_timer = nil
}
}
// MARK: - *** Connection test methods ***
public func isReachable() -> Bool {
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
return self.isReachableWithFlags(flags)
})
}
public func isReachableViaWWAN() -> Bool {
if isRunningOnDevice {
return isReachableWithTest() { flags -> Bool in
// Check we're REACHABLE
if self.isReachable(flags) {
// Now, check we're on WWAN
if self.isOnWWAN(flags) {
return true
}
}
return false
}
}
return false
}
public func isReachableViaWiFi() -> Bool {
return isReachableWithTest() { flags -> Bool in
// Check we're reachable
if self.isReachable(flags) {
if self.isRunningOnDevice {
// Check we're NOT on WWAN
if self.isOnWWAN(flags) {
return false
}
}
return true
}
return false
}
}
// MARK: - *** Private methods ***
private var isRunningOnDevice: Bool = {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return false
#else
return true
#endif
}()
private var reachabilityRef: SCNetworkReachability?
private var reachabilityObject: AnyObject?
private var dispatch_timer: dispatch_source_t?
private lazy var timer_queue: dispatch_queue_t = {
return dispatch_queue_create("uk.co.joylordsystems.reachability_timer_queue", nil)
}()
private var previousReachabilityFlags: SCNetworkReachabilityFlags?
func timerFired() {
let currentReachabilityFlags = reachabilityFlags
if let _previousReachabilityFlags = previousReachabilityFlags {
if currentReachabilityFlags != previousReachabilityFlags {
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
self.reachabilityChanged(currentReachabilityFlags)
self.previousReachabilityFlags = currentReachabilityFlags
})
}
}
}
private func reachabilityChanged(flags: SCNetworkReachabilityFlags) {
if isReachableWithFlags(flags) {
if let block = whenReachable {
block(self)
}
} else {
if let block = whenUnreachable {
block(self)
}
}
notificationCenter.postNotificationName(ReachabilityChangedNotification, object:self)
}
private func isReachableWithFlags(flags: SCNetworkReachabilityFlags) -> Bool {
let reachable = isReachable(flags)
if !reachable {
return false
}
if isConnectionRequiredOrTransient(flags) {
return false
}
if isRunningOnDevice {
if isOnWWAN(flags) && !reachableOnWWAN {
// We don't want to connect when on 3G.
return false
}
}
return true
}
private func isReachableWithTest(test: (SCNetworkReachabilityFlags) -> (Bool)) -> Bool {
var flags: SCNetworkReachabilityFlags = 0
let gotFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &flags) != 0
if gotFlags {
return test(flags)
}
return false
}
// WWAN may be available, but not active until a connection has been established.
// WiFi may require a connection for VPN on Demand.
private func isConnectionRequired() -> Bool {
return connectionRequired()
}
private func connectionRequired() -> Bool {
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
return self.isConnectionRequired(flags)
})
}
// Dynamic, on demand connection?
private func isConnectionOnDemand() -> Bool {
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
return self.isConnectionRequired(flags) && self.isConnectionOnTrafficOrDemand(flags)
})
}
// Is user intervention required?
private func isInterventionRequired() -> Bool {
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
return self.isConnectionRequired(flags) && self.isInterventionRequired(flags)
})
}
private func isOnWWAN(flags: SCNetworkReachabilityFlags) -> Bool {
#if os(iOS)
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsWWAN) != 0
#else
return false
#endif
}
private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool {
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable) != 0
}
private func isConnectionRequired(flags: SCNetworkReachabilityFlags) -> Bool {
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired) != 0
}
private func isInterventionRequired(flags: SCNetworkReachabilityFlags) -> Bool {
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsInterventionRequired) != 0
}
private func isConnectionOnTraffic(flags: SCNetworkReachabilityFlags) -> Bool {
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
}
private func isConnectionOnDemand(flags: SCNetworkReachabilityFlags) -> Bool {
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnDemand) != 0
}
func isConnectionOnTrafficOrDemand(flags: SCNetworkReachabilityFlags) -> Bool {
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic | kSCNetworkReachabilityFlagsConnectionOnDemand) != 0
}
private func isTransientConnection(flags: SCNetworkReachabilityFlags) -> Bool {
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsTransientConnection) != 0
}
private func isLocalAddress(flags: SCNetworkReachabilityFlags) -> Bool {
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsLocalAddress) != 0
}
private func isDirect(flags: SCNetworkReachabilityFlags) -> Bool {
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsDirect) != 0
}
private func isConnectionRequiredOrTransient(flags: SCNetworkReachabilityFlags) -> Bool {
let testcase = SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired | kSCNetworkReachabilityFlagsTransientConnection)
return flags & testcase == testcase
}
private var reachabilityFlags: SCNetworkReachabilityFlags {
var flags: SCNetworkReachabilityFlags = 0
let gotFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &flags) != 0
if gotFlags {
return flags
}
return 0
}
override public var description: String {
var W: String
if isRunningOnDevice {
W = isOnWWAN(reachabilityFlags) ? "W" : "-"
} else {
W = "X"
}
let R = isReachable(reachabilityFlags) ? "R" : "-"
let c = isConnectionRequired(reachabilityFlags) ? "c" : "-"
let t = isTransientConnection(reachabilityFlags) ? "t" : "-"
let i = isInterventionRequired(reachabilityFlags) ? "i" : "-"
let C = isConnectionOnTraffic(reachabilityFlags) ? "C" : "-"
let D = isConnectionOnDemand(reachabilityFlags) ? "D" : "-"
let l = isLocalAddress(reachabilityFlags) ? "l" : "-"
let d = isDirect(reachabilityFlags) ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
deinit {
stopNotifier()
reachabilityRef = nil
whenReachable = nil
whenUnreachable = nil
}
}
| bsd-2-clause | 67a9ea72d6e417509ea5d7153c82cd52 | 35.085791 | 196 | 0.646434 | 5.518655 | false | false | false | false |
jkereako/MosaicLayout2 | MosaicLayout/MosaicLayout/MosaicLayout.swift | 1 | 15809 | //
// MosaicLayout.swift
// MosaicLayout
//
// Created by Jeff Kereakoglow on 10/11/15.
// Copyright ยฉ 2015 Alexis Digital. All rights reserved.
//
import UIKit
protocol MosaicLayoutDelegate: UICollectionViewDelegate {
func blockSize(
collectionView collectionView: UICollectionView, layout: UICollectionViewLayout, indexPath: NSIndexPath
) -> CGSize
func edgeInsets(
collectionView collectionView: UICollectionView, layout: UICollectionViewLayout, indexPath: NSIndexPath
) -> UIEdgeInsets
}
class MosaicLayout: UICollectionViewLayout {
weak var delegate: MosaicLayoutDelegate?
let scrollDirection: UICollectionViewScrollDirection
var blockPixels: CGSize
private var furthestBlockPoint: CGPoint
private var prelayoutEverything: Bool
// previous layout cache.
// this is to prevent choppiness when we scroll to the bottom of the screen - uicollectionview
// will repeatedly call layoutattributesforelementinrect on each scroll event. pow!
private var previousLayoutRect: CGRect
private var previousLayoutAttributes: Array<UICollectionViewLayoutAttributes>
// remember the last indexpath placed, as to not
// relayout the same indexpaths while scrolling
private var lastIndexPathPlaced: NSIndexPath?
private var firstOpenSpace: CGPoint
private var indexPathByPosition: Array<Array<NSIndexPath>>
private var positionByIndexPath: Array<Array<NSValue>>
override init() {
scrollDirection = .Vertical
blockPixels = CGSizeMake(100.0, 100.0)
furthestBlockPoint = CGPointMake(0, 0)
previousLayoutRect = CGRectMake(0.0, 0.0, 0.0, 0.0)
delegate = nil
previousLayoutRect = CGRectZero
prelayoutEverything = false
firstOpenSpace = CGPointZero
previousLayoutAttributes = Array<UICollectionViewLayoutAttributes>()
indexPathByPosition = Array<Array<NSIndexPath>>()
positionByIndexPath = Array<Array<NSValue>>()
super.init()
}
required init?(coder aDecoder: NSCoder) {
scrollDirection = .Vertical
blockPixels = CGSizeMake(100.0, 100.0)
furthestBlockPoint = CGPointMake(0, 0)
previousLayoutRect = CGRectMake(0.0, 0.0, 0.0, 0.0)
previousLayoutRect = CGRectZero
firstOpenSpace = CGPointZero
previousLayoutAttributes = Array<UICollectionViewLayoutAttributes>()
delegate = nil
indexPathByPosition = Array<Array<NSIndexPath>>()
positionByIndexPath = Array<Array<NSValue>>()
prelayoutEverything = false
super.init(coder: aDecoder)
}
private func initialize() {
}
// MARK:- UICollectionViewLayout
override func prepareLayout() {
super.prepareLayout()
guard delegate != nil, let cv = collectionView else {
return
}
let scrollFrame = CGRectMake(
cv.contentOffset.x, cv.contentOffset.y, cv.frame.size.width, cv.frame.size.height
)
let unrestrictedRow: Int
switch scrollDirection {
case .Vertical:
unrestrictedRow = Int((CGRectGetMaxY(scrollFrame) / blockPixels.height) + 1.0)
case .Horizontal:
unrestrictedRow = Int((CGRectGetMaxX(scrollFrame) / blockPixels.width) + 1.0)
}
fillInBlocks(endRow: unrestrictedRow)
}
override func prepareForCollectionViewUpdates(updateItems: [UICollectionViewUpdateItem]) {
super.prepareForCollectionViewUpdates(updateItems)
for item in updateItems {
switch item.updateAction {
case .Insert, .Move:
fillInBlocks(indexPath: item.indexPathAfterUpdate)
default:
break
}
}
}
override func collectionViewContentSize() -> CGSize {
guard let cv = collectionView else {
fatalError("Collection view is not accessible.")
}
let contentRect = UIEdgeInsetsInsetRect(cv.frame, cv.contentInset)
switch scrollDirection {
case .Vertical:
return CGSizeMake(
CGRectGetWidth(contentRect), (furthestBlockPoint.y + 1) * blockPixels.height
)
case .Horizontal:
return CGSizeMake(
(furthestBlockPoint.x + 1) * blockPixels.width, CGRectGetHeight(contentRect)
)
}
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
var insets = UIEdgeInsetsZero
if let cv = collectionView, d = delegate {
insets = d.edgeInsets(collectionView: cv, layout: self, indexPath: indexPath)
}
let frame = frameForIndexPath(indexPath)
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.frame = UIEdgeInsetsInsetRect(frame, insets)
return attributes
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard delegate != nil else {
return []
}
if CGRectEqualToRect(rect, previousLayoutRect) {
return previousLayoutAttributes
}
previousLayoutRect = rect
let unrestrictedDimensionStart: CGFloat
let unrestrictedDimensionLength: CGFloat
switch scrollDirection {
case .Vertical:
unrestrictedDimensionStart = rect.origin.y / blockPixels.height
unrestrictedDimensionLength = rect.size.height / self.blockPixels.height
case .Horizontal:
unrestrictedDimensionStart = rect.origin.x / self.blockPixels.width
unrestrictedDimensionLength = (rect.size.width / self.blockPixels.width) + 1.0
}
let unrestrictedDimensionEnd = Int(unrestrictedDimensionStart + unrestrictedDimensionLength)
fillInBlocks(endRow: unrestrictedDimensionEnd)
var attributes = Set<UICollectionViewLayoutAttributes>()
traverseTilesBetweenUnrestrictedDimension(
start: Int(unrestrictedDimensionStart),
end: Int(unrestrictedDimensionEnd),
callback: { [unowned self] (let point: CGPoint) in
if let ip = self.indexPathForPosition(point: point),
let attr = self.layoutAttributesForItemAtIndexPath(ip){
attributes.insert(attr)
}
return true
}
)
previousLayoutAttributes = Array(attributes)
return previousLayoutAttributes
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return !(CGSizeEqualToSize(newBounds.size, collectionView?.frame.size ?? CGSizeZero))
}
override func invalidateLayout() {
super.invalidateLayout()
furthestBlockPoint = CGPointZero
firstOpenSpace = CGPointZero
previousLayoutRect = CGRectZero
previousLayoutAttributes = Array<UICollectionViewLayoutAttributes>()
lastIndexPathPlaced = nil
// REVIEW
indexPathByPosition = Array<Array<NSIndexPath>>()
positionByIndexPath = Array<Array<NSValue>>()
}
// MARK:- Helpers
func indexPathForPosition(point point: CGPoint) -> NSIndexPath? {
let unrestrictedPoint: Int
let restrictedPoint: Int
switch scrollDirection {
case .Vertical:
unrestrictedPoint = Int(point.y)
restrictedPoint = Int(point.x)
case .Horizontal:
unrestrictedPoint = Int(point.x)
restrictedPoint = Int(point.y)
}
// REVIEW: Infinite loop
guard indexPathByPosition.indices ~= restrictedPoint &&
indexPathByPosition[restrictedPoint].indices ~= unrestrictedPoint else {
return nil
}
return indexPathByPosition[restrictedPoint][unrestrictedPoint]
}
func fillInBlocks(indexPath indexPath: NSIndexPath) {
// we'll have our data structure as if we're planning
// a vertical layout, then when we assign positions to
// the items we'll invert the axis
let sections = collectionView?.numberOfSections() ?? 0
for var section = lastIndexPathPlaced?.section ?? 0; section < sections; ++section {
let rows = collectionView?.numberOfItemsInSection(section)
let row = lastIndexPathPlaced?.row ?? 0
for var aRow = row + 1; row < rows; ++aRow {
guard section < indexPath.section && aRow < indexPath.row else {
return
}
let newIndexPath = NSIndexPath(forRow: aRow, inSection: section)
if placeBlock(indexPath: newIndexPath) {
lastIndexPathPlaced = newIndexPath
}
}
}
}
private func frameForIndexPath(indexPath: NSIndexPath) -> CGRect {
let position = positionForIndexPath(indexPath)
let elementSize = blockSize(indexPath: indexPath)
let contentRect = UIEdgeInsetsInsetRect(
collectionView?.frame ?? CGRectZero, collectionView?.contentInset ?? UIEdgeInsetsZero
)
let dimensions = CGFloat(restrictedDimensionBlockSize())
switch scrollDirection {
case .Vertical:
let initialPaddingForContraintedDimension = (CGRectGetWidth(contentRect) - dimensions * blockPixels.width) / 2
return CGRectMake(position.x * blockPixels.width + initialPaddingForContraintedDimension,
position.y * blockPixels.height,
elementSize.width * blockPixels.width,
elementSize.height * blockPixels.height);
case .Horizontal:
let initialPaddingForContraintedDimension = (CGRectGetHeight(contentRect) - dimensions * blockPixels.height) / 2
return CGRectMake(position.x * blockPixels.width,
position.y * blockPixels.height + initialPaddingForContraintedDimension,
elementSize.width * blockPixels.width,
elementSize.height * blockPixels.height);
}
}
private func fillInBlocks(endRow endRow: Int) {
let sectionCount = collectionView?.numberOfSections() ?? 0
for var section = lastIndexPathPlaced?.section ?? 0; section < sectionCount; ++section {
let rowCount = collectionView?.numberOfItemsInSection(section)
let initialValue: Int
if let ip = lastIndexPathPlaced {
initialValue = ip.row + 1
}
else {
initialValue = 0
}
for var row = initialValue; row < rowCount; ++row {
let indexPath = NSIndexPath(forRow: row, inSection: section)
if placeBlock(indexPath: indexPath) == true {
lastIndexPathPlaced = indexPath
}
let coordinate: Int
switch scrollDirection {
case .Vertical:
coordinate = Int(firstOpenSpace.y)
case .Horizontal:
coordinate = Int(firstOpenSpace.x)
}
guard coordinate < endRow else {
return
}
}
}
}
func placeBlock(indexPath indexPath: NSIndexPath) -> Bool {
let ablockSize = blockSize(indexPath: indexPath)
return !traverseOpenTiles(callback: { [unowned self] (let blockOrigin: CGPoint) in
// we need to make sure each square in the desired
// area is available before we can place the square
let traversedAllBlocks = self.traverseTiles(
point: blockOrigin, size: ablockSize, iterator: {[unowned self] (let point: CGPoint) in
let coordinate: CGFloat
let maximumRestrictedBoundSize: Bool
switch self.scrollDirection {
case .Vertical:
coordinate = point.x
maximumRestrictedBoundSize = blockOrigin.x == 0
case .Horizontal:
coordinate = point.y
maximumRestrictedBoundSize = blockOrigin.y == 0
}
let spaceAvailable: Bool = self.indexPathForPosition(point: point) != nil ? true : false
let inBounds = Int(coordinate) < self.restrictedDimensionBlockSize()
if spaceAvailable && maximumRestrictedBoundSize && !inBounds {
print("layout not enough")
return true
}
return spaceAvailable && inBounds
}
)
if !traversedAllBlocks { return true }
self.setIndexPath(indexPath, forPoint: blockOrigin)
self.traverseTiles(point: blockOrigin, size: ablockSize, iterator: {[unowned self] (let aPoint: CGPoint) in
self.setPosition(aPoint, forIndexPath: indexPath)
self.furthestBlockPoint = aPoint
return true
}
)
return false
}
)
}
func blockSize(indexPath indexPath: NSIndexPath) -> CGSize {
let blockSize = CGSizeMake(1.0, 1.0)
if let result = delegate?.blockSize(collectionView: collectionView!, layout: self, indexPath: indexPath) {
return result
}
return blockSize
}
func traverseTilesBetweenUnrestrictedDimension(
start start: Int, end: Int, callback: (point: CGPoint) -> Bool
) -> Bool {
for var unrestrictedDimension = start; unrestrictedDimension < end; ++unrestrictedDimension {
for var restrictedDimension = 0; restrictedDimension < restrictedDimensionBlockSize(); ++restrictedDimension {
let point: CGPoint
switch scrollDirection {
case .Vertical:
point = CGPointMake(CGFloat(restrictedDimension), CGFloat(unrestrictedDimension))
case .Horizontal:
point = CGPointMake(CGFloat(unrestrictedDimension), CGFloat(restrictedDimension))
}
guard callback(point: point) else {
return false
}
}
}
return true
}
func traverseOpenTiles(callback callback: (point: CGPoint) -> Bool) -> Bool {
var allTakenBefore = true
let initialValue: CGFloat
switch scrollDirection {
case .Vertical:
initialValue = firstOpenSpace.y
case .Horizontal:
initialValue = firstOpenSpace.x
}
for var unrestrictedDimension = initialValue;; ++unrestrictedDimension {
let limit = restrictedDimensionBlockSize()
for var restrictedDimension = 0; restrictedDimension < limit; ++restrictedDimension {
let point: CGPoint
switch scrollDirection {
case .Vertical:
point = CGPointMake(CGFloat(restrictedDimension), unrestrictedDimension)
case .Horizontal:
point = CGPointMake(unrestrictedDimension, CGFloat(restrictedDimension))
}
guard indexPathForPosition(point: point) == nil else {
continue
}
if allTakenBefore {
firstOpenSpace = point
allTakenBefore = false
}
if callback(point: point) == false {
return false
}
}
}
}
func positionForIndexPath(indexPath: NSIndexPath) -> CGPoint {
if indexPath.section >= positionByIndexPath.count ||
indexPath.row >= positionByIndexPath[indexPath.section].count {
fillInBlocks(indexPath: indexPath)
}
let value = positionByIndexPath[indexPath.section][indexPath.row]
return value.CGPointValue()
}
func traverseTiles(
point point: CGPoint, size: CGSize, iterator:(point: CGPoint) -> Bool
) -> Bool {
for var column = point.x; column < point.x + size.width; ++column {
for var row = point.y; row < point.y + size.height; ++row {
if iterator(point: CGPointMake(column, row)) == false {
return false
}
}
}
return true
}
func setPosition(point: CGPoint, forIndexPath indexPath: NSIndexPath) {
let unrestrictedPoint: Int
let restrictedPoint: Int
switch scrollDirection {
case .Vertical:
unrestrictedPoint = Int(point.y)
restrictedPoint = Int(point.x)
case .Horizontal:
unrestrictedPoint = Int(point.x)
restrictedPoint = Int(point.y)
}
indexPathByPosition[restrictedPoint][unrestrictedPoint] = indexPath
}
func setIndexPath(indexPath: NSIndexPath, forPoint point: CGPoint) {
positionByIndexPath[indexPath.section][indexPath.row] = NSValue(CGPoint: point)
}
func restrictedDimensionBlockSize() -> Int {
let size: CGFloat
let contentRect = UIEdgeInsetsInsetRect(collectionView!.frame, collectionView!.contentInset)
switch scrollDirection {
case .Vertical:
size = CGRectGetWidth(contentRect) / blockPixels.width
case .Horizontal:
size = CGRectGetHeight(contentRect) / blockPixels.height
}
guard size > 0 else {
return 1
}
return Int(round(size))
}
}
| mit | e918cafeb3ebd71595fb8be6556fd66f | 29.875 | 119 | 0.686867 | 5.177858 | false | false | false | false |
julienbodet/wikipedia-ios | scripts/localization.swift | 1 | 23140 | import Foundation
fileprivate var dictionaryRegex: NSRegularExpression? = {
do {
return try NSRegularExpression(pattern: "(?:[{][{])(:?[^{]*)(?:[}][}])", options: [])
} catch {
assertionFailure("Localization regex failed to compile")
}
return nil
}()
fileprivate var curlyBraceRegex: NSRegularExpression? = {
do {
return try NSRegularExpression(pattern: "(?:[{][{][a-z]+:)(:?[^{]*)(?:[}][}])", options: [.caseInsensitive])
} catch {
assertionFailure("Localization regex failed to compile")
}
return nil
}()
fileprivate var twnTokenRegex: NSRegularExpression? = {
do {
return try NSRegularExpression(pattern: "(?:[$])(:?[0-9]+)", options: [])
} catch {
assertionFailure("Localization token regex failed to compile")
}
return nil
}()
fileprivate var iOSTokenRegex: NSRegularExpression? = {
do {
return try NSRegularExpression(pattern: "(?:[%])(:?[0-9]+)(?:[$])(:?[@dDuUxXoOfeEgGcCsSpaAF])", options: [])
} catch {
assertionFailure("Localization token regex failed to compile")
}
return nil
}()
fileprivate var mwLocalizedStringRegex: NSRegularExpression? = {
do {
return try NSRegularExpression(pattern: "(?:WMLocalizedString\\(@\\\")(:?[^\"]+)(?:[^\\)]*\\))", options: [])
} catch {
assertionFailure("mwLocalizedStringRegex failed to compile")
}
return nil
}()
fileprivate var countPrefixRegex: NSRegularExpression? = {
do {
return try NSRegularExpression(pattern: "(:?^[0-9]+)(?:=)", options: [])
} catch {
assertionFailure("countPrefixRegex failed to compile")
}
return nil
}()
let keysByPrefix = ["0":"zero", "1":"one", "2":"two", "3":"few"]
extension String {
var fullRange: NSRange {
return NSRange(location: 0, length: (self as NSString).length)
}
var escapedString: String {
return self.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "\n", with: "\\n")
}
func pluralDictionary(with keys: [String], tokens: [String: String]) -> NSDictionary? {
//https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPInternational/StringsdictFileFormat/StringsdictFileFormat.html#//apple_ref/doc/uid/10000171i-CH16-SW1
guard let dictionaryRegex = dictionaryRegex else {
return nil
}
var remainingKeys = keys
let fullRange = self.fullRange
let mutableDictionary = NSMutableDictionary(capacity: 5)
let results = dictionaryRegex.matches(in: self, options: [], range: fullRange)
guard results.count == 1 else {
// we only support strings with a single plural
return nil
}
guard let result = results.first else {
return nil
}
let contents = dictionaryRegex.replacementString(for: result, in: self, offset: 0, template: "$1")
let components = contents.components(separatedBy: "|")
let countOfComponents = components.count
guard countOfComponents > 1 else {
return nil
}
let firstComponent = components[0]
guard firstComponent.hasPrefix("PLURAL:") else {
return nil
}
let token = firstComponent.suffix(from: firstComponent.index(firstComponent.startIndex, offsetBy: 7))
guard (token as NSString).length == 2 else {
return nil
}
let range = result.range
let nsSelf = self as NSString
let keyDictionary = NSMutableDictionary(capacity: 5)
let formatValueType = tokens["1"] ?? "d"
keyDictionary["NSStringFormatSpecTypeKey"] = "NSStringPluralRuleType"
keyDictionary["NSStringFormatValueTypeKey"] = formatValueType
guard let countPrefixRegex = countPrefixRegex else {
abort()
}
var unlabeledComponents: [String] = []
for component in components[1..<countOfComponents] {
var keyForComponent: String?
var actualComponent: String? = component
guard let match = countPrefixRegex.firstMatch(in: component, options: [], range: component.fullRange) else {
unlabeledComponents.append(component)
continue
}
// Support for 0= 1= 2=
let numberString = countPrefixRegex.replacementString(for: match, in: component, offset: 0, template: "$1")
if let key = keysByPrefix[numberString] {
keyForComponent = key
remainingKeys = remainingKeys.filter({ (aKey) -> Bool in
return key != aKey
})
actualComponent = String(component.suffix(from: component.index(component.startIndex, offsetBy: match.range.length)))
} else {
print("Unsupported prefix. Ignoring \(String(describing: component))")
}
guard let keyToInsert = keyForComponent, let componentToInsert = actualComponent else {
continue
}
keyDictionary[keyToInsert] = nsSelf.replacingCharacters(in:range, with: componentToInsert).iOSNativeLocalization(tokens: tokens)
}
guard let other = unlabeledComponents.last else {
print("missing base translation for \(keys) \(tokens)")
abort()
}
keyDictionary["other"] = nsSelf.replacingCharacters(in:range, with: other).iOSNativeLocalization(tokens: tokens)
var keyIndex = 0
for component in unlabeledComponents[0..<(unlabeledComponents.count - 1)] {
guard keyIndex < remainingKeys.count else {
break
}
keyDictionary[remainingKeys[keyIndex]] = nsSelf.replacingCharacters(in:range, with: component).iOSNativeLocalization(tokens: tokens)
keyIndex += 1
}
let key = "v0"
mutableDictionary[key] = keyDictionary
let replacement = "%#@\(key)@"
mutableDictionary["NSStringLocalizedFormatKey"] = replacement
return mutableDictionary
}
public func replacingMatches(fromRegex regex: NSRegularExpression, withFormat format: String) -> String {
let nativeLocalization = NSMutableString(string: self)
var offset = 0
let fullRange = NSRange(location: 0, length: nativeLocalization.length)
regex.enumerateMatches(in: self, options: [], range: fullRange) { (result, flags, stop) in
guard let result = result else {
return
}
let token = regex.replacementString(for: result, in: nativeLocalization as String, offset: offset, template: "$1")
let replacement = String(format: format, token)
let replacementRange = NSRange(location: result.range.location + offset, length: result.range.length)
nativeLocalization.replaceCharacters(in: replacementRange, with: replacement)
offset += (replacement as NSString).length - result.range.length
}
return nativeLocalization as String
}
public func replacingMatches(fromTokenRegex regex: NSRegularExpression, withFormat format: String, tokens: [String: String]) -> String {
let nativeLocalization = NSMutableString(string: self)
var offset = 0
let fullRange = NSRange(location: 0, length: nativeLocalization.length)
regex.enumerateMatches(in: self, options: [], range: fullRange) { (result, flags, stop) in
guard let result = result else {
return
}
let token = regex.replacementString(for: result, in: nativeLocalization as String, offset: offset, template: "$1")
let replacement = String(format: format, token, tokens[token] ?? "@")
let replacementRange = NSRange(location: result.range.location + offset, length: result.range.length)
nativeLocalization.replaceCharacters(in: replacementRange, with: replacement)
offset += (replacement as NSString).length - result.range.length
}
return nativeLocalization as String
}
func iOSNativeLocalization(tokens: [String: String]) -> String {
guard let tokenRegex = twnTokenRegex, let braceRegex = curlyBraceRegex else {
return ""
}
return self.replacingMatches(fromRegex: braceRegex, withFormat: "%@").replacingMatches(fromTokenRegex: tokenRegex, withFormat: "%%%@$%@", tokens: tokens)
}
var twnNativeLocalization: String {
guard let tokenRegex = iOSTokenRegex else {
return ""
}
return self.replacingMatches(fromRegex: tokenRegex, withFormat: "$%@")
}
var iOSTokenDictionary: [String: String] {
guard let iOSTokenRegex = iOSTokenRegex else {
print("Unable to compile iOS token regex")
abort()
}
var tokenDictionary = [String:String]()
iOSTokenRegex.enumerateMatches(in: self, options: [], range:self.fullRange, using: { (result, flags, stop) in
guard let result = result else {
return
}
let number = iOSTokenRegex.replacementString(for: result, in: self as String, offset: 0, template: "$1")
let token = iOSTokenRegex.replacementString(for: result, in: self as String, offset: 0, template: "$2")
if tokenDictionary[number] == nil {
tokenDictionary[number] = token
} else if token != tokenDictionary[number] {
print("Internal token mismatch: \(self)")
abort()
}
})
return tokenDictionary
}
}
func writeStrings(fromDictionary dictionary: NSDictionary, toFile: String) throws {
var shouldWrite = true
if let existingDictionary = NSDictionary(contentsOfFile: toFile) {
shouldWrite = existingDictionary.count != dictionary.count
if (!shouldWrite) {
for (key, value) in dictionary {
guard let value = value as? String, let existingValue = existingDictionary[key] as? NSString else {
shouldWrite = true
break
}
shouldWrite = !existingValue.isEqual(to: value)
if (shouldWrite) {
break;
}
}
}
}
guard shouldWrite else {
return
}
let folder = (toFile as NSString).deletingLastPathComponent
do {
try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true, attributes: nil)
} catch { }
let output = dictionary.descriptionInStringsFileFormat
try output.write(toFile: toFile, atomically: true, encoding: .utf16) //From Apple: Note: It is recommended that you save strings files using the UTF-16 encoding, which is the default encoding for standard strings files. It is possible to create strings files using other property-list formats, including binary property-list formats and XML formats that use the UTF-8 encoding, but doing so is not recommended. For more information about Unicode and its text encodings, go to http://www.unicode.org/ or http://en.wikipedia.org/wiki/Unicode.
}
// See "Localized Metadata" section here: https://docs.fastlane.tools/actions/deliver/
func writeFastlaneAppStoreLocalizedMetadataFile(fileName: String, contents: String, locale: String, path: String) throws {
let pathForFastlaneMetadataForLocale = "\(path)/fastlane/metadata/\(locale)"
try FileManager.default.createDirectory(atPath: pathForFastlaneMetadataForLocale, withIntermediateDirectories: true, attributes: nil)
let descriptionFileURL = URL(fileURLWithPath:"\(pathForFastlaneMetadataForLocale)/\(fileName)", isDirectory: false)
try contents.write(to: descriptionFileURL, atomically: true, encoding: .utf8)
}
func writeTWNStrings(fromDictionary dictionary: [String: String], toFile: String, escaped: Bool) throws {
var output = ""
let sortedDictionary = dictionary.sorted(by: { (kv1, kv2) -> Bool in
return kv1.key < kv2.key
})
for (key, value) in sortedDictionary {
output.append("\"\(key)\" = \"\(escaped ? value.escapedString : value)\";\n")
}
try output.write(toFile: toFile, atomically: true, encoding: .utf8)
}
func exportLocalizationsFromSourceCode(_ path: String) {
let iOSENPath = "\(path)/Wikipedia/iOS Native Localizations/en.lproj/Localizable.strings"
let twnQQQPath = "\(path)/Wikipedia/Localizations/qqq.lproj/Localizable.strings"
let twnENPath = "\(path)/Wikipedia/Localizations/en.lproj/Localizable.strings"
guard let iOSEN = NSDictionary(contentsOfFile: iOSENPath) else {
print("Unable to read \(iOSENPath)")
abort()
}
let twnQQQ = NSMutableDictionary()
let twnEN = NSMutableDictionary()
do {
let commentSet = CharacterSet(charactersIn: "/* ")
let quoteSet = CharacterSet(charactersIn: "\"")
let string = try String(contentsOfFile: iOSENPath)
let lines = string.components(separatedBy: .newlines)
var currentComment: String?
var currentKey: String?
var commentsByKey = [String: String]()
for line in lines {
let cleanedLine = line.trimmingCharacters(in: .whitespaces)
if cleanedLine.hasPrefix("/*") {
currentComment = cleanedLine.trimmingCharacters(in: commentSet)
currentKey = nil
} else if currentComment != nil {
let quotesRemoved = cleanedLine.trimmingCharacters(in: quoteSet)
if let range = quotesRemoved.range(of: "\" = \"") {
currentKey = String(quotesRemoved.prefix(upTo: range.lowerBound))
}
}
if let key = currentKey, let comment = currentComment {
commentsByKey[key] = comment
}
}
for (key, comment) in commentsByKey {
twnQQQ[key] = comment.twnNativeLocalization
}
try writeTWNStrings(fromDictionary: twnQQQ as! [String: String], toFile: twnQQQPath, escaped: false)
for (key, value) in iOSEN {
guard let value = value as? String, let key = key as? String else {
continue
}
twnEN[key] = value.twnNativeLocalization
}
try writeTWNStrings(fromDictionary: twnEN as! [String: String], toFile: twnENPath, escaped: true)
} catch let error {
print("Error exporting localizations: \(error)")
abort()
}
}
let locales = Set<String>(Locale.availableIdentifiers)
func localeIsAvailable(_ locale: String) -> Bool {
let prefix = locale.components(separatedBy: "-").first ?? locale
return locales.contains(prefix)
}
func importLocalizationsFromTWN(_ path: String) {
let enPath = "\(path)/Wikipedia/iOS Native Localizations/en.lproj/Localizable.strings"
guard let enDictionary = NSDictionary(contentsOfFile: enPath) as? [String: String] else {
print("Unable to read \(enPath)")
abort()
}
var enTokensByKey = [String: [String: String]]()
for (key, value) in enDictionary {
enTokensByKey[key] = value.iOSTokenDictionary
}
let fm = FileManager.default
do {
let keysByLanguage = ["pl": ["one", "few"], "sr": ["one", "few", "many"], "ru": ["one", "few", "many"]]
let defaultKeys = ["one"]
let contents = try fm.contentsOfDirectory(atPath: "\(path)/Wikipedia/Localizations")
var pathsForEnglishPlurals: [String] = [] //write english plurals to these paths as placeholders
var englishPluralDictionary: NSMutableDictionary?
for filename in contents {
guard let locale = filename.components(separatedBy: ".").first?.lowercased(), localeIsAvailable(locale) else {
continue
}
guard let twnStrings = NSDictionary(contentsOfFile: "\(path)/Wikipedia/Localizations/\(locale).lproj/Localizable.strings") else {
continue
}
let stringsDict = NSMutableDictionary(capacity: twnStrings.count)
let strings = NSMutableDictionary(capacity: twnStrings.count)
for (key, value) in twnStrings {
guard let twnString = value as? String, let key = key as? String, let enTokens = enTokensByKey[key] else {
continue
}
let nativeLocalization = twnString.iOSNativeLocalization(tokens: enTokens)
let nativeLocalizationTokens = nativeLocalization.iOSTokenDictionary
guard nativeLocalizationTokens == enTokens else {
//print("Mismatched tokens in \(locale) for \(key):\n\(enDictionary[key] ?? "")\n\(nativeLocalization)")
continue
}
if twnString.contains("{{PLURAL:") {
let lang = locale.components(separatedBy: "-").first ?? ""
let keys = keysByLanguage[lang] ?? defaultKeys
stringsDict[key] = twnString.pluralDictionary(with: keys, tokens:enTokens)
strings[key] = nativeLocalization
} else {
strings[key] = nativeLocalization
}
}
let stringsFilePath = "\(path)/Wikipedia/iOS Native Localizations/\(locale).lproj/Localizable.strings"
if locale != "en" { // only write the english plurals, skip the main file
if strings.count > 0 {
try writeStrings(fromDictionary: strings, toFile: stringsFilePath)
// If we have a localized app store description, write a fastlane "description.txt" to a folder for its locale.
if let localizedDescription = strings["app-store-short-description"] as? String {
try writeFastlaneAppStoreLocalizedMetadataFile(fileName: "description.txt", contents: localizedDescription, locale: locale, path: path)
}
// If we have a localized app store subtitle, write a fastlane "subtitle.txt" to a folder for its locale.
if let localizedSubtitle = strings["app-store-subtitle"] as? String {
try writeFastlaneAppStoreLocalizedMetadataFile(fileName: "subtitle.txt", contents: localizedSubtitle, locale: locale, path: path)
}
// If we have localized app store release notes, write a fastlane "release_notes.txt" to a folder for its locale.
if let localizedReleaseNotes = strings["app-store-release-notes"] as? String {
try writeFastlaneAppStoreLocalizedMetadataFile(fileName: "release_notes.txt", contents: localizedReleaseNotes, locale: locale, path: path)
}
// If we have localized app store keywords, write a fastlane "keywords.txt" to a folder for its locale.
if let localizedKeywords = strings["app-store-keywords"] as? String {
try writeFastlaneAppStoreLocalizedMetadataFile(fileName: "keywords.txt", contents: localizedKeywords, locale: locale, path: path)
}
} else {
do {
try fm.removeItem(atPath: stringsFilePath)
} catch { }
}
// If we have a localized app name for "Wikipedia", write a fastlane "name.txt" to a folder for its locale.
let infoPlistPath = "\(path)/Wikipedia/iOS Native Localizations/\(locale).lproj/InfoPlist.strings"
if let infoPlist = NSDictionary(contentsOfFile: infoPlistPath), let localizedAppName = infoPlist["CFBundleDisplayName"] as? String, localizedAppName.count > 0, localizedAppName != "Wikipedia" {
try writeFastlaneAppStoreLocalizedMetadataFile(fileName: "name.txt", contents: localizedAppName, locale: locale, path: path)
}
} else {
englishPluralDictionary = stringsDict
}
let stringsDictFilePath = "\(path)/Wikipedia/iOS Native Localizations/\(locale).lproj/Localizable.stringsdict"
if stringsDict.count > 0 {
stringsDict.write(toFile: stringsDictFilePath, atomically: true)
} else {
pathsForEnglishPlurals.append(stringsDictFilePath)
}
}
for stringsDictFilePath in pathsForEnglishPlurals {
englishPluralDictionary?.write(toFile: stringsDictFilePath, atomically: true)
}
} catch let error {
print("Error importing localizations: \(error)")
abort()
}
}
// Code that updated source translations
// var replacements = [String: String]()
// for (key, comment) in qqq {
// guard let value = en[key] else {
// continue
// }
// replacements[key] = "WMFLocalizedStringWithDefaultValue(@\"\(key.escapedString)\", nil, NSBundle.mainBundle, @\"\(value.iOSNativeLocalization.escapedString)\", \"\(comment.escapedString)\")"
// }
//
// let codePath = "WMF Framework"
// let contents = try FileManager.default.contentsOfDirectory(atPath: codePath)
// guard let mwLocalizedStringRegex = mwLocalizedStringRegex else {
// abort()
// }
// for filename in contents {
// do {
// let path = codePath + "/" + filename
// let string = try String(contentsOfFile: path)
// //let string = try String(contentsOf: #fileLiteral(resourceName: "WMFContentGroup+WMFFeedContentDisplaying.m"))
// let mutableString = NSMutableString(string: string)
// var offset = 0
// let fullRange = NSRange(location: 0, length: mutableString.length)
// mwLocalizedStringRegex.enumerateMatches(in: string, options: [], range: fullRange) { (result, flags, stop) in
// guard let result = result else {
// return
// }
// let key = mwLocalizedStringRegex.replacementString(for: result, in: mutableString as String, offset: offset, template: "$1")
// guard let replacement = replacements[key] else {
// return
// }
// let replacementRange = NSRange(location: result.range.location + offset, length: result.range.length)
// mutableString.replaceCharacters(in: replacementRange, with: replacement)
// offset += (replacement as NSString).length - replacementRange.length
// }
// try mutableString.write(toFile: path, atomically: true, encoding: String.Encoding.utf8.rawValue)
// } catch { }
// }
| mit | d1019a57b91ccf6b2ffdeb691d23a50b | 45.28 | 544 | 0.613872 | 4.880827 | false | false | false | false |
adrfer/swift | validation-test/compiler_crashers_fixed/01198-resolvetypedecl.swift | 2 | 951 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
class d<c>: NSObject {
init(b: c) {
}
}
protocol a {
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
}
protocol a : a {
}
class A : A {
}
class B : C {
}
class c {
func b((Any, c))(a: (Any, AnyObject)) {
}
}
protocol b {
}
struct c {
func e() {
}
}
func d<b: SequenceType, e where Optional<e> == b.Generat<d>(() -> d) {
}
protocol A {
}
class B {
func d() -> String {
}
}
class C: B, A {
override func d() -> String {
}
func c() -> String {
}
}
func e<T where T: A, T: B>(t: T) {
}
enum S<T> : P {
func f<T>() -> T -> T {
}
}
protocol P {
}
func a(b: Int = 0) {
}
struct c<d, e: b where d.c == e
| apache-2.0 | 62547b099877455756cc4cc6b906f8b8 | 13.409091 | 87 | 0.555205 | 2.401515 | false | false | false | false |
tavultesoft/keymanweb | ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPLexicalModel.swift | 1 | 3762 | //
// KMPLexicalModel.swift
// KeymanEngine
//
// Created by Randy Boring on 3/12/19.
// Copyright ยฉ 2019 SIL International. All rights reserved.
//
import Foundation
class KMPLexicalModel: Codable, KMPResource {
public var name: String
public var lexicalModelId: String
public var packageId: String?
public var version: String?
public var isRTL: Bool = false
public var languages: [KMPLanguage]
enum CodingKeys: String, CodingKey {
case name
case lexicalModelId = "id"
case version
case isRTL = "rtl"
case languages
}
internal required init?(from lexicalModel: InstallableLexicalModel) {
self.name = lexicalModel.name
self.lexicalModelId = lexicalModel.id
self.version = lexicalModel.version
self.packageId = lexicalModel.packageID ?? lexicalModel.id
// InstallableLexicalModel doesn't store the language name, so we use the id as a fill-in.
// The 'name' part isn't used for matching, anyway.
self.languages = [KMPLanguage(name: lexicalModel.languageID, languageId: lexicalModel.languageID)]
}
required public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .name)
lexicalModelId = try values.decode(String.self, forKey: .lexicalModelId)
// Our schema says that this field is optional for lexical models.
// In these cases, the version should probably be set to the package's version...
// but this constructor lacks access. We'll let the owning Package instance handle this.
version = try values.decodeIfPresent(String.self, forKey: .version)
isRTL = try values.decodeIfPresent(Bool.self, forKey: .isRTL) ?? false
languages = try values.decode([KMPLanguage].self, forKey: .languages)
}
/** This function will set the value for version only when a lexical model doesn't have a value for it specified directly in its definition.
*/
public func setNilVersion(to version: String) {
self.version = self.version ?? version
}
func hasMatchingMetadata(for resource: InstallableLexicalModel, ignoreLanguage: Bool = false, ignoreVersion: Bool = true) -> Bool {
if id != resource.id {
return false
} else if !ignoreVersion, version != resource.version {
return false
}
if !ignoreLanguage {
let resourceMetadata = KMPLexicalModel(from: resource)!
return languages.contains(where: { language in
return language.languageId == resourceMetadata.languages[0].languageId
})
}
return true
}
internal var installableLexicalModels: [InstallableLexicalModel] {
var installableLexicalModels : [InstallableLexicalModel] = []
for language in self.languages {
let model = InstallableLexicalModel(from: self, packageID: packageId!, lgCode: language.languageId)!
installableLexicalModels.append( model )
}
return installableLexicalModels
}
// Needed to properly support AnyKMPResource.installableResources
// because of weird, weird Swift rules.
public var typedInstallableResources: [InstallableLexicalModel] {
return installableLexicalModels
}
// Provides our class's method of the same signature, but with
// the local type signature we know is available.
public var installableResources: [InstallableLexicalModel] {
return installableLexicalModels
}
public var isValid: Bool {
// Ensures that our 'optional' members are properly instantiated.
// Any file-based checks will be performed by the object's owner,
// which knows the containing package's root folder.
return installableLexicalModels.count > 0
&& self.languages.count > 0
}
public var id: String {
return lexicalModelId
}
}
| apache-2.0 | b18b0a9f9066801544e5986ee3700818 | 33.190909 | 142 | 0.72268 | 4.393692 | false | false | false | false |
zhuyunfeng1224/XiheMtxx | XiheMtxx/ViewController.swift | 1 | 1292 | //
// ViewController.swift
// EasyCard
//
// Created by echo on 2017/2/14.
// Copyright ยฉ 2017ๅนด ็พฒๅ. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let button: UIButton = {
let newValue = UIButton(frame: CGRect(x: 100, y: 200, width: 200, height: 200))
newValue.setTitle("ๆทปๅ ", for: .normal)
newValue.setTitleColor(UIColor.gray, for: .normal)
newValue.addTarget(self, action: #selector(startCreateCard), for: .touchUpInside)
return newValue
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.view.addSubview(self.button)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func startCreateCard() -> Void {
// let mainVC = MainViewController()
// let mainNavigationVC = MainNavigationViewController(rootViewController: mainVC)
// self.present(mainNavigationVC, animated: true) {
//
// }
let albumVC = PhotoAlbumViewController()
let mainNavigationVC = MainNavigationViewController(rootViewController: albumVC)
self.present(mainNavigationVC, animated: true) {
}
}
}
| mit | 4ffe34376a1e1cb9a1761ad1f69e851d | 28.113636 | 89 | 0.638564 | 4.591398 | false | false | false | false |
blackspotbear/MMDViewer | MMDViewer/PMX.swift | 1 | 15867 | import Foundation
import GLKit
private func LoadPMXMeta(_ pmx: PMX, _ reader: DataReader) {
let pmxStr = "PMX " as NSString
for i in 0 ..< pmxStr.length {
let c: UInt8 = reader.read()
if unichar(c) != pmxStr.character(at: i) {
// TODO: impl
}
}
pmx.meta.format = pmxStr as String
pmx.meta.version = reader.read()
var remain = reader.readIntN(1)
pmx.meta.encoding = remain > 0 ? reader.readIntN(1) : 0; remain -= 1
pmx.meta.additionalUVCount = remain > 0 ? reader.readIntN(1) : 0; remain -= 1
pmx.meta.vertexIndexSize = remain > 0 ? reader.readIntN(1) : 0; remain -= 1
pmx.meta.textureIndexSize = remain > 0 ? reader.readIntN(1) : 0; remain -= 1
pmx.meta.materialIndexSize = remain > 0 ? reader.readIntN(1) : 0; remain -= 1
pmx.meta.boneIndexSize = remain > 0 ? reader.readIntN(1) : 0; remain -= 1
pmx.meta.morphIndexSize = remain > 0 ? reader.readIntN(1) : 0; remain -= 1
pmx.meta.rigidBodyIndexSize = remain > 0 ? reader.readIntN(1) : 0; remain -= 1
if remain > 0 {
reader.skip(remain)
}
pmx.meta.modelName = reader.readString()!
pmx.meta.modelNameE = reader.readString()!
pmx.meta.comment = reader.readString()!
pmx.meta.commentE = reader.readString()!
pmx.meta.vertexCount = reader.readIntN(4)
}
private func LoadPMXVertices(_ pmx: PMX, _ reader: DataReader) {
for _ in 0 ..< pmx.meta.vertexCount {
let v = GLKVector3Make(reader.read(), reader.read(), -reader.read())
let n = GLKVector3Make(reader.read(), reader.read(), -reader.read())
let uv = UV(reader.read(), reader.read())
let skinningMethod: UInt8 = reader.read()
var euvs: [GLKVector4] = []
for _ in 0 ..< pmx.meta.additionalUVCount {
let euv = GLKVector4Make(reader.read(), reader.read(), reader.read(), reader.read())
euvs.append(euv)
}
var boneIndices: [UInt16] = []
var boneWeights: [Float] = []
if skinningMethod == 0 {
boneIndices.append(UInt16(reader.readIntN(pmx.meta.boneIndexSize)))
boneIndices.append(0)
boneIndices.append(0)
boneIndices.append(0)
boneWeights.append(1)
boneWeights.append(0)
boneWeights.append(0)
boneWeights.append(0)
} else if skinningMethod == 1 {
boneIndices.append(UInt16(reader.readIntN(pmx.meta.boneIndexSize)))
boneIndices.append(UInt16(reader.readIntN(pmx.meta.boneIndexSize)))
boneIndices.append(0)
boneIndices.append(0)
boneWeights.append(reader.read())
boneWeights.append(1 - boneWeights.last!)
boneWeights.append(0)
boneWeights.append(0)
} else if skinningMethod == 2 {
boneIndices.append(UInt16(reader.readIntN(pmx.meta.boneIndexSize)))
boneIndices.append(UInt16(reader.readIntN(pmx.meta.boneIndexSize)))
boneIndices.append(UInt16(reader.readIntN(pmx.meta.boneIndexSize)))
boneIndices.append(UInt16(reader.readIntN(pmx.meta.boneIndexSize)))
boneWeights.append(reader.read())
boneWeights.append(reader.read())
boneWeights.append(reader.read())
boneWeights.append(reader.read())
} else if skinningMethod == 3 {
boneIndices.append(UInt16(reader.readIntN(pmx.meta.boneIndexSize)))
boneIndices.append(UInt16(reader.readIntN(pmx.meta.boneIndexSize)))
boneIndices.append(0)
boneIndices.append(0)
boneWeights.append(reader.read())
boneWeights.append(1 - boneWeights.last!)
boneWeights.append(0)
boneWeights.append(0)
reader.skip(MemoryLayout<Float>.size * 3 * 3)
} else {
fatalError("not implemented")
}
let vertex = PMXVertex(
v: v,
n: n,
uv: uv,
euvs: euvs,
skinningMethod: skinningMethod,
boneWeights: boneWeights,
boneIndices: boneIndices)
// edge magnification
let _: Float = reader.read() // not supported at this time
pmx.vertices.append(vertex)
}
}
private func LoadPMXFaces(_ pmx: PMX, _ reader: DataReader) {
let faceCount: Int32 = reader.read()
for _ in 0 ..< faceCount / 3 {
let index0 = UInt16(reader.readIntN(pmx.meta.vertexIndexSize))
let index1 = UInt16(reader.readIntN(pmx.meta.vertexIndexSize))
let index2 = UInt16(reader.readIntN(pmx.meta.vertexIndexSize))
pmx.indices.append(index0)
pmx.indices.append(index2)
pmx.indices.append(index1)
}
}
private func LoadPMXTexturePaths(_ pmx: PMX, _ reader: DataReader) {
let textureCount: Int32 = reader.read()
for _ in 0 ..< textureCount {
pmx.texturePaths.append(reader.readString()!)
}
}
private func LoadPMXMaterials(_ pmx: PMX, _ reader: DataReader) {
let materialCount = reader.readIntN(4)
for _ in 0 ..< materialCount {
let name = reader.readString()
let nameE = reader.readString()
let diffuse = Color(reader.read(), reader.read(), reader.read(), reader.read())
let specular = Color(reader.read(), reader.read(), reader.read(), 1.0)
let specularPower: Float = reader.read()
let ambient = Color(reader.read(), reader.read(), reader.read(), 1.0)
let flag: MaterialFlag = reader.read()
let edgeColor = Color(reader.read(), reader.read(), reader.read(), reader.read())
let edgeSize: Float = reader.read()
let textureIndex: Int = reader.readIntN(pmx.meta.textureIndexSize)
let sphereTextureIndex: Int = reader.readIntN(pmx.meta.textureIndexSize)
let sphereMode: UInt8 = reader.read()
let sharedToon: Bool = reader.read()
let toonTextureIndex = sharedToon ? reader.readIntN(1) : reader.readIntN(pmx.meta.textureIndexSize)
let memo = reader.readString()!
let vertexCount: Int32 = reader.read()
let material = Material(
name: name!,
nameE: nameE!,
diffuse: diffuse,
specular: specular,
specularPower: specularPower,
ambient: ambient,
flag: flag,
edgeColor: edgeColor,
edgeSize: edgeSize,
textureIndex: textureIndex,
sphereTextureIndex: sphereTextureIndex,
sphereMode: sphereMode,
sharedToon: sharedToon,
toonTextureIndex: toonTextureIndex,
memo: memo,
vertexCount: vertexCount
)
pmx.materials.append(material)
}
}
private func LoadPMXBones(_ pmx: PMX, _ reader: DataReader) {
let boneCount = reader.readIntN(4)
for _ in 0 ..< boneCount {
let boneName = reader.readString()
let boneNameE = reader.readString()
let pos = GLKVector3Make(reader.read(), reader.read(), -reader.read())
let parentBoneIndex = reader.readIntN(pmx.meta.boneIndexSize)
let deformLayer: Int32 = reader.read()
let bitFlag = BoneFlag(rawValue: reader.read())
var childPos = GLKVector3Make(0, 0, 0)
var childBoneIndex = 0
if bitFlag.contains(.ParentBoneIndex) {
childBoneIndex = reader.readIntN(pmx.meta.boneIndexSize)
} else {
childPos = GLKVector3Make(reader.read(), reader.read(), -reader.read())
}
let adding = bitFlag.isDisjoint(with: [.RotationAdd, .TranslationAdd]) == false
let affectingParentBoneIndex = adding ? reader.readIntN(pmx.meta.boneIndexSize) : 0
let affectingRate: Float = adding ? reader.read() : 0
let fixAxis = bitFlag.contains(.FixAxis) ? GLKVector3Make(reader.read(), reader.read(), -reader.read()) : GLKVector3Make(0, 0, 0)
var xAxis = GLKVector3Make(0, 0, 0)
var zAxis = GLKVector3Make(0, 0, 0)
if bitFlag.contains(.LocalAxis) {
xAxis = GLKVector3Make(reader.read(), reader.read(), -reader.read())
zAxis = GLKVector3Make(reader.read(), reader.read(), -reader.read())
}
let key: Int32 = bitFlag.contains(.DeformExternalParent) ? reader.read() : 0
var ikLinks: [IKLink] = []
var ikTargetBoneIndex: Int = 0
var ikLoopCount: Int32 = 0
var ikAngularLimit: Float = 0
if bitFlag.contains(.InverseKinematics) {
ikTargetBoneIndex = reader.readIntN(pmx.meta.boneIndexSize)
ikLoopCount = reader.read()
ikAngularLimit = reader.read()
let ikLinkCount: Int32 = reader.read()
for _ in 0 ..< ikLinkCount {
let boneIndex = reader.readIntN(pmx.meta.boneIndexSize)
let angularLimit = reader.read() as UInt8 != 0
let angularLimitMin = angularLimit ? GLKVector3Make(reader.read(), reader.read(), reader.read()) : GLKVector3Make(0, 0, 0)
let angularLimitMax = angularLimit ? GLKVector3Make(reader.read(), reader.read(), reader.read()) : GLKVector3Make(0, 0, 0)
let ikLink = IKLink(
boneIndex: boneIndex,
angularLimit: angularLimit,
angularLimitMin: angularLimitMin,
angularLimitMax: angularLimitMax
)
ikLinks.append(ikLink)
}
}
let bone = Bone(
name: boneName!,
nameE: boneNameE!,
pos: pos,
parentBoneIndex: parentBoneIndex,
deformLayer: deformLayer,
bitFlag: bitFlag,
childOffset: childPos,
childBoneIndex: childBoneIndex,
affectingParentBoneIndex: affectingParentBoneIndex,
affectingRate: affectingRate,
fixAxis: fixAxis,
xAxis: xAxis,
zAxis: zAxis,
key: key,
ikTargetBoneIndex: ikTargetBoneIndex,
ikLoopCount: ikLoopCount,
ikAngularLimit: ikAngularLimit,
ikLinks: ikLinks)
pmx.bones.append(bone)
}
}
private func LoadPMXMorphElement(_ type: MorphType, _ pmx: PMX, _ reader: DataReader) -> Any {
switch type {
case .group:
return MorphGroup(index: reader.readIntN(pmx.meta.morphIndexSize), ratio: reader.read())
case .vertex:
return MorphVertex(index: reader.readIntN(pmx.meta.vertexIndexSize),
trans: GLKVector3Make(reader.read(), reader.read(), -reader.read()))
case .bone:
return MorphBone(index: reader.readIntN(pmx.meta.boneIndexSize),
trans: GLKVector3Make(reader.read(), reader.read(), -reader.read()),
rot: GLKQuaternionMake(reader.read(), reader.read(), reader.read(), reader.read()))
case .uv: fallthrough
case .uv1: fallthrough
case .uv2: fallthrough
case .uv3: fallthrough
case .uv4:
return MorphUV(index: reader.readIntN(pmx.meta.vertexIndexSize),
trans: GLKVector4Make(reader.read(), reader.read(), reader.read(), reader.read()))
case .material:
return MorphMaterial(index: reader.readIntN(pmx.meta.materialIndexSize),
opType: reader.read(),
diffuse: GLKVector4Make(reader.read(), reader.read(), reader.read(), reader.read()),
specular: GLKVector3Make(reader.read(), reader.read(), reader.read()),
shininess: reader.read(),
ambient: GLKVector3Make(reader.read(), reader.read(), reader.read()),
edgeColor: GLKVector4Make(reader.read(), reader.read(), reader.read(), reader.read()),
edgeSize: reader.read(),
textureColor: GLKVector4Make(reader.read(), reader.read(), reader.read(), reader.read()),
sphereTextureColor: GLKVector4Make(reader.read(), reader.read(), reader.read(), reader.read()),
toonTextureColor: GLKVector4Make(reader.read(), reader.read(), reader.read(), reader.read()))
}
}
private func LoadPMXMorphs(_ pmx: PMX, _ reader: DataReader) {
let morphCount = reader.readIntN(4)
for _ in 0 ..< morphCount {
var m = Morph(name: reader.readString()!, nameE: reader.readString()!, panel: reader.readIntN(1), type: MorphType(rawValue: reader.readIntN(1))!, elements: [])
let elementCount = reader.readIntN(4)
for _ in 0 ..< elementCount {
m.elements.append(LoadPMXMorphElement(m.type, pmx, reader))
}
pmx.morphs[m.name] = m
}
}
private func Skip(_ pmx: PMX, _ reader: DataReader) {
let rigidCount = reader.readIntN(4)
for _ in 0 ..< rigidCount {
_ = reader.readString()
_ = reader.readString()
_ = reader.read() as UInt8
let n = reader.readIntN(4)
for _ in 0 ..< n {
if reader.read() as UInt8 == 0 {
_ = reader.readIntN(pmx.meta.boneIndexSize)
} else {
_ = reader.readIntN(pmx.meta.morphIndexSize)
}
}
}
}
private func LoadRigidBodies(_ pmx: PMX, _ reader: DataReader) {
let rigidCount = reader.readIntN(4)
for _ in 0 ..< rigidCount {
let rigidBody = RigidBody(name: reader.readString()!, nameE: reader.readString()!, boneIndex: reader.readIntN(pmx.meta.boneIndexSize), groupID: reader.read(), groupFlag: reader.read(), shapeType: reader.read(), size: GLKVector3Make(reader.read(), reader.read(), reader.read()), pos: GLKVector3Make(reader.read(), reader.read(), -reader.read()), rot: GLKVector3Make(reader.read(), reader.read(), reader.read()), mass: reader.read(), linearDamping: reader.read(), angularDamping: reader.read(), restitution: reader.read(), friction: reader.read(), type: reader.read())
pmx.rigidBodies.append(rigidBody)
}
}
private func LoadConstraints(_ pmx: PMX, _ reader: DataReader) {
let constraintCount = reader.readIntN(4)
for _ in 0 ..< constraintCount {
let constraint = Constraint(name: reader.readString()!, nameE: reader.readString()!, type: reader.read(), rigidAIndex: reader.readIntN(pmx.meta.rigidBodyIndexSize), rigidBIndex: reader.readIntN(pmx.meta.rigidBodyIndexSize), pos: GLKVector3Make(reader.read(), reader.read(), -reader.read()), rot: GLKVector3Make(reader.read(), reader.read(), reader.read()), linearLowerLimit: GLKVector3Make(reader.read(), reader.read(), reader.read()), linearUpperLimit: GLKVector3Make(reader.read(), reader.read(), reader.read()), angularLowerLimit: GLKVector3Make(reader.read(), reader.read(), reader.read()), angularUpperLimit: GLKVector3Make(reader.read(), reader.read(), reader.read()), linearSpringStiffness: GLKVector3Make(reader.read(), reader.read(), reader.read()), angularSpringStiffness: GLKVector3Make(reader.read(), reader.read(), reader.read()))
pmx.constraints.append(constraint)
}
}
class PMX {
var meta = PMXMeta()
var vertices: [PMXVertex] = []
var indices: [UInt16] = []
var texturePaths: [String] = []
var materials: [Material] = []
var bones: [Bone] = []
var morphs: [String:Morph] = [:]
var rigidBodies: [RigidBody] = []
var constraints: [Constraint] = []
init(data: Data) {
let reader = DataReader(data: data)
LoadPMXMeta(self, reader)
LoadPMXVertices(self, reader)
LoadPMXFaces(self, reader)
LoadPMXTexturePaths(self, reader)
LoadPMXMaterials(self, reader)
LoadPMXBones(self, reader)
LoadPMXMorphs(self, reader)
Skip(self, reader)
LoadRigidBodies(self, reader)
LoadConstraints(self, reader)
}
}
| mit | 43ab0a92094a58f820cc5f043b923d38 | 41.653226 | 851 | 0.607361 | 3.945052 | false | false | false | false |
tourani/GHIssue | OAuth2PodApp/SignInViewController.swift | 1 | 3594 | //
// ViewController.swift
// OAuth2PodApp
//
//
import UIKit
import p2_OAuth2
import Alamofire
class SignInViewController: UIViewController {
// fileprivate var alamofireManager: SessionManager?
var loader: OAuth2DataLoader?
var oauth2 = OAuth2CodeGrant(settings: [
"client_id": "8ae913c685556e73a16f", // yes, this client-id and secret will work!
"client_secret": "60d81efcc5293fd1d096854f4eee0764edb2da5d",
"authorize_uri": "https://github.com/login/oauth/authorize",
"token_uri": "https://github.com/login/oauth/access_token",
"scope": "repo",
"redirect_uris": ["ppoauthapp://oauth/callback"], // app has registered this scheme
"secret_in_body": true, // GitHub does not accept client secret in the Authorization header
"verbose": true,
] as OAuth2JSON)
@IBOutlet var signInEmbeddedButton: UIButton?
@IBOutlet var forgetButton: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
}
@IBAction func signInEmbedded(_ sender: UIButton?) {
if oauth2.isAuthorizing {
oauth2.abortAuthorization()
return
}
sender?.setTitle("Authorizing...", for: UIControlState.normal)
oauth2.authConfig.authorizeEmbedded = true
oauth2.authConfig.authorizeContext = self
let loader = OAuth2DataLoader(oauth2: oauth2)
self.loader = loader
loader.perform(request: userDataRequest) { response in
do {
let json = try response.responseJSON()
self.didSignIn()
}
catch let error {
self.didCancelOrFail(error)
}
}
}
@IBAction func forgetTokens(_ sender: UIButton?) {
oauth2.forgetTokens()
oauth2.abortAuthorization()
//let storage = HTTPCookieStorage.shared
//storage.cookies?.forEach() { storage.deleteCookie($0) }
resetButtons()
}
// MARK: - Actions
var userDataRequest: URLRequest {
var request = URLRequest(url: URL(string: "https://api.github.com/user")!)
request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")
return request
}
func didSignIn() {
self.signInEmbeddedButton?.isHidden = true
self.forgetButton?.isHidden = false
self.performSegue(withIdentifier: "SegueToProfile", sender: nil)
}
func didCancelOrFail(_ error: Error?) {
DispatchQueue.main.async {
if let error = error {
print("Authorization went wrong: \(error)")
}
self.resetButtons()
}
}
func resetButtons() {
signInEmbeddedButton?.setTitle("Sign In (Embedded)", for: UIControlState())
signInEmbeddedButton?.isEnabled = true
signInEmbeddedButton?.isHidden = false
forgetButton?.isHidden = true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let destVC = segue.destination as? ProfileViewController else{
print("ERROR-cannot init destination View Controller")
return
}
destVC.loader = self.loader
destVC.oauth2 = self.oauth2
}
}
| mit | c4ab12bce9ee2c66c0eee3b1ec4b05ab | 29.201681 | 136 | 0.58709 | 4.811245 | false | false | false | false |
jacobwhite/firefox-ios | Client/Frontend/Login Management/LoginListViewController.swift | 1 | 23442 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
import Storage
import Shared
import SwiftKeychainWrapper
import Deferred
private struct LoginListUX {
static let RowHeight: CGFloat = 58
static let SearchHeight: CGFloat = 58
static let selectionButtonFont = UIFont.systemFont(ofSize: 16)
static let selectionButtonTextColor = UIColor.white
static let selectionButtonBackground = UIConstants.HighlightBlue
static let NoResultsFont: UIFont = UIFont.systemFont(ofSize: 16)
static let NoResultsTextColor: UIColor = UIColor.lightGray
}
private extension UITableView {
var allIndexPaths: [IndexPath] {
return (0..<self.numberOfSections).flatMap { sectionNum in
(0..<self.numberOfRows(inSection: sectionNum)).map { IndexPath(row: $0, section: sectionNum) }
}
}
}
private let LoginCellIdentifier = "LoginCell"
class LoginListViewController: SensitiveViewController {
fileprivate lazy var loginSelectionController: ListSelectionController = {
return ListSelectionController(tableView: self.tableView)
}()
fileprivate lazy var loginDataSource: LoginDataSource = {
let dataSource = LoginDataSource()
dataSource.dataObserver = self
return dataSource
}()
fileprivate let profile: Profile
fileprivate let searchView = SearchInputView()
fileprivate var activeLoginQuery: Deferred<Maybe<[Login]>>?
fileprivate let loadingStateView = LoadingLoginsView()
fileprivate var deleteAlert: UIAlertController?
// Titles for selection/deselect/delete buttons
fileprivate let deselectAllTitle = NSLocalizedString("Deselect All", tableName: "LoginManager", comment: "Label for the button used to deselect all logins.")
fileprivate let selectAllTitle = NSLocalizedString("Select All", tableName: "LoginManager", comment: "Label for the button used to select all logins.")
fileprivate let deleteLoginTitle = NSLocalizedString("Delete", tableName: "LoginManager", comment: "Label for the button used to delete the current login.")
fileprivate lazy var selectionButton: UIButton = {
let button = UIButton()
button.titleLabel?.font = LoginListUX.selectionButtonFont
button.setTitle(self.selectAllTitle, for: [])
button.setTitleColor(LoginListUX.selectionButtonTextColor, for: [])
button.backgroundColor = LoginListUX.selectionButtonBackground
button.addTarget(self, action: #selector(tappedSelectionButton), for: .touchUpInside)
return button
}()
fileprivate var selectionButtonHeightConstraint: Constraint?
fileprivate var selectedIndexPaths = [IndexPath]()
fileprivate let tableView = UITableView()
weak var settingsDelegate: SettingsDelegate?
init(profile: Profile) {
self.profile = profile
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(remoteLoginsDidChange), name: .DataRemoteLoginChangesWereApplied, object: nil)
notificationCenter.addObserver(self, selector: #selector(dismissAlertController), name: .UIApplicationDidEnterBackground, object: nil)
automaticallyAdjustsScrollViewInsets = false
self.view.backgroundColor = UIColor.white
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(beginEditing))
self.title = NSLocalizedString("Logins", tableName: "LoginManager", comment: "Title for Logins List View screen.")
searchView.delegate = self
tableView.register(LoginTableViewCell.self, forCellReuseIdentifier: LoginCellIdentifier)
view.addSubview(searchView)
view.addSubview(tableView)
view.addSubview(loadingStateView)
view.addSubview(selectionButton)
loadingStateView.isHidden = true
searchView.snp.makeConstraints { make in
make.top.equalTo(self.topLayoutGuide.snp.bottom)
make.leading.trailing.equalTo(self.view)
make.height.equalTo(LoginListUX.SearchHeight)
}
tableView.snp.makeConstraints { make in
make.top.equalTo(searchView.snp.bottom)
make.leading.trailing.equalTo(self.view)
make.bottom.equalTo(self.selectionButton.snp.top)
}
selectionButton.snp.makeConstraints { make in
make.leading.trailing.bottom.equalTo(self.view)
make.top.equalTo(self.tableView.snp.bottom)
make.bottom.equalTo(self.view)
selectionButtonHeightConstraint = make.height.equalTo(0).constraint
}
loadingStateView.snp.makeConstraints { make in
make.edges.equalTo(tableView)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.accessibilityIdentifier = "Login List"
tableView.dataSource = loginDataSource
tableView.allowsMultipleSelectionDuringEditing = true
tableView.delegate = self
tableView.tableFooterView = UIView()
KeyboardHelper.defaultHelper.addDelegate(self)
searchView.isEditing ? loadLogins(searchView.inputField.text) : loadLogins()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.loginDataSource.emptyStateView.searchBarHeight = searchView.frame.height
self.loadingStateView.searchBarHeight = searchView.frame.height
}
deinit {
NotificationCenter.default.removeObserver(self)
}
fileprivate func toggleDeleteBarButton() {
// Show delete bar button item if we have selected any items
if loginSelectionController.selectedCount > 0 {
if navigationItem.rightBarButtonItem == nil {
navigationItem.rightBarButtonItem = UIBarButtonItem(title: deleteLoginTitle, style: .plain, target: self, action: #selector(tappedDelete))
navigationItem.rightBarButtonItem?.tintColor = UIColor.red
}
} else {
navigationItem.rightBarButtonItem = nil
}
}
fileprivate func toggleSelectionTitle() {
if loginSelectionController.selectedCount == loginDataSource.count {
selectionButton.setTitle(deselectAllTitle, for: [])
} else {
selectionButton.setTitle(selectAllTitle, for: [])
}
}
// Wrap the SQLiteLogins method to allow us to cancel it from our end.
fileprivate func queryLogins(_ query: String) -> Deferred<Maybe<[Login]>> {
let deferred = Deferred<Maybe<[Login]>>()
profile.logins.searchLoginsWithQuery(query) >>== { logins in
deferred.fillIfUnfilled(Maybe(success: logins.asArray()))
succeed()
}
return deferred
}
}
// MARK: - Selectors
private extension LoginListViewController {
@objc func remoteLoginsDidChange() {
DispatchQueue.main.async {
self.loadLogins()
}
}
@objc func dismissAlertController() {
self.deleteAlert?.dismiss(animated: false, completion: nil)
}
func loadLogins(_ query: String? = nil) {
loadingStateView.isHidden = false
// Fill in an in-flight query and re-query
activeLoginQuery?.fillIfUnfilled(Maybe(success: []))
activeLoginQuery = queryLogins(query ?? "")
activeLoginQuery! >>== self.loginDataSource.setLogins
}
@objc func beginEditing() {
navigationItem.rightBarButtonItem = nil
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelSelection))
selectionButtonHeightConstraint?.update(offset: UIConstants.ToolbarHeight)
self.view.layoutIfNeeded()
tableView.setEditing(true, animated: true)
}
@objc func cancelSelection() {
// Update selection and select all button
loginSelectionController.deselectAll()
toggleSelectionTitle()
selectionButtonHeightConstraint?.update(offset: 0)
self.view.layoutIfNeeded()
tableView.setEditing(false, animated: true)
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(beginEditing))
}
@objc func tappedDelete() {
profile.logins.hasSyncedLogins().uponQueue(.main) { yes in
self.deleteAlert = UIAlertController.deleteLoginAlertWithDeleteCallback({ [unowned self] _ in
// Delete here
let guidsToDelete = self.loginSelectionController.selectedIndexPaths.map { indexPath in
self.loginDataSource.loginAtIndexPath(indexPath)!.guid
}
self.profile.logins.removeLoginsWithGUIDs(guidsToDelete).uponQueue(.main) { _ in
self.cancelSelection()
self.loadLogins()
}
}, hasSyncedLogins: yes.successValue ?? true)
self.present(self.deleteAlert!, animated: true, completion: nil)
}
}
@objc func tappedSelectionButton() {
// If we haven't selected everything yet, select all
if loginSelectionController.selectedCount < loginDataSource.count {
// Find all unselected indexPaths
let unselectedPaths = tableView.allIndexPaths.filter { indexPath in
return !loginSelectionController.indexPathIsSelected(indexPath)
}
loginSelectionController.selectIndexPaths(unselectedPaths)
unselectedPaths.forEach { indexPath in
self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
}
}
// If everything has been selected, deselect all
else {
loginSelectionController.deselectAll()
tableView.allIndexPaths.forEach { indexPath in
self.tableView.deselectRow(at: indexPath, animated: true)
}
}
toggleSelectionTitle()
toggleDeleteBarButton()
}
}
// MARK: - LoginDataSourceObserver
extension LoginListViewController: LoginDataSourceObserver {
func loginSectionsDidUpdate() {
loadingStateView.isHidden = true
tableView.reloadData()
activeLoginQuery = nil
navigationItem.rightBarButtonItem?.isEnabled = loginDataSource.count > 0
restoreSelectedRows()
}
func restoreSelectedRows() {
for path in self.loginSelectionController.selectedIndexPaths {
tableView.selectRow(at: path, animated: false, scrollPosition: .none)
}
}
}
// MARK: - UITableViewDelegate
extension LoginListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Force the headers to be hidden
return 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return LoginListUX.RowHeight
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .none
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.isEditing {
loginSelectionController.selectIndexPath(indexPath)
toggleSelectionTitle()
toggleDeleteBarButton()
} else {
tableView.deselectRow(at: indexPath, animated: true)
let login = loginDataSource.loginAtIndexPath(indexPath)!
let detailViewController = LoginDetailViewController(profile: profile, login: login)
detailViewController.settingsDelegate = settingsDelegate
navigationController?.pushViewController(detailViewController, animated: true)
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if tableView.isEditing {
loginSelectionController.deselectIndexPath(indexPath)
toggleSelectionTitle()
toggleDeleteBarButton()
}
}
}
// MARK: - KeyboardHelperDelegate
extension LoginListViewController: KeyboardHelperDelegate {
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
let coveredHeight = state.intersectionHeightForView(tableView)
tableView.contentInset.bottom = coveredHeight
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) {
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
tableView.contentInset.bottom = 0
}
}
// MARK: - SearchInputViewDelegate
extension LoginListViewController: SearchInputViewDelegate {
@objc func searchInputView(_ searchView: SearchInputView, didChangeTextTo text: String) {
loadLogins(text)
}
@objc func searchInputViewBeganEditing(_ searchView: SearchInputView) {
// Trigger a cancel for editing
cancelSelection()
// Hide the edit button while we're searching
navigationItem.rightBarButtonItem = nil
loadLogins()
}
@objc func searchInputViewFinishedEditing(_ searchView: SearchInputView) {
// Show the edit after we're done with the search
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(beginEditing))
loadLogins()
}
}
/// Controller that keeps track of selected indexes
fileprivate class ListSelectionController: NSObject {
fileprivate unowned let tableView: UITableView
fileprivate(set) var selectedIndexPaths = [IndexPath]()
var selectedCount: Int {
return selectedIndexPaths.count
}
init(tableView: UITableView) {
self.tableView = tableView
super.init()
}
func selectIndexPath(_ indexPath: IndexPath) {
selectedIndexPaths.append(indexPath)
}
func indexPathIsSelected(_ indexPath: IndexPath) -> Bool {
return selectedIndexPaths.contains(indexPath) { path1, path2 in
return path1.row == path2.row && path1.section == path2.section
}
}
func deselectIndexPath(_ indexPath: IndexPath) {
guard let foundSelectedPath = (selectedIndexPaths.filter { $0.row == indexPath.row && $0.section == indexPath.section }).first,
let indexToRemove = selectedIndexPaths.index(of: foundSelectedPath) else {
return
}
selectedIndexPaths.remove(at: indexToRemove)
}
func deselectAll() {
selectedIndexPaths.removeAll()
}
func selectIndexPaths(_ indexPaths: [IndexPath]) {
selectedIndexPaths += indexPaths
}
}
protocol LoginDataSourceObserver: class {
func loginSectionsDidUpdate()
}
/// Data source for handling LoginData objects from a Cursor
class LoginDataSource: NSObject, UITableViewDataSource {
var count: Int = 0
weak var dataObserver: LoginDataSourceObserver?
fileprivate let emptyStateView = NoLoginsView()
fileprivate var sections = [Character: [Login]]() {
didSet {
assert(Thread.isMainThread, "Must be assigned to from the main thread or else data will be out of sync with reloadData.")
self.dataObserver?.loginSectionsDidUpdate()
}
}
fileprivate var titles = [Character]()
fileprivate func loginsForSection(_ section: Int) -> [Login]? {
let titleForSectionIndex = titles[section]
return sections[titleForSectionIndex]
}
func loginAtIndexPath(_ indexPath: IndexPath) -> Login? {
let titleForSectionIndex = titles[indexPath.section]
return sections[titleForSectionIndex]?[indexPath.row]
}
@objc func numberOfSections(in tableView: UITableView) -> Int {
let numOfSections = sections.count
if numOfSections == 0 {
tableView.backgroundView = emptyStateView
tableView.separatorStyle = .none
} else {
tableView.backgroundView = nil
tableView.separatorStyle = .singleLine
}
return numOfSections
}
@objc func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return loginsForSection(section)?.count ?? 0
}
@objc func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: LoginCellIdentifier, for: indexPath) as! LoginTableViewCell
let login = loginAtIndexPath(indexPath)!
cell.style = .noIconAndBothLabels
cell.updateCellWithLogin(login)
return cell
}
@objc func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return titles.map { String($0) }
}
@objc func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return titles.index(of: Character(title)) ?? 0
}
@objc func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return String(titles[section])
}
func setLogins(_ logins: [Login]) {
// NB: Make sure we call the callback on the main thread so it can be synced up with a reloadData to
// prevent race conditions between data/UI indexing.
return computeSectionsFromLogins(logins).uponQueue(.main) { result in
guard let (titles, sections) = result.successValue else {
self.count = 0
self.titles = []
self.sections = [:]
return
}
self.count = logins.count
self.titles = titles
self.sections = sections
}
}
fileprivate func computeSectionsFromLogins(_ logins: [Login]) -> Deferred<Maybe<([Character], [Character: [Login]])>> {
guard logins.count > 0 else {
return deferMaybe( ([Character](), [Character: [Login]]()) )
}
var domainLookup = [GUID: (baseDomain: String?, host: String?, hostname: String)]()
var sections = [Character: [Login]]()
var titleSet = Set<Character>()
// Small helper method for using the precomputed base domain to determine the title/section of the
// given login.
func titleForLogin(_ login: Login) -> Character {
// Fallback to hostname if we can't extract a base domain.
let titleString = domainLookup[login.guid]?.baseDomain?.uppercased() ?? login.hostname
return titleString.first ?? Character("")
}
// Rules for sorting login URLS:
// 1. Compare base domains
// 2. If bases are equal, compare hosts
// 3. If login URL was invalid, revert to full hostname
func sortByDomain(_ loginA: Login, loginB: Login) -> Bool {
guard let domainsA = domainLookup[loginA.guid],
let domainsB = domainLookup[loginB.guid] else {
return false
}
guard let baseDomainA = domainsA.baseDomain,
let baseDomainB = domainsB.baseDomain,
let hostA = domainsA.host,
let hostB = domainsB.host else {
return domainsA.hostname < domainsB.hostname
}
if baseDomainA == baseDomainB {
return hostA < hostB
} else {
return baseDomainA < baseDomainB
}
}
return deferDispatchAsync(DispatchQueue.global(qos: DispatchQoS.userInteractive.qosClass)) {
// Precompute the baseDomain, host, and hostname values for sorting later on. At the moment
// baseDomain() is a costly call because of the ETLD lookup tables.
logins.forEach { login in
domainLookup[login.guid] = (
login.hostname.asURL?.baseDomain,
login.hostname.asURL?.host,
login.hostname
)
}
// 1. Temporarily insert titles into a Set to get duplicate removal for 'free'.
logins.forEach { titleSet.insert(titleForLogin($0)) }
// 2. Setup an empty list for each title found.
titleSet.forEach { sections[$0] = [Login]() }
// 3. Go through our logins and put them in the right section.
logins.forEach { sections[titleForLogin($0)]?.append($0) }
// 4. Go through each section and sort.
sections.forEach { sections[$0] = $1.sorted(by: sortByDomain) }
return deferMaybe( (Array(titleSet).sorted(), sections) )
}
}
}
/// Empty state view when there is no logins to display.
fileprivate class NoLoginsView: UIView {
// We use the search bar height to maintain visual balance with the whitespace on this screen. The
// title label is centered visually using the empty view + search bar height as the size to center with.
var searchBarHeight: CGFloat = 0 {
didSet {
setNeedsUpdateConstraints()
}
}
lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = LoginListUX.NoResultsFont
label.textColor = LoginListUX.NoResultsTextColor
label.text = NSLocalizedString("No logins found", tableName: "LoginManager", comment: "Label displayed when no logins are found after searching.")
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(titleLabel)
}
fileprivate override func updateConstraints() {
super.updateConstraints()
titleLabel.snp.remakeConstraints { make in
make.centerX.equalTo(self)
make.centerY.equalTo(self).offset(-(searchBarHeight / 2))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/// View to display to the user while we are loading the logins
fileprivate class LoadingLoginsView: UIView {
var searchBarHeight: CGFloat = 0 {
didSet {
setNeedsUpdateConstraints()
}
}
lazy var indicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
indicator.hidesWhenStopped = false
return indicator
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(indicator)
backgroundColor = UIColor.white
indicator.startAnimating()
}
fileprivate override func updateConstraints() {
super.updateConstraints()
indicator.snp.remakeConstraints { make in
make.centerX.equalTo(self)
make.centerY.equalTo(self).offset(-(searchBarHeight / 2))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | 7bfbc23f092da68258b829e2c6faa295 | 35.974763 | 161 | 0.665088 | 5.49379 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/CustomerAddressUpdatePayload.swift | 1 | 5833 | //
// CustomerAddressUpdatePayload.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// Return type for `customerAddressUpdate` mutation.
open class CustomerAddressUpdatePayloadQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CustomerAddressUpdatePayload
/// The customerโs updated mailing address.
@discardableResult
open func customerAddress(alias: String? = nil, _ subfields: (MailingAddressQuery) -> Void) -> CustomerAddressUpdatePayloadQuery {
let subquery = MailingAddressQuery()
subfields(subquery)
addField(field: "customerAddress", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@discardableResult
open func customerUserErrors(alias: String? = nil, _ subfields: (CustomerUserErrorQuery) -> Void) -> CustomerAddressUpdatePayloadQuery {
let subquery = CustomerUserErrorQuery()
subfields(subquery)
addField(field: "customerUserErrors", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `customerUserErrors` instead.")
@discardableResult
open func userErrors(alias: String? = nil, _ subfields: (UserErrorQuery) -> Void) -> CustomerAddressUpdatePayloadQuery {
let subquery = UserErrorQuery()
subfields(subquery)
addField(field: "userErrors", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// Return type for `customerAddressUpdate` mutation.
open class CustomerAddressUpdatePayload: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = CustomerAddressUpdatePayloadQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "customerAddress":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CustomerAddressUpdatePayload.self, field: fieldName, value: fieldValue)
}
return try MailingAddress(fields: value)
case "customerUserErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CustomerAddressUpdatePayload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try CustomerUserError(fields: $0) }
case "userErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CustomerAddressUpdatePayload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try UserError(fields: $0) }
default:
throw SchemaViolationError(type: CustomerAddressUpdatePayload.self, field: fieldName, value: fieldValue)
}
}
/// The customerโs updated mailing address.
open var customerAddress: Storefront.MailingAddress? {
return internalGetCustomerAddress()
}
func internalGetCustomerAddress(alias: String? = nil) -> Storefront.MailingAddress? {
return field(field: "customerAddress", aliasSuffix: alias) as! Storefront.MailingAddress?
}
/// The list of errors that occurred from executing the mutation.
open var customerUserErrors: [Storefront.CustomerUserError] {
return internalGetCustomerUserErrors()
}
func internalGetCustomerUserErrors(alias: String? = nil) -> [Storefront.CustomerUserError] {
return field(field: "customerUserErrors", aliasSuffix: alias) as! [Storefront.CustomerUserError]
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `customerUserErrors` instead.")
open var userErrors: [Storefront.UserError] {
return internalGetUserErrors()
}
func internalGetUserErrors(alias: String? = nil) -> [Storefront.UserError] {
return field(field: "userErrors", aliasSuffix: alias) as! [Storefront.UserError]
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "customerAddress":
if let value = internalGetCustomerAddress() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerUserErrors":
internalGetCustomerUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
case "userErrors":
internalGetUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
| mit | 73cc2e65c36b8f55b5c2a660447976bb | 36.850649 | 138 | 0.735289 | 4.251641 | false | false | false | false |
sxiaojian88/swift-UIView-UIScrollView-Extensions | UIViewExtension.swift | 1 | 5178 | //
// UIViewExtension.swift
// ShouViewer
//
// Created by shou.tv on 15/5/13.
// Copyright (c) 2015ๅนด shou. All rights reserved.
//
import UIKit
func CGRectGetCenter(rect :CGRect) -> CGPoint {
let x = CGRectGetMidX(rect)
let y = CGRectGetMidY(rect)
return CGPointMake(x, y)
}
extension UIView{
var width:CGFloat {
set{
var rect = self.frame as CGRect
rect.size.width = newValue
self.frame = rect
}
get{
return self.frame.size.width
}
}
var height:CGFloat {
set{
var rect = self.frame as CGRect
rect.size.height = newValue
self.frame = rect
}
get{
return self.frame.size.height
}
}
var x:CGFloat {
set{
var rect = self.frame as CGRect
rect.origin.x = newValue
self.frame = rect
}
get{
return self.frame.origin.x
}
}
var y:CGFloat {
set{
var rect = self.frame as CGRect
rect.origin.y = newValue
self.frame = rect
}
get{
return self.frame.origin.y
}
}
var centerX:CGFloat {
set{
var point = self.center
point.x = newValue
self.center = point
}
get{
return self.center.x
}
}
var centerY:CGFloat {
set{
var point = self.center
point.y = newValue
self.center = point
}
get{
return self.center.y
}
}
var left:CGFloat{
set{
var rect = self.frame as CGRect
rect.origin.x = newValue
self.frame = rect
}
get{
return self.frame.origin.x
}
}
var right:CGFloat{
set{
var rect = self.frame as CGRect
rect.origin.x = newValue - self.frame.size.width
self.frame = rect
}
get{
return self.frame.origin.x + self.frame.size.width
}
}
var top:CGFloat {
set{
var rect = self.frame as CGRect
rect.origin.y = newValue
self.frame = rect
}
get{
return self.frame.origin.y
}
}
var bottom:CGFloat {
set{
var rect = self.frame as CGRect
rect.origin.y = newValue - self.frame.size.height
self.frame = rect
}
get{
return self.frame.origin.y + self.frame.size.height
}
}
var screenViewX: CGFloat{
get{
var x :CGFloat = CGFloat()
for ( var view: UIView? = self; view != nil; view = view?.superview) {
x += view!.left;
if view!.isKindOfClass(UIScrollView) {
let scrollView = view as! UIScrollView
x -= scrollView.contentOffset.x
}
}
return x
}
}
var screenViewY: CGFloat{
get{
var y :CGFloat = CGFloat()
for ( var view: UIView? = self; view != nil; view = view?.superview) {
y += view!.left;
if view!.isKindOfClass(UIScrollView) {
let scrollView = view as! UIScrollView
y -= scrollView.contentOffset.y
}
}
return y
}
}
var screenFrame :CGRect {
get{
return CGRectMake(self.screenViewX, self.screenViewY, self.width, self.height)
}
}
var origin:CGPoint {
set{
self.frame.origin = newValue
}
get{
return self.frame.origin
}
}
var size :CGSize {
set{
self.frame.size = newValue
}
get{
return self.frame.size
}
}
func removeAllSubviews(){
while (self.subviews.count != 0){
var child:UIView = self.subviews.last as! UIView
child .removeAllSubviews()
}
}
}
extension UIScrollView{
var contentHeight : CGFloat{
get{
return self.contentSize.height
}
set{
var size = self.contentSize
size.height = newValue
self.contentSize = size
}
}
var contentWidth : CGFloat{
get{
return self.contentSize.width
}
set{
var size = self.contentSize
size.width = newValue
self.contentSize = size
}
}
var contentOffsetLeft:CGFloat {
get{
return self.contentOffset.x
}
set{
var offset = self.contentOffset
offset.x = newValue
self.contentOffset = offset
}
}
var contentOffsetTop:CGFloat {
get{
return self.contentOffset.y
}
set{
var offset = self.contentOffset
offset.y = newValue
self.contentOffset = offset
}
}
} | mit | 17a405f69bcdcb152e0a67fb169fffef | 22.531818 | 90 | 0.470634 | 4.658866 | false | false | false | false |
terietor/JSONAPIMapper | Source/MapFromJSON/RelationshipJSONObject.swift | 1 | 2651 | // Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[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.
struct RelationshipJSONObject {
let resourceType: String
let jsonField: String
let id: String
private init(resourceType: String, jsonField: String, id: String) {
self.resourceType = resourceType
self.id = id
self.jsonField = jsonField
}
static func fromJSON(_ JSON: [String : Any]) -> [RelationshipJSONObject]? {
var objects = [RelationshipJSONObject]()
for it in JSON.keys {
guard let jsonObject = JSON[it] as? [String : Any] else {
return nil
}
if
let jsonData = jsonObject["data"] as? [String : Any],
let type = jsonData["type"] as? String,
let id = jsonData["id"] as? String
{
let object = RelationshipJSONObject(
resourceType: type,
jsonField: it,
id: id
)
objects.append(object)
} else if let jsonData = jsonObject["data"] as? [[String : Any]] {
for dataItem in jsonData {
let object = RelationshipJSONObject(
resourceType: dataItem["type"] as! String,
jsonField: it,
id: dataItem["id"] as! String
)
objects.append(object)
} // end for
} // end if
} // end for keys
return objects
}
}
| mit | 3f6c7002f0089bc6842311cb623b8e8c | 37.42029 | 82 | 0.606186 | 4.855311 | false | false | false | false |
cotkjaer/SilverbackFramework | SilverbackFramework/NSManagedObject.swift | 1 | 1256 | //
// NSManagedObject.swift
// SilverbackFramework
//
// Created by Christian Otkjรฆr on 21/04/15.
// Copyright (c) 2015 Christian Otkjรฆr. All rights reserved.
//
import CoreData
extension NSManagedObject
{
public class var entityName: String
{
let fullClassName: String = NSStringFromClass(object_getClass(self))
let classNameComponents: [String] = fullClassName.characters.split
{ $0 == "." }.map { String($0) }
return classNameComponents.last!
}
public var entityName : String
{
return self.dynamicType.entityName
}
public class func fetchRequest() -> NSFetchRequest
{
return NSFetchRequest(entityName: entityName)
}
public func save() throws
{
if managedObjectContext?.hasChanges == true { try managedObjectContext?.save() }
}
public func saveIgnoringErrors()
{
if let context = managedObjectContext
{
if context.hasChanges
{
do
{
try context.save()
}
catch let e as NSError
{
debugPrint(e)
}
}
}
}
}
| mit | b1f7dfd0ca77e2de729456457563bae2 | 22.660377 | 88 | 0.54386 | 5.313559 | false | false | false | false |
milseman/swift | test/stdlib/KVOKeyPaths.swift | 14 | 2990 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
struct Guts {
var internalValue = 42
var value: Int {
get {
return internalValue
}
}
init(value: Int) {
internalValue = value
}
init() {
}
}
class Target : NSObject, NSKeyValueObservingCustomization {
// This dynamic property is observed by KVO
dynamic var objcValue: String
dynamic var objcValue2: String {
willSet {
willChangeValue(for: \.objcValue2)
}
didSet {
didChangeValue(for: \.objcValue2)
}
}
dynamic var objcValue3: String
// This Swift-typed property causes vtable usage on this class.
var swiftValue: Guts
override init() {
self.swiftValue = Guts()
self.objcValue = ""
self.objcValue2 = ""
self.objcValue3 = ""
super.init()
}
static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath> {
if (key == \Target.objcValue) {
return [\Target.objcValue2, \Target.objcValue3]
} else {
return []
}
}
static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool {
if key == \Target.objcValue2 || key == \Target.objcValue3 {
return false
}
return true
}
func print() {
Swift.print("swiftValue \(self.swiftValue.value), objcValue \(objcValue)")
}
}
class ObserverKVO : NSObject {
var target: Target?
var observation: NSKeyValueObservation? = nil
override init() { target = nil; super.init() }
func observeTarget(_ target: Target) {
self.target = target
observation = target.observe(\.objcValue) { (object, change) in
Swift.print("swiftValue \(object.swiftValue.value), objcValue \(object.objcValue)")
}
}
func removeTarget() {
observation!.invalidate()
}
}
var t2 = Target()
var o2 = ObserverKVO()
print("unobserved 2")
t2.objcValue = "one"
t2.objcValue = "two"
print("registering observer 2")
o2.observeTarget(t2)
print("Now witness the firepower of this fully armed and operational panopticon!")
t2.objcValue = "three"
t2.objcValue = "four"
t2.swiftValue = Guts(value: 13)
t2.objcValue2 = "six" //should fire
t2.objcValue3 = "nothing" //should not fire
o2.removeTarget()
t2.objcValue = "five" //make sure that we don't crash or keep posting changes if you deallocate an observation after invalidating it
print("target removed")
// CHECK: registering observer 2
// CHECK-NEXT: Now witness the firepower of this fully armed and operational panopticon!
// CHECK-NEXT: swiftValue 42, objcValue three
// CHECK-NEXT: swiftValue 42, objcValue four
// CHECK-NEXT: swiftValue 13, objcValue four
// CHECK-NEXT: swiftValue 13, objcValue four
// CHECK-NEXT: swiftValue 13, objcValue four
// CHECK-NEXT: target removed
| apache-2.0 | d37893f5b10c34f39ba9c5ae613246fb | 25.936937 | 132 | 0.634114 | 4.223164 | false | false | false | false |
illuminati-fin/LANScan-iOS | LANScan/HostCell.swift | 1 | 3763 | //
// HostCell.swift
// TestApp
//
// Created by Ville Vรคlimaa on 21/01/2017.
// Copyright ยฉ 2017 Ville Vรคlimaa. All rights reserved.
//
import UIKit
import SnapKit
class HostCell: UITableViewCell {
private let icon = with(UIImageView()) { imageView in
imageView.contentMode = UIViewContentMode.center
}
private let hostnameLabel = with(UILabel()) { label in
initLabel(label)
}
private let ipLabel = with(UILabel()) { label in
initLabel(label)
}
private let vendorLabel = with(UILabel()) { label in
initLabel(label)
label.textAlignment = NSTextAlignment.right
}
private let macLabel = with(UILabel()) { label in
initLabel(label)
label.textAlignment = NSTextAlignment.right
}
static func initLabel(_ label: UILabel) {
label.font = UIFont(name: "Press Start 2P", size: 8.0)
label.textColor = UIColor.white
label.adjustsFontSizeToFitWidth = true
label.installShadow(height: 1)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor(red:0.13, green:0.19, blue:0.25, alpha:1.0)
addSubview(icon)
addSubview(hostnameLabel)
addSubview(ipLabel)
addSubview(vendorLabel)
addSubview(macLabel)
makeConstraints()
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.frame = UIEdgeInsetsInsetRect(contentView.frame, UIEdgeInsetsMake(10, 10, 10, 10))
}
func setHostDetails(host: Host) {
hostnameLabel.text = host.hostname
ipLabel.text = host.ipAddress
macLabel.text = host.macAddress
vendorLabel.text = host.manufacturer
setCellImageNamed(name:
host.manufacturer == Constants.APPLE_COMPANY_NAME
? "apple_logo.png"
: "radio.png"
)
}
private func setCellImageNamed(name: String) {
icon.image = Utils.imageWithImage(image: UIImage(named: name)!, scaledToSize: CGSize(width: 65, height: 65))
}
private func makeConstraints() {
icon.snp.makeConstraints { (make) in
make.height.equalTo(self)
make.width.equalTo(80)
make.left.top.equalTo(self)
}
hostnameLabel.snp.makeConstraints { (make) in
make.height.equalTo(self).dividedBy(2)
make.width.equalTo(self).dividedBy(2).inset(20)
make.left.equalTo(self.icon.snp.right)
make.top.equalTo(self)
}
ipLabel.snp.makeConstraints { (make) in
make.height.equalTo(self).dividedBy(2)
make.width.equalTo(self).dividedBy(2).inset(20)
make.left.equalTo(self.icon.snp.right)
make.top.equalTo(self.hostnameLabel.snp.bottom)
}
vendorLabel.snp.makeConstraints { (make) in
make.height.equalTo(self).dividedBy(2)
make.width.equalTo(self).dividedBy(2).inset(25)
make.left.equalTo(self.hostnameLabel.snp.right)
make.right.equalTo(self).inset(10)
make.top.equalTo(self)
}
macLabel.snp.makeConstraints { (make) in
make.height.equalTo(self).dividedBy(2)
make.width.equalTo(self).dividedBy(2).inset(25)
make.left.equalTo(self.ipLabel.snp.right)
make.right.equalTo(self).inset(10)
make.top.equalTo(self.vendorLabel.snp.bottom)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | de97f56ad04acd1a33f81784d1475abf | 30.864407 | 116 | 0.608245 | 4.219978 | false | false | false | false |
vapor-community/stripe | Tests/StripeTests/PaymentSourceTests.swift | 1 | 4253 | //
// PaymentSourceTests.swift
// Stripe
//
// Created by Nicolas Bachschmidt on 2018-08-09.
//
import XCTest
@testable import Stripe
@testable import Vapor
class PaymentSourceTests: XCTestCase {
let sourceListString = """
{
"object": "list",
"total_count": 3,
"data": [
{
"id": "card_1Cs8z3GaLcnLeFWiU9SDCez8",
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "Visa",
"country": "FR",
"customer": "cus_D3t6eeIn7f2nYi",
"cvc_check": "pass",
"dynamic_last4": null,
"exp_month": 12,
"exp_year": 2029,
"fingerprint": "GhnGuMVuycvktkHE",
"funding": "credit",
"last4": "0003",
"metadata": {
},
"name": null,
"tokenization_method": null,
"type": "Visa"
},
{
"id": "src_1CxF9xGaLcnLeFWif1vfiSkS",
"object": "source",
"ach_credit_transfer": {
"account_number": "test_49b8d100bde6",
"bank_name": "TEST BANK",
"fingerprint": "0W7zV79lnzu4L4Ie",
"routing_number": "110000000",
"swift_code": "TSTEZ122"
},
"amount": null,
"client_secret": "src_client_secret_DO1CKYXtHAFzKMNPY4Fsi7d9",
"created": 1533825041,
"currency": "usd",
"flow": "receiver",
"livemode": false,
"metadata": {
},
"owner": {
"address": null,
"email": "[email protected]",
"name": null,
"phone": null,
"verified_address": null,
"verified_email": null,
"verified_name": null,
"verified_phone": null
},
"receiver": {
"address": "110000000-test_49b8d100bde6",
"amount_charged": 0,
"amount_received": 1000,
"amount_returned": 0,
"refund_attributes_method": "email",
"refund_attributes_status": "missing"
},
"statement_descriptor": null,
"status": "chargeable",
"type": "ach_credit_transfer",
"usage": "reusable"
},
{
"id": "ba_1CxEzUGaLcnLeFWiz0fJrOVm",
"object": "bank_account",
"account_holder_name": "",
"account_holder_type": "individual",
"bank_name": "STRIPE TEST BANK",
"country": "US",
"currency": "usd",
"customer": "cus_D3t6eeIn7f2nYi",
"disabled": false,
"fingerprint": "xrXW6SzxS6Gjr4d7",
"last4": "6789",
"metadata": {
},
"name": "",
"routing_number": "110000000",
"status": "new",
"validated": false,
"verified": false
}
],
"has_more": false,
"url": "/v1/customers/cus_D3t6eeIn7f2nYi/sources"
}
"""
func testSourceListIsProperlyParsed() throws {
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let body = HTTPBody(string: sourceListString)
var headers: HTTPHeaders = [:]
headers.replaceOrAdd(name: .contentType, value: MediaType.json.description)
let request = HTTPRequest(headers: headers, body: body)
let futureOrder = try decoder.decode(StripeSourcesList.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop())
futureOrder.do { list in
XCTAssertEqual(list.object, "list")
XCTAssertEqual(list.hasMore, false)
XCTAssertEqual(list.data?.count, 3)
XCTAssertEqual(list.bankAccounts?.count, 1)
XCTAssertEqual(list.cards?.count, 1)
XCTAssertEqual(list.sources?.count, 1)
XCTAssertEqual(list.data?.map { $0.id }, [
"card_1Cs8z3GaLcnLeFWiU9SDCez8",
"src_1CxF9xGaLcnLeFWif1vfiSkS",
"ba_1CxEzUGaLcnLeFWiz0fJrOVm",
])
XCTAssertEqual(list.data?.map { $0.object }, ["card", "source", "bank_account"])
}.catch { (error) in
XCTFail("\(error)")
}
}
catch {
XCTFail("\(error)")
}
}
}
| mit | bd157d4d9262ec85c5a379fa821a2054 | 28.331034 | 129 | 0.536562 | 3.506183 | false | true | false | false |
coodly/ios-gambrinus | Packages/Sources/KioskCore/Persistence/Persistence+SyncStatuses.swift | 1 | 1937 | /*
* Copyright 2018 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import CoreData
private extension NSPredicate {
static let syncable = NSCompoundPredicate(andPredicateWithSubpredicates: [
NSPredicate(format: "syncNeeded = YES"),
NSPredicate(format: "syncFailed = NO")
])
static let waitingSync = NSCompoundPredicate(andPredicateWithSubpredicates: [
NSPredicate(format: "syncStatus.syncNeeded = YES"),
NSPredicate(format: "syncStatus.syncFailed = NO")
])
}
extension NSManagedObjectContext {
internal func fetchedControllerForStatusesNeedingSync() -> NSFetchedResultsController<SyncStatus> {
let sort = NSSortDescriptor(key: "syncNeeded", ascending: true)
return fetchedController(predicate: .syncable, sort: [sort])
}
internal func isMissingDetails<T: Syncable>(for type: T.Type) -> Bool {
return count(instancesOf: T.self, predicate: .waitingSync) != 0
}
internal func itemsNeedingSync<T: Syncable>(for type: T.Type) -> [T] {
return fetch(predicate: .waitingSync, limit: 100)
}
public func resetFailedStatuses() {
let failedPredicate = NSPredicate(format: "syncFailed = YES")
let failed: [SyncStatus] = fetch(predicate: failedPredicate)
Log.debug("Have \(failed.count) failed syncs")
failed.forEach({ $0.syncFailed = false })
}
}
| apache-2.0 | 8691a7f4fb1b5cb15e495739ac34f738 | 36.25 | 103 | 0.7016 | 4.483796 | false | false | false | false |
mumbler/PReVo-iOS | DatumbazKonstruilo/DatumbazKonstruilo/XMLLegiloj (provaj, ne uzataj)/ArtikoloXMLLegilo.swift | 1 | 2326 | //
// ArtikoloXMLLegilo.swift
// DatumbazKonstruilo
//
// Created by Robin Hill on 3/16/20.
// Copyright ยฉ 2020 Robin Hill. All rights reserved.
//
import Foundation
import CoreData
class ArtikoloXMLLegilo: NSObject, XMLParserDelegate {
private let konteksto: NSManagedObjectContext
init(_ konteksto: NSManagedObjectContext) {
self.konteksto = konteksto
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
}
}
// MARK: - Vokilo
extension ArtikoloXMLLegilo {
public static func legiDosierujon(_ ujoURL: URL, radikoURL: String, enKontekston konteksto: NSManagedObjectContext) -> [String] {
// Enlegi literojn
print("Eklegas literojn")
if let literoURL = Bundle.main.url(forResource: radikoURL + "cfg/literoj", withExtension: "xml") {
let literoj = LiteroXMLLegilo.legiDosieron(literoURL, enKontekston: konteksto)
print("Finis literolegadon. Trovis X literojn.")
} else {
print("Eraro: ne trovis litero-dosieron")
}
do {
let artikoloURLoj = try FileManager.default.contentsOfDirectory(at: ujoURL,
includingPropertiesForKeys: nil,
options: .skipsSubdirectoryDescendants)
print("Trovis \(artikoloURLoj.count) artikolojn")
for artikoloURL in artikoloURLoj {
let artikoloLegilo = ArtikoloXMLLegilo(konteksto)
if let parser = XMLParser(contentsOf: artikoloURL) {
parser.delegate = artikoloLegilo
parser.parse()
}
}
return ["OK"]
} catch {
print("Eraro: Ne trovis artikol-dosierujon")
}
return [String]()
}
}
| mit | fa6b7fff162c2fd73e310faf4e0646c2 | 32.214286 | 179 | 0.572043 | 4.454023 | false | false | false | false |
maxim-pervushin/HyperHabit | HyperHabit/HyperHabit/Themes/ThemeManager.swift | 1 | 9136 | //
// Created by Maxim Pervushin on 15/12/15.
// Copyright (c) 2015 Maxim Pervushin. All rights reserved.
//
import UIKit
class ThemeManager {
// MARK: ThemeManager public
static let changedNotification = "ThemeManagerChangedNotification"
var themes: [Theme] {
return [
defaultTheme,
Theme(identifier: "cold",
name: "Cold",
dark: false,
backgroundColor: UIColor(red:0.93, green:0.94, blue:0.95, alpha:1),
foregroundColor: UIColor(red:0.17, green:0.24, blue:0.32, alpha:1)
),
Theme(identifier: "sepia",
name: "Sepia",
dark: false,
backgroundColor: UIColor(red: 0.98, green: 0.96, blue: 0.91, alpha: 1),
foregroundColor: UIColor(red: 0.38, green: 0.24, blue: 0.13, alpha: 1)
),
Theme(identifier: "gray",
name: "Gray",
dark: true,
backgroundColor: UIColor(red: 0.25, green: 0.25, blue: 0.25, alpha: 1),
foregroundColor: UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1)
),
Theme(identifier: "dark",
name: "Dark",
dark: true,
backgroundColor: UIColor(red: 0.05, green: 0.05, blue: 0.05, alpha: 1),
foregroundColor: UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
),
// Theme(identifier: "debug",
// name: "Debug",
// dark: true,
// backgroundColor: UIColor(red: 0.25, green: 0.25, blue: 0.25, alpha: 1),
// foregroundColor: UIColor(red: 0.95, green: 0, blue: 0, alpha: 1)
// ),
]
}
let defaultTheme = Theme(identifier: "light",
name: "Light",
dark: false,
backgroundColor: UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1),
foregroundColor: UIColor(red: 0.05, green: 0.05, blue: 0.05, alpha: 1)
)
var theme: Theme {
didSet {
update()
}
}
func update() {
// UIView.appearance().tintColor = theme.foregroundColor
// Navigation bars
let titleTextAttributes = [
NSForegroundColorAttributeName: theme.foregroundColor,
]
UINavigationBar.appearance().tintColor = theme.foregroundColor
UINavigationBar.appearance().barStyle = theme.barStyle
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(theme.topBarBackgroundImage, forBarPosition: .Any, barMetrics: .Default)
UINavigationBar.appearance().barTintColor = theme.backgroundColor
UINavigationBar.appearance().titleTextAttributes = titleTextAttributes
// Tab bars
UITabBar.appearance().tintColor = theme.foregroundColor
UITabBar.appearance().barStyle = theme.barStyle
UITabBar.appearance().shadowImage = UIImage()
UITabBar.appearance().backgroundImage = theme.bottomBarBackgroundImage
UITabBar.appearance().barTintColor = theme.backgroundColor
// Table views
UITableView.appearance().backgroundColor = theme.backgroundColor
UITableView.appearance().separatorColor = theme.foregroundColor.colorWithAlphaComponent(0.33)
// Table view cells
UITableViewCell.appearance().backgroundColor = UIColor.clearColor()
// Table view header footer views
UIView.appearanceWhenContainedInInstancesOfClasses([UITableViewHeaderFooterView.self]).backgroundColor = theme.backgroundColor
UILabel.appearanceWhenContainedInInstancesOfClasses([UITableViewHeaderFooterView.self]).textColor = theme.foregroundColor
UILabel.appearanceWhenContainedInInstancesOfClasses([UITableViewCell.self]).textColor = theme.foregroundColor
// Button
Button.appearance().backgroundColor = theme.backgroundColor.colorWithAlphaComponent(0.5)
Button.appearance().setTitleColor(theme.textColor, forState: .Normal)
Button.appearance().setTitleColor(theme.inactiveTextColor, forState: .Disabled)
Button.appearance().tintColor = theme.foregroundColor
// ClearButton
ClearButton.appearance().backgroundColor = UIColor.clearColor()
ClearButton.appearance().setTitleColor(theme.textColor, forState: .Normal)
ClearButton.appearance().setTitleColor(theme.inactiveTextColor, forState: .Disabled)
ClearButton.appearance().tintColor = theme.foregroundColor
// UIButton.appearance().backgroundColor = UIColor.clearColor()
// UIButton.appearance().setTitleColor(theme.textColor, forState: .Normal)
// UIButton.appearance().setTitleColor(theme.inactiveTextColor, forState: .Disabled)
// Label
Label.appearance().textColor = theme.foregroundColor
// BackgroundView
BackgroundView.appearance().tintColor = theme.foregroundColor
BackgroundView.appearance().backgroundColor = theme.backgroundColor
UILabel.appearanceWhenContainedInInstancesOfClasses([BackgroundView.self]).textColor = theme.foregroundColor
// BackgroundImageView
BackgroundImageView.appearance().tintColor = theme.foregroundColor
BackgroundImageView.appearance().backgroundColor = theme.backgroundColor
UILabel.appearanceWhenContainedInInstancesOfClasses([BackgroundImageView.self]).textColor = theme.foregroundColor
// TintView
TintView.appearance().backgroundColor = theme.foregroundColor.colorWithAlphaComponent(0.5)
// LineView
LineView.appearance().backgroundColor = theme.foregroundColor.colorWithAlphaComponent(0.25)
LineCollectionReusableView.appearance().backgroundColor = UIColor.clearColor()
// UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = theme.foregroundColor.colorWithAlphaComponent(0.5)
// UIButton.appearanceWhenContainedInInstancesOfClasses([BackgroundImageView.self]).backgroundColor = theme.backgroundColor.colorWithAlphaComponent(0.5)
// TextField
TextField.appearance().textColor = theme.foregroundColor
TextField.appearance().placeholderTextColor = theme.foregroundColor.colorWithAlphaComponent(0.25)
TextField.appearance().backgroundColor = UIColor.clearColor()
// Cells
ReportCell.appearance().tintColor = theme.foregroundColor
// MXCalendarView
MXDayCell.appearance().defaultTextColor = theme.foregroundColor
MXDayCell.appearance().defaultBackgroundColor = UIColor.clearColor()
MXDayCell.appearance().todayDateTextColor = theme.foregroundColor
MXDayCell.appearance().todayDateBackgroundColor = theme.foregroundColor.colorWithAlphaComponent(0.15)
MXDayCell.appearance().selectedDateTextColor = theme.foregroundColor
MXDayCell.appearance().selectedDateBackgroundColor = theme.foregroundColor.colorWithAlphaComponent(0.35)
MXAccessoryView.appearance().activeSegmentColor = theme.foregroundColor
MXAccessoryView.appearance().inactiveSegmentColor = UIColor.clearColor()
MXInactiveDayCell.appearance().defaultTextColor = theme.foregroundColor.colorWithAlphaComponent(0.35)
MXInactiveDayCell.appearance().defaultBackgroundColor = UIColor.clearColor()
// Hack to apply new appearance immediately
for window in UIApplication.sharedApplication().windows {
for subview in window.subviews {
subview.removeFromSuperview()
window.addSubview(subview)
}
}
NSNotificationCenter.defaultCenter().postNotificationName(ThemeManager.changedNotification, object: self, userInfo: nil)
saveDefaults()
}
private func saveDefaults() {
NSUserDefaults.standardUserDefaults().setObject(theme.identifier, forKey: "themeIdentifier")
NSUserDefaults.standardUserDefaults().synchronize()
}
private func loadDefaults() {
if let themeIdentifier = NSUserDefaults.standardUserDefaults().stringForKey("themeIdentifier") {
var currentTheme = defaultTheme
for theme in themes {
if theme.identifier == themeIdentifier {
currentTheme = theme
break
}
}
theme = currentTheme
} else {
theme = defaultTheme
}
}
init() {
theme = defaultTheme
loadDefaults()
}
@objc private func timeout(sender: AnyObject?) {
nextTheme()
}
private var currentThemeIndex = 0
private var timer: NSTimer!
func nextTheme() {
currentThemeIndex++
if currentThemeIndex >= themes.count {
currentThemeIndex = 0
}
theme = themes[currentThemeIndex]
}
}
| mit | 9f37124b2568473ae3eb80843f898fbc | 41.296296 | 159 | 0.646454 | 5.530266 | false | false | false | false |
volodg/iAsync.network | Pods/iAsync.async/Lib/CachedAsyncOperations/JCachedAsync.swift | 2 | 12508 | //
// JCachedAsync.swift
// JAsync
//
// Created by Vladimir Gorbenko on 12.06.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
import iAsync_utils
public enum CachedAsyncTypes<Value>
{
public typealias JResultSetter = (value: Value) -> ()
public typealias JResultGetter = () -> Value?
}
//TODO20 test immediately cancel
//TODO20 test cancel calback for each observer
public class JCachedAsync<Key: Hashable, Value> {
public init() {}
private var delegatesByKey = [Key:ObjectRelatedPropertyData<Value>]()
//type PropertyExtractorType = PropertyExtractor[Key, Value]
private typealias PropertyExtractorType = PropertyExtractor<Key, Value>
//func clearDelegates(delegates: mutable.ArrayBuffer[CallbacksBlocksHolder[Value]]) {
private func clearDelegates(delegates: [CallbacksBlocksHolder<Value>]) {
for callbacks in delegates {
callbacks.clearCallbacks()
}
}
private func clearDataForPropertyExtractor(propertyExtractor: PropertyExtractorType) {
if propertyExtractor.cacheObject == nil {
return
}
propertyExtractor.clearDelegates()
propertyExtractor.setLoaderHandler(nil)
propertyExtractor.setAsyncLoader (nil)
propertyExtractor.clear()
}
private func cancelBlock(propertyExtractor: PropertyExtractorType, callbacks: CallbacksBlocksHolder<Value>) -> JAsyncHandler {
return { (task: JAsyncHandlerTask) -> () in
if propertyExtractor.cleared {
return
}
let handlerOption = propertyExtractor.getLoaderHandler()
if let handler = handlerOption {
switch task {
case .UnSubscribe:
let didLoadDataBlock = callbacks.finishCallback
propertyExtractor.removeDelegate(callbacks)
callbacks.clearCallbacks()
didLoadDataBlock?(result: JResult.error(JAsyncFinishedByUnsubscriptionError()))
case .Cancel:
handler(task: .Cancel)
self.clearDataForPropertyExtractor(propertyExtractor)//TODO should be already cleared here in finish callback
case .Suspend, .Resume:
propertyExtractor.eachDelegate({(callback: CallbacksBlocksHolder<Value>) -> () in
if let onState = callback.stateCallback {
let state = task == .Resume
?JAsyncState.Resumed
:JAsyncState.Suspended
onState(state: state)
}
})
default:
fatalError("unsupported type")
}
}
}
}
private func doneCallbackBlock(propertyExtractor: PropertyExtractorType) -> JAsyncTypes<Value>.JDidFinishAsyncCallback {
return { (result: JResult<Value>) -> () in
//TODO test this if
//may happen when cancel
if propertyExtractor.cacheObject == nil {
return
}
result.onValue { value -> Void in
propertyExtractor.setterOption?(value: value)
}
let copyDelegates = propertyExtractor.copyDelegates()
self.clearDataForPropertyExtractor(propertyExtractor)
for callbacks in copyDelegates {
callbacks.finishCallback?(result: result)
callbacks.clearCallbacks()
}
}
}
private func performNativeLoader(
propertyExtractor: PropertyExtractorType,
callbacks: CallbacksBlocksHolder<Value>) -> JAsyncHandler
{
func progressCallback(progressInfo: AnyObject) {
propertyExtractor.eachDelegate({(delegate: CallbacksBlocksHolder<Value>) -> () in
delegate.progressCallback?(progressInfo: progressInfo)
return
})
}
let doneCallback = doneCallbackBlock(propertyExtractor)
func stateCallback(state: JAsyncState) {
propertyExtractor.eachDelegate({(delegate: CallbacksBlocksHolder<Value>) -> () in
delegate.stateCallback?(state: state)
return
})
}
let loader = propertyExtractor.getAsyncLoader()
let handler = loader!(
progressCallback: progressCallback,
stateCallback: stateCallback,
finishCallback: doneCallback)
if propertyExtractor.cacheObject == nil {
return jStubHandlerAsyncBlock
}
propertyExtractor.setLoaderHandler(handler)
return cancelBlock(propertyExtractor, callbacks: callbacks)
}
public func isLoadingDataForUniqueKey(uniqueKey: Key) -> Bool {
let resultOption = delegatesByKey[uniqueKey]
return resultOption != nil
}
public var hasLoadingData: Bool {
return delegatesByKey.count != 0
}
public func asyncOpMerger(loader: JAsyncTypes<Value>.JAsync, uniqueKey: Key) -> JAsyncTypes<Value>.JAsync {
return asyncOpWithPropertySetter(nil, getter: nil, uniqueKey: uniqueKey, loader: loader)
}
public func asyncOpWithPropertySetter(
setter: CachedAsyncTypes<Value>.JResultSetter?,
getter: CachedAsyncTypes<Value>.JResultGetter?,
uniqueKey: Key,
loader: JAsyncTypes<Value>.JAsync) -> JAsyncTypes<Value>.JAsync
{
return { (
progressCallback: JAsyncProgressCallback?,
stateCallback : JAsyncChangeStateCallback?,
finishCallback : JAsyncTypes<Value>.JDidFinishAsyncCallback?) -> JAsyncHandler in
let propertyExtractor = PropertyExtractorType(setter : setter,
getter : getter,
cacheObject: self,
uniqueKey : uniqueKey,
loader : loader)
if let result = propertyExtractor.getAsyncResult() {
finishCallback?(result: JResult.value(result))
propertyExtractor.clear()
return jStubHandlerAsyncBlock
}
let callbacks = CallbacksBlocksHolder(progressCallback: progressCallback, stateCallback: stateCallback, finishCallback: finishCallback)
let hasDelegates = propertyExtractor.hasDelegates()
propertyExtractor.addDelegate(callbacks)
return hasDelegates
?self.cancelBlock(propertyExtractor, callbacks: callbacks)
:self.performNativeLoader(propertyExtractor, callbacks: callbacks)
}
}
}
private class ObjectRelatedPropertyData<T>
{
//var delegates : mutable.ArrayBuffer[CallbacksBlocksHolder[T]] = null
var delegates = [CallbacksBlocksHolder<T>]()
var loaderHandler: JAsyncHandler?
//var asyncLoader : Async[T] = null
var asyncLoader : JAsyncTypes<T>.JAsync?
func copyDelegates() -> [CallbacksBlocksHolder<T>] {
let result = delegates.map({ (callbacks: CallbacksBlocksHolder<T>) -> CallbacksBlocksHolder<T> in
return CallbacksBlocksHolder(
progressCallback: callbacks.progressCallback,
stateCallback : callbacks.stateCallback ,
finishCallback : callbacks.finishCallback)
})
return result
}
func clearDelegates() {
for callbacks in delegates {
callbacks.clearCallbacks()
}
delegates.removeAll(keepCapacity: false)
}
func eachDelegate(block: (obj: CallbacksBlocksHolder<T>) -> ()) {
for element in delegates {
block(obj: element)
}
}
func hasDelegates() -> Bool {
return delegates.count > 0
}
//func getDelegates: mutable.ArrayBuffer[CallbacksBlocksHolder[ValueT]] = {
func addDelegate(delegate: CallbacksBlocksHolder<T>) {
delegates.append(delegate)
}
func removeDelegate(delegate: CallbacksBlocksHolder<T>) {
for (index, callbacks) in enumerate(delegates) {
if delegate === callbacks {
delegates.removeAtIndex(index)
break
}
}
}
}
private class CallbacksBlocksHolder<T>
{
var progressCallback: JAsyncProgressCallback?
var stateCallback : JAsyncChangeStateCallback?
var finishCallback : JAsyncTypes<T>.JDidFinishAsyncCallback?
init(progressCallback: JAsyncProgressCallback?,
stateCallback : JAsyncChangeStateCallback?,
finishCallback : JAsyncTypes<T>.JDidFinishAsyncCallback?)
{
self.progressCallback = progressCallback
self.stateCallback = stateCallback
self.finishCallback = finishCallback
}
func clearCallbacks() {
progressCallback = nil
stateCallback = nil
finishCallback = nil
}
}
private class PropertyExtractor<KeyT: Hashable, ValueT> {
var cleared = false
var setterOption: CachedAsyncTypes<ValueT>.JResultSetter?
var getterOption: CachedAsyncTypes<ValueT>.JResultGetter?
var cacheObject : JCachedAsync<KeyT, ValueT>?
var uniqueKey : KeyT
init(
setter : CachedAsyncTypes<ValueT>.JResultSetter?,
getter : CachedAsyncTypes<ValueT>.JResultGetter?,
cacheObject: JCachedAsync<KeyT, ValueT>,
uniqueKey : KeyT,
loader : JAsyncTypes<ValueT>.JAsync)
{
self.setterOption = setter
self.getterOption = getter
self.cacheObject = cacheObject
self.uniqueKey = uniqueKey
setAsyncLoader(loader)
}
//private def getObjectRelatedPropertyData: ObjectRelatedPropertyData[ValueT] = {
func getObjectRelatedPropertyData() -> ObjectRelatedPropertyData<ValueT>
{
let resultOption = cacheObject!.delegatesByKey[uniqueKey]
if let result = resultOption {
return result
}
let result = ObjectRelatedPropertyData<ValueT>()
cacheObject!.delegatesByKey[uniqueKey] = result
return result
}
func copyDelegates() -> [CallbacksBlocksHolder<ValueT>] {
return getObjectRelatedPropertyData().copyDelegates()
}
func eachDelegate(block: (obj: CallbacksBlocksHolder<ValueT>) -> ()) {
return getObjectRelatedPropertyData().eachDelegate(block)
}
func hasDelegates() -> Bool {
return getObjectRelatedPropertyData().hasDelegates()
}
func clearDelegates() {
getObjectRelatedPropertyData().clearDelegates()
}
//func getDelegates: mutable.ArrayBuffer[CallbacksBlocksHolder[ValueT]] = {
func addDelegate(delegate: CallbacksBlocksHolder<ValueT>) {
getObjectRelatedPropertyData().addDelegate(delegate)
}
func removeDelegate(delegate: CallbacksBlocksHolder<ValueT>) {
getObjectRelatedPropertyData().removeDelegate(delegate)
}
func getLoaderHandler() -> JAsyncHandler? {
return getObjectRelatedPropertyData().loaderHandler
}
func setLoaderHandler(handler: JAsyncHandler?) {
getObjectRelatedPropertyData().loaderHandler = handler
}
//def getAsyncLoader: Async[ValueT] =
func getAsyncLoader() -> JAsyncTypes<ValueT>.JAsync? {
return getObjectRelatedPropertyData().asyncLoader
}
//def setAsyncLoader(loader: Async[ValueT])
func setAsyncLoader(loader: JAsyncTypes<ValueT>.JAsync?) {
getObjectRelatedPropertyData().asyncLoader = loader
}
func getAsyncResult() -> ValueT? {
return getterOption?()
}
func clear() {
if cleared {
return
}
cacheObject!.delegatesByKey.removeValueForKey(uniqueKey)
setterOption = nil
getterOption = nil
cacheObject = nil
cleared = true
}
}
| mit | db63e7ec99470332798c56deccc06782 | 31.915789 | 147 | 0.601455 | 5.370545 | false | false | false | false |
the-grid/Portal | Portal/Models/BlockType.swift | 1 | 542 | import Argo
import Ogra
/// A content block type.
public enum BlockType: String {
case Audio = "audio"
case Article = "article"
case Code = "code"
case CTA = "cta"
case H1 = "h1"
case H2 = "h2"
case H3 = "h3"
case H4 = "h4"
case H5 = "h5"
case H6 = "h6"
case Image = "image"
case Location = "location"
case Quote = "quote"
case Text = "text"
case Video = "video"
}
// MARK: - Decodable
extension BlockType: Decodable {}
// MARK: - Encodable
extension BlockType: Encodable {}
| mit | 208736340e150731e6e4524f103d7696 | 16.483871 | 33 | 0.586716 | 3.188235 | false | false | false | false |
chrisjmendez/swift-exercises | Games/Timer/Timer/GameScene.swift | 1 | 1752 | //
// GameScene.swift
// Timer
//
// Created by Chris on 2/17/16.
// Copyright (c) 2016 Chris Mendez. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var timer:CountdownTimer?
override func didMoveToView(view: SKView) {
/*
let demoURL = NSBundle.mainBundle().URLForResource("demo", withExtension: "rtf")!
let attrStr = try? NSAttributedString(fileURL: demoURL, options: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType], documentAttributes: nil)
let myLabel = ASAttributedLabelNode(size: self.size)
myLabel.attributedString = attrStr
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(myLabel)
*/
timer = ASAttributedLabelNode(size: self.frame.size) as! CountdownTimer
timer?.createAttributedString("chris")
timer?.startWithDuration(3)
timer?.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
/*
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "Hello, World!"
myLabel.fontSize = 45
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
self.addChild(myLabel)
*/
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
//print(timer?.hasFinished())
timer?.update()
}
}
| mit | 4c44909c2c258802a23653407f849c7e | 30.854545 | 155 | 0.632991 | 4.709677 | false | false | false | false |
CoBug92/MyRestaurant | MyRestraunts/MapRestaurantsLocationViewController.swift | 1 | 3241 | //
// MapRestaurantsLocationViewController.swift
// MyRestaurant
//
// Created by ะะพะณะดะฐะฝ ะะพััััะตะฝะบะพ on 11/10/16.
// Copyright ยฉ 2016 Bogdan Kostyuchenko. All rights reserved.
//
import UIKit
import MapKit
class MapRestaurantsLocationViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var restaurant: Restaurant!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
//ั ะฟะพะผะพััั ััะพะณะพ ะธะท ัะตะบััะฐ ะฒ ัะธัะธะฝั ะธ ะดะพะปะณะพัั ะธ ะฝะฐะพะฑะพัั
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(restaurant.location!, completionHandler: { placemarks, error in
//ะตัะปะธ ะพัะธะฑะบะธ = 0 ัะพ ะฒัะฟะพะปะฝัะผ ะบะพะด ะดะฐะปััะต
guard error == nil else { return }
//ะทะฐะฟะธััะฒะฐะตะผ ะฝะฐั ะพะฟัะธะพะฝะฐะปัะฝัะน ะผะฐััะธะฒ ะฒ ะดััะณะพะน ะผะฐััะธะฒ
guard let placemarks = placemarks else { return }
let placemark = placemarks.first!
//add annotation
let annotation = MKPointAnnotation()
annotation.title = self.restaurant.name
annotation.subtitle = self.restaurant.location
//ะตัะปะธ ะฝะตั ัะฐะบะพะณะพ ะฐะดัะตัะฐ ัะพ ะดะฐะปััะต ะบะพะด ะฝะต ััะฐะฑะพัะฐะตั
guard let location = placemark.location else { return }
annotation.coordinate = location.coordinate
//ะพัะพะฑัะฐะถะฐะตะผ ะฐะฝะฝะพัะฐัะธะธ
self.mapView.showAnnotations([annotation], animated: true)
self.mapView.selectAnnotation(annotation, animated: true)
})
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
//ะฟัะพะฒะตััะตะผ ัะฒะปัะตััั ะปะธ ะฐะฝะฝะพัะฐัะธั ะผะตััะพะผะฟะพะปะพะถะตะฝะธั
guard !(annotation is MKUserLocation) else { return nil }
//ะดะพะฑะฐะฒัะปะตะผ ะฐะฝะฝะพัะฐัะธะพะฝะฝัะน ะฒะธะด. MKPinAnnotationView - ะดะพะฑะฐะฒะปัะตั ะธะณะพะปะบั
let annotationIdentifier = "CurrentPin"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) as? MKPinAnnotationView
//ะตัะปะธ ะฝะต ะฟะพะปััะฐะตััั ะฟะตัะตะธัะฟะพะปัะทะพะฒะฐัั ะฐะฝะฝะพัะฐัะธะธ ัะพ ัะพะทะดะฐะตะผ ะฒัััะฝัั
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
//ะผะพะถะฝะพ ะพัะพะฑัะฐะทะธัั ะดะพะฟ ะธะฝัะพัะผะฐัะธั
annotationView?.canShowCallout = true
}
//Add image
let leftImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
leftImage.image = UIImage(data: restaurant.image as! Data)
annotationView?.leftCalloutAccessoryView = leftImage
//ะธะทะผะตะฝัะตะผ ัะฒะตั ะธะณะพะปะบะธ
annotationView?.pinTintColor = #colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)
return annotationView
}
}
| gpl-3.0 | eade79a0d9b9e3a0ce9996c81f506f6d | 38.736111 | 128 | 0.652919 | 4.5776 | false | false | false | false |
cabarique/TheProposalGame | MyProposalGame/Libraries/SKUtils/ASAttributedLabelNode.swift | 1 | 1805 | //
// ASAttributedLabelNode.swift
//
// Created by Alex Studnicka on 15/08/14.
// Copyright ยฉ 2016 Alex Studnicka. MIT License.
//
import UIKit
import SpriteKit
class ASAttributedLabelNode: SKSpriteNode {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(size: CGSize) {
super.init(texture: nil, color: .clearColor(), size: size)
}
var attributedString: NSAttributedString! {
didSet {
draw()
}
}
func draw() {
guard let attrStr = attributedString else {
texture = nil
return
}
let scaleFactor = UIScreen.mainScreen().scale
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGImageAlphaInfo.PremultipliedLast.rawValue
guard let context = CGBitmapContextCreate(nil, Int(size.width * scaleFactor), Int(size.height * scaleFactor), 8, Int(size.width * scaleFactor) * 4, colorSpace, bitmapInfo) else {
return
}
CGContextScaleCTM(context, scaleFactor, scaleFactor)
CGContextConcatCTM(context, CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height))
UIGraphicsPushContext(context)
let strHeight = attrStr.boundingRectWithSize(size, options: .UsesLineFragmentOrigin, context: nil).height
let yOffset = (size.height - strHeight) / 2.0
attrStr.drawWithRect(CGRect(x: 0, y: yOffset, width: size.width, height: strHeight), options: .UsesLineFragmentOrigin, context: nil)
if let imageRef = CGBitmapContextCreateImage(context) {
texture = SKTexture(CGImage: imageRef)
} else {
texture = nil
}
UIGraphicsPopContext()
}
}
| mit | c97f4588023b54c2fcd8b9621acbf92d | 31.214286 | 186 | 0.618625 | 4.810667 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/AppDelegate.swift | 1 | 8555 | //
// AppDelegate.swift
// selluv-ios
//
// Created by ์กฐ๋ฐฑ๊ทผ on 2016. 10. 25..
// Copyright ยฉ 2016๋
BitBoy Labs. All rights reserved.
//
import UIKit
import UserNotifications
import FacebookCore
import SwiftyUserDefaults
import SwiftMoment
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//test
Sample.shared.apiCheck()
_ = BBNetworkReachability.shared
//๋ฒ์ ์ ๋ณด๋ฅผ ์ฒดํฌํ๋ค.
VersionModel.shared.versionCheck(
updateBlock: { sorting in
let updates = sorting["update"] as! [String]
if updates.count > 0 {
if updates.contains("categories") == true {//์นดํ
๊ณ ๋ฆฌ ์ ๋ณด ์ฒดํฌ
CategoryModel.shared.categoryCheck()
}
if updates.contains("brands") == true {
BrandModel.shared.brandCheck()
}
if updates.contains("codes") == true {
CodeModel.shared.codeCheck()
}
}
}, skipBlock: { sorting in
let skips = sorting["skip"] as! [String]
if skips.count > 0 {
if skips.contains("categories") == true {//์นดํ
๊ณ ๋ฆฌ ์ ๋ณด ์ฒดํฌ
CategoryModel.shared.loadCategory()
}
if skips.contains("brands") == true {
BrandModel.shared.loadBrands()
}
if skips.contains("codes") == true {
CodeModel.shared.loadCodes()
}
}
})
//๋ก์ปฌ ip ํผํฌ๋จผ์ค ์ด์๋ก ์์๋ก ์ด๋ ๊ฒ ์นดํ
๊ณ ๋ฆฌ ๋ก๋ํ์....
// CategoryModel.shared.loadCategory()
// BrandModel.shared.loadBrands()
// CodeModel.shared.loadCodes()
//์ฌ์ด์ฆํ ์ต์ด ์คํ์ ๋ก๋
ClothingSizeConvertInfoSetter.shared.setup()
//FaceBook
SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
//Push Notification
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
//etc
SLVTabBarController.myAppearance()
return true
}
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return .portrait
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
KOSession.handleDidEnterBackground()
}
func applicationWillEnterForeground(_ application: UIApplication) {
KOSession.handleDidBecomeActive()
}
func applicationDidBecomeActive(_ application: UIApplication) {
AppEventsLogger.activate(application)
}
func applicationWillTerminate(_ application: UIApplication) {
}
//MAKR: push
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
log.debug("Message ID: \(userInfo["gcm.message_id"]!)")
log.debug(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
log.debug("Message ID: \(userInfo["gcm.message_id"]!)")
log.debug(userInfo)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
log.debug("Unable to register for remote notifications: \(error.localizedDescription)")
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the InstanceID token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
log.debug("APNs token retrieved: \(deviceToken)")
let token = self.convertTokenStringFrom(deviceToken: deviceToken as NSData)
let loadToken = Defaults[.remoteTokenKey]
if loadToken != token {
Defaults[.remoteTokenKey] = token
}
}
//MARK: open url
public func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
let yes = self.checkURL(url: url)
if yes == false {
let result = SDKApplicationDelegate.shared.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
return result
}
return yes
}
func checkURL(url: URL) -> Bool {
log.debug("url : " + url.description)
log.debug("scheme: " + url.scheme!)
let host = url.host
let scheme = url.scheme
//1. naver
if scheme == NaverScheme {
if host == kCheckResultPage {
let naver = NaverThirdPartyLoginConnection.getSharedInstance()
let result = naver?.receiveAccessToken(url) as! Int
let success = 0//.SUCCESS
if result == success {
return true
}
}
}
else if KOSession.isKakaoAccountLoginCallback(url) {
return KOSession.handleOpen(url)
}
return false
}
public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
let yes = self.checkURL(url: url)
if yes == false {
let result = SDKApplicationDelegate.shared.application(app, open: url, options: options)
return result
}
return yes
}
func readyNaver() {
let naver = NaverThirdPartyLoginConnection.getSharedInstance()
naver?.serviceUrlScheme = NaverScheme
naver?.consumerKey = NaverClientId
naver?.consumerSecret = NaverClientSecret
naver?.appName = "์
๋ฝ"
}
private func convertTokenStringFrom(deviceToken:NSData) -> String {
let description = deviceToken.description.replacing(">", with: "").replacing("<", with: "").replacing(" ", with: "").uppercased()
return description
}
}
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
log.debug("Message ID: \(userInfo["gcm.message_id"]!)")
log.debug(userInfo)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
log.debug("Message ID: \(userInfo["gcm.message_id"]!)")
log.debug(userInfo)
}
}
| mit | d94cf44ffeb341ce82fa9640f1581d20 | 37.820276 | 207 | 0.620489 | 5.291457 | false | false | false | false |
guardianproject/poe | POE/Classes/UIColor+POE.swift | 1 | 1085 | //
// UIColor+POE.swift
// POE
//
// Created by Benjamin Erhart on 09.10.19.
//
import UIKit
public extension UIColor {
/**
Background, dark purple, code #3F2B4F
*/
@objc
static var poeAccent = UIColor(named: "Accent", in: XibViewController.getBundle(), compatibleWith: nil)
/**
Intro progress bar background, darker purple, code #352144
*/
@objc
static var poeAccentDark = UIColor(named: "AccentDark", in: XibViewController.getBundle(), compatibleWith: nil)
/**
Background for connecting view, light Tor purple, code #A577BB
*/
@objc
static var poeAccentLight = UIColor(named: "AccentLight", in: XibViewController.getBundle(), compatibleWith: nil)
/**
Red error view background, code #FB5427
*/
@objc
static var poeError = UIColor.init(named: "Error", in: XibViewController.getBundle(), compatibleWith: nil)
/**
Green connected indicator line, code #7ED321
*/
@objc
static var poeOk = UIColor(named: "Ok", in: XibViewController.getBundle(), compatibleWith: nil)
}
| bsd-3-clause | f49e1df1a96e5a9900b02de5360adfcd | 25.463415 | 117 | 0.660829 | 3.959854 | false | false | false | false |
karimsallam/Reactive | Pods/ReactiveSwift/Sources/Flatten.swift | 2 | 34963 | //
// Flatten.swift
// ReactiveSwift
//
// Created by Neil Pankey on 11/30/15.
// Copyright ยฉ 2015 GitHub. All rights reserved.
//
import enum Result.NoError
/// Describes how multiple producers should be joined together.
public enum FlattenStrategy: Equatable {
/// The producers should be merged, so that any value received on any of the
/// input producers will be forwarded immediately to the output producer.
///
/// The resulting producer will complete only when all inputs have
/// completed.
case merge
/// The producers should be concatenated, so that their values are sent in
/// the order of the producers themselves.
///
/// The resulting producer will complete only when all inputs have
/// completed.
case concat
/// Only the events from the latest input producer should be considered for
/// the output. Any producers received before that point will be disposed
/// of.
///
/// The resulting producer will complete only when the producer-of-producers
/// and the latest producer has completed.
case latest
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` or an active inner producer fails, the returned
/// signal will forward that failure immediately.
///
/// - note: `interrupted` events on inner producers will be treated like
/// `Completed events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If an active inner producer fails, the returned signal will
/// forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - note: If `producer` or an active inner producer fails, the returned
/// producer will forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - note: If an active inner producer fails, the returned producer will
/// forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProtocol where Value: SignalProtocol, Error == Value.Error {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` or an active inner signal emits an error, the
/// returned signal will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If an active inner signal emits an error, the returned signal
/// will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` emits an error, the returned signal will forward
/// that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProtocol where Value: Sequence, Error == NoError {
/// Flattens the `sequence` value sent by `signal` according to
/// the semantics of the given strategy.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Iterator.Element, Error> {
return self.flatMap(strategy) { .init(values: $0) }
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == Value.Error {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If `producer` or an active inner signal emits an error, the
/// returned producer will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If an active inner signal emits an error, the returned producer
/// will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If `producer` emits an error, the returned producer will forward
/// that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerProtocol where Value: Sequence, Error == NoError {
/// Flattens the `sequence` value sent by `producer` according to
/// the semantics of the given strategy.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Iterator.Element, Error> {
return self.flatMap(strategy) { .init(values: $0) }
}
}
extension SignalProtocol where Value: PropertyProtocol {
/// Flattens the inner properties sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.producer }
}
}
extension SignalProducerProtocol where Value: PropertyProtocol {
/// Flattens the inner properties sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.producer }
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal which sends all the values from producer signal emitted
/// from `signal`, waiting until each inner producer completes before
/// beginning to send the values from the next inner producer.
///
/// - note: If any of the inner producers fail, the returned signal will
/// forward that failure immediately
///
/// - note: The returned signal completes only when `signal` and all
/// producers emitted from `signal` complete.
fileprivate func concat() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeConcat(relayObserver, relayDisposable)
return disposable
}
}
fileprivate func observeConcat(_ observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable? = nil) -> Disposable? {
let state = Atomic(ConcatState<Value.Value, Error>())
func startNextIfNeeded() {
while let producer = state.modify({ $0.dequeue() }) {
producer.startWithSignal { signal, inner in
let handle = disposable?.add(inner)
signal.observe { event in
switch event {
case .completed, .interrupted:
handle?.remove()
let shouldStart: Bool = state.modify {
$0.active = nil
return !$0.isStarting
}
if shouldStart {
startNextIfNeeded()
}
case .value, .failed:
observer.action(event)
}
}
}
state.modify { $0.isStarting = false }
}
}
return observe { event in
switch event {
case let .value(value):
state.modify { $0.queue.append(value.producer) }
startNextIfNeeded()
case let .failed(error):
observer.send(error: error)
case .completed:
state.modify { state in
state.queue.append(SignalProducer.empty.on(completed: observer.sendCompleted))
}
startNextIfNeeded()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a producer which sends all the values from each producer emitted
/// from `producer`, waiting until each inner producer completes before
/// beginning to send the values from the next inner producer.
///
/// - note: If any of the inner producers emit an error, the returned
/// producer will emit that error.
///
/// - note: The returned producer completes only when `producer` and all
/// producers emitted from `producer` complete.
fileprivate func concat() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
_ = signal.observeConcat(observer, disposable)
}
}
}
}
extension SignalProducerProtocol {
/// `concat`s `next` onto `self`.
public func concat(_ next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer<SignalProducer<Value, Error>, Error>(values: [ self.producer, next ]).flatten(.concat)
}
/// `concat`s `value` onto `self`.
public func concat(value: Value) -> SignalProducer<Value, Error> {
return self.concat(SignalProducer(value: value))
}
/// `concat`s `self` onto initial `previous`.
public func prefix<P: SignalProducerProtocol>(_ previous: P) -> SignalProducer<Value, Error>
where P.Value == Value, P.Error == Error
{
return previous.concat(self.producer)
}
/// `concat`s `self` onto initial `value`.
public func prefix(value: Value) -> SignalProducer<Value, Error> {
return self.prefix(SignalProducer(value: value))
}
}
private final class ConcatState<Value, Error: Swift.Error> {
typealias SignalProducer = ReactiveSwift.SignalProducer<Value, Error>
/// The active producer, if any.
var active: SignalProducer? = nil
/// The producers waiting to be started.
var queue: [SignalProducer] = []
/// Whether the active producer is currently starting.
/// Used to prevent deep recursion.
var isStarting: Bool = false
/// Dequeue the next producer if one should be started.
///
/// - note: The caller *must* set `isStarting` to false after the returned
/// producer has been started.
///
/// - returns: The `SignalProducer` to start or `nil` if no producer should
/// be started.
func dequeue() -> SignalProducer? {
if active != nil {
return nil
}
active = queue.first
if active != nil {
queue.removeFirst()
isStarting = true
}
return active
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased
/// toward the producer added earlier. Returns a Signal that will forward
/// events from the inner producers as they arrive.
fileprivate func merge() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeMerge(relayObserver, relayDisposable)
return disposable
}
}
fileprivate func observeMerge(_ observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable) -> Disposable? {
let inFlight = Atomic(1)
let decrementInFlight = {
let shouldComplete: Bool = inFlight.modify {
$0 -= 1
return $0 == 0
}
if shouldComplete {
observer.sendCompleted()
}
}
return self.observe { event in
switch event {
case let .value(producer):
producer.startWithSignal { innerSignal, innerDisposable in
inFlight.modify { $0 += 1 }
let handle = disposable.add(innerDisposable)
innerSignal.observe { event in
switch event {
case .completed, .interrupted:
handle.remove()
decrementInFlight()
case .value, .failed:
observer.action(event)
}
}
}
case let .failed(error):
observer.send(error: error)
case .completed:
decrementInFlight()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased
/// toward the producer added earlier. Returns a Signal that will forward
/// events from the inner producers as they arrive.
fileprivate func merge() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { relayObserver, disposable in
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
_ = signal.observeMerge(relayObserver, disposable)
}
}
}
}
extension SignalProtocol {
/// Merges the given signals into a single `Signal` that will emit all
/// values from each of them, and complete when all of them have completed.
public static func merge<Seq: Sequence, S: SignalProtocol>(_ signals: Seq) -> Signal<Value, Error>
where S.Value == Value, S.Error == Error, Seq.Iterator.Element == S
{
return SignalProducer<S, Error>(values: signals)
.flatten(.merge)
.startAndRetrieveSignal()
}
/// Merges the given signals into a single `Signal` that will emit all
/// values from each of them, and complete when all of them have completed.
public static func merge<S: SignalProtocol>(_ signals: S...) -> Signal<Value, Error>
where S.Value == Value, S.Error == Error
{
return Signal.merge(signals)
}
}
extension SignalProducerProtocol {
/// Merges the given producers into a single `SignalProducer` that will emit
/// all values from each of them, and complete when all of them have
/// completed.
public static func merge<Seq: Sequence, S: SignalProducerProtocol>(_ producers: Seq) -> SignalProducer<Value, Error>
where S.Value == Value, S.Error == Error, Seq.Iterator.Element == S
{
return SignalProducer(values: producers).flatten(.merge)
}
/// Merges the given producers into a single `SignalProducer` that will emit
/// all values from each of them, and complete when all of them have
/// completed.
public static func merge<S: SignalProducerProtocol>(_ producers: S...) -> SignalProducer<Value, Error>
where S.Value == Value, S.Error == Error
{
return SignalProducer.merge(producers)
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
fileprivate func switchToLatest() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
let composite = CompositeDisposable()
let serial = SerialDisposable()
composite += serial
composite += self.observeSwitchToLatest(observer, serial)
return composite
}
}
fileprivate func observeSwitchToLatest(_ observer: Observer<Value.Value, Error>, _ latestInnerDisposable: SerialDisposable) -> Disposable? {
let state = Atomic(LatestState<Value, Error>())
return self.observe { event in
switch event {
case let .value(innerProducer):
innerProducer.startWithSignal { innerSignal, innerDisposable in
state.modify {
// When we replace the disposable below, this prevents
// the generated Interrupted event from doing any work.
$0.replacingInnerSignal = true
}
latestInnerDisposable.innerDisposable = innerDisposable
state.modify {
$0.replacingInnerSignal = false
$0.innerSignalComplete = false
}
innerSignal.observe { event in
switch event {
case .interrupted:
// If interruption occurred as a result of a new
// producer arriving, we don't want to notify our
// observer.
let shouldComplete: Bool = state.modify { state in
if !state.replacingInnerSignal {
state.innerSignalComplete = true
}
return !state.replacingInnerSignal && state.outerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .completed:
let shouldComplete: Bool = state.modify {
$0.innerSignalComplete = true
return $0.outerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .value, .failed:
observer.action(event)
}
}
}
case let .failed(error):
observer.send(error: error)
case .completed:
let shouldComplete: Bool = state.modify {
$0.outerSignalComplete = true
return $0.innerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
fileprivate func switchToLatest() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
let latestInnerDisposable = SerialDisposable()
disposable += latestInnerDisposable
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
disposable += signal.observeSwitchToLatest(observer, latestInnerDisposable)
}
}
}
}
private struct LatestState<Value, Error: Swift.Error> {
var outerSignalComplete: Bool = false
var innerSignalComplete: Bool = true
var replacingInnerSignal: Bool = false
}
extension SignalProtocol {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created producers fail, the returned signal
/// will forward that failure immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created signals emit an error, the returned
/// signal will forward that error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward that
/// error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new property, then flattens the
/// resulting properties (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward that
/// error immediately.
public func flatMap<P: PropertyProtocol>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> P) -> Signal<P.Value, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalProtocol where Error == NoError {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerProtocol {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created producers fail, the returned producer
/// will forward that failure immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` fails, the returned producer will forward that failure
/// immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created signals emit an error, the returned
/// producer will forward that error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` emits an error, the returned producer will forward that
/// error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new property, then flattens the
/// resulting properties (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` emits an error, the returned producer will forward that
/// error immediately.
public func flatMap<P: PropertyProtocol>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> P) -> SignalProducer<P.Value, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerProtocol where Error == NoError {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created producers fail, the returned producer will
/// forward that failure immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned
/// producer will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalProtocol {
/// Catches any failure that may occur on the input signal, mapping to a new
/// producer that starts in its place.
public func flatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>) -> Signal<Value, F> {
return Signal { observer in
self.observeFlatMapError(handler, observer, SerialDisposable())
}
}
fileprivate func observeFlatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>, _ observer: Observer<Value, F>, _ serialDisposable: SerialDisposable) -> Disposable? {
return self.observe { event in
switch event {
case let .value(value):
observer.send(value: value)
case let .failed(error):
handler(error).startWithSignal { signal, disposable in
serialDisposable.innerDisposable = disposable
signal.observe(observer)
}
case .completed:
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol {
/// Catches any failure that may occur on the input producer, mapping to a
/// new producer that starts in its place.
public func flatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>) -> SignalProducer<Value, F> {
return SignalProducer { observer, disposable in
let serialDisposable = SerialDisposable()
disposable += serialDisposable
self.startWithSignal { signal, signalDisposable in
serialDisposable.innerDisposable = signalDisposable
_ = signal.observeFlatMapError(handler, observer, serialDisposable)
}
}
}
}
| apache-2.0 | 30381de28f4d80a761c28699796fa9da | 35.456726 | 185 | 0.705709 | 4.106413 | false | false | false | false |
iosdevzone/IDZSwiftCommonCrypto | IDZSwiftCommonCrypto/Digest.swift | 1 | 5165 | //
// Digest.swift
// SwiftCommonCrypto
//
// Created by idz on 9/19/14.
// Copyright (c) 2014 iOS Developer Zone. All rights reserved.
//
import Foundation
import CommonCrypto
// MARK: - Public Interface
/**
Public API for message digests.
Usage is straightforward
````
let s = "The quick brown fox jumps over the lazy dog."
var md5 : Digest = Digest(algorithm:.MD5)
md5.update(s)
let digest = md5.final()
````
*/
open class Digest : Updateable
{
///
/// The status of the Digest.
/// For CommonCrypto this will always be `.Success`.
/// It is here to provide for engines which can fail.
///
open var status = Status.success
///
/// Enumerates available Digest algorithms
///
public enum Algorithm
{
/// Message Digest 2 See: http://en.wikipedia.org/wiki/MD2_(cryptography)
case md2,
/// Message Digest 4
md4,
/// Message Digest 5
md5,
/// Secure Hash Algorithm 1
sha1,
/// Secure Hash Algorithm 2 224-bit
sha224,
/// Secure Hash Algorithm 2 256-bit
sha256,
/// Secure Hash Algorithm 2 384-bit
sha384,
/// Secure Hash Algorithm 2 512-bit
sha512
}
var engine: DigestEngine
/**
Create an algorithm-specific digest calculator
- parameter alrgorithm: the desired message digest algorithm
*/
public init(algorithm: Algorithm)
{
switch algorithm {
case .md2:
engine = DigestEngineCC<CC_MD2_CTX>(initializer:CC_MD2_Init, updater:CC_MD2_Update, finalizer:CC_MD2_Final, length:CC_MD2_DIGEST_LENGTH)
case .md4:
engine = DigestEngineCC<CC_MD4_CTX>(initializer:CC_MD4_Init, updater:CC_MD4_Update, finalizer:CC_MD4_Final, length:CC_MD4_DIGEST_LENGTH)
case .md5:
engine = DigestEngineCC<CC_MD5_CTX>(initializer:CC_MD5_Init, updater:CC_MD5_Update, finalizer:CC_MD5_Final, length:CC_MD5_DIGEST_LENGTH)
case .sha1:
engine = DigestEngineCC<CC_SHA1_CTX>(initializer:CC_SHA1_Init, updater:CC_SHA1_Update, finalizer:CC_SHA1_Final, length:CC_SHA1_DIGEST_LENGTH)
case .sha224:
engine = DigestEngineCC<CC_SHA256_CTX>(initializer:CC_SHA224_Init, updater:CC_SHA224_Update, finalizer:CC_SHA224_Final, length:CC_SHA224_DIGEST_LENGTH)
case .sha256:
engine = DigestEngineCC<CC_SHA256_CTX>(initializer:CC_SHA256_Init, updater:CC_SHA256_Update, finalizer:CC_SHA256_Final, length:CC_SHA256_DIGEST_LENGTH)
case .sha384:
engine = DigestEngineCC<CC_SHA512_CTX>(initializer:CC_SHA384_Init, updater:CC_SHA384_Update, finalizer:CC_SHA384_Final, length:CC_SHA384_DIGEST_LENGTH)
case .sha512:
engine = DigestEngineCC<CC_SHA512_CTX>(initializer:CC_SHA512_Init, updater:CC_SHA512_Update, finalizer:CC_SHA512_Final, length:CC_SHA512_DIGEST_LENGTH)
}
}
/**
Low-level update routine. Updates the message digest calculation with
the contents of a byte buffer.
- parameter buffer: the buffer
- parameter the: number of bytes in buffer
- returns: this Digest object (for optional chaining)
*/
open func update(buffer: UnsafeRawPointer, byteCount: size_t) -> Self?
{
engine.update(buffer: buffer, byteCount: CC_LONG(byteCount))
return self
}
/**
Completes the calculate of the messge digest
- returns: the message digest
*/
open func final() -> [UInt8]
{
return engine.final()
}
}
// MARK: Internal Classes
/**
* Defines the interface between the Digest class and an
* algorithm specific DigestEngine
*/
protocol DigestEngine
{
func update(buffer: UnsafeRawPointer, byteCount: CC_LONG)
func final() -> [UInt8]
}
/**
* Wraps the underlying algorithm specific structures and calls
* in a generic interface.
*/
class DigestEngineCC<C> : DigestEngine {
typealias Context = UnsafeMutablePointer<C>
typealias Buffer = UnsafeRawPointer
typealias Digest = UnsafeMutablePointer<UInt8>
typealias Initializer = (Context) -> (Int32)
typealias Updater = (Context, Buffer, CC_LONG) -> (Int32)
typealias Finalizer = (Digest, Context) -> (Int32)
let context = Context.allocate(capacity: 1)
var initializer : Initializer
var updater : Updater
var finalizer : Finalizer
var length : Int32
init(initializer : @escaping Initializer, updater : @escaping Updater, finalizer : @escaping Finalizer, length : Int32)
{
self.initializer = initializer
self.updater = updater
self.finalizer = finalizer
self.length = length
_ = initializer(context)
}
deinit
{
context.deallocate()
}
func update(buffer: Buffer, byteCount: CC_LONG)
{
_ = updater(context, buffer, byteCount)
}
func final() -> [UInt8]
{
let digestLength = Int(self.length)
var digest = Array<UInt8>(repeating: 0, count: digestLength)
_ = finalizer(&digest, context)
return digest
}
}
| mit | 085ba30915a30f52bd0ff0908e757a2d | 30.882716 | 163 | 0.637561 | 3.942748 | false | false | false | false |
tbaranes/SwiftyUtils | SwiftyUtils Example/iOS Example/Classes/OthersExampleViewController.swift | 1 | 1911 | //
// Created by Tom Baranes on 24/11/15.
// Copyright ยฉ 2015 Tom Baranes. All rights reserved.
//
import UIKit
import SwiftyUtils
final class OthersExampleViewController: UIViewController {
// fromNib
// NSMutableAttributedstring
@IBOutlet private weak var labelAppVersion: UILabel! {
didSet {
labelAppVersion.text = String(format: "App version: %@", Bundle.main.appVersion)
}
}
@IBOutlet private weak var labelAppBuild: UILabel! {
didSet {
labelAppBuild.text = String(format: "App build: %@", Bundle.main.appBuild)
}
}
@IBOutlet private weak var labelScreenOrientation: UILabel! {
didSet {
let isPortrait = UIScreen.currentOrientation == UIInterfaceOrientation.portrait
let orientation = isPortrait ? "portrait" : "landscape"
labelScreenOrientation.text = String(format: "Screen orientation: %@", orientation)
}
}
@IBOutlet private weak var labelScreenSize: UILabel! {
didSet {
labelScreenSize.text = String(format: "Screen width: %.f, screen height: %.f",
UIScreen.size.width,
UIScreen.size.height)
}
}
@IBOutlet private weak var labelStatusBarHeight: UILabel! {
didSet {
labelStatusBarHeight.text = String(format: "Status bar height: %.f",
UIScreen.statusBarHeight)
}
}
@IBOutlet private weak var labelScreenHeightWithoutStatusBar: UILabel! {
didSet {
let text = String(format: "Screen height without status bar: %.f",
UIScreen.heightWithoutStatusBar)
labelScreenHeightWithoutStatusBar.text = text
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
| mit | d4e182a541cd365cdbbb5922cc1db335 | 30.311475 | 95 | 0.588482 | 5.20436 | false | false | false | false |
meetkei/KeiSwiftFramework | KeiSwiftFramework/View/Switch/KUserDefaultsSwitch.swift | 1 | 2264 | //
// KUserDefaultsSwitch.swift
//
// Copyright (c) 2016 Keun young Kim <[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.
//
open class KUserDefaultsSwitch: UISwitch {
open override var isOn: Bool {
didSet {
if let key = userDefaultsKey {
KKeyValueStore.saveBool(isOn, forKey: key)
}
}
}
@IBInspectable open var userDefaultsKey: String? = nil {
didSet {
update()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
update(false)
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
update(false)
}
open override func setOn(_ on: Bool, animated: Bool) {
super.setOn(on, animated: animated)
if let key = userDefaultsKey {
KKeyValueStore.saveBool(on, forKey: key)
}
}
open func update(_ animated: Bool = true) {
if let key = userDefaultsKey {
let isTrue = KKeyValueStore.boolValue(key)
print("UPDATE with \(key) \(isTrue)")
setOn(isTrue, animated: animated)
}
}
}
| mit | 4323531ec271ceea1b839457e940129b | 32.294118 | 81 | 0.644876 | 4.483168 | false | false | false | false |
bananafish911/SmartReceiptsiOS | SmartReceipts/Backup/DataImport.swift | 1 | 3757 | //
// DataImport.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 11/06/2017.
// Copyright ยฉ 2017 Will Baumann. All rights reserved.
//
import objective_zip
class DataImport: NSObject {
var inputPath: String!
var outputPath: String!
init(inputFile: String, output: String) {
super.init()
self.inputPath = inputFile
self.outputPath = output
}
func execute() {
do {
try FileManager.default.createDirectory(atPath: outputPath, withIntermediateDirectories: true, attributes: nil)
} catch {
Logger.error("execute(), error creating directory at path: \(outputPath), error: \(error.localizedDescription)")
}
let zipFile = OZZipFile(fileName: inputPath, mode: .unzip)
let toFile = (outputPath as NSString).appendingPathComponent(SmartReceiptsDatabaseExportName)
extractFrom(zip: zipFile, zipName: SmartReceiptsDatabaseExportName, toFile: toFile)
let preferences = extractDataFrom(zipFile: zipFile, fileName: SmartReceiptsPreferencesExportName)
WBPreferences.setFromXmlString(String(data: preferences!, encoding: .utf8))
// Trips contents
zipFile.goToFirstFileInZip()
repeat {
let info = zipFile.getCurrentFileInZipInfo()
let name = info.name
if name == SmartReceiptsDatabaseExportName || name.hasPrefix("shared_prefs/") {
continue
}
let components = (name as NSString).pathComponents
if components.count != 2 {
continue
}
let tripName = components[0]
let fileName = components[1]
Logger.debug("Extract file for trip: \(tripName)")
let tripPath = ((outputPath as NSString).appendingPathComponent(SmartReceiptsTripsDirectoryName)
as NSString).appendingPathComponent(tripName)
try? FileManager.default.createDirectory(atPath: tripPath, withIntermediateDirectories: true, attributes: nil)
let filePath = (tripPath as NSString).appendingPathComponent(fileName)
let stream = zipFile.readCurrentFileInZip()
writeDataFrom(stream: stream, toFile: filePath)
} while zipFile.goToNextFileInZip()
}
func extractFrom(zip: OZZipFile, zipName: String, toFile: String) {
Logger.debug("Extract file named: \(zipName)")
let found = zip.locateFile(inZip: zipName)
if (!found) {
Logger.warning("File with name \(zipName) not in zip")
return;
}
let stream = zip.readCurrentFileInZip()
writeDataFrom(stream: stream, toFile: toFile)
}
func writeDataFrom(stream: OZZipReadStream, toFile: String) {
let buffer = NSMutableData(length: 8 * 1024)!
let resultData = NSMutableData()
var len = stream.readData(withBuffer: buffer)
while len > 0 {
resultData.append(buffer.mutableBytes, length: Int(len))
len = stream.readData(withBuffer: buffer)
}
stream.finishedReading()
Logger.debug("File size \(resultData.length)")
WBFileManager.forceWrite(resultData as Data, to: toFile)
Logger.debug("Written to \(toFile)")
}
func extractDataFrom(zipFile: OZZipFile, fileName: String) -> Data? {
let tempFile = (NSTemporaryDirectory() as NSString).appendingPathComponent("extract")
extractFrom(zip: zipFile, zipName: fileName, toFile: tempFile)
let data = NSData(contentsOfFile: tempFile)
try? FileManager.default.removeItem(atPath: tempFile)
return data as Data?
}
}
| agpl-3.0 | fe161b336c824a378ef64a5664d5bde2 | 38.536842 | 124 | 0.631523 | 4.846452 | false | false | false | false |
sora0077/iTunesMusicKit | src/Endpoint/GetTrackById.swift | 1 | 1339 | //
// GetTrackById.swift
// iTunesMusicKit
//
// Created by ๆ้ไน on 2015/10/16.
// Copyright ยฉ 2015ๅนด jp.sora0077. All rights reserved.
//
import Foundation
import APIKit
public struct GetTrackById {
public var id: String {
return getTrackByIds.ids[0]
}
var country: String {
return getTrackByIds.country
}
private let getTrackByIds: GetTrackByIds
public init(id: String, country: String) {
self.getTrackByIds = GetTrackByIds(ids: [id], country: country)
}
}
extension GetTrackById: iTunesRequestToken {
public typealias Response = Track
public typealias SerializedObject = [String: AnyObject]
public var method: HTTPMethod {
return getTrackByIds.method
}
public var path: String {
return getTrackByIds.path
}
public var parameters: [String: AnyObject]? {
return getTrackByIds.parameters
}
public func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response {
let res = try getTrackByIds.transform(request, response: response, object: object)
if let item = res.first {
return item
}
throw Error.serializeError(NSError(domain: "", code: 0, userInfo: nil))
}
}
| mit | 64dd8ac217acd3948b05c7730070d6a8 | 23.62963 | 126 | 0.644361 | 4.262821 | false | false | false | false |
AlphaJian/LarsonApp | LarsonApp/LarsonApp/Class/JobDetail/TimeSheet/TimeSheetTableView.swift | 1 | 1442 | //
// TimeSheetTableView.swift
// LarsonApp
//
// Created by Jian Zhang on 11/14/16.
// Copyright ยฉ 2016 Jian Zhang. All rights reserved.
//
import UIKit
class TimeSheetTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
var dataItems = NSMutableArray()
var buttonTapHandler : ButtonTouchUpBlock?
var partDeleteHandler : CellTouchUpBlock?
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.delegate = self
self.dataSource = self
self.register(UINib(nibName: "TimeSheetTableViewCell", bundle: nil) , forCellReuseIdentifier: "TimeSheetTableViewCell")
self.separatorStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TimeSheetTableViewCell") as! TimeSheetTableViewCell
let model = dataItems[indexPath.row] as! TimesheetModel
cell.initUI(model: model, index: indexPath)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
| apache-2.0 | acc2c58225071479bee0314d31ebc601 | 30.326087 | 127 | 0.680777 | 4.95189 | false | false | false | false |
exponent/exponent | ios/versioned/sdk44/ExpoModulesCore/Swift/Records/Record.swift | 2 | 2055 | /**
A protocol that allows initializing the object with a dictionary.
*/
public protocol Record: ConvertibleArgument {
/**
The dictionary type that the record can be created from or converted back.
*/
typealias Dict = [String: Any]
/**
The default initializer. It enforces the structs not to have any uninitialized properties.
*/
init()
/**
Initializes a record from given dictionary. Only members wrapped by `@Field` will be set in the object.
*/
init(from: Dict) throws
/**
Converts the record back to the dictionary. Only members wrapped by `@Field` will be set in the dictionary.
*/
func toDictionary() -> Dict
}
/**
Provides the default implementation of `Record` protocol.
*/
public extension Record {
static func convert(from value: Any?) throws -> Self {
if let value = value as? Dict {
return try Self(from: value)
}
throw Conversions.ConvertingError<Self>(value: value)
}
init(from dict: Dict) throws {
self.init()
try fieldsOf(self).forEach { field in
try field.set(dict[field.key!])
}
}
func toDictionary() -> Dict {
return fieldsOf(self).reduce(into: Dict()) { result, field in
result[field.key!] = field.get()
}
}
}
/**
Returns an array of fields found in record's mirror. If the field is missing the `key`,
it gets assigned to the property label, so after all it's safe to enforce unwrapping it (using `key!`).
*/
fileprivate func fieldsOf(_ record: Record) -> [AnyFieldInternal] {
return Mirror(reflecting: record).children.compactMap { (label: String?, value: Any) in
guard var field = value as? AnyFieldInternal, let key = field.key ?? convertLabelToKey(label) else {
return nil
}
field.options.insert(.keyed(key))
return field
}
}
/**
Converts mirror's label to field's key by dropping the "_" prefix from wrapped property label.
*/
fileprivate func convertLabelToKey(_ label: String?) -> String? {
return (label != nil && label!.starts(with: "_")) ? String(label!.dropFirst()) : label
}
| bsd-3-clause | 23c3fea9da108b753e6d334009d9ae10 | 27.943662 | 110 | 0.675912 | 4.085487 | false | false | false | false |
Holmusk/HMRequestFramework-iOS | HMRequestFrameworkTests/model/database/Dummy1.swift | 1 | 8263 | //
// Dummy1.swift
// HMRequestFramework
//
// Created by Hai Pham on 7/25/17.
// Copyright ยฉ 2017 Holmusk. All rights reserved.
//
import CoreData
import Differentiator
import SwiftUtilities
@testable import HMRequestFramework
public protocol Dummy1Type {
var id: String? { get }
var date: Date? { get }
var int64: NSNumber? { get }
var float: NSNumber? { get }
var version: NSNumber? { get }
}
public extension Dummy1Type {
public func primaryKey() -> String {
return "id"
}
public func primaryValue() -> String? {
return id
}
public func stringRepresentationForResult() -> String {
return id.getOrElse("")
}
}
public final class CDDummy1: NSManagedObject {
@NSManaged public var id: String?
@NSManaged public var int64: NSNumber?
@NSManaged public var date: Date?
@NSManaged public var float: NSNumber?
@NSManaged public var version: NSNumber?
public var sectionName: String? {
if let id = self.id {
let section = String(describing: id)
return section.count == 1 ? section : section.dropLast().description
} else {
return nil
}
}
}
public final class Dummy1 {
fileprivate static var counter = 0
fileprivate var _id: String?
fileprivate var _int64: NSNumber?
fileprivate var _date: Date?
fileprivate var _float: NSNumber?
fileprivate var _version: NSNumber?
public var id: String? {
return _id
}
public var int64: NSNumber? {
return _int64
}
public var date: Date? {
return _date
}
public var float: NSNumber? {
return _float
}
public var version: NSNumber? {
return _version
}
public init() {
Dummy1.counter += 1
let counter = Dummy1.counter
_id = String(describing: counter)
_date = Date.random()
_int64 = Int64(Int.randomBetween(0, 10000)) as NSNumber
_float = Float(Int.randomBetween(0, 10000)) as NSNumber
_version = 1
}
}
extension CDDummy1: Dummy1Type {}
extension CDDummy1: HMCDVersionableMasterType {
public typealias PureObject = Dummy1
public static func cdAttributes() throws -> [NSAttributeDescription]? {
return [
NSAttributeDescription.builder()
.with(name: "id")
.with(type: .stringAttributeType)
.shouldNotBeOptional()
.build(),
NSAttributeDescription.builder()
.with(name: "int64")
.with(type: .integer64AttributeType)
.shouldNotBeOptional()
.build(),
NSAttributeDescription.builder()
.with(name: "date")
.with(type: .dateAttributeType)
.shouldNotBeOptional()
.build(),
NSAttributeDescription.builder()
.with(name: "float")
.with(type: .floatAttributeType)
.shouldNotBeOptional()
.build(),
NSAttributeDescription.builder()
.with(name: "version")
.with(type: .integer16AttributeType)
.shouldNotBeOptional()
.build()
]
}
public func mutateWithPureObject(_ object: PureObject) {
id = object.id
date = object.date
float = object.float
int64 = object.int64
version = object.version
}
public func currentVersion() -> String? {
if let version = self.version {
return String(describing: version)
} else {
return nil
}
}
public func oneVersionHigher() -> String? {
if let version = self.version {
return String(describing: version.intValue + 1)
} else {
return nil
}
}
public func hasPreferableVersion(over obj: HMVersionableType) throws -> Bool {
if let v1 = self.currentVersion(), let v2 = obj.currentVersion() {
return v1 >= v2
} else {
throw Exception("Version not available")
}
}
public func mergeWithOriginalVersion(_ obj: HMVersionableType) throws {}
public func updateVersion(_ version: String?) {
if let version = version, let dbl = Double(version) {
self.version = NSNumber(value: dbl).intValue as NSNumber
}
}
}
extension Dummy1: Equatable {
public static func ==(lhs: Dummy1, rhs: Dummy1) -> Bool {
// We don't compare the version here because it will be bumped when
// an update is successful. During testing, we only compare the other
// properties to make sure that the updated object is the same as this.
return lhs.id == rhs.id &&
lhs.date == rhs.date &&
lhs.int64 == rhs.int64 &&
lhs.float == rhs.float
}
}
extension Dummy1: IdentifiableType {
public var identity: String {
return id ?? ""
}
}
extension Dummy1: Dummy1Type {}
extension Dummy1: CustomStringConvertible {
public var description: String {
return ""
+ "id: \(String(describing: id)), "
+ "int64: \(String(describing: int64)), "
+ "float: \(String(describing: float)), "
+ "date: \(String(describing: date)), "
+ "version: \(String(describing: version))"
}
}
extension Dummy1: HMCDPureObjectMasterType {
public typealias CDClass = CDDummy1
public static func builder() -> Builder {
return Builder()
}
public final class Builder {
private let d1: Dummy1
fileprivate init() {
d1 = Dummy1()
}
@discardableResult
public func with(id: String?) -> Self {
d1._id = id
return self
}
@discardableResult
public func with(date: Date?) -> Self {
d1._date = date
return self
}
@discardableResult
public func with(int64: NSNumber?) -> Self {
d1._int64 = int64
return self
}
@discardableResult
public func with(float: NSNumber?) -> Self {
d1._float = float
return self
}
@discardableResult
public func with(version: NSNumber?) -> Self {
d1._version = version
return self
}
@discardableResult
public func with(version: String?) -> Self {
if let version = version, let dbl = Double(version) {
return with(version: NSNumber(value: dbl).intValue as NSNumber)
} else {
return self
}
}
@discardableResult
public func with(json: [String : Any?]) -> Self {
return self
.with(id: json["id"] as? String)
.with(date: json["date"] as? Date)
.with(int64: json["int64"] as? NSNumber)
.with(float: json["float"] as? NSNumber)
.with(version: json["version"] as? NSNumber)
}
public func with(dummy1: Dummy1Type?) -> Self {
if let dummy1 = dummy1 {
return self
.with(id: dummy1.id)
.with(date: dummy1.date)
.with(int64: dummy1.int64)
.with(float: dummy1.float)
.with(version: dummy1.version)
} else {
return self
}
}
public func build() -> Dummy1 {
return d1
}
}
}
extension Dummy1.Builder: HMCDPureObjectBuilderMasterType {
public typealias Buildable = Dummy1
public func with(cdObject: Buildable.CDClass) -> Self {
return with(dummy1: cdObject)
}
public func with(buildable: Buildable?) -> Self {
if let buildable = buildable {
return with(dummy1: buildable)
} else {
return self
}
}
}
| apache-2.0 | d237eeb2c96f83ebc6d37cc888c19fe3 | 26.54 | 82 | 0.535827 | 4.68102 | false | false | false | false |
svanimpe/around-the-table | Tests/AroundTheTableTests/Models/UserTests.swift | 1 | 2911 | import BSON
import XCTest
@testable import AroundTheTable
class UserTests: XCTestCase {
static var allTests: [(String, (UserTests) -> () throws -> Void)] {
return [
("testEncode", testEncode),
("testEncodeSkipsNilValues", testEncodeSkipsNilValues),
("testDecode", testDecode),
("testDecodeNotADocument", testDecodeNotADocument),
("testDecodeMissingID", testDecodeMissingID),
("testDecodeMissingName", testDecodeMissingName),
("testDecodeMissingLastSignIn", testDecodeMissingLastSignIn)
]
}
private let url = URL(string: "http://github.com/")!
private let location = Location(coordinates: Coordinates(latitude: 50, longitude: 2),
address: "Street 1", city: "City", country: "Country")
private let now = Date()
func testEncode() {
let input = User(id: 1, lastSignIn: now, name: "User", picture: url, location: location)
let expected: Document = [
"_id": 1,
"lastSignIn": now,
"name": "User",
"picture": url,
"location": location
]
XCTAssert(input.typeIdentifier == expected.typeIdentifier)
XCTAssert(input.document == expected)
}
func testEncodeSkipsNilValues() {
let input = User(id: 1, lastSignIn: now, name: "User")
let expected: Document = [
"_id": 1,
"lastSignIn": now,
"name": "User",
]
XCTAssert(input.typeIdentifier == expected.typeIdentifier)
XCTAssert(input.document == expected)
}
func testDecode() throws {
let input: Document = [
"_id": 1,
"lastSignIn": now,
"name": "User",
"picture": url,
"location": location
]
guard let result = try User(input) else {
return XCTFail()
}
XCTAssert(result.id == 1)
assertDatesEqual(result.lastSignIn, now)
XCTAssert(result.name == "User")
XCTAssert(result.picture == url)
XCTAssert(result.location == location)
}
func testDecodeNotADocument() throws {
let input: Primitive = "123"
let result = try User(input)
XCTAssertNil(result)
}
func testDecodeMissingID() {
let input: Document = [
"lastSignIn": now,
"name": "User",
]
XCTAssertThrowsError(try User(input))
}
func testDecodeMissingName() {
let input: Document = [
"_id": 1,
"lastSignIn": now
]
XCTAssertThrowsError(try User(input))
}
func testDecodeMissingLastSignIn() {
let input: Document = [
"_id": 1,
"name": "User"
]
XCTAssertThrowsError(try User(input))
}
}
| bsd-2-clause | b2f8959cb9d7af906d061bcb2e2e00bd | 29.642105 | 96 | 0.542425 | 4.827529 | false | true | false | false |
makhiye/flagMatching | flag Matching/GameViewController[Conflict].swift | 1 | 2236 | //
// GameViewController.swift
// flag Matching
//
// Created by ishmael on 7/17/17.
// Copyright ยฉ 2017 ishmael.mthombeni. All rights reserved.
//
import UIKit
import LTMorphingLabel
class GameViewController: UIViewController, MatchingGameDelegate {
var game = Game()
var gameNumber = 1
@IBOutlet weak var gameLabel: LTMorphingLabel!
@IBOutlet weak var cardButton: UIButton!
var counter = 0
@IBAction func cardTapped(_ sender: UIButton) {
let tagNum = sender.tag
if game.flipCard(atIndexNumber: tagNum-1){
let thisImage = UIImage(named: game.deckOfCards.dealtCards[tagNum - 1])
UIView.transition(with: sender, duration: 0.5, options: . transitionCurlDown, animations: {sender.setImage(thisImage, for: .normal)}, completion: nil)
}
}
@IBAction func newGame(_ sender: UIButton) {
counter += 1
for tagNum in 1...12 {
if let thisButton = self.view.viewWithTag(tagNum) as? UIButton{
thisButton.setImage(#imageLiteral(resourceName: "AACard"), for: .normal)
}
}
game.deckOfCards.drawCards()
gameNumber += 1
gameLabel.text = "Game #\(gameNumber)"
}
func game(_ game: Game, hideCards cards: [Int]) {
for cardIndex in cards {
if let thisButton = self.view.viewWithTag(cardIndex+1) as? UIButton{
thisButton.setImage(#imageLiteral(resourceName: "AACard"), for: .normal)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
game.gameDelegate = self // setting gameDelegate to game
gameLabel.morphingEffect = .burn
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 709bc02e4b3d069b421e7de9b4c36d61 | 22.041237 | 162 | 0.545414 | 4.94469 | false | false | false | false |
catloafsoft/AudioKit | Examples/iOS/AnalogSynthX/AnalogSynthX/CustomControls/SynthStyleKit.swift | 1 | 4062 | //
// SynthStyleKit.swift
// AnalogSynthX
//
// Created by Matthew Fecher on 1/9/16.
// Copyright (c) 2016 AudioKit. All rights reserved.
import UIKit
public class SynthStyleKit : NSObject {
//// Drawing Methods
public class func drawKnobMedium(knobValue knobValue: CGFloat = 0.332) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Image Declarations
let knob140_base = UIImage(named: "knob140_base.png")!
let knob140_indicator = UIImage(named: "knob140_indicator.png")!
//// Variable Declarations
let knobAngle: CGFloat = -240 * knobValue
//// knob base Drawing
let knobBasePath = UIBezierPath(rect: CGRectMake(5, 5, 70, 70))
CGContextSaveGState(context)
knobBasePath.addClip()
knob140_base.drawInRect(CGRectMake(5, 5, knob140_base.size.width, knob140_base.size.height))
CGContextRestoreGState(context)
//// Indicator Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 40, 40)
CGContextRotateCTM(context, -(knobAngle + 120) * CGFloat(M_PI) / 180)
let indicatorPath = UIBezierPath(rect: CGRectMake(-35, -35, 70, 70))
CGContextSaveGState(context)
indicatorPath.addClip()
knob140_indicator.drawInRect(CGRectMake(-35, -35, knob140_indicator.size.width, knob140_indicator.size.height))
CGContextRestoreGState(context)
CGContextRestoreGState(context)
}
public class func drawKnobLarge(knobValue knobValue: CGFloat = 0.332) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Image Declarations
let knob212_base = UIImage(named: "knob212_base.png")!
let knob212_indicator = UIImage(named: "knob212_indicator.png")!
//// Variable Declarations
let knobAngle: CGFloat = -240 * knobValue
//// Picture Drawing
let picturePath = UIBezierPath(rect: CGRectMake(10, 10, 106, 106))
CGContextSaveGState(context)
picturePath.addClip()
knob212_base.drawInRect(CGRectMake(10, 10, knob212_base.size.width, knob212_base.size.height))
CGContextRestoreGState(context)
//// Picture 2 Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 63, 63)
CGContextRotateCTM(context, -(knobAngle + 120) * CGFloat(M_PI) / 180)
let picture2Path = UIBezierPath(rect: CGRectMake(-53, -53, 106, 106))
CGContextSaveGState(context)
picture2Path.addClip()
knob212_indicator.drawInRect(CGRectMake(-53, -53, knob212_indicator.size.width, knob212_indicator.size.height))
CGContextRestoreGState(context)
CGContextRestoreGState(context)
}
public class func drawKnobSmall(knobValue knobValue: CGFloat = 0.332) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Image Declarations
let knob120_base = UIImage(named: "knob120_base.png")!
let knob120_indicator = UIImage(named: "knob120_indicator.png")!
//// Variable Declarations
let knobAngle: CGFloat = -240 * knobValue
//// Picture Drawing
let picturePath = UIBezierPath(rect: CGRectMake(5, 5, 60, 60))
CGContextSaveGState(context)
picturePath.addClip()
knob120_base.drawInRect(CGRectMake(5, 5, knob120_base.size.width, knob120_base.size.height))
CGContextRestoreGState(context)
//// Indicator Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 35, 35)
CGContextRotateCTM(context, -(knobAngle + 120) * CGFloat(M_PI) / 180)
let indicatorPath = UIBezierPath(rect: CGRectMake(-30, -30, 60, 60))
CGContextSaveGState(context)
indicatorPath.addClip()
knob120_indicator.drawInRect(CGRectMake(-30, -30, knob120_indicator.size.width, knob120_indicator.size.height))
CGContextRestoreGState(context)
CGContextRestoreGState(context)
}
}
| mit | 04aac6d9f28ad204c89ca881acb8bd48 | 35.927273 | 119 | 0.665682 | 4.574324 | false | false | false | false |
czechboy0/XcodeServerSDK | XcodeServerSDKTests/XcodeServerEndpointsTests.swift | 2 | 9883 | //
// XcodeServerEndpointsTests.swift
// XcodeServerSDK
//
// Created by Mateusz Zajฤ
c on 20/07/15.
// Copyright ยฉ 2015 Honza Dvorsky. All rights reserved.
//
import XCTest
@testable import XcodeServerSDK
class XcodeServerEndpointsTests: XCTestCase {
let serverConfig = try! XcodeServerConfig(host: "https://127.0.0.1", user: "test", password: "test")
var endpoints: XcodeServerEndpoints?
override func setUp() {
super.setUp()
self.endpoints = XcodeServerEndpoints(serverConfig: serverConfig)
}
// MARK: createRequest()
// If malformed URL is passed to request creation function it should early exit and retur nil
func testMalformedURLCreation() {
let expectation = endpoints?.createRequest(.GET, endpoint: .Bots, params: ["test": "test"], query: ["test//http\\": "!test"], body: ["test": "test"], doBasicAuth: true)
XCTAssertNil(expectation, "Shouldn't create request from malformed URL")
}
func testRequestCreationForEmptyAuthorizationParams() {
let expectedUrl = NSURL(string: "https://127.0.0.1:20343/api/bots/bot_id/integrations")
let expectedRequest = NSMutableURLRequest(URL: expectedUrl!)
// HTTPMethod
expectedRequest.HTTPMethod = "GET"
// Authorization header: "": ""
expectedRequest.setValue("Basic Og==", forHTTPHeaderField: "Authorization")
let noAuthorizationConfig = try! XcodeServerConfig(host: "https://127.0.0.1")
let noAuthorizationEndpoints = XcodeServerEndpoints(serverConfig: noAuthorizationConfig)
let request = noAuthorizationEndpoints.createRequest(.GET, endpoint: .Integrations, params: ["bot": "bot_id"], query: nil, body: nil, doBasicAuth: true)
XCTAssertEqual(expectedRequest, request!)
}
func testGETRequestCreation() {
let expectedUrl = NSURL(string: "https://127.0.0.1:20343/api/bots/bot_id/integrations?format=json")
let expectedRequest = NSMutableURLRequest(URL: expectedUrl!)
// HTTPMethod
expectedRequest.HTTPMethod = "GET"
// Authorization header: "test": "test"
expectedRequest.setValue("Basic dGVzdDp0ZXN0", forHTTPHeaderField: "Authorization")
let request = self.endpoints?.createRequest(.GET, endpoint: .Integrations, params: ["bot": "bot_id"], query: ["format": "json"], body: nil, doBasicAuth: true)
XCTAssertEqual(expectedRequest, request!)
}
func testPOSTRequestCreation() {
let expectedUrl = NSURL(string: "https://127.0.0.1:20343/api/auth/logout")
let expectedRequest = NSMutableURLRequest(URL: expectedUrl!)
// HTTPMethod
expectedRequest.HTTPMethod = "POST"
// HTTPBody
let expectedData = "{\n \"bodyParam\" : \"bodyValue\"\n}".dataUsingEncoding(NSUTF8StringEncoding)
expectedRequest.HTTPBody = expectedData!
expectedRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let request = self.endpoints?.createRequest(.POST, endpoint: .Logout, params: nil, query: nil, body: ["bodyParam": "bodyValue"], doBasicAuth: false)
XCTAssertEqual(expectedRequest, request!)
XCTAssertEqual(expectedRequest.HTTPBody!, request!.HTTPBody!)
}
func testDELETERequestCreation() {
let expectedUrl = NSURL(string: "https://127.0.0.1:20343/api/bots/bot_id/rev_id")
let expectedRequest = NSMutableURLRequest(URL: expectedUrl!)
// HTTPMethod
expectedRequest.HTTPMethod = "DELETE"
let request = self.endpoints?.createRequest(.DELETE, endpoint: .Bots, params: ["bot": "bot_id", "rev": "rev_id"], query: nil, body: nil, doBasicAuth: false)
XCTAssertEqual(expectedRequest, request!)
}
// MARK: endpointURL(.Bots)
func testEndpointURLCreationForBotsPath() {
let expectation = "/api/bots"
let url = self.endpoints?.endpointURL(.Bots)
XCTAssertEqual(url!, expectation, "endpointURL(.Bots) should return \(expectation)")
}
func testEndpointURLCreationForBotsBotPath() {
let expectation = "/api/bots/bot_id"
let params = [
"bot": "bot_id"
]
let url = self.endpoints?.endpointURL(.Bots, params: params)
XCTAssertEqual(url!, expectation, "endpointURL(.Bots, \(params)) should return \(expectation)")
}
func testEndpointURLCreationForBotsBotRevPath() {
let expectation = "/api/bots/bot_id/rev_id"
let params = [
"bot": "bot_id",
"rev": "rev_id",
"method": "DELETE"
]
let url = self.endpoints?.endpointURL(.Bots, params: params)
XCTAssertEqual(url!, expectation, "endpointURL(.Bots, \(params)) should return \(expectation)")
}
// MARK: endpointURL(.Integrations)
func testEndpointURLCreationForIntegrationsPath() {
let expectation = "/api/integrations"
let url = self.endpoints?.endpointURL(.Integrations)
XCTAssertEqual(url!, expectation, "endpointURL(.Integrations) should return \(expectation)")
}
func testEndpointURLCreationForIntegrationsIntegrationPath() {
let expectation = "/api/integrations/integration_id"
let params = [
"integration": "integration_id"
]
let url = self.endpoints?.endpointURL(.Integrations, params: params)
XCTAssertEqual(url!, expectation, "endpointURL(.Integrations, \(params)) should return \(expectation)")
}
func testEndpointURLCreationForBotsBotIntegrationsPath() {
let expectation = "/api/bots/bot_id/integrations"
let params = [
"bot": "bot_id"
]
let url = self.endpoints?.endpointURL(.Integrations, params: params)
XCTAssertEqual(url!, expectation, "endpointURL(.Integrations, \(params)) should return \(expectation)")
}
// MARK: endpointURL(.CancelIntegration)
func testEndpointURLCreationForIntegrationsIntegrationCancelPath() {
let expectation = "/api/integrations/integration_id/cancel"
let params = [
"integration": "integration_id"
]
let url = self.endpoints?.endpointURL(.CancelIntegration, params: params)
XCTAssertEqual(url!, expectation, "endpointURL(.CancelIntegration, \(params)) should return \(expectation)")
}
// MARK: endpointURL(.Devices)
func testEndpointURLCreationForDevicesPath() {
let expectation = "/api/devices"
let url = self.endpoints?.endpointURL(.Devices)
XCTAssertEqual(url!, expectation, "endpointURL(.Devices) should return \(expectation)")
}
// MARK: endpointURL(.UserCanCreateBots)
func testEndpointURLCreationForAuthIsBotCreatorPath() {
let expectation = "/api/auth/isBotCreator"
let url = self.endpoints?.endpointURL(.UserCanCreateBots)
XCTAssertEqual(url!, expectation, "endpointURL(.UserCanCreateBots) should return \(expectation)")
}
// MARK: endpointURL(.Login)
func testEndpointURLCreationForAuthLoginPath() {
let expectation = "/api/auth/login"
let url = self.endpoints?.endpointURL(.Login)
XCTAssertEqual(url!, expectation, "endpointURL(.Login) should return \(expectation)")
}
// MARK: endpointURL(.Logout)
func testEndpointURLCreationForAuthLogoutPath() {
let expectation = "/api/auth/logout"
let url = self.endpoints?.endpointURL(.Logout)
XCTAssertEqual(url!, expectation, "endpointURL(.Logout) should return \(expectation)")
}
// MARK: endpointURL(.Platforms)
func testEndpointURLCreationForPlatformsPath() {
let expectation = "/api/platforms"
let url = self.endpoints?.endpointURL(.Platforms)
XCTAssertEqual(url!, expectation, "endpointURL(.Platforms) should return \(expectation)")
}
// MARK: endpointURL(.SCM_Branches)
func testEndpointURLCreationForScmBranchesPath() {
let expectation = "/api/scm/branches"
let url = self.endpoints?.endpointURL(.SCM_Branches)
XCTAssertEqual(url!, expectation, "endpointURL(.SCM_Branches) should return \(expectation)")
}
// MARK: endpointURL(.Repositories)
func testEndpointURLCreationForRepositoriesPath() {
let expectation = "/api/repositories"
let url = self.endpoints?.endpointURL(.Repositories)
XCTAssertEqual(url!, expectation, "endpointURL(.Repositories) should return \(expectation)")
}
// MARK: endpointURL(.Commits)
func testEndpointURLCreationForCommits() {
let expected = "/api/integrations/integration_id/commits"
let params = [
"integration": "integration_id"
]
let url = self.endpoints?.endpointURL(.Commits, params: params)
XCTAssertEqual(url!, expected)
}
// MARK: endpointURL(.Issues)
func testEndpointURLCreationForIssues() {
let expected = "/api/integrations/integration_id/issues"
let params = [
"integration": "integration_id"
]
let url = self.endpoints?.endpointURL(.Issues, params: params)
XCTAssertEqual(url!, expected)
}
// MARK: endpoingURL(.LiveUpdates)
func testEndpointURLCreationForLiveUpdates_Start() {
let expected = "/xcode/internal/socket.io/1"
let url = self.endpoints?.endpointURL(.LiveUpdates, params: nil)
XCTAssertEqual(url!, expected)
}
func testEndpointURLCreationForLiveUpdates_Poll() {
let expected = "/xcode/internal/socket.io/1/xhr-polling/sup3rS3cret"
let params = [
"poll_id": "sup3rS3cret"
]
let url = self.endpoints?.endpointURL(.LiveUpdates, params: params)
XCTAssertEqual(url!, expected)
}
}
| mit | d24b330ef4468454fd5f9be06a438268 | 40.170833 | 176 | 0.654084 | 4.634615 | false | true | false | false |
nghiaphunguyen/NKit | NKit/Demo/OneViewController.swift | 1 | 1828 | //
// OneViewController.swift
// NKit
//
// Created by Nghia Nguyen on 9/11/16.
// Copyright ยฉ 2016 Nghia Nguyen. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import SnapKit
class OneViewController: UIViewController {
enum Id: String, NKViewIdentifier {
case pushButton
}
override func viewDidLoad() {
super.viewDidLoad()
self.view
.nk_config() {
$0.backgroundColor = UIColor.green
$0.nk_autoHideKeyboardWhenTapOutside()
}
.nk_addSubview(NKTextView()) {
$0.nk_placeholder = "Placeholder"
$0.snp.makeConstraints({ (make) in
make.top.leading.equalToSuperview()
make.height.equalTo(100)
make.width.equalTo(100)
})
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//print("oneViewWillAppear with navigationItem=\(self.navigationController?.navigationItem) leftButton=\(self.navigationController?.navigationItem.leftBarButtonItem)")
self.nk_setBarTintColor(UIColor.green).nk_setRightBarButton("TwoView", selector: #selector(OneViewController.gotoTwoView))
self.nk_setBackBarButton(text: "", color: nil)
self.navigationItem.leftBarButtonItem = nil
self.navigationController?.view.layoutIfNeeded()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.navigationController?.view.layoutIfNeeded()
}
@objc func gotoTwoView() {
self.navigationController?.pushViewController(TwoViewController(), animated: true)
}
}
| mit | 0d96bb103927f665936efcb4f884da41 | 28.467742 | 175 | 0.604269 | 5.161017 | false | false | false | false |
Aprobado/Automatic.Writer | AutomaticWriter/Project/Project.swift | 1 | 3391 | //
// Project.swift
// AutomaticWriter
//
// Created by Raphael on 14.01.15.
// Copyright (c) 2015 HEAD Geneva. All rights reserved.
//
import Cocoa
class Project: NSObject {
var path : String
var folderName : String
init(projectPath : String) {
path = projectPath
folderName = path.lastPathComponent
super.init()
}
func addFilesInFolderPath(folderPath:String, intoArray:NSMutableArray) {
let absolutePath = path.stringByAppendingPathComponent(folderPath)
if let content:NSArray = NSFileManager.defaultManager().contentsOfDirectoryAtPath(absolutePath, error: nil) {
for file in content {
if let fileName = file as? String {
if fileName[fileName.startIndex] == "." {
println("ignore invisible file: \(fileName)")
} else if fileName == "automat" {
println("ignore automat folder")
} else {
let fileRelativePath = folderPath.stringByAppendingPathComponent(fileName)
let fileAbsolutePath = absolutePath.stringByAppendingPathComponent(fileName)
var isDir = ObjCBool(false)
if NSFileManager.defaultManager().fileExistsAtPath(fileAbsolutePath, isDirectory: &isDir) {
if isDir.boolValue {
//println("\(absolutePath) is a folder")
// recursively add files
addFilesInFolderPath(fileRelativePath, intoArray: intoArray)
} else {
//println("adding file: \(fileName)")
if let attributes : [NSObject : AnyObject] = NSFileManager.defaultManager().attributesOfItemAtPath(fileAbsolutePath, error: nil) {
let date:NSDate? = attributes[NSFileModificationDate] as? NSDate
if date == nil {
println("\(self.className):addFilesInFolderPath: date is nil, we're stopping the process to avoid unattended behaviours")
return
}
let fileRelativePathInBook = folderName.stringByAppendingPathComponent(fileRelativePath)
var dico:NSDictionary = ["path": fileRelativePathInBook, "date": date!]
intoArray.addObject(dico)
}
}
}
}
}
}
} else {
println("can't find content at path: \(absolutePath)")
}
}
func getArrayOfFiles() -> NSArray {
var array : NSMutableArray = []
addFilesInFolderPath("", intoArray: array)
return array
}
func getArrayOfFilesAsNSData() -> NSData {
let array = getArrayOfFiles()
let data:NSData = NSKeyedArchiver.archivedDataWithRootObject(array)
return data
}
}
| mit | 468a34bba1dd3e1d29199ecf435d6134 | 41.3875 | 162 | 0.491595 | 6.558994 | false | false | false | false |
bigtreenono/NSPTools | RayWenderlich/Introduction to Swift/8 . Classes/DemoClasses.playground/section-1 (Brian Moakley's conflicted copy 2014-12-19).swift | 1 | 1209 | // Playground - noun: a place where people can play
import UIKit
class Account {
var firstName: String
var lastName: String
var balance: Double
var rate = 0.0
init(firstName:String, lastName:String, balance:Double) {
self.firstName = firstName
self.lastName = lastName
self.balance = balance
}
convenience init() {
self.init(firstName:"", lastName:"", balance:0)
}
func interestOverYears(years:Double) -> Double {
return 0
}
func printBreakDown() {
var balance = NSString(format: "%f", self.balance)
println("\(firstName) \(lastName): \(balance)")
}
}
class CheckingAccount: Account {
override init(firstName:String, lastName:String, balance:Double) {
super.init(firstName:firstName, lastName:lastName, balance:balance)
self.rate = 4.3
}
override func interestOverYears(years: Double) -> Double {
return (balance * rate * years) / 100
}
}
//var account = Account(firstName: "Brian", lastName: "Moakley", balance: 1.0)
//var account = Account()
//account.printBreakDown()
var checkingAccount = CheckingAccount(firstName: "Brian", lastName: "Moakley", balance: 1000.00)
checkingAccount.interestOverYears(1)
| mit | fc252470e4d61e45d758690dd3cd6cc3 | 20.981818 | 96 | 0.682382 | 3.850318 | false | false | false | false |
Kratos28/KPageView | KPageViewSwift/KPageView/HYPageView/KPageViewLayout.swift | 1 | 3225 | //
// KPageViewLayout.swift
// KPageView
//
// Created by Kratos on 17/4/15.
// Copyright ยฉ 2017ๅนด Kratos. All rights reserved.
//
import UIKit
class KPageViewLayout: UICollectionViewLayout {
fileprivate lazy var cellAttrs : [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
var sectionInset : UIEdgeInsets = UIEdgeInsets.zero
var itemSpacing : CGFloat = 0
var lineSpacing : CGFloat = 0
var cols = 4
var rows = 2
fileprivate lazy var pageCount = 0
}
// MARK:- ๅๅคๆๆ็ๅธๅฑ
extension KPageViewLayout {
override func prepare() {
super.prepare()
// 1.ๅฏนcollectionView่ฟ่กๆ ก้ช
guard let collectionView = collectionView else {
return
}
// 2.่ทๅๅคๅฐ็ป
let sectionCount = collectionView.numberOfSections
// 3.่ทๅๆฏ็ปไธญๆๅคๅฐไธชๆฐๆฎ
let itemW : CGFloat = (collectionView.bounds.width - sectionInset.left - sectionInset.right - CGFloat(cols - 1) * itemSpacing) / CGFloat(cols)
let itemH : CGFloat = (collectionView.bounds.height - sectionInset.top - sectionInset.bottom - CGFloat(rows - 1) * lineSpacing) / CGFloat(rows)
// ่ฎก็ฎ็ดฏๅ ็็ปๆๅคๅฐ้กต
for sectionIndex in 0..<sectionCount {
let itemCount = collectionView.numberOfItems(inSection: sectionIndex)
// 4.ไธบๆฏไธไธชcellๅๅปบๅฏนๅบ็UICollectionViewLayoutAttributes
for itemIndex in 0..<itemCount {
// 4.1.ๅๅปบAttributes
let indexPath = IndexPath(item: itemIndex, section: sectionIndex)
let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
// 4.2.ๆฑๅบitemIndexๅจ่ฏฅ็ปไธญ็็ฌฌๅ ้กตไธญ็็ฌฌๅ ไธช
let pageIndex = itemIndex / (rows * cols)
let pageItemIndex = itemIndex % (rows * cols)
// 4.3.ๆฑitemIndexๅจ่ฏฅไนไธญ็ฌฌๅ ่ก/็ฌฌๅ ๅ
let rowIndex = pageItemIndex / cols
let colIndex = pageItemIndex % cols
// 4.2.่ฎพ็ฝฎAttributes็frame
let itemY : CGFloat = sectionInset.top + (itemH + lineSpacing) * CGFloat(rowIndex)
let itemX : CGFloat = CGFloat(pageCount + pageIndex) * collectionView.bounds.width + sectionInset.left + (itemW + itemSpacing) * CGFloat(colIndex)
attr.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH)
// 4.3.ๅฐAttributesๆทปๅ ๅฐๆฐ็ปไธญ
cellAttrs.append(attr)
}
// 5.่ฎก็ฎ่ฏฅ็ปไธๅ
ฑๅ ๆฎๅคๅฐ้กต
pageCount += (itemCount - 1) / (cols * rows) + 1
}
}
}
// MARK:- ่ฟๅๅธๅฑ
extension KPageViewLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return cellAttrs
}
}
// MARK:- ่ฎพ็ฝฎๅฏๆปๅจ็ๅบๅ
extension KPageViewLayout {
override var collectionViewContentSize: CGSize {
return CGSize(width: CGFloat(pageCount) * collectionView!.bounds.width, height: 0)
}
}
| mit | 304b1e7c14e45b13bfd6c659f6f1ded9 | 34.785714 | 162 | 0.607784 | 4.718995 | false | false | false | false |
ferranabello/FloatLabelFields | FloatLabelFields/Classes/FloatLabelTextView.swift | 1 | 7079 | //
// FloatLabelTextView.swift
// FloatLabelFields
//
// Created by Fahim Farook on 28/11/14.
// Copyright (c) 2014 RookSoft Ltd. All rights reserved.
//
import UIKit
@IBDesignable open class FloatLabelTextView: UITextView {
open let animationDuration = 0.3
open let placeholderTextColor = UIColor.lightGray.withAlphaComponent(0.65)
fileprivate var isIB = false
fileprivate var title = UILabel()
fileprivate var hintLabel = UILabel()
fileprivate var initialTopInset: CGFloat = 0
// MARK:- Properties
override open var accessibilityLabel: String? {
get {
if text.isEmpty {
return title.text!
} else {
return text
}
}
set {
}
}
open var titleFont: UIFont = UIFont.systemFont(ofSize: 12.0) {
didSet {
title.font = titleFont
}
}
@IBInspectable open var hint: String = "" {
didSet {
title.text = hint
title.sizeToFit()
var r = title.frame
r.size.width = frame.size.width
title.frame = r
hintLabel.text = hint
hintLabel.sizeToFit()
}
}
@IBInspectable open var hintYPadding: CGFloat = 0.0 {
didSet {
adjustTopTextInset()
}
}
@IBInspectable open var titleYPadding: CGFloat = 0.0 {
didSet {
var r = title.frame
r.origin.y = titleYPadding
title.frame = r
}
}
@IBInspectable open var titleTextColour: UIColor = UIColor.gray {
didSet {
if !isFirstResponder {
title.textColor = titleTextColour
}
}
}
@IBInspectable open var titleActiveTextColour: UIColor = UIColor.cyan {
didSet {
if isFirstResponder {
title.textColor = titleActiveTextColour
}
}
}
// MARK:- Init
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setup()
}
deinit {
if !isIB {
let nc = NotificationCenter.default
nc.removeObserver(self, name: NSNotification.Name.UITextViewTextDidChange, object: self)
nc.removeObserver(self, name: NSNotification.Name.UITextViewTextDidBeginEditing, object: self)
nc.removeObserver(self, name: NSNotification.Name.UITextViewTextDidEndEditing, object: self)
}
}
// MARK:- Overrides
override open func prepareForInterfaceBuilder() {
isIB = true
setup()
}
override open func layoutSubviews() {
super.layoutSubviews()
adjustTopTextInset()
hintLabel.alpha = text.isEmpty ? 1.0 : 0.0
let r = textRect()
hintLabel.frame = CGRect(x: r.origin.x, y: r.origin.y, width: hintLabel.frame.size.width, height: hintLabel.frame.size.height)
setTitlePositionForTextAlignment()
let isResp = isFirstResponder
if isResp && !text.isEmpty {
title.textColor = titleActiveTextColour
} else {
title.textColor = titleTextColour
}
// Should we show or hide the title label?
if text.isEmpty {
// Hide
hideTitle(isResp)
} else {
// Show
showTitle(isResp)
}
}
// MARK:- Private Methods
fileprivate func setup() {
initialTopInset = textContainerInset.top
textContainer.lineFragmentPadding = 0.0
titleActiveTextColour = tintColor
// Placeholder label
hintLabel.font = font
hintLabel.text = hint
hintLabel.numberOfLines = 0
hintLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
hintLabel.backgroundColor = UIColor.clear
hintLabel.textColor = placeholderTextColor
insertSubview(hintLabel, at: 0)
// Set up title label
title.alpha = 0.0
title.font = titleFont
title.textColor = titleTextColour
title.backgroundColor = backgroundColor
if !hint.isEmpty {
title.text = hint
title.sizeToFit()
}
self.addSubview(title)
// Observers
if !isIB {
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(layoutSubviews), name: NSNotification.Name.UITextViewTextDidChange, object: self)
nc.addObserver(self, selector: #selector(layoutSubviews), name: NSNotification.Name.UITextViewTextDidBeginEditing, object: self)
nc.addObserver(self, selector: #selector(layoutSubviews), name: NSNotification.Name.UITextViewTextDidEndEditing, object: self)
}
}
fileprivate func adjustTopTextInset() {
var inset = textContainerInset
inset.top = initialTopInset + title.font.lineHeight + hintYPadding
textContainerInset = inset
}
fileprivate func textRect() -> CGRect {
var r = UIEdgeInsetsInsetRect(bounds, contentInset)
r.origin.x += textContainer.lineFragmentPadding
r.origin.y += textContainerInset.top
return r.integral
}
fileprivate func setTitlePositionForTextAlignment() {
var titleLabelX = textRect().origin.x
var placeholderX = titleLabelX
if textAlignment == NSTextAlignment.center {
titleLabelX = (frame.size.width - title.frame.size.width) * 0.5
placeholderX = (frame.size.width - hintLabel.frame.size.width) * 0.5
} else if textAlignment == NSTextAlignment.right {
titleLabelX = frame.size.width - title.frame.size.width
placeholderX = frame.size.width - hintLabel.frame.size.width
}
var r = title.frame
r.origin.x = titleLabelX
title.frame = r
r = hintLabel.frame
r.origin.x = placeholderX
hintLabel.frame = r
}
fileprivate func showTitle(_ animated: Bool) {
let dur = animated ? animationDuration : 0
UIView.animate(withDuration: dur, delay: 0, options: [UIViewAnimationOptions.beginFromCurrentState, UIViewAnimationOptions.curveEaseOut], animations: {
// Animation
self.title.alpha = 1.0
var r = self.title.frame
r.origin.y = self.titleYPadding + self.contentOffset.y
self.title.frame = r
}, completion: nil)
}
fileprivate func hideTitle(_ animated: Bool) {
let dur = animated ? animationDuration : 0
UIView.animate(withDuration: dur, delay: 0, options: [UIViewAnimationOptions.beginFromCurrentState, UIViewAnimationOptions.curveEaseIn], animations: {
// Animation
self.title.alpha = 0.0
var r = self.title.frame
r.origin.y = self.title.font.lineHeight + self.hintYPadding
self.title.frame = r
}, completion: nil)
}
}
| mit | a2d41e9dfb51306ac87b5a58902f32e7 | 32.234742 | 159 | 0.606865 | 4.895574 | false | false | false | false |
Spriter/SwiftyHue | Sources/Base/BridgeResourceModels/AppData.swift | 1 | 1178 | //
// AppData.swift
// Pods
//
// Created by Marcel Dittmann on 21.04.16.
//
//
import Foundation
import Gloss
public struct AppData: Glossy {
/**
App specific version of the data field. App should take versioning into account when parsing the data string.
*/
public let version: Int
/**
App specific data. Free format string.
*/
public let data: String
public init(version: Int, data: String) {
self.version = version
self.data = data
}
public init?(json: JSON) {
guard let version: Int = "version" <~~ json, let data: String = "data" <~~ json else {
return nil
}
self.version = version
self.data = data
}
public func toJSON() -> JSON? {
return jsonify([
"version" ~~> version,
"data" ~~> data,
])
}
}
extension AppData: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(version)
}
}
public func ==(lhs: AppData, rhs: AppData) -> Bool {
return lhs.version == rhs.version && lhs.data == rhs.data
}
| mit | abedf4b19088d30cbaffa1e01938fd6a | 19.666667 | 117 | 0.540747 | 4.222222 | false | false | false | false |
benlangmuir/swift | test/Sema/diag_defer_block_end.swift | 25 | 517 | // RUN: %target-typecheck-verify-swift
let x = 1
let y = 2
if (x > y) {
defer { // expected-warning {{'defer' statement at end of scope always executes immediately}}{{5-10=do}}
print("not so useful defer stmt.")
}
}
func sr7307(_ value: Bool) {
let negated = !value
defer { // expected-warning {{'defer' statement at end of scope always executes immediately}}{{5-10=do}}
print("negated value is \(negated)")
}
}
sr7307(true)
defer { // No note
print("end of program.")
}
| apache-2.0 | a9c9d42066537c56f5da3997a35f9066 | 21.478261 | 108 | 0.615087 | 3.469799 | false | false | false | false |
benlangmuir/swift | test/Generics/interdependent_protocol_conformance_example_4.swift | 6 | 3107 | // RUN: %target-typecheck-verify-swift
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -disable-requirement-machine-reuse 2>&1 | %FileCheck %s
// CHECK-LABEL: .NonEmptyProtocol@
// CHECK-NEXT: Requirement signature: <Self where Self : Collection, Self.[NonEmptyProtocol]C : Collection, Self.[Sequence]Element == Self.[NonEmptyProtocol]C.[Sequence]Element, Self.[Collection]Index == Self.[NonEmptyProtocol]C.[Collection]Index>
public protocol NonEmptyProtocol: Collection
where Element == C.Element,
Index == C.Index {
associatedtype C: Collection
}
// CHECK-LABEL: .MultiPoint@
// CHECK-NEXT: Requirement signature: <Self where Self.[MultiPoint]C : CoordinateSystem, Self.[MultiPoint]P == Self.[MultiPoint]C.[CoordinateSystem]P, Self.[MultiPoint]X : NonEmptyProtocol, Self.[MultiPoint]C.[CoordinateSystem]P == Self.[MultiPoint]X.[Sequence]Element, Self.[MultiPoint]X.[NonEmptyProtocol]C : NonEmptyProtocol>
public protocol MultiPoint {
associatedtype C: CoordinateSystem
associatedtype P where Self.P == Self.C.P
associatedtype X: NonEmptyProtocol
where X.C: NonEmptyProtocol,
X.Element == Self.P
}
// CHECK-LABEL: .CoordinateSystem@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[CoordinateSystem]B.[BoundingBox]C, Self.[CoordinateSystem]B : BoundingBox, Self.[CoordinateSystem]L : Line, Self.[CoordinateSystem]P : Point, Self.[CoordinateSystem]S : Size, Self.[CoordinateSystem]B.[BoundingBox]C == Self.[CoordinateSystem]L.[MultiPoint]C, Self.[CoordinateSystem]L.[MultiPoint]C == Self.[CoordinateSystem]S.[Size]C>
public protocol CoordinateSystem {
associatedtype P: Point where Self.P.C == Self
associatedtype S: Size where Self.S.C == Self
associatedtype L: Line where Self.L.C == Self
associatedtype B: BoundingBox where Self.B.C == Self
}
// CHECK-LABEL: .Line@
// CHECK-NEXT: Requirement signature: <Self where Self : MultiPoint, Self.[MultiPoint]C == Self.[MultiPoint]P.[Point]C>
public protocol Line: MultiPoint {}
// CHECK-LABEL: .Size@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[Size]C.[CoordinateSystem]S, Self.[Size]C : CoordinateSystem>
public protocol Size {
associatedtype C: CoordinateSystem where Self.C.S == Self
}
// CHECK-LABEL: .BoundingBox@
// CHECK-NEXT: Requirement signature: <Self where Self.[BoundingBox]C : CoordinateSystem>
public protocol BoundingBox {
associatedtype C: CoordinateSystem
typealias P = Self.C.P
typealias S = Self.C.S
}
// CHECK-LABEL: .Point@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[Point]C.[CoordinateSystem]P, Self.[Point]C : CoordinateSystem>
public protocol Point {
associatedtype C: CoordinateSystem where Self.C.P == Self
}
func sameType<T>(_: T, _: T) {}
func conformsToPoint<T : Point>(_: T.Type) {}
func testMultiPoint<T : MultiPoint>(_: T) {
sameType(T.C.P.self, T.X.Element.self)
conformsToPoint(T.P.self)
}
func testCoordinateSystem<T : CoordinateSystem>(_: T) {
sameType(T.P.C.self, T.self)
}
| apache-2.0 | a5d596a049a3d4a6ce1743b50b0b9560 | 40.426667 | 397 | 0.734792 | 3.638173 | false | false | false | false |
cocoascientist/Passengr | Passengr/PassSignaler.swift | 1 | 3303 | //
// PassSignaler.swift
// Passengr
//
// Created by Andrew Shepard on 11/14/15.
// Copyright ยฉ 2015 Andrew Shepard. All rights reserved.
//
import Foundation
typealias PassesFuture = Future<[PassInfo]>
typealias PassFuture = Future<PassInfo>
final class PassSignaler {
private let controller = NetworkController()
private var error: Error? = nil
func future(for passInfo: [PassInfo]) -> PassesFuture {
let future: PassesFuture = Future() { completion in
let group = DispatchGroup()
var updates: [PassInfo] = []
for info in passInfo {
group.enter()
self.futureForPassInfo(info).start({ (result) -> () in
switch result {
case .success(let info):
updates.append(info)
case .failure(let error):
self.error = error
}
group.leave()
})
}
let queue = DispatchQueue.global()
group.notify(queue: queue, execute: {
if let error = self.error {
completion(Result.failure(error))
} else if updates.count == 0 {
completion(Result.failure(PassError.noData))
} else {
completion(Result.success(updates))
}
})
}
self.error = nil
return future
}
private func futureForPassInfo(_ info: PassInfo) -> PassFuture {
let future: PassFuture = Future() { completion in
guard let urlString = info[PassInfoKeys.ReferenceURL] else {
return completion(Result.failure(PassError.noData))
}
guard let url = URL(string: urlString) else {
return completion(Result.failure(PassError.noData))
}
let request = URLRequest(url: url)
let future = self.controller.data(for: request)
future.start { (result) -> () in
let passResult = result.map({ (data) -> PassInfo in
var passInfo = Parser.passInfoFromResponse(response: data)
for (key, value) in info {
passInfo[key] = value
}
return passInfo
})
completion(passResult)
}
}
return future
}
}
enum PassError: Error {
case noData
case offline
}
extension PassError {
init(error: TaskError) {
switch error {
case .offline:
self = PassError.offline
default:
self = PassError.noData
}
}
}
extension PassError: CustomStringConvertible {
var description: String {
switch self {
case .offline:
return NSLocalizedString("Connection is Offline", comment: "Connection is Offline")
case .noData:
return NSLocalizedString("No Data Received", comment: "No Data Received")
}
}
}
| mit | 845e302d50e62defbdccce2dd4c3711d | 27.713043 | 95 | 0.490309 | 5.27476 | false | false | false | false |
fellipecaetano/Redux.swift | Example/Source/CounterView.swift | 1 | 2612 | import UIKit
class CounterView: UIView {
let bigDecrementButton = UIButton(type: .system)
let smallDecrementButton = UIButton(type: .system)
let smallIncrementButton = UIButton(type: .system)
let bigIncrementButton = UIButton(type: .system)
let counterLabel = UILabel()
private var buttons: [UIButton] {
return [
bigDecrementButton,
smallDecrementButton,
smallIncrementButton,
bigIncrementButton
]
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
backgroundColor = .white
setupButton(bigDecrementButton, withTitle: "-5")
setupButton(smallDecrementButton, withTitle: "-1")
setupButton(smallIncrementButton, withTitle: "+1")
setupButton(bigIncrementButton, withTitle: "+5")
let buttonsView = UIStackView(arrangedSubviews: buttons)
setupButtonsView(buttonsView)
setupCounterLabel(counterLabel)
let contentView = UIStackView(arrangedSubviews: [counterLabel, buttonsView])
setupContentView(contentView)
}
private func setupButton(_ button: UIButton, withTitle title: String) {
button.heightAnchor.constraint(equalToConstant: 40).isActive = true
button.widthAnchor.constraint(equalToConstant: 40).isActive = true
button.setTitle(title, for: .normal)
}
private func setupButtonsView(_ buttonsView: UIStackView) {
buttonsView.axis = .horizontal
buttonsView.alignment = .center
buttonsView.spacing = 15
buttonsView.distribution = .equalSpacing
buttonsView.translatesAutoresizingMaskIntoConstraints = false
}
private func setupCounterLabel(_ counterLabel: UILabel) {
counterLabel.font = UIFont.boldSystemFont(ofSize: 45)
counterLabel.textAlignment = .center
}
private func setupContentView(_ contentView: UIStackView) {
contentView.axis = .vertical
contentView.alignment = .center
contentView.spacing = 100
contentView.distribution = .equalSpacing
contentView.translatesAutoresizingMaskIntoConstraints = false
addSubview(contentView)
contentView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
contentView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | aa59f4305bc210bbece4dc06e9343c53 | 32.922078 | 84 | 0.684916 | 5.385567 | false | false | false | false |
elationfoundation/Reporta-iOS | IWMF/ViewControllers/HomeLoginViewController/Step3_CreateAccountVC.swift | 1 | 12200 | //
// Step3_CreateAccountVC.swift
// IWMF
//
// This class is used for display Step-3 of Create Account.
//
//
import UIKit
class Step3_CreateAccountVC: UIViewController {
@IBOutlet var tbl : UITableView!
@IBOutlet weak var ARbtnNavBack: UIButton!
@IBOutlet weak var btnNavBack: UIButton!
@IBOutlet weak var contactlistLable: UILabel!
var createAccntArr : NSMutableArray!
var circle : Circle!
override func viewDidLoad() {
super.viewDidLoad()
btnNavBack.setTitle(NSLocalizedString(Utility.getKey("back"),comment:""), forState: .Normal)
ARbtnNavBack.setTitle(NSLocalizedString(Utility.getKey("back"),comment:""), forState: .Normal)
contactlistLable.text = NSLocalizedString(Utility.getKey("contacts"),comment:"")
createAccntArr = NSMutableArray()
var cell: NextFooterTableViewCell? = tbl.dequeueReusableCellWithIdentifier(Structures.TableViewCellIdentifiers.nextFooterCellIdentifier) as? NextFooterTableViewCell
let arr : NSArray = NSBundle.mainBundle().loadNibNamed("NextFooterTableViewCell", owner: self, options: nil)
cell = arr[0] as? NextFooterTableViewCell
cell?.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 80)
cell?.nextBtn.addTarget(self, action: "btnNextClicked:", forControlEvents: .TouchUpInside)
cell?.nextBtn.setTitle(NSLocalizedString(Utility.getKey("Next"),comment:""), forState: .Normal)
tbl.tableFooterView = cell
tbl.reloadData()
if let path = NSBundle.mainBundle().pathForResource("Step3_CreateAccount", ofType: "plist")
{
createAccntArr = NSMutableArray(contentsOfFile: path)
let arrTemp : NSMutableArray = NSMutableArray(array: createAccntArr)
for (index, element) in arrTemp.enumerate() {
if var innerDict = element as? Dictionary<String, AnyObject> {
let strTitle = innerDict["Title"] as! String!
if strTitle.characters.count != 0
{
let strOptionTitle = innerDict["OptionTitle"] as! String!
if strOptionTitle != nil
{
if strOptionTitle == "Edit"
{
innerDict["OptionTitle"] = NSLocalizedString(Utility.getKey("Edit"),comment:"")
}
}
innerDict["Title"] = NSLocalizedString(Utility.getKey(strTitle),comment:"")
self.createAccntArr.replaceObjectAtIndex(index, withObject: innerDict)
}
}
}
}
//Arabic Alignment
if Structures.Constant.appDelegate.isArabic == true
{
btnNavBack.hidden = true
}
else
{
ARbtnNavBack.hidden = true
}
self.contactlistLable.font = Utility.setNavigationFont()
if Structures.Constant.appDelegate.contactScreensFrom == ContactsFrom.CreateAccount
{
self.contactlistLable.text = NSLocalizedString(Utility.getKey("create_account_header"),comment:"")
}
self.automaticallyAdjustsScrollViewInsets = false
self.tbl.registerNib(UINib(nibName: "HelpTextViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.HelpTextViewCellIdentifier)
self.tbl.registerNib(UINib(nibName: "ARTitleTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.ARTitleTableViewCellIdentifier)
self.tbl.registerNib(UINib(nibName: "TitleTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.TitleTableViewCellIdentifier)
self.tbl.registerNib(UINib(nibName: "TitleTableViewCell2", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.TitleTableViewCellIdentifier2)
}
override func viewWillDisappear(animated: Bool)
{
self.view.endEditing(true)
}
override func viewWillAppear(animated: Bool)
{
tbl.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnBackPressed(sender: AnyObject)
{
backToPreviousScreen()
}
func backToPreviousScreen()
{
let arrVcs : NSArray! = self.navigationController!.viewControllers as NSArray
var vc :Step2_CreateAccountVC
for var i : Int = 0 ; i < arrVcs.count ; i++
{
if arrVcs.objectAtIndex(i) .isKindOfClass(Step2_CreateAccountVC)
{
vc = arrVcs[i] as! Step2_CreateAccountVC
self.navigationController?.popToViewController(vc, animated: true)
break;
}
}
}
@IBAction func btnNextClicked(sender:AnyObject)
{
if (Structures.Constant.appDelegate.dictSignUpCircle?.valueForKey("Contacts") as! NSArray).count > 0
{
var sos_enabeled : Bool!
sos_enabeled = false
for (var i : Int = 0; i < (Structures.Constant.appDelegate.dictSignUpCircle.valueForKey("Contacts") as! NSArray).count ; i++ )
{
if ((Structures.Constant.appDelegate.dictSignUpCircle.valueForKey("Contacts") as! NSArray).objectAtIndex(i).valueForKey("sos_enabled") as! NSString) == "2"
{
sos_enabeled = true
}
}
if sos_enabeled == true
{
let vc : Step4_CreateAccountVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Step4_CreateAccountVC") as! Step4_CreateAccountVC
vc.circle = self.circle!
showViewController(vc, sender: self.view)
}
else
{
Utility.showAlertWithTitle(NSLocalizedString(Utility.getKey("you_must_select"),comment:""), strMessage: "", strButtonTitle: NSLocalizedString(Utility.getKey("Ok"),comment:""), view: self)
}
}
else
{
Utility.showAlertWithTitle(NSLocalizedString(Utility.getKey("no_contact_added"),comment:""), strMessage: "", strButtonTitle: NSLocalizedString(Utility.getKey("Ok"),comment:""), view: self)
}
}
//MARK:- UITableView Delegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.createAccntArr.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
if self.createAccntArr[indexPath.row]["CellIdentifier"] as? NSString == Structures.TableViewCellIdentifiers.HelpTextViewCellIdentifier
{
let cell: HelpTextViewCell = tableView.dequeueReusableCellWithIdentifier(Structures.TableViewCellIdentifiers.HelpTextViewCellIdentifier) as! HelpTextViewCell!
cell.txtHelpTextView.frame = CGRectMake(cell.txtHelpTextView.frame.origin.x, cell.txtHelpTextView.frame.origin.y, tableView.frame.size.width - 60, cell.txtHelpTextView.frame.size.height)
cell.txtHelpTextView.attributedText = CommonUnit.boldSubstring(NSLocalizedString(Utility.getKey("must_enable_app_unlock1"),comment:"") , string: NSLocalizedString(Utility.getKey("must_enable_app_unlock1"),comment:"") + "\n\n" + NSLocalizedString(Utility.getKey("must_enable_app_unlock2"),comment:""), fontName: cell.txtHelpTextView.font)
cell.txtHelpTextView.sizeToFit()
return cell.txtHelpTextView.frame.size.height + 60
}
let kRowHeight = self.createAccntArr[indexPath.row]["RowHeight"] as! CGFloat
return kRowHeight;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let kCellIdentifier = self.createAccntArr[indexPath.row]["CellIdentifier"] as! String
if Structures.Constant.appDelegate.isArabic == true && kCellIdentifier == "TitleTableViewCellIdentifier"
{
if let cell: ARTitleTableViewCell = tableView.dequeueReusableCellWithIdentifier("ARTitleTableViewCellIdentifier") as? ARTitleTableViewCell
{
cell.lblDetail.text = self.createAccntArr[indexPath.row]["OptionTitle"] as! String!
cell.levelString = self.createAccntArr[indexPath.row]["Level"] as! NSString!
cell.lblTitle.text = self.createAccntArr[indexPath.row]["Title"] as! String!
cell.lblTitle.textColor = UIColor(red: 18/255.0, green: 115/255.0, blue: 211/255.0, alpha: 1);
cell.intialize()
return cell
}
}
else
{
if let cell: TitleTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? TitleTableViewCell
{
cell.lblDetail.text = self.createAccntArr[indexPath.row]["OptionTitle"] as! String!
cell.levelString = self.createAccntArr[indexPath.row]["Level"] as! String!
cell.lblTitle.text = self.createAccntArr[indexPath.row]["Title"] as! String!
cell.lblTitle.textColor = UIColor(red: 18/255.0, green: 115/255.0, blue: 211/255.0, alpha: 1);
cell.intialize()
return cell
}
}
if let cell: TitleTableViewCell2 = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? TitleTableViewCell2
{
cell.levelString = self.createAccntArr[indexPath.row]["Level"] as! String!
cell.lblTitle.text = self.createAccntArr[indexPath.row]["Title"] as! String!
if Structures.Constant.appDelegate.isArabic == true
{
cell.lblTitle.textAlignment = NSTextAlignment.Right
}
else
{
cell.lblTitle.textAlignment = NSTextAlignment.Left
}
cell.intialize()
return cell
}
if let cell: HelpTextViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? HelpTextViewCell
{
cell.txtHelpTextView.attributedText = CommonUnit.boldSubstring(NSLocalizedString(Utility.getKey("must_enable_app_unlock1"),comment:"") , string: NSLocalizedString(Utility.getKey("must_enable_app_unlock1"),comment:"") + "\n\n" + NSLocalizedString(Utility.getKey("must_enable_app_unlock2"),comment:""), fontName: cell.txtHelpTextView.font)
if Structures.Constant.appDelegate.isArabic == true
{
cell.txtHelpTextView.textAlignment = NSTextAlignment.Right
}
else
{
cell.txtHelpTextView.textAlignment = NSTextAlignment.Left
}
return cell
}
let blankCell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier)!
return blankCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if indexPath.row == 2
{
let vc : Step3_EnableFriendUnlockVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Step3_EnableFriendUnlockVC") as! Step3_EnableFriendUnlockVC
showViewController(vc, sender: self.view)
}
}
// 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?) {
if segue.identifier == "AddFromAddressBookPush"
{
let vc : AllContactsListVC = segue.destinationViewController as! AllContactsListVC
vc.objContactViewType = contactViewType.FromAddressBook
vc.circle = self.circle
}
}
} | gpl-3.0 | 8edcfd704c971a150d03f8cdba3cd0fe | 48.396761 | 350 | 0.640984 | 5.022643 | false | false | false | false |
yrchen/edx-app-ios | Source/OfflineModeView.swift | 1 | 1852 | //
// OfflineModeView.swift
// edX
//
// Created by Akiva Leffert on 5/15/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
public class OfflineModeView: UIView {
private let verticalMargin = 3
private let bottomDivider : UIView = UIView(frame: CGRectZero)
private let messageView : UILabel = UILabel(frame: CGRectZero)
private let styles : OEXStyles
private var contrastColor : UIColor? {
return styles.secondaryDarkColor()
}
public init(frame: CGRect, styles : OEXStyles) {
self.styles = styles
super.init(frame: frame)
addSubview(bottomDivider)
addSubview(messageView)
backgroundColor = styles.secondaryXLightColor()
bottomDivider.backgroundColor = contrastColor
messageView.attributedText = labelStyle.attributedStringWithText(Strings.offlineMode)
addConstraints()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var labelStyle : OEXTextStyle {
return OEXTextStyle(weight: .SemiBold, size: .XXSmall, color: contrastColor)
}
private func addConstraints() {
bottomDivider.snp_makeConstraints {make in
make.bottom.equalTo(self)
make.height.equalTo(OEXStyles.dividerSize())
make.leading.equalTo(self)
make.trailing.equalTo(self)
}
messageView.snp_makeConstraints {make in
make.top.equalTo(self).offset(verticalMargin)
make.bottom.equalTo(self).offset(-verticalMargin)
make.leading.equalTo(self).offset(StandardHorizontalMargin)
make.trailing.lessThanOrEqualTo(self).offset(StandardHorizontalMargin)
}
}
}
| apache-2.0 | b340b268780600577ce863a51f43fbb4 | 28.396825 | 93 | 0.643089 | 5.005405 | false | false | false | false |
sarah-j-smith/Quest | Common/QuestView.swift | 1 | 3070 | //
// QuestViewController.swift
// SwiftQuest
//
// Created by Sarah Smith on 22/12/2014.
// Copyright (c) 2014 Sarah Smith. All rights reserved.
//
import Foundation
import Cocoa
import WebKit
class QuestView : NSViewController
{
@IBOutlet var webView : WebView!
var stateManager : StatesManager!
var model : GameState {
set {
stateManager = StatesManager(gameState: newValue)
}
get {
return stateManager.gameState
}
}
func loadHtml(htmlString: String)
{
let defaults = NSUserDefaults.standardUserDefaults()
if let webPath: String = defaults.valueForKey("webpath") as? String
{
var err : NSError?
let ok = htmlString.writeToFile(webPath, atomically: false, encoding: NSUTF8StringEncoding, error: &err)
if (ok)
{
NSLog("Wrote HTML: \(webPath)")
}
else
{
NSLog("Could not write to file \(webPath) : \(err?.localizedDescription)")
}
}
else
{
NSLog("No log directory specified for saving HTML file")
}
let bundle = NSBundle.mainBundle()
let baseURL = bundle.resourceURL
webView.mainFrame.loadHTMLString(htmlString, baseURL: baseURL)
}
func refreshView()
{
let html = stateManager.currentHTML()
loadHtml(html)
}
func showAlert(alertString: String, title: String)
{
// let alert = NSAlert()
// alert.messageText = title
// alert.informativeText = alertString
// alert.alertStyle = NSAlertStyle.InformationalAlertStyle
// alert.addButtonWithTitle("OK")
//
// if let w = webView.window
// {
// alert.beginSheetModalForWindow(w, completionHandler: { (response: NSModalResponse) -> Void in
// self.refreshView()
// })
// }
stateManager.renderer.setPopover(bodyText: alertString, titleText: title)
refreshView()
}
override func webView(sender: WebView!, didFailLoadWithError error: NSError!, forFrame frame: WebFrame!)
{
print("didFailLoadWithError")
println(error)
}
override func webView(sender: WebView!, didFailProvisionalLoadWithError error: NSError!, forFrame frame: WebFrame!)
{
print("didFailProvisionalLoadWithError")
println(error)
}
override func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!)
{
print("decidePolicyForNavigationAction: ")
println(request.URL)
if let frag = request.URL.fragment
{
let ( actName, newText ) = stateManager.executeAction( frag )
showAlert(newText, title: actName )
NSLog("Got fragment: \(frag)")
}
listener.use()
}
}
| mit | 7f4939bd9999906d96acaa58fd59073a | 28.805825 | 217 | 0.597394 | 4.904153 | false | false | false | false |
Browncoat/NCCCoreDataClient | Samples/iOS_Swift/CoreDataClientSample/Comment+JSON.swift | 1 | 1197 | //
// CommentJSON.swift
// CoreDataClientSample
//
// Created by Nathaniel Potter on 1/27/15.
// Copyright (c) 2015 Nathaniel Potter. All rights reserved.
//
import Foundation
extension Comment {
override func updateWithDictionary(dictionary: [NSObject : AnyObject]!) {
self.id = dictionary["id"] as String
self.text = dictionary["text"] as String
struct DateFormatter {
static var dateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter
}()
}
var dateFormatter: NSDateFormatter {
get { return DateFormatter.dateFormatter }
}
if let date = dateFormatter.dateFromString(dictionary["created_at"] as String) {
self.createdTime = date
}
let userDict = dictionary["from"] as NSDictionary
let userId = (dictionary["from"] as NSDictionary)["id"] as NSString
self.from = User.upsertObjectWithDictionary(userDict, uid: userId, inManagedObjectContext: self.managedObjectContext)
}
} | mit | 650eda168a1263d45debfdd67b9fe21d | 31.378378 | 125 | 0.6132 | 5.32 | false | false | false | false |
brentsimmons/Evergreen | ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchFeedUnreadCountOperation.swift | 1 | 1900 | //
// FetchFeedUnreadCountOperation.swift
// ArticlesDatabase
//
// Created by Brent Simmons on 1/27/20.
// Copyright ยฉ 2020 Ranchero Software. All rights reserved.
//
import Foundation
import RSCore
import RSDatabase
import RSDatabaseObjC
/// Fetch the unread count for a single feed.
public final class FetchFeedUnreadCountOperation: MainThreadOperation {
var result: SingleUnreadCountResult = .failure(.isSuspended)
// MainThreadOperation
public var isCanceled = false
public var id: Int?
public weak var operationDelegate: MainThreadOperationDelegate?
public var name: String? = "FetchFeedUnreadCountOperation"
public var completionBlock: MainThreadOperation.MainThreadOperationCompletionBlock?
private let queue: DatabaseQueue
private let cutoffDate: Date
private let webFeedID: String
init(webFeedID: String, databaseQueue: DatabaseQueue, cutoffDate: Date) {
self.webFeedID = webFeedID
self.queue = databaseQueue
self.cutoffDate = cutoffDate
}
public func run() {
queue.runInDatabase { databaseResult in
if self.isCanceled {
self.informOperationDelegateOfCompletion()
return
}
switch databaseResult {
case .success(let database):
self.fetchUnreadCount(database)
case .failure:
self.informOperationDelegateOfCompletion()
}
}
}
}
private extension FetchFeedUnreadCountOperation {
func fetchUnreadCount(_ database: FMDatabase) {
let sql = "select count(*) from articles natural join statuses where feedID=? and read=0;"
guard let resultSet = database.executeQuery(sql, withArgumentsIn: [webFeedID]) else {
informOperationDelegateOfCompletion()
return
}
if isCanceled {
informOperationDelegateOfCompletion()
return
}
if resultSet.next() {
let unreadCount = resultSet.long(forColumnIndex: 0)
result = .success(unreadCount)
}
resultSet.close()
informOperationDelegateOfCompletion()
}
}
| mit | 2f2ee9aa6f344adc840e534ad4649f20 | 24.32 | 92 | 0.762507 | 4.101512 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples | GooglePlaces-Swift/GooglePlacesSwiftDemos/Swift/Samples/Autocomplete/AutocompleteWithSearchViewController.swift | 1 | 3241 | // Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GooglePlaces
import UIKit
/// Demo showing the use of GMSAutocompleteViewController with a UISearchController. Please refer to
/// https://developers.google.com/places/ios-sdk/autocomplete
class AutocompleteWithSearchViewController: AutocompleteBaseViewController {
let searchBarAccessibilityIdentifier = "searchBarAccessibilityIdentifier"
private lazy var autoCompleteController: GMSAutocompleteResultsViewController = {
let controller = GMSAutocompleteResultsViewController()
if let config = autocompleteConfiguration {
controller.autocompleteFilter = config.autocompleteFilter
controller.placeFields = config.placeFields
}
controller.delegate = self
return controller
}()
private lazy var searchController: UISearchController = {
let controller =
UISearchController(searchResultsController: autoCompleteController)
controller.hidesNavigationBarDuringPresentation = false
controller.searchBar.autoresizingMask = .flexibleWidth
controller.searchBar.searchBarStyle = .minimal
controller.searchBar.delegate = self
controller.searchBar.accessibilityIdentifier = searchBarAccessibilityIdentifier
controller.searchBar.sizeToFit()
return controller
}()
override func viewDidLoad() {
super.viewDidLoad()
autoCompleteController.delegate = self
navigationItem.titleView = searchController.searchBar
definesPresentationContext = true
searchController.searchResultsUpdater = autoCompleteController
searchController.modalPresentationStyle =
UIDevice.current.userInterfaceIdiom == .pad ? .popover : .fullScreen
// Prevents the tableview goes under the navigation bar.
automaticallyAdjustsScrollViewInsets = true
}
}
extension AutocompleteWithSearchViewController: GMSAutocompleteResultsViewControllerDelegate {
func resultsController(
_ resultsController: GMSAutocompleteResultsViewController,
didAutocompleteWith place: GMSPlace
) {
searchController.isActive = false
super.autocompleteDidSelectPlace(place)
}
func resultsController(
_ resultsController: GMSAutocompleteResultsViewController,
didFailAutocompleteWithError error: Error
) {
searchController.isActive = false
super.autocompleteDidFail(error)
}
}
extension AutocompleteWithSearchViewController: UISearchBarDelegate {
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
// Inform user that the autocomplete query has been cancelled and dismiss the search bar.
searchController.isActive = false
searchController.searchBar.isHidden = true
super.autocompleteDidCancel()
}
}
| apache-2.0 | 8bc0b3d4173c582cffcdfe14ca86db88 | 37.129412 | 100 | 0.78556 | 5.736283 | false | false | false | false |
grantmagdanz/InupiaqKeyboard | Keyboard/KeyboardModel.swift | 2 | 5528 | //
// KeyboardModel.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/10/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import Foundation
var counter = 0
enum ShiftState {
case Disabled
case Enabled
case Locked
func uppercase() -> Bool {
switch self {
case Disabled:
return false
case Enabled:
return true
case Locked:
return true
}
}
}
class Keyboard {
var pages: [Page]
init() {
self.pages = []
}
func addKey(key: Key, row: Int, page: Int) {
if self.pages.count <= page {
for _ in self.pages.count...page {
self.pages.append(Page())
}
}
self.pages[page].addKey(key, row: row)
}
}
class Page {
var rows: [[Key]]
init() {
self.rows = []
}
func addKey(key: Key, row: Int) {
if self.rows.count <= row {
for _ in self.rows.count...row {
self.rows.append([])
}
}
self.rows[row].append(key)
}
}
class Key: Hashable {
enum KeyType: String {
case Character = "Character"
case SpecialCharacter = "SpecialCharacter"
case Shift = "Shift"
case Backspace = "Backspace"
case LetterChange = "ABC"
case NumberChange = "123"
case SpecialCharacterChange = "#+="
case KeyboardChange = "KeyboardChange"
case Period = "Period"
case Space = "Space"
case Return = "Return"
case Settings = "Settings"
case Other = "Other"
}
var type: KeyType
var uppercaseKeyCap: String?
var lowercaseKeyCap: String?
var uppercaseOutput: String?
var lowercaseOutput: String?
var extraCharacters: [String] = []
var uppercaseExtraCharacters: [String] = []
var toMode: Int? //if the key is a mode button, this indicates which page it links to
var isCharacter: Bool {
get {
switch self.type {
case
.Character,
.SpecialCharacter,
.Period:
return true
default:
return false
}
}
}
var isSpecial: Bool {
get {
switch self.type {
case .Shift:
return true
case .Backspace:
return true
case .LetterChange:
return true
case .NumberChange:
return true
case .SpecialCharacterChange:
return true
case .KeyboardChange:
return true
case .Return:
return true
case .Settings:
return true
default:
return false
}
}
}
var hasOutput: Bool {
get {
return (self.uppercaseOutput != nil) || (self.lowercaseOutput != nil)
}
}
// TODO: this is kind of a hack
var hashValue: Int
init(_ type: KeyType) {
self.type = type
self.hashValue = counter
counter += 1
}
convenience init(_ key: Key) {
self.init(key.type)
self.uppercaseKeyCap = key.uppercaseKeyCap
self.lowercaseKeyCap = key.lowercaseKeyCap
self.uppercaseOutput = key.uppercaseOutput
self.lowercaseOutput = key.lowercaseOutput
self.toMode = key.toMode
}
func setExtraLetters(letters: [String]) {
for letter in letters {
self.extraCharacters.append((letter as NSString).lowercaseString)
self.uppercaseExtraCharacters.append((letter as NSString).uppercaseString)
}
}
func setLetter(letter: String) {
self.lowercaseOutput = (letter as NSString).lowercaseString
self.uppercaseOutput = (letter as NSString).uppercaseString
self.lowercaseKeyCap = self.lowercaseOutput
self.uppercaseKeyCap = self.uppercaseOutput
}
func outputForCase(uppercase: Bool) -> String {
if uppercase {
if self.uppercaseOutput != nil {
return self.uppercaseOutput!
}
else if self.lowercaseOutput != nil {
return self.lowercaseOutput!
}
else {
return ""
}
}
else {
if self.lowercaseOutput != nil {
return self.lowercaseOutput!
}
else if self.uppercaseOutput != nil {
return self.uppercaseOutput!
}
else {
return ""
}
}
}
func keyCapForCase(uppercase: Bool) -> String {
if uppercase {
if self.uppercaseKeyCap != nil {
return self.uppercaseKeyCap!
}
else if self.lowercaseKeyCap != nil {
return self.lowercaseKeyCap!
}
else {
return ""
}
}
else {
if self.lowercaseKeyCap != nil {
return self.lowercaseKeyCap!
}
else if self.uppercaseKeyCap != nil {
return self.uppercaseKeyCap!
}
else {
return ""
}
}
}
}
func ==(lhs: Key, rhs: Key) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| bsd-3-clause | 34cacc93daadc1cf29e1b0ea3c3eae0a | 23.789238 | 89 | 0.502352 | 5.053016 | false | false | false | false |
Czajnikowski/TrainTrippin | Pods/RxCocoa/RxCocoa/CocoaUnits/ControlProperty.swift | 3 | 4230 | //
// ControlProperty.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 8/28/15.
// Copyright ยฉ 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
/**
Protocol that enables extension of `ControlProperty`.
*/
public protocol ControlPropertyType : ObservableType, ObserverType {
/**
- returns: `ControlProperty` interface
*/
func asControlProperty() -> ControlProperty<E>
}
/**
Unit for `Observable`/`ObservableType` that represents property of UI element.
It's properties are:
- it never fails
- `shareReplay(1)` behavior
- it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced
- it will `Complete` sequence on control being deallocated
- it never errors out
- it delivers events on `MainScheduler.instance`
**The implementation of `ControlProperty` will ensure that sequence of values is being subscribed on main scheduler
(`subscribeOn(ConcurrentMainScheduler.instance)` behavior).**
**It is implementor's responsibility to make sure that that all other properties enumerated above are satisfied.**
**If they aren't, then using this unit communicates wrong properties and could potentially break someone's code.**
**In case `values` observable sequence that is being passed into initializer doesn't satisfy all enumerated
properties, please don't use this unit.**
*/
public struct ControlProperty<PropertyType> : ControlPropertyType {
public typealias E = PropertyType
let _values: Observable<PropertyType>
let _valueSink: AnyObserver<PropertyType>
/**
Initializes control property with a observable sequence that represents property values and observer that enables
binding values to property.
- parameter values: Observable sequence that represents property values.
- parameter valueSink: Observer that enables binding values to control property.
- returns: Control property created with a observable sequence of values and an observer that enables binding values
to property.
*/
public init<V: ObservableType, S: ObserverType>(values: V, valueSink: S) where E == V.E, E == S.E {
_values = values.subscribeOn(ConcurrentMainScheduler.instance)
_valueSink = valueSink.asObserver()
}
/**
Subscribes an observer to control property values.
- parameter observer: Observer to subscribe to property values.
- returns: Disposable object that can be used to unsubscribe the observer from receiving control property values.
*/
public func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
return _values.subscribe(observer)
}
/**
- returns: `Observable` interface.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func asObservable() -> Observable<E> {
return _values
}
/**
- returns: `ControlProperty` interface.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func asControlProperty() -> ControlProperty<E> {
return self
}
/**
Binds event to user interface.
- In case next element is received, it is being set to control value.
- In case error is received, DEBUG buids raise fatal error, RELEASE builds log event to standard output.
- In case sequence completes, nothing happens.
*/
public func on(_ event: Event<E>) {
switch event {
case .error(let error):
bindingErrorToInterface(error)
case .next:
_valueSink.on(event)
case .completed:
_valueSink.on(event)
}
}
}
extension ControlPropertyType where E == String? {
/**
Transforms control property of type `String?` into control property of type `String`.
*/
public var orEmpty: ControlProperty<String> {
let original: ControlProperty<String?> = self.asControlProperty()
let values: Observable<String> = original._values.map { $0 ?? "" }
let valueSink: AnyObserver<String> = original._valueSink.map { $0 }
return ControlProperty<String>(values: values, valueSink: valueSink)
}
}
| mit | bcdd0f01539b9ed7a562652b9f2986c5 | 33.382114 | 121 | 0.688815 | 4.800227 | false | false | false | false |
akpw/VisualBinaryTrees | VisualBinaryTrees.playground/Pages/Example-Constructing from traversals.xcplaygroundpage/Contents.swift | 1 | 1044 | /*:
- example:
[Constructing a Binary Tree from in-order and post-order traversals](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal)
[Next Page](@next)
[Previous Page](@previous)
*/
import Foundation
let originalTree = TreeNodeRef(SequenceHelper.randomCharacterSequence(length: 14))
let inOrder = originalTree.map{$0.element}
print("Input in-order: \(inOrder)")
originalTree.traversalStrategy = PostOrderTraversalStrategy.self
let postOrder = originalTree.map{$0.element}
print("Input post-order: \(postOrder)")
/*:
* callout(Exercise):
Given the `inOrder` and `postOrder` traversals, re-construct the originalTree
*/
// Solution:
// See `TreeBuilder` in this PlaygroundPage's sources.
// The tree quicklook shows what was constructed, so it can be visually compared with the originalTree
let reconstructedTree = TreeBuilder.buildTree(inOrder: inOrder, postOrder: postOrder)
// test
assert(originalTree == reconstructedTree)
/*:
[Next Page](@next)
[Previous Page](@previous)
*/
| gpl-3.0 | 2d945c28425349fe05d02d47793b0415 | 28 | 160 | 0.756705 | 3.755396 | false | false | false | false |
biohazardlover/ROer | Roer/StatusCalculatorNavigatorView.swift | 1 | 2919 |
import UIKit
enum StatusCalculatorNavigatorItem: String {
case Character = "Character"
case Equipment = "Equipment"
case Buffs = "Buffs"
case Items = "Items"
case Combat = "Combat"
static let allValues: [StatusCalculatorNavigatorItem] = [.Character, .Equipment, .Buffs, .Items, .Combat]
var index: Int {
return StatusCalculatorNavigatorItem.allValues.index(of: self)!
}
func successor() -> StatusCalculatorNavigatorItem {
if index == StatusCalculatorNavigatorItem.allValues.count - 1 {
return self
} else {
return StatusCalculatorNavigatorItem.allValues[index + 1]
}
}
func predecessor() -> StatusCalculatorNavigatorItem {
if index == 0 {
return self
} else {
return StatusCalculatorNavigatorItem.allValues[index - 1]
}
}
}
protocol StatusCalculatorNavigatorViewDelegate: NSObjectProtocol {
func statusCalculatorNavigatorView(_ navigatorView: StatusCalculatorNavigatorView, didSelectNavigatorItem navigatorItem: StatusCalculatorNavigatorItem)
}
class StatusCalculatorNavigatorView: UIView {
var delegate: StatusCalculatorNavigatorViewDelegate?
var selectedNavigatorItem: StatusCalculatorNavigatorItem = .Character {
didSet {
let index = selectedNavigatorItem.index
let button = scrollView.viewWithTag(index) as! UIButton
layoutSubviewsForClickedButton(button)
}
}
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var selectionIndicator: UIView!
@IBOutlet var selectionIndicatorLeadingConstraint: NSLayoutConstraint!
@IBOutlet var selectionIndicatorTrailingConstraint: NSLayoutConstraint!
@IBOutlet var currentSelectedButton: UIButton!
@IBAction func navigatorItemButtonClicked(_ button: UIButton) {
selectedNavigatorItem = StatusCalculatorNavigatorItem.allValues[button.tag]
delegate?.statusCalculatorNavigatorView(self, didSelectNavigatorItem: selectedNavigatorItem)
}
func layoutSubviewsForClickedButton(_ button: UIButton) {
selectionIndicatorLeadingConstraint.isActive = false
selectionIndicatorTrailingConstraint.isActive = false
selectionIndicatorLeadingConstraint = selectionIndicator.leadingAnchor.constraint(equalTo: button.leadingAnchor)
selectionIndicatorTrailingConstraint = selectionIndicator.trailingAnchor.constraint(equalTo: button.trailingAnchor)
selectionIndicatorLeadingConstraint.isActive = true
selectionIndicatorTrailingConstraint.isActive = true
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.scrollView.layoutIfNeeded()
})
currentSelectedButton.isSelected = false
currentSelectedButton = button
currentSelectedButton.isSelected = true
}
}
| mit | 764c441961d5d067e6b629ba598ce407 | 37.407895 | 155 | 0.714628 | 5.701172 | false | false | false | false |
scoremedia/Fisticuffs | Sources/Fisticuffs/TransformBindingHandler.swift | 1 | 2760 | //
// TransformBindingHandler.swift
// Fisticuffs
//
// Created by Darren Clark on 2016-02-12.
// Copyright ยฉ 2016 theScore. All rights reserved.
//
import Foundation
private struct NoReverseTransformError: Error {}
open class TransformBindingHandler<Control: AnyObject, InDataValue, OutDataValue, PropertyValue>: BindingHandler<Control, InDataValue, PropertyValue> {
let bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>
let transform: (InDataValue) -> OutDataValue
let reverseTransform: ((OutDataValue) -> InDataValue)?
init(_ transform: @escaping (InDataValue) -> OutDataValue, reverse: ((OutDataValue) -> InDataValue)?, bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>) {
self.bindingHandler = bindingHandler
self.transform = transform
self.reverseTransform = reverse
}
open override func set(control: Control, oldValue: InDataValue?, value: InDataValue, propertySetter: @escaping PropertySetter) {
bindingHandler.set(control: control, oldValue: oldValue.map(transform), value: transform(value), propertySetter: propertySetter)
}
open override func get(control: Control, propertyGetter: @escaping PropertyGetter) throws -> InDataValue {
guard let reverseTransform = reverseTransform else {
throw NoReverseTransformError()
}
let value = try bindingHandler.get(control: control, propertyGetter: propertyGetter)
return reverseTransform(value)
}
override open func dispose() {
bindingHandler.dispose()
super.dispose()
}
}
public extension BindingHandlers {
static func transform<Control, DataValue, PropertyValue>(_ block: @escaping (DataValue) -> PropertyValue) -> TransformBindingHandler<Control, DataValue, PropertyValue, PropertyValue> {
TransformBindingHandler(block, reverse: nil, bindingHandler: DefaultBindingHandler())
}
static func transform<Control, DataValue, PropertyValue>(_ block: @escaping (DataValue) -> PropertyValue, reverse: @escaping (PropertyValue) -> DataValue) -> TransformBindingHandler<Control, DataValue, PropertyValue, PropertyValue> {
TransformBindingHandler(block, reverse: reverse, bindingHandler: DefaultBindingHandler())
}
static func transform<Control, InDataValue, OutDataValue, PropertyValue>(_ block: @escaping (InDataValue) -> OutDataValue, reverse: ((OutDataValue) -> InDataValue)?, bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>)
-> TransformBindingHandler<Control, InDataValue, OutDataValue, PropertyValue> {
TransformBindingHandler<Control, InDataValue, OutDataValue, PropertyValue>(block, reverse: reverse, bindingHandler: bindingHandler)
}
}
| mit | 30eb5b23e11c387ba4d7bf30af8960ca | 47.403509 | 239 | 0.742298 | 4.421474 | false | false | false | false |
salesforce-ux/design-system-ios | Demo-Swift/slds-sample-app/library/views/LibraryCell.swift | 1 | 2434 | // Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
import UIKit
class LibraryCell: UITableViewCell {
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.loadView()
}
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
override func layoutSubviews() {
super.layoutSubviews()
if let label = self.textLabel {
label.frame = CGRect(x: 0, y: 10, width: self.frame.width, height: 30)
}
}
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
func loadView() {
self.backgroundColor = UIColor.sldsFill(.brandActive)
self.selectedBackgroundView = UIView()
self.selectedBackgroundView?.backgroundColor = UIColor.sldsFill(.brandActive)
if let label = self.textLabel {
label.text = "Library"
label.textAlignment = .center
label.textColor = UIColor.sldsTextColor(.colorTextInverse)
label.font = UIFont.sldsFont(.regular, with: .large)
}
let image = UIImageView(image: UIImage(named: "tokens"))
self.addSubview(image)
self.constrainChild(image, xAlignment: .center, yAlignment: .center, width: 222, height: 175, yOffset: 10)
}
}
| bsd-3-clause | 6f840fc1dbc6ca3a8c013ec91a7194e1 | 33.807692 | 114 | 0.501657 | 5.603715 | false | false | false | false |
thanhtanh/OwlCollectionView | OwlCollectionView/OwlCVDelegate.swift | 1 | 22793 | //
// OwlCVDelegate.swift
// OwlCollectionView
//
// Created by t4nhpt on 9/20/16.
// Copyright ยฉ 2016 T4nhpt. All rights reserved.
//
import UIKit
import MagicalRecord
import CoreData
class OwlCVDelegate: NSObject {
var dataSource: OwlCVDataSource!
var collectionView: UICollectionView!
var numSections = 0
fileprivate var objectChanges:[NSFetchedResultsChangeType: Any] = [:]
fileprivate var sectionChanges:[NSFetchedResultsChangeType: Any] = [:]
private var _fetchedResultsController: NSFetchedResultsController<NSManagedObject>?
var fetchedResultsController: NSFetchedResultsController<NSManagedObject> {
get {
if let controller = self._fetchedResultsController {
return controller
} else {
let fetchRequest = self.dataSource.dataModelClass.mr_requestAllSorted(by: self.dataSource.sortBy, ascending: self.dataSource.sortAscending, with: self.dataSource.predicate)
if let groupBy = self.dataSource.groupBy, groupBy.characters.count > 0 {
let groupByDescriptor = NSSortDescriptor(key: groupBy, ascending: self.dataSource.groupBySortAscending)
fetchRequest.sortDescriptors?.insert(groupByDescriptor, at: 0)
}
if self.dataSource.fetchLimit > 0 {
fetchRequest.fetchLimit = self.dataSource.fetchLimit
fetchRequest.fetchBatchSize = self.dataSource.fetchBatch
}
let xx = fetchRequest as! NSFetchRequest<NSManagedObject>
let theFetchedResultsController:NSFetchedResultsController<NSManagedObject> = NSFetchedResultsController.init(fetchRequest: xx, managedObjectContext: NSManagedObjectContext.mr_default(), sectionNameKeyPath: self.dataSource.groupBy, cacheName: nil)
self._fetchedResultsController = theFetchedResultsController
self._fetchedResultsController!.delegate = self
try? self._fetchedResultsController!.performFetch()
return self.fetchedResultsController
}
}
}
func numberOfItemsInFetchedResultsSection(section: Int) -> Int {
if let sections = self.fetchedResultsController.sections {
if sections.count <= section {
return 0
}
let sectionInfo = sections[section]
let num = sectionInfo.numberOfObjects
return num
}
return 0
}
func dataObjectFor(item:Any?, at indexPath:IndexPath) -> Any? {
var dataObject: Any? = nil
//Retrieve Data Object For Item
switch self.dataSource.dataInputType {
case .coreData:
dataObject = self.dataObjectForFetchedResults(at: indexPath)
case .arrayOfData:
if (item as? UICollectionReusableView) != nil {
dataObject = self.headerDataFromDataArray(section: indexPath.section)
} else {
let rowData = self.rowDataFromDataArray(section: indexPath.section) as! NSArray //Find Row Data
dataObject = self.dataObjectFor(rowData: rowData, row:indexPath.item)
}
case .dataArrayAndCoreData:
let section = indexPath.section
let dataArraySection = self.dataArraySectionForIndexPathSection(section: section)
let rowData = self.rowDataFromDataArray(section: dataArraySection)
if let rowData = rowData as? String, rowData == kCoreData {
let coreDataIP = self.coreDataIndexPath(indexPath: indexPath)
dataObject = self.dataObjectForFetchedResults(at: coreDataIP)
} else if (rowData as? NSArray) != nil {
if (item as? UICollectionReusableView) != nil {
dataObject = self.headerDataFromDataArray(section: indexPath.section)
} else {
let rowData = self.rowDataFromDataArray(section: indexPath.section) as! NSArray //Find Row Data
dataObject = self.dataObjectFor(rowData: rowData, row:indexPath.item)
}
}
}
return dataObject
}
func dataObjectForFetchedResults(at indexPath:IndexPath) -> Any {
var dataObject:Any
dataObject = self.fetchedResultsController.object(at: indexPath)
return dataObject
}
func headerDataFromDataArray(section:Int) -> Any? {
if section < self.dataSource.data.count { //ERROR PROTECTION
let sectionInfo = self.dataSource.data[section]
let headerData: Any? //Find Header Data
//If section info is a dictionary it may contain header data, if not no header exits
if let sectionInfo = sectionInfo as? NSDictionary {
headerData = sectionInfo[kHeaderData]
return headerData
}
}
return nil
}
func dataObjectFor(rowData:NSArray, row:Int) -> Any? {
var dataObject:Any? = nil
if row < rowData.count {
dataObject = rowData[row]
}
return dataObject
}
func coreDataIndexPath(indexPath:IndexPath) -> IndexPath {
var coreDataSection = indexPath.section - self.numDataArraySectionsBeforeCoreData()
coreDataSection = (coreDataSection >= 0 ? coreDataSection : 0) //ERROR PROTECTION
let coreDataIP = IndexPath(item: indexPath.item, section: coreDataSection)
return coreDataIP
}
}
extension OwlCVDelegate: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
@available(iOS 6.0, *)
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return self.dequeueCell(withIdentifier: "", cellClass: "", collectionView: collectionView, indexPath: indexPath)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.numberOfItems(inSection: section)
}
// func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// return self.dequeueCell(withIdentifier: "", cellClass: "", collectionView: collectionView, indexPath: indexPath)
// }
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 1, height: 1)
}
func dequeueCell(withIdentifier cellIdentifier:String,
cellClass cellClassName:String,
collectionView:UICollectionView,
indexPath:IndexPath) -> UICollectionViewCell {
var cellId = cellIdentifier
if cellId == "" {
cellId = "cellIdentifier"
}
if (cellClassName == "") {//IF not in storyboard
collectionView.register(UICollectionView.self, forCellWithReuseIdentifier: cellId)
}
let item = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier,
for:indexPath)
return item
}
private func numberOfItems(inSection section:Int) -> Int {
switch self.dataSource.dataInputType {
case .coreData:
let numRows = self.numberOfItemsInFetchedResultsSection(section: section)
NSLog("%d Items in Section: %d found for Core Data Grid", numRows, section)
return numRows
case .arrayOfData:
var numRows = 0
let rowData = self.rowDataFromDataArray(section: section)
if let rowData = rowData as? NSArray {
numRows = rowData.count
}
return numRows
case .dataArrayAndCoreData:
//Determine if Section datasource is CoreData or DataArray
let dataArraySection = self.dataArraySectionForIndexPathSection(section: section)
let rowData = self.rowDataFromDataArray(section: dataArraySection)
var numRows = 0
if rowData is String &&
(rowData as! String) == kCoreData {
//CoreData
var coreDataSection = section - self.numDataArraySectionsBeforeCoreData()
coreDataSection = (coreDataSection >= 0 ? coreDataSection : 0) //ERROR PROTECTION
numRows = self.numberOfItemsInFetchedResultsSection(section: coreDataSection)
NSLog("%d Items in Core Data Section: %d Actual Section %d", numRows, coreDataSection, section)
} else if let rowData = rowData as? NSArray {
//Data Array
numRows = rowData.count
}
return numRows
}
}
func rowDataFromDataArray(section: Int) -> Any? {
if section < self.dataSource.data.count { //ERROR PROTECTION
let sectionInfo = self.dataSource.data[section]
var rowData:Any? //Find Row Data
if let sectionInfo = sectionInfo as? NSDictionary {
rowData = sectionInfo.object(forKey: kRowData)
//If section info is an array, it is effectively a sectioninfo dictionary with only the rowData key
} else if sectionInfo is NSArray {
rowData = sectionInfo
}
if !(rowData is NSArray) {
return kCoreData
}
return rowData
} else {
return nil
}
}
func dataArraySectionForIndexPathSection(section:Int) -> Int {
let numSectionsBeforeCoreData = self.numDataArraySectionsBeforeCoreData()
let numSectionsUpToAndIncludingCoreData = numSectionsBeforeCoreData + self.numberOfCoreDataSections()
//Determine section in Data Array (all core data sections should be the same data array section)
var dataArraySection = 0
if section < numSectionsBeforeCoreData {
dataArraySection = section
} else if section >= numSectionsBeforeCoreData &&
section < numSectionsUpToAndIncludingCoreData {
dataArraySection = numSectionsBeforeCoreData //Core Data Section
} else if (section >= numSectionsUpToAndIncludingCoreData) {
//Handle case when data array specifies rows of data after core data sections
dataArraySection = section - self.numberOfCoreDataSections() + 1 //Count all core data sections as 1
}
dataArraySection = (dataArraySection >= 0 ? dataArraySection : 0) //ERROR PROTECTION
return dataArraySection
}
func numberOfCoreDataSections() -> Int {
if let sections = self.fetchedResultsController.sections {
let numSections = sections.count
return numSections
}
return 0
}
func numDataArraySectionsBeforeCoreData() -> Int {
var numSectionsBefore = 0
let numSectionsTotal = self.numSections > 0 ? self.numSections : self.numberOfSections()
for s in 0..<numSectionsTotal {
let rowData = self.rowDataFromDataArray(section: s)
if rowData is String &&
(rowData as! String) == kCoreData {
return numSectionsBefore
}
if rowData != nil {
numSectionsBefore += 1
}
}
return numSectionsBefore
}
func numberOfSections() -> Int {
switch (self.dataSource.dataInputType) {
case .coreData:
self.numSections = self.numberOfCoreDataSections()
NSLog("%d Sections found for Core Data Grid", self.numSections)
return numSections
case .arrayOfData:
self.numSections = self.dataSource.data.count
return self.numSections
case .dataArrayAndCoreData:
//eDataArrayPlusCoreData currently assumes only one core data predicate per table
let numDataArraySections = self.dataSource.data.count - 1 //-1 for core data ('data' array must include a section labeled core data)
let numCoreDataSections = self.numberOfCoreDataSections()
let numSections = numDataArraySections + numCoreDataSections
NSLog("%d Sections found for Data Array Plus Core Data Grid", numSections)
self.numSections = numSections
return numSections
}
}
}
extension OwlCVDelegate : NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.objectChanges = [:]
self.sectionChanges = [:]
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
//Reset sectionIndex to account for possible offset in Core Data (occurs when grid is DataArrayPlusCoreData type)
NSLog("Section Index In Core Data: %d", sectionIndex)
let indexPath = self.indexPathForCoreDataPath(coreDataIP: IndexPath(item: 0, section: sectionIndex))
if let indexPath = indexPath {
let newSectionIndex = indexPath.section
NSLog("Section Index In Actual Table: %d", sectionIndex)
if type == .insert || type == .delete {
if let changeSet = self.sectionChanges[type] as? NSMutableIndexSet {
changeSet.add(newSectionIndex)
// [changeSet addIndex:newSectionIndex]
} else {
self.sectionChanges[type] = NSMutableIndexSet(index: newSectionIndex)
}
}
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
//Reset Index Paths to account for possible offset in Core Data IP (occurs when grid is DataArrayPlusCoreData type)
NSLog("Section Index In Core Data: %d", indexPath?.section ?? -1)
NSLog("New Section Index In Core Data: %d", newIndexPath?.section ?? -1)
let oldIP = self.indexPathForCoreDataPath(coreDataIP: indexPath)
let newIP = self.indexPathForCoreDataPath(coreDataIP: newIndexPath)
NSLog("Section Index In Actual Table: %d", indexPath?.section ?? -1)
NSLog("New Section Index In Actual Table: %d", newIndexPath?.section ?? -1)
var changeSet = self.objectChanges[type] as? [Any]
if changeSet == nil {
changeSet = []
self.objectChanges[type] = changeSet
}
if var changeSet = self.objectChanges[type] as? [Any] {
switch(type) {
case .insert:
changeSet.append(newIP)
break
case .delete:
changeSet.append(oldIP)
break
case .update:
changeSet.append(oldIP)
break
case .move:
changeSet.append((old:oldIP, new:newIP))
break
}
self.objectChanges[type] = changeSet
} else {
self.objectChanges[type] = [:]
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
var moves:NSMutableArray = []
if let temp = self.objectChanges[.move] as? NSMutableArray {
moves = temp
}
if (moves.count > 0) {
var updatedMoves:[AnyObject] = []
let insertSections = self.sectionChanges[.insert] as? NSMutableIndexSet ?? NSMutableIndexSet()
let deleteSections = self.sectionChanges[.delete] as? NSMutableIndexSet ?? NSMutableIndexSet()
for move in moves {
let fromIP = (move as! NSArray)[0] as! IndexPath
let toIP = (move as! NSArray)[1] as! IndexPath
if deleteSections.contains(fromIP.section) {
if !insertSections.contains(toIP.section) {
if var changeSet = self.objectChanges[.insert] as? [AnyObject] {
changeSet.append(toIP as AnyObject)
} else {
let changeSet = [toIP]
self.objectChanges[.insert] = changeSet
}
}
} else if insertSections.contains(toIP.section) {
if var changeSet = self.objectChanges[.delete] as? [AnyObject] {
changeSet.append(fromIP as AnyObject)
} else {
let changeSet = [fromIP]
self.objectChanges[.delete] = changeSet
}
} else {
updatedMoves.append(move as AnyObject)
}
}
if (updatedMoves.count > 0) {
self.objectChanges[.move] = updatedMoves
} else {
self.objectChanges.removeValue(forKey: .move)
}
}
if let deletes = self.objectChanges[.delete] as? NSArray, deletes.count > 0 {
let deletedSections = self.sectionChanges[.delete] as? NSMutableIndexSet
deletes.filtered(using: NSPredicate.init(block: { (evaluatedObject, bindings) -> Bool in
if let deletedSections = deletedSections {
let ip = evaluatedObject as! IndexPath
return !deletedSections.contains(ip.section)
} else {
return false
}
}))
}
if let inserts = self.objectChanges[.insert] as? NSArray, inserts.count > 0 {
let insertedSections = self.sectionChanges[.insert] as? NSMutableIndexSet
inserts.filtered(using: NSPredicate.init(block: { (evaluatedObject, bindings) -> Bool in
let ip = evaluatedObject as! IndexPath
if let insertedSections = insertedSections {
return !insertedSections.contains(ip.section)
} else {
return false
}
}))
}
var movedItems = self.objectChanges[.move] as? [(old:IndexPath, new:IndexPath)]
let collectionView = self.collectionView!
collectionView.performBatchUpdates({ [unowned self] in
if let deletedSections = self.sectionChanges[.delete] as? IndexSet, deletedSections.count > 0 {
collectionView.deleteSections(deletedSections)
}
if let insertedSections = self.sectionChanges[.insert] as? IndexSet, insertedSections.count > 0 {
collectionView.insertSections(insertedSections)
}
if let deletedItems = self.objectChanges[.delete] as? [IndexPath], deletedItems.count > 0 {
for path in deletedItems {
NSLog("Deleting Item at Index Path: S:%d R:%d",
path.section,
path.item)
var row = path.row
row = row + 1 //Remove Unused Var Warning
}
collectionView.deleteItems(at: deletedItems)
}
if let insertedItems = self.objectChanges[.insert] as? [IndexPath], insertedItems.count > 0 {
for path in insertedItems {
NSLog("Inserting Item at Index Path: S:%d R:%d", path.section, path.item)
var row = path.row
row = row + 1 //Remove Unused Var Warning
}
collectionView.insertItems(at: insertedItems)
}
if let reloadItems = self.objectChanges[.update] as? [IndexPath], reloadItems.count > 0 {
for path in reloadItems {
NSLog("Reloading Item at Index Path: S:%d R:%d", path.section, path.item)
var row = path.row
row = row + 1 //Remove Unused Var Warning
}
collectionView.reloadItems(at: reloadItems)
}
if let moveItems = self.objectChanges[.move] as? [(old:IndexPath, new:IndexPath)] {
for paths in moveItems {
NSLog("Moving Item at Index Path: S:%d R:%d to Index Path: S:%d R:%d",
paths.old.section,
paths.old.item,
paths.new.section,
paths.new.item)
collectionView.moveItem(at: paths.old, to:paths.new)
}
}
}) { finished in
if (finished) {
if let movedItems = movedItems, movedItems.count > 0 {
var reloadPaths:[IndexPath] = []
for paths in movedItems {
let path = paths.new
NSLog("Reloading Moved Item at Index Path: S:%d R:%d", path.section, path.item)
reloadPaths.append(path)
}
collectionView.reloadItems(at: reloadPaths)
}
movedItems = []
}
}
self.objectChanges = [:]
self.sectionChanges = [:]
}
func indexPathForCoreDataPath(coreDataIP: IndexPath?) -> IndexPath? {
if let coreDataIP = coreDataIP {
let actualSection = coreDataIP.section + self.numDataArraySectionsBeforeCoreData()
let actualIP = IndexPath(item:coreDataIP.item, section:actualSection)
return actualIP
}
return nil
}
}
| mit | f6cde86a9e2745e94312d2b1fcdec3a7 | 40.140794 | 263 | 0.574237 | 5.743952 | false | false | false | false |
auth0/Lock.swift | Lock/HeaderView.swift | 1 | 9786 | // Header.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public class HeaderView: UIView {
weak var logoView: UIImageView?
weak var titleView: UILabel?
weak var closeButton: UIButton?
weak var backButton: UIButton?
weak var maskImageView: UIImageView?
weak var blurView: UIVisualEffectView?
public var onClosePressed: () -> Void = {}
public var showClose: Bool {
get {
return !(self.closeButton?.isHidden ?? true)
}
set {
self.closeButton?.isHidden = !newValue
}
}
public var onBackPressed: () -> Void = {}
public var showBack: Bool {
get {
return !(self.backButton?.isHidden ?? true)
}
set {
self.backButton?.isHidden = !newValue
}
}
public var title: String? {
get {
return self.titleView?.text
}
set {
self.titleView?.text = newValue
}
}
public var titleColor: UIColor = Style.Auth0.titleColor {
didSet {
self.titleView?.textColor = titleColor
self.setNeedsUpdateConstraints()
}
}
public var logo: UIImage? {
get {
return self.logoView?.image
}
set {
self.logoView?.image = newValue
self.setNeedsUpdateConstraints()
}
}
public var maskImage: UIImage? {
get {
return self.maskImageView?.image
}
set {
self.maskImageView?.image = newValue
self.setNeedsUpdateConstraints()
}
}
public var blurred: Bool = Style.Auth0.headerColor == nil {
didSet {
self.applyBackground()
self.setNeedsDisplay()
}
}
public var blurStyle: A0BlurEffectStyle = .light {
didSet {
self.applyBackground()
self.setNeedsDisplay()
}
}
public var maskColor: UIColor = UIColor(red: 0.8745, green: 0.8745, blue: 0.8745, alpha: 1.0) {
didSet {
self.mask?.tintColor = self.maskColor
}
}
public convenience init() {
self.init(frame: CGRect.zero)
}
required override public init(frame: CGRect) {
super.init(frame: frame)
self.layoutHeader()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layoutHeader()
}
private func layoutHeader() {
let titleView = UILabel()
let logoView = UIImageView()
let closeButton = CloseButton(type: .system)
let backButton = CloseButton(type: .system)
let centerGuide = UILayoutGuide()
self.addLayoutGuide(centerGuide)
self.addSubview(titleView)
self.addSubview(logoView)
self.addSubview(closeButton)
self.addSubview(backButton)
constraintEqual(anchor: centerGuide.centerYAnchor, toAnchor: self.centerYAnchor, constant: 10)
constraintEqual(anchor: centerGuide.centerXAnchor, toAnchor: self.centerXAnchor)
constraintEqual(anchor: titleView.bottomAnchor, toAnchor: centerGuide.bottomAnchor)
constraintEqual(anchor: titleView.centerXAnchor, toAnchor: centerGuide.centerXAnchor)
titleView.setContentCompressionResistancePriority(UILayoutPriority.priorityRequired, for: .horizontal)
titleView.setContentHuggingPriority(UILayoutPriority.priorityRequired, for: .horizontal)
titleView.translatesAutoresizingMaskIntoConstraints = false
constraintEqual(anchor: logoView.centerXAnchor, toAnchor: self.centerXAnchor)
constraintEqual(anchor: logoView.bottomAnchor, toAnchor: titleView.topAnchor, constant: -15)
constraintEqual(anchor: logoView.topAnchor, toAnchor: centerGuide.topAnchor)
logoView.translatesAutoresizingMaskIntoConstraints = false
constraintEqual(anchor: closeButton.centerYAnchor, toAnchor: self.topAnchor, constant: 45)
constraintEqual(anchor: closeButton.rightAnchor, toAnchor: self.rightAnchor, constant: -10)
closeButton.widthAnchor.constraint(equalToConstant: 25).isActive = true
closeButton.heightAnchor.constraint(equalToConstant: 25).isActive = true
closeButton.translatesAutoresizingMaskIntoConstraints = false
constraintEqual(anchor: backButton.centerYAnchor, toAnchor: self.topAnchor, constant: 45)
constraintEqual(anchor: backButton.leftAnchor, toAnchor: self.leftAnchor, constant: 10)
backButton.widthAnchor.constraint(equalToConstant: 25).isActive = true
backButton.heightAnchor.constraint(equalToConstant: 25).isActive = true
backButton.translatesAutoresizingMaskIntoConstraints = false
self.applyBackground()
self.apply(style: Style.Auth0)
titleView.font = regularSystemFont(size: 20)
logoView.image = UIImage(named: "ic_auth0", in: bundleForLock(), compatibleWith: self.traitCollection)
closeButton.setBackgroundImage(UIImage(named: "ic_close", in: bundleForLock(), compatibleWith: self.traitCollection)?.withRenderingMode(.alwaysOriginal), for: .normal)
closeButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
backButton.setBackgroundImage(UIImage(named: "ic_back", in: bundleForLock(), compatibleWith: self.traitCollection)?.withRenderingMode(.alwaysOriginal), for: .normal)
backButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
self.titleView = titleView
self.logoView = logoView
self.closeButton = closeButton
self.backButton = backButton
self.showBack = false
self.clipsToBounds = true
}
public override var intrinsicContentSize: CGSize {
return CGSize(width: 200, height: 154)
}
@objc func buttonPressed(_ sender: UIButton) {
if sender == self.backButton {
self.onBackPressed()
}
if sender == self.closeButton {
self.onClosePressed()
}
}
// MARK: - Blur
private var canBlur: Bool {
return self.blurred && !accessibilityIsReduceTransparencyEnabled
}
private func applyBackground() {
self.maskImageView?.removeFromSuperview()
self.blurView?.removeFromSuperview()
self.backgroundColor = self.canBlur ? .white : UIColor(red: 0.9451, green: 0.9451, blue: 0.9451, alpha: 1.0)
guard self.canBlur else { return }
let maskView = UIImageView()
let blur = UIBlurEffect(style: self.blurStyle)
let blurView = UIVisualEffectView(effect: blur)
self.insertSubview(maskView, at: 0)
self.insertSubview(blurView, at: 1)
constraintEqual(anchor: blurView.leftAnchor, toAnchor: self.leftAnchor)
constraintEqual(anchor: blurView.topAnchor, toAnchor: self.topAnchor)
constraintEqual(anchor: blurView.rightAnchor, toAnchor: self.rightAnchor)
constraintEqual(anchor: blurView.bottomAnchor, toAnchor: self.bottomAnchor)
blurView.translatesAutoresizingMaskIntoConstraints = false
maskView.translatesAutoresizingMaskIntoConstraints = false
dimension(dimension: maskView.widthAnchor, withValue: 400)
dimension(dimension: maskView.heightAnchor, withValue: 400)
constraintEqual(anchor: maskView.centerYAnchor, toAnchor: self.centerYAnchor)
constraintEqual(anchor: maskView.centerXAnchor, toAnchor: self.centerXAnchor)
maskView.contentMode = .scaleToFill
maskView.image = UIImage(named: "ic_auth0", in: bundleForLock(), compatibleWith: self.traitCollection)?.withRenderingMode(.alwaysTemplate)
maskView.tintColor = self.maskColor
self.maskImageView = maskView
self.blurView = blurView
}
}
extension HeaderView: Stylable {
func apply(style: Style) {
if let color = style.headerColor {
self.blurred = false
self.backgroundColor = color
} else {
self.blurred = true
self.blurStyle = style.headerBlur
}
self.title = style.hideTitle ? nil : style.title
self.titleColor = style.titleColor
self.logo = style.logo
self.maskImage = style.headerMask
self.backButton?.setBackgroundImage(style.headerBackIcon?.withRenderingMode(.alwaysOriginal), for: .normal)
self.closeButton?.setBackgroundImage(style.headerCloseIcon?.withRenderingMode(.alwaysOriginal), for: .normal)
}
}
private class CloseButton: UIButton {
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return bounds.insetBy(dx: -10, dy: -10).contains(point)
}
}
| mit | 8a1a014b1d2c11f81ffd62bb65095e0c | 36.209125 | 175 | 0.674944 | 5.008188 | false | false | false | false |