repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
abury/FontAwesome.swift | refs/heads/master | FontAwesome/FontAwesome.swift | mit | 2 | // FontAwesome.swift
//
// Copyright (c) 2014-2015 Thi Doan
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreText
private class FontLoader {
class func loadFont(name: String) {
let bundle = NSBundle(forClass: FontLoader.self)
var fontURL = NSURL()
let identifier = bundle.bundleIdentifier
if identifier?.hasPrefix("org.cocoapods") == true {
// If this framework is added using CocoaPods, resources is placed under a subdirectory
fontURL = bundle.URLForResource(name, withExtension: "otf", subdirectory: "FontAwesome.swift.bundle")!
} else {
fontURL = bundle.URLForResource(name, withExtension: "otf")!
}
let data = NSData(contentsOfURL: fontURL)!
let provider = CGDataProviderCreateWithCFData(data)
let font = CGFontCreateWithDataProvider(provider)!
var error: Unmanaged<CFError>?
if !CTFontManagerRegisterGraphicsFont(font, &error) {
let errorDescription: CFStringRef = CFErrorCopyDescription(error!.takeUnretainedValue())
let nsError = error!.takeUnretainedValue() as AnyObject as! NSError
NSException(name: NSInternalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise()
}
}
}
public extension UIFont {
public class func fontAwesomeOfSize(fontSize: CGFloat) -> UIFont {
struct Static {
static var onceToken : dispatch_once_t = 0
}
let name = "FontAwesome"
if (UIFont.fontNamesForFamilyName(name).count == 0) {
dispatch_once(&Static.onceToken) {
FontLoader.loadFont(name)
}
}
return UIFont(name: name, size: fontSize)!
}
}
public extension String {
public static func fontAwesomeIconWithName(name: FontAwesome) -> String {
return name.rawValue.substringToIndex(advance(name.rawValue.startIndex, 1))
}
}
public extension UIImage {
public static func fontAwesomeIconWithName(name: FontAwesome, textColor: UIColor, size: CGSize) -> UIImage {
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = NSLineBreakMode.ByWordWrapping
paragraph.alignment = .Center
let attributedString = NSAttributedString(string: String.fontAwesomeIconWithName(name) as String, attributes: [NSFontAttributeName: UIFont.fontAwesomeOfSize(max(size.width, size.height)), NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName:paragraph])
let size = attributedString.sizeWithMaxWidth(size.width)
UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
attributedString.drawInRect(CGRectMake(0, 0, size.width, size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
private extension NSAttributedString {
func sizeWithMaxWidth(maxWidth: CGFloat) -> CGSize {
return self.boundingRectWithSize(CGSizeMake(maxWidth, 1000), options:(NSStringDrawingOptions.UsesLineFragmentOrigin), context: nil).size
}
}
public extension String {
public static func fontAwesomeIconWithCode(code: String) -> String? {
if let raw = FontAwesomeIcons[code], icon = FontAwesome(rawValue: raw) {
return self.fontAwesomeIconWithName(icon)
}
return nil
}
}
| 7d5f39b218c345df69902a2162f0b8de | 40.481481 | 280 | 0.707366 | false | false | false | false |
creatubbles/ctb-api-swift | refs/heads/develop | CreatubblesAPIClient/Sources/Utils/Logger.swift | mit | 1 | //
// Logger.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import XCGLogger
public enum LogLevel {
case verbose
case debug
case info
case warning
case error
case severe
case none
}
public protocol LogListener: class {
func log(logLevel: LogLevel, message: String?, fileName: String, lineNumber: Int, date: Date)
}
class Logger {
private static var loggerIdentifier = "com.creatubbles.CreatubblesAPIClient.logger"
private static var logger = XCGLogger(identifier: loggerIdentifier, includeDefaultDestinations: true)
private static var listeners: Array<LogListener> = Array<LogListener>()
class func log(_ level: LogLevel, _ message: String?, fileName: StaticString = #file, lineNumber: Int = #line) {
listeners.forEach({ $0.log(logLevel: level, message: message, fileName: String(describing: fileName).lastPathComponent, lineNumber: lineNumber, date: Date()) })
switch level {
case .verbose: logger.verbose(message, fileName: fileName, lineNumber: lineNumber)
case .debug: logger.debug(message, fileName: fileName, lineNumber: lineNumber)
case .info: logger.info(message, fileName: fileName, lineNumber: lineNumber)
case .warning: logger.warning(message, fileName: fileName, lineNumber: lineNumber)
case .error: logger.error(message, fileName: fileName, lineNumber: lineNumber)
case .severe: logger.severe(message, fileName: fileName, lineNumber: lineNumber)
case .none: return
}
}
class func setup(logLevel: LogLevel = .info) {
logger.setup(level: Logger.logLevelToXCGLevel(level: logLevel), showLogIdentifier: true, showFunctionName: false, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, showDate: true, writeToFile: nil, fileLevel: nil)
}
private class func logLevelToXCGLevel(level: LogLevel) -> XCGLogger.Level {
switch level {
case .verbose: return .verbose
case .debug: return .debug
case .info: return .info
case .warning: return .warning
case .error: return .error
case .severe: return .severe
case .none: return .none
}
}
class func addListener(listener: LogListener) {
if !listeners.contains(where: { $0 === listener }) {
listeners.append(listener)
}
}
}
| 0b93a176e847b598c9430cd266f96599 | 42.421687 | 254 | 0.690067 | false | false | false | false |
fgengine/quickly | refs/heads/master | Quickly/Views/Switch/QSwitch.swift | mit | 1 | //
// Quickly
//
open class QSwitchStyleSheet : IQStyleSheet {
public var tintColor: UIColor?
public var onTintColor: UIColor?
public var thumbTintColor: UIColor?
public var onImage: UIImage?
public var offImage: UIImage?
public init(
tintColor: UIColor? = nil,
onTintColor: UIColor? = nil,
thumbTintColor: UIColor? = nil,
onImage: UIImage? = nil,
offImage: UIImage? = nil
) {
self.tintColor = tintColor
self.onTintColor = onTintColor
self.thumbTintColor = thumbTintColor
self.onImage = onImage
self.offImage = offImage
}
public init(_ styleSheet: QSwitchStyleSheet) {
self.tintColor = styleSheet.tintColor
self.onTintColor = styleSheet.onTintColor
self.thumbTintColor = styleSheet.thumbTintColor
self.onImage = styleSheet.onImage
self.offImage = styleSheet.offImage
}
}
open class QSwitch : UISwitch, IQView {
public typealias ChangedClosure = (_ `switch`: QSwitch, _ isOn: Bool) -> Void
public var onChanged: ChangedClosure? = nil
public required init() {
super.init(frame: CGRect.zero)
self.setup()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.setup()
}
open func setup() {
self.addTarget(self, action: #selector(self._handleChanged(_:)), for: .valueChanged)
}
deinit {
self.removeTarget(self, action: #selector(self._handleChanged(_:)), for: .valueChanged)
}
public func apply(_ styleSheet: QSwitchStyleSheet) {
self.tintColor = styleSheet.tintColor
self.onTintColor = styleSheet.onTintColor
self.thumbTintColor = styleSheet.thumbTintColor
self.onImage = styleSheet.onImage
self.offImage = styleSheet.offImage
}
@objc
private func _handleChanged(_ sender: Any) {
guard let onChanged = self.onChanged else { return }
onChanged(self, self.isOn)
}
}
| 54c0bb1a7cde051c6c1092aee7d11ac1 | 26.2125 | 95 | 0.618741 | false | false | false | false |
149393437/Templates | refs/heads/master | Templates/Project Templates/Mac/Application/Game.xctemplate/SpriteKit_AppDelegate.swift | mit | 1 | //
// ___FILENAME___
// ___PACKAGENAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import Cocoa
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
@NSApplicationMain
class ___FILEBASENAME___: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var skView: SKView!
func applicationDidFinishLaunching(aNotification: NSNotification) {
/* Pick a size for the scene */
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
self.skView!.presentScene(scene)
/* Sprite Kit applies additional optimizations to improve rendering performance */
self.skView!.ignoresSiblingOrder = true
self.skView!.showsFPS = true
self.skView!.showsNodeCount = true
}
}
func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
return true
}
}
| e3645c58b908ccebc2c7ca8ad9b802e0 | 32.203704 | 104 | 0.624094 | false | false | false | false |
EdgarM-/MobileComputing | refs/heads/AppStore_Version | ChatIOS/ChatIOS[ea-cj]/Examples/TaskM/Pods/SQLite.swift/SQLite/Core/Blob.swift | apache-2.0 | 28 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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.
//
public struct Blob {
public let bytes: [UInt8]
public init(bytes: [UInt8]) {
self.bytes = bytes
}
public init(bytes: UnsafePointer<Void>, length: Int) {
self.init(bytes: [UInt8](UnsafeBufferPointer(
start: UnsafePointer(bytes), count: length
)))
}
public func toHex() -> String {
return bytes.map {
($0 < 16 ? "0" : "") + String($0, radix: 16, uppercase: false)
}.joinWithSeparator("")
}
}
extension Blob : CustomStringConvertible {
public var description: String {
return "x'\(toHex())'"
}
}
extension Blob : Equatable {
}
public func ==(lhs: Blob, rhs: Blob) -> Bool {
return lhs.bytes == rhs.bytes
}
| 5b6061d8dd74eeb273fc7633340ac70f | 30.344262 | 80 | 0.687238 | false | false | false | false |
toggl/superday | refs/heads/develop | teferi/UI/Common/Views/CategoryButton.swift | bsd-3-clause | 1 | import UIKit
protocol CategoryButtonDelegate:class
{
func categorySelected(category:Category)
}
class CategoryButton : UIView
{
private let animationDuration = TimeInterval(0.225)
var category : Category?
{
didSet
{
guard let category = category else { return }
label.text = category.description
label.sizeToFit()
label.center = CGPoint.zero
label.textColor = category.color
button.backgroundColor = category.color
button.setImage(category.icon.image, for: .normal)
}
}
var angle : CGFloat = -CGFloat.pi / 2 //The default value is so the label appears at the bottom in EditView
{
didSet
{
positionLabel()
}
}
weak var delegate:CategoryButtonDelegate?
private let button : UIButton
private let labelHolder : UIView
private let label : UILabel
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
required override init(frame: CGRect)
{
button = UIButton(frame: frame)
labelHolder = UIView()
label = UILabel()
super.init(frame: frame)
backgroundColor = UIColor.clear
clipsToBounds = false
button.layer.cornerRadius = min(frame.width, frame.height) / 2
button.adjustsImageWhenHighlighted = false
addSubview(button)
label.font = UIFont.boldSystemFont(ofSize: 9)
label.textAlignment = .center
labelHolder.center = button.center
addSubview(labelHolder)
labelHolder.addSubview(label)
positionLabel()
button.addTarget(self, action: #selector(CategoryButton.buttonTap), for: .touchUpInside)
}
func show()
{
let scaleTransform = CGAffineTransform(scaleX: 0.01, y: 0.01)
self.transform = scaleTransform
self.isHidden = false
let changesToAnimate = {
self.layer.removeAllAnimations()
self.transform = .identity
}
self.label.alpha = 0
self.label.transform = CGAffineTransform(scaleX: 0, y: 0)
let showLabelAnimation = {
self.label.alpha = 1
self.label.transform = CGAffineTransform.identity
}
UIView.animate(changesToAnimate, duration: animationDuration, withControlPoints: 0.23, 1, 0.32, 1)
{
UIView.animate(
withDuration: 0.3,
delay: 0.08,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 0.2,
options: UIViewAnimationOptions.curveEaseOut,
animations: showLabelAnimation)
}
}
func hide()
{
let scaleTransform = CGAffineTransform(scaleX: 0.01, y: 0.01)
self.transform = .identity
self.isHidden = false
let changesToAnimate = {
self.layer.removeAllAnimations()
self.transform = scaleTransform
}
UIView.animate(changesToAnimate, duration: animationDuration, withControlPoints: 0.175, 0.885, 0.32, 1)
}
private func positionLabel()
{
let radius = frame.width / 2 + 12
let x = button.center.x + radius * cos(angle - CGFloat.pi)
let y = button.center.y + radius * sin(angle - CGFloat.pi)
labelHolder.center = CGPoint(x: x, y: y)
let labelOffset = -cos(angle)
label.center = CGPoint(x: labelOffset * (label.frame.width / 2 - label.frame.height / 2), y: 0)
}
@objc private func buttonTap()
{
guard let category = category, let delegate = delegate else { return }
delegate.categorySelected(category: category)
}
}
| 08bf4935be4fc6e6908fc8f7a452519a | 27.12766 | 111 | 0.572113 | false | false | false | false |
kNeerajPro/CGFLoatingUIKit | refs/heads/master | CGFloatLabelUITextKit/CGFloatLabelUITextKit/ViewController.swift | mit | 1 | //
// ViewController.swift
// CGFloatLabelUITextKit
//
// Created by Neeraj Kumar on 07/12/14.
// Copyright (c) 2014 Neeraj Kumar. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var firstNameTextField: CGFloatTextField!
@IBOutlet weak var middleNameTextField: CGFloatTextField!
@IBOutlet weak var lastNameTextField: CGFloatTextField!
@IBOutlet weak var floatTextView: CGFloatTextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.firstNameTextField.floatingLabelText = "First Name"
self.firstNameTextField.floatingLabelFontColor = UIColor.blue
self.firstNameTextField.floatingLabelFont = UIFont.systemFont(ofSize: 15)
self.middleNameTextField.floatingLabelText = "Middle Name"
self.middleNameTextField.floatingLabelFontColor = UIColor.green
self.middleNameTextField.animationTime = 1.0
self.middleNameTextField.floatingLabelOffset = 20.0
self.lastNameTextField.floatingLabelText = "Last Name"
self.lastNameTextField.animationTime = 0.5
self.floatTextView.placeholderText = "Enter text here"
self.floatTextView.floatingLabelText = "Enter text here"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 110af8dd5bbfb51ffd23a696fb124c36 | 28.584906 | 81 | 0.684311 | false | false | false | false |
hilen/TSWeChat | refs/heads/master | Pods/TimedSilver/Sources/UIKit/UIImage+TSExtension.swift | mit | 2 | //
// UIImage+TSExtension.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 11/24/15.
// Copyright © 2015 Hilen. All rights reserved.
//
//https://github.com/melvitax/AFImageHelper/blob/master/AFImageHelper/AFImageExtension.swift
import Foundation
import UIKit
import Photos
import QuartzCore
import CoreGraphics
import Accelerate
public extension UIImage {
/**
Applies gradient color overlay to an image.
- parameter gradientColors: An array of colors to use for the gradient
- parameter blendMode: The blending type to use
- returns: new image
*/
func ts_gradientImageWithColors(_ gradientColors: [UIColor], blendMode: CGBlendMode = CGBlendMode.normal) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(blendMode)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
context?.draw(self.cgImage!, in: rect)
// Create gradient
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colors = gradientColors.map {(color: UIColor) -> AnyObject? in return color.cgColor as AnyObject? } as NSArray
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: nil)
// Apply gradient
context?.clip(to: rect, mask: self.cgImage!)
context?.drawLinearGradient(gradient!, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: size.height), options: CGGradientDrawingOptions(rawValue: 0))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image!;
}
/**
Capture screen
- parameter view: view
- parameter rect: rect
- returns: UIImage
*/
@discardableResult
class func ts_screenCaptureWithView(_ view: UIView, rect: CGRect) -> UIImage {
let capture: UIImage
UIGraphicsBeginImageContextWithOptions(rect.size, false, 1.0)
let context: CGContext = UIGraphicsGetCurrentContext()!
context.translateBy(x: -rect.origin.x, y: -rect.origin.y)
// let layer: CALayer = view.layer
let selector = NSSelectorFromString("drawViewHierarchyInRect:afterScreenUpdates:")
if view.responds(to: selector) {
//if view.responds(to, selector(UIView.drawViewHierarchyInRect(_:afterScreenUpdates:))) {
view.drawHierarchy(in: view.frame, afterScreenUpdates: true)
} else {
view.layer.render(in: UIGraphicsGetCurrentContext()!)
}
capture = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return capture
}
/**
Create UIImage with the color
- parameter color: color
- returns: UIImage
*/
class func ts_imageWithColor(_ color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
/**
The Round corner radius
- parameter cornerRadius: value
- returns: UIImage
*/
func ts_roundWithCornerRadius(_ cornerRadius: CGFloat) -> UIImage {
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: self.size)
UIGraphicsBeginImageContextWithOptions(self.size, false, 1)
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
draw(in: rect)
return UIGraphicsGetImageFromCurrentImageContext()!
}
/**
Check the image has alpha or not
- returns: Bool
*/
func ts_hasAlpha() -> Bool {
let alpha: CGImageAlphaInfo = self.cgImage!.alphaInfo
return (alpha == .first || alpha == .last || alpha == .premultipliedFirst || alpha == .premultipliedLast)
}
/**
Returns a copy of the given image, adding an alpha channel if it doesn't already have one.
- returns: a new image
*/
func ts_applyAlpha() -> UIImage? {
if ts_hasAlpha() {
return self
}
let imageRef = self.cgImage;
let width = imageRef?.width;
let height = imageRef?.height;
let colorSpace = imageRef?.colorSpace
// The bitsPerComponent and bitmapInfo values are hard-coded to prevent an "unsupported parameter combination" error
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo().rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)
let offscreenContext = CGContext(data: nil, width: width!, height: height!, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace!, bitmapInfo: bitmapInfo.rawValue)
// Draw the image into the context and retrieve the new image, which will now have an alpha layer
offscreenContext?.draw(imageRef!, in: CGRect(x: 0, y: 0, width: CGFloat(width!), height: CGFloat(height!)))
let imageWithAlpha = UIImage(cgImage: (offscreenContext?.makeImage()!)!)
return imageWithAlpha
}
/**
Creates a new image with a border.
- parameter border: The size of the border.
- parameter color: The color of the border.
- returns: a new image
*/
func ts_applyBorder(_ border:CGFloat, color:UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let width = self.cgImage?.width
let height = self.cgImage?.height
let bits = self.cgImage?.bitsPerComponent
let colorSpace = self.cgImage?.colorSpace
let bitmapInfo = self.cgImage?.bitmapInfo
let context = CGContext(data: nil, width: width!, height: height!, bitsPerComponent: bits!, bytesPerRow: 0, space: colorSpace!, bitmapInfo: (bitmapInfo?.rawValue)!)
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
context?.setStrokeColor(red: red, green: green, blue: blue, alpha: alpha)
context?.setLineWidth(border)
let rect = CGRect(x: 0, y: 0, width: size.width*scale, height: size.height*scale)
let inset = rect.insetBy(dx: border*scale, dy: border*scale)
context?.strokeEllipse(in: inset)
context?.draw(self.cgImage!, in: inset)
let image = UIImage(cgImage: (context?.makeImage()!)!)
UIGraphicsEndImageContext()
return image
}
/**
Applies a blur to an image based on the specified radius, tint color saturation and mask image
- parameter blurRadius: The radius of the blur.
- parameter tintColor: The optional tint color.
- parameter saturationDeltaFactor: The detla for saturation.
- parameter maskImage: The optional image for masking.
- returns: New image or nil
*/
func ts_applyBlur(_ blurRadius:CGFloat, tintColor:UIColor?, saturationDeltaFactor:CGFloat, maskImage:UIImage? = nil) -> UIImage? {
guard size.width > 0 && size.height > 0 && cgImage != nil else {
return nil
}
if maskImage != nil {
guard maskImage?.cgImage != nil else {
return nil
}
}
let imageRect = CGRect(origin: CGPoint.zero, size: size)
var effectImage = self
let hasBlur = blurRadius > CGFloat(Float.ulpOfOne)
let hasSaturationChange = abs(saturationDeltaFactor - 1.0) > CGFloat(Float.ulpOfOne)
if (hasBlur || hasSaturationChange) {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let effectInContext = UIGraphicsGetCurrentContext()
effectInContext?.scaleBy(x: 1.0, y: -1.0)
effectInContext?.translateBy(x: 0, y: -size.height)
effectInContext?.draw(cgImage!, in: imageRect)
var effectInBuffer = vImage_Buffer(
data: effectInContext?.data,
height: UInt((effectInContext?.height)!),
width: UInt((effectInContext?.width)!),
rowBytes: (effectInContext?.bytesPerRow)!)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
let effectOutContext = UIGraphicsGetCurrentContext()
var effectOutBuffer = vImage_Buffer(
data: effectOutContext?.data,
height: UInt((effectOutContext?.height)!),
width: UInt((effectOutContext?.width)!),
rowBytes: (effectOutContext?.bytesPerRow)!)
if hasBlur {
let inputRadius = blurRadius * UIScreen.main.scale
let sqrtValue = CGFloat(sqrt(2.0 * Double.pi))
var radius = UInt32(floor(inputRadius * 3.0 * sqrtValue / 4.0 + 0.5))
if radius % 2 != 1 {
radius += 1 // force radius to be odd so that the three box-blur methodology works.
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s: CGFloat = saturationDeltaFactor
let floatingPointSaturationMatrix: [CGFloat] = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
]
let divisor: CGFloat = 256
let matrixSize = floatingPointSaturationMatrix.count
var saturationMatrix = [Int16](repeating: 0, count: matrixSize)
for i: Int in 0 ..< matrixSize {
saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor))
}
if hasBlur {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
effectImageBuffersAreSwapped = true
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
}
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
if effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
}
// Set up output context.
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let outputContext = UIGraphicsGetCurrentContext()
outputContext?.scaleBy(x: 1.0, y: -1.0)
outputContext?.translateBy(x: 0, y: -size.height)
// Draw base image.
outputContext?.draw(self.cgImage!, in: imageRect)
// Draw effect image.
if hasBlur {
outputContext?.saveGState()
if let image = maskImage {
outputContext?.clip(to: imageRect, mask: image.cgImage!);
}
outputContext?.draw(effectImage.cgImage!, in: imageRect)
outputContext?.restoreGState()
}
// Add in color tint.
if let color = tintColor {
outputContext?.saveGState()
outputContext?.setFillColor(color.cgColor)
outputContext?.fill(imageRect)
outputContext?.restoreGState()
}
// Output image is ready.
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
}
| 1374fda50eb372c3ca6531c5ae852201 | 40.676375 | 173 | 0.606383 | false | false | false | false |
BananosTeam/CreativeLab | refs/heads/develop | Example/Pods/OAuthSwift/OAuthSwift/OAuthSwiftMultipartData.swift | mit | 7 | //
// OAuthSwiftMultipartData.swift
// OAuthSwift
//
// Created by Tomohiro Kawaji on 12/18/15.
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
public struct OAuthSwiftMultipartData {
public var name: String
public var data: NSData
public var fileName: String?
public var mimeType: String?
public init(name: String, data: NSData, fileName: String?, mimeType: String?) {
self.name = name
self.data = data
self.fileName = fileName
self.mimeType = mimeType
}
}
extension NSMutableData {
public func appendMultipartData(multipartData: OAuthSwiftMultipartData, encoding: NSStringEncoding, separatorData: NSData) {
var filenameClause = ""
if let filename = multipartData.fileName {
filenameClause = " filename=\"\(filename)\""
}
let contentDispositionString = "Content-Disposition: form-data; name=\"\(multipartData.name)\";\(filenameClause)r\n"
let contentDispositionData = contentDispositionString.dataUsingEncoding(encoding)!
self.appendData(contentDispositionData)
if let mimeType = multipartData.mimeType {
let contentTypeString = "Content-Type: \(mimeType)\r\n"
let contentTypeData = contentTypeString.dataUsingEncoding(encoding)!
self.appendData(contentTypeData)
}
self.appendData(separatorData)
self.appendData(multipartData.data)
self.appendData(separatorData)
}
} | 01277b02461b6446f91ff55e6e25dfdf | 30.4375 | 128 | 0.680371 | false | false | false | false |
eliasbloemendaal/KITEGURU | refs/heads/master | KITEGURU/MailViewController.swift | mit | 1 | //
// MailViewController.swift
// KITEGURU
//
// Created by Elias Houttuijn Bloemendaal on 26-01-16.
// Copyright © 2016 Elias Houttuijn Bloemendaal. All rights reserved.
//
import UIKit
import MessageUI
class MailViewController: UIViewController, MFMailComposeViewControllerDelegate {
@IBOutlet weak var subjectTextfield: UITextField!
@IBOutlet weak var bodyTextview: UITextView!
// Segue for the mail from personalRatingViewController
var city: String?
var temp: Double?
var desc: String?
var icon: String?
var speed: Double?
var deg: Double?
var kiteguruFinalAdvise: Int?
var firstName: String?
// Variable for the mail
var tempString: String?
var speedString: String?
var degString: String?
var functions = Functions()
override func viewDidLoad() {
super.viewDidLoad()
// Als er geen plaats is opgezocht geef dan een waarden in plaat van nil en voorkom een error
if temp == nil || speed == nil || deg == nil || icon == nil || city == nil || kiteguruFinalAdvise == nil || desc == nil{
temp = 0
speed = 0
deg = 0
icon = "02n"
city = " city "
kiteguruFinalAdvise = 0
desc = "weather mood"
}
// Rounding the numbers for in the mail
tempString = String(format: "%.2f", temp!) + " Celsius"
speedString = String(format: "%.2f", speed!) + " Knots"
degString = String(format: "%.2f", deg!) + " Direction"
// http://stackoverflow.com/questions/26614395/swift-background-image-does-not-fit-showing-small-part-of-the-all-image
let backgroundImage = UIImageView(frame: UIScreen.mainScreen().bounds)
backgroundImage.image = UIImage(named: "kiteBackFour")
backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill
self.view.insertSubview(backgroundImage, atIndex: 0)
// Het opgestelde mailtje met the weather predictions, het kiteguru advies plus cijfer.
let messageBody = bodyTextview
messageBody.text = "YO Dude, KITEGURU gave me an advise! \nThese are the weather conditions in \(city!), Temperature: \(tempString!), Weather mood: \(desc!), Windspeed: \(speedString!), Wind direction \(degString!) \nThis is the grade I got: \(kiteguruFinalAdvise!). This is my personal KITEGURU advice: \(functions.advise(kiteguruFinalAdvise!)). \nlet me know if you want to go! \nHANGLOOSEEE BROTHA!"
// http://stackoverflow.com/questions/17403483/set-title-of-back-bar-button-item-in-ios
// NavigationBar titles
self.navigationItem.title = firstName!
let btn = UIBarButtonItem(title: "Advice", style: .Plain, target: self, action: "backBtnClicked")
self.navigationController?.navigationBar.topItem?.backBarButtonItem = btn
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// De mail button zal een mailtje opstellen plus onderwerp plus een toegevoegde foto van KITEGURU
@IBAction func sendMailButton(sender: AnyObject) {
let messageBody = bodyTextview
var SubjectText = "KITGURU - "
let Recipients = ["[email protected]"]
let mc: MFMailComposeViewController = MFMailComposeViewController()
SubjectText += subjectTextfield.text!
mc.mailComposeDelegate = self
mc.setSubject(SubjectText)
mc.setMessageBody(messageBody.text, isHTML: false)
mc.setToRecipients(Recipients)
mc.addAttachmentData(UIImageJPEGRepresentation(UIImage(named: "kiteGuru.png")!, CGFloat(1.0))!, mimeType: "image/jpeg", fileName: "test.jpeg")
self.presentViewController(mc, animated: true, completion: nil)
}
// Geef een alert als de mail niet verzonden kan worden
func showSendMailErrorAlert(){
let alertview = UIAlertController(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: .Alert)
alertview.addAction(UIAlertAction(title: "OK", style: .Default, handler:
{ (alertAction) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}))
alertview.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
self.presentViewController(alertview, animated: true, completion: nil)
}
// De mail zal verdwijnen nadat de mail is verstuurd of gecanceled
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
// De on screen keyboard zal verdwijnen wanner je buiten het keyboard klikt
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
}
| 9b1e34e2f2afddc91173a2cd9d5bc431 | 44.272727 | 410 | 0.675904 | false | false | false | false |
DTVD/APIKitExt | refs/heads/master | Demo/Pods/ModelMapper/Sources/Mapper.swift | apache-2.0 | 5 | import Foundation
/// Mapper creates strongly typed objects from a given NSDictionary based on the mapping provided by
/// implementing the Mappable protocol (see `Mappable` for an example).
public struct Mapper {
private let JSON: NSDictionary
/// Create a Mapper with a NSDictionary to use as source data
///
/// - parameter JSON: The dictionary to use for the data
public init(JSON: NSDictionary) {
self.JSON = JSON
}
// MARK: - T: RawRepresentable
/// Get a RawRepresentable value from the given field in the source data
///
/// Transparently create instances of enums and other RawRepresentables from the source data
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - throws: MapperError.missingFieldError the field doesn't exist
/// - throws: MapperError.typeMismatchError the value exists but doesn't match the type of the RawValue
/// - throws: MapperError.invalidRawValueError the value exists with the correct type, but the type's
/// initializer fails with the passed rawValue
///
/// - returns: The value for the given field, if it can be converted to the expected type T
public func from<T: RawRepresentable>(_ field: String) throws -> T {
let object = try self.JSONFromField(field)
guard let rawValue = object as? T.RawValue else {
throw MapperError.typeMismatchError(field: field, value: object, type: T.RawValue.self)
}
guard let value = T(rawValue: rawValue) else {
throw MapperError.invalidRawValueError(field: field, value: rawValue, type: T.self)
}
return value
}
/// Get an optional RawRepresentable value from the given field in the source data
///
/// Transparently create instances of enums and other RawRepresentables from source data
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - returns: The value for the given field, if it can be converted to the expected type T otherwise nil
public func optionalFrom<T: RawRepresentable>(_ field: String) -> T? {
return try? self.from(field)
}
/// Get an optional value from the given fields and source data. This returns the first non-nil value
/// produced in order based on the array of fields
///
/// - parameter fields: The array of fields to check from the source data.
///
/// - returns: The first non-nil value to be produced from the array of fields, or nil if none exist
public func optionalFrom<T: RawRepresentable>(_ fields: [String]) -> T? {
for field in fields {
if let value: T = try? self.from(field) {
return value
}
}
return nil
}
/// Get an array of RawRepresentable values from a field in the the source data.
///
/// - note: If T.init(rawValue:) fails given the T.RawValue from the array of source data, that value will
/// be replaced by the passed defaultValue, which defaults to nil. The resulting array is
/// flatMapped and all nils are removed. This means that any unrecognized values will be removed
/// or replaced with the default. This ensures backwards compatibility if your source data has
/// keys that your mapping layer doesn't know about yet.
///
/// - parameter field: The field to use from the source data
/// - parameter defaultValue: The value to use if the rawValue initializer fails
///
/// - throws: MapperError.typeMismatchError when the value for the key is not an array of Any
/// - throws: Any other error produced by a Convertible implementation
///
/// - returns: An array of the RawRepresentable value, with all nils removed
public func from<T: RawRepresentable>(_ field: String, defaultValue: T? = nil) throws ->
[T] where T.RawValue: Convertible, T.RawValue == T.RawValue.ConvertedType
{
let value = try self.JSONFromField(field)
guard let array = value as? [Any] else {
throw MapperError.typeMismatchError(field: field, value: value, type: [Any].self)
}
let rawValues = try array.map { try T.RawValue.fromMap($0) }
return rawValues.flatMap { T(rawValue: $0) ?? defaultValue }
}
// MARK: - T: Mappable
/// Get a Mappable value from the given field in the source data
///
/// This allows you to transparently have nested Mappable values
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - throws: MapperError.missingFieldError if the field doesn't exist
/// - throws: MapperError.typeMismatchError if the field exists but isn't an NSDictionary
///
/// - returns: The value for the given field, if it can be converted to the expected type T
public func from<T: Mappable>(_ field: String) throws -> T {
let value = try self.JSONFromField(field)
if let JSON = value as? NSDictionary {
return try T(map: Mapper(JSON: JSON))
}
throw MapperError.typeMismatchError(field: field, value: value, type: NSDictionary.self)
}
/// Get an array of Mappable values from the given field in the source data
///
/// This allows you to transparently have nested arrays of Mappable values
///
/// - note: If any value in the array of NSDictionaries is invalid, this method throws
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - throws: MapperError.missingFieldError if the field doesn't exist
/// - throws: MapperError.typeMismatchError if the field exists but isn't an array of NSDictionarys
/// - throws: Any errors produced by the subsequent Mappable initializers
///
/// - returns: The value for the given field, if it can be converted to the expected type [T]
public func from<T: Mappable>(_ field: String) throws -> [T] {
let value = try self.JSONFromField(field)
if let JSON = value as? [NSDictionary] {
return try JSON.map { try T(map: Mapper(JSON: $0)) }
}
throw MapperError.typeMismatchError(field: field, value: value, type: [NSDictionary].self)
}
/// Get an optional Mappable value from the given field in the source data
///
/// This allows you to transparently have nested Mappable values
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - returns: The value for the given field, if it can be converted to the expected type T otherwise nil
public func optionalFrom<T: Mappable>(_ field: String) -> T? {
return try? self.from(field)
}
/// Get an optional array of Mappable values from the given field in the source data
///
/// This allows you to transparently have nested arrays of Mappable values
///
/// - note: If any value in the provided array of NSDictionaries is invalid, this method returns nil
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - returns: The value for the given field, if it can be converted to the expected type [T]
public func optionalFrom<T: Mappable>(_ field: String) -> [T]? {
return try? self.from(field)
}
/// Get an optional value from the given fields and source data. This returns the first non-nil value
/// produced in order based on the array of fields
///
/// - parameter fields: The array of fields to check from the source data.
///
/// - returns: The first non-nil value to be produced from the array of fields, or nil if none exist
public func optionalFrom<T: Mappable>(_ fields: [String]) -> T? {
for field in fields {
if let value: T = try? self.from(field) {
return value
}
}
return nil
}
// MARK: - T: Convertible
/// Get a Convertible value from a field in the source data
///
/// This transparently converts your types that conform to Convertible to properties on the Mappable type
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - throws: Any error produced by the custom Convertible implementation
///
/// - returns: The value for the given field, if it can be converted to the expected type T
public func from<T: Convertible>(_ field: String) throws -> T where T == T.ConvertedType {
return try self.from(field, transformation: T.fromMap)
}
/// Get a Convertible value from a field in the source data
///
/// This transparently converts your types that conform to Convertible to properties on the Mappable type
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - throws: Any error produced by the custom Convertible implementation
///
/// - note: This function is necessary because Swift does't coerce the from that returns T to an optional
///
/// - returns: The value for the given field, if it can be converted to the expected type Optional<T>
public func from<T: Convertible>(_ field: String) throws -> T? where T == T.ConvertedType {
return try self.from(field, transformation: T.fromMap)
}
/// Get an array of Convertible values from a field in the source data
///
/// This transparently converts your types that conform to Convertible to an array on the Mappable type
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - throws: MapperError.missingFieldError if the field doesn't exist
/// - throws: MapperError.typeMismatchError if the field exists but isn't an array of Any
/// - throws: Any error produced by the subsequent Convertible implementations
///
/// - returns: The value for the given field, if it can be converted to the expected type [T]
public func from<T: Convertible>(_ field: String) throws -> [T] where T == T.ConvertedType {
let value = try self.JSONFromField(field)
if let JSON = value as? [Any] {
return try JSON.map(T.fromMap)
}
throw MapperError.typeMismatchError(field: field, value: value, type: [Any].self)
}
/// Get a Convertible value from a field in the source data
///
/// This transparently converts your types that conform to Convertible to properties on the Mappable type
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - returns: The value for the given field, if it can be converted to the expected type T otherwise nil
public func optionalFrom<T: Convertible>(_ field: String) -> T? where T == T.ConvertedType {
return try? self.from(field, transformation: T.fromMap)
}
/// Get an optional array of Convertible values from a field in the source data
///
/// This transparently converts your types that conform to Convertible to an array on the Mappable type
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - returns: The value for the given field, if it can be converted to the expected type [T]
public func optionalFrom<T: Convertible>(_ field: String) -> [T]? where T == T.ConvertedType {
return try? self.from(field)
}
/// Get a dictionary of Convertible values from a field in the source data
///
/// This transparently converts a source dictionary to a dictionary of 2 Convertible types
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - throws: MapperError.typeMismatchError if the value for the given field isn't a [AnyHashable: Any]
/// - throws: Any error produced by the Convertible implementation of either expected type
///
/// - returns: A dictionary where the keys and values are created using their convertible implementations
public func from<U: Convertible, T: Convertible>(_ field: String) throws -> [U: T]
where U == U.ConvertedType, T == T.ConvertedType
{
let object = try self.JSONFromField(field)
guard let data = object as? [AnyHashable: Any] else {
throw MapperError.typeMismatchError(field: field, value: object, type: [AnyHashable: Any].self)
}
var result = [U: T]()
for (key, value) in data {
result[try U.fromMap(key)] = try T.fromMap(value)
}
return result
}
/// Get an optional dictionary of Convertible values from a field in the source data
///
/// This transparently converts a source dictionary to a dictionary of 2 Convertible types
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to return the
/// entire data set
///
/// - returns: A dictionary where the keys and values are created using their convertible implementations
/// or nil if anything throws
public func optionalFrom<U: Convertible, T: Convertible>(_ field: String) -> [U: T]?
where U == U.ConvertedType, T == T.ConvertedType
{
return try? self.from(field)
}
/// Get an optional value from the given fields and source data. This returns the first non-nil value
/// produced in order based on the array of fields
///
/// - parameter fields: The array of fields to check from the source data.
///
/// - returns: The first non-nil value to be produced from the array of fields, or nil if none exist
public func optionalFrom<T: Convertible>(_ fields: [String]) -> T? where T == T.ConvertedType {
for field in fields {
if let value: T = try? self.from(field) {
return value
}
}
return nil
}
// MARK: - Custom Transformation
/// Get a typed value from the given field by using the given transformation
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to
/// return the entire data set
/// - parameter transformation: The transformation function used to create the expected value
///
/// - throws: MapperError.missingFieldError if the field doesn't exist
/// - throws: Any exception thrown by the transformation function, if you're implementing the
/// transformation function you should use `MapperError`, see the documentation there for info
///
/// - returns: The value of type T for the given field
public func from<T>(_ field: String, transformation: (Any) throws -> T) throws -> T {
return try transformation(try self.JSONFromField(field))
}
/// Get an optional typed value from the given field by using the given transformation
///
/// - parameter field: The field to retrieve from the source data, can be an empty string to
/// return the entire data set
/// - parameter transformation: The transformation function used to create the expected value
///
/// - returns: The value of type T for the given field, if the transformation function doesn't throw
/// otherwise nil
public func optionalFrom<T>(_ field: String, transformation: (Any) throws -> T?) -> T? {
return (try? transformation(try self.JSONFromField(field))).flatMap { $0 }
}
// MARK: - Private
/// Get the object for a given field. If an empty string is passed, return the entire data source. This
/// allows users to create objects from multiple fields in the top level of the data source
///
/// - parameter field: The field to extract from the data source, can be an empty string to return the
/// entire data set
///
/// - throws: MapperError.missingFieldError if the field doesn't exist
///
/// - returns: The object for the given field
private func JSONFromField(_ field: String) throws -> Any {
if let value = field.isEmpty ? self.JSON : self.JSON.safeValue(forKeyPath: field) {
return value
}
throw MapperError.missingFieldError(field: field)
}
}
| 5a7d94b020fdf3129a86b952bd12586e | 45.964578 | 110 | 0.642725 | false | false | false | false |
enabledhq/Selfie-Bot | refs/heads/master | Selfie-Bot/SelfieBotAnalysisViewController.swift | mit | 1 | //
// SelfieBotCardViewController.swift
// Selfie-Bot
//
// Created by John Smith on 24/2/17.
// Copyright © 2017 Enabled. All rights reserved.
//
import Foundation
import UIKit
class SelfieBotAnalysisViewController: ViewController {
private let viewModel: SelfieBotAnalysisViewModel
private let analysisView: AnalysisView
init(viewModel: SelfieBotAnalysisViewModel) {
self.viewModel = viewModel
analysisView = AnalysisView(options: viewModel.options)
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
let imageView = UIImageView(image: viewModel.image)
let selfieBotSaysLabel = UILabel()
let qouteLabel = UILabel()
let textColor = UIColor(colorLiteralRed: 140 / 255, green: 140 / 255, blue: 140 / 255, alpha: 1)
//Drop Shadow
imageView.layer.shadowOffset = CGSize(width: -1.0, height: -1.0)
imageView.layer.shadowOpacity = 0.5
imageView.contentMode = .scaleAspectFit
selfieBotSaysLabel.textAlignment = .center
selfieBotSaysLabel.text = "Selfie bot says"
selfieBotSaysLabel.textColor = textColor
qouteLabel.textAlignment = .center
qouteLabel.text = viewModel.qoute
qouteLabel.numberOfLines = 0
qouteLabel.font = UIFont.init(name: "ChalkboardSE-Light", size: 17)
qouteLabel.textColor = textColor
view.backgroundColor = UIColor.white
view.addSubview(imageView)
view.addSubview(selfieBotSaysLabel)
view.addSubview(qouteLabel)
view.addSubview(analysisView)
imageView.snp.makeConstraints {
make in
make.height.equalTo(200)
make.top.equalTo(view).inset(50)
make.centerX.equalTo(view)
}
selfieBotSaysLabel.snp.makeConstraints {
make in
make.left.right.equalTo(view).inset(50)
make.top.equalTo(imageView.snp.bottom).offset(20)
}
qouteLabel.snp.makeConstraints {
make in
make.left.right.equalTo(view).inset(70)
make.top.equalTo(selfieBotSaysLabel.snp.bottom).offset(10)
}
analysisView.snp.makeConstraints {
make in
make.top.equalTo(qouteLabel.snp.bottom).offset(20)
make.left.right.equalTo(view).inset(50)
}
}
override func viewDidAppear(_ animated: Bool) {
analysisView.animateConfidenceBars()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| ef7b21b02607ed7313ebfd7405753013 | 29.340659 | 104 | 0.607026 | false | false | false | false |
airspeedswift/swift | refs/heads/master | test/IDE/complete_call_arg.swift | apache-2.0 | 2 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG1 | %FileCheck %s -check-prefix=EXPECT_OINT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG2 | %FileCheck %s -check-prefix=ARG-NAME1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG3 | %FileCheck %s -check-prefix=ARG-NAME2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG4 | %FileCheck %s -check-prefix=EXPECT_INT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG5 | %FileCheck %s -check-prefix=EXPECT_OSTRING
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG6 | %FileCheck %s -check-prefix=ARG-NAME3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG7 | %FileCheck %s -check-prefix=ARG-NAME4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG8 | %FileCheck %s -check-prefix=EXPECT_STRING
// RUN-FIXME: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVERLOAD1 | %FileCheck %s -check-prefix=OVERLOAD1
// RUN-FIXME: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVERLOAD2 | %FileCheck %s -check-prefix=OVERLOAD2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVERLOAD3 | %FileCheck %s -check-prefix=OVERLOAD3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVERLOAD4 | %FileCheck %s -check-prefix=OVERLOAD4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVERLOAD5 | %FileCheck %s -check-prefix=OVERLOAD5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVERLOAD6 | %FileCheck %s -check-prefix=OVERLOAD6
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVERLOAD7 | %FileCheck %s -check-prefix=OVERLOAD6
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=HASERROR1 | %FileCheck %s -check-prefix=HASERROR1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=HASERROR2 | %FileCheck %s -check-prefix=HASERROR2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=HASERROR3 | %FileCheck %s -check-prefix=HASERROR3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=HASERROR4 | %FileCheck %s -check-prefix=HASERROR4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER1 | %FileCheck %s -check-prefix=MEMBER1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER2 | %FileCheck %s -check-prefix=MEMBER2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER3 | %FileCheck %s -check-prefix=MEMBER3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER4 | %FileCheck %s -check-prefix=MEMBER4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER5 | %FileCheck %s -check-prefix=MEMBER2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER6 | %FileCheck %s -check-prefix=MEMBER4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER7 | %FileCheck %s -check-prefix=MEMBER7
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER8 | %FileCheck %s -check-prefix=MEMBER8
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER9 | %FileCheck %s -check-prefix=MEMBER1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FARG1 | %FileCheck %s -check-prefix=EXPECT_INT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FARG2 | %FileCheck %s -check-prefix=EXPECT_STRING
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FARG3 | %FileCheck %s -check-prefix=MEMBER2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FARG4 | %FileCheck %s -check-prefix=MEMBER4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FARG5 | %FileCheck %s -check-prefix=MEMBER2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FARG6 | %FileCheck %s -check-prefix=FARG6
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FARG7 | %FileCheck %s -check-prefix=EXPECT_OINT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIRST_ARG_NAME_1 | %FileCheck %s -check-prefix=FIRST_ARG_NAME_PATTERN
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIRST_ARG_NAME_2 | %FileCheck %s -check-prefix=FIRST_ARG_NAME_PATTERN
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIRST_ARG_NAME_3 -code-complete-call-pattern-heuristics | %FileCheck %s -check-prefix=FIRST_ARG_NAME_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIRST_ARG_NAME_3 | %FileCheck %s -check-prefix=FIRST_ARG_NAME_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BOUND_GENERIC_1_1 | %FileCheck %s -check-prefix=BOUND_GENERIC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BOUND_GENERIC_1_2 | %FileCheck %s -check-prefix=BOUND_GENERIC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EMPTY_OVERLOAD_1 | %FileCheck %s -check-prefix=EMPTY_OVERLOAD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EMPTY_OVERLOAD_2 | %FileCheck %s -check-prefix=EMPTY_OVERLOAD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CALLARG_IUO | %FileCheck %s -check-prefix=CALLARG_IUO
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BOUND_IUO | %FileCheck %s -check-prefix=MEMBEROF_IUO
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FORCED_IUO | %FileCheck %s -check-prefix=MEMBEROF_IUO
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TO_GENERIC | %FileCheck %s -check-prefix=GENERIC_TO_GENERIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_CLOSURE | %FileCheck %s -check-prefix=NESTED_CLOSURE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SHUFFLE_1 | %FileCheck %s -check-prefix=SHUFFLE_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SHUFFLE_2 | %FileCheck %s -check-prefix=SHUFFLE_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SHUFFLE_3 | %FileCheck %s -check-prefix=SHUFFLE_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_1 | %FileCheck %s -check-prefix=SUBSCRIPT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_1_DOT | %FileCheck %s -check-prefix=SUBSCRIPT_1_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_2 | %FileCheck %s -check-prefix=SUBSCRIPT_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_2_DOT | %FileCheck %s -check-prefix=SUBSCRIPT_2_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_3 | %FileCheck %s -check-prefix=SUBSCRIPT_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_3_DOT | %FileCheck %s -check-prefix=SUBSCRIPT_3_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ERRORCONTEXT_NESTED_1 | %FileCheck %s -check-prefix=ERRORCONTEXT_NESTED_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ERRORCONTEXT_NESTED_2 | %FileCheck %s -check-prefix=ERRORCONTEXT_NESTED_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CURRIED_SELF_1 | %FileCheck %s -check-prefix=CURRIED_SELF_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CURRIED_SELF_2 | %FileCheck %s -check-prefix=CURRIED_SELF_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CURRIED_SELF_3 | %FileCheck %s -check-prefix=CURRIED_SELF_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STATIC_METHOD_AFTERPAREN_1 | %FileCheck %s -check-prefix=STATIC_METHOD_AFTERPAREN_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STATIC_METHOD_AFTERPAREN_2 | %FileCheck %s -check-prefix=STATIC_METHOD_AFTERPAREN_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STATIC_METHOD_SECOND | %FileCheck %s -check-prefix=STATIC_METHOD_SECOND
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STATIC_METHOD_SKIPPED | %FileCheck %s -check-prefix=STATIC_METHOD_SKIPPED
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_AFTERPAREN_1 | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_AFTERPAREN_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_AFTERPAREN_2 | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_AFTERPAREN_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_SECOND | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_SECOND
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_SKIPPED | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_SKIPPED
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_ARRAY_1_AFTERPAREN_1 | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_AFTERPAREN_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_ARRAY_1_AFTERPAREN_2 | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_AFTERPAREN_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_ARRAY_1_SECOND | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_SECOND
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_ARRAY_1_SKIPPED | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_SKIPPED
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_ARRAY_2_AFTERPAREN_1 | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_AFTERPAREN_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_ARRAY_2_AFTERPAREN_2 | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_AFTERPAREN_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_ARRAY_2_SECOND | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_SECOND
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_MEMBER_ARRAY_2_SKIPPED | %FileCheck %s -check-prefix=IMPLICIT_MEMBER_SKIPPED
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARCHETYPE_GENERIC_1 | %FileCheck %s -check-prefix=ARCHETYPE_GENERIC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PARAM_WITH_ERROR_AUTOCLOSURE| %FileCheck %s -check-prefix=PARAM_WITH_ERROR_AUTOCLOSURE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPECHECKED_OVERLOADED | %FileCheck %s -check-prefix=TYPECHECKED_OVERLOADED
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPECHECKED_TYPEEXPR | %FileCheck %s -check-prefix=TYPECHECKED_TYPEEXPR
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_PARAMFLAG_INOUT | %FileCheck %s -check-prefix=ARG_PARAMFLAG_INOUT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_PARAMFLAG_AUTOCLOSURE| %FileCheck %s -check-prefix=ARG_PARAMFLAG_AUTOCLOSURE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_PARAMFLAG_IUO | %FileCheck %s -check-prefix=ARG_PARAMFLAG_IUO
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_PARAMFLAG_VARIADIC | %FileCheck %s -check-prefix=ARG_PARAMFLAG_VARIADIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TUPLEELEM_1 | %FileCheck %s -check-prefix=TUPLEELEM_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TUPLEELEM_2 | %FileCheck %s -check-prefix=TUPLEELEM_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYPATH_THUNK_BASE | %FileCheck %s -check-prefix=KEYPATH_THUNK_BASE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VARIADIC_1 | %FileCheck %s -check-prefix=VARIADIC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VARIADIC_2 | %FileCheck %s -check-prefix=VARIADIC_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VARIADIC_3 | %FileCheck %s -check-prefix=VARIADIC_2
var i1 = 1
var i2 = 2
var oi1 : Int?
var oi2 : Int?
var s1 = ""
var s2 = ""
var os1 : String?
var os2 : String?
func voidGen() {}
func ointGen() -> Int? { return 1 }
func intGen() -> Int {return 1}
func ostringGen() -> String? {return ""}
func stringGen() -> String {return ""}
func foo(_ a : Int) {}
func foo(_ a : Int, b1 :Int?) {}
func foo(_ a : Int, b2 :Int?, b3: Int?) {}
func foo1(_ a : Int, b : Int) {}
func bar(_ a : String, b : String?) {}
func bar1(_ a : String, b1 : String) {}
func bar1(_ a : String, b2 : String) {}
func foo3(_ a: Int?) {}
class InternalGen {
func InternalIntGen() -> Int { return 0 }
func InternalIntOpGen() -> Int? {return 0 }
func InternalStringGen() -> String { return "" }
func InternalStringOpGen() -> String? {return ""}
func InternalIntTaker(_ i1 : Int, i2 : Int) {}
func InternalStringTaker(_ s1: String, s2 : String) {}
}
class Gen {
var IG = InternalGen()
func IntGen() -> Int { return 0 }
func IntOpGen() -> Int? {return 0 }
func StringGen() -> String { return "" }
func StringOpGen() -> String? {return ""}
func IntTaker(_ i1 : Int, i2 : Int) {}
func StringTaker(_ s1: String, s2 : String) {}
}
func GenGenerator(_ i : Int) -> Gen { return Gen() }
enum SimpleEnum {
case foo, bar, baz
}
class C1 {
func f1() {
foo(3, b: #^ARG1^#)
}
func f2() {
foo(3, #^ARG2^#)
}
func f3() {
foo1(2, #^ARG3^#
}
func f4() {
foo1(2, b : #^ARG4^#
}
func f5() {
foo(#^FARG1^#, b1 : 2)
}
func f6() {
bar(#^FARG2^#
}
func f7() {
foo3(#^FARG7^#)
}
}
// ARG-NAME1: Begin completions, 2 items
// ARG-NAME1-DAG: Pattern/ExprSpecific: {#b1: Int?#}[#Int?#];
// ARG-NAME1-DAG: Pattern/ExprSpecific: {#b2: Int?#}[#Int?#];
// ARG-NAME2: Begin completions, 1 items
// ARG-NAME2-DAG: Pattern/ExprSpecific: {#b: Int#}[#Int#];
// ARG-NAME3: Begin completions, 1 items
// ARG-NAME3-DAG: Pattern/ExprSpecific: {#b: String?#}[#String?#];
// ARG-NAME4: Begin completions, 2 items
// ARG-NAME4-DAG: Pattern/ExprSpecific: {#b1: String#}[#String#];
// ARG-NAME4-DAG: Pattern/ExprSpecific: {#b2: String#}[#String#];
// ARG-NAME4: End completions
// EXPECT_OINT: Begin completions
// EXPECT_OINT-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: f1()[#Void#]; name=f1()
// EXPECT_OINT-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: f2()[#Void#]; name=f2()
// EXPECT_OINT-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Convertible]: i2[#Int#]; name=i2
// EXPECT_OINT-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Convertible]: i1[#Int#]; name=i1
// EXPECT_OINT-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: oi2[#Int?#]; name=oi2
// EXPECT_OINT-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: oi1[#Int?#]; name=oi1
// EXPECT_OINT-DAG: Decl[GlobalVar]/CurrModule: os1[#String?#]; name=os1
// EXPECT_OINT: End completions
// EXPECT_INT: Begin completions
// EXPECT_INT-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: f1()[#Void#]; name=f1()
// EXPECT_INT-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: f2()[#Void#]; name=f2()
// EXPECT_INT-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: voidGen()[#Void#]; name=voidGen()
// EXPECT_INT-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Identical]: intGen()[#Int#]; name=intGen()
// EXPECT_INT-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: i1[#Int#]; name=i1
// EXPECT_INT-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: i2[#Int#]; name=i2
// EXPECT_INT-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem/TypeRelation[Identical]: Int[#Int#]
// EXPECT_INT-DAG: Decl[FreeFunction]/CurrModule: ointGen()[#Int?#]; name=ointGen()
// EXPECT_INT-DAG: Decl[GlobalVar]/CurrModule: oi1[#Int?#]; name=oi1
// EXPECT_INT-DAG: Decl[GlobalVar]/CurrModule: os2[#String?#]; name=os2
// EXPECT_INT-DAG: Decl[GlobalVar]/CurrModule: oi2[#Int?#]; name=oi2
// EXPECT_INT: End completions
class C2 {
func f1() {
bar("", b: #^ARG5^#)
}
func f2() {
bar("", #^ARG6^#)
}
func f3() {
bar1("", #^ARG7^#
}
func f4() {
bar1("", b : #^ARG8^#
}
}
// EXPECT_OSTRING: Begin completions
// EXPECT_OSTRING-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: f1()[#Void#]; name=f1()
// EXPECT_OSTRING-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: f2()[#Void#]; name=f2()
// EXPECT_OSTRING-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Convertible]: stringGen()[#String#]; name=stringGen()
// EXPECT_OSTRING-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Convertible]: s2[#String#]; name=s2
// EXPECT_OSTRING-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Convertible]: s1[#String#]; name=s1
// EXPECT_OSTRING-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: os1[#String?#]; name=os1
// EXPECT_OSTRING-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: os2[#String?#]; name=os2
// EXPECT_OSTRING-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Identical]: ostringGen()[#String?#]; name=ostringGen()
// EXPECT_OSTRING-DAG: Decl[GlobalVar]/CurrModule: i1[#Int#]; name=i1
// EXPECT_OSTRING-DAG: Decl[GlobalVar]/CurrModule: i2[#Int#]; name=i2
// EXPECT_OSTRING: End completions
// EXPECT_STRING: Begin completions
// EXPECT_STRING-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: f1()[#Void#]; name=f1()
// EXPECT_STRING-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: f2()[#Void#]; name=f2()
// EXPECT_STRING-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Identical]: stringGen()[#String#]; name=stringGen()
// EXPECT_STRING-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem/TypeRelation[Identical]: String[#String#]
// EXPECT_STRING-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: s1[#String#]; name=s1
// EXPECT_STRING-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: s2[#String#]; name=s2
// EXPECT_STRING-DAG: Decl[GlobalVar]/CurrModule: os1[#String?#]; name=os1
// EXPECT_STRING-DAG: Decl[GlobalVar]/CurrModule: os2[#String?#]; name=os2
// EXPECT_STRING: End completions
func foo2(_ a : C1, b1 : C2) {}
func foo2(_ a : C2, b2 : C1) {}
class C3 {
var C1I = C1()
var C2I = C2()
func f1() {
foo2(C1I, #^OVERLOAD1^#)
}
func f2() {
foo2(C2I, #^OVERLOAD2^#)
}
func f3() {
foo2(C1I, b1: #^OVERLOAD3^#)
}
func f4() {
foo2(C2I, b2: #^OVERLOAD4^#)
}
func f5() {
foo2(#^OVERLOAD5^#
}
func overloaded(_ a1: C1, b1: C2) {}
func overloaded(a2: C2, b2: C1) {}
func f6(obj: C3) {
overloaded(#^OVERLOAD6^#
func sync() {}
obj.overloaded(#^OVERLOAD7^#
}
}
// OVERLOAD1: Begin completions, 1 items
// OVERLOAD1-NEXT: Keyword/ExprSpecific: b1: [#Argument name#]; name=b1:
// OVERLOAD1-NEXT: End completions
// OVERLOAD2: Begin completions, 1 items
// OVERLOAD2-NEXT: Keyword/ExprSpecific: b2: [#Argument name#]; name=b2:
// OVERLOAD2-NEXT: End completions
// OVERLOAD3: Begin completions
// OVERLOAD3-DAG: Decl[InstanceVar]/CurrNominal: C1I[#C1#]; name=C1I
// OVERLOAD3-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: f1()[#Void#]; name=f1()
// OVERLOAD3-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: C2I[#C2#]; name=C2I
// OVERLOAD3-DAG: Decl[Class]/CurrModule/TypeRelation[Identical]: C2[#C2#]
// OVERLOAD3: End completions
// FIXME: This should be a negative test case
// NEGATIVE_OVERLOAD_3-NOT: Decl[Class]{{.*}} C1
// OVERLOAD4: Begin completions
// OVERLOAD4-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: C1I[#C1#]; name=C1I
// OVERLOAD4-DAG: Decl[InstanceVar]/CurrNominal: C2I[#C2#]; name=C2I
// OVERLOAD4-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: f1()[#Void#]; name=f1()
// OVERLOAD4-DAG: Decl[Class]/CurrModule/TypeRelation[Identical]: C1[#C1#]
// OVERLOAD4: End completions
// FIXME: This should be a negative test case
// NEGATIVE_OVERLOAD4-NOT: Decl[Class]{{.*}} C2
// OVERLOAD5: Begin completions
// OVERLOAD5-DAG: Decl[FreeFunction]/CurrModule: ['(']{#(a): C1#}, {#b1: C2#}[')'][#Void#]; name=a: C1, b1: C2
// OVERLOAD5-DAG: Decl[FreeFunction]/CurrModule: ['(']{#(a): C2#}, {#b2: C1#}[')'][#Void#]; name=a: C2, b2: C1
// OVERLOAD5-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: C1I[#C1#]; name=C1I
// OVERLOAD5-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: C2I[#C2#]; name=C2I
// OVERLOAD5: End completions
// OVERLOAD6: Begin completions
// OVERLOAD6-DAG: Decl[InstanceMethod]/CurrNominal: ['(']{#(a1): C1#}, {#b1: C2#}[')'][#Void#]; name=a1: C1, b1: C2
// OVERLOAD6-DAG: Decl[InstanceMethod]/CurrNominal: ['(']{#a2: C2#}, {#b2: C1#}[')'][#Void#]; name=a2: C2, b2: C1
// OVERLOAD6-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: C1I[#C1#]; name=C1I
// OVERLOAD6-DAG: Decl[InstanceVar]/CurrNominal: C2I[#C2#]; name=C2I
// OVERLOAD6: End completions
extension C3 {
func hasError(a1: C1, b1: TypeInvalid) -> Int {}
func f7(obj: C3) {
let _ = obj.hasError(#^HASERROR1^#
let _ = obj.hasError(a1: #^HASERROR2^#
let _ = obj.hasError(a1: IC1, #^HASERROR3^#
let _ = obj.hasError(a1: IC1, b1: #^HASERROR4^#
}
}
// HASERROR1: Begin completions
// HASERROR1-DAG: Decl[InstanceMethod]/CurrNominal: ['(']{#a1: C1#}, {#b1: <<error type>>#}[')'][#Int#];
// HASERROR1: End completions
// HASERROR2: Begin completions
// HASERROR2-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: C1I[#C1#];
// HASERROR2-DAG: Decl[InstanceVar]/CurrNominal: C2I[#C2#];
// HASERROR2: End completions
// HASERROR3: Begin completions
// HASERROR3-DAG: Pattern/ExprSpecific: {#b1: <<error type>>#}[#<<error type>>#];
// HASERROR3: End completions
// HASERROR4: Begin completions
// HASERROR4-DAG: Decl[InstanceVar]/CurrNominal: C1I[#C1#];
// HASERROR4-DAG: Decl[InstanceVar]/CurrNominal: C2I[#C2#];
// HASERROR4: End completions
class C4 {
func f1(_ G : Gen) {
foo(1, b1: G.#^MEMBER1^#
}
func f2(_ G : Gen) {
foo1(2, b : G.#^MEMBER2^#
}
func f3(_ G : Gen) {
bar("", b1 : G.#^MEMBER3^#
}
func f4(_ G : Gen) {
bar1("", b1 : G.#^MEMBER4^#
}
func f5(_ G1 : Gen, G2 : Gen) {
G1.IntTaker(1, i1 : G2.#^MEMBER5^#
}
func f6(_ G1 : Gen, G2 : Gen) {
G1.StringTaker("", s2: G2.#^MEMBER6^#
}
func f7(_ GA : [Gen]) {
foo(1, b1 : GA.#^MEMBER7^#
}
func f8(_ GA : Gen) {
foo(1, b1 : GA.IG.#^MEMBER8^#
}
func f9() {
foo(1, b1 : GenGenerator(1).#^MEMBER9^#
}
func f10(_ G: Gen) {
foo(G.#^FARG3^#
}
func f11(_ G: Gen) {
bar(G.#^FARG4^#
}
func f12(_ G1 : Gen, G2 : Gen) {
G1.IntTaker(G2.#^FARG5^#
}
func f13(_ G : Gen) {
G.IntTaker(G.IG.#^FARG6^#
}
}
// MEMBER1: Begin completions
// MEMBER1-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: IntGen()[#Int#]; name=IntGen()
// MEMBER1-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: IntOpGen()[#Int?#]; name=IntOpGen()
// MEMBER1-DAG: Decl[InstanceMethod]/CurrNominal: StringGen()[#String#]; name=StringGen()
// MEMBER1-DAG: Decl[InstanceMethod]/CurrNominal: StringOpGen()[#String?#]; name=StringOpGen()
// MEMBER1-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: IntTaker({#(i1): Int#}, {#i2: Int#})[#Void#]; name=IntTaker(i1: Int, i2: Int)
// MEMBER1-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: StringTaker({#(s1): String#}, {#s2: String#})[#Void#]; name=StringTaker(s1: String, s2: String)
// MEMBER2: Begin completions
// MEMBER2-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: IntGen()[#Int#]; name=IntGen()
// MEMBER2-DAG: Decl[InstanceMethod]/CurrNominal: IntOpGen()[#Int?#]; name=IntOpGen()
// MEMBER2-DAG: Decl[InstanceMethod]/CurrNominal: StringGen()[#String#]; name=StringGen()
// MEMBER2-DAG: Decl[InstanceMethod]/CurrNominal: StringOpGen()[#String?#]; name=StringOpGen()
// MEMBER2-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: IntTaker({#(i1): Int#}, {#i2: Int#})[#Void#]; name=IntTaker(i1: Int, i2: Int)
// MEMBER2-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: StringTaker({#(s1): String#}, {#s2: String#})[#Void#]; name=StringTaker(s1: String, s2: String)
// MEMBER3: Begin completions
// MEMBER3-DAG: Decl[InstanceMethod]/CurrNominal: IntGen()[#Int#]; name=IntGen()
// MEMBER3-DAG: Decl[InstanceMethod]/CurrNominal: IntOpGen()[#Int?#]; name=IntOpGen()
// MEMBER3-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: StringGen()[#String#]; name=StringGen()
// MEMBER3-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: StringOpGen()[#String?#]; name=StringOpGen()
// MEMBER3-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: IntTaker({#(i1): Int#}, {#i2: Int#})[#Void#]; name=IntTaker(i1: Int, i2: Int)
// MEMBER3-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: StringTaker({#(s1): String#}, {#s2: String#})[#Void#]; name=StringTaker(s1: String, s2: String)
// MEMBER4: Begin completions
// MEMBER4-DAG: Decl[InstanceMethod]/CurrNominal: IntGen()[#Int#]; name=IntGen()
// MEMBER4-DAG: Decl[InstanceMethod]/CurrNominal: IntOpGen()[#Int?#]; name=IntOpGen()
// MEMBER4-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: StringGen()[#String#]; name=StringGen()
// MEMBER4-DAG: Decl[InstanceMethod]/CurrNominal: StringOpGen()[#String?#]; name=StringOpGen()
// MEMBER4-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: IntTaker({#(i1): Int#}, {#i2: Int#})[#Void#]; name=IntTaker(i1: Int, i2: Int)
// MEMBER4-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: StringTaker({#(s1): String#}, {#s2: String#})[#Void#]; name=StringTaker(s1: String, s2: String)
// MEMBER7: Begin completions
// MEMBER7-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem/TypeRelation[Invalid]: removeAll()[#Void#]; name=removeAll()
// MEMBER7-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem/TypeRelation[Invalid]: removeAll({#keepingCapacity: Bool#})[#Void#]; name=removeAll(keepingCapacity: Bool)
// MEMBER7-DAG: Decl[InstanceVar]/CurrNominal/IsSystem/TypeRelation[Convertible]: count[#Int#]; name=count
// MEMBER7-DAG: Decl[InstanceVar]/CurrNominal/IsSystem/TypeRelation[Convertible]: capacity[#Int#]; name=capacity
// MEMBER8: Begin completions
// MEMBER8-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: InternalIntGen()[#Int#]; name=InternalIntGen()
// MEMBER8-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: InternalIntOpGen()[#Int?#]; name=InternalIntOpGen()
// MEMBER8-DAG: Decl[InstanceMethod]/CurrNominal: InternalStringGen()[#String#]; name=InternalStringGen()
// MEMBER8-DAG: Decl[InstanceMethod]/CurrNominal: InternalStringOpGen()[#String?#]; name=InternalStringOpGen()
// MEMBER8-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: InternalIntTaker({#(i1): Int#}, {#i2: Int#})[#Void#]; name=InternalIntTaker(i1: Int, i2: Int)
// MEMBER8-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: InternalStringTaker({#(s1): String#}, {#s2: String#})[#Void#]; name=InternalStringTaker(s1: String, s2: String)
// FARG6: Begin completions
// FARG6-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: InternalIntGen()[#Int#]
// FARG6-DAG: Decl[InstanceMethod]/CurrNominal: InternalIntOpGen()[#Int?#]
// FARG6-DAG: Decl[InstanceMethod]/CurrNominal: InternalStringGen()[#String#]
// FARG6-DAG: Decl[InstanceMethod]/CurrNominal: InternalStringOpGen()[#String?#]
// FARG6-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: InternalIntTaker({#(i1): Int#}, {#i2: Int#})[#Void#]
// FARG6-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: InternalStringTaker({#(s1): String#}, {#s2: String#})[#Void#]
func firstArg(arg1 arg1: Int, arg2: Int) {}
func testArg1Name1() {
firstArg(#^FIRST_ARG_NAME_1^#
}
// FIRST_ARG_NAME_PATTERN: ['(']{#arg1: Int#}, {#arg2: Int#}[')']
func testArg2Name1() {
firstArg(#^FIRST_ARG_NAME_2^#)
}
func testArg2Name3() {
firstArg(#^FIRST_ARG_NAME_3^#,
}
// FIRST_ARG_NAME_3: Pattern/ExprSpecific: {#arg1: Int#}[#Int#];
// FIRST_ARG_NAME_4: Decl[FreeFunction]/CurrModule: ['(']{#arg1: Int#}, {#arg2: Int#}[')'][#Void#];
func takeArray<T>(_ x: [T]) {}
struct TestBoundGeneric1 {
let x: [Int]
let y: [Int]
func test1() {
takeArray(self.#^BOUND_GENERIC_1_1^#)
}
func test2() {
takeArray(#^BOUND_GENERIC_1_2^#)
}
// BOUND_GENERIC_1: Decl[InstanceVar]/CurrNominal/TypeRelation[Convertible]: x[#[Int]#];
// BOUND_GENERIC_1: Decl[InstanceVar]/CurrNominal/TypeRelation[Convertible]: y[#[Int]#];
}
func whereConvertible<T>(lhs: T, rhs: T) where T: Collection {
_ = zip(lhs, #^GENERIC_TO_GENERIC^#)
}
// GENERIC_TO_GENERIC: Begin completions
// GENERIC_TO_GENERIC: Decl[LocalVar]/Local: lhs[#Collection#]; name=lhs
// GENERIC_TO_GENERIC: Decl[LocalVar]/Local: rhs[#Collection#]; name=rhs
// GENERIC_TO_GENERIC: End completions
func emptyOverload() {}
func emptyOverload(foo foo: Int) {}
emptyOverload(foo: #^EMPTY_OVERLOAD_1^#)
struct EmptyOverload {
init() {}
init(foo: Int) {}
}
_ = EmptyOverload(foo: #^EMPTY_OVERLOAD_2^#)
// EMPTY_OVERLOAD: Begin completions
// EMPTY_OVERLOAD-DAG: Decl[GlobalVar]/Local/TypeRelation[Identical]: i2[#Int#];
// EMPTY_OVERLOAD-DAG: Decl[GlobalVar]/Local/TypeRelation[Identical]: i1[#Int#];
// EMPTY_OVERLOAD: End completions
public func fopen() -> TestBoundGeneric1! { fatalError() }
func other() {
_ = fopen(#^CALLARG_IUO^#)
// CALLARG_IUO: Begin completions, 1 items
// CALLARG_IUO: Decl[FreeFunction]/CurrModule: ['('][')'][#TestBoundGeneric1!#]; name=
// CALLARG_IUO: End completions
}
class Foo { let x: Int }
class Bar {
var collectionView: Foo!
func foo() {
self.collectionView? .#^BOUND_IUO^#x
self.collectionView! .#^FORCED_IUO^#x
}
// MEMBEROF_IUO: Begin completions, 2 items
// MEMBEROF_IUO: Keyword[self]/CurrNominal: self[#Foo#]; name=self
// MEMBEROF_IUO: Decl[InstanceVar]/CurrNominal: x[#Int#]; name=x
// MEMBEROF_IUO: End completions
}
func curry<T1, T2, R>(_ f: @escaping (T1, T2) -> R) -> (T1) -> (T2) -> R {
return { t1 in { t2 in f(#^NESTED_CLOSURE^#, t2) } }
// NESTED_CLOSURE: Begin completions
// FIXME: Should be '/TypeRelation[Invalid]: t2[#T2#]'
// NESTED_CLOSURE: Decl[LocalVar]/Local: t2[#_#]; name=t2
// NESTED_CLOSURE: Decl[LocalVar]/Local: t1[#T1#]; name=t1
}
func trailingClosureLocal(x: Int, fn: (Int) -> Void) {
trailingClosureLocal(x: 1) { localArg in
var localVar = 1
if #^TRAILING_CLOSURE_LOCAL^#
}
// TRAILING_CLOSURE_LOCAL: Begin completions
// TRAILING_CLOSURE_LOCAL: Decl[LocalVar]/Local: localArg[#Int#]; name=localArg
// TRAILING_CLOSURE_LOCAL: Decl[LocalVar]/Local: localVar[#Int#]; name=localVar
}
func shuffled(_ x: Int ..., y: String = "", z: SimpleEnum = .foo) {}
func testTupleShuffle() {
let _ = shuffled(1, 2, 3, 4, #^SHUFFLE_1^#, z: .foo)
let _ = shuffled(1, 2, 3, y: #^SHUFFLE_2^#
let _ = shuffled(z: .#^SHUFFLE_3^#)
}
// SHUFFLE_1: Begin completions
// SHUFFLE_1-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: i1[#Int#]; name=i1
// SHUFFLE_1-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: i2[#Int#]; name=i2
// SHUFFLE_2: Begin completions
// SHUFFLE_2-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: s1[#String#]; name=s1
// SHUFFLE_2-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: s2[#String#]; name=s2
// SHUFFLE_3: Begin completions, 3 items
// SHUFFLE_3-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: foo[#SimpleEnum#]; name=foo
// SHUFFLE_3-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: bar[#SimpleEnum#]; name=bar
// SHUFFLE_3-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: baz[#SimpleEnum#]; name=baz
class HasSubscript {
subscript(idx: Int) -> String {}
subscript(idx: Int, default defaultValue: String) -> String {}
}
func testSubscript(obj: HasSubscript, intValue: Int, strValue: String) {
let _ = obj[#^SUBSCRIPT_1^#
// SUBSCRIPT_1: Begin completions
// SUBSCRIPT_1-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: i1[#Int#]; name=i1
// SUBSCRIPT_1-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: i2[#Int#]; name=i2
// SUBSCRIPT_1-DAG: Decl[GlobalVar]/CurrModule: s1[#String#]; name=s1
// SUBSCRIPT_1-DAG: Decl[GlobalVar]/CurrModule: s2[#String#]; name=s2
let _ = obj[.#^SUBSCRIPT_1_DOT^#
// SUBSCRIPT_1_DOT: Begin completions
// SUBSCRIPT_1_DOT-NOT: i1
// SUBSCRIPT_1_DOT-NOT: s1
// SUBSCRIPT_1_DOT-DAG: Decl[StaticVar]/ExprSpecific/IsSystem: max[#Int#]; name=max
// SUBSCRIPT_1_DOT-DAG: Decl[StaticVar]/ExprSpecific/IsSystem: min[#Int#]; name=min
let _ = obj[42, #^SUBSCRIPT_2^#
// SUBSCRIPT_2: Begin completions, 1 items
// SUBSCRIPT_2-NEXT: Pattern/ExprSpecific: {#default: String#}[#String#];
let _ = obj[42, .#^SUBSCRIPT_2_DOT^#
// SUBSCRIPT_2_DOT-NOT: Begin completions
let _ = obj[42, default: #^SUBSCRIPT_3^#
// SUBSCRIPT_3: Begin completions
// SUBSCRIPT_3-DAG: Decl[GlobalVar]/CurrModule: i1[#Int#]; name=i1
// SUBSCRIPT_3-DAG: Decl[GlobalVar]/CurrModule: i2[#Int#]; name=i2
// SUBSCRIPT_3-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: s1[#String#]; name=s1
// SUBSCRIPT_3-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: s2[#String#]; name=s2
let _ = obj[42, default: .#^SUBSCRIPT_3_DOT^#
// SUBSCRIPT_3_DOT: Begin completions
// SUBSCRIPT_3_DOT-NOT: i1
// SUBSCRIPT_3_DOT-NOT: s1
// SUBSCRIPT_3_DOT-DAG: Decl[Constructor]/CurrNominal/IsSystem/TypeRelation[Identical]: init()[#String#]; name=init()
// SUBSCRIPT_3_DOT-DAG: Decl[Constructor]/CurrNominal/IsSystem/TypeRelation[Identical]: init({#(c): Character#})[#String#]; name=init(c: Character)
}
func testNestedContext() {
func foo(_ x: Int) {}
func bar(_ y: TypeInvalid) -> Int {}
let _ = foo(bar(#^ERRORCONTEXT_NESTED_1^#))
// ERRORCONTEXT_NESTED_1: Begin completions
// ERRORCONTEXT_NESTED_1-DAG: Decl[GlobalVar]/CurrModule: i1[#Int#]; name=i1
// ERRORCONTEXT_NESTED_1-DAG: Decl[GlobalVar]/CurrModule: i2[#Int#]; name=i2
// ERRORCONTEXT_NESTED_1-NOT: TypeRelation[Identical]
for _ in [bar(#^ERRORCONTEXT_NESTED_2^#)] {}
// Same as ERRORCONTEXT_NESTED_1.
}
class TestImplicitlyCurriedSelf {
func foo(x: Int) { }
func foo(arg: Int, optArg: Int) { }
static func test() {
foo(#^CURRIED_SELF_1^#
func sync();
self.foo(#^CURRIED_SELF_2^#
func sync();
TestImplicitlyCurriedSelf.foo(#^CURRIED_SELF_3^#
// CURRIED_SELF_1: Begin completions, 2 items
// CURRIED_SELF_1-DAG: Decl[InstanceMethod]/CurrNominal: ['(']{#(self): TestImplicitlyCurriedSelf#}[')'][#(Int) -> ()#]{{; name=.+$}}
// CURRIED_SELF_1-DAG: Decl[InstanceMethod]/CurrNominal: ['(']{#(self): TestImplicitlyCurriedSelf#}[')'][#(Int, Int) -> ()#]{{; name=.+$}}
// CURRIED_SELF_1: End completions
}
}
class TestStaticMemberCall {
static func create1(arg1: Int) -> TestStaticMemberCall {
return TestStaticMemberCall()
}
static func create2(_ arg1: Int, arg2: Int = 0, arg3: Int = 1, arg4: Int = 2) -> TestStaticMemberCall {
return TestStaticMemberCall()
}
}
func testStaticMemberCall() {
let _ = TestStaticMemberCall.create1(#^STATIC_METHOD_AFTERPAREN_1^#)
// STATIC_METHOD_AFTERPAREN_1: Begin completions, 1 items
// STATIC_METHOD_AFTERPAREN_1: Decl[StaticMethod]/CurrNominal: ['(']{#arg1: Int#}[')'][#TestStaticMemberCall#]; name=arg1: Int
// STATIC_METHOD_AFTERPAREN_1: End completions
let _ = TestStaticMemberCall.create2(#^STATIC_METHOD_AFTERPAREN_2^#)
// STATIC_METHOD_AFTERPAREN_2: Begin completions
// STATIC_METHOD_AFTERPAREN_2-DAG: Decl[StaticMethod]/CurrNominal/TypeRelation[Identical]: ['(']{#(arg1): Int#}[')'][#TestStaticMemberCall#];
// STATIC_METHOD_AFTERPAREN_2-DAG: Decl[StaticMethod]/CurrNominal/TypeRelation[Identical]: ['(']{#(arg1): Int#}, {#arg2: Int#}, {#arg3: Int#}, {#arg4: Int#}[')'][#TestStaticMemberCall#];
// STATIC_METHOD_AFTERPAREN_2-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem/TypeRelation[Identical]: Int[#Int#];
// STATIC_METHOD_AFTERPAREN_2-DAG: Literal[Integer]/None/TypeRelation[Identical]: 0[#Int#];
// STATIC_METHOD_AFTERPAREN_2: End completions
let _ = TestStaticMemberCall.create2(1, #^STATIC_METHOD_SECOND^#)
// STATIC_METHOD_SECOND: Begin completions, 3 items
// STATIC_METHOD_SECOND: Pattern/ExprSpecific: {#arg2: Int#}[#Int#];
// STATIC_METHOD_SECOND: Pattern/ExprSpecific: {#arg3: Int#}[#Int#];
// STATIC_METHOD_SECOND: Pattern/ExprSpecific: {#arg4: Int#}[#Int#];
// STATIC_METHOD_SECOND: End completions
let _ = TestStaticMemberCall.create2(1, arg3: 2, #^STATIC_METHOD_SKIPPED^#)
// STATIC_METHOD_SKIPPED: Begin completions, 2 items
// FIXME: 'arg3' shouldn't be suggested.
// STATIC_METHOD_SKIPPED: Pattern/ExprSpecific: {#arg3: Int#}[#Int#];
// STATIC_METHOD_SKIPPED: Pattern/ExprSpecific: {#arg4: Int#}[#Int#];
// STATIC_METHOD_SKIPPED: End completions
}
func testImplicitMember() {
let _: TestStaticMemberCall = .create1(#^IMPLICIT_MEMBER_AFTERPAREN_1^#)
// IMPLICIT_MEMBER_AFTERPAREN_1: Begin completions, 1 items
// IMPLICIT_MEMBER_AFTERPAREN_1: Decl[StaticMethod]/CurrNominal: ['(']{#arg1: Int#}[')'][#TestStaticMemberCall#]; name=arg1: Int
// IMPLICIT_MEMBER_AFTERPAREN_1: End completions
let _: TestStaticMemberCall = .create2(#^IMPLICIT_MEMBER_AFTERPAREN_2^#)
// IMPLICIT_MEMBER_AFTERPAREN_2: Begin completions
// IMPLICIT_MEMBER_AFTERPAREN_2-DAG: Decl[StaticMethod]/CurrNominal: ['(']{#(arg1): Int#}[')'][#TestStaticMemberCall#];
// IMPLICIT_MEMBER_AFTERPAREN_2-DAG: Decl[StaticMethod]/CurrNominal: ['(']{#(arg1): Int#}, {#arg2: Int#}, {#arg3: Int#}, {#arg4: Int#}[')'][#TestStaticMemberCall#];
// IMPLICIT_MEMBER_AFTERPAREN_2-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem/TypeRelation[Identical]: Int[#Int#];
// IMPLICIT_MEMBER_AFTERPAREN_2-DAG: Literal[Integer]/None/TypeRelation[Identical]: 0[#Int#];
// IMPLICIT_MEMBER_AFTERPAREN_2: End completions
let _: TestStaticMemberCall = .create2(1, #^IMPLICIT_MEMBER_SECOND^#)
// IMPLICIT_MEMBER_SECOND: Begin completions, 3 items
// IMPLICIT_MEMBER_SECOND: Pattern/ExprSpecific: {#arg2: Int#}[#Int#];
// IMPLICIT_MEMBER_SECOND: Pattern/ExprSpecific: {#arg3: Int#}[#Int#];
// IMPLICIT_MEMBER_SECOND: Pattern/ExprSpecific: {#arg4: Int#}[#Int#];
// IMPLICIT_MEMBER_SECOND: End completions
let _: TestStaticMemberCall = .create2(1, arg3: 2, #^IMPLICIT_MEMBER_SKIPPED^#)
// IMPLICIT_MEMBER_SKIPPED: Begin completions, 2 items
// FIXME: 'arg3' shouldn't be suggested.
// IMPLICIT_MEMBER_SKIPPED: Pattern/ExprSpecific: {#arg3: Int#}[#Int#];
// IMPLICIT_MEMBER_SKIPPED: Pattern/ExprSpecific: {#arg4: Int#}[#Int#];
// IMPLICIT_MEMBER_SKIPPED: End completions
}
func testImplicitMemberInArrayLiteral() {
struct Receiver {
init(_: [TestStaticMemberCall]) {}
init(arg1: Int, arg2: [TestStaticMemberCall]) {}
}
Receiver([
.create1(x: 1),
.create1(#^IMPLICIT_MEMBER_ARRAY_1_AFTERPAREN_1^#),
// Same as IMPLICIT_MEMBER_AFTERPAREN_1.
])
Receiver([
.create2(#^IMPLICIT_MEMBER_ARRAY_1_AFTERPAREN_2^#),
// Same as IMPLICIT_MEMBER_AFTERPAREN_2.
.create2(1, #^IMPLICIT_MEMBER_ARRAY_1_SECOND^#
// Same as IMPLICIT_MEMBER_SECOND.
])
Receiver(arg1: 12, arg2: [
.create2(1, arg3: 2, #^IMPLICIT_MEMBER_ARRAY_1_SKIPPED^#
// Same as IMPLICIT_MEMBER_SKIPPED.
.create1(x: 12)
])
let _: [TestStaticMemberCall] = [
.create1(#^IMPLICIT_MEMBER_ARRAY_2_AFTERPAREN_1^#),
// Same as STATIC_METHOD_AFTERPAREN_1.
.create2(#^IMPLICIT_MEMBER_ARRAY_2_AFTERPAREN_2^#),
// Same as STATIC_METHOD_AFTERPAREN_2.
.create2(1, #^IMPLICIT_MEMBER_ARRAY_2_SECOND^#),
// Same as STATIC_METHOD_SECOND.
.create2(1, arg3: 2, #^IMPLICIT_MEMBER_ARRAY_2_SKIPPED^#),
// Same as STATIC_METHOD_SKIPPED.
]
}
struct Wrap<T> {
func method<U>(_ fn: (T) -> U) -> Wrap<U> {}
}
func testGenricMethodOnGenericOfArchetype<Wrapped>(value: Wrap<Wrapped>) {
value.method(#^ARCHETYPE_GENERIC_1^#)
// ARCHETYPE_GENERIC_1: Begin completions
// ARCHETYPE_GENERIC_1: Decl[InstanceMethod]/CurrNominal: ['(']{#(fn): (Wrapped) -> U##(Wrapped) -> U#}[')'][#Wrap<U>#];
}
struct TestHasErrorAutoclosureParam {
func hasErrorAutoclosureParam(value: @autoclosure () -> Value) {
fatalError()
}
func test() {
hasErrorAutoclosureParam(#^PARAM_WITH_ERROR_AUTOCLOSURE^#
// PARAM_WITH_ERROR_AUTOCLOSURE: Begin completions, 1 items
// PARAM_WITH_ERROR_AUTOCLOSURE: Decl[InstanceMethod]/CurrNominal: ['(']{#value: <<error type>>#}[')'][#Void#];
// PARAM_WITH_ERROR_AUTOCLOSURE: End completions
}
}
struct MyType<T> {
init(arg1: String, arg2: T) {}
func overloaded() {}
func overloaded(_ int: Int) {}
func overloaded(name: String, value: String) {}
}
func testTypecheckedOverloaded<T>(value: MyType<T>) {
value.overloaded(#^TYPECHECKED_OVERLOADED^#)
// TYPECHECKED_OVERLOADED: Begin completions
// TYPECHECKED_OVERLOADED-DAG: Decl[InstanceMethod]/CurrNominal: ['('][')'][#Void#];
// TYPECHECKED_OVERLOADED-DAG: Decl[InstanceMethod]/CurrNominal: ['(']{#(int): Int#}[')'][#Void#];
// TYPECHECKED_OVERLOADED-DAG: Decl[InstanceMethod]/CurrNominal: ['(']{#name: String#}, {#value: String#}[')'][#Void#];
// TYPECHECKED_OVERLOADED: End completions
}
extension MyType where T == Int {
init(_ intVal: T) {}
}
func testTypecheckedTypeExpr() {
MyType(#^TYPECHECKED_TYPEEXPR^#
}
// TYPECHECKED_TYPEEXPR: Begin completions
// TYPECHECKED_TYPEEXPR: Decl[Constructor]/CurrNominal: ['(']{#arg1: String#}, {#arg2: _#}[')'][#MyType<_>#]; name=arg1: String, arg2: _
// TYPECHECKED_TYPEEXPR: Decl[Constructor]/CurrNominal: ['(']{#(intVal): Int#}[')'][#MyType<Int>#]; name=intVal: Int
// TYPECHECKED_TYPEEXPR: End completions
func testPamrameterFlags(_: Int, inoutArg: inout Int, autoclosureArg: @autoclosure () -> Int, iuoArg: Int!, variadicArg: Int...) {
var intVal = 1
testPamrameterFlags(intVal, #^ARG_PARAMFLAG_INOUT^#)
// ARG_PARAMFLAG_INOUT: Begin completions, 1 items
// ARG_PARAMFLAG_INOUT-DAG: Pattern/ExprSpecific: {#inoutArg: &Int#}[#inout Int#]; name=inoutArg:
// ARG_PARAMFLAG_INOUT: End completions
testPamrameterFlags(intVal, inoutArg: &intVal, #^ARG_PARAMFLAG_AUTOCLOSURE^#)
// ARG_PARAMFLAG_AUTOCLOSURE: Begin completions, 1 items
// ARG_PARAMFLAG_AUTOCLOSURE-DAG: Pattern/ExprSpecific: {#autoclosureArg: Int#}[#Int#];
// ARG_PARAMFLAG_AUTOCLOSURE: End completions
testPamrameterFlags(intVal, inoutArg: &intVal, autoclosureArg: intVal, #^ARG_PARAMFLAG_IUO^#)
// ARG_PARAMFLAG_IUO: Begin completions, 1 items
// ARG_PARAMFLAG_IUO-DAG: Pattern/ExprSpecific: {#iuoArg: Int?#}[#Int?#];
// ARG_PARAMFLAG_IUO: End completions
testPamrameterFlags(intVal, inoutArg: &intVal, autoclosureArg: intVal, iuoArg: intVal, #^ARG_PARAMFLAG_VARIADIC^#)
// ARG_PARAMFLAG_VARIADIC: Begin completions, 1 items
// ARG_PARAMFLAG_VARIADIC-DAG: Pattern/ExprSpecific: {#variadicArg: Int...#}[#Int#];
// ARG_PARAMFLAG_VARIADIC: End completions
}
func testTupleElement(arg: (SimpleEnum, SimpleEnum)) {
testTupleElement(arg: (.foo, .#^TUPLEELEM_1^#))
// TUPLEELEM_1: Begin completions, 3 items
// TUPLEELEM_1-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: foo[#SimpleEnum#]; name=foo
// TUPLEELEM_1-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: bar[#SimpleEnum#]; name=bar
// TUPLEELEM_1-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: baz[#SimpleEnum#]; name=baz
// TUPLEELEM_1: End completions
testTupleElement(arg: (.foo, .bar, .#^TUPLEELEM_2^#))
// TUPLEELEM_2-NOT: Begin completions
}
func testKeyPathThunkInBase() {
struct TestKP {
var value: Int { 1 }
}
struct TestKPResult {
func testFunc(_ arg: SimpleEnum) {}
}
func foo(_ fn: (TestKP) -> Int) -> TestKPResult { TestKPResult() }
foo(\.value).testFunc(.#^KEYPATH_THUNK_BASE^#)
// KEYPATH_THUNK_BASE: Begin completions, 3 items
// KEYPATH_THUNK_BASE-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: foo[#SimpleEnum#]; name=foo
// KEYPATH_THUNK_BASE-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: bar[#SimpleEnum#]; name=bar
// KEYPATH_THUNK_BASE-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: baz[#SimpleEnum#]; name=baz
// KEYPATH_THUNK_BASE: End completions
}
func testVariadic(_ arg: Any..., option1: Int = 0, option2: String = 1) {
testVariadic(#^VARIADIC_1^#)
// VARIADIC_1: Begin completions
// VARIADIC_1-DAG: Decl[FreeFunction]/CurrModule: ['(']{#(arg): Any...#}, {#option1: Int#}, {#option2: String#}[')'][#Void#];
// VARIADIC_1-DAG: Decl[GlobalVar]/CurrModule: i1[#Int#];
// VARIADIC_1: End completions
testVariadic(1, #^VARIADIC_2^#)
// VARIADIC_2: Begin completions
// VARIADIC_2-DAG: Pattern/ExprSpecific: {#option1: Int#}[#Int#];
// VARIADIC_2-DAG: Pattern/ExprSpecific: {#option2: String#}[#String#];
// VARIADIC_2-DAG: Decl[GlobalVar]/CurrModule: i1[#Int#];
// VARIADIC_2: End completions
testVariadic(1, 2, #^VARIADIC_3^#)
// Same as VARIADIC_2.
}
| 1a5dfa934f837bd089cc497ddad7ccbe | 52.850575 | 193 | 0.705699 | false | true | false | false |
TTVS/NightOut | refs/heads/master | Clubber/WelcomeViewController.swift | apache-2.0 | 1 | //
// WelcomeViewController.swift
// Clubber
//
// Created by Terra on 6/1/15.
// Copyright (c) 2015 Dino Media Asia. All rights reserved.
//
import UIKit
class WelcomeViewController: UIViewController {
@IBOutlet var welcomeView: UIView!
@IBOutlet var welcomeWebViewBG: UIWebView!
@IBOutlet var welcomeLabel: UILabel!
@IBOutlet var signUpButton: UIButton!
@IBOutlet var loginButton: UIButton!
var colorX : UIColor = UIColor(red: (10/255.0), green: (237/255.0), blue: (213/255.0), alpha: 1.0)
var colorY : UIColor = UIColor(red: (255/255.0), green: (0/255.0), blue: (70/255.0), alpha: 1.0)
override func viewDidLoad() {
super.viewDidLoad()
// Create File Path and Read From It
let filePath = NSBundle.mainBundle().pathForResource("faceBook", ofType: "gif")
let gif = NSData(contentsOfFile: filePath!)
// UIWebView to Load gif
welcomeWebViewBG.loadData(gif!, MIMEType: "image/gif", textEncodingName: "utf-8", baseURL: NSURL(string: "http://localhost/")!)
welcomeWebViewBG.userInteractionEnabled = false
self.view.addSubview(welcomeWebViewBG)
// backgroundFilter
let filter = UIView()
filter.frame = self.view.frame
filter.backgroundColor = UIColor.blackColor()
filter.alpha = 0.35
self.view.addSubview(filter)
welcomeLabel.text = "Welcome Fellow Clubber"
welcomeLabel.textColor = UIColor.whiteColor()
welcomeLabel.font = UIFont(name: "Avenir Next", size: 17)
self.view.addSubview(welcomeLabel)
loginButton.setBackgroundImage(UIImage(named: "cyanOutfill"), forState: UIControlState.Normal)
// loginButton.layer.borderColor = UIColor.whiteColor().CGColor
// loginButton.layer.borderWidth = 1
// loginButton.layer.cornerRadius = 5
loginButton.titleLabel!.font = UIFont(name: "Avenir Next", size: 16)
loginButton.tintColor = colorX
loginButton.backgroundColor = UIColor.clearColor()
loginButton.setTitle("Login", forState: UIControlState.Normal)
loginButton.center = CGPointMake(welcomeView.frame.size.width / 2, welcomeView.frame.size.height / 2)
self.view.addSubview(loginButton)
signUpButton.setBackgroundImage(UIImage(named: "coralRedOutfill"), forState: UIControlState.Normal)
// signUpButton.layer.borderColor = UIColor.whiteColor().CGColor
// signUpButton.layer.borderWidth = 1
// signUpButton.layer.cornerRadius = 5
signUpButton.titleLabel!.font = UIFont(name: "Avenir Next", size: 16)
signUpButton.tintColor = colorY
signUpButton.backgroundColor = UIColor.clearColor()
signUpButton.setTitle("Sign Up", forState: UIControlState.Normal)
self.view.addSubview(signUpButton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| ee1a789e3a5d267b0bc1e9bc010edca5 | 39.654321 | 139 | 0.616155 | false | false | false | false |
yrchen/edx-app-ios | refs/heads/master | Source/IrregularBorderView.swift | apache-2.0 | 1 | //
// IrregularBorderStyle.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 26/10/2015.
// Copyright © 2015 edX. All rights reserved.
//
import UIKit
struct CellPosition : OptionSetType {
let rawValue : UInt
static let Top = CellPosition(rawValue: 1 << 0)
static let Bottom = CellPosition(rawValue: 1 << 1)
var roundedCorners : UIRectCorner {
var result = UIRectCorner()
if self.contains(CellPosition.Top) {
result = result.union([.TopLeft, .TopRight])
}
if self.contains(CellPosition.Bottom) {
result = result.union([.BottomLeft, .BottomRight])
}
return result
}
}
struct IrregularBorderStyle {
let corners : UIRectCorner
let base : BorderStyle
init(corners : UIRectCorner, base : BorderStyle) {
self.corners = corners
self.base = base
}
init(position : CellPosition, base : BorderStyle) {
self.init(corners: position.roundedCorners, base: base)
}
}
class IrregularBorderView : UIImageView {
let cornerMaskView = UIImageView()
init() {
super.init(frame : CGRectZero)
self.addSubview(cornerMaskView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var style : IrregularBorderStyle? {
didSet {
if let style = style {
let radius = style.base.cornerRadius.value(self)
self.cornerMaskView.image = renderMaskWithCorners(style.corners, cornerRadii: CGSizeMake(radius, radius))
self.maskView = cornerMaskView
self.image = renderBorderWithEdges(style.corners, style : style.base)
}
else {
self.maskView = nil
self.image = nil
}
}
}
private func renderMaskWithCorners(corners : UIRectCorner, cornerRadii : CGSize) -> UIImage {
let size = CGSizeMake(cornerRadii.width * 2 + 1, cornerRadii.height * 2 + 1)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIColor.blackColor().setFill()
let path = UIBezierPath(roundedRect: CGRect(origin: CGPointZero, size: size), byRoundingCorners: corners, cornerRadii: cornerRadii)
path.fill()
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result.resizableImageWithCapInsets(UIEdgeInsets(top: cornerRadii.height, left: cornerRadii.width, bottom: cornerRadii.height, right: cornerRadii.width))
}
private func renderBorderWithEdges(corners : UIRectCorner, style : BorderStyle) -> UIImage? {
let radius = style.cornerRadius.value(self)
let size = CGSizeMake(radius * 2 + 1, radius * 2 + 1)
guard let color = style.color else {
return nil
}
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setStroke()
let path = UIBezierPath(roundedRect: CGRect(origin: CGPointZero, size: size), byRoundingCorners: corners, cornerRadii: CGSizeMake(radius, radius))
path.lineWidth = style.width.value
path.stroke()
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result.resizableImageWithCapInsets(UIEdgeInsets(top: radius, left: radius, bottom: radius, right: radius))
}
override func layoutSubviews() {
super.layoutSubviews()
self.maskView?.frame = self.bounds
}
}
| 3f75e819d9eba4c8edc3bd5f7effb701 | 32.333333 | 167 | 0.633611 | false | false | false | false |
chicio/Exploring-SceneKit | refs/heads/master | ExploringSceneKit/Model/Scenes/BlinnPhong/DynamicSphere.swift | mit | 1 | //
// DynamicSphere.swift
// ExploringSceneKit
//
// Created by Fabrizio Duroni on 26.08.17.
//
import SceneKit
class DynamicSphere: Object {
let sphereGeometry: SCNSphere
init(material: BlinnPhongMaterial, physicsBodyFeature: PhysicsBodyFeatures, radius: CGFloat, position: SCNVector3, rotation: SCNVector4) {
sphereGeometry = SCNSphere(radius: radius)
super.init(geometry: sphereGeometry, position: position, rotation: rotation)
node.geometry?.firstMaterial = material.material
node.physicsBody = SCNPhysicsBody.dynamic()
node.physicsBody?.mass = physicsBodyFeature.mass
node.physicsBody?.rollingFriction = physicsBodyFeature.rollingFriction
}
}
| 9412af3a8bfbe3446b381630575ffeac | 33.190476 | 142 | 0.731198 | false | false | false | false |
SwifterSwift/SwifterSwift | refs/heads/master | Tests/SceneKitTests/SCNBoxExtensionsTests.swift | mit | 1 | // SCNBoxExtensionsTests.swift - Copyright 2020 SwifterSwift
@testable import SwifterSwift
import XCTest
#if canImport(SceneKit)
import SceneKit
final class SCNBoxExtensionsTests: XCTestCase {
func testInitWithoutChamferRadius() {
let box = SCNBox(width: 1, height: 2, length: 3)
XCTAssertEqual(box.boundingSize, SCNVector3(1, 2, 3))
}
func testInitWithMaterial() {
let material = SCNMaterial(color: .red)
let box = SCNBox(width: 1, height: 2, length: 3, chamferRadius: 0, material: material)
XCTAssertEqual(box.materials, [material])
}
func testInitWithColor() {
let color = SFColor.red
let box = SCNBox(width: 1, height: 2, length: 3, chamferRadius: 0, color: color)
XCTAssertEqual(box.materials[0].diffuse.contents as? SFColor, color)
}
func testInitWithSideLength() {
let box = SCNBox(sideLength: 1)
XCTAssertEqual(box.boundingSize, SCNVector3(1, 1, 1))
}
func testInitWithSideLengthAndMaterial() {
let material = SCNMaterial(color: .red)
let box = SCNBox(sideLength: 1, chamferRadius: 0, material: material)
XCTAssertEqual(box.boundingSize, SCNVector3(1, 1, 1))
XCTAssertEqual(box.materials, [material])
}
func testInitWithSideLengthAndColor() {
let color = SFColor.red
let box = SCNBox(sideLength: 1, chamferRadius: 0, color: color)
XCTAssertEqual(box.boundingSize, SCNVector3(1, 1, 1))
XCTAssertEqual(box.materials[0].diffuse.contents as? SFColor, color)
}
}
#endif
| 4e1d79ddeb0422d30d2e065c9325c507 | 32.489362 | 94 | 0.672808 | false | true | false | false |
AbelSu131/ios-charts | refs/heads/master | Charts/Classes/Data/BarChartDataSet.swift | apache-2.0 | 2 | //
// BarChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class BarChartDataSet: BarLineScatterCandleChartDataSet
{
/// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width)
public var barSpace: CGFloat = 0.15
/// the maximum number of bars that are stacked upon each other, this value
/// is calculated from the Entries that are added to the DataSet
private var _stackSize = 1
/// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
public var barShadowColor = UIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
/// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
public var highLightAlpha = CGFloat(120.0 / 255.0)
/// the overall entry count, including counting each stack-value individually
private var _entryCountStacks = 0
/// array of labels used to describe the different values of the stacked bars
public var stackLabels: [String] = ["Stack"]
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label);
self.highlightColor = UIColor.blackColor();
self.calcStackSize(yVals as! [BarChartDataEntry]?);
self.calcEntryCountIncludingStacks(yVals as! [BarChartDataEntry]?);
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
var copy = super.copyWithZone(zone) as! BarChartDataSet;
copy.barSpace = barSpace;
copy._stackSize = _stackSize;
copy.barShadowColor = barShadowColor;
copy.highLightAlpha = highLightAlpha;
copy._entryCountStacks = _entryCountStacks;
copy.stackLabels = stackLabels;
return copy;
}
/// Calculates the total number of entries this DataSet represents, including
/// stacks. All values belonging to a stack are calculated separately.
private func calcEntryCountIncludingStacks(yVals: [BarChartDataEntry]!)
{
_entryCountStacks = 0;
for (var i = 0; i < yVals.count; i++)
{
var vals = yVals[i].values;
if (vals == nil)
{
_entryCountStacks++;
}
else
{
_entryCountStacks += vals.count;
}
}
}
/// calculates the maximum stacksize that occurs in the Entries array of this DataSet
private func calcStackSize(yVals: [BarChartDataEntry]!)
{
for (var i = 0; i < yVals.count; i++)
{
var vals = yVals[i].values;
if (vals != nil && vals.count > _stackSize)
{
_stackSize = vals.count;
}
}
}
/// Returns the maximum number of bars that can be stacked upon another in this DataSet.
public var stackSize: Int
{
return _stackSize;
}
/// Returns true if this DataSet is stacked (stacksize > 1) or not.
public var isStacked: Bool
{
return _stackSize > 1 ? true : false;
}
/// returns the overall entry count, including counting each stack-value individually
public var entryCountStacks: Int
{
return _entryCountStacks;
}
} | 4120f2da96a77fcfc85d725a945270d0 | 31.643478 | 148 | 0.620037 | false | false | false | false |
nagyistoce/SwiftHN | refs/heads/master | SwiftHN/AppDelegate.swift | gpl-2.0 | 1 | //
// AppDelegate.swift
// SwiftHN
//
// Created by Thomas Ricouard on 05/06/14.
// Copyright (c) 2014 Thomas Ricouard. All rights reserved.
//
import UIKit
import SwiftHNShared
import HackerSwifter
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
self.setupStyle()
return true
}
func setupStyle() {
UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: false)
UINavigationBar.appearance().barTintColor = UIColor.HNColor()
UINavigationBar.appearance().translucent = true
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(),
NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 16.0)!]
}
func application(application: UIApplication!, performFetchWithCompletionHandler
completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
Post.fetch(Post.PostFilter.Top, completion: {(posts: [Post]!, error: Fetcher.ResponseError!, local: Bool) in
if (!local) {
completionHandler(UIBackgroundFetchResult.NewData)
}
else if (error != nil) {
completionHandler(UIBackgroundFetchResult.Failed)
}
})
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 239272c9403fd8e8073fa7e997c1ef8d | 46.43662 | 285 | 0.713777 | false | false | false | false |
Angelnil/Eva | refs/heads/master | Eva/Eva/Refresh/RefreshBaseView.swift | mit | 1 | //
// RefreshBaseView.swift
// RefreshExample
//
// Created by SunSet on 14-6-23.
// Copyright (c) 2014 zhaokaiyuan. All rights reserved.
//
import UIKit
struct RefreshConst {
let RefreshViewHeight:CGFloat = 64.0
let RefreshSlowAnimationDuration:NSTimeInterval = 0.5
let RefreshFooterPullToRefresh:String = "上拉可以加载更多数据"
let RefreshFooterReleaseToRefresh:String = "松开立即加载更多数据"
let RefreshFooterRefreshing:String = "正在加载数据..."
let RefreshHeaderPullToRefresh:String = "下拉刷新"
let RefreshHeaderReleaseToRefresh:String = "松开立即刷新"
let RefreshHeaderRefreshing:String = "正在刷新中..."
let RefreshHeaderTimeKey:String = "RefreshHeaderView"
let RefreshContentOffset:String = "contentOffset"
let RefreshContentSize:String = "contentSize"
let RefreshLabelTextColor:UIColor = UIColor(red: 150.0/255, green: 150.0/255.0, blue: 150.0/255.0, alpha: 1)
}
//控件的刷新状态
enum RefreshState {
case Pulling // 松开就可以进行刷新的状态
case Normal // 普通状态
case Refreshing // 正在刷新中的状态
case WillRefreshing
}
//控件的类型
enum RefreshViewType {
case TypeHeader // 头部控件
case TypeFooter // 尾部控件
}
class RefreshBaseView: UIView {
// 父控件
var scrollView:UIScrollView!
var scrollViewOriginalInset:UIEdgeInsets!
// 内部的控件
var statusLabel:UILabel!
var arrowImage:UIImageView!
var activityView:UIActivityIndicatorView!
//回调
var beginRefreshingCallback:(()->Void)?
// 交给子类去实现 和 调用
var oldState:RefreshState?
var State:RefreshState = RefreshState.Normal
func setState(newValue:RefreshState){
if self.State != RefreshState.Refreshing {
scrollViewOriginalInset = self.scrollView.contentInset;
}
if self.State == newValue {
return
}
switch newValue {
case .Normal:
self.arrowImage.hidden = false
self.activityView.stopAnimating()
break
case .Pulling:
break
case .Refreshing:
self.arrowImage.hidden = true
activityView.startAnimating()
beginRefreshingCallback!()
break
default:
break
}
}
//控件初始化
override init(frame: CGRect) {
super.init(frame: frame)
//状态标签
statusLabel = UILabel()
statusLabel.autoresizingMask = UIViewAutoresizing.FlexibleWidth
statusLabel.font = UIFont.boldSystemFontOfSize(13)
statusLabel.textColor = RefreshConst().RefreshLabelTextColor
statusLabel.backgroundColor = UIColor.clearColor()
statusLabel.textAlignment = NSTextAlignment.Center
self.addSubview(statusLabel)
//箭头图片
arrowImage = UIImageView(image: UIImage(named: "blueArrow.png"))
arrowImage.frame = CGRectMake(0, 0, 15, 30);
arrowImage.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin
self.addSubview(arrowImage)
//状态标签
activityView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
activityView.bounds = self.arrowImage.bounds
activityView.autoresizingMask = self.arrowImage.autoresizingMask
self.addSubview(activityView)
//自己的属性
self.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.backgroundColor = UIColor.clearColor()
//设置默认状态
self.State = RefreshState.Normal;
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
//箭头
let arrowX:CGFloat = self.frame.size.width * 0.5 - 100
self.arrowImage.center = CGPointMake(arrowX, self.frame.size.height * 0.5)
//指示器
self.activityView.center = self.arrowImage.center
}
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
// 旧的父控件
if (self.superview != nil) {
self.superview!.removeObserver(self,forKeyPath:RefreshConst().RefreshContentSize as String,context: nil)
}
// 新的父控件
if (newSuperview != nil) {
newSuperview!.addObserver(self, forKeyPath: RefreshConst().RefreshContentOffset as String, options: NSKeyValueObservingOptions.New, context: nil)
var rect:CGRect = self.frame
// 设置宽度 位置
rect.size.width = newSuperview!.frame.size.width
rect.origin.x = 0
self.frame = frame;
//UIScrollView
scrollView = newSuperview as! UIScrollView
scrollViewOriginalInset = scrollView.contentInset;
}
}
//显示到屏幕上
override func drawRect(rect: CGRect) {
superview!.drawRect(rect)
if self.State == RefreshState.WillRefreshing {
self.State = RefreshState.Refreshing
}
}
// 刷新相关
// 是否正在刷新
func isRefreshing()->Bool{
return RefreshState.Refreshing == self.State;
}
// 开始刷新
func beginRefreshing(){
// self.State = RefreshState.Refreshing;
if (self.window != nil) {
self.State = RefreshState.Refreshing;
} else {
//不能调用set方法
State = RefreshState.WillRefreshing;
super.setNeedsDisplay()
}
}
//结束刷新
func endRefreshing(){
let delayInSeconds:Double = 0.3
var popTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds));
dispatch_after(popTime, dispatch_get_main_queue(), {
self.State = RefreshState.Normal;
})
}
}
| 69a9032feee2fe0f227fa063a0de2697 | 28.305419 | 157 | 0.618255 | false | false | false | false |
iAladdin/SwiftyFORM | refs/heads/master | Source/Util/DebugViewController.swift | mit | 1 | //
// DebugViewController.swift
// SwiftyFORM
//
// Created by Simon Strandgaard on 20/11/14.
// Copyright (c) 2014 Simon Strandgaard. All rights reserved.
//
import UIKit
public enum WhatToShow {
case Json(json: NSData)
case Text(text: String)
case Url(url: NSURL)
}
/*
Usage:
DebugViewController.showURL(self, url: NSURL(string: "http://www.google.com")!)
DebugViewController.showText(self, text: "hello world")
*/
public class DebugViewController: UIViewController {
public let dismissBlock: Void -> Void
public let whatToShow: WhatToShow
public init(dismissBlock: Void -> Void, whatToShow: WhatToShow) {
self.dismissBlock = dismissBlock
self.whatToShow = whatToShow
super.init(nibName: nil, bundle: nil)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public class func showJSON(parentViewController: UIViewController, jsonData: NSData) {
showModally(parentViewController, whatToShow: WhatToShow.Json(json: jsonData))
}
public class func showText(parentViewController: UIViewController, text: String) {
showModally(parentViewController, whatToShow: WhatToShow.Text(text: text))
}
public class func showURL(parentViewController: UIViewController, url: NSURL) {
showModally(parentViewController, whatToShow: WhatToShow.Url(url: url))
}
public class func showModally(parentViewController: UIViewController, whatToShow: WhatToShow) {
weak var weakSelf = parentViewController
let dismissBlock: Void -> Void = {
if let vc = weakSelf {
vc.dismissViewControllerAnimated(true, completion: nil)
}
}
let vc = DebugViewController(dismissBlock: dismissBlock, whatToShow: whatToShow)
let nc = UINavigationController(rootViewController: vc)
parentViewController.presentViewController(nc, animated: true, completion: nil)
}
public override func loadView() {
let webview = UIWebView()
self.view = webview
let item = UIBarButtonItem(title: "Dismiss", style: .Plain, target: self, action: "dismissAction:")
self.navigationItem.leftBarButtonItem = item
switch whatToShow {
case let .Json(json):
let url = NSURL(string: "http://localhost")!
webview.loadData(json, MIMEType: "application/json", textEncodingName: "utf-8", baseURL: url)
self.title = "JSON"
case let .Text(text):
let url = NSURL(string: "http://localhost")!
let data = (text as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
webview.loadData(data, MIMEType: "text/plain", textEncodingName: "utf-8", baseURL: url)
self.title = "Text"
case let .Url(url):
let request = NSURLRequest(URL: url)
webview.loadRequest(request)
self.title = "URL"
}
}
func dismissAction(sender: AnyObject?) {
dismissBlock()
}
}
| 2df1f83c7f1a3889250628c677eb5fe4 | 29.208791 | 101 | 0.736268 | false | false | false | false |
brightify/torch | refs/heads/fix/xcode11 | Tests/GCDSafetyTest.swift | mit | 1 | //
// GCDSafetyTest.swift
// Torch
//
// Created by Tadeas Kriz on 7/5/17.
// Copyright © 2017 Brightify. All rights reserved.
//
import XCTest
import RealmSwift
import Torch
//class SyncThread: Thread {
// private let lockQueue = DispatchQueue(label: "lockQueue")
// private let dispatchGroup = DispatchGroup()
// private var work: () -> Any = { Void() }
// private var result: Any = Void()
//
// private let queue = OperationQueue()
//
// override func main() {
// self.result = work()
// work = { Void() }
// print(result)
// dispatchGroup.leave()
// }
//
// func sync<RESULT>(work: () -> RESULT) -> RESULT {
// return lockQueue.sync {
// return withoutActuallyEscaping(work) { work in
// self.work = work
// dispatchGroup.enter()
// start()
// dispatchGroup.wait()
// return result as! RESULT
// }
// }
// }
//}
class GCDSafetyTest: XCTestCase {
func testSyncDifferentThread() {
let queue = DispatchQueue(label: "test")
let otherQueue = DispatchQueue(label: "other")
let check = queue.sync {
Thread.current
}
let e = expectation(description: "Threads")
otherQueue.async {
queue.sync {
XCTAssertNotEqual(check, Thread.current)
e.fulfill()
}
}
waitForExpectations(timeout: 5)
}
func testSyncSafety() {
let queue = DispatchQueue(label: "test")
let otherQueue = DispatchQueue(label: "other")
let other2Queue = DispatchQueue(label: "other2")
let (database, check) = queue.sync {
(TestUtils.initDatabase(), Thread.current)
}
let e = expectation(description: "Create")
var entity = OtherData(id: nil, text: "Test")
otherQueue.async {
print("async 1")
queue.sync {
print("sync 1a")
TestUtils.initDatabase(keepData: true).create(&entity)
print("sync 1b")
XCTAssertNotEqual(check, Thread.current)
print("sync 1c")
e.fulfill()
print("sync 1d")
}
}
let e2 = expectation(description: "Load")
other2Queue.async {
sleep(1)
print("async 2")
queue.sync {
print("sync 2a")
print(TestUtils.initDatabase(keepData: true).load(OtherData.self))
print("sync 2b")
XCTAssertNotEqual(check, Thread.current)
print("sync 2c")
e2.fulfill()
print("sync 2d")
}
}
waitForExpectations(timeout: 60)
}
// func testThreadSafety() {
// let otherQueue = DispatchQueue(label: "other")
// let thread = SyncThread()
//
// let check = thread.sync {
// Thread.current
// }
//
//
// let e = expectation(description: "Threads")
//
// otherQueue.async {
// thread.sync {
// XCTAssertEqual(check, Thread.current)
// e.fulfill()
// }
// }
//
// waitForExpectations(timeout: 5)
// }
}
| b2c545fad4b4963e0964c0096c8bca5b | 25.357143 | 82 | 0.509786 | false | true | false | false |
ksco/swift-algorithm-club-cn | refs/heads/master | Fixed Size Array/FixedSizeArray.swift | mit | 2 | /*
An unordered array with a maximum size.
Performance is always O(1).
*/
struct FixedSizeArray<T> {
private var maxSize: Int
private var defaultValue: T
private var array: [T]
private (set) var count = 0
init(maxSize: Int, defaultValue: T) {
self.maxSize = maxSize
self.defaultValue = defaultValue
self.array = [T](count: maxSize, repeatedValue: defaultValue)
}
subscript(index: Int) -> T {
assert(index >= 0)
assert(index < count)
return array[index]
}
mutating func append(newElement: T) {
assert(count < maxSize)
array[count] = newElement
count += 1
}
mutating func removeAtIndex(index: Int) -> T {
assert(index >= 0)
assert(index < count)
count -= 1
let result = array[index]
array[index] = array[count]
array[count] = defaultValue
return result
}
mutating func removeAll() {
for i in 0..<count {
array[i] = defaultValue
}
count = 0
}
}
| 9beed84c7ee6e2a65dcd0eb4dfede457 | 19.913043 | 65 | 0.628898 | false | false | false | false |
neotron/SwiftBot-Discord | refs/heads/master | DiscordAPI/Source/API/WebSockets/API/GatewayUrlRequest.swift | gpl-3.0 | 1 | //
// Created by David Hedbor on 2/12/16.
// Copyright (c) 2016 NeoTron. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
class GatewayUrlRequest {
internal func execute(_ callback: ((Bool)->Void)?) {
guard let token = Registry.instance.token else {
LOG_ERROR("Cannot retrieve endpoint, login first.")
callback?(false)
return
}
// public func request(
// _ url: URLConvertible,
// method: HTTPMethod = .get,
// parameters: Parameters? = nil,
// encoding: ParameterEncoding = URLEncoding.default,
// headers: HTTPHeaders? = nil)
// -> DataRequest
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"User-Agent": Registry.userAgent,
"Authorization": token,
]
Alamofire.request(Endpoints.Simple(.Gateway), headers: headers).responseObject {
(response: DataResponse<GatewayUrlResponseModel>) in
var success = false
if let url = response.result.value?.url {
Registry.instance.websocketEndpoint = url
LOG_INFO("Retrieved websocket endpoint: \(url)")
success = true
} else {
LOG_ERROR("Failed to retrieve websocket endpoint: \(response.result.error)");
}
callback?(success)
}
}
}
| a32941075d5d218344f41cd08250c653 | 32.613636 | 93 | 0.565923 | false | false | false | false |
jacobwhite/firefox-ios | refs/heads/master | Extensions/ShareTo/UXConstants.swift | mpl-2.0 | 1 | /* 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
struct UX {
static let doneDialogAnimationDuration: TimeInterval = 0.2
static let durationToShowDoneDialog: TimeInterval = UX.doneDialogAnimationDuration + 0.8
static let alphaForFullscreenOverlay: CGFloat = 0.3
static let dialogCornerRadius: CGFloat = 8
static let topViewHeight = 320
static let topViewWidth = 345
static let viewHeightForDoneState = 170
static let pageInfoRowHeight = 64
static let actionRowHeight = 44
static let actionRowSpacingBetweenIconAndTitle: CGFloat = 16
static let actionRowIconSize = 24
static let rowInset: CGFloat = 16
static let pageInfoRowLeftInset = UX.rowInset + 6
static let pageInfoLineSpacing: CGFloat = 2
static let doneLabelBackgroundColor = UIColor(red: 76 / 255.0, green: 158 / 255.0, blue: 1.0, alpha: 1.0)
static let doneLabelFont = UIFont.boldSystemFont(ofSize: 17)
static let separatorColor = UIColor(white: CGFloat(205.0/255.0), alpha: 1.0)
static let baseFont = UIFont.systemFont(ofSize: 15)
static let actionRowTextAndIconColor = UIColor.Photon.Grey80
}
| 71673022ac1eaf17c0f6335c35773ee5 | 47.148148 | 109 | 0.740769 | false | false | false | false |
Ivacker/swift | refs/heads/master | validation-test/compiler_crashers_fixed/00875-getselftypeforcontainer.swift | apache-2.0 | 13 | // 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
protocol c {
class A {
if true {
func f: NSObject {
enum A {
}
if c = c(v: NSObject {
}
f = b: e == T) {
func compose<T: C {
}
typealias e = c() -> V {
func a(f: A: A {
}
var d where T>) -> {
let d<T : P {
}
let c: P {
}
protocol c = e, V>: Array) {
}
self] {
print() -> {
}
protocol P {
}
}
var b = {
protocol P {
}
}
enum S<T) {
return g<T>: A() {
}
deinit {
}
}
}
}
}
}
extension NSSet {
}
}
}
var e: e!.e == c: String = compose(false)
protocol P {
}
typealias e : e == ni
| 2b7044d1518d547566f2c62df1540bae | 11.563636 | 87 | 0.580318 | false | false | false | false |
ocrickard/Theodolite | refs/heads/master | Theodolite/UI/Text/TextKitLayer.swift | mit | 1 | //
// TextKitLayer.swift
// Theodolite
//
// Created by Oliver Rickard on 10/31/17.
// Copyright © 2017 Oliver Rickard. All rights reserved.
//
import UIKit
private class TextKitDrawParameters: NSObject {
let attributes: TextKitAttributes
init(attributes: TextKitAttributes) {
self.attributes = attributes
}
}
public final class TextKitLayer: TheodoliteAsyncLayer {
var attributes: TextKitAttributes? = nil {
didSet {
if attributes != oldValue {
self.setNeedsDisplay()
}
}
}
public override init() {
super.init()
#if DEBUG
if let _ = NSClassFromString("XCTest") {
// While tests are running, we need to ensure we display synchronously
self.displayMode = .alwaysSync
} else {
self.displayMode = .alwaysAsync
}
#else
self.displayMode = .alwaysAsync
#endif
}
public override var needsDisplayOnBoundsChange: Bool {
get {
return true
}
set {
// Don't allow this property to be disabled. Unfortunately, UIView will turn this off when setting the
// backgroundColor, for reasons that cannot be understood. Even worse, it doesn't ever set it back, so it will
// subsequently stay off. Just make sure that it never gets overridden, because the text will not be drawn in the
// correct way (or even at all) if this is set to NO.
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override init(layer: Any) {
super.init(layer: layer)
}
public override class func defaultValue(forKey key: String) -> Any? {
switch key {
case "contentsScale":
return NSNumber(value: Double(TextKitLayer.gScreenScale))
default:
return super.defaultValue(forKey: key)
}
}
public override func drawParameters() -> NSObject! {
guard let attributes = self.attributes else {
return NSObject()
}
return TextKitDrawParameters(attributes: attributes)
}
public override func draw(in ctx: CGContext) {
if self.isOpaque, let bgColor = self.backgroundColor {
ctx.saveGState()
let boundsRect = ctx.boundingBoxOfClipPath
ctx.setFillColor(bgColor)
ctx.fill(boundsRect)
ctx.restoreGState()
}
super.draw(in: ctx)
}
public override class func draw(in ctx: CGContext, parameters: NSObject) {
guard let params = parameters as? TextKitDrawParameters else {
return
}
let rect = ctx.boundingBoxOfClipPath
let renderer = TextKitRenderer.renderer(attributes: params.attributes,
constrainedSize: rect.size)
renderer.drawInContext(graphicsContext: ctx,
bounds: rect)
}
public override func didDisplayAsynchronously(_ newContents: Any?, withDrawParameters drawParameters: NSObjectProtocol) {
guard newContents != nil else {
return
}
let image = newContents as! CGImage
let bytes = image.bytesPerRow * image.height
TextKitLayer
.gTextKitRenderArtifactCache
.setObject(image,
forKey: TextKitRendererKey(
attributes: self.attributes!,
constrainedSize: self.bounds.size),
cost: bytes)
}
public override func willDisplayAsynchronously(withDrawParameters drawParameters: NSObjectProtocol) -> Any? {
let cached = TextKitLayer
.gTextKitRenderArtifactCache
.object(forKey: TextKitRendererKey(
attributes: self.attributes!,
constrainedSize: self.bounds.size))
return cached
}
static var gTextKitRenderArtifactCache: TextCache<TextKitRendererKey, AnyObject> = {
let cache = TextCache<TextKitRendererKey, AnyObject>()
cache.totalCostLimit = 6 * 1024 * 1024
return cache
}()
static var gScreenScale: CGFloat = UIScreen.main.scale
}
| 1a093fbfee5e3a6a75cffd2393b3f93f | 28.484848 | 123 | 0.668294 | false | false | false | false |
wireapp/wire-ios-sync-engine | refs/heads/develop | Source/Synchronization/Strategies/UserImageAssetUpdateStrategy.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireRequestStrategy
internal enum AssetTransportError: Error {
case invalidLength
case assetTooLarge
case other(Error?)
init(response: ZMTransportResponse) {
switch (response.httpStatus, response.payloadLabel()) {
case (400, .some("invalid-length")):
self = .invalidLength
case (413, .some("client-error")):
self = .assetTooLarge
default:
self = .other(response.transportSessionError)
}
}
}
public final class UserImageAssetUpdateStrategy: AbstractRequestStrategy, ZMContextChangeTrackerSource, ZMSingleRequestTranscoder, ZMDownstreamTranscoder {
internal let requestFactory = AssetRequestFactory()
internal var upstreamRequestSyncs = [ProfileImageSize: ZMSingleRequestSync]()
internal var deleteRequestSync: ZMSingleRequestSync?
internal var downstreamRequestSyncs = [ProfileImageSize: ZMDownstreamObjectSyncWithWhitelist]()
internal let moc: NSManagedObjectContext
internal weak var imageUploadStatus: UserProfileImageUploadStatusProtocol?
fileprivate var observers: [Any] = []
@objc public convenience init(managedObjectContext: NSManagedObjectContext,
applicationStatusDirectory: ApplicationStatusDirectory,
userProfileImageUpdateStatus: UserProfileImageUpdateStatus) {
self.init(managedObjectContext: managedObjectContext, applicationStatus: applicationStatusDirectory, imageUploadStatus: userProfileImageUpdateStatus)
}
internal init(managedObjectContext: NSManagedObjectContext, applicationStatus: ApplicationStatus, imageUploadStatus: UserProfileImageUploadStatusProtocol) {
self.moc = managedObjectContext
self.imageUploadStatus = imageUploadStatus
super.init(withManagedObjectContext: managedObjectContext, applicationStatus: applicationStatus)
downstreamRequestSyncs[.preview] = whitelistUserImageSync(for: .preview)
downstreamRequestSyncs[.complete] = whitelistUserImageSync(for: .complete)
downstreamRequestSyncs.forEach { (_, sync) in
sync.whiteListObject(ZMUser.selfUser(in: managedObjectContext))
}
upstreamRequestSyncs[.preview] = ZMSingleRequestSync(singleRequestTranscoder: self, groupQueue: moc)
upstreamRequestSyncs[.complete] = ZMSingleRequestSync(singleRequestTranscoder: self, groupQueue: moc)
deleteRequestSync = ZMSingleRequestSync(singleRequestTranscoder: self, groupQueue: moc)
observers.append(NotificationInContext.addObserver(
name: .userDidRequestCompleteAsset,
context: managedObjectContext.notificationContext,
using: { [weak self] in self?.requestAssetForNotification(note: $0) })
)
observers.append(NotificationInContext.addObserver(
name: .userDidRequestPreviewAsset,
context: managedObjectContext.notificationContext,
using: { [weak self] in self?.requestAssetForNotification(note: $0) })
)
}
fileprivate func whitelistUserImageSync(for size: ProfileImageSize) -> ZMDownstreamObjectSyncWithWhitelist {
let predicate: NSPredicate
switch size {
case .preview:
predicate = ZMUser.previewImageDownloadFilter
case .complete:
predicate = ZMUser.completeImageDownloadFilter
}
return ZMDownstreamObjectSyncWithWhitelist(transcoder: self,
entityName: ZMUser.entityName(),
predicateForObjectsToDownload: predicate,
managedObjectContext: moc)
}
internal func size(for requestSync: ZMDownstreamObjectSyncWithWhitelist) -> ProfileImageSize? {
for (size, sync) in downstreamRequestSyncs where sync === requestSync {
return size
}
return nil
}
internal func size(for requestSync: ZMSingleRequestSync) -> ProfileImageSize? {
for (size, sync) in upstreamRequestSyncs where sync === requestSync {
return size
}
return nil
}
func requestAssetForNotification(note: NotificationInContext) {
moc.performGroupedBlock {
guard let objectID = note.object as? NSManagedObjectID,
let object = self.moc.object(with: objectID) as? ZMManagedObject
else { return }
switch note.name {
case .userDidRequestPreviewAsset:
self.downstreamRequestSyncs[.preview]?.whiteListObject(object)
case .userDidRequestCompleteAsset:
self.downstreamRequestSyncs[.complete]?.whiteListObject(object)
default:
break
}
RequestAvailableNotification.notifyNewRequestsAvailable(nil)
}
}
public override func nextRequestIfAllowed(for apiVersion: APIVersion) -> ZMTransportRequest? {
for size in ProfileImageSize.allSizes {
let requestSync = downstreamRequestSyncs[size]
if let request = requestSync?.nextRequest(for: apiVersion) {
return request
}
}
guard let updateStatus = imageUploadStatus else { return nil }
// There are assets added for deletion
if updateStatus.hasAssetToDelete() {
deleteRequestSync?.readyForNextRequestIfNotBusy()
return deleteRequestSync?.nextRequest(for: apiVersion)
}
let sync = ProfileImageSize.allSizes.filter(updateStatus.hasImageToUpload).compactMap { upstreamRequestSyncs[$0] }.first
sync?.readyForNextRequestIfNotBusy()
return sync?.nextRequest(for: apiVersion)
}
// MARK: - ZMContextChangeTrackerSource
public var contextChangeTrackers: [ZMContextChangeTracker] {
return Array(downstreamRequestSyncs.values)
}
// MARK: - ZMDownstreamTranscoder
public func request(forFetching object: ZMManagedObject!, downstreamSync: ZMObjectSync!, apiVersion: APIVersion) -> ZMTransportRequest! {
guard let whitelistSync = downstreamSync as? ZMDownstreamObjectSyncWithWhitelist else { return nil }
guard let user = object as? ZMUser else { return nil }
guard let size = size(for: whitelistSync) else { return nil }
let remoteId: String?
switch size {
case .preview:
remoteId = user.previewProfileAssetIdentifier
case .complete:
remoteId = user.completeProfileAssetIdentifier
}
guard let assetId = remoteId else { return nil }
let path: String
switch apiVersion {
case .v0:
path = "/assets/v3/\(assetId)"
case .v1:
guard let domain = user.domain.nonEmptyValue ?? BackendInfo.domain else {
return nil
}
path = "/assets/v4/\(domain)/\(assetId)"
case .v2:
guard let domain = user.domain.nonEmptyValue ?? BackendInfo.domain else {
return nil
}
path = "/assets/\(domain)/\(assetId)"
}
return ZMTransportRequest.imageGet(fromPath: path, apiVersion: apiVersion.rawValue)
}
public func delete(_ object: ZMManagedObject!, with response: ZMTransportResponse!, downstreamSync: ZMObjectSync!) {
guard let whitelistSync = downstreamSync as? ZMDownstreamObjectSyncWithWhitelist else { return }
guard let user = object as? ZMUser else { return }
switch size(for: whitelistSync) {
case .preview?: user.previewProfileAssetIdentifier = nil
case .complete?: user.completeProfileAssetIdentifier = nil
default: break
}
}
public func update(_ object: ZMManagedObject!, with response: ZMTransportResponse!, downstreamSync: ZMObjectSync!) {
guard let whitelistSync = downstreamSync as? ZMDownstreamObjectSyncWithWhitelist else { return }
guard let user = object as? ZMUser else { return }
guard let size = size(for: whitelistSync) else { return }
user.setImage(data: response.rawData, size: size)
}
// MARK: - ZMSingleRequestTranscoder
public func request(for sync: ZMSingleRequestSync, apiVersion: APIVersion) -> ZMTransportRequest? {
if let size = size(for: sync), let image = imageUploadStatus?.consumeImage(for: size) {
let request = requestFactory.upstreamRequestForAsset(withData: image, shareable: true, retention: .eternal, apiVersion: apiVersion)
request?.addContentDebugInformation("Uploading to /assets/V3: [\(size)] [\(image)] ")
return request
} else if sync === deleteRequestSync {
if let assetId = imageUploadStatus?.consumeAssetToDelete() {
let path = "/assets/v3/\(assetId)"
return ZMTransportRequest(path: path, method: .methodDELETE, payload: nil, apiVersion: apiVersion.rawValue)
}
}
return nil
}
public func didReceive(_ response: ZMTransportResponse, forSingleRequest sync: ZMSingleRequestSync) {
guard let size = size(for: sync) else { return }
guard response.result == .success else {
let error = AssetTransportError(response: response)
imageUploadStatus?.uploadingFailed(imageSize: size, error: error)
return
}
guard let payload = response.payload?.asDictionary(), let assetId = payload["key"] as? String else { fatal("No asset ID present in payload") }
imageUploadStatus?.uploadingDone(imageSize: size, assetId: assetId)
}
}
| adeb27a966cf1127de28e7ad985c2332 | 42.195833 | 160 | 0.673483 | false | false | false | false |
fizx/jane | refs/heads/master | ruby/lib/vendor/grpc-swift/Examples/Google/Datastore/Sources/main.swift | mit | 3 | /*
* Copyright 2017, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Commander
import Dispatch
import Foundation
import SwiftGRPC
import OAuth2
// Convert Encodable objects to dictionaries of property-value pairs.
class PropertiesEncoder {
static func encode<T: Encodable>(_ value: T) throws -> [String: Any]? {
#if os(OSX)
let plist = try PropertyListEncoder().encode(value)
let properties = try PropertyListSerialization.propertyList(from: plist, options: [], format: nil)
#else
let data = try JSONEncoder().encode(value)
let properties = try JSONSerialization.jsonObject(with: data, options: [])
#endif
return properties as? [String: Any]
}
}
// Create Decodable objects from dictionaries of property-value pairs.
class PropertiesDecoder {
static func decode<T: Decodable>(_ type: T.Type, from: [String: Any]) throws -> T {
#if os(OSX)
let plist = try PropertyListSerialization.data(fromPropertyList: from, format: .binary, options: 0)
return try PropertyListDecoder().decode(type, from: plist)
#else
let data = try JSONSerialization.data(withJSONObject: from, options: [])
return try JSONDecoder().decode(type, from: data)
#endif
}
}
// a Swift interface to the Google Cloud Datastore API
class Datastore {
var projectID: String
var service: Google_Datastore_V1_DatastoreServiceClient!
let scopes = ["https://www.googleapis.com/auth/datastore"]
init(projectID: String) {
self.projectID = projectID
}
func authenticate() throws {
var authToken: String!
if let provider = DefaultTokenProvider(scopes: scopes) {
let sem = DispatchSemaphore(value: 0)
try provider.withToken { (token, _) -> Void in
if let token = token {
authToken = token.AccessToken
}
sem.signal()
}
sem.wait()
}
if authToken == nil {
print("ERROR: No OAuth token is available. Did you set GOOGLE_APPLICATION_CREDENTIALS?")
exit(-1)
}
// Initialize gRPC service
gRPC.initialize()
service = Google_Datastore_V1_DatastoreServiceClient(address: "datastore.googleapis.com")
service.metadata = Metadata(["authorization": "Bearer " + authToken])
}
func performList<T: Codable>(type: T.Type) throws -> [Int64: T] {
var request = Google_Datastore_V1_RunQueryRequest()
request.projectID = projectID
var query = Google_Datastore_V1_GqlQuery()
query.queryString = "select * from " + String(describing: type)
request.gqlQuery = query
let result = try service.runquery(request)
var entities: [Int64: T] = [:]
for entityResult in result.batch.entityResults {
var properties: [String: Any] = [:]
for property in entityResult.entity.properties {
let key = property.key
switch property.value.valueType! {
case .integerValue(let v):
properties[key] = v
case .stringValue(let v):
properties[key] = v
default:
print("?")
}
}
let entity = try PropertiesDecoder.decode(type, from: properties)
entities[entityResult.entity.key.path[0].id] = entity
}
return entities
}
func performInsert<T: Codable>(thing: T) throws {
var request = Google_Datastore_V1_CommitRequest()
request.projectID = projectID
request.mode = .nonTransactional
var pathElement = Google_Datastore_V1_Key.PathElement()
pathElement.kind = String(describing: type(of: thing))
var key = Google_Datastore_V1_Key()
key.path = [pathElement]
var entity = Google_Datastore_V1_Entity()
entity.key = key
let properties = try PropertiesEncoder.encode(thing)!
for (k, v) in properties {
var value = Google_Datastore_V1_Value()
switch v {
case let v as String:
value.stringValue = v
case let v as Int:
value.integerValue = Int64(v)
default:
break
}
entity.properties[k] = value
}
var mutation = Google_Datastore_V1_Mutation()
mutation.insert = entity
request.mutations.append(mutation)
let result = try service.commit(request)
for mutationResult in result.mutationResults {
print("\(mutationResult)")
}
}
func performDelete(kind: String,
id: Int64) throws {
var request = Google_Datastore_V1_CommitRequest()
request.projectID = projectID
request.mode = .nonTransactional
var pathElement = Google_Datastore_V1_Key.PathElement()
pathElement.kind = kind
pathElement.id = id
var key = Google_Datastore_V1_Key()
key.path = [pathElement]
var mutation = Google_Datastore_V1_Mutation()
mutation.delete = key
request.mutations.append(mutation)
let result = try service.commit(request)
for mutationResult in result.mutationResults {
print("\(mutationResult)")
}
}
}
let projectID = "your-project-identifier"
struct Thing: Codable {
var name: String
var number: Int
}
Group {
$0.command("insert") { (number: Int) in
let datastore = Datastore(projectID: projectID)
try datastore.authenticate()
let thing = Thing(name: "Thing", number: number)
try datastore.performInsert(thing: thing)
}
$0.command("delete") { (id: Int) in
let datastore = Datastore(projectID: projectID)
try datastore.authenticate()
try datastore.performDelete(kind: "Thing", id: Int64(id))
}
$0.command("list") {
let datastore = Datastore(projectID: projectID)
try datastore.authenticate()
let entities = try datastore.performList(type: Thing.self)
print("\(entities)")
}
}.run()
| a008e4b1bdfc95eb4a5123fee31fa835 | 31.603175 | 105 | 0.673483 | false | false | false | false |
Drusy/auvergne-webcams-ios | refs/heads/master | ActiveLabelDemo/ViewController.swift | apache-2.0 | 2 | //
// ViewController.swift
// ActiveLabelDemo
//
// Created by Johannes Schickling on 9/4/15.
// Copyright © 2015 Optonaut. All rights reserved.
//
import UIKit
import ActiveLabel
class ViewController: UIViewController {
let label = ActiveLabel()
override func viewDidLoad() {
super.viewDidLoad()
let customType = ActiveType.custom(pattern: "\\sare\\b") //Looks for "are"
let customType2 = ActiveType.custom(pattern: "\\sit\\b") //Looks for "it"
let customType3 = ActiveType.custom(pattern: "\\ssupports\\b") //Looks for "supports"
label.enabledTypes.append(customType)
label.enabledTypes.append(customType2)
label.enabledTypes.append(customType3)
label.urlMaximumLength = 31
label.customize { label in
label.text = "This is a post with #multiple #hashtags and a @userhandle. Links are also supported like" +
" this one: http://optonaut.co. Now it also supports custom patterns -> are\n\n" +
"Let's trim a long link: \nhttps://twitter.com/twicket_app/status/649678392372121601"
label.numberOfLines = 0
label.lineSpacing = 4
label.textColor = UIColor(red: 102.0/255, green: 117.0/255, blue: 127.0/255, alpha: 1)
label.hashtagColor = UIColor(red: 85.0/255, green: 172.0/255, blue: 238.0/255, alpha: 1)
label.mentionColor = UIColor(red: 238.0/255, green: 85.0/255, blue: 96.0/255, alpha: 1)
label.URLColor = UIColor(red: 85.0/255, green: 238.0/255, blue: 151.0/255, alpha: 1)
label.URLSelectedColor = UIColor(red: 82.0/255, green: 190.0/255, blue: 41.0/255, alpha: 1)
label.handleMentionTap { self.alert("Mention", message: $0) }
label.handleHashtagTap { self.alert("Hashtag", message: $0) }
label.handleURLTap { self.alert("URL", message: $0.absoluteString) }
//Custom types
label.customColor[customType] = UIColor.purple
label.customSelectedColor[customType] = UIColor.green
label.customColor[customType2] = UIColor.magenta
label.customSelectedColor[customType2] = UIColor.green
label.configureLinkAttribute = { (type, attributes, isSelected) in
var atts = attributes
switch type {
case customType3:
atts[NSAttributedString.Key.font] = isSelected ? UIFont.boldSystemFont(ofSize: 16) : UIFont.boldSystemFont(ofSize: 14)
default: ()
}
return atts
}
label.handleCustomTap(for: customType) { self.alert("Custom type", message: $0) }
label.handleCustomTap(for: customType2) { self.alert("Custom type", message: $0) }
label.handleCustomTap(for: customType3) { self.alert("Custom type", message: $0) }
}
label.frame = CGRect(x: 20, y: 40, width: view.frame.width - 40, height: 300)
view.addSubview(label)
// 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.
}
func alert(_ title: String, message: String) {
let vc = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
vc.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
present(vc, animated: true, completion: nil)
}
}
| 726e2bde836bd45a6ea4706a0d6bbffa | 40.25 | 138 | 0.614601 | false | false | false | false |
zhouxj6112/ARKit | refs/heads/master | ARHome/ARHome/Focus Square/Plane.swift | apache-2.0 | 1 | //
// Plane.swift
// ARCube
//
// Created by 张嘉夫 on 2017/7/10.
// Copyright © 2017年 张嘉夫. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
class Plane: SCNNode {
var anchor: ARPlaneAnchor!
var planeGeometry: SCNPlane!
init(withAnchor anchor: ARPlaneAnchor) {
super.init()
self.anchor = anchor
planeGeometry = SCNPlane(width: CGFloat(anchor.extent.x), height: CGFloat(anchor.extent.z))
// 相比把网格视觉化为灰色平面,我更喜欢用科幻风的颜色来渲染
let material = SCNMaterial()
let img = UIImage(named: "fabric")
material.diffuse.contents = img
material.lightingModel = .physicallyBased
planeGeometry.materials = [material]
let planeNode = SCNNode(geometry: planeGeometry)
planeNode.position = SCNVector3Make(anchor.center.x, 0, anchor.center.z)
// SceneKit 里的平面默认是垂直的,所以需要旋转90度来匹配 ARKit 中的平面
planeNode.transform = SCNMatrix4MakeRotation(Float(-.pi / 2.0), 1.0, 0.0, 0.0)
setTextureScale()
addChildNode(planeNode)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(anchor: ARPlaneAnchor) {
// 随着用户移动,平面 plane 的 范围 extend 和 位置 location 可能会更新。
// 需要更新 3D 几何体来匹配 plane 的新参数。
planeGeometry.width = CGFloat(anchor.extent.x);
planeGeometry.height = CGFloat(anchor.extent.z);
// plane 刚创建时中心点 center 为 0,0,0,node transform 包含了变换参数。
// plane 更新后变换没变但 center 更新了,所以需要更新 3D 几何体的位置
position = SCNVector3Make(anchor.center.x, 0, anchor.center.z)
setTextureScale()
}
func setTextureScale() {
let width = planeGeometry.width
let height = planeGeometry.height
// 平面的宽度/高度 width/height 更新时,我希望 tron grid material 覆盖整个平面,不断重复纹理。
// 但如果网格小于 1 个单位,我不希望纹理挤在一起,所以这种情况下通过缩放更新纹理坐标并裁剪纹理
let material = planeGeometry.materials.first
material?.diffuse.contentsTransform = SCNMatrix4MakeScale(Float(width), Float(height), 1)
material?.diffuse.wrapS = .repeat
material?.diffuse.wrapT = .repeat
}
}
| 1eeea9c6b9890c51b003545ceac777a6 | 31.397059 | 99 | 0.636859 | false | false | false | false |
fuzzymeme/TutorApp | refs/heads/master | Tutor/QandAView.swift | mit | 1 | //
// QandAView.swift
// Tutor
//
// Created by Fuzzymeme on 28/05/2017.
// Copyright © 2017 Fuzzymeme. All rights reserved.
//
import UIKit
class QandAView: UIView {
@IBOutlet weak var optionZeroButton: UIButton!
@IBOutlet weak var optionOneButton: UIButton!
@IBOutlet weak var optionTwoButton: UIButton!
@IBOutlet weak var optionThreeButton: UIButton!
@IBOutlet weak var skipNextButton: UIButton!
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var successLabel: UILabel!
lazy private var buttonToIndexMap: [UIButton: Int] = self.initializeButtonMap()
private var buttons = [UIButton]()
private var viewListener: ViewController?
@IBAction func optionButtonTouched(_ sender: UIButton) {
viewListener?.handleButtonTouchedEvent(buttonIndex: buttonToIndexMap[sender]!)
}
@IBAction func skipNextButtonTouched(_ sender: UIButton) {
viewListener?.handleSkipButtonTouchedEvent()
}
func initializeButtonMap() -> [UIButton: Int] {
return [optionZeroButton: 0, optionOneButton: 1, optionTwoButton: 2, optionThreeButton: 3]
}
func setDelegate(_ viewListener: ViewController) {
self.viewListener = viewListener
}
func setButtonStyleRounded() {
for button in buttonToIndexMap.keys {
button.layer.cornerRadius = 6
button.layer.borderWidth = 0
}
}
func setBackground(color newBackgroundColor: UIColor) {
self.backgroundColor = newBackgroundColor
}
func setButtonsBackground(color newBackgroundColor: UIColor) {
for button in buttonToIndexMap.keys {
button.backgroundColor = newBackgroundColor
}
}
func setSkipNextButtonBackground(color newBackgroundColor: UIColor) {
skipNextButton.backgroundColor = newBackgroundColor
}
func setSkipButtonStyleRounded() {
skipNextButton.layer.cornerRadius = 6
skipNextButton.layer.borderWidth = 0
}
func setSkipNextButtonText(newText: String) {
skipNextButton.setTitle(newText, for: .normal)
}
func setOption(atIndex optionNumber: Int, setTo newValue: String) {
let selectedButton = buttonWithIndex(optionNumber)
selectedButton?.setTitle(newValue, for: .normal)
}
func setAnswers(_ answers: [String]) {
var index = 0
for answer in answers {
setOption(atIndex: index, setTo: answer)
index += 1
}
}
var question: String {
get { return questionLabel.text ?? ""}
set { questionLabel.text = newValue}
}
var displaySuccess: Bool {
get{ return false}
set {
if newValue {
successLabel!.text = "Correct"
successLabel!.backgroundColor = UIColor.green
} else {
successLabel!.text = "Wrong"
successLabel!.backgroundColor = UIColor.red
}
}
}
private func buttonWithIndex(_ index: Int) -> UIButton? {
return buttonToIndexMap.keys.first(where: {[weak self] in self?.buttonToIndexMap[$0] == index})
}
}
protocol QandAViewListener {
func handleButtonTouchedEvent(buttonIndex: Int)
}
| 8168868186244c4453b05021cdf31abf | 28.936364 | 103 | 0.64379 | false | false | false | false |
cohena100/Shimi | refs/heads/master | Carthage/Checkouts/RxSwiftExt/Source/RxSwift/ObservableType+Weak.swift | apache-2.0 | 5 | //
// ObservableType+Weak.swift
// RxSwiftExtDemo
//
// Created by Ian Keen on 17/04/2016.
// Copyright © 2016 RxSwift Community. All rights reserved.
//
import Foundation
import RxSwift
extension ObservableType {
/**
Leverages instance method currying to provide a weak wrapper around an instance function
- parameter obj: The object that owns the function
- parameter method: The instance function represented as `InstanceType.instanceFunc`
*/
fileprivate func weakify<A: AnyObject, B>(_ obj: A, method: ((A) -> (B) -> Void)?) -> ((B) -> Void) {
return { [weak obj] value in
guard let obj = obj else { return }
method?(obj)(value)
}
}
/**
Subscribes an event handler to an observable sequence.
- parameter weak: Weakly referenced object containing the target function.
- parameter on: Function to invoke on `weak` for each event in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe<A: AnyObject>(weak obj: A, _ on: @escaping (A) -> (RxSwift.Event<Self.E>) -> Void) -> Disposable {
return self.subscribe(weakify(obj, method: on))
}
/**
Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence.
- parameter weak: Weakly referenced object containing the target function.
- parameter onNext: Function to invoke on `weak` for each element in the observable sequence.
- parameter onError: Function to invoke on `weak` upon errored termination of the observable sequence.
- parameter onCompleted: Function to invoke on `weak` upon graceful termination of the observable sequence.
- parameter onDisposed: Function to invoke on `weak` upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe<A: AnyObject>(
weak obj: A,
onNext: ((A) -> (Self.E) -> Void)? = nil,
onError: ((A) -> (Error) -> Void)? = nil,
onCompleted: ((A) -> () -> Void)? = nil,
onDisposed: ((A) -> () -> Void)? = nil) -> Disposable {
let disposable: Disposable
if let disposed = onDisposed {
disposable = Disposables.create(with: weakify(obj, method: disposed))
}
else {
disposable = Disposables.create()
}
let observer = AnyObserver { [weak obj] (e: RxSwift.Event<Self.E>) in
guard let obj = obj else { return }
switch e {
case .next(let value):
onNext?(obj)(value)
case .error(let e):
onError?(obj)(e)
disposable.dispose()
case .completed:
onCompleted?(obj)()
disposable.dispose()
}
}
return Disposables.create(self.asObservable().subscribe(observer), disposable)
}
/**
Subscribes an element handler to an observable sequence.
- parameter weak: Weakly referenced object containing the target function.
- parameter onNext: Function to invoke on `weak` for each element in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribeNext<A: AnyObject>(weak obj: A, _ onNext: @escaping (A) -> (Self.E) -> Void) -> Disposable {
return self.subscribe(onNext: weakify(obj, method: onNext))
}
/**
Subscribes an error handler to an observable sequence.
- parameter weak: Weakly referenced object containing the target function.
- parameter onError: Function to invoke on `weak` upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribeError<A: AnyObject>(weak obj: A, _ onError: @escaping (A) -> (Error) -> Void) -> Disposable {
return self.subscribe(onError: weakify(obj, method: onError))
}
/**
Subscribes a completion handler to an observable sequence.
- parameter weak: Weakly referenced object containing the target function.
- parameter onCompleted: Function to invoke on `weak` graceful termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribeCompleted<A: AnyObject>(weak obj: A, _ onCompleted: @escaping (A) -> () -> Void) -> Disposable {
return self.subscribe(onCompleted: weakify(obj, method: onCompleted))
}
}
| f60c755f821dac8d7896ee5444063a72 | 36.364407 | 121 | 0.710365 | false | false | false | false |
marselan/brooch | refs/heads/master | brooch/brooch/HttpClient.swift | gpl-3.0 | 1 | //
// HttpClient.swift
// brooch
//
// Created by Mariano Arselan on 2/19/18.
// Copyright © 2018 Mariano Arselan. All rights reserved.
//
import Foundation
class HttpClient {
func hit(url: String, callback: @escaping (Data?, URLResponse?, Error?) -> Void)
{
let requestURL = URL(string: url)
let request = URLRequest(url: requestURL!)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request, completionHandler: callback)
task.resume()
}
}
extension URLResponse {
func getStatus() -> Int?
{
if let httpResponse = self as? HTTPURLResponse, let status = httpResponse.statusCode as? Int {
return status
}
return nil
}
func getHeader(_ key: String) -> String? {
if let httpResponse = self as? HTTPURLResponse, let field = httpResponse.allHeaderFields[key] as? String {
return field
}
return nil
}
}
| 226da00451cc3ae4e7c350b590a2a2ed | 24.585366 | 114 | 0.618684 | false | true | false | false |
24/ios-o2o-c | refs/heads/master | gxc/OpenSource/PullRefresh/RefreshHeaderView.swift | mit | 1 | //
// RefreshHeaderView.swift
// RefreshExample
//
// Created by SunSet on 14-6-24.
// Copyright (c) 2014 zhaokaiyuan. All rights reserved.
//
import UIKit
class RefreshHeaderView: RefreshBaseView {
class func footer()->RefreshHeaderView{
var footer:RefreshHeaderView = RefreshHeaderView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, CGFloat(RefreshViewHeight)))
return footer
}
// 最后的更新时间
var lastUpdateTime:NSDate = NSDate(){
willSet{
}
didSet{
NSUserDefaults.standardUserDefaults().setObject(lastUpdateTime, forKey: RefreshHeaderTimeKey)
NSUserDefaults.standardUserDefaults().synchronize()
self.updateTimeLabel()
}
}
// 最后的更新时间lable
var lastUpdateTimeLabel:UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
lastUpdateTimeLabel = UILabel()
lastUpdateTimeLabel.autoresizingMask = UIViewAutoresizing.FlexibleWidth
lastUpdateTimeLabel.font = UIFont.boldSystemFontOfSize(12)
lastUpdateTimeLabel.textColor = RefreshLabelTextColor
lastUpdateTimeLabel.backgroundColor = UIColor.clearColor()
lastUpdateTimeLabel.textAlignment = NSTextAlignment.Center
self.addSubview(lastUpdateTimeLabel);
if (NSUserDefaults.standardUserDefaults().objectForKey(RefreshHeaderTimeKey) == nil) {
self.lastUpdateTime = NSDate()
} else {
self.lastUpdateTime = NSUserDefaults.standardUserDefaults().objectForKey(RefreshHeaderTimeKey) as NSDate
}
self.updateTimeLabel()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
var statusX:CGFloat = 0
var statusY:CGFloat = 0
var statusHeight:CGFloat = self.frame.size.height * 0.5
var statusWidth:CGFloat = self.frame.size.width
//状态标签
self.statusLabel.frame = CGRectMake(statusX, statusY, statusWidth, statusHeight)
//时间标签
var lastUpdateY:CGFloat = statusHeight
var lastUpdateX:CGFloat = 0
var lastUpdateHeight:CGFloat = statusHeight
var lastUpdateWidth:CGFloat = statusWidth
self.lastUpdateTimeLabel.frame = CGRectMake(lastUpdateX, lastUpdateY, lastUpdateWidth, lastUpdateHeight);
}
override func willMoveToSuperview(newSuperview: UIView!) {
super.willMoveToSuperview(newSuperview)
// 设置自己的位置和尺寸
var rect:CGRect = self.frame
rect.origin.y = -self.frame.size.height
self.frame = rect
}
func updateTimeLabel(){
//更新时间字符串
var calendar:NSCalendar = NSCalendar.currentCalendar()
var unitFlags:NSCalendarUnit = NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit | NSCalendarUnit.HourCalendarUnit | NSCalendarUnit.MinuteCalendarUnit
var cmp1:NSDateComponents = calendar.components(unitFlags, fromDate:lastUpdateTime)
var cmp2:NSDateComponents = calendar.components(unitFlags, fromDate: NSDate())
var formatter:NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm"
var time:String = formatter.stringFromDate(self.lastUpdateTime)
self.lastUpdateTimeLabel.text = " "
}
//监听UIScrollView的contentOffset属性
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) {
if (!self.userInteractionEnabled || self.hidden){
return
}
if (self.State == RefreshState.Refreshing) {
return
}
if RefreshContentOffset.isEqualToString(keyPath){
self.adjustStateWithContentOffset()
}
}
//调整状态
func adjustStateWithContentOffset()
{
var currentOffsetY:CGFloat = self.scrollView.contentOffset.y
var happenOffsetY:CGFloat = -self.scrollViewOriginalInset.top
if (currentOffsetY >= happenOffsetY) {
return
}
if self.scrollView.dragging{
var normal2pullingOffsetY:CGFloat = happenOffsetY - self.frame.size.height
if self.State == RefreshState.Normal && currentOffsetY < normal2pullingOffsetY{
self.State = RefreshState.Pulling
}else if self.State == RefreshState.Pulling && currentOffsetY >= normal2pullingOffsetY{
self.State = RefreshState.Normal
}
} else if self.State == RefreshState.Pulling {
self.State = RefreshState.Refreshing
}
}
//设置状态
override var State:RefreshState {
willSet {
if State == newValue{
return;
}
oldState = State
setState(newValue)
}
didSet{
switch State{
case .Normal:
self.statusLabel.text = RefreshHeaderPullToRefresh
if RefreshState.Refreshing == oldState {
self.arrowImage.transform = CGAffineTransformIdentity
self.lastUpdateTime = NSDate()
UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: {
var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.top = self.scrollViewOriginalInset.top
self.scrollView.contentInset = contentInset
})
}else {
UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: {
self.arrowImage.transform = CGAffineTransformIdentity
})
}
break
case .Pulling:
self.statusLabel.text = RefreshHeaderReleaseToRefresh
UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: {
self.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI ))
})
break
case .Refreshing:
self.statusLabel.text = RefreshHeaderRefreshing;
UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: {
var top:CGFloat = self.scrollViewOriginalInset.top + self.frame.size.height
var inset:UIEdgeInsets = self.scrollView.contentInset
inset.top = top
self.scrollView.contentInset = inset
var offset:CGPoint = self.scrollView.contentOffset
offset.y = -top
self.scrollView.contentOffset = offset
})
break
default:
break
}
}
}
func addState(state:RefreshState){
self.State = state
}
}
| 71b380e40691adf222234217ee4cedba | 35.967914 | 209 | 0.632234 | false | false | false | false |
LeeMZC/MZCWB | refs/heads/master | MZCWB/MZCWB/Classes/login- 登录相关/Controller/MZCWelcomeViewController.swift | artistic-2.0 | 1 | //
// MZCWelcomeViewController.swift
// MZCWB
//
// Created by 马纵驰 on 16/7/27.
// Copyright © 2016年 马纵驰. All rights reserved.
//
import UIKit
import YYKit
import QorumLogs
class MZCWelcomeViewController: UIViewController {
@IBOutlet weak var userIcon_imgView: UIImageView!
@IBOutlet weak var welcome_label: UILabel!
@IBOutlet weak var iconButtom_layout: NSLayoutConstraint!
// 圆角数值
let userIconRadius = 10 as CGFloat
override func viewDidLoad() {
QL1("")
super.viewDidLoad()
setupUI()
}
func setupUI(){
guard let accountTokenMode = MZCAccountTokenMode.accountToKen() else {
return
}
let iconUrlString = accountTokenMode.user?.avatar_large
let iconUrl = NSURL(string: iconUrlString!)
userIcon_imgView.setImageWithURL(iconUrl!, placeholderImage: UIImage.init(named: "avatar_default_big"))
//设置圆角
userIcon_imgView.layer.cornerRadius = userIconRadius
userIcon_imgView.clipsToBounds = true
welcome_label.alpha = 0
let iconOffset = view.bounds.size.height - iconButtom_layout.constant
UIView.animateWithDuration(MZCWelcomeAniTimer, animations: {
//开始动画
self.iconButtom_layout.constant = iconOffset
self.view.layoutIfNeeded()
}) { (true) in
UIView.animateWithDuration(MZCWelcomeAniTimer, animations: {
self.welcome_label.alpha = 1
}, completion: { (_) in
//通知更换UIWindow
NSNotificationCenter.defaultCenter().postNotificationName(MZCMainViewControllerWillChange, object: nil)
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| cf51db3a52ac8e861c44c07b5ad65c34 | 27.939394 | 123 | 0.623037 | false | false | false | false |
mourodrigo/a-simple-reddit-client | refs/heads/master | a-simple-reddit-client/a-simple-reddit-client/Extensions/String+Extension.swift | mit | 1 | //
// Notification+Extension.swift
// a-simple-reddit-client
//
// Created by Rodrigo Bueno Tomiosso on 07/02/17.
// Copyright © 2017 mourodrigo. All rights reserved.
//
import Foundation
import UIKit
extension String {
var componentsFromQueryString: [String : String] {
var components = [String: String]()
for qs in self.components(separatedBy: "&") {
let key = qs.components(separatedBy: "=")[0]
var value = qs.components(separatedBy: "=")[1]
value = value.replacingOccurrences(of: "+", with: " ")
value = value.removingPercentEncoding!
components[key] = value
}
return components
}
var isURL: Bool {
// create NSURL instance
if let url = NSURL(string: self) {
// check if your application can open the NSURL instance
return UIApplication.shared.canOpenURL(url as URL)
}
return false
}
}
| dd725c2d6aade31698f67c272e190df5 | 24.44186 | 70 | 0.52925 | false | false | false | false |
296245482/ILab-iOS | refs/heads/master | Charts-master/Charts/Classes/Data/Implementations/Standard/BubbleChartDataSet.swift | apache-2.0 | 15 | //
// BubbleChartDataSet.swift
// Charts
//
// Bubble chart implementation:
// Copyright 2015 Pierre-Marc Airoldi
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
public class BubbleChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBubbleChartDataSet
{
// MARK: - Data functions and accessors
internal var _xMax = Double(0.0)
internal var _xMin = Double(0.0)
internal var _maxSize = CGFloat(0.0)
public var xMin: Double { return _xMin }
public var xMax: Double { return _xMax }
public var maxSize: CGFloat { return _maxSize }
public var normalizeSizeEnabled: Bool = true
public var isNormalizeSizeEnabled: Bool { return normalizeSizeEnabled }
public override func calcMinMax(start start: Int, end: Int)
{
let yValCount = self.entryCount
if yValCount == 0
{
return
}
let entries = yVals as! [BubbleChartDataEntry]
// need chart width to guess this properly
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = end
_yMin = yMin(entries[start])
_yMax = yMax(entries[start])
for i in start.stride(through: endValue, by: 1)
{
let entry = entries[i]
let ymin = yMin(entry)
let ymax = yMax(entry)
if (ymin < _yMin)
{
_yMin = ymin
}
if (ymax > _yMax)
{
_yMax = ymax
}
let xmin = xMin(entry)
let xmax = xMax(entry)
if (xmin < _xMin)
{
_xMin = xmin
}
if (xmax > _xMax)
{
_xMax = xmax
}
let size = largestSize(entry)
if (size > _maxSize)
{
_maxSize = size
}
}
}
private func yMin(entry: BubbleChartDataEntry) -> Double
{
return entry.value
}
private func yMax(entry: BubbleChartDataEntry) -> Double
{
return entry.value
}
private func xMin(entry: BubbleChartDataEntry) -> Double
{
return Double(entry.xIndex)
}
private func xMax(entry: BubbleChartDataEntry) -> Double
{
return Double(entry.xIndex)
}
private func largestSize(entry: BubbleChartDataEntry) -> CGFloat
{
return entry.size
}
// MARK: - Styling functions and accessors
/// Sets/gets the width of the circle that surrounds the bubble when highlighted
public var highlightCircleWidth: CGFloat = 2.5
// MARK: - NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! BubbleChartDataSet
copy._xMin = _xMin
copy._xMax = _xMax
copy._maxSize = _maxSize
copy.highlightCircleWidth = highlightCircleWidth
return copy
}
}
| 65339e7af3f17a5e68c57cc2db6e2682 | 22.928571 | 92 | 0.522985 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | refs/heads/master | Foundation/NSCoder.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
extension NSCoder {
/*!
Describes the action an NSCoder should take when it encounters decode failures (e.g. corrupt data) for non-TopLevel decodes. Darwin platfrom supports exceptions here, and there may be other approaches supported in the future, so its included for completeness.
*/
public enum DecodingFailurePolicy : Int {
case setErrorAndReturn
}
}
public protocol NSCoding {
func encode(with aCoder: NSCoder)
init?(coder aDecoder: NSCoder)
}
public protocol NSSecureCoding : NSCoding {
static var supportsSecureCoding: Bool { get }
}
open class NSCoder : NSObject {
internal var _pendingBuffers = Array<(UnsafeMutableRawPointer, Int)>()
deinit {
for buffer in _pendingBuffers {
// Cannot deinitialize a pointer to unknown type.
buffer.0.deallocate(bytes: buffer.1, alignedTo: MemoryLayout<Int>.alignment)
}
}
open func encodeValue(ofObjCType type: UnsafePointer<Int8>, at addr: UnsafeRawPointer) {
NSRequiresConcreteImplementation()
}
open func encode(_ data: Data) {
NSRequiresConcreteImplementation()
}
open func decodeValue(ofObjCType type: UnsafePointer<Int8>, at data: UnsafeMutableRawPointer) {
NSRequiresConcreteImplementation()
}
open func decodeData() -> Data? {
NSRequiresConcreteImplementation()
}
open func version(forClassName className: String) -> Int {
NSRequiresConcreteImplementation()
}
open func decodeObject<DecodedObjectType: NSCoding>(of cls: DecodedObjectType.Type, forKey key: String) -> DecodedObjectType? where DecodedObjectType: NSObject {
NSUnimplemented()
}
/*!
@method decodeObjectOfClasses:forKey:
@abstract Decodes an object for the key, restricted to the specified classes.
@param classes An array of the expected classes.
@param key The code key.
@return The decoded object.
@discussion This function signature differs from Foundation OS X in that
classes is an array of Classes, not a NSSet. This is because AnyClass cannot
be casted to NSObject, nor is it Hashable.
*/
open func decodeObject(of classes: [AnyClass]?, forKey key: String) -> Any? {
NSUnimplemented()
}
open func decodeTopLevelObject() throws -> Any? {
NSUnimplemented()
}
open func decodeTopLevelObject(forKey key: String) throws -> Any? {
NSUnimplemented()
}
open func decodeTopLevelObject<DecodedObjectType: NSCoding>(of cls: DecodedObjectType.Type, forKey key: String) throws -> DecodedObjectType? where DecodedObjectType: NSObject {
NSUnimplemented()
}
/*!
@method decodeTopLevelObjectOfClasses:
@abstract Decodes an top-level object for the key, restricted to the specified classes.
@param classes An array of the expected classes.
@param key The code key.
@return The decoded object.
@discussion This function signature differs from Foundation OS X in that
classes is an array of Classes, not a NSSet. This is because AnyClass cannot
be casted to NSObject, nor is it Hashable.
*/
open func decodeTopLevelObject(of classes: [AnyClass], forKey key: String) throws -> Any? {
NSUnimplemented()
}
open func encode(_ object: Any?) {
var object = object
withUnsafePointer(to: &object) { (ptr: UnsafePointer<Any?>) -> Void in
encodeValue(ofObjCType: "@", at: unsafeBitCast(ptr, to: UnsafeRawPointer.self))
}
}
open func encodeRootObject(_ rootObject: Any) {
encode(rootObject)
}
open func encodeBycopyObject(_ anObject: Any?) {
encode(anObject)
}
open func encodeByrefObject(_ anObject: Any?) {
encode(anObject)
}
open func encodeConditionalObject(_ object: Any?) {
encode(object)
}
open func encodeArray(ofObjCType type: UnsafePointer<Int8>, count: Int, at array: UnsafeRawPointer) {
encodeValue(ofObjCType: "[\(count)\(String(cString: type))]", at: array)
}
open func encodeBytes(_ byteaddr: UnsafeRawPointer?, length: Int) {
var newLength = UInt32(length)
withUnsafePointer(to: &newLength) { (ptr: UnsafePointer<UInt32>) -> Void in
encodeValue(ofObjCType: "I", at: ptr)
}
var empty: [Int8] = []
withUnsafePointer(to: &empty) {
encodeArray(ofObjCType: "c", count: length, at: byteaddr ?? UnsafeRawPointer($0))
}
}
open func decodeObject() -> Any? {
if self.error != nil {
return nil
}
var obj: Any? = nil
withUnsafeMutablePointer(to: &obj) { (ptr: UnsafeMutablePointer<Any?>) -> Void in
decodeValue(ofObjCType: "@", at: unsafeBitCast(ptr, to: UnsafeMutableRawPointer.self))
}
return obj
}
open func decodeArray(ofObjCType itemType: UnsafePointer<Int8>, count: Int, at array: UnsafeMutableRawPointer) {
decodeValue(ofObjCType: "[\(count)\(String(cString: itemType))]", at: array)
}
/*
// TODO: This is disabled, as functions which return unsafe interior pointers are inherently unsafe when we have no autorelease pool.
open func decodeBytes(withReturnedLength lengthp: UnsafeMutablePointer<Int>) -> UnsafeMutableRawPointer? {
var length: UInt32 = 0
withUnsafeMutablePointer(to: &length) { (ptr: UnsafeMutablePointer<UInt32>) -> Void in
decodeValue(ofObjCType: "I", at: unsafeBitCast(ptr, to: UnsafeMutableRawPointer.self))
}
// we cannot autorelease here so instead the pending buffers will manage the lifespan of the returned data... this is wasteful but good enough...
let result = UnsafeMutableRawPointer.allocate(bytes: Int(length), alignedTo: MemoryLayout<Int>.alignment)
decodeValue(ofObjCType: "c", at: result)
lengthp.pointee = Int(length)
_pendingBuffers.append((result, Int(length)))
return result
}
*/
open func encodePropertyList(_ aPropertyList: Any) {
NSUnimplemented()
}
open func decodePropertyList() -> Any? {
NSUnimplemented()
}
open var systemVersion: UInt32 {
return 1000
}
open var allowsKeyedCoding: Bool {
return false
}
open func encode(_ objv: Any?, forKey key: String) {
NSRequiresConcreteImplementation()
}
open func encodeConditionalObject(_ objv: Any?, forKey key: String) {
NSRequiresConcreteImplementation()
}
open func encode(_ boolv: Bool, forKey key: String) {
NSRequiresConcreteImplementation()
}
open func encode(_ intv: Int32, forKey key: String) {
NSRequiresConcreteImplementation()
}
open func encode(_ intv: Int64, forKey key: String) {
NSRequiresConcreteImplementation()
}
open func encode(_ realv: Float, forKey key: String) {
NSRequiresConcreteImplementation()
}
open func encode(_ realv: Double, forKey key: String) {
NSRequiresConcreteImplementation()
}
open func encodeBytes(_ bytesp: UnsafePointer<UInt8>?, length lenv: Int, forKey key: String) {
NSRequiresConcreteImplementation()
}
open func containsValue(forKey key: String) -> Bool {
NSRequiresConcreteImplementation()
}
open func decodeObject(forKey key: String) -> Any? {
NSRequiresConcreteImplementation()
}
open func decodeBool(forKey key: String) -> Bool {
NSRequiresConcreteImplementation()
}
// NOTE: this equivalent to the decodeIntForKey: in Objective-C implementation
open func decodeCInt(forKey key: String) -> Int32 {
NSRequiresConcreteImplementation()
}
open func decodeInt32(forKey key: String) -> Int32 {
NSRequiresConcreteImplementation()
}
open func decodeInt64(forKey key: String) -> Int64 {
NSRequiresConcreteImplementation()
}
open func decodeFloat(forKey key: String) -> Float {
NSRequiresConcreteImplementation()
}
open func decodeDouble(forKey key: String) -> Double {
NSRequiresConcreteImplementation()
}
// TODO: This is disabled, as functions which return unsafe interior pointers are inherently unsafe when we have no autorelease pool.
/*
open func decodeBytes(forKey key: String, returnedLength lengthp: UnsafeMutablePointer<Int>?) -> UnsafePointer<UInt8>? { // returned bytes immutable!
NSRequiresConcreteImplementation()
}
*/
/// - experimental: This method does not exist in the Darwin Foundation.
open func withDecodedUnsafeBufferPointer<ResultType>(forKey key: String, body: (UnsafeBufferPointer<UInt8>?) throws -> ResultType) rethrows -> ResultType {
NSRequiresConcreteImplementation()
}
open func encode(_ intv: Int, forKey key: String) {
NSRequiresConcreteImplementation()
}
open func decodeInteger(forKey key: String) -> Int {
NSRequiresConcreteImplementation()
}
open var requiresSecureCoding: Bool {
return false
}
open func decodePropertyListForKey(_ key: String) -> Any? {
NSUnimplemented()
}
/*!
@property allowedClasses
@abstract The set of coded classes allowed for secure coding. (read-only)
@discussion This property type differs from Foundation OS X in that
classes is an array of Classes, not a Set. This is because AnyClass is not
hashable.
*/
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
open var allowedClasses: [AnyClass]? {
NSUnimplemented()
}
open func failWithError(_ error: Error) {
NSUnimplemented()
// NOTE: disabled for now due to bridging uncertainty
// if let debugDescription = error.userInfo["NSDebugDescription"] {
// NSLog("*** NSKeyedUnarchiver.init: \(debugDescription)")
// } else {
// NSLog("*** NSKeyedUnarchiver.init: decoding error")
// }
}
open var decodingFailurePolicy: NSCoder.DecodingFailurePolicy {
return .setErrorAndReturn
}
open var error: Error? {
NSRequiresConcreteImplementation()
}
internal func _decodeArrayOfObjectsForKey(_ key: String) -> [Any] {
NSRequiresConcreteImplementation()
}
internal func _decodePropertyListForKey(_ key: String) -> Any {
NSRequiresConcreteImplementation()
}
}
| 0d18a653727455ae514fd18d86d7f767 | 33.86478 | 264 | 0.655001 | false | false | false | false |
CodaFi/swift | refs/heads/master | test/IDE/complete_subscript.swift | apache-2.0 | 7 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_UNRESOLVED | %FileCheck %s -check-prefix=METATYPE_UNRESOLVED
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_UNRESOLVED_BRACKET | %FileCheck %s -check-prefix=METATYPE_UNRESOLVED_BRACKET
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_INT | %FileCheck %s -check-prefix=METATYPE_INT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_INT_BRACKET | %FileCheck %s -check-prefix=METATYPE_INT_BRACKET
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSTANCE_INT | %FileCheck %s -check-prefix=INSTANCE_INT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSTANCE_INT_BRACKET | %FileCheck %s -check-prefix=INSTANCE_INT_BRACKET
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_ARCHETYPE | %FileCheck %s -check-prefix=METATYPE_ARCHETYPE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_ARCHETYPE_BRACKET | %FileCheck %s -check-prefix=METATYPE_ARCHETYPE_BRACKET
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSTANCE_ARCHETYPE | %FileCheck %s -check-prefix=INSTANCE_ARCHETYPE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSTANCE_ARCHETYPE_BRACKET | %FileCheck %s -check-prefix=INSTANCE_ARCHETYPE_BRACKET
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_LABEL | %FileCheck %s -check-prefix=METATYPE_LABEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSTANCE_LABEL | %FileCheck %s -check-prefix=INSTANCE_LABEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SELF_IN_INSTANCEMETHOD | %FileCheck %s -check-prefix=SELF_IN_INSTANCEMETHOD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUPER_IN_INSTANCEMETHOD | %FileCheck %s -check-prefix=SUPER_IN_INSTANCEMETHOD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SELF_IN_STATICMETHOD | %FileCheck %s -check-prefix=SELF_IN_STATICMETHOD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUPER_IN_STATICMETHOD | %FileCheck %s -check-prefix=SUPER_IN_STATICMETHOD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=LABELED_SUBSCRIPT | %FileCheck %s -check-prefix=LABELED_SUBSCRIPT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TUPLE | %FileCheck %s -check-prefix=TUPLE
struct MyStruct<T> {
static subscript(x: Int, static defValue: T) -> MyStruct<T> {
fatalError()
}
subscript(x: Int, instance defValue: T) -> Int {
fatalError()
}
}
func test1() {
let _ = MyStruct #^METATYPE_UNRESOLVED^#
// METATYPE_UNRESOLVED: Begin completions, 4 items
// METATYPE_UNRESOLVED-DAG: Decl[Subscript]/CurrNominal: [{#(x): Int#}, {#static: _#}][#MyStruct<_>#];
// METATYPE_UNRESOLVED-DAG: Decl[Constructor]/CurrNominal: ()[#MyStruct<_>#];
// METATYPE_UNRESOLVED-DAG: Keyword[self]/CurrNominal: .self[#MyStruct<_>.Type#];
// METATYPE_UNRESOLVED-DAG: Keyword/CurrNominal: .Type[#MyStruct<_>.Type#];
// METATYPE_UNRESOLVED: End completions
let _ = MyStruct[#^METATYPE_UNRESOLVED_BRACKET^#
// METATYPE_UNRESOLVED_BRACKET: Begin completions
// METATYPE_UNRESOLVED_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#static: _#}[']'][#MyStruct<_>#];
// METATYPE_UNRESOLVED_BRACKET: End completions
let _ = MyStruct<Int> #^METATYPE_INT^#
// METATYPE_INT: Begin completions, 4 items
// METATYPE_INT-DAG: Decl[Subscript]/CurrNominal: [{#(x): Int#}, {#static: Int#}][#MyStruct<Int>#];
// METATYPE_INT-DAG: Decl[Constructor]/CurrNominal: ()[#MyStruct<Int>#];
// METATYPE_INT-DAG: Keyword[self]/CurrNominal: .self[#MyStruct<Int>.Type#];
// METATYPE_INT-DAG: Keyword/CurrNominal: .Type[#MyStruct<Int>.Type#];
// METATYPE_INT: End completions
let _ = MyStruct<Int>[#^METATYPE_INT_BRACKET^#
// METATYPE_INT_BRACKET: Begin completions
// METATYPE_INT_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#static: Int#}[']'][#MyStruct<Int>#];
// METATYPE_INT_BRACKET: End completions
let _ = MyStruct<Int>()#^INSTANCE_INT^#
// INSTANCE_INT: Begin completions, 2 items
// INSTANCE_INT-DAG: Decl[Subscript]/CurrNominal: [{#(x): Int#}, {#instance: Int#}][#Int#];
// INSTANCE_INT-DAG: Keyword[self]/CurrNominal: .self[#MyStruct<Int>#];
// INSTANCE_INT: End completions
let _ = MyStruct<Int>()[#^INSTANCE_INT_BRACKET^#
// INSTANCE_INT_BRACKET: Begin completions
// INSTANCE_INT_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#instance: Int#}[']'][#Int#];
// INSTANCE_INT_BRACKET-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<MyStruct<Int>, Value>#}[']'][#Value#];
// INSTANCE_INT_BRACKET: End completions
}
func test2<U>(value: MyStruct<U>) {
let _ = MyStruct<U>#^METATYPE_ARCHETYPE^#
// METATYPE_ARCHETYPE: Begin completions, 4 items
// METATYPE_ARCHETYPE-DAG: Decl[Subscript]/CurrNominal: [{#(x): Int#}, {#static: U#}][#MyStruct<U>#];
// METATYPE_ARCHETYPE-DAG: Decl[Constructor]/CurrNominal: ()[#MyStruct<U>#];
// METATYPE_ARCHETYPE-DAG: Keyword[self]/CurrNominal: .self[#MyStruct<U>.Type#];
// METATYPE_ARCHETYPE-DAG: Keyword/CurrNominal: .Type[#MyStruct<U>.Type#];
// METATYPE_ARCHETYPE: End completions
let _ = MyStruct<U>[#^METATYPE_ARCHETYPE_BRACKET^#
// METATYPE_ARCHETYPE_BRACKET: Begin completions
// METATYPE_ARCHETYPE_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#static: U#}[']'][#MyStruct<U>#];
// METATYPE_ARCHETYPE_BRACKET: End completions
let _ = value #^INSTANCE_ARCHETYPE^#
// INSTANCE_ARCHETYPE: Begin completions, 2 items
// INSTANCE_ARCHETYPE-DAG: Decl[Subscript]/CurrNominal: [{#(x): Int#}, {#instance: U#}][#Int#];
// INSTANCE_ARCHETYPE-DAG: Keyword[self]/CurrNominal: .self[#MyStruct<U>#];
// INSTANCE_ARCHETYPE: End completions
let _ = value[#^INSTANCE_ARCHETYPE_BRACKET^#
// INSTANCE_ARCHETYPE_BRACKET: Begin completions
// INSTANCE_ARCHETYPE_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#instance: U#}[']'][#Int#];
// INSTANCE_ARCHETYPE_BRACKET-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<MyStruct<U>, Value>#}[']'][#Value#];
// INSTANCE_ARCHETYPE_BRACKET: End completions
let _ = MyStruct<U>[42, #^METATYPE_LABEL^#
// METATYPE_LABEL: Begin completions, 1 items
// METATYPE_LABEL-DAG: Pattern/ExprSpecific: {#static: U#}[#U#];
// METATYPE_LABEL: End completions
let _ = value[42, #^INSTANCE_LABEL^#
// INSTANCE_LABEL: Begin completions, 1 items
// INSTANCE_LABEL-DAG: Pattern/ExprSpecific: {#instance: U#}[#U#];
// INSTANCE_LABEL: End completions
}
class Base {
static subscript(static x: Int) -> Int { return 1 }
subscript(instance x: Int) -> Int { return 1 }
}
class Derived: Base {
static subscript(derivedStatic x: Int) -> Int { return 1 }
subscript(derivedInstance x: Int) -> Int { return 1 }
func testInstance() {
let _ = self[#^SELF_IN_INSTANCEMETHOD^#]
// SELF_IN_INSTANCEMETHOD: Begin completions, 3 items
// SELF_IN_INSTANCEMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#derivedInstance: Int#}[']'][#Int#];
// SELF_IN_INSTANCEMETHOD-DAG: Decl[Subscript]/Super: ['[']{#instance: Int#}[']'][#Int#];
// SELF_IN_INSTANCEMETHOD-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<Derived, Value>#}[']'][#Value#];
// SELF_IN_INSTANCEMETHOD: End completions
let _ = super[#^SUPER_IN_INSTANCEMETHOD^#]
// SUPER_IN_INSTANCEMETHOD: Begin completions, 2 items
// SUPER_IN_INSTANCEMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#instance: Int#}[']'][#Int#];
// SUPER_IN_INSTANCEMETHOD-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<Base, Value>#}[']'][#Value#];
// SUPER_IN_INSTANCEMETHOD: End completions
}
static func testStatic() {
let _ = self[#^SELF_IN_STATICMETHOD^#]
// SELF_IN_STATICMETHOD: Begin completions, 2 items
// SELF_IN_STATICMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#derivedStatic: Int#}[']'][#Int#];
// SELF_IN_STATICMETHOD-DAG: Decl[Subscript]/Super: ['[']{#static: Int#}[']'][#Int#];
// SELF_IN_STATICMETHOD: End completions
let _ = super[#^SUPER_IN_STATICMETHOD^#]
// SUPER_IN_STATICMETHOD: Begin completions, 1 items
// SUPER_IN_STATICMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#static: Int#}[']'][#Int#];
// SUPER_IN_STATICMETHOD: End completions
}
}
struct MyStruct1<X: Comparable> {
subscript(idx1 _: Int, idx2 _: X) -> Int! { return 1 }
}
func testSubscriptCallSig<T>(val: MyStruct1<T>) {
val[#^LABELED_SUBSCRIPT^#
// LABELED_SUBSCRIPT: Begin completions, 2 items
// LABELED_SUBSCRIPT-DAG: Decl[Subscript]/CurrNominal: ['[']{#idx1: Int#}, {#idx2: Comparable#}[']'][#Int!#];
// LABELED_SUBSCRIPT-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<MyStruct1<T>, Value>#}[']'][#Value#];
// LABELED_SUBSCRIPT: End completions
}
func testSubcscriptTuple(val: (x: Int, String)) {
val[#^TUPLE^#]
// TUPLE: Begin completions, 1 items
// TUPLE-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<(x: Int, String), Value>#}[']'][#Value#];
// TUPLE: End completions
}
| bcc0f869ae13364c6f174bb353f595d8 | 59.628931 | 176 | 0.686307 | false | true | false | false |
Eonil/Editor | refs/heads/develop | Editor4/TemporalLazyCollection.swift | mit | 1 | //
// TemporalLazyCollection.swift
// Editor4
//
// Created by Hoon H. on 2016/05/26.
// Copyright © 2016 Eonil. All rights reserved.
//
/// A collection that is valid only at specific time range. For optimization.
///
/// This GUARANTEES the content of the collection is immutable and won't be
/// changed later. Anyway, you can access elements only while
/// `version == accessibleVersion`.
///
struct TemporalLazyCollection<Element>: CollectionType {
typealias Index = AnyRandomAccessIndex
// typealias SubSequence =
private(set) var version: Version
private var controller: TemporalLazyCollectionController<Element>?
var accessibleVersion: Version {
get { return controller?.version ?? version }
}
/// Initializes an empty sequence.
init() {
self.version = emptySequenceVersion
self.controller = nil
}
init<C: CollectionType where C.Generator.Element == Element, C.Index: RandomAccessIndexType>(_ elements: C) {
let c = TemporalLazyCollectionController<Element>()
c.source = AnyRandomAccessCollection<Element>(elements)
self.init(controller: c)
}
private init(controller: TemporalLazyCollectionController<Element>) {
self.version = controller.version
self.controller = controller
}
var isEmpty: Bool {
get { return getSource().isEmpty }
}
func generate() -> AnyGenerator<Element> {
return getSource().generate()
}
var startIndex: AnyRandomAccessIndex {
get { return getSource().startIndex }
}
var endIndex: AnyRandomAccessIndex {
get { return getSource().endIndex ?? AnyRandomAccessIndex(0) }
}
subscript(position: AnyRandomAccessIndex) -> Element {
get { return getSource()[position] }
}
private func getSource() -> AnyRandomAccessCollection<Element> {
// Shouldn't be broken even the controller is missing.
assert(controller != nil, InvalidationErrorMessage)
assert(version == accessibleVersion, InvalidationErrorMessage)
return controller?.source ?? AnyRandomAccessCollection([])
}
}
private let InvalidationErrorMessage = "This sequence has been invalidated. You cannot access this now."
extension TemporalLazyCollection: ArrayLiteralConvertible {
init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
/// Performs all mutations here.
/// For each time you mutate, you'll get *conceptually* new sequence.
/// And old sequence gets invalidated, and shouldn't be accessed anymore.
final class TemporalLazyCollectionController<T> {
private(set) var sequence = TemporalLazyCollection<T>()
var version = Version()
/// Setting a new source will invalidate any existing copies.
var source: AnyRandomAccessCollection<T> = AnyRandomAccessCollection<T>([]) {
didSet {
version.revise()
sequence = TemporalLazyCollection(controller: self)
}
}
}
private let emptySequenceVersion = Version()
| ef67536661e4354db58becffa26535b7 | 28.784314 | 113 | 0.686965 | false | false | false | false |
1457792186/JWSwift | refs/heads/master | SwiftWX/LGWeChatKit/LGChatKit/conversion/imagePick/LGAssetGridViewController.swift | apache-2.0 | 1 | //
// LGAssetGridViewController.swift
// LGChatViewController
//
// Created by jamy on 10/22/15.
// Copyright © 2015 jamy. All rights reserved.
//
import UIKit
import Photos
private let reuseIdentifier = "girdCell"
private let itemMargin: CGFloat = 5
private let durationTime = 0.3
private let itemSize: CGFloat = 80
class LGAssetGridViewController: UICollectionViewController, UIViewControllerTransitioningDelegate {
let presentController = LGPresentAnimationController()
let dismissController = LGDismissAnimationController()
var assetsFetchResults: PHFetchResult<AnyObject>! {
willSet {
for i in 0...newValue.count - 1 {
let asset = newValue[i] as! PHAsset
let assetModel = LGAssetModel(asset: asset, select: false)
self.assetModels.append(assetModel)
}
}
}
var toolBar: LGAssetToolView!
var assetViewCtrl: LGAssetViewController!
var assetModels = [LGAssetModel]()
var selectedInfo: NSMutableArray?
var previousPreRect: CGRect!
lazy var imageManager: PHCachingImageManager = {
return PHCachingImageManager()
}()
init() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: itemSize, height: itemSize)
layout.minimumInteritemSpacing = itemMargin
layout.minimumLineSpacing = itemMargin
layout.sectionInset = UIEdgeInsetsMake(itemMargin, itemMargin, itemMargin, itemMargin)
super.init(collectionViewLayout: layout)
self.collectionView?.collectionViewLayout = layout
collectionView?.contentInset = UIEdgeInsetsMake(0, 0, 50, 0)
}
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView!.backgroundColor = UIColor.white
// Register cell classes
self.collectionView!.register(LGAssertGridViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
previousPreRect = CGRect.zero
toolBar = LGAssetToolView(leftTitle: "预览", leftSelector: #selector(LGAssetGridViewController.preView), rightSelector: #selector(LGAssetGridViewController.send), parent: self)
toolBar.frame = CGRect(x: 0, y: view.bounds.height - 50, width: view.bounds.width, height: 50)
view.addSubview(toolBar)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
toolBar.selectCount = 0
for assetModel in assetModels {
if assetModel.select {
toolBar.addSelectCount = 1
}
}
collectionView?.reloadData()
}
func preView() {
let assetCtrl = LGAssetViewController()
assetCtrl.assetModels = assetModels
self.navigationController?.pushViewController(assetCtrl, animated: true)
}
func send() {
navigationController?.viewControllers[0].dismiss(animated: true, completion: nil)
}
// MARK: - UIViewControllerTransitioningDelegate
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.selectedIndexPath = assetViewCtrl.currentIndex
return dismissController
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return presentController
}
}
extension LGAssetGridViewController {
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return assetModels.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! LGAssertGridViewCell
let asset = assetModels[indexPath.row].asset
cell.assetModel = assetModels[indexPath.row]
cell.assetIdentifier = asset.localIdentifier
cell.selectIndicator.tag = indexPath.row
if assetModels[indexPath.row].select {
cell.buttonSelect = true
} else {
cell.buttonSelect = false
}
cell.selectIndicator.addTarget(self, action: #selector(LGAssetGridViewController.selectButton(_:)), for: .touchUpInside)
let scale = UIScreen.main.scale
imageManager.requestImage(for: asset, targetSize: CGSize(width: itemSize * scale, height: itemSize * scale), contentMode: .aspectFill, options: nil) { (image, _:[AnyHashable: Any]?) -> Void in
if cell.assetIdentifier == asset.localIdentifier {
cell.imageView.image = image
}
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let assetCtrl = LGAssetViewController()
self.selectedIndexPath = indexPath
assetCtrl.assetModels = assetModels
assetCtrl.selectedInfo = selectedInfo
assetCtrl.selectIndex = indexPath.row
self.assetViewCtrl = assetCtrl
let nav = UINavigationController(rootViewController: assetCtrl)
nav.transitioningDelegate = self
self.present(nav, animated: true, completion: nil)
}
// MARK: cell button selector
func selectButton(_ button: UIButton) {
let assetModel = assetModels[button.tag]
let cell = collectionView?.cellForItem(at: IndexPath(row: button.tag, section: 0)) as! LGAssertGridViewCell
if button.isSelected == false {
assetModel.setSelect(true)
toolBar.addSelectCount = 1
button.isSelected = true
button.addAnimation(durationTime)
selectedInfo?.add(cell.imageView.image!)
button.setImage(UIImage(named: "CellBlueSelected"), for: UIControlState())
} else {
button.isSelected = false
assetModel.setSelect(false)
toolBar.addSelectCount = -1
selectedInfo?.remove(cell.imageView.image!)
button.setImage(UIImage(named: "CellGreySelected"), for: UIControlState())
}
}
// MARK: update chache asset
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
updateAssetChache()
}
func updateAssetChache() {
let isViewVisible = self.isViewLoaded && self.view.window != nil
if !isViewVisible {
return
}
var preRect = (self.collectionView?.bounds)!
preRect = preRect.insetBy(dx: 0, dy: -0.5 * preRect.height)
let delta = abs(preRect.midY - previousPreRect.midY)
if delta > (collectionView?.bounds.height)! / 3 {
var addIndexPaths = [IndexPath]()
var remoeIndexPaths = [IndexPath]()
differentBetweenRect(previousPreRect, newRect: preRect, removeHandler: { (removeRect) -> Void in
remoeIndexPaths.append(contentsOf: self.indexPathInRect(removeRect))
}, addHandler: { (addRect) -> Void in
addIndexPaths.append(contentsOf: self.indexPathInRect(addRect))
})
imageManager.startCachingImages(for: assetAtIndexPath(addIndexPaths), targetSize: CGSize(width: itemSize, height: itemSize), contentMode: .aspectFill, options: nil)
imageManager.stopCachingImages(for: assetAtIndexPath(remoeIndexPaths), targetSize: CGSize(width: itemSize, height: itemSize), contentMode: .aspectFill, options: nil)
}
}
func assetAtIndexPath(_ indexPaths: [IndexPath]) -> [PHAsset] {
if indexPaths.count == 0 {
return []
}
var assets = [PHAsset]()
for indexPath in indexPaths {
assets.append(assetsFetchResults[indexPath.row] as! PHAsset)
}
return assets
}
func indexPathInRect(_ rect: CGRect) -> [IndexPath]{
let allAttributes = collectionView?.collectionViewLayout.layoutAttributesForElements(in: rect)
if allAttributes?.count == 0 {
return []
}
var indexPaths = [IndexPath]()
for layoutAttribute in allAttributes! {
indexPaths.append(layoutAttribute.indexPath)
}
return indexPaths
}
func differentBetweenRect(_ oldRect: CGRect, newRect: CGRect, removeHandler: (CGRect)->Void, addHandler:(CGRect)->Void) {
if newRect.intersects(oldRect) {
let oldMaxY = oldRect.maxY
let oldMinY = oldRect.minY
let newMaxY = newRect.maxY
let newMinY = newRect.minY
if newMaxY > oldMaxY {
let rectToAdd = CGRect(x: newRect.x, y: oldMaxY, width: newRect.width, height: newMaxY - oldMaxY)
addHandler(rectToAdd)
}
if oldMinY > newMinY {
let rectToAdd = CGRect(x: newRect.x, y: newMinY, width: newRect.width, height: oldMinY - newMinY)
addHandler(rectToAdd)
}
if newMaxY < oldMaxY {
let rectToMove = CGRect(x: newRect.x, y: newMaxY, width: newRect.width, height: oldMaxY - newMaxY)
removeHandler(rectToMove)
}
if oldMinY < newMinY {
let rectToMove = CGRect(x: newRect.x, y: oldMinY, width: newRect.width, height: newMinY - oldMinY)
removeHandler(rectToMove)
}
} else {
addHandler(newRect)
removeHandler(oldRect)
}
}
}
| d842e00e9ff1ec3704465127673e0c90 | 37.406716 | 200 | 0.639075 | false | false | false | false |
OpsLabJPL/MarsImagesIOS | refs/heads/main | MarsImagesIOS/Curiosity.swift | apache-2.0 | 1 | //
// Curiosity.swift
// MarsImagesIOS
//
// Created by Mark Powell on 7/28/17.
// Copyright © 2017 Mark Powell. All rights reserved.
//
import Foundation
class Curiosity: Mission {
let SOL = "Sol"
let LTST = "LTST"
let RMC = "RMC"
enum TitleState {
case START,
SOL_NUMBER,
IMAGESET_ID,
INSTRUMENT_NAME,
MARS_LOCAL_TIME,
DISTANCE,
YAW,
PITCH,
ROLL,
TILT,
ROVER_MOTION_COUNTER
}
override init() {
super.init()
var comps = DateComponents()
comps.day=6
comps.month=8
comps.year=2012
comps.hour=6
comps.minute=30
comps.second=00
comps.timeZone = TimeZone(abbreviation: "UTC")
self.epoch = Calendar.current.date(from: comps)
self.eyeIndex = 1
self.instrumentIndex = 0
self.sampleTypeIndex = 17
self.cameraFOVs["NL"] = 0.785398163
self.cameraFOVs["NR"] = 0.785398163
self.cameraFOVs["ML"] = 0.261799388
self.cameraFOVs["MR"] = 0.087266463
}
override func urlPrefix() -> String {
return "https://s3-us-west-1.amazonaws.com/msl-raws"
}
override func rowTitle(_ title: String) -> String {
return tokenize(title).instrumentName
}
override func tokenize(_ title: String) -> Title {
let msl = Title()
let tokens = title.components(separatedBy: " ")
var state = TitleState.START
for word in tokens {
if word == SOL {
state = TitleState.SOL_NUMBER
continue
}
else if word == LTST {
state = TitleState.MARS_LOCAL_TIME
continue
}
else if word == RMC {
state = TitleState.ROVER_MOTION_COUNTER
continue
}
var indices:[Int] = []
switch (state) {
case .START:
break
case .SOL_NUMBER:
msl.sol = Int(word)!
state = TitleState.IMAGESET_ID
break
case .IMAGESET_ID:
msl.imageSetID = word
state = TitleState.INSTRUMENT_NAME
break
case .INSTRUMENT_NAME:
if msl.instrumentName.isEmpty {
msl.instrumentName = String(word)
} else {
msl.instrumentName.append(" \(word)")
}
break
case .MARS_LOCAL_TIME:
msl.marsLocalTime = word
break
case .ROVER_MOTION_COUNTER:
indices = word.components(separatedBy: "-").map { Int($0)! }
msl.siteIndex = indices[0]
msl.driveIndex = indices[1]
break
default:
print("Unexpected state in parsing image title: \(state)")
break
}
}
return msl
}
override func imageName(imageId: String) -> String {
let instrument = getInstrument(imageId: imageId)
if instrument == "N" || instrument == "F" || instrument == "R" {
let eye = getEye(imageId: imageId)
if eye == "L" {
return "Left"
} else {
return "Right"
}
}
return ""
}
func isStereo(instrument:String) -> Bool {
return instrument == "F" || instrument == "R" || instrument == "N"
}
override func getCameraId(imageId: String) -> String {
let c:Character = imageId[0]
if c >= "0" && c <= "9" {
return imageId[4..<5]
} else {
return imageId[0..<1]
}
}
override func stereoImageIndices(imageIDs: [String]) -> (Int,Int)? {
let imageid = imageIDs[0]
let instrument = getInstrument(imageId: imageid)
if !isStereo(instrument: instrument) {
return nil
}
var leftImageIndex = -1;
var rightImageIndex = -1;
var index = 0;
for imageId in imageIDs {
let eye = getEye(imageId: imageId)
if leftImageIndex == -1 && eye=="L" {
leftImageIndex = index;
}
if rightImageIndex == -1 && eye=="R" {
rightImageIndex = index;
}
index += 1;
}
if (leftImageIndex >= 0 && rightImageIndex >= 0) {
return (Int(leftImageIndex), Int(rightImageIndex))
}
return nil
}
override func mastPosition() -> [Double] {
return [0.80436, 0.55942, -1.90608]
}
}
| a21810b2b90d7c9e5ef8d15fddaaed2f | 27.309524 | 76 | 0.485913 | false | false | false | false |
alexfish/tissue | refs/heads/master | tissue/Modules/Issues/IssueViewController.swift | mit | 1 | //
// IssueViewController.swift
// tissue
//
// Created by Alex Fish on 07/06/2014.
// Copyright (c) 2014 alexefish. All rights reserved.
//
import UIKit
class IssueViewController: TableViewController {
override func setupTitle() {
self.title = repo.id
}
override func getData(completionHandler: () -> Void) {
let client: Client = Client(repo: self.repo)
client.getObjects(Issue.self, { issues in
self.data = issues
completionHandler()
})
}
}
extension IssueViewController : UITableViewDataSource {
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return self.data.count
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
if indexPath!.row < self.data.count {
let issue: Issue = self.data[indexPath!.row] as Issue
cell.text = "#\(issue.id) - \(issue.title)"
}
return cell
}
}
| 689437e51732f359facdaa44ba230bcd | 26.595745 | 143 | 0.657672 | false | false | false | false |
rnystrom/GitHawk | refs/heads/master | Pods/StyledTextKit/Source/StyledTextView.swift | mit | 1 | //
// StyledTextKitView.swift
// StyledTextKit
//
// Created by Ryan Nystrom on 12/14/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
public protocol StyledTextViewDelegate: class {
func didTap(view: StyledTextView, attributes: [NSAttributedStringKey: Any], point: CGPoint)
func didLongPress(view: StyledTextView, attributes: [NSAttributedStringKey: Any], point: CGPoint)
}
open class StyledTextView: UIView {
open weak var delegate: StyledTextViewDelegate?
open var gesturableAttributes = Set<NSAttributedStringKey>()
open var drawsAsync = false
private var renderer: StyledTextRenderer?
private var tapGesture: UITapGestureRecognizer?
private var longPressGesture: UILongPressGestureRecognizer?
private var highlightLayer = CAShapeLayer()
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
translatesAutoresizingMaskIntoConstraints = false
layer.contentsGravity = kCAGravityTopLeft
let tap = UITapGestureRecognizer(target: self, action: #selector(onTap(recognizer:)))
tap.cancelsTouchesInView = false
addGestureRecognizer(tap)
self.tapGesture = tap
let long = UILongPressGestureRecognizer(target: self, action: #selector(onLong(recognizer:)))
addGestureRecognizer(long)
self.longPressGesture = long
self.highlightColor = UIColor.black.withAlphaComponent(0.1)
layer.addSublayer(highlightLayer)
}
public var highlightColor: UIColor? {
get {
guard let color = highlightLayer.fillColor else { return nil }
return UIColor(cgColor: color)
}
set { highlightLayer.fillColor = newValue?.cgColor }
}
// MARK: Overrides
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard let touch = touches.first else { return }
highlight(at: touch.location(in: self))
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
clearHighlight()
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
clearHighlight()
}
// MARK: UIGestureRecognizerDelegate
override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard (gestureRecognizer === tapGesture || gestureRecognizer === longPressGesture),
let attributes = renderer?.attributes(at: gestureRecognizer.location(in: self)) else {
return super.gestureRecognizerShouldBegin(gestureRecognizer)
}
for attribute in attributes.attributes {
if gesturableAttributes.contains(attribute.key) {
return true
}
}
return false
}
// MARK: Private API
@objc func onTap(recognizer: UITapGestureRecognizer) {
let point = recognizer.location(in: self)
guard let attributes = renderer?.attributes(at: point) else { return }
delegate?.didTap(view: self, attributes: attributes.attributes, point: point)
}
@objc func onLong(recognizer: UILongPressGestureRecognizer) {
let point = recognizer.location(in: self)
guard recognizer.state == .began,
let attributes = renderer?.attributes(at: point)
else { return }
delegate?.didLongPress(view: self, attributes: attributes.attributes, point: point)
}
private func highlight(at point: CGPoint) {
guard let renderer = renderer,
let attributes = renderer.attributes(at: point),
attributes.attributes[.highlight] != nil
else { return }
let storage = renderer.storage
let maxLen = storage.length
var min = attributes.index
var max = attributes.index
storage.enumerateAttributes(
in: NSRange(location: 0, length: attributes.index),
options: .reverse
) { (attrs, range, stop) in
if attrs[.highlight] != nil && min > 0 {
min = range.location
} else {
stop.pointee = true
}
}
storage.enumerateAttributes(
in: NSRange(location: attributes.index, length: maxLen - attributes.index),
options: []
){ (attrs, range, stop) in
if attrs[.highlight] != nil && max < maxLen {
max = range.location + range.length
} else {
stop.pointee = true
}
}
let range = NSRange(location: min, length: max - min)
var firstRect: CGRect = CGRect.null
var bodyRect: CGRect = CGRect.null
var lastRect: CGRect = CGRect.null
let path = UIBezierPath()
renderer.layoutManager.enumerateEnclosingRects(
forGlyphRange: range,
withinSelectedGlyphRange: NSRange(location: NSNotFound, length: 0),
in: renderer.textContainer
) { (rect, stop) in
if firstRect.isNull {
firstRect = rect
} else if lastRect.isNull {
lastRect = rect
} else {
// We have a lastRect that was previously filled, now it needs to be dumped into the body
bodyRect = lastRect.intersection(bodyRect)
// and save the current rect as the new "lastRect"
lastRect = rect
}
}
if !firstRect.isNull {
path.append(UIBezierPath(roundedRect: firstRect.insetBy(dx: -2, dy: -2), cornerRadius: 3))
}
if !bodyRect.isNull {
path.append(UIBezierPath(roundedRect: bodyRect.insetBy(dx: -2, dy: -2), cornerRadius: 3))
}
if !lastRect.isNull {
path.append(UIBezierPath(roundedRect: lastRect.insetBy(dx: -2, dy: -2), cornerRadius: 3))
}
highlightLayer.frame = bounds
highlightLayer.path = path.cgPath
}
private func clearHighlight() {
highlightLayer.path = nil
}
private func setRenderResults(renderer: StyledTextRenderer, result: (CGImage?, CGSize)) {
layer.contents = result.0
frame = CGRect(origin: CGPoint(x: renderer.inset.left, y: renderer.inset.top), size: result.1)
}
static var renderQueue = DispatchQueue(
label: "com.whoisryannystrom.StyledText.renderQueue",
qos: .default, attributes: DispatchQueue.Attributes(rawValue: 0),
autoreleaseFrequency: .workItem,
target: nil
)
// MARK: Public API
open func configure(with renderer: StyledTextRenderer, width: CGFloat) {
self.renderer = renderer
layer.contentsScale = renderer.scale
reposition(for: width)
accessibilityLabel = renderer.string.allText
}
open func reposition(for width: CGFloat) {
guard let capturedRenderer = self.renderer else { return }
// First, we check if we can immediately apply a previously cached render result.
let cachedResult = capturedRenderer.cachedRender(for: width)
if let cachedImage = cachedResult.image, let cachedSize = cachedResult.size {
setRenderResults(renderer: capturedRenderer, result: (cachedImage, cachedSize))
return
}
// We have to do a full render, so if we are drawing async it's time to dispatch:
if drawsAsync {
StyledTextView.renderQueue.async {
// Compute the render result (sizing and rendering to an image) on a bg thread
let result = capturedRenderer.render(for: width)
DispatchQueue.main.async {
// If the renderer changed, then our computed result is now invalid, so we have to throw it out.
if capturedRenderer !== self.renderer { return }
// If the renderer hasn't changed, we're OK to actually apply the result of our computation.
self.setRenderResults(renderer: capturedRenderer, result: result)
}
}
} else {
// We're in fully-synchronous mode. Immediately compute the result and set it.
let result = capturedRenderer.render(for: width)
setRenderResults(renderer: capturedRenderer, result: result)
}
}
}
| 7849765475c3816eabed5f1d3d4cacf1 | 35.578059 | 116 | 0.627639 | false | false | false | false |
xmartlabs/Opera | refs/heads/master | Example/Example/Controllers/RepositoryReleasesController.swift | mit | 1 | // RepositoryReleasesController.swift
// Example-iOS ( https://github.com/xmartlabs/Example-iOS )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
import OperaSwift
import RxSwift
import RxCocoa
class RepositoryReleasesController: RepositoryBaseController {
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
let refreshControl = UIRefreshControl()
var disposeBag = DisposeBag()
lazy var viewModel: PaginationViewModel<PaginationRequest<Release>> = { [unowned self] in
return PaginationViewModel(paginationRequest: PaginationRequest(route: GithubAPI.Repository.GetReleases(owner: self.owner, repo: self.name)))
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.keyboardDismissMode = .onDrag
tableView.addSubview(self.refreshControl)
emptyStateLabel.text = "No releases found"
let refreshControl = self.refreshControl
rx.sentMessage(#selector(RepositoryForksController.viewWillAppear(_:)))
.map { _ in false }
.bind(to: viewModel.refreshTrigger)
.disposed(by: disposeBag)
tableView.rx.reachedBottom
.bind(to: viewModel.loadNextPageTrigger)
.disposed(by: disposeBag)
viewModel.loading
.drive(activityIndicatorView.rx.isAnimating)
.disposed(by: disposeBag)
Driver.combineLatest(viewModel.elements.asDriver(), viewModel.firstPageLoading) { elements, loading in return loading ? [] : elements }
.asDriver()
.drive(tableView.rx.items(cellIdentifier: "Cell")) { _, release, cell in
cell.textLabel?.text = release.tagName
cell.detailTextLabel?.text = release.user
}
.disposed(by: disposeBag)
refreshControl.rx.valueChanged
.filter { refreshControl.isRefreshing }
.map { true }
.bind(to: viewModel.refreshTrigger)
.disposed(by: disposeBag)
viewModel.loading
.filter { !$0 && refreshControl.isRefreshing }
.drive(onNext: { _ in refreshControl.endRefreshing() })
.disposed(by: disposeBag)
viewModel.emptyState
.drive(onNext: { [weak self] emptyState in self?.emptyStateLabel.isHidden = !emptyState })
.disposed(by: disposeBag)
}
}
| d0010cf5c19feb111af480273da84a04 | 38.784091 | 149 | 0.688946 | false | false | false | false |
towlebooth/watchos-countdown-tutorial | refs/heads/master | CountdownTutorial/DisplayViewController.swift | mit | 1 | //
// DisplayViewController.swift
// CountdownTutorial
//
// Created by Chad Towle on 12/23/15.
// Copyright © 2015 Intertech. All rights reserved.
//
import UIKit
import WatchConnectivity
class DisplayViewController: UIViewController, WCSessionDelegate {
@IBOutlet weak var startDateLabel: UILabel!
var savedDate: NSDate = NSDate()
let userCalendar = NSCalendar.currentCalendar()
var session : WCSession!
override func viewDidLoad() {
super.viewDidLoad()
if (WCSession.isSupported()) {
session = WCSession.defaultSession()
session.delegate = self;
session.activateSession()
}
// get values from user defaults
let defaults = NSUserDefaults.standardUserDefaults()
if let dateString = defaults.stringForKey("dateKey")
{
startDateLabel.text = dateString
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func saveSegue(segue:UIStoryboardSegue) {
let dateFormat = NSDateFormatter()
dateFormat.calendar = userCalendar
dateFormat.dateFormat = "yyyy-MM-dd"
let savedDateString = dateFormat.stringFromDate(savedDate)
startDateLabel.text = savedDateString
// save to user defaults for use here in phone app
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(savedDateString, forKey: "dateKey")
// save values to session to be shared with watch
let applicationDict = ["dateKey":savedDateString]
do {
try session.updateApplicationContext(applicationDict)
} catch {
print("Error updating application context.")
}
// update complication
if session.watchAppInstalled {
session.transferCurrentComplicationUserInfo(applicationDict)
}
}
}
| 9a1d1ab53e082154177a4f17f42da7d0 | 29.878788 | 72 | 0.640824 | false | true | false | false |
ProfileCreator/ProfileCreator | refs/heads/master | ProfileCreator/ProfileCreator/Profile Editor TableView CellViews/PayloadCellViewHostPort.swift | mit | 1 | //
// PayloadCellViewHostPort.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
import ProfilePayloads
class PayloadCellViewHostPort: PayloadCellView, ProfileCreatorCellView, NSTextFieldDelegate {
// MARK: -
// MARK: Instance Variables
var textFieldHost: PayloadTextField?
var textFieldPort: PayloadTextField?
var constraintPortTrailing: NSLayoutConstraint?
@objc var valuePort: NSNumber?
var isEditingHost: Bool = false
var isEditingPort: Bool = false
var valueBeginEditingHost: String?
var valueBeginEditingPort: String?
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(subkey: PayloadSubkey, payloadIndex: Int, enabled: Bool, required: Bool, editor: ProfileEditor) {
super.init(subkey: subkey, payloadIndex: payloadIndex, enabled: enabled, required: required, editor: editor)
// ---------------------------------------------------------------------
// Setup Custom View Content
// ---------------------------------------------------------------------
self.textFieldHost = EditorTextField.input(defaultString: "", placeholderString: "Host", cellView: self)
self.setupTextField(host: self.textFieldHost!)
self.textFieldPort = EditorTextField.input(defaultString: "", placeholderString: "Port", cellView: self)
self.setupTextField(port: self.textFieldPort!)
_ = EditorTextField.label(string: ":", fontWeight: .regular, leadingItem: self.textFieldHost!, leadingConstant: nil, trailingItem: self.textFieldPort!, constraints: &self.cellViewConstraints, cellView: self)
// ---------------------------------------------------------------------
// Setup KeyView Loop Items
// ---------------------------------------------------------------------
self.leadingKeyView = self.textFieldHost
self.trailingKeyView = self.textFieldPort
// ---------------------------------------------------------------------
// Activate Layout Constraints
// ---------------------------------------------------------------------
NSLayoutConstraint.activate(self.cellViewConstraints)
}
// MARK: -
// MARK: PayloadCellView Functions
override func enable(_ enable: Bool) {
self.isEnabled = enable
self.textFieldHost?.isEnabled = enable
self.textFieldHost?.isSelectable = enable
self.textFieldPort?.isEnabled = enable
self.textFieldPort?.isSelectable = enable
}
}
// MARK: -
// MARK: NSControl Functions
extension PayloadCellViewHostPort {
internal func controlTextDidBeginEditing(_ obj: Notification) {
guard
let textField = obj.object as? NSTextField,
let userInfo = obj.userInfo,
let fieldEditor = userInfo["NSFieldEditor"] as? NSTextView,
let originalString = fieldEditor.textStorage?.string else {
return
}
if textField == self.textFieldHost {
self.isEditingHost = true
self.valueBeginEditingHost = originalString
} else if textField == self.textFieldPort {
self.isEditingPort = true
self.valueBeginEditingPort = originalString
}
}
internal func controlTextDidEndEditing(_ obj: Notification) {
if !isEditingHost && !isEditingPort { return }
guard
let textField = obj.object as? NSTextField,
let userInfo = obj.userInfo,
let fieldEditor = userInfo["NSFieldEditor"] as? NSTextView,
let newString = fieldEditor.textStorage?.string else {
if isEditingHost {
self.isEditingHost = false
} else if isEditingPort {
self.isEditingPort = false
}
return
}
if textField == self.textFieldHost, newString != self.valueBeginEditingHost {
// self.profile.settings.updatePayloadSettings(value: newString, subkey: self.subkey, payloadIndex: self.payloadIndex)
self.profile.settings.setValue(newString, forSubkey: self.subkey, payloadIndex: self.payloadIndex)
self.isEditingHost = false
} else if textField == self.textFieldPort, newString != self.valueBeginEditingPort {
// self.profile.settings.updatePayloadSettings(value: newString, subkey: self.subkey, payloadIndex: self.payloadIndex)
self.profile.settings.setValue(newString, forSubkey: self.subkey, payloadIndex: self.payloadIndex)
self.isEditingPort = false
}
}
}
// MARK: -
// MARK: Setup NSLayoutConstraints
extension PayloadCellViewHostPort {
private func setupTextField(host: NSTextField) {
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.addSubview(host)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Below
self.addConstraints(forViewBelow: host)
// Leading
self.addConstraints(forViewLeading: host)
}
private func setupTextField(port: NSTextField) {
// ---------------------------------------------------------------------
// Add Number Formatter to TextField
// ---------------------------------------------------------------------
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .none
numberFormatter.minimum = 1
numberFormatter.maximum = 65_535
port.formatter = numberFormatter
port.bind(.value, to: self, withKeyPath: "valuePort", options: [NSBindingOption.nullPlaceholder: "Port", NSBindingOption.continuouslyUpdatesValue: true])
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.addSubview(port)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Width (fixed size to fit 5 characters: 49.0)
self.cellViewConstraints.append(NSLayoutConstraint(item: port,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 49.0))
// Trailing
self.constraintPortTrailing = NSLayoutConstraint(item: self,
attribute: .trailing,
relatedBy: .equal,
toItem: port,
attribute: .trailing,
multiplier: 1.0,
constant: 8.0)
self.cellViewConstraints.append(self.constraintPortTrailing!)
}
}
| 014302572e9dce35bb25fa86a37c998a | 40.747312 | 215 | 0.498261 | false | false | false | false |
PureSwift/Bluetooth | refs/heads/master | Sources/BluetoothHCI/HCILESetScanParameters.swift | mit | 1 | //
// HCILESetScanParameters.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// LE Set Scan Parameters Command
///
/// Used to set the scan parameters.
///
/// - Note: The Host shall not issue this command when scanning is enabled in the Controller;
/// if it is the Command Disallowed error code shall be used.
public struct HCILESetScanParameters: HCICommandParameter { // HCI_LE_Set_Scan_Parameters
public static let command = HCILowEnergyCommand.setScanParameters // 0x000B
public static let length = 1 + 2 + 2 + 1 + 1
public typealias TimeInterval = LowEnergyScanTimeInterval
/// Controls the type of scan to perform
public let type: ScanType // LE_Scan_Type
/// This is defined as the time interval from when the Controller
/// started its last LE scan until it begins the subsequent LE scan.
public let interval: TimeInterval // LE_Scan_Interval
/// The duration of the LE scan.
/// Should be less than or equal to `interval`.
public let window: TimeInterval // LE_Scan_Window
/// Determines the address used (Public or Random Device Address) when performing active scan.
public let addressType: LowEnergyAddressType // Own_Address_Type
/// Scanning filter policy.
public let filterPolicy: FilterPolicy
public init(type: ScanType = .passive,
interval: TimeInterval = TimeInterval(rawValue: 0x01E0)!,
window: TimeInterval = TimeInterval(rawValue: 0x0030)!,
addressType: LowEnergyAddressType = .public,
filterPolicy: FilterPolicy = .accept) {
precondition(window <= interval, "LE_Scan_Window shall be less than or equal to LE_Scan_Interval")
self.type = type
self.interval = interval
self.window = window
self.addressType = addressType
self.filterPolicy = filterPolicy
}
public var data: Data {
let scanType = type.rawValue
let scanInterval = interval.rawValue.littleEndian.bytes
let scanWindow = window.rawValue.littleEndian.bytes
let ownAddressType = addressType.rawValue
let filter = filterPolicy.rawValue
return Data([scanType, scanInterval.0, scanInterval.1, scanWindow.0, scanWindow.1, ownAddressType, filter])
}
}
// MARK: - Supporting Types
public extension HCILESetScanParameters {
/// Controls the type of scan to perform
enum ScanType: UInt8 {
/// Passive scanning.
///
/// No scanning PDUs shall be sent.
case passive = 0x0
/// Active scanning.
///
/// Scanning PDUs may be sent.
case active = 0x1
/// Initialize with default value (Passive scanning).
public init() {
self = .passive
}
}
enum FilterPolicy: UInt8 { // Scanning_Filter_Policy
/// Accept all advertisement packets.
///
/// Directed advertising packets which are not addressed for this device shall be ignored.
case accept = 0x0
/// Ignore advertisement packets from devices not in the White List Only.
///
/// Directed advertising packets which are not addressed for this device shall be ignored.
case ignore = 0x1
/// Accept all advertising packets except:
/// • advertising packets where the advertiser's identity address is not in the White List; and
/// • directed advertising packets where the initiator's identity address does not address this device
///
/// - Note: Directed advertising packets where the initiator's address is a resolvable private address that cannot be resolved are also accepted.
case directed = 0x02
/// Initialize with default value (Accept all advertisement packets).
public init() {
self = .accept
}
}
}
| 343187db3352e6afee31010560d37ff5 | 34.452174 | 153 | 0.639195 | false | false | false | false |
alexdoloz/Gridy | refs/heads/master | Gridy/Source/Cell.swift | mit | 1 | import Foundation
import CoreGraphics
/** Defines 2d cell with `Int` coordinates.*/
public struct Cell {
var x = 0
var y = 0
var point: CGPoint {
return CGPoint(x: x, y: y)
}
}
extension Cell: CustomStringConvertible {
public var description: String {
return "(\(x), \(y))"
}
}
extension Cell: Hashable {
public var hashValue: Int {
return x ^ y
}
}
// MARK: Operators
public func == (lhs: Cell, rhs: Cell) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
| 048e8c6424a002fe734bcfc3fd466227 | 13.861111 | 47 | 0.571963 | false | false | false | false |
DiUS/pact-consumer-swift | refs/heads/master | Tests/PactConsumerSwiftTests/AnimalServiceClient.swift | mit | 1 | import Foundation
public struct Animal: Decodable {
public let name: String
public let type: String
public let dob: String?
public let legs: Int?
enum CodingKeys: String, CodingKey {
case name
case type
case dob = "dateOfBirth"
case legs
}
}
open class AnimalServiceClient: NSObject, URLSessionDelegate {
fileprivate let baseUrl: String
public init(baseUrl : String) {
self.baseUrl = baseUrl
}
// MARK: -
open func getAlligators(_ success: @escaping (Array<Animal>) -> Void, failure: @escaping (NSError?) -> Void) {
self.performRequest("\(baseUrl)/alligators", decoder: decodeAnimals) { animals, nsError in
if let animals = animals {
success(animals)
} else {
if let error = nsError {
failure(error)
} else {
failure(NSError(domain: "", code: 42, userInfo: nil))
}
}
}
}
open func getSecureAlligators(authToken: String, success: @escaping (Array<Animal>) -> Void, failure: @escaping (NSError?) -> Void) {
self.performRequest("\(baseUrl)/alligators", headers: ["Authorization": authToken], decoder: decodeAnimals) { animals, nsError in
if let animals = animals {
success(animals)
} else {
if let error = nsError {
failure(error)
} else {
failure(NSError(domain: "", code: 42, userInfo: nil))
}
}
}
}
open func getAlligator(_ id: Int, success: @escaping (Animal) -> Void, failure: @escaping (NSError?) -> Void) {
self.performRequest("\(baseUrl)/alligators/\(id)", decoder: decodeAnimal) { animal, nsError in
if let animal = animal {
success(animal)
} else {
if let error = nsError {
failure(error)
} else {
failure(NSError(domain: "", code: 42, userInfo: nil))
}
}
}
}
open func findAnimals(live: String, response: @escaping ([Animal]) -> Void) {
let liveEncoded = live.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
self.performRequest("\(baseUrl)/animals?live=\(liveEncoded)", decoder: decodeAnimals) { animals, nsError in
if let animals = animals {
response(animals)
}
}
}
open func eat(animal: String, success: @escaping () -> Void, error: @escaping (Int) -> Void) {
self.performRequest("\(baseUrl)/alligator/eat", method: "patch", parameters: ["type": animal], decoder: decodeString) { string, nsError in
if let localErr = nsError {
error(localErr.code)
} else {
success()
}
}
}
open func wontEat(animal: String, success: @escaping () -> Void, error: @escaping (Int) -> Void) {
self.performRequest("\(baseUrl)/alligator/eat", method: "delete", parameters: ["type": animal], decoder: decodeAnimals) { animals, nsError in
if let localErr = nsError {
error(localErr.code)
} else {
success()
}
}
}
open func eats(_ success: @escaping ([Animal]) -> Void) {
self.performRequest("\(baseUrl)/alligator/eat", decoder: decodeAnimals) { animals, nsError in
if let animals = animals {
success(animals)
}
}
}
// MARK: - URLSessionDelegate
public func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
) {
guard
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
challenge.protectionSpace.host.contains("localhost"),
let serverTrust = challenge.protectionSpace.serverTrust
else {
completionHandler(.performDefaultHandling, nil)
return
}
let credential = URLCredential(trust: serverTrust)
completionHandler(.useCredential, credential)
}
// MARK: - Networking and Decoding
private lazy var session = {
URLSession(configuration: .ephemeral, delegate: self, delegateQueue: .main)
}()
private func performRequest<T: Decodable>(_ urlString: String,
headers: [String: String]? = nil,
method: String = "get",
parameters: [String: String]? = nil,
decoder: @escaping (_ data: Data) throws -> T,
completionHandler: @escaping (_ response: T?, _ error: NSError?) -> Void
) {
var request = URLRequest(url: URL(string: urlString)!)
request.httpMethod = method
if let headers = headers {
request.allHTTPHeaderFields = headers
}
if let parameters = parameters,
let data = try? JSONSerialization.data(withJSONObject: parameters, options: []) {
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = data
}
let task = self.session.dataTask(with: request) { data, response, error in
if let error = error {
completionHandler(nil, error as NSError)
return
}
if let data = data,
let response = response as? HTTPURLResponse,
(200..<300).contains(response.statusCode) {
do {
let result = try decoder(data)
completionHandler(result, nil)
} catch {
completionHandler(nil, error as NSError)
}
} else {
completionHandler(nil, NSError(domain: "", code: 41, userInfo: nil))
}
}
task.resume()
}
private func decodeAnimal(_ data: Data) throws -> Animal {
let decoder = JSONDecoder()
return try decoder.decode(Animal.self, from: data)
}
private func decodeAnimals(_ data: Data) throws -> [Animal] {
let decoder = JSONDecoder()
return try decoder.decode([Animal].self, from: data)
}
private func decodeString(_ data: Data) throws -> String {
guard let result = String(data: data, encoding: .utf8) else {
throw NSError(domain: "", code: 63, userInfo: nil)
}
return result
}
}
| 09535c458aa4ef0f6fc0a8884cb58f9d | 30.888298 | 145 | 0.618182 | false | false | false | false |
Fidetro/SwiftFFDB | refs/heads/master | Sources/Select.swift | apache-2.0 | 1 | //
// Select.swift
// Swift-FFDB
//
// Created by Fidetro on 2018/5/25.
// Copyright © 2018年 Fidetro. All rights reserved.
//
import Foundation
public struct Select:STMT {
public let stmt : String
public init( _ columns: [String]) {
var columnString = ""
for (index,column) in columns.enumerated() {
if index == 0 {
columnString += column
}else{
columnString = columnString + "," + column
}
}
self.init(columnString)
}
public init(_ stmt : String) {
self.stmt = "select" +
" " +
stmt +
" "
}
}
// MARK: - From
extension Select {
public func from(_ from:String) -> From {
return From(stmt, format: from)
}
public func from(_ table:FFObject.Type) -> From {
return From(stmt, table: table)
}
}
| 804d6a18aa90054d6c6999b2df753e0b | 19.340426 | 58 | 0.48431 | false | false | false | false |
ls1intum/sReto | refs/heads/master | Source/sReto/Core/Utils/MappingSequence.swift | mit | 1 | //
// StateSequence.swift
// sReto
//
// Created by Julian Asamer on 21/08/14.
// Copyright (c) 2014 - 2016 Chair for Applied Software Engineering
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness
// for a particular purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability,
// whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.
//
import Foundation
/**
* The iterateMapping function creates a sequence by applying a mapping to a state an arbitrary number of times.
* For example, iterateMapping(initialState: 0, { $0 + 1 }) constructs an infinite list of the numbers 0, 1, 2, ...
*/
func iterateMapping<E>(initialState: E, mapping: @escaping (E) -> E?) -> MappingSequence<E> {
return MappingSequence(initialState: initialState, mapping: mapping)
}
struct MappingGenerator<E>: IteratorProtocol {
typealias Element = E
var state: E?
let mapping: (E) -> E?
init(initialState: E, mapping: @escaping (E) -> E?) {
self.state = initialState
self.mapping = mapping
}
mutating func next() -> Element? {
let result = self.state
if let state = self.state { self.state = self.mapping(state) }
return result
}
}
struct MappingSequence<E>: Sequence {
let initialState: E
let mapping: (E) -> E?
func makeIterator() -> MappingGenerator<E> {
return MappingGenerator(initialState: self.initialState, mapping: self.mapping)
}
}
| 1ae0aa3a6ebb6a4473f47b7e847c2d4e | 42.407407 | 159 | 0.712884 | false | false | false | false |
DuckDeck/GrandStore | refs/heads/master | GrandStoreDemo/TempSaveTestViewController.swift | mit | 1 | //
// TempSaveTestViewController.swift
// GrandStoreDemo
//
// Created by HuStan on 3/3/16.
// Copyright © 2016 Qfq. All rights reserved.
//
import UIKit
class TempSaveTestViewController: UIViewController {
var demoTemp = GrandStore(name: "demoTemp", defaultValue: "temp", timeout: 0)
var txtString:UITextField?
var btnSet:UIButton?
var btnGet:UIButton?
var lblString:UILabel?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
txtString = UITextField(frame: CGRect(x: 20, y: 167, width: UIScreen.main.bounds.width - 40, height: 40))
txtString?.layer.borderColor = UIColor.blue.cgColor
txtString?.layer.borderWidth = 0.5
view.addSubview(txtString!)
btnSet = UIButton(frame: CGRect(x: 20, y: txtString!.frame.maxY, width: UIScreen.main.bounds.width - 40, height: 40))
btnSet?.setTitle("设值", for: UIControl.State())
btnSet?.setTitleColor(UIColor.black, for: UIControl.State())
btnSet?.addTarget(self, action: #selector(TempSaveTestViewController.setString(_:)), for: UIControl.Event.touchUpInside)
view.addSubview(btnSet!)
btnGet = UIButton(frame: CGRect(x: 20, y: btnSet!.frame.maxY, width: UIScreen.main.bounds.width - 40, height: 40))
btnGet?.setTitle("取值", for: UIControl.State())
btnGet?.setTitleColor(UIColor.black, for: UIControl.State())
btnGet?.addTarget(self, action: #selector(TempSaveTestViewController.getString(_:)), for: UIControl.Event.touchUpInside)
view.addSubview(btnGet!)
lblString = UILabel(frame: CGRect(x: 20, y:btnGet!.frame.maxY, width: UIScreen.main.bounds.width - 40, height: 40))
lblString?.textColor = UIColor.black
view.addSubview(lblString!)
}
@objc func setString(_ sender:UIButton)
{
if let txt = txtString?.text{
demoTemp.Value = txt
}
}
@objc func getString(_ sender:UIButton)
{
lblString?.text = demoTemp.Value
}
}
| 9ec6aa92802688dca5674d2c940cd353 | 35.017241 | 128 | 0.649114 | false | true | false | false |
adelang/DoomKit | refs/heads/master | Sources/Graphic.swift | mit | 1 | //
// Graphic.swift
// DoomKit
//
// Created by Arjan de Lang on 03-01-15.
// Copyright (c) 2015 Blue Depths Media. All rights reserved.
//
import Cocoa
var __graphicsCache = [String: Graphic]()
open class Graphic {
open var width: Int16 = 0
open var height: Int16 = 0
open var xOffset: Int16 = 0
open var yOffset: Int16 = 0
var _pixelData: [UInt8?] = []
var _cachedImage: NSImage?
open class func graphicWithLumpName(_ lumpName: String, inWad wad: Wad) -> Graphic? {
if lumpName == "-" {
return nil
}
if let graphic = __graphicsCache[lumpName] {
return graphic
}
for lump in wad.lumps {
if lump.name == lumpName {
if let data = lump.data {
var dataPointer = 0
var width: Int16 = 0
(data as NSData).getBytes(&width, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size))
dataPointer += MemoryLayout<Int16>.size
var height: Int16 = 0
(data as NSData).getBytes(&height, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size))
dataPointer += MemoryLayout<Int16>.size
var xOffset: Int16 = 0
(data as NSData).getBytes(&xOffset, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size))
dataPointer += MemoryLayout<Int16>.size
var yOffset: Int16 = 0
(data as NSData).getBytes(&yOffset, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size))
dataPointer += MemoryLayout<Int16>.size
var pixelData = [UInt8?](repeating: nil, count: (Int(width) * Int(height)))
var columnPointers: [UInt32] = []
for _ in (0 ..< width) {
var columnPointer: UInt32 = 0
(data as NSData).getBytes(&columnPointer, range: NSMakeRange(dataPointer, MemoryLayout<UInt32>.size))
columnPointers.append(columnPointer)
dataPointer += MemoryLayout<UInt32>.size
}
var x: Int16 = 0
for _ in columnPointers {
readPoles: while(true) {
var y: UInt8 = 0
(data as NSData).getBytes(&y, range: NSMakeRange(dataPointer, MemoryLayout<UInt8>.size))
dataPointer += MemoryLayout<UInt8>.size
if y == 255 {
break readPoles
}
var numberOfPixels: UInt8 = 0
(data as NSData).getBytes(&numberOfPixels, range: NSMakeRange(dataPointer, MemoryLayout<UInt8>.size))
dataPointer += MemoryLayout<UInt8>.size
// Ignore first byte
dataPointer += MemoryLayout<UInt8>.size
var pixelIndex = Int(y) + Int(x * height)
for _ in (0 ..< numberOfPixels) {
var paletteIndex: UInt8 = 0
(data as NSData).getBytes(&paletteIndex, range: NSMakeRange(dataPointer, MemoryLayout<UInt8>.size))
pixelData[pixelIndex] = paletteIndex
pixelIndex += 1
dataPointer += MemoryLayout<UInt8>.size
}
// Also ignore last byte
dataPointer += MemoryLayout<UInt8>.size
}
x += 1
}
let graphic = Graphic(width: width, height: height, xOffset: xOffset, yOffset: yOffset, pixelData: pixelData)
__graphicsCache[lumpName] = graphic
return graphic
}
}
}
print("Unable to find graphic with name '\(lumpName)'")
return nil
}
open class func flatWithLumpName(_ lumpName: String, inWad wad: Wad) -> Graphic? {
if lumpName == "-" {
return nil
}
if let graphic = __graphicsCache[lumpName] {
return graphic
}
for lump in wad.lumps {
if lump.name == lumpName {
if let data = lump.data {
let width: Int16 = 64
let height: Int16 = 64
let xOffset: Int16 = 0
let yOffset: Int16 = 0
var pixelData = [UInt8](repeating: 0, count: (Int(width) * Int(height)))
(data as NSData).getBytes(&pixelData, range: NSMakeRange(0, MemoryLayout<UInt8>.size * Int(width) * Int(height)))
let graphic = Graphic(width: width, height: height, xOffset: xOffset, yOffset: yOffset, pixelData: pixelData)
__graphicsCache[lumpName] = graphic
return graphic
}
}
}
print("Unable to find graphic with name '\(lumpName)'")
return nil
}
public init(width: Int16, height: Int16, xOffset: Int16, yOffset: Int16, pixelData: [UInt8?]) {
self.width = width
self.height = height
self.xOffset = xOffset
self.yOffset = yOffset
self._pixelData = pixelData
}
open func imageWithPalette(_ palette: Palette) -> NSImage {
if let image = _cachedImage {
return image
}
let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(width), pixelsHigh: Int(height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: Int(4 * width), bitsPerPixel: 32)
let image = NSImage()
image.addRepresentation(bitmap!)
var pixelIndex = 0
for x in 0 ..< Int(width) {
for y in 0 ..< Int(height) {
let paletteIndex = _pixelData[pixelIndex]
pixelIndex += 1
let color: NSColor
if let paletteIndex = paletteIndex {
color = palette.colors[Int(paletteIndex)]
} else {
color = NSColor.clear
}
bitmap?.setColor(color, atX: x, y: y)
}
}
_cachedImage = image
return image
}
}
| 5ea55f9b8f3334adf850a5f93e3a36dc | 28.011429 | 264 | 0.647627 | false | false | false | false |
rudkx/swift | refs/heads/main | test/Generics/generic_types.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=verify -requirement-machine-inferred-signatures=verify
protocol MyFormattedPrintable {
func myFormat() -> String
}
func myPrintf(_ format: String, _ args: MyFormattedPrintable...) {}
extension Int : MyFormattedPrintable {
func myFormat() -> String { return "" }
}
struct S<T : MyFormattedPrintable> {
var c : T
static func f(_ a: T) -> T {
return a
}
func f(_ a: T, b: Int) {
return myPrintf("%v %v %v", a, b, c)
}
}
func makeSInt() -> S<Int> {}
typealias SInt = S<Int>
var a : S<Int> = makeSInt()
a.f(1,b: 2)
var b : Int = SInt.f(1)
struct S2<T> {
@discardableResult
static func f() -> T {
S2.f()
}
}
struct X { }
var d : S<X> // expected-error{{type 'X' does not conform to protocol 'MyFormattedPrintable'}}
enum Optional<T> {
case element(T)
case none
init() { self = .none }
init(_ t: T) { self = .element(t) }
}
typealias OptionalInt = Optional<Int>
var uniontest1 : (Int) -> Optional<Int> = OptionalInt.element
var uniontest2 : Optional<Int> = OptionalInt.none
var uniontest3 = OptionalInt(1)
// FIXME: Stuff that should work, but doesn't yet.
// var uniontest4 : OptInt = .none
// var uniontest5 : OptInt = .Some(1)
func formattedTest<T : MyFormattedPrintable>(_ a: T) {
myPrintf("%v", a)
}
struct formattedTestS<T : MyFormattedPrintable> {
func f(_ a: T) {
formattedTest(a)
}
}
struct GenericReq<T : IteratorProtocol, U : IteratorProtocol>
where T.Element == U.Element {
}
func getFirst<R : IteratorProtocol>(_ r: R) -> R.Element {
var r = r
return r.next()!
}
func testGetFirst(ir: Range<Int>) {
_ = getFirst(ir.makeIterator()) as Int
}
struct XT<T> {
init(t : T) {
prop = (t, t)
}
static func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
class YT<T> {
init(_ t : T) {
prop = (t, t)
}
deinit {}
class func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
struct ZT<T> {
var x : T, f : Float
}
struct Dict<K, V> {
subscript(key: K) -> V { get {} set {} }
}
class Dictionary<K, V> { // expected-note{{generic type 'Dictionary' declared here}}
subscript(key: K) -> V { get {} set {} }
}
typealias XI = XT<Int>
typealias YI = YT<Int>
typealias ZI = ZT<Int>
var xi = XI(t: 17)
var yi = YI(17)
var zi = ZI(x: 1, f: 3.0)
var i : Int = XI.f()
i = XI.f()
i = xi.g()
i = yi.f() // expected-error{{static member 'f' cannot be used on instance of type 'YI' (aka 'YT<Int>')}}
i = yi.g()
var xif : (XI) -> () -> Int = XI.g
var gif : (YI) -> () -> Int = YI.g
var ii : (Int, Int) = xi.prop
ii = yi.prop
xi.prop = ii
yi.prop = ii
var d1 : Dict<String, Int>
var d2 : Dictionary<String, Int>
d1["hello"] = d2["world"]
i = d2["blarg"]
struct RangeOfPrintables<R : Sequence>
where R.Iterator.Element : MyFormattedPrintable {
var r : R
func format() -> String {
var s : String
for e in r {
s = s + e.myFormat() + " "
}
return s
}
}
struct Y {}
struct SequenceY : Sequence, IteratorProtocol {
typealias Iterator = SequenceY
typealias Element = Y
func next() -> Element? { return Y() }
func makeIterator() -> Iterator { return self }
}
func useRangeOfPrintables(_ roi : RangeOfPrintables<[Int]>) {
var rop : RangeOfPrintables<X> // expected-error{{type 'X' does not conform to protocol 'Sequence'}}
var rox : RangeOfPrintables<SequenceY> // expected-error{{type 'SequenceY.Element' (aka 'Y') does not conform to protocol 'MyFormattedPrintable'}}
}
var dfail : Dictionary<Int> // expected-error{{generic type 'Dictionary' specialized with too few type parameters (got 1, but expected 2)}}
var notgeneric : Int<Float> // expected-error{{cannot specialize non-generic type 'Int'}}{{21-28=}}
var notgenericNested : Array<Int<Float>> // expected-error{{cannot specialize non-generic type 'Int'}}{{33-40=}}
// Make sure that redundant typealiases (that map to the same
// underlying type) don't break protocol conformance or use.
class XArray : ExpressibleByArrayLiteral {
typealias Element = Int
init() { }
required init(arrayLiteral elements: Int...) { }
}
class YArray : XArray {
typealias Element = Int
required init(arrayLiteral elements: Int...) {
super.init()
}
}
var yarray : YArray = [1, 2, 3]
var xarray : XArray = [1, 2, 3]
// Type parameters can be referenced only via unqualified name lookup
struct XParam<T> { // expected-note{{'XParam' declared here}}
func foo(_ x: T) {
_ = x as T
}
static func bar(_ x: T) {
_ = x as T
}
}
var xp : XParam<Int>.T = Int() // expected-error{{'T' is not a member type of generic struct 'generic_types.XParam<Swift.Int>'}}
// Diagnose failure to meet a superclass requirement.
class X1 { }
class X2<T : X1> { } // expected-note{{requirement specified as 'T' : 'X1' [with T = X3]}}
class X3 { }
var x2 : X2<X3> // expected-error{{'X2' requires that 'X3' inherit from 'X1'}}
protocol P {
associatedtype AssocP
}
protocol Q {
associatedtype AssocQ
}
struct X4 : P, Q {
typealias AssocP = Int
typealias AssocQ = String
}
struct X5<T, U> where T: P, T: Q, T.AssocP == T.AssocQ { } // expected-note{{requirement specified as 'T.AssocP' == 'T.AssocQ' [with T = X4]}}
var y: X5<X4, Int> // expected-error{{'X5' requires the types 'X4.AssocP' (aka 'Int') and 'X4.AssocQ' (aka 'String') be equivalent}}
// Recursive generic signature validation.
class Top {}
class Bottom<T : Bottom<Top>> {}
// expected-error@-1 {{'Bottom' requires that 'Top' inherit from 'Bottom<Top>'}}
// expected-note@-2 {{requirement specified as 'T' : 'Bottom<Top>' [with T = Top]}}
// expected-error@-3 *{{generic class 'Bottom' has self-referential generic requirements}}
// Invalid inheritance clause
struct UnsolvableInheritance1<T : T.A> {}
// expected-error@-1 {{'A' is not a member type of type 'T'}}
struct UnsolvableInheritance2<T : U.A, U : T.A> {}
// expected-error@-1 {{'A' is not a member type of type 'U'}}
// expected-error@-2 {{'A' is not a member type of type 'T'}}
enum X7<T> where X7.X : G { case X } // expected-error{{enum case 'X' is not a member type of 'X7<T>'}}
// expected-error@-1{{cannot find type 'G' in scope}}
// Test that contextual type resolution for generic metatypes is consistent
// under a same-type constraint.
protocol MetatypeTypeResolutionProto {}
struct X8<T> {
static var property1: T.Type { T.self }
static func method1() -> T.Type { T.self }
}
extension X8 where T == MetatypeTypeResolutionProto {
static var property2: T.Type { property1 } // ok, still .Protocol
static func method2() -> T.Type { method1() } // ok, still .Protocol
}
| 00fdaf62f5827370ac7e87a35dd8f252 | 24.661479 | 148 | 0.643973 | false | false | false | false |
oskarpearson/rileylink_ios | refs/heads/dev | MinimedKit/PumpEvents/ChangeSensorSetup2PumpEvent.swift | mit | 2 | //
// ChangeSensorSetup2PumpEvent.swift
// RileyLink
//
// Created by Pete Schwamb on 3/8/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct ChangeSensorSetup2PumpEvent: TimestampedPumpEvent {
public let length: Int
public let rawData: Data
public let timestamp: DateComponents
public init?(availableData: Data, pumpModel: PumpModel) {
if pumpModel.hasLowSuspend {
length = 41
} else {
length = 37
}
guard length <= availableData.count else {
return nil
}
rawData = availableData.subdata(in: 0..<length)
timestamp = DateComponents(pumpEventData: availableData, offset: 2)
}
public var dictionaryRepresentation: [String: Any] {
return [
"_type": "ChangeSensorSetup2",
]
}
}
| 0b2201575ec1a31301d066756bf198fb | 23.081081 | 75 | 0.612795 | false | false | false | false |
edx/edx-app-ios | refs/heads/master | Source/ProfilePictureTaker.swift | apache-2.0 | 1 | //
// ProfilePictureTaker.swift
// edX
//
// Created by Michael Katz on 10/1/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
import MobileCoreServices
protocol ProfilePictureTakerDelegate : AnyObject {
func showImagePickerController(picker: UIImagePickerController)
func showChooserAlert(alert: UIAlertController)
func imagePicked(image: UIImage, picker: UIImagePickerController)
func cancelPicker(picker: UIImagePickerController)
func deleteImage()
}
class ProfilePictureTaker : NSObject {
weak var delegate: ProfilePictureTakerDelegate?
init(delegate: ProfilePictureTakerDelegate) {
self.delegate = delegate
}
func start(alreadyHasImage: Bool) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let action = UIAlertAction(title: Strings.Profile.takePicture, style: .default) { _ in
self.showImagePicker(sourceType: .camera)
}
alert.addAction(action)
}
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let action = UIAlertAction(title: Strings.Profile.chooseExisting, style: .default) { _ in
self.showImagePicker(sourceType: .photoLibrary)
}
alert.addAction(action)
}
if alreadyHasImage {
let action = UIAlertAction(title: Strings.Profile.removeImage, style: .destructive) { _ in
self.delegate?.deleteImage()
}
alert.addAction(action)
}
alert.addCancelAction()
delegate?.showChooserAlert(alert: alert)
}
private func showImagePicker(sourceType : UIImagePickerController.SourceType) {
let imagePicker = UIImagePickerController()
let mediaType: String = kUTTypeImage as String
imagePicker.mediaTypes = [mediaType]
imagePicker.sourceType = sourceType
imagePicker.delegate = self
if sourceType == .camera {
imagePicker.showsCameraControls = true
imagePicker.cameraCaptureMode = .photo
imagePicker.cameraDevice = .front
imagePicker.cameraFlashMode = .auto
}
self.delegate?.showImagePickerController(picker: imagePicker)
}
}
extension ProfilePictureTaker : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
let rotatedImage = image.rotateUp()
let cropper = CropViewController(image: rotatedImage) { [weak self] maybeImage in
if let newImage = maybeImage {
self?.delegate?.imagePicked(image: newImage, picker: picker)
} else {
self?.delegate?.cancelPicker(picker: picker)
}
}
picker.pushViewController(cropper, animated: true)
} else {
fatalError("no image returned from picker")
}
}
}
| 223503b89396c33ffdded27362223c85 | 34.170213 | 144 | 0.649425 | false | false | false | false |
tedgoddard/Augra | refs/heads/master | Augra/ModelLoader.swift | mit | 1 | //
// ModelLoader.swift
// Augra
//
// Created by Ted Goddard on 2016-09-08.
//
import Foundation
import SceneKit
import SceneKit.ModelIO
class ModelLoader {
let environmentScene: SCNScene?
var fanRadius = Double(4)
var modelClamp = Float(2)
init(environmentScene: SCNScene?) {
self.environmentScene = environmentScene
}
func addAssortedMesh() {
let daeURLs = Bundle.main.urls(forResourcesWithExtension: "dae", subdirectory: "ARassets.scnassets")
let objURLs = Bundle.main.urls(forResourcesWithExtension: "obj", subdirectory: "ARassets.scnassets")
var modelURLs: [URL] = []
modelURLs += daeURLs ?? []
modelURLs += objURLs ?? []
if let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let userURLs = (try? FileManager.default.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: []))
modelURLs += userURLs ?? []
}
for (index, modelURL) in modelURLs.enumerated() {
//partition arc equally and count endpoints to balance it
let theta = Double(index + 1) / Double(modelURLs.count + 2) * (Double.pi * 2.0)
let fanPosition = SCNVector3(x: -1 * Float(fanRadius * sin(theta)), y: 1.0, z: Float(fanRadius * cos(theta)))
let importedModel = clampAndPlaceModel(url: modelURL, atPosition: fanPosition)
// debugBubble(modelNode: importedModel)
}
}
func clampAndPlaceModel(url: URL, atPosition: SCNVector3) -> SCNNode? {
let modelScene = try? SCNScene(url: url, options: nil)
guard let sceneRoot = modelScene?.rootNode else {
print("import FAIL \(url)")
return nil
}
guard let modelNode = sceneRoot.childNodes.first else { return nil }
modelNode.name = url.lastPathComponent
let (modelCenter, modelRadius) = modelNode.boundingSphere
if (modelRadius > modelClamp) {
modelNode.scale = scale(SCNVector3(x: 1, y: 1, z: 1), modelClamp / modelRadius)
}
modelNode.position = atPosition
print("added model \(modelNode.name) \(atPosition)")
environmentScene?.rootNode.addChildNode(modelNode)
return modelNode
}
func debugBubble(modelNode: SCNNode?, color: UIColor = .green) {
guard let modelNode = modelNode else { return }
let sphere = SCNNode()
sphere.geometry = SCNSphere(radius: CGFloat(modelNode.boundingSphere.radius))
sphere.position = modelNode.boundingSphere.center
sphere.geometry?.firstMaterial?.diffuse.contents = color.withAlphaComponent(0.5)
modelNode.addChildNode(sphere)
}
func debugBox(modelNode: SCNNode?, color: UIColor = .green) {
guard let modelNode = modelNode else { return }
let boxNode = SCNNode()
let boundingBoxEnds = modelNode.boundingBox
let boundingBox = SCNBox()
let boundingDelta = sum(boundingBoxEnds.max, scale(boundingBoxEnds.min, -1))
boundingBox.width = CGFloat(boundingDelta.x)
boundingBox.height = CGFloat(boundingDelta.y)
boundingBox.length = CGFloat(boundingDelta.z)
boxNode.geometry = boundingBox
boxNode.position = sum(boundingBoxEnds.min, scale(boundingDelta, 0.5))
boxNode.geometry?.firstMaterial?.diffuse.contents = color.withAlphaComponent(0.5)
modelNode.addChildNode(boxNode)
}
}
| 42a38044885a3018f204bd865d0c3ab9 | 39.045977 | 137 | 0.65729 | false | false | false | false |
bugcoding/macOSCalendar | refs/heads/master | MacCalendar/CalendarUtils.swift | gpl-2.0 | 1 | /*====================
FileName : CalendarUtils
Desc : Utils Function For Calendar 天体运算部分移植自<算法的乐趣 -- 王晓华> 书中示例代码
Author : bugcode
Email : [email protected]
CreateDate : 2016-5-8
====================*/
import Foundation
import Darwin
open class CalendarUtils{
// 单例
class var sharedInstance : CalendarUtils{
struct Static{
static let ins:CalendarUtils = CalendarUtils()
}
return Static.ins
}
fileprivate init(){
}
// 每天的时间结构
struct WZDayTime{
// 年月日时分秒
var year:Int = 0
var month:Int = 0
var day:Int = 0
var hour:Int = 0
var minute:Int = 0
var second:Double = 0
init(_ y: Int, _ m: Int, _ d: Int) {
year = y
month = m
day = d
}
public var description : String {
return "\(year)-" + "\(month)-" + "\(day)"
}
}
// 根据当前日期获取下一个节日
func getNextHolidayBy(wzTime: WZDayTime) -> (String, Int) {
let res = wzTime.month * 100 + wzTime.day
var holidayName = ""
var days = 0
for key in CalendarConstant.generalHolidaysArray {
if res < key {
let (name, month, day) = CalendarConstant.generalHolidaysDict[key]!
holidayName = name
days = CalendarUtils.sharedInstance.calcDaysBetweenDate(wzTime.year, monthStart: wzTime.month, dayStart: wzTime.day, yearEnd: wzTime.year, monthEnd: month, dayEnd: day)
break
}
}
return (holidayName, days)
}
// 根据农历月与农历日获取农历节日名称,没有返回空字符串
func getLunarFestivalNameBy(month: Int, day: Int) -> String {
let combineStr = String(month) + "-" + String(day)
if let festivalName = CalendarConstant.lunarHolidaysDict[combineStr] {
return festivalName
} else {
return ""
}
}
// 获取公历假日名称,如果不是假日返回空字符串
func getHolidayNameBy(month: Int, day: Int) -> String {
let combineStr = String(month) + "-" + String(day)
if let holidayName = CalendarConstant.georiHolidaysDict[combineStr] {
//print("name = \(holidayName)")
return holidayName
} else {
return ""
}
}
// 蔡勒公式算公历某天的星期
func getWeekDayBy(_ year:Int, month m:Int, day d:Int) -> Int {
var year = year
var m = m
if m < 3 {
year -= 1
m += 12
}
// 年份的最后二位. 2003 -> 03 | 1997 -> 97
let y:Int = year % 100
// 年份的前二位. 2003 -> 20 | 1997 -> 19
let c:Int = Int(year / 100)
var week:Int = Int(c / 4) - 2 * c + y + Int(y / 4) + (26 * (m + 1) / 10) + d - 1
week = (week % 7 + 7) % 7
return week
}
// 根据当前年月日获取下个节气的序号
func getNextJieqiNumBy(calendar: LunarCalendarUtils, month: Int, day: Int) -> Int {
var next = 0
var count = 0
var year = calendar.getCurrentYear()
var dayCount = day
var monthCount = month
// 循环到找到下一个节气为止
while true {
// 节气一般相差十五天左右,30天为容错,足够找到下一个节气了
count += 1
if count > 30 {
break
}
// 当前的农历日期
let mi = calendar.getMonthInfo(month: monthCount)
let dayInfo = mi.getDayInfo(day: dayCount)
// 当前日期就是节气
if dayInfo.st != -1 {
next = dayInfo.st
break
}
// 此月份天数
let days = getDaysBy(year: year, month: monthCount)
dayCount += 1
if dayCount > days {
dayCount = 1
monthCount += 1
if monthCount > 12 {
year += 1
monthCount = 1
}
}
}
//print("getNextJieqiNum = next = \(next) termName = \(CalendarConstant.nameOfJieQi[next])")
return next
}
// 根据当前日期获取当前所属于的节令月
func getLunarJieqiMonthNameBy(calendar: LunarCalendarUtils, month: Int, day: Int) -> Int {
var jieqiMonthName = 0
let nextJieqi = getNextJieqiNumBy(calendar: calendar, month: month, day: day)
switch nextJieqi {
case 22 ... 23:
jieqiMonthName = 1
case 0 ... 1:
jieqiMonthName = 2
case 2 ... 3:
jieqiMonthName = 3
case 4 ... 5:
jieqiMonthName = 4
case 6 ... 7:
jieqiMonthName = 5
case 8 ... 9:
jieqiMonthName = 6
case 10 ... 11:
jieqiMonthName = 7
case 12 ... 13:
jieqiMonthName = 8
case 14 ... 15:
jieqiMonthName = 9
case 16 ... 17:
jieqiMonthName = 10
case 18 ... 19:
jieqiMonthName = 11
case 20 ... 21:
jieqiMonthName = 12
default:
jieqiMonthName = 0
}
//print("getLunarJieqiMonthNameBy = \(jieqiMonthName)")
return jieqiMonthName
}
// 通过2000年有基准获取某一农历年的干支
func getLunarYearNameBy(_ year:Int) -> (heaven:String, earthy:String, zodiac:String){
let baseMinus:Int = year - 2000
var heavenly = (7 + baseMinus) % 10
var earth = (5 + baseMinus) % 12
if heavenly <= 0 {
heavenly += 10
}
if earth <= 0 {
earth += 12
}
return (CalendarConstant.HEAVENLY_STEMS_NAME[heavenly - 1], CalendarConstant.EARTHY_BRANCHES_NAME[earth - 1], CalendarConstant.CHINESE_ZODIC_NAME[earth - 1])
}
// 根据年,月,获取月干支
func getLunarMonthNameBy(calendar: LunarCalendarUtils, month: Int, day: Int) -> (heaven: String, earthy: String) {
var sbMonth:Int = 0, sbDay:Int = 0
var year = calendar.getCurrentYear()
// 算出农历年干支,以立春为界
calendar.getSpringBeginDay(month: &sbMonth, day: &sbDay)
year = (month >= sbMonth) ? year : year - 1
let baseMinus:Int = year - 2000
var heavenly = (7 + baseMinus) % 10
let curJieqiMonth = CalendarUtils.sharedInstance.getLunarJieqiMonthNameBy(calendar: calendar, month: month, day: day)
if heavenly <= 0 {
heavenly += 10
}
var monthHeavenly = ((heavenly * 2) + curJieqiMonth) % 10
if monthHeavenly <= 0 {
monthHeavenly = 10
}
return (CalendarConstant.HEAVENLY_STEMS_NAME[monthHeavenly - 1], CalendarConstant.EARTHY_MONTH_NAME[curJieqiMonth - 1])
}
// 获取日干支
func getLunarDayNameBy(year: Int, month: Int, day: Int) -> (heaven:String, earthy:String) {
var year = year
var month = month
if month == 1 || month == 2 {
month += 12
year -= 1
}
let x = Int(year / 100)
let y = year % 100
// 日 干 计算
let res = (5 * (x + y) + Int(x / 4) + Int(y / 4) + (month + 1) * 3 / 5 + day - 3 - x)
var dayHeavenly = res % 10
if dayHeavenly == 0 {
dayHeavenly = 10
}
// 日 支 计算
let i = (month % 2 != 0) ? 0 : 6
var dayEarthy = (res + 4 * x + 10 + i) % 12
if dayEarthy == 0 {
dayEarthy = 12
}
return (CalendarConstant.HEAVENLY_STEMS_NAME[dayHeavenly - 1], CalendarConstant.EARTHY_BRANCHES_NAME[dayEarthy - 1])
}
// 平,闫年判定
func getIsLeapBy(_ year:Int) -> Bool {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
// 指定月份的天数
func getDaysBy(year:Int, month: Int) -> Int {
var days = 0
if getIsLeapBy(year) {
days = CalendarConstant.DAYS_OF_MONTH_LEAP_YEAR[month]
}
else{
days = CalendarConstant.DAYS_OF_MONTH_NORMAL_YEAR[month]
}
return days
}
// 今天的日期
func getDateStringOfToday() -> String {
let nowDate = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let dateString = formatter.string(from: nowDate)
return dateString
}
// 根据日期字符串 yyyy-mm-dd形式获取(year,month,day)的元组
func getYMDTuppleBy(_ dateString:String) -> (year:Int, month:Int, day:Int) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let date = formatter.date(from: dateString)
formatter.dateFormat = "yyyy"
let y = formatter.string(from: date!)
formatter.dateFormat = "MM"
let m = formatter.string(from: date!)
formatter.dateFormat = "dd"
let d = formatter.string(from: date!)
return (Int(y)!, Int(m)!, Int(d)!)
}
// 手动切分日期字符串
func manualSplitDate(_ dateString: String) -> (year:Int, month:Int, day:Int) {
let strArr = dateString.components(separatedBy: "-")
let year = strArr[0]
let month = strArr[1]
let day = strArr[2]
return (Int(year)!, Int(month)!, Int(day)!)
}
// 根据传入日期字符串获取下月
func getMonthDateStringBy(year: Int, month: Int, step:Int) -> (year: Int, month: Int) {
var year = year
var curMonth = month
curMonth = curMonth + step
if curMonth > 12 && step > 0 {
curMonth = 1
year = year + 1
}
else if curMonth < 1 && step < 0{
curMonth = 12
year = year - 1
}
return (year, curMonth)
}
// 月份增减的时候保证天数不超出当月的最大天数
func fixMonthDays(year: Int, month: Int, day: Int) -> Int {
var retDay = day
let days = getDaysOfMonthBy(year, month: month)
if day > days {
retDay = days
}
return retDay
}
// 获取某月某天是周几
func getWeekBy(year: Int, month: Int, andFirstDay:Int) -> Int {
let weekDay = getWeekDayBy(year, month: month, day: andFirstDay)
return weekDay
}
// 获取一个月有几天
func getDaysOfMonthBy(_ year:Int, month:Int) -> Int {
if month < 1 || month > 12 {
return 0
}
if getIsLeapBy(year) {
return CalendarConstant.DAYS_OF_MONTH_LEAP_YEAR[month]
}
return CalendarConstant.DAYS_OF_MONTH_NORMAL_YEAR[month]
}
// 计算一年中过去的天数,含指定的这天
func calcYearPassDays(_ year:Int, month:Int, day:Int) -> Int {
var passedDays = 0
for i in 0 ..< month - 1 {
if getIsLeapBy(year) {
passedDays += CalendarConstant.DAYS_OF_MONTH_LEAP_YEAR[i]
}else{
passedDays += CalendarConstant.DAYS_OF_MONTH_NORMAL_YEAR[i]
}
}
passedDays += day
return passedDays
}
// 计算一年剩下的天数,不含指定的这天
func calcYearRestDays(_ year:Int, month:Int, day:Int) -> Int{
var leftDays = 0
if getIsLeapBy(year) {
leftDays = CalendarConstant.DAYS_OF_MONTH_LEAP_YEAR[month] - day
}else{
leftDays = CalendarConstant.DAYS_OF_MONTH_NORMAL_YEAR[month] - day
}
for i in month ..< CalendarConstant.MONTHES_FOR_YEAR {
if getIsLeapBy(year) {
leftDays += CalendarConstant.DAYS_OF_MONTH_LEAP_YEAR[i]
}else{
leftDays += CalendarConstant.DAYS_OF_MONTH_NORMAL_YEAR[i]
}
}
return leftDays
}
// 计算二个年份之间的天数 前面包含元旦,后面不包含
func calcYearsDays(_ yearStart:Int, yearEnd:Int) -> Int {
var days = 0
for i in yearStart ..< yearEnd {
if getIsLeapBy(i) {
days += CalendarConstant.DAYS_OF_LEAP_YEAR
}else{
days += CalendarConstant.DAYS_OF_NORMAL_YEAR
}
}
return days
}
// 计算二个指定日期之间的天数
func calcDaysBetweenDate(_ yearStart:Int, monthStart:Int, dayStart:Int, yearEnd:Int, monthEnd:Int, dayEnd:Int) -> Int {
var days = calcYearRestDays(yearStart, month: monthStart, day: dayStart)
if yearStart != yearEnd {
if yearEnd - yearStart >= 2 {
days += calcYearsDays(yearStart + 1, yearEnd: yearEnd)
}
days += calcYearPassDays(yearEnd, month: monthEnd, day: dayEnd)
}else{
days -= calcYearRestDays(yearEnd, month: monthEnd, day: dayEnd)
}
return days
}
// 判定日期是否使用了格里历
func isGregorianDays(_ year:Int, month:Int, day:Int) -> Bool {
if year < CalendarConstant.GREGORIAN_CALENDAR_OPEN_YEAR {
return false
}
if year == CalendarConstant.GREGORIAN_CALENDAR_OPEN_YEAR {
if (month < CalendarConstant.GREGORIAN_CALENDAR_OPEN_MONTH)
|| (month == CalendarConstant.GREGORIAN_CALENDAR_OPEN_MONTH && day < CalendarConstant.GREGORIAN_CALENDAR_OPEN_DAY){
return false
}
}
return true
}
// 计算儒略日
func calcJulianDay(_ year:Int, month:Int, day:Int, hour:Int, min:Int, second:Double) -> Double {
var year = year
var month = month
if month <= 2 {
month += 12
year -= 1
}
var B = -2
if isGregorianDays(year, month: month, day: day) {
B = year / 400 - year / 100
}
let a = 365.25 * Double(year)
let b = 30.6001 * Double(month + 1)
let sec:Double = Double(hour) / 24.0 + Double(min) / 1440.0 + Double(second) / 86400.0
let param:Double = Double(Int(a)) + Double(Int(b)) + Double(B) + Double(day)
let res = param + sec + 1720996.5
return res
}
// 儒略日获得日期
func getDayTimeFromJulianDay(_ jd:Double, dt:inout WZDayTime){
var cna:Int, cnd:Int
var cnf:Double
let jdf:Double = jd + 0.5
cna = Int(jdf)
cnf = jdf - Double(cna)
if cna > 2299161 {
cnd = Int((Double(cna) - 1867216.25) / 36524.25)
cna = cna + 1 + cnd - Int(cnd / 4)
}
cna = cna + 1524
var year = Int((Double(cna) - 122.1) / 365.25)
cnd = cna - Int(Double(year) * 365.25)
var month = Int(Double(cnd) / 30.6001)
let day = cnd - Int(Double(month) * 30.6001)
year -= 4716
month = month - 1
if month > 12 {
month -= 12
}
if month <= 2 {
year += 1
}
if year < 1 {
year -= 1
}
cnf = cnf * 24.0
dt.hour = Int(cnf)
cnf = cnf - Double(dt.hour)
cnf *= 60.0
dt.minute = Int(cnf)
cnf = cnf - Double(dt.minute)
dt.second = cnf * 60.0
dt.year = year
dt.month = month
dt.day = day
}
// 360度转换
func mod360Degree(_ degrees:Double) -> Double {
var dbValue:Double = degrees
while dbValue < 0.0{
dbValue += 360.0
}
while dbValue > 360.0{
dbValue -= 360.0
}
return dbValue
}
// 角度转弧度
func degree2Radian(_ degree:Double) -> Double {
return degree * CalendarConstant.PI / 180.0
}
// 弧度转角度
func radian2Degree(_ radian:Double) -> Double {
return radian * 180.0 / CalendarConstant.PI
}
func getEarthNutationParameter(dt:Double, D:inout Double, M:inout Double, Mp:inout Double, F:inout Double, Omega:inout Double) {
// T是从J2000起算的儒略世纪数
let T = dt * 10
let T2 = T * T
let T3 = T2 * T
// 平距角(如月对地心的角距离)
D = 297.85036 + 445267.111480 * T - 0.0019142 * T2 + T3 / 189474.0
// 太阳(地球)平近点角
M = 357.52772 + 35999.050340 * T - 0.0001603 * T2 - T3 / 300000.0
// 月亮平近点角
Mp = 134.96298 + 477198.867398 * T + 0.0086972 * T2 + T3 / 56250.0
// 月亮纬度参数
F = 93.27191 + 483202.017538 * T - 0.0036825 * T2 + T3 / 327270.0
// 黄道与月亮平轨道升交点黄经
Omega = 125.04452 - 1934.136261 * T + 0.0020708 * T2 + T3 / 450000.0
}
// 计算某时刻的黄经章动干扰量,dt是儒略千年数,返回值单位是度
func calcEarthLongitudeNutation(dt:Double) -> Double {
let T = dt * 10
var D:Double = 0.0, M:Double = 0.0, Mp:Double = 0.0, F:Double = 0.0, Omega:Double = 0.0
getEarthNutationParameter(dt: dt, D: &D, M: &M, Mp: &Mp, F: &F, Omega: &Omega)
var resulte = 0.0
for i in 0 ..< CalendarConstant.nutation.count {
var sita = CalendarConstant.nutation[i].D * D + CalendarConstant.nutation[i].M * M + CalendarConstant.nutation[i].Mp * Mp + CalendarConstant.nutation[i].F * F + CalendarConstant.nutation[i].omega * Omega
sita = degree2Radian(sita)
resulte += (CalendarConstant.nutation[i].sine1 + CalendarConstant.nutation[i].sine2 * T ) * sin(sita)
}
/*先乘以章动表的系数 0.0001,然后换算成度的单位*/
return resulte * 0.0001 / 3600.0
}
/*计算某时刻的黄赤交角章动干扰量,dt是儒略千年数,返回值单位是度*/
func calcEarthObliquityNutation(dt:Double) -> Double {
// T是从J2000起算的儒略世纪数
let T = dt * 10
var D = 0.0, M = 0.0, Mp = 0.0, F = 0.0, Omega = 0.0
getEarthNutationParameter(dt:dt, D: &D, M: &M, Mp: &Mp, F: &F, Omega: &Omega)
var resulte = 0.0
for i in 0 ..< CalendarConstant.nutation.count {
var sita = CalendarConstant.nutation[i].D * D + CalendarConstant.nutation[i].M * M + CalendarConstant.nutation[i].Mp * Mp + CalendarConstant.nutation[i].F * F + CalendarConstant.nutation[i].omega * Omega
sita = degree2Radian(sita)
resulte += (CalendarConstant.nutation[i].cosine1 + CalendarConstant.nutation[i].cosine2 * T ) * cos(sita)
}
// 先乘以章动表的系数 0.001,然后换算成度的单位
return resulte * 0.0001 / 3600.0
}
// 利用已知节气推算其它节气的函数,st的值以小寒节气为0,大寒为1,其它节气类推
func calculateSolarTermsByExp(year:Int, st:Int) -> Double {
if st < 0 || st > 24 {
return 0.0
}
let stJd = 365.24219878 * Double(year - 1900) + CalendarConstant.stAccInfo[st] / 86400.0
return CalendarConstant.base1900SlightColdJD + stJd
}
/*
moved from <算法的乐趣 - 王晓华> 示例代码
计算节气和朔日的经验公式
当天到1900年1月0日(星期日)的差称为积日,那么第y年(1900算0年)第x个节气的积日是:
F = 365.242 * y + 6.2 + 15.22 *x - 1.9 * sin(0.262 * x)
从1900年开始的第m个朔日的公式是:
M = 1.6 + 29.5306 * m + 0.4 * sin(1 - 0.45058 * m)
*/
func calculateSolarTermsByFm(year:Int, st:Int) -> Double {
let baseJD = calcJulianDay(1900, month: 1, day: 1, hour: 0, min: 0, second: 0.0) - 1
let y = year - 1900
let tmp = 15.22 * Double(st) - 1.0 * sin(0.262 * Double(st))
let accDay = 365.2422 * Double(y) + 6.2 + tmp
return baseJD + accDay
}
func calculateNewMoonByFm(m:Int) -> Double {
let baseJD = calcJulianDay(1900, month: 1, day: 1, hour: 0, min: 0, second: 0.0) - 1
let accDay = 1.6 + 29.5306 * Double(m) + 0.4 * sin(1 - 0.45058 * Double(m))
return baseJD + accDay
}
func calcPeriodicTerm(coff:[PlanetData.VSOP87_COEFFICIENT], count:Int, dt:Double) -> Double {
var val = 0.0
for i in 0 ..< count {
val += (coff[i].A * cos((coff[i].B + coff[i].C * dt)))
}
return val
}
// 计算太阳的地心黄经(度),dt是儒略千年数
func calcSunEclipticLongitudeEC(dt:Double) -> Double {
let L0 = calcPeriodicTerm(coff: PlanetData.Earth_L0, count: PlanetData.Earth_L0.count, dt: dt)
let L1 = calcPeriodicTerm(coff: PlanetData.Earth_L1, count: PlanetData.Earth_L1.count, dt: dt)
let L2 = calcPeriodicTerm(coff: PlanetData.Earth_L2, count: PlanetData.Earth_L2.count, dt: dt)
let L3 = calcPeriodicTerm(coff: PlanetData.Earth_L3, count: PlanetData.Earth_L3.count, dt: dt)
let L4 = calcPeriodicTerm(coff: PlanetData.Earth_L4, count: PlanetData.Earth_L4.count, dt: dt)
let L5 = calcPeriodicTerm(coff: PlanetData.Earth_L5, count: PlanetData.Earth_L5.count, dt: dt)
let L = (((((L5 * dt + L4) * dt + L3) * dt + L2) * dt + L1) * dt + L0) / 100000000.0
// 地心黄经 = 日心黄经 + 180度
return (mod360Degree(mod360Degree(L / CalendarConstant.RADIAN_PER_ANGLE) + 180.0))
}
func calcSunEclipticLatitudeEC(dt:Double) -> Double {
let B0 = calcPeriodicTerm(coff: PlanetData.Earth_B0, count: PlanetData.Earth_B0.count, dt: dt)
let B1 = calcPeriodicTerm(coff: PlanetData.Earth_B1, count: PlanetData.Earth_B1.count, dt: dt)
let B2 = calcPeriodicTerm(coff: PlanetData.Earth_B2, count: PlanetData.Earth_B2.count, dt: dt)
let B3 = calcPeriodicTerm(coff: PlanetData.Earth_B3, count: PlanetData.Earth_B3.count, dt: dt)
let B4 = calcPeriodicTerm(coff: PlanetData.Earth_B4, count: PlanetData.Earth_B4.count, dt: dt)
let B = (((((B4 * dt) + B3) * dt + B2) * dt + B1) * dt + B0) / 100000000.0
// 地心黄纬 = -日心黄纬
return -(B / CalendarConstant.RADIAN_PER_ANGLE)
}
/*修正太阳的地心黄经,longitude, latitude 是修正前的太阳地心黄经和地心黄纬(度),dt是儒略千年数,返回值单位度*/
func adjustSunEclipticLongitudeEC(dt:Double, longitude:Double, latitude:Double) -> Double {
//T是儒略世纪数
let T = dt * 10
var dbLdash = longitude - 1.397 * T - 0.00031 * T * T
// 转换为弧度
dbLdash *= Double(CalendarConstant.RADIAN_PER_ANGLE)
return (-0.09033 + 0.03916 * (cos(dbLdash) + sin(dbLdash)) * tan(latitude * CalendarConstant.RADIAN_PER_ANGLE)) / 3600.0
}
/*修正太阳的地心黄纬,longitude是修正前的太阳地心黄经(度),dt是儒略千年数,返回值单位度*/
func adjustSunEclipticLatitudeEC(dt:Double, longitude:Double) -> Double {
//T是儒略世纪数
let T = dt * 10
var dLdash = longitude - 1.397 * T - 0.00031 * T * T
// 转换为弧度
dLdash *= CalendarConstant.RADIAN_PER_ANGLE
return (0.03916 * (cos(dLdash) - sin(dLdash))) / 3600.0
}
func calcSunEarthRadius(dt:Double) -> Double {
let R0 = calcPeriodicTerm(coff: PlanetData.Earth_R0, count: PlanetData.Earth_R0.count, dt: dt)
let R1 = calcPeriodicTerm(coff: PlanetData.Earth_R1, count: PlanetData.Earth_R1.count, dt: dt)
let R2 = calcPeriodicTerm(coff: PlanetData.Earth_R2, count: PlanetData.Earth_R2.count, dt: dt)
let R3 = calcPeriodicTerm(coff: PlanetData.Earth_R3, count: PlanetData.Earth_R3.count, dt: dt)
let R4 = calcPeriodicTerm(coff: PlanetData.Earth_R4, count: PlanetData.Earth_R4.count, dt: dt)
let R = (((((R4 * dt) + R3) * dt + R2) * dt + R1) * dt + R0) / 100000000.0
return R
}
// 得到某个儒略日的太阳地心黄经(视黄经),单位度
func getSunEclipticLongitudeEC(jde:Double) -> Double {
// 儒略千年数
let dt = (jde - CalendarConstant.JD2000) / 365250.0
// 计算太阳的地心黄经
var longitude = calcSunEclipticLongitudeEC(dt: dt)
// 计算太阳的地心黄纬
let latitude = calcSunEclipticLatitudeEC(dt: dt) * 3600.0
// 修正精度
longitude += adjustSunEclipticLongitudeEC(dt: dt, longitude: longitude, latitude: latitude)
// 修正天体章动
longitude += calcEarthLongitudeNutation(dt: dt)
// 修正光行差
/*太阳地心黄经光行差修正项是: -20".4898/R*/
longitude -= (20.4898 / calcSunEarthRadius(dt: dt)) / 3600.0
return longitude
}
// 得到某个儒略日的太阳地心黄纬(视黄纬),单位度
func getSunEclipticLatitudeEC(jde:Double) -> Double {
// 儒略千年数
let dt = (jde - CalendarConstant.JD2000) / 365250.0
// 计算太阳的地心黄经
let longitude = calcSunEclipticLongitudeEC(dt: dt)
// 计算太阳的地心黄纬
var latitude = calcSunEclipticLatitudeEC(dt: dt) * 3600.0
// 修正精度
let delta = adjustSunEclipticLatitudeEC(dt: dt, longitude: longitude)
latitude += delta * 3600.0
return latitude
}
func getMoonEclipticParameter(dt:Double, Lp:inout Double, D: inout Double, M: inout Double, Mp:inout Double, F: inout Double, E: inout Double) {
// T是从J2000起算的儒略世纪数
let T = dt
let T2 = T * T
let T3 = T2 * T
let T4 = T3 * T
// 月球平黄经
Lp = 218.3164591 + 481267.88134236 * T - 0.0013268 * T2 + T3/538841.0 - T4 / 65194000.0
Lp = mod360Degree(Lp)
// 月日距角
D = 297.8502042 + 445267.1115168 * T - 0.0016300 * T2 + T3 / 545868.0 - T4 / 113065000.0
D = mod360Degree(D)
// 太阳平近点角
M = 357.5291092 + 35999.0502909 * T - 0.0001536 * T2 + T3 / 24490000.0
M = mod360Degree(M)
// 月亮平近点角
Mp = 134.9634114 + 477198.8676313 * T + 0.0089970 * T2 + T3 / 69699.0 - T4 / 14712000.0
Mp = mod360Degree(Mp)
// 月球经度参数(到升交点的平角距离)
F = 93.2720993 + 483202.0175273 * T - 0.0034029 * T2 - T3 / 3526000.0 + T4 / 863310000.0
F = mod360Degree(F)
E = 1 - 0.002516 * T - 0.0000074 * T2
}
// 计算月球地心黄经周期项的和
func calcMoonECLongitudePeriodic(D: Double, M: Double, Mp: Double, F: Double, E: Double) -> Double {
var EI = 0.0
for i in 0 ..< PlanetData.Moon_longitude.count {
var sita = PlanetData.Moon_longitude[i].D * D + PlanetData.Moon_longitude[i].M * M + PlanetData.Moon_longitude[i].Mp * Mp + PlanetData.Moon_longitude[i].F * F
sita = degree2Radian(sita)
EI += (PlanetData.Moon_longitude[i].eiA * sin(sita) * pow(E, fabs(PlanetData.Moon_longitude[i].M)))
}
return EI
}
// 计算月球地心黄纬周期项的和
func calcMoonECLatitudePeriodicTbl(D: Double, M: Double, Mp: Double, F: Double, E: Double) -> Double {
var EB = 0.0
for i in 0 ..< PlanetData.moon_Latitude.count {
var sita = PlanetData.moon_Latitude[i].D * D + PlanetData.moon_Latitude[i].M * M + PlanetData.moon_Latitude[i].Mp * Mp + PlanetData.moon_Latitude[i].F * F
sita = degree2Radian(sita)
EB += (PlanetData.moon_Latitude[i].eiA * sin(sita) * pow(E, fabs(PlanetData.Moon_longitude[i].M)))
}
return EB
}
// 计算月球地心距离周期项的和
func calcMoonECDistancePeriodicTbl(D: Double, M: Double, Mp: Double, F: Double, E: Double) -> Double {
var ER = 0.0
for i in 0 ..< PlanetData.Moon_longitude.count {
var sita = PlanetData.Moon_longitude[i].D * D + PlanetData.Moon_longitude[i].M * M + PlanetData.Moon_longitude[i].Mp * Mp + PlanetData.Moon_longitude[i].F * F
sita = degree2Radian(sita)
ER += (PlanetData.Moon_longitude[i].erA * cos(sita) * pow(E, fabs(PlanetData.Moon_longitude[i].M)))
}
return ER
}
// 计算金星摄动,木星摄动以及地球扁率摄动对月球地心黄经的影响,dt 是儒略世纪数,Lp和F单位是度
func calcMoonLongitudePerturbation(dt: Double, Lp: Double, F: Double) -> Double {
// T是从J2000起算的儒略世纪数
let T = dt
var A1 = 119.75 + 131.849 * T
var A2 = 53.09 + 479264.290 * T
A1 = mod360Degree(A1)
A2 = mod360Degree(A2)
var result = 3958.0 * sin(degree2Radian(A1))
result += (1962.0 * sin(degree2Radian(Lp - F)))
result += (318.0 * sin(degree2Radian(A2)))
return result
}
// 计算金星摄动,木星摄动以及地球扁率摄动对月球地心黄纬的影响,dt 是儒略世纪数,Lp、Mp和F单位是度
func calcMoonLatitudePerturbation(dt: Double, Lp: Double, F: Double, Mp: Double) -> Double {
// T是从J2000起算的儒略世纪数
let T = dt
var A1 = 119.75 + 131.849 * T
var A3 = 313.45 + 481266.484 * T
A1 = mod360Degree(A1)
A3 = mod360Degree(A3)
var result = -2235.0 * sin(degree2Radian(Lp))
result += (382.0 * sin(degree2Radian(A3)))
result += (175.0 * sin(degree2Radian(A1 - F)))
result += (175.0 * sin(degree2Radian(A1 + F)))
result += (127.0 * sin(degree2Radian(Lp - Mp)))
result += (115.0 * sin(degree2Radian(Lp + Mp)))
return result
}
func getMoonEclipticLongitudeEC(dbJD: Double) -> Double {
var Lp:Double = 0.0, D:Double = 0.0, M:Double = 0.0, Mp:Double = 0.0, F:Double = 0.0, E:Double = 0.0
// 儒略世纪数
let dt = (dbJD - CalendarConstant.JD2000) / 36525.0
getMoonEclipticParameter(dt: dt, Lp: &Lp, D: &D, M: &M, Mp: &Mp, F: &F, E: &E)
// 计算月球地心黄经周期项
var EI = calcMoonECLongitudePeriodic(D: D, M: M, Mp: Mp, F: F, E: E)
// 修正金星,木星以及地球扁率摄动
EI += calcMoonLongitudePerturbation(dt: dt, Lp: Lp, F: F)
// 计算月球地心黄经
var longitude = Lp + EI / 1000000.0
// 计算天体章动干扰
longitude += calcEarthLongitudeNutation(dt: dt / 10.0)
// 映射到0-360范围内
longitude = mod360Degree(longitude)
return longitude
}
func getMoonEclipticLatitudeEC(dbJD: Double) -> Double {
// 儒略世纪数
let dt = (dbJD - CalendarConstant.JD2000) / 36525.0
var Lp = 0.0, D = 0.0, M = 0.0, Mp = 0.0, F = 0.0, E = 0.0
getMoonEclipticParameter(dt: dt, Lp: &Lp, D: &D, M: &M, Mp: &Mp, F: &F, E: &E)
// 计算月球地心黄纬周期项
var EB = calcMoonECLatitudePeriodicTbl(D: D, M: M, Mp: Mp, F: F, E: E)
// 修正金星,木星以及地球扁率摄动
EB += calcMoonLatitudePerturbation(dt: dt, Lp: Lp, F: F, Mp: Mp)
// 计算月球地心黄纬*/
let latitude = EB / 1000000.0
return latitude
}
func getMoonEarthDistance(dbJD: Double) -> Double {
// 儒略世纪数
let dt = (dbJD - CalendarConstant.JD2000) / 36525.0
var Lp = 0.0, D = 0.0, M = 0.0, Mp = 0.0, F = 0.0, E = 0.0
getMoonEclipticParameter(dt: dt, Lp: &Lp, D: &D, M: &M, Mp: &Mp, F: &F, E: &E)
// 计算月球地心距离周期项
let ER = calcMoonECDistancePeriodicTbl(D: D, M: M, Mp: Mp, F: F, E: E)
// 计算月球地心黄纬
let distance = 385000.56 + ER / 1000.0
return distance
}
func getInitialEstimateSolarTerms(year: Int, angle: Int) -> Double {
var STMonth = Int(ceil(Double((Double(angle) + 90.0) / 30.0)))
STMonth = STMonth > 12 ? STMonth - 12 : STMonth
// 每月第一个节气发生日期基本都4-9日之间,第二个节气的发生日期都在16-24日之间
if (angle % 15 == 0) && (angle % 30 != 0) {
return calcJulianDay(year, month: STMonth, day: 6, hour: 12, min: 0, second: 0.0)
}else{
return calcJulianDay(year, month: STMonth, day: 20, hour: 12, min: 0, second: 0.0)
}
}
// 计算指定年份的任意节气,angle是节气在黄道上的读数
// 返回指定节气的儒略日时间(力学时)
func calculateSolarTerms(year: Int, angle: Int) -> Double {
var JD0:Double, JD1:Double, stDegree:Double, stDegreep:Double
JD1 = getInitialEstimateSolarTerms(year: year, angle: angle)
repeat
{
JD0 = JD1
stDegree = getSunEclipticLongitudeEC(jde: JD0)
/*
对黄经0度迭代逼近时,由于角度360度圆周性,估算黄经值可能在(345,360]和[0,15)两个区间,
如果值落入前一个区间,需要进行修正
*/
stDegree = ((angle == 0) && (stDegree > 345.0)) ? stDegree - 360.0 : stDegree
stDegreep = (getSunEclipticLongitudeEC(jde: Double(JD0) + 0.000005) - getSunEclipticLongitudeEC(jde: Double(JD0) - 0.000005)) / 0.00001
JD1 = JD0 - (stDegree - Double(angle)) / stDegreep
//print("getInitialEstimateSolarTerms JD1-JD0 = \(JD1 - JD0)")
}while((fabs(JD1 - JD0) > 0.0000001))
return JD1
}
/*
得到给定的时间后面第一个日月合朔的时间,平均误差小于3秒
输入参数是指定时间的力学时儒略日数
返回值是日月合朔的力学时儒略日数
*/
func calculateMoonShuoJD(tdJD: Double) -> Double {
var JD0:Double, JD1:Double, stDegree:Double, stDegreep:Double
var count = 0
JD1 = tdJD
repeat
{
JD0 = JD1
var moonLongitude = getMoonEclipticLongitudeEC(dbJD: JD0)
var sunLongitude = getSunEclipticLongitudeEC(jde: JD0)
if (moonLongitude > 330.0) && (sunLongitude < 30.0) {
sunLongitude = 360.0 + sunLongitude
}
if (sunLongitude > 330.0) && (moonLongitude < 30.0) {
moonLongitude = 60.0 + moonLongitude
}
stDegree = moonLongitude - sunLongitude
if(stDegree >= 360.0){
stDegree -= 360.0
}
if(stDegree < -360.0) {
stDegree += 360.0
}
stDegreep = (getMoonEclipticLongitudeEC(dbJD: JD0 + 0.000005) - getSunEclipticLongitudeEC(jde: JD0 + 0.000005) - getMoonEclipticLongitudeEC(dbJD: JD0 - 0.000005) + getSunEclipticLongitudeEC(jde: JD0 - 0.000005)) / 0.00001
JD1 = JD0 - stDegree / stDegreep
count += 1
if count > 500 {
break
}
}while((fabs(JD1 - JD0) > 0.00000001))
return JD1
}
// 根据年份计算农历干支与生肖
func calculateStemsBranches(year: Int, stems: inout Int, branches: inout Int) {
let sc = year - 2000
stems = (7 + sc) % 10
branches = (5 + sc) % 12
if stems < 0 {
stems += 10
}
if branches <= 0 {
branches += 12
}
}
// TD - UT1 误差校验结构
private struct TD_UTC_DELTA{
var year: Int
var d1:Double, d2: Double, d3: Double, d4: Double
init(_ year: Int, _ d1: Double, _ d2: Double, _ d3: Double, _ d4: Double) {
self.year = year
self.d1 = d1
self.d2 = d2
self.d3 = d3
self.d4 = d4
}
}
// TD - UT1 误差计算表
private static let deltaTbl:[TD_UTC_DELTA] = [
TD_UTC_DELTA( -4000, 108371.7,-13036.80,392.000, 0.0000 ),
TD_UTC_DELTA( -500, 17201.0, -627.82, 16.170,-0.3413 ),
TD_UTC_DELTA( -150, 12200.6, -346.41, 5.403,-0.1593 ),
TD_UTC_DELTA( 150, 9113.8, -328.13, -1.647, 0.0377 ),
TD_UTC_DELTA( 500, 5707.5, -391.41, 0.915, 0.3145 ),
TD_UTC_DELTA( 900, 2203.4, -283.45, 13.034,-0.1778 ),
TD_UTC_DELTA( 1300, 490.1, -57.35, 2.085,-0.0072 ),
TD_UTC_DELTA( 1600, 120.0, -9.81, -1.532, 0.1403 ),
TD_UTC_DELTA( 1700, 10.2, -0.91, 0.510,-0.0370 ),
TD_UTC_DELTA( 1800, 13.4, -0.72, 0.202,-0.0193 ),
TD_UTC_DELTA( 1830, 7.8, -1.81, 0.416,-0.0247 ),
TD_UTC_DELTA( 1860, 8.3, -0.13, -0.406, 0.0292 ),
TD_UTC_DELTA( 1880, -5.4, 0.32, -0.183, 0.0173 ),
TD_UTC_DELTA( 1900, -2.3, 2.06, 0.169,-0.0135 ),
TD_UTC_DELTA( 1920, 21.2, 1.69, -0.304, 0.0167 ),
TD_UTC_DELTA( 1940, 24.2, 1.22, -0.064, 0.0031 ),
TD_UTC_DELTA( 1960, 33.2, 0.51, 0.231,-0.0109 ),
TD_UTC_DELTA( 1980, 51.0, 1.29, -0.026, 0.0032 ),
TD_UTC_DELTA( 2000, 63.87, 0.1, 0.0, 0.0 ),
TD_UTC_DELTA( 2005, 0.0, 0.0, 0.0, 0.0 )
]
func deltaExt(y: Double, jsd: Int) -> Double {
let dy = (y - 1820.0) / 100.0
return -20.0 + Double(jsd) * dy * dy
}
func tdUtcDeltaT(y: Double) -> Double {
if y >= 2005 {
let y1: Int = 2014
let sd = 0.4
let jsd: Int = 31
if y <= Double(y1) {
return 64.7 + (y - 2005) * sd
}
var v = deltaExt(y: y, jsd: jsd)
let dv = deltaExt(y: Double(y1), jsd: jsd) - (64.7 + Double(y1 - 2005) * sd)
if y < Double(y1) + 100 {
v -= dv * (Double(y1) + 100 - y) / 100
}
return v
} else {
var i = 0
for flag in 0 ..< CalendarUtils.deltaTbl.count {
i = flag
if y < Double(CalendarUtils.deltaTbl[i + 1].year) {
break
}
}
let t1 = Double(y - Double(CalendarUtils.deltaTbl[i].year)) / Double(CalendarUtils.deltaTbl[i + 1].year - CalendarUtils.deltaTbl[i].year) * 10.0
let t2 = t1 * t1
let t3 = t2 * t1
return CalendarUtils.deltaTbl[i].d1 + CalendarUtils.deltaTbl[i].d2 * t1 + CalendarUtils.deltaTbl[i].d3 * t2 + CalendarUtils.deltaTbl[i].d4 * t3
}
}
func tdUtcDeltaT2(jd2k: Double) -> Double {
return tdUtcDeltaT(y: jd2k / 365.2425 + 2000) / 86400.0
}
// 本地时间转utc
func jdLocalTimetoUTC(localJD: Double) -> Double {
let tz = NSTimeZone.default
let secs = -tz.secondsFromGMT()
return localJD + Double(secs) / 86400.0
}
// utc转本地时间
func jdUTCToLocalTime(utcJD: Double) -> Double {
let tz = NSTimeZone.default
let secs = -tz.secondsFromGMT()
return utcJD - Double(secs) / 86400.0
}
func jdTDtoUTC(tdJD: Double) -> Double {
var _tdJD = tdJD
let jd2k = tdJD - CalendarConstant.JD2000
let tian = tdUtcDeltaT2(jd2k: jd2k)
_tdJD -= tian
return _tdJD
}
func jdTDtoLocalTime(tdJD: Double) -> Double {
let tmp = jdTDtoUTC(tdJD: tdJD)
return jdUTCToLocalTime(utcJD: tmp)
}
func jdUTCtoTD(utcJD: Double) -> Double {
var _utcJD = utcJD
let jd2k = utcJD - CalendarConstant.JD2000
let tian = tdUtcDeltaT2(jd2k: jd2k)
_utcJD += tian
return _utcJD
}
func jdLocalTimetoTD(localJD: Double) -> Double {
let tmp = jdLocalTimetoUTC(localJD: localJD)
return jdUTCtoTD(utcJD: tmp)
}
}
| 988538c4b3d0182349bc85114bb9c9f8 | 31.87069 | 233 | 0.526619 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io | refs/heads/master | Carthage/Checkouts/Alamofire/Source/Request.swift | apache-2.0 | 22 | //
// Request.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
public protocol RequestAdapter {
/// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result.
///
/// - parameter urlRequest: The URL request to adapt.
///
/// - throws: An `Error` if the adaptation encounters an error.
///
/// - returns: The adapted `URLRequest`.
func adapt(_ urlRequest: URLRequest) throws -> URLRequest
}
// MARK: -
/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not.
public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void
/// A type that determines whether a request should be retried after being executed by the specified session manager
/// and encountering an error.
public protocol RequestRetrier {
/// Determines whether the `Request` should be retried by calling the `completion` closure.
///
/// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
/// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
/// cleaned up after.
///
/// - parameter manager: The session manager the request was executed on.
/// - parameter request: The request that failed due to the encountered error.
/// - parameter error: The error encountered when executing the request.
/// - parameter completion: The completion closure to be executed when retry decision has been determined.
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion)
}
// MARK: -
protocol TaskConvertible {
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask
}
/// A dictionary of headers to apply to a `URLRequest`.
public typealias HTTPHeaders = [String: String]
// MARK: -
/// Responsible for sending a request and receiving the response and associated data from the server, as well as
/// managing its underlying `URLSessionTask`.
open class Request {
// MARK: Helper Types
/// A closure executed when monitoring upload or download progress of a request.
public typealias ProgressHandler = (Progress) -> Void
enum RequestTask {
case data(TaskConvertible?, URLSessionTask?)
case download(TaskConvertible?, URLSessionTask?)
case upload(TaskConvertible?, URLSessionTask?)
case stream(TaskConvertible?, URLSessionTask?)
}
// MARK: Properties
/// The delegate for the underlying task.
open internal(set) var delegate: TaskDelegate {
get {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
return taskDelegate
}
set {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
taskDelegate = newValue
}
}
/// The underlying task.
open var task: URLSessionTask? { return delegate.task }
/// The session belonging to the underlying task.
open let session: URLSession
/// The request sent or to be sent to the server.
open var request: URLRequest? { return task?.originalRequest }
/// The response received from the server, if any.
open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse }
/// The number of times the request has been retried.
open internal(set) var retryCount: UInt = 0
let originalTask: TaskConvertible?
var startTime: CFAbsoluteTime?
var endTime: CFAbsoluteTime?
var validations: [() -> Void] = []
private var taskDelegate: TaskDelegate
private var taskDelegateLock = NSLock()
// MARK: Lifecycle
init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
self.session = session
switch requestTask {
case .data(let originalTask, let task):
taskDelegate = DataTaskDelegate(task: task)
self.originalTask = originalTask
case .download(let originalTask, let task):
taskDelegate = DownloadTaskDelegate(task: task)
self.originalTask = originalTask
case .upload(let originalTask, let task):
taskDelegate = UploadTaskDelegate(task: task)
self.originalTask = originalTask
case .stream(let originalTask, let task):
taskDelegate = TaskDelegate(task: task)
self.originalTask = originalTask
}
delegate.error = error
delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
}
// MARK: Authentication
/// Associates an HTTP Basic credential with the request.
///
/// - parameter user: The user.
/// - parameter password: The password.
/// - parameter persistence: The URL credential persistence. `.ForSession` by default.
///
/// - returns: The request.
@discardableResult
open func authenticate(
user: String,
password: String,
persistence: URLCredential.Persistence = .forSession)
-> Self
{
let credential = URLCredential(user: user, password: password, persistence: persistence)
return authenticate(usingCredential: credential)
}
/// Associates a specified credential with the request.
///
/// - parameter credential: The credential.
///
/// - returns: The request.
@discardableResult
open func authenticate(usingCredential credential: URLCredential) -> Self {
delegate.credential = credential
return self
}
/// Returns a base64 encoded basic authentication credential as an authorization header tuple.
///
/// - parameter user: The user.
/// - parameter password: The password.
///
/// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise.
open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? {
guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }
let credential = data.base64EncodedString(options: [])
return (key: "Authorization", value: "Basic \(credential)")
}
// MARK: State
/// Resumes the request.
open func resume() {
guard let task = task else { delegate.queue.isSuspended = false ; return }
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
task.resume()
NotificationCenter.default.post(
name: Notification.Name.Task.DidResume,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Suspends the request.
open func suspend() {
guard let task = task else { return }
task.suspend()
NotificationCenter.default.post(
name: Notification.Name.Task.DidSuspend,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Cancels the request.
open func cancel() {
guard let task = task else { return }
task.cancel()
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
}
// MARK: - CustomStringConvertible
extension Request: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the HTTP method and URL, as
/// well as the response status code if a response has been received.
open var description: String {
var components: [String] = []
if let HTTPMethod = request?.httpMethod {
components.append(HTTPMethod)
}
if let urlString = request?.url?.absoluteString {
components.append(urlString)
}
if let response = response {
components.append("(\(response.statusCode))")
}
return components.joined(separator: " ")
}
}
// MARK: - CustomDebugStringConvertible
extension Request: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, in the form of a cURL command.
open var debugDescription: String {
return cURLRepresentation()
}
func cURLRepresentation() -> String {
var components = ["$ curl -v"]
guard let request = self.request,
let url = request.url,
let host = url.host
else {
return "$ curl command could not be created"
}
if let httpMethod = request.httpMethod, httpMethod != "GET" {
components.append("-X \(httpMethod)")
}
if let credentialStorage = self.session.configuration.urlCredentialStorage {
let protectionSpace = URLProtectionSpace(
host: host,
port: url.port ?? 0,
protocol: url.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
for credential in credentials {
guard let user = credential.user, let password = credential.password else { continue }
components.append("-u \(user):\(password)")
}
} else {
if let credential = delegate.credential, let user = credential.user, let password = credential.password {
components.append("-u \(user):\(password)")
}
}
}
if session.configuration.httpShouldSetCookies {
if
let cookieStorage = session.configuration.httpCookieStorage,
let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
{
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
#if swift(>=3.2)
components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"")
#else
components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
#endif
}
}
var headers: [AnyHashable: Any] = [:]
if let additionalHeaders = session.configuration.httpAdditionalHeaders {
for (field, value) in additionalHeaders where field != AnyHashable("Cookie") {
headers[field] = value
}
}
if let headerFields = request.allHTTPHeaderFields {
for (field, value) in headerFields where field != "Cookie" {
headers[field] = value
}
}
for (field, value) in headers {
let escapedValue = String(describing: value).replacingOccurrences(of: "\"", with: "\\\"")
components.append("-H \"\(field): \(escapedValue)\"")
}
if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(url.absoluteString)\"")
return components.joined(separator: " \\\n\t")
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDataTask`.
open class DataRequest: Request {
// MARK: Helper Types
struct Requestable: TaskConvertible {
let urlRequest: URLRequest
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let urlRequest = try self.urlRequest.adapt(using: adapter)
return queue.sync { session.dataTask(with: urlRequest) }
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
if let requestable = originalTask as? Requestable { return requestable.urlRequest }
return nil
}
/// The progress of fetching the response data from the server for the request.
open var progress: Progress { return dataDelegate.progress }
var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
// MARK: Stream
/// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
///
/// This closure returns the bytes most recently received from the server, not including data from previous calls.
/// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
/// also important to note that the server data in any `Response` object will be `nil`.
///
/// - parameter closure: The code to be executed periodically during the lifecycle of the request.
///
/// - returns: The request.
@discardableResult
open func stream(closure: ((Data) -> Void)? = nil) -> Self {
dataDelegate.dataStream = closure
return self
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
dataDelegate.progressHandler = (closure, queue)
return self
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
open class DownloadRequest: Request {
// MARK: Helper Types
/// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
/// destination URL.
public struct DownloadOptions: OptionSet {
/// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
public let rawValue: UInt
/// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
/// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
/// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
///
/// - parameter rawValue: The raw bitmask value for the option.
///
/// - returns: A new log level instance.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
}
/// A closure executed once a download request has successfully completed in order to determine where to move the
/// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
/// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
/// the options defining how the file should be moved.
public typealias DownloadFileDestination = (
_ temporaryURL: URL,
_ response: HTTPURLResponse)
-> (destinationURL: URL, options: DownloadOptions)
enum Downloadable: TaskConvertible {
case request(URLRequest)
case resumeData(Data)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .request(urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.downloadTask(with: urlRequest) }
case let .resumeData(resumeData):
task = queue.sync { session.downloadTask(withResumeData: resumeData) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable {
return urlRequest
}
return nil
}
/// The resume data of the underlying download task if available after a failure.
open var resumeData: Data? { return downloadDelegate.resumeData }
/// The progress of downloading the response data from the server for the request.
open var progress: Progress { return downloadDelegate.progress }
var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
// MARK: State
/// Cancels the request.
open override func cancel() {
downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task as Any]
)
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
downloadDelegate.progressHandler = (closure, queue)
return self
}
// MARK: Destination
/// Creates a download file destination closure which uses the default file manager to move the temporary file to a
/// file URL in the first available directory with the specified search path directory and search path domain mask.
///
/// - parameter directory: The search path directory. `.DocumentDirectory` by default.
/// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
///
/// - returns: A download file destination closure.
open class func suggestedDownloadDestination(
for directory: FileManager.SearchPathDirectory = .documentDirectory,
in domain: FileManager.SearchPathDomainMask = .userDomainMask)
-> DownloadFileDestination
{
return { temporaryURL, response in
let directoryURLs = FileManager.default.urls(for: directory, in: domain)
if !directoryURLs.isEmpty {
return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
}
return (temporaryURL, [])
}
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
open class UploadRequest: DataRequest {
// MARK: Helper Types
enum Uploadable: TaskConvertible {
case data(Data, URLRequest)
case file(URL, URLRequest)
case stream(InputStream, URLRequest)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .data(data, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, from: data) }
case let .file(url, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) }
case let .stream(_, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
guard let uploadable = originalTask as? Uploadable else { return nil }
switch uploadable {
case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest):
return urlRequest
}
}
/// The progress of uploading the payload to the server for the upload request.
open var uploadProgress: Progress { return uploadDelegate.uploadProgress }
var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
// MARK: Upload Progress
/// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
/// the server.
///
/// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
/// of data being read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is sent to the server.
///
/// - returns: The request.
@discardableResult
open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
uploadDelegate.uploadProgressHandler = (closure, queue)
return self
}
}
// MARK: -
#if !os(watchOS)
/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open class StreamRequest: Request {
enum Streamable: TaskConvertible {
case stream(hostName: String, port: Int)
case netService(NetService)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
let task: URLSessionTask
switch self {
case let .stream(hostName, port):
task = queue.sync { session.streamTask(withHostName: hostName, port: port) }
case let .netService(netService):
task = queue.sync { session.streamTask(with: netService) }
}
return task
}
}
}
#endif
| 4c17b9cb307ea708614b714c9703a502 | 36.203364 | 131 | 0.641979 | false | false | false | false |
turekj/ReactiveTODO | refs/heads/master | ReactiveTODOFramework/Classes/Logic/Messages/Impl/MessageImageFactory.swift | mit | 1 | import Foundation
class MessageImageFactory: MessageImageFactoryProtocol {
let bundle: NSBundle
let priorityFormatter: PriorityImageNameFormatterProtocol
let outputImageSize: CGSize
init(bundle: NSBundle, priorityFormatter: PriorityImageNameFormatterProtocol,
outputImageSize: CGSize) {
self.bundle = bundle
self.priorityFormatter = priorityFormatter
self.outputImageSize = outputImageSize
}
func createMessageImage(note: TODONote) -> UIImage {
let priorityIcon = self.priorityIcon(note)
UIGraphicsBeginImageContextWithOptions(self.outputImageSize, false, 0.0)
let context = UIGraphicsGetCurrentContext()!
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillRect(context, CGRect(origin: CGPointMake(0, 0), size: self.outputImageSize))
priorityIcon.drawInRect(self.priorityIconDrawRect(priorityIcon))
let img = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return img
}
private func priorityIcon(note: TODONote) -> UIImage {
let priorityIconName = self.priorityFormatter.format(note.priority)
return UIImage(named: priorityIconName,
inBundle: self.bundle,
compatibleWithTraitCollection: nil)!
}
private func priorityIconDrawRect(priorityIcon: UIImage) -> CGRect {
let x = (self.outputImageSize.width - priorityIcon.size.width) * 0.5
let y = (self.outputImageSize.height - priorityIcon.size.height) * 0.5
let width = priorityIcon.size.width
let height = priorityIcon.size.height
return CGRectMake(x, y, width, height)
}
}
| e9eab6c8d43d56e2f0f68135e1d88d94 | 37.12766 | 97 | 0.68192 | false | false | false | false |
jakeshi01/IFlySpeechPackage | refs/heads/master | IFlyTest/IFlyTest/SpeechRecognizerAdapter.swift | mit | 1 | //
// SpeechRecognizerAdapter.swift
// IFlyTest
//
// Created by Jake on 2017/7/4.
// Copyright © 2017年 Jake. All rights reserved.
//
import Foundation
import UIKit
class SpeechRecognizerAdapter: NSObject {
fileprivate var speechRecognizer: SpeechRecognizeable = SpeechRecognizer()
fileprivate var recognizeResult: String = ""
fileprivate var finishTask: Task?
fileprivate var isCanceled: Bool = false
var recognizerBar: SpeechRecognizerControl? {
didSet{
recognizerBar?.delegate = self
}
}
var handleView: SpeechRecognizeAction? {
didSet{
handleView?.finishAction = { [weak self] in
self?.recognizerBar?.speechBtn.isUserInteractionEnabled = true
}
}
}
override init() {
super.init()
speechRecognizer.delegate = self
}
}
extension SpeechRecognizerAdapter: SpeechRecognizerControlDelegate {
func beginSpeech() {
let isBegin = speechRecognizer.startListening()
guard isBegin else { return }
if let task = finishTask {
cancel(task)
}
cancel(finishTask)
handleView?.isCancelHidden = true
handleView?.showAnimation()
handleView?.beginSpeechAction()
}
func willCancelSpeech() {
handleView?.cancelSpeechAction()
}
func resumeSpeech() {
handleView?.resumeSpeechAction()
}
func speechEnd() {
handleView?.endSpeechAction()
speechRecognizer.stopListening()
}
func speechCanceled() {
isCanceled = true
handleView?.dismissAnimation()
speechRecognizer.cancelSpeech()
handleView?.endSpeechAction()
}
}
extension SpeechRecognizerAdapter: SpeechRecognizerDelegate {
func onError(_ errorCode: IFlySpeechError) {
handleView?.isCancelHidden = false
finishTask = delay(1.0, task: { [weak self] in
self?.handleView?.dismissAnimation()
})
print("errorCode = \(errorCode.errorDesc)")
if errorCode.errorCode == SpeechError.successCode.rawValue {
//此处用于解决讯飞第一次短暂识别(单击,无语音)无数据(错误码应该为10118时)实际返回errorCode = 0的问题
guard recognizeResult.characters.count == 0 else {
recognizeResult = ""
return
}
handleView?.setRecognizeResult("未识别到语音")
recognizeResult = ""
} else if errorCode.errorCode == SpeechError.networkDisableCode.rawValue {
//没有网络
} else if errorCode.errorCode == SpeechError.recordDisabelCode.rawValue {
//录音初始化失败
} else{
handleView?.setRecognizeResult("未识别到语音")
}
}
func onResults(_ recognizeResult: String) {
self.recognizeResult = recognizeResult
handleView?.setRecognizeResult(recognizeResult)
}
func onEndOfSpeech() {
print("识别中")
speechEnd()
guard !isCanceled else { return }
handleView?.showProgressHud()
//识别期间禁止再次点击语音
recognizerBar?.speechBtn.isUserInteractionEnabled = false
}
func onCancel() {
print("取消识别")
}
func onVolumeChanged(_ value: Int32) {
handleView?.speechAnimation(with: value)
}
}
| 04c966951b2e80541d7a61bf300d4758 | 26.278689 | 82 | 0.610276 | false | false | false | false |
Ethenyl/JAMFKit | refs/heads/master | JamfKit/Tests/Models/HardwareGroup/HardwareGroupTests.swift | mit | 1 | //
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
import XCTest
@testable import JamfKit
class HardwareGroupTests: XCTestCase {
// MARK: - Constants
let subfolder = "ComputerGroup/"
let defaultIdentifier: UInt = 12345
let defaultName = "computers"
let defaultIsSmart = true
// MARK: - Tests
func testShouldInstantiate() {
let actualValue = HardwareGroup(identifier: defaultIdentifier, name: defaultName)
XCTAssertNotNil(actualValue)
XCTAssertEqual(actualValue?.identifier, defaultIdentifier)
XCTAssertEqual(actualValue?.name, defaultName)
}
func testShouldNotInstantiateWithInvalidParameters() {
let actualValue = HardwareGroup(identifier: defaultIdentifier, name: "")
XCTAssertNil(actualValue)
}
}
| 7504598b38f0c6f76ce618a066e2b7f2 | 25.911765 | 102 | 0.713661 | false | true | false | false |
stripe/stripe-ios | refs/heads/master | IntegrationTester/IntegrationTester/Views/CardSetupIntentsView.swift | mit | 1 | //
// CardSetupIntentsView.swift
// IntegrationTester
//
// Created by David Estes on 2/8/21.
//
import SwiftUI
import Stripe
struct CardSetupIntentsView: View {
@StateObject var model = MySIModel()
@State var isConfirmingSetupIntent = false
@State var paymentMethodParams: STPPaymentMethodParams?
var body: some View {
VStack {
STPPaymentCardTextField.Representable(paymentMethodParams: $paymentMethodParams)
.padding()
if let setupIntent = model.intentParams {
Button("Setup") {
setupIntent.paymentMethodParams = paymentMethodParams
isConfirmingSetupIntent = true
}.setupIntentConfirmationSheet(isConfirmingSetupIntent: $isConfirmingSetupIntent,
setupIntentParams: setupIntent,
onCompletion: model.onCompletion)
.disabled(isConfirmingSetupIntent || paymentMethodParams == nil)
} else {
ProgressView()
}
if let paymentStatus = model.paymentStatus {
PaymentHandlerStatusView(actionStatus: paymentStatus, lastPaymentError: model.lastPaymentError)
}
}.onAppear { model.prepareSetupIntent() }
}
}
struct CardSetupIntentsView_Preview : PreviewProvider {
static var previews: some View {
CardSetupIntentsView()
}
}
| 87f3da7264e8337561ae00625ed255cf | 31.309524 | 105 | 0.665438 | false | false | false | false |
kantega/tech-ex-2015 | refs/heads/master | ios/TechEx/views/TechexTextField.swift | mit | 1 | //
// TechexTextField.swift
// TechEx
//
// Created by Kristian Lier Selnæs on 18/02/15.
// Copyright (c) 2015 Technoport. All rights reserved.
//
import UIKit
class TechexTextField: UITextField {
let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);
override func textRectForBounds(bounds: CGRect) -> CGRect {
return self.newBounds(bounds)
}
override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
return self.newBounds(bounds)
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return self.newBounds(bounds)
}
private func newBounds(bounds: CGRect) -> CGRect {
var newBounds = bounds
newBounds.origin.x += padding.left
newBounds.origin.y += padding.top
newBounds.size.height -= (padding.top * 2) - padding.bottom
newBounds.size.width -= (padding.left * 2) - padding.right
return newBounds
}
}
| fe93a70c024bab27f6d37f2634a9e72d | 24.842105 | 70 | 0.63442 | false | false | false | false |
gametimesf/GAMConstants | refs/heads/master | Source/GTStringsManager.swift | mit | 2 | //
// GTStringsManager.swift
// Gametime
//
// Created by Mike Silvis on 8/16/16.
//
//
import UIKit
public class GTStringsManager {
public static let sharedInstance = GTStringsManager()
public func string(key: String?) -> String {
guard let key = key else { return "" }
return find(key: key, safeToNotExist: false)
}
public func string(key: String?, args: CVaListPointer) -> String {
guard let key = key else { return "" }
return NSString(format: find(key: key, safeToNotExist: false), locale: Locale.current, arguments: args) as String
}
public func string(key: String?, safetoNotExist: Bool) -> String {
guard let key = key else { return "" }
return find(key: key, safeToNotExist: safetoNotExist)
}
//
// MARK: Finders
//
fileprivate func find(key: String, safeToNotExist: Bool) -> String {
if let string = findIntercepted(key: key) {
return string
}
return findLocalized(key: key, safeToNotExist: safeToNotExist)
}
fileprivate func findLocalized(key: String, safeToNotExist: Bool) -> String {
let string = NSLocalizedString(key, comment: "")
if string == key {
assert(safeToNotExist, "Key: \(key) does not exist. Please add it")
}
if safeToNotExist && string.isEmpty {
return key
}
return string
}
fileprivate func findIntercepted(key: String) -> String? {
return GTInterceptionManager.sharedInstance.hotFix(key: key)
}
}
// To be used by objc only
public class GTStringBridger: NSObject {
@objc public static func string(key: String) -> String {
return GTStringsManager.sharedInstance.string(key: key)
}
}
| 7088ffbe414cfcf3a7cf462d954082f2 | 24.73913 | 121 | 0.626689 | false | false | false | false |
safx/TypetalkKit | refs/heads/master | Example-iOS/Example-iOS/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// iOSExample
//
// Created by Safx Developer on 2014/09/17.
// Copyright (c) 2014年 Safx Developers. All rights reserved.
//
import UIKit
import TypetalkKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
//navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
_ = TypetalkAPI.setDeveloperSettings(
clientId: "Your ClientID",
clientSecret: "Your SecretID",
scopes: [Scope.my, Scope.topicRead], // e.g. typetalkkit://auth/success
redirectURI: "Your custome scheme")
_ = TypetalkAPI.restoreTokenFromAccountStore()
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if TypetalkAPI.isRedirectURL(url) {
if #available(iOS 9.0, *) {
if let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String?, sourceApplication == "com.apple.mobilesafari" {
return TypetalkAPI.authorizationDone(URL: url)
}
} else {
// Fallback on earlier versions
}
}
return false
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
}
| 37bfa3af8802f7b699a5cda7b4e347ec | 39.666667 | 191 | 0.674473 | false | false | false | false |
SteveKChiu/CoreDataMonk | refs/heads/master | CoreDataMonk/CoreDataExpression.swift | mit | 1 | //
// https://github.com/SteveKChiu/CoreDataMonk
//
// Copyright 2015, Steve K. Chiu <[email protected]>
//
// The MIT License (http://www.opensource.org/licenses/mit-license.php)
//
// 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 CoreData
//---------------------------------------------------------------------------
public struct CoreDataQuery {
let predicate: NSPredicate
private init(_ predicate: NSPredicate) {
self.predicate = predicate
}
public static func Where(_ format: String, _ args: Any...) -> CoreDataQuery {
return CoreDataQuery(NSPredicate(format: format, argumentArray: args))
}
public static func Where(_ predicate: NSPredicate) -> CoreDataQuery {
return CoreDataQuery(predicate)
}
}
public func && (lhs: CoreDataQuery, rhs: CoreDataQuery) -> CoreDataQuery {
return .Where(NSCompoundPredicate(type: .and, subpredicates: [ lhs.predicate, rhs.predicate ]))
}
public func || (lhs: CoreDataQuery, rhs: CoreDataQuery) -> CoreDataQuery {
return .Where(NSCompoundPredicate(type: .or, subpredicates: [ lhs.predicate, rhs.predicate ]))
}
public prefix func ! (lhs: CoreDataQuery) -> CoreDataQuery {
return .Where(NSCompoundPredicate(type: .not, subpredicates: [ lhs.predicate ]))
}
//---------------------------------------------------------------------------
public enum CoreDataQueryKey {
case key(String)
case keyModifier(String, NSComparisonPredicate.Modifier)
case keyPath([String])
var path: String {
switch self {
case let .key(path):
return path
case let .keyModifier(path, _):
return path
case let .keyPath(list):
var path = list.first!
for item in list[1 ..< list.count] {
path += "."
path += item
}
return path
}
}
var modifier: NSComparisonPredicate.Modifier {
switch self {
case let .keyModifier(_, mod):
return mod
default:
return .direct
}
}
var list: [String] {
switch self {
case let .key(path):
return [ path ]
case let .keyModifier(path, _):
return [ path ]
case let .keyPath(list):
return list
}
}
public var any: CoreDataQueryKey {
return .keyModifier(self.path, .any)
}
public var all: CoreDataQueryKey {
return .keyModifier(self.path, .all)
}
fileprivate func compare(_ op: NSComparisonPredicate.Operator, _ key: CoreDataQueryKey) -> CoreDataQuery {
return .Where(NSComparisonPredicate(
leftExpression: NSExpression(forKeyPath: self.path),
rightExpression: NSExpression(forKeyPath: key.path),
modifier: self.modifier,
type: op,
options: []))
}
fileprivate func compare(_ op: NSComparisonPredicate.Operator, _ value: Any) -> CoreDataQuery {
return .Where(NSComparisonPredicate(
leftExpression: NSExpression(forKeyPath: self.path),
rightExpression: NSExpression(forConstantValue: value),
modifier: self.modifier,
type: op,
options: []))
}
}
prefix operator %
postfix operator %
public prefix func % (key: CoreDataQueryKey) -> CoreDataQueryKey {
return key
}
public prefix func % (name: String) -> CoreDataQueryKey {
return CoreDataQueryKey.key(name)
}
public postfix func % (name: String) -> CoreDataQueryKey {
return CoreDataQueryKey.key(name)
}
public func | (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQueryKey {
return .keyPath(lhs.list + rhs.list)
}
public func == (lhs: CoreDataQueryKey, rhs: Any?) -> CoreDataQuery {
return lhs.compare(.equalTo, rhs ?? NSNull())
}
public func == (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery {
return lhs.compare(.equalTo, rhs)
}
public func != (lhs: CoreDataQueryKey, rhs: Any?) -> CoreDataQuery {
return lhs.compare(.notEqualTo, rhs ?? NSNull())
}
public func != (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery {
return lhs.compare(.notEqualTo, rhs)
}
public func > (lhs: CoreDataQueryKey, rhs: Any) -> CoreDataQuery {
return lhs.compare(.greaterThan, rhs)
}
public func > (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery {
return lhs.compare(.greaterThan, rhs)
}
public func < (lhs: CoreDataQueryKey, rhs: Any) -> CoreDataQuery {
return lhs.compare(.lessThan, rhs)
}
public func < (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery {
return lhs.compare(.lessThan, rhs)
}
public func >= (lhs: CoreDataQueryKey, rhs: Any) -> CoreDataQuery {
return lhs.compare(.greaterThanOrEqualTo, rhs)
}
public func >= (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery {
return lhs.compare(.greaterThanOrEqualTo, rhs)
}
public func <= (lhs: CoreDataQueryKey, rhs: Any) -> CoreDataQuery {
return lhs.compare(.lessThanOrEqualTo, rhs)
}
public func <= (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery {
return lhs.compare(.lessThanOrEqualTo, rhs)
}
//---------------------------------------------------------------------------
public struct CoreDataSelect {
fileprivate let descriptions: [Any]
fileprivate init(_ expression: Any) {
self.descriptions = [ expression ]
}
fileprivate init(_ expressions: [Any]) {
self.descriptions = expressions
}
private init(function: String, property: String, alias: String?, type: NSAttributeType) {
let key = NSExpression(forKeyPath: property)
let expression = NSExpression(forFunction: function, arguments: [ key ])
let description = NSExpressionDescription()
description.name = alias ?? property
description.expression = expression
description.expressionResultType = type
self.descriptions = [ description ]
}
public static func Select(_ keys: String...) -> CoreDataSelect {
return CoreDataSelect(keys)
}
public static func Expression(_ expression: NSExpressionDescription) -> CoreDataSelect {
return CoreDataSelect(expression)
}
public static func Sum(_ property: String, alias: String? = nil) -> CoreDataSelect {
return CoreDataSelect(function: "sum:", property: property, alias: alias, type: .decimalAttributeType)
}
public static func Average(_ property: String, alias: String? = nil) -> CoreDataSelect {
return CoreDataSelect(function: "average:", property: property, alias: alias, type: .decimalAttributeType)
}
public static func StdDev(_ property: String, alias: String? = nil) -> CoreDataSelect {
return CoreDataSelect(function: "stddev:", property: property, alias: alias, type: .decimalAttributeType)
}
public static func Count(_ property: String, alias: String? = nil) -> CoreDataSelect {
return CoreDataSelect(function: "count:", property: property, alias: alias, type: .integer64AttributeType)
}
public static func Max(_ property: String, alias: String? = nil) -> CoreDataSelect {
return CoreDataSelect(function: "max:", property: property, alias: alias, type: .undefinedAttributeType)
}
public static func Min(_ property: String, alias: String? = nil) -> CoreDataSelect {
return CoreDataSelect(function: "min:", property: property, alias: alias, type: .undefinedAttributeType)
}
public static func Median(_ property: String, alias: String? = nil) -> CoreDataSelect {
return CoreDataSelect(function: "median:", property: property, alias: alias, type: .undefinedAttributeType)
}
private func keyPathResultType(_ key: String, entity: NSEntityDescription) throws -> NSAttributeType {
if let r = key.range(of: ".") {
let name = key.substring(to: r.lowerBound)
let next = key.substring(from: key.index(after: r.lowerBound))
guard let relate = entity.relationshipsByName[name]?.destinationEntity else {
throw CoreDataError("Can not find relationship [\(name)] of [\(entity.name)]")
}
return try keyPathResultType(next, entity: relate)
}
guard let attr = entity.attributesByName[key] else {
throw CoreDataError("Can not find attribute [\(key)] of [\(entity.name)]")
}
return attr.attributeType
}
func resolve(_ entity: NSEntityDescription) throws -> [Any] {
var properties = [Any]()
for unknownDescription in self.descriptions {
if unknownDescription is String {
properties.append(unknownDescription)
continue
}
guard let description = unknownDescription as? NSExpressionDescription else {
throw CoreDataError("Can not resolve property \(unknownDescription)")
}
guard description.expressionResultType == .undefinedAttributeType else {
properties.append(description)
continue
}
let expression = description.expression!
switch expression.expressionType {
case .keyPath:
properties.append(expression.keyPath)
case .function:
guard let argument = expression.arguments?.first, argument.expressionType == .keyPath else {
throw CoreDataError("Can not resolve function result type unless its argument is key path: \(expression)")
}
description.expressionResultType = try keyPathResultType(argument.keyPath, entity: entity)
properties.append(description)
default:
throw CoreDataError("Can not resolve result type of expression: \(expression)")
}
}
return properties
}
}
public func | (lhs: CoreDataSelect, rhs: CoreDataSelect) -> CoreDataSelect {
return CoreDataSelect(lhs.descriptions + rhs.descriptions)
}
//---------------------------------------------------------------------------
public struct CoreDataOrderBy {
let descriptors: [NSSortDescriptor]
fileprivate init(_ descriptor: NSSortDescriptor) {
self.descriptors = [ descriptor ]
}
fileprivate init(_ descriptors: [NSSortDescriptor]) {
self.descriptors = descriptors
}
public static func Ascending(_ key: String) -> CoreDataOrderBy {
return CoreDataOrderBy(NSSortDescriptor(key: key, ascending: true))
}
public static func Ascending(_ key: String, selector: Selector) -> CoreDataOrderBy {
return CoreDataOrderBy(NSSortDescriptor(key: key, ascending: true, selector: selector))
}
public static func Descending(_ key: String) -> CoreDataOrderBy {
return CoreDataOrderBy(NSSortDescriptor(key: key, ascending: false))
}
public static func Descending(_ key: String, selector: Selector) -> CoreDataOrderBy {
return CoreDataOrderBy(NSSortDescriptor(key: key, ascending: false, selector: selector))
}
public static func Sort(_ descriptor: NSSortDescriptor) -> CoreDataOrderBy {
return CoreDataOrderBy(descriptor)
}
}
public func | (lhs: CoreDataOrderBy, rhs: CoreDataOrderBy) -> CoreDataOrderBy {
return CoreDataOrderBy(lhs.descriptors + rhs.descriptors)
}
//---------------------------------------------------------------------------
public enum CoreDataQueryOptions {
case noSubEntities
case noPendingChanges
case noPropertyValues
case limit(Int)
case offset(Int)
case batch(Int)
case prefetch([String])
case propertiesOnly([String])
case distinct
case tweak((Any) -> Void)
case multiple([CoreDataQueryOptions])
fileprivate var options: [CoreDataQueryOptions] {
switch self {
case let .multiple(list):
return list
default:
return [ self ]
}
}
func apply<T: NSFetchRequestResult>(_ request: NSFetchRequest<T>) throws {
switch self {
case .noSubEntities:
request.includesSubentities = false
case .noPendingChanges:
request.includesPendingChanges = false
case .noPropertyValues:
request.includesPropertyValues = false
case let .limit(limit):
request.fetchLimit = limit
case let .offset(offset):
request.fetchOffset = offset
case let .batch(size):
request.fetchBatchSize = size
case let .prefetch(keys):
request.relationshipKeyPathsForPrefetching = keys
case let .propertiesOnly(keys):
if request.resultType == .managedObjectResultType {
request.propertiesToFetch = keys
}
case .distinct:
request.returnsDistinctResults = true
case let .tweak(tweak):
tweak(request)
case let .multiple(list):
for option in list {
try option.apply(request)
}
}
}
}
public func | (lhs: CoreDataQueryOptions, rhs: CoreDataQueryOptions) -> CoreDataQueryOptions {
return .multiple(lhs.options + rhs.options)
}
| c85811562c1d25ba775f32cecd933e91 | 33.307512 | 126 | 0.62258 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/IRGen/objc_properties.swift | apache-2.0 | 4 | // This file is also used by objc_properties_ios.swift.
// RUN: %swift -target x86_64-apple-macosx10.11 %s -disable-target-os-checking -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-NEW %s
// RUN: %swift -target x86_64-apple-macosx10.10 %s -disable-target-os-checking -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-OLD %s
// REQUIRES: OS=macosx
// REQUIRES: objc_interop
@objc class SomeObject {
var readonly : SomeObject {
get {
return self
}
}
var readwrite : SomeObject {
get {
return bareIvar
}
set {
bareIvar = newValue
}
}
var bareIvar : SomeObject
@objc(wobble) var wibble : SomeObject
init() {
bareIvar = SomeObject()
wibble = SomeObject()
}
static var sharedProp: Int64 = 0
}
extension SomeObject {
var extensionProperty : SomeObject {
get {
return self
}
set {
bareIvar = self
}
}
class var extensionClassProp : SomeObject.Type {
return self
}
}
// <rdar://problem/16952186> Crash with @lazy in @objc class
@objc
class LazyPropertyCrash {
lazy var applicationFilesDirectory: LazyPropertyCrash = LazyPropertyCrash()
}
// <rdar://16909436>
@objc class Tree {
weak var parent: Tree?
}
// <rdar://problem/17127126> swift compiler segfaults trying to generate a setter for a @lazy property in a subclass of NSObject
func test17127126(f : Class17127126) {
f.x = 2 // this is the problem
}
@objc
class Class17127126 {
lazy var x = 1
}
@objc protocol Proto {
var value: Int { get }
static var sharedInstance: AnyObject { get set }
}
// CHECK-NEW: [[SHARED_NAME:@.*]] = private unnamed_addr constant [11 x i8] c"sharedProp\00"
// CHECK-NEW: [[SHARED_ATTRS:@.*]] = private unnamed_addr constant [17 x i8] c"Tq,N,VsharedProp\00"
// CHECK-NEW: @_CLASS_PROPERTIES__TtC15objc_properties10SomeObject = private constant { {{.*}}] } {
// CHECK-NEW: i32 16,
// CHECK-NEW: i32 1,
// CHECK-NEW: [1 x { i8*, i8* }] [{
// CHECK-NEW: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SHARED_NAME]], i64 0, i64 0),
// CHECK-NEW: i8* getelementptr inbounds ([17 x i8], [17 x i8]* [[SHARED_ATTRS]], i64 0, i64 0)
// CHECK-NEW: }]
// CHECK-NEW: }, section "__DATA, __objc_const", align 8
// CHECK: @_METACLASS_DATA__TtC15objc_properties10SomeObject = private constant { {{.*}} } {
// CHECK-SAME: i32 {{[0-9]+}}, i32 {{[0-9]+}}, i32 {{[0-9]+}}, i32 {{[0-9]+}},
// CHECK-SAME: i8* null,
// CHECK-SAME: i8* getelementptr inbounds ([{{.+}} x i8], [{{.+}} x i8]* {{@.+}}, i64 0, i64 0),
// CHECK-SAME: { {{.+}} }* @_CLASS_METHODS__TtC15objc_properties10SomeObject,
// CHECK-SAME: i8* null, i8* null, i8* null,
// CHECK-NEW-SAME: { {{.+}} }* @_CLASS_PROPERTIES__TtC15objc_properties10SomeObject
// CHECK-OLD-SAME: i8* null
// CHECK-SAME: }, section "__DATA, __objc_const", align 8
// CHECK: [[GETTER_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00"
// CHECK: [[SETTER_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK: @_INSTANCE_METHODS__TtC15objc_properties10SomeObject = private constant { {{.*}}] } {
// CHECK: i32 24,
// CHECK: i32 8,
// CHECK: [8 x { i8*, i8*, i8* }] [{
// CHECK: i8* getelementptr inbounds ([9 x i8], [9 x i8]* @"\01L_selector_data(readonly)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE0:%.*]]* ([[OPAQUE1:%.*]]*, i8*)* @_T015objc_properties10SomeObjectC8readonlyACvgTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(readwrite)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE0]]* ([[OPAQUE1]]*, i8*)* @_T015objc_properties10SomeObjectC9readwriteACvgTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setReadwrite:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE3:%.*]]*, i8*, [[OPAQUE4:%.*]]*)* @_T015objc_properties10SomeObjectC9readwriteACvsTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([9 x i8], [9 x i8]* @"\01L_selector_data(bareIvar)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE0]]* ([[OPAQUE1]]*, i8*)* @_T015objc_properties10SomeObjectC8bareIvarACvgTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([13 x i8], [13 x i8]* @"\01L_selector_data(setBareIvar:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE3]]*, i8*, [[OPAQUE4]]*)* @_T015objc_properties10SomeObjectC8bareIvarACvsTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(wobble)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (%0* (%0*, i8*)* @_T015objc_properties10SomeObjectC6wibbleACvgTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(setWobble:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void (%0*, i8*, %0*)* @_T015objc_properties10SomeObjectC6wibbleACvsTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE5:%.*]]* ([[OPAQUE6:%.*]]*, i8*)* @_T015objc_properties10SomeObjectCACycfcTo to i8*)
// CHECK: }]
// CHECK: }, section "__DATA, __objc_const", align 8
// This appears earlier because it's also used in an ivar description.
// CHECK: [[BAREIVAR_NAME:@.*]] = private unnamed_addr constant [9 x i8] c"bareIvar\00"
// CHECK: [[READONLY_NAME:@.*]] = private unnamed_addr constant [9 x i8] c"readonly\00"
// CHECK: [[READONLY_ATTRS:@.*]] = private unnamed_addr constant [42 x i8] c"T@\22_TtC15objc_properties10SomeObject\22,N,R\00"
// CHECK: [[READWRITE_NAME:@.*]] = private unnamed_addr constant [10 x i8] c"readwrite\00"
// CHECK: [[READWRITE_ATTRS:@.*]] = private unnamed_addr constant [42 x i8] c"T@\22_TtC15objc_properties10SomeObject\22,N,&\00"
// CHECK: [[BAREIVAR_ATTRS:@.*]] = private unnamed_addr constant [52 x i8] c"T@\22_TtC15objc_properties10SomeObject\22,N,&,VbareIvar\00"
// CHECK: [[WIBBLE_NAME:@.*]] = private unnamed_addr constant [7 x i8] c"wobble\00"
// CHECK: [[WIBBLE_ATTRS:@.*]] = private unnamed_addr constant [50 x i8] c"T@\22_TtC15objc_properties10SomeObject\22,N,&,Vwibble\00"
// CHECK: @_PROPERTIES__TtC15objc_properties10SomeObject = private constant { {{.*}}] } {
// CHECK: i32 16,
// CHECK: i32 4,
// CHECK: [4 x { i8*, i8* }] [{
// CHECK: i8* getelementptr inbounds ([9 x i8], [9 x i8]* [[READONLY_NAME]], i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([42 x i8], [42 x i8]* [[READONLY_ATTRS]], i64 0, i64 0)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[READWRITE_NAME]], i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([42 x i8], [42 x i8]* [[READWRITE_ATTRS]], i64 0, i64 0)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([9 x i8], [9 x i8]* [[BAREIVAR_NAME]], i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([52 x i8], [52 x i8]* [[BAREIVAR_ATTRS]], i64 0, i64 0)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[WIBBLE_NAME]], i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([50 x i8], [50 x i8]* [[WIBBLE_ATTRS]], i64 0, i64 0)
// CHECK: }]
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @_DATA__TtC15objc_properties10SomeObject = private constant { {{.+}} } {
// CHECK: i32 {{[0-9]+}}, i32 {{[0-9]+}}, i32 {{[0-9]+}}, i32 {{[0-9]+}},
// CHECK: i8* null,
// CHECK: i8* getelementptr inbounds ([{{.+}} x i8], [{{.+}} x i8]* {{@.+}}, i64 0, i64 0),
// CHECK: { {{.+}} }* @_INSTANCE_METHODS__TtC15objc_properties10SomeObject,
// CHECK: i8* null,
// CHECK: { {{.+}} }* @_IVARS__TtC15objc_properties10SomeObject,
// CHECK: i8* null,
// CHECK: { {{.+}} }* @_PROPERTIES__TtC15objc_properties10SomeObject
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC15objc_properties10SomeObject_$_objc_properties" = private constant { {{.*}}] } {
// CHECK: i32 24,
// CHECK: i32 2,
// CHECK: [2 x { i8*, i8*, i8* }] [{
// CHECK: { i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(extensionProperty)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE0]]* ([[OPAQUE1]]*, i8*)* @_T015objc_properties10SomeObjectC17extensionPropertyACvgTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([22 x i8], [22 x i8]* @"\01L_selector_data(setExtensionProperty:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE3]]*, i8*, [[OPAQUE4]]*)* @_T015objc_properties10SomeObjectC17extensionPropertyACvsTo to i8*)
// CHECK: }]
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: [[EXTENSIONPROPERTY_NAME:@.*]] = private unnamed_addr constant [18 x i8] c"extensionProperty\00"
// CHECK: @"_CATEGORY_PROPERTIES__TtC15objc_properties10SomeObject_$_objc_properties" = private constant { {{.*}}] } {
// CHECK: i32 16,
// CHECK: i32 1,
// CHECK: [1 x { i8*, i8* }] [{
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* [[EXTENSIONPROPERTY_NAME]], i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([42 x i8], [42 x i8]* [[READWRITE_ATTRS]], i64 0, i64 0)
// CHECK: }]
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK-NEW: [[EXTENSIONCLASSPROPERTY_NAME:@.*]] = private unnamed_addr constant [19 x i8] c"extensionClassProp\00"
// CHECK-NEW: [[EXTENSIONCLASSPROPERTY_ATTRS:@.*]] = private unnamed_addr constant [7 x i8] c"T#,N,R\00"
// CHECK-NEW: @"_CATEGORY_CLASS_PROPERTIES__TtC15objc_properties10SomeObject_$_objc_properties" = private constant { {{.*}}] } {
// CHECK-NEW: i32 16,
// CHECK-NEW: i32 1,
// CHECK-NEW: [1 x { i8*, i8* }] [{
// CHECK-NEW: i8* getelementptr inbounds ([19 x i8], [19 x i8]* [[EXTENSIONCLASSPROPERTY_NAME]], i64 0, i64 0),
// CHECK-NEW: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[EXTENSIONCLASSPROPERTY_ATTRS]], i64 0, i64 0)
// CHECK-NEW: }]
// CHECK-NEW: }, section "__DATA, __objc_const", align 8
// CHECK: @"_CATEGORY__TtC15objc_properties10SomeObject_$_objc_properties" = private constant { {{.+}} } {
// CHECK: i8* getelementptr inbounds ([{{.+}} x i8], [{{.+}} x i8]* {{@.+}}, i64 0, i64 0),
// CHECK: %swift.type* bitcast (i64* getelementptr inbounds (<{ {{.+}} }>* @_T015objc_properties10SomeObjectCMf, i32 0, i32 2) to %swift.type*),
// CHECK: { {{.+}} }* @"_CATEGORY_INSTANCE_METHODS__TtC15objc_properties10SomeObject_$_objc_properties",
// CHECK: { {{.+}} }* @"_CATEGORY_CLASS_METHODS__TtC15objc_properties10SomeObject_$_objc_properties",
// CHECK: i8* null,
// CHECK: { {{.+}} }* @"_CATEGORY_PROPERTIES__TtC15objc_properties10SomeObject_$_objc_properties",
// CHECK-NEW: { {{.+}} }* @"_CATEGORY_CLASS_PROPERTIES__TtC15objc_properties10SomeObject_$_objc_properties",
// CHECK-OLD: i8* null,
// CHECK: i32 60
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @_INSTANCE_METHODS__TtC15objc_properties4Tree =
// CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(parent)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (%2* (%2*, i8*)* @_T015objc_properties4TreeC6parentACSgXwvgTo to i8*)
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(setParent:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void (%2*, i8*, %2*)* @_T015objc_properties4TreeC6parentACSgXwvsTo to i8*)
// CHECK: @_PROTOCOL__TtP15objc_properties5Proto_ = private constant { {{.+}} } {
// CHECK: i8* null,
// CHECK: i8* getelementptr inbounds ([{{.+}} x i8], [{{.+}} x i8]* {{@.+}}, i64 0, i64 0),
// CHECK: i8* null,
// CHECK: { {{.+}} }* @_PROTOCOL_INSTANCE_METHODS__TtP15objc_properties5Proto_,
// CHECK: { {{.+}} }* @_PROTOCOL_CLASS_METHODS__TtP15objc_properties5Proto_,
// CHECK: i8* null,
// CHECK: i8* null,
// CHECK: { {{.+}} }* @_PROTOCOL_PROPERTIES__TtP15objc_properties5Proto_,
// CHECK: i32 96, i32 1,
// CHECK: [{{.+}}]* @_PROTOCOL_METHOD_TYPES__TtP15objc_properties5Proto_,
// CHECK: i8* null,
// CHECK-NEW: { {{.+}} }* @_PROTOCOL_CLASS_PROPERTIES__TtP15objc_properties5Proto_
// CHECK-OLD: i8* null
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: [[PROTOCOLPROPERTY_NAME:@.+]] = private unnamed_addr constant [6 x i8] c"value\00"
// CHECK: [[PROTOCOLPROPERTY_ATTRS:@.+]] = private unnamed_addr constant [7 x i8] c"Tq,N,R\00"
// CHECK: @_PROTOCOL_PROPERTIES__TtP15objc_properties5Proto_ = private constant { {{.*}}] } {
// CHECK: i32 16,
// CHECK: i32 1,
// CHECK: [1 x { i8*, i8* }] [{
// CHECK: i8* getelementptr inbounds ([6 x i8], [6 x i8]* [[PROTOCOLPROPERTY_NAME]], i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[PROTOCOLPROPERTY_ATTRS]], i64 0, i64 0)
// CHECK: }]
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK-NEW: [[PROTOCOLCLASSPROPERTY_NAME:@.+]] = private unnamed_addr constant [15 x i8] c"sharedInstance\00"
// CHECK-NEW: [[PROTOCOLCLASSPROPERTY_ATTRS:@.+]] = private unnamed_addr constant [7 x i8] c"T@,N,&\00"
// CHECK-NEW: @_PROTOCOL_CLASS_PROPERTIES__TtP15objc_properties5Proto_ = private constant { {{.*}}] } {
// CHECK-NEW: i32 16,
// CHECK-NEW: i32 1,
// CHECK-NEW: [1 x { i8*, i8* }] [{
// CHECK-NEW: i8* getelementptr inbounds ([15 x i8], [15 x i8]* [[PROTOCOLCLASSPROPERTY_NAME]], i64 0, i64 0),
// CHECK-NEW: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[PROTOCOLCLASSPROPERTY_ATTRS]], i64 0, i64 0)
// CHECK-NEW: }]
// CHECK-NEW: }, section "__DATA, __objc_const", align 8
| 20b536dbc31a4d4c84e36289dbe89793 | 51.361702 | 193 | 0.620005 | false | false | false | false |
netguru/ResponseDetective | refs/heads/develop | ResponseDetective/Tests/Specs/ResponseDetectiveSpec.swift | mit | 1 | //
// ResponseDetectiveSpec.swift
//
// Copyright © 2016-2020 Netguru S.A. All rights reserved.
// Licensed under the MIT License.
//
import Foundation
import Nimble
import OHHTTPStubs
import ResponseDetective
import Quick
internal final class ResponseDetectiveSpec: QuickSpec {
override func spec() {
describe("ResponseDetective") {
beforeSuite {
stub(condition: isHost("httpbin.org")) { _ in
return HTTPStubsResponse(data: Data(), statusCode: 200, headers: nil)
}
}
beforeEach {
ResponseDetective.reset()
}
afterSuite {
HTTPStubs.removeAllStubs()
}
describe("initial state") {
it("should use default output facility") {
expect(type(of: ResponseDetective.outputFacility) == ConsoleOutputFacility.self).to(beTruthy())
}
it("should use default url protocol class") {
expect(ResponseDetective.URLProtocolClass).to(beIdenticalTo(NSClassFromString("RDTURLProtocol")!))
}
}
describe("enabling in url session configuration") {
let configuration = URLSessionConfiguration.default
beforeEach {
ResponseDetective.enable(inConfiguration: configuration)
}
it("should add protocol class at the beginning of array") {
expect(configuration.protocolClasses!.first == ResponseDetective.URLProtocolClass).to(beTrue())
}
}
describe("ignoring requests") {
let request = URLRequest(url: URL(string: "http://foo.bar")!)
context("before adding predicate") {
it("should not ignore the request") {
expect {
ResponseDetective.canIncercept(request: request)
}.to(beTruthy())
}
}
context("after adding predicate") {
beforeEach {
ResponseDetective.ignoreRequests(matchingPredicate: NSPredicate { subject, _ in
guard let subject = subject as? URLRequest, let url = subject.url else {
return true
}
let string = url.absoluteString
return string.contains("foo")
})
}
it("should ignore the request") {
expect {
ResponseDetective.canIncercept(request: request)
}.to(beFalsy())
}
}
}
describe("body deserialization") {
context("before registering a custom body deserializer") {
it("should return no deserialized body") {
expect {
ResponseDetective.deserialize(body: Data(), contentType: "foo/bar")
}.to(beNil())
}
}
context("after registering an explicit body deserializer") {
beforeEach {
ResponseDetective.registerBodyDeserializer(
TestBodyDeserializer(fixedDeserializedBody: "lorem ipsum"),
forContentType: "foo/bar"
)
}
it("should return a deserialized body") {
expect {
ResponseDetective.deserialize(body: Data(), contentType: "foo/bar")
}.to(equal("lorem ipsum"))
}
it("should return a deserialized body for content type containing properties") {
expect {
ResponseDetective.deserialize(body: Data(), contentType: "foo/bar; charset=utf8")
}.to(equal("lorem ipsum"))
}
}
context("after registering a wildcard body deserializer") {
beforeEach {
ResponseDetective.registerBodyDeserializer(
TestBodyDeserializer(fixedDeserializedBody: "dolor sit amet"),
forContentType: "foo/*"
)
}
it("should return a deserialized body") {
expect {
ResponseDetective.deserialize(body: Data(), contentType: "foo/baz")
}.to(equal("dolor sit amet"))
}
}
}
describe("request interception") {
let buffer = BufferOutputFacility()
let configuration = URLSessionConfiguration.default
beforeEach {
ResponseDetective.outputFacility = buffer
ResponseDetective.registerBodyDeserializer(TestBodyDeserializer(), forContentType: "*/*")
ResponseDetective.enable(inConfiguration: configuration)
}
context("before request has been sent") {
it("should intercept no requests") {
expect(buffer.requestRepresentations).to(beEmpty())
}
}
context("after request has been sent") {
let request: URLRequest = {
var request = URLRequest(url: URL(string: "https://httpbin.org/post")!)
request.httpMethod = "POST"
request.httpBody = Data(base64Encoded: "foo", options: [])
return request
}()
beforeEach {
let session = URLSession(configuration: configuration)
session.dataTask(with: request).resume()
}
it("should eventually intercept it") {
expect(buffer.requestRepresentations.count).toEventually(beGreaterThanOrEqualTo(1), timeout: .seconds(5))
expect(buffer.responseRepresentations.last?.body).toEventuallyNot(beNil(), timeout: .seconds(5))
}
}
}
describe("response interception") {
let buffer = BufferOutputFacility()
let configuration = URLSessionConfiguration.default
beforeEach {
ResponseDetective.outputFacility = buffer
ResponseDetective.registerBodyDeserializer(TestBodyDeserializer(), forContentType: "*/*")
ResponseDetective.enable(inConfiguration: configuration)
}
context("before request has been sent") {
it("should intercept no responses") {
expect(buffer.responseRepresentations).to(beEmpty())
}
}
context("after request has been sent") {
let request = URLRequest(url: URL(string: "https://httpbin.org/get")!)
beforeEach {
let session = URLSession(configuration: configuration)
session.dataTask(with: request).resume()
}
it("should eventually intercept its response") {
expect(buffer.responseRepresentations.count).toEventually(beGreaterThanOrEqualTo(1), timeout: .seconds(5))
}
}
}
describe("error interception") {
let buffer = BufferOutputFacility()
let configuration = URLSessionConfiguration.default
beforeEach {
ResponseDetective.outputFacility = buffer
ResponseDetective.registerBodyDeserializer(TestBodyDeserializer(), forContentType: "*/*")
ResponseDetective.enable(inConfiguration: configuration)
}
context("before request has been sent") {
it("should intercept no errors") {
expect(buffer.responseRepresentations).to(beEmpty())
}
}
context("after request has been sent") {
let request = URLRequest(url: URL(string: "https://foobar")!)
beforeEach {
let session = URLSession(configuration: configuration)
session.dataTask(with: request).resume()
}
it("should eventually intercept its error") {
expect(buffer.errorRepresentations.count).toEventually(beGreaterThanOrEqualTo(1), timeout: .seconds(5))
}
}
}
}
}
}
| feb9789d4c8dad5dbe6d4ee8fec2144c | 23.836431 | 112 | 0.66966 | false | true | false | false |
GYLibrary/GPRS | refs/heads/master | OznerGPRS/NetWork/GYNetWorking.swift | mit | 1 | //
// GYNetWorking.swift
// GYHelpToolsSwift
//
// Created by ZGY on 2017/4/12.
// Copyright © 2017年 Giant. All rights reserved.
//
// Author: Airfight
// My GitHub: https://github.com/airfight
// My Blog: http://airfight.github.io/
// My Jane book: http://www.jianshu.com/users/17d6a01e3361
// Current Time: 2017/4/12 16:53
// GiantForJade: Efforts to do my best
// Real developers ship.
import UIKit
import Alamofire
public func Print<T>(_ message: T,file: String = #file,method: String = #function, line: Int = #line)
{
#if DEBUG
print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
#endif
}
typealias AlamofireManager = Alamofire.SessionManager
enum GYNetWorkStatus {
/// 未知网络
case UnKnown
/// 无网络
case NotReachable
/// 手机网络
case ReachableViaWWAN
/// WIFI
case ReachableViaWiFi
}
enum GYRequestSerializer {
/// Json格式
case Json
/// 二进制格式
case Http
}
typealias GYHttpRequestSuccess = (AnyObject) -> Void
typealias GYHttpRequestFailed = (Error) -> Void
typealias GYAlamofireResponse = (DataResponse<Any>) -> Void
typealias GYNetWorkState = (GYNetWorkStatus) -> Void
class GYNetWorking{
static let `default`: GYNetWorking = GYNetWorking()
/// 网络监听
let manager = NetworkReachabilityManager(host: "www.baidu.com")
var alldataRequestTask:NSMutableDictionary = NSMutableDictionary()
/// 是否只接受第一次请求 默认只接受第一次请求
var isRequest: Bool = true
}
// MARK: - 获取当前网络状态
extension GYNetWorking {
func netWorkStatusWithBlock(_ block: @escaping GYNetWorkState) {
manager?.startListening()
manager?.listener = { status in
switch status {
case .unknown:
block(.UnKnown)
case .notReachable:
DispatchQueue.main.async {
appDelegate.window?.noticeOnlyText("无网络")
}
block(.NotReachable)
case .reachable(.ethernetOrWiFi):
block(.ReachableViaWiFi)
case .reachable(.wwan):
block(.ReachableViaWWAN)
}
}
}
fileprivate func isReachable() -> Bool{
return (manager?.isReachable)!
}
fileprivate func isWWANetwork() -> Bool {
return (manager?.isReachableOnWWAN)!
}
fileprivate func isWiFiNetwork() -> Bool {
return (manager?.isReachableOnEthernetOrWiFi)!
}
}
// MARK: - 网络请求
extension GYNetWorking {
/// 自动校验 返回Json格式
///
/// - Parameters:
/// - urlRequest: urlRequest description
/// - sucess: sucess description
/// - failure: failure description
func requestJson(_ urlRequest: URLRequestConvertible, sucess:@escaping GYHttpRequestSuccess,failure: @escaping GYHttpRequestFailed) {
if !GYNetWorking.default.isReachable() {
DispatchQueue.main.async {
appDelegate.window?.noticeOnlyText("无网络")
}
// return
}
let hud = appDelegate.window?.pleaseWait()
Print(urlRequest.urlRequest)
let responseJSON: (DataResponse<Any>) -> Void = { [weak self] (response:DataResponse<Any>) in
hud?.hide()
if let value = urlRequest.urlRequest?.url?.absoluteString {
// sleep(3)
self?.alldataRequestTask.removeObject(forKey: value)
}
self?.handleResponse(response, sucess: sucess, failure: failure)
}
let task = alldataRequestTask.value(forKey: (urlRequest.urlRequest?.url?.absoluteString)!) as? DataRequest
guard isRequest && (task == nil) else {
return
}
task?.cancel()
let manager = AlamofireManager.default
// 此处设置超时无效
// manager.session.configuration.timeoutIntervalForRequest = 3
let dataRequest = manager.request(urlRequest)
.responseJSON(completionHandler: responseJSON)
alldataRequestTask.setValue(dataRequest, forKey: (urlRequest.urlRequest?.url?.absoluteString)!)
}
func requesttext(_ urlRequest: URLRequestConvertible, sucess:@escaping GYHttpRequestSuccess,failure: @escaping GYHttpRequestFailed) {
if !GYNetWorking.default.isReachable() {
DispatchQueue.main.async {
appDelegate.window?.noticeOnlyText("无网络")
}
// return
}
let hud = appDelegate.window?.pleaseWait()
Print(urlRequest.urlRequest)
let responseJSON: (DataResponse<String>) -> Void = { [weak self] (response:DataResponse<String>) in
hud?.hide()
if let value = urlRequest.urlRequest?.url?.absoluteString {
// sleep(3)
self?.alldataRequestTask.removeObject(forKey: value)
}
self?.handle(response, sucess: sucess, failure: failure)
}
let task = alldataRequestTask.value(forKey: (urlRequest.urlRequest?.url?.absoluteString)!) as? DataRequest
guard isRequest && (task == nil) else {
return
}
task?.cancel()
let manager = AlamofireManager.default
// 此处设置超时无效
// manager.session.configuration.timeoutIntervalForRequest = 3
let dataRequest = manager.request(urlRequest)
.validate(contentType: ["text/html"])
.responseString(completionHandler: responseJSON)
alldataRequestTask.setValue(dataRequest, forKey: (urlRequest.urlRequest?.url?.absoluteString)!)
}
}
// MARK: - 处理请求结果
extension GYNetWorking {
fileprivate func handle(_ response: DataResponse<String> ,sucess:@escaping GYHttpRequestSuccess,failure: @escaping GYHttpRequestFailed) {
if let _ = response.result.value {
switch response.result {
case .success(let value):
sucess(value as AnyObject)
break
case .failure(let error):
failure(error)
default:
break
}
}
}
/// 处理请求结果 (根据项目需求修改)
///
/// - Parameters:
/// - response: response description
/// - sucess: sucess description
/// - failure: failure description
fileprivate func handleResponse(_ response: DataResponse<Any> ,sucess:@escaping GYHttpRequestSuccess,failure: @escaping GYHttpRequestFailed) {
if let _ = response.result.value {
switch response.result {
case .success(let json):
// var result = json as! [String:AnyObject]
// Print(json)
// guard let code = result["status"] as? NSInteger else {
// return
// }
// if code > 0 {
sucess(json as AnyObject)
// } else {
//
// var str = result["msg"] as? String ?? "未知错误"
//
// if code == -10002 {
// str = "服务器异常"
// }
//
// let errorString = str
// let userInfo = [NSLocalizedDescriptionKey:errorString]
// let error: NSError = NSError(domain: errorString, code: code, userInfo: userInfo)
//
//
// DispatchQueue.main.async {
// if errorString == "该用户未填写详细信息" {
//
// } else {
//
// appDelegate.window?.noticeOnlyText(errorString)
//
// }
//
// }
// failure(error)
// }
case .failure(let error):
failure(error)
}
} else {
DispatchQueue.main.async {
if response.result.debugDescription.contains("Code=-1001") {
appDelegate.window?.noticeOnlyText("请求超时")
} else {
Print(response.value)
}
// response.result
Print(response.result.error?.localizedDescription)
if response.result.error != nil {
failure(response.result.error!)
}
}
}
}
}
| 30959095761bae73fcb128d2f4a23225 | 27.908197 | 146 | 0.528184 | false | false | false | false |
LeeShiYoung/DouYu | refs/heads/master | DouYuAPP/DouYuAPP/Classes/Home/Controller/Yo_GameViewController.swift | apache-2.0 | 1 | //
// Yo_GameViewController.swift
// DouYuAPP
//
// Created by shying li on 2017/3/28.
// Copyright © 2017年 李世洋. All rights reserved.
//
import UIKit
class Yo_GameViewController: GenericViewController<Yo_GameContentView> {
override func viewDidLoad() {
super.viewDidLoad()
contentView.setupUI()
loadGameData()
commonGameViewModel.registerCell {[weak self] () -> (listView: UICollectionView, cell: [String : UICollectionViewCell.Type]) in
return ((self?.contentView.commonGameView)!, [CommonGameViewCell: Yo_CommonGameViewCell.self])
}
allGameViewModel.registerReusableView(Kind: UICollectionElementKindSectionHeader) {[weak self] () -> (listView: UICollectionView, view: [String : UIView.Type]) in
return ((self?.contentView.allGameView)!, [AllGameHeaderView: Yo_BaseSectionHeaderView.self])
}
allGameViewModel.registerCell {[weak self] () -> (listView: UICollectionView, cell: [String : UICollectionViewCell.Type]) in
return ((self?.contentView.allGameView)!, [AllGameViewCellID: Yo_AllGameViewCell.self])
}
}
fileprivate lazy var gameViewModel = Yo_GameViewModel()
fileprivate lazy var commonGameViewModel: Yo_CommonGameCollectionViewModel = {[weak self] in
let commonGameViewModel = Yo_CommonGameCollectionViewModel(sourceView: (self?.contentView.commonGameView)!)
return commonGameViewModel
}()
fileprivate lazy var allGameViewModel: Yo_AllGameCollectionViewModel = {[weak self] in
let allGameViewModel = Yo_AllGameCollectionViewModel(sourceView: (self?.contentView.allGameView)!)
return allGameViewModel
}()
}
extension Yo_GameViewController {
fileprivate func loadGameData() {
gameViewModel.loadGameData { (commonGame, allGame) in
self.commonGameViewModel.set(DataSource: { () -> [Yo_GameModel] in
return commonGame
}, completion: {
self.contentView.commonGameView.reloadData()
})
self.allGameViewModel.set(DataSource: { () -> [Yo_GameModel] in
return allGame
}, completion: {
self.contentView.allGameView.reloadData()
})
}
}
}
| c140f0bcb6f9df8dd77fe92b5bb03b2a | 36.09375 | 170 | 0.640691 | false | false | false | false |
Mykhailo-Vorontsov-owo/OfflineCommute | refs/heads/master | OfflineCommute/Sources/Controllers/SyncOperations/UpdateDistanceSyncOperation.swift | mit | 1 | //
// UpdateDistanceSyncOperation.swift
// OfflineCommute
//
// Created by Mykhailo Vorontsov on 27/02/2016.
// Copyright © 2016 Mykhailo Vorontsov. All rights reserved.
//
import UIKit
import MapKit
import CoreData
class UpdateDistanceSyncOperation: DataRetrievalOperation, ManagedObjectRetrievalOperationProtocol {
let center:CLLocationCoordinate2D
var dataManager: CoreDataManager!
init(center:CLLocationCoordinate2D) {
self.center = center
super.init()
}
// override func main() {
override func parseData() throws {
var internalError:ErrorType? = nil
let context = dataManager.dataContext
context.performBlockAndWait { () -> Void in
// Clear old data
do {
guard let allDocks = try context.executeFetchRequest(NSFetchRequest(entityName: "DockStation")) as? [DockStation] else {
return
}
let location = CLLocation(latitude: self.center.latitude, longitude: self.center.longitude)
for dock in allDocks {
let dockLocation = CLLocation(latitude:dock.latitude.doubleValue, longitude: dock.longitude.doubleValue)
let distance = location.distanceFromLocation(dockLocation)
dock.distance = distance
}
try context.save()
} catch {
internalError = error
}
}
guard nil == internalError else {
throw internalError!
}
}
}
| e95e1c95a5160bb7e69e1e68ea9c646a | 24.310345 | 128 | 0.653951 | false | false | false | false |
kinetic-fit/sensors-swift | refs/heads/master | Sources/SwiftySensors/Sensor.swift | mit | 1 | //
// Sensor.swift
// SwiftySensors
//
// https://github.com/kinetic-fit/sensors-swift
//
// Copyright © 2017 Kinetic. All rights reserved.
//
import CoreBluetooth
import Signals
/**
Sensor wraps a CoreBluetooth Peripheral and manages the hierarchy of Services and Characteristics.
*/
open class Sensor: NSObject {
// Internal Constructor. SensorManager manages the instantiation and destruction of Sensor objects
/// :nodoc:
required public init(peripheral: CBPeripheral, advertisements: [CBUUID] = []) {
self.peripheral = peripheral
self.advertisements = advertisements
super.init()
peripheral.delegate = self
peripheral.addObserver(self, forKeyPath: "state", options: [.new, .old], context: &myContext)
}
deinit {
peripheral.removeObserver(self, forKeyPath: "state")
peripheral.delegate = nil
rssiPingTimer?.invalidate()
}
/// Backing CoreBluetooth Peripheral
public let peripheral: CBPeripheral
/// Discovered Services
public fileprivate(set) var services = Dictionary<String, Service>()
/// Advertised UUIDs
public let advertisements: [CBUUID]
/// Raw Advertisement Data
public internal(set) var advertisementData: [String: Any]? {
didSet {
onAdvertisementDataUpdated => advertisementData
}
}
/// Advertisement Data Changed Signal
public let onAdvertisementDataUpdated = Signal<([String: Any]?)>()
/// Name Changed Signal
public let onNameChanged = Signal<Sensor>()
/// State Changed Signal
public let onStateChanged = Signal<Sensor>()
/// Service Discovered Signal
public let onServiceDiscovered = Signal<(Sensor, Service)>()
/// Service Features Identified Signal
public let onServiceFeaturesIdentified = Signal<(Sensor, Service)>()
/// Characteristic Discovered Signal
public let onCharacteristicDiscovered = Signal<(Sensor, Characteristic)>()
/// Characteristic Value Updated Signal
public let onCharacteristicValueUpdated = Signal<(Sensor, Characteristic)>()
/// Characteristic Value Written Signal
public let onCharacteristicValueWritten = Signal<(Sensor, Characteristic)>()
/// RSSI Changed Signal
public let onRSSIChanged = Signal<(Sensor, Int)>()
/// Most recent RSSI value
public internal(set) var rssi: Int = Int.min {
didSet {
onRSSIChanged => (self, rssi)
}
}
/// Last time of Sensor Communication with the Sensor Manager (Time Interval since Reference Date)
public fileprivate(set) var lastSensorActivity = Date.timeIntervalSinceReferenceDate
/**
Get a service by its UUID or by Type
- parameter uuid: UUID string
- returns: Service
*/
public func service<T: Service>(_ uuid: String? = nil) -> T? {
if let uuid = uuid {
return services[uuid] as? T
}
for service in services.values {
if let s = service as? T {
return s
}
}
return nil
}
/**
Check if a Sensor advertised a specific UUID Service
- parameter uuid: UUID string
- returns: `true` if the sensor advertised the `uuid` service
*/
open func advertisedService(_ uuid: String) -> Bool {
let service = CBUUID(string: uuid)
for advertisement in advertisements {
if advertisement.isEqual(service) {
return true
}
}
return false
}
//////////////////////////////////////////////////////////////////
// Private / Internal Classes, Properties and Constants
//////////////////////////////////////////////////////////////////
internal weak var serviceFactory: SensorManager.ServiceFactory?
private var rssiPingTimer: Timer?
private var myContext = 0
/// :nodoc:
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &myContext {
if keyPath == "state" {
peripheralStateChanged()
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
fileprivate var rssiPingEnabled: Bool = false {
didSet {
if rssiPingEnabled {
if rssiPingTimer == nil {
rssiPingTimer = Timer.scheduledTimer(timeInterval: SensorManager.RSSIPingInterval, target: self, selector: #selector(Sensor.rssiPingTimerHandler), userInfo: nil, repeats: true)
}
} else {
rssi = Int.min
rssiPingTimer?.invalidate()
rssiPingTimer = nil
}
}
}
}
// Private Funtions
extension Sensor {
fileprivate func peripheralStateChanged() {
switch peripheral.state {
case .connected:
rssiPingEnabled = true
case .connecting:
break
case .disconnected:
fallthrough
default:
rssiPingEnabled = false
services.removeAll()
}
SensorManager.logSensorMessage?("Sensor: peripheralStateChanged: \(peripheral.state.rawValue)")
onStateChanged => self
}
fileprivate func serviceDiscovered(_ cbs: CBService) {
if let service = services[cbs.uuid.uuidString], service.cbService == cbs {
return
}
if let ServiceType = serviceFactory?.serviceTypes[cbs.uuid.uuidString] {
let service = ServiceType.init(sensor: self, cbs: cbs)
services[cbs.uuid.uuidString] = service
onServiceDiscovered => (self, service)
SensorManager.logSensorMessage?("Sensor: Service Created: \(service)")
if let sp = service as? ServiceProtocol {
let charUUIDs: [CBUUID] = type(of: sp).characteristicTypes.keys.map { uuid in
return CBUUID(string: uuid)
}
peripheral.discoverCharacteristics(charUUIDs.count > 0 ? charUUIDs : nil, for: cbs)
}
} else {
SensorManager.logSensorMessage?("Sensor: Service Ignored: \(cbs)")
}
}
fileprivate func characteristicDiscovered(_ cbc: CBCharacteristic, cbs: CBService) {
guard let service = services[cbs.uuid.uuidString] else { return }
if let characteristic = service.characteristic(cbc.uuid.uuidString), characteristic.cbCharacteristic == cbc {
return
}
guard let sp = service as? ServiceProtocol else { return }
if let CharType = type(of: sp).characteristicTypes[cbc.uuid.uuidString] {
let characteristic = CharType.init(service: service, cbc: cbc)
service.characteristics[cbc.uuid.uuidString] = characteristic
characteristic.onValueUpdated.subscribe(with: self) { [weak self] c in
if let s = self {
s.onCharacteristicValueUpdated => (s, c)
}
}
characteristic.onValueWritten.subscribe(with: self) { [weak self] c in
if let s = self {
s.onCharacteristicValueWritten => (s, c)
}
}
SensorManager.logSensorMessage?("Sensor: Characteristic Created: \(characteristic)")
onCharacteristicDiscovered => (self, characteristic)
} else {
SensorManager.logSensorMessage?("Sensor: Characteristic Ignored: \(cbc)")
}
}
@objc func rssiPingTimerHandler() {
if peripheral.state == .connected {
peripheral.readRSSI()
}
}
internal func markSensorActivity() {
lastSensorActivity = Date.timeIntervalSinceReferenceDate
}
}
extension Sensor: CBPeripheralDelegate {
/// :nodoc:
public func peripheralDidUpdateName(_ peripheral: CBPeripheral) {
onNameChanged => self
markSensorActivity()
}
/// :nodoc:
public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard let cbss = peripheral.services else { return }
for cbs in cbss {
serviceDiscovered(cbs)
}
markSensorActivity()
}
/// :nodoc:
public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard let cbcs = service.characteristics else { return }
for cbc in cbcs {
characteristicDiscovered(cbc, cbs: service)
}
markSensorActivity()
}
/// :nodoc:
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard let service = services[characteristic.service.uuid.uuidString] else { return }
guard let char = service.characteristics[characteristic.uuid.uuidString] else { return }
if char.cbCharacteristic !== characteristic {
char.cbCharacteristic = characteristic
}
char.valueUpdated()
markSensorActivity()
}
/// :nodoc:
public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
guard let service = services[characteristic.service.uuid.uuidString] else { return }
guard let char = service.characteristics[characteristic.uuid.uuidString] else { return }
if char.cbCharacteristic !== characteristic {
char.cbCharacteristic = characteristic
}
char.valueWritten()
markSensorActivity()
}
/// :nodoc:
public func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
if RSSI.intValue < 0 {
rssi = RSSI.intValue
markSensorActivity()
}
}
}
| b6d116fa0a8c3ea20082df2e0674a994 | 32.13355 | 196 | 0.600767 | false | false | false | false |
GoogleCloudPlatform/ios-docs-samples | refs/heads/master | translation/swift/Translation/ViewController.swift | apache-2.0 | 1 | //
// Copyright 2019 Google 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 UIKit
import MaterialComponents
import googleapis
class ViewController: UIViewController {
var appBar = MDCAppBar()
// Text Field
var inputTextField: MDCTextField = {
let textField = MDCTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
var textFieldBottomConstraint: NSLayoutConstraint!
let inputTextFieldController: MDCTextInputControllerOutlined
var tableViewDataSource = [[String: String]]()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var pickerBackgroundView: UIView!
@IBOutlet weak var pickerSwapButton: UIBarButtonItem!
@IBOutlet weak var pickerSourceButton: UIBarButtonItem!
@IBOutlet weak var pickerTagerButton: UIBarButtonItem!
var sourceLanguageCode = [String]()
var targetLanguageCode = [String]()
var glossaryList = [Glossary]()
var isPickerForLanguage = true
//init with nib name
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
inputTextFieldController = MDCTextInputControllerOutlined(textInput: inputTextField)
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
inputTextFieldController.placeholderText = ApplicationConstants.queryTextFieldPlaceHolder
}
//init with coder
required init?(coder aDecoder: NSCoder) {
inputTextFieldController = MDCTextInputControllerOutlined(textInput: inputTextField)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.tintColor = .black
self.view.backgroundColor = ApplicationScheme.shared.colorScheme.surfaceColor
self.title = ApplicationConstants.title
setUpNavigationBarAndItems()
registerKeyboardNotifications()
self.view.addSubview(inputTextField)
inputTextField.backgroundColor = .white
inputTextField.returnKeyType = .send
inputTextFieldController.placeholderText = ApplicationConstants.queryTextFieldPlaceHolder
inputTextField.delegate = self
// Constraints
textFieldBottomConstraint = NSLayoutConstraint(item: inputTextField,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1,
constant: 0)
var constraints = [NSLayoutConstraint]()
constraints.append(textFieldBottomConstraint)
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:|-[intentTF]-|",
options: [],
metrics: nil,
views: [ "intentTF" : inputTextField]))
NSLayoutConstraint.activate(constraints)
let colorScheme = ApplicationScheme.shared.colorScheme
MDCTextFieldColorThemer.applySemanticColorScheme(colorScheme,
to: self.inputTextFieldController)
}
@IBAction func dismissKeyboardAction(_ sender:Any) {
inputTextField.resignFirstResponder()
}
@IBAction func reverseLanguagesAction(_ sender: Any) {
print("reverseLanguagesAction")
let sourceCodeIndex = pickerView.selectedRow(inComponent: 0)
let targetCodeIndex = pickerView.selectedRow(inComponent: 1)
pickerView.selectRow(targetCodeIndex, inComponent: 0, animated: true)
pickerView.selectRow(sourceCodeIndex, inComponent: 1, animated: true)
}
@IBAction func doneButtonAction(_ sender: Any) {
pickerBackgroundView.isHidden = true
view.sendSubviewToBack(pickerBackgroundView)
if isPickerForLanguage {
let sourceCodeIndex = pickerView.selectedRow(inComponent: 0)
let targetCodeIndex = pickerView.selectedRow(inComponent: 1)
let sourceCode = sourceLanguageCode[sourceCodeIndex]
let targetCode = targetLanguageCode[targetCodeIndex]
print("SourceCode = \(sourceCode), TargetCode = \(targetCode)")
UserDefaults.standard.set(sourceCode, forKey: ApplicationConstants.sourceLanguageCode)
UserDefaults.standard.set(targetCode, forKey: ApplicationConstants.targetLanguageCode)
} else {
let sourceCodeIndex = pickerView.selectedRow(inComponent: 0)
let sourceCode = glossaryList[sourceCodeIndex].name
UserDefaults.standard.set(sourceCode, forKey: "SelectedGlossary")
}
}
@IBAction func cancelButtonAction(_ sender: Any) {
pickerBackgroundView.isHidden = true
view.sendSubviewToBack(pickerBackgroundView)
}
func setUpNavigationBarAndItems() {
//Initialize and add AppBar
self.addChild(appBar.headerViewController)
appBar.addSubviewsToParent()
let barButtonLeadingItem = UIBarButtonItem()
barButtonLeadingItem.tintColor = ApplicationScheme.shared.colorScheme.primaryColorVariant
barButtonLeadingItem.image = #imageLiteral(resourceName: "baseline_swap_horiz_black_48pt")
barButtonLeadingItem.target = self
barButtonLeadingItem.action = #selector(presentNavigationDrawer)
appBar.navigationBar.backItem = barButtonLeadingItem
let rightBarButton = UIBarButtonItem()
rightBarButton.tintColor = ApplicationScheme.shared.colorScheme.primaryColorVariant
rightBarButton.title = ApplicationConstants.glossaryButton
rightBarButton.target = self
rightBarButton.action = #selector(glossaryButtonTapped)
appBar.navigationBar.rightBarButtonItem = rightBarButton
MDCAppBarColorThemer.applySemanticColorScheme(ApplicationScheme.shared.colorScheme, to:self.appBar)
}
@objc func glossaryButtonTapped() {
let glossaryStatus = UserDefaults.standard.bool(forKey: ApplicationConstants.glossaryStatus)
let alertVC = UIAlertController(title: ApplicationConstants.glossaryAlertTitle, message: glossaryStatus ? ApplicationConstants.glossaryDisbleAlertMessage : ApplicationConstants.glossaryEnableAlertMessage, preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: glossaryStatus ? ApplicationConstants.glossaryAlerOKDisableTitle : ApplicationConstants.glossaryAlertOKEnableTitle, style: .default, handler: { (_) in
UserDefaults.standard.set(!glossaryStatus, forKey: ApplicationConstants.glossaryStatus)
if !glossaryStatus {
self.getListOfGlossary()
}
}))
if glossaryStatus {
alertVC.addAction(UIAlertAction(title: "Choose glossary" , style: .default, handler: {(_) in
self.getListOfGlossary()
}))
}
alertVC.addAction(UIAlertAction(title: ApplicationConstants.glossaryAlertCacelTitle, style: .default))
present(alertVC, animated: true)
}
@objc func presentNavigationDrawer() {
// present picker view with languages
// self.presentPickerView()
TextToTranslationService.sharedInstance.getLanguageCodes { (responseObj, error) in
if let errorText = error {
self.handleError(error: errorText)
return
}
guard let supportedLanguages = responseObj else {return}
if supportedLanguages.languagesArray_Count > 0, let languages = supportedLanguages.languagesArray as? [SupportedLanguage] {
self.sourceLanguageCode = languages.filter({return $0.supportSource }).map({ (supportedLanguage) -> String in
return supportedLanguage.languageCode
})
self.targetLanguageCode = languages.filter({return $0.supportTarget }).map({ (supportedLanguage) -> String in
return supportedLanguage.languageCode
})
self.isPickerForLanguage = true
self.presentPickerView()
}
}
}
func getListOfGlossary() {
isPickerForLanguage = false
TextToTranslationService.sharedInstance.getListOfGlossary { (responseObj, error) in
if let errorText = error {
self.handleError(error: errorText)
return
}
guard let response = responseObj else {return}
print("getListOfGlossary")
if let glossaryArray = response.glossariesArray as? [Glossary] {
self.glossaryList = glossaryArray
self.presentPickerView()
}
}
}
func presentPickerView() {
pickerBackgroundView.isHidden = false
view.bringSubviewToFront(pickerBackgroundView)
pickerView.reloadAllComponents()
if isPickerForLanguage {
pickerSourceButton.title = "Source"
pickerSwapButton.image = #imageLiteral(resourceName: "baseline_swap_horiz_black_48pt")
pickerTagerButton.title = "Target"
guard let sourceCode = UserDefaults.standard.value(forKey: ApplicationConstants.sourceLanguageCode) as? String,
let targetCode = UserDefaults.standard.value(forKey: ApplicationConstants.targetLanguageCode) as? String,
let sourceIndex = sourceLanguageCode.firstIndex(of: sourceCode),
let targetIndex = targetLanguageCode.firstIndex(of: targetCode)
else { return }
pickerView.selectRow(sourceIndex, inComponent: 0, animated: true)
pickerView.selectRow(targetIndex, inComponent: 1, animated: true)
} else {
pickerSourceButton.title = "List of Glossaries"
pickerSwapButton.image = nil
pickerTagerButton.title = ""
guard let selectedGlossary = UserDefaults.standard.value(forKey: "SelectedGlossary") as? String,
let sourceIndex = glossaryList.firstIndex(where: { $0.name == selectedGlossary })
else { return }
pickerView.selectRow(sourceIndex, inComponent: 0, animated: true)
}
}
}
extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return isPickerForLanguage ? 2 : 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return isPickerForLanguage ? max(sourceLanguageCode.count, targetLanguageCode.count) : glossaryList.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if isPickerForLanguage {
if component == 0 {
return sourceLanguageCode.count > row ? sourceLanguageCode[row] : ""
} else {
return targetLanguageCode.count > row ? targetLanguageCode[row] : ""
}
} else {
return glossaryList.count > row ? (glossaryList[row].name.components(separatedBy: "/").last ?? "") : ""
}
}
}
// MARK: - Keyboard Handling
extension ViewController {
func registerKeyboardNotifications() {
NotificationCenter.default.addObserver(
self,
selector: #selector(self.keyboardWillShow),
name: UIResponder.keyboardDidShowNotification,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.keyboardWillHide),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
let keyboardFrame =
(notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
textFieldBottomConstraint.constant = -keyboardFrame.height
}
@objc func keyboardWillHide(notification: NSNotification) {
textFieldBottomConstraint.constant = 0
}
}
//MARK: Textfield delegate
extension ViewController: UITextFieldDelegate {
//Captures the query typed by user
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if let text = textField.text, text.count > 0 {
textToTranslation(text: text)
tableViewDataSource.append([ApplicationConstants.selfKey: text])
tableView.insertRows(at: [IndexPath(row: tableViewDataSource.count - 1, section: 0)], with: .automatic)
}
textField.text = ""
return true
}
func handleError(error: String) {
let alertVC = UIAlertController(title: "Error", message: error, preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "OK", style: .default))
present(alertVC, animated: true)
}
//start sending text
func textToTranslation(text: String) {
TextToTranslationService.sharedInstance.textToTranslate(text: text, completionHandler:
{ (responseObj, error) in
if let errorText = error {
self.handleError(error: errorText)
return
}
guard let response = responseObj else {return}
//Handle success response
var responseText = ""
if response.glossaryTranslationsArray_Count > 0, let tResponse = response.glossaryTranslationsArray.firstObject as? Translation {
responseText = "Glossary: " + tResponse.translatedText + "\n\n"
}
if response.translationsArray_Count > 0, let tResponse = response.translationsArray.firstObject as? Translation {
responseText += ("Translated: " + tResponse.translatedText)
}
if !responseText.isEmpty {
self.tableViewDataSource.append([ApplicationConstants.botKey: responseText])
self.tableView.insertRows(at: [IndexPath(row: self.tableViewDataSource.count - 1, section: 0)], with: .automatic)
self.tableView.scrollToBottom()
}
})
}
}
// MARK: Table delegate handling
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableViewDataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = tableViewDataSource[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: data[ApplicationConstants.selfKey] != nil ? "selfCI" : "intentCI", for: indexPath) as! ChatTableViewCell
if data[ApplicationConstants.selfKey] != nil {
cell.selfText.text = data[ApplicationConstants.selfKey]
} else {
cell.botResponseText.text = data[ApplicationConstants.botKey]
}
return cell
}
}
extension UITableView {
func scrollToBottom(animated: Bool = true) {
let sections = self.numberOfSections
let rows = self.numberOfRows(inSection: sections - 1)
if (rows > 0) {
self.scrollToRow(at: NSIndexPath(row: rows - 1, section: sections - 1) as IndexPath, at: .bottom, animated: true)
}
}
}
| fb686a7faaf75518e2b2ec6a88e1516e | 40.416667 | 232 | 0.710262 | false | false | false | false |
vector-im/riot-ios | refs/heads/develop | Riot/Modules/Common/Buttons/Close/RoundedButton.swift | apache-2.0 | 1 | /*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
final class RoundedButton: UIButton, Themable {
// MARK: - Constants
private enum Constants {
static let backgroundColorAlpha: CGFloat = 0.2
static let cornerRadius: CGFloat = 6.0
static let fontSize: CGFloat = 17.0
}
// MARK: - Properties
// MARK: Private
private var theme: Theme?
// MARK: Public
var actionStyle: UIAlertAction.Style = .default {
didSet {
self.updateButtonStyle()
}
}
// MARK: - Life cycle
override func awakeFromNib() {
super.awakeFromNib()
self.layer.masksToBounds = true
self.titleLabel?.font = UIFont.systemFont(ofSize: Constants.fontSize)
self.update(theme: ThemeService.shared().theme)
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = Constants.cornerRadius
}
// MARK: - Private
private func updateButtonStyle() {
guard let theme = theme else {
return
}
let backgroundColor: UIColor
switch self.actionStyle {
case .default:
backgroundColor = theme.tintColor
default:
backgroundColor = theme.noticeColor
}
self.vc_setBackgroundColor(backgroundColor.withAlphaComponent(Constants.backgroundColorAlpha), for: .normal)
self.setTitleColor(backgroundColor, for: .normal)
}
// MARK: - Themable
func update(theme: Theme) {
self.theme = theme
self.updateButtonStyle()
}
}
| 60924064e0373a0e53cf432ebddc0395 | 25.2 | 116 | 0.626852 | false | false | false | false |
Xiomara7/bookiao-ios | refs/heads/master | bookiao-ios/EmployeeViewController.swift | mit | 1 | //
// EmployeeViewController.swift
// bookiao-ios
//
// Created by Xiomara on 11/1/14.
// Copyright (c) 2014 UPRRP. All rights reserved.
//
class EmployeeViewController: UIViewController, UIPickerViewDelegate {
let application = UIApplication.sharedApplication().delegate as AppDelegate
class Singleton {
class var sharedInstance : Singleton {
struct Static {
static let instance : Singleton = Singleton()
}
return Static.instance
}
}
let pickerView = UIPickerView()
var businessResponse: Int = Int()
var placetxtField: UITextField = CustomDesign.getNameTxtField
var emailtxtField: UITextField = CustomDesign.getNameTxtField
var passwtxtField: UITextField = CustomDesign.getNameTxtField
var confirmsField: UITextField = CustomDesign.getNameTxtField
var nameTextField: UITextField = CustomDesign.getNameTxtField
var localTxtField: UITextField = CustomDesign.getNameTxtField
let registerButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
override func viewDidLoad() {
let customDesign = CustomDesign()
self.view.backgroundColor = customDesign.UIColorFromRGB(0xE4E4E4)
super.viewDidLoad()
nameTextField.frame = (CGRectMake(20, 70, self.view.bounds.width - 40, 40))
nameTextField.placeholder = "Nombre"
emailtxtField.frame = CGRectMake(20, 120, self.view.bounds.width - 40, 40)
emailtxtField.placeholder = "Correo electrónico"
passwtxtField.frame = CGRectMake(20, 170, self.view.bounds.width - 40, 40)
passwtxtField.placeholder = "Contraseña"
confirmsField.frame = CGRectMake(20, 220, self.view.bounds.width - 40, 40)
confirmsField.placeholder = "Número telefónico"
placetxtField.frame = CGRectMake(20, 270, self.view.bounds.width - 40, 40)
placetxtField.placeholder = "Negocio"
localTxtField.frame = (CGRectMake(20, 320, self.view.bounds.width - 40, 40))
localTxtField.placeholder = "Localización"
registerButton.frame = CGRectMake(20, 440, self.view.bounds.width - 40, 40)
registerButton.tintColor = UIColor.whiteColor()
registerButton.backgroundColor = customDesign.UIColorFromRGB(0x34A3DB)
registerButton.titleLabel?.font = UIFont.boldSystemFontOfSize(16.0)
registerButton.setTitle("Registrarme", forState: UIControlState.Normal)
registerButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview( emailtxtField)
self.view.addSubview( placetxtField)
self.view.addSubview( passwtxtField)
self.view.addSubview( localTxtField)
self.view.addSubview( confirmsField)
self.view.addSubview( nameTextField)
self.view.addSubview(registerButton)
pickerView.delegate = self
placetxtField.inputView = pickerView
// Do any additional setup after loading the view.
let postButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("dismiss"))
self.navigationItem.leftBarButtonItem = postButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool) {
self.tabBarController?.navigationItem.title = "Empleado"
self.tabBarController?.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.tabBarController?.navigationController?.navigationBar.backgroundColor = UIColor.whiteColor()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func dismiss() {
let back = LoginViewController(nibName: nil, bundle: nil)
self.presentViewController(back, animated: true, completion: nil)
}
func buttonAction(sender:UIButton!) {
let request = HTTPrequests()
let name = nameTextField.text
let email = emailtxtField.text
let phone = confirmsField.text
let password = passwtxtField.text
let location = localTxtField.text
let business = placetxtField.text
let businessID = businessResponse
request.registerRequest(email, name: name, phone: phone, passwd: password) {(str, error) -> Void in
if let ok = str {request.authRequest(email, passwd: password) {(str, error) -> Void in
if let ok = str {request.employeeReq(email, name: name, phone: phone, business: 1) {(str, error) -> Void in
if let ok = str {request.getUserInfo(email, completion: { (str, error) -> Void in
if let ok = str {
dispatch_async(dispatch_get_main_queue(), {
let views = ViewController()
self.presentViewController(views, animated: true, completion: nil)
})}})}}}}}
}
}
// returns the number of 'columns' to display.
func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{
return 1
}
// returns the # of rows in each component..
func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int {
return DataManager.sharedManager.titles.count
}
func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
return DataManager.sharedManager.titles[row]["name"] as String
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) {
println("titles: \(DataManager.sharedManager.titles)")
placetxtField.text = DataManager.sharedManager.titles[row]["name"] as String
businessResponse = row + 1
}
} | c5f91d280c95094ec9938a4bde099cd7 | 40.451389 | 133 | 0.666052 | false | false | false | false |
Pursuit92/antlr4 | refs/heads/master | runtime/Swift/Antlr4/org/antlr/v4/runtime/atn/ATN.swift | bsd-3-clause | 3 | /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
public class ATN {
public static let INVALID_ALT_NUMBER: Int = 0
public final var states: Array<ATNState?> = Array<ATNState?>()
/** Each subrule/rule is a decision point and we must track them so we
* can go back later and build DFA predictors for them. This includes
* all the rules, subrules, optional blocks, ()+, ()* etc...
*/
public final var decisionToState: Array<DecisionState> = Array<DecisionState>()
/**
* Maps from rule index to starting state number.
*/
public final var ruleToStartState: [RuleStartState]!
/**
* Maps from rule index to stop state number.
*/
public final var ruleToStopState: [RuleStopState]!
public final let modeNameToStartState: Dictionary<String, TokensStartState> = Dictionary<String, TokensStartState>()
//LinkedHashMap<String, TokensStartState>();
/**
* The type of the ATN.
*/
public let grammarType: ATNType!
/**
* The maximum value for any symbol recognized by a transition in the ATN.
*/
public let maxTokenType: Int
/**
* For lexer ATNs, this maps the rule index to the resulting token type.
* For parser ATNs, this maps the rule index to the generated bypass token
* type if the
* {@link org.antlr.v4.runtime.atn.ATNDeserializationOptions#isGenerateRuleBypassTransitions}
* deserialization option was specified; otherwise, this is {@code null}.
*/
public final var ruleToTokenType: [Int]!
/**
* For lexer ATNs, this is an array of {@link org.antlr.v4.runtime.atn.LexerAction} objects which may
* be referenced by action transitions in the ATN.
*/
public final var lexerActions: [LexerAction]!
public final var modeToStartState: Array<TokensStartState> = Array<TokensStartState>()
/** Used for runtime deserialization of ATNs from strings */
public init(_ grammarType: ATNType, _ maxTokenType: Int) {
self.grammarType = grammarType
self.maxTokenType = maxTokenType
}
/** Compute the set of valid tokens that can occur starting in state {@code s}.
* If {@code ctx} is null, the set of tokens will not include what can follow
* the rule surrounding {@code s}. In other words, the set will be
* restricted to tokens reachable staying within {@code s}'s rule.
*/
public func nextTokens(_ s: ATNState, _ ctx: RuleContext?)throws -> IntervalSet {
let anal: LL1Analyzer = LL1Analyzer(self)
let next: IntervalSet = try anal.LOOK(s, ctx)
return next
}
/**
* Compute the set of valid tokens that can occur starting in {@code s} and
* staying in same rule. {@link org.antlr.v4.runtime.Token#EPSILON} is in set if we reach end of
* rule.
*/
public func nextTokens(_ s: ATNState) throws -> IntervalSet {
if let nextTokenWithinRule = s.nextTokenWithinRule
{
return nextTokenWithinRule
}
let intervalSet = try nextTokens(s, nil)
s.nextTokenWithinRule = intervalSet
try intervalSet.setReadonly(true)
return intervalSet
}
public func addState(_ state: ATNState?) {
if let state = state {
state.atn = self
state.stateNumber = states.count
}
states.append(state)
}
public func removeState(_ state: ATNState) {
states[state.stateNumber] = nil
//states.set(state.stateNumber, nil); // just free mem, don't shift states in list
}
@discardableResult
public func defineDecisionState(_ s: DecisionState) -> Int {
decisionToState.append(s)
s.decision = decisionToState.count-1
return s.decision
}
public func getDecisionState(_ decision: Int) -> DecisionState? {
if !decisionToState.isEmpty {
return decisionToState[decision]
}
return nil
}
public func getNumberOfDecisions() -> Int {
return decisionToState.count
}
/**
* Computes the set of input symbols which could follow ATN state number
* {@code stateNumber} in the specified full {@code context}. This method
* considers the complete parser context, but does not evaluate semantic
* predicates (i.e. all predicates encountered during the calculation are
* assumed true). If a path in the ATN exists from the starting state to the
* {@link org.antlr.v4.runtime.atn.RuleStopState} of the outermost context without matching any
* symbols, {@link org.antlr.v4.runtime.Token#EOF} is added to the returned set.
*
* <p>If {@code context} is {@code null}, it is treated as
* {@link org.antlr.v4.runtime.ParserRuleContext#EMPTY}.</p>
*
* @param stateNumber the ATN state number
* @param context the full parse context
* @return The set of potentially valid input symbols which could follow the
* specified state in the specified context.
* @throws IllegalArgumentException if the ATN does not contain a state with
* number {@code stateNumber}
*/
public func getExpectedTokens(_ stateNumber: Int, _ context: RuleContext) throws -> IntervalSet {
if stateNumber < 0 || stateNumber >= states.count {
throw ANTLRError.illegalArgument(msg: "Invalid state number.")
/* throw IllegalArgumentException("Invalid state number."); */
}
var ctx: RuleContext? = context
//TODO: s may be nil
let s: ATNState = states[stateNumber]!
var following: IntervalSet = try nextTokens(s)
if !following.contains(CommonToken.EPSILON) {
return following
}
let expected: IntervalSet = try IntervalSet()
try expected.addAll(following)
try expected.remove(CommonToken.EPSILON)
while let ctxWrap = ctx , ctxWrap.invokingState >= 0 && following.contains(CommonToken.EPSILON) {
let invokingState: ATNState = states[ctxWrap.invokingState]!
let rt: RuleTransition = invokingState.transition(0) as! RuleTransition
following = try nextTokens(rt.followState)
try expected.addAll(following)
try expected.remove(CommonToken.EPSILON)
ctx = ctxWrap.parent
}
if following.contains(CommonToken.EPSILON) {
try expected.add(CommonToken.EOF)
}
return expected
}
public final func appendDecisionToState(_ state: DecisionState) {
decisionToState.append(state)
}
public final func appendModeToStartState(_ state: TokensStartState) {
modeToStartState.append(state)
}
}
| ef96c3910c0cfe0b5cf859a381372da7 | 35.956757 | 121 | 0.656721 | false | false | false | false |
NikitaAsabin/pdpDecember | refs/heads/master | Pods/FSHelpers+Swift/Swift/Helpers/FSExtensions/FSE+UIImage.swift | mit | 1 | //
// FSE+UIImage.swift
// DayPhoto
//
// Created by Kruperfone on 23.09.15.
// Copyright © 2015 Flatstack. All rights reserved.
//
import UIKit
public struct FSBitmapPixel {
public var r: UInt8
public var g: UInt8
public var b: UInt8
public var a: UInt8
public init (value: UInt32) {
self.r = UInt8((value >> 0) & 0xFF)
self.g = UInt8((value >> 8) & 0xFF)
self.b = UInt8((value >> 16) & 0xFF)
self.a = UInt8((value >> 24) & 0xFF)
}
public init (color: UIColor) {
var red: CGFloat = -1
var green: CGFloat = -1
var blue: CGFloat = -1
var alpha: CGFloat = -1
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
self.r = UInt8(red * 255)
self.g = UInt8(green * 255)
self.b = UInt8(blue * 255)
self.a = UInt8(alpha * 255)
}
public var value: UInt32 {
let red = UInt32(self.r) << 0
let green = UInt32(self.g) << 8
let blue = UInt32(self.b) << 16
let alpha = UInt32(self.a) << 24
let result = red+green+blue+alpha
return result
}
public var color: UIColor {
return UIColor(
red: CGFloat(self.r)/255,
green: CGFloat(self.g)/255,
blue: CGFloat(self.b)/255,
alpha: CGFloat(self.a)/255)
}
public var description: String {
return "\(self.r)|\(self.g)|\(self.b)|\(self.a)"
}
public var brightness: UInt8 {
return UInt8((CGFloat(self.brightness32)/(255*3))*255)
}
private var brightness32: UInt32 {
return UInt32(self.r) + UInt32(self.g) + UInt32(self.b)
}
}
public class FSBitmap: NSObject {
private var bytesPerRow: Int {
return Int(self.size.width)
}
public var data: UnsafeMutablePointer<UInt32>
public var size: (width: Int, height: Int)
public init (data: UnsafeMutablePointer<UInt32>, size: (width: Int, height: Int)) {
self.size = size
self.data = data
super.init()
}
public init (size: (width: Int, height: Int)) {
self.size = size
self.data = UnsafeMutablePointer<UInt32>(calloc(self.size.width*self.size.height, sizeof(UInt32)))
super.init()
}
convenience public init (size: CGSize) {
self.init(size: (width: Int(size.width), height: Int(size.height)))
}
public func getCGImage () -> CGImage {
let width = self.size.width
let height = self.size.height
let bitsPerComponent = 8
let bytesPerPixel = 4
let bitsPerPixel = bytesPerPixel * 8
let bytesPerRow = width * bytesPerPixel
let colorSpace = CGColorSpaceCreateDeviceRGB()
let renderingIntent = CGColorRenderingIntent.RenderingIntentDefault
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue | CGBitmapInfo.ByteOrder32Big.rawValue)
let bitmapData = self.data
let bufferLength = width * height * bytesPerPixel
let provider = CGDataProviderCreateWithData(nil, bitmapData, bufferLength, nil)
let image = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, provider, nil, true, renderingIntent)
return image!
}
public func getUIImage (scale: CGFloat = UIScreen.mainScreen().scale, orientation: UIImageOrientation = UIImageOrientation.Up) -> UIImage {
let image = self.getCGImage()
return UIImage(CGImage: image, scale: scale, orientation: orientation)
}
public func getPixel (x: Int, _ y: Int) -> FSBitmapPixel {
return FSBitmapPixel(value: self.data[self.index(x, y)])
}
public func setPixel (pixel: FSBitmapPixel, point: (x: Int, y: Int)) {
self.data[self.index(point.x, point.y)] = pixel.value
}
private func index (x: Int, _ y: Int) -> Int {
return self.bytesPerRow*y + x
}
}
public extension UIImage {
public func fs_getBitmap () -> FSBitmap {
let imageRef: CGImageRef? = self.CGImage
//Get image width, height
let pixelsWide = CGImageGetWidth(imageRef)
let pixelsHigh = CGImageGetHeight(imageRef)
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and alpha.
let bytesPerPixel = 4
let bitsPerComponent = 8
let bitmapBytesPerRow = Int(pixelsWide) * bytesPerPixel
// Use the generic RGB color space.
let colorSpace = CGColorSpaceCreateDeviceRGB()
// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
let bitmapData = UnsafeMutablePointer<UInt32>(calloc(pixelsWide*pixelsHigh, sizeof(UInt32)))
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue | CGBitmapInfo.ByteOrder32Big.rawValue
let context = CGBitmapContextCreate(bitmapData, pixelsWide, pixelsHigh, bitsPerComponent, bitmapBytesPerRow, colorSpace, bitmapInfo)
CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(pixelsWide), CGFloat(pixelsHigh)), imageRef)
return FSBitmap(data: bitmapData, size: (pixelsWide, pixelsHigh))
}
public var fs_base64: String {
let imageData = UIImagePNGRepresentation(self)!
let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return base64String
}
}
| e01c489f400c63cab5c3729957daebd7 | 33.04023 | 164 | 0.605099 | false | false | false | false |
ibari/ios-twitter | refs/heads/master | Twitter/User.swift | gpl-2.0 | 1 | //
// User.swift
// Twitter
//
// Created by Ian on 5/20/15.
// Copyright (c) 2015 Ian Bari. All rights reserved.
//
import UIKit
var _currentUser: User?
let currentUserKey = "kCurrentUserKey"
let userDidLoginNotification = "userDidLoginNotification"
let userDidLogoutNotification = "userDidLogoutNotification"
class User: NSObject {
var id: Int?
var name: String?
var screenName: String?
var profileImageURL: NSURL?
var profileBackgroundImageURL: NSURL?
var statusesCount: Int?
var followersCount: Int?
var friendsCount: Int?
var dictionary: NSDictionary?
init(dictionary: NSDictionary) {
self.dictionary = dictionary
id = dictionary["id"] as? Int
name = dictionary["name"] as? String
screenName = dictionary["screen_name"] as? String
let profileImageURLString = dictionary["profile_image_url"] as? String
if profileImageURLString != nil {
profileImageURL = NSURL(string: profileImageURLString!)!
} else {
profileImageURL = nil
}
let profileBackgroundImageURLString = dictionary["profile_background_image_url"] as? String
if profileBackgroundImageURLString != nil {
profileBackgroundImageURL = NSURL(string: profileBackgroundImageURLString!)!
} else {
profileBackgroundImageURL = nil
}
statusesCount = dictionary["statuses_count"] as? Int
followersCount = dictionary["followers_count"] as? Int
friendsCount = dictionary["friends_count"] as? Int
}
func logout() {
User.currentUser = nil
TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
NSNotificationCenter.defaultCenter().postNotificationName(userDidLogoutNotification, object: nil)
}
class var currentUser: User? {
get {
if _currentUser == nil {
var data = NSUserDefaults.standardUserDefaults().objectForKey(currentUserKey) as? NSData
if data != nil {
var dictionary = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary
_currentUser = User(dictionary: dictionary)
}
}
return _currentUser
}
set(user) {
_currentUser = user
if _currentUser != nil {
var data = NSJSONSerialization.dataWithJSONObject(user!.dictionary!, options: nil, error: nil)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: currentUserKey)
} else {
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: currentUserKey)
}
NSUserDefaults.standardUserDefaults().synchronize()
}
}
}
| d744be74e4f557474f9ff268ac8f1f42 | 28.534091 | 115 | 0.688342 | false | false | false | false |
scoremedia/Fisticuffs | refs/heads/master | Sources/Fisticuffs/ComposedBindingHandler.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2019 theScore Inc.
//
// 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
/// A `BindingHandler` whose input and output is a function of the two components `BindingHandler`s
class ComposedBindingHandler<Control: AnyObject, InDataValue, OutDataValue, PropertyValue>: BindingHandler<Control, InDataValue, PropertyValue> {
let bindingHandler1: BindingHandler<Control, InDataValue, OutDataValue>
let bindingHandler2: BindingHandler<Control, OutDataValue, PropertyValue>
private var bindingHandler1OldValue: OutDataValue?
init(handler1: BindingHandler<Control, InDataValue, OutDataValue>, handler2: BindingHandler<Control, OutDataValue, PropertyValue>) {
self.bindingHandler1 = handler1
self.bindingHandler2 = handler2
}
override func set(control: Control, oldValue: InDataValue?, value: InDataValue, propertySetter: @escaping PropertySetter) {
bindingHandler1.set(control: control, oldValue: oldValue, value: value) { [handler = self.bindingHandler2, oldValue = bindingHandler1OldValue, weak self] (control, value) in
handler.set(control: control, oldValue: oldValue, value: value, propertySetter: propertySetter)
self?.bindingHandler1OldValue = value
}
}
override func get(control: Control, propertyGetter: @escaping PropertyGetter) throws -> InDataValue {
try bindingHandler1.get(control: control, propertyGetter: { [handler = self.bindingHandler2] (control) -> OutDataValue in
try! handler.get(control: control, propertyGetter: propertyGetter)
})
}
override func dispose() {
bindingHandler1.dispose()
bindingHandler2.dispose()
super.dispose()
}
}
/// Composes two `BindingHandler` objcts so that the data flows through the LHS first performing and transfromations and then the RHS
///
/// - Parameters:
/// - lhs: The first binding handler
/// - rhs: the second binding handler
/// - Returns: A binding handle that composes the functions of the two `BindingHandler`s provided
public func && <Control: AnyObject, InDataValue, OutDataValue, PropertyValue>(lhs: BindingHandler<Control, InDataValue, OutDataValue>, rhs:BindingHandler<Control, OutDataValue, PropertyValue>) -> BindingHandler<Control, InDataValue, PropertyValue> {
ComposedBindingHandler(handler1: lhs, handler2: rhs)
}
| e9d8bcb38f5ae5d7ce2b6c47b329c34d | 51.575758 | 249 | 0.739769 | false | false | false | false |
abdullah-chhatra/iLayout | refs/heads/master | Example/Example/ExampleViewController.swift | mit | 1 | //
// ExampleViewController.swift
// Example
//
// Created by Abdulmunaf Chhatra on 6/6/15.
// Copyright (c) 2015 Abdulmunaf Chhatra. All rights reserved.
//
import UIKit
class ExampleViewController: UIViewController {
let myView : UIView
let titleText : String
init(view: UIView, titleText: String) {
myView = view
self.titleText = titleText
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = myView
navigationItem.title = titleText
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.isTranslucent = false
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: UIBarButtonItemStyle.plain, target: self, action: nil)
}
}
| eab082898406342d2ce152301dd43416 | 24.459459 | 135 | 0.649682 | false | false | false | false |
stone-payments/onestap-sdk-ios | refs/heads/master | OnestapSDK/User/Entities/Vehicle.swift | apache-2.0 | 1 | //
// Vehicle.swift
// OnestapSDK
//
// Created by Munir Wanis on 22/08/17.
// Copyright © 2017 Stone Payments. All rights reserved.
//
import Foundation
public struct Vehicle {
public init(licensePlate: String) {
self.licensePlate = licensePlate
}
public internal(set) var key: String = ""
public var licensePlate: String
public var licensePlateCity: String? = nil
public var licensePlateState: String? = nil
public var licensePlateCountry: String? = nil
}
extension Vehicle: Encondable {
func toDictionary() -> JSON {
return [
"licensePlate": licensePlate,
"licensePlateCity": licensePlateCity as Any,
"licensePlateState": licensePlateState as Any,
"licensePlateCountry": licensePlateCountry as Any
]
}
}
| f8ed1722df44603ee63e448c5d91ed89 | 25.516129 | 61 | 0.656934 | false | true | false | false |
xgdgsc/AlecrimCoreData | refs/heads/master | Source/AlecrimCoreData/Core/Protocols/AttributeQueryType.swift | mit | 1 | //
// AttributeQueryType.swift
// AlecrimCoreData
//
// Created by Vanderlei Martinelli on 2015-08-08.
// Copyright (c) 2015 Alecrim. All rights reserved.
//
import Foundation
import CoreData
public protocol AttributeQueryType: CoreDataQueryable {
var returnsDistinctResults: Bool { get set }
var propertiesToFetch: [String] { get set }
}
// MARK: -
extension AttributeQueryType {
public func distinct() -> Self {
var clone = self
clone.returnsDistinctResults = true
return self
}
}
// MARK: - GenericQueryable
extension AttributeQueryType {
public func toArray() -> [Self.Item] {
var results: [Self.Item] = []
do {
let fetchRequestResult = try self.dataContext.executeFetchRequest(self.toFetchRequest())
if let dicts = fetchRequestResult as? [NSDictionary] {
for dict in dicts {
guard dict.count == 1, let value = dict.allValues.first as? Self.Item else {
throw AlecrimCoreDataError.UnexpectedValue(value: dict)
}
results.append(value)
}
}
else {
throw AlecrimCoreDataError.UnexpectedValue(value: fetchRequestResult)
}
}
catch {
// TODO: throw error?
}
return results
}
}
extension AttributeQueryType where Self.Item: NSDictionary {
public func toArray() -> [NSDictionary] {
do {
let fetchRequestResult = try self.dataContext.executeFetchRequest(self.toFetchRequest())
if let dicts = fetchRequestResult as? [NSDictionary] {
return dicts
}
else {
throw AlecrimCoreDataError.UnexpectedValue(value: fetchRequestResult)
}
}
catch {
// TODO: throw error?
return [NSDictionary]()
}
}
}
// MARK: - CoreDataQueryable
extension AttributeQueryType {
public func toFetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest()
fetchRequest.entity = self.entityDescription
fetchRequest.fetchOffset = self.offset
fetchRequest.fetchLimit = self.limit
fetchRequest.fetchBatchSize = (self.limit > 0 && self.batchSize > self.limit ? 0 : self.batchSize)
fetchRequest.predicate = self.predicate
fetchRequest.sortDescriptors = self.sortDescriptors
//
fetchRequest.resultType = .DictionaryResultType
fetchRequest.returnsDistinctResults = self.returnsDistinctResults
fetchRequest.propertiesToFetch = self.propertiesToFetch
//
return fetchRequest
}
}
| 421f829b32f92a16fd65c53fc458d8ec | 25.036364 | 106 | 0.582053 | false | false | false | false |
jmgc/swift | refs/heads/master | test/attr/global_actor.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -typecheck -verify %s -enable-experimental-concurrency
// REQUIRES: concurrency
actor class SomeActor { }
// -----------------------------------------------------------------------
// @globalActor attribute itself.
// -----------------------------------------------------------------------
// Well-formed global actor.
@globalActor
struct GA1 {
static let shared = SomeActor()
}
@globalActor
struct GenericGlobalActor<T> {
static var shared: SomeActor { SomeActor() }
}
// Ill-formed global actors.
@globalActor
open class GA2 { // expected-error{{global actor 'GA2' requires a static property 'shared' that produces an actor instance}}{{17-17=\n public static let shared = <#actor instance#>}}
}
@globalActor
struct GA3 { // expected-error{{global actor 'GA3' requires a static property 'shared' that produces an actor instance}}
let shared = SomeActor() // expected-note{{'shared' property in global actor is not 'static'}}{{3-3=static }}
}
@globalActor
struct GA4 { // expected-error{{global actor 'GA4' requires a static property 'shared' that produces an actor instance}}
private static let shared = SomeActor() // expected-note{{'shared' property has more restrictive access (private) than its global actor (internal)}}{{3-11=}}
}
@globalActor
open class GA5 { // expected-error{{global actor 'GA5' requires a static property 'shared' that produces an actor instance}}
static let shared = SomeActor() // expected-note{{'shared' property has more restrictive access (internal) than its global actor (public)}}{{3-3=public}}
}
@globalActor
struct GA6<T> { // expected-error{{global actor 'GA6' requires a static property 'shared' that produces an actor instance}}
}
extension GA6 where T: Equatable {
static var shared: SomeActor { SomeActor() } // expected-note{{'shared' property in global actor cannot be in a constrained extension}}
}
@globalActor
class GA7 { // expected-error{{global actor 'GA7' requires a static property 'shared' that produces an actor instance}}
static let shared = 5 // expected-note{{'shared' property type 'Int' does not conform to the 'Actor' protocol}}
}
// -----------------------------------------------------------------------
// Applying global actors to entities.
// -----------------------------------------------------------------------
@globalActor
struct OtherGlobalActor {
static let shared = SomeActor()
}
@GA1 func f() {
@GA1 let x = 17 // expected-error{{local variable 'x' cannot have a global actor}}
_ = x
}
@GA1 struct X {
@GA1 var member: Int // expected-error{{stored property 'member' of a struct cannot have a global actor}}
}
struct Y {
@GA1 subscript(i: Int) -> Int { i }
}
@GA1 extension Y { }
@GA1 func g() { }
class SomeClass {
@GA1 init() { }
@GA1 deinit { } // expected-error{{deinitializer cannot have a global actor}}
}
@GA1 typealias Integer = Int // expected-error{{type alias cannot have a global actor}}
@GA1 actor class ActorInTooManyPlaces { } // expected-error{{actor class 'ActorInTooManyPlaces' cannot have a global actor}}
@GA1 @OtherGlobalActor func twoGlobalActors() { } // expected-error{{declaration can not have multiple global actor attributes ('OtherGlobalActor' and 'GA1')}}
struct Container {
// FIXME: Diagnostic could be improved to show the generic arguments.
@GenericGlobalActor<Int> @GenericGlobalActor<String> func twoGenericGlobalActors() { } // expected-error{{declaration can not have multiple global actor attributes ('GenericGlobalActor' and 'GenericGlobalActor')}}
}
// -----------------------------------------------------------------------
// Redundant attributes
// -----------------------------------------------------------------------
extension SomeActor {
@GA1 @actorIndependent func conflict1() { } // expected-error{{instance method 'conflict1()' has multiple actor-isolation attributes ('actorIndependent' and 'GA1')}}
}
| c9b9b46ead9daa5dd9df9c223930b1a4 | 38.16 | 213 | 0.645557 | false | false | false | false |
tomisacat/AudioTips | refs/heads/master | AudioTips/AudioFormatService.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
import AudioToolbox
// function
func openFile() -> AudioFileID? {
let url = Bundle.main.url(forResource: "guitar", withExtension: "m4a")
var fd: AudioFileID? = nil
AudioFileOpenURL(url! as CFURL, .readPermission, kAudioFileM4AType, &fd)
// Or in iOS platform, the file type could be 0 directly
// AudioFileOpenURL(url! as CFURL, .readPermission, 0, &fd)
return fd
}
func closeFile(fd: AudioFileID) {
AudioFileClose(fd)
}
// use
let fd: AudioFileID? = openFile()
if let fd = fd {
var status: OSStatus = noErr
var propertySize: UInt32 = 0
var writable: UInt32 = 0
// magic cookie
status = AudioFileGetPropertyInfo(fd, kAudioFilePropertyMagicCookieData, &propertySize, &writable)
// if status != noErr {
// return
// }
let magic: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>.allocate(capacity: Int(propertySize))
status = AudioFileGetProperty(fd, kAudioFilePropertyMagicCookieData, &propertySize, magic)
// if status != noErr {
// return
// }
// format info
var desc: AudioStreamBasicDescription = AudioStreamBasicDescription()
var descSize: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
status = AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, propertySize, magic, &descSize, &desc)
// if status != noErr {
// return
// }
print(desc)
// format name
status = AudioFileGetProperty(fd, kAudioFilePropertyDataFormat, &descSize, &desc)
// if status != noErr {
// return
// }
var formatName: CFString = String() as CFString
var formatNameSize: UInt32 = UInt32(MemoryLayout<CFString>.size)
status = AudioFormatGetProperty(kAudioFormatProperty_FormatName, descSize, &desc, &formatNameSize, &formatName)
// if status != noErr {
// return
// }
print(formatName)
// format info
var formatInfo: AudioFormatInfo = AudioFormatInfo(mASBD: desc,
mMagicCookie: magic,
mMagicCookieSize: propertySize)
var outputFormatInfoSize: UInt32 = 0
status = AudioFormatGetPropertyInfo(kAudioFormatProperty_FormatList,
UInt32(MemoryLayout<AudioFormatInfo>.size),
&formatInfo,
&outputFormatInfoSize)
// format list
let formatListItem: UnsafeMutablePointer<AudioFormatListItem> = UnsafeMutablePointer<AudioFormatListItem>.allocate(capacity: Int(outputFormatInfoSize))
status = AudioFormatGetProperty(kAudioFormatProperty_FormatList,
UInt32(MemoryLayout<AudioFormatInfo>.size),
&formatInfo,
&outputFormatInfoSize,
formatListItem)
// if status != noErr {
// return
// }
let itemCount = outputFormatInfoSize / UInt32(MemoryLayout<AudioFormatListItem>.size)
for idx in 0..<itemCount {
let item: AudioFormatListItem = formatListItem.advanced(by: Int(idx)).pointee
print("channel layout tag is \(item.mChannelLayoutTag), mASBD is \(item.mASBD)")
}
closeFile(fd: fd)
}
| 55b27c307b0e03ab71bc0ef989775278 | 33.34 | 155 | 0.618521 | false | false | false | false |
amagain/Typhoon-Swift-Example | refs/heads/master | PocketForecastTests/Integration/WeatherClientTests.swift | apache-2.0 | 3 | ////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Typhoon Framework Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
import PocketForecast
public class WeatherClientTests : XCTestCase {
var weatherClient: WeatherClient!
public override func setUp() {
let assembly = ApplicationAssembly().activate()
let configurer = TyphoonConfigPostProcessor()
configurer.useResourceWithName("Configuration.plist")
assembly.attachPostProcessor(configurer)
self.weatherClient = assembly.coreComponents.weatherClient() as! WeatherClient
}
public func test_it_receives_a_wather_report_given_a_valid_city() {
var receivedReport : WeatherReport?
self.weatherClient.loadWeatherReportFor("Manila", onSuccess: {
(weatherReport) in
receivedReport = weatherReport
}, onError: {
(message) in
println("Unexpected error: " + message)
})
TyphoonTestUtils.waitForCondition( { () -> Bool in
return receivedReport != nil
}, andPerformTests: {
println(String(format: "Got report: %@", receivedReport!))
})
}
public func test_it_invokes_error_block_given_invalid_city() {
var receivedMessage : String?
self.weatherClient.loadWeatherReportFor("Foobarville", onSuccess: nil, onError: {
(message) in
receivedMessage = message
println("Got message: " + message)
})
TyphoonTestUtils.waitForCondition( { () -> Bool in
return receivedMessage == "Unable to find any matching weather location to the query submitted!"
})
}
}
| 0321de8e326e191a33ba5bbf9f7dfcd6 | 28.333333 | 108 | 0.543182 | false | true | false | false |
googleprojectzero/fuzzilli | refs/heads/main | Sources/Fuzzilli/Base/Contributor.swift | apache-2.0 | 1 | // Copyright 2020 Google 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
//
// https://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.
/// Something that contributes to the creation of a program.
/// This class is used to compute detailed statistics about correctness and timeout rates as well as the number of interesting or crashing programs generated, etc.
public class Contributor {
// Number of valid programs produced (i.e. programs that run to completion)
private var validSamples = 0
// Number of interesting programs produces (i.e. programs that triggered new interesting behavior). All interesting programs are also valid.
private var interestingSamples = 0
// Number of invalid programs produced (i.e. programs that raised an exception or timed out)
private var invalidSamples = 0
// Number of produced programs that resulted in a timeout.
private var timedOutSamples = 0
// Number of crashing programs produced.
private var crashingSamples = 0
// Number of times this instance failed to generate/mutate code.
private var failures = 0
// Total number of instructions added to programs by this contributor.
private var totalInstructionProduced = 0
func generatedValidSample() {
validSamples += 1
}
func generatedInterestingSample() {
interestingSamples += 1
}
func generatedInvalidSample() {
invalidSamples += 1
}
func generatedTimeOutSample() {
timedOutSamples += 1
}
func generatedCrashingSample() {
crashingSamples += 1
}
func addedInstructions(_ n: Int) {
totalInstructionProduced += n
}
func failedToGenerate() {
failures += 1
}
public var crashesFound: Int {
return crashingSamples
}
public var totalSamples: Int {
return validSamples + interestingSamples + invalidSamples + timedOutSamples + crashingSamples
}
public var correctnessRate: Double {
guard totalSamples > 0 else { return 1.0 }
return Double(validSamples + interestingSamples) / Double(totalSamples)
}
public var interestingSamplesRate: Double {
guard totalSamples > 0 else { return 0.0 }
return Double(interestingSamples) / Double(totalSamples)
}
public var timeoutRate: Double {
guard totalSamples > 0 else { return 0.0 }
return Double(timedOutSamples) / Double(totalSamples)
}
public var failureRate: Double {
let totalAttempts = totalSamples + failures
guard totalAttempts > 0 else { return 0.0 }
return Double(failures) / Double(totalAttempts)
}
// Note: even if for example a CodeGenerator always generates exactly one instruction, this number may be
// slightly higher than one as the same CodeGenerator may run multiple times to generate one program.
public var avgNumberOfInstructionsGenerated: Double {
guard totalSamples > 0 else { return 0.0 }
return Double(totalInstructionProduced) / Double(totalSamples)
}
}
/// All "things" (Mutators, CodeGenerators, ProgramTemplates, ...) that contributed directly (i.e. not including parent programs) to the creation of a particular program.
public struct Contributors {
private var chain = [Contributor]()
public init() {}
public mutating func add(_ contributor: Contributor) {
// The chains should be pretty short, so a linear search is probably faster than using an additional Set.
if !chain.contains(where: { $0 === contributor}) {
chain.append(contributor)
}
}
public func generatedValidSample() {
chain.forEach { $0.generatedValidSample() }
}
public func generatedInterestingSample() {
chain.forEach { $0.generatedInterestingSample() }
}
public func generatedInvalidSample() {
chain.forEach { $0.generatedInvalidSample() }
}
public func generatedCrashingSample() {
chain.forEach { $0.generatedCrashingSample() }
}
public func generatedTimeOutSample() {
chain.forEach { $0.generatedTimeOutSample() }
}
public mutating func removeAll() {
chain.removeAll()
}
}
| fc46af64146d78e8ac13c8a1ca1e7c0b | 32.978102 | 170 | 0.690226 | false | false | false | false |
BigxMac/firefox-ios | refs/heads/master | StorageTests/TestTableTable.swift | mpl-2.0 | 19 | /* 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 XCTest
class TestSchemaTable: XCTestCase {
// This is a very basic test. Adds an entry. Retrieves it, and then clears the database
func testTable() {
let files = MockFiles()
var db = BrowserDB(filename: "browser.db", files: files)
// Test creating a table
var testTable = getCreateTable()
db.createOrUpdate(testTable)
// Now make sure the item is in the table-table
var err: NSError? = nil
let table = SchemaTable<TableInfo>()
var cursor = db.withReadableConnection(&err) { (connection, err) -> Cursor<TableInfo> in
return table.query(connection, options: QueryOptions(filter: testTable.name))
}
verifyTable(cursor, table: testTable)
// We have to close this cursor to ensure we don't get results from a sqlite memory cache below when
// we requery the table.
cursor.close()
// Now test updating the table
testTable = getUpgradeTable()
db.createOrUpdate(testTable)
cursor = db.withReadableConnection(&err) { (connection, err) -> Cursor<TableInfo> in
return table.query(connection, options: QueryOptions(filter: testTable.name))
}
verifyTable(cursor, table: testTable)
// We have to close this cursor to ensure we don't get results from a sqlite memory cache below when
// we requery the table.
cursor.close()
// Now try updating it again to the same version. This shouldn't call create or upgrade
testTable = getNoOpTable()
db.createOrUpdate(testTable)
// Cleanup
files.remove("browser.db")
}
// Helper for verifying that the data in a cursor matches whats in a table
private func verifyTable(cursor: Cursor<TableInfo>, table: TestTable) {
XCTAssertEqual(cursor.count, 1, "Cursor is the right size")
var data = cursor[0] as! TableInfoWrapper
XCTAssertNotNil(data, "Found an object of the right type")
XCTAssertEqual(data.name, table.name, "Table info has the right name")
XCTAssertEqual(data.version, table.version, "Table info has the right version")
}
// A test class for fake table creation/upgrades
class TestTable: Table {
var name: String { return "testName" }
var _version: Int = -1
var version: Int { return _version }
typealias Type = Int
// Called if the table is created
let createCallback: () -> Bool
// Called if the table is upgraded
let updateCallback: (from: Int, to: Int) -> Bool
let dropCallback: (() -> Void)?
init(version: Int,
createCallback: () -> Bool,
updateCallback: (from: Int, to: Int) -> Bool,
dropCallback: (() -> Void)? = nil) {
self._version = version
self.createCallback = createCallback
self.updateCallback = updateCallback
self.dropCallback = dropCallback
}
func exists(db: SQLiteDBConnection) -> Bool {
let res = db.executeQuery("SELECT name FROM sqlite_master WHERE type = 'table' AND name=?", factory: StringFactory, withArgs: [name])
return res.count > 0
}
func drop(db: SQLiteDBConnection) -> Bool {
if let dropCallback = dropCallback {
dropCallback()
}
let sqlStr = "DROP TABLE IF EXISTS \(name)"
let err = db.executeChange(sqlStr, withArgs: [])
return err == nil
}
func create(db: SQLiteDBConnection, version: Int) -> Bool {
// BrowserDB uses a different query to determine if a table exists, so we need to ensure it actually happens
db.executeChange("CREATE TABLE IF NOT EXISTS \(name) (ID INTEGER PRIMARY KEY AUTOINCREMENT)")
return createCallback()
}
func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool {
return updateCallback(from: from, to: to)
}
// These are all no-ops for testing
func insert(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { return -1 }
func update(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { return -1 }
func delete(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { return -1 }
func query(db: SQLiteDBConnection, options: QueryOptions?) -> Cursor<Type> { return Cursor(status: .Failure, msg: "Shouldn't hit this") }
}
// This function will create a table with appropriate callbacks set. Pass "create" if you expect the table to
// be created. Pass "update" if it should be updated. Pass anythign else if neither callback should be called.
func getCreateTable() -> TestTable {
let t = TestTable(version: 1, createCallback: { _ -> Bool in
XCTAssert(true, "Should have created table")
return true
}, updateCallback: { (from, to) -> Bool in
XCTFail("Should not try to update table")
return false
})
return t
}
func getUpgradeTable() -> TestTable {
var upgraded = false
var dropped = false
let t = TestTable(version: 2, createCallback: { _ -> Bool in
XCTAssertTrue(dropped, "Create should be called after upgrade attempt")
return true
}, updateCallback: { (from, to) -> Bool in
XCTAssert(true, "Should try to update table")
XCTAssertEqual(from, 1, "From is correct")
XCTAssertEqual(to, 2, "To is correct")
// We'll return false here. The db will take that as a sign to drop and recreate our table.
upgraded = true
return false
}, dropCallback: { () -> Void in
XCTAssertTrue(upgraded, "Should try to drop table")
dropped = true
})
return t
}
func getNoOpTable() -> TestTable {
let t = TestTable(version: 2, createCallback: { _ -> Bool in
XCTFail("Should not try to create table")
return false
}, updateCallback: { (from, to) -> Bool in
XCTFail("Should not try to update table")
return false
})
return t
}
}
| ad4fe73b452c8902d3fcb56487e1d5d7 | 40.240506 | 145 | 0.608195 | false | true | false | false |
daaavid/TIY-Assignments | refs/heads/master | 14--High-Voltage/High-Voltage/High-Voltage/Brainerino.swift | cc0-1.0 | 1 | //
// CalculatorBrainerino.swift
// High-Voltage
//
// Created by david on 10/22/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import Foundation
class Brainerino
{
var watts: Float = 0.0
var volts: Float = 0.0
var amps: Float = 0.0
var ohms: Float = 0.0
var wattStr = ""
var voltStr = ""
var ampStr = ""
var ohmStr = ""
var calculateFinished = false
func calculate()
{
if watts != 0 && amps != 0
{
ohms = ohmsCalc(3)
volts = voltsCalc(2)
}
else if watts != 0 && volts != 0
{
ohms = ohmsCalc(2)
amps = ampsCalc(2)
}
else if watts != 0 && ohms != 0
{
amps = ampsCalc(2)
volts = voltsCalc(3)
}
else if volts != 0 && amps != 0
{
ohms = ohmsCalc(1)
watts = wattsCalc(1)
}
else if volts != 0 && ohms != 0
{
watts = wattsCalc(2)
amps = ampsCalc(1)
}
else if ohms != 0 && amps != 0
{
watts = wattsCalc(3)
volts = voltsCalc(1)
}
wattStr = String(watts)
voltStr = String(volts)
ampStr = String(amps)
ohmStr = String(ohms)
calculateFinished = true
}
func ohmsCalc(cv: Int) -> Float
{
switch cv
{
case 1:
ohms = volts / amps
case 2:
ohms = (volts * volts) / watts
case 3:
ohms = watts / (amps * amps)
default:
ohms = 1000000
}
return ohms
}
func ampsCalc(cv: Int) -> Float
{
switch cv
{
case 1:
amps = volts / ohms
case 2:
amps = watts / volts
case 3:
amps = Float(sqrt(Double(watts) / Double(ohms)))
default:
amps = 1000000
}
return amps
}
func voltsCalc(cv: Int) -> Float
{
switch cv
{
case 1:
volts = amps * ohms
case 2:
volts = watts / amps
case 3:
volts = Float(sqrt(Double(watts) * Double(ohms)))
default:
volts = 1000000
}
return volts
}
func wattsCalc(cv: Int) -> Float
{
switch cv
{
case 1:
watts = volts * amps
case 2:
watts = (volts * volts) / ohms
case 3:
watts = (amps * amps) * ohms
default:
watts = 1000000
}
return watts
}
func reset()
{
watts = 0
volts = 0
amps = 0
ohms = 0
wattStr = ""
voltStr = ""
ampStr = ""
ohmStr = ""
}
} | 663262ac257915832ccc8c6afdf60106 | 19.190141 | 61 | 0.417306 | false | false | false | false |
mgadda/zig | refs/heads/master | Sources/zig/Shell.swift | mit | 1 | //
// Shell.swift
// zigPackageDescription
//
// Created by Matt Gadda on 11/14/17.
//
import Foundation
struct Shell {
/// Run command at `path` with `arguments`. `run` does not use `Process`
/// because it does not correctly set up `STDIN`, `STDOUT`, `STDERR` for the
/// child process. Instead it uses posix_spawn directly.
static func run(path: String, arguments: [String]) throws {
var pid: pid_t = pid_t()
let cPath = strdup("/usr/bin/env")
let cArgs = ([path] + arguments).map { $0.withCString { strdup($0) }} + [nil]
let cEnv = ProcessInfo.processInfo.environment.map { (key, value) in strdup("\(key)=\(value)") } + [nil]
defer {
free(cPath)
cEnv.forEach { free($0) }
cArgs.forEach { free($0) }
}
#if os(macOS)
var fileActions: posix_spawn_file_actions_t? = nil
#else
var fileActions = posix_spawn_file_actions_t()
#endif
posix_spawn_file_actions_init(&fileActions)
// posix_spawn_file_actions_addinherit_np(&fileActions, STDIN_FILENO)
posix_spawn_file_actions_adddup2(&fileActions, 0, 0)
posix_spawn_file_actions_adddup2(&fileActions, 1, 1)
posix_spawn_file_actions_adddup2(&fileActions, 2, 2)
guard posix_spawn(&pid, cPath, &fileActions, nil, cArgs, cEnv) != -1 else {
throw ZigError.genericError("Failed to execute \(path)")
}
var res: Int32 = 0
waitpid(pid, &res, 0)
guard res == 0 else {
throw ZigError.shellError(res)
}
}
static func replace(with path: String, arguments: [String]) throws {
let cPath = path.withCString { strdup($0) }
let cArgs = arguments.map { $0.withCString { strdup($0) }} + [nil]
guard execv(cPath, cArgs) != -1 else {
let scriptName = String(describing: path.split(separator: "/").last)
throw ZigError.genericError("Failed to load \(scriptName) with error \(errno)")
}
}
}
| fa6e6b19db6cf2f42f56d618e4b25a93 | 31.067797 | 108 | 0.634778 | false | false | false | false |
renzifeng/ZFZhiHuDaily | refs/heads/master | ZFZhiHuDaily/Other/Extension/SwiftExtension/UIKit/UINaVigationBar/NavigationBarExtension.swift | apache-2.0 | 1 | //
// NavigationBarExtension.swift
// ParallaxHeaderView
//
// Created by wl on 15/11/5.
// Copyright © 2015年 wl. All rights reserved.
//
import UIKit
var key: String = "coverView"
extension UINavigationBar {
/// 定义的一个计算属性,如果可以我更希望直接顶一个存储属性。它用来返回和设置我们需要加到
/// UINavigationBar上的View
var coverView: UIView? {
get {
//这句的意思大概可以理解为利用key在self中取出对应的对象,如果没有key对应的对象就返回niu
return objc_getAssociatedObject(self, &key) as? UIView
}
set {
//与上面对应是重新设置这个对象,最后一个参数如果学过oc的话很好理解,就是代表这个newValue的属性
//OBJC_ASSOCIATION_RETAIN_NONATOMIC意味着:strong,nonatomic
objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func setMyBackgroundColor(color: UIColor) {
if self.coverView != nil {
self.coverView!.backgroundColor = color
}else {
self.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.shadowImage = UIImage()
let view = UIView(frame: CGRectMake(0, -20, UIScreen.mainScreen().bounds.size.width, CGRectGetHeight(self.bounds) + 20))
view.userInteractionEnabled = false
view.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
self.insertSubview(view, atIndex: 0)
view.backgroundColor = color
self.coverView = view
}
}
func setMyBackgroundColorAlpha(alpha: CGFloat) {
guard let coverView = self.coverView else {
return
}
self.coverView!.backgroundColor = coverView.backgroundColor?.colorWithAlphaComponent(alpha)
}
}
| 512b0321866f348d11c92537e455407d | 30.333333 | 132 | 0.624113 | false | false | false | false |
beepscore/WebKitty | refs/heads/master | WebKitty/FileUtils.swift | mit | 1 | //
// FileUtils.swift
// WebKitty
//
// Created by Steve Baker on 4/22/15.
// Copyright (c) 2015 Beepscore LLC. All rights reserved.
//
// In general, Apple recommends references files via NSURL instead of NSString path.
// For more info see Apple NSFileManager and NSURL class references.
import Foundation
class FileUtils: NSObject {
/**
* If source file exists at destination, replaces it.
* http://stackoverflow.com/questions/24097826/read-and-write-data-from-text-file
*/
class func duplicateFileToTempDir(_ fileUrl: URL?) -> URL? {
if fileUrl == nil {
return nil
}
let fileMgr = FileManager.default
let tempPath = NSTemporaryDirectory()
let tempWwwUrl = URL(fileURLWithPath: tempPath).appendingPathComponent("www")
do {
try fileMgr.createDirectory(at: tempWwwUrl, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print("Error createDirectoryAtURL at \(tempWwwUrl)")
print(error.debugDescription)
return nil
}
let pathComponent = fileUrl!.lastPathComponent
let destinationUrl = tempWwwUrl.appendingPathComponent(pathComponent)
let _ = deleteFileAtUrl(destinationUrl)
do {
try fileMgr.copyItem(at: fileUrl!, to: destinationUrl)
} catch let error as NSError {
print("copyItemAtURL error \(error.localizedDescription)")
return nil
}
return destinationUrl
}
/** If file exists, deletes it.
return true if fileUrl was nil or file didn't exist or file was deleted
return false if file existed but couldn't delete it
*/
class func deleteFileAtUrl(_ fileUrl : URL?) -> Bool {
let fileMgr = FileManager.default
if let url = fileUrl {
if fileMgr.fileExists(atPath: url.path) {
do {
try fileMgr.removeItem(at: url)
return true
} catch let error as NSError {
print("Error removeItemAtURL at \(url)")
print(error.debugDescription)
return false
}
} else {
// file doesn't exist
return true
}
} else {
// fileURL nil
return true
}
}
func fileNamesAtBundleResourcePath() -> [String] {
// Returns list of all files in bundle resource path
// NOTE:
// I tried writing a function to enumerate the contents of a subdirectory
// such as webViewResources
// func fileNamesInSubdirectory(subpath: String?) -> [String]
// It didn't work.
// Apparently the bundle contains many files at the same heirarchical level,
// doesn't keep index.html and style.css in a subdirectory
// http://stackoverflow.com/questions/25285016/swift-iterate-through-files-in-a-folder-and-its-subfolders?lq=1
var fileNames : [String] = []
let bundle = Bundle.main
// let bundlePath = bundle.bundlePath
// let sourcePath = resourcePath!.stringByAppendingPathComponent(subpath!)
let resourcePath = bundle.resourcePath
let fileManager = FileManager()
// this returns empty
// if let enumerator: NSDirectoryEnumerator = fileManager.enumeratorAtPath(sourcePath) {
// this returns many files, could filter by file extension
if let enumerator: FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: resourcePath!) {
for element in enumerator.allObjects {
fileNames.append(element as! String)
}
}
return fileNames
}
func fileNamesAtURL() -> [String] {
let bundle = Bundle.main
guard let resourcePath = bundle.resourcePath else {
return []
}
var urlComponents = URLComponents()
urlComponents.scheme = "file"
urlComponents.host = ""
urlComponents.path = resourcePath
let resourceURL = urlComponents.url
let fileManager = FileManager()
var lastPathComponents : [String] = []
if let enumerator = fileManager.enumerator(at: resourceURL!,
includingPropertiesForKeys: nil,
options: .skipsSubdirectoryDescendants,
errorHandler: nil) {
for element in enumerator.allObjects {
lastPathComponents.append((element as! URL).lastPathComponent)
}
}
return lastPathComponents
}
func fileNamesWithExtensionHtml() -> [String] {
let bundle = Bundle.main
let urls = bundle.urls(forResourcesWithExtension: "html", subdirectory: "")
var lastPathComponents : [String] = []
for url in urls! {
lastPathComponents.append(url.lastPathComponent)
}
return lastPathComponents
}
}
| 56b258ddcb6ceed06ed15aa8af3b2b27 | 33.569536 | 118 | 0.583525 | false | false | false | false |
andersio/MantleData | refs/heads/master | MantleData/ReactiveArray.swift | mit | 1 | //
// ArraySet.swift
// MantleData
//
// Created by Anders on 13/1/2016.
// Copyright © 2016 Anders. All rights reserved.
//
import Foundation
import ReactiveSwift
import enum Result.NoError
private struct BatchingState<Element> {
var seq = 0
var removals: [Int] = []
var insertions: [(index: Int?, value: Element)] = []
var updates: Set<Int> = []
}
final public class ReactiveArray<E> {
public var name: String? = nil
public let events: Signal<SectionedCollectionEvent, NoError>
fileprivate let eventObserver: Observer<SectionedCollectionEvent, NoError>
fileprivate var storage: [E] = []
private var batchingState: BatchingState<E>?
public init<S: Sequence>(_ content: S) where S.Iterator.Element == E {
(events, eventObserver) = Signal.pipe()
storage = Array(content)
}
public required convenience init() {
self.init([])
}
/// Batch mutations to the array for one collection changed event.
///
/// Removals respect the old indexes, while insertions and update respect
/// the order after the removals are applied.
///
/// - parameters:
/// - action: The action which mutates the array.
public func batchUpdate(action: () -> Void) {
batchingState = BatchingState()
action()
if let state = batchingState {
apply(state)
batchingState = nil
}
}
private func apply(_ state: BatchingState<E>) {
let removals = state.removals.sorted(by: >)
var updates = state.updates.sorted(by: >)
for index in removals {
storage.remove(at: index)
for i in updates.indices {
if updates[i] < index {
break
} else {
assert(updates[i] != index, "Attempt to update an element to be deleted.")
updates[i] -= 1
}
}
}
let insertions = state.insertions
var insertedRows = [Int]()
insertedRows.reserveCapacity(insertions.count)
for (index, value) in insertions {
let index = index ?? storage.endIndex
storage.insert(value, at: index)
for i in insertedRows.indices {
if insertedRows[i] >= index {
insertedRows[i] += 1
}
}
insertedRows.append(index)
for i in updates.indices.reversed() {
if updates[i] < index {
break
} else {
assert(updates[i] != index, "Attempt to update a element to be inserted.")
updates[i] += 1
}
}
}
let changes = SectionedCollectionChanges(deletedRows: removals.map { IndexPath(row: $0, section: 0) },
insertedRows: insertedRows.map { IndexPath(row: $0, section: 0) },
updatedRows: updates.map { IndexPath(row: $0, section: 0) })
eventObserver.send(value: .updated(changes))
}
public func append(_ element: E) {
_insert(element, at: nil)
}
public func append<S: Sequence>(contentsOf elements: S) where S.Iterator.Element == E {
for element in elements {
_insert(element, at: nil)
}
}
public func insert(_ element: E, at index: Int) {
_insert(element, at: index)
}
private func _insert(_ element: E, at index: Int?) {
if batchingState == nil {
let index = index ?? storage.endIndex
storage.insert(element, at: index)
let changes = SectionedCollectionChanges(insertedRows: [IndexPath(row: index, section: 0)])
eventObserver.send(value: .updated(changes))
} else {
batchingState!.insertions.append((index, element))
}
}
@discardableResult
public func remove(at index: Int) -> E {
if batchingState == nil {
let value = storage.remove(at: index)
let changes = SectionedCollectionChanges(deletedRows: [IndexPath(row: index, section: 0)])
eventObserver.send(value: .updated(changes))
return value
} else {
batchingState!.removals.append(index)
return storage[index]
}
}
public func removeAll() {
storage.removeAll()
batchingState = nil
let changes = SectionedCollectionChanges(deletedSections: [0])
eventObserver.send(value: .updated(changes))
}
public func move(elementAt index: Int, to newIndex: Int) {
if batchingState == nil {
let value = storage.remove(at: index)
storage.insert(value, at: newIndex)
let changes = SectionedCollectionChanges(movedRows: [(from: IndexPath(row: index, section: 0),
to: IndexPath(row: newIndex, section: 0))])
eventObserver.send(value: .updated(changes))
} else {
batchingState!.removals.append(index)
batchingState!.insertions.append((newIndex, storage[index]))
}
}
public subscript(position: Int) -> E {
get {
return storage[position]
}
set {
storage[position] = newValue
if batchingState == nil {
let changes = SectionedCollectionChanges(updatedRows: [IndexPath(row: position, section: 0)])
eventObserver.send(value: .updated(changes))
} else {
batchingState!.updates.insert(position)
}
}
}
deinit {
eventObserver.sendCompleted()
}
}
extension ReactiveArray: SectionedCollection {
public typealias Index = IndexPath
public var sectionCount: Int {
return 0
}
public var startIndex: IndexPath {
return IndexPath(row: storage.startIndex, section: 0)
}
public var endIndex: IndexPath {
return IndexPath(row: storage.endIndex, section: 0)
}
public func index(after i: IndexPath) -> IndexPath {
return IndexPath(row: i.row + 1, section: 0)
}
public func index(before i: IndexPath) -> IndexPath {
return IndexPath(row: i.row - 1, section: 0)
}
public subscript(row row: Int, section section: Int) -> E {
assert(section == 0, "ReactiveArray supports only one section.")
return storage[row]
}
public func sectionName(for section: Int) -> String? {
return nil
}
public func rowCount(for section: Int) -> Int {
return section > 0 ? 0 : storage.count
}
}
| dd29bfc81789d429e21f5b64ee2e4238 | 24.446429 | 109 | 0.666491 | false | false | false | false |
CosmicMind/Samples | refs/heads/development | Projects/Programmatic/Grid/Grid/ViewController.swift | bsd-3-clause | 1 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 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 UIKit
import Material
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
prepareHorizontalExample()
prepareVerticalExample()
}
}
extension ViewController {
fileprivate func prepareHorizontalExample() {
let container = View()
container.backgroundColor = nil
container.shapePreset = .square
container.grid.interimSpacePreset = .interimSpace3
view.layout(container).center().left(20).right(20).height(300)
for _ in 0..<12 {
let v = View()
v.grid.columns = 1
v.backgroundColor = Color.blue.base
container.grid.views.append(v)
}
}
fileprivate func prepareVerticalExample() {
let container = View()
container.backgroundColor = nil
container.shapePreset = .square
container.grid.axis.direction = .vertical
container.grid.interimSpacePreset = .interimSpace3
view.layout(container).center().left(20).right(20).height(300)
for _ in 0..<12 {
let v = View()
v.grid.rows = 1
v.backgroundColor = Color.blue.base
container.grid.views.append(v)
}
}
}
| 8f2f6da2b048e9093959759df7bf61ce | 32.625 | 87 | 0.752045 | false | false | false | false |
citysite102/kapi-kaffeine | refs/heads/master | kapi-kaffeine/kapi-kaffeine/KPNomadDataModel.swift | mit | 1 | //
// KPNomadDataModel.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/5/26.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import Foundation
import ObjectMapper
class KPNomadDataModel: NSObject, Mappable, GMUClusterItem {
var identifier: String!
var name: String!
var city: String!
var wifi: NSNumber?
var seat: NSNumber?
var quite: NSNumber?
var tasty: NSNumber?
var cheap: NSNumber?
var music: NSNumber?
var url: String?
var address: String?
var latitude: String?
var longitude: String?
var limitedTime: String?
var socket: String?
var standingDesk: String?
var mrt: String?
var openTime: String?
var usableFeatureCount: Int? {
get {
var count:Int = 0
count += self.wifi?.intValue == 0 ? 0 : 1;
count += self.seat?.intValue == 0 ? 0 : 1;
count += self.quite?.intValue == 0 ? 0 : 1;
count += self.tasty?.intValue == 0 ? 0 : 1;
count += self.cheap?.intValue == 0 ? 0 : 1;
count += self.music?.intValue == 0 ? 0 : 1;
return count
}
}
var score: Double? {
get {
var sum = 0.0;
sum += (self.wifi?.doubleValue) ?? 0;
sum += (self.seat?.doubleValue) ?? 0;
sum += (self.quite?.doubleValue) ?? 0;
sum += (self.tasty?.doubleValue) ?? 0;
sum += (self.cheap?.doubleValue) ?? 0;
sum += (self.music?.doubleValue) ?? 0;
return sum/Double(self.usableFeatureCount!)
}
}
var position: CLLocationCoordinate2D {
get {
if let latstr = self.latitude, let latitude = Double(latstr),
let longstr = self.longitude, let longitude = Double(longstr) {
return CLLocationCoordinate2DMake(latitude, longitude)
}
return CLLocationCoordinate2DMake(-90, 0)
}
}
required init?(map: Map) {
}
func mapping(map: Map) {
identifier <- map["identifier"]
name <- map["name"]
city <- map["city"]
wifi <- map["wifi"]
seat <- map["seat"]
quite <- map["quite"]
tasty <- map["tasty"]
cheap <- map["cheap"]
music <- map["music"]
url <- map["url"]
address <- map["address"]
latitude <- map["latitude"]
longitude <- map["longitude"]
limitedTime <- map["limited_time"]
socket <- map["socket"]
standingDesk <- map["standing_desk"]
mrt <- map["mrt"]
openTime <- map["open_time"]
}
}
| 83fc4e83e51b4b1a8102e99462c8ed49 | 29.414141 | 79 | 0.466955 | false | false | false | false |
xiekw2010/iOS7PlayGround | refs/heads/master | ViewControllers/WaterFlowCollectionViewCell.swift | mit | 1 | //
// WaterFlowCollectionViewCell.swift
// UICategories
//
// Created by xiekw on 1/28/15.
// Copyright (c) 2015 xiekw. All rights reserved.
//
import UIKit
let textAtr: NSDictionary = [NSFontAttributeName: UIFont.systemFontOfSize(16.0)]
let imageY: CGFloat = 5.0
let betweenImageAndLabel: CGFloat = 3.0
let bottomOffset: CGFloat = 5.0
func WaterFlowCellSuggestHeight(image: UIImage, text: String, constrainedWidth: CGFloat) -> CGFloat {
var imageSize = image.size
let imageSizeRatio = (constrainedWidth / imageSize.width)
imageSize = CGSizeMake(constrainedWidth, imageSize.height * imageSizeRatio)
let nsText = text as NSString
let textSize = nsText.boundingRectWithSize(CGSizeMake(constrainedWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textAtr, context: nil).size
let result = imageY + imageSize.height + betweenImageAndLabel + textSize.height + bottomOffset
return result
}
class WaterFlowCollectionViewCell: UICollectionViewCell {
var textLabel: UILabel!
var imageView: UIImageView!
var photo: DXPhoto! {
willSet(newValue) {
imageView.image = newValue.display
textLabel.text = newValue.photoDes
setNeedsLayout()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
imageView = UIImageView(frame: bounds)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
textLabel = UILabel(frame: bounds)
textLabel.numberOfLines = 0
textLabel.font = textAtr[NSFontAttributeName] as UIFont
textLabel.backgroundColor = UIColor.redColor()
addSubview(imageView)
addSubview(textLabel)
backgroundColor = UIColor.grayColor()
}
override func layoutSubviews() {
super.layoutSubviews()
layoutMyViews()
}
func layoutMyViews() {
let selfSize = bounds.size
let nsText = photo.photoDes as NSString
let textSize = nsText.boundingRectWithSize(CGSizeMake(selfSize.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textAtr, context: nil).size
var imageSize = photo.display.size
let imageSizeRatio = (selfSize.width / imageSize.width)
imageSize = CGSizeMake(selfSize.width, imageSize.height * imageSizeRatio)
imageView.frame = CGRectMake(0, imageY, imageSize.width, imageSize.height)
textLabel.frame = CGRectMake(0, CGRectGetMaxY(imageView.frame) + betweenImageAndLabel, selfSize.width, textSize.height)
}
override func prepareForReuse() {
imageView.image = nil
textLabel.text = nil
}
}
| 6d51512f87b5c8ebcfa01001ac47e5f4 | 33.607143 | 187 | 0.68937 | false | false | false | false |
aahmedae/blitz-news-ios | refs/heads/master | Blitz News/Model/Model.swift | mit | 1 | //
// Model.swift
// Blitz News
//
// Created by Asad Ahmed on 5/13/17.
// Contains classes used to represent the parsed JSON data from the NewsAPI service
//
import Foundation
// Represents a single news item
class NewsItem
{
var newsTitle = "Title"
var newsDescription = "Description"
var sourceName = "Source Name"
var imageURL = "http://www.google.com"
var contentURL = "http://www.google.com"
}
| a236ef749e375a88d2e15a7ef5630f16 | 20.35 | 84 | 0.681499 | false | false | false | false |
AgentTen/ios-sdk | refs/heads/antitypical-Result | Apps/Kort sagt/KortSagt-master/Pods/Alamofire/Source/Stream.swift | apache-2.0 | 51 | // Stream.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
#if !os(watchOS)
@available(iOS 9.0, OSX 10.11, *)
extension Manager {
private enum Streamable {
case Stream(String, Int)
case NetService(NSNetService)
}
private func stream(streamable: Streamable) -> Request {
var streamTask: NSURLSessionStreamTask!
switch streamable {
case .Stream(let hostName, let port):
dispatch_sync(queue) {
streamTask = self.session.streamTaskWithHostName(hostName, port: port)
}
case .NetService(let netService):
dispatch_sync(queue) {
streamTask = self.session.streamTaskWithNetService(netService)
}
}
let request = Request(session: session, task: streamTask)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
/**
Creates a request for bidirectional streaming with the given hostname and port.
- parameter hostName: The hostname of the server to connect to.
- parameter port: The port of the server to connect to.
:returns: The created stream request.
*/
public func stream(hostName hostName: String, port: Int) -> Request {
return stream(.Stream(hostName, port))
}
/**
Creates a request for bidirectional streaming with the given `NSNetService`.
- parameter netService: The net service used to identify the endpoint.
- returns: The created stream request.
*/
public func stream(netService netService: NSNetService) -> Request {
return stream(.NetService(netService))
}
}
// MARK: -
@available(iOS 9.0, OSX 10.11, *)
extension Manager.SessionDelegate: NSURLSessionStreamDelegate {
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`.
public var streamTaskReadClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
get {
return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void
}
set {
_streamTaskReadClosed = newValue
}
}
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`.
public var streamTaskWriteClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
get {
return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void
}
set {
_streamTaskWriteClosed = newValue
}
}
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`.
public var streamTaskBetterRouteDiscovered: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
get {
return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> Void
}
set {
_streamTaskBetterRouteDiscovered = newValue
}
}
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`.
public var streamTaskDidBecomeInputStream: ((NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void)? {
get {
return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void
}
set {
_streamTaskDidBecomeInputStream = newValue
}
}
// MARK: Delegate Methods
/**
Tells the delegate that the read side of the connection has been closed.
- parameter session: The session.
- parameter streamTask: The stream task.
*/
public func URLSession(session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) {
streamTaskReadClosed?(session, streamTask)
}
/**
Tells the delegate that the write side of the connection has been closed.
- parameter session: The session.
- parameter streamTask: The stream task.
*/
public func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) {
streamTaskWriteClosed?(session, streamTask)
}
/**
Tells the delegate that the system has determined that a better route to the host is available.
- parameter session: The session.
- parameter streamTask: The stream task.
*/
public func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) {
streamTaskBetterRouteDiscovered?(session, streamTask)
}
/**
Tells the delegate that the stream task has been completed and provides the unopened stream objects.
- parameter session: The session.
- parameter streamTask: The stream task.
- parameter inputStream: The new input stream.
- parameter outputStream: The new output stream.
*/
public func URLSession(
session: NSURLSession,
streamTask: NSURLSessionStreamTask,
didBecomeInputStream inputStream: NSInputStream,
outputStream: NSOutputStream)
{
streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream)
}
}
#endif
| b1546211df8f189d13e76a25ff863ee5 | 35.494444 | 132 | 0.685645 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.