hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
5b5018a806ba6c2b0e76c9d98403c299a36c51b7 | 2,295 | //
// OEAContentStateView.swift
// OEAContentStateView
//
// Created by Omer Emre Aslan on 14.02.2018.
// Copyright © 2018 Omer Emre Aslan. All rights reserved.
//
class OEALoadingStateView: UIView {
private lazy var activityIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView()
activityIndicator.activityIndicatorViewStyle = .gray
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
return activityIndicator
}()
private lazy var textLabel: UILabel = {
let textLabel = UILabel()
textLabel.numberOfLines = 0
textLabel.font = UIFont.systemFont(ofSize: 16)
textLabel.textColor = .gray
textLabel.textAlignment = .center
textLabel.translatesAutoresizingMaskIntoConstraints = false
return textLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension OEALoadingStateView {
func setText(_ text: String) {
textLabel.text = text
}
}
private extension OEALoadingStateView {
func setupLayout() {
addActivityIndicator()
addTextLabel()
}
func addActivityIndicator() {
addSubview(activityIndicator)
activityIndicator
.centerYAnchor
.constraint(equalTo: self.centerYAnchor,
constant: -10)
.isActive = true
activityIndicator
.centerXAnchor
.constraint(equalTo: self.centerXAnchor)
.isActive = true
activityIndicator.startAnimating()
}
func addTextLabel() {
addSubview(textLabel)
textLabel
.topAnchor
.constraint(equalTo: activityIndicator.bottomAnchor,
constant: 5.0)
.isActive = true
textLabel
.leadingAnchor
.constraint(equalTo: self.leadingAnchor, constant: 15.0)
.isActive = true
textLabel
.trailingAnchor
.constraint(equalTo: self.trailingAnchor, constant: -15.0)
.isActive = true
}
}
| 27.987805 | 75 | 0.612636 |
ace69e76aee01c131a69cd81c2c4ef173006c8f6 | 31,033 | //
// BESwiftCamera.swift
// BESwiftCamera
//
// Created by Brian Earley on 1/18/16.
// Copyright © 2016 brianearley. All rights reserved.
//
import UIKit
import AVFoundation
import ImageIO
enum BESwiftCameraPosition {
case Rear
case Front
}
enum BESwiftCameraFlash {
case Off
case On
case Auto
}
enum BESwiftCameraMirror {
case Off
case On
case Auto
}
enum BESwiftCameraErrorCode:ErrorType {
case CameraPermission
case MicrophonePermission
case Session
case VideoNotEnabled
case Unknown
}
class BESwiftCamera: UIViewController, AVCaptureFileOutputRecordingDelegate {
private var preview:UIView!
private var stillImageOutput:AVCaptureStillImageOutput!
private var session:AVCaptureSession!
private var videoCaptureDevice:AVCaptureDevice!
private var audioCaptureDevice:AVCaptureDevice!
private var videoDeviceInput:AVCaptureDeviceInput!
private var audioDeviceInput:AVCaptureDeviceInput!
private var captureVideoPreviewLayer:AVCaptureVideoPreviewLayer!
private var tapGesture:UITapGestureRecognizer!
private var focusBoxLayer:CALayer!
private var focusBoxAnimation:CAAnimation!
private var movieFileOutput:AVCaptureMovieFileOutput!
private var cameraPosition:BESwiftCameraPosition!
var didRecord:((BESwiftCamera,NSURL) -> Void)!
/**
* Triggered on device change.
*/
var onDeviceChange:((BESwiftCamera!, AVCaptureDevice!) -> Void)!
/**
* Camera quality, set a constants prefixed with AVCaptureSessionPreset.
* Make sure to call before calling -(void)initialize method, otherwise it would be late.
*/
var cameraQuality:String!
var flash:BESwiftCameraFlash! // Camera flash mode
var mirror:BESwiftCameraMirror! // Camera mirror mode
var position:BESwiftCameraPosition! // Position of the camera
var videoEnabled:Bool! // Boolean value to indicate if the video is enabled
var recording:Bool! // Boolean value to indicate if the camera is recording a video at the current moment
var tapToFocus:Bool! // Set NO if you don't want to enable user triggered focusing. Enabled by default.
/**
* Fixes the orientation after the image is captured is set to Yes.
* see: http://stackoverflow.com/questions/5427656/ios-uiimagepickercontroller-result-image-orientation-after-upload
*/
var fixOrientationAfterCapture:Bool!
/**
* Set YES if your view controller does not allow autorotation,
* however you want to take the device rotation into account no matter what. Disabled by default.
*/
var useDeviceOrientation:Bool!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupWithQuality(AVCaptureSessionPresetHigh, position:.Rear, videoEnabled:true)
}
convenience init() {
self.init(withVideoEnabled:false)
}
convenience init(withVideoEnabled videoEnabled:Bool) {
self.init(withQuality: AVCaptureSessionPresetHigh, position:.Rear, videoEnabled:videoEnabled)
}
init(withQuality quality:String, position:BESwiftCameraPosition, videoEnabled:Bool) {
super.init(nibName: nil, bundle: nil)
self.setupWithQuality(quality, position:position, videoEnabled:videoEnabled)
}
func setupWithQuality(quality:String, position:BESwiftCameraPosition, videoEnabled:Bool) {
self.cameraQuality = quality
self.position = position
self.fixOrientationAfterCapture = false
self.tapToFocus = true
self.useDeviceOrientation = false
self.flash = .Off
self.mirror = .Auto
self.videoEnabled = videoEnabled
self.recording = false
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clearColor()
self.view.autoresizingMask = .None
self.preview = UIView(frame: CGRectZero)
self.preview.backgroundColor = UIColor.clearColor()
self.view.addSubview(self.preview)
// tap to focus
self.tapGesture = UITapGestureRecognizer(target: self, action: Selector("previewTapped:"))
self.tapGesture.numberOfTapsRequired = 1
self.tapGesture.delaysTouchesEnded = false
self.preview.addGestureRecognizer(self.tapGesture)
// add focus box to view
self.addDefaultFocusBox()
}
// Mark: Camera
func attachToViewController(vc:UIViewController, withFrame frame:CGRect) {
vc.view.addSubview(self.view)
vc.addChildViewController(self)
self.didMoveToParentViewController(vc)
vc.view.frame = frame
}
func start() throws {
switch AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) {
case .Authorized: try self.requestPermissions()
case .Denied: throw BESwiftCameraErrorCode.CameraPermission
case .Restricted: throw BESwiftCameraErrorCode.CameraPermission
case .NotDetermined: try self.requestPermissions()
}
}
func requestPermissions() throws {
do {
try BESwiftCamera.requestCameraPermission() {
granted in
if (granted) {
do {
// Request microphone permission if video is enabled
if self.videoEnabled == true
{
try BESwiftCamera.requestMicrophonePermission() {
granted in
if (granted) {
self.initialize()
} else {
throw BESwiftCameraErrorCode.MicrophonePermission
}
}
} else {
self.initialize()
}
}
} else {
throw BESwiftCameraErrorCode.CameraPermission
}
}
}
}
func initialize() {
self.session = AVCaptureSession()
self.session.sessionPreset = self.cameraQuality
// preview layer
let bounds:CGRect = self.preview.layer.bounds
self.captureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
self.captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.captureVideoPreviewLayer.bounds = bounds
self.captureVideoPreviewLayer.position = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds))
self.preview.layer.addSublayer(self.captureVideoPreviewLayer)
var devicePosition:AVCaptureDevicePosition
switch self.position! {
case .Rear:
if BESwiftCamera.isRearCameraAvailable() {
devicePosition = AVCaptureDevicePosition.Back
} else {
devicePosition = AVCaptureDevicePosition.Front
self.position = .Front
}
case .Front:
if BESwiftCamera.isFrontCameraAvailable() {
devicePosition = AVCaptureDevicePosition.Front
} else {
devicePosition = AVCaptureDevicePosition.Back
self.position = .Rear
}
//default:
//devicePosition = AVCaptureDevicePosition.Unspecified
}
if devicePosition == .Unspecified {
self.videoCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
} else {
self.videoCaptureDevice = self.cameraWithPosition(devicePosition)
}
do {
self.videoDeviceInput = try AVCaptureDeviceInput(device: self.videoCaptureDevice)
} catch let error as NSError { print("ERROR: \(error), \(error.userInfo)") }
if self.session.canAddInput(self.videoDeviceInput) {
self.session.addInput(self.videoDeviceInput)
self.captureVideoPreviewLayer.connection.videoOrientation = self.orientationForConnection
}
// add audio if video is enabled
if self.videoEnabled != nil {
self.audioCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
do {
self.audioDeviceInput = try AVCaptureDeviceInput(device: self.audioCaptureDevice)
} catch let error as NSError { print("ERROR: \(error), \(error.userInfo)") }
if self.session.canAddInput(self.audioDeviceInput) {
self.session.addInput(self.audioDeviceInput)
}
self.movieFileOutput = AVCaptureMovieFileOutput()
self.movieFileOutput.movieFragmentInterval = kCMTimeInvalid
if self.session.canAddOutput(self.movieFileOutput) {
self.session.addOutput(self.movieFileOutput)
}
}
self.stillImageOutput = AVCaptureStillImageOutput()
self.stillImageOutput.outputSettings = [AVVideoCodecJPEG : AVVideoCodecKey]
self.session.addOutput(self.stillImageOutput)
//if we had disabled the connection on capture, re-enable it
if self.captureVideoPreviewLayer.connection.enabled {
self.captureVideoPreviewLayer.connection.enabled = true
}
self.session.startRunning()
}
/**
* Stops the running camera session. Needs to be called when the app doesn't show the view.
*/
func stop() {
if self.session != nil {
self.session.stopRunning()
}
}
// MARK: - Image Capture
/*func capture(onCaptureBlock:((BESwiftCamera,UIImage,NSDictionary) -> Void), exactSeenImage:Bool) {
if self.session == nil {
onCaptureBlock(self,UIImage(),[:])
return
}
// get connection and set orientation
let videoConnection = self.captureConnection
videoConnection.videoOrientation = self.orientationForConnection
// freeze the screen
self.captureVideoPreviewLayer.connection.enabled = false
self.stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {
buffer, error in
let exifAttachments = CMGetAttachment(buffer, kCGImagePropertyExifDictionary, nil) as! CFDictionaryRef
let metaData = exifAttachments
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
var image = UIImage(data: imageData)!
if exactSeenImage {
image = self.cropImageUsingPreviewBounds(image)
}
if self.fixOrientationAfterCapture == true {
//image = image.fixOrientation()
}
// trigger the block
dispatch_async(dispatch_get_main_queue()) {
onCaptureBlock(self,image,metaData)
}
}
}*/
func capture(exactSeenImage exactSeenImage:Bool, onCaptureBlock:((BESwiftCamera,UIImage,NSDictionary) -> Void)) {
if self.session == nil {
onCaptureBlock(self,UIImage(),[:])
return
}
// get connection and set orientation
let videoConnection = self.captureConnection
videoConnection.videoOrientation = self.orientationForConnection
// freeze the screen
self.captureVideoPreviewLayer.connection.enabled = false
self.stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {
buffer, error in
let exifAttachments = CMGetAttachment(buffer, kCGImagePropertyExifDictionary, nil) as! CFDictionaryRef
let metaData = exifAttachments
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
var image = UIImage(data: imageData)!
if exactSeenImage {
image = self.cropImageUsingPreviewBounds(image)
}
if self.fixOrientationAfterCapture == true {
image = image.fixOrientation()
}
// trigger the block
dispatch_async(dispatch_get_main_queue()) {
onCaptureBlock(self,image,metaData)
}
}
}
func capture(onCapture:((BESwiftCamera,UIImage,NSDictionary) -> Void)) {
self.capture(exactSeenImage:false, onCaptureBlock: onCapture)
}
// MARK: - Video Capture
func startRecordingWithOutputUrl(url:NSURL) throws {
// check if video is enabled
if self.videoEnabled == false {
throw BESwiftCameraErrorCode.VideoNotEnabled
}
if self.session == nil {
throw BESwiftCameraErrorCode.Session
}
if self.flash == .On {
self.enableTorch(true)
}
// set video orientation
for connection in self.movieFileOutput.connections as! [AVCaptureConnection] {
for port in connection.inputPorts! as! [AVCaptureInputPort] {
// get only the video media types
if (port.mediaType == AVMediaTypeVideo) {
if connection.supportsVideoOrientation {
self.captureConnection.videoOrientation = connection.videoOrientation
//self.captureConnection.videoOrientation = self.orientationForConnection
//connection.videoOrientation = self.orientationForConnection // From original Objective-C
}
}
}
}
self.movieFileOutput.startRecordingToOutputFileURL(url, recordingDelegate:self)
}
/**
* Stop recording video with a completion block.
*/
func stopRecording(completionBlock:((BESwiftCamera, NSURL) -> Void)) {
if (!self.videoEnabled) {
return
}
self.didRecord = completionBlock
self.movieFileOutput.stopRecording()
}
func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
self.recording = true
}
func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
self.recording = false
self.enableTorch(false)
if self.didRecord != nil {
self.didRecord(self, outputFileURL)
}
}
func enableTorch(enabled:Bool) {
// check if the device has a torch, otherwise don't even bother to take any action.
if self.isTorchAvailable() {
self.session.beginConfiguration()
try! self.videoCaptureDevice.lockForConfiguration()
if (enabled) {
self.videoCaptureDevice.torchMode = AVCaptureTorchMode.On
} else {
self.videoCaptureDevice.torchMode = AVCaptureTorchMode.Off
}
self.videoCaptureDevice.unlockForConfiguration()
self.session.commitConfiguration()
}
}
// MARK: - Helpers
func cropImageUsingPreviewBounds(image:UIImage) -> UIImage {
let previewBounds = self.captureVideoPreviewLayer.bounds
let outputRect = self.captureVideoPreviewLayer.metadataOutputRectOfInterestForRect(previewBounds)
let takenCGImage = image.CGImage
let width = CGImageGetWidth(takenCGImage)
let height = CGImageGetHeight(takenCGImage)
let cropRect = CGRectMake(outputRect.origin.x * CGFloat(width), outputRect.origin.y * CGFloat(height),
outputRect.size.width * CGFloat(width), outputRect.size.height * CGFloat(height))
let cropCGImage = CGImageCreateWithImageInRect(takenCGImage, cropRect)
return UIImage(CGImage: cropCGImage!, scale: 1, orientation: image.imageOrientation)
}
var captureConnection:AVCaptureConnection {
var videoConnection:AVCaptureConnection!
for connection in self.stillImageOutput.connections {
for port in connection.inputPorts! {
if port.mediaType == AVMediaTypeVideo {
videoConnection = connection as! AVCaptureConnection
}
}
}
return videoConnection
}
func setVideoCaptureDevice(videoCaptureDevice:AVCaptureDevice) {
self.videoCaptureDevice = videoCaptureDevice
if videoCaptureDevice.flashMode == .Auto {
self.flash = .Auto
} else if videoCaptureDevice.flashMode == .On {
self.flash = .On
} else if videoCaptureDevice.flashMode == .Off {
self.flash = .Off
} else {
self.flash = .Off
}
// trigger block
self.onDeviceChange(self, videoCaptureDevice)
}
/**
* Checks if flash is avilable for the currently active device.
*/
func isFlashAvailable() -> Bool {
return self.videoCaptureDevice.hasFlash && self.videoCaptureDevice.flashAvailable
}
/**
* Checks if torch (flash for video) is avilable for the currently active device.
*/
func isTorchAvailable() -> Bool {
return self.videoCaptureDevice.hasTorch && self.videoCaptureDevice.torchAvailable
}
func updateFlashMode(cameraFlash:BESwiftCameraFlash) -> Bool {
if self.session == nil {
return false
}
var flashMode:AVCaptureFlashMode
if cameraFlash == .On {
flashMode = AVCaptureFlashMode.On
} else if (cameraFlash == .Auto) {
flashMode = AVCaptureFlashMode.Auto
} else {
flashMode = AVCaptureFlashMode.Off
}
if self.videoCaptureDevice.isFlashModeSupported(flashMode) {
do {
try self.videoCaptureDevice.lockForConfiguration()
} catch let error as NSError { print("ERROR: \(error), \(error.userInfo)") }
self.videoCaptureDevice.flashMode = flashMode
self.videoCaptureDevice.unlockForConfiguration()
self.flash = cameraFlash
return true
} else {
return false
}
}
func setMirror(mirror:BESwiftCameraMirror) {
self.mirror = mirror
if self.session == nil {
return
}
let videoConnection:AVCaptureConnection = self.movieFileOutput.connectionWithMediaType(AVMediaTypeVideo)
let pictureConnection:AVCaptureConnection = self.stillImageOutput.connectionWithMediaType(AVMediaTypeVideo)
switch mirror {
case .Off:
if videoConnection.supportsVideoMirroring {
videoConnection.videoMirrored = false
}
if pictureConnection.supportsVideoMirroring {
pictureConnection.videoMirrored = false
}
case .On:
if videoConnection.supportsVideoMirroring {
videoConnection.videoMirrored = true
}
if pictureConnection.supportsVideoMirroring {
pictureConnection.videoMirrored = true
}
case .Auto:
let shouldMirror = (self.position == .Front)
if videoConnection.supportsVideoMirroring {
videoConnection.videoMirrored = shouldMirror
}
if pictureConnection.supportsVideoMirroring {
pictureConnection.videoMirrored = shouldMirror
}
}
return
}
func togglePosition() -> BESwiftCameraPosition {
if self.session == nil {
return self.position
}
if self.position == .Rear {
//self.cameraPosition = .Front
self.setCameraPosition(.Front)
} else {
//self.cameraPosition = .Rear
self.setCameraPosition(.Rear)
}
return self.position
}
func setCameraPosition(cameraPosition:BESwiftCameraPosition) {
if ((self.position == cameraPosition) || (self.session == nil)) {
return
}
if ((cameraPosition == .Rear) && (!self.classForCoder.isRearCameraAvailable())) {
return
}
if ((cameraPosition == .Front) && (!self.classForCoder.isFrontCameraAvailable())) {
return
}
self.session.beginConfiguration()
// remove existing input
self.session.removeInput(self.videoDeviceInput)
// get new input
var device:AVCaptureDevice
if self.videoDeviceInput.device.position == .Back {
device = self.cameraWithPosition(.Front)
} else {
device = self.cameraWithPosition(.Back)
}
//if device == nil { return }
// add input to session
var videoInput:AVCaptureDeviceInput
do {
videoInput = try AVCaptureDeviceInput(device: device)
} catch let error as NSError { print("ERROR: \(error), \(error.userInfo)"); self.session.commitConfiguration(); return }
self.position = cameraPosition
self.session.addInput(videoInput)
self.session.commitConfiguration()
self.videoCaptureDevice = device
self.videoDeviceInput = videoInput
self.setMirror(self.mirror)
}
// Find a camera with the specified AVCaptureDevicePosition, returning nil if one is not found
func cameraWithPosition(position:AVCaptureDevicePosition) -> AVCaptureDevice! {
let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
for device in devices {
if device.position == position { return device as! AVCaptureDevice }
}
return nil
}
// MARK: - Focus
func previewTapped(gestureRecognizer:UIGestureRecognizer) {
if self.tapToFocus == false || self.session == nil {
return
}
let touchedPoint:CGPoint = gestureRecognizer.locationInView(self.preview)
// focus
let pointOfInterest = self.convertToPointOfInterestFromViewCoordinates(touchedPoint)
self.focusAtPoint(pointOfInterest)
// show the box
self.showFocusBox(touchedPoint)
}
func addDefaultFocusBox() {
let focusBox = CALayer()
focusBox.cornerRadius = 5.0
focusBox.bounds = CGRectMake(0.0, 0.0, 70, 60)
focusBox.borderWidth = 3.0
focusBox.borderColor = UIColor.yellowColor().CGColor
focusBox.opacity = 0.0
self.view.layer.addSublayer(focusBox)
let focusBoxAnimation = CABasicAnimation(keyPath: "opacity")
focusBoxAnimation.duration = 0.75
focusBoxAnimation.autoreverses = false
focusBoxAnimation.repeatCount = 0.0
focusBoxAnimation.fromValue = 1
focusBoxAnimation.toValue = 0
self.alterFocusBox(focusBox, animation:focusBoxAnimation)
}
func alterFocusBox(layer:CALayer, animation:CAAnimation) {
self.focusBoxLayer = layer
self.focusBoxAnimation = animation
}
func focusAtPoint(point:CGPoint) {
let device = self.videoCaptureDevice
if (device.focusPointOfInterestSupported && device.isFocusModeSupported(AVCaptureFocusMode.AutoFocus)) {
do {
try device.lockForConfiguration()
device.focusPointOfInterest = point
device.focusMode = AVCaptureFocusMode.AutoFocus
device.unlockForConfiguration()
} catch let error as NSError { print("ERROR: \(error), \(error.userInfo)") }
}
}
func showFocusBox(point:CGPoint) {
// clear animations
self.focusBoxLayer.removeAllAnimations()
// move layer to the touch point
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey:kCATransactionDisableActions)
self.focusBoxLayer.position = point
CATransaction.commit()
if self.focusBoxAnimation != nil {
// run the animation
self.focusBoxLayer.addAnimation(self.focusBoxAnimation, forKey:"animateOpacity")
}
}
func convertToPointOfInterestFromViewCoordinates(viewCoordinates:CGPoint) -> CGPoint {
let previewLayer = self.captureVideoPreviewLayer
var pointOfInterest = CGPointMake(0.5, 0.5)
let frameSize = previewLayer.frame.size
if previewLayer.videoGravity == AVLayerVideoGravityResize {
pointOfInterest = CGPointMake(viewCoordinates.y / frameSize.height, 1 - (viewCoordinates.x / frameSize.width))
} else {
var cleanAperture:CGRect
for port in self.videoDeviceInput.ports {
if port.mediaType == AVMediaTypeVideo {
cleanAperture = CMVideoFormatDescriptionGetCleanAperture(port.formatDescription, true)
let apertureSize = cleanAperture.size
let point = viewCoordinates
let apertureRatio:CGFloat = apertureSize.height / apertureSize.width
let viewRatio:CGFloat = frameSize.width / frameSize.height
var xc:CGFloat = 0.5
var yc:CGFloat = 0.5
if previewLayer.videoGravity == AVLayerVideoGravityResizeAspect {
if viewRatio > apertureRatio {
let y2:CGFloat = frameSize.height
let x2:CGFloat = frameSize.height * apertureRatio
let x1:CGFloat = frameSize.width
let blackBar:CGFloat = (x1-x2)/2
if ((point.x >= blackBar) && (point.x <= blackBar+x2)) {
xc = point.y / y2
yc = 1 - ((point.x-blackBar)/x2)
}
} else {
let y2:CGFloat = frameSize.width / apertureRatio
let y1:CGFloat = frameSize.height
let x2:CGFloat = frameSize.width
let blackBar:CGFloat = (y1-y2)/2
if ((point.y >= blackBar) && (point.y <= blackBar+y2)) {
xc = ((point.y-blackBar)/y2)
yc = 1 - (point.x / x2)
}
}
} else if previewLayer.videoGravity == AVLayerVideoGravityResizeAspectFill {
if viewRatio > apertureRatio {
let y2:CGFloat = apertureSize.width * (frameSize.width / apertureSize.height)
xc = (point.y + ((y2 - frameSize.height) / 2)) / y2
yc = (frameSize.width - point.x) / frameSize.width
} else {
let x2:CGFloat = apertureSize.height * (frameSize.height / apertureSize.width)
yc = 1 - ((point.x + ((x2 - frameSize.width) / 2)) / x2)
xc = point.y / frameSize.height
}
}
pointOfInterest = CGPointMake(xc, yc)
}
}
}
return pointOfInterest
}
// MARK: UIViewController
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.preview.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)
let bounds = self.preview.bounds
if let _ = self.captureVideoPreviewLayer {
self.captureVideoPreviewLayer.bounds = bounds
self.captureVideoPreviewLayer.position = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds))
self.captureVideoPreviewLayer.connection.videoOrientation = self.orientationForConnection
}
}
var orientationForConnection:AVCaptureVideoOrientation {
var videoOrientation:AVCaptureVideoOrientation = AVCaptureVideoOrientation.Portrait
if self.useDeviceOrientation == true {
switch UIDevice.currentDevice().orientation {
case .LandscapeLeft:
// yes we to the right, this is not a bug!
videoOrientation = AVCaptureVideoOrientation.LandscapeRight
case .LandscapeRight:
videoOrientation = AVCaptureVideoOrientation.LandscapeLeft
case .PortraitUpsideDown:
videoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown
default:
videoOrientation = AVCaptureVideoOrientation.Portrait
}
} else {
//switch (self.interfaceOrientation) {
switch UIApplication.sharedApplication().statusBarOrientation {
case .LandscapeLeft:
videoOrientation = AVCaptureVideoOrientation.LandscapeLeft
case .LandscapeRight:
videoOrientation = AVCaptureVideoOrientation.LandscapeRight
case .PortraitUpsideDown:
videoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown
default:
videoOrientation = AVCaptureVideoOrientation.Portrait
}
}
return videoOrientation
}
// MARK: Legacy Getters
func isVideoEnabled() -> Bool { return self.videoEnabled }
func isRecording() -> Bool { return self.recording }
// MARK: Class Methods
/**
* Use this method to request camera permission before initalizing LLSimpleCamera.
*/
class func requestCameraPermission(completionBlock:(Bool throws -> Void)) rethrows {
if (AVCaptureDevice.respondsToSelector(Selector("requestAccessForMediaType:completionHandler"))) {
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: {
granted in
dispatch_async(dispatch_get_main_queue()) {
try! completionBlock(granted)
}
})
} else {
try! completionBlock(true)
}
}
/**
* Use this method to request microphone permission before initalizing LLSimpleCamera.
*/
class func requestMicrophonePermission(completionBlock:(Bool throws -> Void)) rethrows {
if AVAudioSession.sharedInstance().respondsToSelector("requestRecordPermission:") {
AVAudioSession.sharedInstance().requestRecordPermission {
granted in
dispatch_async(dispatch_get_main_queue()) {
try! completionBlock(granted)
}
}
}
}
/**
* Checks is the front camera is available.
*/
class func isFrontCameraAvailable() -> Bool {
return UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front)
}
/**
* Checks is the rear camera is available.
*/
class func isRearCameraAvailable() -> Bool {
return UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Rear)
}
}
| 36.900119 | 180 | 0.622047 |
dbe14c210201adff37ab52d76800735ef412b2ba | 3,596 | /*
* Tencent is pleased to support the open source community by making
* WCDB available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of
* the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
public final class Select: Selectable {
private let keys: [CodingTableKeyBase]
private lazy var decoder = TableDecoder(keys, on: optionalRecyclableHandleStatement!)
init(with core: Core, on propertyConvertibleList: [PropertyConvertible], table: String, isDistinct: Bool) throws {
//TODO: Use generic to check all coding table keys conform to same root type
keys = propertyConvertibleList.asCodingTableKeys()
let statement = StatementSelect().select(distinct: isDistinct, propertyConvertibleList).from(table)
super.init(with: core, statement: statement)
}
/// Get next selected object according to the `CodingTableKey`. You can do an iteration using it.
///
/// - Returns: Table decodable object according to the `CodingTableKey`. Nil means the end of iteration.
/// - Throws: `Error`
public func nextObject() throws -> Any? {
let rootType = keys[0].rootType as? TableDecodableBase.Type
assert(rootType != nil, "\(keys[0].rootType) must conform to TableDecodable protocol.")
guard try next() else {
return nil
}
return try rootType!.init(from: decoder)
}
/// Get all selected objects according to the `CodingTableKey`.
///
/// - Returns: Table decodable objects according to the `CodingTableKey`
/// - Throws: `Error`
public func allObjects() throws -> [Any] {
let rootType = keys[0].rootType as? TableDecodableBase.Type
assert(rootType != nil, "\(keys[0].rootType) must conform to TableDecodable protocol.")
var objects: [Any] = []
while try next() {
objects.append(try rootType!.init(from: decoder))
}
return objects
}
/// Get next selected object with type. You can do an iteration using it.
///
/// - Parameter type: Type of table decodable object
/// - Returns: Table decodable object. Nil means the end of iteration.
/// - Throws: `Error`
public func nextObject<Object: TableDecodable>(of type: Object.Type = Object.self) throws -> Object? {
assert(keys is [Object.CodingKeys], "Properties must belong to \(Object.self).CodingKeys.")
guard try next() else {
return nil
}
return try Object.init(from: decoder)
}
/// Get all selected objects.
///
/// - Parameter type: Type of table decodable object
/// - Returns: Table decodable objects.
/// - Throws: `Error`
public func allObjects<Object: TableDecodable>(of type: Object.Type = Object.self) throws -> [Object] {
assert(keys is [Object.CodingKeys], "Properties must belong to \(Object.self).CodingKeys.")
var objects: [Object] = []
while try next() {
objects.append(try Object.init(from: decoder))
}
return objects
}
}
| 40.404494 | 118 | 0.664905 |
64f89b09220351da65b31076bd306c8a9fa9927c | 1,832 | /*
Copyright 2020 Armando Brito
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
extension UIView {
func addContainedView(_ containedView: UIView) {
containedView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(containedView)
self.topAnchor.constraint(equalTo: containedView.topAnchor).isActive = true
self.leadingAnchor.constraint(equalTo: containedView.leadingAnchor).isActive = true
self.trailingAnchor.constraint(equalTo: containedView.trailingAnchor).isActive = true
self.widthAnchor.constraint(equalTo: containedView.widthAnchor).isActive = true
self.bottomAnchor.constraint(equalTo: containedView.bottomAnchor).isActive = true
self.heightAnchor.constraint(equalTo: containedView.heightAnchor).isActive = true
}
}
| 63.172414 | 460 | 0.775655 |
72bab28598b12badf15c3c5cf92d11b6655bcb7b | 961 | //
// VGPlayerTests.swift
// VGPlayerTests
//
// Created by Vein on 2017/5/29.
// Copyright © 2017年 Vein. All rights reserved.
//
import XCTest
@testable import VGPlayer
class VGPlayerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.972973 | 111 | 0.630593 |
e58b77495b12ed35cf03ce54f0d27eea8ee0ede3 | 1,879 | //
// Extension.swift
// Chat
//
// Created by zapcannon87 on 2019/5/5.
// Copyright © 2019 LeanCloud. All rights reserved.
//
import Foundation
import UIKit
func mainQueueExecuting(_ closure: @escaping () -> Void) {
if Thread.isMainThread {
closure()
} else {
DispatchQueue.main.async {
closure()
}
}
}
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MM'-'dd HH':'mm':'ss"
formatter.timeZone = .current
return formatter
}()
extension UIAlertController {
static func show(error aError: Error, controller: UIViewController?) {
self.show(error: "\(aError)", controller: controller)
}
static func show(error string: String, controller: UIViewController?) {
mainQueueExecuting {
let alert = UIAlertController(
title: "Error",
message: string,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .cancel))
controller?.present(alert, animated: true)
}
}
}
extension UIImage {
static func whiteImage(size: CGSize) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, true, 1.0)
UIColor.white.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
enum JPEGQuality: CGFloat {
case lowest = 0
case low = 0.25
case medium = 0.5
case high = 0.75
case highest = 1
}
func jpeg(quality: JPEGQuality = .medium) -> Data? {
return jpegData(compressionQuality: quality.rawValue)
}
}
| 24.723684 | 77 | 0.588079 |
91b4e2d70f749455d1e2c4e470a97ab7462fe4f4 | 341 | //
// DescCollection+Hashable.swift
// OrderedCollection
//
// Created by Vitali Kurlovich on 1/15/19.
//
import Foundation
extension DescCollection: Hashable where Buffer: Hashable {
public var hashValue: Int { return buffer.hashValue }
public func hash(into hasher: inout Hasher) {
buffer.hash(into: &hasher)
}
}
| 20.058824 | 59 | 0.697947 |
e07062a61760d39df3376162c3589e2163d6b722 | 7,138 | //
// KYWithdrawListViewController.swift
// KYMart
//
// Created by JUN on 2017/6/29.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
import MJRefresh
fileprivate let KYWithDrawListTVCellIdentifier = "kYWithDrawListTVCell"
class KYWithdrawListViewController: BaseViewController {
/// 列表
fileprivate lazy var tableView : UITableView = {
let tableView = UITableView(frame:CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT), style: .plain)
tableView.showsVerticalScrollIndicator = false
tableView.separatorStyle = .none
tableView.register(UINib(nibName: "KYWithDrawListTVCell", bundle: nil), forCellReuseIdentifier: KYWithDrawListTVCellIdentifier)
tableView.backgroundColor = UIColor.white
tableView.delegate = self
tableView.dataSource = self
tableView.tableHeaderView = self.tableViewHeadView
return tableView
}()
fileprivate lazy var tableViewHeadView : KYUserInfoView = {
let tableViewHeadView = KYUserInfoView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH*3/5 + 51 + 51))
tableViewHeadView.userModel = SingleManager.instance.userInfo
tableViewHeadView.titleL.text = "提现信息"
return tableViewHeadView
}()
/// 下拉刷新
fileprivate lazy var header:MJRefreshNormalHeader = {
let header = MJRefreshNormalHeader()
header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
return header
}()
/// 上拉加载
fileprivate lazy var footer:MJRefreshAutoNormalFooter = {
let footer = MJRefreshAutoNormalFooter()
footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
return footer
}()
//刷新页数
var page = 1
/// 数据源
var info:Info?{
didSet {
}
}
fileprivate lazy var dataArray:NSMutableArray = {
let dataArray = NSMutableArray()
return dataArray
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.subviews[0].alpha = 0
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.subviews[0].alpha = 1
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
// Do any additional setup after loading the view.
}
func setupUI() {
view.addSubview(tableView)
setBackButtonInNav()
self.automaticallyAdjustsScrollViewInsets = false
view.backgroundColor = UIColor.white
// tableView.mj_header = header
tableView.mj_footer = footer
dataRequest()
}
// 下拉加载
func headerRefresh() {
page = 1
dataRequest()
}
/// 上拉刷新
func footerRefresh() {
page += 1
dataRequest()
}
func dataRequest(){
SJBRequestModel.pull_fetchWithdrawListData(page: page) { (response, status) in
// self.tableView.mj_header.endRefreshing()
if status == 1 {
let model = response as! KYWithdrawListModel
self.info = model.info
if self.page == 1{
self.dataArray.removeAllObjects()
}
else
{
if model.result.count == 0{
XHToast.showBottomWithText("没有更多数据")
self.page -= 1
self.tableView.mj_footer.endRefreshing()
return
}
else
{
self.tableView.mj_footer.endRefreshing()
}
}
if self.dataArray.count > 0{
//去重
for item in model.result {
let predicate = NSPredicate(format: "id = %@", String(item.id))
let result = self.dataArray.filtered(using: predicate)
if result.count <= 0{
self.dataArray.add(item)
}
}
}
else
{
self.dataArray.addObjects(from: model.result!)
}
self.tableView.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension KYWithdrawListViewController:UITableViewDelegate,UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: KYWithDrawListTVCellIdentifier, for: indexPath) as! KYWithDrawListTVCell
if indexPath.section == 1 {
cell.result = dataArray[indexPath.row] as? Result
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
let headView = KYWithdrawHeadView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 336))
headView.info = self.info
headView.saveResult({
self.navigationController?.popViewController(animated: true)
})
return headView
}
return nil
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 336
}
return 0
}
// 去除头部悬停
func scrollViewDidScroll(_ scrollView: UIScrollView) {
navigationController?.navigationBar.subviews[0].alpha = scrollView.contentOffset.y/(SCREEN_WIDTH*3/5 + 51)
let sectionHeaderH:CGFloat = 336
if tableView.contentOffset.y < sectionHeaderH && tableView.contentOffset.y > 0 {
tableView.contentInset = UIEdgeInsetsMake(-tableView.contentOffset.y, 0, 0, 0)
}
else if (tableView.contentOffset.y >= sectionHeaderH){
tableView.contentInset = UIEdgeInsetsMake(-sectionHeaderH, 0, 0, 0)
}
}
}
| 34.819512 | 137 | 0.597646 |
28fcaada2ff6eeac23b9ffd817473d6be576d049 | 278 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<b: T: a {
enum S<T.h:as b: T: C {
var e: NSObject {
if true {
[k<j
{
protocol h : a {
class
case c,
| 19.857143 | 87 | 0.694245 |
f984b8bac103de2befc532804201f9e4521c55e8 | 472 | //
// DownloadingDelegate.swift
// StreamAudio
//
// Created by leven on 2020/8/21.
// Copyright © 2020 leven. All rights reserved.
//
import Foundation
public protocol DownloadingDelegate: class {
func download(_ download: Downloading, changeState state: DownloadingState)
func download(_ download: Downloading, completedWithError error: Error?)
func download(_ download: Downloading, didReceivedData data: Data, progress: Float)
}
| 22.47619 | 87 | 0.71822 |
5dfebc9a4476255279e7ee18f5644654f8fe1648 | 3,593 | //
// ExpressionAnalyzerViewController.swift
// Demo
//
// Created by Dave DeLong on 11/21/17.
//
import Cocoa
import MathParser
class ExpressionAnalyzerViewController: AnalyzerViewController, NSOutlineViewDelegate, NSOutlineViewDataSource {
@IBOutlet var expressionTree: NSOutlineView?
var parsedExpression: Expression?
override init() {
super.init()
title = "Expression"
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func analyzeString(_ string: String) {
do {
parsedExpression = try Expression(string: string)
} catch let e as MathParserError {
parsedExpression = nil
analyzerDelegate?.analyzerViewController(self, wantsErrorPresented: e)
} catch let other {
fatalError("Unknown error parsing expression: \(other)")
}
expressionTree?.reloadItem(nil, reloadChildren: true)
expressionTree?.expandItem(nil, expandChildren: true)
}
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item == nil {
return parsedExpression == nil ? 0 : 1
}
var maybeExpression = item as? Expression
maybeExpression = maybeExpression ?? parsedExpression
guard let expression = maybeExpression else { return 0 }
switch expression.kind {
case .function(_, let arguments): return arguments.count
default: return 0
}
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if item == nil, let e = parsedExpression { return e }
guard let expression = item as? Expression else { fatalError("should only have Expressions") }
switch expression.kind {
case .function(_, let arguments): return arguments[index]
default: fatalError("only argument functions have children")
}
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
return self.outlineView(outlineView, numberOfChildrenOfItem: item) > 0
}
func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? {
if item == nil { return "<root>"}
guard let expression = item as? Expression else { fatalError("should only have Expressions") }
let info: String
switch expression.kind {
case .number(let d): info = "Number: \(d)"
case .variable(let v): info = "Variable: \(v)"
case .function(let f, let args):
let argInfo = args.count == 1 ? "1 argument" : "\(args.count) arguments"
info = "\(f)(\(argInfo))"
}
return "\(info) - range: \(expression.range)"
}
func outlineViewSelectionDidChange(_ notification: Notification) {
let row = expressionTree?.selectedRow ?? -1
if row >= 0 {
guard let item = expressionTree?.item(atRow: row) else { fatalError("missing item at row \(row)") }
guard let expression = item as? Expression else { fatalError("only expressions should be in the tree") }
analyzerDelegate?.analyzerViewController(self, wantsHighlightedRanges: [expression.range])
} else {
// unhighlight everything in the textfield
analyzerDelegate?.analyzerViewController(self, wantsHighlightedRanges: [])
}
}
}
| 38.634409 | 123 | 0.624548 |
1c57e7ab32819e6f3d639aaee3dbff09b0044a68 | 901 | //
// MCTagCollectionView.swift
// MobileChallenge
//
// Created by VASILIJEVIC Sebastien on 20/04/2021.
//
import UIKit
class MCTagCollectionView: UICollectionView {
var isDynamicSizeRequired: Bool = false
var isUserEditing: Bool = false
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
if self.intrinsicContentSize.height > frame.size.height {
self.invalidateIntrinsicContentSize()
}
if isDynamicSizeRequired {
self.invalidateIntrinsicContentSize()
}
}
}
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
self.layoutIfNeeded()
}
override var intrinsicContentSize: CGSize {
return contentSize
}
}
| 23.710526 | 73 | 0.630411 |
0915dc4275f5e4ed920babbd82cfbd1a1d871e78 | 2,492 | // RUN: %target-parse-verify-swift
func f0(_ x: Float) -> Float {}
func f1(_ x: Float) -> Float {}
func f2(_ x: @autoclosure () -> Float) {}
var f : Float
_ = f0(f0(f))
_ = f0(1)
_ = f1(f1(f))
f2(f)
f2(1.0)
func call_lvalue(_ rhs: @autoclosure () -> Bool) -> Bool {
return rhs()
}
// Function returns
func weirdCast<T, U>(_ x: T) -> U {}
func ff() -> (Int) -> (Float) { return weirdCast }
// Block <-> function conversions
var funct: (Int) -> Int = { $0 }
var block: @convention(block) (Int) -> Int = funct
funct = block
block = funct
// Application of implicitly unwrapped optional functions
var optFunc: ((String) -> String)! = { $0 }
var s: String = optFunc("hi")
// <rdar://problem/17652759> Default arguments cause crash with tuple permutation
func testArgumentShuffle(_ first: Int = 7, third: Int = 9) {
}
testArgumentShuffle(third: 1, 2)
func rejectsAssertStringLiteral() {
assert("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}}
precondition("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}}
}
// <rdar://problem/22243469> QoI: Poor error message with throws, default arguments, & overloads
func process(_ line: UInt = #line, _ fn: () -> Void) {}
func process(_ line: UInt = #line) -> Int { return 0 }
func dangerous() throws {}
func test() {
process { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'}}
try dangerous()
test()
}
}
// <rdar://problem/19962010> QoI: argument label mismatches produce not-great diagnostic
class A {
func a(_ text:String) {
}
func a(_ text:String, something:Int?=nil) {
}
}
A().a(text:"sometext") // expected-error{{extraneous argument label 'text:' in call}}{{7-12=}}
// <rdar://problem/22451001> QoI: incorrect diagnostic when argument to print has the wrong type
func r22451001() -> AnyObject {}
print(r22451001(5)) // expected-error {{argument passed to call that takes no arguments}}
// SR-590 Passing two parameters to a function that takes one argument of type Any crashes the compiler
// SR-1028: Segmentation Fault: 11 when superclass init takes parameter of type 'Any'
func sr590(_ x: Any) {}
sr590(3,4) // expected-error {{extra argument in call}}
sr590() // expected-error {{missing argument for parameter #1 in call}}
// Make sure calling with structural tuples still works.
sr590(())
sr590((1, 2))
| 28.976744 | 152 | 0.672953 |
876093fdf7591c60d428b95015e88df5b220a839 | 335 | //
// ViewController.swift
// BookRoom
//
// Created by romance on 2017/5/3.
// Copyright © 2017年 firstleap. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| 16.75 | 76 | 0.692537 |
8f11c4282b0378821a7079397f4e50c87636cf4b | 425 | //
// Comparable+Ext.swift
// PhantomKit
//
// Created by Pawel Wiszenko on 25.05.2021.
// Copyright © 2021 Pawel Wiszenko. All rights reserved.
//
import Foundation
extension Comparable {
public func clamped(to bounds: PartialRangeFrom<Self>) -> Self {
max(self, bounds.lowerBound)
}
public func clamped(to bounds: PartialRangeThrough<Self>) -> Self {
min(self, bounds.upperBound)
}
}
| 21.25 | 71 | 0.670588 |
d9b63cd79438005d698274cb9e7f0dd094503593 | 775 | //
// ResultsSearchViewHelper.swift
// SearchShowsTests
//
// Created by Jeans Ruiz on 20/12/21.
//
@testable import SearchShows
@testable import Shared
public func createSectionModel(recentSearchs: [String], resultShows: [TVShow]) -> [ResultSearchSectionModel] {
var dataSource: [ResultSearchSectionModel] = []
let recentSearchsItem = recentSearchs.map { ResultSearchSectionItem.recentSearchs(items: $0) }
let resultsShowsItem = resultShows
.map { TVShowCellViewModel(show: $0) }
.map { ResultSearchSectionItem.results(items: $0) }
if !recentSearchsItem.isEmpty {
dataSource.append(.recentSearchs(items: recentSearchsItem))
}
if !resultsShowsItem.isEmpty {
dataSource.append(.results(items: resultsShowsItem))
}
return dataSource
}
| 25.833333 | 110 | 0.743226 |
d94c2e409f84e3a907b0e419083549673badc73f | 1,346 | //
// AppDelegate.swift
// LinkedList
//
// Created by SuniMac on 2020/10/6.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.378378 | 179 | 0.745914 |
469ec46cf39d67f8cca923fbeb365e51ea60ee4d | 2,886 | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*/
import HTTPServerMock
import XCTest
private extension ExampleApplication {
func tapPushNextScreenButton() {
buttons["Push Next Screen"].tap()
}
func tapBackButton() {
navigationBars["Screen 4"].buttons["Screen 3"].tap()
}
func tapPopToTheFirstScreenButton() {
buttons["Pop To The First Screen"].tap()
}
func swipeInteractiveBackGesture() {
let coordinate1 = coordinate(withNormalizedOffset: .init(dx: 0, dy: 0.5))
let coordinate2 = coordinate(withNormalizedOffset: .init(dx: 0.75, dy: 0.5))
coordinate1.press(forDuration: 0.5, thenDragTo: coordinate2)
}
}
class RUMNavigationControllerScenarioTests: IntegrationTests, RUMCommonAsserts {
func testRUMNavigationControllerScenario() throws {
// Server session recording RUM events send to `HTTPServerMock`.
let rumServerSession = server.obtainUniqueRecordingSession()
let app = ExampleApplication()
app.launchWith(
testScenario: RUMNavigationControllerScenario.self,
serverConfiguration: HTTPServerMockConfiguration(
rumEndpoint: rumServerSession.recordingURL
)
) // start on "Screen1"
app.tapPushNextScreenButton() // go to "Screen2"
app.tapPushNextScreenButton() // go to "Screen3"
app.tapPushNextScreenButton() // go to "Screen4"
app.tapBackButton() // go to "Screen3"
app.tapPopToTheFirstScreenButton() // go to "Screen1"
app.tapPushNextScreenButton() // go to "Screen2"
app.swipeInteractiveBackGesture() // swipe back to "Screen1"
// Get RUM Sessions with expected number of View visits
let recordedRUMRequests = try rumServerSession.pullRecordedRequests(timeout: dataDeliveryTimeout) { requests in
try RUMSessionMatcher.from(requests: requests)?.viewVisits.count == 8
}
assertRUM(requests: recordedRUMRequests)
let session = try XCTUnwrap(RUMSessionMatcher.from(requests: recordedRUMRequests))
XCTAssertEqual(session.viewVisits[0].path, "Screen1")
XCTAssertEqual(session.viewVisits[0].actionEvents[0].action.type, .applicationStart)
XCTAssertEqual(session.viewVisits[1].path, "Screen2")
XCTAssertEqual(session.viewVisits[2].path, "Screen3")
XCTAssertEqual(session.viewVisits[3].path, "Screen4")
XCTAssertEqual(session.viewVisits[4].path, "Screen3")
XCTAssertEqual(session.viewVisits[5].path, "Screen1")
XCTAssertEqual(session.viewVisits[6].path, "Screen2")
XCTAssertEqual(session.viewVisits[7].path, "Screen1")
}
}
| 41.228571 | 119 | 0.693694 |
ed80671846a544fa40d9d151d313235925ccdd75 | 447 | /// The role for an Apple Watch icon
public enum AppleWatchRole: String, Codable {
/** The icon is used in the notification center. */
case notificationCenter
/**
The icon is used in settings.
*/
case companionSettings
/** The icon is used in the app launcher. */
case appLauncher
/** The icon is used for a long-look notification. */
case longLook
/** The icon is used for a short-look notification. */
case quickLook
}
| 27.9375 | 56 | 0.691275 |
268a7215b8cc8b1f60c676b6b02378501243c021 | 764 | import UIKit
import XCTest
import MakeColor
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 25.466667 | 111 | 0.60733 |
39f871e168c7662332e9d8e4af8d5b75f0eade57 | 17,360 | //
// JSSAlertView
// JSSAlertView
//
// Created by Jay Stakelon on 9/16/14.
// Maintained by Tomas Sykora since 2015
// Copyright (c) 2016 / https://github.com/JSSAlertView - all rights reserved.
//
// Inspired by and modeled after https://github.com/vikmeup/SCLAlertView-Swift
// by Victor Radchenko: https://github.com/vikmeup
//
import Foundation
import UIKit
/// Enum describing Text Color theme
///
/// - dark: Dark Text Color theme
/// - light: Light Text Color theme
public enum TextColorTheme {
case dark, light
}
/// Custom modal controller
open class JSSAlertView: UIViewController {
var containerView: UIView!
var alertBackgroundView: UIView!
var dismissButton: UIButton!
var cancelButton: UIButton!
var buttonLabel: UILabel!
var cancelButtonLabel: UILabel!
var titleLabel: UILabel!
var timerLabel:UILabel!
var textView: UITextView!
weak var rootViewController: UIViewController!
var iconImage: UIImage!
var iconImageView: UIImageView!
var closeAction: (()->Void)!
var cancelAction: (()->Void)!
var isAlertOpen: Bool = false
var noButtons: Bool = false
var timeLeft: UInt?
enum FontType {
case title, text, button, timer
}
var titleFont = "HelveticaNeue-Light"
var textFont = "HelveticaNeue"
var buttonFont = "HelveticaNeue-Bold"
var timerFont = "HelveticaNeue"
var defaultColor = UIColorFromHex(0xF2F4F4, alpha: 1)
var darkTextColor = UIColorFromHex(0x000000, alpha: 0.75)
var lightTextColor = UIColorFromHex(0xffffff, alpha: 0.9)
public enum ActionType {
case close, cancel
}
let baseHeight: CGFloat = 160.0
var alertWidth: CGFloat = 290.0
let buttonHeight: CGFloat = 70.0
let padding: CGFloat = 20.0
var viewWidth: CGFloat?
var viewHeight: CGFloat?
// Allow alerts to be closed/renamed in a chainable manner
//MARK: Initializators
/// Public contructor overriding parent
///
/// - Parameters:
/// - nibNameOrNil: Nib name is never used, should be always nil, there is no nib in JSSAlertView
/// - nibBundleOrNil: Nib bundle is never used there is no nib bundle in JJSAlertView Controller
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Recolors text to given color
///
/// - Parameter color: Color to be recolored to
func recolorText(_ color: UIColor) {
if titleLabel != nil {
titleLabel.textColor = color
}
if textView != nil {
textView.textColor = color
}
if timerLabel != nil {
timerLabel.textColor = color
}
if self.noButtons == false {
buttonLabel.textColor = color
if cancelButtonLabel != nil {
cancelButtonLabel.textColor = color
}
}
}
open override func viewDidLayoutSubviews() {
super.viewWillLayoutSubviews()
let size = self.rootViewControllerSize()
self.viewWidth = size.width
self.viewHeight = size.height
var yPos: CGFloat = 0.0
let contentWidth:CGFloat = self.alertWidth - (self.padding*2)
// position the icon image view, if there is one
if self.iconImageView != nil {
yPos += iconImageView.frame.height
let centerX = (self.alertWidth-self.iconImageView.frame.width)/2
self.iconImageView.frame.origin = CGPoint(x: centerX, y: self.padding)
yPos += padding
}
// position the title
var titleAttr: Dictionary<NSAttributedString.Key, Any>? = nil
if self.titleLabel != nil {
let titleString = titleLabel.text! as NSString
let titleSize = CGSize(width: contentWidth, height: 90)
titleAttr = [NSAttributedString.Key.font: titleLabel.font!]
let titleRect = titleString.boundingRect(with: titleSize, options: .usesLineFragmentOrigin, attributes: titleAttr, context: nil)
yPos += padding
titleLabel.frame = CGRect(x: padding, y: yPos, width: alertWidth - (padding * 2), height: ceil(titleRect.height))
yPos += ceil(titleRect.height)
}
// position text
if self.textView != nil {
let textString = textView.text! as NSString
let textAttr = [NSAttributedString.Key.font: textView.font!]
let realSize = textView.sizeThatFits(CGSize(width: contentWidth, height: CGFloat.greatestFiniteMagnitude))
let textSize = CGSize(width: contentWidth, height: CGFloat(fmaxf(Float(90.0), Float(realSize.height))))
let textRect = textString.boundingRect(with: textSize, options: .usesLineFragmentOrigin, attributes: textAttr, context: nil)
textView.frame = CGRect(x: padding, y: yPos, width: alertWidth - (padding * 2), height: ceil(textRect.height) * 2)
yPos += ceil(textRect.height) + padding / 2
}
// position timer
if self.timerLabel != nil {
let timerString = timerLabel.text! as NSString
let timerSize = CGSize(width: contentWidth, height: 20)
let timerRect = timerString.boundingRect(with: timerSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: titleAttr, context: nil)
self.timerLabel.frame = CGRect(x: self.padding, y: yPos, width: self.alertWidth - (self.padding*2), height: ceil(timerRect.size.height))
yPos += ceil(timerRect.size.height)
}
// position the buttons
if !noButtons {
yPos += padding
var buttonWidth = alertWidth
if cancelButton != nil {
buttonWidth = alertWidth / 2
cancelButton.frame = CGRect(x: 0, y: yPos, width: buttonWidth - 0.5, height: buttonHeight)
if cancelButtonLabel != nil {
cancelButtonLabel.frame = CGRect(x: padding, y: (buttonHeight / 2) - 15, width: buttonWidth - (padding * 2), height: 30)
}
}
let buttonX = buttonWidth == alertWidth ? 0 : buttonWidth
dismissButton.frame = CGRect(x: buttonX, y: yPos, width: buttonWidth, height: buttonHeight)
if buttonLabel != nil {
buttonLabel.frame = CGRect(x: padding, y: (buttonHeight / 2) - 15, width: buttonWidth - (padding * 2), height: 30)
}
// set button fonts
if buttonLabel != nil {
buttonLabel.font = UIFont(name: buttonFont, size: 27)
}
if cancelButtonLabel != nil {
cancelButtonLabel.font = UIFont(name: buttonFont, size: 27)
}
yPos += buttonHeight
}else{
yPos += padding
}
// size the background view
alertBackgroundView.frame = CGRect(x: 0, y: 0, width: alertWidth, height: yPos)
// size the container that holds everything together
containerView.frame = CGRect(x: (viewWidth! - alertWidth) / 2, y: (viewHeight! - yPos)/2, width: alertWidth, height: yPos)
}
// MARK: - Main Show Method
/// Main method for rendering JSSAlertViewController
///
///
/// - Parameters:
/// - viewController: ViewController above which JSSAlertView will be shown
/// - title: JSSAlertView title
/// - text: JSSAlertView text
/// - noButtons: Option for no buttons, ehen activated, it gets closed by tap
/// - buttonText: Button text
/// - cancelButtonText: Cancel button text
/// - color: JSSAlertView color
/// - iconImage: Image which gets placed above title
/// - delay: Delay after which JSSAlertView automatically disapears
/// - timeLeft: Counter aka Tinder counter shows time in seconds
/// - Returns: returns JSSAlertViewResponder
@discardableResult
public func show(_ viewController: UIViewController,
title: String?=nil,
text: String?=nil,
noButtons: Bool = false,
buttonText: String? = nil,
cancelButtonText: String? = nil,
color: UIColor? = nil,
iconImage: UIImage? = nil,
delay: Double? = nil,
timeLeft: UInt? = nil) -> JSSAlertViewResponder {
rootViewController = viewController
view.backgroundColor = UIColorFromHex(0x000000, alpha: 0.2)//DEREK
var baseColor:UIColor?
if let customColor = color {
baseColor = customColor
} else {
baseColor = defaultColor
}
let textColor = darkTextColor
let sz = screenSize()
viewWidth = sz.width
viewHeight = sz.height
view.frame.size = sz
// Container for the entire alert modal contents
containerView = UIView()
view.addSubview(containerView!)
// Background view/main color
alertBackgroundView = UIView()
alertBackgroundView.backgroundColor = baseColor
alertBackgroundView.layer.cornerRadius = 12
alertBackgroundView.layer.masksToBounds = true
containerView.addSubview(alertBackgroundView!)
// Icon
self.iconImage = iconImage
if iconImage != nil {
iconImageView = UIImageView(image: iconImage)
containerView.addSubview(iconImageView)
}
// Title
if let title = title {
titleLabel = UILabel()
titleLabel.textColor = textColor
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
titleLabel.font = UIFont(name: self.titleFont, size: 28)
titleLabel.text = title
containerView.addSubview(titleLabel)
}
// View text
if let text = text {
textView = UITextView()
textView.isUserInteractionEnabled = false
textView.isEditable = false
textView.textColor = textColor
textView.textAlignment = .center
textView.font = UIFont(name: self.textFont, size: 16)
textView.backgroundColor = UIColor.clear
textView.text = text
containerView.addSubview(textView)
}
//timer
if let time = timeLeft {
self.timerLabel = UILabel()
timerLabel.textAlignment = .center
self.timeLeft = time
self.timerLabel.font = UIFont(name: self.timerFont, size: 27)
self.timerLabel.textColor = textColor
self.containerView.addSubview(timerLabel)
configureTimer()
}
// Button
self.noButtons = true
if !noButtons {
self.noButtons = false
dismissButton = UIButton()
let buttonColor = UIImage.with(color: adjustBrightness(baseColor!, amount: 0.8))
let buttonHighlightColor = UIImage.with(color: adjustBrightness(baseColor!, amount: 0.9))
dismissButton.setBackgroundImage(buttonColor, for: .normal)
dismissButton.setBackgroundImage(buttonHighlightColor, for: .highlighted)
dismissButton.addTarget(self, action: #selector(buttonTap), for: .touchUpInside)
alertBackgroundView!.addSubview(dismissButton)
// Button text
buttonLabel = UILabel()
buttonLabel.textColor = textColor
buttonLabel.numberOfLines = 1
buttonLabel.textAlignment = .center
if let text = buttonText {
buttonLabel.text = text
} else {
buttonLabel.text = "OK"
}
dismissButton.accessibilityLabel = buttonLabel.text
dismissButton.addSubview(buttonLabel)
// Second cancel button
if cancelButtonText != nil {
cancelButton = UIButton()
let buttonColor = UIImage.with(color: adjustBrightness(baseColor!, amount: 0.8))
let buttonHighlightColor = UIImage.with(color: adjustBrightness(baseColor!, amount: 0.9))
cancelButton.setBackgroundImage(buttonColor, for: .normal)
cancelButton.setBackgroundImage(buttonHighlightColor, for: .highlighted)
cancelButton.addTarget(self, action: #selector(JSSAlertView.cancelButtonTap), for: .touchUpInside)
alertBackgroundView!.addSubview(cancelButton)
// Button text
cancelButtonLabel = UILabel()
cancelButtonLabel.alpha = 0.7
cancelButtonLabel.textColor = textColor
cancelButtonLabel.numberOfLines = 1
cancelButtonLabel.textAlignment = .center
cancelButtonLabel.text = cancelButtonText
cancelButton.accessibilityLabel = cancelButtonText
cancelButton.addSubview(cancelButtonLabel)
}
}
// Animate it in
view.alpha = 0
definesPresentationContext = true
modalPresentationStyle = .overFullScreen
viewController.present(self, animated: false, completion: {
// Animate it in
UIView.animate(withDuration: 0.2) {
self.view.alpha = 1
}
self.containerView.center.x = self.view.center.x
self.containerView.center.y = -500
UIView.animate(withDuration: 0.5, delay: 0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: [], animations: {
self.containerView.center = self.view.center
}, completion: { finished in
self.isAlertOpen = true
if let d = delay {
DispatchQueue.main.asyncAfter(deadline: .now() + d, execute: {
self.closeView(true)
})
}
})
})
return JSSAlertViewResponder(alertview: self)
}
/// Adding action for button which is not cancel button
///
/// - Parameter action: func which gets executed when disapearing
func addAction(_ action: @escaping () -> Void) {
self.closeAction = action
}
/// Method for removing JSSAlertView from view when there are no buttons
@objc func buttonTap() {
closeView(true, source: .close);
}
/// Adds action as a function which gets executed when cancel button is tapped
///
/// - Parameter action: func which gets executed
func addCancelAction(_ action: @escaping () -> Void) {
self.cancelAction = action
}
/// Cancel button tap
@objc func cancelButtonTap() {
closeView(true, source: .cancel);
}
/// Removes view
///
/// - Parameters:
/// - withCallback: callback availabel
/// - source: Type of removing view see ActionType
public func closeView(_ withCallback: Bool, source: ActionType = .close) {
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: {
self.containerView.center.y = self.view.center.y + self.viewHeight!
}, completion: { finished in
UIView.animate(withDuration: 0.1, animations: {
self.view.alpha = 0
}, completion: { finished in
self.dismiss(animated: false, completion: {
if withCallback {
if let action = self.closeAction , source == .close {
action()
}
else if let action = self.cancelAction, source == .cancel {
action()
}
}
})
})
})
}
/// Removes view from superview
func removeView() {
isAlertOpen = false
removeFromParent()
view.removeFromSuperview()
}
/// Returns rootViewControllers size
///
/// - Returns: root view controller size
func rootViewControllerSize() -> CGSize {
let size = rootViewController.view.frame.size
if (NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1) && UIApplication.shared.statusBarOrientation.isLandscape {
return CGSize(width: size.height, height: size.width)
}
return size
}
/// Gets screen size
///
/// - Returns: screen size
func screenSize() -> CGSize {
let screenSize = UIScreen.main.bounds.size
if (NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1) && UIApplication.shared.statusBarOrientation.isLandscape {
return CGSize(width: screenSize.height, height: screenSize.width)
}
return screenSize
}
/// Tracks touches used when there are no buttons to remove view
///
/// - Parameters:
/// - touches: touched actions form user
/// - event: touches event
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let locationPoint = touch.location(in: view)
let converted = containerView.convert(locationPoint, from: view)
if containerView.point(inside: converted, with: event){
if noButtons {
closeView(true, source: .cancel)
}
}
}
}
//MARK: - Memory management
/// Memory management not actually needed
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK: - Setters
extension JSSAlertView {
/// Sets Font
///
/// - Parameters:
/// - fontStr: name of font
/// - type: target to set font to e.g. title, text ...
func setFont(_ fontStr: String, type: FontType) {
switch type {
case .title:
self.titleFont = fontStr
if let font = UIFont(name: self.titleFont, size: 28) {
self.titleLabel.font = font
} else {
self.titleLabel.font = UIFont.systemFont(ofSize: 28)
}
case .text:
if self.textView != nil {
self.textFont = fontStr
if let font = UIFont(name: self.textFont, size: 16) {
self.textView.font = font
} else {
self.textView.font = UIFont.systemFont(ofSize: 16)
}
}
case .button:
self.buttonFont = fontStr
if let font = UIFont(name: self.buttonFont, size: 27) {
self.buttonLabel.font = font
} else {
self.buttonLabel.font = UIFont.systemFont(ofSize: 27)
}
case .timer:
self.timerFont = fontStr
if let font = UIFont(name: self.timerFont, size: 27) {
self.buttonLabel.font = font
} else {
self.buttonLabel.font = UIFont.systemFont(ofSize: 27)
}
}
// relayout to account for size changes
self.viewDidLayoutSubviews()
}
/// Sets theme
///
/// - Parameter theme: TextColorTheme
func setTextTheme(_ theme: TextColorTheme) {
switch theme {
case .light:
recolorText(lightTextColor)
case .dark:
recolorText(darkTextColor)
}
}
}
| 31.111111 | 162 | 0.673387 |
6a39aa2d972af9bf6e28df12d6495ecf2364bfb2 | 2,403 | //
// GreatPersons.swift
// SmartAILibrary
//
// Created by Michael Rommel on 04.08.20.
// Copyright © 2020 Michael Rommel. All rights reserved.
//
import Foundation
// https://forums.civfanatics.com/resources/the-mechanism-of-great-people.26276/
public class GreatPersons: Codable {
enum CodingKeys: CodingKey {
case spawned
case current
}
var spawned: [GreatPerson]
var current: [GreatPerson]
init() {
self.spawned = []
self.current = []
self.fillCurrent(in: .ancient)
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.spawned = try container.decode([GreatPerson].self, forKey: .spawned)
self.current = try container.decode([GreatPerson].self, forKey: .current)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.spawned, forKey: .spawned)
try container.encode(self.current, forKey: .current)
}
func fillCurrent(in era: EraType) {
for greatPersonType in GreatPersonType.all {
// check for empty slots
if self.current.first(where: { $0.type() == greatPersonType }) == nil {
var possibleGreatPersons = GreatPerson.all.filter({ $0.era() == era && $0.type() == greatPersonType && !self.spawned.contains($0) })
// consider next era
if possibleGreatPersons.isEmpty {
possibleGreatPersons = GreatPerson.all.filter({ $0.era() == era.next() && $0.type() == greatPersonType && !self.spawned.contains($0) })
}
if !possibleGreatPersons.isEmpty {
self.current.append(possibleGreatPersons.randomItem())
}
}
}
}
func person(of greatPersonType: GreatPersonType) -> GreatPerson? {
return self.current.first(where: { $0.type() == greatPersonType })
}
func invalidate(greatPerson: GreatPerson, in gameModel: GameModel?) {
guard let gameModel = gameModel else {
fatalError("cant get gameModel")
}
self.current.removeAll(where: { $0 == greatPerson })
self.spawned.append(greatPerson)
self.fillCurrent(in: gameModel.worldEra())
}
}
| 27.94186 | 155 | 0.612151 |
0971ba4415e620418ae127b6ae27d9cddd83cb35 | 901 | //
// Helper.swift
// Project24
//
// Created by Hudzilla on 25/11/2014.
// Copyright (c) 2014 Hudzilla. All rights reserved.
//
import UIKit
func RandomInt(#min: Int, #max: Int) -> Int {
if max < min { return min }
return Int(arc4random_uniform(UInt32((max - min) + 1))) + min
}
extension Int {
mutating func plusOne() {
++self
}
static func random(#min: Int, max: Int) -> Int {
if max < min { return min }
return Int(arc4random_uniform((max - min) + 1)) + min
}
}
extension String {
mutating func trim() {
self = stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
}
extension UIColor {
class func chartreuseColor() -> UIColor {
return UIColor(red: 0.875, green: 1, blue: 0, alpha: 1)
}
}
extension UIView {
func fadeOut(duration: NSTimeInterval) {
UIView.animateWithDuration(duration) { [unowned self] in
self.alpha = 0
}
}
} | 20.022222 | 91 | 0.671476 |
01e0e57009a19ea85700810f1249dae8614c7ed1 | 2,047 | //
// BCRawArrayDeserializableTests.swift
// BlueCapKit
//
// Created by Troy Stribling on 2/9/15.
// Copyright (c) 2015 Troy Stribling. The MIT License (MIT).
//
import UIKit
import XCTest
import CoreBluetooth
import CoreLocation
@testable import BlueCapKit
// MARK: - BCRawArrayDeserializableTests -
class BCRawArrayDeserializableTests: XCTestCase {
struct RawArray: BCRawArrayDeserializable {
let value1:Int8
let value2:Int8
// RawArrayDeserializable
static let UUID = "abc"
static let size = 2
init?(rawValue:[Int8]) {
if rawValue.count == 2 {
self.value1 = rawValue[0]
self.value2 = rawValue[1]
} else {
return nil
}
}
var rawValue : [Int8] {
return [self.value1, self.value2]
}
}
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testSuccessfulDeserialization() {
let data = "02ab".dataFromHexString()
if let value : RawArray = BCSerDe.deserialize(data) {
XCTAssert(value.value1 == 2 && value.value2 == -85, "RawArrayDeserializable deserialization value invalid: \(value.value1), \(value.value2)")
} else {
XCTFail("RawArrayDeserializable deserialization failed")
}
}
func testFailedDeserialization() {
let data = "02ab0c".dataFromHexString()
if let _ : RawArray = BCSerDe.deserialize(data) {
XCTFail("RawArrayDeserializable deserialization succeeded")
}
}
func testSerialization() {
if let value = RawArray(rawValue: [5, 100]) {
let data = BCSerDe.serialize(value)
XCTAssert(data.hexStringValue() == "0564", "RawArrayDeserializable serialization value invalid: \(data)")
} else {
XCTFail("RawArrayDeserializable RawArray creation failed")
}
}
}
| 26.934211 | 153 | 0.586224 |
677a03218654422cf164c71561e8acc768ed5cae | 3,287 | #if canImport(CommonCrypto)
import CommonCrypto
#else
import CryptoSwift
#endif
import Foundation
#if canImport(CommonCrypto)
private extension String {
func md5() -> String {
let context = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: 1)
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5_Init(context)
CC_MD5_Update(context, self, CC_LONG(lengthOfBytes(using: .utf8)))
CC_MD5_Final(&digest, context)
context.deallocate()
return digest.reduce(into: "") { $0.append(String(format: "%02x", $1)) }
}
}
#endif
extension Configuration {
// MARK: Caching Configurations By Path (In-Memory)
private static var cachedConfigurationsByPath = [String: Configuration]()
private static var cachedConfigurationsByPathLock = NSLock()
internal func setCached(atPath path: String) {
Configuration.cachedConfigurationsByPathLock.lock()
Configuration.cachedConfigurationsByPath[path] = self
Configuration.cachedConfigurationsByPathLock.unlock()
}
internal static func getCached(atPath path: String) -> Configuration? {
cachedConfigurationsByPathLock.lock()
defer { cachedConfigurationsByPathLock.unlock() }
return cachedConfigurationsByPath[path]
}
/// Returns a copy of the current `Configuration` with its `computedCacheDescription` property set to the value of
/// `cacheDescription`, which is expensive to compute.
public func withPrecomputedCacheDescription() -> Configuration {
var result = self
result.computedCacheDescription = result.cacheDescription
return result
}
// MARK: SwiftLint Cache (On-Disk)
internal var cacheDescription: String {
if let computedCacheDescription = computedCacheDescription {
return computedCacheDescription
}
let cacheRulesDescriptions = rules
.map { rule in
return [type(of: rule).description.identifier, rule.cacheDescription]
}
.sorted { rule1, rule2 in
return rule1[0] < rule2[0]
}
let jsonObject: [Any] = [
rootPath ?? FileManager.default.currentDirectoryPath,
cacheRulesDescriptions
]
if let jsonData = try? JSONSerialization.data(withJSONObject: jsonObject),
let jsonString = String(data: jsonData, encoding: .utf8) {
return jsonString.md5()
}
queuedFatalError("Could not serialize configuration for cache")
}
internal var cacheURL: URL {
let baseURL: URL
if let path = cachePath {
baseURL = URL(fileURLWithPath: path)
} else {
#if os(Linux)
baseURL = URL(fileURLWithPath: "/var/tmp/")
#else
baseURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
#endif
}
let folder = baseURL.appendingPathComponent("SwiftLint/\(Version.current.value)")
do {
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, attributes: nil)
} catch {
queuedPrintError("Error while creating cache: " + error.localizedDescription)
}
return folder
}
}
| 34.6 | 118 | 0.65896 |
260a09273ea6bb128d72409cf8dec2137b21fb68 | 2,352 | //
// FakeDataSource.swift
// Vimeo
//
// Created by Westendorf, Michael on 7/25/16.
// Copyright © 2016 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
@testable import VimeoNetworking
class FakeDataSource<T: VIMMappable> {
private let mapper = VIMObjectMapper()
var items: [T]?
var error: NSError?
init(jsonData: [AnyHashable: Any], keyPath: String) {
mapper.addMappingClass(T.self, forKeypath: keyPath)
guard let mappedData = mapper.applyMapping(toJSON: jsonData) as? [AnyHashable: Any] else {
return
}
if let objects = mappedData["data"] as? [T] {
self.items = objects
}
else if let object = mappedData as? T {
self.items = [object]
}
}
static func loadJSONFile(jsonFileName: String, withExtension: String) -> [AnyHashable: Any] {
let jsonFilePath = Bundle.main.path(forResource: jsonFileName, ofType: withExtension)
let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonFilePath!))
let jsonDict = try! JSONSerialization.jsonObject(with: jsonData!, options: JSONSerialization.ReadingOptions.allowFragments)
return (jsonDict as? [AnyHashable: Any])!
}
}
| 39.864407 | 131 | 0.693878 |
f56f56c1157368502647503cd614cf736fbec92c | 57,968 | // This file contains parts of Apple's Combine that remain unimplemented in OpenCombine
// Please remove the corresponding piece from this file if you implement something,
// and complement this file as features are added in Apple's Combine
extension Publishers {
/// A publisher that receives and combines the latest elements from two publishers.
public struct CombineLatest<A, B> : Publisher where A : Publisher, B : Publisher, A.Failure == B.Failure {
/// The kind of values published by this publisher.
public typealias Output = (A.Output, B.Output)
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public init(_ a: A, _ b: B)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, B.Failure == S.Failure, S.Input == (A.Output, B.Output)
}
/// A publisher that receives and combines the latest elements from three publishers.
public struct CombineLatest3<A, B, C> : Publisher where A : Publisher, B : Publisher, C : Publisher, A.Failure == B.Failure, B.Failure == C.Failure {
/// The kind of values published by this publisher.
public typealias Output = (A.Output, B.Output, C.Output)
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public init(_ a: A, _ b: B, _ c: C)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, C.Failure == S.Failure, S.Input == (A.Output, B.Output, C.Output)
}
/// A publisher that receives and combines the latest elements from four publishers.
public struct CombineLatest4<A, B, C, D> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, A.Failure == B.Failure, B.Failure == C.Failure, C.Failure == D.Failure {
/// The kind of values published by this publisher.
public typealias Output = (A.Output, B.Output, C.Output, D.Output)
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public let d: D
public init(_ a: A, _ b: B, _ c: C, _ d: D)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, D.Failure == S.Failure, S.Input == (A.Output, B.Output, C.Output, D.Output)
}
}
extension Publisher {
/// Subscribes to an additional publisher and publishes a tuple upon receiving output from either publisher.
///
/// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer.
/// All upstream publishers need to finish for this publisher to finsh. If an upstream publisher never publishes a value, this publisher never finishes.
/// If any of the combined publishers terminates with a failure, this publisher also fails.
/// - Parameters:
/// - other: Another publisher to combine with this one.
/// - Returns: A publisher that receives and combines elements from this and another publisher.
public func combineLatest<P>(_ other: P) -> Publishers.CombineLatest<Self, P> where P : Publisher, Self.Failure == P.Failure
/// Subscribes to an additional publisher and invokes a closure upon receiving output from either publisher.
///
/// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer.
/// All upstream publishers need to finish for this publisher to finsh. If an upstream publisher never publishes a value, this publisher never finishes.
/// If any of the combined publishers terminates with a failure, this publisher also fails.
/// - Parameters:
/// - other: Another publisher to combine with this one.
/// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish.
/// - Returns: A publisher that receives and combines elements from this and another publisher.
public func combineLatest<P, T>(_ other: P, _ transform: @escaping (Self.Output, P.Output) -> T) -> Publishers.Map<Publishers.CombineLatest<Self, P>, T> where P : Publisher, Self.Failure == P.Failure
/// Subscribes to two additional publishers and publishes a tuple upon receiving output from any of the publishers.
///
/// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer.
/// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes.
/// If any of the combined publishers terminates with a failure, this publisher also fails.
/// - Parameters:
/// - publisher1: A second publisher to combine with this one.
/// - publisher2: A third publisher to combine with this one.
/// - Returns: A publisher that receives and combines elements from this publisher and two other publishers.
public func combineLatest<P, Q>(_ publisher1: P, _ publisher2: Q) -> Publishers.CombineLatest3<Self, P, Q> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure
/// Subscribes to two additional publishers and invokes a closure upon receiving output from any of the publishers.
///
/// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer.
/// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes.
/// If any of the combined publishers terminates with a failure, this publisher also fails.
/// - Parameters:
/// - publisher1: A second publisher to combine with this one.
/// - publisher2: A third publisher to combine with this one.
/// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish.
/// - Returns: A publisher that receives and combines elements from this publisher and two other publishers.
public func combineLatest<P, Q, T>(_ publisher1: P, _ publisher2: Q, _ transform: @escaping (Self.Output, P.Output, Q.Output) -> T) -> Publishers.Map<Publishers.CombineLatest3<Self, P, Q>, T> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure
/// Subscribes to three additional publishers and publishes a tuple upon receiving output from any of the publishers.
///
/// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer.
/// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes.
/// If any of the combined publishers terminates with a failure, this publisher also fails.
/// - Parameters:
/// - publisher1: A second publisher to combine with this one.
/// - publisher2: A third publisher to combine with this one.
/// - publisher3: A fourth publisher to combine with this one.
/// - Returns: A publisher that receives and combines elements from this publisher and three other publishers.
public func combineLatest<P, Q, R>(_ publisher1: P, _ publisher2: Q, _ publisher3: R) -> Publishers.CombineLatest4<Self, P, Q, R> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure
/// Subscribes to three additional publishers and invokes a closure upon receiving output from any of the publishers.
///
/// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer.
/// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes.
/// If any of the combined publishers terminates with a failure, this publisher also fails.
/// - Parameters:
/// - publisher1: A second publisher to combine with this one.
/// - publisher2: A third publisher to combine with this one.
/// - publisher3: A fourth publisher to combine with this one.
/// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish.
/// - Returns: A publisher that receives and combines elements from this publisher and three other publishers.
public func combineLatest<P, Q, R, T>(_ publisher1: P, _ publisher2: Q, _ publisher3: R, _ transform: @escaping (Self.Output, P.Output, Q.Output, R.Output) -> T) -> Publishers.Map<Publishers.CombineLatest4<Self, P, Q, R>, T> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure
}
extension Publishers {
/// A strategy for collecting received elements.
public enum TimeGroupingStrategy<Context> where Context : Scheduler {
/// A grouping that collects and periodically publishes items.
case byTime(Context, Context.SchedulerTimeType.Stride)
/// A grouping that collects and publishes items periodically or when a buffer reaches a maximum size.
case byTimeOrCount(Context, Context.SchedulerTimeType.Stride, Int)
}
/// A publisher that buffers and periodically publishes its items.
public struct CollectByTime<Upstream, Context> : Publisher where Upstream : Publisher, Context : Scheduler {
/// The kind of values published by this publisher.
public typealias Output = [Upstream.Output]
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = Upstream.Failure
/// The publisher that this publisher receives elements from.
public let upstream: Upstream
/// The strategy with which to collect and publish elements.
public let strategy: Publishers.TimeGroupingStrategy<Context>
/// `Scheduler` options to use for the strategy.
public let options: Context.SchedulerOptions?
public init(upstream: Upstream, strategy: Publishers.TimeGroupingStrategy<Context>, options: Context.SchedulerOptions?)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, Upstream.Failure == S.Failure, S.Input == [Upstream.Output]
}
}
extension Publisher {
/// Collects elements by a given time-grouping strategy, and emits a single array of
/// the collection.
///
/// Use `collect(_:options:)` to emit arrays of elements on a schedule specified by
/// a `Scheduler` and `Stride` that you provide. At the end of each scheduled
/// interval, the publisher sends an array that contains the items it collected.
/// If the upstream publisher finishes before filling the buffer, the publisher sends
/// an array that contains items it received. This may be fewer than the number of
/// elements specified in the requested `Stride`.
///
/// If the upstream publisher fails with an error, this publisher forwards the error
/// to the downstream receiver instead of sending its output.
///
/// The example above collects timestamps generated on a one-second `Timer` in groups
/// (`Stride`) of five.
///
/// let sub = Timer.publish(every: 1, on: .main, in: .default)
/// .autoconnect()
/// .collect(.byTime(RunLoop.main, .seconds(5)))
/// .sink { print("\($0)", terminator: "\n\n") }
///
/// // Prints: "[2020-01-24 00:54:46 +0000, 2020-01-24 00:54:47 +0000,
/// // 2020-01-24 00:54:48 +0000, 2020-01-24 00:54:49 +0000,
/// // 2020-01-24 00:54:50 +0000]"
///
/// > Note: When this publisher receives a request for `.max(n)` elements, it requests
/// `.max(count * n)` from the upstream publisher.
///
/// - Parameters:
/// - strategy: The timing group strategy used by the operator to collect and
/// publish elements.
/// - options: ``Scheduler`` options to use for the strategy.
/// - Returns: A publisher that collects elements by a given strategy, and emits
/// a single array of the collection.
public func collect<S>(_ strategy: Publishers.TimeGroupingStrategy<S>, options: S.SchedulerOptions? = nil) -> Publishers.CollectByTime<Self, S> where S : Scheduler
}
extension Publishers {
/// A publisher created by applying the merge function to two upstream publishers.
public struct Merge<A, B> : Publisher where A : Publisher, B : Publisher, A.Failure == B.Failure, A.Output == B.Output {
/// The kind of values published by this publisher.
public typealias Output = A.Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public init(_ a: A, _ b: B)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, B.Failure == S.Failure, B.Output == S.Input
public func merge<P>(with other: P) -> Publishers.Merge3<A, B, P> where P : Publisher, B.Failure == P.Failure, B.Output == P.Output
public func merge<Z, Y>(with z: Z, _ y: Y) -> Publishers.Merge4<A, B, Z, Y> where Z : Publisher, Y : Publisher, B.Failure == Z.Failure, B.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output
public func merge<Z, Y, X>(with z: Z, _ y: Y, _ x: X) -> Publishers.Merge5<A, B, Z, Y, X> where Z : Publisher, Y : Publisher, X : Publisher, B.Failure == Z.Failure, B.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output
public func merge<Z, Y, X, W>(with z: Z, _ y: Y, _ x: X, _ w: W) -> Publishers.Merge6<A, B, Z, Y, X, W> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, B.Failure == Z.Failure, B.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output
public func merge<Z, Y, X, W, V>(with z: Z, _ y: Y, _ x: X, _ w: W, _ v: V) -> Publishers.Merge7<A, B, Z, Y, X, W, V> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, V : Publisher, B.Failure == Z.Failure, B.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output, W.Failure == V.Failure, W.Output == V.Output
public func merge<Z, Y, X, W, V, U>(with z: Z, _ y: Y, _ x: X, _ w: W, _ v: V, _ u: U) -> Publishers.Merge8<A, B, Z, Y, X, W, V, U> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, V : Publisher, U : Publisher, B.Failure == Z.Failure, B.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output, W.Failure == V.Failure, W.Output == V.Output, V.Failure == U.Failure, V.Output == U.Output
}
/// A publisher created by applying the merge function to three upstream publishers.
public struct Merge3<A, B, C> : Publisher where A : Publisher, B : Publisher, C : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output {
/// The kind of values published by this publisher.
public typealias Output = A.Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public init(_ a: A, _ b: B, _ c: C)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, C.Failure == S.Failure, C.Output == S.Input
public func merge<P>(with other: P) -> Publishers.Merge4<A, B, C, P> where P : Publisher, C.Failure == P.Failure, C.Output == P.Output
public func merge<Z, Y>(with z: Z, _ y: Y) -> Publishers.Merge5<A, B, C, Z, Y> where Z : Publisher, Y : Publisher, C.Failure == Z.Failure, C.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output
public func merge<Z, Y, X>(with z: Z, _ y: Y, _ x: X) -> Publishers.Merge6<A, B, C, Z, Y, X> where Z : Publisher, Y : Publisher, X : Publisher, C.Failure == Z.Failure, C.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output
public func merge<Z, Y, X, W>(with z: Z, _ y: Y, _ x: X, _ w: W) -> Publishers.Merge7<A, B, C, Z, Y, X, W> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, C.Failure == Z.Failure, C.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output
public func merge<Z, Y, X, W, V>(with z: Z, _ y: Y, _ x: X, _ w: W, _ v: V) -> Publishers.Merge8<A, B, C, Z, Y, X, W, V> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, V : Publisher, C.Failure == Z.Failure, C.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output, W.Failure == V.Failure, W.Output == V.Output
}
/// A publisher created by applying the merge function to four upstream publishers.
public struct Merge4<A, B, C, D> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output {
/// The kind of values published by this publisher.
public typealias Output = A.Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public let d: D
public init(_ a: A, _ b: B, _ c: C, _ d: D)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, D.Failure == S.Failure, D.Output == S.Input
public func merge<P>(with other: P) -> Publishers.Merge5<A, B, C, D, P> where P : Publisher, D.Failure == P.Failure, D.Output == P.Output
public func merge<Z, Y>(with z: Z, _ y: Y) -> Publishers.Merge6<A, B, C, D, Z, Y> where Z : Publisher, Y : Publisher, D.Failure == Z.Failure, D.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output
public func merge<Z, Y, X>(with z: Z, _ y: Y, _ x: X) -> Publishers.Merge7<A, B, C, D, Z, Y, X> where Z : Publisher, Y : Publisher, X : Publisher, D.Failure == Z.Failure, D.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output
public func merge<Z, Y, X, W>(with z: Z, _ y: Y, _ x: X, _ w: W) -> Publishers.Merge8<A, B, C, D, Z, Y, X, W> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, D.Failure == Z.Failure, D.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output
}
/// A publisher created by applying the merge function to five upstream publishers.
public struct Merge5<A, B, C, D, E> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, E : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output {
/// The kind of values published by this publisher.
public typealias Output = A.Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public let d: D
public let e: E
public init(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, E.Failure == S.Failure, E.Output == S.Input
public func merge<P>(with other: P) -> Publishers.Merge6<A, B, C, D, E, P> where P : Publisher, E.Failure == P.Failure, E.Output == P.Output
public func merge<Z, Y>(with z: Z, _ y: Y) -> Publishers.Merge7<A, B, C, D, E, Z, Y> where Z : Publisher, Y : Publisher, E.Failure == Z.Failure, E.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output
public func merge<Z, Y, X>(with z: Z, _ y: Y, _ x: X) -> Publishers.Merge8<A, B, C, D, E, Z, Y, X> where Z : Publisher, Y : Publisher, X : Publisher, E.Failure == Z.Failure, E.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output
}
/// A publisher created by applying the merge function to six upstream publishers.
public struct Merge6<A, B, C, D, E, F> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output {
/// The kind of values published by this publisher.
public typealias Output = A.Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public let d: D
public let e: E
public let f: F
public init(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, F.Failure == S.Failure, F.Output == S.Input
public func merge<P>(with other: P) -> Publishers.Merge7<A, B, C, D, E, F, P> where P : Publisher, F.Failure == P.Failure, F.Output == P.Output
public func merge<Z, Y>(with z: Z, _ y: Y) -> Publishers.Merge8<A, B, C, D, E, F, Z, Y> where Z : Publisher, Y : Publisher, F.Failure == Z.Failure, F.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output
}
/// A publisher created by applying the merge function to seven upstream publishers.
public struct Merge7<A, B, C, D, E, F, G> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, G : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output, F.Failure == G.Failure, F.Output == G.Output {
/// The kind of values published by this publisher.
public typealias Output = A.Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public let d: D
public let e: E
public let f: F
public let g: G
public init(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, G.Failure == S.Failure, G.Output == S.Input
public func merge<P>(with other: P) -> Publishers.Merge8<A, B, C, D, E, F, G, P> where P : Publisher, G.Failure == P.Failure, G.Output == P.Output
}
/// A publisher created by applying the merge function to eight upstream publishers.
public struct Merge8<A, B, C, D, E, F, G, H> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, G : Publisher, H : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output, F.Failure == G.Failure, F.Output == G.Output, G.Failure == H.Failure, G.Output == H.Output {
/// The kind of values published by this publisher.
public typealias Output = A.Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public let d: D
public let e: E
public let f: F
public let g: G
public let h: H
public init(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, H.Failure == S.Failure, H.Output == S.Input
}
public struct MergeMany<Upstream> : Publisher where Upstream : Publisher {
/// The kind of values published by this publisher.
public typealias Output = Upstream.Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = Upstream.Failure
public let publishers: [Upstream]
public init(_ upstream: Upstream...)
public init<S>(_ upstream: S) where Upstream == S.Element, S : Sequence
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, Upstream.Failure == S.Failure, Upstream.Output == S.Input
public func merge(with other: Upstream) -> Publishers.MergeMany<Upstream>
}
}
extension Publisher {
/// Combines elements from this publisher with those from another publisher, delivering an interleaved sequence of elements.
///
/// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error.
/// - Parameter other: Another publisher.
/// - Returns: A publisher that emits an event when either upstream publisher emits an event.
public func merge<P>(with other: P) -> Publishers.Merge<Self, P> where P : Publisher, Self.Failure == P.Failure, Self.Output == P.Output
/// Combines elements from this publisher with those from two other publishers, delivering an interleaved sequence of elements.
///
/// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameters:
/// - b: A second publisher.
/// - c: A third publisher.
/// - Returns: A publisher that emits an event when any upstream publisher emits
/// an event.
public func merge<B, C>(with b: B, _ c: C) -> Publishers.Merge3<Self, B, C> where B : Publisher, C : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output
/// Combines elements from this publisher with those from three other publishers, delivering
/// an interleaved sequence of elements.
///
/// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameters:
/// - b: A second publisher.
/// - c: A third publisher.
/// - d: A fourth publisher.
/// - Returns: A publisher that emits an event when any upstream publisher emits an event.
public func merge<B, C, D>(with b: B, _ c: C, _ d: D) -> Publishers.Merge4<Self, B, C, D> where B : Publisher, C : Publisher, D : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output
/// Combines elements from this publisher with those from four other publishers, delivering an interleaved sequence of elements.
///
/// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameters:
/// - b: A second publisher.
/// - c: A third publisher.
/// - d: A fourth publisher.
/// - e: A fifth publisher.
/// - Returns: A publisher that emits an event when any upstream publisher emits an event.
public func merge<B, C, D, E>(with b: B, _ c: C, _ d: D, _ e: E) -> Publishers.Merge5<Self, B, C, D, E> where B : Publisher, C : Publisher, D : Publisher, E : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output
/// Combines elements from this publisher with those from five other publishers, delivering an interleaved sequence of elements.
///
/// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameters:
/// - b: A second publisher.
/// - c: A third publisher.
/// - d: A fourth publisher.
/// - e: A fifth publisher.
/// - f: A sixth publisher.
/// - Returns: A publisher that emits an event when any upstream publisher emits an event.
public func merge<B, C, D, E, F>(with b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> Publishers.Merge6<Self, B, C, D, E, F> where B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output
/// Combines elements from this publisher with those from six other publishers, delivering an interleaved sequence of elements.
///
/// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameters:
/// - b: A second publisher.
/// - c: A third publisher.
/// - d: A fourth publisher.
/// - e: A fifth publisher.
/// - f: A sixth publisher.
/// - g: A seventh publisher.
/// - Returns: A publisher that emits an event when any upstream publisher emits an event.
public func merge<B, C, D, E, F, G>(with b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> Publishers.Merge7<Self, B, C, D, E, F, G> where B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, G : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output, F.Failure == G.Failure, F.Output == G.Output
/// Combines elements from this publisher with those from seven other publishers, delivering an interleaved sequence of elements.
///
/// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameters:
/// - b: A second publisher.
/// - c: A third publisher.
/// - d: A fourth publisher.
/// - e: A fifth publisher.
/// - f: A sixth publisher.
/// - g: A seventh publisher.
/// - h: An eighth publisher.
/// - Returns: A publisher that emits an event when any upstream publisher emits an event.
public func merge<B, C, D, E, F, G, H>(with b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> Publishers.Merge8<Self, B, C, D, E, F, G, H> where B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, G : Publisher, H : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output, F.Failure == G.Failure, F.Output == G.Output, G.Failure == H.Failure, G.Output == H.Output
/// Combines elements from this publisher with those from another publisher of the same type, delivering an interleaved sequence of elements.
///
/// - Parameter other: Another publisher of this publisher's type.
/// - Returns: A publisher that emits an event when either upstream publisher emits
/// an event.
public func merge(with other: Self) -> Publishers.MergeMany<Self>
}
extension Publishers {
/// A publisher created by applying the zip function to two upstream publishers.
public struct Zip<A, B> : Publisher where A : Publisher, B : Publisher, A.Failure == B.Failure {
/// The kind of values published by this publisher.
public typealias Output = (A.Output, B.Output)
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public init(_ a: A, _ b: B)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, B.Failure == S.Failure, S.Input == (A.Output, B.Output)
}
/// A publisher created by applying the zip function to three upstream publishers.
public struct Zip3<A, B, C> : Publisher where A : Publisher, B : Publisher, C : Publisher, A.Failure == B.Failure, B.Failure == C.Failure {
/// The kind of values published by this publisher.
public typealias Output = (A.Output, B.Output, C.Output)
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public init(_ a: A, _ b: B, _ c: C)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, C.Failure == S.Failure, S.Input == (A.Output, B.Output, C.Output)
}
/// A publisher created by applying the zip function to four upstream publishers.
public struct Zip4<A, B, C, D> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, A.Failure == B.Failure, B.Failure == C.Failure, C.Failure == D.Failure {
/// The kind of values published by this publisher.
public typealias Output = (A.Output, B.Output, C.Output, D.Output)
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public let d: D
public init(_ a: A, _ b: B, _ c: C, _ d: D)
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, D.Failure == S.Failure, S.Input == (A.Output, B.Output, C.Output, D.Output)
}
}
extension Publisher {
/// Combine elements from another publisher and deliver pairs of elements as tuples.
///
/// The returned publisher waits until both publishers have emitted an event, then delivers the oldest unconsumed event from each publisher together as a tuple to the subscriber.
/// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits event `c`, the zip publisher emits the tuple `(a, c)`. It won’t emit a tuple with event `b` until `P2` emits another event.
/// If either upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same.
///
/// - Parameter other: Another publisher.
/// - Returns: A publisher that emits pairs of elements from the upstream publishers as tuples.
public func zip<P>(_ other: P) -> Publishers.Zip<Self, P> where P : Publisher, Self.Failure == P.Failure
/// Combine elements from another publisher and deliver a transformed output.
///
/// The returned publisher waits until both publishers have emitted an event, then delivers the oldest unconsumed event from each publisher together as a tuple to the subscriber.
/// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits event `c`, the zip publisher emits the tuple `(a, c)`. It won’t emit a tuple with event `b` until `P2` emits another event.
/// If either upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same.
///
/// - Parameter other: Another publisher.
/// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish.
/// - Returns: A publisher that emits pairs of elements from the upstream publishers as tuples.
public func zip<P, T>(_ other: P, _ transform: @escaping (Self.Output, P.Output) -> T) -> Publishers.Map<Publishers.Zip<Self, P>, T> where P : Publisher, Self.Failure == P.Failure
/// Combine elements from two other publishers and deliver groups of elements as tuples.
///
/// The returned publisher waits until all three publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber.
/// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the event `e`, the zip publisher emits the tuple `(a, c, e)`. It won’t emit a tuple with elements `b` or `d` until `P3` emits another event.
/// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same.
///
/// - Parameters:
/// - publisher1: A second publisher.
/// - publisher2: A third publisher.
/// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples.
public func zip<P, Q>(_ publisher1: P, _ publisher2: Q) -> Publishers.Zip3<Self, P, Q> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure
/// Combine elements from two other publishers and deliver a transformed output.
///
/// The returned publisher waits until all three publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber.
/// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the event `e`, the zip publisher emits the tuple `(a, c, e)`. It won’t emit a tuple with elements `b` or `d` until `P3` emits another event.
/// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same.
///
/// - Parameters:
/// - publisher1: A second publisher.
/// - publisher2: A third publisher.
/// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish.
/// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples.
public func zip<P, Q, T>(_ publisher1: P, _ publisher2: Q, _ transform: @escaping (Self.Output, P.Output, Q.Output) -> T) -> Publishers.Map<Publishers.Zip3<Self, P, Q>, T> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure
/// Combine elements from three other publishers and deliver groups of elements as tuples.
///
/// The returned publisher waits until all four publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber.
/// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the elements `e` and `f`, and publisher `P4` emits the event `g`, the zip publisher emits the tuple `(a, c, e, g)`. It won’t emit a tuple with elements `b`, `d`, or `f` until `P4` emits another event.
/// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same.
///
/// - Parameters:
/// - publisher1: A second publisher.
/// - publisher2: A third publisher.
/// - publisher3: A fourth publisher.
/// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples.
public func zip<P, Q, R>(_ publisher1: P, _ publisher2: Q, _ publisher3: R) -> Publishers.Zip4<Self, P, Q, R> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure
/// Combine elements from three other publishers and deliver a transformed output.
///
/// The returned publisher waits until all four publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber.
/// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the elements `e` and `f`, and publisher `P4` emits the event `g`, the zip publisher emits the tuple `(a, c, e, g)`. It won’t emit a tuple with elements `b`, `d`, or `f` until `P4` emits another event.
/// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same.
///
/// - Parameters:
/// - publisher1: A second publisher.
/// - publisher2: A third publisher.
/// - publisher3: A fourth publisher.
/// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish.
/// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples.
public func zip<P, Q, R, T>(_ publisher1: P, _ publisher2: Q, _ publisher3: R, _ transform: @escaping (Self.Output, P.Output, Q.Output, R.Output) -> T) -> Publishers.Map<Publishers.Zip4<Self, P, Q, R>, T> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure
}
extension Publishers.CombineLatest : Equatable where A : Equatable, B : Equatable {
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A combineLatest publisher to compare for equality.
/// - rhs: Another combineLatest publisher to compare for equality.
/// - Returns: `true` if the corresponding upstream publishers of each combineLatest publisher are equal, `false` otherwise.
public static func == (lhs: Publishers.CombineLatest<A, B>, rhs: Publishers.CombineLatest<A, B>) -> Bool
}
extension Publishers.CombineLatest3 : Equatable where A : Equatable, B : Equatable, C : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Publishers.CombineLatest3<A, B, C>, rhs: Publishers.CombineLatest3<A, B, C>) -> Bool
}
extension Publishers.CombineLatest4 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Publishers.CombineLatest4<A, B, C, D>, rhs: Publishers.CombineLatest4<A, B, C, D>) -> Bool
}
extension Publishers.Merge : Equatable where A : Equatable, B : Equatable {
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A merging publisher to compare for equality.
/// - rhs: Another merging publisher to compare for equality..
/// - Returns: `true` if the two merging - rhs: Another merging publisher to compare for equality.
public static func == (lhs: Publishers.Merge<A, B>, rhs: Publishers.Merge<A, B>) -> Bool
}
extension Publishers.Merge3 : Equatable where A : Equatable, B : Equatable, C : Equatable {
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A merging publisher to compare for equality.
/// - rhs: Another merging publisher to compare for equality.
/// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise.
public static func == (lhs: Publishers.Merge3<A, B, C>, rhs: Publishers.Merge3<A, B, C>) -> Bool
}
extension Publishers.Merge4 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable {
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A merging publisher to compare for equality.
/// - rhs: Another merging publisher to compare for equality.
/// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise.
public static func == (lhs: Publishers.Merge4<A, B, C, D>, rhs: Publishers.Merge4<A, B, C, D>) -> Bool
}
extension Publishers.Merge5 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable, E : Equatable {
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A merging publisher to compare for equality.
/// - rhs: Another merging publisher to compare for equality.
/// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise.
public static func == (lhs: Publishers.Merge5<A, B, C, D, E>, rhs: Publishers.Merge5<A, B, C, D, E>) -> Bool
}
extension Publishers.Merge6 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable, E : Equatable, F : Equatable {
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A merging publisher to compare for equality.
/// - rhs: Another merging publisher to compare for equality.
/// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise.
public static func == (lhs: Publishers.Merge6<A, B, C, D, E, F>, rhs: Publishers.Merge6<A, B, C, D, E, F>) -> Bool
}
extension Publishers.Merge7 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable, E : Equatable, F : Equatable, G : Equatable {
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A merging publisher to compare for equality.
/// - rhs: Another merging publisher to compare for equality.
/// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise.
public static func == (lhs: Publishers.Merge7<A, B, C, D, E, F, G>, rhs: Publishers.Merge7<A, B, C, D, E, F, G>) -> Bool
}
extension Publishers.Merge8 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable, E : Equatable, F : Equatable, G : Equatable, H : Equatable {
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A merging publisher to compare for equality.
/// - rhs: Another merging publisher to compare for equality.
/// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise.
public static func == (lhs: Publishers.Merge8<A, B, C, D, E, F, G, H>, rhs: Publishers.Merge8<A, B, C, D, E, F, G, H>) -> Bool
}
extension Publishers.MergeMany : Equatable where Upstream : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Publishers.MergeMany<Upstream>, rhs: Publishers.MergeMany<Upstream>) -> Bool
}
extension Publishers.Zip : Equatable where A : Equatable, B : Equatable {
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A zip publisher to compare for equality.
/// - rhs: Another zip publisher to compare for equality.
/// - Returns: `true` if the corresponding upstream publishers of each zip publisher are equal, `false` otherwise.
public static func == (lhs: Publishers.Zip<A, B>, rhs: Publishers.Zip<A, B>) -> Bool
}
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A zip publisher to compare for equality.
/// - rhs: Another zip publisher to compare for equality.
/// - Returns: `true` if the corresponding upstream publishers of each zip publisher are equal, `false` otherwise.
extension Publishers.Zip3 : Equatable where A : Equatable, B : Equatable, C : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Publishers.Zip3<A, B, C>, rhs: Publishers.Zip3<A, B, C>) -> Bool
}
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A zip publisher to compare for equality.
/// - rhs: Another zip publisher to compare for equality.
/// - Returns: `true` if the corresponding upstream publishers of each zip publisher are equal, `false` otherwise.
extension Publishers.Zip4 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Publishers.Zip4<A, B, C, D>, rhs: Publishers.Zip4<A, B, C, D>) -> Bool
}
| 59.454359 | 587 | 0.651377 |
ac4700aed239450a4e62e09d046da7ea153d6e7e | 7,710 | //
// ImageSliderController.swift
// News_Feed
//
// Created by clines329 on 11/10/19.
// Copyright © 2019 clines329. All rights reserved.
//
import UIKit
class ImageSliderController: UIViewController,UIScrollViewDelegate {
@IBOutlet weak var pageController: UIPageControl!
@IBOutlet weak var nextImageBtn: UIButton!
@IBOutlet weak var skipBtn: UIButton!
@IBOutlet weak var scrollView: UIScrollView!{
didSet {
scrollView.delegate = self
}
}
var imageSlides:[IntroImageSlider] = [];
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.alwaysBounceHorizontal = false
self.scrollView.alwaysBounceVertical = false
self.scrollView.scrollsToTop = false
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
imageSlides = createSlides()
setupSlideScrollView(slides: imageSlides)
self.scrollView.bounces = false
self.scrollView.bouncesZoom = false
pageController.numberOfPages = imageSlides.count
pageController.currentPage = 0
view.bringSubviewToFront(pageController)
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.navigationBar.isHidden = true
}
func createSlides() -> [IntroImageSlider] {
let slide1:IntroImageSlider = Bundle.main.loadNibNamed("IntroImageSlider", owner: self, options: nil)?.first as! IntroImageSlider
slide1.sliderImage.image = UIImage(named: "ic_rocket")
slide1.textLabel.text = "New Version"
slide1.descriptionLabel.text = "Fast so we can take you to our space"
slide1.backgroundColor = UIColor.hexStringToUIColor(hex: "2C4154")
let slide2:IntroImageSlider = Bundle.main.loadNibNamed("IntroImageSlider", owner: self, options: nil)?.first as! IntroImageSlider
slide2.sliderImage.image = UIImage(named: "ic_magnifying_glass")
slide2.textLabel.text = "Search Globally"
slide2.descriptionLabel.text = "Find new friends and contacts"
slide2.backgroundColor = UIColor.hexStringToUIColor(hex: "FCB741")
let slide3:IntroImageSlider = Bundle.main.loadNibNamed("IntroImageSlider", owner: self, options: nil)?.first as! IntroImageSlider
slide3.sliderImage.image = UIImage(named: "ic_paper_plane")
slide3.textLabel.text = "New Features"
slide3.descriptionLabel.text = "Send & Recieve all kind of messages"
slide3.backgroundColor = UIColor.hexStringToUIColor(hex: "2385C2")
let slide4:IntroImageSlider = Bundle.main.loadNibNamed("IntroImageSlider", owner: self, options: nil)?.first as! IntroImageSlider
slide4.sliderImage.image = UIImage(named: "ic_chat_violet")
slide4.textLabel.text = "Stay Sync"
slide4.descriptionLabel.text = "Keep you conversation going from all devices"
slide4.backgroundColor = UIColor.hexStringToUIColor(hex: "8E43AC")
return [slide1, slide2, slide3, slide4]
}
func setupSlideScrollView(slides : [IntroImageSlider]) {
scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
scrollView.contentSize = CGSize(width: view.frame.width * CGFloat(slides.count), height: view.frame.height)
scrollView.isPagingEnabled = true
for i in 0 ..< slides.count {
slides[i].frame = CGRect(x: view.frame.width * CGFloat(i), y: 0, width: view.frame.width, height: view.frame.height)
scrollView.addSubview(slides[i])
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageIndex = round(scrollView.contentOffset.x/view.frame.width)
pageController.currentPage = Int(pageIndex)
if pageController.currentPage == 3 {
self.skipBtn.isHidden = true
self.nextImageBtn.setImage(UIImage(named: "verified"), for: .normal)
}else {
self.skipBtn.isHidden = false
self.nextImageBtn.setImage(UIImage(named: "arrow-pointing"), for: .normal)
self.nextImageBtn.setTitle(nil, for: .normal)
}
}
func scrollToNextSlide(){
let cellSize = CGSize(width: self.view.frame.width, height: self.view.frame.height)
let contentOffset = scrollView.contentOffset;
scrollView.scrollRectToVisible(CGRect(x: contentOffset.x + cellSize.width, y: contentOffset.y, width: cellSize.width, height: cellSize.height), animated: true);
}
func scrollView(_ scrollView: UIScrollView, didScrollToPercentageOffset percentageHorizontalOffset: CGFloat) {
if(pageController.currentPage == 0) {
//Change background color to toRed: 103/255, fromGreen: 58/255, fromBlue: 183/255, fromAlpha: 1
//Change pageControl selected color to toRed: 103/255, toGreen: 58/255, toBlue: 183/255, fromAlpha: 0.2
//Change pageControl unselected color to toRed: 255/255, toGreen: 255/255, toBlue: 255/255, fromAlpha: 1
let pageUnselectedColor: UIColor = fade(fromRed: 255/255, fromGreen: 255/255, fromBlue: 255/255, fromAlpha: 1, toRed: 103/255, toGreen: 58/255, toBlue: 183/255, toAlpha: 1, withPercentage: percentageHorizontalOffset * 3)
pageController.pageIndicatorTintColor = pageUnselectedColor
let bgColor: UIColor = fade(fromRed: 103/255, fromGreen: 58/255, fromBlue: 183/255, fromAlpha: 1, toRed: 255/255, toGreen: 255/255, toBlue: 255/255, toAlpha: 1, withPercentage: percentageHorizontalOffset * 3)
imageSlides[pageController.currentPage].backgroundColor = bgColor
let pageSelectedColor: UIColor = fade(fromRed: 81/255, fromGreen: 36/255, fromBlue: 152/255, fromAlpha: 1, toRed: 103/255, toGreen: 58/255, toBlue: 183/255, toAlpha: 1, withPercentage: percentageHorizontalOffset * 3)
pageController.currentPageIndicatorTintColor = pageSelectedColor
}
}
func fade(fromRed: CGFloat,fromGreen: CGFloat,fromBlue: CGFloat,fromAlpha: CGFloat,toRed: CGFloat,
toGreen: CGFloat,toBlue: CGFloat,toAlpha: CGFloat,withPercentage percentage: CGFloat) -> UIColor {
let red: CGFloat = (toRed - fromRed) * percentage + fromRed
let green: CGFloat = (toGreen - fromGreen) * percentage + fromGreen
let blue: CGFloat = (toBlue - fromBlue) * percentage + fromBlue
let alpha: CGFloat = (toAlpha - fromAlpha) * percentage + fromAlpha
// return the fade colour
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
@IBAction func Next(_ sender: Any) {
if pageController.currentPage == 3 {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myVC = storyboard.instantiateViewController(withIdentifier: "News_FeedVC") as! UINavigationController
self.present(myVC, animated: true, completion: nil)
}
else {
self.scrollToNextSlide()
}
}
@IBAction func Skip(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myVC = storyboard.instantiateViewController(withIdentifier: "News_FeedVC") as! UINavigationController
self.present(myVC, animated: true, completion: nil)
}
}
| 40.578947 | 232 | 0.647211 |
567ff054a0a3881945e7aa62f8c50333a78afdcf | 2,032 | //
// AutoInsettingMultiScrollViewController.swift
// Tabman-UITests
//
// Created by Merrick Sapsford on 29/01/2018.
// Copyright © 2018 UI At Six. All rights reserved.
//
import UIKit
import PureLayout
class AutoInsettingMultiScrollViewController: TestViewController {
let tableView = UITableView()
let secondTableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
secondTableView.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
view.addSubview(tableView)
tableView.autoPinEdge(toSuperviewEdge: .top)
tableView.autoPinEdge(toSuperviewEdge: .leading)
tableView.autoPinEdge(toSuperviewEdge: .trailing)
tableView.autoSetDimension(.height, toSize: 300)
view.addSubview(secondTableView)
secondTableView.autoPinEdge(toSuperviewEdge: .leading)
secondTableView.autoPinEdge(toSuperviewEdge: .trailing)
secondTableView.autoPinEdge(.top, to: .bottom, of: tableView)
secondTableView.autoPinEdge(toSuperviewEdge: .bottom)
tableView.dataSource = self
secondTableView.dataSource = self
}
}
extension AutoInsettingMultiScrollViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "Cell"
var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: identifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
}
cell.textLabel?.text = "Row \(indexPath.row)"
cell.backgroundColor = .clear
return cell
}
}
| 31.75 | 100 | 0.677657 |
466f9728ff41a470d187d17637db20bb0ff49b6a | 956 | import Foundation
#if os(iOS) || os(tvOS) || os(macOS)
public struct ImageWrapper: Codable {
public let image: CacheImage
public enum CodingKeys: String, CodingKey {
case image
}
public init(image: CacheImage) {
self.image = image
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let data = try container.decode(Data.self, forKey: CodingKeys.image)
guard let image = CacheImage(data: data) else {
throw StorageError.decodingFailed
}
self.image = image
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
guard let data = image.cache_toData() else {
throw StorageError.encodingFailed
}
try container.encode(data, forKey: CodingKeys.image)
}
}
#endif
| 27.314286 | 76 | 0.620293 |
6a456efcc393b198f65006ff073b6931eca97dff | 1,434 | //
// AnalysisResultViewController.swift
// AloServiceModel
//
// Created by Aloisio Formento Junior on 14/01/21.
//
import UIKit
import Vision
class AnalysisResultViewController: UIViewController {
@IBOutlet weak var uiResultImageView: UIImageView!
@IBOutlet weak var uiResulLabel: UILabel!
@IBOutlet weak var uiConfidenceLabel: UILabel!
private var results: [VNClassificationObservation]
private var imageToLoad: UIImage
init(image: UIImage, results: [VNClassificationObservation]) {
self.imageToLoad = image
self.results = results
super.init(nibName: "AnalysisResultViewController", bundle: Bundle(for: AnalysisResultViewController.self))
//super.init(nibName: "AnalysisResultViewController", bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupResults()
}
//MARK: - Methods
private func setupResults() {
uiResultImageView.image = imageToLoad
if let firstResult = results.first {
uiResulLabel.text = "Este é o numero: \(firstResult.identifier)"
uiConfidenceLabel.text = "\(Int(firstResult.confidence * 100))% de confiança"
} else {
navigationController?.popToRootViewController(animated: true)
}
}
}
| 28.68 | 115 | 0.665969 |
e84171b530e9108483eee2dd0dea177563a66a13 | 1,737 | // Created by eric_horacek on 9/1/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
/// A singleton that enables consumers to control how bar installers' internal implementations
/// behave across the entire app, without needing to update every place that uses it.
///
/// Can additionally be provided when initializing a bar installer to customize the behavior of
/// that specific instance.
public struct BarInstallerConfiguration {
// MARK: Lifecycle
public init(
applyBars: ((_ container: BarContainer, _ bars: [BarModeling], _ animated: Bool) -> Void)? = nil)
{
self.applyBars = applyBars
}
// MARK: Public
/// The default configuration instance used if none is provided when initializing a bar installer.
///
/// Set this to a new instance to override the default configuration.
public static var shared = BarInstallerConfiguration()
/// A closure that's invoked whenever new bar models are set on a `BarInstaller` following its
/// initial configuration to customize _when_ those same bars are applied to the underlying
/// `BarContainer`.
///
/// For example, if the bar installer is actively participating in a shared element transition,
/// this property can be used to defer bar updates until the transition is over to ensure that the
/// shared bar elements remain constant over the course of the transition.
///
/// Defaults to `nil`, resulting in any new bars being immediately applied to the underlying
/// `BarContainer`.
///
/// Not calling `setBars` on the given `BarContainer` with the provided bars will result in
/// skipped bar model updates.
public var applyBars: ((_ container: BarContainer, _ bars: [BarModeling], _ animated: Bool) -> Void)?
}
| 41.357143 | 103 | 0.729994 |
fcf6c0a2a54f46b6ba8d6294faff319fe2569cbe | 437 | //
// RouteSegment.swift
// AugmentedReality
//
// Created by Bibinur on 11/9/19.
// Copyright © 2019 Bibinur. All rights reserved.
//
import CoreLocation
struct RouteSegment {
var startLatitude: CLLocationDegrees
var startLongitude: CLLocationDegrees
var startAltitude: CLLocationDegrees
var endLatitude: CLLocationDegrees
var endLongitude: CLLocationDegrees
var endAltitude: CLLocationDegrees
}
| 20.809524 | 50 | 0.73913 |
0195d095bcbb26da29188e291d45117d2258de00 | 710 | //
// OnboardingViewController.swift
// AwkDate
//
// Created by Lambda_School_Loaner_34 on 5/7/19.
// Copyright © 2019 JS. All rights reserved.
//
import UIKit
class OnboardingViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 22.903226 | 106 | 0.671831 |
f8d8e2c86644e769caf2aa190d553aad854552d4 | 1,566 | //
// danmuModel.swift
// zhnbilibili
//
// Created by zhn on 16/12/17.
// Copyright © 2016年 zhn. All rights reserved.
//
import UIKit
import SwiftyJSON
class danmuModel {
/// 弹幕的显示时间
var danmuShowingTime: Float = 0
/// 弹幕显示的内容
var danmuText = ""
/// 弹幕的显示 1-> 滚动弹幕 5->顶端弹幕 4->底部弹幕
var danmuShowIngType: Int = 0
/// 弹幕颜色的10进制
var danmuColor: Int = 0
/// 弹幕xml转modal
class func modelArray(dict: [AnyHashable : Any]) -> [danmuModel] {
let resultJson = JSON(dict)
guard let danmuArray = resultJson["i"]["d"].array else {return []}
var danmuModelArray = [danmuModel]()
for danmuDict in danmuArray {
// 1.先解析出数据
let danmuDictObject = danmuDict.dictionaryObject
guard let danmuItemString = danmuDictObject?["p"] as? String else {return []}
let danmuDetailArray = danmuItemString.components(separatedBy: ",")
// 2.赋值数据
guard let text = danmuDictObject?["text"] as? String else {return []}
guard let showingTime = Float(danmuDetailArray[0]) else {return []}
guard let showIngType = Int(danmuDetailArray[1]) else {return []}
guard let color = Int(danmuDetailArray[3]) else {return []}
let model = danmuModel()
model.danmuText = text
model.danmuShowingTime = showingTime
model.danmuShowIngType = showIngType
model.danmuColor = color
danmuModelArray.append(model)
}
return danmuModelArray
}
}
| 32.625 | 89 | 0.60281 |
e58446157d21bc77f0388692daaf62419df65220 | 294 | //
// DivAttributeParser.swift
// Pods
//
// Created by Bartek Tułodziecki on 03/03/2017.
//
//
import Foundation
public struct DivAttributeParser: AttributeValueParser {
public func parsed(attributes: [NSAttributedString.Key : Any]) -> [TagAttribute] {
return []
}
}
| 17.294118 | 86 | 0.670068 |
38de4eca836ca0bd30578be1b39f1390c2e96886 | 1,255 | //
// CacheableObject.swift
// UniversalDownloader
//
// Created by Umair Bhatti on 25/05/2019.
// Copyright © 2019 MindValley. All rights reserved.
//
import Foundation
class CacheableObject: NSObject, NSCoding {
//Vars
let object: Cacheable?
init(object: Cacheable) {
self.object = object
}
//Create respective object from the type
required init?(coder decoder: NSCoder) {
guard let rawData = decoder.decodeObject(forKey: "rawData") as? Data,
let namespace = Bundle(for: CacheableObject.self).infoDictionary!["CFBundleExecutable"] as? String,
let type = decoder.decodeObject(forKey: "type") as? String else {
object = nil
return
}
object = (NSClassFromString("\(namespace).\(type)") as? Cacheable.Type)?.init(rawData: rawData)
}
//Encode both object and its type
func encode(with coder: NSCoder) {
guard let object = object else {
return
}
coder.encode(object.rawData, forKey: "rawData")
coder.encode("\(type(of: object))", forKey: "type")
}
}
| 24.607843 | 111 | 0.556972 |
f93961f3ea3878eae21e028464bcc2e9c2645f58 | 1,934 | //
// DeletionView.swift
// FocusEntityPlacer
//
// Created by baochong on 2021/11/13.
//
import SwiftUI
struct DeletionView : View {
@EnvironmentObject var sceneManager : SceneManagerViewModel
@EnvironmentObject var modelDeletionManager : ModelDeletionManagerViewModel
var body: some View {
HStack {
Spacer()
DeletionButton(systemIconName: "xmark.circle.fill") {
print("Cancel Deletion button pressed")
modelDeletionManager.entitySelectedForDeletion = nil
}
Spacer()
DeletionButton(systemIconName: "trash.circle.fill") {
print("Confirmed Deletion button pressed")
guard let anchor = self.modelDeletionManager.entitySelectedForDeletion?.anchor else {return}
let anchoringIdentifier = anchor.anchorIdentifier
if let index = self.sceneManager.anchorEntities.firstIndex(where: {$0.anchorIdentifier == anchoringIdentifier}) {
print("Deleting anchorEntity with id \(String(describing: anchoringIdentifier))")
self.sceneManager.anchorEntities.remove(at: index)
}
anchor.removeFromParent()
self.modelDeletionManager.entitySelectedForDeletion = nil
}
Spacer()
}.padding(.bottom, 30)
}
}
struct DeletionButton: View {
let systemIconName: String
let action : () -> Void
var body : some View {
Button(action: {
self.action()
}) {
Image(systemName: systemIconName)
.font(.system(size:50, weight: .light, design: .default))
.foregroundColor(systemIconName == "trash.circle.fill" ? .red : .white)
.buttonStyle(PlainButtonStyle())
}
.frame(width: 85, height: 85)
}
}
| 34.535714 | 129 | 0.586867 |
5b0a62a1b8138186fbe6ca53da7c3c6b959e8250 | 538 | //
// UIViewController+fromNib.swift
// EnvironmentSwitcher
//
// Created by Stas on 11/06/2019.
// Copyright © 2019 AERO. All rights reserved.
//
import UIKit
/// Wapper for load view controller from xib file
public extension UIViewController {
/// Load view controller from xib file
/// - Returns: view controller object from Nib in current Bundle
static func fromNib() -> Self {
let bundle = Bundle(for: self)
return self.init(nibName: String(describing: self.self), bundle: bundle)
}
}
| 24.454545 | 80 | 0.672862 |
644cb8b90b127c3229c3ac32fa3afc6e87098d56 | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:274e79363b782fdd59b80b724f0960074886e85b50b007aad00768eacb50c58d
size 2427
| 32.25 | 75 | 0.883721 |
4a46e3b505f49106151a1e739a5f3bc6565aa666 | 9,699 | //
// ECCBManager.swift
// ECsoreApp
//
// Created by Pradeep on 7/23/17.
// Copyright © 2017 Pradeep. All rights reserved.
//
import UIKit
let ecommerceAppDataBase = "ecommerceAppDataBase"
let menuItemKVOKey = "menuItems"
let kEncryptionKey = "seekrit"
class ECCBManager: NSObject {
let cbManager:CBLManager = CBLManager.sharedInstance()
var dbNames:[String]?
var database:CBLDatabase?
var loggedInUser:String?
// This is the remote URL of the Sync Gateway (public Port)
let kRemoteSyncUrl = "https://cdb.citypost.us:4984"
let kDbName:String = "ecommerceapp" // CHANGE THIS TO THE NAME OF DATABASE THAT YOU HAVE CREATED ON YOUR SYNC GATEWAY VIA ADMIN PORT
let kPublicDoc:String = "public"
let kPrivateDoc:String = "private"
var docsEnumerator:CBLQueryEnumerator? {
didSet {
}
}
var dbName:String? {
didSet {
getAllDatabases()
}
}
var liveQuery:CBLLiveQuery?
static let sharedInstance = ECCBManager()
private override init() {
print("ECCBManager Initialized")
}
// Creates a DB in local store
func createDBWithName(_ name:String) {
do {
// 1: Set Database Options
let options = CBLDatabaseOptions()
options.storageType = kCBLSQLiteStorage
options.create = true
if kEncryptionEnabled {
options.encryptionKey = kEncryptionKey
}
// 2: Create a DB if it does not exist else return handle to existing one
self.database = try cbManager.openDatabaseNamed(name.lowercased(), with: options)
print("Database \(name) was created succesfully at path \(CBLManager.defaultDirectory())")
}
catch {
print("Database \(name) creation failed:\(error.localizedDescription)")
}
}
func getAllDatabases() {
self.dbNames = cbManager.allDatabaseNames
}
func getAllDocumentsForDataBase(name : String) -> CBLDatabase {
// 1. Get handle to DB with specified name
do {
if dbName != nil{
self.database = try cbManager.existingDatabaseNamed(name)
}
}catch {
}
return self.database!
}
// Deletes a Document in database
func deleteDocAtIndex(_ index:Int) {
do {
// 1: Get the document associated with the row
let doc = self.docAtIndex(index)
print("doc to remove \(String(describing: doc?.userProperties))")
// 2: Delete the document
try doc?.delete()
}
catch {
}
}
func deleteDoc(doc : CBLDocument) {
do {
// Delete the document
try doc.delete()
} catch {
}
}
// Helper function to get document at specified index
func docAtIndex(_ index:Int) -> CBLDocument? {
// 1. Get the CBLQueryRow object at specified index
let queryRow = self.docsEnumerator?.row(at: UInt(index))
// 2: Get the document associated with the row
let doc = queryRow?.document
return doc
}
// Creates a DB in local store if it does not exist
func openDatabaseForUser(dbName:String, user:String, password:String)-> Bool {
do {
// 1: Set Database Options
let options = CBLDatabaseOptions()
options.storageType = kCBLSQLiteStorage
options.create = true
// 2: Create a DB for logged in user if it does not exist else return handle to existing one
self.database = try cbManager.openDatabaseNamed(dbName.lowercased(), with: options)
// 3. Start replication with remote Sync Gateway
startDatabaseReplicationForUser(user, password: password)
return true
}
catch {
print("Failed to create database named \(user)")
}
return false
}
// Start Replication/ Synching with remote Sync Gateway
func startDatabaseReplicationForUser(_ user:String, password:String) {
// 1. Create Authenticator to be sent with every request.
let auth = CBLAuthenticator.basicAuthenticator(withName: user, password: password)
// 2. Create a Pull replication to start pulling from remote source
self.startPullReplicationWithAuthenticator(auth)
// 3. Create a Push replication to start pushing to remote source
self.startPushReplicationWithAuthenticator(auth)
self.startPullReplication();
// 4: Start Observing push/pull changes to/from remote database
self.addRemoteDatabaseChangesObserverAndStartObserving()
}
func startPullReplication() {
// 1: Create a Pull replication to start pulling from remote source
let pullRepl = database?.createPullReplication(URL(string: kDbName, relativeTo: URL.init(string: kRemoteSyncUrl))!)
// 2. Set Authenticator for pull replication
// pullRepl?.authenticator = auth
// Continuously look for changes
pullRepl?.continuous = true
// Optionally, Set channels from which to pull
// pullRepl?.channels = [...]
// 4. Start the pull replicator
pullRepl?.start()
}
func startPullReplicationWithAuthenticator(_ auth:CBLAuthenticatorProtocol?) {
// 1: Create a Pull replication to start pulling from remote source
let pullRepl = database?.createPullReplication(URL(string: kDbName, relativeTo: URL.init(string: kRemoteSyncUrl))!)
// 2. Set Authenticator for pull replication
pullRepl?.authenticator = auth
// Continuously look for changes
pullRepl?.continuous = true
// Optionally, Set channels from which to pull
// pullRepl?.channels = [...]
// 4. Start the pull replicator
pullRepl?.start()
}
func startPushReplicationWithAuthenticator(_ auth:CBLAuthenticatorProtocol?) {
// 1: Create a push replication to start pushing to remote source
let pushRepl = database?.createPushReplication(URL(string: kDbName, relativeTo: URL.init(string:kRemoteSyncUrl))!)
// 2. Set Authenticator for push replication
pushRepl?.authenticator = auth
// Continuously push changes
pushRepl?.continuous = true
// 3. Start the push replicator
pushRepl?.start()
}
func addRemoteDatabaseChangesObserverAndStartObserving() {
// 1. iOS Specific. Add observer to the NOtification Center to observe replicator changes
NotificationCenter.default.addObserver(forName: NSNotification.Name.cblReplicationChange, object: nil, queue: nil) {_ in
// Handle changes to the replicator status - Such as displaying progress
// indicator when status is .running
}
}
func removeRemoteDatabaseObserverAndStopObserving(controller:AnyObject) {
// 1. iOS Specific. Remove observer from Replication state changes
NotificationCenter.default.removeObserver(controller, name: NSNotification.Name.cblReplicationChange, object: nil)
}
func addLiveQueryObserverAndStartObserving() {
guard let liveQuery = liveQuery else {
return
}
// 1. iOS Specific. Add observer to the live Query object
liveQuery.addObserver(self, forKeyPath: "rows", options: NSKeyValueObservingOptions.new, context: nil)
// 2. Start observing changes
liveQuery.start()
}
func removeLiveQueryObserverAndStopObserving() {
guard let liveQuery = liveQuery else {
return
}
// 1. iOS Specific. Remove observer from the live Query object
liveQuery.removeObserver(self, forKeyPath: "rows")
// 2. Stop observing changes
liveQuery.stop()
}
func updateInputParameters(properties:[String : Any]?) {
// Create a manager
// let manager = CBLManager.sharedInstance()
let database: CBLDatabase
do {
// Create or open the database named app
database = try cbManager.databaseNamed("ecommerceapp".lowercased())
} catch {
print("Database creation or opening failed")
return
}
// Create a new document
let document: CBLDocument = database.createDocument()
do {
// Save the document to the database
try document.putProperties(properties!)
} catch {
print("Can't save document in database")
return
}
// Log the document ID (generated by the database)
// and properties
print("Document ID :: \(document.documentID)")
print("Learning \(document.property(forKey: "sdk")!)")
// // Create replicators to push & pull changes to & from Sync Gateway
// let url = URL(string: "http://localhost:4984/hello")!
// let push = database.createPushReplication(url)
// let pull = database.createPullReplication(url)
// push.continuous = true
// pull.continuous = true
//
// // Start replicators
// push.start()
// pull.start()
}
}
| 33.329897 | 136 | 0.600268 |
755eb53b7ea42560e4b4d807cb56dba43a6a8125 | 692 | import Vapor
extension Session: FlashProviding {
private static let flashSessionKey = "_flash"
public var flashes: [Flash] {
get {
guard
let data = data[Self.flashSessionKey]?.data(using: .utf8),
let flashes = try? JSONDecoder().decode([Flash].self, from: data)
else {
return []
}
return flashes
}
set {
if let flashData = try? JSONEncoder().encode(newValue) {
data[Self.flashSessionKey] = String(data: flashData, encoding: .utf8)
} else {
data[Self.flashSessionKey] = nil
}
}
}
}
| 26.615385 | 85 | 0.504335 |
1c669d0a366c5ffd455ac5d42a03403b08758526 | 2,396 | //
// AppDelegate.swift
// XTPlayer
//
// Created by victor on 17/3/22.
// Copyright © 2017年 victor. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame:UIScreen.main.bounds)
let listC = XTMusciListController()
let navC = UINavigationController.init(rootViewController: listC)
window?.rootViewController = navC
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 42.035088 | 285 | 0.732053 |
50e6cc4d6438509b0a2d6b8acbf8089a9de8bc01 | 724 | //
// Xcore
// Copyright © 2017 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
/// A helper struct to store composed data source sections and data sources.
struct DataSourceIndex<DataSourceType> {
private typealias GlobalSection = Int
private typealias DataSource = (dataSource: DataSourceType, localSection: Int)
private var index = [GlobalSection: DataSource]()
subscript(_ section: Int) -> (dataSource: DataSourceType, localSection: Int) {
get { index[section]! }
set { index[section] = newValue }
}
}
public struct DataSource<DataSourceType> {
public let dataSource: DataSourceType
public let globalSection: Int
public let localSection: Int
}
| 27.846154 | 82 | 0.71547 |
ccfb7b7aef10395c2b5475d7f75ec9c1b6982e35 | 5,369 | import ABI45_0_0ExpoModulesTestCore
@testable import ABI45_0_0ExpoModulesCore
class FunctionSpec: ExpoSpec {
override func spec() {
let appContext = AppContext()
let functionName = "test function name"
func testFunctionReturning<T: Equatable>(value returnValue: T) {
waitUntil { done in
mockModuleHolder(appContext) {
function(functionName) {
return returnValue
}
}
.call(function: functionName, args: []) { value, _ in
expect(value).notTo(beNil())
expect(value).to(beAKindOf(T.self))
expect(value as? T).to(equal(returnValue))
done()
}
}
}
it("is called") {
waitUntil { done in
mockModuleHolder(appContext) {
function(functionName) {
done()
}
}
.call(function: functionName, args: [])
}
}
it("returns bool values") {
testFunctionReturning(value: true)
testFunctionReturning(value: false)
testFunctionReturning(value: [true, false])
}
it("returns int values") {
testFunctionReturning(value: 1_234)
testFunctionReturning(value: [2, 1, 3, 7])
}
it("returns double values") {
testFunctionReturning(value: 3.14)
testFunctionReturning(value: [0, 1.1, 2.2])
}
it("returns string values") {
testFunctionReturning(value: "a string")
testFunctionReturning(value: ["expo", "modules", "core"])
}
it("is called with nil value") {
let str: String? = nil
mockModuleHolder(appContext) {
function(functionName) { (a: String?) in
expect(a == nil) == true
}
}
.callSync(function: functionName, args: [str as Any])
}
it("is called with an array of arrays") {
let array: [[String]] = [["expo"]]
mockModuleHolder(appContext) {
function(functionName) { (a: [[String]]) in
expect(a.first!.first) == array.first!.first
}
}
.callSync(function: functionName, args: [array])
}
describe("converting dicts to records") {
struct TestRecord: Record {
@Field var property: String = "expo"
@Field var optionalProperty: Int?
@Field("propertyWithCustomKey") var customKeyProperty: String = "expo"
}
let dict = [
"property": "Hello",
"propertyWithCustomKey": "Expo!"
]
it("converts to simple record when passed as an argument") {
waitUntil { done in
mockModuleHolder(appContext) {
function(functionName) { (a: TestRecord) in
return a.property
}
}
.call(function: functionName, args: [dict]) { value, _ in
expect(value).notTo(beNil())
expect(value).to(beAKindOf(String.self))
expect(value).to(be(dict["property"]))
done()
}
}
}
it("converts to record with custom key") {
waitUntil { done in
mockModuleHolder(appContext) {
function(functionName) { (a: TestRecord) in
return a.customKeyProperty
}
}
.call(function: functionName, args: [dict]) { value, _ in
expect(value).notTo(beNil())
expect(value).to(beAKindOf(String.self))
expect(value).to(be(dict["propertyWithCustomKey"]))
done()
}
}
}
it("returns the record back") {
waitUntil { done in
mockModuleHolder(appContext) {
function(functionName) { (a: TestRecord) in
return a.toDictionary()
}
}
.call(function: functionName, args: [dict]) { value, _ in
expect(value).notTo(beNil())
expect(value).to(beAKindOf(Record.Dict.self))
let valueAsDict = value as! Record.Dict
expect(valueAsDict["property"] as? String).to(equal(dict["property"]))
expect(valueAsDict["propertyWithCustomKey"] as? String).to(equal(dict["propertyWithCustomKey"]))
done()
}
}
}
}
it("throws when called with more arguments than expected") {
waitUntil { done in
mockModuleHolder(appContext) {
function(functionName) { (_: Int) in
return "something"
}
}
// Function expects one argument, let's give it more.
.call(function: functionName, args: [1, 2]) { _, error in
expect(error).notTo(beNil())
expect(error).to(beAKindOf(FunctionCallException.self))
expect((error as! Exception).isCausedBy(InvalidArgsNumberException.self)) == true
done()
}
}
}
it("throws when called with arguments of incompatible types") {
waitUntil { done in
mockModuleHolder(appContext) {
function(functionName) { (_: String) in
return "something"
}
}
// Function expects a string, let's give it a number.
.call(function: functionName, args: [1]) { value, error in
expect(error).notTo(beNil())
expect(error).to(beAKindOf(FunctionCallException.self))
expect((error as! Exception).isCausedBy(Conversions.CastingException<String>.self)) == true
done()
}
}
}
}
}
| 29.994413 | 108 | 0.562861 |
4baa5475e17d548b9fd5f88476a463c9508dfe1c | 4,177 | //
// GetENSTextRecordsCoordinator.swift
// AlphaWallet
//
// Created by Vladyslav Shepitko on 24.09.2021.
//
import Foundation
import CryptoSwift
import Result
import web3swift
import PromiseKit
enum ENSTextRecord: Equatable, Hashable {
/// A URL to an image used as an avatar or logo
case avatar
/// A description of the name
case description
/// A canonical display name for the ENS name; this MUST match the ENS name when its case is folded, and clients should ignore this value if it does not (e.g. "ricmoo.eth" could set this to "RicMoo.eth")
case display
/// An e-mail address
case email
/// A list of comma-separated keywords, ordered by most significant first; clients that interpresent this field may choose a threshold beyond which to ignore
case keywords
/// A physical mailing address
case mail
/// A notice regarding this name
case notice
/// A generic location (e.g. "Toronto, Canada")
case location
/// A phone number as an E.164 string
case phone
/// A website URL
case url
case custom(String)
var rawValue: String {
switch self {
case .avatar: return "avatar"
case .description: return "description"
case .display: return "display"
case .email: return "email"
case .keywords: return "keywords"
case .notice: return "notice"
case .location: return "location"
case .phone: return "phone"
case .url: return "url"
case .custom(let value): return value
case .mail: return "mail"
}
}
}
/// https://eips.ethereum.org/EIPS/eip-634
final class GetENSTextRecordsCoordinator {
private struct ENSLookupKey: Hashable {
let name: String
let server: RPCServer
let record: ENSTextRecord
}
private static var resultsCache = [ENSLookupKey: String]()
private (set) var server: RPCServer
private let ensReverseLookup: ENSReverseLookupCoordinator
init(server: RPCServer) {
self.server = server
ensReverseLookup = ENSReverseLookupCoordinator(server: server)
}
func getENSRecord(for address: AlphaWallet.Address, record: ENSTextRecord) -> Promise<String> {
firstly {
ensReverseLookup.getENSNameFromResolver(forAddress: address)
}.then { ens -> Promise<String> in
self.getENSRecord(for: ens, record: record)
}
}
func getENSRecord(for input: String, record: ENSTextRecord) -> Promise<String> {
guard !input.components(separatedBy: ".").isEmpty else {
return .init(error: AnyError(Web3Error(description: "\(input) is invalid ENS name")))
}
let addr = input.lowercased().nameHash
if let cachedResult = cachedResult(forNode: addr, record: record) {
return .value(cachedResult)
}
let function = GetENSTextRecord()
let server = self.server
return callSmartContract(withServer: server, contract: server.endRecordsContract, functionName: function.name, abiString: function.abi, parameters: [addr as AnyObject, record.rawValue as AnyObject]).then { result -> Promise<String> in
guard let record = result["0"] as? String else {
return .init(error: AnyError(Web3Error(description: "interface doesn't support for server: \(self.server)")))
}
if record.isEmpty {
return .init(error: AnyError(Web3Error(description: "ENS text record not found for record: \(record) for server: \(self.server)")))
} else {
return .value(record)
}
}.get { value in
self.cache(forNode: addr, record: record, result: value)
}
}
private func cachedResult(forNode node: String, record: ENSTextRecord) -> String? {
return GetENSTextRecordsCoordinator.resultsCache[ENSLookupKey(name: node, server: server, record: record)]
}
private func cache(forNode node: String, record: ENSTextRecord, result: String) {
GetENSTextRecordsCoordinator.resultsCache[ENSLookupKey(name: node, server: server, record: record)] = result
}
}
| 36.008621 | 242 | 0.656213 |
48e8a98c3872155608e1416db7f2431baaf90c3f | 473 | //
// SafariView.swift
// SwiftUIMoviesiOS
//
// Created by Nadheer on 23/08/2021.
//
import SafariServices
import SwiftUI
struct SafariView: UIViewControllerRepresentable {
let url: URL
func updateUIViewController(_ uiViewController: SFSafariViewController, context: Context) {}
func makeUIViewController(context: Context) -> SFSafariViewController {
let safariVC = SFSafariViewController(url: self.url)
return safariVC
}
}
| 21.5 | 96 | 0.718816 |
fb1ed19bc36ef740e9143e6589f4d8846284d2b0 | 1,663 | //
// AppleAuthenticationView.swift
// AuthServicesExample
//
// Created by Russell Gordon on 2021-04-04.
//
import SwiftUI
struct AppleAuthenticationView: View {
// Access to Apple authentication information
@EnvironmentObject var appleAuthenticationStore: AppleAuthentication
// Access to Google authentication information
@EnvironmentObject var googleAuthenticationDelegate: GoogleAuthenticationDelegate
var body: some View {
Group {
if appleAuthenticationStore.userStatus == .signedIn {
// When user is signed in to Apple, show information from that source
AppleUserInfoView()
} else if appleAuthenticationStore.userStatus == .indeterminate {
VStack {
Spacer()
ProgressView("Checking authentication status…")
Spacer()
}
} else {
if !googleAuthenticationDelegate.signedIn {
WelcomeMessageView()
.padding(10)
AppleSignInView()
}
}
}
.onAppear {
// Automatically sign in the user when the user opens the main page and they have already authenticated
appleAuthenticationStore.restoreSignIn()
}
}
}
struct AppleAuthenticationView_Previews: PreviewProvider {
static var previews: some View {
AppleAuthenticationView()
}
}
| 26.396825 | 115 | 0.541792 |
2f927cf20342f436981e139a46f4903239f78c94 | 2,291 | //
// QKMRZScanResult.swift
// QKMRZScanner
//
// Created by Matej Dorcak on 16/10/2018.
//
import Foundation
import QKMRZParser
public class QKMRZScanResult {
public let documentImage: UIImage
public let rotateDocumentImage: UIImage?
public let nfcDocumentImage: UIImage?
public let documentType: String
public let countryCode: String
public let surnames: String
public let givenNames: String
public let documentNumber: String
public let nationality: String
public let birthDate: Date?
public let sex: String?
public let expiryDate: Date?
public let personalNumber: String
public let personalNumber2: String?
public lazy fileprivate(set) var faceImage: UIImage? = {
guard let documentImage = CIImage(image: documentImage) else {
return nil
}
let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: CIContext.shared, options: [CIDetectorAccuracy: CIDetectorAccuracyLow])!
guard let face = faceDetector.features(in: documentImage).first else {
return nil
}
let increasedFaceBounds = face.bounds.insetBy(dx: -30, dy: -85).offsetBy(dx: 0, dy: 50)
let faceImage = documentImage.cropped(to: increasedFaceBounds)
guard let cgImage = CIContext.shared.createCGImage(faceImage, from: faceImage.extent) else {
return nil
}
return UIImage(cgImage: cgImage)
}()
init(mrzResult: QKMRZResult,
documentImage image: UIImage,
rotateDocumentImage: UIImage? = nil,
nfcDocumentImage: UIImage? = nil) {
self.rotateDocumentImage = rotateDocumentImage
self.nfcDocumentImage = nfcDocumentImage
documentImage = image
documentType = mrzResult.documentType
countryCode = mrzResult.countryCode
surnames = mrzResult.surnames
givenNames = mrzResult.givenNames
documentNumber = mrzResult.documentNumber
nationality = mrzResult.nationality
birthDate = mrzResult.birthDate
sex = mrzResult.sex
expiryDate = mrzResult.expiryDate
personalNumber = mrzResult.personalNumber
personalNumber2 = mrzResult.personalNumber2
}
}
| 33.202899 | 147 | 0.671323 |
2958ae058571dc0657dbd408aa127cad721f0c65 | 11,719 | //
// MainPlaygroundVewController.swift
// ModalInputTest
//
// Created by Colin Rofls on 2019-04-15.
// Copyright © 2019 Colin Rofls. All rights reserved.
//
import Cocoa
let OUTPUT_TOOLBAR_ITEM_TAG = 10;
let TOOLCHAIN_SELECT_TOOLBAR_ITEM_TAG = 13;
let RUN_TOOLBAR_ITEM_TAG = 14;
let ACTIVITY_SPINNER_TOOLBAR_ITEM_TAG = -1;
let SHARE_DISABLED_TOOLBAR_ITEM_TAG = 15;
let SHARE_TOOLBAR_ITEM_TAG = 16;
let SHARE_TOOLBAR_IDENTIFIER = NSToolbarItem.Identifier(rawValue: "share")
let SHARE_DISABLED_TOOLBAR_IDENTIFIER = NSToolbarItem.Identifier(rawValue: "shareDisabled")
let TOOLCHAIN_ITEM_TAG_OFFSET = 1000;
let SHARE_PREFERENCES_TAB_VIEW_INDEX = 1;
class MainPlaygroundViewController: NSSplitViewController {
var outputViewController: OutputViewController {
return splitViewItems[1].viewController as! OutputViewController
}
var editViewController: EditViewController {
return splitViewItems[0].viewController as! EditViewController
}
lazy var toggleOutputToolbarButton: NSButton = {
let toolbarItem = view.window?.toolbar?.items.first {
$0.tag == OUTPUT_TOOLBAR_ITEM_TAG
}
return toolbarItem!.view as! NSButton
}()
lazy var toolchainSelectButton: NSPopUpButton = {
let toolbarItem = view.window?.toolbar?.items.first {
$0.tag == TOOLCHAIN_SELECT_TOOLBAR_ITEM_TAG
}
return toolbarItem!.view as! NSPopUpButton
}()
lazy var runButton: NSButton = {
let toolbarItem = view.window?.toolbar?.items.first {
$0.tag == RUN_TOOLBAR_ITEM_TAG
}
return toolbarItem!.view as! NSButton
}()
lazy var activitySpinner: NSProgressIndicator = {
let toolbarItem = view.window?.toolbar?.items.first {
$0.tag == ACTIVITY_SPINNER_TOOLBAR_ITEM_TAG
}
return toolbarItem!.view as! NSProgressIndicator
}()
var buildForRelease = false;
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(toolchainsChanged(_:)),
name: AppDelegate.toolchainsChangedNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(githubTokenChanged(_:)),
name: EditorPreferences.githubTokenChangedNotification,
object: nil)
}
override func viewDidAppear() {
super.viewDidAppear()
let initSplitHeight = max(200, view.frame.height / 3).rounded(.down);
splitView.setPosition(view.frame.height - initSplitHeight, ofDividerAt: 0)
splitViewItems[1].isCollapsed = true
activitySpinner.isDisplayedWhenStopped = false
configureShareToolbarItem()
}
func configureShareToolbarItem() {
guard let toolbar = view.window?.toolbar else { return }
if let toRemove = toolbar.items.firstIndex(where: {
$0.tag == SHARE_TOOLBAR_ITEM_TAG
|| $0.tag == SHARE_DISABLED_TOOLBAR_ITEM_TAG
}) {
toolbar.removeItem(at: toRemove)
}
let shareDisabled = EditorPreferences.shared.githubToken.isEmpty
let identifier = shareDisabled ? SHARE_DISABLED_TOOLBAR_IDENTIFIER : SHARE_TOOLBAR_IDENTIFIER
toolbar.insertItem(withItemIdentifier: identifier, at: toolbar.items.count)
}
@objc func toolchainsChanged(_ notification: Notification) {
toolchainSelectButton.removeAllItems()
for toolchain in AppDelegate.shared.toolchains {
toolchainSelectButton.addItem(withTitle: toolchain.displayName)
}
if AppDelegate.shared.toolchains.count == 0 {
//TODO: only show this if rustup is actually missing?
showMissingRustupView()
}
toolchainSelectButton.isEnabled = AppDelegate.shared.toolchains.count > 1
toolchainSelectButton.isHidden = AppDelegate.shared.toolchains.count == 0
runButton.isEnabled = AppDelegate.shared.toolchains.count > 0
//TODO: show a warning if no toolchains are found
}
@objc func githubTokenChanged(_ notification: Notification) {
configureShareToolbarItem()
}
@IBAction func debugPrintEnvironment(_ sender: Any?) {
let env = ProcessInfo.processInfo.environment
if !outputViewIsVisible {
outputViewIsVisible = true
}
outputViewController.clearOutput()
outputViewController.printHeader("ENV")
for (key, value) in env {
outputViewController.printText(("\(key):\n\t\(value)\n"))
}
outputViewController.printHeader("Done")
}
@IBAction func toggleReleaseBuild(_ sender: NSMenuItem?) {
if sender?.state == .on {
sender?.state = .off;
} else {
sender?.state = .on;
}
buildForRelease = sender?.state == .on
}
func showMissingRustupView() {
let rustupView = MissingRustupInfoView(frame: self.view.bounds)
rustupView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(rustupView)
self.view.addConstraints([
NSLayoutConstraint(item: self.view, attribute: .leading, relatedBy: .equal, toItem: rustupView, attribute: .leading, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: self.view, attribute: .trailing, relatedBy: .equal, toItem: rustupView, attribute: .trailing, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: self.view, attribute: .top, relatedBy: .equal, toItem: rustupView, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: self.view, attribute: .bottom, relatedBy: .equal, toItem: rustupView, attribute: .bottom, multiplier: 1.0, constant: 0),
])
self.view.needsLayout = true
}
var outputViewIsVisible: Bool = false {
didSet {
let isVisible = outputViewIsVisible
toggleOutputToolbarButton.highlight(true)
NSAnimationContext.runAnimationGroup({ (context) in
context.allowsImplicitAnimation = true
context.duration = 0.25
self.splitViewItems[1].isCollapsed = !isVisible
self.splitView.layoutSubtreeIfNeeded()
}, completionHandler: {
let newState: NSControl.StateValue = isVisible ? .on : .off
self.toggleOutputToolbarButton.highlight(false)
self.toggleOutputToolbarButton.state = newState
if newState == .on {
AppDelegate.shared.toggleConsoleMenu.title = "Hide Console"
} else {
AppDelegate.shared.toggleConsoleMenu.title = "Show Console"
}
})
}
}
@IBAction func increaseFontSize(_ sender: Any?) {
EditorPreferences.shared.increaseFontSize()
}
@IBAction func decreaseFontSize(_ sender: Any?) {
EditorPreferences.shared.decreaseFontSize()
}
@IBAction func toggleOutputView(_ sender: NSButton?) {
outputViewIsVisible = !outputViewIsVisible
}
@IBAction func toolchainSelectAction(_ sender: NSToolbarItem) {
}
@IBAction func toggleConsoleAction(_ sender: NSMenuItem) {
outputViewIsVisible = !outputViewIsVisible
}
@IBAction func shareDisabledAction(_ sender: NSToolbarItem) {
let prefController = AppDelegate.shared.preferencesWindowController
guard let tabController = prefController.contentViewController as? NSTabViewController else { return }
tabController.selectedTabViewItemIndex = SHARE_PREFERENCES_TAB_VIEW_INDEX;
prefController.showWindow(nil)
}
@IBAction func createGist(_ sender: Any?) {
createGistAndReportErrors() { NSWorkspace.shared.open($0.toGistUrl()) }
}
@IBAction func sendToWebPlayground(_ sender: Any?) {
createGistAndReportErrors() { NSWorkspace.shared.open($0.toPlaygroundUrl()) }
}
func createGistAndReportErrors(completion: @escaping (GistIdentifier) -> ()) {
let text = AppDelegate.shared.core.getDocument()
GithubConnection(token: EditorPreferences.shared.githubToken) .createGist(withContent: text) { [weak self] (result) in
DispatchQueue.main.async {
switch result {
case .failure(let err):
self?.showGithubError(err)
case .success(let gistId):
completion(gistId)
}
}
}
}
func showGithubError(_ error: GithubError) {
guard let window = view.window else { return }
let alert = NSAlert(error: error)
alert.messageText = error.localizedDescription
alert.beginSheetModal(for: window)
}
@IBAction func buildAction(_ sender: Any?) {
build(andRun: false)
}
@IBAction func runAction(_ sender: Any?) {
build(andRun: true)
}
func build(andRun run: Bool) {
if !outputViewIsVisible {
outputViewIsVisible = true
}
outputViewController.clearOutput()
outputViewController.printInfo(text: "Compiling")
activitySpinner.startAnimation(self)
runButton.isEnabled = false
let task = generateTask()
let buildDir = AppDelegate.shared.defaultBuildDirectory
DispatchQueue.global(qos: .default).async {
let result = self.executeTask(task, inDirectory: buildDir)
DispatchQueue.main.async {
self.taskFinished(result, run: run)
}
}
}
func taskFinished(_ result: Result<CompilerResult, PlaygroundError>, run: Bool) {
activitySpinner.stopAnimation(self)
runButton.isEnabled = true
switch result {
case .failure(let badNews):
outputViewController.printInfo(text: "Error")
outputViewController.handleStdErr(text: badNews.message)
case .success(let goodNews):
displayTaskOutput(goodNews)
if goodNews.success && run, let executablePath = goodNews.executable {
runCommand(atPath: executablePath, handler: outputViewController)
}
}
outputViewController.printInfo(text: "Done")
}
func displayTaskOutput(_ result: CompilerResult) {
if result.stdErr.count > 0 {
outputViewController.printHeader("Standard Error")
outputViewController.printText(result.stdErr)
}
if result.stdOut.count > 0 {
outputViewController.printHeader("Standard Output")
outputViewController.printText(result.stdOut)
}
}
func executeTask(_ task: CompilerTask, inDirectory directory: URL) -> Result<CompilerResult, PlaygroundError> {
return RustPlayground.executeTask(inDirectory: directory, task: task, stderr: { [weak self] (line) in
DispatchQueue.main.async {
self?.outputViewController.handleRawStdErrLine(line)
}
})
}
func generateTask() -> CompilerTask {
let activeToolchainIdx = toolchainSelectButton.indexOfSelectedItem
let toolchain = AppDelegate.shared.toolchains[activeToolchainIdx].name
let code = AppDelegate.shared.core.getDocument()
let taskType: CompilerTask.TaskType = .run
return CompilerTask(toolchain: toolchain, code: code, type: taskType, backtrace: true, release: buildForRelease)
}
}
| 37.803226 | 161 | 0.644424 |
672f972903b0608a4983056d7592f85770736ee1 | 2,491 | //
// Copyright 2021 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 XCTest
import RiotSwiftUI
/// XCTestCase subclass to ease testing of `MockScreenState`.
/// Creates a test case for each screen state, launches the app,
/// goes to the correct screen and provides the state and key for each
/// invocation of the test.
@available(iOS 14.0, *)
class MockScreenTest: XCTestCase {
enum Constants {
static let defaultTimeout: TimeInterval = 3
}
class var screenType: MockScreenState.Type? {
return nil
}
class func createTest() -> MockScreenTest {
return MockScreenTest()
}
var screenState: MockScreenState?
var screenStateKey: String?
let app = XCUIApplication()
override class var defaultTestSuite: XCTestSuite {
let testSuite = XCTestSuite(name: NSStringFromClass(self))
guard let screenType = screenType else {
return testSuite
}
// Create a test case for each screen state
screenType.screenStates.enumerated().forEach { index, screenState in
let key = screenType.screenStateKeys[index]
addTestFor(screenState: screenState, screenStateKey: key, toTestSuite: testSuite)
}
return testSuite
}
class func addTestFor(screenState: MockScreenState, screenStateKey: String, toTestSuite testSuite: XCTestSuite) {
let test = createTest()
test.screenState = screenState
test.screenStateKey = screenStateKey
testSuite.addTest(test)
}
open override func setUpWithError() throws {
// For every test case launch the app and go to the relevant screen
continueAfterFailure = false
app.launch()
goToScreen()
}
private func goToScreen() {
guard let screenKey = screenStateKey else { fatalError("no screen") }
let link = app.buttons[screenKey]
link.tap()
}
}
| 32.776316 | 117 | 0.675231 |
ed2230b9fb5bd46287f4cff597c7f0796e6fd7b9 | 1,978 | //
// CharactersApiDataProvider.swift
// RickMorty
//
// Created by Alejandro Hernández Matías on 31/10/18.
// Copyright © 2018 Alejandro Hernández Matías. All rights reserved.
//
import UIKit
import Alamofire
import ObjectMapper
class CharactersApiDataProvider: NSObject {
static let sharedInstance = CharactersApiDataProvider()
override init() {
super.init()
}
// Using the Ids from the characters array in episode model, we create the request to the Api
func getCharactersById(currentIds:[Int], completion:@escaping ([RMCharacter]?,RickMortyError?)->Void){
let parametersIds:String = currentIds.compactMap({"\($0)"}).joined(separator: ",")
let serviceUrl = RickMortyDefines.ContentServices.baseUrl+RickMortyDefines.ContentServices.Characters.getCharacters+parametersIds
let sessionManager = Alamofire.SessionManager.default
sessionManager.request(serviceUrl, method: .get, parameters: nil, encoding: URLEncoding(destination: .queryString), headers: nil).responseString { (response) -> Void in
guard response.response != nil, response.result.isSuccess, let value = response.result.value else {
/* error handling */
let currentStatus = Reach().connectionStatus()
switch currentStatus {
case .unknown, .offline:
completion(nil,RickMortyError.noConnection)
return
case .online(.wwan), .online(.wiFi):
completion(nil,RickMortyError.unknown)
return
}
}
let rMCharacters = Mapper<RMCharacter>().mapArray(JSONString: value)
guard let currentCharacters = rMCharacters, currentCharacters.count > 0 else{
completion(nil,RickMortyError.noPageAllowed)
return
}
completion(currentCharacters,nil)
}
}
}
| 39.56 | 176 | 0.638524 |
46d7d1fc03cab1600eed73fe22c449e6929176d3 | 267 | //
// CC Value.swift
// MIDIKit • https://github.com/orchetect/MIDIKit
//
extension MIDI.Event.CC {
public typealias Value = MIDI.Event.ChanVoice7Bit32BitValue
public typealias ValueValidated = MIDI.Event.ChanVoice7Bit32BitValue.Validated
}
| 20.538462 | 82 | 0.715356 |
4ac85853479f8e1a0fafb61ec7d75109653dc9d8 | 3,508 | //
// BalloonConfiguration.swift
// Scratc
//
// Created by Andreas Verhoeven on 31/05/2021.
//
import UIKit
/// This defines the properties of a balloon
public struct BalloonConfiguration: Equatable {
/// the corner radius of the balloon
public var cornerRadius: CornerRadius = .fixed(8)
/// the stem configuration
public var stem: StemConfiguration = StemConfiguration()
public init(cornerRadius: CornerRadius = .fixed(8), stem: StemConfiguration = .init()) {
self.cornerRadius = cornerRadius
self.stem = stem
}
/// the edge at which we show the stem
public enum Edge {
/// the stem is at the top edge
case top
/// the stem is at the left edge
case left
/// the stem is at the bottom edge
case bottom
/// the stem is at the right edge
case right
}
/// how the corner radius is rendered
public enum CornerRadius: Equatable {
/// use a corner radius that results in an oval
case oval
/// use a fixed corner radius
case fixed(CGFloat)
/// no corner radius
public static let none: Self = .fixed(0)
}
/// how the stem is rendered
public struct StemConfiguration: Equatable {
/// how we smooth the stems corners
public enum CornerSmoothening: Equatable {
/// corner smoothing uses a custom smoothening ratio
/// of the width/height
case custom(widthRatio: CGFloat, heightRatio: CGFloat)
/// corner smoothing is disabled
public static let disabled: Self = .custom(widthRatio: 0, heightRatio: 0)
/// corner smoothing is enabled
public static let enabled: Self = .custom(widthRatio: 0.3, heightRatio: 0.25)
}
/// which edge to add the stem too
public var edge: Edge = .bottom
/// offset from the center
public var offset: CGFloat = 0
/// the size of the stem
public var size = CGSize(width: 40, height: 40)
/// how much we smoothen the corners
public var cornerSmoothening: CornerSmoothening = .enabled
/// how much we smoothen the tip of the stem
public var tipSmoothenWidth = CGFloat(4)
public init(edge: Edge = .bottom,
offset: CGFloat = 0,
size: CGSize = CGSize(width: 40, height: 40),
cornerSmoothening: CornerSmoothening = .enabled,
tipSmoothenWidth: CGFloat = 4) {
self.edge = edge
self.offset = offset
self.size = size
self.cornerSmoothening = cornerSmoothening
self.tipSmoothenWidth = tipSmoothenWidth
}
}
}
extension BalloonConfiguration {
/// gets the rect without the stem
public func rectWithoutStem(_ rect: CGRect) -> CGRect {
return rect.inset(by: insetsForStem(in: rect))
}
/// gets the insets for the stem
public func insetsForStem(in rect: CGRect) -> UIEdgeInsets {
let (stemSize, _) = stem.stemSizeAndCornerSmootheningSize(for: rect)
switch stem.edge {
case .top:
return UIEdgeInsets(top: stemSize.height, left: 0, bottom: 0, right: 0)
case .bottom:
return UIEdgeInsets(top: 0, left: 0, bottom: stemSize.height, right: 0)
case .left:
return UIEdgeInsets(top: 0, left: stemSize.width, bottom: 0, right: 0)
case .right:
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: stemSize.width)
}
}
/// gets the effective corner radius for a rectangle
public func effectiveCornerRadius(in rect: CGRect) -> CGFloat {
return cornerRadius.width(for: rectWithoutStem(rect))
}
/// gets the effective corner radius for a rectangle with the rectangle not taken the stem into account
public func effectiveCornerRadius(with rect: CGRect) -> CGFloat {
return cornerRadius.width(for: rect)
}
}
| 26.778626 | 104 | 0.703535 |
acd7eb59d341d38ad6801e0e0b536feec197743f | 3,256 | import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
// I think those there is no double between those two, and this is the exact threshold:
private let maxInt64ConvertibleDouble = Double(9223372036854775295 as Int64)
private let minInt64NonConvertibleDouble = Double(9223372036854775296 as Int64)
// Not sure about the exact threshold
private let minInt64ConvertibleDouble = Double(Int64.min)
private let maxInt64NonConvertibleDouble: Double = -9.223372036854777e+18
// Not sure about the exact threshold
private let maxInt32ConvertibleDouble: Double = 2147483647.999999
private let minInt32NonConvertibleDouble: Double = 2147483648
// Not sure about the exact threshold
private let minInt32ConvertibleDouble: Double = -2147483648.999999
private let maxInt32NonConvertibleDouble: Double = -2147483649
class NumericOverflowTests: GRDBTestCase {
func testHighInt64FromDoubleOverflows() {
XCTAssertEqual(Int64.fromDatabaseValue(maxInt64ConvertibleDouble.databaseValue)!, 9223372036854774784)
XCTAssertTrue(Int64.fromDatabaseValue((minInt64NonConvertibleDouble).databaseValue) == nil)
}
func testLowInt64FromDoubleOverflows() {
XCTAssertEqual(Int64.fromDatabaseValue(minInt64ConvertibleDouble.databaseValue)!, Int64.min)
XCTAssertTrue(Int64.fromDatabaseValue(maxInt64NonConvertibleDouble.databaseValue) == nil)
}
func testHighInt32FromDoubleOverflows() {
XCTAssertEqual(Int32.fromDatabaseValue(maxInt32ConvertibleDouble.databaseValue)!, Int32.max)
XCTAssertTrue(Int32.fromDatabaseValue(minInt32NonConvertibleDouble.databaseValue) == nil)
}
func testLowInt32FromDoubleOverflows() {
XCTAssertEqual(Int32.fromDatabaseValue(minInt32ConvertibleDouble.databaseValue)!, Int32.min)
XCTAssertTrue(Int32.fromDatabaseValue(maxInt32NonConvertibleDouble.databaseValue) == nil)
}
func testHighIntFromDoubleOverflows() {
if Int64(Int.max) == Int64.max {
// 64 bits Int
XCTAssertEqual(Int64(Int.fromDatabaseValue(maxInt64ConvertibleDouble.databaseValue)!), 9223372036854774784)
XCTAssertTrue(Int.fromDatabaseValue((minInt64NonConvertibleDouble).databaseValue) == nil)
} else {
// 32 bits Int
XCTAssertEqual(Int.max, Int(Int32.max))
XCTAssertEqual(Int.fromDatabaseValue(maxInt32ConvertibleDouble.databaseValue)!, Int.max)
XCTAssertTrue(Int.fromDatabaseValue(minInt32NonConvertibleDouble.databaseValue) == nil)
}
}
func testLowIntFromDoubleOverflows() {
if Int64(Int.max) == Int64.max {
// 64 bits Int
XCTAssertEqual(Int.fromDatabaseValue(minInt64ConvertibleDouble.databaseValue)!, Int.min)
XCTAssertTrue(Int.fromDatabaseValue(maxInt64NonConvertibleDouble.databaseValue) == nil)
} else {
// 32 bits Int
XCTAssertEqual(Int.max, Int(Int32.max))
XCTAssertEqual(Int.fromDatabaseValue(minInt32ConvertibleDouble.databaseValue)!, Int.min)
XCTAssertTrue(Int.fromDatabaseValue(maxInt32NonConvertibleDouble.databaseValue) == nil)
}
}
}
| 43.413333 | 119 | 0.743857 |
5bcb3fbae2d665343741e26372c97639ca09c68f | 478 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
enum S<T where h:S{
class a{let a=b=Swift.d func c
enum S<T where g:a
let g=c
class b
| 34.142857 | 78 | 0.740586 |
4aeece80336ff03333f60c3f7b2002e8a8070ec8 | 3,441 | //
// AnalyticsAppService.swift
// i2app
//
// Created by Arcus Team on 11/14/17.
/*
* Copyright 2019 Arcus Project
*
* 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 RxSwift
import Cornea
/**
*/
class AnalyticsAppService: ArcusApplicationServiceProtocol, ArcusPlaceCapability {
/**
*/
let disposeBag = DisposeBag()
/**
*/
required init(eventPublisher: ArcusApplicationServiceEventPublisher) {
observeApplicationEvents(eventPublisher)
}
func serviceDidFinishLaunching(_ event: ArcusApplicationServiceEvent) {
setUpApptentive()
setUpGlobalTags()
}
func serviceDidBecomeActive(_ event: ArcusApplicationServiceEvent) {
ArcusAnalytics.tag(named: AnalyticsTags.Background)
}
private func setUpGlobalTags() {
GlobalTagAttributes.getInstance().put(AnalyticsTags.PersonIdKey) { () -> AnyObject in
guard let value = RxCornea.shared.settings?.currentPerson?.modelId else {
return "" as AnyObject
}
return value as AnyObject
}
GlobalTagAttributes.getInstance().put(AnalyticsTags.PlaceIdKey) { () -> AnyObject in
guard let value = RxCornea.shared.settings?.currentPlace?.modelId else {
return "" as AnyObject
}
return value as AnyObject
}
// TODO: Add number of paired devices to each tag
GlobalTagAttributes.getInstance().put(AnalyticsTags.DeviceCount) { () -> AnyObject in
return "" as AnyObject
}
GlobalTagAttributes.getInstance().put(AnalyticsTags.Source) { () -> AnyObject in
return "IOS" as AnyObject
}
GlobalTagAttributes.getInstance().put(AnalyticsTags.Version) { () -> AnyObject in
guard let dictionary = Bundle.main.infoDictionary,
let appVersion = dictionary["CFBundleShortVersionString"] else {
return "" as AnyObject
}
return appVersion as AnyObject
}
GlobalTagAttributes.getInstance().put(AnalyticsTags.ServiceLevel) { () -> AnyObject in
guard let currentPlace = RxCornea.shared.settings?.currentPlace else {
return "" as AnyObject
}
if let serviceLevel = self.getPlaceServiceLevel(currentPlace) {
return serviceLevel.rawValue as AnyObject
} else {
return "UNKNOWN" as AnyObject
}
}
}
private func setUpApptentive() {
let apptentiveRouteBuilder = TagRouteBuilder.routeTagsMatchingAny(ApptentiveAnalyticsEndpoint())
_ = apptentiveRouteBuilder.whereNameEquals(AnalyticsTags.DashboardHistoryClick)
_ = apptentiveRouteBuilder.whereNameEquals(AnalyticsTags.Dashboard)
ArcusAnalytics.deleteAllRoutes()
ArcusAnalytics.addRoute(TagRouteBuilder.routeAllTagsTo(LogAnalyticsEndpoint()))
ArcusAnalytics.addRoute(TagRouteBuilder.routeAllTagsTo(FabricAnalyticsEndpoint()))
ArcusAnalytics.addRoute(TagRouteBuilder.routeAllTagsTo(CorneaAnalyticsEndpoint()))
ArcusAnalytics.addRoute(apptentiveRouteBuilder.build())
}
}
| 31.281818 | 100 | 0.722464 |
160ba390a8bb7b83750a94a7cad947b430e91382 | 4,395 | //
// AppDelegate.swift
// Twitter
//
// Created by user116136 on 2/8/16.
// Copyright © 2016 Hannah Werbel. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var storyboard = UIStoryboard(name: "Main", bundle: nil)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
/* Attempt at Tab Bar
let TweetsNavigationController = storyboard.instantiateViewControllerWithIdentifier("TweetsNavigationController")as! UINavigationController
TweetsNavigationController.tabBarItem.title = "Timeline"
TweetsNavigationController.tabBarItem.image = UIImage(named: "homeIcon.png")
let ProfileNavigationController = storyboard.instantiateViewControllerWithIdentifier("ProfileNavigationController")as! UINavigationController
let profilePageViewController = ProfileNavigationController.topViewController as! ProfileViewController
ProfileNavigationController.tabBarItem.title = "Me"
ProfileNavigationController.tabBarItem.image = UIImage(named: "profileIcon.png")
profilePageViewController.user = User.currentUser
let tabBarController = UITabBarController()
tabBarController.viewControllers = [TweetsNavigationController, ProfileNavigationController]
tabBarController.tabBar.tintColor = UIColor(red: 85/225.0, green: 172/225.0, blue: 238/225.0, alpha: 1.0)
*/
NSNotificationCenter.defaultCenter().addObserver(self, selector: "userDidLogout", name: userDidLogoutNotification, object: nil)
if User.currentUser != nil {
// Go to logged in Screen
print("current user detected: \(User.currentUser?.name)")
let vc = storyboard.instantiateViewControllerWithIdentifier("TweetsNavigationController")
window?.rootViewController = vc
window?.makeKeyAndVisible()
} else {
let vc = storyboard.instantiateInitialViewController()
window?.rootViewController = vc
}
return true
}
func userDidLogout() {
let vc = storyboard.instantiateInitialViewController() as UIViewController!
window?.rootViewController = vc
}
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:.
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
TwitterClient.sharedInstance.openUrl(url)
return true
}
}
| 49.382022 | 285 | 0.729238 |
fffb16cf1e0d1250fab2995e2a3b9046f61d4987 | 335 | //
// ReaderLastPage.swift
// PeasNovel
//
// Created by lieon on 2019/4/22.
// Copyright © 2019 NotBroken. All rights reserved.
//
import Foundation
class ReaderLastPageGuessBookResponse: BaseResponseArray<ReaderLastPageGuessBook> {}
class ReaderLastPageGuessBook: RecommendBook {
var locaAdTemConfig: LocalTempAdConfig?
}
| 20.9375 | 84 | 0.770149 |
feaf2d56b4be51899ed67584f2c45ccfadf93caa | 2,796 | //
// FunctionCollectionViewCell.swift
// 0610
//
// Created by Chris on 2019/6/17.
// Copyright © 2019 user. All rights reserved.
//
import UIKit
//import Kingfisher
import Alamofire
import AlamofireImage
class FunctionCollectionViewCell: UICollectionViewCell {
var imageStr: String? {
didSet {
if let imageStr = imageStr, let url = URL(string: imageStr) {
// let imageView = UIImageView(frame: frame)
// let placeholderImage = UIImage(named: "placeholder")!
// let filter = ScaledToSizeFilter(size: iconImageView.frame.size)
// let filter = AspectScaledToFillSizeWithRoundedCornersFilter(
// size: cellImageView.frame.size,
// radius: 20.0
// )
// iconImageView.af_setImage(
// withURL: url,
// placeholderImage: nil,
// filter: filter,
// imageTransition: .crossDissolve(0.2)
// )
iconImageView.kf.setImage(with: url, placeholder: UIImage(named: "image-placeholder-icon"), options: nil, progressBlock: nil, completionHandler: nil)
// let processor = DownsamplingImageProcessor(size: iconImageView.frame.size)
//
// iconImageView.kf.indicatorType = .activity
// iconImageView.kf.setImage(
// with: url,
// placeholder: nil,
// options: [
// .processor(processor),
// .scaleFactor(UIScreen.main.scale),
// .transition(.fade(1)),
// .cacheOriginalImage
// ])
// {
// result in
// switch result {
// case .success(let value):
// log.info("Task done for: \(value.source.url?.absoluteString ?? "")")
// case .failure(let error):
// log.error("Job failed: \(error.localizedDescription)")
// }
// }
} else {
iconImageView.image = UIImage(named: "image-placeholder-icon")
}
}
}
var titleStr: String? {
didSet {
if let titleStr = titleStr {
titleLabel.text = titleStr
}
}
}
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var contentBackgoundView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| 31.066667 | 165 | 0.490343 |
bf38eea167adf79685c59de72201bdbed7f02069 | 761 |
//
// User.swift
// POC
//
// Created by Chris Nevin on 08/03/2019.
// Copyright © 2019 Chris Nevin. All rights reserved.
//
import Foundation
import RealmSwift
struct User: Comparable, ModelType {
static func < (lhs: User, rhs: User) -> Bool {
return lhs.name < rhs.name
}
let id: String
let name: String
func asRealm() -> UserObject {
let o = UserObject()
o.id = id
o.name = name
return o
}
}
final class UserObject: Object, RealmType {
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
override public class func primaryKey() -> String? {
return #keyPath(id)
}
func asModel() -> User {
return User(id: id, name: name)
}
}
| 18.560976 | 56 | 0.580815 |
f7aa192c5d6d699c3c88628cf7af14db8d42f127 | 839 | /**
* 推送弹框
*/
import UIKit
class THJGPushMsgView: UIView {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var textView: UITextView!
var block: (()->Void)?
var bean: [AnyHashable: Any]! {
didSet {
titleLabel.text = (bean["title"] as? String) ?? ""
textView.text = (bean["content"] as? String) ?? ""
}
}
static func showPushView() -> THJGPushMsgView {
return Bundle.main.loadNibNamed("THJGPushMsgView", owner: self, options: nil)?.last as! THJGPushMsgView
}
}
extension THJGPushMsgView {
//取消事件监听
@IBAction func ignoreBtnDidClicked(_ sender: UIButton) {
removeFromSuperview()
}
//查看事件监听
@IBAction func checkBtnDidClicked(_ sender: UIButton) {
removeFromSuperview()
block?()
}
}
| 21.512821 | 111 | 0.592372 |
e27cb44021f15533d2059320555a6bc4e1ac1117 | 3,612 |
import UIKit
@IBDesignable
open class ProgressView: UIView {
private let trackView = UIView()
private lazy var trackViewWidthConstraint: NSLayoutConstraint = { NSLayoutConstraint(item: self.trackView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 0) }()
@IBInspectable
open var barColor: UIColor = .gray {
didSet {
self.layer.backgroundColor = barColor.cgColor
}
}
@IBInspectable
open var trackColor: UIColor = .green {
didSet {
trackView.layer.backgroundColor = trackColor.cgColor
}
}
@IBInspectable
open var isCornersRounded: Bool = true {
didSet {
if !isCornersRounded {
self.layer.cornerRadius = 0
trackView.layer.cornerRadius = 0
}
layoutSubviews()
}
}
@IBInspectable
open var maximumValue: Float = 100.0 {
didSet {
progress = { progress }()
}
}
@IBInspectable
open var minimumValue: Float = 0.0 {
didSet {
progress = { progress }()
}
}
@IBInspectable
open private(set) var progress: Float = 0 {
didSet {
if progress > maximumValue {
progress = maximumValue
} else if progress < minimumValue {
progress = minimumValue
}
layoutSubviews()
}
}
@IBInspectable
open var barInset: CGFloat = 0 {
didSet {
layoutSubviews()
}
}
open var animationDuration: TimeInterval = 0.25
override init(frame: CGRect) {
super.init(frame: frame)
prepare()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
open func prepare() {
self.addSubview(trackView)
trackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
NSLayoutConstraint(item: trackView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .leftMargin, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: trackView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .topMargin, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: trackView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottomMargin, multiplier: 1.0, constant: 0),
trackViewWidthConstraint
])
self.layoutMargins = .zero
}
open func setProgress(_ value: Float, animated: Bool) {
self.progress = value
if animated {
UIView.animate(withDuration: animationDuration, animations: {
self.layoutIfNeeded()
})
}
}
override open func layoutSubviews() {
super.layoutSubviews()
let maxWidth: CGFloat = max(self.frame.width - barInset * 2, 0) // prevent from becoming negative
let calculatedWidth: CGFloat = maximumValue - minimumValue != 0 ? CGFloat((progress - minimumValue) / (maximumValue - minimumValue)) * maxWidth : 0
trackViewWidthConstraint.constant = calculatedWidth
if isCornersRounded {
self.layer.cornerRadius = self.frame.height / 2
trackView.layer.cornerRadius = trackView.frame.height / 2
}
self.layoutMargins = UIEdgeInsets(top: barInset, left: barInset, bottom: barInset, right: barInset)
}
}
| 30.352941 | 224 | 0.589978 |
fbb64a1649aebf28b1bc8658effea1900d3475b6 | 2,684 | import UIKit
import RxSwift
import RxDataSources
import RxComposableArchitecture
public class TodoListViewController: UIViewController {
private let _store: Store<TodoListState, TodoListAction>
private var _todos: [Todo] = []
private let _tableView = UITableView()
private var _dataSource: RxTableViewSectionedAnimatedDataSource<Section>!
private let _bag = DisposeBag()
override public func viewDidLoad() {
super.viewDidLoad()
title = "Todo List"
_setupTableViewLayout()
_tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
_dataSource = RxTableViewSectionedAnimatedDataSource(configureCell: { ds, tv, _, item in
let cell = tv.dequeueReusableCell(withIdentifier: "UITableViewCell")
?? UITableViewCell(style: .default, reuseIdentifier: "UITableViewCell")
let text: String
if item.done {
text = "✓ \(item.title)"
} else {
text = item.title
}
cell.textLabel?.text = text
return cell
}, titleForHeaderInSection: { ds, index in
return ds.sectionModels[index].header
}
)
_store.observableValue
.map { [Section(header: "", items: $0.todos)] }
.bind(to: _tableView.rx.items(dataSource: _dataSource))
.disposed(by: _bag)
_tableView.rx.setDelegate(self)
.disposed(by: _bag)
_tableView.rx
.modelSelected(Todo.self)
.map(TodoListAction.toggle)
.bind { [weak _store] in _store?.send($0) }
.disposed(by: _bag)
}
public init(store: Store<TodoListState, TodoListAction>) {
_store = store
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func _setupTableViewLayout() {
_tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(_tableView)
view.topAnchor.constraint(equalTo: _tableView.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: _tableView.bottomAnchor).isActive = true
view.leadingAnchor.constraint(equalTo: _tableView.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: _tableView.trailingAnchor).isActive = true
}
}
extension TodoListViewController {
struct Section {
var header: String
var items: [Todo]
}
}
extension TodoListViewController.Section: AnimatableSectionModelType {
var identity: String { header }
init(original:TodoListViewController.Section, items: [Todo]) {
self = original
self.items = items
}
}
extension Todo: IdentifiableType {
public var identity: String { title }
}
extension TodoListViewController: UITableViewDelegate {}
| 27.958333 | 92 | 0.713115 |
5d5d30763ade667e797d619b239ecdde35080fa4 | 1,936 | //
// ShakeView.swift
// GoCard
//
// Created by ナム Nam Nguyen on 3/16/17.
// Copyright © 2017 GoCard, Ltd. All rights reserved.
//
import UIKit
class ShakeView: UIView {
@IBOutlet var ovals: [UIImageView]?
@IBOutlet weak var locationIcon: UIImageView?
@IBOutlet weak var backButton: UIButton?
@IBOutlet weak var backgroundView: UIView?
@IBOutlet weak var title:UILabel!
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
private func setup() {
title.characterSpacing(1.27, lineHeight: 16, withFont: UIFont.boldRoboto(size:14))
backgroundView?.round(6)
backButton?.round()
backButton?.characterSpacing(1.5, lineHeight: 16, withFont: UIFont.boldRoboto(size:14))
UserDefaults.standard.set(true, forKey: "waitingForShaking")
ovals?.forEach{
$0.alpha = 0.0
}
UIView.animateKeyframes(withDuration: 1.0, delay: 0.25, options: [.repeat,.calculationModeLinear], animations: {
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.25, animations: {
self.ovals?[0].alpha = 1.0
})
UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.25, animations: {
self.ovals?[1].alpha = 1.0
})
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: {
self.ovals?[2].alpha = 1.0
})
UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: {
self.ovals?[3].alpha = 1.0
})
}, completion: { done in
self.ovals?.forEach{
$0.alpha = 0.0
}
})
}
@IBAction func didTouchBack(_ sender: Any) {
self.removeFromSuperview()
UserDefaults.standard.set(false, forKey: "waitingForShaking")
}
}
| 33.964912 | 120 | 0.600207 |
56a16b37aa7a3c980a1bea6e050cde0ca9784f3d | 2,832 | //
// PageTitleView.swift
// DouyuDemo
//
// Created by w on 2017/4/16.
// Copyright © 2017年 w. All rights reserved.
//
import UIKit
fileprivate let scrollLineH:CGFloat = 2
class PageTitleView: UIView {
//MARK: - 定义构造函数
fileprivate var titles : [String]
//MARK: - 懒加载属性
fileprivate lazy var titleLabel: [UILabel] = [UILabel]()
fileprivate lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
fileprivate lazy var scrollLine: UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
//自定义构造函数
init(frame: CGRect, titles: [String]) {
self.titles = titles
super.init(frame: frame)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:设置UI界面
extension PageTitleView {
fileprivate func setupUI() {
addSubview(scrollView)
scrollView.frame = bounds
//添加title对应的Label
setupTitleLbels()
setupBottomMenuAndScrollLine()
}
//添加TieleLabel
private func setupTitleLbels() {
let labelW: CGFloat = frame.width / (CGFloat)(titles.count)
let labelH: CGFloat = frame.height - scrollLineH
let labelY: CGFloat = 0
for (index, title) in titles.enumerated(){
let label = UILabel()
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = UIColor.darkGray
label.textAlignment = .center
let labelX: CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
scrollView.addSubview(label)
titleLabel.append(label)
}
}
//添加底线和滚动线
private func setupBottomMenuAndScrollLine(){
//底线
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray
let lineH:CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
//滚动线
guard let firstLabel = titleLabel.first else {
return
}
firstLabel.textColor = UIColor.orange
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - scrollLineH, width: firstLabel.frame.width, height: scrollLineH)
}
}
| 26.716981 | 146 | 0.592161 |
0a8fd9dca7ab4b064eea3a467b679ff50f6152bb | 7,257 | // This file is generated
import XCTest
#if canImport(MapboxMaps)
@testable import MapboxMaps
#else
@testable import MapboxMapsStyle
#endif
class SymbolLayerIntegrationTests: MapViewIntegrationTestCase {
internal func testBaseClass() throws {
// Do nothing
}
internal func testWaitForIdle() throws {
guard let style = style else {
XCTFail("There should be valid MapView and Style objects created by setUp.")
return
}
let successfullyAddedLayerExpectation = XCTestExpectation(description: "Successfully added SymbolLayer to Map")
successfullyAddedLayerExpectation.expectedFulfillmentCount = 1
let successfullyRetrievedLayerExpectation = XCTestExpectation(description: "Successfully retrieved SymbolLayer from Map")
successfullyRetrievedLayerExpectation.expectedFulfillmentCount = 1
style.styleURI = .streets
didFinishLoadingStyle = { _ in
var layer = SymbolLayer(id: "test-id")
layer.source = "some-source"
layer.sourceLayer = nil
layer.minZoom = 10.0
layer.maxZoom = 20.0
layer.layout?.visibility = .constant(.visible)
layer.layout?.iconAllowOverlap = Value<Bool>.testConstantValue()
layer.layout?.iconAnchor = Value<IconAnchor>.testConstantValue()
layer.layout?.iconIgnorePlacement = Value<Bool>.testConstantValue()
layer.layout?.iconImage = Value<ResolvedImage>.testConstantValue()
layer.layout?.iconKeepUpright = Value<Bool>.testConstantValue()
layer.layout?.iconOptional = Value<Bool>.testConstantValue()
layer.layout?.iconPadding = Value<Double>.testConstantValue()
layer.layout?.iconPitchAlignment = Value<IconPitchAlignment>.testConstantValue()
layer.layout?.iconRotate = Value<Double>.testConstantValue()
layer.layout?.iconRotationAlignment = Value<IconRotationAlignment>.testConstantValue()
layer.layout?.iconSize = Value<Double>.testConstantValue()
layer.layout?.iconTextFit = Value<IconTextFit>.testConstantValue()
layer.layout?.symbolAvoidEdges = Value<Bool>.testConstantValue()
layer.layout?.symbolPlacement = Value<SymbolPlacement>.testConstantValue()
layer.layout?.symbolSortKey = Value<Double>.testConstantValue()
layer.layout?.symbolSpacing = Value<Double>.testConstantValue()
layer.layout?.symbolZOrder = Value<SymbolZOrder>.testConstantValue()
layer.layout?.textAllowOverlap = Value<Bool>.testConstantValue()
layer.layout?.textAnchor = Value<TextAnchor>.testConstantValue()
layer.layout?.textField = Value<String>.testConstantValue()
layer.layout?.textFont = Value<[String]>.testConstantValue()
layer.layout?.textIgnorePlacement = Value<Bool>.testConstantValue()
layer.layout?.textJustify = Value<TextJustify>.testConstantValue()
layer.layout?.textKeepUpright = Value<Bool>.testConstantValue()
layer.layout?.textLetterSpacing = Value<Double>.testConstantValue()
layer.layout?.textLineHeight = Value<Double>.testConstantValue()
layer.layout?.textMaxAngle = Value<Double>.testConstantValue()
layer.layout?.textMaxWidth = Value<Double>.testConstantValue()
layer.layout?.textOptional = Value<Bool>.testConstantValue()
layer.layout?.textPadding = Value<Double>.testConstantValue()
layer.layout?.textPitchAlignment = Value<TextPitchAlignment>.testConstantValue()
layer.layout?.textRadialOffset = Value<Double>.testConstantValue()
layer.layout?.textRotate = Value<Double>.testConstantValue()
layer.layout?.textRotationAlignment = Value<TextRotationAlignment>.testConstantValue()
layer.layout?.textSize = Value<Double>.testConstantValue()
layer.layout?.textTransform = Value<TextTransform>.testConstantValue()
layer.layout?.textVariableAnchor = Value<[TextAnchor]>.testConstantValue()
layer.layout?.textWritingMode = Value<[TextWritingMode]>.testConstantValue()
layer.paint?.iconColor = Value<ColorRepresentable>.testConstantValue()
layer.paint?.iconColorTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.iconHaloBlur = Value<Double>.testConstantValue()
layer.paint?.iconHaloBlurTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.iconHaloColor = Value<ColorRepresentable>.testConstantValue()
layer.paint?.iconHaloColorTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.iconHaloWidth = Value<Double>.testConstantValue()
layer.paint?.iconHaloWidthTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.iconOpacity = Value<Double>.testConstantValue()
layer.paint?.iconOpacityTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.iconTranslateTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.iconTranslateAnchor = Value<IconTranslateAnchor>.testConstantValue()
layer.paint?.textColor = Value<ColorRepresentable>.testConstantValue()
layer.paint?.textColorTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.textHaloBlur = Value<Double>.testConstantValue()
layer.paint?.textHaloBlurTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.textHaloColor = Value<ColorRepresentable>.testConstantValue()
layer.paint?.textHaloColorTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.textHaloWidth = Value<Double>.testConstantValue()
layer.paint?.textHaloWidthTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.textOpacity = Value<Double>.testConstantValue()
layer.paint?.textOpacityTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.textTranslateTransition = StyleTransition(duration: 10.0, delay: 10.0)
layer.paint?.textTranslateAnchor = Value<TextTranslateAnchor>.testConstantValue()
// Add the layer
let addResult = style.addLayer(layer: layer)
switch (addResult) {
case .success(_):
successfullyAddedLayerExpectation.fulfill()
case .failure(let error):
XCTFail("Failed to add SymbolLayer because of error: \(error)")
}
// Retrieve the layer
let retrieveResult = style.getLayer(with: "test-id", type: SymbolLayer.self)
switch (retrieveResult) {
case .success(_):
successfullyRetrievedLayerExpectation.fulfill()
case .failure(let error):
XCTFail("Failed to retreive SymbolLayer because of error: \(error)")
}
}
wait(for: [successfullyAddedLayerExpectation, successfullyRetrievedLayerExpectation], timeout: 5.0)
}
}
// End of generated file | 57.141732 | 129 | 0.676313 |
ddc2d43e7a78fdc063d3af57d4c0e03f41338eba | 939 | //
// ImageUtil.swift
// ReadReceipt
//
// Created by mnrn on 2019/09/12.
// Copyright © 2019 mnrn. All rights reserved.
//
import UIKit
func resizeImage(_ imageSize: CGSize, image: UIImage) -> Data {
UIGraphicsBeginImageContext(imageSize)
image.draw(in: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
let resizedImage = newImage!.pngData()
UIGraphicsEndImageContext()
return resizedImage!
}
func base64EncodeImage(_ image: UIImage) -> String {
var imagedata = image.pngData()
// Resize the image if it exceeds the 2MB API limit
if imagedata?.count ?? 0 > 2_097_152 {
let oldSize: CGSize = image.size
let newSize: CGSize = CGSize(width: 800, height: oldSize.height / oldSize.width * 800)
imagedata = resizeImage(newSize, image: image)
}
return imagedata!.base64EncodedString(options: .endLineWithCarriageReturn)
}
| 29.34375 | 90 | 0.72737 |
1cc1c9e98165f93f0db975873ebea5b63ed5b992 | 29,636 | //
// WSConnection.swift
// SwiftHTTP
//
// Created by Sriram Panyam on 12/30/15.
// Copyright © 2015 Sriram Panyam. All rights reserved.
//
import SwiftIO
public typealias WSCallback = (message: WSMessage) -> Void
public protocol WSConnectionDelegate
{
/**
* Connection was closed.
*/
func connectionClosed(connection: WSConnection)
}
public protocol WSConnectionHandler
{
func handle(connection: WSConnection)
}
public class WSConnection
{
public typealias ClosedCallback = Void -> Void
public typealias MessageCallback = (message: WSMessage) -> Void
var delegate : WSConnectionDelegate?
private var frameReader: WSFrameReader
private var frameWriter: WSFrameWriter
public var onMessage : MessageCallback?
public var onClosed : ClosedCallback?
private var controlFrameBuffer : ReadBufferType = ReadBufferType.alloc(256)
private var extensions = [WSExtension]()
private var transportClosed = false
public init(_ reader: Reader, writer: Writer, _ extensions: [WSExtension])
{
self.maxFrameWriteSize = DEFAULT_MAX_FRAME_SIZE
self.frameReader = WSFrameReader(reader)
self.frameWriter = WSFrameWriter(writer)
self.extensions = extensions
startReading()
}
private func handleClose() {
self.connectionClosed()
}
private func handleMessage(message: WSMessage)
{
// TODO: What should happen onMessage == nil? Should it be allowed to be nil?
self.onMessage?(message: message)
}
/**
* Called when a control frame has been read and needs to be handled.
*/
private func handleControlFrame(frame: WSFrame, completion: CompletionCallback?)
{
if frame.reserved1Set || frame.reserved2Set || frame.reserved3Set
{
self.connectionClosed()
completion?(error: nil)
} else
{
self.frameReader.read(controlFrameBuffer, length: frame.payloadLength, fully: true) { (length, error) -> Void in
if error != nil {
completion?(error: error)
} else {
Log.debug("\n\nControl Frame \(frame.opcode) Length: \(frame.payloadLength)")
assert(frame.payloadLength == length, "Read fully didnt read fully!")
if frame.opcode == WSFrame.Opcode.CloseFrame
{
var source = BufferPayload(buffer: self.controlFrameBuffer, length: length)
if frame.payloadLength > 0 {
let code : UInt = ((UInt(self.controlFrameBuffer[0]) << 8) & 0xff00) | (UInt(self.controlFrameBuffer[1]) & 0xff)
if code < 1000 || (code >= 1004 && code <= 1006) || (code >= 1012 && code < 3000) || (code >= 5000){
// invalid close codes
let codeBuffer = ReadBufferType.alloc(2)
codeBuffer[0] = 0x03
codeBuffer[1] = 0xEA
source = BufferPayload(buffer: codeBuffer, length: 2)
}
else if length > 2 {
if let utf8String = NSString(data: NSData(bytes: self.controlFrameBuffer.advancedBy(2), length: length - 2), encoding: NSUTF8StringEncoding)
{
Log.debug("Received UTF8 payload: \(utf8String)")
} else {
let codeBuffer = ReadBufferType.alloc(2)
codeBuffer[0] = 0x03
codeBuffer[1] = 0xEA
source = BufferPayload(buffer: codeBuffer, length: 2)
}
}
}
let replyCode = WSFrame.Opcode.CloseFrame
let message = self.startMessage(replyCode)
self.write(message, maskingKey: 0, source: source, isFinal: true, callback: completion)
}
else if frame.opcode == WSFrame.Opcode.PingFrame
{
let source = BufferPayload(buffer: self.controlFrameBuffer, length: length)
let replyCode = WSFrame.Opcode.PongFrame
let message = self.startMessage(replyCode)
self.write(message, maskingKey: 0, source: source, isFinal: true, callback: completion)
} else {
// ignore others (but finish their payloads off first)!
completion?(error: nil)
}
}
}
}
}
private func connectionClosed()
{
self.delegate?.connectionClosed(self)
self.onClosed?()
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// All Message write related operations
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Frames wont be bigger than this
*/
private var maxFrameWriteSize : Int = DEFAULT_MAX_FRAME_SIZE
private var currMessageCount = 0
private var allMessages = [WSMessage]()
private var currentWriteMessage : WSMessage?
/**
* Starts a new message tha
t can be streamed out by the caller.
* Once a message is created it can be written to continuosly.
*/
/**
* Starts a new message that can be streamed out by the caller.
* Once a message is created it can be written to continuosly.
*/
public func startMessage(opcode: WSFrame.Opcode) -> WSMessage
{
currMessageCount += 1
let newMessage = WSMessage(type: opcode, id: String(format: "msg:%05d", currMessageCount))
allMessages.append(newMessage)
return newMessage
}
/**
* Appends more data to a message.
*/
public func write(message: WSMessage, maskingKey: UInt32, source: Payload, isFinal: Bool, callback: CompletionCallback?)
{
// queue the request
if self.transportClosed
{
callback?(error: IOErrorType.Closed)
} else {
message.write(source, isFinal: isFinal, maskingKey: maskingKey, callback: callback)
continueWriting()
}
}
/**
* Appends more data to a message.
*/
public func write(message: WSMessage, source: Payload, isFinal: Bool, callback: CompletionCallback?)
{
write(message, maskingKey: 0, source: source, isFinal: isFinal, callback: callback)
}
/**
* Appends more data to a message.
*/
public func write(message: WSMessage, source: Payload, callback: CompletionCallback?)
{
write(message, maskingKey: 0, source: source, isFinal: false, callback: callback)
}
/**
* Closes the message. This message can no longer be written to.
*/
public func closeMessage(message: WSMessage, callback: CompletionCallback?)
{
if self.transportClosed
{
callback?(error: IOErrorType.Closed)
} else {
message.close(callback)
}
self.continueReading()
}
/**
* Writing messages is slightly simpler than reading messages. With reading there was the problem of not
* knowing when a message started and having to notify connection handlers on new messages so that *then*
* they could initiate reads.
*
* With writes this problem does not exist. ie a write can only be initiate by the connection handler and
* each write marks the start of a new message. How the message gets fragment is what this writer controls
* in concert with the actual message source that is provided at the start of a write.
*
* So to prevent a front of line blocking of messages, round-robin (or with some other custom scheduling
* technique) can be used to decide which message is to be sent in each write call.
*/
private func continueWriting()
{
// only start a request if the writer is idle
// (if it is already writing a frame then dont bother it)
if frameWriter.isIdle
{
if currentWriteMessage != nil
{
sendNextFrame(currentWriteMessage!)
} else {
// pick a message which has messages
for message in allMessages
{
if !message.writeQueue.isEmpty
{
currentWriteMessage = message
continueWriting()
return
}
}
}
}
}
private func sendNextFrame(message: WSMessage)
{
message.writeNextFrame(frameWriter, maxFrameSize: maxFrameWriteSize) { (writeRequest, error) -> Void in
if error != nil
{
self.transportClosed = (error as? IOErrorType) == IOErrorType.Closed
writeRequest?.callback?(error: error)
self.unwindWritesWithError(message, error: error!)
}
else
{
if !message.hasMoreFrames
{
self.currentWriteMessage = nil
assert(self.frameWriter.isIdle)
}
writeRequest?.callback?(error: error)
self.continueWriting()
}
}
}
/**
* Called when a read error occurred so all queued requests now need to be cancelled
* with the error.
*/
private func unwindWritesWithError(message: WSMessage, error: ErrorType)
{
Log.debug("Unwinding with error: \(error)")
while let next = message.writeQueue.first
{
message.writeQueue.removeFirst()
next.callback?(error: error)
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// All Message read related operations
/////////////////////////////////////////////////////////////////////////////////////////////////////////
public var validateUtf8 = true
public var utf8Validator = Utf8Validator()
private var messageCounter = 0
/**
* Information about the current message and frame being read
* Only one frame can be read at a time. It is upto the extensions
* to demux these frames into messages across several channels
*/
private var currentReadMessage : WSMessage?
private var currentFrame = WSFrame()
/**
* Holds the outstanding read requests for each message as they are being read.
* TODO: Make this a dictionary keyed by the channel and/or message id
*/
// private var readQueue = WSReadRequest()
private var currentReadRequest : WSReadRequest?
/**
* This method must always be called
*/
public func startReading()
{
self.continueReading()
}
/**
* Reads the body. Here we can do a couple of things:
* When a read is called, the reader can be either in "idle" state or in "reading header" state or in "reading payload" state
* Here if a start is happening then we have to defer the "read" to when the start has finsished till we have data.
* Once the reader is in "reading payload" state, we can have the following scenarios:
* 1. The frame is a control frame, then just handle the frame and go back to reading again till the next two cases
* match.
* 2. The frame belongs to a message that is new - so call the onMessage to begin handling of a new message
* (this should get the message handler to start doing reads on the data which will come back through this path again)
* 3. The frame belongs to an existing message (ie is a continuation):
* a. The message has outstanding read requests so serve it (and pop request off the queue)
* b. The message has no outstanding read requests. At this point we can do two things:
* 1. Buffer the data until we read frames corresponding to a message that has outstanding read requests.
* If there are no messages with read requests then dont buffer any data obviously. Also if the buffer
* exceeds a particular threshold then the connection can just close with a 1009 response.
* 2. Or just block until a read comes from the handler of this message and queues a read request.
* This is not a bad option since this way buffering can be done by the caller who may decide how much
* buffering to do (and in general buffer management can get messy).
*
* How to handle the first ever message? When a connection is first created it has a stream from which reads
* and writes can be done. This reader will be wrapped with a frame reader to return frames which is also nice.
* However the frame reader will only be read from when a read on a message is invoked. However a message cannot
* be created unless the frame reader has been read. So a start on the frame reader has to be kicked off at some
* time (or an intial read has to be kicked off) so that frames can start getting read and passed off to the message
* handlers for processing.
*
* One other scenario this can end up in is say if there are 5 messages being processed and neither of them have done a read yet
* so on the connection there is a frame for a new message, since the read is not happening this new frame wont be read.
*
* Looks like both cases can be solved with a periodic read that happens in a loop (say every second or so as long as the
* read queue is empty)
*/
public func read(message: WSMessage, buffer : ReadBufferType, length: LengthType, fully: Bool, callback: WSMessageReadCallback?)
{
if transportClosed
{
callback?(length: 0, endReached: true, error: IOErrorType.Closed)
} else {
// queue the request
assert(currentReadRequest == nil, "A read request is already running. Make the request in a callback of another request or use promises")
currentReadRequest = WSReadRequest(message: message, buffer: buffer, fully: fully, length: length, satisfied: 0, callback: callback)
continueReading()
}
}
private var frameReadStarted = false
/**
* This method is the main "scheduler" loop of the reader.
*/
func continueReading()
{
// now see what to do based on the reader state
// TODO: ensure a single loop/queue
if frameReader.isIdle
{
// no frames have been read yet
startReadingNextFrame()
}
// means we have started a frame, whether it is a control frame or not
// someone will "read" it. So if there are no read requests it means
// there is eventually bound to be one
if frameReader.processingPayload && currentReadRequest != nil && !frameReadStarted
{
assert(!frameReadStarted)
frameReadStarted = true
var theReadRequest = currentReadRequest!
let currentBuffer = theReadRequest.buffer.advancedBy(theReadRequest.satisfied)
let remaining = theReadRequest.remaining
// Log.debug("Message Reader Started reading next frame body, Type: \(self.currentFrame.opcode), Remaining: \(remaining)")
frameReader.read(currentBuffer, length: remaining, fully: theReadRequest.fully) { (length, error) in
self.frameReadStarted = false
if error == nil
{
assert(length >= 0, "Length cannot be negative")
theReadRequest.satisfied += length
if self.currentFrame.isControlFrame
{
// do nothing - wait till entire frame is processed
if theReadRequest.remaining == 0
{
// process the frame and start the next frame
self.startReadingNextFrame()
} else {
// do nothing as the control frame must be read fully before being processed
self.continueReading()
}
} else {
// so we have some data, pass this through all the extensions to see what can be done
// with it
for extn in self.extensions {
let (frame, error) = extn.newFrameRead(self.currentFrame)
if error != nil {
self.readerClosed()
return
}
self.currentFrame = frame
}
let endReached = self.frameReader.remaining == 0 && self.currentFrame.isFinal
if self.currentReadMessage!.messageType == WSFrame.Opcode.TextFrame && self.validateUtf8
{
let utf8Validated = self.utf8Validator.validate(currentBuffer, length) &&
(!endReached || self.utf8Validator.finish())
if !utf8Validated
{
self.readerClosed()
return
}
}
self.currentReadRequest = nil
if endReached
{
self.currentReadMessage = nil
}
theReadRequest.callback?(length: theReadRequest.satisfied, endReached: endReached, error: error)
}
} else {
self.currentReadRequest = nil
self.currentReadMessage = nil
theReadRequest.callback?(length: 0, endReached: false, error: error)
}
}
}
}
private func startReadingNextFrame()
{
// kick off the reading of the first frame
// Log.debug("Started reading next frame header, State: \(reader.state)")
self.frameReader.start { (frame, error) in
if error == nil && frame != nil {
// we have the frame so process it and start the next frame
self.processNewFrame(frame!) {(error) in
if !self.transportClosed
{
self.continueReading()
} else {
Log.debug("Transport closed")
}
}
} else {
self.readerClosed()
}
}
}
private func readerClosed()
{
transportClosed = true
self.onClosed?()
}
var frameCount = 0
/**
* This method will only be called when a control frame has
* finished or if a non-control frame is of size 0
*/
private func processNewFrame(frame: WSFrame, callback : CompletionCallback?)
{
frameCount += 1
self.currentFrame = frame
if self.currentFrame.isControlFrame
{
if !self.currentFrame.isFinal || self.currentFrame.payloadLength > 125 || frame.reserved1Set || frame.reserved2Set || frame.reserved3Set
{
// close the connection
self.readerClosed()
} else {
self.handleControlFrame(self.currentFrame) {(error) in
if (self.currentFrame.opcode == WSFrame.Opcode.CloseFrame)
{
self.readerClosed()
} else {
callback?(error: error)
}
}
}
} else { // a non control frame
// here get the frame through extensions
for extn in extensions {
let (frame, error) = extn.newFrameRead(self.currentFrame)
if error != nil {
self.readerClosed()
return
}
self.currentFrame = frame
}
// after all extensions have gone through the frame, we cannot have reserved bits set
if currentFrame.reserved1Set || currentFrame.reserved2Set || currentFrame.reserved3Set
{
// non 0 reserved bits without negotiated extensions
// close the connection
self.readerClosed()
}
else if self.currentFrame.opcode.isReserved
{
// close the connection
self.readerClosed()
} else if currentFrame.opcode == WSFrame.Opcode.ContinuationFrame {
if currentReadMessage == nil
{
self.readerClosed()
} else {
callback?(error: nil)
}
} else {
if currentReadMessage != nil
{
// we already have a message so drop this
self.readerClosed()
} else {
// starting a new message
self.utf8Validator.reset()
self.messageCounter += 1
let messageId = String(format: "%05d", self.messageCounter)
currentReadMessage = WSMessage(type: self.currentFrame.opcode, id: messageId)
self.handleMessage(currentReadMessage!)
}
}
}
}
private struct WSReadRequest
{
var message : WSMessage?
var buffer : ReadBufferType
var fully : Bool = false
var length : LengthType
var satisfied : LengthType = 0
var callback : WSMessageReadCallback?
var remaining : LengthType { return length - satisfied }
}
}
let READ_QUEUE_INTERVAL = 1.0
let WRITE_QUEUE_INTERVAL = 1.0
public let DEFAULT_MAX_FRAME_SIZE = DEFAULT_BUFFER_LENGTH
public typealias WSMessageReadCallback = (length: LengthType, endReached: Bool, error: ErrorType?) -> Void
public class WSMessage
{
/**
* Message type being sent
*/
public var messageType : WSFrame.Opcode = WSFrame.Opcode.ContinuationFrame
/**
* An user defined identifier associated with a message.
*/
var messageId : String = ""
var totalFramesRead = 0
var totalFramesWritten = 0
/**
* List of write requests on this message
*/
var writeQueue = [WriteRequest]()
public var identifier : String { get { return messageId } }
public init(type: WSFrame.Opcode, id : String)
{
messageType = type
messageId = id
}
public convenience init(type: WSFrame.Opcode)
{
self.init(type: type, id: "")
}
var extraDataDict = [String : Any]()
public func extraData(key: String) -> Any?
{
return extraDataDict[key]
}
public func setExtraData(key: String, value: Any?)
{
if value == nil {
extraDataDict.removeValueForKey(key)
} else {
extraDataDict[key] = value!
}
}
public func write(source: Payload, isFinal: Bool, maskingKey: UInt32, callback: CompletionCallback?)
{
let newRequest = WriteRequest(source: source, callback: callback)
newRequest.maskingKey = maskingKey
newRequest.isFinalRequest = isFinal
writeQueue.append(newRequest)
}
public func close(callback: CompletionCallback?)
{
// assert(false, "Not yet implemented")
}
public var hasMoreFrames : Bool {
return !writeQueue.isEmpty
}
class WriteRequest
{
/**
* The source of the message.
*/
var maskingKey: UInt32 = 0
/**
* The total length of the message as indicated by the payload.
* If it does not exist then we fall back to the frame length
* which is obtained by calling Payload.nextFrame()
*/
var isFinalRequest = false
var numFramesWritten = 0
var hasTotalLength = false
var currentLength : LengthType = 0
var source : Payload
var satisfied : LengthType = 0
var callback : CompletionCallback?
init(source: Payload, callback: CompletionCallback?)
{
self.source = source
self.callback = callback
}
var remaining : LengthType {
return currentLength > satisfied ? currentLength - satisfied : 0
}
func calculateLengths() -> Bool
{
if numFramesWritten == 0
{
if let totalLength = source.totalLength
{
hasTotalLength = true
currentLength = LengthType(totalLength)
return true
} else if let currFrameLength = source.nextFrame()
{
hasTotalLength = false
currentLength = LengthType(currFrameLength)
return true
}
} else if !hasTotalLength {
// should no longer calculate total Length
if let currFrameLength = source.nextFrame()
{
currentLength = LengthType(currFrameLength)
return true
}
}
return false
}
}
private func popWriteRequest(writeRequest : WriteRequest)
{
assert(self.writeQueue.isEmpty || self.writeQueue.first === writeRequest)
if !self.writeQueue.isEmpty
{
self.writeQueue.removeFirst()
}
}
func writeNextFrame(writer: WSFrameWriter, maxFrameSize: Int, frameCallback : (writeRequest: WriteRequest?, error: ErrorType?) -> Void)
{
assert(writer.isIdle, "Writer MUST be idle when this method is called. Later on we could just skip this instead of asserting")
// writer is idle so start the frame
if let writeRequest = self.writeQueue.first
{
if writeRequest.currentLength == 0
{
// first time we are dealing with this frame so do a bit of book keeping
if !writeRequest.calculateLengths()
{
popWriteRequest(writeRequest)
frameCallback(writeRequest: writeRequest, error: nil)
return
}
}
let length = min(writeRequest.remaining, maxFrameSize)
let isFirstFrame = totalFramesWritten == 0
let isFinalFrame = writeRequest.remaining <= maxFrameSize && writeRequest.isFinalRequest
let realOpcode = isFirstFrame ? messageType : WSFrame.Opcode.ContinuationFrame
// Log.debug("Started writing next frame header: \(realOpcode), Length: \(length), isFinal: \(isFinalFrame)")
writer.start(realOpcode, frameLength: length, isFinal: isFinalFrame, maskingKey: writeRequest.maskingKey) { (frame, error) in
// Log.debug("Finished writing next frame header: \(realOpcode), Length: \(length), isFinal: \(isFinalFrame)")
if error != nil {
self.popWriteRequest(writeRequest)
frameCallback(writeRequest: writeRequest, error: error)
return
}
// Log.debug("Started writing next frame body: \(realOpcode), Length: \(length), isFinal: \(isFinalFrame)")
writeRequest.source.write(writer, length: length) { (error) in
// Log.debug("Finished writing next frame body: \(realOpcode), Length: \(length), isFinal: \(isFinalFrame)")
// Log.debug("-----------------------------------------------------------------------------------------------\n")
if error == nil
{
self.totalFramesWritten += 1
writeRequest.numFramesWritten += 1
writeRequest.satisfied += length
if writeRequest.remaining == 0
{
// first time we are dealing with this frame so do a bit of book keeping
if !writeRequest.calculateLengths()
{
self.popWriteRequest(writeRequest)
frameCallback(writeRequest: writeRequest, error: nil)
return
}
}
}
frameCallback(writeRequest: nil, error: error)
}
}
}
}
}
| 40.048649 | 172 | 0.541267 |
50f1b0d03c63c020ddb8c3330d2a1cc35a975d34 | 33,084 | /**
* Copyright IBM Corporation 2016,2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/// Object containing everything needed to build HTTP requests and execute them
public class RestRequest: NSObject {
// Check if there exists a self-signed certificate and whether it's a secure connection
private let isSecure: Bool
private let isSelfSigned: Bool
/// A default `URLSession` instance
private var session: URLSession {
var session = URLSession(configuration: URLSessionConfiguration.default)
if isSecure && isSelfSigned {
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalCacheData
session = URLSession(configuration: config, delegate: self, delegateQueue: .main)
}
return session
}
// The HTTP Request
private var request: URLRequest
/// `CircuitBreaker` instance for this `RestRequest`
public var circuitBreaker: CircuitBreaker<(Data?, HTTPURLResponse?, Error?) -> Void, String>?
/// Parameters for a `CircuitBreaker` instance.
/// When set, a new circuitBreaker instance is created
public var circuitParameters: CircuitParameters<String>? = nil {
didSet {
if let params = circuitParameters {
circuitBreaker = CircuitBreaker(name: params.name,
timeout: params.timeout,
resetTimeout: params.resetTimeout,
maxFailures: params.maxFailures,
rollingWindow: params.rollingWindow,
bulkhead: params.bulkhead,
command: handleInvocation,
fallback: params.fallback)
}
}
}
// MARK: HTTP Request Paramters
/// URL `String` used to store a url containing replacable template values
private var urlTemplate: String?
/// The string representation of HTTP request url
private var url: String
/// The HTTP request method: defaults to Get
public var method: HTTPMethod {
get {
return HTTPMethod(fromRawValue: request.httpMethod ?? "unknown")
}
set {
request.httpMethod = newValue.rawValue
}
}
/// HTTP Credentials
public var credentials: Credentials? {
didSet {
// set the request's authentication credentials
if let credentials = credentials {
switch credentials {
case .apiKey: break
case .basicAuthentication(let username, let password):
let authData = (username + ":" + password).data(using: .utf8)!
let authString = authData.base64EncodedString()
request.setValue("Basic \(authString)", forHTTPHeaderField: "Authorization")
}
} else {
request.setValue(nil, forHTTPHeaderField: "Authorization")
}
}
}
/// HTTP Header Parameters
public var headerParameters: [String: String] {
get {
return request.allHTTPHeaderFields ?? [:]
}
set {
// Remove any header fields external to the RestRequest supported headers
let s: Set<String> = ["Authorization", "Accept", "Content-Type", "User-Agent"]
_ = request.allHTTPHeaderFields?.map { key, value in if !s.contains(key) { request.setValue(nil, forHTTPHeaderField: key) } }
// Add new header parameters
for (key, value) in newValue {
request.setValue(value, forHTTPHeaderField: key)
}
}
}
/// HTTP Accept Type Header: defaults to application/json
public var acceptType: String? {
get {
return request.value(forHTTPHeaderField: "Accept")
}
set {
request.setValue(newValue, forHTTPHeaderField: "Accept")
}
}
/// HTTP Content Type Header: defaults to application/json
public var contentType: String? {
get {
return request.value(forHTTPHeaderField: "Content-Type")
}
set {
request.setValue(newValue, forHTTPHeaderField: "Content-Type")
}
}
/// HTTP User-Agent Header
public var productInfo: String? {
get {
return request.value(forHTTPHeaderField: "User-Agent")
}
set {
request.setValue(newValue?.generateUserAgent(), forHTTPHeaderField: "User-Agent")
}
}
/// HTTP Message Body
public var messageBody: Data? {
get {
return request.httpBody
}
set {
request.httpBody = newValue
}
}
/// HTTP Request Query Items
public var queryItems: [URLQueryItem]? {
set {
// Replace queryitems on request.url with new queryItems
if let currentURL = request.url, var urlComponents = URLComponents(url: currentURL, resolvingAgainstBaseURL: false) {
urlComponents.queryItems = newValue
// Must encode "+" to %2B (URLComponents does not do this)
urlComponents.percentEncodedQuery = urlComponents.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
request.url = urlComponents.url
}
}
get {
if let currentURL = request.url, var urlComponents = URLComponents(url: currentURL, resolvingAgainstBaseURL: false) {
return urlComponents.queryItems
}
return nil
}
}
/// Initialize a `RestRequest` instance
///
/// - Parameters:
/// - url: URL string to use for network request
public init(method: HTTPMethod = .get, url: String, containsSelfSignedCert: Bool? = false) {
self.isSecure = url.contains("https")
self.isSelfSigned = containsSelfSignedCert ?? false
// Instantiate basic mutable request
let urlComponents = URLComponents(string: url) ?? URLComponents(string: "")!
let urlObject = urlComponents.url ?? URL(string: "n/a")!
self.request = URLRequest(url: urlObject)
// Set inital fields
self.url = url
super.init()
self.method = method
self.acceptType = "application/json"
self.contentType = "application/json"
// We accept URLs with templated values which `URLComponents` does not treat as valid
if URLComponents(string: url) == nil {
self.urlTemplate = url
}
}
// MARK: Response methods
/// Request response method that either invokes `CircuitBreaker` or executes the HTTP request
///
/// - Parameter completionHandler: Callback used on completion of operation
public func response(completionHandler: @escaping (Data?, HTTPURLResponse?, Error?) -> Void) {
if let breaker = circuitBreaker {
breaker.run(commandArgs: completionHandler, fallbackArgs: "Circuit is open")
} else {
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil, let response = response as? HTTPURLResponse else {
completionHandler(nil, nil, error)
return
}
let code = response.statusCode
if code >= 200 && code < 300 {
completionHandler(data, response, error)
} else {
completionHandler(data,
response,
RestError.erroredResponseStatus(code))
}
}
task.resume()
}
}
/// Request response method with the expected result of a `Data` object
///
/// - Parameters:
/// - templateParams: URL templating parameters used for substituion if possible
/// - queryItems: array containing `URLQueryItem` objects that will be appended to the request's URL
/// - completionHandler: Callback used on completion of operation
public func responseData(templateParams: [String: String]? = nil,
queryItems: [URLQueryItem]? = nil,
completionHandler: @escaping (RestResponse<Data>) -> Void) {
if let error = performSubstitutions(params: templateParams) {
let result = Result<Data>.failure(error)
let dataResponse = RestResponse(request: request, response: nil, data: nil, result: result)
completionHandler(dataResponse)
return
}
self.queryItems = queryItems
response { data, response, error in
if let error = error {
let result = Result<Data>.failure(error)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
return
}
guard let data = data else {
let result = Result<Data>.failure(RestError.noData)
let dataResponse = RestResponse(request: self.request, response: response, data: nil, result: result)
completionHandler(dataResponse)
return
}
let result = Result.success(data)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
}
}
/// Request response method with the expected result of the object, `T` specified
///
/// - Parameters:
/// - responseToError: Error callback closure in case of request failure
/// - path: Array of Json keys leading to desired Json
/// - templateParams: URL templating parameters used for substituion if possible
/// - queryItems: array containing `URLQueryItem` objects that will be appended to the request's URL
/// - completionHandler: Callback used on completion of operation
public func responseObject<T: JSONDecodable>(
responseToError: ((HTTPURLResponse?, Data?) -> Error?)? = nil,
path: [JSONPathType]? = nil,
templateParams: [String: String]? = nil,
queryItems: [URLQueryItem]? = nil,
completionHandler: @escaping (RestResponse<T>) -> Void) {
if let error = performSubstitutions(params: templateParams) {
let result = Result<T>.failure(error)
let dataResponse = RestResponse(request: request, response: nil, data: nil, result: result)
completionHandler(dataResponse)
return
}
self.queryItems = queryItems
response { data, response, error in
if let error = error {
let result = Result<T>.failure(error)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
return
}
if let responseToError = responseToError,
let error = responseToError(response, data) {
let result = Result<T>.failure(error)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
return
}
// ensure data is not nil
guard let data = data else {
let result = Result<T>.failure(RestError.noData)
let dataResponse = RestResponse(request: self.request, response: response, data: nil, result: result)
completionHandler(dataResponse)
return
}
// parse json object
let result: Result<T>
do {
let json = try JSONWrapper(data: data)
let object: T
if let path = path {
switch path.count {
case 0: object = try json.decode()
case 1: object = try json.decode(at: path[0])
case 2: object = try json.decode(at: path[0], path[1])
case 3: object = try json.decode(at: path[0], path[1], path[2])
case 4: object = try json.decode(at: path[0], path[1], path[2], path[3])
case 5: object = try json.decode(at: path[0], path[1], path[2], path[3], path[4])
default: throw JSONWrapper.Error.keyNotFound(key: "ExhaustedVariadicParameterEncoding")
}
} else {
object = try json.decode()
}
result = .success(object)
} catch {
result = .failure(error)
}
// execute callback
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
}
}
/// Request response method with the expected result of an array of type `T` specified
///
/// - Parameters:
/// - responseToError: Error callback closure in case of request failure
/// - path: Array of Json keys leading to desired Json
/// - templateParams: URL templating parameters used for substituion if possible
/// - queryItems: array containing `URLQueryItem` objects that will be appended to the request's URL
/// - completionHandler: Callback used on completion of operation
public func responseObject<T: Decodable>(
responseToError: ((HTTPURLResponse?, Data?) -> Error?)? = nil,
templateParams: [String: String]? = nil,
queryItems: [URLQueryItem]? = nil,
completionHandler: @escaping (RestResponse<T>) -> Void) {
if let error = performSubstitutions(params: templateParams) {
let result = Result<T>.failure(error)
let dataResponse = RestResponse(request: request, response: nil, data: nil, result: result)
completionHandler(dataResponse)
return
}
response { data, response, error in
if let error = error ?? responseToError?(response, data) {
let result = Result<T>.failure(error)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
return
}
// ensure data is not nil
guard let data = data else {
let result = Result<T>.failure(RestError.noData)
let dataResponse = RestResponse(request: self.request, response: response, data: nil, result: result)
completionHandler(dataResponse)
return
}
// parse json object
let result: Result<T>
do {
let object = try JSONDecoder().decode(T.self, from: data)
result = .success(object)
} catch {
result = .failure(error)
}
// execute callback
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
}
}
/// Request response method with the expected result of an array of type `T` specified
///
/// - Parameters:
/// - responseToError: Error callback closure in case of request failure
/// - path: Array of Json keys leading to desired Json
/// - templateParams: URL templating parameters used for substituion if possible
/// - queryItems: array containing `URLQueryItem` objects that will be appended to the request's URL
/// - completionHandler: Callback used on completion of operation
public func responseArray<T: JSONDecodable>(
responseToError: ((HTTPURLResponse?, Data?) -> Error?)? = nil,
path: [JSONPathType]? = nil,
templateParams: [String: String]? = nil,
queryItems: [URLQueryItem]? = nil,
completionHandler: @escaping (RestResponse<[T]>) -> Void) {
if let error = performSubstitutions(params: templateParams) {
let result = Result<[T]>.failure(error)
let dataResponse = RestResponse(request: request, response: nil, data: nil, result: result)
completionHandler(dataResponse)
return
}
self.queryItems = queryItems
response { data, response, error in
if let error = error {
let result = Result<[T]>.failure(error)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
return
}
if let responseToError = responseToError,
let error = responseToError(response, data) {
let result = Result<[T]>.failure(error)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
return
}
// ensure data is not nil
guard let data = data else {
let result = Result<[T]>.failure(RestError.noData)
let dataResponse = RestResponse(request: self.request, response: response, data: nil, result: result)
completionHandler(dataResponse)
return
}
// parse json object
let result: Result<[T]>
do {
let json = try JSONWrapper(data: data)
var array: [JSONWrapper]
if let path = path {
switch path.count {
case 0: array = try json.getArray()
case 1: array = try json.getArray(at: path[0])
case 2: array = try json.getArray(at: path[0], path[1])
case 3: array = try json.getArray(at: path[0], path[1], path[2])
case 4: array = try json.getArray(at: path[0], path[1], path[2], path[3])
case 5: array = try json.getArray(at: path[0], path[1], path[2], path[3], path[4])
default: throw JSONWrapper.Error.keyNotFound(key: "ExhaustedVariadicParameterEncoding")
}
} else {
array = try json.getArray()
}
let objects: [T] = try array.map { json in try json.decode() }
result = .success(objects)
} catch {
result = .failure(error)
}
// execute callback
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
}
}
/// Request response method with the expected result of a `String`
///
/// - Parameters:
/// - responseToError: Error callback closure in case of request failure
/// - templateParams: URL templating parameters used for substituion if possible
/// - queryItems: array containing `URLQueryItem` objects that will be appended to the request's URL
/// - completionHandler: Callback used on completion of operation
public func responseString(
responseToError: ((HTTPURLResponse?, Data?) -> Error?)? = nil,
templateParams: [String: String]? = nil,
queryItems: [URLQueryItem]? = nil,
completionHandler: @escaping (RestResponse<String>) -> Void) {
if let error = performSubstitutions(params: templateParams) {
let result = Result<String>.failure(error)
let dataResponse = RestResponse(request: request, response: nil, data: nil, result: result)
completionHandler(dataResponse)
return
}
self.queryItems = queryItems
response { data, response, error in
if let error = error {
let result = Result<String>.failure(error)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
return
}
if let responseToError = responseToError,
let error = responseToError(response, data) {
let result = Result<String>.failure(error)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
return
}
// ensure data is not nil
guard let data = data else {
let result = Result<String>.failure(RestError.noData)
let dataResponse = RestResponse(request: self.request, response: response, data: nil, result: result)
completionHandler(dataResponse)
return
}
// Retrieve string encoding type
let encoding = self.getCharacterEncoding(from: response?.allHeaderFields["Content-Type"] as? String)
// parse data as a string
guard let string = String(data: data, encoding: encoding) else {
let result = Result<String>.failure(RestError.serializationError)
let dataResponse = RestResponse(request: self.request, response: response, data: nil, result: result)
completionHandler(dataResponse)
return
}
// execute callback
let result = Result.success(string)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
}
}
/// Request response method to use when there is no expected result
///
/// - Parameters:
/// - responseToError: Error callback closure in case of request failure
/// - templateParams: URL templating parameters used for substituion if possible
/// - queryItems: array containing `URLQueryItem` objects that will be appended to the request's URL
/// - completionHandler: Callback used on completion of operation
public func responseVoid(
responseToError: ((HTTPURLResponse?, Data?) -> Error?)? = nil,
templateParams: [String: String]? = nil,
queryItems: [URLQueryItem]? = nil,
completionHandler: @escaping (RestResponse<Void>) -> Void) {
if let error = performSubstitutions(params: templateParams) {
let result = Result<Void>.failure(error)
let dataResponse = RestResponse(request: request, response: nil, data: nil, result: result)
completionHandler(dataResponse)
return
}
self.queryItems = queryItems
response { data, response, error in
if let error = error {
let result = Result<Void>.failure(error)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
return
}
if let responseToError = responseToError, let error = responseToError(response, data) {
let result = Result<Void>.failure(error)
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
return
}
// execute callback
let result = Result<Void>.success(())
let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result)
completionHandler(dataResponse)
}
}
/// Utility method to download a file from a remote origin
///
/// - Parameters:
/// - destination: URL destination to save the file to
/// - completionHandler: Callback used on completion of operation
public func download(to destination: URL, completionHandler: @escaping (HTTPURLResponse?, Error?) -> Void) {
let task = session.downloadTask(with: request) { (source, response, error) in
do {
guard let source = source else {
throw RestError.invalidFile
}
let fileManager = FileManager.default
try fileManager.moveItem(at: source, to: destination)
completionHandler(response as? HTTPURLResponse, error)
} catch {
completionHandler(nil, RestError.fileManagerError)
}
}
task.resume()
}
/// Method used by `CircuitBreaker` as the contextCommand
///
/// - Parameter invocation: `Invocation` contains a command argument, Void return type, and a String fallback arguement
private func handleInvocation(invocation: Invocation<(Data?, HTTPURLResponse?, Error?) -> Void, String>) {
let task = session.dataTask(with: request) { (data, response, error) in
if error != nil {
invocation.notifyFailure(error: BreakerError(reason: error?.localizedDescription))
} else {
invocation.notifySuccess()
}
let callback = invocation.commandArgs
callback(data, response as? HTTPURLResponse, error)
}
task.resume()
}
/// Method to perform substitution on `String` URL if it contains templated placeholders
///
/// - Parameter params: dictionary of parameters to substitute in
/// - Returns: returns either a `RestError` or nil if there were no problems setting new URL on our `URLRequest` object
private func performSubstitutions(params: [String: String]?) -> RestError? {
guard let params = params else {
return nil
}
// Get urlTemplate if available, otherwise just use the request's url
let urlString = urlTemplate ?? url
guard let urlComponents = urlString.expand(params: params) else {
return RestError.invalidSubstitution
}
self.request.url = urlComponents.url
return nil
}
/// Method to identify the charset encoding defined by the Content-Type header
/// - Defaults set to .utf8
/// - Parameter contentType: The content-type header string
/// - Returns: returns the defined or default String.Encoding.Type
private func getCharacterEncoding(from contentType: String? = nil) -> String.Encoding {
guard let text = contentType,
let regex = try? NSRegularExpression(pattern: "(?<=charset=).*?(?=$|;|\\s)", options: [.caseInsensitive]),
let match = regex.matches(in: text, range: NSRange(text.startIndex..., in: text)).last,
let range = Range(match.range, in: text) else {
return .utf8
}
/// Strip whitespace and quotes
let charset = String(text[range]).trimmingCharacters(in: CharacterSet(charactersIn: "\"").union(.whitespaces))
switch String(charset).lowercased() {
case "iso-8859-1": return .isoLatin1
default: return .utf8
}
}
}
/// Encapsulates properties needed to initialize a `CircuitBreaker` object within the `RestRequest` init.
/// `A` is the type of the fallback's parameter
public struct CircuitParameters<A> {
/// The circuit name: defaults to '1000'test'
let name: String
/// The circuit timeout: defaults to 1000
public let timeout: Int
/// The circuit timeout: defaults to 60000
public let resetTimeout: Int
/// Max failures allowed: defaults to 5
public let maxFailures: Int
/// Rolling Window: defaults to 10000
public let rollingWindow: Int
/// Bulkhead: defaults to 0
public let bulkhead: Int
/// The error fallback callback
public let fallback: (BreakerError, A) -> Void
/// Initialize a `CircuitPrameters` instance
public init(name: String = "circuitName", timeout: Int = 2000, resetTimeout: Int = 60000, maxFailures: Int = 5, rollingWindow: Int = 10000, bulkhead: Int = 0, fallback: @escaping (BreakerError, A) -> Void) {
self.name = name
self.timeout = timeout
self.resetTimeout = resetTimeout
self.maxFailures = maxFailures
self.rollingWindow = rollingWindow
self.bulkhead = bulkhead
self.fallback = fallback
}
}
/// Contains data associated with a finished network request.
/// With `T` being the type of the response expected to be received
public struct RestResponse<T> {
/// The rest request
public let request: URLRequest?
/// The response to the request
public let response: HTTPURLResponse?
/// The Response Data
public let data: Data?
/// The Reponse Result
public let result: Result<T>
}
/// Enum to differentiate a success or failure
public enum Result<T> {
/// a success of generic type `T`
case success(T)
/// a failure with an `Error` object
case failure(Error)
}
/// Enum used to specify the type of authentication being used
public enum Credentials {
/// an API key is being used, no additional data needed
case apiKey
/// a basic username/password authentication is being used with said value, passed in
case basicAuthentication(username: String, password: String)
}
/// Enum describing error types that can occur during a rest request and response
public enum RestError: Error, CustomStringConvertible {
/// no data was returned from the network
case noData
/// data couldn't be parsed correctly
case serializationError
/// failure to encode data into a certain format
case encodingError
/// failure in file manipulation
case fileManagerError
/// the file trying to be accessed is invalid
case invalidFile
/// the url substitution attempted could not be made
case invalidSubstitution
/// Error response status
case erroredResponseStatus(Int)
/// Error Description
public var description: String {
switch self {
case .noData : return "No Data"
case .serializationError : return "Serialization Error"
case .encodingError : return "Encoding Error"
case .fileManagerError : return "File Manager Error"
case .invalidFile : return "Invalid File"
case .invalidSubstitution : return "Invalid Data"
case .erroredResponseStatus(let s) : return "Error HTTP Response: `\(s)`"
}
}
/// Computed Property to extract error code
public var code: Int? {
switch self {
case .erroredResponseStatus(let status): return status
default: return nil
}
}
}
// URL Session extension
extension RestRequest: URLSessionDelegate {
/// URL session function to allow trusting certain URLs
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let method = challenge.protectionSpace.authenticationMethod
let host = challenge.protectionSpace.host
guard let url = URLComponents(string: self.url), let baseHost = url.host else {
completionHandler(.performDefaultHandling, nil)
return
}
let warning = "Attempting to establish a secure connection; This is only supported by macOS 10.6 or higher. Resorting to default handling."
switch (method, host) {
case (NSURLAuthenticationMethodServerTrust, baseHost):
#if !os(Linux)
guard #available(iOS 3.0, macOS 10.6, *), let trust = challenge.protectionSpace.serverTrust else {
Log.warning(warning)
fallthrough
}
let credential = URLCredential(trust: trust)
completionHandler(.useCredential, credential)
#else
Log.warning(warning)
fallthrough
#endif
default:
completionHandler(.performDefaultHandling, nil)
}
}
}
| 40.150485 | 211 | 0.599081 |
230755bcfa40811f789a527c268b947b43d7e7fe | 940 | //
// AppVersionUpdateDataModel.swift
// LLInfo
//
// Created by CmST0us on 2018/1/6.
// Copyright © 2018年 eki. All rights reserved.
//
import Foundation
class AppVersionUpdateDataModel {
private var _dataDictionary: Dictionary<String, Any>
struct CodingKey{
static let versionKey = "version"
static let messageKey = "message"
}
var version: Float? {
return _dataDictionary[CodingKey.versionKey] as? Float
}
var message: String? {
return _dataDictionary[CodingKey.messageKey] as? String
}
init(dictionary: Dictionary<String, Any>) {
_dataDictionary = dictionary
}
}
extension AppVersionUpdateDataModel: CommonApiRequestParamProtocol {
static func requestApiRequestParam() -> ApiRequestParam {
let p = ApiRequestParam()
p.method = ApiRequestParam.Method.GET
p.path = "/app/ios/version"
return p
}
}
| 24.102564 | 68 | 0.659574 |
719bb30b1a56bbecdd9e39fd85bfca44d3bc292a | 2,499 | import Foundation
import Combine
//Introducing publisher(for:options:)
let queue = OperationQueue()
//let subscription = queue.publisher(for: \.operationCount)
// .sink {
// print("Outstanding operations in queue: \($0)")
// }
//Preparing and subscribing to your own KVO-compliant propertie
struct PureSwift {
let a: (Int, Bool)
}
class TestObject: NSObject { //NSObject 프로토콜을 상속하는 클래스 생성 //KVO에 필요하다.
@objc dynamic var integerProperty: Int = 0
//관찰할 속성을 @objc dynamic로 표시한다.
@objc dynamic var stringProperty: String = ""
@objc dynamic var arrayProperty: [Float] = []
// @objc dynamic var structProperty: PureSwift = .init(a: (0,false)) //PureSwift type
//오류가 발생한다.
}
let obj = TestObject()
//let subscription = obj.publisher(for: \.integerProperty)
//obj의 integerProperty 속성을 관찰하는 publisher를 생성하고 구독한다.
//obj.publisher(for: \.stringProperty, options: [])
//로 작성하면, 초기값을 생략할 수 있다.
//let subscription = obj.publisher(for: \.integerProperty, options: [.prior])
// .sink {
// print("integerProperty changes to \($0)")
// }
let subscription2 = obj.publisher(for: \.stringProperty)
.sink {
print("stringProperty changes to \($0)")
}
let subscription3 = obj.publisher(for: \.arrayProperty)
.sink {
print("arrayProperty changes to \($0)")
}
obj.integerProperty = 100
obj.integerProperty = 200
obj.stringProperty = "Hello"
obj.arrayProperty = [1.0]
obj.stringProperty = "World"
obj.arrayProperty = [1.0, 2.0]
//값을 업데이트 한다.
//ObservableObject
class MonitorObject: ObservableObject {
@Published var someProperty = false
@Published var someOtherProperty = ""
}
let object = MonitorObject()
let subscription = object.objectWillChange.sink { //<Void, Never>로 실제 어떤 값이 변경됐는지는 알 수 없다.
print("object will change")
}
object.someProperty = true
object.someOtherProperty = "Hello world"
//Key points
// • Key-Value Observing은 주로 Objective-C 런타임(runtime)과 NSObject 프로토콜(protocol)의 메서드(methods)에 의존(relies on)한다.
// • Apple 프레임 워크(frameworks)의 많은 Objective-C 클래스(classes)는 KVO를 준수(compliant)하는 속성(properties)을 제공한다.
// • NSObject를 상속(inheriting)하는 클래스(class)에 속해있고 @objc dynamic 특성(attributes)으로 표시된 고유한 속성(properties)을 관찰가능(observable)하게 만들 수 있다.
// • ObservableObject를 상속(inherit)하고, 속성(properties)에 @Published를 사용할 수도 있다.
// 컴파일러에서 생성한(compiler-generated) objectWillChange publisher는 @Published 속성 중 하나가 변경(changes)될 때마다 실행(triggers)된다.
// 하지만 어떤 속성이 변경(changed)되었는지는 알려주지 않는다.
| 28.724138 | 131 | 0.697879 |
4b191c9e388e541a7340b6bea0570152487efad5 | 258 | //
// ViewController.swift
// FireChat
//
// Created by 윤병일 on 2021/07/05.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 12.9 | 54 | 0.670543 |
bf3588004474cd0b93c08bd88cbafa636fea9abd | 2,942 | import SpriteKit
public class MSKEmitterLabel: SKNode {
private let text: String
private let font: UIFont
private let emitterName: String
private let marginHorizontal: CGFloat
private let animationDuration: Double
private let addEmitterInterval: Double
private var _childEmitters = [SKEmitterNode]()
private var _width: CGFloat = 0
public var width: CGFloat {
return _width
}
public init(text: String, font: UIFont, emitterName: String, marginHorizontal: CGFloat = 10.0, animationDuration: Double = 2.0, addEmitterInterval: Double = 0.1) {
self.text = text
self.font = font
self.emitterName = emitterName
self.marginHorizontal = marginHorizontal
self.animationDuration = animationDuration
self.addEmitterInterval = addEmitterInterval
super.init()
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
_childEmitters.removeAll()
let addChildEmittersCount = Int(animationDuration/addEmitterInterval) > 0 ? Int(animationDuration/addEmitterInterval) : 0
for character in text {
guard let path = UIBezierPath.init(character: character, font: font) else { continue }
let characterNode = SKNode()
characterNode.position.x = _width
addChild(characterNode)
_width += marginHorizontal + path.bounds.width
path.cgPath.getPaths().forEach { path in
let drawingEmitter = getEmitter()
characterNode.addChild(drawingEmitter)
drawingEmitter.run(.sequence([
.follow(path, duration: animationDuration),
.run { drawingEmitter.particleBirthRate = 0 }
]))
drawingEmitter.run(.repeat(.sequence([
.wait(forDuration: addEmitterInterval),
.run {
let childEmitter = self.getEmitter()
self._childEmitters.append(childEmitter)
childEmitter.position = drawingEmitter.position
characterNode.addChild(childEmitter)
}]
), count: addChildEmittersCount))
}
}
}
public func fadeOutChildEmitters() {
_childEmitters.forEach { emitter in
let randomWait = 1/Double(arc4random_uniform(10)+1)
emitter.run(.sequence([
.wait(forDuration: randomWait),
.run { emitter.particleBirthRate = 0 }
]))
}
}
private func getEmitter() -> SKEmitterNode {
guard let emitter = SKEmitterNode(fileNamed: emitterName) else {
fatalError("ERROR: Emitter with name: \(emitterName) could not be created.")
}
return emitter
}
}
| 36.320988 | 167 | 0.599932 |
d5b3fd9fb9fc41537f069bbc72fc0ef823746146 | 2,606 | //
// GrowingTextViewController.swift
// edX
//
// Created by Akiva Leffert on 8/17/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
/// Supports a text view nested inside of a scroll view, where the text view is sized to fit its entire content.
/// Updates the ``contentOffset`` of the scroll view to track typing
/// and the ``contentSize`` of the scroll view to track resizing.
///
/// To use:
///
/// 1. Set up your view so that its height depends on the text view's ``intrinsicContentSize``.
///
/// 2. Create one of these controllers.
///
/// 3. Call the public methods on this from your view controller as described on each method.
open class GrowingTextViewController {
fileprivate var scrollView : UIScrollView?
fileprivate var textView : UITextView?
fileprivate var bottomView : UIView?
fileprivate var textUpdating = false
/// Call from viewDidLoad
open func setupWithScrollView(_ scrollView : UIScrollView, textView : UITextView, bottomView : UIView) {
textView.isScrollEnabled = false
self.scrollView = scrollView
self.textView = textView
self.bottomView = bottomView
}
/// Call from inside textViewDidChange: in your text view's delegate
open func handleTextChange() {
textUpdating = true
self.scrollView?.setNeedsLayout()
self.scrollView?.layoutIfNeeded()
textUpdating = false
}
/// Call from viewDidLayoutSubviews in your view controller
open func scrollToVisible() {
if let scrollView = self.scrollView,
let textView = self.textView,
let range = textView.selectedTextRange
{
let rect = textView.caretRect(for: range.end)
let scrollRect = scrollView.convert(rect, from:textView)
let offsetRect = scrollRect.offsetBy(dx: 0, dy: 10) // add a little margin for the text
scrollView.scrollRectToVisible(offsetRect, animated: true)
if let bottomView = self.bottomView {
// If we just made a new line of text, the bottom position might not actually be updated
// yet when we get here
// So, wait until the next run loop to update the contentSize.
DispatchQueue.main.async {
let buttonFrame = scrollView.convert(bottomView.bounds, from:bottomView)
scrollView.contentSize = CGSize(width: scrollView.bounds.size.width, height: buttonFrame.maxY + StandardHorizontalMargin)
}
}
}
}
}
| 36.704225 | 141 | 0.649271 |
fe6a09507c5deba628e1c06a679543ecaf46e500 | 69 | extension String {
var doubleValue: Double? { Double(self) }
}
| 11.5 | 45 | 0.652174 |
14ca3da9929d42c737160bcc1ffe91ed85638379 | 541 | //
// MockRequestable.swift
// iOSBackbone
//
// Created by Giorgy Gunawan on 8/10/20.
// Copyright © 2020 joji. All rights reserved.
//
import Foundation
@testable import iOSBackbone
struct MockRequestable: Requestable {
typealias ResponseType = MockCodable
var format: RequestFormat
init(format: RequestFormat) {
self.format = RequestFormat(baseURL: "", path: format.path, method: format.method, parameters: format.parameters, headerParameters: format.headerParameters, stubFileName: format.stubFileName)
}
}
| 28.473684 | 199 | 0.739372 |
14738cf5079520ecaf86c28924781723f96d6e4e | 14,163 | //
// ViewController.swift
// AMLoginSingup
//
// Created by amir on 10/11/16.
// Copyright © 2016 amirs.eu. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Locksmith
enum AMLoginSignupViewMode {
case login
case signup
}
class LoginViewController: UIViewController {
let animationDuration = 0.25
var mode:AMLoginSignupViewMode = .signup
var domain: String?
var loginURL: String?
var signUpURL: String?
let sharedContainer = UserDefaults(suiteName: "group.YAN.com.apollomillennium")
//MARK: - background image constraints
@IBOutlet weak var backImageLeftConstraint: NSLayoutConstraint!
@IBOutlet weak var backImageBottomConstraint: NSLayoutConstraint!
//MARK: - login views and constrains
@IBOutlet weak var loginView: UIView!
@IBOutlet weak var loginContentView: UIView!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var loginButtonVerticalCenterConstraint: NSLayoutConstraint!
@IBOutlet weak var loginButtonTopConstraint: NSLayoutConstraint!
@IBOutlet weak var loginWidthConstraint: NSLayoutConstraint!
//MARK: - signup views and constrains
@IBOutlet weak var signupView: UIView!
@IBOutlet weak var signupContentView: UIView!
@IBOutlet weak var signupButton: UIButton!
@IBOutlet weak var signupButtonVerticalCenterConstraint: NSLayoutConstraint!
@IBOutlet weak var signupButtonTopConstraint: NSLayoutConstraint!
//MARK: - logo and constrains
@IBOutlet weak var logoView: UIView!
@IBOutlet weak var logoTopConstraint: NSLayoutConstraint!
@IBOutlet weak var logoHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var logoBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var logoButtomInSingupConstraint: NSLayoutConstraint!
@IBOutlet weak var logoCenterConstraint: NSLayoutConstraint!
@IBOutlet weak var forgotPassTopConstraint: NSLayoutConstraint!
@IBOutlet weak var socialsView: UIView!
//MARK: - input views
@IBOutlet weak var loginEmailInputView: AMInputView!
@IBOutlet weak var loginPasswordInputView: AMInputView!
@IBOutlet weak var signupEmailInputView: AMInputView!
@IBOutlet weak var signupPasswordInputView: AMInputView!
@IBOutlet weak var signupPasswordConfirmInputView: AMInputView!
//MARK: - controller
override func viewDidLoad() {
super.viewDidLoad()
self.domain = sharedContainer?.value(forKey: "domain") as? String ?? "https://apollomillenniumcapital.com"
self.loginURL = domain! + "/login"
self.signUpURL = domain! + "/register"
// set view to login mode
toggleViewMode(animated: false)
//add keyboard notification
NotificationCenter.default.addObserver(self, selector: #selector(keyboarFrameChange(notification:)), name: .UIKeyboardWillChangeFrame, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: .UIApplicationDidBecomeActive, object: nil)
}
@objc private func appDidBecomeActive() {
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// showDialog()
}
private func showDialog() {
// var alertController:UIAlertController?
// alertController = UIAlertController(title: "Enter server address",
// message: "use IP address and port",
// preferredStyle: .alert)
//
// alertController!.addTextField(
// configurationHandler: {(textField: UITextField!) in
// textField.placeholder = "http://localhost:3000"
// })
// var enteredText: String?
// let action = UIAlertAction(title: "Submit",
// style: UIAlertActionStyle.default,
// handler: { //[weak self]
// (paramAction:UIAlertAction!) in
// if let textFields = alertController?.textFields{
// let theTextFields = textFields as [UITextField]
// enteredText = theTextFields[0].text
// }
// if enteredText!.count > 0 {
// __domain__ = enteredText!
// }
// print(enteredText!)
//
// })
//
// alertController?.addAction(action)
// self.present(alertController!,
// animated: true,
// completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func verifyLogin(email: String, password: String, callback: @escaping (JSON) -> Void) -> Void {
let param: Parameters = ["username": email, "password": password]
Alamofire.request(self.loginURL!, method: .post, parameters: param)
.responseJSON(completionHandler: { (response: DataResponse) -> Void in
let json = JSON(data: response.data!)
if json["status"] == "success" {
callback(json)
}
else {
print("bad login")
}
})
}
//MARK: - button actions
@IBAction func loginButtonTouchUpInside(_ sender: AnyObject) {
if mode == .signup {
toggleViewMode(animated: true)
}else{
print("Email:\(String(describing: loginEmailInputView.textFieldView.text)) Password:\(String(describing: loginPasswordInputView.textFieldView.text))")
let email = loginEmailInputView.textFieldView.text
let password = loginPasswordInputView.textFieldView.text
verifyLogin(email: email!, password: password!) { json in
print("token", json["token"])
let token = json["token"].string
let userId = json["userId"].string
//save token and userId to userDefault
self.updateUserDefaultsWithCredentials(email: email!, password: password!, token: token!, userId: userId!)
// self.updateKeyChain(email: email!, password: password!, token: token!, userId: userId!)
self.presentNextVC()
}
}
}
private func updateUserDefaultsWithCredentials(email: String, password: String, token: String, userId: String) {
sharedContainer?.setValue(token, forKey: "token")
sharedContainer?.setValue(userId, forKey: "userId")
sharedContainer?.setValue(email, forKey: "email")
sharedContainer?.setValue(password, forKey: "password")
}
private func presentNextVC() {
// let tab = TabViewController()
let nextVC = mainYanShareVC
let navVC = UINavigationController.init(rootViewController: nextVC!)
navVC.viewControllers = [nextVC!]
navVC.navigationBar.topItem?.title = "Yan"
self.present(navVC, animated: true, completion: nil)
}
private func submitSignUp(email: String, password: String, callback: @escaping (JSON) -> Void) {
let param: Parameters = ["username": email, "password": password]
Alamofire.request(self.signUpURL!, method: .post, parameters: param)
.responseJSON(completionHandler: { (response: DataResponse) -> Void in
let json = JSON(data: response.data!)
if json["status"] == "success" {
callback(json)
}
else {
print("bad sign up")
// TODO:
}
})
}
@IBAction func signupButtonTouchUpInside(_ sender: AnyObject) {
if mode == .login {
toggleViewMode(animated: true)
}else{
//TODO: signup by this data
NSLog("Email:\(String(describing: signupEmailInputView.textFieldView.text)) Password:\(String(describing: signupPasswordInputView.textFieldView.text)), PasswordConfirm:\(String(describing: signupPasswordConfirmInputView.textFieldView.text))")
let email = signupEmailInputView.textFieldView.text
let password = signupPasswordInputView.textFieldView.text
let passwordConfirmation = signupPasswordConfirmInputView.textFieldView.text
if password != passwordConfirmation {
print("password does not match with confirmation")
// TODO
}
submitSignUp(email: email!, password: password!) { json in
print("token", json["token"])
let token = json["token"].string
let userId = json["userId"].string
self.updateUserDefaultsWithCredentials(email: email!, password: password!, token: token!, userId: userId!)
// self.updateKeyChain(email: email!, password: password!, token: token!, userId: userId!)
self.presentNextVC()
}
}
}
private func updateKeyChain(email: String, password: String, token: String, userId: String) {
do {
try Locksmith.saveData(data: ["email": email, "password": password, "token": token, "userId": userId], forUserAccount: "Yan")
}
catch let e {
print(e.localizedDescription)
}
}
//MARK: - toggle view
func toggleViewMode(animated:Bool){
// toggle mode
mode = mode == .login ? .signup:.login
// set constraints changes
backImageLeftConstraint.constant = mode == .login ? 0:-self.view.frame.size.width
loginWidthConstraint.isActive = mode == .signup ? true:false
logoCenterConstraint.constant = (mode == .login ? -1:1) * (loginWidthConstraint.multiplier * self.view.frame.size.width)/2
loginButtonVerticalCenterConstraint.priority = mode == .login ? 300:900
signupButtonVerticalCenterConstraint.priority = mode == .signup ? 300:900
//animate
self.view.endEditing(true)
UIView.animate(withDuration:animated ? animationDuration:0) {
//animate constraints
self.view.layoutIfNeeded()
//hide or show views
self.loginContentView.alpha = self.mode == .login ? 1:0
self.signupContentView.alpha = self.mode == .signup ? 1:0
// rotate and scale login button
let scaleLogin:CGFloat = self.mode == .login ? 1:0.4
let rotateAngleLogin:CGFloat = self.mode == .login ? 0:CGFloat(-M_PI_2)
var transformLogin = CGAffineTransform(scaleX: scaleLogin, y: scaleLogin)
transformLogin = transformLogin.rotated(by: rotateAngleLogin)
self.loginButton.transform = transformLogin
// rotate and scale signup button
let scaleSignup:CGFloat = self.mode == .signup ? 1:0.4
let rotateAngleSignup:CGFloat = self.mode == .signup ? 0:CGFloat(-M_PI_2)
var transformSignup = CGAffineTransform(scaleX: scaleSignup, y: scaleSignup)
transformSignup = transformSignup.rotated(by: rotateAngleSignup)
self.signupButton.transform = transformSignup
}
}
//MARK: - keyboard
func keyboarFrameChange(notification:NSNotification){
let userInfo = notification.userInfo as! [String:AnyObject]
// get top of keyboard in view
let topOfKetboard = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue .origin.y
// get animation curve for animate view like keyboard animation
var animationDuration:TimeInterval = 0.25
var animationCurve:UIViewAnimationCurve = .easeOut
if let animDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber {
animationDuration = animDuration.doubleValue
}
if let animCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
animationCurve = UIViewAnimationCurve.init(rawValue: animCurve.intValue)!
}
// check keyboard is showing
let keyboardShow = topOfKetboard != self.view.frame.size.height
//hide logo in little devices
let hideLogo = self.view.frame.size.height < 667
// set constraints
backImageBottomConstraint.constant = self.view.frame.size.height - topOfKetboard
logoTopConstraint.constant = keyboardShow ? (hideLogo ? 0:20):50
logoHeightConstraint.constant = keyboardShow ? (hideLogo ? 0:40):60
logoBottomConstraint.constant = keyboardShow ? 20:32
logoButtomInSingupConstraint.constant = keyboardShow ? 20:32
forgotPassTopConstraint.constant = keyboardShow ? 30:45
loginButtonTopConstraint.constant = keyboardShow ? 25:30
signupButtonTopConstraint.constant = keyboardShow ? 23:35
loginButton.alpha = keyboardShow ? 1:0.7
signupButton.alpha = keyboardShow ? 1:0.7
// animate constraints changes
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(animationDuration)
UIView.setAnimationCurve(animationCurve)
self.view.layoutIfNeeded()
UIView.commitAnimations()
}
//MARK: - hide status bar in swift3
override var prefersStatusBarHidden: Bool {
return true
}
override func viewWillAppear(_ animated: Bool) {
}
}
| 38.80274 | 254 | 0.601991 |
1c5e6dc0c0c2ad2fd34d6d022520357e8c73068d | 2,021 | //
// ==----------------------------------------------------------------------== //
//
// CalendarScreen.swift
//
// Created by Trevor Beasty on 10/21/19.
//
//
// This source file is part of the Lasso open source project
//
// https://github.com/ww-tech/lasso
//
// Copyright © 2019-2020 WW International, Inc.
//
// ==----------------------------------------------------------------------== //
//
import Lasso
import WWLayout
enum CalendarScreenModule: ScreenModule {
struct State: Equatable {
var selectedDate = Date()
}
enum Action: Equatable {
case didSelectDate(Date)
}
enum Output: Equatable { }
static var defaultInitialState: State { return State() }
static func createScreen(with store: CalendarStore) -> Screen {
let controller = CalendarController(store: store.asViewStore())
return Screen(store, controller)
}
}
class CalendarStore: LassoStore<CalendarScreenModule> {
override func handleAction(_ action: CalendarScreenModule.Action) {
switch action {
case .didSelectDate(let date):
update { $0.selectedDate = date }
}
}
}
class CalendarController: UIViewController, LassoView {
let store: CalendarScreenModule.ViewStore
private let datePicker = UIDatePicker()
init(store: CalendarScreenModule.ViewStore) {
self.store = store
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) { fatalError() }
override func viewDidLoad() {
super.viewDidLoad()
setUpView()
bind()
}
private func setUpView() {
view.addSubview(datePicker)
datePicker.layout
.fill(.superview)
datePicker.datePickerMode = .date
}
private func bind() {
store.observeState(\.selectedDate) { [weak self] (date) in
self?.datePicker.setDate(date, animated: true)
}
datePicker.bindDateChange(to: store) { .didSelectDate($0) }
}
}
| 22.707865 | 80 | 0.581395 |
627c89d6e382c0c991fb37930cab8ef1307a69b9 | 1,574 | //
// ViperAssembly.swift
// ArchitectureHW
//
// Created by u17716644 on 12/08/2019.
// Copyright © 2019 Maksim Ivanov. All rights reserved.
//
import UIKit
class ViperAssembly {
static func assembleAnimalListView() -> UIViewController {
let animalListCollectionViewDataSource = AnimalListCollectionViewDataSource()
let animalListCollectionViewDelegate = AnimalListCollectionViewDelegate()
let animalListView = AnimalListViewController()
animalListView.animalListCollectionViewDataSource = animalListCollectionViewDataSource
animalListView.animalListCollectionViewDelegate = animalListCollectionViewDelegate
let animalListPresenter = AnimalListPresenter()
let animalListInteractor = AnimalListInteractor()
animalListPresenter.animalListView = animalListView
animalListPresenter.animalListProvider = animalListInteractor
animalListInteractor.output = animalListPresenter
animalListView.presenter = animalListPresenter
return animalListView
}
static func assembleAnimalDetails(animal: Animal?) -> UIViewController {
// Model: animal
// View
let animalDetailsViewController = AnimalDetailsViewController()
// Presenter
let animalDetailsPresenter = AnimalDetailsPresenter(animalDetailsViewController, animal)
animalDetailsViewController.presenter = animalDetailsPresenter
return animalDetailsViewController
}
}
| 32.791667 | 96 | 0.714104 |
fb5c608c0518332bd2b704e06b6ee286257bef3f | 12,694 | //
// STPPaymentIntentParams.swift
// Stripe
//
// Created by Daniel Jackson on 7/3/18.
// Copyright © 2018 Stripe, Inc. All rights reserved.
//
import Foundation
/// An object representing parameters used to confirm a PaymentIntent object.
/// A PaymentIntent must have a PaymentMethod or Source associated in order to successfully confirm it.
/// That PaymentMethod or Source can either be:
/// - created during confirmation, by passing in a `STPPaymentMethodParams` or `STPSourceParams` object in the `paymentMethodParams` or `sourceParams` field
/// - a pre-existing PaymentMethod or Source can be associated by passing its id in the `paymentMethodId` or `sourceId` field
/// - or already set via your backend, either when creating or updating the PaymentIntent
/// - seealso: https://stripe.com/docs/api#confirm_payment_intent
public class STPPaymentIntentParams: NSObject {
/// Initialize this `STPPaymentIntentParams` with a `clientSecret`, which is the only required
/// field.
/// - Parameter clientSecret: the client secret for this PaymentIntent
@objc
public init(clientSecret: String) {
self.clientSecret = clientSecret
super.init()
}
@objc convenience override init() {
self.init(clientSecret: "")
}
/// The Stripe id of the PaymentIntent, extracted from the clientSecret.
@objc public var stripeId: String? {
return STPPaymentIntent.id(fromClientSecret: clientSecret)
}
/// The client secret of the PaymentIntent. Required
@objc public var clientSecret: String
/// Provide a supported `STPPaymentMethodParams` object, and Stripe will create a
/// PaymentMethod during PaymentIntent confirmation.
/// @note alternative to `paymentMethodId`
@objc public var paymentMethodParams: STPPaymentMethodParams?
/// Provide an already created PaymentMethod's id, and it will be used to confirm the PaymentIntent.
/// @note alternative to `paymentMethodParams`
@objc public var paymentMethodId: String?
/// Provide a supported `STPSourceParams` object into here, and Stripe will create a Source
/// during PaymentIntent confirmation.
/// @note alternative to `sourceId`
@objc public var sourceParams: STPSourceParams?
/// Provide an already created Source's id, and it will be used to confirm the PaymentIntent.
/// @note alternative to `sourceParams`
@objc public var sourceId: String?
/// Email address that the receipt for the resulting payment will be sent to.
@objc public var receiptEmail: String?
/// `@YES` to save this PaymentIntent’s PaymentMethod or Source to the associated Customer,
/// if the PaymentMethod/Source is not already attached.
/// This should be a boolean NSNumber, so that it can be `nil`
@objc public var savePaymentMethod: NSNumber?
/// The URL to redirect your customer back to after they authenticate or cancel
/// their payment on the payment method’s app or site.
/// This should probably be a URL that opens your iOS app.
@objc public var returnURL: String?
/// When provided, this property indicates how you intend to use the payment method that your customer provides after the current payment completes.
/// If applicable, additional authentication may be performed to comply with regional legislation or network rules required to enable the usage of the same payment method for additional payments.
public var setupFutureUsage: STPPaymentIntentSetupFutureUsage?
/// When provided, this property indicates how you intend to use the payment method that your customer provides after the current payment completes.
/// If applicable, additional authentication may be performed to comply with regional legislation or network rules required to enable the usage of the same payment method for additional payments.
/// This property should only be used in Objective-C. In Swift, use `setupFutureUsage`.
/// - seealso: STPPaymentIntentSetupFutureUsage for more details on what values you can provide.
@available(swift, obsoleted: 1.0, renamed: "setupFutureUsage")
@objc(setupFutureUsage) public var setupFutureUsage_objc: NSNumber? {
get {
setupFutureUsage?.rawValue as NSNumber?
}
set {
if let newValue = newValue {
setupFutureUsage = STPPaymentIntentSetupFutureUsage(rawValue: Int(truncating: newValue))
} else {
setupFutureUsage = nil
}
}
}
/// A boolean number to indicate whether you intend to use the Stripe SDK's functionality to handle any PaymentIntent next actions.
/// If set to false, STPPaymentIntent.nextAction will only ever contain a redirect url that can be opened in a webview or mobile browser.
/// When set to true, the nextAction may contain information that the Stripe SDK can use to perform native authentication within your
/// app.
@objc public var useStripeSDK: NSNumber?
internal var _mandateData: STPMandateDataParams?
/// Details about the Mandate to create.
/// @note If this value is null and the (self.paymentMethod.type == STPPaymentMethodTypeSEPADebit | | self.paymentMethodParams.type == STPPaymentMethodTypeAUBECSDebit || self.paymentMethodParams.type == STPPaymentMethodTypeBacsDebit) && self.mandate == nil`, the SDK will set this to an internal value indicating that the mandate data should be inferred from the current context.
@objc public var mandateData: STPMandateDataParams? {
set {
_mandateData = newValue
}
get {
if let _mandateData = _mandateData {
return _mandateData
}
switch paymentMethodParams?.type {
case .AUBECSDebit, .bacsDebit, .bancontact, .iDEAL, .SEPADebit, .EPS, .sofort:
// Create default infer from client mandate_data
let onlineParams = STPMandateOnlineParams(ipAddress: "", userAgent: "")
onlineParams.inferFromClient = NSNumber(value: true)
if let customerAcceptance = STPMandateCustomerAcceptanceParams(
type: .online, onlineParams: onlineParams)
{
return STPMandateDataParams(customerAcceptance: customerAcceptance)
}
default: break
}
return nil
}
}
/// Options to update the associated PaymentMethod during confirmation.
/// - seealso: STPConfirmPaymentMethodOptions
@objc public var paymentMethodOptions: STPConfirmPaymentMethodOptions?
/// Shipping information.
@objc public var shipping: STPPaymentIntentShippingDetailsParams?
/// The URL to redirect your customer back to after they authenticate or cancel
/// their payment on the payment method’s app or site.
/// This property has been renamed to `returnURL` and deprecated.
@available(*, deprecated, renamed: "returnURL")
@objc public var returnUrl: String? {
get {
return returnURL
}
set(returnUrl) {
returnURL = returnUrl
}
}
/// `@YES` to save this PaymentIntent’s Source to the associated Customer,
/// if the Source is not already attached.
/// This should be a boolean NSNumber, so that it can be `nil`
/// This property has been renamed to `savePaymentMethod` and deprecated.
@available(*, deprecated, renamed: "savePaymentMethod")
@objc public var saveSourceToCustomer: NSNumber? {
get {
return savePaymentMethod
}
set(saveSourceToCustomer) {
savePaymentMethod = saveSourceToCustomer
}
}
/// :nodoc:
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
/// Provide an STPPaymentResult from STPPaymentContext, and this will populate
/// the proper field (either paymentMethodId or paymentMethodParams) for your PaymentMethod.
@objc
public func configure(with paymentResult: STPPaymentResult) {
if let paymentMethod = paymentResult.paymentMethod {
paymentMethodId = paymentMethod.stripeId
} else if let params = paymentResult.paymentMethodParams {
paymentMethodParams = params
}
}
/// :nodoc:
@objc public override var description: String {
let props: [String] = [
// Object
String(format: "%@: %p", NSStringFromClass(STPPaymentIntentParams.self), self),
// Identifier
"stripeId = \(String(describing: stripeId))",
// PaymentIntentParams details (alphabetical)
"clientSecret = \((clientSecret.count > 0) ? "<redacted>" : "")",
"receiptEmail = \(String(describing: receiptEmail))",
"returnURL = \(String(describing: returnURL))",
"savePaymentMethod = \(String(describing: savePaymentMethod?.boolValue))",
"setupFutureUsage = \(String(describing: setupFutureUsage))",
"shipping = \(String(describing: shipping))",
"useStripeSDK = \(String(describing: useStripeSDK?.boolValue))",
// Source
"sourceId = \(String(describing: sourceId))",
"sourceParams = \(String(describing: sourceParams))",
// PaymentMethod
"paymentMethodId = \(String(describing: paymentMethodId))",
"paymentMethodParams = \(String(describing: paymentMethodParams))",
// Mandate
"mandateData = \(String(describing: mandateData))",
// PaymentMethodOptions
"paymentMethodOptions = @\(String(describing: paymentMethodOptions))",
// Additional params set by app
"additionalAPIParameters = \(additionalAPIParameters)",
]
return "<\(props.joined(separator: "; "))>"
}
static internal let isClientSecretValidRegex: NSRegularExpression? = try? NSRegularExpression(
pattern: "^pi_[^_]+_secret_[^_]+$", options: [])
class internal func isClientSecretValid(_ clientSecret: String) -> Bool {
return
(isClientSecretValidRegex?.numberOfMatches(
in: clientSecret,
options: .anchored,
range: NSRange(location: 0, length: clientSecret.count))) == 1
}
}
// MARK: - STPFormEncodable
extension STPPaymentIntentParams: STPFormEncodable {
@objc internal var setupFutureUsageRawString: String? {
return setupFutureUsage?.stringValue
}
@objc
public class func rootObjectName() -> String? {
return nil
}
@objc
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:clientSecret)): "client_secret",
NSStringFromSelector(#selector(getter:paymentMethodParams)): "payment_method_data",
NSStringFromSelector(#selector(getter:paymentMethodId)): "payment_method",
NSStringFromSelector(#selector(getter:setupFutureUsageRawString)): "setup_future_usage",
NSStringFromSelector(#selector(getter:sourceParams)): "source_data",
NSStringFromSelector(#selector(getter:sourceId)): "source",
NSStringFromSelector(#selector(getter:receiptEmail)): "receipt_email",
NSStringFromSelector(#selector(getter:savePaymentMethod)): "save_payment_method",
NSStringFromSelector(#selector(getter:returnURL)): "return_url",
NSStringFromSelector(#selector(getter:useStripeSDK)): "use_stripe_sdk",
NSStringFromSelector(#selector(getter:mandateData)): "mandate_data",
NSStringFromSelector(#selector(getter:paymentMethodOptions)): "payment_method_options",
NSStringFromSelector(#selector(getter:shipping)): "shipping",
]
}
}
// MARK: - NSCopying
extension STPPaymentIntentParams: NSCopying {
/// :nodoc:
@objc
public func copy(with zone: NSZone? = nil) -> Any {
let copy = STPPaymentIntentParams(clientSecret: clientSecret)
copy.paymentMethodParams = paymentMethodParams
copy.paymentMethodId = paymentMethodId
copy.sourceParams = sourceParams
copy.sourceId = sourceId
copy.receiptEmail = receiptEmail
copy.savePaymentMethod = savePaymentMethod
copy.returnURL = returnURL
copy.setupFutureUsage = setupFutureUsage
copy.useStripeSDK = useStripeSDK
copy.mandateData = mandateData
copy.paymentMethodOptions = paymentMethodOptions
copy.shipping = shipping
copy.additionalAPIParameters = additionalAPIParameters
return copy
}
}
| 45.661871 | 383 | 0.680164 |
4638ec19db03ef5ef5d4757343df957216409c03 | 1,093 | //
// Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.
// The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
//
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and limitations under the License.
//
import Foundation
extension IDXClient.Message.Collection: Collection {
public typealias Index = Int
public typealias Element = IDXClient.Message
public var startIndex: Index {
messages.startIndex
}
public var endIndex: Index {
messages.endIndex
}
public subscript(index: Index) -> Element {
messages[index]
}
public func index(after i: Index) -> Index {
messages.index(after: i)
}
}
| 31.228571 | 120 | 0.703568 |
f56c98310cbbef3ec2c0af386473f976d9481d9c | 3,374 | // Copyright © 2021 Saleem Abdulrasool <[email protected]>
// SPDX-License-Identifier: BSD-3-Clause
import XCTest
import WinSDK
import struct Foundation.Date
@testable import SwiftWin32
final class DateTests: XCTestCase {
func testFileTimeConstruction() {
XCTAssertEqual(FILETIME(timeIntervalSince1970: 0).timeIntervalSince1970, 0)
}
func testUnixEpoch() {
let ftUnixEpoch: FILETIME = FILETIME(timeIntervalSince1970: 0)
XCTAssertEqual(ftUnixEpoch.dwLowDateTime, 3577643008)
XCTAssertEqual(ftUnixEpoch.dwHighDateTime, 27111902)
let stUnixEpoch: SYSTEMTIME = SYSTEMTIME(ftUnixEpoch)
XCTAssertEqual(stUnixEpoch.wYear, 1970)
XCTAssertEqual(stUnixEpoch.wMonth, 1)
XCTAssertEqual(stUnixEpoch.wDayOfWeek, 4)
XCTAssertEqual(stUnixEpoch.wDay, 1)
XCTAssertEqual(stUnixEpoch.wHour, 0)
XCTAssertEqual(stUnixEpoch.wMinute, 0)
XCTAssertEqual(stUnixEpoch.wSecond, 0)
XCTAssertEqual(stUnixEpoch.wMilliseconds, 0)
}
func testSystemTimeConversion() {
let stTimeStamp: SYSTEMTIME =
SYSTEMTIME(wYear: 2020, wMonth: 11, wDayOfWeek: 0, wDay: 7,
wHour: 0, wMinute: 0, wSecond: 0, wMilliseconds: 0)
XCTAssertEqual(FILETIME(stTimeStamp).timeIntervalSince1970,
1604707200)
}
func testFileTimeConversion() {
let ftTimeStamp: FILETIME = FILETIME(timeIntervalSince1970: 1604707200)
let stTimeStamp: SYSTEMTIME = SYSTEMTIME(ftTimeStamp)
XCTAssertEqual(stTimeStamp.wYear, 2020)
XCTAssertEqual(stTimeStamp.wMonth, 11)
// We cannot check the day of week because it is ignored on the conversion
// and we are going from UTC to local time zone to UTC, which changes the
// day.
/* XCTAssertEqual(stTimeStamp.wDayOfWeek, 0) */
XCTAssertEqual(stTimeStamp.wDay, 7)
XCTAssertEqual(stTimeStamp.wHour, 0)
XCTAssertEqual(stTimeStamp.wMinute, 0)
XCTAssertEqual(stTimeStamp.wSecond, 0)
XCTAssertEqual(stTimeStamp.wMilliseconds, 0)
}
func testRoundTrip() {
let ftSystemTimeInitial: SYSTEMTIME =
SYSTEMTIME(wYear: 2020, wMonth: 11, wDayOfWeek: 6, wDay: 7,
wHour: 0, wMinute: 0, wSecond: 0, wMilliseconds: 0)
let ftSystemTimeConverted: SYSTEMTIME =
SYSTEMTIME(FILETIME(ftSystemTimeInitial))
XCTAssertEqual(ftSystemTimeInitial.wYear, ftSystemTimeConverted.wYear)
XCTAssertEqual(ftSystemTimeInitial.wMonth, ftSystemTimeConverted.wMonth)
// We cannot check the day of week because it is ignored on the conversion
// and we are going from UTC to local time zone to UTC, which changes the
// day.
/* XCTAssertEqual(ftSystemTimeInitial.wDayOfWeek, ftSystemTimeConverted.wDayOfWeek) */
XCTAssertEqual(ftSystemTimeInitial.wDay, ftSystemTimeConverted.wDay)
XCTAssertEqual(ftSystemTimeInitial.wHour, ftSystemTimeConverted.wHour)
XCTAssertEqual(ftSystemTimeInitial.wMinute, ftSystemTimeConverted.wMinute)
XCTAssertEqual(ftSystemTimeInitial.wSecond, ftSystemTimeConverted.wSecond)
XCTAssertEqual(ftSystemTimeInitial.wMilliseconds, ftSystemTimeConverted.wMilliseconds)
}
static var allTests = [
("testFileTimeConstruction", testFileTimeConstruction),
("testUnixEpoch", testUnixEpoch),
("testSystemTimeConversion", testSystemTimeConversion),
("testFileTimeConversion", testFileTimeConversion),
("testRoundTrip", testRoundTrip),
]
}
| 38.781609 | 90 | 0.75163 |
487978f3b05475a2c0ce19658d73be8cec1da295 | 157 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(RuleKitTests.allTests),
]
}
#endif
| 15.7 | 45 | 0.66879 |
1f01034c7a63d520ddc3597f7d6aa0685d187dad | 20,612 | //
// TrackProgress.swift
// DEPNotify
//
// Created by Joel Rennich on 2/16/17.
// Copyright © 2017 Orchard & Grove Inc. All rights reserved.
// FileWave log processing added by Damon O'Hare and Dan DeRusha
// Additional Jamf log processing added by Zack Thompson
import Foundation
enum StatusState {
case start
case done
}
enum OtherLogs {
static let jamf = "/var/log/jamf.log"
static let filewave = "/var/log/fwcld.log"
static let munki = "/Library/Managed Installs/Logs/ManagedSoftwareUpdate.log"
static let none = ""
}
class TrackProgress: NSObject {
// set up some defaults
var path: String
@objc dynamic var statusText: String
@objc dynamic var command: String
var status: StatusState
let task = Process()
let fm = FileManager()
var additionalPath = OtherLogs.none
var fwDownloadsStarted = false
var filesets = Set<String>()
// init
override init() {
path = "/var/tmp/depnotify.log"
for arg in 0...(CommandLine.arguments.count - 1) {
switch CommandLine.arguments[arg] {
case "-path" :
guard (CommandLine.arguments.count >= arg + 1) else { continue }
path = CommandLine.arguments[arg + 1]
case "-jamf" :
additionalPath = OtherLogs.jamf
case "-munki" :
additionalPath = OtherLogs.munki
case "-filewave" :
additionalPath = OtherLogs.filewave
statusText = "Downloading Filewave configuration"
default :
break
}
}
statusText = "Starting configuration"
command = ""
status = .start
task.launchPath = "/usr/bin/tail"
task.arguments = ["-f", path, additionalPath]
}
// watch for updates and post them
func run() {
// check to make sure the file exists
if !fm.fileExists(atPath: path) {
// need to make the file
fm.createFile(atPath: path, contents: nil, attributes: nil)
}
let pipe = Pipe()
task.standardOutput = pipe
let outputHandle = pipe.fileHandleForReading
outputHandle.waitForDataInBackgroundAndNotify()
var dataAvailable : NSObjectProtocol!
dataAvailable = NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable,
object: outputHandle, queue: nil) { notification -> Void in
let data = pipe.fileHandleForReading.availableData
if data.count > 0 {
if let str = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
//print("Task sent some data: \(str)")
self.processCommands(commands: str as String)
}
outputHandle.waitForDataInBackgroundAndNotify()
} else {
NotificationCenter.default.removeObserver(dataAvailable)
}
}
var dataReady : NSObjectProtocol!
dataReady = NotificationCenter.default.addObserver(forName: Process.didTerminateNotification,
object: pipe.fileHandleForReading, queue: nil) { notification -> Void in
NSLog("Task terminated!")
NotificationCenter.default.removeObserver(dataReady)
}
task.launch()
statusText = "Reticulating splines..."
}
func processCommands(commands: String) {
let allCommands = commands.components(separatedBy: "\n")
for line in allCommands {
switch line.components(separatedBy: " ").first! {
case "Status:" :
statusText = line.replacingOccurrences(of: "Status: ", with: "")
case "Command:" :
command = line.replacingOccurrences(of: "Command: ", with: "")
default:
switch additionalPath {
case OtherLogs.jamf :
// Define Variables
struct globalVariables {
static var fileVaultState = "Disabled"
static var failedReason = "Unable to determine..."
}
let actions = ["Installing", "Executing Policy", "Downloading", "Successfully installed", "failed", "Error:", "FileVault", "Encrypt", "Encryption", "DEPNotify Quit"]
// Reads a file and returns the lines -- used to get the item and reason an install failed.
func readFile(path: String) -> Array<String> {
do {
let contents:NSString = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue)
let trimmed:String = contents.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
let lines:Array<String> = NSString(string: trimmed).components(separatedBy: .newlines)
return lines
} catch {
NSLog("Unable to read file: \(path)");
return [String]()
}
}
for action in actions where line.contains(action) {
if (!(line.range(of: "flat package") != nil)) && (!(line.range(of: "bom") != nil)) && (!(line.range(of: "an Apple package...") != nil)) && (!(line.range(of: "com.jamfsoftware.task.errors") != nil)) {
switch true {
case line.range(of: "Downloading") != nil:
let lineDownloadingItem = line.components(separatedBy: "CasperShare/")
let getDownloadingItem = lineDownloadingItem[1]
NSLog(getDownloadingItem)
let pattern = "(%20)" // If you have prefixes on packages that you'd like to remove, you can add the pattern here, like so: "(%20)|(Prefix.Postfix)|(ExStr)"
let removeRegex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let downloadingItem = removeRegex.stringByReplacingMatches(in: getDownloadingItem, options: [], range: NSRange(location: 0, length: getDownloadingItem.count), withTemplate: "")
if !(downloadingItem.isEmpty) {
NSLog("Downloading: \(downloadingItem)")
statusText = "Downloading: \(downloadingItem)"
}
case line.range(of: "Installing") != nil:
let lineInstallItem = line.components(separatedBy: "Installing ")
let getInstallItem = lineInstallItem[1]
let pattern = "\\[.*?\\]\\s" // If you have prefixes on packages that you'd like to remove, you can add the pattern here, like so: "(%20)|(Prefix.Postfix)|(ExStr)"
let removeRegex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let installItem = removeRegex.stringByReplacingMatches(in: getInstallItem, options: [], range: NSRange(location: 0, length: getInstallItem.count), withTemplate: "")
if !(installItem.isEmpty) {
NSLog("Installing: \(installItem)")
statusText = "Installing: \(installItem)"
}
case line.range(of: "Executing Policy") != nil:
let lineInstallItem = line.components(separatedBy: "]: Executing Policy ")
let getInstallItem = lineInstallItem[1]
let pattern = "\\[.*?\\]\\s" // If you have prefixes on packages that you'd like to remove, you can add the pattern here, like so: "(%20)|(Prefix.Postfix)|(ExStr)"
let removeRegex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let installItem = removeRegex.stringByReplacingMatches(in: getInstallItem, options: [], range: NSRange(location: 0, length: getInstallItem.count), withTemplate: "")
if !(installItem.isEmpty) {
NSLog("Getting: \(installItem)")
statusText = "Getting: \(installItem)"
}
case line.range(of: "Successfully installed") != nil:
let lineInstalledItem = line.components(separatedBy: "]: Successfully installed")
let getInstalledItem = lineInstalledItem[1]
let pattern = "\\s*\\[.*?\\]\\s*" // If you have prefixes on packages that you'd like to remove, you can add the pattern here, like so: "(%20)|(Prefix.Postfix)|(ExStr)"
let removeRegex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let installedItem = removeRegex.stringByReplacingMatches(in: getInstalledItem, options: [], range: NSRange(location: 0, length: getInstalledItem.count), withTemplate: "")
if !(installedItem.isEmpty) {
NSLog("Successfully installed: \(installedItem)")
statusText = "Successfuly installed: \(installedItem)"
}
case line.range(of: "failed") != nil:
let logLines = readFile(path: OtherLogs.jamf)
let lineFailedItem = (logLines.firstIndex(where: {$0.contains("\(line)")}))
let lineItemInstalled = lineFailedItem! - 1
let lineFailedReason = lineFailedItem! + 1
let getInstalledItem = logLines[lineItemInstalled].components(separatedBy: "Installing ")
if (logLines[lineFailedReason].range(of: "Cannot install on volume / because it is disabled.") != nil) {
let getFailedReason = logLines[lineFailedReason].components(separatedBy: "installer: ")
NSLog("\(getFailedReason)")
globalVariables.failedReason = getFailedReason[1]
NSLog(globalVariables.failedReason)
}
else {
let getFailedReason = logLines[lineFailedItem!].components(separatedBy: "installer: ")
NSLog("\(getFailedReason)")
globalVariables.failedReason = getFailedReason[1]
NSLog(globalVariables.failedReason)
}
if !(getInstalledItem[1].isEmpty) {
NSLog("Failed to install: \(getInstalledItem[1]) Reason: \(globalVariables.failedReason)")
statusText = "Failed to install: \(getInstalledItem[1]) Reason: \(globalVariables.failedReason)"
}
case line.range(of: "Error:") != nil:
let lineErrorItem = line.components(separatedBy: "Error: ")
let getErrorItem = lineErrorItem[1]
let pattern = "(%20)" // If you have prefixes on packages that you'd like to remove, you can add the pattern here, like so: "(%20)|(Prefix.Postfix)|(ExStr)"
let removeRegex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let errorItem = removeRegex.stringByReplacingMatches(in: getErrorItem, options: [], range: NSRange(location: 0, length: getErrorItem.count), withTemplate: "")
if !(errorItem.isEmpty) {
NSLog("Error: \(errorItem)")
statusText = "Error installing: \(errorItem)"
}
case (action.range(of: "FileVault") != nil) || (action.range(of: "Encrypt") != nil) || (action.range(of: "Encryption") != nil):
if (globalVariables.fileVaultState == "Disabled") {
statusText = "Configuring for FileVault Encryption..."
command = "FileVault: FileVault has been enabled on this machine and a reboot will be required to start the encryption process."
globalVariables.fileVaultState = "Enabled"
}
case action.range(of: "DEPNotify Quit") != nil:
statusText = "Setup Complete!"
if (globalVariables.fileVaultState == "Enabled") {
command = "Quit: Setup Complete! A reboot is needed to complete the encryption process."
}
else {
command = "Quit: Setup Complete!"
}
default:
break
}
}
}
case OtherLogs.filewave :
if line.contains("Done processing Fileset") {
do {
let typePattern = "(?<=Fileset\\sContainer\\sID\\s)(.*)"
let typeRange = line.range(of: typePattern,
options: .regularExpression)
let wantedText = line[typeRange!].trimmingCharacters(in: .whitespacesAndNewlines)
filesets.insert(wantedText)
}
}
else if line.contains("download/activation cancelled") {
do {
let typePattern = "(?<=Fileset\\sID\\s)(.*)(?=\\swere\\snot\\smet)"
let typeRange = line.range(of: typePattern,
options: .regularExpression)
let wantedText = line[typeRange!].trimmingCharacters(in: .whitespacesAndNewlines)
filesets.remove(wantedText)
}
}
else if line.contains("verifyAllFilesAndFolders") {
do {
let typePattern = "(?<=ID:\\s)(.*)"
let typeRange = line.range(of: typePattern,
options: .regularExpression)
let wantedText = line[typeRange!].trimmingCharacters(in: .whitespacesAndNewlines)
filesets.remove(wantedText)
}
}
else if line.contains("about to download") && (fwDownloadsStarted == false) {
do {
fwDownloadsStarted = true
command = "Determinate: \(filesets.count * 2)"
}
}
else if line.contains("Downloading Fileset:") {
do {
let typePattern = "(?<=Fileset:)(.*)(?=ID:)"
let typeRange = line.range(of: typePattern,
options: .regularExpression)
let insertText = "Downloading: "
let wantedText = line[typeRange!].trimmingCharacters(in: .whitespacesAndNewlines)
statusText = "\(insertText) \(wantedText)"
}
}
else if line.contains("Create all folders of fileset") {
do {
let typePattern = "(?<=Create\\sall\\sfolders\\sof\\sfileset\\sID\\s)(.*)(?=\\sID:)"
let typeRange = line.range(of: typePattern,
options: .regularExpression)
let insertText = "Installing: "
let wantedText = line[typeRange!].trimmingCharacters(in: .whitespacesAndNewlines)
statusText = "\(insertText) \(wantedText)"
}
}
else if line.contains("= HEADER =") {
do {
fwDownloadsStarted = false
filesets.removeAll()
command = "DeterminateOffReset:"
statusText = "Please wait while FileWave continues processing..."
}
}
case OtherLogs.munki :
if (line.contains("Installing") || line.contains("Downloading"))
&& !line.contains(" at ") && !line.contains(" from ") {
do {
let installerRegEx = try NSRegularExpression(pattern: "^.{0,27}")
let status = installerRegEx.stringByReplacingMatches(in: line,
options: NSRegularExpression.MatchingOptions.anchored,
range: NSMakeRange(0, line.count),
withTemplate: "").trimmingCharacters(in: .whitespacesAndNewlines)
statusText = status
} catch {
NSLog("Couldn't parse ManagedSoftwareUpdate.log")
}
}
case OtherLogs.none :
break
default:
break
}
break
}
}
}
func killCommandFile() {
// delete the command file
let fs = FileManager.init()
if fs.isDeletableFile(atPath: path) {
do {
try fs.removeItem(atPath: path)
NSLog("Deleted DEPNotify command file")
} catch {
NSLog("Unable to delete command file")
}
}
}
}
| 56.626374 | 223 | 0.443965 |
dbea69070de81c9c99ba32232bc8070b29395e14 | 298 | // RUN: not --crash %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
var d{struct S<T where g:d{class n{class B<T:CollectionType}class c{var f=(
| 42.571429 | 87 | 0.748322 |
28590c7783d9038cbdeec8057cb9bbc2399c3f35 | 3,082 | //
// PluginTestCase.swift
// TRON
//
// Created by Denys Telezhkin on 30.01.16.
// Copyright © 2016 Denys Telezhkin. All rights reserved.
//
import TRON
import XCTest
class PluginTestCase: ProtocolStubbedTestCase {
func testGlobalPluginsAreCalledCorrectly() {
let pluginTester = PluginTester()
let request: APIRequest<Int, APIError> = tron.swiftyJSON
.request("status/200")
.usingPlugin(pluginTester)
.stubStatusCode(200)
let waitingForRequest = expectation(description: "wait for request")
request.performCollectingTimeline(withCompletion: { _ in
waitingForRequest.fulfill()
})
waitForExpectations(timeout: 1)
XCTAssertTrue(pluginTester.willSendCalled)
XCTAssertTrue(pluginTester.willSendAlamofireCalled)
XCTAssertTrue(pluginTester.didSendAlamofireCalled)
XCTAssertTrue(pluginTester.didReceiveResponseCalled)
}
func testLocalPluginsAreCalledCorrectly() {
let pluginTester = PluginTester()
let request: APIRequest<String, APIError> = tron.swiftyJSON
.request("status/200")
.usingPlugin(pluginTester)
.stubStatusCode(200)
let expectation = self.expectation(description: "PluginTester expectation")
request.perform(withSuccess: { _ in
if pluginTester.didReceiveResponseCalled && pluginTester.willSendCalled {
expectation.fulfill()
}
}, failure: { _ in
if pluginTester.didReceiveResponseCalled && pluginTester.willSendCalled {
expectation.fulfill()
}
})
waitForExpectations(timeout: 1, handler: nil)
}
func testPluginsAreInitializable() {
_ = NetworkLoggerPlugin()
#if os(iOS)
_ = NetworkActivityPlugin(application: UIApplication.shared)
#endif
}
func testMultipartRequestsCallGlobalAndLocalPlugins() {
let globalPluginTester = PluginTester()
let localPluginTester = PluginTester()
let configuration = URLSessionConfiguration.default
configuration.protocolClasses = [StubbingURLProtocol.self]
tron = TRON(baseURL: "https://httpbin.org", session: Session(configuration: configuration))
let request: UploadAPIRequest<String, APIError> = tron.swiftyJSON
.uploadMultipart("status/200") { _ in }
.stubStatusCode(200)
.usingPlugin(localPluginTester)
tron.plugins.append(globalPluginTester)
let waitForRequest = expectation(description: "waiting for request")
request.perform(withSuccess: { _ in
waitForRequest.fulfill()
}, failure: { _ in
waitForRequest.fulfill()
})
waitForExpectations(timeout: 1)
XCTAssertTrue(localPluginTester.willSendCalled)
XCTAssertTrue(globalPluginTester.willSendCalled)
XCTAssertTrue(localPluginTester.didReceiveResponseCalled)
XCTAssertTrue(globalPluginTester.didReceiveResponseCalled)
}
}
| 35.022727 | 99 | 0.667748 |
5db42fe6a59fe43f2e95435644e168cbb582e835 | 155 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(X1KitTests.allTests),
]
}
#endif
| 15.5 | 45 | 0.664516 |
f5998e7880d3b12812880ca8155b3f48dd4917fe | 2,650 | // REQUIRES: plus_zero_runtime
// RUN: %target-swift-frontend -module-name generic_witness -emit-silgen -enable-sil-ownership %s | %FileCheck %s
// RUN: %target-swift-frontend -module-name generic_witness -emit-ir -enable-sil-ownership %s
protocol Runcible {
func runce<A>(_ x: A)
}
// CHECK-LABEL: sil hidden @$S15generic_witness3foo{{[_0-9a-zA-Z]*}}F : $@convention(thin) <B where B : Runcible> (@in_guaranteed B) -> () {
func foo<B : Runcible>(_ x: B) {
// CHECK: [[METHOD:%.*]] = witness_method $B, #Runcible.runce!1 : {{.*}} : $@convention(witness_method: Runcible) <τ_0_0 where τ_0_0 : Runcible><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[METHOD]]<B, Int>
x.runce(5)
}
// CHECK-LABEL: sil hidden @$S15generic_witness3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@in_guaranteed Runcible) -> ()
func bar(_ x: Runcible) {
var x = x
// CHECK: [[BOX:%.*]] = alloc_box ${ var Runcible }
// CHECK: [[TEMP:%.*]] = alloc_stack $Runcible
// CHECK: [[EXIST:%.*]] = open_existential_addr immutable_access [[TEMP]] : $*Runcible to $*[[OPENED:@opened(.*) Runcible]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #Runcible.runce!1
// CHECK: apply [[METHOD]]<[[OPENED]], Int>
x.runce(5)
}
protocol Color {}
protocol Ink {
associatedtype Paint
}
protocol Pen {}
protocol Pencil : Pen {
associatedtype Stroke : Pen
}
protocol Medium {
associatedtype Texture : Ink
func draw<P : Pencil>(paint: Texture.Paint, pencil: P) where P.Stroke == Texture.Paint
}
struct Canvas<I : Ink> where I.Paint : Pen {
typealias Texture = I
func draw<P : Pencil>(paint: I.Paint, pencil: P) where P.Stroke == Texture.Paint { }
}
extension Canvas : Medium {}
// CHECK-LABEL: sil private [transparent] [thunk] @$S15generic_witness6CanvasVyxGAA6MediumA2aEP4draw5paint6pencily6StrokeQyd___qd__tAA6PencilRd__7Texture_5PaintQZAKRSlFTW : $@convention(witness_method: Medium) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in_guaranteed τ_0_0.Paint, @in_guaranteed τ_1_0, @in_guaranteed Canvas<τ_0_0>) -> () {
// CHECK: [[FN:%.*]] = function_ref @$S15generic_witness6CanvasV4draw5paint6pencily5PaintQz_qd__tAA6PencilRd__6StrokeQyd__AHRSlF : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in_guaranteed τ_0_0.Paint, @in_guaranteed τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: apply [[FN]]<τ_0_0, τ_1_0>({{.*}}) : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in_guaranteed τ_0_0.Paint, @in_guaranteed τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: }
| 44.915254 | 381 | 0.689434 |
e6e5aea28ae1d79ab5d3fb7f671dc5a13e5ee048 | 349 | //
// ContentView.swift
// TestLib001
//
// Created by CAICA on 2019/11/19.
// Copyright © 2019 nn. All rights reserved.
//
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello World")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 15.863636 | 46 | 0.636103 |
f59d08259d34fe3486fa57b9c632e58d591b98cd | 7,800 | //===----------------------------------------------------------------------===//
//
// 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 String.Index {
/// Creates an index in the given string that corresponds exactly to the
/// specified `UnicodeScalarView` position.
///
/// The following example converts the position of the Unicode scalar `"e"`
/// into its corresponding position in the string's character view. The
/// character at that position is the composed `"é"` character.
///
/// let cafe = "Cafe\u{0301}"
/// print(cafe)
/// // Prints "Café"
///
/// let scalarsIndex = cafe.unicodeScalars.index(of: "e")!
/// let charactersIndex = String.Index(scalarsIndex, within: cafe)!
///
/// print(String(cafe.characters.prefix(through: charactersIndex)))
/// // Prints "Café"
///
/// If the position passed in `unicodeScalarIndex` doesn't have an exact
/// corresponding position in `other.characters`, the result of the
/// initializer is `nil`. For example, an attempt to convert the position of
/// the combining acute accent (`"\u{0301}"`) fails. Combining Unicode
/// scalars do not have their own position in a character view.
///
/// let nextIndex = String.Index(cafe.unicodeScalars.index(after: scalarsIndex),
/// within: cafe)
/// print(nextIndex)
/// // Prints "nil"
///
/// - Parameters:
/// - unicodeScalarIndex: A position in the `unicodeScalars` view of the
/// `other` parameter.
/// - other: The string referenced by both `unicodeScalarIndex` and the
/// resulting index.
public init?(
_ unicodeScalarIndex: String.UnicodeScalarIndex,
within other: String
) {
if !other.unicodeScalars._isOnGraphemeClusterBoundary(unicodeScalarIndex) {
return nil
}
self.init(_base: unicodeScalarIndex, in: other.characters)
}
/// Creates an index in the given string that corresponds exactly to the
/// specified `UTF16View` position.
///
/// The following example finds the position of a space in a string's `utf16`
/// view and then converts that position to an index in the string's
/// `characters` view. The value `32` is the UTF-16 encoded value of a space
/// character.
///
/// let cafe = "Café 🍵"
///
/// let utf16Index = cafe.utf16.index(of: 32)!
/// let charactersIndex = String.Index(utf16Index, within: cafe)!
///
/// print(String(cafe.characters.prefix(upTo: charactersIndex)))
/// // Prints "Café"
///
/// If the position passed in `utf16Index` doesn't have an exact
/// corresponding position in `other.characters`, the result of the
/// initializer is `nil`. For example, an attempt to convert the position of
/// the trailing surrogate of a UTF-16 surrogate pair fails.
///
/// The next example attempts to convert the indices of the two UTF-16 code
/// points that represent the teacup emoji (`"🍵"`). The index of the lead
/// surrogate is successfully converted to a position in `other.characters`,
/// but the index of the trailing surrogate is not.
///
/// let emojiHigh = cafe.utf16.index(after: utf16Index)
/// print(String.Index(emojiHigh, within: cafe))
/// // Prints "Optional(String.Index(...))"
///
/// let emojiLow = cafe.utf16.index(after: emojiHigh)
/// print(String.Index(emojiLow, within: cafe))
/// // Prints "nil"
///
/// - Parameters:
/// - utf16Index: A position in the `utf16` view of the `other` parameter.
/// - other: The string referenced by both `utf16Index` and the resulting
/// index.
public init?(
_ utf16Index: String.UTF16Index,
within other: String
) {
if let me = utf16Index.samePosition(
in: other.unicodeScalars
)?.samePosition(in: other) {
self = me
}
else {
return nil
}
}
/// Creates an index in the given string that corresponds exactly to the
/// specified `UTF8View` position.
///
/// If the position passed in `utf8Index` doesn't have an exact corresponding
/// position in `other.characters`, the result of the initializer is `nil`.
/// For example, an attempt to convert the position of a UTF-8 continuation
/// byte returns `nil`.
///
/// - Parameters:
/// - utf8Index: A position in the `utf8` view of the `other` parameter.
/// - other: The string referenced by both `utf8Index` and the resulting
/// index.
public init?(
_ utf8Index: String.UTF8Index,
within other: String
) {
if let me = utf8Index.samePosition(
in: other.unicodeScalars
)?.samePosition(in: other) {
self = me
}
else {
return nil
}
}
/// Returns the position in the given UTF-8 view that corresponds exactly to
/// this index.
///
/// The index must be a valid index of `String(utf8).characters`.
///
/// This example first finds the position of the character `"é"` and then uses
/// this method find the same position in the string's `utf8` view.
///
/// let cafe = "Café"
/// if let i = cafe.characters.index(of: "é") {
/// let j = i.samePosition(in: cafe.utf8)
/// print(Array(cafe.utf8.suffix(from: j)))
/// }
/// // Prints "[195, 169]"
///
/// - Parameter utf8: The view to use for the index conversion.
/// - Returns: The position in `utf8` that corresponds exactly to this index.
public func samePosition(
in utf8: String.UTF8View
) -> String.UTF8View.Index {
return String.UTF8View.Index(self, within: utf8)
}
/// Returns the position in the given UTF-16 view that corresponds exactly to
/// this index.
///
/// The index must be a valid index of `String(utf16).characters`.
///
/// This example first finds the position of the character `"é"` and then uses
/// this method find the same position in the string's `utf16` view.
///
/// let cafe = "Café"
/// if let i = cafe.characters.index(of: "é") {
/// let j = i.samePosition(in: cafe.utf16)
/// print(cafe.utf16[j])
/// }
/// // Prints "233"
///
/// - Parameter utf16: The view to use for the index conversion.
/// - Returns: The position in `utf16` that corresponds exactly to this index.
public func samePosition(
in utf16: String.UTF16View
) -> String.UTF16View.Index {
return String.UTF16View.Index(self, within: utf16)
}
/// Returns the position in the given view of Unicode scalars that
/// corresponds exactly to this index.
///
/// The index must be a valid index of `String(unicodeScalars).characters`.
///
/// This example first finds the position of the character `"é"` and then uses
/// this method find the same position in the string's `unicodeScalars`
/// view.
///
/// let cafe = "Café"
/// if let i = cafe.characters.index(of: "é") {
/// let j = i.samePosition(in: cafe.unicodeScalars)
/// print(cafe.unicodeScalars[j])
/// }
/// // Prints "é"
///
/// - Parameter unicodeScalars: The view to use for the index conversion.
/// - Returns: The position in `unicodeScalars` that corresponds exactly to
/// this index.
public func samePosition(
in unicodeScalars: String.UnicodeScalarView
) -> String.UnicodeScalarView.Index {
return String.UnicodeScalarView.Index(self, within: unicodeScalars)
}
}
| 37.681159 | 86 | 0.628846 |
875a7dce9d33b512f2beb663dfb8f26e7ef44e89 | 3,717 | // swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Bubo",
platforms: [
.macOS(.v10_13),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.0.1"),
.package(url: "https://github.com/JohnSundell/ShellOut.git", from: "2.0.0"),
.package(url: "https://github.com/mtynior/ColorizeSwift.git", from: "1.5.0"),
.package(url: "https://github.com/davecom/SwiftGraph.git", from: "3.0.0"),
.package(name: "SwiftSyntax", url: "https://github.com/apple/swift-syntax.git", from: "0.50200.0"),
.package(name: "IndexStoreDB", url: "https://github.com/apple/indexstore-db.git", .branch("swift-5.2-branch"))
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "GraphBuilderModule",
dependencies: [
.product(name: "SwiftGraph", package: "SwiftGraph"),
.product(name: "SwiftSyntax", package: "SwiftSyntax"),
.product(name: "IndexStoreDB", package: "IndexStoreDB"),
.target(name: "ResourceManagerModule")
]
),
.target(
name: "ResourceManagerModule",
dependencies: [
.product(name: "SwiftGraph", package: "SwiftGraph"),
.product(name: "SwiftSyntax", package: "SwiftSyntax"),
.product(name: "IndexStoreDB", package: "IndexStoreDB"),
.product(name: "ColorizeSwift", package: "ColorizeSwift"),
]
),
.target(
name: "OperationsManagerModule",
dependencies: [
.product(name: "SwiftGraph", package: "SwiftGraph"),
.product(name: "SwiftSyntax", package: "SwiftSyntax"),
.product(name: "IndexStoreDB", package: "IndexStoreDB"),
.product(name: "ColorizeSwift", package: "ColorizeSwift"),
.target(name: "GraphBuilderModule"),
.target(name: "ResourceManagerModule"),
.target(name: "ServiceAnalyserModule")
]
),
.target(
name: "ServiceAnalyserModule",
dependencies: [
.product(name: "SwiftGraph", package: "SwiftGraph"),
.product(name: "SwiftSyntax", package: "SwiftSyntax"),
.product(name: "IndexStoreDB", package: "IndexStoreDB"),
.target(name: "ResourceManagerModule"),
.target(name: "GraphBuilderModule")
]
),
.target(
name: "Bubo",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "ShellOut", package: "ShellOut"),
.product(name: "SwiftGraph", package: "SwiftGraph"),
.target(name: "GraphBuilderModule"),
.target(name: "OperationsManagerModule"),
.target(name: "ServiceAnalyserModule")
]),
.testTarget(
name: "BuboTests",
dependencies: [
.target(name: "Bubo"),
.target(name: "GraphBuilderModule"),
.target(name: "ResourceManagerModule")
]),
]
)
| 44.25 | 122 | 0.555556 |
e5aed01e1e0e82bb14ba02442d7fc1d52be6cd11 | 1,438 | //
// MainMenu.swift
// CyrusLyrics
//
// Created by Aaron Krauss on 1/14/22.
//
import SwiftUI
struct MainMenu: View {
let width: CGFloat
let isOpen: Bool
let menuClose: () -> Void
var body: some View {
ZStack {
GeometryReader { _ in
EmptyView()
}
.background(Color.gray.opacity(0.3))
.opacity(self.isOpen ? 1.0 : 0.0)
.animation(Animation.easeIn.delay(0.25))
.onTapGesture {
self.menuClose()
}
HStack {
MenuContent()
.frame(width: self.width)
.background(Color.white)
.offset(x: self.isOpen ? 0 : -self.width)
.animation(.default)
Spacer()
}
}
}
}
//struct MainMenu_Previews: PreviewProvider {
// static var previews: some View {
// MainMenu(width: 270,
// isOpen: true,
// menuClose: self.openMenu) }
//}
struct MenuContent: View {
var body: some View {
List {
Text("My Profile").onTapGesture {
print("My Profile")
}
Text("Posts").onTapGesture {
print("Posts")
}
Text("Logout").onTapGesture {
print("Logout")
}
}
}
}
| 23.193548 | 61 | 0.442976 |
ed2afc28e6579e15cad2c7daf4b943db51ffbcf6 | 2,063 | //
// AppDelegate.swift
// OhMyPullRequests
//
// Created by Zihua Li on 2021/8/7.
//
import Cocoa
import KeychainSwift
import SwiftyUserDefaults
import OctoKit
@main
class AppDelegate: NSObject, NSApplicationDelegate {
let menu = DropdownMenu()
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
var pullRequestManager: PullRequestManager?
lazy var loginWindowController = LoginWindowController(windowNibName: "LoginWindowController")
func applicationDidFinishLaunching(_ aNotification: Notification) {
if let button = statusItem.button {
button.title = "..."
button.image = NSImage(named: "github")
button.imagePosition = .imageLeading
button.imageScaling = .scaleProportionallyUpOrDown
}
menu.actionDelegate = self
menu.set(pullRequests: [])
statusItem.menu = menu
updatePullRequestManager()
}
func updatePullRequestManager() {
if let token = TokenManager.shared.get() {
pullRequestManager = PullRequestManager(token: token, repo: Defaults.repository)
pullRequestManager?.delegate = self
pullRequestManager?.start()
} else {
pullRequestManager = nil
}
}
@IBAction func openLoginWindow(_ sender: Any) {
NSApp.activate(ignoringOtherApps: true)
loginWindowController.delegate = self
loginWindowController.showWindow(sender)
}
}
extension AppDelegate: PullRequestManagerDelegate {
func pullRequestsFetched(_ prs: [PullRequestManager.InterestedPullRequest]) {
statusItem.button?.title = prs.count > 0 ? String(prs.count) : ""
menu.set(pullRequests: prs)
}
}
extension AppDelegate: DropdownMenuDelegate {
func loginWindowShouldOpen(_ sender: Any) {
openLoginWindow(sender)
}
}
extension AppDelegate: LoginWindowControllerDelegate {
func settingUpdated(_ sender: Any) {
updatePullRequestManager()
}
}
| 29.471429 | 98 | 0.6762 |
ac95d2d17da956e3c7383ab5c8cff60fe27c8998 | 1,100 | //
// AppDelegate.swift
// GitTime
//
// Created by Kanz on 09/05/2019.
// Copyright © 2019 KanzDevelop. All rights reserved.
//
import UIKit
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var dependency: AppDependency!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.dependency = self.dependency ?? CompositionRoot.resolve(launchOptions: launchOptions)
self.dependency.configureSDKs()
self.dependency.configureAppearance()
self.window = self.dependency.window
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
UserDefaultsConfig.didEnterBackgroundTime = Date()
}
func applicationWillEnterForeground(_ application: UIApplication) {
if let didEnterBackgroundTime = UserDefaultsConfig.didEnterBackgroundTime {
if didEnterBackgroundTime.anHourAfater() == true {
NotificationCenter.default.post(name: .backgroundRefresh, object: nil)
}
}
UserDefaultsConfig.didEnterBackgroundTime = nil
}
}
| 28.947368 | 142 | 0.775455 |
d73136accbc1adecfd5a196162c311ab09706510 | 5,423 | //
// RecommendVC.swift
// DouYuTV
//
// Created by apple on 2017/7/18.
// Copyright © 2017年 apple. All rights reserved.
//
import UIKit
//MARK:- 定义常量
private let kItemMargin : CGFloat = 10
private let kItemW : CGFloat = (kScreenW - 3 * kItemMargin)/2
private let kNormalItemH : CGFloat = kItemW * 3 / 4
private let kPrettyItemH : CGFloat = kItemW * 4 / 3
private let kHeaderViewH : CGFloat = 50
private let kCycleViewH = kScreenW * 3 / 8
private let kNormalCellID = "kNormalCellID"
private let kHeaderViewID = "kHeaderViewID"
private let kPrettyCellID = "kPrettyCellID"
class RecommendVC: UIViewController {
//MARK:- 懒加载属性
fileprivate lazy var recommendVM : RecommendViewModel = RecommendViewModel()
fileprivate lazy var collectionView : UICollectionView = {
//1、创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0//行间距
layout.minimumInteritemSpacing = kItemMargin//item间距
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
//2、创建collectionview
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.contentInset = UIEdgeInsetsMake(0, 10, 0, 10)
collectionView.autoresizingMask = [.flexibleHeight, .flexibleHeight]
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.register(UINib(nibName:"CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName:"CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
return collectionView
}()
fileprivate lazy var recommendCycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x:0, y:-kCycleViewH, width:kScreenW, height:kCycleViewH)
return cycleView
}()
//MARK:- 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setupUI()
//请求数据
loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK:- 请求网络数据
extension RecommendVC{
func loadData(){
//请求无线轮播数据
recommendVM.requestCycleData {
self.recommendCycleView.cycleModels = self.recommendVM.cycleModels
}
//请求推荐数据
recommendVM.requestData {
self.collectionView.reloadData()
}
}
}
//MARK:- 设置UI界面
extension RecommendVC{
func setupUI() {
//1、将collectionview添加到View中
view.addSubview(collectionView)
//2、将cycleview添加到collectionview
collectionView.addSubview(recommendCycleView)
//3、设置collectionview的内边距
collectionView.contentInset = UIEdgeInsets(top: kCycleViewH, left: 0, bottom: 0, right: 0)
}
}
extension RecommendVC : UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return recommendVM.anchoGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let group = recommendVM.anchoGroups[section]
return group.anchors.count
// if section==0{
// return 8
// }
// return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1、取出模型对象
let group = recommendVM.anchoGroups[indexPath.section]
let anchor = group.anchors[indexPath.item]
//2、定义cell
var cell : CollectionBaseCell!
//3、取出cell
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell
}else{
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
}
//4、将模型赋值给cell
cell.anchor = anchor
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//1、取出HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID, for: indexPath)
as! CollectionHeaderView
//2、取出模型
headerView.group = recommendVM.anchoGroups[indexPath.section]
return headerView
}
}
//MARK:- 遵守UIcollectionViewDelegate
extension RecommendVC : UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrettyItemH)
}else{
return CGSize(width: kItemW, height: kNormalItemH)
}
}
}
| 35.913907 | 186 | 0.697953 |
eda1681f7707d3d4fa05e2e8cc2b73833a121034 | 358 | //
// ComponentsImageViews.swift
// Forms
//
// Created by Konrad on 4/28/20.
// Copyright © 2020 Limbo. All rights reserved.
//
import UIKit
public enum ComponentsImageViews: ComponentsList {
public static func `default`() -> ImageView {
let component = ImageView()
component.contentMode = .center
return component
}
}
| 19.888889 | 50 | 0.659218 |
5687a79f5d0924378aa0f184ebd816d6161e9f17 | 1,004 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -module-name IgnoreInherited -emit-module-path %t/IgnoreInherited.swiftmodule
// RUN: %target-swift-symbolgraph-extract -module-name IgnoreInherited -I %t -pretty-print -output-dir %t
// RUN: %FileCheck %s --input-file %t/IgnoreInherited.symbols.json
public protocol P {
associatedtype T
static func foo() -> T
}
public struct S<T> {}
extension S: P where T: Sequence, T.Element == Int {
public static func foo() -> AnySequence<Int> {
return AnySequence([0])
}
}
// CHECK-LABEL: "precise": "s:15IgnoreInherited1SVAASTRzSi7ElementRtzlE3foos11AnySequenceVySiGyFZ"
// CHECK: swiftExtension
// CHECK: "constraints": [
// CHECK-NEXT: {
// CHECK-NEXT: "kind": "conformance",
// CHECK-NEXT: "lhs": "T",
// CHECK-NEXT: "rhs": "Sequence"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "kind": "sameType",
// CHECK-NEXT: "lhs": "T.Element",
// CHECK-NEXT: "rhs": "Int"
// CHECK-NEXT: }
// CHECK-NEXT: ]
| 30.424242 | 108 | 0.653386 |
1cc8217f0dc4b926171a54cfb3677bfcf68637a6 | 4,576 |
import AsyncDisplayKit
import Then
protocol SettingsViewControllerDelegate: class {
func settingsDidSelectChannelList()
func settingsDidSelectDownloads()
func settingsDidSelectHidden()
func settingsDidSelectAppSettings()
func settingsDidSelectLicenses()
}
final class SettingsViewController: ASViewController<ASTableNode> {
private weak var delegate: SettingsViewControllerDelegate?
init(delegate: SettingsViewControllerDelegate) {
self.delegate = delegate
let table = ASTableNode(style: .grouped)
table.backgroundColor = .white
super.init(node: table)
table.dataSource = self
table.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Navigation
extension SettingsViewController {
func showSubscriptions() {
delegate?.settingsDidSelectChannelList()
}
func showDoanloads() {
delegate?.settingsDidSelectDownloads()
}
func showLicenses() {
delegate?.settingsDidSelectLicenses()
}
func showSettings() {
delegate?.settingsDidSelectAppSettings()
}
func showHidden() {
delegate?.settingsDidSelectHidden()
}
}
extension SettingsViewController: ASTableDataSource {
func numberOfSections(in tableNode: ASTableNode) -> Int {
return TableViewSection.allCases.count
}
func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int {
switch section {
case TableViewSection.media.rawValue: return MediaCellRows.allCases.count
case TableViewSection.subscriptions.rawValue: return SubscriptionCellRows.allCases.count
case TableViewSection.options.rawValue: return OptionCellRows.allCases.count
default: return 0
}
}
func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode {
let node = ASTextCellNode().then {
$0.backgroundColor = .white
}
if indexPath.section == TableViewSection.subscriptions.rawValue {
node.text = SubscriptionCellRows(rawValue: indexPath.row)!.description
} else if indexPath.section == TableViewSection.media.rawValue {
node.text = MediaCellRows(rawValue: indexPath.row)!.description
} else if indexPath.section == TableViewSection.options.rawValue {
node.text = OptionCellRows(rawValue: indexPath.row)!.description
}
return node
}
}
extension SettingsViewController: ASTableDelegate {
func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) {
tableNode.deselectRow(at: indexPath, animated: true)
if indexPath.section == TableViewSection.subscriptions.rawValue {
switch indexPath.row {
case SubscriptionCellRows.viewSubscriptions.rawValue:
showSubscriptions()
default: return
}
} else if indexPath.section == TableViewSection.media.rawValue {
switch indexPath.row {
case MediaCellRows.downloads.rawValue:
showDoanloads()
case MediaCellRows.hidden.rawValue:
showHidden()
default: return
}
} else if indexPath.section == TableViewSection.options.rawValue {
switch indexPath.row {
case OptionCellRows.settings.rawValue:
showSettings()
case OptionCellRows.licenses.rawValue:
showLicenses()
default: return
}
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return TableViewSection(rawValue: section)?.description
}
}
private extension SettingsViewController {
enum TableViewSection: Int, CaseIterable, CustomStringConvertible {
case subscriptions
case media
case options
var description: String {
switch self {
case .subscriptions: return "Channels"
case .media: return "Media"
case .options: return "Settings"
}
}
}
enum SubscriptionCellRows: Int, CaseIterable, CustomStringConvertible {
case viewSubscriptions
var description: String {
switch self {
case .viewSubscriptions: return "Channels"
}
}
}
enum MediaCellRows: Int, CaseIterable, CustomStringConvertible {
case downloads
case hidden
var description: String {
switch self {
case .downloads: return "Downloads"
case .hidden: return "Hidden"
}
}
}
enum OptionCellRows: Int, CaseIterable, CustomStringConvertible {
case settings
case licenses
var description: String {
switch self {
case .settings: return "App Settings"
case .licenses: return "Licenses"
}
}
}
}
| 24.470588 | 93 | 0.710446 |
1a9ade8a770687d77816720fc7c4e604438f66f0 | 1,937 | //
// PeerBrowser.swift
// Bitfinex Demo
//
// Created by Jonathan Gikabu on 28/08/2021.
//
import Network
var sharedBrowser: PeerBrowser?
// Update the UI when you receive new browser results.
protocol PeerBrowserDelegate: AnyObject {
func refreshResults(results: Set<NWBrowser.Result>)
func displayBrowseError(_ error: NWError)
}
class PeerBrowser {
weak var delegate: PeerBrowserDelegate?
var browser: NWBrowser?
// Create a browsing object with a delegate.
init(delegate: PeerBrowserDelegate) {
self.delegate = delegate
startBrowsing()
}
// Start browsing for services.
func startBrowsing() {
// Create parameters, and allow browsing over peer-to-peer link.
let parameters = NWParameters()
parameters.includePeerToPeer = true
// Browse for a custom "_bitfinex._tcp" service type.
let browser = NWBrowser(for: .bonjour(type: "_bitfinex._tcp", domain: nil), using: parameters)
self.browser = browser
browser.stateUpdateHandler = { newState in
switch newState {
case .failed(let error):
// Restart the browser if it loses its connection
if error == NWError.dns(DNSServiceErrorType(kDNSServiceErr_DefunctConnection)) {
print("Browser failed with \(error), restarting")
browser.cancel()
self.startBrowsing()
} else {
print("Browser failed with \(error), stopping")
self.delegate?.displayBrowseError(error)
browser.cancel()
}
case .ready:
// Post initial results.
self.delegate?.refreshResults(results: browser.browseResults)
case .cancelled:
sharedBrowser = nil
self.delegate?.refreshResults(results: Set())
default:
break
}
}
// When the list of discovered endpoints changes, refresh the delegate.
browser.browseResultsChangedHandler = { results, changes in
self.delegate?.refreshResults(results: results)
}
// Start browsing and ask for updates on the main queue.
browser.start(queue: .main)
}
}
| 27.28169 | 96 | 0.720186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.