repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
szpnygo/firefox-ios | Client/Frontend/Reader/ReadabilityService.swift | 18 | 4144 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
private let ReadabilityServiceSharedInstance = ReadabilityService()
private let ReadabilityTaskDefaultTimeout = 15
private let ReadabilityServiceDefaultConcurrency = 1
enum ReadabilityOperationResult {
case Success(ReadabilityResult)
case Error(NSError)
case Timeout
}
class ReadabilityOperation: NSOperation, WKNavigationDelegate, ReadabilityBrowserHelperDelegate {
var url: NSURL
var semaphore: dispatch_semaphore_t
var result: ReadabilityOperationResult?
var browser: Browser!
init(url: NSURL) {
self.url = url
self.semaphore = dispatch_semaphore_create(0)
}
override func main() {
if self.cancelled {
return
}
// Setup a browser, attach a Readability helper. Kick all this off on the main thread since UIKit
// and WebKit are not safe from other threads.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let configuration = WKWebViewConfiguration()
self.browser = Browser(configuration: configuration)
self.browser.createWebview()
self.browser.navigationDelegate = self
if let readabilityBrowserHelper = ReadabilityBrowserHelper(browser: self.browser) {
readabilityBrowserHelper.delegate = self
self.browser.addHelper(readabilityBrowserHelper, name: ReadabilityBrowserHelper.name())
}
// Load the page in the webview. This either fails with a navigation error, or we get a readability
// callback. Or it takes too long, in which case the semaphore times out.
self.browser.loadRequest(NSURLRequest(URL: self.url))
})
if dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, Int64(Double(ReadabilityTaskDefaultTimeout) * Double(NSEC_PER_SEC)))) != 0 {
result = ReadabilityOperationResult.Timeout
}
// Maybe this is where we should store stuff in the cache / run a callback?
if let result = self.result {
switch result {
case .Timeout:
// Don't do anything on timeout
break
case .Success(let readabilityResult):
var error: NSError? = nil
if !ReaderModeCache.sharedInstance.put(url, readabilityResult, error: &error) {
if error != nil {
println("Failed to store readability results in the cache: \(error?.localizedDescription)")
// TODO Fail
}
}
case .Error(let error):
// TODO Not entitely sure what to do on error. Needs UX discussion and followup bug.
break
}
}
}
func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
result = ReadabilityOperationResult.Error(error)
dispatch_semaphore_signal(semaphore)
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
result = ReadabilityOperationResult.Error(error)
dispatch_semaphore_signal(semaphore)
}
func readabilityBrowserHelper(readabilityBrowserHelper: ReadabilityBrowserHelper, didFinishWithReadabilityResult readabilityResult: ReadabilityResult) {
result = ReadabilityOperationResult.Success(readabilityResult)
dispatch_semaphore_signal(semaphore)
}
}
class ReadabilityService {
class var sharedInstance: ReadabilityService {
return ReadabilityServiceSharedInstance
}
var queue: NSOperationQueue
init() {
queue = NSOperationQueue()
queue.maxConcurrentOperationCount = ReadabilityServiceDefaultConcurrency
}
func process(url: NSURL) {
queue.addOperation(ReadabilityOperation(url: url))
}
} | mpl-2.0 | 3f0fc76cd2eb70ab963cbc1b60ed1527 | 36.342342 | 156 | 0.662645 | 5.496021 | false | false | false | false |
openHPI/xikolo-ios | Common/Data/Helper/FetchRequests/SectionProgressHelper+FetchRequest.swift | 1 | 837 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import CoreData
public enum SectionProgressHelper {
public enum FetchRequest {
public static func sectionProgresses(forCourse course: Course) -> NSFetchRequest<SectionProgress> {
let request: NSFetchRequest<SectionProgress> = SectionProgress.fetchRequest()
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [
NSPredicate(format: "courseProgress.id = %@", course.id),
NSPredicate(format: "available = %@", NSNumber(value: true)),
])
let positionSort = NSSortDescriptor(keyPath: \SectionProgress.position, ascending: true)
request.sortDescriptors = [positionSort]
return request
}
}
}
| gpl-3.0 | 6d90be73dbc52fd80841244ea5f6b34e | 32.44 | 107 | 0.657895 | 5.097561 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGPU/CoreImage/CoreImage.swift | 1 | 81418 | //
// CoreImage.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
#if canImport(CoreImage)
extension CIImage {
public func sharpenLuminance(sharpness: Float = 0.4,
radius: Float = 1.69) -> CIImage {
guard let filter = CIFilter(name: "CISharpenLuminance") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(sharpness, forKey: "inputSharpness")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
public func unsharpMask(radius: Float = 2.5,
intensity: Float = 0.5) -> CIImage {
guard let filter = CIFilter(name: "CIUnsharpMask") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(intensity, forKey: "inputIntensity")
return filter.outputImage ?? .empty()
}
public func circularScreen(center: CGPoint = CGPoint(x: 150, y: 150),
width: Float = 6,
sharpness: Float = 0.7) -> CIImage {
guard let filter = CIFilter(name: "CICircularScreen") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(sharpness, forKey: "inputSharpness")
return filter.outputImage ?? .empty()
}
public func cmykHalftone(center: CGPoint = CGPoint(x: 150, y: 150),
width: Float = 6,
angle: Float = 0,
sharpness: Float = 0.7,
grayComponentReplacement: Float = 1,
underColorRemoval: Float = 0.5) -> CIImage {
guard let filter = CIFilter(name: "CICMYKHalftone") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(sharpness, forKey: "inputSharpness")
filter.setValue(grayComponentReplacement, forKey: "inputGCR")
filter.setValue(underColorRemoval, forKey: "inputUCR")
return filter.outputImage ?? .empty()
}
public func dotScreen(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 6,
sharpness: Float = 0.7) -> CIImage {
guard let filter = CIFilter(name: "CIDotScreen") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(sharpness, forKey: "inputSharpness")
return filter.outputImage ?? .empty()
}
public func hatchedScreen(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 6,
sharpness: Float = 0.7) -> CIImage {
guard let filter = CIFilter(name: "CIHatchedScreen") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(sharpness, forKey: "inputSharpness")
return filter.outputImage ?? .empty()
}
public func lineScreen(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 6,
sharpness: Float = 0.7) -> CIImage {
guard let filter = CIFilter(name: "CILineScreen") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(sharpness, forKey: "inputSharpness")
return filter.outputImage ?? .empty()
}
public func bicubicScaleTransform(scale: Float = 1,
aspectRatio: Float = 1,
b: Float = 0,
c: Float = 0.75) -> CIImage {
guard let filter = CIFilter(name: "CIBicubicScaleTransform") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(scale, forKey: "inputScale")
filter.setValue(aspectRatio, forKey: "inputAspectRatio")
filter.setValue(b, forKey: "inputB")
filter.setValue(c, forKey: "inputC")
return filter.outputImage ?? .empty()
}
public func edgePreserveUpsample(smallImage: CIImage,
spatialSigma: Float = 3,
lumaSigma: Float = 0.15) -> CIImage {
guard let filter = CIFilter(name: "CIEdgePreserveUpsampleFilter") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(smallImage, forKey: "inputSmallImage")
filter.setValue(spatialSigma, forKey: "inputSpatialSigma")
filter.setValue(lumaSigma, forKey: "inputLumaSigma")
return filter.outputImage ?? .empty()
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
public func keystoneCorrectionCombined(focalLength: Float = 28) -> CIImage {
let filter = CIFilter.keystoneCorrectionCombined()
filter.setValue(self, forKey: "inputImage")
filter.focalLength = focalLength
return filter.outputImage ?? .empty()
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
public func keystoneCorrectionHorizontal(focalLength: Float = 28) -> CIImage {
let filter = CIFilter.keystoneCorrectionHorizontal()
filter.setValue(self, forKey: "inputImage")
filter.focalLength = focalLength
return filter.outputImage ?? .empty()
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
public func keystoneCorrectionVertical(focalLength: Float = 28) -> CIImage {
let filter = CIFilter.keystoneCorrectionVertical()
filter.setValue(self, forKey: "inputImage")
filter.focalLength = focalLength
return filter.outputImage ?? .empty()
}
public func lanczosScaleTransform(scale: Float = 1,
aspectRatio: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CILanczosScaleTransform") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(scale, forKey: "inputScale")
filter.setValue(aspectRatio, forKey: "inputAspectRatio")
return filter.outputImage ?? .empty()
}
public func perspectiveCorrection(topLeft: CGPoint = CGPoint(x: 118, y: 484),
topRight: CGPoint = CGPoint(x: 646, y: 507),
bottomRight: CGPoint = CGPoint(x: 548, y: 140),
bottomLeft: CGPoint = CGPoint(x: 155, y: 153),
crop: Bool = true) -> CIImage {
guard let filter = CIFilter(name: "CIPerspectiveCorrection") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: topLeft), forKey: "inputTopLeft")
filter.setValue(CIVector(cgPoint: topRight), forKey: "inputTopRight")
filter.setValue(CIVector(cgPoint: bottomRight), forKey: "inputBottomRight")
filter.setValue(CIVector(cgPoint: bottomLeft), forKey: "inputBottomLeft")
filter.setValue(crop, forKey: "inputCrop")
return filter.outputImage ?? .empty()
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
public func perspectiveRotate(focalLength: Float = 28,
pitch: Float = 0,
yaw: Float = 0,
roll: Float = 0) -> CIImage {
let filter = CIFilter.perspectiveRotate()
filter.setValue(self, forKey: "inputImage")
filter.focalLength = focalLength
filter.pitch = pitch
filter.yaw = yaw
filter.roll = roll
return filter.outputImage ?? .empty()
}
public func perspectiveTransform(topLeft: CGPoint = CGPoint(x: 118, y: 484),
topRight: CGPoint = CGPoint(x: 646, y: 507),
bottomRight: CGPoint = CGPoint(x: 548, y: 140),
bottomLeft: CGPoint = CGPoint(x: 155, y: 153)) -> CIImage {
guard let filter = CIFilter(name: "CIPerspectiveTransform") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: topLeft), forKey: "inputTopLeft")
filter.setValue(CIVector(cgPoint: topRight), forKey: "inputTopRight")
filter.setValue(CIVector(cgPoint: bottomRight), forKey: "inputBottomRight")
filter.setValue(CIVector(cgPoint: bottomLeft), forKey: "inputBottomLeft")
return filter.outputImage ?? .empty()
}
public func perspectiveTransformWithExtent(extent: CGRect = CGRect(x: 0, y: 0, width: 300, height: 300),
topLeft: CGPoint = CGPoint(x: 118, y: 484),
topRight: CGPoint = CGPoint(x: 646, y: 507),
bottomRight: CGPoint = CGPoint(x: 548, y: 140),
bottomLeft: CGPoint = CGPoint(x: 155, y: 153)) -> CIImage {
guard let filter = CIFilter(name: "CIPerspectiveTransformWithExtent") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgRect: extent), forKey: "inputExtent")
filter.setValue(CIVector(cgPoint: topLeft), forKey: "inputTopLeft")
filter.setValue(CIVector(cgPoint: topRight), forKey: "inputTopRight")
filter.setValue(CIVector(cgPoint: bottomRight), forKey: "inputBottomRight")
filter.setValue(CIVector(cgPoint: bottomLeft), forKey: "inputBottomLeft")
return filter.outputImage ?? .empty()
}
public func straighten(angle: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CIStraightenFilter") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(angle, forKey: "inputAngle")
return filter.outputImage ?? .empty()
}
public func accordionFoldTransition(targetImage: CIImage,
bottomHeight: Float = 0,
numberOfFolds: Float = 3,
foldShadowAmount: Float = 0.1,
time: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CIAccordionFoldTransition") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(targetImage, forKey: "inputTargetImage")
filter.setValue(bottomHeight, forKey: "inputBottomHeight")
filter.setValue(numberOfFolds, forKey: "inputNumberOfFolds")
filter.setValue(foldShadowAmount, forKey: "inputFoldShadowAmount")
filter.setValue(time, forKey: "inputTime")
return filter.outputImage ?? .empty()
}
public func barsSwipeTransition(targetImage: CIImage,
angle: Float = 3.141592653589793,
width: Float = 30,
barOffset: Float = 10,
time: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CIBarsSwipeTransition") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(targetImage, forKey: "inputTargetImage")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(barOffset, forKey: "inputBarOffset")
filter.setValue(time, forKey: "inputTime")
return filter.outputImage ?? .empty()
}
public func copyMachineTransition(targetImage: CIImage,
extent: CGRect = CGRect(x: 0, y: 0, width: 300, height: 300),
color: CIColor = CIColor(red: 0.6, green: 1, blue: 0.8, alpha: 1),
time: Float = 0,
angle: Float = 0,
width: Float = 200,
opacity: Float = 1.3) -> CIImage {
guard let filter = CIFilter(name: "CICopyMachineTransition") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(targetImage, forKey: "inputTargetImage")
filter.setValue(CIVector(cgRect: extent), forKey: "inputExtent")
filter.setValue(color, forKey: "inputColor")
filter.setValue(time, forKey: "inputTime")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(opacity, forKey: "inputOpacity")
return filter.outputImage ?? .empty()
}
public func disintegrateWithMaskTransition(targetImage: CIImage,
maskImage: CIImage,
time: Float = 0,
shadowRadius: Float = 8,
shadowDensity: Float = 0.65,
shadowOffset: CGPoint = CGPoint(x: 0, y: -10)) -> CIImage {
guard let filter = CIFilter(name: "CIDisintegrateWithMaskTransition") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(targetImage, forKey: "inputTargetImage")
filter.setValue(maskImage, forKey: "inputMaskImage")
filter.setValue(time, forKey: "inputTime")
filter.setValue(shadowRadius, forKey: "inputShadowRadius")
filter.setValue(shadowDensity, forKey: "inputShadowDensity")
filter.setValue(shadowOffset, forKey: "inputShadowOffset")
return filter.outputImage ?? .empty()
}
public func dissolveTransition(targetImage: CIImage,
time: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CIDissolveTransition") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(targetImage, forKey: "inputTargetImage")
filter.setValue(time, forKey: "inputTime")
return filter.outputImage ?? .empty()
}
public func flashTransition(targetImage: CIImage,
center: CGPoint = CGPoint(x: 150, y: 150),
extent: CGRect = CGRect(x: 0, y: 0, width: 300, height: 300),
color: CIColor = CIColor(red: 1, green: 0.8, blue: 0.6, alpha: 1),
time: Float = 0,
maxStriationRadius: Float = 2.58,
striationStrength: Float = 0.5,
striationContrast: Float = 1.375,
fadeThreshold: Float = 0.85) -> CIImage {
guard let filter = CIFilter(name: "CIFlashTransition") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(targetImage, forKey: "inputTargetImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(CIVector(cgRect: extent), forKey: "inputExtent")
filter.setValue(color, forKey: "inputColor")
filter.setValue(time, forKey: "inputTime")
filter.setValue(maxStriationRadius, forKey: "inputMaxStriationRadius")
filter.setValue(striationStrength, forKey: "inputStriationStrength")
filter.setValue(striationContrast, forKey: "inputStriationContrast")
filter.setValue(fadeThreshold, forKey: "inputFadeThreshold")
return filter.outputImage ?? .empty()
}
public func modTransition(targetImage: CIImage,
center: CGPoint = CGPoint(x: 150, y: 150),
time: Float = 0,
angle: Float = 2,
radius: Float = 150,
compression: Float = 300) -> CIImage {
guard let filter = CIFilter(name: "CIModTransition") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(targetImage, forKey: "inputTargetImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(time, forKey: "inputTime")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(compression, forKey: "inputCompression")
return filter.outputImage ?? .empty()
}
public func pageCurlTransition(targetImage: CIImage,
backsideImage: CIImage,
shadingImage: CIImage,
extent: CGRect = CGRect(x: 0, y: 0, width: 300, height: 300),
time: Float = 0,
angle: Float = 0,
radius: Float = 100) -> CIImage {
guard let filter = CIFilter(name: "CIPageCurlTransition") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(targetImage, forKey: "inputTargetImage")
filter.setValue(backsideImage, forKey: "inputBacksideImage")
filter.setValue(shadingImage, forKey: "inputShadingImage")
filter.setValue(CIVector(cgRect: extent), forKey: "inputExtent")
filter.setValue(time, forKey: "inputTime")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
public func pageCurlWithShadowTransition(targetImage: CIImage,
backsideImage: CIImage,
extent: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0),
time: Float = 0,
angle: Float = 0,
radius: Float = 100,
shadowSize: Float = 0.5,
shadowAmount: Float = 0.7,
shadowExtent: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)) -> CIImage {
guard let filter = CIFilter(name: "CIPageCurlWithShadowTransition") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(targetImage, forKey: "inputTargetImage")
filter.setValue(backsideImage, forKey: "inputBacksideImage")
filter.setValue(CIVector(cgRect: extent), forKey: "inputExtent")
filter.setValue(time, forKey: "inputTime")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(shadowSize, forKey: "inputShadowSize")
filter.setValue(shadowAmount, forKey: "inputShadowAmount")
filter.setValue(CIVector(cgRect: shadowExtent), forKey: "inputShadowExtent")
return filter.outputImage ?? .empty()
}
public func rippleTransition(targetImage: CIImage,
shadingImage: CIImage,
center: CGPoint = CGPoint(x: 150, y: 150),
extent: CGRect = CGRect(x: 0, y: 0, width: 300, height: 300),
time: Float = 0,
width: Float = 100,
scale: Float = 50) -> CIImage {
guard let filter = CIFilter(name: "CIRippleTransition") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(targetImage, forKey: "inputTargetImage")
filter.setValue(shadingImage, forKey: "inputShadingImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(CIVector(cgRect: extent), forKey: "inputExtent")
filter.setValue(time, forKey: "inputTime")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(scale, forKey: "inputScale")
return filter.outputImage ?? .empty()
}
public func swipeTransition(targetImage: CIImage,
extent: CGRect = CGRect(x: 0, y: 0, width: 300, height: 300),
color: CIColor = CIColor(red: 1, green: 1, blue: 1, alpha: 1),
time: Float = 0,
angle: Float = 0,
width: Float = 300,
opacity: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CISwipeTransition") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(targetImage, forKey: "inputTargetImage")
filter.setValue(CIVector(cgRect: extent), forKey: "inputExtent")
filter.setValue(color, forKey: "inputColor")
filter.setValue(time, forKey: "inputTime")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(opacity, forKey: "inputOpacity")
return filter.outputImage ?? .empty()
}
public func colorClamp(minComponents: CIVector = CIVector(x: 0, y: 0, z: 0, w: 0),
maxComponents: CIVector = CIVector(x: 1, y: 1, z: 1, w: 1)) -> CIImage {
guard let filter = CIFilter(name: "CIColorClamp") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(minComponents, forKey: "inputMinComponents")
filter.setValue(maxComponents, forKey: "inputMaxComponents")
return filter.outputImage ?? .empty()
}
public func colorControls(saturation: Float = 1,
brightness: Float = 0,
contrast: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CIColorControls") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(saturation, forKey: "inputSaturation")
filter.setValue(brightness, forKey: "inputBrightness")
filter.setValue(contrast, forKey: "inputContrast")
return filter.outputImage ?? .empty()
}
public func colorMatrix(rVector: CIVector = CIVector(x: 1, y: 0, z: 0, w: 0),
gVector: CIVector = CIVector(x: 0, y: 1, z: 0, w: 0),
bVector: CIVector = CIVector(x: 0, y: 0, z: 1, w: 0),
aVector: CIVector = CIVector(x: 0, y: 0, z: 0, w: 1),
biasVector: CIVector = CIVector(x: 0, y: 0, z: 0, w: 0)) -> CIImage {
guard let filter = CIFilter(name: "CIColorMatrix") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(rVector, forKey: "inputRVector")
filter.setValue(gVector, forKey: "inputGVector")
filter.setValue(bVector, forKey: "inputBVector")
filter.setValue(aVector, forKey: "inputAVector")
filter.setValue(biasVector, forKey: "inputBiasVector")
return filter.outputImage ?? .empty()
}
public func colorPolynomial(redCoefficients: CIVector = CIVector(x: 0, y: 1, z: 0, w: 0),
greenCoefficients: CIVector = CIVector(x: 0, y: 1, z: 0, w: 0),
blueCoefficients: CIVector = CIVector(x: 0, y: 1, z: 0, w: 0),
alphaCoefficients: CIVector = CIVector(x: 0, y: 1, z: 0, w: 0)) -> CIImage {
guard let filter = CIFilter(name: "CIColorPolynomial") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(redCoefficients, forKey: "inputRedCoefficients")
filter.setValue(greenCoefficients, forKey: "inputGreenCoefficients")
filter.setValue(blueCoefficients, forKey: "inputBlueCoefficients")
filter.setValue(alphaCoefficients, forKey: "inputAlphaCoefficients")
return filter.outputImage ?? .empty()
}
public func depthToDisparity() -> CIImage {
return self.applyingFilter("CIDepthToDisparity", parameters: [:])
}
public func disparityToDepth() -> CIImage {
return self.applyingFilter("CIDisparityToDepth", parameters: [:])
}
public func exposureAdjust(ev: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CIExposureAdjust") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(ev, forKey: "inputEV")
return filter.outputImage ?? .empty()
}
public func gammaAdjust(power: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CIGammaAdjust") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(power, forKey: "inputPower")
return filter.outputImage ?? .empty()
}
public func hueAdjust(angle: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CIHueAdjust") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(angle, forKey: "inputAngle")
return filter.outputImage ?? .empty()
}
public func linearToSRGBToneCurve() -> CIImage {
return self.applyingFilter("CILinearToSRGBToneCurve", parameters: [:])
}
public func sRGBToneCurveToLinear() -> CIImage {
return self.applyingFilter("CISRGBToneCurveToLinear", parameters: [:])
}
public func temperatureAndTint(neutral: CIVector = CIVector(x: 6500, y: 0),
targetNeutral: CIVector = CIVector(x: 6500, y: 0)) -> CIImage {
guard let filter = CIFilter(name: "CITemperatureAndTint") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(neutral, forKey: "inputNeutral")
filter.setValue(targetNeutral, forKey: "inputTargetNeutral")
return filter.outputImage ?? .empty()
}
public func toneCurve(point0: CGPoint = CGPoint(x: 0, y: 0),
point1: CGPoint = CGPoint(x: 0.25, y: 0.25),
point2: CGPoint = CGPoint(x: 0.5, y: 0.5),
point3: CGPoint = CGPoint(x: 0.75, y: 0.75),
point4: CGPoint = CGPoint(x: 1, y: 1)) -> CIImage {
guard let filter = CIFilter(name: "CIToneCurve") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: point0), forKey: "inputPoint0")
filter.setValue(CIVector(cgPoint: point1), forKey: "inputPoint1")
filter.setValue(CIVector(cgPoint: point2), forKey: "inputPoint2")
filter.setValue(CIVector(cgPoint: point3), forKey: "inputPoint3")
filter.setValue(CIVector(cgPoint: point4), forKey: "inputPoint4")
return filter.outputImage ?? .empty()
}
public func vibrance(amount: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CIVibrance") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(amount, forKey: "inputAmount")
return filter.outputImage ?? .empty()
}
public func whitePointAdjust(color: CIColor = CIColor(red: 1, green: 1, blue: 1, alpha: 1)) -> CIImage {
guard let filter = CIFilter(name: "CIWhitePointAdjust") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(color, forKey: "inputColor")
return filter.outputImage ?? .empty()
}
public func colorCrossPolynomial(redCoefficients: CIVector = CIVector([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
greenCoefficients: CIVector = CIVector([0, 1, 0, 0, 0, 0, 0, 0, 0, 0]),
blueCoefficients: CIVector = CIVector([0, 0, 1, 0, 0, 0, 0, 0, 0, 0])) -> CIImage {
guard let filter = CIFilter(name: "CIColorCrossPolynomial") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(redCoefficients, forKey: "inputRedCoefficients")
filter.setValue(greenCoefficients, forKey: "inputGreenCoefficients")
filter.setValue(blueCoefficients, forKey: "inputBlueCoefficients")
return filter.outputImage ?? .empty()
}
public func colorInvert() -> CIImage {
return self.applyingFilter("CIColorInvert", parameters: [:])
}
public func colorMap(gradientImage: CIImage) -> CIImage {
guard let filter = CIFilter(name: "CIColorMap") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(gradientImage, forKey: "inputGradientImage")
return filter.outputImage ?? .empty()
}
public func colorMonochrome(color: CIColor = CIColor(red: 0.6, green: 0.45, blue: 0.3, alpha: 1),
intensity: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CIColorMonochrome") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(color, forKey: "inputColor")
filter.setValue(intensity, forKey: "inputIntensity")
return filter.outputImage ?? .empty()
}
public func colorPosterize(levels: Float = 6) -> CIImage {
guard let filter = CIFilter(name: "CIColorPosterize") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(levels, forKey: "inputLevels")
return filter.outputImage ?? .empty()
}
@available(macOS 10.14, iOS 12.0, tvOS 12.0, *)
public func dither(intensity: Float = 0.1) -> CIImage {
guard let filter = CIFilter(name: "CIDither") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(intensity, forKey: "inputIntensity")
return filter.outputImage ?? .empty()
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
public func documentEnhancer(amount: Float = 1) -> CIImage {
let filter = CIFilter.documentEnhancer()
filter.setValue(self, forKey: "inputImage")
filter.amount = amount
return filter.outputImage ?? .empty()
}
public func falseColor(color0: CIColor = CIColor(red: 0.3, green: 0, blue: 0, alpha: 1),
color1: CIColor = CIColor(red: 1, green: 0.9, blue: 0.8, alpha: 1)) -> CIImage {
guard let filter = CIFilter(name: "CIFalseColor") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(color0, forKey: "inputColor0")
filter.setValue(color1, forKey: "inputColor1")
return filter.outputImage ?? .empty()
}
public func labDeltaE(image2: CIImage) -> CIImage {
guard let filter = CIFilter(name: "CILabDeltaE") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(image2, forKey: "inputImage2")
return filter.outputImage ?? .empty()
}
public func maskToAlpha() -> CIImage {
return self.applyingFilter("CIMaskToAlpha", parameters: [:])
}
public func maximumComponent() -> CIImage {
return self.applyingFilter("CIMaximumComponent", parameters: [:])
}
public func minimumComponent() -> CIImage {
return self.applyingFilter("CIMinimumComponent", parameters: [:])
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
public func paletteCentroid(paletteImage: CIImage,
perceptual: Bool = false) -> CIImage {
let filter = CIFilter.paletteCentroid()
filter.setValue(self, forKey: "inputImage")
filter.paletteImage = paletteImage
filter.perceptual = perceptual
return filter.outputImage ?? .empty()
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
public func palettize(paletteImage: CIImage,
perceptual: Bool = false) -> CIImage {
let filter = CIFilter.palettize()
filter.setValue(self, forKey: "inputImage")
filter.paletteImage = paletteImage
filter.perceptual = perceptual
return filter.outputImage ?? .empty()
}
public func photoEffectChrome() -> CIImage {
return self.applyingFilter("CIPhotoEffectChrome", parameters: [:])
}
public func photoEffectFade() -> CIImage {
return self.applyingFilter("CIPhotoEffectFade", parameters: [:])
}
public func photoEffectInstant() -> CIImage {
return self.applyingFilter("CIPhotoEffectInstant", parameters: [:])
}
public func photoEffectMono() -> CIImage {
return self.applyingFilter("CIPhotoEffectMono", parameters: [:])
}
public func photoEffectNoir() -> CIImage {
return self.applyingFilter("CIPhotoEffectNoir", parameters: [:])
}
public func photoEffectProcess() -> CIImage {
return self.applyingFilter("CIPhotoEffectProcess", parameters: [:])
}
public func photoEffectTonal() -> CIImage {
return self.applyingFilter("CIPhotoEffectTonal", parameters: [:])
}
public func photoEffectTransfer() -> CIImage {
return self.applyingFilter("CIPhotoEffectTransfer", parameters: [:])
}
public func sepiaTone(intensity: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CISepiaTone") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(intensity, forKey: "inputIntensity")
return filter.outputImage ?? .empty()
}
public func thermal() -> CIImage {
return self.applyingFilter("CIThermal", parameters: [:])
}
public func vignette(intensity: Float = 0,
radius: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CIVignette") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(intensity, forKey: "inputIntensity")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
public func vignetteEffect(center: CGPoint = CGPoint(x: 150, y: 150),
radius: Float = 150,
intensity: Float = 1,
falloff: Float = 0.5) -> CIImage {
guard let filter = CIFilter(name: "CIVignetteEffect") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(intensity, forKey: "inputIntensity")
filter.setValue(falloff, forKey: "inputFalloff")
return filter.outputImage ?? .empty()
}
public func xRay() -> CIImage {
return self.applyingFilter("CIXRay", parameters: [:])
}
public func affineClamp(transform: CGAffineTransform = .identity) -> CIImage {
guard let filter = CIFilter(name: "CIAffineClamp") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
#if os(macOS)
let _transform = AffineTransform(m11: transform.a, m12: transform.b, m21: transform.c, m22: transform.d, tX: transform.tx, tY: transform.ty)
filter.setValue(_transform as NSAffineTransform, forKey: "inputTransform")
#else
filter.setValue(NSValue(cgAffineTransform: transform), forKey: "inputTransform")
#endif
return filter.outputImage ?? .empty()
}
public func affineTile(transform: CGAffineTransform = .identity) -> CIImage {
guard let filter = CIFilter(name: "CIAffineTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
#if os(macOS)
let _transform = AffineTransform(m11: transform.a, m12: transform.b, m21: transform.c, m22: transform.d, tX: transform.tx, tY: transform.ty)
filter.setValue(_transform as NSAffineTransform, forKey: "inputTransform")
#else
filter.setValue(NSValue(cgAffineTransform: transform), forKey: "inputTransform")
#endif
return filter.outputImage ?? .empty()
}
public func eightfoldReflectedTile(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 100) -> CIImage {
guard let filter = CIFilter(name: "CIEightfoldReflectedTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
return filter.outputImage ?? .empty()
}
public func fourfoldReflectedTile(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 100,
acuteAngle: Float = 1.570796326794897) -> CIImage {
guard let filter = CIFilter(name: "CIFourfoldReflectedTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(acuteAngle, forKey: "inputAcuteAngle")
return filter.outputImage ?? .empty()
}
public func fourfoldRotatedTile(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 100) -> CIImage {
guard let filter = CIFilter(name: "CIFourfoldRotatedTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
return filter.outputImage ?? .empty()
}
public func fourfoldTranslatedTile(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 100,
acuteAngle: Float = 1.570796326794897) -> CIImage {
guard let filter = CIFilter(name: "CIFourfoldTranslatedTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(acuteAngle, forKey: "inputAcuteAngle")
return filter.outputImage ?? .empty()
}
public func glideReflectedTile(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 100) -> CIImage {
guard let filter = CIFilter(name: "CIGlideReflectedTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
return filter.outputImage ?? .empty()
}
public func kaleidoscope(count: Int = 6,
center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CIKaleidoscope") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(count, forKey: "inputCount")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
return filter.outputImage ?? .empty()
}
public func opTile(center: CGPoint = CGPoint(x: 150, y: 150),
scale: Float = 2.8,
angle: Float = 0,
width: Float = 65) -> CIImage {
guard let filter = CIFilter(name: "CIOpTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(scale, forKey: "inputScale")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
return filter.outputImage ?? .empty()
}
public func parallelogramTile(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
acuteAngle: Float = 1.570796326794897,
width: Float = 100) -> CIImage {
guard let filter = CIFilter(name: "CIParallelogramTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(acuteAngle, forKey: "inputAcuteAngle")
filter.setValue(width, forKey: "inputWidth")
return filter.outputImage ?? .empty()
}
public func perspectiveTile(topLeft: CGPoint = CGPoint(x: 118, y: 484),
topRight: CGPoint = CGPoint(x: 646, y: 507),
bottomRight: CGPoint = CGPoint(x: 548, y: 140),
bottomLeft: CGPoint = CGPoint(x: 155, y: 153)) -> CIImage {
guard let filter = CIFilter(name: "CIPerspectiveTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: topLeft), forKey: "inputTopLeft")
filter.setValue(CIVector(cgPoint: topRight), forKey: "inputTopRight")
filter.setValue(CIVector(cgPoint: bottomRight), forKey: "inputBottomRight")
filter.setValue(CIVector(cgPoint: bottomLeft), forKey: "inputBottomLeft")
return filter.outputImage ?? .empty()
}
public func sixfoldReflectedTile(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 100) -> CIImage {
guard let filter = CIFilter(name: "CISixfoldReflectedTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
return filter.outputImage ?? .empty()
}
public func sixfoldRotatedTile(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 100) -> CIImage {
guard let filter = CIFilter(name: "CISixfoldRotatedTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
return filter.outputImage ?? .empty()
}
public func triangleKaleidoscope(point: CGPoint = CGPoint(x: 150, y: 150),
size: Float = 700,
rotation: Float = 5.924285296593801,
decay: Float = 0.85) -> CIImage {
guard let filter = CIFilter(name: "CITriangleKaleidoscope") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: point), forKey: "inputPoint")
filter.setValue(size, forKey: "inputSize")
filter.setValue(rotation, forKey: "inputRotation")
filter.setValue(decay, forKey: "inputDecay")
return filter.outputImage ?? .empty()
}
public func triangleTile(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 100) -> CIImage {
guard let filter = CIFilter(name: "CITriangleTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
return filter.outputImage ?? .empty()
}
public func twelvefoldReflectedTile(center: CGPoint = CGPoint(x: 150, y: 150),
angle: Float = 0,
width: Float = 100) -> CIImage {
guard let filter = CIFilter(name: "CITwelvefoldReflectedTile") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(angle, forKey: "inputAngle")
filter.setValue(width, forKey: "inputWidth")
return filter.outputImage ?? .empty()
}
public func blendWithAlphaMask(backgroundImage: CIImage,
maskImage: CIImage) -> CIImage {
guard let filter = CIFilter(name: "CIBlendWithAlphaMask") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(backgroundImage, forKey: "inputBackgroundImage")
filter.setValue(maskImage, forKey: "inputMaskImage")
return filter.outputImage ?? .empty()
}
public func blendWithBlueMask(backgroundImage: CIImage,
maskImage: CIImage) -> CIImage {
guard let filter = CIFilter(name: "CIBlendWithBlueMask") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(backgroundImage, forKey: "inputBackgroundImage")
filter.setValue(maskImage, forKey: "inputMaskImage")
return filter.outputImage ?? .empty()
}
public func blendWithMask(backgroundImage: CIImage,
maskImage: CIImage) -> CIImage {
guard let filter = CIFilter(name: "CIBlendWithMask") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(backgroundImage, forKey: "inputBackgroundImage")
filter.setValue(maskImage, forKey: "inputMaskImage")
return filter.outputImage ?? .empty()
}
public func blendWithRedMask(backgroundImage: CIImage,
maskImage: CIImage) -> CIImage {
guard let filter = CIFilter(name: "CIBlendWithRedMask") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(backgroundImage, forKey: "inputBackgroundImage")
filter.setValue(maskImage, forKey: "inputMaskImage")
return filter.outputImage ?? .empty()
}
public func bloom(radius: Float = 10,
intensity: Float = 0.5) -> CIImage {
guard let filter = CIFilter(name: "CIBloom") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(intensity, forKey: "inputIntensity")
return filter.outputImage ?? .empty()
}
public func comicEffect() -> CIImage {
return self.applyingFilter("CIComicEffect", parameters: [:])
}
public func crystallize(radius: Float = 20,
center: CGPoint = CGPoint(x: 150, y: 150)) -> CIImage {
guard let filter = CIFilter(name: "CICrystallize") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
return filter.outputImage ?? .empty()
}
public func depthOfField(point0: CGPoint = CGPoint(x: 0, y: 300),
point1: CGPoint = CGPoint(x: 300, y: 300),
saturation: Float = 1.5,
unsharpMaskRadius: Float = 2.5,
unsharpMaskIntensity: Float = 0.5,
radius: Float = 6) -> CIImage {
guard let filter = CIFilter(name: "CIDepthOfField") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: point0), forKey: "inputPoint0")
filter.setValue(CIVector(cgPoint: point1), forKey: "inputPoint1")
filter.setValue(saturation, forKey: "inputSaturation")
filter.setValue(unsharpMaskRadius, forKey: "inputUnsharpMaskRadius")
filter.setValue(unsharpMaskIntensity, forKey: "inputUnsharpMaskIntensity")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
public func edges(intensity: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CIEdges") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(intensity, forKey: "inputIntensity")
return filter.outputImage ?? .empty()
}
public func edgeWork(radius: Float = 3) -> CIImage {
guard let filter = CIFilter(name: "CIEdgeWork") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
public func gaborGradients() -> CIImage {
let filter = CIFilter.gaborGradients()
filter.setValue(self, forKey: "inputImage")
return filter.outputImage ?? .empty()
}
public func gloom(radius: Float = 10,
intensity: Float = 0.5) -> CIImage {
guard let filter = CIFilter(name: "CIGloom") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(intensity, forKey: "inputIntensity")
return filter.outputImage ?? .empty()
}
public func heightFieldFromMask(radius: Float = 10) -> CIImage {
guard let filter = CIFilter(name: "CIHeightFieldFromMask") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
public func hexagonalPixellate(center: CGPoint = CGPoint(x: 150, y: 150),
scale: Float = 8) -> CIImage {
guard let filter = CIFilter(name: "CIHexagonalPixellate") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(scale, forKey: "inputScale")
return filter.outputImage ?? .empty()
}
public func highlightShadowAdjust(radius: Float = 0,
shadowAmount: Float = 0,
highlightAmount: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CIHighlightShadowAdjust") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(shadowAmount, forKey: "inputShadowAmount")
filter.setValue(highlightAmount, forKey: "inputHighlightAmount")
return filter.outputImage ?? .empty()
}
public func lineOverlay(nrNoiseLevel: Float = 0.07000000000000001,
nrSharpness: Float = 0.71,
edgeIntensity: Float = 1,
threshold: Float = 0.1,
contrast: Float = 50) -> CIImage {
guard let filter = CIFilter(name: "CILineOverlay") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(nrNoiseLevel, forKey: "inputNRNoiseLevel")
filter.setValue(nrSharpness, forKey: "inputNRSharpness")
filter.setValue(edgeIntensity, forKey: "inputEdgeIntensity")
filter.setValue(threshold, forKey: "inputThreshold")
filter.setValue(contrast, forKey: "inputContrast")
return filter.outputImage ?? .empty()
}
@available(macOS 10.14, iOS 12.0, tvOS 12.0, *)
public func mix(backgroundImage: CIImage,
amount: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CIMix") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(backgroundImage, forKey: "inputBackgroundImage")
filter.setValue(amount, forKey: "inputAmount")
return filter.outputImage ?? .empty()
}
public func pixellate(center: CGPoint = CGPoint(x: 150, y: 150),
scale: Float = 8) -> CIImage {
guard let filter = CIFilter(name: "CIPixellate") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(scale, forKey: "inputScale")
return filter.outputImage ?? .empty()
}
public func pointillize(radius: Float = 20,
center: CGPoint = CGPoint(x: 150, y: 150)) -> CIImage {
guard let filter = CIFilter(name: "CIPointillize") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
return filter.outputImage ?? .empty()
}
@available(macOS 10.14, iOS 12.0, tvOS 12.0, *)
public func saliencyMap() -> CIImage {
return self.applyingFilter("CISaliencyMapFilter", parameters: [:])
}
public func shadedMaterial(shadingImage: CIImage,
scale: Float = 10) -> CIImage {
guard let filter = CIFilter(name: "CIShadedMaterial") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(shadingImage, forKey: "inputShadingImage")
filter.setValue(scale, forKey: "inputScale")
return filter.outputImage ?? .empty()
}
public func spotColor(centerColor1: CIColor = CIColor(red: 0.0784, green: 0.0627, blue: 0.0706, alpha: 1),
replacementColor1: CIColor = CIColor(red: 0.4392, green: 0.1922, blue: 0.1961, alpha: 1),
closeness1: Float = 0.22,
contrast1: Float = 0.98,
centerColor2: CIColor = CIColor(red: 0.5255, green: 0.3059, blue: 0.3451, alpha: 1),
replacementColor2: CIColor = CIColor(red: 0.9137, green: 0.5608, blue: 0.5059, alpha: 1),
closeness2: Float = 0.15,
contrast2: Float = 0.98,
centerColor3: CIColor = CIColor(red: 0.9216, green: 0.4549, blue: 0.3333, alpha: 1),
replacementColor3: CIColor = CIColor(red: 0.9098, green: 0.7529, blue: 0.6078, alpha: 1),
closeness3: Float = 0.5,
contrast3: Float = 0.99) -> CIImage {
guard let filter = CIFilter(name: "CISpotColor") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(centerColor1, forKey: "inputCenterColor1")
filter.setValue(replacementColor1, forKey: "inputReplacementColor1")
filter.setValue(closeness1, forKey: "inputCloseness1")
filter.setValue(contrast1, forKey: "inputContrast1")
filter.setValue(centerColor2, forKey: "inputCenterColor2")
filter.setValue(replacementColor2, forKey: "inputReplacementColor2")
filter.setValue(closeness2, forKey: "inputCloseness2")
filter.setValue(contrast2, forKey: "inputContrast2")
filter.setValue(centerColor3, forKey: "inputCenterColor3")
filter.setValue(replacementColor3, forKey: "inputReplacementColor3")
filter.setValue(closeness3, forKey: "inputCloseness3")
filter.setValue(contrast3, forKey: "inputContrast3")
return filter.outputImage ?? .empty()
}
public func spotLight(lightPosition: CIVector = CIVector(x: 400, y: 600, z: 150),
lightPointsAt: CIVector = CIVector(x: 200, y: 200, z: 0),
brightness: Float = 3,
concentration: Float = 0.1,
color: CIColor = CIColor(red: 1, green: 1, blue: 1, alpha: 1)) -> CIImage {
guard let filter = CIFilter(name: "CISpotLight") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(lightPosition, forKey: "inputLightPosition")
filter.setValue(lightPointsAt, forKey: "inputLightPointsAt")
filter.setValue(brightness, forKey: "inputBrightness")
filter.setValue(concentration, forKey: "inputConcentration")
filter.setValue(color, forKey: "inputColor")
return filter.outputImage ?? .empty()
}
public func bokehBlur(radius: Float = 20,
ringAmount: Float = 0,
ringSize: Float = 0.1,
softness: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CIBokehBlur") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(ringAmount, forKey: "inputRingAmount")
filter.setValue(ringSize, forKey: "inputRingSize")
filter.setValue(softness, forKey: "inputSoftness")
return filter.outputImage ?? .empty()
}
public func boxBlur(radius: Float = 10) -> CIImage {
guard let filter = CIFilter(name: "CIBoxBlur") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
public func discBlur(radius: Float = 8) -> CIImage {
guard let filter = CIFilter(name: "CIDiscBlur") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
public func maskedVariableBlur(mask: CIImage,
radius: Float = 5) -> CIImage {
guard let filter = CIFilter(name: "CIMaskedVariableBlur") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(mask, forKey: "inputMask")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
public func median() -> CIImage {
return self.applyingFilter("CIMedianFilter", parameters: [:])
}
public func morphologyGradient(radius: Float = 5) -> CIImage {
guard let filter = CIFilter(name: "CIMorphologyGradient") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
public func morphologyMaximum(radius: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CIMorphologyMaximum") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
public func morphologyMinimum(radius: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CIMorphologyMinimum") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
public func morphologyRectangleMaximum(width: Float = 5,
height: Float = 5) -> CIImage {
let filter = CIFilter.morphologyRectangleMaximum()
filter.setValue(self, forKey: "inputImage")
filter.width = width
filter.height = height
return filter.outputImage ?? .empty()
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
public func morphologyRectangleMinimum(width: Float = 5,
height: Float = 5) -> CIImage {
let filter = CIFilter.morphologyRectangleMinimum()
filter.setValue(self, forKey: "inputImage")
filter.width = width
filter.height = height
return filter.outputImage ?? .empty()
}
public func motionBlur(radius: Float = 20,
angle: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CIMotionBlur") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(angle, forKey: "inputAngle")
return filter.outputImage ?? .empty()
}
public func noiseReduction(noiseLevel: Float = 0.02,
sharpness: Float = 0.4) -> CIImage {
guard let filter = CIFilter(name: "CINoiseReduction") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(noiseLevel, forKey: "inputNoiseLevel")
filter.setValue(sharpness, forKey: "inputSharpness")
return filter.outputImage ?? .empty()
}
public func zoomBlur(center: CGPoint = CGPoint(x: 150, y: 150),
amount: Float = 20) -> CIImage {
guard let filter = CIFilter(name: "CIZoomBlur") else { return .empty() }
filter.setValue(self, forKey: "inputImage")
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(amount, forKey: "inputAmount")
return filter.outputImage ?? .empty()
}
}
extension CIImage {
public class func GaussianGradient(center: CGPoint = CGPoint(x: 150, y: 150),
color0: CIColor = CIColor(red: 1, green: 1, blue: 1, alpha: 1),
color1: CIColor = CIColor(red: 0, green: 0, blue: 0, alpha: 0),
radius: Float = 300) -> CIImage {
guard let filter = CIFilter(name: "CIGaussianGradient") else { return .empty() }
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(color0, forKey: "inputColor0")
filter.setValue(color1, forKey: "inputColor1")
filter.setValue(radius, forKey: "inputRadius")
return filter.outputImage ?? .empty()
}
public class func HueSaturationValueGradient(value: Float = 1,
radius: Float = 300,
softness: Float = 1,
dither: Float = 1,
colorSpace: CGColorSpace? = CGColorSpace(name: CGColorSpace.sRGB)) -> CIImage {
guard let filter = CIFilter(name: "CIHueSaturationValueGradient") else { return .empty() }
filter.setValue(value, forKey: "inputValue")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(softness, forKey: "inputSoftness")
filter.setValue(dither, forKey: "inputDither")
filter.setValue(colorSpace, forKey: "inputColorSpace")
return filter.outputImage ?? .empty()
}
public class func LinearGradient(point0: CGPoint = CGPoint(x: 0, y: 0),
point1: CGPoint = CGPoint(x: 200, y: 200),
color0: CIColor = CIColor(red: 1, green: 1, blue: 1, alpha: 1),
color1: CIColor = CIColor(red: 0, green: 0, blue: 0, alpha: 1)) -> CIImage {
guard let filter = CIFilter(name: "CILinearGradient") else { return .empty() }
filter.setValue(CIVector(cgPoint: point0), forKey: "inputPoint0")
filter.setValue(CIVector(cgPoint: point1), forKey: "inputPoint1")
filter.setValue(color0, forKey: "inputColor0")
filter.setValue(color1, forKey: "inputColor1")
return filter.outputImage ?? .empty()
}
public class func RadialGradient(center: CGPoint = CGPoint(x: 150, y: 150),
radius0: Float = 5,
radius1: Float = 100,
color0: CIColor = CIColor(red: 1, green: 1, blue: 1, alpha: 1),
color1: CIColor = CIColor(red: 0, green: 0, blue: 0, alpha: 1)) -> CIImage {
guard let filter = CIFilter(name: "CIRadialGradient") else { return .empty() }
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(radius0, forKey: "inputRadius0")
filter.setValue(radius1, forKey: "inputRadius1")
filter.setValue(color0, forKey: "inputColor0")
filter.setValue(color1, forKey: "inputColor1")
return filter.outputImage ?? .empty()
}
public class func SmoothLinearGradient(point0: CGPoint = CGPoint(x: 0, y: 0),
point1: CGPoint = CGPoint(x: 200, y: 200),
color0: CIColor = CIColor(red: 1, green: 1, blue: 1, alpha: 1),
color1: CIColor = CIColor(red: 0, green: 0, blue: 0, alpha: 1)) -> CIImage {
guard let filter = CIFilter(name: "CISmoothLinearGradient") else { return .empty() }
filter.setValue(CIVector(cgPoint: point0), forKey: "inputPoint0")
filter.setValue(CIVector(cgPoint: point1), forKey: "inputPoint1")
filter.setValue(color0, forKey: "inputColor0")
filter.setValue(color1, forKey: "inputColor1")
return filter.outputImage ?? .empty()
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
public class func RoundedRectangleGenerator(extent: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100),
radius: Float = 10,
color: CIColor = CIColor(red: 1, green: 1, blue: 1, alpha: 1)) -> CIImage {
let filter = CIFilter.roundedRectangleGenerator()
filter.extent = extent
filter.radius = radius
filter.color = color
return filter.outputImage ?? .empty()
}
public class func StarShineGenerator(center: CGPoint = CGPoint(x: 150, y: 150),
color: CIColor = CIColor(red: 1, green: 0.8, blue: 0.6, alpha: 1),
radius: Float = 50,
crossScale: Float = 15,
crossAngle: Float = 0.6,
crossOpacity: Float = -2,
crossWidth: Float = 2.5,
epsilon: Float = -2) -> CIImage {
guard let filter = CIFilter(name: "CIStarShineGenerator") else { return .empty() }
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(color, forKey: "inputColor")
filter.setValue(radius, forKey: "inputRadius")
filter.setValue(crossScale, forKey: "inputCrossScale")
filter.setValue(crossAngle, forKey: "inputCrossAngle")
filter.setValue(crossOpacity, forKey: "inputCrossOpacity")
filter.setValue(crossWidth, forKey: "inputCrossWidth")
filter.setValue(epsilon, forKey: "inputEpsilon")
return filter.outputImage ?? .empty()
}
public class func StripesGenerator(center: CGPoint = CGPoint(x: 150, y: 150),
color0: CIColor = CIColor(red: 1, green: 1, blue: 1, alpha: 1),
color1: CIColor = CIColor(red: 0, green: 0, blue: 0, alpha: 1),
width: Float = 80,
sharpness: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CIStripesGenerator") else { return .empty() }
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(color0, forKey: "inputColor0")
filter.setValue(color1, forKey: "inputColor1")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(sharpness, forKey: "inputSharpness")
return filter.outputImage ?? .empty()
}
public class func SunbeamsGenerator(center: CGPoint = CGPoint(x: 150, y: 150),
color: CIColor = CIColor(red: 1, green: 0.5, blue: 0, alpha: 1),
sunRadius: Float = 40,
maxStriationRadius: Float = 2.58,
striationStrength: Float = 0.5,
striationContrast: Float = 1.375,
time: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CISunbeamsGenerator") else { return .empty() }
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(color, forKey: "inputColor")
filter.setValue(sunRadius, forKey: "inputSunRadius")
filter.setValue(maxStriationRadius, forKey: "inputMaxStriationRadius")
filter.setValue(striationStrength, forKey: "inputStriationStrength")
filter.setValue(striationContrast, forKey: "inputStriationContrast")
filter.setValue(time, forKey: "inputTime")
return filter.outputImage ?? .empty()
}
public class func AztecCodeGenerator(message: String,
correction level: Float = 23,
layers: Float? = nil,
compact: Bool = false) -> CIImage {
guard let data = message.data(using: .isoLatin1) else { return .empty() }
guard let filter = CIFilter(name: "CIAztecCodeGenerator") else { return .empty() }
filter.setValue(data, forKey: "inputMessage")
filter.setValue(level, forKey: "inputCorrectionLevel")
filter.setValue(layers, forKey: "inputLayers")
filter.setValue(compact, forKey: "inputCompactStyle")
return filter.outputImage ?? .empty()
}
public enum QRCorrectionLevel: String, CaseIterable {
case low = "L"
case medium = "M"
case quartile = "Q"
case high = "H"
}
public class func QRCodeGenerator(message: String,
correction level: QRCorrectionLevel = .medium) -> CIImage {
guard let data = message.data(using: .isoLatin1) else { return .empty() }
guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return .empty() }
filter.setValue(data, forKey: "inputMessage")
filter.setValue(level.rawValue, forKey: "inputCorrectionLevel")
return filter.outputImage ?? .empty()
}
public class func Code128BarcodeGenerator(message: String,
quietSpace: Float = 7,
barcodeHeight: Float = 32) -> CIImage {
guard let data = message.data(using: .ascii) else { return .empty() }
guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else { return .empty() }
filter.setValue(data, forKey: "inputMessage")
filter.setValue(quietSpace, forKey: "inputQuietSpace")
filter.setValue(barcodeHeight, forKey: "inputBarcodeHeight")
return filter.outputImage ?? .empty()
}
public class func CheckerboardGenerator(center: CGPoint = CGPoint(x: 150, y: 150),
color0: CIColor = CIColor(red: 1, green: 1, blue: 1, alpha: 1),
color1: CIColor = CIColor(red: 0, green: 0, blue: 0, alpha: 1),
width: Float = 80,
sharpness: Float = 1) -> CIImage {
guard let filter = CIFilter(name: "CICheckerboardGenerator") else { return .empty() }
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(color0, forKey: "inputColor0")
filter.setValue(color1, forKey: "inputColor1")
filter.setValue(width, forKey: "inputWidth")
filter.setValue(sharpness, forKey: "inputSharpness")
return filter.outputImage ?? .empty()
}
public class func LenticularHaloGenerator(center: CGPoint = CGPoint(x: 150, y: 150),
color: CIColor = CIColor(red: 1, green: 0.9, blue: 0.8, alpha: 1),
haloRadius: Float = 70,
haloWidth: Float = 87,
haloOverlap: Float = 0.77,
striationStrength: Float = 0.5,
striationContrast: Float = 1,
time: Float = 0) -> CIImage {
guard let filter = CIFilter(name: "CILenticularHaloGenerator") else { return .empty() }
filter.setValue(CIVector(cgPoint: center), forKey: "inputCenter")
filter.setValue(color, forKey: "inputColor")
filter.setValue(haloRadius, forKey: "inputHaloRadius")
filter.setValue(haloWidth, forKey: "inputHaloWidth")
filter.setValue(haloOverlap, forKey: "inputHaloOverlap")
filter.setValue(striationStrength, forKey: "inputStriationStrength")
filter.setValue(striationContrast, forKey: "inputStriationContrast")
filter.setValue(time, forKey: "inputTime")
return filter.outputImage ?? .empty()
}
public class func PDF417BarcodeGenerator(message: String,
minWidth: Float,
maxWidth: Float,
minHeight: Float,
maxHeight: Float,
dataColumns: Float,
rows: Float,
preferredAspectRatio: Float,
compactionMode: Float,
compactStyle: Float,
correctionLevel: Float,
alwaysSpecifyCompaction: Float) -> CIImage {
guard let data = message.data(using: .isoLatin1) else { return .empty() }
guard let filter = CIFilter(name: "CIPDF417BarcodeGenerator") else { return .empty() }
filter.setValue(data, forKey: "inputMessage")
filter.setValue(minWidth, forKey: "inputMinWidth")
filter.setValue(maxWidth, forKey: "inputMaxWidth")
filter.setValue(minHeight, forKey: "inputMinHeight")
filter.setValue(maxHeight, forKey: "inputMaxHeight")
filter.setValue(dataColumns, forKey: "inputDataColumns")
filter.setValue(rows, forKey: "inputRows")
filter.setValue(preferredAspectRatio, forKey: "inputPreferredAspectRatio")
filter.setValue(compactionMode, forKey: "inputCompactionMode")
filter.setValue(compactStyle, forKey: "inputCompactStyle")
filter.setValue(correctionLevel, forKey: "inputCorrectionLevel")
filter.setValue(alwaysSpecifyCompaction, forKey: "inputAlwaysSpecifyCompaction")
return filter.outputImage ?? .empty()
}
public class func RandomGenerator() -> CIImage {
return CIFilter(name: "CIRandomGenerator")?.outputImage ?? .empty()
}
}
#endif
| mit | bcfe8b39de313771de2494e1aff4f2fb | 42.70263 | 148 | 0.563119 | 4.735807 | false | false | false | false |
TonnyTao/HowSwift | how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/Filter.swift | 8 | 2923 | //
// Filter.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/17/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Filters the elements of an observable sequence based on a predicate.
- seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html)
- parameter predicate: A function to test each source element for a condition.
- returns: An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
public func filter(_ predicate: @escaping (Element) throws -> Bool)
-> Observable<Element> {
Filter(source: self.asObservable(), predicate: predicate)
}
}
extension ObservableType {
/**
Skips elements and completes (or errors) when the observable sequence completes (or errors). Equivalent to filter that always returns false.
- seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html)
- returns: An observable sequence that skips all elements of the source sequence.
*/
public func ignoreElements()
-> Observable<Never> {
self.flatMap { _ in Observable<Never>.empty() }
}
}
final private class FilterSink<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Predicate = (Element) throws -> Bool
typealias Element = Observer.Element
private let predicate: Predicate
init(predicate: @escaping Predicate, observer: Observer, cancel: Cancelable) {
self.predicate = predicate
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case .next(let value):
do {
let satisfies = try self.predicate(value)
if satisfies {
self.forwardOn(.next(value))
}
}
catch let e {
self.forwardOn(.error(e))
self.dispose()
}
case .completed, .error:
self.forwardOn(event)
self.dispose()
}
}
}
final private class Filter<Element>: Producer<Element> {
typealias Predicate = (Element) throws -> Bool
private let source: Observable<Element>
private let predicate: Predicate
init(source: Observable<Element>, predicate: @escaping Predicate) {
self.source = source
self.predicate = predicate
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = FilterSink(predicate: self.predicate, observer: observer, cancel: cancel)
let subscription = self.source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| mit | fb066b18ff18f4fa4155e1629000095b | 32.976744 | 171 | 0.645791 | 4.813839 | false | false | false | false |
royratcliffe/ManagedObject | Sources/NSEntityDescription+ManagedObject.swift | 1 | 3040 | // ManagedObject NSEntityDescription+ManagedObject.swift
//
// Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom
//
// 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, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//------------------------------------------------------------------------------
import CoreData
extension NSEntityDescription {
/// Returns a new fetch request for this entity. Returns `nil` if the entity
/// description has no name.
public func fetchRequest<Result: NSFetchRequestResult>() -> NSFetchRequest<Result>? {
guard let name = name else { return nil }
return NSFetchRequest<Result>(entityName: name)
}
/// Returns new fetch request with given predicate; `nil` for nameless entity.
public func fetchRequest<Result: NSFetchRequestResult>(where predicate: NSPredicate) -> NSFetchRequest<Result>? {
guard let request: NSFetchRequest<Result> = fetchRequest() else { return nil }
request.predicate = predicate
return request
}
// MARK: - Fetch
/// Fetches the first result.
public func fetchFirst<Result: NSFetchRequestResult>(in context: NSManagedObjectContext) throws -> Result? {
guard let request: NSFetchRequest<Result> = fetchRequest() else { return nil }
request.fetchLimit = 1
return try context.fetch(request).first
}
/// Fetches all results matching the given predicate.
public func fetchAll<Result: NSFetchRequestResult>(where predicate: NSPredicate, in context: NSManagedObjectContext) throws -> [Result] {
guard let request: NSFetchRequest<Result> = fetchRequest(where: predicate) else { return [] }
return try context.fetch(request)
}
/// Fetches the first result matching the given predicate.
public func fetchFirst<Result: NSFetchRequestResult>(where predicate: NSPredicate, in context: NSManagedObjectContext) throws -> Result? {
guard let request: NSFetchRequest<Result> = fetchRequest(where: predicate) else { return nil }
request.fetchLimit = 1
return try context.fetch(request).first
}
}
| mit | ba8774bba94d7664b6317a654dd012c6 | 45.630769 | 140 | 0.730782 | 4.96072 | false | false | false | false |
sashohadz/swift | photoStories/photoStories/photoStories/AppDelegate.swift | 1 | 5397 | //
// AppDelegate.swift
// photoStories
//
// Created by Sasho Hadzhiev on 2/21/17.
// Copyright © 2017 Sasho Hadzhiev. All rights reserved.
//
import UserNotifications
import UIKit
#if DEBUG
import AdSupport
#endif
import Leanplum
//TO DO:
fileprivate let viewActionIdentifier = "VIEW_IDENTIFIER"
fileprivate let newsCategoryIdentifier = "NEWS_CATEGORY"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
var welcomeMessage = LPVar.define("sashoTestVar",with: "Welcome to Leanplum!")
var profileImage = LPVar.define("loginImage", withFile: "plum")
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
let appId = "app_dHd3SBGm3lRS4YsQf3UDC1r5NdZjfsW7GpW0KMcx0HU"
let prodkey = "prod_qGy3LNPI9iQRpD91fzHbbVqV0izYDVUaeJgkOhh2Fsk"
let devKey = "dev_JmC5uop607VcQaWVcgagZsQOaNcXArHnxVWMSstJzAo"
#if DEBUG
Leanplum.setAppId(appId, withDevelopmentKey:devKey)
#else
Leanplum.setAppId(appId, withProductionKey:prodkey)
#endif
Leanplum.setVerboseLoggingInDevelopmentMode(true)
Leanplum.start()
configureUserNotifications()
Leanplum.onStartResponse{ (success:Bool) in
print("Got a Start call response Success: \(success)")
let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
Leanplum.setUserAttributes(["oddNumbers" : oddNumbers])
}
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Device Token: \(token)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
{
print("Failed to register: \(error)")
}
func configureUserNotifications(){
if #available(iOS 10.0, *) {
print("IOS 10 push registration")
UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .alert, .badge]) { (granted,error) in
if error == nil {
print("Permission granted: \(granted)")
guard granted else { return }
// 1
let viewAction = UNNotificationAction(identifier: viewActionIdentifier,
title: "View",
options: [.foreground])
// 2
let newsCategory = UNNotificationCategory(identifier: newsCategoryIdentifier,
actions: [viewAction],
intentIdentifiers: [],
options: [])
UNUserNotificationCenter.current().setNotificationCategories([newsCategory])
self.getNotificationSettings()
} else {
print(error?.localizedDescription ?? "Error while registering push")
}
}
}
//iOS 8-10
else {
let settings = UIUserNotificationSettings.init(types: [UIUserNotificationType.alert,
UIUserNotificationType.badge,
UIUserNotificationType.sound],
categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
UIApplication.shared.registerForRemoteNotifications()
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("My own did receive remote notification \(userInfo)")
completionHandler(.newData)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("did receive response \(response)")
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("will present")
completionHandler(.alert);
}
}
| mit | b1b743f8e10e6b4314b7bc6cea689e2b | 40.829457 | 207 | 0.594329 | 5.852495 | false | false | false | false |
tdyas/SwiftDialog | SwiftDialog/SwiftTableViewController.swift | 2 | 5908 | // Copyright 2014 Thomas K. Dyas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
//
// Unfortunately, a bug in how Swift handles UITableViewController makes
// this reimplementation of UITableViewController necessary. Specifically,
// even though UITableViewController.init(style:) is the supposedly the designated
// initializer for UITableViewController, Swift does not like the fact that
// init(style:) calls UIViewController.init() which in turn calls the subclass
// implementation of init(nibName, bundle). This causes all variables to be
// reinitialized to default values which makes for "fun" when subclassing
// UITableViewController in Swift.
//
// This basic reimplementation of UITableViewController fixes the issue.
//
open class SwiftTableViewController : UIViewController {
open let style: UITableViewStyle
open var tableView: UITableView!
open var clearsSelectionOnViewWillAppear: Bool = true
open var refreshControl: UIRefreshControl? {
willSet {
if let control = refreshControl {
control.removeFromSuperview()
}
}
didSet {
if let control = refreshControl {
tableView.addSubview(control)
}
}
}
var hasBeenShownOnce: Bool = false
var keyboardRectOpt: CGRect?
var isVisible: Bool = false
public init(style: UITableViewStyle) {
self.style = style
super.init(nibName: nil, bundle: nil)
}
deinit {
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func loadView() {
let screenBounds = UIScreen.main.bounds
self.view = UIView(frame: screenBounds)
self.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.tableView = UITableView(frame: screenBounds, style: style)
self.tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(tableView)
}
open override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(SwiftTableViewController.willShowKeyboard(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(SwiftTableViewController.willHideKeyboard(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
open override func viewWillLayoutSubviews() {
var bounds = view.bounds
if let keyboardRect = self.keyboardRectOpt {
bounds.size.height = keyboardRect.minY - bounds.origin.y
}
tableView.frame = bounds
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !hasBeenShownOnce {
tableView.reloadData()
hasBeenShownOnce = true
}
if clearsSelectionOnViewWillAppear {
if let indexPaths = tableView.indexPathsForSelectedRows {
for indexPath in indexPaths {
tableView.deselectRow(at: indexPath, animated: animated)
}
}
}
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.flashScrollIndicators()
isVisible = true
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
isVisible = false
}
open override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.setEditing(editing, animated: animated)
}
@objc
func willShowKeyboard(_ notification: Notification!) {
let userInfo = notification.userInfo
if let keyboardRectValue = userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
keyboardRectOpt = self.view.convert(keyboardRectValue.cgRectValue, from: nil)
if isVisible {
let animationDurationOpt = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber
let animationDuration = animationDurationOpt?.doubleValue ?? 1.0
UIView.animate(withDuration: animationDuration, animations: {
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
})
} else {
self.view.setNeedsLayout()
}
}
}
@objc
func willHideKeyboard(_ notification: Notification!) {
keyboardRectOpt = nil
if isVisible {
let userInfo = notification.userInfo
let animationDurationOpt = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber
let animationDuration = animationDurationOpt?.doubleValue ?? 1.0
UIView.animate(withDuration: animationDuration, animations: {
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
})
} else {
self.view.setNeedsLayout()
}
}
}
| apache-2.0 | 6fb75844a5c1813609a006180ebd5e26 | 34.806061 | 171 | 0.648104 | 5.621313 | false | false | false | false |
hmoraes/actor-platform | actor-apps/app-ios/ActorApp/Controllers/Group/GroupViewController.swift | 19 | 14504 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class GroupViewController: AATableViewController {
private let GroupInfoCellIdentifier = "GroupInfoCellIdentifier"
private let UserCellIdentifier = "UserCellIdentifier"
private let CellIdentifier = "CellIdentifier"
let gid: Int
var group: ACGroupVM?
var binder = Binder()
private var tableData: UATableData!
private var groupMembers: IOSObjectArray?
private var groupNameTextField: UITextField?
init (gid: Int) {
self.gid = gid
super.init(style: UITableViewStyle.Plain)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = MainAppTheme.list.bgColor
edgesForExtendedLayout = UIRectEdge.Top
automaticallyAdjustsScrollViewInsets = false
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.backgroundColor = MainAppTheme.list.backyardColor
tableView.clipsToBounds = false
group = Actor.getGroupWithGid(jint(gid))
tableData = UATableData(tableView: tableView)
tableData.registerClass(GroupPhotoCell.self, forCellReuseIdentifier: GroupInfoCellIdentifier)
tableData.registerClass(GroupMemberCell.self, forCellReuseIdentifier: UserCellIdentifier)
tableData.tableScrollClosure = { (tableView: UITableView) -> () in
self.applyScrollUi(tableView)
}
// Banner
tableData.addSection()
.addCustomCell { (tableView, indexPath) -> UITableViewCell in
var cell = tableView.dequeueReusableCellWithIdentifier(
self.GroupInfoCellIdentifier,
forIndexPath: indexPath)
as! GroupPhotoCell
cell.contentView.superview?.clipsToBounds = false
cell.selectionStyle = UITableViewCellSelectionStyle.None
self.applyScrollUi(tableView, cell: cell)
return cell
}
.setHeight(avatarHeight)
// Change Photo
var adminSection = tableData.addSection(autoSeparator: true)
.setFooterHeight(15)
adminSection.addActionCell("GroupSetPhoto", actionClosure: { () -> () in
var hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
self.showActionSheet( hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"],
cancelButton: "AlertCancel",
destructButton: self.group?.getAvatarModel().get() != nil ? "PhotoRemove" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if (index == -2) {
self.confirmUser("PhotoRemoveGroupMessage",
action: "PhotoRemove",
cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
Actor.removeGroupAvatarWithGid(jint(self.gid))
})
} else if (index >= 0) {
let takePhoto: Bool = (index == 0) && hasCamera
self.pickAvatar(takePhoto, closure: { (image) -> () in
Actor.changeGroupAvatar(jint(self.gid), image: image)
})
}
})
})
adminSection
.addActionCell("GroupSetTitle", actionClosure: { () -> () in
self.editName()
})
adminSection
.addNavigationCell("GroupIntegrations", actionClosure: { () -> () in
self.navigateNext(IntegrationViewController(gid: jint(self.gid)), removeCurrent: false)
})
// Notifications
tableData.addSection(autoSeparator: true)
.setHeaderHeight(15)
.setFooterHeight(15)
.addCommonCell()
.setStyle(.Switch)
.setContent("GroupNotifications")
.setModificator { (cell) -> () in
let groupPeer: ACPeer! = ACPeer.groupWithInt(jint(self.gid))
cell.setSwitcherOn(Actor.isNotificationsEnabledWithPeer(groupPeer))
cell.switchBlock = { (on: Bool) -> () in
Actor.changeNotificationsEnabledWithPeer(groupPeer, withValue: on)
}
}
// Members
var membersSection = tableData.addSection(autoSeparator: true)
.setHeaderHeight(15)
membersSection
.addCustomCells(48, countClosure: { () -> Int in
if self.groupMembers != nil {
return Int(self.groupMembers!.length())
}
return 0
}) { (tableView, index, indexPath) -> UITableViewCell in
var cell: GroupMemberCell = tableView.dequeueReusableCellWithIdentifier(self.UserCellIdentifier, forIndexPath: indexPath) as! GroupMemberCell
if let groupMember = self.groupMembers!.objectAtIndex(UInt(index)) as? ACGroupMember,
let user = Actor.getUserWithUid(groupMember.getUid()) {
var username = user.getNameModel().get()
let avatar: ACAvatar? = user.getAvatarModel().get()
cell.userAvatarView.bind(username, id: user.getId(), avatar: avatar)
cell.setUsername(username)
}
return cell
}.setAction { (index) -> () in
if let groupMember = self.groupMembers!.objectAtIndex(UInt(index)) as? ACGroupMember, let user = Actor.getUserWithUid(groupMember.getUid()) {
if (user.getId() == Actor.myUid()) {
return
}
var name = user.getNameModel().get()
self.showActionSheet(name,
buttons: isIPhone ? ["GroupMemberInfo", "GroupMemberWrite", "GroupMemberCall"] : ["GroupMemberInfo", "GroupMemberWrite"],
cancelButton: "Cancel",
destructButton: groupMember.getUid() != Actor.myUid() && (groupMember.getInviterUid() == Actor.myUid() || self.group!.getCreatorId() == Actor.myUid()) ? "GroupMemberKick" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if (index == -2) {
self.confirmUser(NSLocalizedString("GroupMemberKickMessage", comment: "Button Title").stringByReplacingOccurrencesOfString("{name}", withString: name, options: NSStringCompareOptions.allZeros, range: nil),
action: "GroupMemberKickAction",
cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
self.execute(Actor.kickMemberCommandWithGid(jint(self.gid), withUid: user.getId()))
})
} else if (index >= 0) {
if (index == 0) {
self.navigateNext(UserViewController(uid: Int(user.getId())), removeCurrent: false)
} else if (index == 1) {
self.navigateDetail(ConversationViewController(peer: ACPeer.userWithInt(user.getId())))
self.popover?.dismissPopoverAnimated(true)
} else if (index == 2) {
var phones = user.getPhonesModel().get()
if phones.size() == 0 {
self.alertUser("GroupMemberCallNoPhones")
} else if phones.size() == 1 {
var number = phones.getWithInt(0)
UIApplication.sharedApplication().openURL(NSURL(string: "telprompt://+\(number.getPhone())")!)
} else {
var numbers = [String]()
for i in 0..<phones.size() {
var p = phones.getWithInt(i)
numbers.append("\(p.getTitle()): +\(p.getPhone())")
}
self.showActionSheet(numbers,
cancelButton: "AlertCancel",
destructButton: nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if (index >= 0) {
var number = phones.getWithInt(jint(index))
UIApplication.sharedApplication().openURL(NSURL(string: "telprompt://+\(number.getPhone())")!)
}
})
}
}
}
})
}
}
// Add member
membersSection
.setFooterHeight(15)
.addActionCell("GroupAddParticipant", actionClosure: { () -> () in
let addParticipantController = AddParticipantViewController(gid: self.gid)
let navigationController = AANavigationController(rootViewController: addParticipantController)
if (isIPad) {
navigationController.modalInPopover = true
navigationController.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
}
self.presentViewController(navigationController, animated: true, completion: nil)
})
.setLeftInset(65.0)
// Leave group
tableData.addSection(autoSeparator: true)
.setFooterHeight(15)
.setHeaderHeight(15)
.addActionCell("GroupLeave", actionClosure: { () -> () in
self.confirmUser("GroupLeaveConfirm", action: "GroupLeaveConfirmAction", cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
self.execute(Actor.leaveGroupCommandWithGid(jint(self.gid)))
})
})
.setStyle(.DestructiveCentered)
// Init table
tableView.reloadData()
// Bind group info
binder.bind(group!.getNameModel()!, closure: { (value: String?) -> () in
var cell: GroupPhotoCell? = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? GroupPhotoCell
if cell != nil {
cell!.setGroupName(value!)
}
self.title = value!
})
binder.bind(group!.getAvatarModel(), closure: { (value: ACAvatar?) -> () in
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? GroupPhotoCell {
if (self.group!.isMemberModel().get().booleanValue()) {
cell.groupAvatarView.bind(self.group!.getNameModel().get(), id: jint(self.gid), avatar: value)
} else {
cell.groupAvatarView.bind(self.group!.getNameModel().get(), id: jint(self.gid), avatar: nil)
}
}
})
// Bind members
binder.bind(group!.getMembersModel(), closure: { (value: JavaUtilHashSet?) -> () in
if value != nil {
self.groupMembers = value!.toArray()
self.tableView.reloadData()
}
})
// Bind membership status
binder.bind(group!.isMemberModel(), closure: { (member: JavaLangBoolean?) -> () in
if member != nil {
if Bool(member!.booleanValue()) == true {
self.hidePlaceholder()
} else {
self.showPlaceholderWithImage(
UIImage(named: "contacts_list_placeholder"),
title: NSLocalizedString("Placeholder_Group_Title", comment: "Not a member Title"),
subtitle: NSLocalizedString("Placeholder_Group_Message", comment: "Message Title"))
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? GroupPhotoCell {
cell.groupAvatarView.bind(self.group!.getNameModel().get(), id: jint(self.gid), avatar: nil)
}
}
}
})
}
func editName() {
textInputAlert("GroupEditHeader", content: group!.getNameModel().get(), action: "AlertSave") { (nval) -> () in
if count(nval) > 0 {
self.confirmUser("GroupEditConfirm",
action: "GroupEditConfirmAction",
cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
self.execute(Actor.editGroupTitleCommandWithGid(jint(self.gid), withTitle: nval));
})
}
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.lt_reset()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
applyScrollUi(tableView)
navigationController?.navigationBar.shadowImage = UIImage()
}
}
| mit | 3f62a61b5c7fa47893401e52e08ebf46 | 45.487179 | 233 | 0.511238 | 5.764706 | false | false | false | false |
tkcfjips/FCAnimation | FCAnimation.swift | 1 | 13050 | //
// FCAnimation.swift
// FCAnimation
//
// Created by Kenichi Saito on 2/5/15.
// Copyright (c) 2015 FarConnection. All rights reserved.
//
import UIKit
class FCAnimation {
enum FCAnimationType {
case BounceLeft
case BounceRight
case BounceUp
case BounceDown
case FadeIn
case FadeOut
case ZoomIn
case ZoomOut
case Pop
case Stretch
case Shake
}
func performAnimation(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval, type: FCAnimationType) {
switch type {
case .BounceLeft: bounceLeft(view, duration: duration, delay: delay)
case .BounceRight: bounceRight(view, duration: duration, delay: delay)
case .BounceUp: bounceUp(view, duration: duration, delay: delay)
case .BounceDown: bounceDown(view, duration: duration, delay: delay)
case .FadeIn: fadeIn(view, duration: duration, delay: delay)
case .FadeOut: fadeOut(view, duration: duration, delay: delay)
case .ZoomIn: zoomIn(view, duration: duration, delay: delay)
case .ZoomOut: zoomOut(view, duration: duration, delay: delay)
case .Pop: pop(view, duration: duration, delay: delay)
case .Stretch: stretch(view, duration: duration, delay: delay)
case .Shake: shake(view, duration: duration, delay: delay)
default: return
}
}
}
extension FCAnimation {
private func bounceLeft(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) {
view.transform = CGAffineTransformMakeTranslation(CGRectGetWidth(UIScreen.mainScreen().bounds), 0)
UIView.animateKeyframesWithDuration(duration/4, delay: delay, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(-10, 0)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(5, 0)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(-2, 0)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(0, 0)
}, completion: {(finished: Bool) in
})
})
})
})
}
private func bounceRight(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) {
view.transform = CGAffineTransformMakeTranslation(-CGRectGetWidth(UIScreen.mainScreen().bounds), 0)
UIView.animateKeyframesWithDuration(duration/4, delay: delay, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(10, 0)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(-5, 0)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(2, 0)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(0, 0)
}, completion: {(finished: Bool) in
})
})
})
})
}
private func bounceUp(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) {
view.transform = CGAffineTransformMakeTranslation(0, CGRectGetWidth(UIScreen.mainScreen().bounds))
UIView.animateKeyframesWithDuration(duration/4, delay: delay, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(0, 10)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(0, -5)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(0, 2)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(0, 0)
}, completion: {(finished: Bool) in
})
})
})
})
}
private func bounceDown(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) {
view.transform = CGAffineTransformMakeTranslation(0, -CGRectGetWidth(UIScreen.mainScreen().bounds))
UIView.animateKeyframesWithDuration(duration/4, delay: delay, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(0, -10)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(0, 5)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(0, -2)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(0, 0)
}, completion: {(finished: Bool) in
})
})
})
})
}
private func fadeIn(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) {
view.alpha = 0
UIView.animateKeyframesWithDuration(duration, delay: delay, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.alpha = 1
}, completion: {(finished: Bool) in
})
}
private func fadeOut(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) {
view.alpha = 1
UIView.animateKeyframesWithDuration(duration, delay: delay, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.alpha = 0
}, completion: {(finished: Bool) in
})
}
private func zoomIn(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) {
view.transform = CGAffineTransformMakeScale(1, 1)
view.alpha = 1
UIView.animateKeyframesWithDuration(duration, delay: delay, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeScale(2, 2)
view.alpha = 0
}, completion: {(finished: Bool) in
})
}
private func zoomOut(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) {
view.transform = CGAffineTransformMakeScale(2, 2)
view.alpha = 0
UIView.animateKeyframesWithDuration(duration, delay: delay, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeScale(1, 1)
view.alpha = 1
}, completion: {(finished: Bool) in
})
}
private func pop(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) {
view.transform = CGAffineTransformMakeScale(1, 1)
UIView.animateKeyframesWithDuration(duration/3, delay: delay, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeScale(1.2, 1.2)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/3, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeScale(0.9, 0.9)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/3, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeScale(1, 1)
}, completion: {(finished: Bool) in
})
})
})
}
private func stretch(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) {
view.transform = CGAffineTransformMakeScale(1, 1)
UIView.animateKeyframesWithDuration(duration/4, delay: delay, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeScale(1, 1.2)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeScale(1.2, 0.9)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeScale(0.9, 0.9)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeScale(1, 1)
}, completion: {(finished: Bool) in
})
})
})
})
}
private func shake(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) {
view.transform = CGAffineTransformMakeTranslation(0, 0)
UIView.animateKeyframesWithDuration(duration/5, delay: delay, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(30, 0)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/5, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(-30, 0)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/5, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(15, 0)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/5, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(-15, 0)
}, completion: {(finished: Bool) in
UIView.animateKeyframesWithDuration(duration/5, delay: 0, options: UIViewKeyframeAnimationOptions.allZeros, animations: {
view.transform = CGAffineTransformMakeTranslation(0, 0)
}, completion: {(finished: Bool) in
})
})
})
})
})
}
}
| mit | 1e1a4d0b1e060b67bbfd01333fff992a | 57.783784 | 161 | 0.60023 | 5.915684 | false | false | false | false |
hgani/ganilib-ios | glib/Classes/Http/Rest.swift | 1 | 13227 | //import Alamofire
import SVProgressHUD
import SwiftyJSON
public typealias Json = JSON
typealias NonNullParams = [String: Any]
public class Rest {
public struct Response {
public let statusCode: Int
public let content: Json
public let headers: Json
}
private let request: HttpRequest
private var task: URLSessionDataTask?
private var canceled: Bool
init(request: HttpRequest) {
self.request = request
canceled = false
}
public func cancel() {
GLog.i("Request canceled: \(request.string)")
canceled = true
if let task = self.task {
task.cancel()
}
}
// private func executeGeneric(indicator: ProgressIndicator,
// onHttpSuccess: @escaping (Response) -> Bool,
// onHttpFailure: @escaping (Error) -> Bool) {
// GLog.i(string)
// #if DEBUG || ADHOC
// GLog.i("Params: \(params)")
// #endif
//
// indicator.show()
// if let r = request {
// r.responseString { response in
// if let r = response.response {
// if !GHttp.instance.delegate.processResponse(r) {
// indicator.hide()
// return
// }
// }
//
// switch response.result {
// case .success(let value):
// indicator.hide()
//
// var status = "Unknown status"
// if let code = response.response?.statusCode {
// status = String(code)
// }
//
// var headers = Json()
// if let fields = response.response?.allHeaderFields {
// for field in fields {
// GLog.t("KEY: \(String(describing: field.key))")
// headers[String(describing: field.key)] = Json(field.value)
// }
// }
//
// let content = JSON(parseJSON: value)
//
// GLog.d("[\(status)]: \(content)")
// if !onHttpSuccess(Response(content: content, headers: headers)) {
// indicator.show(error: content["message"].string ?? content["error"].string ?? "")
// }
// case .failure(let error):
// if !onHttpFailure(error) {
// indicator.show(error: error.localizedDescription)
// }
// }
// }
// }
// }
public func execute(indicator: ProgressIndicatorEnum = .standard,
localCache: Bool = false,
onHttpFailure: @escaping (Error) -> Bool = { _ in false },
onHttpSuccess: @escaping (Response) -> Bool) -> Self {
return execute(indicator: indicator.backend,
localCache: localCache,
onHttpFailure: onHttpFailure,
onHttpSuccess: onHttpSuccess)
}
// (16 Nov 2017) We've tested using CFGetRetainCount() and deinit() to make sure that onHttpSuccess doesn't linger
// after the request finishes. This is true even in the case where the request object (i.e. Rest) is assigned to an
// instance variable, so it is safe to pass a closure that accesses `self` without `unowned`.
public func execute(indicator: ProgressIndicator,
localCache: Bool = false,
onHttpFailure: @escaping (Error) -> Bool = { _ in false },
onHttpSuccess: @escaping (Response) -> Bool) -> Self {
if canceled {
return self
}
switch request.method {
case .multipart:
GLog.t("TODO")
// Alamofire.upload(multipartFormData: { (formData) in
// for (key, value) in self.params {
// if value is UIImage {
// formData.append(UIImageJPEGRepresentation((value as! UIImage), 1)!,
// withName: key,
// fileName: "images.jpeg",
// mimeType: "image/jpeg")
// }
// else {
// formData.append(String(describing: value).data(using: .utf8)!, withName: key)
// }
// }
// }, usingThreshold: 0,
// to: self.url,
// method: HTTPMethod.post,
// headers: self.headers,
// encodingCompletion: { (result) in
// switch result {
// case .failure(let error):
// indicator.show(error: error.localizedDescription)
// case .success(let upload, _, _):
// upload.uploadProgress { progress in
// // Subtract because it's potentially confusing to the user when we are at 100% for a few seconds.
// let fraction = progress.fractionCompleted - 0.02
// let percentage = (fraction * 100).rounded()
// GLog.t("Uploading (\(percentage)%) -- \(fraction)")
// indicator.show(progress: Float(fraction))
// }
//
// self.request = upload
// self.executeGeneric(indicator: indicator, onHttpSuccess: onHttpSuccess, onHttpFailure: onHttpFailure)
// }
// })
default:
if var urlRequest = request.urlRequest {
let session = URLSession.shared
var localEtag: String?
if localCache,
let cache = session.configuration.urlCache,
let response = cache.cachedResponse(for: urlRequest),
let httpResponse = response as? HTTPURLResponse {
let content = JSON(response.data)
localEtag = httpResponse.allHeaderFields["Etag"] as? String
onHttpSuccess(Response(statusCode: -1, content: content, headers: Json()))
}
task = session.dataTask(with: urlRequest) { data, response, error in
if let httpResponse = response as? HTTPURLResponse {
// URLSession masks 304 as 200 so we need to compare etags manually
if localCache, let etag = localEtag, !etag.isEmpty {
if etag == httpResponse.allHeaderFields["Etag"] as? String {
return
}
}
self.handleResponse(content: Json(data), response: httpResponse, indicator: indicator, onHttpSuccess: onHttpSuccess)
} else {
if let safeError = error {
DispatchQueue.main.async {
if !onHttpFailure(safeError) {
indicator.show(error: safeError.localizedDescription)
}
}
}
}
}
}
if let safeTask = task {
indicator.show()
safeTask.resume()
} else {
indicator.show(error: "Failed connecting to server")
}
}
return self
}
private func handleResponse(content: Json,
response: HTTPURLResponse,
indicator: ProgressIndicator,
onHttpSuccess: @escaping (Response) -> Bool) {
GLog.i(request.string)
indicator.hide()
if !GHttp.instance.listener.processResponse(response) {
return
}
var headers = Json()
for field in response.allHeaderFields {
headers[String(describing: field.key)] = Json(field.value)
}
let statusCode = response.statusCode
GLog.d("[\(statusCode)]: \(content)")
DispatchQueue.main.async {
if !onHttpSuccess(Response(statusCode: statusCode, content: content, headers: headers)) {
indicator.show(error: content["message"].string ?? content["error"].string ?? "")
}
}
}
public func done() {
// End chaining
}
private static func augmentPostParams(_ params: GParams, _ method: HttpMethod) -> GParams {
switch method {
case .patch, .delete:
var mutableParams = params
mutableParams["_method"] = method.name
return mutableParams
default: // Don't augment .post to allow caller specify their own `_method`
return params
}
}
private static func request(_ url: String, _ method: HttpMethod, _ params: GParams, _ headers: HttpHeaders) -> Rest {
let augmentedParams = augmentPostParams(params, method)
let restParams: NonNullParams, restHeaders: HttpHeaders
if url.starts(with: GHttp.instance.host()) {
let request = HttpRequest(method: method, url: url, params: params, headers: headers)
restParams = prepareParams(GHttp.instance.listener.restParams(from: augmentedParams, request: request))
restHeaders = GHttp.instance.listener.restHeaders(from: headers, request: request)
} else {
restParams = prepareParams(augmentedParams)
restHeaders = headers
}
return Rest(request: HttpRequest(method: method, url: url, params: restParams, headers: restHeaders))
}
private static func prepareParams(_ params: GParams) -> NonNullParams {
var data = [String: Any]()
for (key, value) in params {
if let sub = value as? GParams {
data[key] = prepareParams(sub)
} else {
data[key] = value ?? ""
}
}
return data
}
// MARK: URL-based
public static func post(url: String, params: GParams = GParams(), headers: HttpHeaders = HttpHeaders()) -> Rest {
return request(url, .post, params, headers)
}
public static func patch(url: String, params: GParams = GParams(), headers: HttpHeaders = HttpHeaders()) -> Rest {
return request(url, .patch, params, headers)
}
public static func delete(url: String, params: GParams = GParams(), headers: HttpHeaders = HttpHeaders()) -> Rest {
return request(url, .delete, params, headers)
}
public static func get(url: String, params: GParams = GParams(), headers: HttpHeaders = HttpHeaders()) -> Rest {
return request(url, .get, params, headers)
}
public static func multipart(url: String, params: GParams = GParams(), headers: HttpHeaders = HttpHeaders()) -> Rest {
return request(url, .multipart, params, headers)
}
// MARK: Path-based
private static func url(from path: String) -> String {
return "\(GHttp.instance.host())\(path)"
}
public static func post(path: String, params: GParams = GParams(), headers: HttpHeaders = HttpHeaders()) -> Rest {
return post(url: url(from: path), params: params, headers: headers)
}
public static func patch(path: String, params: GParams = GParams(), headers: HttpHeaders = HttpHeaders()) -> Rest {
return patch(url: url(from: path), params: params, headers: headers)
}
public static func delete(path: String, params: GParams = GParams(), headers: HttpHeaders = HttpHeaders()) -> Rest {
return delete(url: url(from: path), params: params, headers: headers)
}
public static func get(path: String, params: GParams = GParams(), headers: HttpHeaders = HttpHeaders()) -> Rest {
return get(url: url(from: path), params: params, headers: headers)
}
public static func multipart(path: String, params: GParams = GParams(), headers: HttpHeaders = HttpHeaders()) -> Rest {
return multipart(url: url(from: path), params: params, headers: headers)
}
public static func from(method: String, url: String, params: GParams = GParams(), headers: HttpHeaders = HttpHeaders()) -> Rest? {
switch method {
case "post":
return post(url: url, params: params, headers: headers)
case "patch":
return patch(url: url, params: params, headers: headers)
case "delete":
return delete(url: url, params: params, headers: headers)
case "get":
return get(url: url, params: params, headers: headers)
case "multipart":
return multipart(url: url, params: params, headers: headers)
default:
return nil
}
}
}
| mit | 188e6d7e2e8bf8fe2f4accddf5b058df | 40.205607 | 140 | 0.515914 | 4.911623 | false | false | false | false |
saraheolson/TechEmpathy-iOS | TechEmpathy/TechEmpathy/Controllers/FirebaseManager.swift | 1 | 761 | //
// FirebaseManager.swift
// TechEmpathy
//
// Created by Sarah Olson on 4/15/17.
// Copyright © 2017 SarahEOlson. All rights reserved.
//
import Foundation
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase
class FirebaseManager {
static let sharedInstance = FirebaseManager()
private init() { }
// Get firebase reference
var firebaseRef = FIRDatabase.database().reference()
// var storageRef = FIRStorage.storage().reference()
var storiesStorage = FIRStorage.storage().reference().child("stories")
var anonymousUser: String? = nil
func authenticate() {
FIRAuth.auth()?.signInAnonymously() { (user, error) in
self.anonymousUser = user?.uid
}
}
}
| apache-2.0 | 6192c73a4afc972651ad7d7d31e4eb5b | 22.030303 | 74 | 0.663158 | 4.444444 | false | false | false | false |
Jnosh/swift | stdlib/public/core/VarArgs.swift | 2 | 15224 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Instances of conforming types can be encoded, and appropriately
/// passed, as elements of a C `va_list`.
///
/// This protocol is useful in presenting C "varargs" APIs natively in
/// Swift. It only works for APIs that have a `va_list` variant, so
/// for example, it isn't much use if all you have is:
///
/// ~~~ c
/// int c_api(int n, ...)
/// ~~~
///
/// Given a version like this, though,
///
/// ~~~ c
/// int c_api(int, va_list arguments)
/// ~~~
///
/// you can write:
///
/// func swiftAPI(_ x: Int, arguments: CVarArg...) -> Int {
/// return withVaList(arguments) { c_api(x, $0) }
/// }
public protocol CVarArg {
// Note: the protocol is public, but its requirement is stdlib-private.
// That's because there are APIs operating on CVarArg instances, but
// defining conformances to CVarArg outside of the standard library is
// not supported.
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
var _cVarArgEncoding: [Int] { get }
}
/// Floating point types need to be passed differently on x86_64
/// systems. CoreGraphics uses this to make CGFloat work properly.
public // SPI(CoreGraphics)
protocol _CVarArgPassedAsDouble : CVarArg {}
/// Some types require alignment greater than Int on some architectures.
public // SPI(CoreGraphics)
protocol _CVarArgAligned : CVarArg {
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
var _cVarArgAlignment: Int { get }
}
#if arch(x86_64)
@_versioned
let _x86_64CountGPRegisters = 6
@_versioned
let _x86_64CountSSERegisters = 8
@_versioned
let _x86_64SSERegisterWords = 2
@_versioned
let _x86_64RegisterSaveWords = _x86_64CountGPRegisters + _x86_64CountSSERegisters * _x86_64SSERegisterWords
#endif
/// Invokes the given closure with a C `va_list` argument derived from the
/// given array of arguments.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withVaList(_:_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameters:
/// - args: An array of arguments to convert to a C `va_list` pointer.
/// - body: A closure with a `CVaListPointer` parameter that references the
/// arguments passed as `args`. If `body` has a return value, it is used
/// as the return value for the `withVaList(_:)` function. The pointer
/// argument is valid only for the duration of the function's execution.
/// - Returns: The return value of the `body` closure parameter, if any.
///
/// - SeeAlso: `getVaList(_:)`
public func withVaList<R>(_ args: [CVarArg],
_ body: (CVaListPointer) -> R) -> R {
let builder = _VaListBuilder()
for a in args {
builder.append(a)
}
return _withVaList(builder, body)
}
/// Invoke `body` with a C `va_list` argument derived from `builder`.
internal func _withVaList<R>(
_ builder: _VaListBuilder,
_ body: (CVaListPointer) -> R
) -> R {
let result = body(builder.va_list())
_fixLifetime(builder)
return result
}
#if _runtime(_ObjC)
// Excluded due to use of dynamic casting and Builtin.autorelease, neither
// of which correctly work without the ObjC Runtime right now.
// See rdar://problem/18801510
/// Returns a `CVaListPointer` that is backed by autoreleased storage, built
/// from the given array of arguments.
///
/// You should prefer `withVaList(_:_:)` instead of this function. In some
/// uses, such as in a `class` initializer, you may find that the
/// language rules do not allow you to use `withVaList(_:_:)` as intended.
///
/// - Parameters args: An array of arguments to convert to a C `va_list`
/// pointer.
/// - Returns: The return value of the `body` closure parameter, if any.
///
/// - SeeAlso: `withVaList(_:_:)`
public func getVaList(_ args: [CVarArg]) -> CVaListPointer {
let builder = _VaListBuilder()
for a in args {
builder.append(a)
}
// FIXME: Use some Swift equivalent of NS_RETURNS_INNER_POINTER if we get one.
Builtin.retain(builder)
Builtin.autorelease(builder)
return builder.va_list()
}
#endif
public func _encodeBitsAsWords<T>(_ x: T) -> [Int] {
let result = [Int](
repeating: 0,
count: (MemoryLayout<T>.size + MemoryLayout<Int>.size - 1) / MemoryLayout<Int>.size)
_sanityCheck(result.count > 0)
var tmp = x
// FIXME: use UnsafeMutablePointer.assign(from:) instead of memcpy.
_memcpy(dest: UnsafeMutablePointer(result._baseAddressIfContiguous!),
src: UnsafeMutablePointer(Builtin.addressof(&tmp)),
size: UInt(MemoryLayout<T>.size))
return result
}
// CVarArg conformances for the integer types. Everything smaller
// than an Int32 must be promoted to Int32 or CUnsignedInt before
// encoding.
// Signed types
extension Int : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension Int64 : CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
extension Int32 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension Int16 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(Int32(self))
}
}
extension Int8 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(Int32(self))
}
}
// Unsigned types
extension UInt : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UInt64 : CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
extension UInt32 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UInt16 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(CUnsignedInt(self))
}
}
extension UInt8 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(CUnsignedInt(self))
}
}
extension OpaquePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UnsafePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UnsafeMutablePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
#if _runtime(_ObjC)
extension AutoreleasingUnsafeMutablePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@_inlineable
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
#endif
extension Float : _CVarArgPassedAsDouble, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(Double(self))
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: Double(self))
}
}
extension Double : _CVarArgPassedAsDouble, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
#if !arch(x86_64)
/// An object that can manage the lifetime of storage backing a
/// `CVaListPointer`.
final internal class _VaListBuilder {
func append(_ arg: CVarArg) {
// Write alignment padding if necessary.
// This is needed on architectures where the ABI alignment of some
// supported vararg type is greater than the alignment of Int, such
// as non-iOS ARM. Note that we can't use alignof because it
// differs from ABI alignment on some architectures.
#if arch(arm) && !os(iOS)
if let arg = arg as? _CVarArgAligned {
let alignmentInWords = arg._cVarArgAlignment / MemoryLayout<Int>.size
let misalignmentInWords = count % alignmentInWords
if misalignmentInWords != 0 {
let paddingInWords = alignmentInWords - misalignmentInWords
appendWords([Int](repeating: -1, count: paddingInWords))
}
}
#endif
// Write the argument's value itself.
appendWords(arg._cVarArgEncoding)
}
func va_list() -> CVaListPointer {
// Use Builtin.addressof to emphasize that we are deliberately escaping this
// pointer and assuming it is safe to do so.
let emptyAddr = UnsafeMutablePointer<Int>(
Builtin.addressof(&_VaListBuilder.alignedStorageForEmptyVaLists))
return CVaListPointer(_fromUnsafeMutablePointer: storage ?? emptyAddr)
}
// Manage storage that is accessed as Words
// but possibly more aligned than that.
// FIXME: this should be packaged into a better storage type
func appendWords(_ words: [Int]) {
let newCount = count + words.count
if newCount > allocated {
let oldAllocated = allocated
let oldStorage = storage
let oldCount = count
allocated = max(newCount, allocated * 2)
let newStorage = allocStorage(wordCount: allocated)
storage = newStorage
// count is updated below
if let allocatedOldStorage = oldStorage {
newStorage.moveInitialize(from: allocatedOldStorage, count: oldCount)
deallocStorage(wordCount: oldAllocated, storage: allocatedOldStorage)
}
}
let allocatedStorage = storage!
for word in words {
allocatedStorage[count] = word
count += 1
}
}
func rawSizeAndAlignment(_ wordCount: Int) -> (Builtin.Word, Builtin.Word) {
return ((wordCount * MemoryLayout<Int>.stride)._builtinWordValue,
requiredAlignmentInBytes._builtinWordValue)
}
func allocStorage(wordCount: Int) -> UnsafeMutablePointer<Int> {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
let rawStorage = Builtin.allocRaw(rawSize, rawAlignment)
return UnsafeMutablePointer<Int>(rawStorage)
}
func deallocStorage(
wordCount: Int,
storage: UnsafeMutablePointer<Int>
) {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
Builtin.deallocRaw(storage._rawValue, rawSize, rawAlignment)
}
deinit {
if let allocatedStorage = storage {
deallocStorage(wordCount: allocated, storage: allocatedStorage)
}
}
// FIXME: alignof differs from the ABI alignment on some architectures
let requiredAlignmentInBytes = MemoryLayout<Double>.alignment
var count = 0
var allocated = 0
var storage: UnsafeMutablePointer<Int>?
static var alignedStorageForEmptyVaLists: Double = 0
}
#else
/// An object that can manage the lifetime of storage backing a
/// `CVaListPointer`.
final internal class _VaListBuilder {
@_versioned
struct Header {
var gp_offset = CUnsignedInt(0)
var fp_offset = CUnsignedInt(_x86_64CountGPRegisters * MemoryLayout<Int>.stride)
var overflow_arg_area: UnsafeMutablePointer<Int>?
var reg_save_area: UnsafeMutablePointer<Int>?
}
init() {
// prepare the register save area
storage = ContiguousArray(repeating: 0, count: _x86_64RegisterSaveWords)
}
func append(_ arg: CVarArg) {
var encoded = arg._cVarArgEncoding
if arg is _CVarArgPassedAsDouble
&& sseRegistersUsed < _x86_64CountSSERegisters {
var startIndex = _x86_64CountGPRegisters
+ (sseRegistersUsed * _x86_64SSERegisterWords)
for w in encoded {
storage[startIndex] = w
startIndex += 1
}
sseRegistersUsed += 1
}
else if encoded.count == 1 && gpRegistersUsed < _x86_64CountGPRegisters {
storage[gpRegistersUsed] = encoded[0]
gpRegistersUsed += 1
}
else {
for w in encoded {
storage.append(w)
}
}
}
func va_list() -> CVaListPointer {
header.reg_save_area = storage._baseAddress
header.overflow_arg_area
= storage._baseAddress + _x86_64RegisterSaveWords
return CVaListPointer(
_fromUnsafeMutablePointer: UnsafeMutableRawPointer(
Builtin.addressof(&self.header)))
}
var gpRegistersUsed = 0
var sseRegistersUsed = 0
final // Property must be final since it is used by Builtin.addressof.
var header = Header()
var storage: ContiguousArray<Int>
}
#endif
@available(*, unavailable, renamed: "CVarArg")
public typealias CVarArgType = CVarArg
@available(*, unavailable)
final public class VaListBuilder {}
| apache-2.0 | e128a1c34978a15968fd000930bfa91c | 30.983193 | 107 | 0.692853 | 4.184717 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/FeaturedApps/Oscilloscope/OscilloscopeChartView.swift | 1 | 6355 | //******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// OscilloscopeChartView.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
enum DataSource {
case Fourier
case Lisajous
}
class OscilloscopeChartView: OscilloscopeLayout {
var _selectedSource: DataSource = .Fourier
var _isDigitalLine = false
let _dataSeries1 = SCIXyDataSeries(xType: .double, yType: .double)
let _dataSeries2 = SCIXyDataSeries(xType: .double, yType: .double)
let _rSeries = SCIFastLineRenderableSeries()
var _lastTimeDraw: TimeInterval = 0
var _displayLink: CADisplayLink!
var _phase0 = 0.0
var _phase1 = 0.0
var _phaseIncrement = .pi * 0.1
let _xAxis = SCINumericAxis()
let _yAxis = SCINumericAxis()
override func commonInit() {
weak var wSelf = self;
self.seriesTypeTouched = { wSelf?.changeSeriesType() }
self.rotateTouched = { wSelf?.rotateChart() }
self.flippedVerticallyTouched = { wSelf?.flipChartVertically() }
self.flippedHorizontallyTouched = { wSelf?.flipChartHorizontally() }
}
override func initExample() {
_xAxis.autoRange = .never
_xAxis.axisTitle = "Time (ms)"
_xAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(2.5), max: SCIGeneric(4.5))
_yAxis.autoRange = .never
_yAxis.axisTitle = "Voltage (mV)"
_yAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(-12.5), max: SCIGeneric(12.5))
_dataSeries1.acceptUnsortedData = true
_dataSeries2.acceptUnsortedData = true
_rSeries.isDigitalLine = _isDigitalLine
surface.xAxes.add(_xAxis)
surface.yAxes.add(_yAxis)
surface.renderableSeries.add(_rSeries)
SCIThemeManager.applyDefaultTheme(toThemeable: surface)
}
@objc fileprivate func updateOscilloscopeData(_ displayLink: CADisplayLink) {
_lastTimeDraw = _displayLink.timestamp
let doubleSeries = DoubleSeries()
if (_selectedSource == .Lisajous) {
DataManager.setLissajousCurve(doubleSeries, alpha: 0.12, beta: _phase1, delta: _phase0, count: 2500)
_dataSeries1.clear()
_dataSeries1.appendRangeX(doubleSeries.xValues, y: doubleSeries.yValues, count: doubleSeries.size)
_rSeries.dataSeries = _dataSeries1
} else {
DataManager.setFourierSeries(doubleSeries, amplitude: 2.0, phaseShift: _phase0, count: 1000)
_dataSeries2.clear()
_dataSeries2.appendRangeX(doubleSeries.xValues, y: doubleSeries.yValues, count: doubleSeries.size)
_rSeries.dataSeries = _dataSeries2
}
_phase0 += _phaseIncrement
_phase1 += _phaseIncrement * 0.005
}
fileprivate func changeSeriesType() {
let alertController = UIAlertController(title: "Data Source", message: "Select data source or make the line Digital", preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "Fourier", style: .default, handler: {[unowned self] (action: UIAlertAction) -> Void in
self._selectedSource = .Fourier
self.surface.xAxes[0].visibleRange = SCIDoubleRange(min: SCIGeneric(2.5), max: SCIGeneric(4.5))
self.surface.yAxes[0].visibleRange = SCIDoubleRange(min: SCIGeneric(-12.5), max: SCIGeneric(12.5))
}))
alertController.addAction(UIAlertAction(title: "Lisajous", style: .default, handler: {[unowned self] (action: UIAlertAction) -> Void in
self._selectedSource = .Lisajous
self.surface.xAxes[0].visibleRange = SCIDoubleRange(min: SCIGeneric(-1.2), max: SCIGeneric(1.2))
self.surface.yAxes[0].visibleRange = SCIDoubleRange(min: SCIGeneric(-1.2), max: SCIGeneric(1.2))
}))
alertController.addAction(UIAlertAction(title: "Make line Digital", style: .default, handler: {[unowned self] (action: UIAlertAction) -> Void in
self._isDigitalLine = !self._isDigitalLine
self._rSeries.isDigitalLine = self._isDigitalLine
}))
var topVC = UIApplication.shared.delegate?.window??.rootViewController
while ((topVC?.presentedViewController) != nil) {
topVC = topVC?.presentedViewController
}
topVC?.present(alertController, animated: true, completion: nil)
}
fileprivate func rotateChart() {
var xAlignment: Int = Int(surface.xAxes[0].axisAlignment.rawValue)
xAlignment += 1
if (xAlignment > 4) {
xAlignment = 1;
}
surface.xAxes[0].axisAlignment = SCIAxisAlignment(rawValue: Int32(xAlignment))!
var yAlignment: Int = Int(surface.yAxes[0].axisAlignment.rawValue)
yAlignment += 1
if (yAlignment > 4) {
yAlignment = 1;
}
surface.yAxes[0].axisAlignment = SCIAxisAlignment(rawValue: Int32(yAlignment))!
}
func flipChartVertically() {
let flip = surface.yAxes[0].flipCoordinates
surface.yAxes[0].flipCoordinates = !flip
}
func flipChartHorizontally() {
let flip = surface.xAxes[0].flipCoordinates
surface.xAxes[0].flipCoordinates = !flip
}
override func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
if(_displayLink == nil) {
_lastTimeDraw = 0.0
_displayLink = CADisplayLink.init(target: self, selector: #selector(updateOscilloscopeData))
_displayLink.add(to: RunLoop.main, forMode: .defaultRunLoopMode)
} else {
_displayLink.invalidate()
_displayLink = nil;
}
}
}
| mit | 0d3c57c9c3a707dafe05b0974219251d | 40.789474 | 155 | 0.630353 | 4.371645 | false | false | false | false |
dudeofawesome/Wallcycle | Wallcycle/ViewController.swift | 1 | 2439 | //
// ViewController.swift
// Wallcycle
//
// Created by Louis Orleans on 3/17/15.
// Copyright (c) 2015 Louis Orleans. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var chkRandomize: NSButton!
@IBOutlet weak var txtImageFolder: NSTextField!
@IBOutlet weak var txtInterval: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let defaults = NSUserDefaults.standardUserDefaults()
if (defaults.objectForKey("FolderPath") != nil) {
txtImageFolder.stringValue = defaults.objectForKey("FolderPath") as String
}
if (defaults.objectForKey("SwitchTime") != nil) {
txtInterval.integerValue = defaults.objectForKey("SwitchTime") as Int
}
if (defaults.objectForKey("Randomize") != nil) {
chkRandomize.state = (defaults.objectForKey("Randomize") as Bool) ? NSOnState : NSOffState
}
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func onBtnSelect(sender: NSButton) {
let openPanel:NSOpenPanel = NSOpenPanel()
openPanel.nameFieldLabel = "Select wallpaper folder"
openPanel.canChooseDirectories = true
openPanel.canChooseFiles = false
openPanel.canCreateDirectories = true
if (openPanel.runModal() == NSOKButton) {
let url = openPanel.URL?.absoluteString?.stringByReplacingOccurrencesOfString("file://", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
txtImageFolder.stringValue = url!
}
}
@IBAction func onBtnSave(sender: NSButton) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(txtImageFolder.stringValue, forKey: "FolderPath")
defaults.setBool(chkRandomize.state == NSOnState, forKey: "Randomize")
defaults.setInteger(txtInterval.integerValue, forKey: "SwitchTime")
defaults.synchronize()
// window.close()
let wallcycle = Wallcycle()
wallcycle.update()
NSApplication.sharedApplication().terminate(self)
}
@IBAction func onBtnCancel(sender: NSButton) {
// window.close()
NSApplication.sharedApplication().terminate(self)
}
}
| gpl-2.0 | ded687a7c650e2599dc0a69ae22dd3bc | 34.347826 | 175 | 0.654367 | 4.947262 | false | false | false | false |
Vadimkomis/Myclok | Pods/Auth0/Auth0/Request.swift | 2 | 4423 | // Request.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
#if DEBUG
let parameterPropertyKey = "com.auth0.parameter"
#endif
/**
Auth0 API request
```
let request: Request<Credentials, Authentication.Error> = //
request.start { result in
//handle result
}
```
*/
public struct Request<T, E: Auth0Error>: Requestable {
public typealias Callback = (Result<T>) -> Void
let session: URLSession
let url: URL
let method: String
let handle: (Response<E>, Callback) -> Void
let payload: [String: Any]
let headers: [String: String]
let logger: Logger?
let telemetry: Telemetry
// swiftlint:disable:next function_parameter_count
init(session: URLSession, url: URL, method: String, handle: @escaping (Response<E>, Callback) -> Void, payload: [String: Any] = [:], headers: [String: String] = [:], logger: Logger?, telemetry: Telemetry) {
self.session = session
self.url = url
self.method = method
self.handle = handle
self.payload = payload
self.headers = headers
self.logger = logger
self.telemetry = telemetry
}
var request: URLRequest {
let request = NSMutableURLRequest(url: url)
request.httpMethod = method
if !payload.isEmpty, let httpBody = try? JSONSerialization.data(withJSONObject: payload, options: []) {
request.httpBody = httpBody
#if DEBUG
URLProtocol.setProperty(payload, forKey: parameterPropertyKey, in: request)
#endif
}
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
headers.forEach { name, value in request.setValue(value, forHTTPHeaderField: name) }
telemetry.addTelemetryHeader(request: request)
return request as URLRequest
}
/**
Starts the request to the server
- parameter callback: called when the request finishes and yield it's result
*/
public func start(_ callback: @escaping Callback) {
let handler = self.handle
let request = self.request
let logger = self.logger
logger?.trace(request: request, session: self.session)
let task = session.dataTask(with: request, completionHandler: { data, response, error in
if error == nil, let response = response {
logger?.trace(response: response, data: data)
}
handler(Response(data: data, response: response, error: error), callback)
})
task.resume()
}
}
/**
* A concatenated request, if the first one fails it will yield it's error, otherwise it will return the last request outcome
*/
public struct ConcatRequest<F, S, E: Auth0Error>: Requestable {
let first: Request<F, E>
let second: Request<S, E>
public typealias ResultType = S
/**
Starts the request to the server
- parameter callback: called when the request finishes and yield it's result
*/
public func start(_ callback: @escaping (Result<ResultType>) -> Void) {
let second = self.second
first.start { result in
switch result {
case .failure(let cause):
callback(.failure(error: cause))
case .success:
second.start(callback)
}
}
}
}
| mit | 8a067aa987d155d5cb04c8e9d6375dd4 | 34.103175 | 210 | 0.66109 | 4.517875 | false | false | false | false |
stripe/stripe-ios | StripePayments/StripePayments/API Bindings/Models/PaymentIntents/STPPaymentIntentShippingDetails.swift | 1 | 3062 | //
// STPPaymentIntentShippingDetails.swift
// StripePayments
//
// Created by Yuki Tokuhiro on 4/27/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
import Foundation
/// Shipping information for a PaymentIntent
/// You cannot directly instantiate an `STPPaymentIntentShippingDetails`.
/// You should only use one that is part of an existing `STPPaymentMethod` object.
/// - seealso: https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping
public class STPPaymentIntentShippingDetails: NSObject {
/// Shipping address.
@objc public let address: STPPaymentIntentShippingDetailsAddress?
/// Recipient name.
@objc public let name: String?
/// The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc.
@objc public let carrier: String?
/// Recipient phone (including extension).
@objc public let phone: String?
/// The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas.
@objc public let trackingNumber: String?
/// :nodoc:
@objc public let allResponseFields: [AnyHashable: Any]
/// :nodoc:
@objc public override var description: String {
let props: [String] = [
// Object
String(format: "%@: %p", NSStringFromClass(STPPaymentIntentShippingDetails.self), self),
// Properties
"address = \(String(describing: address))",
"name = \(String(describing: name))",
"carrier = \(String(describing: carrier))",
"phone = \(String(describing: phone))",
"trackingNumber = \(String(describing: trackingNumber))",
]
return "<\(props.joined(separator: "; "))>"
}
private init(
address: STPPaymentIntentShippingDetailsAddress?,
name: String?,
carrier: String?,
phone: String?,
trackingNumber: String?,
allResponseFields: [AnyHashable: Any]
) {
self.address = address
self.name = name
self.carrier = carrier
self.phone = phone
self.trackingNumber = trackingNumber
self.allResponseFields = allResponseFields
super.init()
}
}
// MARK: - STPAPIResponseDecodable
extension STPPaymentIntentShippingDetails: STPAPIResponseDecodable {
@objc
public class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? {
guard let dict = response else {
return nil
}
return STPPaymentIntentShippingDetails(
address: STPPaymentIntentShippingDetailsAddress.decodedObject(
fromAPIResponse: dict["address"] as? [AnyHashable: Any]
),
name: dict["name"] as? String,
carrier: dict["carrier"] as? String,
phone: dict["phone"] as? String,
trackingNumber: dict["tracking_number"] as? String,
allResponseFields: dict
) as? Self
}
}
| mit | 27c7ae87867d044aa0c2966a13fc011e | 33.011111 | 184 | 0.645541 | 4.782813 | false | false | false | false |
stripe/stripe-ios | StripeUICore/StripeUICore/Source/Validators/STPVPANumberValidator.swift | 1 | 971 | //
// STPVPANumberValidator.swift
// StripeUICore
//
// Created by Nick Porter on 9/8/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) public class STPVPANumberValidator: NSObject {
public class func stringIsValidPartialVPANumber(_ string: String?) -> Bool {
guard let string = string else {
return true // an empty string isn't *invalid*
}
return (string.components(separatedBy: "@").count - 1) <= 1
}
public class func stringIsValidVPANumber(_ string: String?) -> Bool {
if string == nil || (string?.count ?? 0) > 30 {
return false
}
// regex from https://stackoverflow.com/questions/55143204/how-to-validate-a-upi-id-using-regex
let pattern = "[a-zA-Z0-9.\\-_]{2,256}@[a-zA-Z]{2,64}"
let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)
return predicate.evaluate(with: string?.lowercased())
}
}
| mit | 6b41b339031c350bb66d2a024435a116 | 33.642857 | 103 | 0.62268 | 3.730769 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Library/CodableCoreData/CodableCoreDataStorable.swift | 1 | 13824 | //
// CodableCoreDataStorable.swift
//
// Copyright 2017 Emily Ivie
// Licensed under The MIT License
// For full copyright and license information, please see http://opensource.org/licenses/MIT
// Redistributions of files must retain the above copyright notice.
import CoreData
public protocol CodableCoreDataStorable: Codable {
// MARK: Required
/// Type of the core data entity.
associatedtype EntityType: NSManagedObject
/// Alters the predicate to retrieve only the row equal to this object.
func setIdentifyingPredicate(
fetchRequest: NSFetchRequest<EntityType>
)
/// Sets core data values to match struct values (specific).
func setAdditionalColumnsOnSave(
coreItem: EntityType
)
/// Initializes value type from core data object with serialized data.
init?(coreItem: EntityType)
// MARK: Optional/Default
/// Source Data
var rawData: Data? { get set }
/// A reference to the current core data manager.
static var defaultManager: CodableCoreDataManageable { get }
/// Returns the CoreData row that is equal to this object.
func entity(context: NSManagedObjectContext?) -> EntityType?
/// String description of EntityType.
static var entityName: String { get }
/// String description of serialized data column in entity
static var serializedDataKey: String { get }
/// Sets core data values to match struct values (general).
///
/// DON'T OVERRIDE.
func setColumnsOnSave(
coreItem: EntityType
)
/// Gets the struct to match the core data request.
static func get(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Self?
/// Gets the struct to match the core data request.
static func getCount(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Int
/// Gets all structs that match the core data request.
static func getAll(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> [Self]
/// Saves the struct to core data.
mutating func save(
with manager: CodableCoreDataManageable?
) -> Bool
/// Saves all the structs to core data.
static func saveAll(
items: [Self],
with manager: CodableCoreDataManageable?
) -> Bool
/// Copies all rows that match the core data request.
static func copyAll(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>,
setChangedValues: @escaping SetAdditionalColumns<EntityType>
) -> Bool
/// Deletes the struct's core data equivalent.
mutating func delete(
with manager: CodableCoreDataManageable?
) -> Bool
/// Deletes all rows that match the core data request.
static func deleteAll(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Bool
/// Applies a dictionary data set of changes, and returns an updated copy of the object
func changed(
_ changes: [String: Any?]
) -> Self
/// Required for CodableDictionary/GameRowStorable stuff, so we can override it correctly.
/// (override doesn't work w/o protocol declaration here)
func resetChangedDataFromSource(source: Self) -> Self
}
extension CodableCoreDataStorable {
/// The closure type for editing fetch requests.
public typealias AlterFetchRequest<T: NSManagedObject> = ((NSFetchRequest<T>) -> Void)
/// The closure type for editing fetched entity objects.
public typealias SetAdditionalColumns<T: NSManagedObject> = ((T) -> Void)
/// Convenience - get the static version for easy instance reference.
public var defaultManager: CodableCoreDataManageable {
return Self.defaultManager
}
/// (Protocol default)
/// Returns the CoreData row that is equal to this object.
public func entity(context: NSManagedObjectContext?) -> EntityType? {
return type(of: defaultManager).init(context: context).getObject(item: self)
}
/// (Protocol default)
/// String description of EntityType
public static var entityName: String { return EntityType.description() }
/// (Protocol default)
/// String description of serialized data column in entity
public static var serializedDataKey: String { return "serializedData" }
/// (Protocol default)
/// Initializes value type from core data object with serialized data.
public init?(coreItem: EntityType) {
// Warning: make sure parent runs this in the correct context/thread for this entity
if let data = coreItem.value(forKey: Self.serializedDataKey) as? Data {
do {
let decodable = try Self.defaultManager.decoder.decode(GenericDecodable.self, from: data)
try self.init(from: decodable.decoder)
self.rawData = data
return
} catch let decodeError {
print("Error: decoding failed for \(Self.self): \(decodeError)")
}
}
return nil
}
/// Sets core data values to match struct values (general).
///
/// DON'T OVERRIDE.
public func setColumnsOnSave(
coreItem: EntityType
) {
do {
let data: Data = try {
if let data = rawData {
return data
} else {
return try defaultManager.encoder.encode(self)
}
}()
coreItem.setValue(data, forKey: Self.serializedDataKey)
} catch let encodeError {
print("Error: decoding failed for \(type(of: self)): \(encodeError)")
coreItem.setValue(nil, forKey: Self.serializedDataKey)
}
setAdditionalColumnsOnSave(coreItem: coreItem)
}
/// (Protocol default)
/// Gets the struct to match the core data request.
public static func get(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Self? {
return _get(with: manager, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of get:manager:AlterFetchRequest<EntityType>
/// (manager not required).
public static func get(
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Self? {
return get(with: nil, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of get:manager:AlterFetchRequest<EntityType>
/// (no parameters required).
public static func get(
with manager: CodableCoreDataManageable? = nil
) -> Self? {
return get(with: manager) { _ in }
}
/// Root version of get:manager:AlterFetchRequest<EntityType> (you can still call this if you override that).
///
/// DO NOT OVERRIDE.
internal static func _get(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Self? {
let manager = manager ?? defaultManager
let one: Self? = manager.getValue(alterFetchRequest: alterFetchRequest)
return one
}
/// (Protocol default)
/// Gets the struct to match the core data request.
public static func getCount(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Int {
let manager = manager ?? defaultManager
return manager.getCount(alterFetchRequest: alterFetchRequest)
}
/// Convenience version of getCount:manager:AlterFetchRequest<EntityType>
/// (manager not required).
public static func getCount(
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Int {
return getCount(with: nil, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of getCount:manager:AlterFetchRequest<EntityType>
/// (AlterFetchRequest<EntityType> not required).
public static func getCount(
with manager: CodableCoreDataManageable?
) -> Int {
return getCount(with: manager, alterFetchRequest: { _ in })
}
/// Convenience version of getCount:manager:AlterFetchRequest<EntityType>
/// (no parameters required).
public static func getCount() -> Int {
return getCount(with: nil) { _ in }
}
/// (Protocol default)
/// Gets all structs that match the core data request.
public static func getAll(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> [Self] {
return _getAll(with: manager, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of getAll:manager:AlterFetchRequest<EntityType>
/// (manager not required).
public static func getAll(
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> [Self] {
return getAll(with: nil, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of getAll:manager:AlterFetchRequest<EntityType>
/// (no parameters required).
public static func getAll(
with manager: CodableCoreDataManageable? = nil
) -> [Self] {
return getAll(with: manager) { _ in }
}
/// Root version of getAll:manager:AlterFetchRequest<EntityType> (you can still call this if you override that).
///
/// DO NOT OVERRIDE.
internal static func _getAll(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> [Self] {
let manager = manager ?? defaultManager
let all: [Self] = manager.getAllValues(alterFetchRequest: alterFetchRequest)
return all
}
/// (Protocol default)
/// Saves the struct to core data.
public mutating func save(
with manager: CodableCoreDataManageable?
) -> Bool {
let manager = manager ?? defaultManager
let isSaved = manager.saveValue(item: self)
return isSaved
}
/// Convenience version of save:manager
/// (no parameters required).
public mutating func save() -> Bool {
return save(with: nil)
}
/// (Protocol default)
/// Saves all the structs to core data.
public static func saveAll(
items: [Self],
with manager: CodableCoreDataManageable?
) -> Bool {
guard !items.isEmpty else { return true }
let manager = manager ?? defaultManager
let isSaved = manager.saveAllValues(items: items)
return isSaved
}
/// Convenience version of saveAll:items:manager
/// (manager not required).
public static func saveAll(
items: [Self]
) -> Bool {
return saveAll(items: items, with: nil)
}
/// (Protocol default)
/// Copies all rows that match the core data request.
public static func copyAll(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>,
setChangedValues: @escaping SetAdditionalColumns<EntityType>
) -> Bool {
let manager = manager ?? defaultManager
return manager.copyAll(alterFetchRequest: alterFetchRequest, setChangedValues: setChangedValues)
}
/// Convenience version of copyAll:manager:AlterFetchRequest<EntityType>
/// (manager not required).
public static func copyAll(
alterFetchRequest: @escaping AlterFetchRequest<EntityType>,
setChangedValues: @escaping SetAdditionalColumns<EntityType>
) -> Bool {
return copyAll(with: nil, alterFetchRequest: alterFetchRequest, setChangedValues: setChangedValues)
}
/// (Protocol default)
/// Deletes the struct's core data equivalent.
public mutating func delete(
with manager: CodableCoreDataManageable?
) -> Bool {
let manager = manager ?? defaultManager
let isDeleted = manager.deleteValue(item: self)
return isDeleted
}
/// Convenience version of delete:manager
/// (no parameters required).
public mutating func delete() -> Bool {
return delete(with: nil)
}
/// (Protocol default)
/// Deletes all rows that match the core data request.
public static func deleteAll(
with manager: CodableCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Bool {
let manager = manager ?? defaultManager
let isDeleted = manager.deleteAll(alterFetchRequest: alterFetchRequest)
return isDeleted
}
/// Convenience version of deleteAll:manager:AlterFetchRequest<EntityType>
/// (manager not required).
public static func deleteAll(
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Bool {
return deleteAll(with: nil, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of deleteAll:manager:AlterFetchRequest<EntityType>
/// (AlterFetchRequest<EntityType> not required).
public static func deleteAll(
with manager: CodableCoreDataManageable?
) -> Bool {
return deleteAll(with: manager) { _ in }
}
/// Convenience version of deleteAll:manager:AlterFetchRequest<EntityType>
/// (no parameters required).
public static func deleteAll() -> Bool {
return deleteAll(with: nil) { _ in }
}
// /// (Protocol default)
// /// Applies a dictionary data set of changes, and returns an updated copy of the object
// func changed(
// _ changes: [String: Any?]
// ) -> Self {
// return self
// }
}
| mit | 1bb8c01805cb8b14ef68289b6e30fc41 | 33.821159 | 116 | 0.659722 | 5.220544 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/Root/Models/ZSUserBookshelf.swift | 1 | 602 | //
// ZSUserBookshelf.swift
// zhuishushenqi
//
// Created by yung on 2018/10/21.
// Copyright © 2018年 QS. All rights reserved.
//
import UIKit
import HandyJSON
class ZSUserBookshelf: NSObject, HandyJSON {
var id:String = ""
var updated:String = ""
var recordUpdated:String = ""
var modifyTime:String = ""
var type = 0
required override init() {}
}
//{
// "id": "583281b48aa389077cec86c3",
// "updated": "2017-02-28T05:39:36.707Z",
// "recordUpdated": "2018-09-10T02:24:33.886Z",
// "modifyTime": "2018-09-10T12:51:05.652Z",
// "type": 0
//}
| mit | 8572b7f12b3ec9434ed4785dbdd55e5a | 18.966667 | 50 | 0.611018 | 2.879808 | false | false | false | false |
rgbycch/rgbycch_swift_api | Pod/Classes/RGBYCCHAPIParsers.swift | 1 | 7538 | // The MIT License (MIT)
// Copyright (c) 2015 rgbycch
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import SwiftyJSON
enum RGBYCCHAPIParserError: ErrorType {
case RGBYCCHAPIParserEmptyResponse
case RGBYCCHAPIParserInvalidFieldType
}
enum CommonParserConstants : String {
case identifier = "id"
case user = "user"
case email = "email"
case team = "team"
case teams = "teams"
case title = "title"
case clubs = "clubs"
case club = "club"
case url = "url"
}
enum UserParserConstants : String {
case authToken = "auth_token"
}
enum PlayerParserConstants : String {
case firstName = "first_name"
case lastName = "last_name"
case nickName = "nick_name"
case dob = "dob"
case phone_number = "phone_number"
case players = "players"
case player = "player"
}
enum ClubParserConstants : String {
case founded = "founded"
}
public protocol RGBYCCHAPIParser {
func parse(json:JSON) throws -> ([AnyObject]?)
}
public class RGBYCCHAPIUserParser : RGBYCCHAPIParser {
public func parse(json:JSON) throws -> ([AnyObject]?) {
let user = User()
user.identifier = json[CommonParserConstants.user.rawValue][CommonParserConstants.identifier.rawValue].int32Value
user.email = json[CommonParserConstants.user.rawValue][CommonParserConstants.email.rawValue].stringValue
user.authToken = json[CommonParserConstants.user.rawValue][UserParserConstants.authToken.rawValue].stringValue
RGBYCCHAPICurrentUser.sharedInstance.user = user;
return ([user])
}
}
public class RGBYCCHAPITeamParser : RGBYCCHAPIParser {
public func parse(json:JSON) throws -> ([AnyObject]?) {
return ([self.parseTeam(json)])
}
public func parseTeam(json:JSON) -> Team {
let team = Team()
let teamDictionary = json[CommonParserConstants.team.rawValue]
team.identifier = teamDictionary[CommonParserConstants.identifier.rawValue].int32Value
team.title = teamDictionary[CommonParserConstants.title.rawValue].stringValue
return team
}
}
public class RGBYCCHAPITeamsParser : RGBYCCHAPIParser {
public func parse(json:JSON) throws -> ([AnyObject]?) {
let teamParser = RGBYCCHAPITeamParser()
let teams = json[CommonParserConstants.teams.rawValue].arrayValue
var parsedTeams:Array<AnyObject> = []
for entry in teams {
let team = teamParser.parseTeam(entry)
parsedTeams.append(team)
}
return (parsedTeams)
}
}
public class RGBYCCHAPIUpdateTeamParser : RGBYCCHAPIParser {
public func parse(json:JSON) throws -> ([AnyObject]?) {
let teamParser = RGBYCCHAPITeamParser()
let team = teamParser.parseTeam(json[CommonParserConstants.team.rawValue])
return ([team])
}
}
public class RGBYCCHAPIPlayerParser : RGBYCCHAPIParser {
public func parse(json:JSON) throws -> ([AnyObject]?) {
return ([self.parsePlayer(json)])
}
public func parsePlayer (json:JSON) -> Player {
let player = Player()
let formatter = NSDateFormatter()
formatter.dateFormat = RGBYCCHAPIDateFormat.dateFormat.rawValue
player.identifier = json[CommonParserConstants.identifier.rawValue].int32Value
player.firstName = json[PlayerParserConstants.firstName.rawValue].stringValue
player.lastName = json[PlayerParserConstants.lastName.rawValue].stringValue
player.nickName = json[PlayerParserConstants.nickName.rawValue].stringValue
let dateString = json[PlayerParserConstants.dob.rawValue].stringValue
player.dob = formatter.dateFromString(dateString)!
player.email = json[CommonParserConstants.email.rawValue].stringValue
player.phoneNumber = json[PlayerParserConstants.phone_number.rawValue].stringValue
return player
}
}
public class RGBYCCHAPIPlayersParser : RGBYCCHAPIParser {
public func parse(json:JSON) throws -> ([AnyObject]?) {
let playerParser = RGBYCCHAPIPlayerParser()
let players = json[PlayerParserConstants.players.rawValue].arrayValue
var parsedPlayers:Array<AnyObject> = []
for entry in players {
let player = playerParser.parsePlayer(entry)
parsedPlayers.append(player)
}
return (parsedPlayers)
}
}
public class RGBYCCHAPIDeletionParser : RGBYCCHAPIParser {
public func parse(json:JSON) throws -> ([AnyObject]?) {
return (nil)
}
}
public class RGBYCCHAPIUpdatePlayerParser : RGBYCCHAPIParser {
public func parse(json:JSON) throws -> ([AnyObject]?) {
let playerParser = RGBYCCHAPIPlayerParser()
let player = playerParser.parsePlayer(json[PlayerParserConstants.player.rawValue])
return ([player])
}
}
public class RGBYCCHAPIClubParser : RGBYCCHAPIParser {
public func parse(json:JSON) throws -> ([AnyObject]?) {
return ([self.parseClub(json)])
}
public func parseClub(json:JSON) -> Club {
let club = Club()
let clubDictionary = json[CommonParserConstants.club.rawValue]
club.identifier = clubDictionary[CommonParserConstants.identifier.rawValue].int32Value
club.title = clubDictionary[CommonParserConstants.title.rawValue].stringValue
club.url = clubDictionary[CommonParserConstants.url.rawValue].stringValue
let formatter = NSDateFormatter()
formatter.dateFormat = RGBYCCHAPIDateFormat.dateFormat.rawValue
let dateString:NSString = json[ClubParserConstants.founded.rawValue].stringValue
if dateString.length > 0 {
club.founded = formatter.dateFromString(dateString as String)!
}
return club
}
}
public class RGBYCCHAPIClubsParser : RGBYCCHAPIParser {
public func parse(json:JSON) throws -> ([AnyObject]?) {
let clubParser = RGBYCCHAPIClubParser()
let clubs = json[CommonParserConstants.clubs.rawValue].arrayValue
var parsedClubs = [AnyObject]()
for entry in clubs {
let club = clubParser.parseClub(entry)
parsedClubs.append(club)
}
return (parsedClubs)
}
}
public class RGBYCCHAPIUpdateClubParser : RGBYCCHAPIParser {
public func parse(json:JSON) throws -> ([AnyObject]?) {
let clubParser = RGBYCCHAPIClubParser()
let club = clubParser.parseClub(json[CommonParserConstants.club.rawValue])
return ([club])
}
} | mit | 1225aa07b07cf98b40b8a74024a27b07 | 34.729858 | 121 | 0.698063 | 4.282955 | false | false | false | false |
juandesant/test_swift_cli | test_swift_cli/main.swift | 1 | 1951 | //
// main.swift
// test_swift_cli
//
// Created by Santander-Vela, Juande on 17/09/2015.
// Copyright © 2015 Santander-Vela, Juande. All rights reserved.
//
import Foundation
// 456789012345678901234567890123456789012345678901234567890123456789012
// Create a generator from Process.arguments, so that we can use it
// inside the `while` loop, for obtaining the next argument for flags
// that provide a value
var arguments = CommandLine.arguments.makeIterator()
// We will use flagA as a flip-flop flag, and valB as an integer value
var flagA = false
var valB: Int = 0
// We use `while let arg` so that the while ends when there are no more
// arguments
while let arg = arguments.next() {
print("Parsing \(arg)") // to see the process in the while loop
switch arg {
// we can use comparisons because the while let ensures
// that arg is set, and cannot be nil
case "-a":
// we negate the value of flagA for each
// occurence of -a as an argument
flagA = !flagA
case "-b":
// In the case of the -b flag, we want
// the value. We could check if -b was used
// before, but in this case the last value wins
print("Getting value for -b")
let valBarg = arguments.next()
valB = Int(valBarg!)!
print("Setting \(String(describing: valBarg))")
default:
// We hit this case for non understandable values
// We could choose to exit instead.
print("Argument \(arg) not processed")
continue;
}
}
// List all arguments (including the tool path, which will be the first argument)
for pArg in CommandLine.arguments {
print(pArg)
}
// Show one message or the other
if flagA {
print("Flag A was set")
} else {
print("Flag A was not set")
}
// If valB is not 0, it was set
if valB != 0 {
print("B was set as \(valB)")
}
| mit | e362311cbdf1ea9fff6a7dad14731ef7 | 30.451613 | 81 | 0.627692 | 3.955375 | false | false | false | false |
mobilabsolutions/jenkins-ios | JenkinsiOS/View/StarRatingView.swift | 1 | 2567 | //
// StarRatingView.swift
// JenkinsiOS
//
// Created by Robert on 01.12.16.
// Copyright © 2016 MobiLab Solutions. All rights reserved.
//
import UIKit
@IBDesignable class StarRatingView: UIView {
@IBOutlet var stars: [UIImageView]!
@IBInspectable var offImage: UIImage?
@IBInspectable var onImage: UIImage?
var delegate: StarRatingViewDelegate?
private(set) var selectedNumberOfStars = 0
private var view: UIView?
private func loadFromNib() -> UIView? {
return UINib(nibName: "StarRatingView", bundle: Bundle(for: type(of: self))).instantiate(withOwner: self, options: nil)[0] as? UIView
}
private func setupWithXIB() {
view = loadFromNib()
guard let view = view
else { return }
addSubview(view)
addConstraints(to: view)
}
private func addConstraints(to view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
view.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
view.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
view.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
view.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
override func layoutSubviews() {
for starView in stars {
starView.isUserInteractionEnabled = true
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped))
starView.addGestureRecognizer(tapRecognizer)
}
selectStars(count: selectedNumberOfStars)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupWithXIB()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupWithXIB()
}
@objc private func tapped(gestureRecognizer: UIGestureRecognizer) {
guard let star = gestureRecognizer.view as? UIImageView
else { return }
guard let index = stars.index(of: star)
else { return }
var numberOfStars = index + 1
if numberOfStars == selectedNumberOfStars {
// The user tapped on an already selected last star
numberOfStars -= 1
}
delegate?.userDidChangeNumberOfStars(to: numberOfStars)
selectStars(count: numberOfStars)
}
func selectStars(count: Int) {
selectedNumberOfStars = count
for (offset, star) in stars.enumerated() {
star.image = (offset <= (count - 1)) ? onImage : offImage
}
}
}
| mit | bab41e7906a9ed61b79eb4eeffa65693 | 27.511111 | 141 | 0.650039 | 4.769517 | false | false | false | false |
nua-schroers/AccessibilityExamples | AccessibilityExamples/ViewWithCustomElements.swift | 1 | 4265 | //
// ViewWithCustomElements.swift
// AccessibilityExamples
//
// Created by Dr. Wolfram Schroers on 3/1/15.
// Copyright (c) 2015 Wolfram Schroers. All rights reserved.
//
import UIKit
/// This is a view with custom-drawn elements. These are not derived
/// from any UIKit objects and are therefore non-accessible. In order
/// to make them accessible, we must set the property
/// accessibilityElements (or, alternatively, adopt the other methods
/// from the UIAccessibilityContainer informal protocol).
///
/// The order of the elements matters and should go from top left to
/// bottom right.
class ViewWithCustomElements: CustomView {
/// MARK: Override from UIView
override func draw(_ rect: CGRect) {
// View setup (nothing to do with Accessibility).
// Draw the string "Hello" left-ish in this view.
let someString = NSString(format: "Hello")
someString.draw(at: CGPoint(x: 10, y: 10), withAttributes: nil)
// Draw the string "World" right-ish in this view.
let someOtherString = NSString(format: "World")
let attribs: [String: AnyObject] = [convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): UIColor.green]
someOtherString.draw(at: CGPoint(x: 120, y: 10), withAttributes: convertToOptionalNSAttributedStringKeyDictionary(attribs))
// Setup the accessibility container.
self.setupContainer()
}
/// MARK: Setting up the Accessibility Container.
func setupContainer() {
// Instantiate proxies as a stand-in for the custom-drawn
// elements.
//
// Note that this method would have to be called whenever the
// screen changes, e.g. when the device is rotated. The
// ViewController would be responsible for doing that since
// drawRect may not be called again automatically.
// Get the frame of the first string (in screen coordinates).
let firstStringSize = NSString(format: "Hello").size(withAttributes: nil)
let firstStringRect = CGRect(x: 10, y: 10, width: firstStringSize.width, height: firstStringSize.height)
let firstStringFrame = self.convert(firstStringRect, to: nil)
// Get the frame of the second string (in screen coordinates).
let secondStringSize = NSString(format: "World").size(withAttributes: nil)
let secondStringRect = CGRect(x: 120, y: 10, width: secondStringSize.width, height: secondStringSize.height)
let secondStringFrame = self.convert(secondStringRect, to: nil)
// Properly configure the stand-in for the custom-drawn string
// "Hello". This works like any other "regular" view.
let element1 = UIAccessibilityElement(accessibilityContainer: self)
element1.accessibilityFrame = firstStringFrame
element1.accessibilityLabel = "Shows Hello"
element1.accessibilityTraits = UIAccessibilityTraits.staticText
// Do the same for the second element, the stand-in for the
// custom-drawn string "World".
let element2 = UIAccessibilityElement(accessibilityContainer: self)
element2.accessibilityFrame = secondStringFrame
element2.accessibilityLabel = "Shows World"
element2.accessibilityTraits = UIAccessibilityTraits.staticText
// Set the accessbilityElements which turns this view into an
// Accessibility Container.
self.accessibilityElements = [element1, element2]
}
/// MARK: Setup method
override func setup() {
super.setup()
// Accessibility setup.
self.isAccessibilityElement = false
// We don't need to do anything else since drawRect is
// automatically called when needed.
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
| mit | f7b9f249fe1dd65913f289a91e7a8be2 | 40.813725 | 132 | 0.702696 | 4.786756 | false | false | false | false |
airbnb/lottie-ios | Sources/Private/Utility/Primitives/VectorsExtensions.swift | 2 | 7246 | //
// Vector.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/7/19.
//
import CoreGraphics
import Foundation
import QuartzCore
// MARK: - LottieVector1D + Codable
/// Single value container. Needed because lottie sometimes wraps a Double in an array.
extension LottieVector1D: Codable {
// MARK: Lifecycle
public init(from decoder: Decoder) throws {
/// Try to decode an array of doubles
do {
var container = try decoder.unkeyedContainer()
value = try container.decode(Double.self)
} catch {
value = try decoder.singleValueContainer().decode(Double.self)
}
}
// MARK: Public
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(value)
}
// MARK: Internal
var cgFloatValue: CGFloat {
CGFloat(value)
}
}
// MARK: - LottieVector1D + AnyInitializable
extension LottieVector1D: AnyInitializable {
init(value: Any) throws {
if
let array = value as? [Double],
let double = array.first
{
self.value = double
} else if let double = value as? Double {
self.value = double
} else {
throw InitializableError.invalidInput
}
}
}
extension Double {
var vectorValue: LottieVector1D {
LottieVector1D(self)
}
}
// MARK: - LottieVector2D
/// Needed for decoding json {x: y:} to a CGPoint
public struct LottieVector2D: Codable, Hashable {
// MARK: Lifecycle
init(x: Double, y: Double) {
self.x = x
self.y = y
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: LottieVector2D.CodingKeys.self)
do {
let xValue: [Double] = try container.decode([Double].self, forKey: .x)
x = xValue[0]
} catch {
x = try container.decode(Double.self, forKey: .x)
}
do {
let yValue: [Double] = try container.decode([Double].self, forKey: .y)
y = yValue[0]
} catch {
y = try container.decode(Double.self, forKey: .y)
}
}
// MARK: Public
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: LottieVector2D.CodingKeys.self)
try container.encode(x, forKey: .x)
try container.encode(y, forKey: .y)
}
// MARK: Internal
var x: Double
var y: Double
var pointValue: CGPoint {
CGPoint(x: x, y: y)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case x
case y
}
}
// MARK: AnyInitializable
extension LottieVector2D: AnyInitializable {
init(value: Any) throws {
guard let dictionary = value as? [String: Any] else {
throw InitializableError.invalidInput
}
if
let array = dictionary[CodingKeys.x.rawValue] as? [Double],
let double = array.first
{
x = double
} else if let double = dictionary[CodingKeys.x.rawValue] as? Double {
x = double
} else {
throw InitializableError.invalidInput
}
if
let array = dictionary[CodingKeys.y.rawValue] as? [Double],
let double = array.first
{
y = double
} else if let double = dictionary[CodingKeys.y.rawValue] as? Double {
y = double
} else {
throw InitializableError.invalidInput
}
}
}
extension CGPoint {
var vector2dValue: LottieVector2D {
LottieVector2D(x: Double(x), y: Double(y))
}
}
// MARK: - LottieVector3D + Codable
/// A three dimensional vector.
/// These vectors are encoded and decoded from [Double]
extension LottieVector3D: Codable {
// MARK: Lifecycle
init(x: CGFloat, y: CGFloat, z: CGFloat) {
self.x = Double(x)
self.y = Double(y)
self.z = Double(z)
}
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
if !container.isAtEnd {
x = try container.decode(Double.self)
} else {
x = 0
}
if !container.isAtEnd {
y = try container.decode(Double.self)
} else {
y = 0
}
if !container.isAtEnd {
z = try container.decode(Double.self)
} else {
z = 0
}
}
// MARK: Public
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(x)
try container.encode(y)
try container.encode(z)
}
}
// MARK: - LottieVector3D + AnyInitializable
extension LottieVector3D: AnyInitializable {
init(value: Any) throws {
guard var array = value as? [Double] else {
throw InitializableError.invalidInput
}
x = array.count > 0 ? array.removeFirst() : 0
y = array.count > 0 ? array.removeFirst() : 0
z = array.count > 0 ? array.removeFirst() : 0
}
}
extension LottieVector3D {
public var pointValue: CGPoint {
CGPoint(x: x, y: y)
}
public var sizeValue: CGSize {
CGSize(width: x, height: y)
}
}
extension CGPoint {
var vector3dValue: LottieVector3D {
LottieVector3D(x: x, y: y, z: 0)
}
}
extension CGSize {
var vector3dValue: LottieVector3D {
LottieVector3D(x: width, y: height, z: 1)
}
}
extension CATransform3D {
static func makeSkew(skew: CGFloat, skewAxis: CGFloat) -> CATransform3D {
let mCos = cos(skewAxis.toRadians())
let mSin = sin(skewAxis.toRadians())
let aTan = tan(skew.toRadians())
let transform1 = CATransform3D(
m11: mCos,
m12: mSin,
m13: 0,
m14: 0,
m21: -mSin,
m22: mCos,
m23: 0,
m24: 0,
m31: 0,
m32: 0,
m33: 1,
m34: 0,
m41: 0,
m42: 0,
m43: 0,
m44: 1)
let transform2 = CATransform3D(
m11: 1,
m12: 0,
m13: 0,
m14: 0,
m21: aTan,
m22: 1,
m23: 0,
m24: 0,
m31: 0,
m32: 0,
m33: 1,
m34: 0,
m41: 0,
m42: 0,
m43: 0,
m44: 1)
let transform3 = CATransform3D(
m11: mCos,
m12: -mSin,
m13: 0,
m14: 0,
m21: mSin,
m22: mCos,
m23: 0,
m24: 0,
m31: 0,
m32: 0,
m33: 1,
m34: 0,
m41: 0,
m42: 0,
m43: 0,
m44: 1)
return CATransform3DConcat(transform3, CATransform3DConcat(transform2, transform1))
}
static func makeTransform(
anchor: CGPoint,
position: CGPoint,
scale: CGSize,
rotation: CGFloat,
skew: CGFloat?,
skewAxis: CGFloat?)
-> CATransform3D
{
if let skew = skew, let skewAxis = skewAxis {
return CATransform3DMakeTranslation(position.x, position.y, 0).rotated(rotation).skewed(skew: -skew, skewAxis: skewAxis)
.scaled(scale * 0.01).translated(anchor * -1)
}
return CATransform3DMakeTranslation(position.x, position.y, 0).rotated(rotation).scaled(scale * 0.01).translated(anchor * -1)
}
func rotated(_ degrees: CGFloat) -> CATransform3D {
CATransform3DRotate(self, degrees.toRadians(), 0, 0, 1)
}
func translated(_ translation: CGPoint) -> CATransform3D {
CATransform3DTranslate(self, translation.x, translation.y, 0)
}
func scaled(_ scale: CGSize) -> CATransform3D {
CATransform3DScale(self, scale.width, scale.height, 1)
}
func skewed(skew: CGFloat, skewAxis: CGFloat) -> CATransform3D {
CATransform3DConcat(CATransform3D.makeSkew(skew: skew, skewAxis: skewAxis), self)
}
}
| apache-2.0 | 628260c7a52d06ebbf0804951e81f13d | 20.249267 | 129 | 0.61979 | 3.480307 | false | false | false | false |
Synchronized-TV/cordova-plugin-parse | src/ios/Parse.swift | 2 | 17844 |
import Foundation
import Parse
@objc protocol SNSUtils {
class func unlinkUserInBackground(user: PFUser!, block: PFBooleanResultBlock!)
class func unlinkUserInBackground(user: PFUser!, target: AnyObject!, selector: Selector)
}
@objc(CDVParse) class CDVParse : CDVPlugin {
// catches FB oauth
override func handleOpenURL(notification: NSNotification!) {
super.handleOpenURL(notification);
var sourceApplication = "test";
var wasHandled:AnyObject = FBAppCall.handleOpenURL(notification.object as NSURL, sourceApplication:nil, withSession:PFFacebookUtils.session());
NSLog("wasHandled \(wasHandled)");
}
private func getPluginResult(success: Bool, message: String) -> CDVPluginResult {
NSLog("pluginResult(\(success)): \(message)");
return CDVPluginResult(status: (success ? CDVCommandStatus_OK : CDVCommandStatus_ERROR), messageAsString: message);
}
private func getPluginResult(success: Bool, message: String, data: Dictionary<String, AnyObject>) -> CDVPluginResult {
NSLog("pluginResult(\(success)): \(message)");
return CDVPluginResult(status: (success ? CDVCommandStatus_OK : CDVCommandStatus_ERROR), messageAsDictionary: data);
}
// store keys for the client
var appKeys = [String: String]();
// setup accounts on startup
override func pluginInitialize() {
NSLog("pluginInitialize");
var plist = NSBundle.mainBundle();
// store some keys for the client SDKs
appKeys["ParseApplicationId"] = plist.objectForInfoDictionaryKey("ParseApplicationId") as String!
//appKeys["ParseClientKey"] = plist.objectForInfoDictionaryKey("ParseClientKey") as String!
// not needed (yet) because twitter not included in the Parse client SDK
// appKeys["TwitterConsumerKey"] = plist.objectForInfoDictionaryKey("TwitterConsumerKey") as? String
appKeys["FacebookAppID"] = plist.objectForInfoDictionaryKey("FacebookAppID") as String!
Parse.setApplicationId(
appKeys["ParseApplicationId"],
clientKey: appKeys["ParseClientKey"]
)
PFFacebookUtils.initializeFacebook()
PFTwitterUtils.initializeWithConsumerKey(
plist.objectForInfoDictionaryKey("TwitterConsumerKey") as String!,
consumerSecret: plist.objectForInfoDictionaryKey("TwitterConsumerSecret") as String!
)
let enableAutomaticUser: AnyObject! = plist.objectForInfoDictionaryKey("ParseEnableAutomaticUser");
if enableAutomaticUser===true {
PFUser.enableAutomaticUser();
}
}
// return user status
func getStatus(command: CDVInvokedUrlCommand) -> Void {
var pluginResult = CDVPluginResult()
var currentUser = PFUser.currentUser()
var userStatus = [
"isNew": true,
"isAuthenticated": false,
"facebook": false,
"twitter": false,
"username": "",
"email": "",
"emailVerified": false
];
if (currentUser != nil) {
// force refresh user data
currentUser.fetchInBackgroundWithBlock {
(user:PFObject!, error: NSError!) -> Void in
if (error == nil) {
// update with logged in user data
userStatus["sessionToken"] = currentUser.sessionToken
userStatus["isNew"] = currentUser.isNew
userStatus["username"] = currentUser.username
userStatus["email"] = currentUser.email
userStatus["isAuthenticated"] = currentUser.isAuthenticated()
userStatus["facebook"] = PFFacebookUtils.isLinkedWithUser(currentUser)
userStatus["twitter"] = PFTwitterUtils.isLinkedWithUser(currentUser)
userStatus["keys"] = self.appKeys
if (currentUser.objectForKey("emailVerified") != nil) {
userStatus["emailVerified"] = currentUser["emailVerified"] as Bool
}
for item in user.allKeys() {
let key = item as String
userStatus[key] = user[key] as? NSObject
}
pluginResult = self.getPluginResult(true, message: "getStatus", data:userStatus)
} else {
let errorString = error.userInfo!["error"] as NSString
pluginResult = self.getPluginResult(false, message: errorString)
}
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
}
func unlinkFacebook(command: CDVInvokedUrlCommand) -> Void {
var result = self.unlinkNetwork("facebook");
commandDelegate.sendPluginResult(result, callbackId:command.callbackId)
}
func unlinkTwitter(command: CDVInvokedUrlCommand) -> Void {
var result = self.unlinkNetwork("twitter");
commandDelegate.sendPluginResult(result, callbackId:command.callbackId)
}
private func getNetworkClass(network: String) -> AnyClass {
var networks: Dictionary<String, AnyClass> = [
"facebook": PFFacebookUtils.self,
"twitter": PFTwitterUtils.self
];
return networks[network]!;
}
private func unlinkNetwork(network: String) -> CDVPluginResult {
var pluginResult = CDVPluginResult();
var currentUser = PFUser.currentUser();
let networkCls: AnyClass = getNetworkClass(network);
if (networkCls.isLinkedWithUser(currentUser)) {
networkCls.unlinkUserInBackground(currentUser as PFUser!, {
(succeeded: Bool, error: NSError!) -> Void in
if succeeded {
pluginResult = self.getPluginResult(true, message: "The user is no longer associated with their \(network) account.");
} else {
pluginResult = self.getPluginResult(false, message: "Cannot unlink user to their \(network) account.");
}
})
} else {
pluginResult = self.getPluginResult(false, message: "User not linked to \(network)");
}
return pluginResult;
}
private func loginWith(network: String, permissions: Array<String>=[]) -> CDVPluginResult {
// handle both FB and Twitter login processes
// handle existing and new account
var pluginResult = CDVPluginResult();
var currentUser = PFUser.currentUser();
let networkCls: AnyClass = getNetworkClass(network);
// PFUser already exists
if (currentUser != nil) {
if (networkCls.isLinkedWithUser(currentUser)) {
pluginResult = self.getPluginResult(true, message: "user already logged in with \(network)!");
} else {
if (network == "facebook") {
// facebook needs special permissions
PFFacebookUtils.linkUser(currentUser, permissions: permissions as Array, {
(succeeded: Bool, error: NSError!) -> Void in
if succeeded {
// fetch user details with FB api
FBRequestConnection.startForMeWithCompletionHandler({connection, result, error in
if (error === nil)
{
currentUser["fbId"] = result.objectID as String;
currentUser["fbName"] = result.name as String;
currentUser["fbEmail"] = result.email as String;
currentUser.saveEventually()
pluginResult = self.getPluginResult(true, message: "user logged in with \(network)!");
} else {
pluginResult = self.getPluginResult(false, message: "Cannot fetch \(network) account details :/");
}
})
} else {
pluginResult = self.getPluginResult(false, message: "Error linking \(network) account :/");
}
})
} else if (network == "twitter") {
PFTwitterUtils.linkUser(currentUser, {
(succeeded: Bool, error: NSError!) -> Void in
if succeeded {
// store twitter handle
currentUser["twitterHandle"] = PFTwitterUtils.twitter().screenName;
currentUser.saveEventually()
pluginResult = self.getPluginResult(true, message: "user logged in with \(network)!");
} else {
pluginResult = self.getPluginResult(false, message: "Error linking \(network) account :/");
}
})
}
}
// user not logged, create a new account from FB
} else {
if (network == "facebook") {
// create a new user using FB
PFFacebookUtils.logInWithPermissions(permissions as Array, {
(user: PFUser!, error: NSError!) -> Void in
if user == nil {
pluginResult = self.getPluginResult(false, message: "Uh oh. The user cancelled the \(network) login.");
} else if user.isNew {
pluginResult = self.getPluginResult(true, message: "User signed up and logged in through \(network)!");
} else {
pluginResult = self.getPluginResult(true, message: "User logged in through \(network)!");
}
})
} else if (network == "twitter") {
// create a new user using twitter
PFTwitterUtils.logInWithBlock {
(user: PFUser!, error: NSError!) -> Void in
if user == nil {
pluginResult = self.getPluginResult(false, message: "Uh oh. The user cancelled the \(network) login.");
} else if user.isNew {
pluginResult = self.getPluginResult(true, message: "User signed up and logged in through \(network)!");
} else {
pluginResult = self.getPluginResult(true, message: "User logged in through \(network)!");
}
}
}
}
return pluginResult
}
// start FB login process
func loginWithFacebook(command: CDVInvokedUrlCommand) -> Void {
var options = command.arguments[0] as [String: AnyObject];
if (options["permissions"] === nil) {
options["permissions"] = ["public_profile", "email"];
}
var result = self.loginWith("facebook", permissions: options["permissions"] as Array);
self.commandDelegate.sendPluginResult(result, callbackId:command.callbackId)
}
// start Twitter login process
func loginWithTwitter(command: CDVInvokedUrlCommand) -> Void {
var result = self.loginWith("twitter");
self.commandDelegate.sendPluginResult(result, callbackId:command.callbackId)
}
func logout(command: CDVInvokedUrlCommand) -> Void {
var pluginResult = self.getPluginResult(true, message: "user logged out");
PFUser.logOut();
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
// create a new Parse account
func signUp(command: CDVInvokedUrlCommand) -> Void {
var email = command.arguments[0] as String
var password = command.arguments[1] as String
var pluginResult = CDVPluginResult()
var user = PFUser()
user.username = email
user.password = password
user.email = email
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
if error == nil {
pluginResult = self.getPluginResult(true, message: "user signed up successfully");
} else {
let errorString = error.userInfo!["error"] as NSString
pluginResult = self.getPluginResult(false, message: errorString);
}
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
// login to a new Parse account
func logIn(command: CDVInvokedUrlCommand) -> Void {
var email = command.arguments[0] as String
var password = command.arguments[1] as String
var pluginResult = CDVPluginResult()
PFUser.logInWithUsernameInBackground(email, password:password) {
(user: PFUser!, error: NSError!) -> Void in
if user != nil {
pluginResult = self.getPluginResult(true, message: "user logged in successfully");
} else {
let errorString = error.userInfo!["error"] as NSString
pluginResult = self.getPluginResult(false, message: errorString);
}
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
// launch Parse password receovery process
func resetPassword(command: CDVInvokedUrlCommand) -> Void {
var email = command.arguments[0] as String
var pluginResult = CDVPluginResult()
PFUser.requestPasswordResetForEmailInBackground(email) {
(succeeded: Bool!, error: NSError!) -> Void in
if error == nil {
pluginResult = self.getPluginResult(true, message: "password reset email sent");
} else {
let errorString = error.userInfo!["error"] as NSString
pluginResult = self.getPluginResult(false, message: errorString);
}
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
func setUserKey(command: CDVInvokedUrlCommand) -> Void {
var key = command.arguments[0] as String
var value = command.arguments[1] as String
var currentUser = PFUser.currentUser()
currentUser[key] = value
currentUser.saveEventually();
var pluginResult = self.getPluginResult(true, message: "user updated successfully");
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
// create a decente Twitter API call
private func getTwitterRequest(url: String, method: String = "POST", bodyData: String = "") -> NSMutableURLRequest {
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = method
if bodyData != "" {
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
}
PFTwitterUtils.twitter().signRequest(request)
return request
}
// parse errors if any
private func handleTwitterResponse(data: NSData) -> CDVPluginResult {
var pluginResult = CDVPluginResult()
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
if let errors = jsonResult["errors"]? as? NSArray {
if errors.count > 0 {
pluginResult = self.getPluginResult(false, message: errors[0]["message"] as String);
} else {
pluginResult = self.getPluginResult(true, message: "success");
}
} else {
pluginResult = self.getPluginResult(true, message: "success");
}
return pluginResult
}
// create/destroy retweet
private func twitterRetweetStatus(command: CDVInvokedUrlCommand, enable: Bool) -> Void {
let tweetId = command.arguments[0] as String
let action: String = enable ? "retweet" : "destroy";
let url = "https://api.twitter.com/1.1/statuses/\(action)/\(tweetId).json"
var request = self.getTwitterRequest(url, method: "POST")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
let pluginResult: CDVPluginResult = self.handleTwitterResponse(data);
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
func twitterRetweet(command: CDVInvokedUrlCommand) -> Void {
self.twitterRetweetStatus(command, enable: true);
}
func twitterCancelRetweet(command: CDVInvokedUrlCommand) -> Void {
self.twitterRetweetStatus(command, enable: false);
}
// create/destroy favorite
private func twitterFavoriteStatus(command: CDVInvokedUrlCommand, enable: Bool) -> Void {
let tweetId = command.arguments[0] as String
let action: String = enable ? "create" : "destroy";
let url = "https://api.twitter.com/1.1/favorites/\(action).json"
var request = self.getTwitterRequest(url, method: "POST", bodyData: "id=\(tweetId)")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
let pluginResult: CDVPluginResult = self.handleTwitterResponse(data);
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
func twitterFavorite(command: CDVInvokedUrlCommand) -> Void {
self.twitterFavoriteStatus(command, enable: true);
}
func twitterCancelFavorite(command: CDVInvokedUrlCommand) -> Void {
self.twitterFavoriteStatus(command, enable: false);
}
}
| mit | 18f9a5711e35631e654e65133c867831 | 45.834646 | 160 | 0.599305 | 5.368231 | false | false | false | false |
ibrdrahim/TopBarMenu | TopBarMenu/MenuCell.swift | 1 | 1343 | //
// MenuCell.swift
// TopBarMenu
//
// Created by ibrahim on 11/3/16.
// Copyright © 2016 Indosytem. All rights reserved.
//
import UIKit
class MenuCell: BaseCell {
let menu: UILabel = {
let lbl = UILabel()
lbl.textColor = UIColor.white.withAlphaComponent(0.4)
lbl.textAlignment = NSTextAlignment.center
lbl.font = lbl.font.withSize(14.0)
return lbl
}()
override var isHighlighted: Bool {
didSet {
menu.textColor = isHighlighted ? UIColor.white : UIColor.white.withAlphaComponent(0.4)
}
}
override var isSelected: Bool {
didSet {
menu.textColor = isHighlighted ? UIColor.white : UIColor.white.withAlphaComponent(0.4)
}
}
override func setupViews() {
super.setupViews()
addSubview(menu)
addConstraintsWithFormat(format:"H:[v0(110)]", views: menu)
addConstraintsWithFormat(format:"V:[v0(28)]", views: menu)
addConstraint(NSLayoutConstraint(item: menu, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: menu, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
}
}
| mit | 2217e338624c94e139df7060632e5bb9 | 29.5 | 156 | 0.621461 | 4.28754 | false | false | false | false |
foodfacts/FoodFacts-Swift-SDK | FoodFactsSDK/Classes/FFProductsResults.swift | 1 | 843 | //
// FFProductResults.swift
// Pods
//
// Created by Mackensie Alvarez on 2/17/17.
//
//
import Foundation
import SwiftyJSON
public class FFProductsResults {
/// Total results
public var totalResults: Int
/// Total results for this page
public var resultsPerPage: String
/// Current page you are in
public var currentPage: String
/// Status cooe for this API call
public var code: Int
public var products: [FFProduct]
init(json : JSON) {
self.totalResults = json["totalResults"].intValue
self.resultsPerPage = json["resultsPerPage"].stringValue
self.currentPage = json["currentPage"].stringValue
self.code = json["code"].intValue
self.products = json["products"].arrayValue.map({ j in return FFProduct(json: j) })
}
}
| mit | 5e7730658cc4b398789a10ba97ebbf29 | 23.085714 | 92 | 0.640569 | 4.323077 | false | false | false | false |
firebase/quickstart-ios | database/DatabaseExampleSwift/PostListViewController.swift | 1 | 3295 | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebaseDatabase
import FirebaseDatabaseUI
import FirebaseAuth
@objc(PostListViewController)
class PostListViewController: UIViewController, UITableViewDelegate {
// [START define_database_reference]
var ref: DatabaseReference!
// [END define_database_reference]
var dataSource: FUITableViewDataSource?
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// [START create_database_reference]
ref = Database.database().reference()
// [END create_database_reference]
let identifier = "post"
let nib = UINib(nibName: "PostTableViewCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: identifier)
dataSource =
FUITableViewDataSource(query: getQuery()) { (tableView, indexPath, snap) -> UITableViewCell in
let cell = tableView.dequeueReusableCell(
withIdentifier: identifier,
for: indexPath
) as! PostTableViewCell
guard let post = Post(snapshot: snap) else { return cell }
cell.authorImage.image = UIImage(named: "ic_account_circle")
cell.authorLabel.text = post.author
var imageName = "ic_star_border"
if (post.stars?[self.getUid()]) != nil {
imageName = "ic_star"
}
cell.starButton.setImage(UIImage(named: imageName), for: .normal)
if let starCount = post.starCount {
cell.numStarsLabel.text = "\(starCount)"
}
cell.postTitle.text = post.title
cell.postBody.text = post.body
return cell
}
dataSource?.bind(to: tableView)
tableView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "detail", sender: indexPath)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
func getUid() -> String {
return (Auth.auth().currentUser?.uid)!
}
func getQuery() -> DatabaseQuery {
return ref
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let indexPath: IndexPath = sender as? IndexPath else { return }
guard let detail: PostDetailTableViewController = segue
.destination as? PostDetailTableViewController else {
return
}
if let dataSource = dataSource {
detail.postKey = dataSource.snapshot(at: indexPath.row).key
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
getQuery().removeAllObservers()
}
}
| apache-2.0 | 03648d352d13e7afec968709bd63c4e2 | 30.084906 | 100 | 0.691958 | 4.538567 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/SupportingFiles/SharedTests.swift | 1 | 1537 | /**
* (C) Copyright IBM Corp. 2018, 2020.
*
* 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 IBMSwiftSDKCore
class SharedTests: XCTestCase {
func testHeaders() {
let serviceName = "test-service"
let serviceVersion = "v9"
let methodName = "testMethod"
let userAgentHeader = Shared.userAgent
let headers = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: methodName)
let analyticsHeader = headers["X-IBMCloud-SDK-Analytics"]
XCTAssertNotNil(userAgentHeader)
XCTAssertNotNil(analyticsHeader)
if let userAgentHeader = userAgentHeader {
#if os(iOS)
XCTAssert(userAgentHeader.contains("iOS"))
#endif
}
if let analyticsHeader = analyticsHeader {
let expectedHeader = "service_name=test-service;service_version=v9;operation_id=testMethod;async=true"
XCTAssertEqual(analyticsHeader, expectedHeader)
}
}
}
| apache-2.0 | 3dc2287019c2ba15c5bd327a8b58caa7 | 34.744186 | 124 | 0.692908 | 4.615616 | false | true | false | false |
krad/buffie | Sources/Buffie/Capture/Camera/CaptureSession.swift | 1 | 5706 | import Foundation
import AVKit
internal protocol CaptureSessionProtocol {
var videoOutput: AVCaptureVideoDataOutput? { get }
var audioOutput: AVCaptureAudioDataOutput? { get }
func start()
func start(onComplete: ((AVCaptureSession) -> Void)?)
func stop()
func changeToCamera(position: AVCaptureDevice.Position) -> Bool
}
internal class CaptureSession: CaptureSessionProtocol {
private var controlDelegate: CameraControlDelegate
@objc private var session: AVCaptureSession
var sessionObserver: NSKeyValueObservation?
private var videoInput: AVCaptureInput?
internal var videoOutput: AVCaptureVideoDataOutput?
private let videoQueue = DispatchQueue(label: "videoQ")
private var audioInput: AVCaptureInput?
internal var audioOutput: AVCaptureAudioDataOutput?
private let audioQueue = DispatchQueue(label: "audioQ")
required init(videoInput: AVCaptureInput? = nil,
audioInput: AVCaptureInput? = nil,
controlDelegate: CameraControlDelegate,
cameraReader: AVReaderProtocol) throws
{
self.controlDelegate = controlDelegate
self.session = AVCaptureSession()
if let vInput = videoInput {
self.videoInput = vInput
self.videoOutput = AVCaptureVideoDataOutput()
self.videoOutput?.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8PlanarFullRange]
// Add the video i/o to the session
self.session.addInput(self.videoInput!)
self.session.addOutput(self.videoOutput!)
self.videoOutput!.setSampleBufferDelegate(cameraReader.videoReader, queue: videoQueue)
}
if let aInput = audioInput {
self.audioInput = aInput
self.audioOutput = AVCaptureAudioDataOutput()
#if os(macOS)
self.audioOutput?.audioSettings = [
AVFormatIDKey: kAudioFormatLinearPCM,
AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsFloatKey: false,
AVLinearPCMIsNonInterleaved: false,
]
#endif
// Add the audio i/o to the session
self.session.addInput(self.audioInput!)
self.session.addOutput(self.audioOutput!)
self.audioOutput!.setSampleBufferDelegate(cameraReader.audioReader, queue: audioQueue)
}
self.setupObservers()
}
convenience init(videoDeviceID: String?,
audioDeviceID: String?,
controlDelegate: CameraControlDelegate,
cameraReader: AVReaderProtocol) throws
{
var videoInput: AVCaptureInput? = nil
var audioInput: AVCaptureInput? = nil
// Attempt to configure the video device
videoInput = try AVCaptureDeviceInput.input(for: videoDeviceID)
// Attempt to configure the video device
audioInput = try AVCaptureDeviceInput.input(for: audioDeviceID)
// Ensure we have at least one input
if videoInput == nil && audioInput == nil {
throw CaptureDeviceError.noDevicesAvailable
}
try self.init(videoInput: videoInput,
audioInput: audioInput,
controlDelegate: controlDelegate,
cameraReader: cameraReader)
}
convenience init(_ position: AVCaptureDevice.Position,
controlDelegate: CameraControlDelegate,
cameraReader: AVReaderProtocol) throws
{
let videoDevice = try AVCaptureDevice.firstDevice(for: .video, in: position)
let audioDevice = try AVCaptureDevice.firstDevice(for: .audio, in: position)
try self.init(videoDeviceID: videoDevice.uniqueID,
audioDeviceID: audioDevice.uniqueID,
controlDelegate: controlDelegate,
cameraReader: cameraReader)
}
public func start() {
self.start(onComplete: nil)
}
public func start(onComplete: ((AVCaptureSession) -> Void)? = nil) {
self.session.startRunning()
onComplete?(self.session)
}
public func stop() {
self.session.stopRunning()
}
public func changeToCamera(position: AVCaptureDevice.Position) -> Bool {
do {
for input in self.session.inputs {
for port in input.ports {
if port.mediaType == .video {
let videoDevice = try AVCaptureDevice.firstDevice(for: .video, in: position)
let newVideoInput = try AVCaptureDeviceInput(device: videoDevice)
self.session.beginConfiguration()
self.session.removeInput(input)
self.session.addInput(newVideoInput)
self.session.commitConfiguration()
return true
}
}
}
return false
} catch {
return false
}
}
private func setupObservers() {
self.sessionObserver = self.session.observe(\.isRunning) { session, _ in
if session.isRunning {
self.controlDelegate.cameraStarted()
} else {
self.controlDelegate.cameraStopped()
}
}
}
deinit { self.sessionObserver?.invalidate() }
}
| mit | 7cac79ca06d5e6b6723303c3625d2575 | 34.222222 | 136 | 0.586225 | 5.816514 | false | false | false | false |
onmyway133/Github.swift | Sources/Classes/Entity/Entity.swift | 1 | 3442 | //
// Entity.swift
// Pods
//
// Created by Khoa Pham on 25/03/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
import Tailor
import Sugar
// Represents any GitHub object which is capable of owning repositories.
public class Entity: Object {
// The unique name for this entity, used in GitHub URLs.
public private(set) var login: String = ""
// The full name of this entity.
//
// Returns `login` if no name is explicitly set.
public private(set) var name: String = ""
// The short biography associated with this account.
public private(set) var bio: String = ""
// The OCTRepository objects associated with this entity.
//
// OCTClient endpoints do not actually set this property. It is provided as
// a convenience for persistence and model merging.
public var repositories: [Repository] = []
// The email address for this account.
public private(set) var email: String = ""
// The URL for any avatar image.
public private(set) var avatarURL: NSURL?
// The web URL for this account.
public private(set) var HTMLURL: NSURL?
// A reference to a blog associated with this account.
public private(set) var blog: String = ""
// The name of a company associated with this account.
public private(set) var company: String = ""
// The location associated with this account.
public private(set) var location: String = ""
// The total number of collaborators that this account has on their private repositories.
public private(set) var collaborators: Int = 0
// The number of public repositories owned by this account.
public private(set) var publicRepoCount: Int = 0
// The number of private repositories owned by this account.
public private(set) var privateRepoCount: Int = 0
// The number of public gists owned by this account.
public private(set) var publicGistCount: Int = 0
// The number of private gists owned by this account.
public private(set) var privateGistCount: Int = 0
// The number of followers for this account.
public private(set) var followers: Int = 0
// The number of following for this account.
public private(set) var following: Int = 0
// The number of kilobytes occupied by this account's repositories on disk.
public private(set) var diskUsage: Int = 0
// The plan that this account is on.
public private(set) var plan: Plan?
public required init(_ map: JSONDictionary) {
super.init(map)
login <- map.property("login")
name <- map.property("name")
bio <- map.property("bio")
repositories <- map.relations("repositories")
email <- map.property("email")
avatarURL <- map.transform("avatar_url", transformer: NSURL.init(string: ))
HTMLURL <- map.transform("html_url", transformer: NSURL.init(string: ))
blog <- map.property("blog")
company <- map.property("company")
location <- map.property("location")
collaborators <- map.property("collaborators")
publicRepoCount <- map.property("public_repos")
privateRepoCount <- map.property("owned_private_repos")
publicGistCount <- map.property("public_gists")
privateGistCount <- map.property("private_gists")
followers <- map.property("followers")
following <- map.property("following")
diskUsage <- map.property("disk_usage")
plan <- map.relation("plan")
if name.isEmpty {
name = login
}
}
}
| mit | d48bcde47acd157db7b9dcaeeb8c997d | 31.771429 | 91 | 0.688463 | 4.21175 | false | false | false | false |
JGiola/swift | test/attr/attr_iboutlet.swift | 1 | 6563 | // RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
import Foundation
// expected-error@+1 {{@IBOutlet property cannot have non-object type 'Int'}}
@IBOutlet // expected-error {{only class instance properties can be declared @IBOutlet}} {{1-11=}}
var iboutlet_global: Int?
@IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}}
class IBOutletClassTy {}
@IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}}
struct IBStructTy {}
@IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}}
func IBFunction() -> () {}
@objc
class IBOutletWrapperTy {
@IBOutlet
var value : IBOutletWrapperTy! = IBOutletWrapperTy() // no-warning
@IBOutlet
class var staticValue: IBOutletWrapperTy? = 52 // expected-error {{cannot convert value of type 'Int' to specified type 'IBOutletWrapperTy?'}}
// expected-error@-2 {{only class instance properties can be declared @IBOutlet}} {{3-12=}}
// expected-error@-2 {{class stored properties not supported}}
@IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{3-13=}}
func click() -> () {}
@IBOutlet // expected-error {{@IBOutlet attribute requires property to be mutable}} {{3-13=}}
let immutable: IBOutletWrapperTy? = nil
@IBOutlet // expected-error {{@IBOutlet attribute requires property to be mutable}} {{3-13=}}
var computedImmutable: IBOutletWrapperTy? {
return nil
}
}
struct S { }
enum E { }
protocol P1 { }
protocol P2 { }
protocol CP1 : class { }
protocol CP2 : class { }
@objc protocol OP1 { }
@objc protocol OP2 { }
class NonObjC {}
// Ensure that only ObjC types work
@objc class X {
// Class type
@IBOutlet var outlet2: X?
@IBOutlet var outlet3: X!
@IBOutlet var outlet2a: NonObjC? // expected-error{{@IBOutlet property cannot have non-'@objc' class type 'NonObjC'}} {{3-13=}}
@IBOutlet var outlet3a: NonObjC! // expected-error{{@IBOutlet property cannot have non-'@objc' class type 'NonObjC'}} {{3-13=}}
// AnyObject
@IBOutlet var outlet5: AnyObject?
@IBOutlet var outlet6: AnyObject!
// Any
@IBOutlet var outlet5a: Any?
@IBOutlet var outlet6a: Any!
// Protocol types
@IBOutlet var outlet10: P1? // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var outlet11: CP1? // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var outlet12: OP1?
@IBOutlet var outlet13: P1! // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var outlet14: CP1! // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var outlet15: OP1!
// Class metatype
@IBOutlet var outlet16: X.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet17: X.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
// AnyClass
@IBOutlet var outlet19: AnyClass? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet20: AnyClass! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
// Protocol metatype types
@IBOutlet var outlet24: P1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet25: CP1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet26: OP1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet27: P1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet28: CP1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet29: OP1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
// String
@IBOutlet var outlet33: String?
@IBOutlet var outlet34: String!
// Other bad cases
@IBOutlet var outlet35: S? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet36: E? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet37: (X, X)? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet38: Int? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var collection1b: [AnyObject]?
@IBOutlet var collection1c: [AnyObject]!
@IBOutlet var collection2b: [X]?
@IBOutlet var collection2c: [X]!
@IBOutlet var collection3b: [OP1]?
@IBOutlet var collection3c: [OP1]!
@IBOutlet var collection4b: ([CP1])? // expected-error{{@IBOutlet property cannot be an array of non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var collection4c: ([CP1])! // expected-error{{@IBOutlet property cannot be an array of non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var collection5b: ([String])?
@IBOutlet var collection5c: ([String])!
@IBOutlet var collection6b: ([NonObjC])? // expected-error{{@IBOutlet property cannot be an array of non-'@objc' class type}} {{3-13=}}
@IBOutlet var collection6c: ([NonObjC])! // expected-error{{@IBOutlet property cannot be an array of non-'@objc' class type}} {{3-13=}}
init() { }
}
// Check that the type is optional
@objc class OX {
// expected-error@+3 {{@IBOutlet property has non-optional type 'OX'}}
// expected-note @+2 {{add '?' to form the optional type 'OX?'}}
// expected-note @+1 {{add '!' to form an implicitly unwrapped optional}}
@IBOutlet var ox: OX
init() { }
}
// Check reference storage types
@objc class RSX {
@IBOutlet weak var rsx1: RSX?
@IBOutlet unowned var rsx2: RSX?
@IBOutlet unowned(unsafe) var rsx3: RSX?
init() { }
}
@objc class Infer {
@IBOutlet var outlet1: Infer!
@IBOutlet weak var outlet2: Infer!
func testOptionalNess() {
_ = outlet1!
_ = outlet2!
}
func testUnchecked() {
_ = outlet1
_ = outlet2
}
// This outlet is strong and optional.
@IBOutlet var outlet4: AnyObject?
func testStrong() {
if outlet4 != nil {}
}
}
// https://bugs.swift.org/browse/SR-9889
@objc class NonOptionalWeak {
// expected-error@+3 {{@IBOutlet property has non-optional type 'OX'}}
// expected-note @+2 {{add '?' to form the optional type 'OX?'}}
// expected-note @+1 {{add '!' to form an implicitly unwrapped optional}}
@IBOutlet weak var something: OX
init() { }
}
| apache-2.0 | 396a0642234c3b71d03b34612f5b35b4 | 37.156977 | 145 | 0.684291 | 3.720522 | false | false | false | false |
JGiola/swift | test/SILOptimizer/cast_folding_parameterized_protocol.swift | 1 | 4136 | // RUN: %target-swift-frontend %s -emit-sil -disable-availability-checking -O -o - | %FileCheck %s
public protocol P<T> {
associatedtype T
}
public protocol Q: P where T == Int {}
public struct X: Q {
public typealias T = Int
}
public struct Y<T>: P {}
extension Y: Q where T == Int {}
@_optimize(none)
func use<T>(_ t: T) {}
// CHECK-LABEL: sil @$s35cast_folding_parameterized_protocol23concrete_to_existentialyyAA1XV_AA1YVyxGAFySiGtlF : $@convention(thin) <T> (X, Y<T>, Y<Int>) -> ()
public func concrete_to_existential<T>(_ x: X, _ yt: Y<T>, _ yi: Y<Int>) {
// CHECK:{{%.*}} = init_existential_addr %6 : $*P, $X
use(x as! any P)
// CHECK: unconditional_checked_cast_addr X in {{%.*}} : $*X to P<T> in {{%.*}} : $*P<T>
use(x as! any P<T>)
// CHECK: unconditional_checked_cast_addr X in {{%.*}} : $*X to P<Int> in {{%.*}} : $*P<Int>
use(x as! any P<Int>)
// CHECK: unconditional_checked_cast_addr X in {{%.*}} : $*X to P<String> in {{%.*}} : $*P<String>
use(x as! any P<String>)
// CHECK: {{%.*}} = init_existential_addr {{%.*}} : $*Q, $X
use(x as! any Q)
// CHECK: {{%.*}} = init_existential_addr {{%.*}} : $*P, $Y<T>
use(yt as! any P)
// CHECK: unconditional_checked_cast_addr Y<T> in {{%.*}} : $*Y<T> to P<T> in {{%.*}} : $*P<T>
use(yt as! any P<T>)
// CHECK: unconditional_checked_cast_addr Y<T> in {{%.*}} : $*Y<T> to P<Int> in {{%.*}} : $*P<Int>
use(yt as! any P<Int>)
// CHECK: unconditional_checked_cast_addr Y<T> in {{%.*}} : $*Y<T> to P<String> in {{%.*}} : $*P<String>
use(yt as! any P<String>)
// CHECK: unconditional_checked_cast_addr Y<T> in {{%.*}} : $*Y<T> to Q in {{%.*}} : $*Q
use(yt as! any Q)
// CHECK: {{%.*}} = init_existential_addr {{%.*}} : $*P, $Y<Int>
use(yi as! any P)
// CHECK: unconditional_checked_cast_addr Y<Int> in {{%.*}} : $*Y<Int> to P<T> in {{%.*}} : $*P<T>
use(yi as! any P<T>)
// CHECK: unconditional_checked_cast_addr Y<Int> in {{%.*}} : $*Y<Int> to P<Int> in {{%.*}} : $*P<Int>
use(yi as! any P<Int>)
// CHECK: unconditional_checked_cast_addr Y<Int> in {{%.*}} : $*Y<Int> to P<String> in {{%.*}} : $*P<String>
use(yi as! any P<String>)
// CHECK: {{%.*}} = init_existential_addr {{%.*}} : $*Q, $Y<Int>
use(yi as! any Q)
}
// CHECK-LABEL: sil @$s35cast_folding_parameterized_protocol23existential_to_concreteyyxm_AA1P_px1TRts_XPtlF : $@convention(thin) <T> (@thick T.Type, @in_guaranteed P<T>) -> ()
public func existential_to_concrete<T>(_: T.Type, _ p: any P<T>) {
// CHECK: unconditional_checked_cast_addr P<T> in {{%.*}} : $*P<T> to X in {{%.*}} : $*X
_ = p as! X
// CHECK: unconditional_checked_cast_addr P<T> in {{%.*}} : $*P<T> to Y<T> in {{%.*}} : $*Y<T>
_ = p as! Y<T>
// CHECK: unconditional_checked_cast_addr P<T> in {{%.*}} : $*P<T> to Y<Int> in {{%.*}} : $*Y<Int>
_ = p as! Y<Int>
// CHECK: unconditional_checked_cast_addr P<T> in {{%.*}} : $*P<T> to Y<String> in {{%.*}} : $*Y<String>
_ = p as! Y<String>
}
// CHECK-LABEL: sil @$s35cast_folding_parameterized_protocol015existential_to_E0yyAA1P_px1TRts_XP_AA1Q_ptlF : $@convention(thin) <T> (@in_guaranteed P<T>, @in_guaranteed Q) -> ()
public func existential_to_existential<T>(_ p: any P<T>, _ q: any Q) {
// CHECK: unconditional_checked_cast_addr P<T> in {{%.*}} : $*P<T> to Q in {{%.*}} : $*Q
_ = p as! any Q
// CHECK: unconditional_checked_cast_addr P<T> in {{%.*}} : $*P<T> to P in {{%.*}} : $*P
_ = p as! any P
// CHECK: unconditional_checked_cast_addr P<T> in {{%.*}} : $*P<T> to P<Int> in {{%.*}} : $*P<Int>
_ = p as! any P<Int>
// CHECK: unconditional_checked_cast_addr P<T> in {{%.*}} : $*P<T> to P<String> in {{%.*}} : $*P<String>
_ = p as! any P<String>
// CHECK: unconditional_checked_cast_addr Q in {{%.*}} : $*Q to P in {{%.*}} : $*P
_ = q as! any P
// CHECK: unconditional_checked_cast_addr Q in {{%.*}} : $*Q to P<T> in {{%.*}} : $*P<T>
_ = q as! any P<T>
// CHECK: unconditional_checked_cast_addr Q in {{%.*}} : $*Q to P<Int> in {{%.*}} : $*P<Int>
_ = q as! any P<Int>
// CHECK: unconditional_checked_cast_addr Q in {{%.*}} : $*Q to P<String> in {{%.*}} : $*P<String>
_ = q as! any P<String>
}
| apache-2.0 | 95f7554a2b75f5ba9bf116dc72d81574 | 48.831325 | 178 | 0.546663 | 2.80597 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ApplicationContext.swift | 1 | 36971 | import Foundation
import TGUIKit
import SwiftSignalKit
import Postbox
import TelegramCore
import Localization
import InAppSettings
import IOKit
private final class AuthModalController : ModalController {
override var background: NSColor {
return theme.colors.background
}
override var dynamicSize: Bool {
return true
}
override var closable: Bool {
return false
}
override func measure(size: NSSize) {
self.modal?.resize(with: NSMakeSize(size.width, size.height), animated: false)
}
}
final class UnauthorizedApplicationContext {
let account: UnauthorizedAccount
let rootController: MajorNavigationController
let window:Window
let modal: ModalController
let sharedContext: SharedAccountContext
private let updatesDisposable: DisposableSet = DisposableSet()
var rootView: NSView {
return rootController.view
}
init(window:Window, sharedContext: SharedAccountContext, account: UnauthorizedAccount, otherAccountPhoneNumbers: ((String, AccountRecordId, Bool)?, [(String, AccountRecordId, Bool)])) {
window.maxSize = NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude)
window.minSize = NSMakeSize(380, 550)
updatesDisposable.add(managedAppConfigurationUpdates(accountManager: sharedContext.accountManager, network: account.network).start())
if window.frame.height < window.minSize.height || window.frame.width < window.minSize.width {
window.setFrame(NSMakeRect(window.frame.minX, window.frame.minY, window.minSize.width, window.minSize.height), display: true)
window.center()
}
self.account = account
self.window = window
self.sharedContext = sharedContext
self.rootController = MajorNavigationController(AuthController.self, AuthController(account, sharedContext: sharedContext, otherAccountPhoneNumbers: otherAccountPhoneNumbers), window)
rootController._frameRect = NSMakeRect(0, 0, window.frame.width, window.frame.height)
self.modal = AuthModalController(rootController)
rootController.alwaysAnimate = true
account.shouldBeServiceTaskMaster.set(.single(.now))
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(receiveWakeNote(_:)), name: NSWorkspace.screensDidWakeNotification, object: nil)
}
deinit {
account.shouldBeServiceTaskMaster.set(.single(.never))
updatesDisposable.dispose()
NSWorkspace.shared.notificationCenter.removeObserver(self)
}
@objc func receiveWakeNote(_ notificaiton:Notification) {
account.shouldBeServiceTaskMaster.set(.single(.never) |> then(.single(.now)))
}
}
enum ApplicationContextLaunchAction {
case navigate(ViewController)
case preferences
}
let leftSidebarWidth: CGFloat = 72
private final class ApplicationContainerView: View {
fileprivate let splitView: SplitView
fileprivate private(set) var leftSideView: NSView?
required init(frame frameRect: NSRect) {
splitView = SplitView(frame: NSMakeRect(0, 0, frameRect.width, frameRect.height))
super.init(frame: frameRect)
addSubview(splitView)
autoresizingMask = [.width, .height]
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateLeftSideView(_ view: NSView?, animated: Bool) {
if let view = view {
addSubview(view)
} else {
self.leftSideView?.removeFromSuperview()
}
self.leftSideView = view
needsLayout = true
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
splitView.backgroundColor = theme.colors.background
}
override func layout() {
super.layout()
if let leftSideView = leftSideView {
leftSideView.frame = NSMakeRect(0, 0, leftSidebarWidth, frame.height)
splitView.frame = NSMakeRect(leftSideView.frame.maxX, 0, frame.width - leftSideView.frame.maxX, frame.height)
} else {
splitView.frame = bounds
}
}
}
final class AuthorizedApplicationContext: NSObject, SplitViewDelegate {
var rootView: View {
return view
}
let context: AccountContext
private let window:Window
private let view:ApplicationContainerView
private let leftController:MainViewController
private let rightController:MajorNavigationController
private let emptyController:EmptyChatViewController
private var entertainment: EntertainmentViewController?
private var leftSidebarController: LeftSidebarController?
private let loggedOutDisposable = MetaDisposable()
private let ringingStatesDisposable = MetaDisposable()
private let settingsDisposable = MetaDisposable()
private let suggestedLocalizationDisposable = MetaDisposable()
private let alertsDisposable = MetaDisposable()
private let audioDisposable = MetaDisposable()
private let termDisposable = MetaDisposable()
private let someActionsDisposable = DisposableSet()
private let clearReadNotifiesDisposable = MetaDisposable()
private let appUpdateDisposable = MetaDisposable()
private let updatesDisposable = MetaDisposable()
private let updateFoldersDisposable = MetaDisposable()
private let _ready:Promise<Bool> = Promise()
var ready: Signal<Bool, NoError> {
return _ready.get() |> filter { $0 } |> take (1)
}
func applyNewTheme() {
rightController.backgroundColor = theme.colors.background
rightController.backgroundMode = theme.controllerBackgroundMode
view.updateLocalizationAndTheme(theme: theme)
}
private var launchAction: ApplicationContextLaunchAction?
init(window: Window, context: AccountContext, launchSettings: LaunchSettings, callSession: PCallSession?, groupCallContext: GroupCallContext?, folders: ChatListFolders?) {
self.context = context
emptyController = EmptyChatViewController(context)
self.window = window
if !window.initFromSaver {
window.setFrame(NSMakeRect(0, 0, 800, 650), display: true)
window.center()
}
window.maxSize = NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude)
window.minSize = NSMakeSize(380, 550)
context.account.importableContacts.set(.single([:]))
self.view = ApplicationContainerView(frame: window.contentView!.bounds)
self.view.splitView.setProportion(proportion: SplitProportion(min:380, max:300+350), state: .single);
self.view.splitView.setProportion(proportion: SplitProportion(min:300+350, max:300+350+600), state: .dual)
rightController = ExMajorNavigationController(context, ChatController.self, emptyController);
rightController.set(header: NavigationHeader(44, initializer: { header, contextObject, view -> (NavigationHeaderView, CGFloat) in
let newView = view ?? InlineAudioPlayerView(header)
newView.update(with: contextObject)
return (newView, 44)
}))
rightController.set(callHeader: CallNavigationHeader(35, initializer: { header, contextObject, view -> (NavigationHeaderView, CGFloat) in
let newView: NavigationHeaderView
if contextObject is GroupCallContext {
if let view = view, view.className == GroupCallNavigationHeaderView.className() {
newView = view
} else {
newView = GroupCallNavigationHeaderView(header)
}
} else if contextObject is PCallSession {
if let view = view, view.className == CallNavigationHeaderView.className() {
newView = view
} else {
newView = CallNavigationHeaderView(header)
}
} else {
fatalError("not supported")
}
newView.update(with: contextObject)
return (newView, 35 + 18)
}))
window.rootViewController = rightController
leftController = MainViewController(context);
super.init()
updatesDisposable.set(managedAppConfigurationUpdates(accountManager: context.sharedContext.accountManager, network: context.account.network).start())
context.bindings = AccountContextBindings(rootNavigation: { [weak self] () -> MajorNavigationController in
guard let `self` = self else {
return MajorNavigationController(ViewController.self, ViewController(), window)
}
return self.rightController
}, mainController: { [weak self] () -> MainViewController in
guard let `self` = self else {
fatalError("Cannot use bindings. Application context is not exists")
}
return self.leftController
}, showControllerToaster: { [weak self] toaster, animated in
guard let `self` = self else {
fatalError("Cannot use bindings. Application context is not exists")
}
self.rightController.controller.show(toaster: toaster, animated: animated)
}, globalSearch: { [weak self] search in
guard let `self` = self else {
fatalError("Cannot use bindings. Application context is not exists")
}
self.leftController.tabController.select(index: self.leftController.chatIndex)
self.leftController.globalSearch(search)
}, entertainment: { [weak self] () -> EntertainmentViewController in
guard let `self` = self else {
return EntertainmentViewController.init(size: NSZeroSize, context: context)
}
if self.entertainment == nil {
self.entertainment = EntertainmentViewController(size: NSMakeSize(350, 350), context: self.context)
}
return self.entertainment!
}, switchSplitLayout: { [weak self] state in
guard let `self` = self else {
fatalError("Cannot use bindings. Application context is not exists")
}
self.view.splitView.state = state
}, needFullsize: { [weak self] in
self?.view.splitView.needFullsize()
}, displayUpgradeProgress: { progress in
})
termDisposable.set((context.account.stateManager.termsOfServiceUpdate |> deliverOnMainQueue).start(next: { terms in
if let terms = terms {
showModal(with: TermsModalController(context, terms: terms), for: context.window)
} else {
closeModal(TermsModalController.self)
}
}))
// var forceNotice:Bool = false
if FastSettings.isMinimisize {
self.view.splitView.mustMinimisize = true
// forceNotice = true
} else {
self.view.splitView.mustMinimisize = false
}
self.view.splitView.delegate = self;
self.view.splitView.update(false)
let accountId = context.account.id
self.loggedOutDisposable.set(context.account.loggedOut.start(next: { value in
if value {
let _ = logoutFromAccount(id: accountId, accountManager: context.sharedContext.accountManager, alreadyLoggedOutRemotely: false).start()
}
}))
alertsDisposable.set((context.account.stateManager.displayAlerts |> deliverOnMainQueue).start(next: { alerts in
for text in alerts {
let alert:NSAlert = NSAlert()
alert.window.appearance = theme.appearance
alert.alertStyle = .informational
alert.messageText = appName
alert.informativeText = text.text
if text.isDropAuth {
alert.addButton(withTitle: strings().editAccountLogout)
alert.addButton(withTitle: strings().modalCancel)
}
alert.beginSheetModal(for: window, completionHandler: { result in
if result.rawValue == 1000 && text.isDropAuth {
let _ = logoutFromAccount(id: context.account.id, accountManager: context.sharedContext.accountManager, alreadyLoggedOutRemotely: false).start()
}
})
}
}))
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.rightController.push(ChatController(context: context, chatLocation: .peer(context.peerId)))
return .invoked
}, with: self, for: .Zero, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(0, false)
return .invoked
}, with: self, for: .One, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(1, false)
return .invoked
}, with: self, for: .Two, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(2, false)
return .invoked
}, with: self, for: .Three, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(3, false)
return .invoked
}, with: self, for: .Four, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(4, false)
return .invoked
}, with: self, for: .Five, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(5, false)
return .invoked
}, with: self, for: .Six, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(6, false)
return .invoked
}, with: self, for: .Seven, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(7, false)
return .invoked
}, with: self, for: .Eight, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(8, false)
return .invoked
}, with: self, for: .Nine, priority: .low, modifierFlags: [.command])
window.set(handler: { _ -> KeyHandlerResult in
appDelegate?.sharedApplicationContextValue?.notificationManager.updatePasslock(context.sharedContext.accountManager.transaction { transaction -> Bool in
switch transaction.getAccessChallengeData() {
case .none:
return false
default:
return true
}
})
return .invoked
}, with: self, for: .L, priority: .supreme, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(0, true)
return .invoked
}, with: self, for: .One, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(1, true)
return .invoked
}, with: self, for: .Two, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(2, true)
return .invoked
}, with: self, for: .Three, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(3, true)
return .invoked
}, with: self, for: .Four, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(4, true)
return .invoked
}, with: self, for: .Five, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(5, true)
return .invoked
}, with: self, for: .Six, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(6, true)
return .invoked
}, with: self, for: .Seven, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(7, true)
return .invoked
}, with: self, for: .Eight, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(8, true)
return .invoked
}, with: self, for: .Nine, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(9, true)
return .invoked
}, with: self, for: .Minus, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(1, true)
return .invoked
}, with: self, for: .One, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(2, true)
return .invoked
}, with: self, for: .Two, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(3, true)
return .invoked
}, with: self, for: .Three, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(4, true)
return .invoked
}, with: self, for: .Four, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(5, true)
return .invoked
}, with: self, for: .Five, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(6, true)
return .invoked
}, with: self, for: .Six, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(7, true)
return .invoked
}, with: self, for: .Seven, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(8, true)
return .invoked
}, with: self, for: .Eight, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(9, true)
return .invoked
}, with: self, for: .Nine, priority: .low, modifierFlags: [.control])
#if DEBUG
window.set(handler: { [weak self] _ -> KeyHandlerResult in
// context.bindings.rootNavigation().push(ForumTopicInfoController(context: context, purpose: .create))
// let rect = self!.window.contentView!.frame.focus(NSMakeSize(160, 160))
// self!.window.contentView!.addSubview(CustomReactionEffectView(frame: rect, context: context, fileId: 5415816441561619011))
// let layer = InlineStickerItemLayer(account: context.account, inlinePacksContext: context.inlinePacksContext, emoji: .init(fileId: 5415816441561619011, file: nil, emoji: ""), size: NSMakeSize(30, 30))
// testParabolla(layer, window: context.window)
// showModal(with: PremiumLimitController.init(context: context, type: .pin), for: context.window)
// showModal(with: PremiumBoardingController(context: context), for: context.window)
// showInactiveChannels(context: context, source: .create)
// showModal(with: AvatarConstructorController(context, target: .avatar), for: context.window)
return .invoked
}, with: self, for: .T, priority: .supreme, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
showModal(with: PremiumLimitController(context: context, type: .pin), for: context.window)
return .invoked
}, with: self, for: .Y, priority: .supreme, modifierFlags: [.command])
#endif
// window.set(handler: { [weak self] _ -> KeyHandlerResult in
// self?.leftController.focusSearch(animated: true)
// return .invoked
// }, with: self, for: .F, priority: .supreme, modifierFlags: [.command, .shift])
window.set(handler: { _ -> KeyHandlerResult in
context.bindings.rootNavigation().push(ShortcutListController(context: context))
return .invoked
}, with: self, for: .Slash, priority: .low, modifierFlags: [.command])
appUpdateDisposable.set((context.account.stateManager.appUpdateInfo |> deliverOnMainQueue).start(next: { info in
}))
suggestedLocalizationDisposable.set(( context.account.postbox.preferencesView(keys: [PreferencesKeys.suggestedLocalization]) |> mapToSignal { preferences -> Signal<SuggestedLocalizationInfo, NoError> in
let preferences = preferences.values[PreferencesKeys.suggestedLocalization]?.get(SuggestedLocalizationEntry.self)
if preferences == nil || !preferences!.isSeen, preferences?.languageCode != appCurrentLanguage.languageCode, preferences?.languageCode != "en" {
let current = Locale.preferredLanguages[0]
let split = current.split(separator: "-")
let lan: String = !split.isEmpty ? String(split[0]) : "en"
if lan != "en" {
return context.engine.localization.suggestedLocalizationInfo(languageCode: lan, extractKeys: ["Suggest.Localization.Header", "Suggest.Localization.Other"]) |> take(1)
}
}
return .complete()
} |> deliverOnMainQueue).start(next: { suggestionInfo in
if suggestionInfo.availableLocalizations.count >= 2 {
showModal(with: SuggestionLocalizationViewController(context, suggestionInfo: suggestionInfo), for: window)
}
}))
someActionsDisposable.add(context.engine.peers.managedUpdatedRecentPeers().start())
clearReadNotifiesDisposable.set(context.account.stateManager.appliedIncomingReadMessages.start(next: { msgIds in
UNUserNotifications.current?.clearNotifies(by: msgIds)
}))
someActionsDisposable.add(applyUpdateTextIfNeeded(context.account.postbox).start())
if let folders = folders {
self.updateLeftSidebar(with: folders, layout: context.layout, animated: false)
}
self.view.splitView.layout()
if let navigation = launchSettings.navigation {
switch navigation {
case .settings:
self.launchAction = .preferences
_ready.set(leftController.settings.ready.get())
leftController.tabController.select(index: leftController.settingsIndex)
case let .profile(peerId, necessary):
_ready.set(leftController.chatList.ready.get())
self.leftController.tabController.select(index: self.leftController.chatIndex)
if (necessary || context.layout != .single) {
let controller = PeerInfoController(context: context, peerId: peerId)
controller.navigationController = self.rightController
controller.loadViewIfNeeded(self.rightController.bounds)
self.launchAction = .navigate(controller)
self._ready.set(combineLatest(self.leftController.chatList.ready.get(), controller.ready.get()) |> map { $0 && $1 })
self.leftController.tabController.select(index: self.leftController.chatIndex)
} else {
_ready.set(leftController.chatList.ready.get())
self.leftController.tabController.select(index: self.leftController.chatIndex)
}
case let .chat(peerId, necessary):
_ready.set(leftController.chatList.ready.get())
self.leftController.tabController.select(index: self.leftController.chatIndex)
if (necessary || context.layout != .single) {
let controller = ChatController(context: context, chatLocation: .peer(peerId))
controller.navigationController = self.rightController
controller.loadViewIfNeeded(self.rightController.bounds)
self.launchAction = .navigate(controller)
self._ready.set(combineLatest(self.leftController.chatList.ready.get(), controller.ready.get()) |> map { $0 && $1 })
self.leftController.tabController.select(index: self.leftController.chatIndex)
} else {
// self._ready.set(.single(true))
_ready.set(leftController.chatList.ready.get())
self.leftController.tabController.select(index: self.leftController.chatIndex)
}
case let .thread(threadId, fromId, threadData, _):
self.leftController.tabController.select(index: self.leftController.chatIndex)
self._ready.set(self.leftController.chatList.ready.get())
if let fromId = fromId {
context.navigateToThread(threadId, fromId: fromId)
} else if let _ = threadData {
_ = ForumUI.openTopic(makeMessageThreadId(threadId), peerId: threadId.peerId, context: context).start()
}
}
} else {
// self._ready.set(.single(true))
_ready.set(leftController.chatList.ready.get())
leftController.tabController.select(index: leftController.chatIndex)
// _ready.set(leftController.ready.get())
}
if let session = callSession {
rightController.callHeader?.show(true, contextObject: session)
}
if let groupCallContext = groupCallContext {
rightController.callHeader?.show(true, contextObject: groupCallContext)
}
self.updateFoldersDisposable.set(combineLatest(queue: .mainQueue(), chatListFilterPreferences(engine: context.engine), context.layoutValue).start(next: { [weak self] value, layout in
self?.updateLeftSidebar(with: value, layout: layout, animated: true)
}))
if let controller = context.audioPlayer, let _ = self.rightController.header {
self.rightController.header?.show(false, contextObject: InlineAudioPlayerView.ContextObject(controller: controller, context: context, tableView: nil, supportTableView: nil))
}
// _ready.set(.single(true))
}
private var folders: ChatListFolders?
private var previousLayout: SplitViewState?
private let foldersReadyDisposable = MetaDisposable()
private func updateLeftSidebar(with folders: ChatListFolders, layout: SplitViewState, animated: Bool) -> Void {
let currentSidebar = !folders.isEmpty && (folders.sidebar || layout == .minimisize)
let previousSidebar = self.folders == nil ? nil : !self.folders!.isEmpty && (self.folders!.sidebar || self.previousLayout == SplitViewState.minimisize)
let readySignal: Signal<Bool, NoError>
if currentSidebar != previousSidebar {
if !currentSidebar {
leftSidebarController?.removeFromSuperview()
leftSidebarController = nil
readySignal = .single(true)
} else {
let controller = LeftSidebarController(context, filterData: leftController.chatList.filterSignal, updateFilter: leftController.chatList.updateFilter)
controller._frameRect = NSMakeRect(0, 0, leftSidebarWidth, window.frame.height)
controller.loadViewIfNeeded()
self.leftSidebarController = controller
readySignal = controller.ready.get() |> take(1)
}
let enlarge: CGFloat
if currentSidebar && previousSidebar != nil {
enlarge = leftSidebarWidth
} else {
if previousSidebar == true {
enlarge = -leftSidebarWidth
} else {
enlarge = 0
}
}
foldersReadyDisposable.set(readySignal.start(next: { [weak self] _ in
guard let `self` = self else {
return
}
self.view.updateLeftSideView(self.leftSidebarController?.genericView, animated: animated)
if !self.window.isFullScreen {
self.window.setFrame(NSMakeRect(max(0, self.window.frame.minX - enlarge), self.window.frame.minY, self.window.frame.width + enlarge, self.window.frame.height), display: true, animate: false)
}
self.updateMinMaxWindowSize(animated: animated)
}))
}
self.folders = folders
self.previousLayout = layout
}
private func updateMinMaxWindowSize(animated: Bool) {
var width: CGFloat = 380
if leftSidebarController != nil {
width += leftSidebarWidth
}
if context.layout == .minimisize {
width += 70
}
window.minSize = NSMakeSize(width, 550)
if window.frame.width < window.minSize.width {
window.setFrame(NSMakeRect(max(0, window.frame.minX - (window.minSize.width - window.frame.width)), window.frame.minY, window.minSize.width, window.frame.height), display: true, animate: false)
}
}
func runLaunchAction() {
if let launchAction = launchAction {
switch launchAction {
case let .navigate(controller):
leftController.tabController.select(index: leftController.chatIndex)
context.bindings.rootNavigation().push(controller, context.layout == .single)
case .preferences:
leftController.tabController.select(index: leftController.settingsIndex)
}
self.launchAction = nil
} else {
leftController.tabController.select(index: leftController.chatIndex)
}
Queue.mainQueue().justDispatch { [weak self] in
self?.leftController.prepareControllers()
}
}
private func openChat(_ index: Int, _ force: Bool = false) {
leftController.openChat(index, force: force)
}
private func switchAccount(_ index: Int, _ force: Bool = false) {
let accounts = context.sharedContext.activeAccounts |> take(1) |> deliverOnMainQueue
let context = self.context
_ = accounts.start(next: { accounts in
let account = accounts.accounts[min(index - 1, accounts.accounts.count - 1)]
context.sharedContext.switchToAccount(id: account.0, action: nil)
})
}
func splitResizeCursor(at point: NSPoint) -> NSCursor? {
if FastSettings.isMinimisize {
return NSCursor.resizeRight
} else {
if window.frame.width - point.x <= 380 {
return NSCursor.resizeLeft
}
return NSCursor.resizeLeftRight
}
}
func splitViewShouldResize(at point: NSPoint) {
if !FastSettings.isMinimisize {
let max_w = window.frame.width - 380
let result = round(min(max(point.x, 300), max_w))
FastSettings.updateLeftColumnWidth(result)
self.view.splitView.updateStartSize(size: NSMakeSize(result, result), controller: leftController)
}
}
func splitViewDidNeedSwapToLayout(state: SplitViewState) {
let previousState = self.view.splitView.state
self.view.splitView.removeAllControllers()
let w:CGFloat = FastSettings.leftColumnWidth
FastSettings.isMinimisize = false
self.view.splitView.mustMinimisize = false
switch state {
case .single:
rightController.empty = leftController
if rightController.modalAction != nil {
if rightController.controller is ChatController {
rightController.push(ForwardChatListController(context), false)
}
}
if rightController.stackCount == 1, previousState != .none {
leftController.viewWillAppear(false)
}
self.view.splitView.addController(controller: rightController, proportion: SplitProportion(min:380, max:CGFloat.greatestFiniteMagnitude))
if rightController.stackCount == 1, previousState != .none {
leftController.viewDidAppear(false)
}
case .dual:
rightController.empty = emptyController
if rightController.controller is ForwardChatListController {
rightController.back(animated:false)
}
self.view.splitView.addController(controller: leftController, proportion: SplitProportion(min:w, max:w))
self.view.splitView.addController(controller: rightController, proportion: SplitProportion(min:380, max:CGFloat.greatestFiniteMagnitude))
case .minimisize:
self.view.splitView.mustMinimisize = true
FastSettings.isMinimisize = true
self.view.splitView.addController(controller: leftController, proportion: SplitProportion(min:70, max:70))
self.view.splitView.addController(controller: rightController, proportion: SplitProportion(min:380, max:CGFloat.greatestFiniteMagnitude))
default:
break;
}
updateMinMaxWindowSize(animated: false)
DispatchQueue.main.async {
self.view.splitView.needsLayout = true
}
context.layout = state
}
func splitViewDidNeedMinimisize(controller: ViewController) {
}
func splitViewDidNeedFullsize(controller: ViewController) {
}
func splitViewIsCanMinimisize() -> Bool {
return self.leftController.isCanMinimisize();
}
func splitViewDrawBorder() -> Bool {
return false
}
deinit {
self.loggedOutDisposable.dispose()
window.removeAllHandlers(for: self)
settingsDisposable.dispose()
ringingStatesDisposable.dispose()
suggestedLocalizationDisposable.dispose()
audioDisposable.dispose()
alertsDisposable.dispose()
termDisposable.dispose()
viewer?.close()
someActionsDisposable.dispose()
clearReadNotifiesDisposable.dispose()
appUpdateDisposable.dispose()
updatesDisposable.dispose()
updateFoldersDisposable.dispose()
foldersReadyDisposable.dispose()
context.cleanup()
NotificationCenter.default.removeObserver(self)
}
}
| gpl-2.0 | 6d16f3985c4cdecd2748fdbd90c5bc8b | 40.634009 | 213 | 0.606151 | 5.016418 | false | false | false | false |
akane/Gaikan | GaikanTests/Style/StyleSpec.swift | 1 | 1734 | //
// This file is part of Gaikan
//
// Created by JC on 18/10/15.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code
//
import Foundation
import Quick
import Nimble
@testable import Gaikan
class StyleSpec: QuickSpec {
override func spec() {
var style: Style!
beforeEach {
style = Style() { (style: inout StyleRule) in
style.color = UIColor.blue
}
}
describe("state") {
context("when pseudo class does not exist yet") {
it("should be nil") {
expect(style[.highlighted]).to(beNil())
}
it("should add it") {
style = style.state(.highlighted) { (style: inout StyleRule) -> () in
}
expect(style[.highlighted]).toNot(beNil())
}
it("should not be merged with .Normal") {
style = style.state(.highlighted) { (style: inout StyleRule) -> () in
}
expect(style[.highlighted]?.color).to(beNil())
}
}
context("when pseudo class exist") {
beforeEach {
style = style.state(.highlighted) { (style: inout StyleRule) -> () in
style.color = .green
}
}
it("should replace it") {
style = style.state(.highlighted) { (style: inout StyleRule) -> () in
}
expect(style[.highlighted]?.color).to(beNil())
}
}
}
}
}
| mit | 6a3d1d5df610860ec04ee3471fc70705 | 27.42623 | 89 | 0.464245 | 5.055394 | false | false | false | false |
legendecas/Rocket.Chat.iOS | Rocket.Chat.Shared/Extensions/StringExtensions.swift | 1 | 1616 | //
// StringExtensions.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/6/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import CommonCrypto
func localized(_ string: String) -> String {
return NSLocalizedString(string, bundle: Bundle.rocketChat, comment: "")
}
extension String {
static func random(_ length: Int = 20) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.characters.count))
randomString += "\(base[base.characters.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
func hexStringFromData(input: NSData) -> String {
var bytes = [UInt8](repeating: 0, count: input.length)
input.getBytes(&bytes, length: input.length)
var hexString = ""
for byte in bytes {
hexString += String(format:"%02x", UInt8(byte))
}
return hexString
}
func sha256() -> String {
if let stringData = self.data(using: String.Encoding.utf8) {
return hexStringFromData(input: digest(input: stringData as NSData))
}
return ""
}
private func digest(input: NSData) -> NSData {
let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
var hash = [UInt8](repeating: 0, count: digestLength)
CC_SHA256(input.bytes, UInt32(input.length), &hash)
return NSData(bytes: hash, length: digestLength)
}
}
| mit | 165a09e32a8a564f9ca2958d47cdf4bf | 27.333333 | 105 | 0.629721 | 4.238845 | false | false | false | false |
oskarpearson/rileylink_ios | MinimedKit/PumpEvents/JournalEntryInsulinMarkerPumpEvent.swift | 1 | 1071 | //
// JournalEntryInsulinMarkerPumpEvent.swift
// RileyLink
//
// Created by Pete Schwamb on 7/16/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct JournalEntryInsulinMarkerPumpEvent: TimestampedPumpEvent {
public let length: Int
public let rawData: Data
public let timestamp: DateComponents
public let amount: Double
public init?(availableData: Data, pumpModel: PumpModel) {
length = 8
guard length <= availableData.count else {
return nil
}
rawData = availableData.subdata(in: 0..<length)
timestamp = DateComponents(pumpEventData: availableData, offset: 2)
let lowBits = rawData[1] as UInt8
let highBits = rawData[4] as UInt8
amount = Double((Int(highBits & 0b1100000) << 3) + Int(lowBits)) / 10.0
}
public var dictionaryRepresentation: [String: Any] {
return [
"_type": "JournalEntryInsulinMarker",
"amount": amount,
]
}
}
| mit | ff3c1838591663fe545185fc5917e5ca | 26.435897 | 79 | 0.617757 | 4.514768 | false | false | false | false |
RajaveluC/SYNQueue | SYNQueueDemo/SYNQueueDemo/ViewController.swift | 1 | 5245 | //
// ViewController.swift
// SYNQueueDemo
//
import UIKit
import SYNQueue
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var collectionView: UICollectionView!
let reachability = Reachability.init()
var totalTasksSeen = 0
lazy var queue: SYNQueue = {
return SYNQueue(queueName: "myQueue",
maxConcurrency: 2,
maxRetries: 3,
logProvider: ConsoleLogger(),
serializationProvider: UserDefaultsSerializer(),
completionBlock: { [weak self] in self?.taskComplete($0, $1) })
}()
// MARK: - UIViewController Overrides
override func viewDidLoad() {
super.viewDidLoad()
queue.addTaskHandler("cellTask", taskHandler: taskHandler)
queue.loadSerializedTasks()
}
override func viewDidLayoutSubviews() {
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.itemSize = CGSize(width: collectionView.bounds.size.width, height: 50)
}
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
collectionView.performBatchUpdates(nil, completion: nil)
}
// MARK: - SYNQueueTask Handling
func taskHandler(_ task: SYNQueueTask) {
// NOTE: Tasks are not actually handled here like usual since task
// completion in this example is based on user interaction, unless
// we enable the setting for task autocompletion
log(.Info, "Running task \(task.taskID)")
// Do something with data and call task.completed() when done
// let data = task.data
// Here, for example, we just auto complete the task
let taskShouldAutocomplete = UserDefaults.standard.bool(forKey: kAutocompleteTaskSettingKey)
if taskShouldAutocomplete {
// Set task completion after 3 seconds
runOnMainThreadAfterDelay(3, { () -> () in
task.completed(nil)
})
}
runOnMainThread { self.collectionView.reloadData() }
}
func taskComplete(_ error: NSError?, _ task: SYNQueueTask) {
if let error = error {
log(.Error, "Task \(task.taskID) failed with error: \(error)")
} else {
log(.Info, "Task \(task.taskID) completed successfully")
}
if queue.operationCount == 0 {
totalTasksSeen = 0
}
updateProgress()
runOnMainThread { self.collectionView.reloadData() }
}
// MARK: - UICollectionView Delegates
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection
section: Int) -> Int {
return queue.operationCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt
indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: "TaskCell", for: indexPath) as! TaskCell
cell.backgroundColor = UIColor.red
if let task = queue.operations[indexPath.item] as? SYNQueueTask {
cell.task = task
cell.nameLabel.text = "task \(task.taskID)"
let taskShouldAutocomplete = UserDefaults.standard.bool(forKey: kAutocompleteTaskSettingKey)
if task.isExecuting && !taskShouldAutocomplete {
cell.backgroundColor = UIColor.blue
cell.failButton.isEnabled = true
cell.succeedButton.isEnabled = true
} else {
cell.backgroundColor = UIColor.gray
cell.succeedButton.isEnabled = false
cell.failButton.isEnabled = false
}
}
return cell
}
// MARK: - IBActions
@IBAction func addTapped(_ sender: UIButton) {
let task1 = SYNQueueTask(queue: queue, taskType: "cellTask")
if UserDefaults.standard.bool(forKey: kAddDependencySettingKey) {
let task2 = SYNQueueTask(queue: queue, taskType: "cellTask")
// Make the first task dependent on the second
task1.addDependency(task2)
queue.addOperation(task2)
}
queue.addOperation(task1)
totalTasksSeen = max(totalTasksSeen, queue.operationCount)
updateProgress()
collectionView.reloadData()
}
@IBAction func removeTapped(_ sender: UIButton) {
// Find the first task in the list
if let task = queue.operations.first as? SYNQueueTask {
log(.Info, "Removing task \(task.taskID)")
task.cancel()
collectionView.reloadData()
}
}
// MARK: - Helpers
func updateProgress() {
let tasks = queue.tasks
let progress = Double(totalTasksSeen - tasks.count) / Double(totalTasksSeen)
runOnMainThread { self.progressView.progress = Float(progress) }
}
}
| mit | 23cc1438d317c588ef5b23e038fe9203 | 33.506579 | 104 | 0.605529 | 5.330285 | false | false | false | false |
pushuhengyang/dyzb | DYZB/DYZB/Classes/Tools工具/DYButton.swift | 1 | 937 | //
// DYButton.swift
// DYZB
//
// Created by xuwenhao on 16/11/12.
// Copyright © 2016年 xuwenhao. All rights reserved.
//
import Foundation
import UIKit
extension UIButton {
class func creat(imageName : String, heightImageName: String = "", size :CGSize = CGSize.zero , target : AnyObject? = nil ,action : Selector? = nil) -> UIButton {
let btn = UIButton.init(type: UIButtonType.custom);
btn.setImage(UIImage.init(named: imageName), for: UIControlState.normal);
if (heightImageName != "") {
btn.setImage(UIImage.init(named: heightImageName), for: .highlighted
);
}
if (size != CGSize.zero) {
btn.frame = CGRect.init(origin: CGPoint.zero, size: size);
}
btn.addTarget(target, action: action!, for: .touchUpInside);
return btn;
}
}
| mit | adfb0dbe4fc88d77b35b28516d5bf027 | 20.227273 | 166 | 0.561028 | 4.26484 | false | false | false | false |
vimeo/VimeoNetworking | Sources/Shared/Models/VIMLive.swift | 1 | 5626 | //
// VIMLive.swift
// VimeoNetworking
//
// Created by Van Nguyen on 08/29/2017.
// Copyright (c) Vimeo (https://vimeo.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// The streaming status of a live video.
///
/// - unavailable: The RTMP link is visible but not yet able to receive the stream.
/// - pending: Vimeo is working on setting up the connection.
/// - ready: The RTMP's URL is ready to receive video content.
/// - streamingPreview: The stream is in a "preview" state. It will be accessible to the public when you transition to "streaming".
/// - streaming: The stream is open and receiving content.
/// - streamingError: The stream has failed due to an error relating to the broadcaster; They may have reached their monthly broadcast limit, for example.
/// - archiving: The stream has finished, and the video is in the process of being archived, but is not ready to play yet.
/// - archiveError: There was a problem archiving the stream.
/// - done: The stream has been ended intentionally by the end-user.
public enum LiveStreamingStatus: String {
case unavailable = "unavailable"
case pending = "pending"
case ready = "ready"
case streamingPreview = "streaming_preview"
case streaming = "streaming"
case streamingError = "streaming_error"
case archiving = "archiving"
case archiveError = "archive_error"
case done = "done"
}
/// An object that represents the `live` field in
/// a `clip` response.
public class VIMLive: VIMModelObject {
private struct Constants {
static let ChatKey = "chat"
}
/// The RTMP link is visible but not yet able to receive the stream.
@objc public static let LiveStreamStatusUnavailable = "unavailable"
/// Vimeo is working on setting up the connection.
@objc public static let LiveStreamStatusPending = "pending"
/// The RTMP's URL is ready to receive video content.
@objc public static let LiveStreamStatusReady = "ready"
/// The stream is in a "preview" state. It will be accessible to the public when you transition to "streaming".
@objc public static let LiveStreamStatusStreamingPreview = "streaming_preview"
/// The stream is open and receiving content.
@objc public static let LiveStreamStatusStreaming = "streaming"
/// The stream has failed due to an error relating to the broadcaster; They may have reached their monthly broadcast limit, for example.
@objc public static let LiveStreamStatusStreamingError = "streaming_error"
/// The stream has finished, and the video is in the process of being archived, but is not ready to play yet.
@objc public static let LiveStreamStatusArchiving = "archiving"
/// There was a problem archiving the stream.
@objc public static let LiveStreamStatusArchiveError = "archive_error"
/// The stream has been ended intentionally by the end-user.
@objc public static let LiveStreamStatusDone = "done"
/// An RTMP link used to host a live stream.
@objc dynamic public private(set) var link: String?
/// A token for streaming.
@objc dynamic public private(set) var key: String?
/// The timestamp that the stream is active.
@objc dynamic public private(set) var activeTime: NSDate?
/// The timestamp that the stream is over.
@objc dynamic public private(set) var endedTime: NSDate?
/// The timestamp that the live video is
/// archived.
@objc dynamic public private(set) var archivedTime: NSDate?
/// The timestamp that the live video is
/// scheduled to be online.
@objc dynamic public private(set) var scheduledStartTime: NSDate?
/**
The status of the live video in string.
- Note:
Technically, this property should not be used to
check the status of a live video. Use
`liveStreamingStatus` instead for easy checking.
*/
@objc dynamic public private(set) var status: String?
/// The status of the live video in `LiveStreamingStatus` enum.
public var liveStreamingStatus: LiveStreamingStatus? {
guard let status = self.status else {
return nil
}
return LiveStreamingStatus(rawValue: status)
}
/// The live event's chat.
@objc public private(set) var chat: VIMLiveChat?
public override func getClassForObjectKey(_ key: String!) -> AnyClass? {
if key == Constants.ChatKey {
return VIMLiveChat.self
}
return nil
}
}
| mit | ccaba012e64d885810f7e05106c4dbc0 | 40.674074 | 154 | 0.696765 | 4.490024 | false | false | false | false |
scoremedia/Fisticuffs | Sources/Fisticuffs/ComputedBindingHandler.swift | 1 | 3217 | //
// ComputedBindingHandler.swift
// Fisticuffs
//
// Created by Darren Clark on 2016-05-05.
// Copyright © 2016 theScore. All rights reserved.
//
import Foundation
//TODO: Make all binding handlers refresh when a computed value changes
open class ComputedBindingHandler<Control: AnyObject, InDataValue, OutDataValue, PropertyValue>: BindingHandler<Control, InDataValue, PropertyValue> {
let bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>
let transform: (InDataValue) -> OutDataValue
let inValue: Observable<InDataValue?> = Observable(nil)
var computed: Computed<OutDataValue?>!
var subscription: Disposable? = nil
init(_ transform: @escaping (InDataValue) -> OutDataValue, bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>) {
self.bindingHandler = bindingHandler
self.transform = transform
super.init()
self.computed = Computed { [weak self] in
if let inValue = self?.inValue.value {
return transform(inValue)
}
else {
return nil
}
}
}
deinit {
subscription?.dispose()
}
/// The callbacks for the computed value will be passed on the main thread
open override func set(control: Control, oldValue: InDataValue?, value: InDataValue, propertySetter: @escaping PropertySetter) {
subscription?.dispose()
// so we get oldValue/newValue information, we'll notifyOnSubscription = false, then set it to the new value after
let opts = SubscriptionOptions(notifyOnSubscription: false, when: .afterChange, receiveOn: MainThreadScheduler())
subscription = computed.subscribe(opts) { [weak self, weak control] oldValue, newValue in
if let bindingHandler = self?.bindingHandler, let control = control, let oldValue = oldValue, let newValue = newValue {
bindingHandler.set(control: control, oldValue: oldValue, value: newValue, propertySetter: propertySetter)
}
}
inValue.value = value
// Force an update right away (instead of waiting for next runloop) so that we don't leave old data on screen. This is especially
// important for table view/collection view cells where views are reused.
computed.updateValue()
}
override open func dispose() {
bindingHandler.dispose()
super.dispose()
}
}
public extension BindingHandlers {
static func computed<Control, DataValue, PropertyValue>(_ block: @escaping (DataValue) -> PropertyValue) -> ComputedBindingHandler<Control, DataValue, PropertyValue, PropertyValue> {
ComputedBindingHandler(block, bindingHandler: DefaultBindingHandler())
}
static func computed<Control, InDataValue, OutDataValue, PropertyValue>(_ block: @escaping (InDataValue) -> OutDataValue, reverse: ((OutDataValue) -> InDataValue)?, bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>)
-> ComputedBindingHandler<Control, InDataValue, OutDataValue, PropertyValue> {
ComputedBindingHandler<Control, InDataValue, OutDataValue, PropertyValue>(block, bindingHandler: bindingHandler)
}
}
| mit | ab60be9e285cb0b6f7ee7b79aa0a519b | 41.88 | 238 | 0.698694 | 4.587732 | false | false | false | false |
developerY/Swift2_Playgrounds | Swift Standard Library.playground/Pages/Indexing and Slicing Strings.xcplaygroundpage/Sources/Message.swift | 4 | 1328 | import Foundation
public struct Message {
public let from: String
public let contents: String
public let date: NSDate
public init(from: String, contents: String, date: NSDate) {
self.from = from
self.contents = contents
self.date = date
}
}
extension Message: CustomDebugStringConvertible {
public var debugDescription: String {
return "[\(date) From: \(from)] \(contents)"
}
}
private var dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.doesRelativeDateFormatting = true
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .ShortStyle
return formatter
}()
extension Message: CustomStringConvertible {
public var description: String {
return "\(contents)\n \(from) \(dateFormatter.stringFromDate(date))"
}
}
public var messages: [Message] = [
Message(from: "Sandy", contents: "Hey, what's going on tonight?", date: messageDates[0]),
Message(from: "Michelle", contents: "Studying for Friday's exam. You guys aren't?", date: messageDates[1]),
Message(from: "Christian", contents: "Nope. That's what tomorrow is for. Let's get food, I'm hungry!", date: messageDates[2]),
Message(from: "Michelle", contents: "Maybe. What do you want to eat?", date: messageDates[3])
]
| mit | e57e3a4fc2b0b5dd4d6b248e1e76109e | 31.390244 | 130 | 0.675452 | 4.229299 | false | false | false | false |
Johnnywang1221/actor-platform | actor-apps/app-ios/Actor/Utils/Strings.swift | 31 | 1259 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import Foundation
extension String {
func trim() -> String {
return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet());
}
func size() -> Int {
return count(self);
}
subscript (i: Int) -> Character {
return self[advance(self.startIndex, i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
func first(count: Int) -> String {
let realCount = min(count, size());
return substringToIndex(advance(startIndex, realCount));
}
func strip(set: NSCharacterSet) -> String {
return "".join(componentsSeparatedByCharactersInSet(set))
}
func toLong() -> Int64? {
return NSNumberFormatter().numberFromString(self)?.longLongValue
}
func smallValue() -> String {
let trimmed = trim();
if (trimmed.isEmpty){
return "#";
}
let letters = NSCharacterSet.letterCharacterSet()
var res: String = self[0];
if (res.rangeOfCharacterFromSet(letters) != nil) {
return res.uppercaseString;
} else {
return "#";
}
}
} | mit | f64ce7e3b4e91e81c637d577cf99ff98 | 23.705882 | 88 | 0.566322 | 4.733083 | false | false | false | false |
Mioke/PlanB | PlanB/PlanB/Base/KMNetworking/Generators/KMRequestGenerator.swift | 1 | 873 | //
// KMRequestGenerator.swift
// swiftArchitecture
//
// Created by Klein Mioke on 15/12/7.
// Copyright © 2015年 KleinMioke. All rights reserved.
//
import UIKit
import Alamofire
class KMRequestGenerator: NSObject {
class func generateRequestWithAPI(api: BaseApiManager, method: Alamofire.Method, params: [String: AnyObject]) -> Request {
let request = Manager.sharedInstance.request(method, api.apiURLString(), parameters: params, encoding: .URL, headers: nil)
// FIXME: Do additional configuration or signature etc.
Log.debugPrintln("\n==================================\nSend request:\n\tURL:\(api.apiURLString())\n\tparam:\(params)\n==================================\n")
SystemLog.write("Send request:\n\tRequest Info:\(request.request!)\n\tParam:\(params)")
return request
}
}
| gpl-3.0 | 096035e63a01513d9c89dbe1ccb32f44 | 35.25 | 165 | 0.622989 | 4.285714 | false | false | false | false |
yiqiok/learn_ios | ButtonFun/ButtonFun/ViewController.swift | 1 | 799 | //
// ViewController.swift
// ButtonFun
//
// Created by yiqiok on 14/08/2017.
// Copyright © 2017 yiqiok. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var statusLabel: UILabel!
@IBAction func buttonPressed(_ sender: UIButton) {
let title = sender.title(for: .selected)!
let text = "\(title) button pressed"
statusLabel.text = text
let styledText = NSMutableAttributedString(string: text)
let attributes = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: statusLabel.font.pointSize)]
let nameRange = (text as NSString).range(of: title)
styledText.setAttributes(attributes,range: nameRange)
statusLabel.attributedText = styledText
}
}
| mit | 8710ad43a7f14a0cece4f66ce8e32cd7 | 25.6 | 105 | 0.665414 | 4.586207 | false | false | false | false |
natecook1000/swift | test/stdlib/UnsafePointerDiagnostics.swift | 2 | 8132 | // RUN: %target-typecheck-verify-swift
// Test availability attributes on UnsafePointer initializers.
// Assume the original source contains no UnsafeRawPointer types.
func unsafePointerConversionAvailability(
mrp: UnsafeMutableRawPointer,
rp: UnsafeRawPointer,
umpv: UnsafeMutablePointer<Void>, // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
upv: UnsafePointer<Void>, // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
umpi: UnsafeMutablePointer<Int>,
upi: UnsafePointer<Int>,
umps: UnsafeMutablePointer<String>,
ups: UnsafePointer<String>) {
let omrp: UnsafeMutableRawPointer? = mrp
let orp: UnsafeRawPointer? = rp
let oumpv: UnsafeMutablePointer<Void> = umpv // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
let oupv: UnsafePointer<Void>? = upv // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
let oumpi: UnsafeMutablePointer<Int>? = umpi
let oupi: UnsafePointer<Int>? = upi
let oumps: UnsafeMutablePointer<String>? = umps
let oups: UnsafePointer<String>? = ups
_ = UnsafeMutableRawPointer(mrp)
_ = UnsafeMutableRawPointer(rp) // expected-error {{'init' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(umpv)
_ = UnsafeMutableRawPointer(upv) // expected-error {{'init' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(umpi)
_ = UnsafeMutableRawPointer(upi) // expected-error {{'init' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(umps)
_ = UnsafeMutableRawPointer(ups) // expected-error {{'init' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(omrp)
_ = UnsafeMutableRawPointer(orp) // expected-error {{'init' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(oumpv)
_ = UnsafeMutableRawPointer(oupv) // expected-error {{'init' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(oumpi)
_ = UnsafeMutableRawPointer(oupi) // expected-error {{'init' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(oumps)
_ = UnsafeMutableRawPointer(oups) // expected-error {{'init' has been renamed to 'init(mutating:)'}}
// These all correctly pass with no error.
_ = UnsafeRawPointer(mrp)
_ = UnsafeRawPointer(rp)
_ = UnsafeRawPointer(umpv)
_ = UnsafeRawPointer(upv)
_ = UnsafeRawPointer(umpi)
_ = UnsafeRawPointer(upi)
_ = UnsafeRawPointer(umps)
_ = UnsafeRawPointer(ups)
_ = UnsafeRawPointer(omrp)
_ = UnsafeRawPointer(orp)
_ = UnsafeRawPointer(oumpv)
_ = UnsafeRawPointer(oupv)
_ = UnsafeRawPointer(oumpi)
_ = UnsafeRawPointer(oupi)
_ = UnsafeRawPointer(oumps)
_ = UnsafeRawPointer(oups)
_ = UnsafePointer<Int>(upi)
_ = UnsafePointer<Int>(oumpi)
_ = UnsafePointer<Int>(oupi)
_ = UnsafeMutablePointer<Int>(umpi)
_ = UnsafeMutablePointer<Int>(oumpi)
_ = UnsafeMutablePointer<Void>(rp) // expected-warning 4 {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'RawPointer'}}
_ = UnsafeMutablePointer<Void>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'RawPointer'}} expected-warning 4 {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
_ = UnsafeMutablePointer<Void>(umpv) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
_ = UnsafeMutablePointer<Void>(umpi) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
_ = UnsafeMutablePointer<Void>(umps) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
_ = UnsafePointer<Void>(rp) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'RawPointer'}} expected-warning 4 {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'RawPointer'}} expected-warning 4 {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(umpv) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(upv) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(umpi) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(upi) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(umps) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(ups) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafeMutablePointer<Int>(rp) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'RawPointer'}}
_ = UnsafeMutablePointer<Int>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'RawPointer'}}
_ = UnsafeMutablePointer<Int>(orp) // expected-error {{cannot convert value of type 'UnsafeRawPointer?' to expected argument type 'RawPointer'}}
_ = UnsafeMutablePointer<Int>(omrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer?' to expected argument type 'RawPointer'}}
_ = UnsafePointer<Int>(rp) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'RawPointer'}}
_ = UnsafePointer<Int>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'RawPointer'}}
_ = UnsafePointer<Int>(orp) // expected-error {{cannot convert value of type 'UnsafeRawPointer?' to expected argument type 'RawPointer'}}
_ = UnsafePointer<Int>(omrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer?' to expected argument type 'RawPointer'}}
}
func unsafeRawBufferPointerConversions(
mrp: UnsafeMutableRawPointer,
rp: UnsafeRawPointer,
mrbp: UnsafeMutableRawBufferPointer,
rbp: UnsafeRawBufferPointer,
mbpi: UnsafeMutableBufferPointer<Int>,
bpi: UnsafeBufferPointer<Int>) {
let omrp: UnsafeMutableRawPointer? = mrp
let orp: UnsafeRawPointer? = rp
_ = UnsafeMutableRawBufferPointer(start: mrp, count: 1)
_ = UnsafeRawBufferPointer(start: mrp, count: 1)
_ = UnsafeMutableRawBufferPointer(start: rp, count: 1) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'UnsafeMutableRawPointer?'}}
_ = UnsafeRawBufferPointer(start: rp, count: 1)
_ = UnsafeMutableRawBufferPointer(mrbp)
_ = UnsafeRawBufferPointer(mrbp)
_ = UnsafeMutableRawBufferPointer(rbp) // expected-error {{cannot invoke initializer for type 'UnsafeMutableRawBufferPointer' with an argument list of type '(UnsafeRawBufferPointer)'}} expected-note {{overloads for 'UnsafeMutableRawBufferPointer' exist with these partially matching parameter lists: (UnsafeMutableRawBufferPointer), (UnsafeMutableBufferPointer<T>)}}
_ = UnsafeRawBufferPointer(rbp)
_ = UnsafeMutableRawBufferPointer(mbpi)
_ = UnsafeRawBufferPointer(mbpi)
_ = UnsafeMutableRawBufferPointer(bpi) // expected-error {{cannot invoke initializer for type 'UnsafeMutableRawBufferPointer' with an argument list of type '(UnsafeBufferPointer<Int>)'}} expected-note {{overloads for 'UnsafeMutableRawBufferPointer' exist with these partially matching parameter lists: (UnsafeMutableRawBufferPointer), (UnsafeMutableBufferPointer<T>)}}
_ = UnsafeRawBufferPointer(bpi)
_ = UnsafeMutableRawBufferPointer(start: omrp, count: 1)
_ = UnsafeRawBufferPointer(start: omrp, count: 1)
_ = UnsafeMutableRawBufferPointer(start: orp, count: 1) // expected-error {{cannot convert value of type 'UnsafeRawPointer?' to expected argument type 'UnsafeMutableRawPointer?'}}
_ = UnsafeRawBufferPointer(start: orp, count: 1)
} | apache-2.0 | da9b0fd0ca9099dabab735fb1df114f0 | 68.512821 | 370 | 0.756763 | 4.706019 | false | false | false | false |
megavolt605/CNLUIKitTools | CNLUIKitTools/CNLUIT+UIImageView.swift | 1 | 553 | //
// CNLUIT+UIImageView.swift
// CNLUIKitTools
//
// Created by Igor Smirnov on 11/11/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import UIKit
public extension UIImageView {
public func makeMeRounded(_ borderWidth: CGFloat = 3.0, borderColor: UIColor? = nil) {
layer.cornerRadius = frame.width / 2.0
clipsToBounds = true
if borderWidth > 0.0 {
layer.borderWidth = borderWidth
layer.borderColor = borderColor?.cgColor ?? UIColor.white.cgColor
}
}
}
| mit | 60c8486624009a77afe3453b3e3a3ef9 | 24.090909 | 90 | 0.63587 | 4.150376 | false | false | false | false |
megavolt605/CNLUIKitTools | CNLUIKitTools/CNLCheckBox.swift | 1 | 14664 | //
// CNLCheckBox.swift
// CNLUIKitTools
//
// Created by Igor Smirnov on 24/11/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import UIKit
import CNLFoundationTools
/// State of the check box
///
/// - empty: not checked
/// - tick: checked with tick
/// - cross: checked with cross
public enum CNLCheckBoxState {
case empty, tick, cross
}
/// Form of the check box
///
/// - circle: Circle shape
/// - square: Square shape
public enum CNLCheckBoxForm {
case circle, square
}
/// Check box with set of states (empty, tick, cross) with simple animations
public class CNLCheckBox: UIView {
/// Line width for state icons
public var lineWidth: [CNLCheckBoxState: CGFloat] = [.empty: 2.0, .tick: 4.0, .cross: 4.0]
private var currentLineWidth: CGFloat { return lineWidth[state] ?? 0.0 }
/// Line color for state icons
public var lineColor: [CNLCheckBoxState: UIColor] = [.empty: UIColor.white, .tick: UIColor.white, .cross: UIColor.white]
private var currentLineColor: UIColor { return lineColor[state] ?? UIColor.white }
/// Fill color of inner circle for empty state
public var emptyFillColor: UIColor = UIColor.white
/// Border width for empty state
public var borderLineWidth: [CNLCheckBoxState: CGFloat] = [.empty: 2.0, .tick: 0.0, .cross: 0.0] {
didSet {
updateLayers()
}
}
private var currentBorderLineWidth: CGFloat { return borderLineWidth[state] ?? 0.0 }
/// Border color for empty state, fill color for others
public var fillColor: [CNLCheckBoxState: UIColor] = [.empty: UIColor.black, .tick: UIColor.green, .cross: UIColor.red] {
didSet {
updateLayers()
}
}
private var currentFillColor: UIColor { return fillColor[state] ?? UIColor.white }
/// Sequence for automatic state change, default is [.empty, .tick]
public var stateSequence: [CNLCheckBoxState] = [.empty, .tick] {
didSet {
stateSequenceIndex = 0
//setState(stateSequence[stateSequenceIndex], animated: false)
}
}
public var stateSequenceIndex: Int = 0
/// Current check box state. When changed, state will change without animation
public var state: CNLCheckBoxState {
get { return _state }
set { setState(newValue, animated: false) }
}
private var _state: CNLCheckBoxState = .empty
/// Form of the check box
public var form: CNLCheckBoxForm = .circle {
didSet {
updateLayers()
}
}
/// Callback when the state was changed
public var stateWasChanged: ((_ toState: CNLCheckBoxState) -> Void)?
/// State change animation duration
public var animationDuration: Double = 0.2
private var borderShape: CAShapeLayer!
private var centerShape: CAShapeLayer!
private var tapGestureRecognizer: UITapGestureRecognizer!
private var sideWidth: CGFloat = 0.0
private var doublePi: CGFloat = CGFloat.pi * 2.0
/// Init check box within a frame
///
/// - Parameter frame: frame (CGRect)
override required public init(frame: CGRect) {
super.init(frame: frame)
initializeUI()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeUI()
}
private func initializeUI() {
sideWidth = min(frame.size.width, frame.size.height)
backgroundColor = UIColor.white
borderShape = CAShapeLayer()
layer.addSublayer(borderShape)
centerShape = CAShapeLayer()
layer.addSublayer(centerShape)
updateLayers()
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognizerAction))
addGestureRecognizer(tapGestureRecognizer)
}
public func removeAllAnimations() {
borderShape.removeAllAnimations()
centerShape.removeAllAnimations()
}
/// Sets new state to the check box. Animatable.
///
/// - Parameters:
/// - state: new state
/// - animated: animation flag
public func setState(_ state: CNLCheckBoxState, animated: Bool) {
if (self.state != state) || !animated {
_state = state
if let subLayers = borderShape.sublayers {
for subLayer in subLayers {
subLayer.removeFromSuperlayer()
}
}
//updateLayers()
startBorderLayerAnimation(animated: animated)
startScaleBorderLayerAnimaiton(animated: animated)
addStateSublayers(animated: animated)
stateWasChanged?(_state)
}
}
private var borderPath: UIBezierPath {
let centerPoint = CGPoint(x: sideWidth / 2.0, y: sideWidth / 2.0)
let result: UIBezierPath
switch form {
case .circle:
result = UIBezierPath(
arcCenter: centerPoint,
radius: sideWidth / 2.0,
startAngle: 0.0,
endAngle: doublePi,
clockwise: true
)
case .square:
result = UIBezierPath(
rect: CGRect(
origin: CGPoint.zero,
size: CGSize(width: sideWidth, height: sideWidth)
)
)
}
return result
}
private var centerPath: UIBezierPath {
let centerPoint = CGPoint(x: sideWidth / 2.0, y: sideWidth / 2.0)
let result: UIBezierPath
switch form {
case .circle:
result = UIBezierPath(
arcCenter: centerPoint,
radius: sideWidth / 2.0 - currentBorderLineWidth,
startAngle: 0.0,
endAngle: doublePi,
clockwise: true
)
case .square:
result = UIBezierPath(
rect: CGRect(
origin: CGPoint(x: currentBorderLineWidth, y: currentBorderLineWidth),
size: CGSize(width: sideWidth - currentBorderLineWidth * 2.0, height: sideWidth - currentBorderLineWidth * 2.0)
)
)
}
return result
}
private func updateLayers() {
borderShape.path = borderPath.cgPath
borderShape.fillColor = currentFillColor.cgColor
centerShape.path = centerPath.cgPath
centerShape.fillColor = emptyFillColor.cgColor
}
@objc private func tapGestureRecognizerAction() {
if isUserInteractionEnabled {
if stateSequenceIndex == (stateSequence.count - 1) {
stateSequenceIndex = 0
} else {
stateSequenceIndex += 1
}
setState(stateSequence[stateSequenceIndex], animated: true)
}
}
private func startBorderLayerAnimation(animated: Bool) {
if state == .empty {
let finalPath = centerPath.cgPath
/*UIBezierPath(
arcCenter: CGPoint(x: sideWidth / 2.0, y: sideWidth / 2.0),
radius: sideWidth / 2.0 - currentBorderLineWidth,
startAngle: 0.0,
endAngle: doublePi,
clockwise: true
).cgPath*/
if animated {
CABasicAnimation(keyPath: "path") --> {
$0.fromValue = UIBezierPath(
arcCenter: CGPoint(x: sideWidth / 2.0, y: sideWidth / 2.0),
radius: 0.1,
startAngle: 0.0,
endAngle: doublePi,
clockwise: true
).cgPath
$0.toValue = finalPath
$0.duration = animationDuration / 3.0 * 2.0
$0.isRemovedOnCompletion = false
$0.fillMode = kCAFillModeForwards
centerShape.add($0, forKey: nil)
}
} else {
centerShape.path = finalPath
}
} else {
let finalPath = UIBezierPath(
arcCenter: CGPoint(x: sideWidth / 2.0, y: sideWidth / 2.0),
radius: 0.1,
startAngle: 0.0,
endAngle: doublePi,
clockwise: true
).cgPath
if animated {
CABasicAnimation(keyPath: "path") --> {
$0.fromValue = UIBezierPath(
arcCenter: CGPoint(x: sideWidth / 2.0, y: sideWidth / 2.0),
radius: sideWidth / 2.0 - currentBorderLineWidth,
startAngle: 0.0,
endAngle: doublePi,
clockwise: true
).cgPath
$0.toValue = finalPath
$0.duration = animationDuration / 3.0 * 2.0
$0.isRemovedOnCompletion = false
$0.fillMode = kCAFillModeForwards
centerShape.add($0, forKey: nil)
}
} else {
centerShape.path = finalPath
}
}
if animated {
CABasicAnimation(keyPath: "fillColor") --> {
$0.toValue = currentFillColor.cgColor
$0.duration = animationDuration / 3.0 * 2.0
$0.isRemovedOnCompletion = false
$0.fillMode = kCAFillModeForwards
borderShape.add($0, forKey: nil)
}
} else {
borderShape.fillColor = currentFillColor.cgColor
}
}
private func startScaleBorderLayerAnimaiton(animated: Bool) {
var toValue = CATransform3DIdentity
toValue = CATransform3DTranslate(toValue, bounds.size.width / 2.0, bounds.size.height / 2.0, 0.0)
toValue = CATransform3DScale(toValue, 1.0, 1.0, 1.0)
toValue = CATransform3DTranslate(toValue, -bounds.size.width / 2.0, -bounds.size.height / 2.0, 0.0)
if animated {
var byValue = CATransform3DIdentity
byValue = CATransform3DTranslate(byValue, bounds.size.width / 2.0, bounds.size.height / 2.0, 0.0)
byValue = CATransform3DScale(byValue, 0.8, 0.8, 1.0)
byValue = CATransform3DTranslate(byValue, -bounds.size.width / 2.0, -bounds.size.height / 2.0, 0.0)
let firstScaleAnimation = CABasicAnimation(keyPath: "transform") --> {
$0.toValue = NSValue(caTransform3D: byValue)
$0.duration = animationDuration / 2.0
$0.isRemovedOnCompletion = false
$0.fillMode = kCAFillModeForwards
}
let secondScaleAnimation = CABasicAnimation(keyPath: "transform") --> {
$0.toValue = NSValue(caTransform3D: toValue)
$0.beginTime = animationDuration / 2.0
$0.duration = animationDuration / 2.0
$0.isRemovedOnCompletion = false
$0.fillMode = kCAFillModeForwards
}
let scaleAnimationGroup = CAAnimationGroup() --> {
$0.animations = [firstScaleAnimation, secondScaleAnimation]
$0.duration = animationDuration
}
borderShape.add(scaleAnimationGroup, forKey: nil)
centerShape.add(scaleAnimationGroup, forKey: nil)
} else {
borderShape.transform = toValue
centerShape.transform = toValue
}
}
private func addStateSublayers(animated: Bool) {
switch state {
case .tick:
let unitLength = sideWidth / 30.0
let beginPoint = CGPoint(x: unitLength * 7.0, y: unitLength * 14.0)
let transitionPoint = CGPoint(x: unitLength * 13.0, y: unitLength * 20.0)
let endPoint = CGPoint(x: unitLength * 22.0, y: unitLength * 10.0)
let tickPath = UIBezierPath() --> {
$0.move(to: beginPoint)
$0.addLine(to: transitionPoint)
$0.addLine(to: endPoint)
}
let tickLayer = CAShapeLayer() --> {
$0.path = tickPath.cgPath
$0.lineWidth = currentLineWidth
$0.lineCap = kCALineCapRound
$0.lineJoin = kCALineJoinRound
$0.fillColor = UIColor.clear.cgColor
$0.strokeColor = currentLineColor.cgColor
$0.strokeEnd = 0.0
borderShape.addSublayer($0)
}
if animated {
CABasicAnimation(keyPath: "strokeEnd") --> {
$0.toValue = 1.0
$0.duration = animationDuration
$0.isRemovedOnCompletion = false
$0.fillMode = kCAFillModeForwards
tickLayer.add($0, forKey: nil)
}
} else {
tickLayer.strokeEnd = 1.0
}
case .cross:
let datumPoint = sideWidth / 3.0
let pointTopLeft = CGPoint(x: datumPoint, y: datumPoint)
let pointTopRight = CGPoint(x: 2.0 * datumPoint, y: datumPoint)
let pointBottomLeft = CGPoint(x: datumPoint, y: 2.0 * datumPoint)
let pointBottomRight = CGPoint(x: 2.0 * datumPoint, y: 2.0 * datumPoint)
let tickLayer = CAShapeLayer() --> {
$0.path = (UIBezierPath() --> {
$0.move(to: pointTopLeft)
$0.addLine(to: pointBottomRight)
$0.move(to: pointTopRight)
$0.addLine(to: pointBottomLeft)
}).cgPath
$0.lineWidth = currentLineWidth
$0.lineCap = kCALineCapRound
$0.lineJoin = kCALineJoinRound
$0.fillColor = UIColor.clear.cgColor
$0.strokeColor = currentLineColor.cgColor
$0.strokeEnd = 0.0
borderShape.addSublayer($0)
}
if animated {
CABasicAnimation(keyPath: "strokeEnd") --> {
$0.toValue = 1.0
$0.duration = animationDuration
$0.isRemovedOnCompletion = false
$0.fillMode = kCAFillModeForwards
tickLayer.add($0, forKey: nil)
}
} else {
tickLayer.strokeEnd = 1.0
}
default: break
}
}
}
| mit | 70f7049c59d71d020822c1df6fd82a17 | 35.384615 | 131 | 0.538907 | 5.02674 | false | false | false | false |
Antondomashnev/FBSnapshotsViewer | FBSnapshotsViewer/Managers/TestClassNameExtractor.swift | 1 | 3358 | //
// TestClassNameExtractor.swift
// FBSnapshotsViewer
//
// Created by Anton Domashnev on 15.08.17.
// Copyright © 2017 Anton Domashnev. All rights reserved.
//
import Foundation
enum TestClassNameExtractorError: Error {
case unexpectedLogLine(message: String)
}
protocol TestClassNameExtractor: AutoMockable {
func extractTestClassName(from logLine: ApplicationLogLine) throws -> String
}
class TestClassNameExtractorFactory {
func extractor(for logLine: ApplicationLogLine) -> TestClassNameExtractor? {
switch logLine {
case .kaleidoscopeCommandMessage:
return FailedTestClassNameExtractor()
case .referenceImageSavedMessage:
return RecordedTestClassNameExtractor()
default:
return nil
}
}
}
private class TestClassNameExtractorHelper {
static func extractTestClassName(from imagePath: String) -> String? {
let pathComponents = imagePath.components(separatedBy: "/")
return pathComponents.count >= 2 ? pathComponents[pathComponents.count - 2] : nil
}
}
class FailedTestClassNameExtractor: TestClassNameExtractor {
func extractTestClassName(from logLine: ApplicationLogLine) throws -> String {
guard case let ApplicationLogLine.kaleidoscopeCommandMessage(line) = logLine else {
throw TestClassNameExtractorError.unexpectedLogLine(message: "Unexpected \(logLine). Expected kaleidoscopeCommandMessage")
}
let lineComponents = line.components(separatedBy: "\"")
guard lineComponents.count >= 2,
let testClassName = TestClassNameExtractorHelper.extractTestClassName(from: lineComponents[1].replacingOccurrences(of: "reference_", with: "")) else {
throw TestClassNameExtractorError.unexpectedLogLine(message: "Unexpected \(line). Expected ksdiff \"/Users/antondomashnev/Library/Developer/CoreSimulator/Devices/B1AC0517-7FC0-4B32-8543-9EC263071FE5/data/Containers/Data/Application/8EEE157C-41B9-47F8-8634-CF3D60962E19/tmp/FBSnapshotsViewerExampleTests/[email protected]\" \"/Users/antondomashnev/Library/Developer/CoreSimulator/Devices/B1AC0517-7FC0-4B32-8543-9EC263071FE5/data/Containers/Data/Application/8EEE157C-41B9-47F8-8634-CF3D60962E19/tmp/FBSnapshotsViewerExampleTests/[email protected]\"")
}
return testClassName
}
}
class RecordedTestClassNameExtractor: TestClassNameExtractor {
func extractTestClassName(from logLine: ApplicationLogLine) throws -> String {
guard case let ApplicationLogLine.referenceImageSavedMessage(line) = logLine else {
throw TestClassNameExtractorError.unexpectedLogLine(message: "Unexpected \(logLine). Expected referenceImageSavedMessage")
}
let lineComponents = line.components(separatedBy: ": ")
guard lineComponents.count >= 2,
let testClassName = TestClassNameExtractorHelper.extractTestClassName(from: lineComponents[1]) else {
throw TestClassNameExtractorError.unexpectedLogLine(message: "Unexpected \(line). Expected 2017-04-25 21:15:37.107 FBSnapshotsViewerExample[56034:787919] Reference image save at: /Users/antondomashnev/Work/FBSnapshotsViewerExample/FBSnapshotsViewerExampleTests/ReferenceImages_64/FBSnapshotsViewerExampleTests/[email protected]")
}
return testClassName
}
}
| mit | fbd38e1307fd4021701ed4e140f7324c | 50.646154 | 581 | 0.752755 | 4.417105 | false | true | false | false |
alblue/swift-corelibs-foundation | Foundation/String.swift | 1 | 3003 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import CoreFoundation
extension String : _ObjectiveCBridgeable {
public typealias _ObjectType = NSString
public func _bridgeToObjectiveC() -> _ObjectType {
return NSString(self)
}
static public func _forceBridgeFromObjectiveC(_ source: _ObjectType, result: inout String?) {
result = _unconditionallyBridgeFromObjectiveC(source)
}
@discardableResult
static public func _conditionallyBridgeFromObjectiveC(_ source: _ObjectType, result: inout String?) -> Bool {
if type(of: source) == NSString.self || type(of: source) == NSMutableString.self {
result = source._storage
} else if type(of: source) == _NSCFString.self {
let cf = unsafeBitCast(source, to: CFString.self)
if let str = CFStringGetCStringPtr(cf, CFStringEncoding(kCFStringEncodingUTF8)) {
result = String(cString: str)
} else {
let length = CFStringGetLength(cf)
let buffer = UnsafeMutablePointer<UniChar>.allocate(capacity: length)
CFStringGetCharacters(cf, CFRangeMake(0, length), buffer)
let str = String(decoding: UnsafeBufferPointer(start: buffer, count: length), as: UTF16.self)
buffer.deinitialize(count: length)
buffer.deallocate()
result = str
}
} else if type(of: source) == _NSCFConstantString.self {
let conststr = unsafeDowncast(source, to: _NSCFConstantString.self)
let str = String(decoding: UnsafeBufferPointer(start: conststr._ptr, count: Int(conststr._length)), as: UTF8.self)
result = str
} else {
let len = source.length
var characters = [unichar](repeating: 0, count: len)
result = characters.withUnsafeMutableBufferPointer() { (buffer: inout UnsafeMutableBufferPointer<unichar>) -> String? in
source.getCharacters(buffer.baseAddress!, range: NSRange(location: 0, length: len))
return String(decoding: buffer, as: UTF16.self)
}
}
return result != nil
}
static public func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectType?) -> String {
if let object = source {
var value: String?
_conditionallyBridgeFromObjectiveC(object, result: &value)
return value!
} else {
return ""
}
}
}
| apache-2.0 | bb56b4e99c8760f067fec44f0f2fc41f | 43.161765 | 132 | 0.59041 | 5.240838 | false | false | false | false |
Darr758/Swift-Algorithms-and-Data-Structures | Data Structures/HashTable.playground/Contents.swift | 1 | 1895 | //IM
class HashTable<key:Hashable, value>{
private typealias Element = (key:key, value:value)
private typealias Bucket = [Element]
private var buckets:[Bucket]
private(set) public var count = 0
func isEmpty() -> Bool{
return count == 0
}
init(_ capacity:Int){
precondition(capacity > 0, "Capacity must be greater than zero")
self.buckets = Array(repeatElement([], count: capacity))
}
public func getIndex(_ key:key) -> Int{
return abs(key.hashValue)%buckets.count
}
public subscript(key:key) -> value?{
get{
return getValue(key)
}
set{
if let value = newValue{
updateValue(key:key,value:value)
}else{
removeValue(key)
}
}
}
public func getValue(_ key:key) -> value?{
let index = getIndex(key)
for element in buckets[index]{
if element.key == key{
return element.value
}
}
return nil
}
public func updateValue(key:key, value:value) -> value?{
let index = getIndex(key)
for (i, element) in buckets[index].enumerated(){
if element.key == key{
let oldValue = element.value
self.buckets[index][i].value = value
return oldValue
}
}
self.buckets[index].append(key:key,value:value)
return nil
}
public func removeValue(_ key:key) -> value?{
let index = getIndex(key)
for (i, element) in buckets[index].enumerated(){
if element.key == key{
let value = element.value
buckets[index].remove(at:i)
count -= 1
return value
}
}
return nil
}
}
| mit | 621dce1f4170e761378384441c9fb278 | 25.319444 | 72 | 0.505541 | 4.633252 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/IoTThingsGraph/IoTThingsGraph_Error.swift | 1 | 2669 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for IoTThingsGraph
public struct IoTThingsGraphErrorType: AWSErrorType {
enum Code: String {
case internalFailureException = "InternalFailureException"
case invalidRequestException = "InvalidRequestException"
case limitExceededException = "LimitExceededException"
case resourceAlreadyExistsException = "ResourceAlreadyExistsException"
case resourceInUseException = "ResourceInUseException"
case resourceNotFoundException = "ResourceNotFoundException"
case throttlingException = "ThrottlingException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize IoTThingsGraph
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
public static var internalFailureException: Self { .init(.internalFailureException) }
public static var invalidRequestException: Self { .init(.invalidRequestException) }
public static var limitExceededException: Self { .init(.limitExceededException) }
public static var resourceAlreadyExistsException: Self { .init(.resourceAlreadyExistsException) }
public static var resourceInUseException: Self { .init(.resourceInUseException) }
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
public static var throttlingException: Self { .init(.throttlingException) }
}
extension IoTThingsGraphErrorType: Equatable {
public static func == (lhs: IoTThingsGraphErrorType, rhs: IoTThingsGraphErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension IoTThingsGraphErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 | 8039fbc30159cd2ec2ce819888fa567b | 38.25 | 117 | 0.685275 | 5.182524 | false | false | false | false |
vector-im/vector-ios | Riot/Managers/Settings/RiotSettings.swift | 1 | 18559 | /*
Copyright 2018 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/// Store Riot specific app settings.
@objcMembers
final class RiotSettings: NSObject {
// MARK: - Constants
public enum UserDefaultsKeys {
static let enableAnalytics = "enableAnalytics"
static let matomoAnalytics = "enableCrashReport"
static let notificationsShowDecryptedContent = "showDecryptedContent"
static let allowStunServerFallback = "allowStunServerFallback"
static let pinRoomsWithMissedNotificationsOnHome = "pinRoomsWithMissedNotif"
static let pinRoomsWithUnreadMessagesOnHome = "pinRoomsWithUnread"
static let showAllRoomsInHomeSpace = "showAllRoomsInHomeSpace"
static let enableUISIAutoReporting = "enableUISIAutoReporting"
}
static let shared = RiotSettings()
/// UserDefaults to be used on reads and writes.
static var defaults: UserDefaults = {
guard let userDefaults = UserDefaults(suiteName: BuildSettings.applicationGroupIdentifier) else {
fatalError("[RiotSettings] Fail to load shared UserDefaults")
}
return userDefaults
}()
private override init() {
super.init()
}
/// Indicate if UserDefaults suite has been migrated once.
var isUserDefaultsMigrated: Bool {
return RiotSettings.defaults.object(forKey: UserDefaultsKeys.notificationsShowDecryptedContent) != nil
}
func migrate() {
// read all values from standard
let dictionary = UserDefaults.standard.dictionaryRepresentation()
// write values to suite
// remove redundant values from standard
for (key, value) in dictionary {
RiotSettings.defaults.set(value, forKey: key)
UserDefaults.standard.removeObject(forKey: key)
}
}
// MARK: Servers
@UserDefault(key: "homeserverurl", defaultValue: BuildSettings.serverConfigDefaultHomeserverUrlString, storage: defaults)
var homeserverUrlString
@UserDefault(key: "identityserverurl", defaultValue: BuildSettings.serverConfigDefaultIdentityServerUrlString, storage: defaults)
var identityServerUrlString
// MARK: Notifications
/// Indicate if `showDecryptedContentInNotifications` settings has been set once.
var isShowDecryptedContentInNotificationsHasBeenSetOnce: Bool {
return RiotSettings.defaults.object(forKey: UserDefaultsKeys.notificationsShowDecryptedContent) != nil
}
/// Indicate if encrypted messages content should be displayed in notifications.
@UserDefault(key: UserDefaultsKeys.notificationsShowDecryptedContent, defaultValue: false, storage: defaults)
var showDecryptedContentInNotifications
/// Indicate if rooms with missed notifications should be displayed first on home screen.
@UserDefault(key: UserDefaultsKeys.pinRoomsWithMissedNotificationsOnHome, defaultValue: false, storage: defaults)
var pinRoomsWithMissedNotificationsOnHome
/// Indicate if rooms with unread messages should be displayed first on home screen.
@UserDefault(key: UserDefaultsKeys.pinRoomsWithUnreadMessagesOnHome, defaultValue: false, storage: defaults)
var pinRoomsWithUnreadMessagesOnHome
/// Indicate to show Not Safe For Work public rooms.
@UserDefault(key: "showNSFWPublicRooms", defaultValue: false, storage: defaults)
var showNSFWPublicRooms
// MARK: User interface
@UserDefault<String?>(key: "userInterfaceTheme", defaultValue: nil, storage: defaults)
var userInterfaceTheme
// MARK: Analytics & Rageshakes
/// Whether the user was previously shown the Matomo analytics prompt.
var hasSeenAnalyticsPrompt: Bool {
RiotSettings.defaults.object(forKey: UserDefaultsKeys.enableAnalytics) != nil
}
/// Whether the user has both seen the Matomo analytics prompt and declined it.
var hasDeclinedMatomoAnalytics: Bool {
RiotSettings.defaults.object(forKey: UserDefaultsKeys.matomoAnalytics) != nil && !RiotSettings.defaults.bool(forKey: UserDefaultsKeys.matomoAnalytics)
}
/// Whether the user previously accepted the Matomo analytics prompt.
/// This allows these users to be shown a different prompt to explain the changes.
var hasAcceptedMatomoAnalytics: Bool {
RiotSettings.defaults.bool(forKey: UserDefaultsKeys.matomoAnalytics)
}
/// `true` when the user has opted in to send analytics.
@UserDefault(key: UserDefaultsKeys.enableAnalytics, defaultValue: false, storage: defaults)
var enableAnalytics
/// Indicates if the device has already called identify for this session to PostHog.
/// This is separate to `enableAnalytics` as logging out will leave analytics
/// enabled but reset identification.
@UserDefault(key: "isIdentifiedForAnalytics", defaultValue: false, storage: defaults)
var isIdentifiedForAnalytics
@UserDefault(key: "enableRageShake", defaultValue: false, storage: defaults)
var enableRageShake
// MARK: User
/// A dictionary of dictionaries keyed by user ID for storage of the `UserSessionProperties` from any active `UserSession`s.
@UserDefault(key: "userSessionProperties", defaultValue: [:], storage: defaults)
var userSessionProperties: [String: [String: Any]]
// MARK: Labs
/// Indicates if CallKit ringing is enabled for group calls. This setting does not disable the CallKit integration for group calls, only relates to ringing.
@UserDefault(key: "enableRingingForGroupCalls", defaultValue: false, storage: defaults)
var enableRingingForGroupCalls
/// Indicates if threads enabled in the timeline.
@UserDefault(key: "enableThreads", defaultValue: false, storage: defaults)
var enableThreads
/// Indicates if auto reporting of decryption errors is enabled
@UserDefault(key: UserDefaultsKeys.enableUISIAutoReporting, defaultValue: BuildSettings.cryptoUISIAutoReportingEnabled, storage: defaults)
var enableUISIAutoReporting
// MARK: Calls
/// Indicate if `allowStunServerFallback` settings has been set once.
var isAllowStunServerFallbackHasBeenSetOnce: Bool {
return RiotSettings.defaults.object(forKey: UserDefaultsKeys.allowStunServerFallback) != nil
}
@UserDefault(key: UserDefaultsKeys.allowStunServerFallback, defaultValue: false, storage: defaults)
var allowStunServerFallback
// MARK: Key verification
@UserDefault(key: "hideVerifyThisSessionAlert", defaultValue: false, storage: defaults)
var hideVerifyThisSessionAlert
@UserDefault(key: "hideReviewSessionsAlert", defaultValue: false, storage: defaults)
var hideReviewSessionsAlert
@UserDefault(key: "matrixApps", defaultValue: false, storage: defaults)
var matrixApps
// MARK: - Rooms Screen
@UserDefault(key: "roomsAllowToJoinPublicRooms", defaultValue: BuildSettings.roomsAllowToJoinPublicRooms, storage: defaults)
var roomsAllowToJoinPublicRooms
@UserDefault(key: UserDefaultsKeys.showAllRoomsInHomeSpace, defaultValue: true, storage: defaults)
var showAllRoomsInHomeSpace
// MARK: - Room Screen
@UserDefault(key: "roomScreenAllowVoIPForDirectRoom", defaultValue: BuildSettings.roomScreenAllowVoIPForDirectRoom, storage: defaults)
var roomScreenAllowVoIPForDirectRoom
@UserDefault(key: "roomScreenAllowVoIPForNonDirectRoom", defaultValue: BuildSettings.roomScreenAllowVoIPForNonDirectRoom, storage: defaults)
var roomScreenAllowVoIPForNonDirectRoom
@UserDefault(key: "roomScreenAllowCameraAction", defaultValue: BuildSettings.roomScreenAllowCameraAction, storage: defaults)
var roomScreenAllowCameraAction
@UserDefault(key: "roomScreenAllowMediaLibraryAction", defaultValue: BuildSettings.roomScreenAllowMediaLibraryAction, storage: defaults)
var roomScreenAllowMediaLibraryAction
@UserDefault(key: "roomScreenAllowStickerAction", defaultValue: BuildSettings.roomScreenAllowStickerAction, storage: defaults)
var roomScreenAllowStickerAction
@UserDefault(key: "roomScreenAllowFilesAction", defaultValue: BuildSettings.roomScreenAllowFilesAction, storage: defaults)
var roomScreenAllowFilesAction
@UserDefault(key: "roomScreenShowsURLPreviews", defaultValue: true, storage: defaults)
var roomScreenShowsURLPreviews
@UserDefault(key: "roomScreenEnableMessageBubbles", defaultValue: BuildSettings.isRoomScreenEnableMessageBubblesByDefault, storage: defaults)
var roomScreenEnableMessageBubbles
var roomTimelineStyleIdentifier: RoomTimelineStyleIdentifier {
return self.roomScreenEnableMessageBubbles ? .bubble : .plain
}
/// A setting used to display the latest known display name and avatar in the timeline
/// for both the sender and target, rather than the profile at the time of the event.
///
/// Note: this is set up from Room perspective, which means that if a user updates their profile after
/// leaving a Room, it will show up the latest profile used in the Room rather than the latest overall.
@UserDefault(key: "roomScreenUseOnlyLatestUserAvatarAndName", defaultValue: BuildSettings.roomScreenUseOnlyLatestUserAvatarAndName, storage: defaults)
var roomScreenUseOnlyLatestUserAvatarAndName
// MARK: - Room Contextual Menu
@UserDefault(key: "roomContextualMenuShowMoreOptionForMessages", defaultValue: BuildSettings.roomContextualMenuShowMoreOptionForMessages, storage: defaults)
var roomContextualMenuShowMoreOptionForMessages
@UserDefault(key: "roomContextualMenuShowMoreOptionForStates", defaultValue: BuildSettings.roomContextualMenuShowMoreOptionForStates, storage: defaults)
var roomContextualMenuShowMoreOptionForStates
@UserDefault(key: "roomContextualMenuShowReportContentOption", defaultValue: BuildSettings.roomContextualMenuShowReportContentOption, storage: defaults)
var roomContextualMenuShowReportContentOption
// MARK: - Room Info Screen
@UserDefault(key: "roomInfoScreenShowIntegrations", defaultValue: BuildSettings.roomInfoScreenShowIntegrations, storage: defaults)
var roomInfoScreenShowIntegrations
// MARK: - Room Member Screen
@UserDefault(key: "roomMemberScreenShowIgnore", defaultValue: BuildSettings.roomMemberScreenShowIgnore, storage: defaults)
var roomMemberScreenShowIgnore
// MARK: - Room Creation Screen
@UserDefault(key: "roomCreationScreenAllowEncryptionConfiguration", defaultValue: BuildSettings.roomCreationScreenAllowEncryptionConfiguration, storage: defaults)
var roomCreationScreenAllowEncryptionConfiguration
@UserDefault(key: "roomCreationScreenRoomIsEncrypted", defaultValue: BuildSettings.roomCreationScreenRoomIsEncrypted, storage: defaults)
var roomCreationScreenRoomIsEncrypted
@UserDefault(key: "roomCreationScreenAllowRoomTypeConfiguration", defaultValue: BuildSettings.roomCreationScreenAllowRoomTypeConfiguration, storage: defaults)
var roomCreationScreenAllowRoomTypeConfiguration
@UserDefault(key: "roomCreationScreenRoomIsPublic", defaultValue: BuildSettings.roomCreationScreenRoomIsPublic, storage: defaults)
var roomCreationScreenRoomIsPublic
// MARK: Features
@UserDefault(key: "allowInviteExernalUsers", defaultValue: BuildSettings.allowInviteExernalUsers, storage: defaults)
var allowInviteExernalUsers
/// When set to false the original image is sent and a 1080p preset is used for videos.
/// If `BuildSettings.roomInputToolbarCompressionMode` has a value other than prompt, the build setting takes priority for images.
@UserDefault(key: "showMediaCompressionPrompt", defaultValue: false, storage: defaults)
var showMediaCompressionPrompt
// MARK: - Main Tabs
@UserDefault(key: "homeScreenShowFavouritesTab", defaultValue: BuildSettings.homeScreenShowFavouritesTab, storage: defaults)
var homeScreenShowFavouritesTab
@UserDefault(key: "homeScreenShowPeopleTab", defaultValue: BuildSettings.homeScreenShowPeopleTab, storage: defaults)
var homeScreenShowPeopleTab
@UserDefault(key: "homeScreenShowRoomsTab", defaultValue: BuildSettings.homeScreenShowRoomsTab, storage: defaults)
var homeScreenShowRoomsTab
@UserDefault(key: "homeScreenShowCommunitiesTab", defaultValue: BuildSettings.homeScreenShowCommunitiesTab, storage: defaults)
var homeScreenShowCommunitiesTab
// MARK: General Settings
@UserDefault(key: "settingsScreenShowChangePassword", defaultValue: BuildSettings.settingsScreenShowChangePassword, storage: defaults)
var settingsScreenShowChangePassword
@UserDefault(key: "settingsScreenShowEnableStunServerFallback", defaultValue: BuildSettings.settingsScreenShowEnableStunServerFallback, storage: defaults)
var settingsScreenShowEnableStunServerFallback
@UserDefault(key: "settingsScreenShowNotificationDecodedContentOption", defaultValue: BuildSettings.settingsScreenShowNotificationDecodedContentOption, storage: defaults)
var settingsScreenShowNotificationDecodedContentOption
@UserDefault(key: "settingsScreenShowNsfwRoomsOption", defaultValue: BuildSettings.settingsScreenShowNsfwRoomsOption, storage: defaults)
var settingsScreenShowNsfwRoomsOption
@UserDefault(key: "settingsSecurityScreenShowSessions", defaultValue: BuildSettings.settingsSecurityScreenShowSessions, storage: defaults)
var settingsSecurityScreenShowSessions
@UserDefault(key: "settingsSecurityScreenShowSetupBackup", defaultValue: BuildSettings.settingsSecurityScreenShowSetupBackup, storage: defaults)
var settingsSecurityScreenShowSetupBackup
@UserDefault(key: "settingsSecurityScreenShowRestoreBackup", defaultValue: BuildSettings.settingsSecurityScreenShowRestoreBackup, storage: defaults)
var settingsSecurityScreenShowRestoreBackup
@UserDefault(key: "settingsSecurityScreenShowDeleteBackup", defaultValue: BuildSettings.settingsSecurityScreenShowDeleteBackup, storage: defaults)
var settingsSecurityScreenShowDeleteBackup
@UserDefault(key: "settingsSecurityScreenShowCryptographyInfo", defaultValue: BuildSettings.settingsSecurityScreenShowCryptographyInfo, storage: defaults)
var settingsSecurityScreenShowCryptographyInfo
@UserDefault(key: "settingsSecurityScreenShowCryptographyExport", defaultValue: BuildSettings.settingsSecurityScreenShowCryptographyExport, storage: defaults)
var settingsSecurityScreenShowCryptographyExport
@UserDefault(key: "settingsSecurityScreenShowAdvancedBlacklistUnverifiedDevices", defaultValue: BuildSettings.settingsSecurityScreenShowAdvancedUnverifiedDevices, storage: defaults)
var settingsSecurityScreenShowAdvancedUnverifiedDevices
// MARK: - Room Settings Screen
@UserDefault(key: "roomSettingsScreenShowLowPriorityOption", defaultValue: BuildSettings.roomSettingsScreenShowLowPriorityOption, storage: defaults)
var roomSettingsScreenShowLowPriorityOption
@UserDefault(key: "roomSettingsScreenShowDirectChatOption", defaultValue: BuildSettings.roomSettingsScreenShowDirectChatOption, storage: defaults)
var roomSettingsScreenShowDirectChatOption
@UserDefault(key: "roomSettingsScreenAllowChangingAccessSettings", defaultValue: BuildSettings.roomSettingsScreenAllowChangingAccessSettings, storage: defaults)
var roomSettingsScreenAllowChangingAccessSettings
@UserDefault(key: "roomSettingsScreenAllowChangingHistorySettings", defaultValue: BuildSettings.roomSettingsScreenAllowChangingHistorySettings, storage: defaults)
var roomSettingsScreenAllowChangingHistorySettings
@UserDefault(key: "roomSettingsScreenShowAddressSettings", defaultValue: BuildSettings.roomSettingsScreenShowAddressSettings, storage: defaults)
var roomSettingsScreenShowAddressSettings
@UserDefault(key: "roomSettingsScreenShowFlairSettings", defaultValue: BuildSettings.roomSettingsScreenShowFlairSettings, storage: defaults)
var roomSettingsScreenShowFlairSettings
@UserDefault(key: "roomSettingsScreenShowAdvancedSettings", defaultValue: BuildSettings.roomSettingsScreenShowAdvancedSettings, storage: defaults)
var roomSettingsScreenShowAdvancedSettings
@UserDefault(key: "roomSettingsScreenAdvancedShowEncryptToVerifiedOption", defaultValue: BuildSettings.roomSettingsScreenAdvancedShowEncryptToVerifiedOption, storage: defaults)
var roomSettingsScreenAdvancedShowEncryptToVerifiedOption
// MARK: - Unified Search
@UserDefault(key: "unifiedSearchScreenShowPublicDirectory", defaultValue: BuildSettings.unifiedSearchScreenShowPublicDirectory, storage: defaults)
var unifiedSearchScreenShowPublicDirectory
// MARK: - Secrets Recovery
@UserDefault(key: "secretsRecoveryAllowReset", defaultValue: BuildSettings.secretsRecoveryAllowReset, storage: defaults)
var secretsRecoveryAllowReset
// MARK: - Beta
@UserDefault(key: "hideSpaceBetaAnnounce", defaultValue: false, storage: defaults)
var hideSpaceBetaAnnounce
@UserDefault(key: "threadsNoticeDisplayed", defaultValue: false, storage: defaults)
var threadsNoticeDisplayed
// MARK: - Version check
@UserDefault(key: "versionCheckNextDisplayDateTimeInterval", defaultValue: 0.0, storage: defaults)
var versionCheckNextDisplayDateTimeInterval
@UserDefault(key: "slideMenuRoomsCoachMessageHasBeenDisplayed", defaultValue: false, storage: defaults)
var slideMenuRoomsCoachMessageHasBeenDisplayed
// MARK: - Metrics
/// Number of spaces previously tracked by the `AnalyticsSpaceTracker` instance.
@UserDefault(key: "lastNumberOfTrackedSpaces", defaultValue: nil, storage: defaults)
var lastNumberOfTrackedSpaces: Int?
}
| apache-2.0 | 59695e175c8d7334d7b9b54c00faae8e | 48.889785 | 185 | 0.777197 | 5.224944 | false | false | false | false |
SandcastleApps/partyup | PartyUP/Dynamo.swift | 1 | 579 | //
// Dynamo.swift
// PartyUP
//
// Created by Fritz Vander Heide on 2015-09-20.
// Copyright © 2015 Sandcastle Application Development. All rights reserved.
//
import AWSDynamoDB
import AWSCore
func wrapValue<T>(value: T) -> AWSDynamoDBAttributeValue? {
var wrappedValue: AWSDynamoDBAttributeValue? = AWSDynamoDBAttributeValue()
switch value.self {
case is NSString:
wrappedValue!.S = value as? String
case is NSNumber:
wrappedValue!.N = "\(value)"
case is NSData:
wrappedValue!.B = value as? NSData
default:
wrappedValue = nil
}
return wrappedValue
}
| mit | f583807a2e4a1ecafa36beb6b3b76288 | 19.642857 | 77 | 0.726644 | 3.658228 | false | false | false | false |
kkYFL/WBSwift | YFLWBSwift/Classes/View/Home/WBHomeViewController.swift | 1 | 1760 | //
// WBHomeViewController.swift
// YFLWBSwift
//
// Created by 杨丰林 on 17/4/20.
// Copyright © 2017年 杨丰林. All rights reserved.
//
import UIKit
class WBHomeViewController: WBBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//重写
override func setUpUI() {
super.setUpUI()
//设置导航栏按钮,局限性系统的按钮没有高亮
/*
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", style: .plain, target: self, action: #selector(showFriends))
//Swift调用OC方法,返回instanceType,无法判断返回的类型
let btn: UIButton = UIButton.cz_textButton("好友", fontSize: 16, normalColor: UIColor.darkGray, highlightedColor: UIColor.orange)
btn.addTarget(self, action: #selector(showFriends), for: .touchUpInside)
*/
/*
navigationItem
不使用navigationItem:隐藏了系统nagationBar自定义了nagationBar和navagationItem:navItem,故不适用navigationItem
*/
navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontSize: 16, target: self, action: #selector(showFriends))
}
//显示好友
@objc private func showFriends() {
print(#function)
let vc = WBTestViewController()
vc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 613bed05dab140417f0bed3250f6bfa9 | 24.951613 | 136 | 0.627098 | 4.677326 | false | false | false | false |
zerovagner/Desafio-Mobfiq | desafioMobfiq/desafioMobfiq/CategoriesViewController.swift | 1 | 2879 | //
// CategoriesViewController.swift
// desafioMobfiq
//
// Created by Vagner Oliveira on 6/16/17.
// Copyright © 2017 Vagner Oliveira. All rights reserved.
//
import UIKit
class CategoriesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var categoriesTableView: UITableView!
var categoryList = [Category]()
var loadOverlay = LoadingOverlay()
override func viewDidLoad() {
super.viewDidLoad()
categoriesTableView.delegate = self
categoriesTableView.dataSource = self
loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categoryList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell") as! CategoryTableViewCell
cell.setUp(fromCategory: categoryList[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if categoryList[indexPath.row].subcategories != nil {
performSegue(withIdentifier: "subcategorySegue", sender: categoryList[indexPath.row])
tableView.deselectRow(at: indexPath, animated: false)
}
}
// 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?) {
if segue.identifier == "subcategorySegue" {
if let destination = segue.destination as? SubcategoryTableViewController {
if let baseCategory = sender as? Category {
destination.baseCategory = baseCategory
}
}
}
}
func loadData() {
loadOverlay.showOverlay(view: self.view)
fetchCategories {
(list: [Category]?) in
self.loadOverlay.hideOverlayView()
if let res = list {
self.categoryList = res
self.categoriesTableView.reloadData()
} else {
self.alertDownloadFailure()
}
}
}
func alertDownloadFailure () {
let msg = "Houve um problema ao obter os dados.\nPressione OK para tentar novamente."
let alert = UIAlertController(title: "Desafio Mobfiq", message: msg, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
self.loadData()
})
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1;
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert, animated: true, completion: nil)
}
}
| mit | 0baa35771186026dba5a43805d0056f2 | 28.979167 | 116 | 0.734885 | 4.251108 | false | false | false | false |
amosavian/FileProvider | Sources/ExtendedLocalFileProvider.swift | 2 | 25482 | //
// ExtendedLocalFileProvider.swift
// FileProvider
//
// Created by Amir Abbas Mousavian.
// Copyright © 2017 Mousavian. Distributed under MIT license.
//
#if os(macOS) || os(iOS) || os(tvOS)
import Foundation
import ImageIO
import CoreGraphics
import AVFoundation
extension LocalFileProvider: ExtendedFileProvider {
open func thumbnailOfFileSupported(path: String) -> Bool {
switch path.pathExtension.lowercased() {
case LocalFileInformationGenerator.imageThumbnailExtensions.contains:
return true
case LocalFileInformationGenerator.audioThumbnailExtensions.contains:
return true
case LocalFileInformationGenerator.videoThumbnailExtensions.contains:
return true
case LocalFileInformationGenerator.pdfThumbnailExtensions.contains:
return true
case LocalFileInformationGenerator.officeThumbnailExtensions.contains:
return true
case LocalFileInformationGenerator.customThumbnailExtensions.contains:
return true
default:
return false
}
}
open func propertiesOfFileSupported(path: String) -> Bool {
let fileExt = path.pathExtension.lowercased()
switch fileExt {
case LocalFileInformationGenerator.imagePropertiesExtensions.contains:
return LocalFileInformationGenerator.imageProperties != nil
case LocalFileInformationGenerator.audioPropertiesExtensions.contains:
return LocalFileInformationGenerator.audioProperties != nil
case LocalFileInformationGenerator.videoPropertiesExtensions.contains:
return LocalFileInformationGenerator.videoProperties != nil
case LocalFileInformationGenerator.pdfPropertiesExtensions.contains:
return LocalFileInformationGenerator.pdfProperties != nil
case LocalFileInformationGenerator.archivePropertiesExtensions.contains:
return LocalFileInformationGenerator.archiveProperties != nil
case LocalFileInformationGenerator.officePropertiesExtensions.contains:
return LocalFileInformationGenerator.officeProperties != nil
case LocalFileInformationGenerator.customPropertiesExtensions.contains:
return LocalFileInformationGenerator.customProperties != nil
default:
return false
}
}
@discardableResult
open func thumbnailOfFile(path: String, dimension: CGSize? = nil, completionHandler: @escaping ((_ image: ImageClass?, _ error: Error?) -> Void)) -> Progress? {
let dimension = dimension ?? CGSize(width: 64, height: 64)
(dispatch_queue).async {
var thumbnailImage: ImageClass? = nil
// Check cache
let fileURL = self.url(of: path)
// Create Thumbnail and cache
switch fileURL.pathExtension.lowercased() {
case LocalFileInformationGenerator.videoThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.videoThumbnail(fileURL, dimension)
case LocalFileInformationGenerator.audioThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.audioThumbnail(fileURL, dimension)
case LocalFileInformationGenerator.imageThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.imageThumbnail(fileURL, dimension)
case LocalFileInformationGenerator.pdfThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.pdfThumbnail(fileURL, dimension)
case LocalFileInformationGenerator.officeThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.officeThumbnail(fileURL, dimension)
case LocalFileInformationGenerator.customThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.customThumbnail(fileURL, dimension)
default:
completionHandler(nil, nil)
return
}
completionHandler(thumbnailImage, nil)
}
return nil
}
@discardableResult
open func propertiesOfFile(path: String, completionHandler: @escaping ((_ propertiesDictionary: [String: Any], _ keys: [String], _ error: Error?) -> Void)) -> Progress? {
(dispatch_queue).async {
let fileExt = path.pathExtension.lowercased()
var getter: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))?
switch fileExt {
case LocalFileInformationGenerator.imagePropertiesExtensions.contains:
getter = LocalFileInformationGenerator.imageProperties
case LocalFileInformationGenerator.audioPropertiesExtensions.contains:
getter = LocalFileInformationGenerator.audioProperties
case LocalFileInformationGenerator.videoPropertiesExtensions.contains:
getter = LocalFileInformationGenerator.videoProperties
case LocalFileInformationGenerator.pdfPropertiesExtensions.contains:
getter = LocalFileInformationGenerator.pdfProperties
case LocalFileInformationGenerator.archivePropertiesExtensions.contains:
getter = LocalFileInformationGenerator.archiveProperties
case LocalFileInformationGenerator.officePropertiesExtensions.contains:
getter = LocalFileInformationGenerator.officeProperties
case LocalFileInformationGenerator.customPropertiesExtensions.contains:
getter = LocalFileInformationGenerator.customProperties
default:
break
}
var dic = [String: Any]()
var keys = [String]()
if let getterMethod = getter {
(dic, keys) = getterMethod(self.url(of: path))
}
completionHandler(dic, keys, nil)
}
return nil
}
}
/// Holds supported file types and thumbnail/properties generator for specefied type of file
public struct LocalFileInformationGenerator {
/// Image extensions supportes for thumbnail.
///
/// Default: `["jpg", "jpeg", "gif", "bmp", "png", "tif", "tiff", "ico"]`
static public var imageThumbnailExtensions: [String] = ["heic", "jpg", "jpeg", "gif", "bmp", "png", "tif", "tiff", "ico"]
/// Audio and music extensions supportes for thumbnail.
///
/// Default: `["mp1", "mp2", "mp3", "mpa", "mpga", "m1a", "m2a", "m4a", "m4b", "m4p", "m4r", "aac", "snd", "caf", "aa", "aax", "adts", "aif", "aifc", "aiff", "au", "flac", "amr", "wav", "wave", "bwf", "ac3", "eac3", "ec3", "cdda"]`
static public var audioThumbnailExtensions: [String] = ["mp1", "mp2", "mp3", "mpa", "mpga", "m1a", "m2a", "m4a", "m4b", "m4p", "m4r", "aac", "snd", "caf", "aa", "aax", "adts", "aif", "aifc", "aiff", "au", "flac", "amr", "wav", "wave", "bwf", "ac3", "eac3", "ec3", "cdda"]
/// Video extensions supportes for thumbnail.
///
/// Default: `["mov", "mp4", "mpg4", "m4v", "mqv", "mpg", "mpeg", "avi", "vfw", "3g2", "3gp", "3gp2", "3gpp", "qt"]`
static public var videoThumbnailExtensions: [String] = ["mov", "mp4", "mpg4", "m4v", "mqv", "mpg", "mpeg", "avi", "vfw", "3g2", "3gp", "3gp2", "3gpp", "qt"]
/// Portable document file extensions supportes for thumbnail.
///
/// Default: `["pdf"]`
static public var pdfThumbnailExtensions: [String] = ["pdf"]
/// Office document extensions supportes for thumbnail.
///
/// Default: `empty`
static public var officeThumbnailExtensions: [String] = []
/// Custom document extensions supportes for thumbnail.
///
/// Default: `empty`
static public var customThumbnailExtensions: [String] = []
/// Image extensions supportes for properties.
///
/// Default: `["jpg", "jpeg", "gif", "bmp", "png", "tif", "tiff"]`
static public var imagePropertiesExtensions: [String] = ["heic", "jpg", "jpeg", "bmp", "gif", "png", "tif", "tiff"]
/// Audio and music extensions supportes for properties.
///
/// Default: `["mp1", "mp2", "mp3", "mpa", "mpga", "m1a", "m2a", "m4a", "m4b", "m4p", "m4r", "aac", "snd", "caf", "aa", "aax", "adts", "aif", "aifc", "aiff", "au", "flac", "amr", "wav", "wave", "bwf", "ac3", "eac3", "ec3", "cdda"]`
static public var audioPropertiesExtensions: [String] = ["mp1", "mp2", "mp3", "mpa", "mpga", "m1a", "m2a", "m4a", "m4b", "m4p", "m4r", "aac", "snd", "caf", "aa", "aax", "adts", "aif", "aifc", "aiff", "au", "flac", "amr", "wav", "wave", "bwf", "ac3", "eac3", "ec3", "cdda"]
/// Video extensions supportes for properties.
///
/// Default: `["mov", "mp4", "mpg4", "m4v", "mqv", "mpg", "mpeg", "avi", "vfw", "3g2", "3gp", "3gp2", "3gpp", "qt"]`
static public var videoPropertiesExtensions: [String] = ["mov", "mp4", "mpg4", "m4v", "mqv", "mpg", "mpeg", "avi", "vfw", "3g2", "3gp", "3gp2", "3gpp", "qt"]
/// Portable document file extensions supportes for properties.
///
/// Default: `["pdf"]`
static public var pdfPropertiesExtensions: [String] = ["pdf"]
/// Archive extensions (like zip) supportes for properties.
///
/// Default: `empty`
static public var archivePropertiesExtensions: [String] = []
/// Office document extensions supportes for properties.
///
/// Default: `empty`
static public var officePropertiesExtensions: [String] = []
/// Custom document extensions supportes for properties.
///
/// Default: `empty`
static public var customPropertiesExtensions: [String] = []
/// Thumbnail generator closure for image files.
static public var imageThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
return LocalFileProvider.scaleDown(fileURL: fileURL, toSize: dimension)
}
/// Thumbnail generator closure for audio and music files.
static public var audioThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
let playerItem = AVPlayerItem(url: fileURL)
let metadataList = playerItem.asset.commonMetadata
let commonKeyArtwork = AVMetadataKey.commonKeyArtwork
for item in metadataList {
if item.commonKey == commonKeyArtwork {
if let data = item.dataValue {
return LocalFileProvider.scaleDown(data: data, toSize: dimension)
}
}
}
return nil
}
/// Thumbnail generator closure for video files.
static public var videoThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
let asset = AVAsset(url: fileURL)
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.maximumSize = dimension ?? .zero
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTime(value: asset.duration.value / 3, timescale: asset.duration.timescale)
if let cgImage = try? assetImgGenerate.copyCGImage(at: time, actualTime: nil) {
#if os(macOS)
return ImageClass(cgImage: cgImage, size: .zero)
#else
return ImageClass(cgImage: cgImage)
#endif
}
return nil
}
/// Thumbnail generator closure for portable document files files.
static public var pdfThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
return LocalFileProvider.convertToImage(pdfURL: fileURL, maxSize: dimension)
}
/// Thumbnail generator closure for office document files.
/// - Note: No default implementation is avaiable
static public var officeThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
return nil
}
/// Thumbnail generator closure for custom type of files.
/// - Note: No default implementation is avaiable
static public var customThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
return nil
}
/// Properties generator closure for image files.
static public var imageProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = { fileURL in
var dic = [String: Any]()
var keys = [String]()
func add(key: String, value: Any?) {
if let value = value, !((value as? String)?.isEmpty ?? false) {
keys.append(key)
dic[key] = value
}
}
func simplify(_ top:Int64, _ bottom:Int64) -> (newTop:Int, newBottom:Int) {
var x = top
var y = bottom
while (y != 0) {
let buffer = y
y = x % y
x = buffer
}
let hcfVal = x
let newTopVal = top/hcfVal
let newBottomVal = bottom/hcfVal
return(Int(newTopVal), Int(newBottomVal))
}
guard let source = CGImageSourceCreateWithURL(fileURL as CFURL, nil), let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as NSDictionary? else {
return (dic, keys)
}
let tiffDict = properties[kCGImagePropertyTIFFDictionary as String] as? NSDictionary ?? [:]
let exifDict = properties[kCGImagePropertyExifDictionary as String] as? NSDictionary ?? [:]
let gpsDict = properties[kCGImagePropertyGPSDictionary as String] as? NSDictionary ?? [:]
if let pixelWidth = properties.object(forKey: kCGImagePropertyPixelWidth) as? NSNumber, let pixelHeight = properties.object(forKey: kCGImagePropertyPixelHeight) as? NSNumber {
add(key: "Dimensions", value: "\(pixelWidth)x\(pixelHeight)")
}
add(key: "DPI", value: properties[kCGImagePropertyDPIWidth as String])
add(key: "Device maker", value: tiffDict[kCGImagePropertyTIFFMake as String])
add(key: "Device model", value: tiffDict[kCGImagePropertyTIFFModel as String])
add(key: "Lens model", value: exifDict[kCGImagePropertyExifLensModel as String])
add(key: "Artist", value: tiffDict[kCGImagePropertyTIFFArtist as String] as? String)
add(key: "Copyright", value: tiffDict[kCGImagePropertyTIFFCopyright as String] as? String)
add(key: "Date taken", value: tiffDict[kCGImagePropertyTIFFDateTime as String] as? String)
if let latitude = gpsDict[kCGImagePropertyGPSLatitude as String] as? NSNumber,
let longitude = gpsDict[kCGImagePropertyGPSLongitude as String] as? NSNumber {
let altitudeDesc = (gpsDict[kCGImagePropertyGPSAltitude as String] as? NSNumber).map({ " at \($0.format(precision: 0))m" }) ?? ""
add(key: "Location", value: "\(latitude.format()), \(longitude.format())\(altitudeDesc)")
}
add(key: "Area", value: gpsDict[kCGImagePropertyGPSAreaInformation as String])
add(key: "Color space", value: properties[kCGImagePropertyColorModel as String])
add(key: "Color depth", value: (properties[kCGImagePropertyDepth as String] as? NSNumber).map({ "\($0) bits" }))
add(key: "Color profile", value: properties[kCGImagePropertyProfileName as String])
add(key: "Focal length", value: exifDict[kCGImagePropertyExifFocalLength as String])
add(key: "White banance", value: exifDict[kCGImagePropertyExifWhiteBalance as String])
add(key: "F number", value: exifDict[kCGImagePropertyExifFNumber as String])
add(key: "Exposure program", value: exifDict[kCGImagePropertyExifExposureProgram as String])
if let exp = exifDict[kCGImagePropertyExifExposureTime as String] as? NSNumber {
let expfrac = simplify(Int64(exp.doubleValue * 1_163_962_800_000), 1_163_962_800_000)
add(key: "Exposure time", value: "\(expfrac.newTop)/\(expfrac.newBottom)")
}
add(key: "ISO speed", value: (exifDict[kCGImagePropertyExifISOSpeedRatings as String] as? [NSNumber])?.first)
return (dic, keys)
}
/// Properties generator closure for audio and music files.
static var audioProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = { fileURL in
var dic = [String: Any]()
var keys = [String]()
func add(key: String, value: Any?) {
if let value = value {
keys.append(key)
dic[key] = value
}
}
func makeKeyDescription(_ key: String?) -> String? {
guard let key = key else {
return nil
}
guard let regex = try? NSRegularExpression(pattern: "([a-z])([A-Z])" , options: []) else {
return nil
}
let newKey = regex.stringByReplacingMatches(in: key, options: [], range: NSRange(location: 0, length: (key as NSString).length) , withTemplate: "$1 $2")
return newKey.capitalized
}
func parseLocationData(_ value: String) -> (latitude: Double, longitude: Double, height: Double?)? {
let scanner = Scanner.init(string: value)
var latitude: Double = 0.0, longitude: Double = 0.0, height: Double = 0
if scanner.scanDouble(&latitude), scanner.scanDouble(&longitude) {
scanner.scanDouble(&height)
return (latitude, longitude, height)
} else {
return nil
}
}
guard fileURL.fileExists else {
return (dic, keys)
}
let playerItem = AVPlayerItem(url: fileURL)
let metadataList = playerItem.asset.commonMetadata
for item in metadataList {
let commonKey = item.commonKey?.rawValue
if let key = makeKeyDescription(commonKey) {
if commonKey == "location", let value = item.stringValue, let loc = parseLocationData(value) {
keys.append(key)
let heightStr: String = (loc.height as NSNumber?).map({ ", \($0.format(precision: 0))m" }) ?? ""
dic[key] = "\((loc.latitude as NSNumber).format())°, \((loc.longitude as NSNumber).format())°\(heightStr)"
} else if let value = item.dateValue {
keys.append(key)
dic[key] = value
} else if let value = item.numberValue {
keys.append(key)
dic[key] = value
} else if let value = item.stringValue {
keys.append(key)
dic[key] = value
}
}
}
if let ap = try? AVAudioPlayer(contentsOf: fileURL) {
add(key: "Duration", value: ap.duration.formatshort)
add(key: "Bitrate", value: ap.settings[AVSampleRateKey] as? Int)
}
return (dic, keys)
}
/// Properties generator closure for video files.
static public var videoProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = { fileURL in
var dic = [String: Any]()
var keys = [String]()
func add(key: String, value: Any?) {
if let value = value {
keys.append(key)
dic[key] = value
}
}
if let audioprops = LocalFileInformationGenerator.audioProperties?(fileURL) {
dic = audioprops.prop
keys = audioprops.keys
dic.removeValue(forKey: "Duration")
if let index = keys.firstIndex(of: "Duration") {
keys.remove(at: index)
}
}
let asset = AVURLAsset(url: fileURL, options: nil)
let videoTracks = asset.tracks(withMediaType: AVMediaType.video)
if let videoTrack = videoTracks.first {
var bitrate: Float = 0
let width = Int(videoTrack.naturalSize.width)
let height = Int(videoTrack.naturalSize.height)
add(key: "Dimensions", value: "\(width)x\(height)")
var duration: Int64 = 0
for track in videoTracks {
duration += track.timeRange.duration.timescale > 0 ? track.timeRange.duration.value / Int64(track.timeRange.duration.timescale) : 0
bitrate += track.estimatedDataRate
}
add(key: "Duration", value: TimeInterval(duration).formatshort)
add(key: "Video Bitrate", value: "\(Int(ceil(bitrate / 1000))) kbps")
}
let audioTracks = asset.tracks(withMediaType: AVMediaType.audio)
// dic["Audio channels"] = audioTracks.count
var bitrate: Float = 0
for track in audioTracks {
bitrate += track.estimatedDataRate
}
add(key: "Audio Bitrate", value: "\(Int(ceil(bitrate / 1000))) kbps")
return (dic, keys)
}
/// Properties generator closure for protable documents files.
static public var pdfProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = { fileURL in
var dic = [String: Any]()
var keys = [String]()
func add(key: String, value: Any?) {
if let value = value, !((value as? String)?.isEmpty ?? false) {
keys.append(key)
dic[key] = value
}
}
func getKey(_ key: String, from dict: CGPDFDictionaryRef) -> String? {
var cfStrValue: CGPDFStringRef?
if (CGPDFDictionaryGetString(dict, key, &cfStrValue)), let value = cfStrValue.flatMap({ CGPDFStringCopyTextString($0) }) {
return value as String
}
var cfArrayValue: CGPDFArrayRef?
if (CGPDFDictionaryGetArray(dict, key, &cfArrayValue)), let cfArray = cfArrayValue {
var array = [String]()
for i in 0..<CGPDFArrayGetCount(cfArray) {
var cfItemValue: CGPDFStringRef?
if CGPDFArrayGetString(cfArray, i, &cfItemValue), let item = cfItemValue.flatMap({ CGPDFStringCopyTextString($0) }) {
array.append(item as String)
}
}
return array.joined(separator: ", ")
}
return nil
}
func convertDate(_ date: String?) -> Date? {
guard let date = date else { return nil }
let dateStr = date.replacingOccurrences(of: "'", with: "").replacingOccurrences(of: "D:", with: "", options: .anchored)
let dateFormatter = DateFormatter()
let formats: [String] = ["yyyyMMddHHmmssTZ", "yyyyMMddHHmmssZZZZZ", "yyyyMMddHHmmssZ", "yyyyMMddHHmmss"]
for format in formats {
dateFormatter.dateFormat = format
if let result = dateFormatter.date(from: dateStr) {
return result
}
}
return nil
}
guard let provider = CGDataProvider(url: fileURL as CFURL), let reference = CGPDFDocument(provider), let dict = reference.info else {
return (dic, keys)
}
add(key: "Title", value: getKey("Title", from: dict))
add(key: "Author", value: getKey("Author", from: dict))
add(key: "Subject", value: getKey("Subject", from: dict))
add(key: "Producer", value: getKey("Producer", from: dict))
add(key: "Keywords", value: getKey("Keywords", from: dict))
var majorVersion: Int32 = 0
var minorVersion: Int32 = 0
reference.getVersion(majorVersion: &majorVersion, minorVersion: &minorVersion)
if majorVersion > 0 {
add(key: "Version", value: String(majorVersion) + "." + String(minorVersion))
}
add(key: "Pages", value: reference.numberOfPages)
if reference.numberOfPages > 0, let pageRef = reference.page(at: 1) {
let size = pageRef.getBoxRect(CGPDFBox.mediaBox).size
add(key: "Resolution", value: "\(Int(size.width))x\(Int(size.height))")
}
add(key: "Content creator", value: getKey("Creator", from: dict))
add(key: "Creation date", value: convertDate(getKey("CreationDate", from: dict)))
add(key: "Modified date", value: convertDate(getKey("ModDate", from: dict)))
add(key: "Security", value: reference.isEncrypted ? (reference.isUnlocked ? "Present" : "Password Protected") : "None")
add(key: "Allows printing", value: reference.allowsPrinting)
add(key: "Allows copying", value: reference.allowsCopying)
return (dic, keys)
}
/// Properties generator closure for video files.
/// - Note: No default implementation is avaiable
static public var archiveProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = nil
/// Properties generator closure for office doument files.
/// - Note: No default implementation is avaiable
static public var officeProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = nil
/// Properties generator closure for custom type of files.
/// - Note: No default implementation is avaiable
static public var customProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = nil
}
#endif
| mit | 9da112a3a32842394e22325f69c3e6fe | 48.861057 | 278 | 0.609796 | 4.472354 | false | false | false | false |
ayushn21/AvatarImageView | Example Project/AvatarImageViewExample/AvatarImageExampleData.swift | 1 | 885 | //
// AvatarImageExampleData.swift
// AvatarImageViewExample
//
// Created by Ayush Newatia on 12/08/2016.
// Copyright © 2016 Spectrum. All rights reserved.
//
import Foundation
import AvatarImageView
struct ExampleData: AvatarImageViewDataSource {
var name: String
var avatar: UIImage?
init() {
name = ExampleData.randomName()
}
static func randomName() -> String {
let charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
let charSetArray = charSet.map { String($0) }
var string = ""
for _ in 0..<5 {
string += charSetArray[Int(arc4random()) % charSetArray.count]
}
string += " "
for _ in 0..<5 {
string += charSetArray[Int(arc4random()) % charSetArray.count]
}
return string
}
}
| mit | bd17bf2ddd2565e57bf037b4719af4e0 | 22.263158 | 76 | 0.579186 | 4.580311 | false | false | false | false |
kalvish21/AndroidMessenger | AndroidMessengerMacDesktopClient/Pods/Swifter/Sources/HttpServerIO.swift | 1 | 6294 | //
// HttpServer.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Foundation
#endif
public class HttpServerIO {
private var listenSocket: Socket = Socket(socketFileDescriptor: -1)
private var clientSockets: Set<Socket> = []
private let clientSocketsLock = NSLock()
public func start(listenPort: in_port_t = 8080, forceIPv4: Bool = false, priority: Int = DISPATCH_QUEUE_PRIORITY_BACKGROUND) throws {
stop()
listenSocket = try Socket.tcpSocketForListen(listenPort, forceIPv4: forceIPv4)
dispatch_async(dispatch_get_global_queue(priority, 0)) {
while let socket = try? self.listenSocket.acceptClientSocket() {
self.lock(self.clientSocketsLock) {
self.clientSockets.insert(socket)
}
dispatch_async(dispatch_get_global_queue(priority, 0), {
self.handleConnection(socket)
self.lock(self.clientSocketsLock) {
self.clientSockets.remove(socket)
}
})
}
self.stop()
}
}
public func stop() {
listenSocket.release()
lock(self.clientSocketsLock) {
for socket in self.clientSockets {
socket.shutdwn()
}
self.clientSockets.removeAll(keepCapacity: true)
}
}
public func dispatch(request: HttpRequest) -> ([String: String], HttpRequest -> HttpResponse) {
return ([:], { _ in HttpResponse.NotFound })
}
private func handleConnection(socket: Socket) {
let address = try? socket.peername()
let parser = HttpParser()
while let request = try? parser.readHttpRequest(socket) {
let request = request
let (params, handler) = self.dispatch(request)
request.address = address
request.params = params;
let response = handler(request)
var keepConnection = parser.supportsKeepAlive(request.headers)
do {
keepConnection = try self.respond(socket, response: response, keepAlive: keepConnection)
} catch {
print("Failed to send response: \(error)")
break
}
if let session = response.socketSession() {
session(socket)
break
}
if !keepConnection { break }
}
socket.release()
}
private func lock(handle: NSLock, closure: () -> ()) {
handle.lock()
closure()
handle.unlock();
}
private struct InnerWriteContext: HttpResponseBodyWriter {
let socket: Socket
func write(file: File) {
var offset: off_t = 0
let _ = sendfile(fileno(file.pointer), socket.socketFileDescriptor, 0, &offset, nil, 0)
}
func write(data: [UInt8]) {
write(ArraySlice(data))
}
func write(data: ArraySlice<UInt8>) {
do {
try socket.writeUInt8(data)
} catch {
print("\(error)")
}
}
}
private func respond(socket: Socket, response: HttpResponse, keepAlive: Bool) throws -> Bool {
try socket.writeUTF8("HTTP/1.1 \(response.statusCode()) \(response.reasonPhrase())\r\n")
let content = response.content()
if content.length >= 0 {
try socket.writeUTF8("Content-Length: \(content.length)\r\n")
}
if keepAlive && content.length != -1 {
try socket.writeUTF8("Connection: keep-alive\r\n")
}
for (name, value) in response.headers() {
try socket.writeUTF8("\(name): \(value)\r\n")
}
try socket.writeUTF8("\r\n")
if let writeClosure = content.write {
let context = InnerWriteContext(socket: socket)
try writeClosure(context)
}
return keepAlive && content.length != -1;
}
}
#if os(Linux)
import Glibc
struct sf_hdtr { }
func sendfile(source: Int32, _ target: Int32, _: off_t, _: UnsafeMutablePointer<off_t>, _: UnsafeMutablePointer<sf_hdtr>, _: Int32) -> Int32 {
var buffer = [UInt8](count: 1024, repeatedValue: 0)
while true {
let readResult = read(source, &buffer, buffer.count)
guard readResult > 0 else {
return Int32(readResult)
}
var writeCounter = 0
while writeCounter < readResult {
let writeResult = write(target, &buffer + writeCounter, readResult - writeCounter)
guard writeResult > 0 else {
return Int32(writeResult)
}
writeCounter = writeCounter + writeResult
}
}
}
public class NSLock {
private var mutex = pthread_mutex_t()
init() { pthread_mutex_init(&mutex, nil) }
public func lock() { pthread_mutex_lock(&mutex) }
public func unlock() { pthread_mutex_unlock(&mutex) }
deinit { pthread_mutex_destroy(&mutex) }
}
let DISPATCH_QUEUE_PRIORITY_BACKGROUND = 0
private class dispatch_context {
let block: ((Void) -> Void)
init(_ block: ((Void) -> Void)) {
self.block = block
}
}
func dispatch_get_global_queue(queueId: Int, _ arg: Int) -> Int { return 0 }
func dispatch_async(queueId: Int, _ block: ((Void) -> Void)) {
let unmanagedDispatchContext = Unmanaged.passRetained(dispatch_context(block))
let context = UnsafeMutablePointer<Void>(unmanagedDispatchContext.toOpaque())
var pthread: pthread_t = 0
pthread_create(&pthread, nil, { (context: UnsafeMutablePointer<Void>) -> UnsafeMutablePointer<Void> in
let unmanaged = Unmanaged<dispatch_context>.fromOpaque(COpaquePointer(context))
unmanaged.takeUnretainedValue().block()
unmanaged.release()
return context
}, context)
}
#endif
| mit | 7caf4adc0e81230e1c95336f1fe465fd | 31.438144 | 146 | 0.552201 | 4.661481 | false | false | false | false |
vl4298/mah-income | Mah Income/Mah Income/Workers/Reason/ReasonWorker.swift | 1 | 1142 | //
// ReasonWorker.swift
// Mah Income
//
// Created by Van Luu on 4/30/17.
// Copyright © 2017 Van Luu. All rights reserved.
//
import Foundation
import RealmSwift
class ReasonWorker {
var helper: ReasonHelper!
init?() {
do {
try helper = ReasonHelper()
} catch {
return nil
}
}
func insertReason(title: String, comment: String? = nil) -> MahError? {
// TODO: add extension to filter name
let finalName = title.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if finalName == "" {
return MahError.cannotInsert
}
let reason = ReasonModel()
reason.title = title
reason.comment = comment
return helper.insertReason(reason)
}
// func updateReason(reason: Reason, name: String) -> MahError? {
// // TODO: filter Name
// let finalName = name
//
// return helper.updateCategory(category, name: finalName)
// }
// func deleteCategory(category: CategoryModel) -> MahError? {
// return helper.deleteCategory(category)
// }
func getAllReason() -> Results<ReasonModel> {
return helper.getAllReason()
}
}
| mit | 69d981167186d6f3bb43ecee99f2e7cb | 20.528302 | 85 | 0.63979 | 3.828859 | false | false | false | false |
apple/swift-corelibs-foundation | Tests/Foundation/Tests/TestNSNumber.swift | 1 | 85955 | // 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
//
class TestNSNumber : XCTestCase {
static var allTests: [(String, (TestNSNumber) -> () throws -> Void)] {
return [
("test_NumberWithBool", test_NumberWithBool ),
("test_CFBoolean", test_CFBoolean ),
("test_numberWithChar", test_numberWithChar ),
("test_numberWithUnsignedChar", test_numberWithUnsignedChar ),
("test_numberWithShort", test_numberWithShort ),
("test_numberWithUnsignedShort", test_numberWithUnsignedShort ),
("test_numberWithLong", test_numberWithLong ),
("test_numberWithUnsignedLong", test_numberWithUnsignedLong ),
("test_numberWithLongLong", test_numberWithLongLong ),
("test_numberWithUnsignedLongLong", test_numberWithUnsignedLongLong ),
("test_numberWithInt", test_numberWithInt ),
("test_numberWithUInt", test_numberWithUInt ),
("test_numberWithFloat", test_numberWithFloat ),
("test_numberWithDouble", test_numberWithDouble ),
("test_compareNumberWithBool", test_compareNumberWithBool ),
("test_compareNumberWithChar", test_compareNumberWithChar ),
("test_compareNumberWithUnsignedChar", test_compareNumberWithUnsignedChar ),
("test_compareNumberWithShort", test_compareNumberWithShort ),
("test_compareNumberWithFloat", test_compareNumberWithFloat ),
("test_compareNumberWithDouble", test_compareNumberWithDouble ),
("test_description", test_description ),
("test_descriptionWithLocale", test_descriptionWithLocale ),
("test_objCType", test_objCType ),
("test_stringValue", test_stringValue),
("test_Equals", test_Equals),
("test_boolValue", test_boolValue),
("test_hash", test_hash),
]
}
func test_NumberWithBool() {
XCTAssertEqual(NSNumber(value: true).boolValue, true)
XCTAssertEqual(NSNumber(value: true).int8Value, Int8(1))
XCTAssertEqual(NSNumber(value: true).uint8Value, UInt8(1))
XCTAssertEqual(NSNumber(value: true).int16Value, Int16(1))
XCTAssertEqual(NSNumber(value: true).uint16Value, UInt16(1))
XCTAssertEqual(NSNumber(value: true).int32Value, Int32(1))
XCTAssertEqual(NSNumber(value: true).uint32Value, UInt32(1))
XCTAssertEqual(NSNumber(value: true).int64Value, Int64(1))
XCTAssertEqual(NSNumber(value: true).uint64Value, UInt64(1))
XCTAssertEqual(NSNumber(value: true).floatValue, Float(1))
XCTAssertEqual(NSNumber(value: true).doubleValue, Double(1))
XCTAssertEqual(NSNumber(value: false).boolValue, false)
XCTAssertEqual(NSNumber(value: false).int8Value, Int8(0))
XCTAssertEqual(NSNumber(value: false).uint8Value, UInt8(0))
XCTAssertEqual(NSNumber(value: false).int16Value, Int16(0))
XCTAssertEqual(NSNumber(value: false).uint16Value, UInt16(0))
XCTAssertEqual(NSNumber(value: false).int32Value, Int32(0))
XCTAssertEqual(NSNumber(value: false).uint32Value, UInt32(0))
XCTAssertEqual(NSNumber(value: false).int64Value, Int64(0))
XCTAssertEqual(NSNumber(value: false).uint64Value, UInt64(0))
XCTAssertEqual(NSNumber(value: false).floatValue, Float(0))
XCTAssertEqual(NSNumber(value: false).doubleValue, Double(0))
}
func test_CFBoolean() {
guard let plist = try? PropertyListSerialization.data(fromPropertyList: ["test" : true], format: .binary, options: 0) else {
XCTFail()
return
}
guard let obj = (try? PropertyListSerialization.propertyList(from: plist, format: nil)) as? [String : Any] else {
XCTFail()
return
}
guard let value = obj["test"] else {
XCTFail()
return
}
guard let boolValue = value as? Bool else {
XCTFail("Expected de-serialization as round-trip boolean value")
return
}
XCTAssertTrue(boolValue)
}
func test_numberWithChar() {
XCTAssertEqual(NSNumber(value: Int8(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: Int8(0)).int8Value, Int8(0))
XCTAssertEqual(NSNumber(value: Int8(0)).uint8Value, UInt8(0))
XCTAssertEqual(NSNumber(value: Int8(0)).int16Value, Int16(0))
XCTAssertEqual(NSNumber(value: Int8(0)).uint16Value, UInt16(0))
XCTAssertEqual(NSNumber(value: Int8(0)).int32Value, Int32(0))
XCTAssertEqual(NSNumber(value: Int8(0)).uint32Value, UInt32(0))
XCTAssertEqual(NSNumber(value: Int8(0)).int64Value, Int64(0))
XCTAssertEqual(NSNumber(value: Int8(0)).uint64Value, UInt64(0))
XCTAssertEqual(NSNumber(value: Int8(-37)).boolValue, true)
XCTAssertEqual(NSNumber(value: Int8(-37)).int8Value, Int8(-37))
#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
// Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
XCTAssertEqual(NSNumber(value: Int8(-37)).int16Value, Int16(-37))
XCTAssertEqual(NSNumber(value: Int8(-37)).int32Value, Int32(-37))
XCTAssertEqual(NSNumber(value: Int8(-37)).int64Value, Int64(-37))
#endif
XCTAssertEqual(NSNumber(value: Int8(42)).boolValue, true)
XCTAssertEqual(NSNumber(value: Int8(42)).int8Value, Int8(42))
XCTAssertEqual(NSNumber(value: Int8(42)).uint8Value, UInt8(42))
XCTAssertEqual(NSNumber(value: Int8(42)).int16Value, Int16(42))
XCTAssertEqual(NSNumber(value: Int8(42)).uint16Value, UInt16(42))
XCTAssertEqual(NSNumber(value: Int8(42)).int32Value, Int32(42))
XCTAssertEqual(NSNumber(value: Int8(42)).uint32Value, UInt32(42))
XCTAssertEqual(NSNumber(value: Int8(42)).int64Value, Int64(42))
XCTAssertEqual(NSNumber(value: Int8(42)).uint64Value, UInt64(42))
XCTAssertEqual(NSNumber(value: Int8.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int8.max).int8Value, Int8(Int8.max))
XCTAssertEqual(NSNumber(value: Int8.max).uint8Value, UInt8(Int8.max))
XCTAssertEqual(NSNumber(value: Int8.max).int16Value, Int16(Int8.max))
XCTAssertEqual(NSNumber(value: Int8.max).uint16Value, UInt16(Int8.max))
XCTAssertEqual(NSNumber(value: Int8.max).int32Value, Int32(Int8.max))
XCTAssertEqual(NSNumber(value: Int8.max).uint32Value, UInt32(Int8.max))
XCTAssertEqual(NSNumber(value: Int8.max).int64Value, Int64(Int8.max))
XCTAssertEqual(NSNumber(value: Int8.max).uint64Value, UInt64(Int8.max))
XCTAssertEqual(NSNumber(value: Int8.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int8.min).int8Value, Int8(Int8.min))
#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
// Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
XCTAssertEqual(NSNumber(value: Int8.min).int16Value, Int16(Int8.min))
XCTAssertEqual(NSNumber(value: Int8.min).int32Value, Int32(Int8.min))
XCTAssertEqual(NSNumber(value: Int8.min).int64Value, Int64(Int8.min))
#endif
XCTAssertEqual(NSNumber(value: Int8(0)).floatValue, Float(0))
#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
// Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
XCTAssertEqual(NSNumber(value: Int8(-37)).floatValue, Float(-37))
#endif
XCTAssertEqual(NSNumber(value: Int8(42)).floatValue, Float(42))
XCTAssertEqual(NSNumber(value: Int8.max).floatValue, Float(Int8.max))
#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
// Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
XCTAssertEqual(NSNumber(value: Int8.min).floatValue, Float(Int8.min))
#endif
XCTAssertEqual(NSNumber(value: Int8(0)).doubleValue, Double(0))
#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
// Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
XCTAssertEqual(NSNumber(value: Int8(-37)).doubleValue, Double(-37))
#endif
XCTAssertEqual(NSNumber(value: Int8(42)).doubleValue, Double(42))
XCTAssertEqual(NSNumber(value: Int8.max).doubleValue, Double(Int8.max))
#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
// Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
XCTAssertEqual(NSNumber(value: Int8.min).doubleValue, Double(Int8.min))
#endif
}
func test_numberWithUnsignedChar() {
XCTAssertEqual(NSNumber(value: UInt8(42)).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt8(42)).int8Value, Int8(42))
XCTAssertEqual(NSNumber(value: UInt8(42)).uint8Value, UInt8(42))
XCTAssertEqual(NSNumber(value: UInt8(42)).int16Value, Int16(42))
XCTAssertEqual(NSNumber(value: UInt8(42)).uint16Value, UInt16(42))
XCTAssertEqual(NSNumber(value: UInt8(42)).int32Value, Int32(42))
XCTAssertEqual(NSNumber(value: UInt8(42)).uint32Value, UInt32(42))
XCTAssertEqual(NSNumber(value: UInt8(42)).int64Value, Int64(42))
XCTAssertEqual(NSNumber(value: UInt8(42)).uint64Value, UInt64(42))
XCTAssertEqual(NSNumber(value: UInt8(42)).floatValue, Float(42))
XCTAssertEqual(NSNumber(value: UInt8(42)).doubleValue, Double(42))
XCTAssertEqual(NSNumber(value: UInt8.min).boolValue, false)
XCTAssertEqual(NSNumber(value: UInt8.min).int8Value, Int8(UInt8.min))
XCTAssertEqual(NSNumber(value: UInt8.min).int16Value, Int16(UInt8.min))
XCTAssertEqual(NSNumber(value: UInt8.min).int32Value, Int32(UInt8.min))
XCTAssertEqual(NSNumber(value: UInt8.min).int64Value, Int64(UInt8.min))
XCTAssertEqual(NSNumber(value: UInt8.min).floatValue, Float(UInt8.min))
XCTAssertEqual(NSNumber(value: UInt8.min).doubleValue, Double(UInt8.min))
//--------
XCTAssertEqual(NSNumber(value: UInt8(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: UInt8(0)).int8Value, 0)
XCTAssertEqual(NSNumber(value: UInt8(0)).int16Value, 0)
XCTAssertEqual(NSNumber(value: UInt8(0)).int32Value, 0)
XCTAssertEqual(NSNumber(value: UInt8(0)).int64Value, 0)
XCTAssertEqual(NSNumber(value: UInt8(0)).uint8Value, 0)
XCTAssertEqual(NSNumber(value: UInt8(0)).uint16Value, 0)
XCTAssertEqual(NSNumber(value: UInt8(0)).uint32Value, 0)
XCTAssertEqual(NSNumber(value: UInt8(0)).uint64Value, 0)
XCTAssertEqual(NSNumber(value: UInt8(0)).intValue, 0)
XCTAssertEqual(NSNumber(value: UInt8(0)).uintValue, 0)
XCTAssertEqual(NSNumber(value: UInt8(0)).floatValue, 0)
XCTAssertEqual(NSNumber(value: UInt8(0)).doubleValue, 0)
//------
XCTAssertEqual(NSNumber(value: UInt8.max).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt8.max).int8Value, -1)
XCTAssertEqual(NSNumber(value: UInt8.max).int16Value, 255)
XCTAssertEqual(NSNumber(value: UInt8.max).int32Value, 255)
XCTAssertEqual(NSNumber(value: UInt8.max).int64Value, 255)
XCTAssertEqual(NSNumber(value: UInt8.max).uint8Value, 255)
XCTAssertEqual(NSNumber(value: UInt8.max).uint16Value, 255)
XCTAssertEqual(NSNumber(value: UInt8.max).uint32Value, 255)
XCTAssertEqual(NSNumber(value: UInt8.max).uint64Value, 255)
XCTAssertEqual(NSNumber(value: UInt8.max).intValue, 255)
XCTAssertEqual(NSNumber(value: UInt8.max).uintValue, 255)
XCTAssertEqual(NSNumber(value: UInt8.max).floatValue, Float(UInt8.max))
XCTAssertEqual(NSNumber(value: UInt8.max).doubleValue, Double(UInt8.max))
}
func test_numberWithShort() {
XCTAssertEqual(NSNumber(value: Int16(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: Int16(0)).int8Value, Int8(0))
XCTAssertEqual(NSNumber(value: Int16(0)).uint8Value, UInt8(0))
XCTAssertEqual(NSNumber(value: Int16(0)).int16Value, Int16(0))
XCTAssertEqual(NSNumber(value: Int16(0)).uint16Value, UInt16(0))
XCTAssertEqual(NSNumber(value: Int16(0)).int32Value, Int32(0))
XCTAssertEqual(NSNumber(value: Int16(0)).uint32Value, UInt32(0))
XCTAssertEqual(NSNumber(value: Int16(0)).int64Value, Int64(0))
XCTAssertEqual(NSNumber(value: Int16(0)).uint64Value, UInt64(0))
XCTAssertEqual(NSNumber(value: Int16(-37)).boolValue, true)
XCTAssertEqual(NSNumber(value: Int16(-37)).int8Value, Int8(-37))
XCTAssertEqual(NSNumber(value: Int16(-37)).int16Value, Int16(-37))
XCTAssertEqual(NSNumber(value: Int16(-37)).int32Value, Int32(-37))
XCTAssertEqual(NSNumber(value: Int16(-37)).int64Value, Int64(-37))
XCTAssertEqual(NSNumber(value: Int16(42)).boolValue, true)
XCTAssertEqual(NSNumber(value: Int16(42)).int8Value, Int8(42))
XCTAssertEqual(NSNumber(value: Int16(42)).uint8Value, UInt8(42))
XCTAssertEqual(NSNumber(value: Int16(42)).int16Value, Int16(42))
XCTAssertEqual(NSNumber(value: Int16(42)).uint16Value, UInt16(42))
XCTAssertEqual(NSNumber(value: Int16(42)).int32Value, Int32(42))
XCTAssertEqual(NSNumber(value: Int16(42)).uint32Value, UInt32(42))
XCTAssertEqual(NSNumber(value: Int16(42)).int64Value, Int64(42))
XCTAssertEqual(NSNumber(value: Int16(42)).uint64Value, UInt64(42))
XCTAssertEqual(NSNumber(value: Int16.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int16.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int16(0)).floatValue, Float(0))
XCTAssertEqual(NSNumber(value: Int16(-37)).floatValue, Float(-37))
XCTAssertEqual(NSNumber(value: Int16(42)).floatValue, Float(42))
XCTAssertEqual(NSNumber(value: Int16(0)).doubleValue, Double(0))
XCTAssertEqual(NSNumber(value: Int16(-37)).doubleValue, Double(-37))
XCTAssertEqual(NSNumber(value: Int16(42)).doubleValue, Double(42))
//------
XCTAssertEqual(NSNumber(value: Int16(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: Int16(0)).int8Value, 0)
XCTAssertEqual(NSNumber(value: Int16(0)).int16Value, 0)
XCTAssertEqual(NSNumber(value: Int16(0)).int32Value, 0)
XCTAssertEqual(NSNumber(value: Int16(0)).int64Value, 0)
XCTAssertEqual(NSNumber(value: Int16(0)).uint8Value, 0)
XCTAssertEqual(NSNumber(value: Int16(0)).uint16Value, 0)
XCTAssertEqual(NSNumber(value: Int16(0)).uint32Value, 0)
XCTAssertEqual(NSNumber(value: Int16(0)).uint64Value, 0)
XCTAssertEqual(NSNumber(value: Int16(0)).intValue, 0)
XCTAssertEqual(NSNumber(value: Int16(0)).uintValue, 0)
XCTAssertEqual(NSNumber(value: Int16(0)).floatValue, 0)
XCTAssertEqual(NSNumber(value: Int16(0)).doubleValue, 0)
//------
XCTAssertEqual(NSNumber(value: Int16.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int16.min).int8Value, 0)
XCTAssertEqual(NSNumber(value: Int16.min).int16Value, -32768)
XCTAssertEqual(NSNumber(value: Int16.min).int32Value, -32768)
XCTAssertEqual(NSNumber(value: Int16.min).int64Value, -32768)
XCTAssertEqual(NSNumber(value: Int16.min).uint8Value, 0)
XCTAssertEqual(NSNumber(value: Int16.min).uint16Value, 32768)
XCTAssertEqual(NSNumber(value: Int16.min).uint32Value, 4294934528)
XCTAssertEqual(NSNumber(value: Int16.min).uint64Value, 18446744073709518848)
XCTAssertEqual(NSNumber(value: Int16.min).intValue, -32768)
let uintSize = MemoryLayout<UInt>.size
switch uintSize {
case 4: XCTAssertEqual(NSNumber(value: Int16.min).uintValue, 4294934528)
case 8:
#if arch(arm)
break
#else
XCTAssertEqual(NSNumber(value: Int16.min).uintValue, 18446744073709518848)
#endif
default: XCTFail("Unexpected UInt size: \(uintSize)")
}
XCTAssertEqual(NSNumber(value: Int16.min).floatValue, Float(Int16.min))
XCTAssertEqual(NSNumber(value: Int16.min).doubleValue, Double(Int16.min))
//------
XCTAssertEqual(NSNumber(value: Int16.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int16.max).int8Value, -1)
XCTAssertEqual(NSNumber(value: Int16.max).int16Value, 32767)
XCTAssertEqual(NSNumber(value: Int16.max).int32Value, 32767)
XCTAssertEqual(NSNumber(value: Int16.max).int64Value, 32767)
XCTAssertEqual(NSNumber(value: Int16.max).uint8Value, 255)
XCTAssertEqual(NSNumber(value: Int16.max).uint16Value, 32767)
XCTAssertEqual(NSNumber(value: Int16.max).uint32Value, 32767)
XCTAssertEqual(NSNumber(value: Int16.max).uint64Value, 32767)
XCTAssertEqual(NSNumber(value: Int16.max).intValue, 32767)
XCTAssertEqual(NSNumber(value: Int16.max).uintValue, 32767)
XCTAssertEqual(NSNumber(value: Int16.max).floatValue, Float(Int16.max))
XCTAssertEqual(NSNumber(value: Int16.max).doubleValue, Double(Int16.max))
}
func test_numberWithUnsignedShort() {
XCTAssertEqual(NSNumber(value: UInt16(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: UInt16(0)).int8Value, 0)
XCTAssertEqual(NSNumber(value: UInt16(0)).int16Value, 0)
XCTAssertEqual(NSNumber(value: UInt16(0)).int32Value, 0)
XCTAssertEqual(NSNumber(value: UInt16(0)).int64Value, 0)
XCTAssertEqual(NSNumber(value: UInt16(0)).uint8Value, 0)
XCTAssertEqual(NSNumber(value: UInt16(0)).uint16Value, 0)
XCTAssertEqual(NSNumber(value: UInt16(0)).uint32Value, 0)
XCTAssertEqual(NSNumber(value: UInt16(0)).uint64Value, 0)
XCTAssertEqual(NSNumber(value: UInt16(0)).intValue, 0)
XCTAssertEqual(NSNumber(value: UInt16(0)).uintValue, 0)
XCTAssertEqual(NSNumber(value: UInt16(0)).floatValue, 0.0)
XCTAssertEqual(NSNumber(value: UInt16(0)).doubleValue, 0.0)
//------
XCTAssertEqual(NSNumber(value: UInt16.max).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt16.max).int8Value, -1)
XCTAssertEqual(NSNumber(value: UInt16.max).int16Value, -1)
XCTAssertEqual(NSNumber(value: UInt16.max).int32Value, 65535)
XCTAssertEqual(NSNumber(value: UInt16.max).int64Value, 65535)
XCTAssertEqual(NSNumber(value: UInt16.max).uint8Value, 255)
XCTAssertEqual(NSNumber(value: UInt16.max).uint16Value, 65535)
XCTAssertEqual(NSNumber(value: UInt16.max).uint32Value, 65535)
XCTAssertEqual(NSNumber(value: UInt16.max).uint64Value, 65535)
XCTAssertEqual(NSNumber(value: UInt16.max).intValue, 65535)
XCTAssertEqual(NSNumber(value: UInt16.max).uintValue, 65535)
XCTAssertEqual(NSNumber(value: UInt16.max).floatValue, Float(UInt16.max))
XCTAssertEqual(NSNumber(value: UInt16.max).doubleValue, Double(UInt16.max))
}
func test_numberWithLong() {
XCTAssertEqual(NSNumber(value: Int32(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: Int32(0)).int8Value, 0)
XCTAssertEqual(NSNumber(value: Int32(0)).int16Value, 0)
XCTAssertEqual(NSNumber(value: Int32(0)).int32Value, 0)
XCTAssertEqual(NSNumber(value: Int32(0)).int64Value, 0)
XCTAssertEqual(NSNumber(value: Int32(0)).uint8Value, 0)
XCTAssertEqual(NSNumber(value: Int32(0)).uint16Value, 0)
XCTAssertEqual(NSNumber(value: Int32(0)).uint32Value, 0)
XCTAssertEqual(NSNumber(value: Int32(0)).uint64Value, 0)
XCTAssertEqual(NSNumber(value: Int32(0)).intValue, 0)
XCTAssertEqual(NSNumber(value: Int32(0)).uintValue, 0)
XCTAssertEqual(NSNumber(value: Int32(0)).floatValue, 0)
XCTAssertEqual(NSNumber(value: Int32(0)).doubleValue, 0)
//------
XCTAssertEqual(NSNumber(value: Int32.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int32.min).int8Value, 0)
XCTAssertEqual(NSNumber(value: Int32.min).int16Value, 0)
XCTAssertEqual(NSNumber(value: Int32.min).int32Value, -2147483648)
XCTAssertEqual(NSNumber(value: Int32.min).int64Value, -2147483648)
XCTAssertEqual(NSNumber(value: Int32.min).uint8Value, 0)
XCTAssertEqual(NSNumber(value: Int32.min).uint16Value, 0)
XCTAssertEqual(NSNumber(value: Int32.min).uint32Value, 2147483648)
XCTAssertEqual(NSNumber(value: Int32.min).uint64Value, 18446744071562067968)
XCTAssertEqual(NSNumber(value: Int32.min).intValue, -2147483648)
let uintSize = MemoryLayout<UInt>.size
switch uintSize {
case 4: XCTAssertEqual(NSNumber(value: Int32.min).uintValue, 2147483648)
case 8:
#if arch(arm)
break
#else
XCTAssertEqual(NSNumber(value: Int32.min).uintValue, 18446744071562067968)
#endif
default: XCTFail("Unexpected UInt size: \(uintSize)")
}
XCTAssertEqual(NSNumber(value: Int32.min).floatValue, Float(Int32.min))
XCTAssertEqual(NSNumber(value: Int32.min).doubleValue, Double(Int32.min))
//------
XCTAssertEqual(NSNumber(value: Int32.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int32.max).int8Value, -1)
XCTAssertEqual(NSNumber(value: Int32.max).int16Value, -1)
XCTAssertEqual(NSNumber(value: Int32.max).int32Value, 2147483647)
XCTAssertEqual(NSNumber(value: Int32.max).int64Value, 2147483647)
XCTAssertEqual(NSNumber(value: Int32.max).uint8Value, 255)
XCTAssertEqual(NSNumber(value: Int32.max).uint16Value, 65535)
XCTAssertEqual(NSNumber(value: Int32.max).uint32Value, 2147483647)
XCTAssertEqual(NSNumber(value: Int32.max).uint64Value, 2147483647)
XCTAssertEqual(NSNumber(value: Int32.max).intValue, 2147483647)
XCTAssertEqual(NSNumber(value: Int32.max).uintValue, 2147483647)
XCTAssertEqual(NSNumber(value: Int32.max).floatValue, Float(Int32.max))
XCTAssertEqual(NSNumber(value: Int32.max).doubleValue, Double(Int32.max))
}
func test_numberWithUnsignedLong() {
XCTAssertEqual(NSNumber(value: UInt32(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: UInt32(0)).int8Value, 0)
XCTAssertEqual(NSNumber(value: UInt32(0)).int16Value, 0)
XCTAssertEqual(NSNumber(value: UInt32(0)).int32Value, 0)
XCTAssertEqual(NSNumber(value: UInt32(0)).int64Value, 0)
XCTAssertEqual(NSNumber(value: UInt32(0)).uint8Value, 0)
XCTAssertEqual(NSNumber(value: UInt32(0)).uint16Value, 0)
XCTAssertEqual(NSNumber(value: UInt32(0)).uint32Value, 0)
XCTAssertEqual(NSNumber(value: UInt32(0)).uint64Value, 0)
XCTAssertEqual(NSNumber(value: UInt32(0)).intValue, 0)
XCTAssertEqual(NSNumber(value: UInt32(0)).uintValue, 0)
XCTAssertEqual(NSNumber(value: UInt32(0)).floatValue, 0.0)
XCTAssertEqual(NSNumber(value: UInt32(0)).doubleValue, 0.0)
//------
XCTAssertEqual(NSNumber(value: UInt32.max).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt32.max).int8Value, -1)
XCTAssertEqual(NSNumber(value: UInt32.max).int16Value, -1)
XCTAssertEqual(NSNumber(value: UInt32.max).int32Value, -1)
XCTAssertEqual(NSNumber(value: UInt32.max).int64Value, 4294967295)
XCTAssertEqual(NSNumber(value: UInt32.max).uint8Value, 255)
XCTAssertEqual(NSNumber(value: UInt32.max).uint16Value, 65535)
XCTAssertEqual(NSNumber(value: UInt32.max).uint32Value, 4294967295)
XCTAssertEqual(NSNumber(value: UInt32.max).uint64Value, 4294967295)
let intSize = MemoryLayout<Int>.size
switch intSize {
case 4: XCTAssertEqual(NSNumber(value: UInt32.max).intValue, -1)
case 8:
#if arch(arm)
break
#else
XCTAssertEqual(NSNumber(value: UInt32.max).intValue, 4294967295)
#endif
default: XCTFail("Unexpected Int size: \(intSize)")
}
XCTAssertEqual(NSNumber(value: UInt32.max).uintValue, 4294967295)
XCTAssertEqual(NSNumber(value: UInt32.max).floatValue, Float(UInt32.max))
XCTAssertEqual(NSNumber(value: UInt32.max).doubleValue, Double(UInt32.max))
}
func test_numberWithLongLong() {
XCTAssertEqual(NSNumber(value: Int64(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: Int64(0)).int8Value, 0)
XCTAssertEqual(NSNumber(value: Int64(0)).int16Value, 0)
XCTAssertEqual(NSNumber(value: Int64(0)).int32Value, 0)
XCTAssertEqual(NSNumber(value: Int64(0)).int64Value, 0)
XCTAssertEqual(NSNumber(value: Int64(0)).uint8Value, 0)
XCTAssertEqual(NSNumber(value: Int64(0)).uint16Value, 0)
XCTAssertEqual(NSNumber(value: Int64(0)).uint32Value, 0)
XCTAssertEqual(NSNumber(value: Int64(0)).uint64Value, 0)
XCTAssertEqual(NSNumber(value: Int64(0)).intValue, 0)
XCTAssertEqual(NSNumber(value: Int64(0)).uintValue, 0)
XCTAssertEqual(NSNumber(value: Int64(0)).floatValue, 0)
XCTAssertEqual(NSNumber(value: Int64(0)).doubleValue, 0)
XCTAssertEqual(NSNumber(value: Int64.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int64.min).int8Value, 0)
XCTAssertEqual(NSNumber(value: Int64.min).int16Value, 0)
XCTAssertEqual(NSNumber(value: Int64.min).int32Value, 0)
XCTAssertEqual(NSNumber(value: Int64.min).int64Value, -9223372036854775808)
XCTAssertEqual(NSNumber(value: Int64.min).uint8Value, 0)
XCTAssertEqual(NSNumber(value: Int64.min).uint16Value, 0)
XCTAssertEqual(NSNumber(value: Int64.min).uint32Value, 0)
XCTAssertEqual(NSNumber(value: Int64.min).uint64Value, 9223372036854775808)
let intSize = MemoryLayout<Int>.size
switch intSize {
case 4: XCTAssertEqual(NSNumber(value: Int64.min).intValue, 0)
case 8:
#if arch(arm)
break
#else
XCTAssertEqual(NSNumber(value: Int64.min).intValue, -9223372036854775808)
#endif
default: XCTFail("Unexpected Int size: \(intSize)")
}
let uintSize = MemoryLayout<UInt>.size
switch uintSize {
case 4: XCTAssertEqual(NSNumber(value: Int64.min).uintValue, 0)
case 8:
#if arch(arm)
break
#else
XCTAssertEqual(NSNumber(value: Int64.min).uintValue, 9223372036854775808)
#endif
default: XCTFail("Unexpected UInt size: \(uintSize)")
}
XCTAssertEqual(NSNumber(value: Int64.min).floatValue, Float(Int64.min))
XCTAssertEqual(NSNumber(value: Int64.min).doubleValue, Double(Int64.min))
//------
XCTAssertEqual(NSNumber(value: Int64.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int64.max).int8Value, -1)
XCTAssertEqual(NSNumber(value: Int64.max).int16Value, -1)
XCTAssertEqual(NSNumber(value: Int64.max).int32Value, -1)
XCTAssertEqual(NSNumber(value: Int64.max).int64Value, 9223372036854775807)
XCTAssertEqual(NSNumber(value: Int64.max).uint8Value, 255)
XCTAssertEqual(NSNumber(value: Int64.max).uint16Value, 65535)
XCTAssertEqual(NSNumber(value: Int64.max).uint32Value, 4294967295)
XCTAssertEqual(NSNumber(value: Int64.max).uint64Value, 9223372036854775807)
switch intSize {
case 4: XCTAssertEqual(NSNumber(value: Int64.max).intValue, -1)
case 8:
#if arch(arm)
break
#else
XCTAssertEqual(NSNumber(value: Int64.max).intValue, 9223372036854775807)
#endif
default: XCTFail("Unexpected Int size: \(intSize)")
}
switch uintSize {
case 4: XCTAssertEqual(NSNumber(value: Int64.max).uintValue, 4294967295)
case 8:
#if arch(arm)
break
#else
XCTAssertEqual(NSNumber(value: Int64.max).uintValue, 9223372036854775807)
#endif
default: XCTFail("Unexpected UInt size: \(uintSize)")
}
XCTAssertEqual(NSNumber(value: Int64.max).floatValue, Float(Int64.max))
XCTAssertEqual(NSNumber(value: Int64.max).doubleValue, Double(Int64.max))
}
func test_numberWithUnsignedLongLong() {
XCTAssertEqual(NSNumber(value: UInt64(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: UInt64(0)).int8Value, 0)
XCTAssertEqual(NSNumber(value: UInt64(0)).int16Value, 0)
XCTAssertEqual(NSNumber(value: UInt64(0)).int32Value, 0)
XCTAssertEqual(NSNumber(value: UInt64(0)).int64Value, 0)
XCTAssertEqual(NSNumber(value: UInt64(0)).uint8Value, 0)
XCTAssertEqual(NSNumber(value: UInt64(0)).uint16Value, 0)
XCTAssertEqual(NSNumber(value: UInt64(0)).uint32Value, 0)
XCTAssertEqual(NSNumber(value: UInt64(0)).uint64Value, 0)
XCTAssertEqual(NSNumber(value: UInt64(0)).intValue, 0)
XCTAssertEqual(NSNumber(value: UInt64(0)).uintValue, 0)
XCTAssertEqual(NSNumber(value: UInt64(0)).floatValue, 0.0)
XCTAssertEqual(NSNumber(value: UInt64(0)).doubleValue, 0.0)
//------
XCTAssertEqual(NSNumber(value: UInt64.max).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt64.max).int8Value, -1)
XCTAssertEqual(NSNumber(value: UInt64.max).int16Value, -1)
XCTAssertEqual(NSNumber(value: UInt64.max).int32Value, -1)
XCTAssertEqual(NSNumber(value: UInt64.max).int64Value, -1)
XCTAssertEqual(NSNumber(value: UInt64.max).uint8Value, 255)
XCTAssertEqual(NSNumber(value: UInt64.max).uint16Value, 65535)
XCTAssertEqual(NSNumber(value: UInt64.max).uint32Value, 4294967295)
XCTAssertEqual(NSNumber(value: UInt64.max).uint64Value, 18446744073709551615)
XCTAssertEqual(NSNumber(value: UInt64.max).intValue, -1)
let uintSize = MemoryLayout<UInt>.size
switch uintSize {
case 4: XCTAssertEqual(NSNumber(value: UInt64.max).uintValue, 4294967295)
case 8:
#if arch(arm)
break
#else
XCTAssertEqual(NSNumber(value: UInt64.max).uintValue, 18446744073709551615)
#endif
default: XCTFail("Unexpected UInt size: \(uintSize)")
}
XCTAssertEqual(NSNumber(value: UInt64.max).floatValue, Float(UInt64.max))
XCTAssertEqual(NSNumber(value: UInt64.max).doubleValue, Double(UInt64.max))
}
func test_numberWithInt() {
XCTAssertEqual(NSNumber(value: Int(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: Int(0)).int8Value, 0)
XCTAssertEqual(NSNumber(value: Int(0)).int16Value, 0)
XCTAssertEqual(NSNumber(value: Int(0)).int32Value, 0)
XCTAssertEqual(NSNumber(value: Int(0)).int64Value, 0)
XCTAssertEqual(NSNumber(value: Int(0)).uint8Value, 0)
XCTAssertEqual(NSNumber(value: Int(0)).uint16Value, 0)
XCTAssertEqual(NSNumber(value: Int(0)).uint32Value, 0)
XCTAssertEqual(NSNumber(value: Int(0)).uint64Value, 0)
XCTAssertEqual(NSNumber(value: Int(0)).intValue, 0)
XCTAssertEqual(NSNumber(value: Int(0)).uintValue, 0)
XCTAssertEqual(NSNumber(value: Int(0)).floatValue, 0)
XCTAssertEqual(NSNumber(value: Int(0)).doubleValue, 0)
//------
let intSize = MemoryLayout<Int>.size
let uintSize = MemoryLayout<UInt>.size
switch (intSize, uintSize) {
case (4, 4):
XCTAssertEqual(NSNumber(value: Int.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int.min).int8Value, 0)
XCTAssertEqual(NSNumber(value: Int.min).int16Value, 0)
XCTAssertEqual(NSNumber(value: Int.min).int32Value, -2147483648)
XCTAssertEqual(NSNumber(value: Int.min).int64Value, -2147483648)
XCTAssertEqual(NSNumber(value: Int.min).uint8Value, 0)
XCTAssertEqual(NSNumber(value: Int.min).uint16Value, 0)
XCTAssertEqual(NSNumber(value: Int.min).uint32Value, 2147483648)
XCTAssertEqual(NSNumber(value: Int.min).uint64Value, 18446744071562067968)
XCTAssertEqual(NSNumber(value: Int.min).intValue, -2147483648)
#if !arch(arm)
XCTAssertEqual(NSNumber(value: Int.min).uintValue, 18446744071562067968)
#endif
XCTAssertEqual(NSNumber(value: Int.min).floatValue, Float(Int.min))
XCTAssertEqual(NSNumber(value: Int.min).doubleValue, Double(Int.min))
//--------
XCTAssertEqual(NSNumber(value: Int.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int.max).int8Value, -1)
XCTAssertEqual(NSNumber(value: Int.max).int16Value, -1)
XCTAssertEqual(NSNumber(value: Int.max).int32Value, 2147483647)
XCTAssertEqual(NSNumber(value: Int.max).int64Value, 2147483647)
XCTAssertEqual(NSNumber(value: Int.max).uint8Value, 255)
XCTAssertEqual(NSNumber(value: Int.max).uint16Value, 65535)
XCTAssertEqual(NSNumber(value: Int.max).uint32Value, 2147483647)
XCTAssertEqual(NSNumber(value: Int.max).uint64Value, 2147483647)
XCTAssertEqual(NSNumber(value: Int.max).intValue, 2147483647)
XCTAssertEqual(NSNumber(value: Int.max).uintValue, 2147483647)
XCTAssertEqual(NSNumber(value: Int.max).floatValue, Float(Int.max))
XCTAssertEqual(NSNumber(value: Int.max).doubleValue, Double(Int.max))
case (8, 8):
#if arch(arm)
break
#else
XCTAssertEqual(NSNumber(value: Int.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int.min).int8Value, 0)
XCTAssertEqual(NSNumber(value: Int.min).int16Value, 0)
XCTAssertEqual(NSNumber(value: Int.min).int32Value, 0)
XCTAssertEqual(NSNumber(value: Int.min).int64Value, -9223372036854775808)
XCTAssertEqual(NSNumber(value: Int.min).uint8Value, 0)
XCTAssertEqual(NSNumber(value: Int.min).uint16Value, 0)
XCTAssertEqual(NSNumber(value: Int.min).uint32Value, 0)
XCTAssertEqual(NSNumber(value: Int.min).uint64Value, 9223372036854775808)
XCTAssertEqual(NSNumber(value: Int.min).intValue, -9223372036854775808)
XCTAssertEqual(NSNumber(value: Int.min).uintValue, 9223372036854775808)
XCTAssertEqual(NSNumber(value: Int.min).floatValue, Float(Int.min))
XCTAssertEqual(NSNumber(value: Int.min).doubleValue, Double(Int.min))
//--------
XCTAssertEqual(NSNumber(value: Int.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int.max).int8Value, -1)
XCTAssertEqual(NSNumber(value: Int.max).int16Value, -1)
XCTAssertEqual(NSNumber(value: Int.max).int32Value, -1)
XCTAssertEqual(NSNumber(value: Int.max).int64Value, 9223372036854775807)
XCTAssertEqual(NSNumber(value: Int.max).uint8Value, 255)
XCTAssertEqual(NSNumber(value: Int.max).uint16Value, 65535)
XCTAssertEqual(NSNumber(value: Int.max).uint32Value, 4294967295)
XCTAssertEqual(NSNumber(value: Int.max).uint64Value, 9223372036854775807)
XCTAssertEqual(NSNumber(value: Int.max).intValue, 9223372036854775807)
XCTAssertEqual(NSNumber(value: Int.max).uintValue, 9223372036854775807)
XCTAssertEqual(NSNumber(value: Int.max).floatValue, Float(Int.max))
XCTAssertEqual(NSNumber(value: Int.max).doubleValue, Double(Int.max))
#endif
default: XCTFail("Unexpected mismatched Int & UInt sizes: \(intSize) & \(uintSize)")
}
}
func test_numberWithUInt() {
XCTAssertEqual(NSNumber(value: UInt(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: UInt(0)).int8Value, 0)
XCTAssertEqual(NSNumber(value: UInt(0)).int16Value, 0)
XCTAssertEqual(NSNumber(value: UInt(0)).int32Value, 0)
XCTAssertEqual(NSNumber(value: UInt(0)).int64Value, 0)
XCTAssertEqual(NSNumber(value: UInt(0)).uint8Value, 0)
XCTAssertEqual(NSNumber(value: UInt(0)).uint16Value, 0)
XCTAssertEqual(NSNumber(value: UInt(0)).uint32Value, 0)
XCTAssertEqual(NSNumber(value: UInt(0)).uint64Value, 0)
XCTAssertEqual(NSNumber(value: UInt(0)).intValue, 0)
XCTAssertEqual(NSNumber(value: UInt(0)).uintValue, 0)
XCTAssertEqual(NSNumber(value: UInt(0)).floatValue, 0)
XCTAssertEqual(NSNumber(value: UInt(0)).doubleValue, 0)
//------
let intSize = MemoryLayout<Int>.size
let uintSize = MemoryLayout<UInt>.size
switch (intSize, uintSize) {
case (4, 4):
XCTAssertEqual(NSNumber(value: UInt.max).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt.max).int8Value, -1)
XCTAssertEqual(NSNumber(value: UInt.max).int16Value, -1)
XCTAssertEqual(NSNumber(value: UInt.max).int32Value, -1)
XCTAssertEqual(NSNumber(value: UInt.max).int64Value, 4294967295)
XCTAssertEqual(NSNumber(value: UInt.max).uint8Value, 255)
XCTAssertEqual(NSNumber(value: UInt.max).uint16Value, 65535)
XCTAssertEqual(NSNumber(value: UInt.max).uint32Value, 4294967295)
XCTAssertEqual(NSNumber(value: UInt.max).uint64Value, 4294967295)
#if !arch(arm)
XCTAssertEqual(NSNumber(value: UInt.max).intValue, 4294967295)
#endif
XCTAssertEqual(NSNumber(value: UInt.max).uintValue, 4294967295)
XCTAssertEqual(NSNumber(value: UInt.max).floatValue, Float(UInt.max))
XCTAssertEqual(NSNumber(value: UInt.max).doubleValue, Double(UInt.max))
case (8, 8):
XCTAssertEqual(NSNumber(value: UInt.max).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt.max).int8Value, -1)
XCTAssertEqual(NSNumber(value: UInt.max).int16Value, -1)
XCTAssertEqual(NSNumber(value: UInt.max).int32Value, -1)
XCTAssertEqual(NSNumber(value: UInt.max).int64Value, -1)
XCTAssertEqual(NSNumber(value: UInt.max).uint8Value, 255)
XCTAssertEqual(NSNumber(value: UInt.max).uint16Value, 65535)
XCTAssertEqual(NSNumber(value: UInt.max).uint32Value, 4294967295)
XCTAssertEqual(NSNumber(value: UInt.max).uint64Value, 18446744073709551615)
XCTAssertEqual(NSNumber(value: UInt.max).intValue, -1)
#if !arch(arm)
XCTAssertEqual(NSNumber(value: UInt.max).uintValue, 18446744073709551615)
#endif
XCTAssertEqual(NSNumber(value: UInt.max).floatValue, Float(UInt.max))
XCTAssertEqual(NSNumber(value: UInt.max).doubleValue, Double(UInt.max))
default: XCTFail("Unexpected mismatched Int & UInt sizes: \(intSize) & \(uintSize)")
}
}
func test_numberWithFloat() {
XCTAssertEqual(NSNumber(value: Float(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: Float(0)).int8Value, Int8(0))
XCTAssertEqual(NSNumber(value: Float(0)).uint8Value, UInt8(0))
XCTAssertEqual(NSNumber(value: Float(0)).int16Value, Int16(0))
XCTAssertEqual(NSNumber(value: Float(0)).uint16Value, UInt16(0))
XCTAssertEqual(NSNumber(value: Float(0)).int32Value, Int32(0))
XCTAssertEqual(NSNumber(value: Float(0)).uint32Value, UInt32(0))
XCTAssertEqual(NSNumber(value: Float(0)).int64Value, Int64(0))
XCTAssertEqual(NSNumber(value: Float(0)).uint64Value, UInt64(0))
XCTAssertEqual(NSNumber(value: Float(1)).boolValue, true)
XCTAssertEqual(NSNumber(value: Float(1)).int8Value, Int8(1))
XCTAssertEqual(NSNumber(value: Float(1)).uint8Value, UInt8(1))
XCTAssertEqual(NSNumber(value: Float(1)).int16Value, Int16(1))
XCTAssertEqual(NSNumber(value: Float(1)).uint16Value, UInt16(1))
XCTAssertEqual(NSNumber(value: Float(1)).int32Value, Int32(1))
XCTAssertEqual(NSNumber(value: Float(1)).uint32Value, UInt32(1))
XCTAssertEqual(NSNumber(value: Float(1)).int64Value, Int64(1))
XCTAssertEqual(NSNumber(value: Float(1)).uint64Value, UInt64(1))
XCTAssertEqual(NSNumber(value: Float(-37)).boolValue, true)
XCTAssertEqual(NSNumber(value: Float(-37)).int8Value, Int8(-37))
XCTAssertEqual(NSNumber(value: Float(-37)).int16Value, Int16(-37))
XCTAssertEqual(NSNumber(value: Float(-37)).int32Value, Int32(-37))
XCTAssertEqual(NSNumber(value: Float(-37)).int64Value, Int64(-37))
XCTAssertEqual(NSNumber(value: Float(42)).boolValue, true)
XCTAssertEqual(NSNumber(value: Float(42)).int8Value, Int8(42))
XCTAssertEqual(NSNumber(value: Float(42)).uint8Value, UInt8(42))
XCTAssertEqual(NSNumber(value: Float(42)).int16Value, Int16(42))
XCTAssertEqual(NSNumber(value: Float(42)).uint16Value, UInt16(42))
XCTAssertEqual(NSNumber(value: Float(42)).int32Value, Int32(42))
XCTAssertEqual(NSNumber(value: Float(42)).uint32Value, UInt32(42))
XCTAssertEqual(NSNumber(value: Float(42)).int64Value, Int64(42))
XCTAssertEqual(NSNumber(value: Float(42)).uint64Value, UInt64(42))
XCTAssertEqual(NSNumber(value: Float(0)).floatValue, Float(0))
XCTAssertEqual(NSNumber(value: Float(1)).floatValue, Float(1))
XCTAssertEqual(NSNumber(value: Float(-37.5)).floatValue, Float(-37.5))
XCTAssertEqual(NSNumber(value: Float(42.1)).floatValue, Float(42.1))
XCTAssertEqual(NSNumber(value: Float(0)).doubleValue, Double(0))
XCTAssertEqual(NSNumber(value: Float(1)).doubleValue, Double(1))
XCTAssertEqual(NSNumber(value: Float(-37.5)).doubleValue, Double(-37.5))
XCTAssertEqual(NSNumber(value: Float(42.5)).doubleValue, Double(42.5))
let nanFloat = NSNumber(value: Float.nan)
XCTAssertTrue(nanFloat.doubleValue.isNaN)
}
func test_numberWithDouble() {
XCTAssertEqual(NSNumber(value: Double(0)).boolValue, false)
XCTAssertEqual(NSNumber(value: Double(0)).int8Value, Int8(0))
XCTAssertEqual(NSNumber(value: Double(0)).uint8Value, UInt8(0))
XCTAssertEqual(NSNumber(value: Double(0)).int16Value, Int16(0))
XCTAssertEqual(NSNumber(value: Double(0)).uint16Value, UInt16(0))
XCTAssertEqual(NSNumber(value: Double(0)).int32Value, Int32(0))
XCTAssertEqual(NSNumber(value: Double(0)).uint32Value, UInt32(0))
XCTAssertEqual(NSNumber(value: Double(0)).int64Value, Int64(0))
XCTAssertEqual(NSNumber(value: Double(0)).uint64Value, UInt64(0))
XCTAssertEqual(NSNumber(value: Double(-37)).boolValue, true)
XCTAssertEqual(NSNumber(value: Double(-37)).int8Value, Int8(-37))
XCTAssertEqual(NSNumber(value: Double(-37)).int16Value, Int16(-37))
XCTAssertEqual(NSNumber(value: Double(-37)).int32Value, Int32(-37))
XCTAssertEqual(NSNumber(value: Double(-37)).int64Value, Int64(-37))
XCTAssertEqual(NSNumber(value: Double(42)).boolValue, true)
XCTAssertEqual(NSNumber(value: Double(42)).int8Value, Int8(42))
XCTAssertEqual(NSNumber(value: Double(42)).uint8Value, UInt8(42))
XCTAssertEqual(NSNumber(value: Double(42)).int16Value, Int16(42))
XCTAssertEqual(NSNumber(value: Double(42)).uint16Value, UInt16(42))
XCTAssertEqual(NSNumber(value: Double(42)).int32Value, Int32(42))
XCTAssertEqual(NSNumber(value: Double(42)).uint32Value, UInt32(42))
XCTAssertEqual(NSNumber(value: Double(42)).int64Value, Int64(42))
XCTAssertEqual(NSNumber(value: Double(42)).uint64Value, UInt64(42))
XCTAssertEqual(NSNumber(value: Double(0)).floatValue, Float(0))
XCTAssertEqual(NSNumber(value: Double(-37.5)).floatValue, Float(-37.5))
XCTAssertEqual(NSNumber(value: Double(42.1)).floatValue, Float(42.1))
XCTAssertEqual(NSNumber(value: Double(0)).doubleValue, Double(0))
XCTAssertEqual(NSNumber(value: Double(-37.5)).doubleValue, Double(-37.5))
XCTAssertEqual(NSNumber(value: Double(42.1)).doubleValue, Double(42.1))
let nanDouble = NSNumber(value: Double.nan)
XCTAssertTrue(nanDouble.floatValue.isNaN)
}
func test_compareNumberWithBool() {
XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: true)), .orderedSame)
XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: false)), .orderedDescending)
XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: true)), .orderedAscending)
XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Int8(0))), .orderedSame)
#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
// Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Int8(-1))), .orderedDescending)
#endif
XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Int8(1))), .orderedAscending)
XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Int8(1))), .orderedSame)
XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Int8(0))), .orderedDescending)
XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Int8(2))), .orderedAscending)
XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Double(0))), .orderedSame)
XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Double(-0.1))), .orderedDescending)
XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Double(0.1))), .orderedAscending)
XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Double(1))), .orderedSame)
XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Double(0.9))), .orderedDescending)
XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Double(1.1))), .orderedAscending)
}
func test_compareNumberWithChar() {
XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: Int8(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: Int8(0))), .orderedDescending)
#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
// Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
XCTAssertEqual(NSNumber(value: Int8(-37)).compare(NSNumber(value: Int8(16))), .orderedAscending)
#endif
XCTAssertEqual(NSNumber(value: Int8(1)).compare(NSNumber(value: true)), .orderedSame)
XCTAssertEqual(NSNumber(value: Int8(1)).compare(NSNumber(value: false)), .orderedDescending)
#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
// Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
XCTAssertEqual(NSNumber(value: Int8(-37)).compare(NSNumber(value: true)), .orderedAscending)
#endif
XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: UInt8(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: UInt8(16))), .orderedDescending)
#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
// Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
XCTAssertEqual(NSNumber(value: Int8(-37)).compare(NSNumber(value: UInt8(255))), .orderedAscending)
#endif
XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: Float(42))), .orderedSame)
#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
// Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
XCTAssertEqual(NSNumber(value: Int8(-16)).compare(NSNumber(value: Float(-37.5))), .orderedDescending)
#endif
XCTAssertEqual(NSNumber(value: Int8(16)).compare(NSNumber(value: Float(16.1))), .orderedAscending)
}
func test_compareNumberWithUnsignedChar() {
XCTAssertEqual(NSNumber(value: UInt8(42)).compare(NSNumber(value: UInt8(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: UInt8(42)).compare(NSNumber(value: UInt8(0))), .orderedDescending)
// XCTAssertEqual(NSNumber(value: UInt8(42)).compare(NSNumber(value: UInt8(255))), .orderedAscending)
XCTAssertEqual(NSNumber(value: UInt8(1)).compare(NSNumber(value: true)), .orderedSame)
XCTAssertEqual(NSNumber(value: UInt8(1)).compare(NSNumber(value: false)), .orderedDescending)
XCTAssertEqual(NSNumber(value: UInt8(0)).compare(NSNumber(value: true)), .orderedAscending)
XCTAssertEqual(NSNumber(value: UInt8(42)).compare(NSNumber(value: Int16(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: UInt8(0)).compare(NSNumber(value: Int16(-123))), .orderedDescending)
XCTAssertEqual(NSNumber(value: UInt8(255)).compare(NSNumber(value: Int16(12345))), .orderedAscending)
XCTAssertEqual(NSNumber(value: UInt8(42)).compare(NSNumber(value: Float(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: UInt8(0)).compare(NSNumber(value: Float(-37.5))), .orderedDescending)
XCTAssertEqual(NSNumber(value: UInt8(255)).compare(NSNumber(value: Float(1234.5))), .orderedAscending)
}
func test_compareNumberWithShort() {
XCTAssertEqual(NSNumber(value: Int16(42)).compare(NSNumber(value: Int16(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: Int16(42)).compare(NSNumber(value: Int16(0))), .orderedDescending)
XCTAssertEqual(NSNumber(value: Int16(-37)).compare(NSNumber(value: Int16(12345))), .orderedAscending)
XCTAssertEqual(NSNumber(value: Int16(1)).compare(NSNumber(value: true)), .orderedSame)
XCTAssertEqual(NSNumber(value: Int16(1)).compare(NSNumber(value: false)), .orderedDescending)
XCTAssertEqual(NSNumber(value: Int16(0)).compare(NSNumber(value: true)), .orderedAscending)
XCTAssertEqual(NSNumber(value: Int16(42)).compare(NSNumber(value: UInt8(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: Int16(42)).compare(NSNumber(value: UInt8(0))), .orderedDescending)
XCTAssertEqual(NSNumber(value: Int16(-37)).compare(NSNumber(value: UInt8(255))), .orderedAscending)
XCTAssertEqual(NSNumber(value: Int16(42)).compare(NSNumber(value: Float(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: Int16(0)).compare(NSNumber(value: Float(-37.5))), .orderedDescending)
XCTAssertEqual(NSNumber(value: Int16(255)).compare(NSNumber(value: Float(1234.5))), .orderedAscending)
}
func test_compareNumberWithFloat() {
XCTAssertEqual(NSNumber(value: Float(42)).compare(NSNumber(value: Float(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: Float(42)).compare(NSNumber(value: Float(0))), .orderedDescending)
XCTAssertEqual(NSNumber(value: Float(-37)).compare(NSNumber(value: Float(12345))), .orderedAscending)
XCTAssertEqual(NSNumber(value: Float(1)).compare(NSNumber(value: true)), .orderedSame)
XCTAssertEqual(NSNumber(value: Float(0.1)).compare(NSNumber(value: false)), .orderedDescending)
XCTAssertEqual(NSNumber(value: Float(0.9)).compare(NSNumber(value: true)), .orderedAscending)
XCTAssertEqual(NSNumber(value: Float(42)).compare(NSNumber(value: UInt8(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: Float(0.1)).compare(NSNumber(value: UInt8(0))), .orderedDescending)
XCTAssertEqual(NSNumber(value: Float(-254.9)).compare(NSNumber(value: UInt8(255))), .orderedAscending)
XCTAssertEqual(NSNumber(value: Float(42)).compare(NSNumber(value: Double(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: Float(0)).compare(NSNumber(value: Double(-37.5))), .orderedDescending)
XCTAssertEqual(NSNumber(value: Float(-37.5)).compare(NSNumber(value: Double(1234.5))), .orderedAscending)
}
func test_compareNumberWithDouble() {
XCTAssertEqual(NSNumber(value: Double(42)).compare(NSNumber(value: Double(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: Double(42)).compare(NSNumber(value: Double(0))), .orderedDescending)
XCTAssertEqual(NSNumber(value: Double(-37)).compare(NSNumber(value: Double(12345))), .orderedAscending)
XCTAssertEqual(NSNumber(value: Double(1)).compare(NSNumber(value: true)), .orderedSame)
XCTAssertEqual(NSNumber(value: Double(0.1)).compare(NSNumber(value: false)), .orderedDescending)
XCTAssertEqual(NSNumber(value: Double(0.9)).compare(NSNumber(value: true)), .orderedAscending)
XCTAssertEqual(NSNumber(value: Double(42)).compare(NSNumber(value: UInt8(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: Double(0.1)).compare(NSNumber(value: UInt8(0))), .orderedDescending)
XCTAssertEqual(NSNumber(value: Double(-254.9)).compare(NSNumber(value: UInt8(255))), .orderedAscending)
XCTAssertEqual(NSNumber(value: Double(42)).compare(NSNumber(value: Float(42))), .orderedSame)
XCTAssertEqual(NSNumber(value: Double(0)).compare(NSNumber(value: Float(-37.5))), .orderedDescending)
XCTAssertEqual(NSNumber(value: Double(-37.5)).compare(NSNumber(value: Float(1234.5))), .orderedAscending)
}
func test_description() {
XCTAssertEqual(NSNumber(value: 1000).description, "1000")
XCTAssertEqual(NSNumber(value: 0.001).description, "0.001")
XCTAssertEqual(NSNumber(value: Int8.min).description, "-128")
XCTAssertEqual(NSNumber(value: Int8.max).description, "127")
XCTAssertEqual(NSNumber(value: Int16.min).description, "-32768")
XCTAssertEqual(NSNumber(value: Int16.max).description, "32767")
XCTAssertEqual(NSNumber(value: Int32.min).description, "-2147483648")
XCTAssertEqual(NSNumber(value: Int32.max).description, "2147483647")
XCTAssertEqual(NSNumber(value: Int64.min).description, "-9223372036854775808")
XCTAssertEqual(NSNumber(value: Int64.max).description, "9223372036854775807")
XCTAssertEqual(NSNumber(value: UInt8.min).description, "0")
XCTAssertEqual(NSNumber(value: UInt8.max).description, "255")
XCTAssertEqual(NSNumber(value: UInt16.min).description, "0")
XCTAssertEqual(NSNumber(value: UInt16.max).description, "65535")
XCTAssertEqual(NSNumber(value: UInt32.min).description, "0")
XCTAssertEqual(NSNumber(value: UInt32.max).description, "4294967295")
XCTAssertEqual(NSNumber(value: UInt64.min).description, "0")
XCTAssertEqual(NSNumber(value: UInt64.max).description, "18446744073709551615")
XCTAssertEqual(NSNumber(value: 1.2 as Float).description, "1.2")
XCTAssertEqual(NSNumber(value: 1000_000_000 as Float).description, "1e+09")
XCTAssertEqual(NSNumber(value: -0.99 as Float).description, "-0.99")
XCTAssertEqual(NSNumber(value: Float.zero).description, "0.0")
XCTAssertEqual(NSNumber(value: Float.nan).description, "nan")
XCTAssertEqual(NSNumber(value: Float.leastNormalMagnitude).description, "1.1754944e-38")
XCTAssertEqual(NSNumber(value: Float.leastNonzeroMagnitude).description, "1e-45")
XCTAssertEqual(NSNumber(value: Float.greatestFiniteMagnitude).description, "3.4028235e+38")
XCTAssertEqual(NSNumber(value: Float.pi).description, "3.1415925")
XCTAssertEqual(NSNumber(value: 1.2 as Double).description, "1.2")
XCTAssertEqual(NSNumber(value: 1000_000_000 as Double).description, "1000000000.0")
XCTAssertEqual(NSNumber(value: -0.99 as Double).description, "-0.99")
XCTAssertEqual(NSNumber(value: Double.zero).description, "0.0")
XCTAssertEqual(NSNumber(value: Double.nan).description, "nan")
XCTAssertEqual(NSNumber(value: Double.leastNormalMagnitude).description, "2.2250738585072014e-308")
XCTAssertEqual(NSNumber(value: Double.leastNonzeroMagnitude).description, "5e-324")
XCTAssertEqual(NSNumber(value: Double.greatestFiniteMagnitude).description, "1.7976931348623157e+308")
XCTAssertEqual(NSNumber(value: Double.pi).description, "3.141592653589793")
}
func test_descriptionWithLocale() {
// nil Locale
XCTAssertEqual(NSNumber(value: 1000).description(withLocale: nil), "1000")
XCTAssertEqual(NSNumber(value: 0.001).description(withLocale: nil), "0.001")
XCTAssertEqual(NSNumber(value: Int8.min).description(withLocale: nil), "-128")
XCTAssertEqual(NSNumber(value: Int8.max).description(withLocale: nil), "127")
XCTAssertEqual(NSNumber(value: Int16.min).description(withLocale: nil), "-32768")
XCTAssertEqual(NSNumber(value: Int16.max).description(withLocale: nil), "32767")
XCTAssertEqual(NSNumber(value: Int32.min).description(withLocale: nil), "-2147483648")
XCTAssertEqual(NSNumber(value: Int32.max).description(withLocale: nil), "2147483647")
XCTAssertEqual(NSNumber(value: Int64.min).description(withLocale: nil), "-9223372036854775808")
XCTAssertEqual(NSNumber(value: Int64.max).description(withLocale: nil), "9223372036854775807")
XCTAssertEqual(NSNumber(value: UInt8.min).description(withLocale: nil), "0")
XCTAssertEqual(NSNumber(value: UInt8.max).description(withLocale: nil), "255")
XCTAssertEqual(NSNumber(value: UInt16.min).description(withLocale: nil), "0")
XCTAssertEqual(NSNumber(value: UInt16.max).description(withLocale: nil), "65535")
XCTAssertEqual(NSNumber(value: UInt32.min).description(withLocale: nil), "0")
XCTAssertEqual(NSNumber(value: UInt32.max).description(withLocale: nil), "4294967295")
XCTAssertEqual(NSNumber(value: UInt64.min).description(withLocale: nil), "0")
XCTAssertEqual(NSNumber(value: UInt64.max).description(withLocale: nil), "18446744073709551615")
XCTAssertEqual(NSNumber(value: 1.2 as Float).description(withLocale: nil), "1.2")
XCTAssertEqual(NSNumber(value: 1000_000_000 as Float).description(withLocale: nil), "1e+09")
XCTAssertEqual(NSNumber(value: -0.99 as Float).description(withLocale: nil), "-0.99")
XCTAssertEqual(NSNumber(value: Float.zero).description(withLocale: nil), "0.0")
XCTAssertEqual(NSNumber(value: Float.nan).description(withLocale: nil), "nan")
XCTAssertEqual(NSNumber(value: Float.leastNormalMagnitude).description(withLocale: nil), "1.1754944e-38")
XCTAssertEqual(NSNumber(value: Float.leastNonzeroMagnitude).description(withLocale: nil), "1e-45")
XCTAssertEqual(NSNumber(value: Float.greatestFiniteMagnitude).description(withLocale: nil), "3.4028235e+38")
XCTAssertEqual(NSNumber(value: Float.pi).description(withLocale: nil), "3.1415925")
XCTAssertEqual(NSNumber(value: 1.2 as Double).description(withLocale: nil), "1.2")
XCTAssertEqual(NSNumber(value: 1000_000_000 as Double).description(withLocale: nil), "1000000000.0")
XCTAssertEqual(NSNumber(value: -0.99 as Double).description(withLocale: nil), "-0.99")
XCTAssertEqual(NSNumber(value: Double.zero).description(withLocale: nil), "0.0")
XCTAssertEqual(NSNumber(value: Double.nan).description(withLocale: nil), "nan")
XCTAssertEqual(NSNumber(value: Double.leastNormalMagnitude).description(withLocale: nil), "2.2250738585072014e-308")
XCTAssertEqual(NSNumber(value: Double.leastNonzeroMagnitude).description(withLocale: nil), "5e-324")
XCTAssertEqual(NSNumber(value: 2 * Double.leastNonzeroMagnitude).description, "1e-323")
XCTAssertEqual(NSNumber(value: Double.greatestFiniteMagnitude).description(withLocale: nil), "1.7976931348623157e+308")
XCTAssertEqual(NSNumber(value: Double.pi).description(withLocale: nil), "3.141592653589793")
// en_GB Locale
XCTAssertEqual(NSNumber(value: 1000).description(withLocale: Locale(identifier: "en_GB")), "1,000")
XCTAssertEqual(NSNumber(value: 0.001).description(withLocale: Locale(identifier: "en_GB")), "0.001")
XCTAssertEqual(NSNumber(value: Int8.min).description(withLocale: Locale(identifier: "en_GB")), "-128")
XCTAssertEqual(NSNumber(value: Int8.max).description(withLocale: Locale(identifier: "en_GB")), "127")
XCTAssertEqual(NSNumber(value: Int16.min).description(withLocale: Locale(identifier: "en_GB")), "-32,768")
XCTAssertEqual(NSNumber(value: Int16.max).description(withLocale: Locale(identifier: "en_GB")), "32,767")
XCTAssertEqual(NSNumber(value: Int32.min).description(withLocale: Locale(identifier: "en_GB")), "-2,147,483,648")
XCTAssertEqual(NSNumber(value: Int32.max).description(withLocale: Locale(identifier: "en_GB")), "2,147,483,647")
XCTAssertEqual(NSNumber(value: Int64.min).description(withLocale: Locale(identifier: "en_GB")), "-9,223,372,036,854,775,808")
XCTAssertEqual(NSNumber(value: Int64.max).description(withLocale: Locale(identifier: "en_GB")), "9,223,372,036,854,775,807")
XCTAssertEqual(NSNumber(value: UInt8.min).description(withLocale: Locale(identifier: "en_GB")), "0")
XCTAssertEqual(NSNumber(value: UInt8.max).description(withLocale: Locale(identifier: "en_GB")), "255")
XCTAssertEqual(NSNumber(value: UInt16.min).description(withLocale: Locale(identifier: "en_GB")), "0")
XCTAssertEqual(NSNumber(value: UInt16.max).description(withLocale: Locale(identifier: "en_GB")), "65,535")
XCTAssertEqual(NSNumber(value: UInt32.min).description(withLocale: Locale(identifier: "en_GB")), "0")
XCTAssertEqual(NSNumber(value: UInt32.max).description(withLocale: Locale(identifier: "en_GB")), "4,294,967,295")
XCTAssertEqual(NSNumber(value: UInt64.min).description(withLocale: Locale(identifier: "en_GB")), "0")
// This is the correct value but currently buggy and the locale is not used
// XCTAssertEqual(NSNumber(value: UInt64.max).description(withLocale: Locale(identifier: "en_GB")), "18,446,744,073,709,551,615")
XCTAssertEqual(NSNumber(value: UInt64.max).description(withLocale: Locale(identifier: "en_GB")), "18446744073709551615")
XCTAssertEqual(NSNumber(value: 1.2 as Float).description(withLocale: Locale(identifier: "en_GB")), "1.2")
XCTAssertEqual(NSNumber(value: 1000_000_000 as Float).description(withLocale: Locale(identifier: "en_GB")), "1E+09")
XCTAssertEqual(NSNumber(value: -0.99 as Float).description(withLocale: Locale(identifier: "en_GB")), "-0.99")
XCTAssertEqual(NSNumber(value: Float.zero).description(withLocale: Locale(identifier: "en_GB")), "0")
XCTAssertEqual(NSNumber(value: Float.nan).description(withLocale: Locale(identifier: "en_GB")), "NaN")
XCTAssertEqual(NSNumber(value: Float.leastNormalMagnitude).description(withLocale: Locale(identifier: "en_GB")), "1.175494E-38")
XCTAssertEqual(NSNumber(value: Float.leastNonzeroMagnitude).description(withLocale: Locale(identifier: "en_GB")), "1.401298E-45")
XCTAssertEqual(NSNumber(value: Float.greatestFiniteMagnitude).description(withLocale: Locale(identifier: "en_GB")), "3.402823E+38")
XCTAssertEqual(NSNumber(value: Float.pi).description(withLocale: Locale(identifier: "en_GB")), "3.141593")
XCTAssertEqual(NSNumber(value: 1.2 as Double).description(withLocale: Locale(identifier: "en_GB")), "1.2")
XCTAssertEqual(NSNumber(value: 1000_000_000 as Double).description(withLocale: Locale(identifier: "en_GB")), "1,000,000,000")
XCTAssertEqual(NSNumber(value: -0.99 as Double).description(withLocale: Locale(identifier: "en_GB")), "-0.99")
XCTAssertEqual(NSNumber(value: Double.zero).description(withLocale: Locale(identifier: "en_GB")), "0")
XCTAssertEqual(NSNumber(value: Double.nan).description(withLocale: Locale(identifier: "en_GB")), "NaN")
XCTAssertEqual(NSNumber(value: Double.leastNormalMagnitude).description(withLocale: Locale(identifier: "en_GB")), "2.225073858507201E-308")
// Currently disabled as the latest ICU (62+) which uses Google's double-conversion library currently converts Double.leastNonzeroMagnitude to 0
// although ICU61 version correctly converted it to 5E-324 - Test left in to check for the bug being fixed in the future.
// This test works in ICU67 so re-enable it after upgrading.
//XCTAssertEqual(NSNumber(value: Double.leastNonzeroMagnitude).description(withLocale: Locale(identifier: "en_GB")), "5E-324")
XCTAssertEqual(NSNumber(value: 2 * Double.leastNonzeroMagnitude).description(withLocale: Locale(identifier: "en_GB")), "1E-323")
XCTAssertEqual(NSNumber(value: Double.greatestFiniteMagnitude).description(withLocale: Locale(identifier: "en_GB")), "1.797693134862316E+308")
// de_DE Locale
XCTAssertEqual(NSNumber(value: 1000).description(withLocale: Locale(identifier: "de_DE")), "1.000")
XCTAssertEqual(NSNumber(value: 0.001).description(withLocale: Locale(identifier: "de_DE")), "0,001")
XCTAssertEqual(NSNumber(value: Int8.min).description(withLocale: Locale(identifier: "de_DE")), "-128")
XCTAssertEqual(NSNumber(value: Int8.max).description(withLocale: Locale(identifier: "de_DE")), "127")
XCTAssertEqual(NSNumber(value: Int16.min).description(withLocale: Locale(identifier: "de_DE")), "-32.768")
XCTAssertEqual(NSNumber(value: Int16.max).description(withLocale: Locale(identifier: "de_DE")), "32.767")
XCTAssertEqual(NSNumber(value: Int32.min).description(withLocale: Locale(identifier: "de_DE")), "-2.147.483.648")
XCTAssertEqual(NSNumber(value: Int32.max).description(withLocale: Locale(identifier: "de_DE")), "2.147.483.647")
XCTAssertEqual(NSNumber(value: Int64.min).description(withLocale: Locale(identifier: "de_DE")), "-9.223.372.036.854.775.808")
XCTAssertEqual(NSNumber(value: Int64.max).description(withLocale: Locale(identifier: "de_DE")), "9.223.372.036.854.775.807")
XCTAssertEqual(NSNumber(value: UInt8.min).description(withLocale: Locale(identifier: "de_DE")), "0")
XCTAssertEqual(NSNumber(value: UInt8.max).description(withLocale: Locale(identifier: "de_DE")), "255")
XCTAssertEqual(NSNumber(value: UInt16.min).description(withLocale: Locale(identifier: "de_DE")), "0")
XCTAssertEqual(NSNumber(value: UInt16.max).description(withLocale: Locale(identifier: "de_DE")), "65.535")
XCTAssertEqual(NSNumber(value: UInt32.min).description(withLocale: Locale(identifier: "de_DE")), "0")
XCTAssertEqual(NSNumber(value: UInt32.max).description(withLocale: Locale(identifier: "de_DE")), "4.294.967.295")
XCTAssertEqual(NSNumber(value: UInt64.min).description(withLocale: Locale(identifier: "de_DE")), "0")
// This is the correct value but currently buggy and the locale is not used
//XCTAssertEqual(NSNumber(value: UInt64.max).description(withLocale: Locale(identifier: "de_DE")), "18.446.744.073.709.551.615")
XCTAssertEqual(NSNumber(value: UInt64.max).description(withLocale: Locale(identifier: "de_DE")), "18446744073709551615")
XCTAssertEqual(NSNumber(value: 1.2 as Float).description(withLocale: Locale(identifier: "de_DE")), "1,2")
XCTAssertEqual(NSNumber(value: 1000_000_000 as Float).description(withLocale: Locale(identifier: "de_DE")), "1E+09")
XCTAssertEqual(NSNumber(value: -0.99 as Float).description(withLocale: Locale(identifier: "de_DE")), "-0,99")
XCTAssertEqual(NSNumber(value: Float.pi).description(withLocale: Locale(identifier: "de_DE")), "3,141593")
XCTAssertEqual(NSNumber(value: Float.zero).description(withLocale: Locale(identifier: "de_DE")), "0")
XCTAssertEqual(NSNumber(value: Float.nan).description(withLocale: Locale(identifier: "de_DE")), "NaN")
XCTAssertEqual(NSNumber(value: Float.leastNormalMagnitude).description(withLocale: Locale(identifier: "de_DE")), "1,175494E-38")
XCTAssertEqual(NSNumber(value: Float.leastNonzeroMagnitude).description(withLocale: Locale(identifier: "de_DE")), "1,401298E-45")
XCTAssertEqual(NSNumber(value: Float.greatestFiniteMagnitude).description(withLocale: Locale(identifier: "de_DE")), "3,402823E+38")
XCTAssertEqual(NSNumber(value: 1.2 as Double).description(withLocale: Locale(identifier: "de_DE")), "1,2")
XCTAssertEqual(NSNumber(value: 1000_000_000 as Double).description(withLocale: Locale(identifier: "de_DE")), "1.000.000.000")
XCTAssertEqual(NSNumber(value: -0.99 as Double).description(withLocale: Locale(identifier: "de_DE")), "-0,99")
XCTAssertEqual(NSNumber(value: Double.zero).description(withLocale: Locale(identifier: "de_DE")), "0")
XCTAssertEqual(NSNumber(value: Double.nan).description(withLocale: Locale(identifier: "de_DE")), "NaN")
XCTAssertEqual(NSNumber(value: Double.leastNormalMagnitude).description(withLocale: Locale(identifier: "de_DE")), "2,225073858507201E-308")
// Currently disabled as the latest ICU (62+) which uses Google's double-conversion library currently converts Double.leastNonzeroMagnitude to 0
// although ICU61 version correctly converted it to 5E-324 - Test left in to check for the bug being fixed in the future.
// This test works in ICU67 so re-enable it after upgrading.
//XCTAssertEqual(NSNumber(value: Double.leastNonzeroMagnitude).description(withLocale: Locale(identifier: "de_DE")), "5E-324")
XCTAssertEqual(NSNumber(value: 2 * Double.leastNonzeroMagnitude).description(withLocale: Locale(identifier: "de_DE")), "1E-323")
XCTAssertEqual(NSNumber(value: Double.greatestFiniteMagnitude).description(withLocale: Locale(identifier: "de_DE")), "1,797693134862316E+308")
}
func test_objCType() {
let objCType: (NSNumber) -> UnicodeScalar = { number in
return UnicodeScalar(UInt8(number.objCType.pointee))
}
XCTAssertEqual("c" /* 0x63 */, objCType(NSNumber(value: true)))
XCTAssertEqual("c" /* 0x63 */, objCType(NSNumber(value: Int8.max)))
XCTAssertEqual("s" /* 0x73 */, objCType(NSNumber(value: UInt8(Int8.max))))
XCTAssertEqual("s" /* 0x73 */, objCType(NSNumber(value: UInt8(Int8.max) + 1)))
XCTAssertEqual("s" /* 0x73 */, objCType(NSNumber(value: Int16.max)))
XCTAssertEqual("i" /* 0x69 */, objCType(NSNumber(value: UInt16(Int16.max))))
XCTAssertEqual("i" /* 0x69 */, objCType(NSNumber(value: UInt16(Int16.max) + 1)))
XCTAssertEqual("i" /* 0x69 */, objCType(NSNumber(value: Int32.max)))
XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: UInt32(Int32.max))))
XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: UInt32(Int32.max) + 1)))
XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: Int64.max)))
// When value is lower equal to `Int64.max`, it returns 'q' even if using `UInt64`
XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: UInt64(Int64.max))))
XCTAssertEqual("Q" /* 0x51 */, objCType(NSNumber(value: UInt64(Int64.max) + 1)))
// Depends on architectures
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: Int.max)))
// When value is lower equal to `Int.max`, it returns 'q' even if using `UInt`
XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: UInt(Int.max))))
XCTAssertEqual("Q" /* 0x51 */, objCType(NSNumber(value: UInt(Int.max) + 1)))
#elseif arch(i386) || arch(arm)
XCTAssertEqual("i" /* 0x71 */, objCType(NSNumber(value: Int.max)))
XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: UInt(Int.max))))
XCTAssertEqual("q" /* 0x51 */, objCType(NSNumber(value: UInt(Int.max) + 1)))
#else
#error("This architecture isn't known. Add it to the 32-bit or 64-bit line.")
#endif
XCTAssertEqual("f" /* 0x66 */, objCType(NSNumber(value: Float.greatestFiniteMagnitude)))
XCTAssertEqual("d" /* 0x64 */, objCType(NSNumber(value: Double.greatestFiniteMagnitude)))
}
func test_stringValue() {
if UInt.max == UInt32.max {
XCTAssertEqual(NSNumber(value: UInt.min).stringValue, "0")
XCTAssertEqual(NSNumber(value: UInt.min + 1).stringValue, "1")
XCTAssertEqual(NSNumber(value: UInt.max).stringValue, "4294967295")
XCTAssertEqual(NSNumber(value: UInt.max - 1).stringValue, "4294967294")
} else if UInt.max == UInt64.max {
XCTAssertEqual(NSNumber(value: UInt.min).stringValue, "0")
XCTAssertEqual(NSNumber(value: UInt.min + 1).stringValue, "1")
XCTAssertEqual(NSNumber(value: UInt.max).stringValue, "18446744073709551615")
XCTAssertEqual(NSNumber(value: UInt.max - 1).stringValue, "18446744073709551614")
}
XCTAssertEqual(NSNumber(value: UInt8.min).stringValue, "0")
XCTAssertEqual(NSNumber(value: UInt8.min + 1).stringValue, "1")
XCTAssertEqual(NSNumber(value: UInt8.max).stringValue, "255")
XCTAssertEqual(NSNumber(value: UInt8.max - 1).stringValue, "254")
XCTAssertEqual(NSNumber(value: UInt16.min).stringValue, "0")
XCTAssertEqual(NSNumber(value: UInt16.min + 1).stringValue, "1")
XCTAssertEqual(NSNumber(value: UInt16.max).stringValue, "65535")
XCTAssertEqual(NSNumber(value: UInt16.max - 1).stringValue, "65534")
XCTAssertEqual(NSNumber(value: UInt32.min).stringValue, "0")
XCTAssertEqual(NSNumber(value: UInt32.min + 1).stringValue, "1")
XCTAssertEqual(NSNumber(value: UInt32.max).stringValue, "4294967295")
XCTAssertEqual(NSNumber(value: UInt32.max - 1).stringValue, "4294967294")
XCTAssertEqual(NSNumber(value: UInt64.min).stringValue, "0")
XCTAssertEqual(NSNumber(value: UInt64.min + 1).stringValue, "1")
XCTAssertEqual(NSNumber(value: UInt64.max).stringValue, "18446744073709551615")
XCTAssertEqual(NSNumber(value: UInt64.max - 1).stringValue, "18446744073709551614")
if Int.max == Int32.max {
XCTAssertEqual(NSNumber(value: Int.min).stringValue, "-2147483648")
XCTAssertEqual(NSNumber(value: Int.min + 1).stringValue, "-2147483647")
XCTAssertEqual(NSNumber(value: Int.max).stringValue, "2147483647")
XCTAssertEqual(NSNumber(value: Int.max - 1).stringValue, "2147483646")
} else if Int.max == Int64.max {
XCTAssertEqual(NSNumber(value: Int.min).stringValue, "-9223372036854775808")
XCTAssertEqual(NSNumber(value: Int.min + 1).stringValue, "-9223372036854775807")
XCTAssertEqual(NSNumber(value: Int.max).stringValue, "9223372036854775807")
XCTAssertEqual(NSNumber(value: Int.max - 1).stringValue, "9223372036854775806")
}
XCTAssertEqual(NSNumber(value: Int8.min).stringValue, "-128")
XCTAssertEqual(NSNumber(value: Int8.min + 1).stringValue, "-127")
XCTAssertEqual(NSNumber(value: Int8.max).stringValue, "127")
XCTAssertEqual(NSNumber(value: Int8.max - 1).stringValue, "126")
XCTAssertEqual(NSNumber(value: Int16.min).stringValue, "-32768")
XCTAssertEqual(NSNumber(value: Int16.min + 1).stringValue, "-32767")
XCTAssertEqual(NSNumber(value: Int16.max).stringValue, "32767")
XCTAssertEqual(NSNumber(value: Int16.max - 1).stringValue, "32766")
XCTAssertEqual(NSNumber(value: Int32.min).stringValue, "-2147483648")
XCTAssertEqual(NSNumber(value: Int32.min + 1).stringValue, "-2147483647")
XCTAssertEqual(NSNumber(value: Int32.max).stringValue, "2147483647")
XCTAssertEqual(NSNumber(value: Int32.max - 1).stringValue, "2147483646")
XCTAssertEqual(NSNumber(value: Int64.min).stringValue, "-9223372036854775808")
XCTAssertEqual(NSNumber(value: Int64.min + 1).stringValue, "-9223372036854775807")
XCTAssertEqual(NSNumber(value: Int64.max).stringValue, "9223372036854775807")
XCTAssertEqual(NSNumber(value: Int64.max - 1).stringValue, "9223372036854775806")
}
func test_Equals() {
// Booleans: false only equals 0, true only equals 1
XCTAssertTrue(NSNumber(value: true) == NSNumber(value: Bool(true)))
XCTAssertTrue(NSNumber(value: true) == NSNumber(value: Int(1)))
XCTAssertTrue(NSNumber(value: true) == NSNumber(value: Float(1)))
XCTAssertTrue(NSNumber(value: true) == NSNumber(value: Double(1)))
XCTAssertTrue(NSNumber(value: true) == NSNumber(value: Int8(1)))
XCTAssertTrue(NSNumber(value: true) != NSNumber(value: false))
XCTAssertTrue(NSNumber(value: true) != NSNumber(value: Int8(-1)))
let f: Float = 1.01
let floatNum = NSNumber(value: f)
XCTAssertTrue(NSNumber(value: true) != floatNum)
let d: Double = 1234.56
let doubleNum = NSNumber(value: d)
XCTAssertTrue(NSNumber(value: true) != doubleNum)
XCTAssertTrue(NSNumber(value: true) != NSNumber(value: 2))
XCTAssertTrue(NSNumber(value: true) != NSNumber(value: Int.max))
XCTAssertTrue(NSNumber(value: false) == NSNumber(value: Bool(false)))
XCTAssertTrue(NSNumber(value: false) == NSNumber(value: Int(0)))
XCTAssertTrue(NSNumber(value: false) == NSNumber(value: Float(0)))
XCTAssertTrue(NSNumber(value: false) == NSNumber(value: Double(0)))
XCTAssertTrue(NSNumber(value: false) == NSNumber(value: Int8(0)))
XCTAssertTrue(NSNumber(value: false) == NSNumber(value: UInt64(0)))
XCTAssertTrue(NSNumber(value: false) != NSNumber(value: 1))
XCTAssertTrue(NSNumber(value: false) != NSNumber(value: 2))
XCTAssertTrue(NSNumber(value: false) != NSNumber(value: Int.max))
XCTAssertTrue(NSNumber(value: Int8(-1)) == NSNumber(value: Int16(-1)))
XCTAssertTrue(NSNumber(value: Int16(-1)) == NSNumber(value: Int32(-1)))
XCTAssertTrue(NSNumber(value: Int32(-1)) == NSNumber(value: Int64(-1)))
XCTAssertTrue(NSNumber(value: Int8.max) != NSNumber(value: Int16.max))
XCTAssertTrue(NSNumber(value: Int16.max) != NSNumber(value: Int32.max))
XCTAssertTrue(NSNumber(value: Int32.max) != NSNumber(value: Int64.max))
XCTAssertTrue(NSNumber(value: UInt8.min) == NSNumber(value: UInt16.min))
XCTAssertTrue(NSNumber(value: UInt16.min) == NSNumber(value: UInt32.min))
XCTAssertTrue(NSNumber(value: UInt32.min) == NSNumber(value: UInt64.min))
XCTAssertTrue(NSNumber(value: UInt8.max) != NSNumber(value: UInt16.max))
XCTAssertTrue(NSNumber(value: UInt16.max) != NSNumber(value: UInt32.max))
XCTAssertTrue(NSNumber(value: UInt32.max) != NSNumber(value: UInt64.max))
XCTAssertTrue(NSNumber(value: Int8(0)) == NSNumber(value: UInt16(0)))
XCTAssertTrue(NSNumber(value: UInt16(0)) == NSNumber(value: Int32(0)))
XCTAssertTrue(NSNumber(value: Int32(0)) == NSNumber(value: UInt64(0)))
XCTAssertTrue(NSNumber(value: Int(0)) == NSNumber(value: UInt(0)))
XCTAssertTrue(NSNumber(value: Int8.min) == NSNumber(value: Float(-128)))
XCTAssertTrue(NSNumber(value: Int8.max) == NSNumber(value: Double(127)))
XCTAssertTrue(NSNumber(value: UInt16.min) == NSNumber(value: Float(0)))
XCTAssertTrue(NSNumber(value: UInt16.max) == NSNumber(value: Double(65535)))
XCTAssertTrue(NSNumber(value: 1.1) != NSNumber(value: Int64(1)))
let num = NSNumber(value: Int8.min)
XCTAssertFalse(num == NSNumber(value: num.uint64Value))
let zero = NSNumber(value: 0)
let one = NSNumber(value: 1)
let minusOne = NSNumber(value: -1)
let intMin = NSNumber(value: Int.min)
let intMax = NSNumber(value: Int.max)
let nanFloat = NSNumber(value: Float.nan)
XCTAssertEqual(nanFloat.compare(nanFloat), .orderedSame)
XCTAssertFalse(nanFloat == zero)
XCTAssertFalse(zero == nanFloat)
XCTAssertEqual(nanFloat.compare(zero), .orderedAscending)
XCTAssertEqual(zero.compare(nanFloat), .orderedDescending)
XCTAssertEqual(nanFloat.compare(one), .orderedAscending)
XCTAssertEqual(one.compare(nanFloat), .orderedDescending)
XCTAssertEqual(nanFloat.compare(intMax), .orderedAscending)
XCTAssertEqual(intMax.compare(nanFloat), .orderedDescending)
XCTAssertEqual(nanFloat.compare(minusOne), .orderedDescending)
XCTAssertEqual(minusOne.compare(nanFloat), .orderedAscending)
XCTAssertEqual(nanFloat.compare(intMin), .orderedDescending)
XCTAssertEqual(intMin.compare(nanFloat), .orderedAscending)
let nanDouble = NSNumber(value: Double.nan)
XCTAssertEqual(nanDouble.compare(nanDouble), .orderedSame)
XCTAssertFalse(nanDouble == zero)
XCTAssertFalse(zero == nanDouble)
XCTAssertEqual(nanDouble.compare(zero), .orderedAscending)
XCTAssertEqual(zero.compare(nanDouble), .orderedDescending)
XCTAssertEqual(nanDouble.compare(one), .orderedAscending)
XCTAssertEqual(one.compare(nanDouble), .orderedDescending)
XCTAssertEqual(nanDouble.compare(intMax), .orderedAscending)
XCTAssertEqual(intMax.compare(nanDouble), .orderedDescending)
XCTAssertEqual(nanDouble.compare(minusOne), .orderedDescending)
XCTAssertEqual(minusOne.compare(nanDouble), .orderedAscending)
XCTAssertEqual(nanDouble.compare(intMin), .orderedDescending)
XCTAssertEqual(intMin.compare(nanDouble), .orderedAscending)
XCTAssertEqual(nanDouble, nanFloat)
XCTAssertEqual(nanFloat, nanDouble)
XCTAssertEqual(NSNumber(value: Double.leastNonzeroMagnitude).compare(NSNumber(value: 0)), .orderedDescending)
XCTAssertEqual(NSNumber(value: Double.greatestFiniteMagnitude).compare(NSNumber(value: 0)), .orderedDescending)
XCTAssertTrue(NSNumber(value: Double(-0.0)) == NSNumber(value: Double(0.0)))
}
func test_boolValue() {
XCTAssertEqual(NSNumber(value: UInt8.max).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt8.min).boolValue, false)
XCTAssertEqual(NSNumber(value: UInt16.max).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt16.min).boolValue, false)
XCTAssertEqual(NSNumber(value: UInt32.max).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt32.min).boolValue, false)
XCTAssertEqual(NSNumber(value: UInt64.max).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt64.min).boolValue, false)
XCTAssertEqual(NSNumber(value: UInt.max).boolValue, true)
XCTAssertEqual(NSNumber(value: UInt.min).boolValue, false)
XCTAssertEqual(NSNumber(value: Int8.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int8.max - 1).boolValue, true)
XCTAssertEqual(NSNumber(value: Int8.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int8.min + 1).boolValue, true)
XCTAssertEqual(NSNumber(value: Int8(-1)).boolValue, true)
XCTAssertEqual(NSNumber(value: Int16.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int16.max - 1).boolValue, true)
XCTAssertEqual(NSNumber(value: Int16.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int16.min + 1).boolValue, true)
XCTAssertEqual(NSNumber(value: Int16(-1)).boolValue, true)
XCTAssertEqual(NSNumber(value: Int32.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int32.max - 1).boolValue, true)
XCTAssertEqual(NSNumber(value: Int32.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int32.min + 1).boolValue, true)
XCTAssertEqual(NSNumber(value: Int32(-1)).boolValue, true)
XCTAssertEqual(NSNumber(value: Int64.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int64.max - 1).boolValue, true)
XCTAssertEqual(NSNumber(value: Int64.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int64.min + 1).boolValue, true)
XCTAssertEqual(NSNumber(value: Int64(-1)).boolValue, true)
XCTAssertEqual(NSNumber(value: Int.max).boolValue, true)
XCTAssertEqual(NSNumber(value: Int.max - 1).boolValue, true)
XCTAssertEqual(NSNumber(value: Int.min).boolValue, true)
XCTAssertEqual(NSNumber(value: Int.min + 1).boolValue, true)
XCTAssertEqual(NSNumber(value: Int(-1)).boolValue, true)
}
func test_hash() {
// A zero double hashes as zero.
XCTAssertEqual(NSNumber(value: 0 as Double).hash, 0)
// A positive double without fractional part should hash the same as the
// equivalent 64 bit number.
XCTAssertEqual(NSNumber(value: 123456 as Double).hash, NSNumber(value: 123456 as Int64).hash)
// A negative double without fractional part should hash the same as the
// equivalent 64 bit number.
XCTAssertEqual(NSNumber(value: -123456 as Double).hash, NSNumber(value: -123456 as Int64).hash)
#if arch(i386) || arch(arm)
// This test used to fail in 32 bit platforms.
XCTAssertNotEqual(NSNumber(value: 551048378.24883795 as Double).hash, 0)
// Some hashes are correctly zero, though. Like the following which
// was found by trial and error.
XCTAssertEqual(NSNumber(value: 1.3819660135 as Double).hash, 0)
#endif
}
}
| apache-2.0 | cd2bd2deeb93bc3453dee2bbdda0411b | 56.804304 | 152 | 0.688663 | 4.025053 | false | true | false | false |
roambotics/swift | benchmark/single-source/Ackermann.swift | 2 | 1597 | //===--- Ackermann.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test is based on test Ackermann from utils/benchmark, with modifications
// for performance measuring.
import TestsUtils
public let benchmarks =
BenchmarkInfo(
name: "Ackermann2",
runFunction: run_Ackermann,
tags: [.algorithm])
func _ackermann(_ m: Int, _ n : Int) -> Int {
if (m == 0) { return n + 1 }
if (n == 0) { return _ackermann(m - 1, 1) }
return _ackermann(m - 1, _ackermann(m, n - 1))
}
@inline(never)
func ackermann(_ m: Int, _ n : Int) -> Int {
// This if prevents optimizer from computing return value of Ackermann(3,9)
// at compile time.
if getFalse() { return 0 }
if (m == 0) { return n + 1 }
if (n == 0) { return _ackermann(m - 1, 1) }
return _ackermann(m - 1, _ackermann(m, n - 1))
}
let ref_result = [5, 13, 29, 61, 125, 253, 509, 1021, 2045, 4093, 8189, 16381, 32765, 65533, 131069]
@inline(never)
public func run_Ackermann(_ N: Int) {
let (m, n) = (3, 6)
var result = 0
for _ in 1...N {
result = ackermann(m, n)
if result != ref_result[n] {
break
}
}
check(result == ref_result[n])
}
| apache-2.0 | c292860d0c4d2f2c0d12fcd444e8ed53 | 29.711538 | 100 | 0.58109 | 3.383475 | false | true | false | false |
mitsuse/mastodon-swift | Sources/Error+APIKit.swift | 1 | 949 | import APIKit
func convert(error: SessionTaskError) -> Error {
switch error {
case .connectionError:
return .connection
case let .requestError(error):
return (error as? RequestError).map(convert) ?? .fatal
case let .responseError(error):
return (error as? ResponseError).map(convert) ?? .fatal
}
}
func convert(error: RequestError) -> Error {
let reason: InvalidRequestReason
switch error {
case let .invalidBaseURL(url): reason = .endpoint(url)
case .unexpectedURLRequest: reason = .unexpected
}
return .request(reason)
}
func convert(error: ResponseError) -> Error {
let reason: InvalidResponseReason
switch error {
case .nonHTTPURLResponse: reason = .broken
case let .unacceptableStatusCode(statusCode): reason = .unacceptableStatusCode(statusCode)
case let .unexpectedObject(object): reason = .unexpectedBody(object)
}
return .response(reason)
}
| mit | a48d8e8d227a03c65c4f48c0e04938e6 | 29.612903 | 94 | 0.694415 | 4.476415 | false | false | false | false |
coolmacmaniac/swift-ios | DesignPatterns/DesignPatterns/Factory/DPTraversableElement.swift | 1 | 1338 | //
// DPTraversableElement.swift
// DesignPatterns
//
// Created by Sourabh on 26/06/17.
// Copyright © 2017 Home. All rights reserved.
//
import Foundation
/**
Specifies the type of element that needs to be used in traversable objects
*/
class DPTraversableElement<T> {
/**
The inherent value that is saved, retrieved and traversed in by the traversable objects, its type `T` is supplied at run time.
*/
let value: T
/**
Specifies the previous element in the traversable object, it holds the references to the similar `DPTraversableElement<T>` objects, and may also be nil.
*/
var previous: DPTraversableElement<T>?
/**
Specifies the next element in the traversable object, it holds the references to the similar `DPTraversableElement<T>` objects, and may also be nil.
*/
var next: DPTraversableElement<T>?
/**
Initializes with a value of type `T` and also provides the directional references for the current element
- parameter previous: a reference to the previous element of type `DPTraversableElement<T>`, defaults to nil
- parameter next: a reference to the next element of type `DPTraversableElement<T>`, defaults to nil
*/
init(value: T, previous: DPTraversableElement<T>? = nil, next: DPTraversableElement<T>? = nil) {
self.value = value
self.previous = previous
self.next = next
}
}
| gpl-3.0 | 871ef8b75a0a11b48fdc06520110abe5 | 30.093023 | 153 | 0.735228 | 3.472727 | false | false | false | false |
brentsimmons/Evergreen | Account/Sources/Account/DataExtensions.swift | 1 | 1725 | //
// DataExtensions.swift
// NetNewsWire
//
// Created by Brent Simmons on 10/7/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
import Articles
import RSParser
public extension Notification.Name {
static let WebFeedSettingDidChange = Notification.Name(rawValue: "FeedSettingDidChangeNotification")
}
public extension WebFeed {
static let WebFeedSettingUserInfoKey = "feedSetting"
struct WebFeedSettingKey {
public static let homePageURL = "homePageURL"
public static let iconURL = "iconURL"
public static let faviconURL = "faviconURL"
public static let name = "name"
public static let editedName = "editedName"
public static let authors = "authors"
public static let contentHash = "contentHash"
public static let conditionalGetInfo = "conditionalGetInfo"
}
}
extension WebFeed {
func takeSettings(from parsedFeed: ParsedFeed) {
iconURL = parsedFeed.iconURL
faviconURL = parsedFeed.faviconURL
homePageURL = parsedFeed.homePageURL
name = parsedFeed.title
authors = Author.authorsWithParsedAuthors(parsedFeed.authors)
}
func postFeedSettingDidChangeNotification(_ codingKey: WebFeedMetadata.CodingKeys) {
let userInfo = [WebFeed.WebFeedSettingUserInfoKey: codingKey.stringValue]
NotificationCenter.default.post(name: .WebFeedSettingDidChange, object: self, userInfo: userInfo)
}
}
public extension Article {
var account: Account? {
// The force unwrapped shared instance was crashing Account.framework unit tests.
guard let manager = AccountManager.shared else {
return nil
}
return manager.existingAccount(with: accountID)
}
var webFeed: WebFeed? {
return account?.existingWebFeed(withWebFeedID: webFeedID)
}
}
| mit | 64368a86a0215c918abc60ba95b64157 | 26.365079 | 101 | 0.772622 | 4.114558 | false | false | false | false |
kstaring/swift | test/expr/cast/array_downcast.swift | 4 | 1599 | // RUN: %target-parse-verify-swift
// XFAIL: linux
// FIXME: Should go into the standard library.
public extension _ObjectiveCBridgeable {
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self {
var result: Self?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
class V {}
class U : V {}
class T : U {}
var v = V()
var u = U()
var t = T()
var va = [v]
var ua = [u]
var ta = [t]
va = ta
var va2: ([V])? = va as [V]
var v2: V = va2![0]
var ua2: ([U])? = va as? [U]
var u2: U = ua2![0]
var ta2: ([T])? = va as? [T]
var t2: T = ta2![0]
// Check downcasts that require bridging.
class A {
var x = 0
}
struct B : _ObjectiveCBridgeable {
func _bridgeToObjectiveC() -> A {
return A()
}
static func _forceBridgeFromObjectiveC(
_ x: A,
result: inout B?
) {
}
static func _conditionallyBridgeFromObjectiveC(
_ x: A,
result: inout B?
) -> Bool {
return true
}
}
func testBridgedDowncastAnyObject(_ arr: [AnyObject], arrOpt: [AnyObject]?,
arrIUO: [AnyObject]!) {
var b = B()
if let bArr = arr as? [B] {
b = bArr[0]
}
if let bArr = arrOpt as? [B] {
b = bArr[0]
}
if let bArr = arrIUO as? [B] {
b = bArr[0]
}
_ = b
}
func testBridgedIsAnyObject(_ arr: [AnyObject], arrOpt: [AnyObject]?,
arrIUO: [AnyObject]!) -> Bool {
let b = B()
if arr is [B] { return arr is [B] }
if arrOpt is [B] { return arrOpt is [B] }
if arrIUO is [B] { return arrIUO is [B] }
_ = b
return false
}
| apache-2.0 | 8834bce3fdc30c19091fa798bacb2823 | 16.966292 | 78 | 0.56035 | 3.069098 | false | false | false | false |
imobilize/Molib | Molib/Classes/Utils/Int+Utils.swift | 1 | 1023 | import Foundation
extension TimeInterval {
public enum Intervals {
public static let secondsInAMinute: Double = 60
public static let secondsInAnHour: Double = 3600
public static let secondsInADay: Double = 86400
}
public func secondsToHoursMinutesSeconds() -> (Int, Int, Int) {
let time = self
return (Int(time / Intervals.secondsInAnHour),
Int((time.truncatingRemainder(dividingBy: Intervals.secondsInAnHour)) / Intervals.secondsInAMinute), Int((time.truncatingRemainder(dividingBy: Intervals.secondsInAnHour)).truncatingRemainder(dividingBy: Intervals.secondsInAMinute)))
}
public func durationInMinsAndSecondsString() -> String {
var durationString = ""
let (_, minutes, seconds) = secondsToHoursMinutesSeconds()
if 0...9 ~= seconds {
durationString = "\(minutes):0\(seconds)"
} else {
durationString = "\(minutes):\(seconds)"
}
return durationString
}
}
| apache-2.0 | 09acab15a9daa750f694a5fe668b8a28 | 27.416667 | 248 | 0.652981 | 5.140704 | false | false | false | false |
giovannipozzobon/PNChart-Swift | PNChartSwift/TableViewChartController.swift | 1 | 8121 | //
// TableViewChart.swift
// PNChartSwift
//
// Created by Giovanni Pozzobon on 11/08/17.
//
//
import Foundation
import UIKit
import Alamofire
import SwiftyJSON
class tableViewChartController: UITableViewController {
var nameCharts = [String]()
var vc_StoryBoardID = [String]()
var datiScambiati : ExchageData = ExchageData()
var chartTypes : Array<String> = [];
//Indicatori di caricamento dei dati
var graphLoaded : Bool = false;
var topOrderLoaded : Bool = false;
var topUserLoaded : Bool = false;
var userDefault: UserDefaultUtility = UserDefaultUtility()
override func viewDidLoad() {
super.viewDidLoad()
// riempi l'array che poi saranno le righe della tabella
nameCharts = ["Line Chart", "Bar Chart", "Pie Chart", "Top Order", "Top User", "Dett Order"]
// anche se non usate per ora prepariamo la gestione di più ViewControll chiamati una per una ogni riga della tabella
vc_StoryBoardID = ["Chart", "Chart", "Chart", "Information", "Information", "Information"]
// inizializza le variabili flag che indicano il caricamenteo dei dati
datiScambiati.graphLoaded = false
datiScambiati.topUserLoaded = false
datiScambiati.topOrderLoaded = false
// carica gli URL utente
userDefault.readValueUser()
// carica i dati per i grafici
caricaJSONOrdini()
// carica i dati per il TopOrders
caricaJSONTopOrders()
// carica i dati per i TopUsers
caricaJSONTopUsers()
/* codice per uso di test per verificare le risposte dei vari WebServices
Alamofire.request(querypoint, method: .post, parameters: parameters, encoding: JSONEncoding.default).response { response in
//Alamofire.request("http://188.125.99.46:61862/QueryPoint/term.getOrdersAmount?qry={"startDate": "20100501","endDate": "20180505"}").response { response in
print("Request: \(String(describing: response.request))")
print("Response: \(String(describing: response.response))")
print("Error: \(String(describing: response.error))")
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}*/
}
// MARK: -
// MARK: caricamento JSON
func caricaJSONOrdini() -> Void {
//let querypointGraph : String = String("http://88.36.205.44:61862/QueryPoint/term.getOrdersAmount?qry=")
//let querypointGraph : String = String("http://192.168.0.230:61862/QueryPoint/term.getOrdersAmount?qry=")
let querypointGraph = userDefault.urlOrder
print(querypointGraph)
let parametersGraph: Parameters = [
"startDate": "20170712",
"endDate": "20170801"
]
Alamofire.request(querypointGraph, method: .post, parameters: parametersGraph, encoding: JSONEncoding.default).responseJSON
{ (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["results"].arrayObject {
self.datiScambiati.arrGraphRes = resData as! [[String:AnyObject]]
print("datiScambiati.arrGraphRes: \(self.datiScambiati.arrGraphRes) \n")
}
self.datiScambiati.graphLoaded = true
}
}
}
func caricaJSONTopOrders() -> Void {
//let querypointTopOrder : String = String("http://88.36.205.44:61862/QueryPoint/term.getTopOrder?qry=")
//let querypointTopOrder : String = String("http://192.168.0.230:61862/QueryPoint/term.getTopOrder?qry=")
let querypointTopOrder = userDefault.urlCustomer
print(querypointTopOrder)
let parametersTopOrder: Parameters = [
"Date": "20170504"
]
// carica i dati del top order
Alamofire.request(querypointTopOrder, method: .post, parameters: parametersTopOrder, encoding: JSONEncoding.default).responseJSON
{ (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["results"].arrayObject {
self.datiScambiati.arrTopOrderRes = resData as! [[String:AnyObject]]
print("datiScambiati.arrTopOrderRes: \(self.datiScambiati.arrTopOrderRes)")
}
self.datiScambiati.topOrderLoaded = true
}
}
}
func caricaJSONTopUsers() -> Void {
//let querypointTopUser : String = String("http://88.36.205.44:61862/QueryPoint/term.getTopUser?qry=")
//let querypointTopUser : String = String("http://192.168.0.230:61862/QueryPoint/term.getTopUser?qry=")
let querypointTopUser = userDefault.urlSales
print(querypointTopUser)
let parametersTopUser: Parameters = [
"startDate": "20100501",
"endDate": "20180505"
]
// carica i dati del top user
Alamofire.request(querypointTopUser, method: .post, parameters: parametersTopUser, encoding: JSONEncoding.default).responseJSON
{ (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["results"].arrayObject {
self.datiScambiati.arrTopUserRes = resData as! [[String:AnyObject]]
print("datiScambiati.arrTopUserRes: \(self.datiScambiati.arrTopUserRes) \n")
}
self.datiScambiati.topUserLoaded = true
}
}
}
// MARK: -
// MARK: Lifecycle Tabella
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameCharts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = nameCharts[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc_Name = vc_StoryBoardID[indexPath.row]
let viewController = (storyboard?.instantiateViewController(withIdentifier: vc_Name) as! TemplateViewController)
viewController.exchangeData = datiScambiati
viewController.chartType = nameCharts[indexPath.row]
self.navigationController?.pushViewController(viewController, animated: true)
}
/* Questa funzione non viene chiamata perchè viene usata quella della ViewTable
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var indexPath : IndexPath = self.tableView.indexPathForSelectedRow!
let destViewController = segue.destination as! ChartViewController
destViewController.exchangeData = datiScambiati
destViewController.chartType = nameCharts[indexPath.row]
} */
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | fa122e0939bdf460dd5504d55a978c1a | 34.76652 | 165 | 0.586279 | 4.5638 | false | false | false | false |
wuhduhren/Mr-Ride-iOS | Mr-Ride-iOS/Model/MapData/PublicToilets/PublicToiletModel.swift | 1 | 889 | //
// PublicToiletModel.swift
// Mr-Ride-iOS
//
// Created by Eph on 2016/6/24.
// Copyright © 2016年 AppWorks School WuDuhRen. All rights reserved.
//
import CoreLocation
class PublicToiletModel {
let identifier: String
let name: String
let location: String
let district: String
let coordinate: CLLocationCoordinate2D
let forTheDisabled: Bool
init(identifier: String,
name: String,
location: String,
district: String,
coordinate: CLLocationCoordinate2D,
forTheDisabled: Bool
) {
self.identifier = identifier
self.name = name
self.location = location
self.district = district
self.coordinate = coordinate
self.forTheDisabled = forTheDisabled
}
} | mit | b7dc675647dd2ea4f43132d7faf28b77 | 17.87234 | 68 | 0.572235 | 4.922222 | false | false | false | false |
CoderST/DYZB | DYZB/DYZB/Class/Live/Controller/LiveViewController.swift | 1 | 3353 | //
// LiveViewController.swift
// DYZB
//
// Created by xiudou on 2017/6/17.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
class LiveViewController: UIViewController {
// MARK:- 懒加载
fileprivate lazy var liveViewModel : LiveViewModel = LiveViewModel()
// MARK:- 生命周期
override func viewDidLoad() {
super.viewDidLoad()
loadTitlesDatas()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.statusBarStyle = .lightContent
removeOrAddTitleView(isHidden: false, navigationBar: navigationController!.navigationBar)
setStatusBarBackgroundColor(UIColor.orange)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = .default
removeOrAddTitleView(isHidden: true, navigationBar: navigationController!.navigationBar)
setStatusBarBackgroundColor(UIColor.clear)
}
// 移除和添加titleView
fileprivate func removeOrAddTitleView(isHidden : Bool, navigationBar : UINavigationBar) {
for subView in navigationBar.subviews{
if subView is STTitlesView{
subView.isHidden = isHidden
}
}
}
///设置状态栏背景颜色
func setStatusBarBackgroundColor(_ color : UIColor) {
let statusBarWindow : UIView = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView
let statusBar : UIView = statusBarWindow.value(forKey: "statusBar") as! UIView
if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
statusBar.backgroundColor = color
}
}
}
// MARK:- UI设置
extension LiveViewController {
func loadTitlesDatas() {
liveViewModel.loadLiveTitles {
// 获得titles数据
let liveModelDatas = self.liveViewModel.liveModelDatas
// 去除titles
var titles : [String] = [String]()
// 创建零时数组
var childsVC = [UIViewController]()
for liveModelData in liveModelDatas{
let title = liveModelData.cate_name
titles.append(title)
let subVC = LiveSubViewController()
subVC.cate_id = liveModelData.cate_id
childsVC.append(subVC)
}
let rect = CGRect(x: 0, y: 64, width: sScreenW, height: sScreenH - sStatusBarH - sNavatationBarH - sTabBarH)
// 样式
let style = STPageViewStyle()
style.isShowScrollLine = true
style.isScrollEnable = true
style.normalColor = UIColor(r: 250, g: 250, b: 250, alpha: 0.8)
style.selectColor = UIColor(r: 255.0, g: 255.0, b: 255.0)
style.bottomLineColor = UIColor.white
style.titleViewBackgroundColor = UIColor.orange
// titleView
let titleView = self.navigationController?.navigationBar
let pageView = STPageView(frame: rect, titles: titles, childsVC: childsVC, parentVC: self, style: style, titleViewParentView: titleView)
self.view.addSubview(pageView)
}
}
}
| mit | 4783d2598d59ba632e6014c59b13e69f | 31.76 | 148 | 0.615995 | 4.993902 | false | false | false | false |
smoope/ios-sdk | Pod/Classes/SPUserMetadata.swift | 1 | 1195 | /*
* Copyright 2016 smoope GmbH
*
* 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
public class SPUserMetadata: SPBase {
public var data: [String:String]
public required init(data: [String: AnyObject]) {
self.data = [:]
super.init(data: data)
if let data = data["data"] as? [String:String] {
data.forEach { key, value in
self.data[key] = value
}
}
}
public override func unmap() -> [String: AnyObject] {
var temp: [String: String] = [:]
data.forEach { key, value in
temp[key] = value
}
var result: [String: AnyObject] = ["data": temp]
return result
.append(super.unmap())
}
} | apache-2.0 | 3c2a30a34f6b851f50f6d79d2fc7bff8 | 25.577778 | 74 | 0.661925 | 3.892508 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Widgets/OneLineTableViewCell.swift | 2 | 6430 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
enum OneLineTableViewCustomization {
case regular
case inactiveCell
}
struct OneLineTableViewCellViewModel {
let title: String?
var leftImageView: UIImage?
var leftImageViewContentView: UIView.ContentMode
let accessoryView: UIImageView?
let accessoryType: UITableViewCell.AccessoryType
}
class OneLineTableViewCell: UITableViewCell,
ReusableCell,
ThemeApplicable {
// Tableview cell items
struct UX {
static let imageSize: CGFloat = 29
static let borderViewMargin: CGFloat = 16
static let labelFontSize: CGFloat = 17
static let verticalMargin: CGFloat = 8
static let leftImageViewSize: CGFloat = 28
static let separatorViewHeight: CGFloat = 0.7
static let labelMargin: CGFloat = 4
static let shortLeadingMargin: CGFloat = 5
static let longLeadingMargin: CGFloat = 13
static let cornerRadius: CGFloat = 5
}
var shouldLeftAlignTitle = false
var customization: OneLineTableViewCustomization = .regular
private lazy var selectedView: UIView = .build { _ in }
private lazy var containerView: UIView = .build { _ in }
lazy var leftImageView: UIImageView = .build { imageView in
imageView.contentMode = .scaleAspectFit
imageView.layer.cornerRadius = UX.cornerRadius
imageView.clipsToBounds = true
}
lazy var titleLabel: UILabel = .build { label in
label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body,
size: UX.labelFontSize)
label.textAlignment = .natural
}
private lazy var bottomSeparatorView: UIView = .build { separatorLine in
// separator hidden by default
separatorLine.isHidden = true
separatorLine.backgroundColor = UIColor.Photon.Grey40
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var defaultSeparatorInset: UIEdgeInsets {
return UIEdgeInsets(top: 0,
left: UX.imageSize + 2 * UX.borderViewMargin,
bottom: 0,
right: 0)
}
private func setupLayout() {
separatorInset = defaultSeparatorInset
selectionStyle = .default
containerView.addSubviews(leftImageView,
titleLabel,
bottomSeparatorView)
contentView.addSubview(containerView)
bringSubviewToFront(containerView)
let containerViewTrailingAnchor = accessoryView?.leadingAnchor ?? contentView.trailingAnchor
let midViewLeadingMargin: CGFloat = shouldLeftAlignTitle ? UX.shortLeadingMargin : UX.longLeadingMargin
NSLayoutConstraint.activate([
containerView.topAnchor.constraint(equalTo: contentView.topAnchor,
constant: UX.verticalMargin),
containerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor,
constant: -UX.verticalMargin),
containerView.trailingAnchor.constraint(equalTo: containerViewTrailingAnchor),
leftImageView.centerYAnchor.constraint(equalTo: titleLabel.centerYAnchor),
leftImageView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor,
constant: UX.borderViewMargin),
leftImageView.widthAnchor.constraint(equalToConstant: UX.leftImageViewSize),
leftImageView.heightAnchor.constraint(equalToConstant: UX.leftImageViewSize),
leftImageView.trailingAnchor.constraint(equalTo: titleLabel.leadingAnchor,
constant: -midViewLeadingMargin),
titleLabel.topAnchor.constraint(equalTo: containerView.topAnchor,
constant: UX.labelMargin),
titleLabel.bottomAnchor.constraint(equalTo: containerView.bottomAnchor,
constant: -UX.labelMargin),
titleLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor,
constant: -UX.verticalMargin),
bottomSeparatorView.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
bottomSeparatorView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
bottomSeparatorView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
bottomSeparatorView.heightAnchor.constraint(equalToConstant: UX.separatorViewHeight)
])
selectedBackgroundView = selectedView
}
override func prepareForReuse() {
super.prepareForReuse()
selectionStyle = .default
separatorInset = defaultSeparatorInset
titleLabel.text = nil
leftImageView.image = nil
}
// To simplify setup, OneLineTableViewCell now has a viewModel
// Use it for new code, replace when possible in old code
func configure(viewModel: OneLineTableViewCellViewModel) {
titleLabel.text = viewModel.title
leftImageView.image = viewModel.leftImageView
leftImageView.contentMode = viewModel.leftImageViewContentView
accessoryView = viewModel.accessoryView
editingAccessoryType = viewModel.accessoryType
}
func configureTapState(isEnabled: Bool) {
titleLabel.alpha = isEnabled ? 1.0 : 0.5
leftImageView.alpha = isEnabled ? 1.0 : 0.5
}
func applyTheme(theme: Theme) {
selectedView.backgroundColor = theme.colors.layer5Hover
backgroundColor = theme.colors.layer5
titleLabel.textColor = theme.colors.textPrimary
bottomSeparatorView.backgroundColor = theme.colors.borderPrimary
}
}
| mpl-2.0 | 560e4e7a4b08a7908a9ab0f992901549 | 41.026144 | 111 | 0.652877 | 5.998134 | false | false | false | false |
NSObjects/OMGImagePicker | OMGImagePicker/Classes/AlbumTableViewController.swift | 1 | 4903 | //
// AlbumTableViewController.swift
// ImagePickController
//
// Created by 林涛 on 2016/12/9.
// Copyright © 2016年 林涛. All rights reserved.
//
import UIKit
import Photos
protocol AlbumTableViewControllerDelegate:NSObjectProtocol {
func albumViewController(vc:AlbumTableViewController, didSelect assetCollection:PHAssetCollection)
func albumViewController(vc:AlbumTableViewController, didAllPhoto result:PHFetchResult<PHAsset>)
}
class AlbumTableViewController: UITableViewController {
private enum Section: Int {
case allPhotos = 0
case smartAlbums
static let count = 2
}
public weak var delegate:AlbumTableViewControllerDelegate?
fileprivate var thumbnailSize: CGSize!
fileprivate let imageManager = PHCachingImageManager()
fileprivate var allPhotos: PHFetchResult<PHAsset>?
fileprivate var smartAlbums:[PHAssetCollection]?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(AlbumTableViewCell.self, forCellReuseIdentifier: String(describing: AlbumTableViewCell.self))
tableView.tableFooterView = UIView(frame: CGRect.zero)
let allPhotosOptions = PHFetchOptions()
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
allPhotos = PHAsset.fetchAssets(with: allPhotosOptions)
let albums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
var smartAlbums = [PHAssetCollection]()
albums.enumerateObjects({ (collection, index, stop) in
let result = PHAsset.fetchAssets(in: collection, options: nil)
if result.count > 0 {
smartAlbums.append(collection)
}
})
self.smartAlbums = smartAlbums
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.superview?.layer.cornerRadius = 0
view.superview?.backgroundColor = UIColor.white
let scale = UIScreen.main.scale
thumbnailSize = CGSize(width: 100 * scale, height: 100 * scale)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .allPhotos: return 1
case .smartAlbums: return smartAlbums?.count ?? 0
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return Section.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Section(rawValue: indexPath.section)! {
case .allPhotos:
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: AlbumTableViewCell.self), for: indexPath) as! AlbumTableViewCell
cell.titleLabel.text = NSLocalizedString("All Photos", comment: "")
if let allPhotos = allPhotos {
cell.photoCount.text = "\(allPhotos.count)"
if let asset = allPhotos.firstObject {
imageManager.requestImage(for: asset, targetSize: thumbnailSize, contentMode: .aspectFill, options: nil, resultHandler: { image, _ in
cell.thumbnailImage.image = image
})
}
}
return cell
case .smartAlbums:
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: AlbumTableViewCell.self), for: indexPath) as! AlbumTableViewCell
let collection = smartAlbums![indexPath.row]
let option = PHFetchOptions()
option.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let photos = PHAsset.fetchAssets(in: collection, options: option)
cell.photoCount.text = "\(photos.count)"
if let asset = photos.firstObject {
imageManager.requestImage(for: asset, targetSize: thumbnailSize, contentMode: .aspectFill, options: nil, resultHandler: { image, _ in
cell.thumbnailImage.image = image
})
}
cell.titleLabel.text = collection.localizedTitle
return cell
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 101
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch Section(rawValue: indexPath.section)! {
case .allPhotos:
delegate?.albumViewController(vc: self, didAllPhoto: allPhotos!)
case .smartAlbums:
delegate?.albumViewController(vc: self, didSelect: smartAlbums![indexPath.row])
}
}
}
| mit | e0d0eaf1abfb083a58158f0731dcf618 | 39.766667 | 153 | 0.65372 | 5.472036 | false | false | false | false |
macc704/iKF | iKF/KFService.swift | 1 | 20184 | //
// KFService.swift
// iKF
//
// Created by Yoshiaki Matsuzawa on 2014-07-23.
// Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved.
//
import UIKit
private let kfServiceInstance = KFService();
class KFService: NSObject {
class func getInstance() -> KFService{
return kfServiceInstance;
}
private var host:String?;
private var baseURL:String?;
var username:String?
var password:String?
private var jsonScanner = KFJSONScanner();
//cache
var currentRegistration:KFRegistration!;
var currentUser:KFUser!;
private var editTemplate:String?;
private var readTemplate:String?;
private var mobileJS:String?;
private override init(){
}
func initialize(host:String){
self.host = host;
self.baseURL = "http://\(host)/kforum/";
//clear cache
self.currentRegistration = nil;
self.currentUser = nil;
self.editTemplate = nil;
self.readTemplate = nil;
self.mobileJS = nil;
}
func getHost() -> String{
return self.host!;
}
func getHostURLString() -> String{
return "http://\(host!)/";
}
func getAppURL() -> String{
return self.baseURL!;
}
func getHostURL() -> NSURL{
return NSURL(string: getHostURLString())!;
}
func testConnectionToGoogle() -> Bool{
return self.test("http://www.google.com/").getStatusCode() == 200;
}
func testConnectionToTheHost() -> Bool{
return self.test(self.baseURL!).getStatusCode() == 200;
}
func test(urlString:String) -> KFHttpResponse{
let req = KFHttpRequest(urlString: urlString, method: "GET");
req.nsRequest.timeoutInterval = 12.0;
let res = KFHttpConnection.connect(req);
return res;
}
func getURL(urlString:String) -> String?{
let req = KFHttpRequest(urlString: urlString, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
return nil;
}
return res.getBodyAsString();
}
func login(userName:String, password:String) -> Bool{
logout();
let url = "\(self.baseURL!)rest/account/userLogin";
let req = KFHttpRequest(urlString: url, method: "POST");
req.addParam("userName", value: userName);
req.addParam("password", value: password);
self.username = userName;
self.password = password;
let res = KFHttpConnection.connect(req);
return res.getStatusCode() == 200;
}
private func logout() -> Bool{
let url = "\(self.baseURL!)rest/account/userLogout";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
return res.getStatusCode() == 200;
}
func refreshCurrentUser() -> Bool{
let url = "\(self.baseURL!)rest/account/currentUser";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in currentUser() code=\(res.getStatusCode())");
return false;
}
let json = res.getBodyAsJSON();
let user = jsonScanner.scanUser(json);
self.currentUser = user;
return true;
}
func registerCommunity(registrationCode:String) -> Bool{
let url = "\(self.baseURL!)rest/mobile/register/" + registrationCode;
let req = KFHttpRequest(urlString: url, method: "POST");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in registerCommunity() code=\(res.getStatusCode())");
return false;
}
return true;
}
func getRegistrations() -> [KFRegistration]{
let url = "\(self.baseURL!)rest/account/registrations";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in getRegistrations() code=\(res.getStatusCode())");
return [];
}
return jsonScanner.scanRegistrations(res.getBodyAsJSON()).array;
}
func enterCommunity(registration:KFRegistration) -> Bool{
let url = "\(self.baseURL!)rest/account/selectSection/\(registration.guid)";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in enterCommunity() code=\(res.getStatusCode())");
return false;
}
self.currentRegistration = registration;
return true;
}
func refreshViews(){
self.currentRegistration.community.views = getViews(self.currentRegistration.community.guid);
}
private func getViews(communityId:String) -> KFModelArray<KFView>{
// let url = "\(self.baseURL!)rest/content/getSectionViews/\(communityId)";
let url = "\(self.baseURL!)rest/mobile/getViewsOrdered/\(communityId)";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in getViews() code=\(res.getStatusCode())");
return KFModelArray<KFView>();
}
return jsonScanner.scanViews(res.getBodyAsJSON());
}
func refreshMembers(){
self.currentRegistration.community.members = getMembers(self.currentRegistration.community.guid);
}
private func getMembers(communityId:String) -> KFModelArray<KFUser>{
let url = "\(self.baseURL!)rest/mobile/getMembers/\(communityId)";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in getViews() code=\(res.getStatusCode())");
return KFModelArray<KFUser>();
}
return jsonScanner.scanUsers(res.getBodyAsJSON());
}
func getAllPosts() -> KFModelArray<KFPost>{
let url = "\(self.baseURL!)rest/mobile/getPostsOrdered/\(currentRegistration.community.guid)";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in getPostsOrdered() code=\(res.getStatusCode())");
return KFModelArray<KFPost>();
}
return jsonScanner.scanPosts(res.getBodyAsJSON());
}
func getPost(postId:String) -> KFPost?{
let url = "\(self.baseURL!)rest/mobile/getPost/\(postId)";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in getPost() code=\(res.getStatusCode())");
return nil;
}
let json = res.getBodyAsJSON();
let post = jsonScanner.scanPost(json["body"]);
//builds-on parsing ommited now
return post;
}
func getPostRefs(viewId:String) -> [String: KFReference]{
let url = "\(self.baseURL!)rest/mobile/getView/\(viewId)";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in getPosts() code=\(res.getStatusCode())");
return [:];
}
let json = res.getBodyAsJSON();
let dic = jsonScanner.scanView(json).dic;
return dic;
}
func getPostRef(postRefId:String) -> KFReference?{
let url = "\(self.baseURL!)rest/mobile/getPostRef/\(postRefId)";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in getPosts() code=\(res.getStatusCode())");
return nil;
}
let json = res.getBodyAsJSON();
let ref = jsonScanner.scanPostRef(json["body"]);
for each in json["buildsons"].asArray! {
let fromId = each["from"].asString!;
let toId = each["to"].asString!; //parent
if(fromId == ref.post!.guid){ //be supposed to
ref.post!.buildsOn = getPost(toId);
}
}
return ref;
}
func updatePostAuthors(post:KFPost) -> Bool{
let url = "\(self.baseURL!)rest/mobile/updatePostAuthors/\(post.guid)";
let req = KFHttpRequest(urlString: url, method: "POST");
req.addParams("authorIds", values: post.authors.keys.array);
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in updatePostRef() code=\(res.getStatusCode())");
return false;
}
return true;
}
func updatePostRef(viewId:String, postRef:KFReference) -> Bool{
postRef.location.x = max(5, postRef.location.x);//avoid minus
postRef.location.y = max(5, postRef.location.y);//avoid minus
postRef.location.x = min(3995, postRef.location.x);//avoid over range
postRef.location.y = min(2995, postRef.location.y);//avoid over range
if(postRef.isShowInPlace() && postRef.width < 50){
postRef.width = 50;
}
if(postRef.isShowInPlace() && postRef.height < 50){
postRef.height = 50;
}
let url = "\(self.baseURL!)rest/mobile/updatePostRef/\(viewId)/\(postRef.guid)";
let req = KFHttpRequest(urlString: url, method: "POST");
req.addParam("x", value: String(Int(postRef.location.x)));
req.addParam("y", value: String(Int(postRef.location.y)));
//println(postRef.width);
//println(postRef.height);
req.addParam("width", value: String(Int(postRef.width)));
req.addParam("height", value: String(Int(postRef.height)));
req.addParam("rotation", value: "\(Double(postRef.rotation))");
req.addParam("display", value: String(Int(postRef.displayFlags)));
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in updatePostRef() code=\(res.getStatusCode())");
return false;
}
return true;
}
func deletePostRef(viewId:String, postRef:KFReference) -> Bool{
let url = "\(self.baseURL!)rest/mobile/deletePostRef/\(viewId)/\(postRef.guid)";
let req = KFHttpRequest(urlString: url, method: "POST");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in deletePostRef() code=\(res.getStatusCode())");
return false;
}
return true;
}
func getNoteAsHTML(post:KFPost) -> String{
let url = "\(self.baseURL!)rest/mobile/getNoteAsHTMLwJS/\(post.guid)";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in getNoteAsHTML() code=\(res.getStatusCode())");
return "";
}
return req.getBodyAsString();
}
func readPost(post:KFPost) -> Bool{
let url = "\(self.baseURL!)rest/mobile/readPost/\(post.guid)";
let req = KFHttpRequest(urlString: url, method: "POST");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in readPost() code=\(res.getStatusCode())");
return false;
}
return true;
}
func createView(title:String, viewIdToLink:String?, location:CGPoint?, isPrivate:Bool) -> Bool{
let url = "\(self.baseURL!)rest/mobile/createView/";
let req = KFHttpRequest(urlString: url, method: "POST");
if(viewIdToLink != nil){
req.addParam("viewIdToLink", value: viewIdToLink!);
req.addParam("x", value: String(Int(location!.x)));
req.addParam("y", value: String(Int(location!.y)));
req.addParam("isPrivate", value: "\(isPrivate)");
}
req.addParam("title", value: title);
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in createView() code=\(res.getStatusCode())");
return false;
}
return true;
}
func createNote(viewId:String, buildsOn:KFReference? = nil, location:CGPoint, title:String = "NewNote", body:String = "") -> Bool{
let url = "\(self.baseURL!)rest/mobile/createNote/\(viewId)";
let req = KFHttpRequest(urlString: url, method: "POST");
req.addParam("x", value: String(Int(location.x)));
req.addParam("y", value: String(Int(location.y)));
req.addParam("title", value: title);
req.addParam("body", value: body);
if(buildsOn != nil){
req.addParam("buildsOnNoteId", value: buildsOn!.guid);
}
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in createNote() code=\(res.getStatusCode())");
return false;
}
return true;
}
func createViewLink(fromViewId:String, toViewId:String, location:CGPoint) -> Bool{
let url = "\(self.baseURL!)rest/mobile/createViewLink/\(fromViewId)/\(toViewId)";
let req = KFHttpRequest(urlString: url, method: "POST");
req.addParam("x", value: String(Int(location.x)));
req.addParam("y", value: String(Int(location.y)));
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in createViewLink() code=\(res.getStatusCode())");
return false;
}
return true;
}
func createPostLink(fromViewId:String, toPostId:String, location:CGPoint) -> Bool{
let url = "\(self.baseURL!)rest/mobile/createPostLink/\(fromViewId)/\(toPostId)";
let req = KFHttpRequest(urlString: url, method: "POST");
req.addParam("x", value: String(Int(location.x)));
req.addParam("y", value: String(Int(location.y)));
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in createPostLink() code=\(res.getStatusCode())");
return false;
}
return true;
}
func updateNote(note:KFNote)->Bool{
let url = "\(self.baseURL!)rest/mobile/updateNote/\(note.guid)";
let req = KFHttpRequest(urlString: url, method: "POST");
req.addParam("title", value: note.title);
req.addParam("body", value: note.content);
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in updateNote() code=\(res.getStatusCode())");
return false;
}
return true;
}
func getScaffolds(viewId:String) -> [KFScaffold]{
let url = "\(self.baseURL!)rest/mobile/getScaffolds/\(viewId)";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in getScaffolds() code=\(res.getStatusCode())");
return [];
}
return jsonScanner.scanScaffolds(res.getBodyAsJSON()).array;
}
func getNextViewVersionAsync(viewId:String, currentVersion:Int) -> Int{
let url = "\(self.baseURL!)rest/mobile/getNextViewVersionAsync/\(viewId)/\(String(currentVersion))";
let req = KFHttpRequest(urlString: url, method: "GET");
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in getNextViewVersionAsync() code=\(res.getStatusCode())");
return -1;
}
return res.getBodyAsString().toInt()!;
}
func createPicture(image:UIImage, viewId:String, location:CGPoint) -> Bool{
let imageData = UIImagePNGRepresentation(image);
let filenameBase = iKFUtil.generateRandomString(8);
let filename = "\(filenameBase!).png";
let jsonobj = self.sendAttachment(imageData, mime: "image/png", filename: filename);
if(jsonobj == nil){
return false;
}
let w = Int(image.size.width);
let h = Int(image.size.height);
let attachmentURL = jsonobj!["url"].asString!;
var svg = NSMutableString();
svg.appendFormat("<svg width=\"%d\" height=\"%d\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">", w, h);
svg.appendFormat("<g id=\"group\">");
svg.appendFormat("<title>Layer 1</title>");
svg.appendFormat("<image xlink:href=\"/%@\" id=\"svg_5\" x=\"0\" y=\"0\" width=\"%d\" height=\"%d\" />", attachmentURL, w, h);
svg.appendFormat("</g></svg>");
let drawingResult = self.createDrawing(viewId, svg: svg, location: location);
return drawingResult;
}
private func sendAttachment(data:NSData, mime:String, filename:String) -> JSON?{
// generate url
let url = "\(self.baseURL!)rest/file/easyUpload/" + currentRegistration.community.guid;
// generate form boundary
let key = iKFUtil.generateRandomString(16);
let formBoundary = "----FormBoundary\(key!)";
let path = "C\\fakepath\\\(filename)";
// generate post body
let postbody = NSMutableData();
postbody.appendData(stringData(String(format:"--%@\n", formBoundary)));
postbody.appendData(stringData(String(format:"Content-Disposition: form-data; name=\"upload\"; filename=\"%@\"\n", filename)));
postbody.appendData(stringData(String(format:"Content-Type: %@\n\n", mime)));
postbody.appendData(data);
postbody.appendData(stringData(String(format:"\n")));
postbody.appendData(stringData(String(format:"--%@\n", formBoundary)));
postbody.appendData(stringData(String(format:"Content-Disposition: form-data; name=\"name\"\n")));
postbody.appendData(stringData(String(format:"\n")));
postbody.appendData(stringData(String(format:"%@", path)));
postbody.appendData(stringData(String(format:"\n")));
postbody.appendData(stringData(String(format:"--%@--\n", formBoundary)));
// generate req
let req = KFHttpRequest(urlString: url, method: "POST");
req.nsRequest.setValue(String(format:"multipart/form-data; boundary=%@", formBoundary), forHTTPHeaderField: "Content-Type");
req.nsRequest.setValue(String(postbody.length), forHTTPHeaderField: "Content-Length");
req.nsRequest.HTTPBody = postbody;
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in sendAttachment() code=\(res.getStatusCode())");
return nil;
}
return res.getBodyAsJSON();
}
private func stringData(text:String) -> NSData{
return text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!;
}
private func createDrawing(viewId:String, svg:String, location:CGPoint) -> Bool{
let url = "\(self.baseURL!)rest/mobile/createDrawing/\(viewId)";
let req = KFHttpRequest(urlString: url, method: "POST");
req.addParam("x", value: String(Int(location.x)));
req.addParam("y", value: String(Int(location.y)));
req.addParam("svg", value: svg);
let res = KFHttpConnection.connect(req);
if(res.getStatusCode() != 200){
handleError("in createDrawing() code=\(res.getStatusCode())");
return false;
}
return true;
}
func handleError(msg:String){
//KFAppUtils.debug("KFService: Error: \(msg)");
KFAppUtils.showAlert("KFService Error: \(msg)", msg: "Please check connection.");
}
}
| gpl-2.0 | 5ad8bd1afa155d14efe809adb1b35d10 | 38.968317 | 190 | 0.596562 | 4.127607 | false | false | false | false |
phatblat/realm-cocoa | RealmSwift/Tests/ObjectSchemaTests.swift | 2 | 8113 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import RealmSwift
class ObjectSchemaTests: TestCase {
var objectSchema: ObjectSchema!
var swiftObjectSchema: ObjectSchema {
return try! Realm().schema["SwiftObject"]!
}
func testProperties() {
let objectSchema = swiftObjectSchema
let propertyNames = objectSchema.properties.map { $0.name }
XCTAssertEqual(propertyNames,
["boolCol", "intCol", "int8Col", "int16Col", "int32Col", "int64Col", "intEnumCol", "floatCol", "doubleCol",
"stringCol", "binaryCol", "dateCol", "decimalCol",
"objectIdCol", "objectCol", "uuidCol", "anyCol", "arrayCol", "setCol", "mapCol"]
)
}
// Cannot name testClassName() because it interferes with the method on XCTest
func testClassNameProperty() {
let objectSchema = swiftObjectSchema
XCTAssertEqual(objectSchema.className, "SwiftObject")
}
func testObjectClass() {
let objectSchema = swiftObjectSchema
XCTAssertTrue(objectSchema.objectClass === SwiftObject.self)
}
func testPrimaryKeyProperty() {
let objectSchema = swiftObjectSchema
XCTAssertNil(objectSchema.primaryKeyProperty)
XCTAssertEqual(try! Realm().schema["SwiftPrimaryStringObject"]!.primaryKeyProperty!.name, "stringCol")
}
func testDescription() {
let objectSchema = swiftObjectSchema
let expected = """
SwiftObject {
boolCol {
type = bool;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
intCol {
type = int;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
int8Col {
type = int;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
int16Col {
type = int;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
int32Col {
type = int;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
int64Col {
type = int;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
intEnumCol {
type = int;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
floatCol {
type = float;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
doubleCol {
type = double;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
stringCol {
type = string;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
binaryCol {
type = data;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
dateCol {
type = date;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
decimalCol {
type = decimal128;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
objectIdCol {
type = object id;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
objectCol {
type = object;
objectClassName = SwiftBoolObject;
linkOriginPropertyName = (null);
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = YES;
}
uuidCol {
type = uuid;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
anyCol {
type = mixed;
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = NO;
optional = NO;
}
arrayCol {
type = object;
objectClassName = SwiftBoolObject;
linkOriginPropertyName = (null);
indexed = NO;
isPrimary = NO;
array = YES;
set = NO;
dictionary = NO;
optional = NO;
}
setCol {
type = object;
objectClassName = SwiftBoolObject;
linkOriginPropertyName = (null);
indexed = NO;
isPrimary = NO;
array = NO;
set = YES;
dictionary = NO;
optional = NO;
}
mapCol {
type = object;
objectClassName = SwiftBoolObject;
linkOriginPropertyName = (null);
indexed = NO;
isPrimary = NO;
array = NO;
set = NO;
dictionary = YES;
optional = YES;
}
}
"""
XCTAssertEqual(objectSchema.description, expected.replacingOccurrences(of: " ", with: "\t"))
}
func testSubscript() {
let objectSchema = swiftObjectSchema
XCTAssertNil(objectSchema["noSuchProperty"])
XCTAssertEqual(objectSchema["boolCol"]!.name, "boolCol")
}
func testEquals() {
let objectSchema = swiftObjectSchema
XCTAssert(try! objectSchema == Realm().schema["SwiftObject"]!)
XCTAssert(try! objectSchema != Realm().schema["SwiftStringObject"]!)
}
}
| apache-2.0 | e7fb4ca0b43b22c6bebc0fe95e2ed827 | 29.731061 | 130 | 0.417108 | 5.782609 | false | false | false | false |
tomaszpieczykolan/EneGive | EneGIVE/API/RestAPI.swift | 1 | 4205 | //
// EneGIVE - RestAPI.swift
// Copyright © 2017 Tomasz Pieczykolan. All rights reserved.
//
import Foundation
enum RestAPI {
// MARK: - Configuration
fileprivate static let endpointBase = "https://clorcepowerapi-test.herokuapp.com/"
// MARK: - Requests
static func get(_ urlString: String, auth: Bool = false, parameters: [String: String]? = nil, headers: [String: String]? = nil, completion: @escaping ((_ statusCode: Int, _ data: Data?) -> Void)) {
self.httpRequestDebug(method: "GET", urlString, auth: auth, parameters: parameters, body: nil, headers: headers, completion: completion)
}
static func post(_ urlString: String, auth: Bool = false, parameters: [String: String]? = nil, body: [String: String]? = nil, headers: [String: String]? = nil, completion: @escaping ((_ statusCode: Int, _ data: Data?) -> Void)) {
self.httpRequestDebug(method: "POST", urlString, auth: auth, parameters: parameters, body: body, headers: headers, completion: completion)
}
static func put(_ urlString: String, auth: Bool = false, parameters: [String: String]? = nil, body: [String: String]? = nil, headers: [String: String]? = nil, completion: @escaping ((_ statusCode: Int, _ data: Data?) -> Void)) {
self.httpRequestDebug(method: "PUT", urlString, auth: auth, parameters: parameters, body: body, headers: headers, completion: completion)
}
fileprivate static func httpRequestDebug(method: String, _ urlString: String, auth: Bool = false, parameters: [String: String]?, body: [String: String]?, headers: [String: String]?, completion: @escaping ((_ statusCode: Int, _ data: Data?) -> Void)) {
httpRequest(method: method, urlString, auth: auth, parameters: parameters, body: body, headers: headers) { (statusCode: Int, data: Data?) in
print("Status code: \(statusCode)")
completion(statusCode, data)
}
}
// MARK: - Generic request
fileprivate static func httpRequest(method: String, _ urlString: String, auth: Bool = false, parameters: [String: String]?, body: [String: String]?, headers: [String: String]?, completion: @escaping ((_ statusCode: Int, _ data: Data?) -> Void)) {
var parametersString = ""
if let parameters = parameters {
parametersString += "?"
for parameter in parameters {
parametersString += "\(parameter.key)=\(parameter.value)&"
}
parametersString.characters.removeLast()
}
guard let url = URL(string: "\(endpointBase)\(urlString)\(parametersString)") else {
completion(-1, nil)
return
}
print("\(method) link: \(url)")
var request = URLRequest(url: url)
request.httpMethod = method
if auth {
guard let authString = AccountManager.shared.authString else {
completion(-1, nil)
return
}
request.addValue("Basic \(authString)", forHTTPHeaderField: "Authorization")
}
if let headersUnwrapped = headers {
for header in headersUnwrapped {
request.addValue(header.value, forHTTPHeaderField: header.key)
}
}
if let httpBody = body {
request.httpBody = try? JSONSerialization.data(withJSONObject: httpBody)
}
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request) { (data, response, error) in
if let e = error {
let statusCode = -1
print("Error from response: \(e)")
completion(statusCode, nil)
return
}
guard let httpResponse = response as? HTTPURLResponse else {
let statusCode = -1
print("Response cast error")
completion(statusCode, nil)
return
}
completion(httpResponse.statusCode, data)
}
task.resume()
}
}
| mit | d1345e830e97e66d36e4074730188f85 | 41.897959 | 255 | 0.58706 | 4.804571 | false | true | false | false |
toggl/superday | teferi/UI/Modules/Goals/NewGoal/NewGoalPresenter.swift | 1 | 3106 | import Foundation
import UIKit
class NewGoalPresenter: NSObject
{
private weak var viewController : NewGoalViewController!
private let viewModelLocator : ViewModelLocator
fileprivate var padding : ContainerPadding?
fileprivate let swipeInteractionController = SwipeInteractionController()
private init(viewModelLocator: ViewModelLocator)
{
self.viewModelLocator = viewModelLocator
}
static func create(with viewModelLocator: ViewModelLocator, goalToBeEdited: Goal? = nil) -> NewGoalViewController
{
let presenter = NewGoalPresenter(viewModelLocator: viewModelLocator)
let viewModel = viewModelLocator.getNewGoalViewModel(goalToBeEdited: goalToBeEdited)
let viewController = StoryboardScene.Goal.newGoal.instantiate()
viewController.inject(presenter: presenter, viewModel: viewModel)
presenter.viewController = viewController
return viewController
}
func dismiss(showEnableNotifications: Bool = false)
{
let parentViewController = viewController.presentingViewController
viewController.dismiss(animated: true) { [unowned self] in
if showEnableNotifications {
self.showEnableNotificationsUI(inViewController: parentViewController)
}
}
}
private func showEnableNotificationsUI(inViewController parentViewController: UIViewController?)
{
guard let parentViewController = parentViewController else { return }
let topAndBottomPadding = (UIScreen.main.bounds.height - 278) / 2
padding = ContainerPadding(left: 16, top: topAndBottomPadding, right: 16, bottom: topAndBottomPadding)
let vc = EnableNotificationsPresenter.create(with: viewModelLocator)
vc.modalPresentationStyle = .custom
vc.transitioningDelegate = self
parentViewController.present(vc, animated: true, completion: nil)
swipeInteractionController.wireToViewController(viewController: vc)
}
}
extension NewGoalPresenter : UIViewControllerTransitioningDelegate
{
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?
{
return ModalPresentationController(presentedViewController: presented, presenting: presenting, containerPadding: padding)
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
return FromBottomTransition(presenting:true)
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
return FromBottomTransition(presenting:false)
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?
{
return swipeInteractionController.interactionInProgress ? swipeInteractionController : nil
}
}
| bsd-3-clause | b0831aa6756bfc116cf05732d537df95 | 40.413333 | 168 | 0.744688 | 6.417355 | false | false | false | false |
HaloWang/Halo | Halo/Classes/UITextView+Halo.swift | 1 | 1571 |
import UIKit
public extension UITextView {
@discardableResult
func returnKeyType(_ returnKeyType: UIReturnKeyType) -> Self {
self.returnKeyType = returnKeyType
return self
}
@discardableResult
func keyboardType(_ keyboardType: UIKeyboardType) -> Self {
self.keyboardType = keyboardType
return self
}
@discardableResult
func secureTextEntry(_ secureTextEntry: Bool) -> Self {
self.isSecureTextEntry = secureTextEntry
return self
}
@discardableResult
func editable(_ editable: Bool) -> Self {
self.isEditable = editable
return self
}
@discardableResult
func selectable(_ selectable: Bool) -> Self {
self.isSelectable = selectable
return self
}
@discardableResult
func textContainerInset(_ textContainerInset: UIEdgeInsets) -> Self {
self.textContainerInset = textContainerInset
return self
}
}
extension UITextView : HasText {
public var h_text: String {
get {
return text ?? ""
}
set {
text = newValue
}
}
public var h_textColor: UIColor {
get {
return textColor ?? .black
}
set {
textColor = newValue
}
}
public var h_font: UIFont {
get {
return font ?? UIFont.systemFont(ofSize: 12)
}
set {
font = newValue
}
}
public var h_textAlignment: NSTextAlignment {
get {
return textAlignment
}
set {
textAlignment = newValue
}
}
}
| mit | 33cac0ee8ad9151701d016fa919d03ac | 18.6375 | 73 | 0.593253 | 4.971519 | false | false | false | false |
vivekvpandya/GetSwifter | GetSwifter/CompletedChallengeVC.swift | 2 | 6578 | //
// CompletedChallengeVC.swift
// GetSwifter
//
import UIKit
import Alamofire
class CompletedChallengeVC: UITableViewController,UIAlertViewDelegate{
// URL to get details in JSON format
let serviceEndPoint = "http://tc-search.herokuapp.com/challenges/v2/search?q=technologies:Swift%20AND%20status:Completed"
var completedChallenges :[NSDictionary] = [] {
didSet{
self.tableView!.reloadData()
}
}
var searchResult : [NSDictionary] = []
override func viewDidLoad() {
super.viewDidLoad()
getCompletedChallenges()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.searchDisplayController!.searchResultsTableView {
return self.searchResult.count
}
else{
return completedChallenges.count
}
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell {
let cell = self.tableView!.dequeueReusableCellWithIdentifier("completedChallenge", forIndexPath: indexPath!) as CompletedChallengeTableViewCell
var dateFormater : NSDateFormatter = NSDateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSz"
dateFormater.timeZone = NSTimeZone(name:"GMT")
var opDateFormater : NSDateFormatter = NSDateFormatter()
opDateFormater.timeZone = NSTimeZone(name:"GMT")
opDateFormater.dateStyle=NSDateFormatterStyle.MediumStyle
opDateFormater.timeStyle = NSDateFormatterStyle.LongStyle
var details : NSDictionary
var source : NSDictionary
if tableView == self.searchDisplayController?.searchResultsTableView{
details = searchResult[indexPath!.row] as NSDictionary
}
else{
details = completedChallenges[indexPath!.row] as NSDictionary
}
source = details.objectForKey("_source") as NSDictionary
if let challengeTitle = source.objectForKey("challengeName") as? NSString {
cell.challengeTitle.text = challengeTitle
}
if let numSubmission = source.objectForKey("numSubmission") as? Int {
cell.numSubmissionLabel.text = "\(numSubmission)"
}
if let numRegistrants = source.objectForKey("numSubmissions") as? Int {
cell.registrantsLabel.text = "\(numRegistrants)"
}
if let totalPrize = source.objectForKey("totalPrize") as? Int {
cell.totalPrizeLabel.text = " $ \(totalPrize)"
}
if let technologyArray = source.objectForKey("technologies") as? NSArray {
cell.technologyLabel.text = technologyArray.componentsJoinedByString(",")
}
if let platformArray = source.objectForKey("platforms") as? NSArray {
cell.platformlLabel.text = platformArray.componentsJoinedByString(",")
}
if let subEndDate = source.objectForKey("submissionEndDate") as? NSString {
let subEndDate = dateFormater.dateFromString(subEndDate)
let subEndDateString = opDateFormater.stringFromDate(subEndDate!)
cell.subEndDateLabel.text = subEndDateString
}
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func getCompletedChallenges() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
Alamofire.request(.GET,serviceEndPoint, encoding : .JSON).responseJSON{(request,response,JSON,error) in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error == nil {
if response?.statusCode == 200 {
self.completedChallenges = JSON as [NSDictionary]
}
else{
var alert = UIAlertView(title:"Error" , message:"Sorry! error in details loading. " , delegate:self, cancelButtonTitle:"Dismiss")
alert.show()
}
}
else{
var alert = UIAlertView(title:"Error" , message:"Sorry! error in details loading. " , delegate:self, cancelButtonTitle:"Dismiss")
alert.show()
}
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 208.0
}
@IBAction func refreshTableView(sender: AnyObject) {
getCompletedChallenges()
self.refreshControl?.endRefreshing()
}
func filterContentForSearchText(searchText: String) {
// Filter the array using the filter method
self.searchResult = self.completedChallenges.filter({( challenge: NSDictionary) -> Bool in
let source = challenge.objectForKey("_source") as NSDictionary
let challangeName = source.objectForKey("challengeName") as NSString
let stringMatch = challangeName.rangeOfString(searchText)
return (stringMatch.length != 0) && true
})
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
self.filterContentForSearchText(searchString)
return true
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool {
self.filterContentForSearchText(self.searchDisplayController!.searchBar.text)
return true
}
}
| mit | a64d25684e30d6abf5f4763283a417e2 | 28.235556 | 151 | 0.580572 | 6.235071 | false | false | false | false |
CodePath-Parse/MiAR | MiAR/View Controllers/NewNoteViewController.swift | 2 | 16013 | //
// NewNoteViewController.swift
// MiAR
//
// Created by Oscar Bonilla on 10/12/17.
// Copyright © 2017 MiAR. All rights reserved.
//
import UIKit
import CoreLocation
import CLTokenInputView
class NewNoteViewController: UIViewController {
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var tempImageView: UIImageView!
@IBOutlet weak var noteTextView: UITextView!
@IBOutlet weak var drawView: UIView!
@IBOutlet weak var tokenInputView: CLTokenInputView?
@IBOutlet weak var tableView: UITableView?
@IBOutlet weak var imagesButton: UIButton!
@IBOutlet weak var cameraButton: UIButton!
var lastPoint = CGPoint.zero
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false
var noteImage: UIImage!
let locationManager = CLLocationManager()
var activeTextView: UITextView!
var noteTextColor: UIColor = UIColor.black
var emptyNote = true
var dismissingKeyboard = false
var note: Note?
var userList: [User] = [User]()
var filteredUsers: [User] = [User]()
var selectedUsers: [User] = [User]()
var completion: ((Note) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
noteTextView.delegate = self
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(NewNoteViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
registerForKeyboardNotifications()
User.getAllUsers(onSuccess: { (users) in
self.userList = users
self.tableView?.reloadData()
}) { (error) in
print("Failed to get users")
}
tokenInputView?.fieldName = "Send Note To:"
tokenInputView?.placeholderText = "Everybody"
tokenInputView?.delegate = self
tokenInputView?.drawBottomBorder = true
tableView?.delegate = self
tableView?.dataSource = self
tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
noteTextView.isHidden = true
if !UIImagePickerController.isSourceTypeAvailable(.camera) {
cameraButton.isEnabled = false
}
}
override func viewDidAppear(_ animated: Bool) {
}
@objc func infoButtonTapped(sender: Any?) {
}
// MARK: - Drawing functions
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touches began")
if dismissingKeyboard {
return
}
swiped = false
if let touch = touches.first {
lastPoint = touch.location(in: mainImageView)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touches moved")
if dismissingKeyboard {
return
}
swiped = true
if let touch = touches.first {
let currentPoint = touch.location(in: mainImageView)
drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)
lastPoint = currentPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touches ended")
if dismissingKeyboard {
dismissingKeyboard = false
return
}
if !swiped {
// draw a single point
drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
}
// backgroundImageView.image = UIImage(named: "background")
// let rect = AVMakeRect(aspectRatio: backgroundImageView.image?.size ?? view.frame.size, insideRect: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
// Merge tempImageView into mainImageView
UIGraphicsBeginImageContext(mainImageView.frame.size)
// backgroundImageView.image?.draw(in: rect, blendMode: .normal, alpha: 1.0)
mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height), blendMode: .normal, alpha: 1.0)
tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height), blendMode: .normal, alpha: opacity)
mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
tempImageView.image = nil
}
func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {
UIGraphicsBeginImageContext(mainImageView.frame.size)
let context = UIGraphicsGetCurrentContext()
if let context = context {
tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height))
context.move(to: fromPoint)
context.addLine(to: toPoint)
context.setLineCap(.round)
context.setLineWidth(brushWidth)
context.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
context.setBlendMode(.normal)
context.strokePath()
tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
tempImageView.alpha = opacity
}
UIGraphicsEndImageContext()
}
// MARK: - Button actions
let colors: [(CGFloat, CGFloat, CGFloat)] = [
(0, 0, 0),
(105.0 / 255.0, 105.0 / 255.0, 105.0 / 255.0),
(1.0, 0, 0),
(0, 0, 1.0),
(51.0 / 255.0, 204.0 / 255.0, 1.0),
(102.0 / 255.0, 1.0, 0),
(160.0 / 255.0, 82.0 / 255.0, 45.0 / 255.0),
(1.0, 102.0 / 255.0, 0),
(1.0, 1.0, 0),
(1.0, 1.0, 1.0),
]
@IBAction func colorPicked(_ sender: AnyObject) {
print("color picked")
var index = sender.tag ?? 0
if index < 0 || index >= colors.count {
index = 0
}
(red, green, blue) = colors[index]
if index == colors.count - 1 {
opacity = 1.0
}
// set text to same color as crayon
noteTextColor = UIColor(displayP3Red: red, green: green, blue: blue, alpha: 1.0)
}
@IBAction func reset(_ sender: Any) {
mainImageView.image = nil
}
@IBAction func eraser(_ sender: Any) {
(red, green, blue) = colors[colors.count - 1]
opacity = 1.0
}
@IBAction func onCancelButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func onTextButton(_ sender: Any) {
noteTextView.isHidden = false
noteTextView.isUserInteractionEnabled = true
noteTextView.updateFocusIfNeeded()
noteTextView.becomeFirstResponder()
}
@IBAction func onSendButton(_ sender: Any) {
let rect = CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height)
UIGraphicsBeginImageContextWithOptions(mainImageView.bounds.size, true, 1)
// white background (replace with backgroundImage)
if backgroundImageView.image != nil {
backgroundImageView.image?.draw(in: rect, blendMode: .normal, alpha: 1)
} else {
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(UIColor.white.cgColor)
context!.fill(rect)
}
mainImageView.image?.draw(in: rect, blendMode: .normal, alpha: 1)
if let text = noteTextView.text,
text != "" && text != "Leave a message" {
let textImage = noteTextView.snapshot()
textImage?.draw(in: rect, blendMode: .multiply, alpha: 1)
}
noteImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
var currentLocation: CLLocation? = nil
if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
currentLocation = locationManager.location
}
// we can call to create the note here or pass along to another VC to ask for sharing options
let toUser = selectedUsers.first
let note = Note(to: toUser, text: noteTextView.text, image: noteImage, location: currentLocation?.coordinate)
completion?(note)
dismiss(animated: true, completion: nil)
}
@IBAction func onImages(_ sender: Any) {
let vc = UIImagePickerController()
vc.delegate = self
vc.allowsEditing = true
vc.sourceType = .photoLibrary
self.present(vc, animated: true, completion: nil)
}
@IBAction func onCamera(_ sender: Any) {
let vc = UIImagePickerController()
vc.delegate = self
vc.allowsEditing = true
if UIImagePickerController.isSourceTypeAvailable(.camera) {
print("Camera is available 📸")
vc.sourceType = .camera
self.present(vc, animated: true, completion: nil)
}
}
// MARK: - Keyboard and scrolling
@objc func dismissKeyboard() {
print("dismiss keyboard")
view.endEditing(true)
}
func registerForKeyboardNotifications(){
//Adding notifies on keyboard appearing
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func deregisterFromKeyboardNotifications(){
//Removing notifies on keyboard appearing
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification){
//Need to calculate keyboard exact size due to Apple suggestions
print("keyboard shown")
// var info = notification.userInfo!
// let keyboardSize = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size
// dismissingKeyboard = true
//
// var aRect = view.frame
// aRect.size.height -= keyboardSize!.height
// if let activeView = activeTextView.superview {
// let viewPoint = CGPoint(x: activeView.frame.origin.x, y: activeView.frame.origin.y + activeView.frame.size.height)
// if (!aRect.contains(viewPoint)){
// let translateY = aRect.size.height - (viewPoint.y + activeView.frame.size.height)
// drawView.transform = CGAffineTransform(translationX: 0, y: translateY)
// }
// }
}
@objc func keyboardWillBeHidden(notification: NSNotification){
print("keyboard hidden")
drawView.transform = CGAffineTransform.identity
}
deinit {
deregisterFromKeyboardNotifications()
}
}
// MARK: - TextView delegate
extension NewNoteViewController: UITextViewDelegate {
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
activeTextView = textView
return true
}
func textViewDidBeginEditing(_ textView: UITextView) {
print("text view begin editing")
if emptyNote {
textView.text = ""
emptyNote = false
}
textView.textColor = noteTextColor
}
func textViewDidEndEditing(_ textView: UITextView) {
print("text view end editing")
if textView.text.isEmpty {
emptyNote = true
noteTextView.text = "#Leave a message"
noteTextView.textColor = UIColor.lightGray
}
activeTextView = nil
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
print("detected newline")
textView.resignFirstResponder()
textView.isUserInteractionEnabled = false
}
return true
}
}
// MARK: -
extension NewNoteViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.userList.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let emails = userList.map { $0.username }
return emails[row]
}
}
extension NewNoteViewController: CLTokenInputViewDelegate {
func tokenInputView(_ view: CLTokenInputView, didChangeText text: String?) {
print("Text Changed")
guard let text = text,
text != "" else {
filteredUsers = [User]()
tableView?.isHidden = true
drawView.isHidden = false
tableView?.reloadData()
return
}
filteredUsers = userList.filter { $0.username.lowercased().contains(text.lowercased()) }
tableView?.isHidden = false
drawView.isHidden = true
tableView?.reloadData()
}
func tokenInputViewDidBeginEditing(_ view: CLTokenInputView) {
print("Began editing")
}
func tokenInputViewDidEndEditing(_ view: CLTokenInputView) {
print("Finished editing")
}
func tokenInputView(_ view: CLTokenInputView, didAdd token: CLToken) {
print("Add token")
if let user = userList.filter({ $0.username == token.displayText }).first {
selectedUsers.append(user)
}
}
func tokenInputView(_ view: CLTokenInputView, didRemove token: CLToken) {
print("Removed Token")
selectedUsers = selectedUsers.filter { $0.username != token.displayText }
}
func tokenInputView(_ view: CLTokenInputView, tokenForText text: String) -> CLToken? {
print("Token for text" )
if let matchingUser = filteredUsers.first {
let match = CLToken(displayText: matchingUser.username, context: matchingUser)
return match
}
return nil
}
}
extension NewNoteViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredUsers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let user = filteredUsers[indexPath.row]
cell.textLabel?.text = user.username
if selectedUsers.contains(user) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let user = filteredUsers[indexPath.row]
let token = CLToken(displayText: user.username, context: user)
tokenInputView?.add(token)
}
}
extension NewNoteViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
backgroundImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | b5a728930c24e9094ed31de17bc5c73e | 35.301587 | 190 | 0.631083 | 4.928879 | false | false | false | false |
mgfigueroa/Pterattack | Pterattack/Pterattack/Meteor.swift | 1 | 1372 | //
// Meteor.swift
// Pterattack
//
// Created by Clement on 12/4/15.
//
//
import Foundation
import SpriteKit
class Meteor : SKSpriteNode {
private var _velocity : Int = -1
private var _health : Int = -1
private var _damage : Int = -1
var velocity : Int {
get {
return _velocity
}
}
var health : Int {
get {
return _health
}
}
var damage : Int {
get {
return _damage
}
}
init(texture: SKTexture?, color: UIColor, size: CGSize, health: Int) {
super.init(texture: texture, color: color, size: size)
position.x = CGFloat(arc4random_uniform(UInt32(GameScene.getInstance()!.size.width)))
position.y = size.height/2 + (GameScene.getInstance()?.size.height)!
physicsBody = SKPhysicsBody(texture: texture!, size: size)
physicsBody?.categoryBitMask = METEOR_BITMASK
physicsBody?.collisionBitMask = BLANK_BITMASK
physicsBody?.contactTestBitMask = SHIP_BITMASK | PROJECTILE_BITMASK
self._damage = 25
self._velocity = 4
self._health = health
self.name = NSStringFromClass(Meteor)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 3bb23d1ffac92d7bbb531a1e2f8a13ac | 22.655172 | 94 | 0.568513 | 4.247678 | false | false | false | false |
tdscientist/ShelfView-iOS | Example/Pods/Kingfisher/Sources/Networking/ImagePrefetcher.swift | 1 | 12708 | //
// ImagePrefetcher.swift
// Kingfisher
//
// Created by Claire Knight <[email protected]> on 24/02/2016
//
// Copyright (c) 2018 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
/// Progress update block of prefetcher.
///
/// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while
/// downloading, encountered an error when downloading or the download not being started at all.
/// - `completedResources`: An array of resources that are downloaded and cached successfully.
public typealias PrefetcherProgressBlock =
((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
/// Completion block of prefetcher.
///
/// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while
/// downloading, encountered an error when downloading or the download not being started at all.
/// - `completedResources`: An array of resources that are downloaded and cached successfully.
public typealias PrefetcherCompletionHandler =
((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
/// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them.
/// This is useful when you know a list of image resources and want to download them before showing. It also works with
/// some Cocoa prefetching mechanism like table view or collection view `prefetchDataSource`, to start image downloading
/// and caching before they display on screen.
public class ImagePrefetcher {
/// The maximum concurrent downloads to use when prefetching images. Default is 5.
public var maxConcurrentDownloads = 5
// The dispatch queue to use for handling resource process, so downloading does not occur on the main thread
// This prevents stuttering when preloading images in a collection view or table view.
private var prefetchQueue: DispatchQueue
private let prefetchResources: [Resource]
private let optionsInfo: KingfisherParsedOptionsInfo
private var progressBlock: PrefetcherProgressBlock?
private var completionHandler: PrefetcherCompletionHandler?
private var tasks = [URL: DownloadTask]()
private var pendingResources: ArraySlice<Resource>
private var skippedResources = [Resource]()
private var completedResources = [Resource]()
private var failedResources = [Resource]()
private var stopped = false
// A manager used for prefetching. We will use the helper methods in manager.
private let manager: KingfisherManager
private var finished: Bool {
let totalFinished = failedResources.count + skippedResources.count + completedResources.count
return totalFinished == prefetchResources.count && tasks.isEmpty
}
/// Creates an image prefetcher with an array of URLs.
///
/// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable.
/// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process.
/// The images which are already cached will be skipped without downloading again.
///
/// - Parameters:
/// - urls: The URLs which should be prefetched.
/// - options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called every time an resource is downloaded, skipped or cancelled.
/// - completionHandler: Called when the whole prefetching process finished.
///
/// - Note:
/// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
/// the downloader and cache target respectively. You can specify another downloader or cache by using
/// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in
/// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method.
public convenience init(urls: [URL],
options: KingfisherOptionsInfo? = nil,
progressBlock: PrefetcherProgressBlock? = nil,
completionHandler: PrefetcherCompletionHandler? = nil)
{
let resources: [Resource] = urls.map { $0 }
self.init(
resources: resources,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
/// Creates an image prefetcher with an array of resources.
///
/// - Parameters:
/// - resources: The resources which should be prefetched. See `Resource` type for more.
/// - options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called every time an resource is downloaded, skipped or cancelled.
/// - completionHandler: Called when the whole prefetching process finished.
///
/// - Note:
/// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
/// the downloader and cache target respectively. You can specify another downloader or cache by using
/// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in
/// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method.
public init(resources: [Resource],
options: KingfisherOptionsInfo? = nil,
progressBlock: PrefetcherProgressBlock? = nil,
completionHandler: PrefetcherCompletionHandler? = nil)
{
var options = KingfisherParsedOptionsInfo(options)
prefetchResources = resources
pendingResources = ArraySlice(resources)
// Set up the dispatch queue that all our work should occur on.
let prefetchQueueName = "com.onevcat.Kingfisher.PrefetchQueue"
prefetchQueue = DispatchQueue(label: prefetchQueueName)
// We want all callbacks from our prefetch queue, so we should ignore the callback queue in options.
// Add our own callback dispatch queue to make sure all internal callbacks are
// coming back in our expected queue.
options.callbackQueue = .untouch
optionsInfo = options
let cache = optionsInfo.targetCache ?? .default
let downloader = optionsInfo.downloader ?? .default
manager = KingfisherManager(downloader: downloader, cache: cache)
self.progressBlock = progressBlock
self.completionHandler = completionHandler
}
/// Starts to download the resources and cache them. This can be useful for background downloading
/// of assets that are required for later use in an app. This code will not try and update any UI
/// with the results of the process.
public func start()
{
// Since we want to handle the resources cancellation in the prefetch queue only.
prefetchQueue.async {
guard !self.stopped else {
assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.")
self.handleComplete()
return
}
guard self.maxConcurrentDownloads > 0 else {
assertionFailure("There should be concurrent downloads value should be at least 1.")
self.handleComplete()
return
}
// Empty case.
guard self.prefetchResources.count > 0 else {
self.handleComplete()
return
}
let initialConcurrentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads)
for _ in 0 ..< initialConcurrentDownloads {
if let resource = self.pendingResources.popFirst() {
self.startPrefetching(resource)
}
}
}
}
/// Stops current downloading progress, and cancel any future prefetching activity that might be occuring.
public func stop() {
prefetchQueue.async {
if self.finished { return }
self.stopped = true
self.tasks.values.forEach { $0.cancel() }
}
}
func downloadAndCache(_ resource: Resource) {
let downloadTaskCompletionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void) = { result in
self.tasks.removeValue(forKey: resource.downloadURL)
if let _ = result.error {
self.failedResources.append(resource)
} else {
self.completedResources.append(resource)
}
self.reportProgress()
if self.stopped {
if self.tasks.isEmpty {
self.failedResources.append(contentsOf: self.pendingResources)
self.handleComplete()
}
} else {
self.reportCompletionOrStartNext()
}
}
let downloadTask = manager.loadAndCacheImage(
source: .network(resource),
options: optionsInfo,
completionHandler: downloadTaskCompletionHandler)
if let downloadTask = downloadTask {
tasks[resource.downloadURL] = downloadTask
}
}
func append(cached resource: Resource) {
skippedResources.append(resource)
reportProgress()
reportCompletionOrStartNext()
}
func startPrefetching(_ resource: Resource)
{
if optionsInfo.forceRefresh {
downloadAndCache(resource)
return
}
let cacheType = manager.cache.imageCachedType(
forKey: resource.cacheKey,
processorIdentifier: optionsInfo.processor.identifier)
switch cacheType {
case .memory:
append(cached: resource)
case .disk:
if optionsInfo.alsoPrefetchToMemory {
_ = manager.retrieveImageFromCache(
source: .network(resource),
options: optionsInfo)
{
_ in
self.append(cached: resource)
}
} else {
append(cached: resource)
}
case .none:
downloadAndCache(resource)
}
}
func reportProgress() {
progressBlock?(skippedResources, failedResources, completedResources)
}
func reportCompletionOrStartNext() {
prefetchQueue.async {
if let resource = self.pendingResources.popFirst() {
self.startPrefetching(resource)
} else {
guard self.tasks.isEmpty else { return }
self.handleComplete()
}
}
}
func handleComplete() {
// The completion handler should be called on the main thread
DispatchQueue.main.safeAsync {
self.completionHandler?(self.skippedResources, self.failedResources, self.completedResources)
self.completionHandler = nil
self.progressBlock = nil
}
}
}
| mit | 56e024f42cb029b5bc5ea4d46daa20fc | 42.22449 | 120 | 0.654863 | 5.554196 | false | false | false | false |
RNT17/FriendlyChat-Android-Codelab | ios/swift/FriendlyChatSwift/AppDelegate.swift | 1 | 6033 | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
// UserNotifications are only required for the optional FCM step
import UserNotifications
import Firebase
import GoogleSignIn
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
var window: UIWindow?
@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any])
-> Bool {
return self.application(application, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: "")
}
func application(_ application: UIApplication,
open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: annotation)
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
if let error = error {
print("Error \(error)")
return
}
guard let authentication = user.authentication else { return }
let credential = FIRGoogleAuthProvider.credential(withIDToken: authentication.idToken,
accessToken: authentication.accessToken)
FIRAuth.auth()?.signIn(with: credential) { (user, error) in
if let error = error {
print("Error \(error)")
return
}
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FIRApp.configure()
GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
GIDSignIn.sharedInstance().delegate = self
////////////////////////////////////////////////////////////////////////
// //
// CODE BELOW THIS POINT IS ONLY REQUIRED FOR THE OPTIONAL FCM STEP //
// //
////////////////////////////////////////////////////////////////////////
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions) {_,_ in }
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
showAlert(withUserInfo: userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
showAlert(withUserInfo: userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func showAlert(withUserInfo userInfo: [AnyHashable : Any]) {
let apsKey = "aps"
let gcmMessage = "alert"
let gcmLabel = "google.c.a.c_l"
if let aps = userInfo[apsKey] as? NSDictionary {
if let message = aps[gcmMessage] as? String {
DispatchQueue.main.async {
let alert = UIAlertController(title: userInfo[gcmLabel] as? String ?? "",
message: message, preferredStyle: .alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .destructive, handler: nil)
alert.addAction(dismissAction)
self.window?.rootViewController?.presentedViewController?.present(alert, animated: true, completion: nil)
}
}
}
}
}
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
showAlert(withUserInfo: userInfo)
// Change this to your preferred presentation option
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
showAlert(withUserInfo: userInfo)
completionHandler()
}
}
| apache-2.0 | 727d5b620bac3b463776c1d94028734e | 40.040816 | 158 | 0.668324 | 5.484545 | false | false | false | false |
szehnder/AERecord | AERecordExample/MasterViewController.swift | 1 | 4221 | //
// MasterViewController.swift
// AERecordExample
//
// Created by Marko Tadic on 11/3/14.
// Copyright (c) 2014 ae. All rights reserved.
//
import UIKit
import CoreData
import AERecord
class MasterViewController: CoreDataTableViewController, UISplitViewControllerDelegate {
private var collapseDetailViewController = true
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
splitViewController?.delegate = self
// setup row height
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
// setup buttons
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
// setup fetchedResultsController property
refreshFetchedResultsController()
}
// MARK: - CoreData
func insertNewObject(sender: AnyObject) {
// create object
Event.createWithAttributes(["timeStamp" : NSDate()])
AERecord.saveContextAndWait()
}
func refreshFetchedResultsController() {
let sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: true)]
let request = Event.createFetchRequest(sortDescriptors: sortDescriptors)
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: AERecord.defaultContext, sectionNameKeyPath: nil, cacheName: nil)
}
// MARK: - Table View
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
if let frc = fetchedResultsController {
if let event = frc.objectAtIndexPath(indexPath) as? Event {
// set data
cell.textLabel!.text = event.timeStamp.description
cell.accessoryType = event.selected ? .Checkmark : .None
// set highlight color
let highlightColorView = UIView()
highlightColorView.backgroundColor = yellow
cell.selectedBackgroundView = highlightColorView
cell.textLabel!.highlightedTextColor = UIColor.darkGrayColor()
}
}
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// delete object
if let event = fetchedResultsController?.objectAtIndexPath(indexPath) as? NSManagedObject {
event.delete()
AERecord.saveContext()
}
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// update value
if let frc = fetchedResultsController {
if let event = frc.objectAtIndexPath(indexPath) as? Event {
// deselect previous / select current
if let previous = Event.firstWithAttribute("selected", value: true) as? Event {
previous.selected = false
}
event.selected = true
AERecord.saveContextAndWait()
}
}
}
// MARK: - UISplitViewControllerDelegate
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController!, ontoPrimaryViewController primaryViewController: UIViewController!) -> Bool {
return collapseDetailViewController
}
}
| mit | e0ceb9741ee472c1d9f13c9b87133ae5 | 37.027027 | 226 | 0.663587 | 6.434451 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Core/Math.swift | 1 | 22685 | //
// Math.swift
// CesiumKit
//
// Created by Ryan Walklin on 12/06/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Foundation
public struct Math {
/**
* 0.1
* @type {Number}
* @constant
*/
static let Epsilon1: Double = 0.1
/**
* 0.01
* @type {Number}
* @constant
*/
static let Epsilon2: Double = 0.01
/**
* 0.001
* @type {Number}
* @constant
*/
static let Epsilon3: Double = 0.001
/**
* 0.0001
* @type {Number}
* @constant
*/
static let Epsilon4: Double = 0.0001
/**
* 0.00001
* @type {Number}
* @constant
*/
static let Epsilon5: Double = 0.00001
/**
* 0.000001
* @type {Number}
* @constant
*/
static let Epsilon6: Double = 0.000001
/**
* 0.0000001
* @type {Number}
* @constant
*/
static let Epsilon7: Double = 0.0000001
/**
* 0.00000001
* @type {Number}
* @constant
*/
static let Epsilon8: Double = 0.00000001
/**
* 0.000000001
* @type {Number}
* @constant
*/
static let Epsilon9: Double = 0.000000001
/**
* 0.0000000001
* @type {Number}
* @constant
*/
static let Epsilon10: Double = 0.0000000001
/**
* 0.00000000001
* @type {Number}
* @constant
*/
static let Epsilon11: Double = 0.00000000001
/**
* 0.000000000001
* @type {Number}
* @constant
*/
static let Epsilon12: Double = 0.000000000001
/**
* 0.0000000000001
* @type {Number}
* @constant
*/
static let Epsilon13: Double = 0.0000000000001
/**
* 0.00000000000001
* @type {Number}
* @constant
*/
static let Epsilon14: Double = 0.00000000000001
/**
* 0.000000000000001
* @type {Number}
* @constant
*/
static let Epsilon15: Double = 0.000000000000001
/**
* 0.0000000000000001
* @type {Number}
* @constant
*/
static let Epsilon16: Double = 0.0000000000000001
/**
* 0.00000000000000001
* @type {Number}
* @constant
*/
static let Epsilon17: Double = 0.00000000000000001
/**
* 0.000000000000000001
* @type {Number}
* @constant
*/
static let Epsilon18: Double = 0.000000000000000001
/**
* 0.0000000000000000001
* @type {Number}
* @constant
*/
static let Epsilon19: Double = 0.0000000000000000001
/**
* 0.00000000000000000001
* @type {Number}
* @constant
*/
static let Epsilon20: Double = 0.00000000000000000001
/**
* 3.986004418e14
* @type {Number}
* @constant
*/
static let GravitationalParameter: Double = 3.986004418e14
/**
* Radius of the sun in meters: 6.955e8
* @type {Number}
* @constant
*/
static let SolarRadius: Double = 6.955e8
/**
* The mean radius of the moon, according to the "Report of the IAU/IAG Working Group on
* Cartographic Coordinates and Rotational Elements of the Planets and satellites: 2000",
* Celestial Mechanics 82: 83-110, 2002.
* @type {Number}
* @constant
*/
static let LunarRadius: Double = 1737400.0
/**
* 64 * 1024
* @type {Number}
* @constant
*/
static let SixtyFourKilobytes: Int = 64 * 1024
/**
* Returns the sign of the value; 1 if the value is positive, -1 if the value is
* negative, or 0 if the value is 0.
*
* @param {Number} value The value to return the sign of.
* @returns {Number} The sign of value.
*/
static func sign (_ value: Double) -> Int {
if value > 0.0 {
return 1
}
if value < 0.0 {
return -1
}
return 0
}
/**
* Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative.
* This is similar to {@link CesiumMath#sign} except that returns 1.0 instead of
* 0.0 when the input value is 0.0.
* @param {Number} value The value to return the sign of.
* @returns {Number} The sign of value.
*/
static func signNotZero (_ value: Double) -> Int {
return value < 0.0 ? -1 : 1
}
/**
* Converts a scalar value in the range [-1.0, 1.0] to a SNORM in the range [0, rangeMax]
* @param {Number} value The scalar value in the range [-1.0, 1.0]
* @param {Number} [rangeMax=255] The maximum value in the mapped range, 255 by default.
* @returns {Number} A SNORM value, where 0 maps to -1.0 and rangeMax maps to 1.0.
*
* @see CesiumMath.fromSNorm
*/
static func toSNorm (_ value: Double, rangeMax: Int = 255) -> Int {
return Int(round((Math.clamp(value, min: -1.0, max: 1.0) * 0.5 + 0.5) * Double(rangeMax)))
}
/**
* Converts a SNORM value in the range [0, rangeMax] to a scalar in the range [-1.0, 1.0].
* @param {Number} value SNORM value in the range [0, 255]
* @param {Number} [rangeMax=255] The maximum value in the SNORM range, 255 by default.
* @returns {Number} Scalar in the range [-1.0, 1.0].
*
* @see CesiumMath.toSNorm
*/
static func fromSNorm (_ value: Int, rangeMax: Int = 255) -> Double {
return clamp(Double(value), min: 0.0, max: Double(rangeMax)) / Double(rangeMax) * 2.0 - 1.0
}
/*
/**
* Returns the hyperbolic sine of a number.
* The hyperbolic sine of <em>value</em> is defined to be
* (<em>e<sup>x</sup> - e<sup>-x</sup></em>)/2.0
* where <i>e</i> is Euler's number, approximately 2.71828183.
*
* <p>Special cases:
* <ul>
* <li>If the argument is NaN, then the result is NaN.</li>
*
* <li>If the argument is infinite, then the result is an infinity
* with the same sign as the argument.</li>
*
* <li>If the argument is zero, then the result is a zero with the
* same sign as the argument.</li>
* </ul>
*</p>
*
* @param {Number} value The number whose hyperbolic sine is to be returned.
* @returns {Number} The hyperbolic sine of <code>value</code>.
*/
CesiumMath.sinh = function(value) {
var part1 = Math.pow(Math.E, value);
var part2 = Math.pow(Math.E, -1.0 * value);
return (part1 - part2) * 0.5;
};
/**
* Returns the hyperbolic cosine of a number.
* The hyperbolic cosine of <strong>value</strong> is defined to be
* (<em>e<sup>x</sup> + e<sup>-x</sup></em>)/2.0
* where <i>e</i> is Euler's number, approximately 2.71828183.
*
* <p>Special cases:
* <ul>
* <li>If the argument is NaN, then the result is NaN.</li>
*
* <li>If the argument is infinite, then the result is positive infinity.</li>
*
* <li>If the argument is zero, then the result is 1.0.</li>
* </ul>
*</p>
*
* @param {Number} value The number whose hyperbolic cosine is to be returned.
* @returns {Number} The hyperbolic cosine of <code>value</code>.
*/
CesiumMath.cosh = function(value) {
var part1 = Math.pow(Math.E, value);
var part2 = Math.pow(Math.E, -1.0 * value);
return (part1 + part2) * 0.5;
};
*/
/**
* Computes the linear interpolation of two values.
*
* @param {Number} p The start value to interpolate.
* @param {Number} q The end value to interpolate.
* @param {Number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
* @returns {Number} The linearly interpolated value.
*
* @example
* var n = Cesium.Math.lerp(0.0, 2.0, 0.5); // returns 1.0
*/
static public func lerp (p: Double, q: Double, time: Double) -> Double {
return (1.0 - time) * p + time * q
}
/*
/**
* pi
*
* @type {Number}
* @constant
*/
CesiumMath.PI = Math.PI;
/**
* 1/pi
*
* @type {Number}
* @constant
*/
CesiumMath.ONE_OVER_PI = 1.0 / Math.PI;
/**
* pi/2
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_TWO = Math.PI * 0.5;
/**
* pi/3
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_THREE = Math.PI / 3.0;
/**
* pi/4
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_FOUR = Math.PI / 4.0;
/**
* pi/6
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_SIX = Math.PI / 6.0;
/**
* 3pi/2
*
* @type {Number}
* @constant
*/
CesiumMath.THREE_PI_OVER_TWO = (3.0 * Math.PI) * 0.5;
*/
/**
* 2pi
*
* @type {Number}
* @constant
*/
static let TwoPi = 2.0 * .pi
/*
/**
* 1/2pi
*
* @type {Number}
* @constant
*/
CesiumMath.ONE_OVER_TWO_PI = 1.0 / (2.0 * Math.PI);
*/
/**
* The number of radians in a degree.
*
* @type {Number}
* @constant
* @default Math.PI / 180.0
*/
public static let RadiansPerDegree = .pi / 180.0
/**
* The number of degrees in a radian.
*
* @type {Number}
* @constant
* @default 180.0 / Math.PI
*/
public static let DegreesPerRadian = 180.0 / .pi
/**
* The number of radians in an arc second.
*
* @type {Number}
* @constant
* @default {@link CesiumMath.RADIANS_PER_DEGREE} / 3600.0
*/
static let RadiansPerArcSecond = RadiansPerDegree / 3600.0
/**
* Converts degrees to radians.
* @param {Number} degrees The angle to convert in degrees.
* @returns {Number} The corresponding angle in radians.
*/
public static func toRadians(_ degrees: Double) -> Double {
return degrees * RadiansPerDegree
}
/**
* Converts radians to degrees.
* @param {Number} radians The angle to convert in radians.
* @returns {Number} The corresponding angle in degrees.
*/
public static func toDegrees(_ radians: Double) -> Double {
return radians * DegreesPerRadian
}
/*
/**
* Converts a longitude value, in radians, to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
*
* @param {Number} angle The longitude value, in radians, to convert to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
* @returns {Number} The equivalent longitude value in the range [<code>-Math.PI</code>, <code>Math.PI</code>).
*
* @example
* // Convert 270 degrees to -90 degrees longitude
* var longitude = Cesium.Math.convertLongitudeRange(Cesium.Math.toRadians(270.0));
*/
CesiumMath.convertLongitudeRange = function(angle) {
//>>includeStart('debug', pragmas.debug);
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
//>>includeEnd('debug');
var twoPi = CesiumMath.TWO_PI;
var simplified = angle - Math.floor(angle / twoPi) * twoPi;
if (simplified < -Math.PI) {
return simplified + twoPi;
}
if (simplified >= Math.PI) {
return simplified - twoPi;
}
return simplified;
};
*/
/**
* Convenience function that clamps a latitude value, in radians, to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
* Useful for sanitizing data before use in objects requiring correct range.
*
* @param {Number} angle The latitude value, in radians, to clamp to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
* @returns {Number} The latitude value clamped to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
*
* @example
* // Clamp 108 degrees latitude to 90 degrees latitude
* var latitude = Cesium.Math.clampToLatitudeRange(Cesium.Math.toRadians(108.0));
*/
static func clampToLatitudeRange (angle: Double) -> Double {
return clamp(angle, min: -.pi/2, max: .pi/2)
}
/**
* Produces an angle in the range -Pi <= angle <= Pi which is equivalent to the provided angle.
*
* @param {Number} angle in radians
* @returns {Number} The angle in the range [<code>-CesiumMath.PI</code>, <code>CesiumMath.PI</code>].
*/
static func negativePiToPi (_ angle: Double) -> Double {
return zeroToTwoPi(angle + .pi) - .pi
}
/**
* Produces an angle in the range 0 <= angle <= 2Pi which is equivalent to the provided angle.
*
* @param {Number} angle in radians
* @returns {Number} The angle in the range [0, <code>CesiumMath.TWO_PI</code>].
*/
static func zeroToTwoPi (_ angle: Double) -> Double {
let mod = Math.mod(angle, Math.TwoPi)
if (abs(mod) < Math.Epsilon14 && abs(angle) > Math.Epsilon14) {
return Math.TwoPi
}
return mod
}
/**
* The modulo operation that also works for negative dividends.
*
* @param {Number} m The dividend.
* @param {Number} n The divisor.
* @returns {Number} The remainder.
*/
static func mod (_ m: Double, _ n: Double) -> Double {
return fmod(fmod(m, n) + n, n)
}
/**
* Determines if two values are equal using an absolute or relative tolerance test. This is useful
* to avoid problems due to roundoff error when comparing floatingpoint values directly. The values are
* first compared using an absolute tolerance test. If that fails, a relative tolerance test is performed.
* Use this test if you are unsure of the magnitudes of left and right.
*
* @param {Number} left The first value to compare.
* @param {Number} right The other value to compare.
* @param {Number} relativeEpsilon The maximum inclusive delta between <code>left</code> and <code>right</code> for the relative tolerance test.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The maximum inclusive delta between <code>left</code> and <code>right</code> for the absolute tolerance test.
* @returns {Boolean} <code>true</code> if the values are equal within the epsilon; otherwise, <code>false</code>.
*
* @example
* var a = Cesium.Math.equalsEpsilon(0.0, 0.01, Cesium.Math.EPSILON2); // true
* var b = Cesium.Math.equalsEpsilon(0.0, 0.1, Cesium.Math.EPSILON2); // false
* var c = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON7); // true
* var d = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON9); // false
*/
static func equalsEpsilon(_ left: Double, _ right: Double, relativeEpsilon: Double, absoluteEpsilon: Double? = nil) -> Bool {
let epsilon = absoluteEpsilon ?? relativeEpsilon
let absDiff = abs(left - right)
return absDiff <= epsilon || absDiff <= relativeEpsilon * max(abs(left), abs(right))
}
/*
var factorials = [1];
/**
* Computes the factorial of the provided number.
*
* @param {Number} n The number whose factorial is to be computed.
* @returns {Number} The factorial of the provided number or undefined if the number is less than 0.
*
* @exception {DeveloperError} A number greater than or equal to 0 is required.
*
* @see {@link http://en.wikipedia.org/wiki/Factorial|Factorial on Wikipedia}
*
* @example
* //Compute 7!, which is equal to 5040
* var computedFactorial = Cesium.Math.factorial(7);
*/
CesiumMath.factorial = function(n) {
//>>includeStart('debug', pragmas.debug);
if (typeof n !== 'number' || n < 0) {
throw new DeveloperError('A number greater than or equal to 0 is required.');
}
//>>includeEnd('debug');
var length = factorials.length;
if (n >= length) {
var sum = factorials[length - 1];
for (var i = length; i <= n; i++) {
factorials.push(sum * i);
}
}
return factorials[n];
};
*/
/**
* Increments a number with a wrapping to a minimum value if the number exceeds the maximum value.
*
* @param {Number} [n] The number to be incremented.
* @param {Number} [maximumValue] The maximum incremented value before rolling over to the minimum value.
* @param {Number} [minimumValue=0.0] The number reset to after the maximum value has been exceeded.
* @returns {Number} The incremented number.
*
* @exception {DeveloperError} Maximum value must be greater than minimum value.
*
* @example
* var n = Cesium.Math.incrementWrap(5, 10, 0); // returns 6
* var n = Cesium.Math.incrementWrap(10, 10, 0); // returns 0
*/
static func incrementWrap (_ n: Int, maximumValue: Int, minimumValue: Int) -> Int {
var result = n
assert(maximumValue > minimumValue, "maximumValue must be greater than minimumValue")
result += 1
if (result > maximumValue) {
result = minimumValue
}
return result
}
/**
* Determines if a positive integer is a power of two.
*
* @param {Number} n The positive integer to test.
* @returns {Boolean} <code>true</code> if the number if a power of two; otherwise, <code>false</code>.
*
* @exception {DeveloperError} A number greater than or equal to 0 is required.
*
* @example
* var t = Cesium.Math.isPowerOfTwo(16); // true
* var f = Cesium.Math.isPowerOfTwo(20); // false
*/
static func isPowerOfTwo(_ n: Int) -> Bool {
return n > 0 && n & (n - 1) == 0
}
/*
/**
* Computes the next power-of-two integer greater than or equal to the provided positive integer.
*
* @param {Number} n The positive integer to test.
* @returns {Number} The next power-of-two integer.
*
* @exception {DeveloperError} A number greater than or equal to 0 is required.
*
* @example
* var n = Cesium.Math.nextPowerOfTwo(29); // 32
* var m = Cesium.Math.nextPowerOfTwo(32); // 32
*/
CesiumMath.nextPowerOfTwo = function(n) {
//>>includeStart('debug', pragmas.debug);
if (typeof n !== 'number' || n < 0) {
throw new DeveloperError('A number greater than or equal to 0 is required.');
}
//>>includeEnd('debug');
// From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
--n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
++n;
return n;
};*/
/**
* Constraint a value to lie between two values.
*
* @param {Number} value The value to constrain.
* @param {Number} min The minimum value.
* @param {Number} max The maximum value.
* @returns {Number} The value clamped so that min <= value <= max.
*/
static public func clamp (_ value: Double, min: Double, max: Double) -> Double {
return value < min ? min : value > max ? max : value
}
/*
var randomNumberGenerator = new MersenneTwister();
/**
* Sets the seed used by the random number generator
* in {@link CesiumMath#nextRandomNumber}.
*
* @param {Number} seed An integer used as the seed.
*/
CesiumMath.setRandomNumberSeed = function(seed) {
//>>includeStart('debug', pragmas.debug);
if (!defined(seed)) {
throw new DeveloperError('seed is required.');
}
//>>includeEnd('debug');
randomNumberGenerator = new MersenneTwister(seed);
};
/**
* Generates a random number in the range of [0.0, 1.0)
* using a Mersenne twister.
*
* @returns {Number} A random number in the range of [0.0, 1.0).
*
* @see CesiumMath.setRandomNumberSeed
* @see {@link http://en.wikipedia.org/wiki/Mersenne_twister|Mersenne twister on Wikipedia}
*/
CesiumMath.nextRandomNumber = function() {
return randomNumberGenerator.random();
};
*/
/**
* Computes <code>Math.acos(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
* so that the function will never return NaN.
*
* @param {Number} value The value for which to compute acos.
* @returns {Number} The acos of the value if the value is in the range [-1.0, 1.0], or the acos of -1.0 or 1.0,
*/
static func acosClamped(_ value: Double) -> Double {
return acos(clamp(value, min: -1.0, max: 1.0))
}
/**
* Computes <code>Math.asin(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
* so that the function will never return NaN.
*
* @param {Number} value The value for which to compute asin.
* @returns {Number} The asin of the value if the value is in the range [-1.0, 1.0], or the asin of -1.0 or 1.0,
*/
static func asinClamped (_ value: Double) -> Double {
return asin(clamp(value, min: -1.0, max: 1.0))
}
/*
/**
* Finds the chord length between two points given the circle's radius and the angle between the points.
*
* @param {Number} angle The angle between the two points.
* @param {Number} radius The radius of the circle.
* @returns {Number} The chord length.
*/
CesiumMath.chordLength = function(angle, radius) {
//>>includeStart('debug', pragmas.debug);
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
if (!defined(radius)) {
throw new DeveloperError('radius is required.');
}
//>>includeEnd('debug');
return 2.0 * radius * Math.sin(angle * 0.5);
};
*/
/**
* Finds the logarithm of a number to a base.
*
* @param {Number} number The number.
* @param {Number} base The base.
* @returns {Number} The result.
*/
static func logBase (_ number: Double, base: Double) -> Double {
return log(number) / log(base)
}
/**
* @private
*/
static func fog (_ distanceToCamera: Double, density: Double) -> Double {
let scalar = distanceToCamera * density
return 1.0 - exp(-(scalar * scalar))
}
}
public extension Double {
var wholeComponent: Double {
return self - (self.truncatingRemainder(dividingBy: 1.0))
}
var fractionalComponent: Double {
return self.truncatingRemainder(dividingBy: 1.0)
}
// Given a value to round and a factor to round to,
// round the value to the nearest multiple of that factor.
func roundTo(_ nearest: Double) -> Double {
return (self / nearest).rounded() * nearest
}
// Given a value to round and a factor to round to,
// round the value DOWN to the largest previous multiple
// of that factor.
func roundDown(_ nearest: Double) -> Double {
return floor(self / nearest) * nearest
}
// Given a value to round and a factor to round to,
// round the value DOWN to the largest previous multiple
// of that factor.
func roundUp(_ nearest: Double) -> Double {
return ceil(self / nearest) * nearest
}
func roundToPlaces(_ decimalPlaces: Int) -> Double {
let divisor = pow(10.0, Double(decimalPlaces))
return (self * divisor).rounded() / divisor
}
}
extension Int {
init (_ bool: Bool) {
if bool {
self.init(1)
} else {
self.init(0)
}
}
}
| apache-2.0 | 535585a85de6cee9f61d81a267a054b4 | 27.934949 | 161 | 0.599074 | 3.612261 | false | false | false | false |
HeartRateLearning/HRLClassifier | HRLClassifier/Classes/Record.swift | 1 | 4047 | //
// Record.swift
// Pods
//
// Created by Enrique de la Torre (dev) on 22/12/2016.
//
//
import Foundation
import HRLAlgorithms
// MARK: Properties & public methods
/// A heart rate record as expected by a `Classifier` or a `DataFrame`.
public final class Record: NSObject {
// MARK: - Public propeties
/**
Day of the week when the heart rate was recorded.
Range: 1...7, 1 = Sunday, 2 = Monday, ...
*/
let weekday: Int
// MARK: - Private properties
/// Values as expected by `HRLVector`.
fileprivate let values: [HRLValue]
fileprivate static let calendar = defaultCalendar()
// MARK: - Init methods
/**
Initializes a new heart rate record.
- Parameters:
- date: Date when the heart rate was recorded.
- bpm: Beats Per Minute when the heart rate was recorded.
- Returns: A new heart rate record.
*/
public convenience init(date: Date, bpm: Float) {
let weekday = Record.weekday(from: date)
let values = [
HRLValue(weekday),
HRLValue(Record.timeIntervalFromMidnight(to: date)),
HRLValue(bpm)
]
self.init(weekday: weekday, values: values)
}
/**
Private initializer. Use convenience initializers instead.
- Parameters:
- weekday: Day of the week when the heart rate was recorded.
- values: Values as expected by `HRLVector`.
- Returns: A new heart rate record.
*/
fileprivate init(weekday: Int, values: [HRLValue]) {
self.weekday = weekday
self.values = values
}
// MARK: - Public methods
public override func isEqual(_ object: Any?) -> Bool {
guard let rhs = object as? Record else {
return false
}
return (weekday == rhs.weekday) && (values == rhs.values)
}
}
// MARK: - NSCoding methods
extension Record: NSCoding {
// This init does not have a `required` modifier because this class is `final`
public convenience init?(coder aDecoder: NSCoder) {
guard let weekday = aDecoder.decodeObject(forKey: Constants.Keys.Weekday) as? Int,
let values = aDecoder.decodeObject(forKey: Constants.Keys.Values) as? [HRLValue]
else {
return nil
}
self.init(weekday: weekday, values: values)
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(weekday as NSNumber, forKey: Constants.Keys.Weekday)
aCoder.encode(values, forKey: Constants.Keys.Values)
}
}
// MARK: - HRLVector methods
extension Record: HRLVector {
public func count() -> HRLSize {
return HRLSize(values.count)
}
public func value(at index: HRLSize) -> HRLValue {
return values[Int(index)]
}
}
// MARK: - Private methods
private extension Record {
enum Constants {
static let TimeZoneGMT = "GMT"
static let LocalePOSIX = "en_US_POSIX"
enum Keys {
static let Weekday = "weekday"
static let Values = "values"
}
}
static func defaultCalendar() -> Calendar {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(abbreviation: Constants.TimeZoneGMT)!
calendar.locale = Locale(identifier: Constants.LocalePOSIX)
return calendar
}
static func weekday(from date: Date) -> Int {
return calendar.component(.weekday, from: date)
}
static func timeIntervalFromMidnight(to date: Date) -> TimeInterval {
let midnight = startOfDay(for: date)
return date.timeIntervalSince(midnight)
}
static func startOfDay(for date: Date) -> Date {
var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second],
from: date)
components.hour = 0
components.minute = 0
components.second = 0
return calendar.date(from: components)!
}
}
| mit | 749145a306c179c5a8217354a26146d8 | 25.801325 | 96 | 0.603163 | 4.422951 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/AssistantV1/Models/RuntimeResponseGenericRuntimeResponseTypeVideo.swift | 1 | 3868 | /**
* (C) Copyright IBM Corp. 2022.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import IBMSwiftSDKCore
/**
RuntimeResponseGenericRuntimeResponseTypeVideo.
Enums with an associated value of RuntimeResponseGenericRuntimeResponseTypeVideo:
RuntimeResponseGeneric
*/
public struct RuntimeResponseGenericRuntimeResponseTypeVideo: Codable, Equatable {
/**
The type of response returned by the dialog node. The specified response type must be supported by the client
application or channel.
*/
public var responseType: String
/**
The `https:` URL of the video.
*/
public var source: String
/**
The title or introductory text to show before the response.
*/
public var title: String?
/**
The description to show with the response.
*/
public var description: String?
/**
An array of objects specifying channels for which the response is intended. If **channels** is present, the
response is intended for a built-in integration and should not be handled by an API client.
*/
public var channels: [ResponseGenericChannel]?
/**
For internal use only.
*/
public var channelOptions: [String: JSON]?
/**
Descriptive text that can be used for screen readers or other situations where the video cannot be seen.
*/
public var altText: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case responseType = "response_type"
case source = "source"
case title = "title"
case description = "description"
case channels = "channels"
case channelOptions = "channel_options"
case altText = "alt_text"
}
/**
Initialize a `RuntimeResponseGenericRuntimeResponseTypeVideo` with member variables.
- parameter responseType: The type of response returned by the dialog node. The specified response type must be
supported by the client application or channel.
- parameter source: The `https:` URL of the video.
- parameter title: The title or introductory text to show before the response.
- parameter description: The description to show with the response.
- parameter channels: An array of objects specifying channels for which the response is intended. If
**channels** is present, the response is intended for a built-in integration and should not be handled by an API
client.
- parameter channelOptions: For internal use only.
- parameter altText: Descriptive text that can be used for screen readers or other situations where the video
cannot be seen.
- returns: An initialized `RuntimeResponseGenericRuntimeResponseTypeVideo`.
*/
public init(
responseType: String,
source: String,
title: String? = nil,
description: String? = nil,
channels: [ResponseGenericChannel]? = nil,
channelOptions: [String: JSON]? = nil,
altText: String? = nil
)
{
self.responseType = responseType
self.source = source
self.title = title
self.description = description
self.channels = channels
self.channelOptions = channelOptions
self.altText = altText
}
}
| apache-2.0 | 098acf9fff35f1255132a91e29782f2d | 33.535714 | 120 | 0.686918 | 4.828964 | false | false | false | false |
velvetroom/columbus | Source/View/CreateSearch/VCreateSearchBaseBar+Factory.swift | 1 | 1339 | import UIKit
extension VCreateSearchBaseBar
{
//MARK: internal
func factoryViews()
{
let border:VBorder = VBorder(colour:UIColor.colourBackgroundGray)
let searchBar:UISearchBar = UISearchBar(frame:CGRect.zero)
searchBar.translatesAutoresizingMaskIntoConstraints = false
searchBar.backgroundColor = UIColor.clear
searchBar.searchBarStyle = UISearchBarStyle.minimal
searchBar.showsCancelButton = true
searchBar.tintColor = UIColor.colourBackgroundDark
searchBar.delegate = self
self.searchBar = searchBar
addSubview(border)
addSubview(searchBar)
NSLayoutConstraint.bottomToBottom(
view:border,
toView:self)
NSLayoutConstraint.height(
view:border,
constant:ViewMain.Constants.borderWidth)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
NSLayoutConstraint.topToTop(
view:searchBar,
toView:self,
constant:VCreateSearchBaseBar.Constants.barTop)
NSLayoutConstraint.bottomToBottom(
view:searchBar,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:searchBar,
toView:self)
}
}
| mit | 56bb072460f0e22abe08fd5930cc18fa | 29.431818 | 73 | 0.629574 | 5.898678 | false | false | false | false |
space150/spaceLock | ios/spacelab/SLSettingsViewController.swift | 3 | 3710 | //
// SLSettingsViewController.swift
// spacelab
//
// Created by Shawn Roske on 5/18/15.
// Copyright (c) 2015 space150. All rights reserved.
//
import UIKit
class SLSettingsViewController: UITableViewController
{
@IBOutlet weak var versionLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
versionLabel.text = version()
}
func version() -> String
{
let dictionary = NSBundle.mainBundle().infoDictionary!
let version = dictionary["CFBundleShortVersionString"] as! String
let build = dictionary["CFBundleVersion"] as! String
return "\(version)b\(build)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 2
}
/*
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
*/
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | 18806490f735f26bbb095f069d86e9c7 | 32.423423 | 157 | 0.675741 | 5.529061 | false | false | false | false |
dfrib/swift-snippets-and-utilities | Sources/EquatableConstruct.swift | 1 | 5228 | //
// EquatableConstruct.swift
//
// Created by David Friberg on 1/2/31.
//
// Copyright (c) 2016 David Friberg.
//
// 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.
//
//===----------------------------------------------------------------------===//
///
/// EquatableConstruct
///
/// Generic conformance of class and structure types to Equatable using runtime
/// introspection for automatic property-by-property comparison.
///
/// Constructs conforming to EquatableConstruct are equatable.
///
/// Notes:
/// - Will be slower than a construct-custom conformance to Equatable,
/// probably negligible for non-heavy construct comparison usage.construct
/// - Naturally limited to constructs which contain only nominal types that;
/// e.g. not intended for constructs containing closures (the latter can
/// never conform to PseudoEquatableType).
///
protocol EquatableConstruct : Equatable { }
/* Heterogeneous protocol acts as castable meta-type used for
property-by-property equalitu testing in EquatableConstruct */
protocol PseudoEquatableType {
func isEqual(to other: PseudoEquatableType) -> Bool
}
extension PseudoEquatableType where Self : Equatable {
func isEqual(to other: PseudoEquatableType) -> Bool {
if let o = other as? Self { return self == o }
return false
}
}
/* Extend fundamental (equatable) Swift types to PseudoEquatableType */
extension Bool : PseudoEquatableType {}
extension Int : PseudoEquatableType {}
extension Int8 : PseudoEquatableType {}
extension Int16 : PseudoEquatableType {}
extension Int32 : PseudoEquatableType {}
extension Int64 : PseudoEquatableType {}
extension UInt : PseudoEquatableType {}
extension UInt8 : PseudoEquatableType {}
extension UInt16 : PseudoEquatableType {}
extension UInt32 : PseudoEquatableType {}
extension UInt64 : PseudoEquatableType {}
/* EquatableConstruct's conformance to Equatable */
protocol EquatableConstruct : Equatable { }
func ==<T: EquatableConstruct>(lhs: T, rhs: T) -> Bool {
let mirrorLhs = Mirror(reflecting: lhs)
let mirrorRhs = Mirror(reflecting: rhs)
guard let displayStyle = mirrorLhs.displayStyle,
(displayStyle == .struct || displayStyle == .class) else {
print("Invalid use: type is not a construct.")
return false
}
let childrenLhs = mirrorLhs.children.filter { $0.label != nil }
let childrenRhs = mirrorRhs.children.filter { $0.label != nil }
guard childrenLhs.count == childrenRhs.count else { return false }
guard !childrenLhs.contains(where: { !($0.value is PseudoEquatableType) }) else {
print("Invalid use: not all members have types that conforms to PseudoEquatableType.")
return false
}
return zip(
childrenLhs.flatMap { $0.value as? PseudoEquatableType },
childrenRhs.flatMap { $0.value as? PseudoEquatableType })
.reduce(true) { $0 && $1.0.isEqual(to: $1.1) }
}
//===----------------------------------------------------------------------===//
// Example usage
struct MyStruct {
var myInt: Int = 0
var myString: String = ""
}
class MyClass {
var myInt: Int
var myString: String
var myStruct: MyStruct
init(myInt: Int, myString: String,
myStruct: MyStruct, myColor: UIColor) {
self.myInt = myInt
self.myString = myString
self.myStruct = myStruct
}
}
/* As a MyStruct instance is contained in MyClass, extend MyStruct to PseudoEquatableType
to add the type to allowed property types in EquatableConstruct */
extension MyStruct : PseudoEquatableType {}
/* Conformance to EquatableConstruct implies conformance to Equatable */
extension MyStruct : EquatableConstruct {}
extension MyClass : EquatableConstruct {}
/* Example */
var aa = MyStruct()
var bb = MyStruct()
aa == bb // true
aa.myInt = 1
aa == bb // false
var a = MyClass(myInt: 10, myString: "foo", myStruct: aa)
var b = MyClass(myInt: 10, myString: "foo", myStruct: aa)
a == b // true
a.myInt = 2
a == b // false
b.myInt = 2
b.myString = "Foo"
a.myString = "Foo"
a == b // true
a.myStruct.myInt = 2
a == b // false
| mit | 84a6dde1800a82917f0ba8dae553e196 | 34.324324 | 94 | 0.678653 | 4.345802 | false | false | false | false |
mcudich/TemplateKit | Examples/Twitter/Source/App.swift | 1 | 2355 | //
// App.swift
// TwitterClientExample
//
// Created by Matias Cudich on 10/27/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import Foundation
import TemplateKit
import CSSLayout
struct AppState: State {
var tweets = [Tweet]()
}
func ==(lhs: AppState, rhs: AppState) -> Bool {
return lhs.tweets == rhs.tweets
}
class App: Component<AppState, DefaultProperties, UIView> {
override func didBuild() {
TwitterClient.shared.fetchSearchResultsWithQuery(query: "donald trump") { tweets in
self.updateState { state in
state.tweets = tweets
}
}
}
override func render() -> Template {
var properties = DefaultProperties()
properties.core.layout = self.properties.core.layout
var tree: Element!
if state.tweets.count > 0 {
tree = box(properties, [
renderTweets()
])
} else {
properties.core.layout.alignItems = CSSAlignCenter
properties.core.layout.justifyContent = CSSJustifyCenter
tree = box(properties, [
activityIndicator(ActivityIndicatorProperties(["activityIndicatorViewStyle": UIActivityIndicatorViewStyle.gray]))
])
}
return Template(tree)
}
@objc func handleEndReached() {
guard let maxId = state.tweets.last?.id else {
return
}
TwitterClient.shared.fetchSearchResultsWithQuery(query: "donald trump", maxId: maxId) { tweets in
self.updateState { state in
state.tweets.append(contentsOf: tweets.dropFirst())
}
}
}
private func renderTweets() -> Element {
var properties = TableProperties()
properties.core.layout.flex = 1
properties.tableViewDataSource = self
properties.items = [TableSection(items: state.tweets, hashValue: 0)]
properties.onEndReached = #selector(App.handleEndReached)
properties.onEndReachedThreshold = 700
return table(properties)
}
}
extension App: TableViewDataSource {
func tableView(_ tableView: TableView, elementAtIndexPath indexPath: IndexPath) -> Element {
var properties = TweetProperties()
properties.tweet = state.tweets[indexPath.row]
properties.core.layout.width = self.properties.core.layout.width
return component(TweetItem.self, properties)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return state.tweets.count
}
}
| mit | eac16b392d0815e73c333bbd621b9770 | 26.694118 | 121 | 0.697111 | 4.343173 | false | false | false | false |
BENMESSAOUD/RSS | News/Networking/Connector.swift | 1 | 1688 | //
// Connector.swift
// News
//
// Created by Mahmoud Ben Messaoud on 17/03/2017.
// Copyright © 2017 Mahmoud Ben Messaoud. All rights reserved.
//
import Foundation
enum ConnectorError: Error{
case url
case xml
case server
var code: Int {
switch self {
case .url:
return 0
case .xml:
return 1
case .server:
return 2
}
}
var message: String {
switch self {
case .url:
return "Error: cannot create URL"
case .xml:
return "Wrong XML format."
case .server:
return "An Error has been occured. Please try later."
}
}
}
class Connector {
var session: URLSession
init(_ session: URLSession = URLSession(configuration: .default)) {
self.session = session
}
public func loadRSS(_ rssURL: String, completion: @escaping (String?, ConnectorError?) -> Void) {
guard let url = URL(string: rssURL) else {
completion(nil, ConnectorError.url)
return
}
let task = session.dataTask(with: url) { (data, response, error) in
let httpResponse = response as! HTTPURLResponse
if let data = data , httpResponse.statusCode == 200 && error == nil {
if let xmlString = String(data: data, encoding: .utf8) {
completion(xmlString, nil)
}
else{
completion(nil, ConnectorError.xml)
}
}
else {
completion(nil, ConnectorError.server)
}
}
task.resume()
}
}
| mit | 84a43322925022bf79061d057208aa5f | 23.449275 | 101 | 0.5246 | 4.621918 | false | false | false | false |
kusl/swift | test/SILPasses/mandatory_inlining.swift | 9 | 4890 | // RUN: %target-swift-frontend -primary-file %s -emit-sil -o - -verify | FileCheck %s
// These tests are deliberately shallow, because I do not want to depend on the
// specifics of SIL generation, which might change for reasons unrelated to this
// pass
func foo(x: Float) -> Float {
return bar(x);
}
// CHECK-LABEL: sil hidden @_TF18mandatory_inlining3foo
// CHECK: bb0(%0 : $Float):
// CHECK-NEXT: debug_value %0 : $Float // let x
// CHECK-NEXT: return %0
@_transparent func bar(x: Float) -> Float {
return baz(x)
}
// CHECK-LABEL: sil hidden [transparent] @_TF18mandatory_inlining3bar
// CHECK-NOT: function_ref
// CHECK-NOT: apply
// CHECK: return
@_transparent func baz(x: Float) -> Float {
return x;
}
// CHECK-LABEL: sil hidden [transparent] @_TF18mandatory_inlining3baz
// CHECK: return
func spam(x: Int) -> Int {
return x
}
// CHECK-LABEL: sil hidden @_TF18mandatory_inlining4spam
@_transparent func ham(x: Int) -> Int {
return spam(x)
}
// CHECK-LABEL: sil hidden [transparent] @_TF18mandatory_inlining3ham
// CHECK: function_ref @_TF18mandatory_inlining4spam
// CHECK: apply
// CHECK: return
func eggs(x: Int) -> Int {
return ham(x)
}
// CHECK-LABEL: sil hidden @_TF18mandatory_inlining4eggs
// CHECK: function_ref @_TF18mandatory_inlining4spam
// CHECK: apply
// CHECK: return
@_transparent func call_auto_closure(@autoclosure x: () -> Bool) -> Bool {
return x()
}
func test_auto_closure_with_capture(x: Bool) -> Bool {
return call_auto_closure(x)
}
// This should be fully inlined and simply return x; however, there's a lot of
// non-SSA cruft that I don't want this test to depend on, so I'm just going
// to verify that it doesn't have any function applications left
// CHECK-LABEL: sil hidden @{{.*}}test_auto_closure_with_capture
// CHECK-NOT: = apply
// CHECK: return
func test_auto_closure_without_capture() -> Bool {
return call_auto_closure(false)
}
// This should be fully inlined and simply return false, which is easier to check for
// CHECK-LABEL: sil hidden @_TF18mandatory_inlining33test_auto_closure_without_captureFT_Sb
// CHECK: [[FV:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK: [[FALSE:%.*]] = struct $Bool ([[FV:%.*]] : $Builtin.Int1)
// CHECK: return [[FALSE]]
@_transparent func test_curried(x: Int)(y: Int) -> Int { // expected-warning{{curried function declaration syntax will be removed in a future version of Swift}}
return y
}
func call_uncurried(x: Int, y: Int) -> Int {
return test_curried(x)(y: y)
}
// CHECK-LABEL: sil hidden @_TF18mandatory_inlining14call_uncurried
// CHECK-NOT: = apply
// CHECK: return
func call_curried(x: Int, y: Int) -> Int {
let z = test_curried(x)
return z(y: y)
}
// CHECK-LABEL: sil hidden @_TF18mandatory_inlining12call_curried
// CHECK: = apply
// CHECK: = apply
// CHECK: return
infix operator &&& {
associativity left
precedence 120
}
infix operator ||| {
associativity left
precedence 110
}
@_transparent func &&& (lhs: Bool, @autoclosure rhs: ()->Bool) -> Bool {
if lhs {
return rhs()
}
return false
}
@_transparent func ||| (lhs: Bool, @autoclosure rhs: ()->Bool) -> Bool {
if lhs {
return true
}
return rhs()
}
func test_chained_short_circuit(x: Bool, y: Bool, z: Bool) -> Bool {
return x &&& (y ||| z)
}
// The test below just makes sure there are no uninlined [transparent] calls
// left (i.e. the autoclosure and the short-circuiting boolean operators are
// recursively inlined properly)
// CHECK-LABEL: sil hidden @_TF18mandatory_inlining26test_chained_short_circuit
// CHECK-NOT = apply [transparent]
// CHECK: return
// Union element constructors should be inlined automatically.
enum X {
case onetransp
case twotransp
}
func testInlineUnionElement() -> X {
return X.onetransp;
// CHECK-LABEL: sil hidden @_TF18mandatory_inlining22testInlineUnionElementFT_OS_1X
// CHECK: enum $X, #X.onetransp!enumelt
// CHECK-NOT = apply
// CHECK: return
}
@_transparent
func call_let_auto_closure(@autoclosure x: () -> Bool) -> Bool {
return x()
}
// CHECK: sil hidden @{{.*}}test_let_auto_closure_with_value_capture
// CHECK: bb0(%0 : $Bool):
// CHECK-NEXT: debug_value %0 : $Bool
// CHECK-NEXT: return %0 : $Bool
func test_let_auto_closure_with_value_capture(x: Bool) -> Bool {
return call_let_auto_closure(x)
}
class C {}
// CHECK-LABEL: sil hidden [transparent] @_TF18mandatory_inlining25class_constrained_generic
@_transparent
func class_constrained_generic<T : C>(o: T) -> AnyClass? {
// CHECK: return
return T.self
}
// CHECK-LABEL: sil hidden @_TF18mandatory_inlining6invokeFCS_1CT_ : $@convention(thin) (@owned C) -> () {
func invoke(c: C) {
// CHECK-NOT: function_ref @_TF18mandatory_inlining25class_constrained_generic
// CHECK-NOT: apply
// CHECK: init_existential_metatype
class_constrained_generic(c)
// CHECK: return
}
| apache-2.0 | 53695ec9439a1238e7ba2346320c5d53 | 24.602094 | 160 | 0.680777 | 3.275285 | false | true | false | false |
willer88/Rappi-Catalog | RappiCatalog/RappiCatalog/Controllers/AppListController.swift | 1 | 3515 | //
// AppListController.swift
// RappiCatalog
//
// Created by wilmar lema on 6/14/16.
// Copyright © 2016 Lemax Inc. All rights reserved.
//
import UIKit
class AppListController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var mainCollectionView: UICollectionView!
@IBOutlet weak var mainTableView: UITableView!
var apps: [App]?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Apps"
}
override func viewWillDisappear(animated: Bool) {
UIView.animateWithDuration(0.75, animations: { () -> Void in
UIView.setAnimationCurve(UIViewAnimationCurve.EaseInOut)
UIView.setAnimationTransition(UIViewAnimationTransition.CurlDown, forView: self.navigationController!.view, cache: false)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Mark: Private
func loadAppDetail(row: Int) {
let storyboard = UIStoryboard(name: "AppDetail", bundle: nil)
let appDetailController = storyboard.instantiateViewControllerWithIdentifier("AppDetailController") as! AppDetailController
appDetailController.app = self.apps![row]
UIView.animateWithDuration(0.75, animations: { () -> Void in
UIView.setAnimationCurve(UIViewAnimationCurve.EaseInOut)
self.navigationController?.pushViewController(appDetailController, animated: true)
UIView.setAnimationTransition(UIViewAnimationTransition.CurlUp, forView: self.navigationController!.view!, cache: false)
})
}
//Mark: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (apps?.count)!
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let appCell = mainTableView.dequeueReusableCellWithIdentifier(AppTableCell.cellIdentifier(), forIndexPath: indexPath) as! AppTableCell
let app = apps![indexPath.row]
appCell.configureWithIconUrl(app.iconUrl, appName: app.name)
return appCell
}
//Mark: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
loadAppDetail(indexPath.row)
}
//Mark: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (apps?.count)!
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let collectionCell = mainCollectionView.dequeueReusableCellWithReuseIdentifier(AppCollectionCell.cellIdentifier(), forIndexPath: indexPath) as! AppCollectionCell
let app = apps![indexPath.row]
collectionCell.configureWithIconUrl(app.iconUrl, appName: app.name)
return collectionCell
}
//Mark: UITableViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
loadAppDetail(indexPath.row)
}
}
| mit | b919e7de144da6512773e1bab6be9852 | 34.14 | 169 | 0.697496 | 5.751227 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Editor/View/EditorStickerItemView.swift | 1 | 16636 | //
// EditorStickerItemView.swift
// HXPHPicker
//
// Created by Slience on 2021/7/20.
//
import UIKit
protocol EditorStickerItemViewDelegate: AnyObject {
func stickerItemView(shouldTouchBegan itemView: EditorStickerItemView) -> Bool
func stickerItemView(didTouchBegan itemView: EditorStickerItemView)
func stickerItemView(touchEnded itemView: EditorStickerItemView)
func stickerItemView(_ itemView: EditorStickerItemView, updateStickerText item: EditorStickerItem)
func stickerItemView(_ itemView: EditorStickerItemView, tapGestureRecognizerNotInScope point: CGPoint)
func stickerItemView(_ itemView: EditorStickerItemView, panGestureRecognizerChanged panGR: UIPanGestureRecognizer)
func stickerItemView(panGestureRecognizerEnded itemView: EditorStickerItemView) -> Bool
func stickerItemView(_ itemView: EditorStickerItemView, moveToCenter rect: CGRect) -> Bool
func stickerItemView(_ itemView: EditorStickerItemView, maxScale itemSize: CGSize) -> CGFloat
func stickerItemView(_ itemView: EditorStickerItemView, minScale itemSize: CGSize) -> CGFloat
}
class EditorStickerItemView: UIView {
weak var delegate: EditorStickerItemViewDelegate?
lazy var contentView: EditorStickerContentView = {
let view = EditorStickerContentView(item: item)
view.center = center
return view
}()
lazy var externalBorder: CALayer = {
let externalBorder = CALayer()
externalBorder.shadowOpacity = 0.3
externalBorder.shadowOffset = CGSize(width: 0, height: 0)
externalBorder.shadowRadius = 1
externalBorder.shouldRasterize = true
externalBorder.rasterizationScale = UIScreen.main.scale
return externalBorder
}()
var item: EditorStickerItem
var isEnabled: Bool = true {
didSet {
isUserInteractionEnabled = isEnabled
contentView.isUserInteractionEnabled = isEnabled
}
}
var isDelete: Bool = false
var scale: CGFloat
var touching: Bool = false
var isSelected: Bool = false {
willSet {
if isSelected == newValue {
return
}
if item.music == nil {
externalBorder.cornerRadius = newValue ? 1 / scale : 0
externalBorder.borderWidth = newValue ? 1 / scale : 0
}
isUserInteractionEnabled = newValue
if newValue {
update(size: contentView.item.frame.size)
}else {
firstTouch = false
}
}
}
var itemMargin: CGFloat = 20
var initialScale: CGFloat = 1
var initialPoint: CGPoint = .zero
var initialRadian: CGFloat = 0
var initialAngle: CGFloat = 0
var initialMirrorType: EditorImageResizerView.MirrorType = .none
init(item: EditorStickerItem, scale: CGFloat) {
self.item = item
self.scale = scale
let rect = CGRect(x: 0, y: 0, width: item.frame.width, height: item.frame.height)
super.init(frame: rect)
let margin = itemMargin / scale
externalBorder.frame = CGRect(
x: -margin * 0.5,
y: -margin * 0.5,
width: width + margin,
height: height + margin
)
layer.addSublayer(externalBorder)
contentView.scale = scale
addSubview(contentView)
if item.music == nil {
externalBorder.borderColor = UIColor.white.cgColor
}
// layer.shadowOpacity = 0.3
// layer.shadowOffset = CGSize(width: 0, height: 0)
// layer.shadowRadius = 1
initGestures()
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
if bounds.contains(point) {
return contentView
}
return view
}
func invalidateTimer() {
self.contentView.invalidateTimer()
}
func initGestures() {
contentView.isUserInteractionEnabled = true
let tapGR = UITapGestureRecognizer(target: self, action: #selector(contentViewTapClick(tapGR:)))
contentView.addGestureRecognizer(tapGR)
let panGR = UIPanGestureRecognizer(target: self, action: #selector(contentViewPanClick(panGR:)))
contentView.addGestureRecognizer(panGR)
if item.music == nil {
let pinchGR = UIPinchGestureRecognizer(target: self, action: #selector(contentViewPinchClick(pinchGR:)))
contentView.addGestureRecognizer(pinchGR)
}
let rotationGR = UIRotationGestureRecognizer(
target: self,
action: #selector(contentViewRotationClick(rotationGR:))
)
contentView.addGestureRecognizer(rotationGR)
}
@objc func contentViewTapClick(tapGR: UITapGestureRecognizer) {
if isDelete {
return
}
if let shouldTouch = delegate?.stickerItemView(shouldTouchBegan: self), !shouldTouch {
return
}
let point = tapGR.location(in: self)
if !contentView.frame.contains(point) {
delegate?.stickerItemView(self, tapGestureRecognizerNotInScope: point)
isSelected = false
return
}
if firstTouch && isSelected && item.text != nil && !touching {
delegate?.stickerItemView(self, updateStickerText: item)
}
firstTouch = true
}
@objc func contentViewPanClick(panGR: UIPanGestureRecognizer) {
if isDelete {
return
}
if let shouldTouch = delegate?.stickerItemView(shouldTouchBegan: self), !shouldTouch {
return
}
switch panGR.state {
case .began:
// layer.shadowOpacity = 0
touching = true
firstTouch = true
delegate?.stickerItemView(didTouchBegan: self)
isSelected = true
initialPoint = self.center
case .changed:
let point = panGR.translation(in: superview)
center = CGPoint(x: initialPoint.x + point.x, y: initialPoint.y + point.y)
delegate?.stickerItemView(self, panGestureRecognizerChanged: panGR)
case .ended, .cancelled, .failed:
// layer.shadowOpacity = 0.3
touching = false
var isDelete = false
if let panIsDelete = delegate?.stickerItemView(panGestureRecognizerEnded: self) {
isDelete = panIsDelete
}
self.delegate?.stickerItemView(touchEnded: self)
let rect = convert(contentView.frame, to: superview?.viewController?.view)
if let moveToCenter = delegate?.stickerItemView(self, moveToCenter: rect), !isDelete {
let keyWindow = UIApplication.shared.keyWindow
if let view = keyWindow, moveToCenter,
let viewCenter = superview?.convert(
CGPoint(x: view.width * 0.5, y: view.height * 0.5),
from: view
) {
UIView.animate(withDuration: 0.25) {
self.center = viewCenter
}
}
}
default:
break
}
}
@objc func contentViewPinchClick(pinchGR: UIPinchGestureRecognizer) {
if isDelete {
return
}
if let shouldTouch = delegate?.stickerItemView(shouldTouchBegan: self), !shouldTouch {
return
}
switch pinchGR.state {
case .began:
// layer.shadowOpacity = 0
touching = true
firstTouch = true
delegate?.stickerItemView(didTouchBegan: self)
isSelected = true
initialScale = pinchScale
update(pinchScale: initialScale * pinchGR.scale, isPinch: true, isMirror: true)
case .changed:
update(pinchScale: initialScale * pinchGR.scale, isPinch: true, isMirror: true)
case .ended, .cancelled, .failed:
// layer.shadowOpacity = 0.3
touching = false
delegate?.stickerItemView(touchEnded: self)
default:
break
}
if pinchGR.state == .began && pinchGR.state == .changed {
pinchGR.scale = 1
}
}
@objc func contentViewRotationClick(rotationGR: UIRotationGestureRecognizer) {
if isDelete {
return
}
if let shouldTouch = delegate?.stickerItemView(shouldTouchBegan: self), !shouldTouch {
return
}
switch rotationGR.state {
case .began:
// layer.shadowOpacity = 0
firstTouch = true
touching = true
isSelected = true
delegate?.stickerItemView(didTouchBegan: self)
initialRadian = radian
rotationGR.rotation = 0
case .changed:
if let superView = superview, superView is EditorStickerView {
if superMirrorType == .none {
if mirrorType == .horizontal {
radian = initialRadian - rotationGR.rotation
}else {
radian = initialRadian + rotationGR.rotation
}
}else {
if mirrorType == .horizontal {
radian = initialRadian - rotationGR.rotation
}else {
radian = initialRadian + rotationGR.rotation
}
}
}else {
if superMirrorType == .none {
if mirrorType == .horizontal {
radian = initialRadian - rotationGR.rotation
}else {
radian = initialRadian + rotationGR.rotation
}
}else {
if mirrorType == .horizontal {
radian = initialRadian - rotationGR.rotation
}else {
radian = initialRadian + rotationGR.rotation
}
}
}
update(pinchScale: pinchScale, rotation: radian, isMirror: true)
case .ended, .cancelled, .failed:
// layer.shadowOpacity = 0.3
touching = false
delegate?.stickerItemView(touchEnded: self)
rotationGR.rotation = 0
default:
break
}
}
var firstTouch: Bool = false
var radian: CGFloat = 0
var pinchScale: CGFloat = 1
var mirrorType: EditorImageResizerView.MirrorType = .none
var superMirrorType: EditorImageResizerView.MirrorType = .none
var superAngle: CGFloat = 0
func update(pinchScale: CGFloat,
rotation: CGFloat = CGFloat(MAXFLOAT),
isInitialize: Bool = false,
isPinch: Bool = false,
isMirror: Bool = false) {
if rotation != CGFloat(MAXFLOAT) {
radian = rotation
}
var minScale = 0.2 / scale
var maxScale = 3.0 / scale
if let min = delegate?.stickerItemView(self, minScale: item.frame.size) {
minScale = min / scale
}
if let max = delegate?.stickerItemView(self, maxScale: item.frame.size) {
maxScale = max / scale
}
if isInitialize {
self.pinchScale = pinchScale
}else {
if isPinch {
if pinchScale > maxScale {
if pinchScale < initialScale {
self.pinchScale = pinchScale
}else {
if initialScale < maxScale {
self.pinchScale = min(max(pinchScale, minScale), maxScale)
}else {
self.pinchScale = initialScale
}
}
}else if pinchScale < minScale {
if pinchScale > initialScale {
self.pinchScale = pinchScale
}else {
if minScale < initialScale {
self.pinchScale = min(max(pinchScale, minScale), maxScale)
}else {
self.pinchScale = initialScale
}
}
}else {
self.pinchScale = min(max(pinchScale, minScale), maxScale)
}
}else {
self.pinchScale = pinchScale
}
}
transform = .identity
var margin = itemMargin / scale
if touching {
margin *= scale
contentView.transform = .init(scaleX: self.pinchScale * scale, y: self.pinchScale * scale)
}else {
contentView.transform = .init(scaleX: self.pinchScale, y: self.pinchScale)
}
var rect = frame
rect.origin.x += (rect.width - contentView.width) / 2
rect.origin.y += (rect.height - contentView.height) / 2
rect.size.width = contentView.width
rect.size.height = contentView.height
frame = rect
CATransaction.begin()
CATransaction.setDisableActions(true)
externalBorder.frame = CGRect(
x: -margin * 0.5,
y: -margin * 0.5,
width: width + margin,
height: height + margin
)
CATransaction.commit()
contentView.center = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5)
if isMirror {
if let superView = superview, superView is EditorStickerView {
if superMirrorType == .none {
if mirrorType == .horizontal {
transform = transform.scaledBy(x: -1, y: 1)
}
}else {
if mirrorType == .none {
transform = transform.scaledBy(x: -1, y: 1)
}
}
}else {
if superMirrorType == .none {
if mirrorType == .horizontal {
if superAngle.truncatingRemainder(dividingBy: 180) != 0 {
transform = transform.scaledBy(x: 1, y: -1)
}else {
transform = transform.scaledBy(x: -1, y: 1)
}
}
}else {
if mirrorType == .horizontal {
transform = transform.scaledBy(x: -1, y: 1)
}else {
if superAngle.truncatingRemainder(dividingBy: 180) != 0 {
transform = transform.scaledBy(x: -1, y: -1)
}else {
transform = transform.scaledBy(x: 1, y: 1)
}
}
}
}
}
transform = transform.rotated(by: radian)
if isSelected && item.music == nil {
CATransaction.begin()
CATransaction.setDisableActions(true)
if touching {
externalBorder.borderWidth = 1
externalBorder.cornerRadius = 1
}else {
externalBorder.borderWidth = 1 / scale
externalBorder.cornerRadius = 1 / scale
}
CATransaction.commit()
}
}
func update(item: EditorStickerItem) {
self.item = item
contentView.update(item: item)
update(size: item.frame.size, isMirror: true)
}
func update(size: CGSize, isMirror: Bool = false) {
let center = self.center
var frame = frame
frame.size = CGSize(width: size.width, height: size.height)
self.frame = frame
self.center = center
let margin = itemMargin / scale
externalBorder.frame = CGRect(
x: -margin * 0.5,
y: -margin * 0.5,
width: width + margin,
height: height + margin
)
contentView.transform = .identity
transform = .identity
contentView.size = size
contentView.center = CGPoint(x: width * 0.5, y: height * 0.5)
update(pinchScale: pinchScale, rotation: radian, isMirror: isMirror)
}
func resetRotaion() {
update(pinchScale: pinchScale, rotation: radian, isMirror: true)
}
override func layoutSubviews() {
super.layoutSubviews()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | d1f4c960ac3fe31310dfc5c767c82c25 | 37.509259 | 118 | 0.546706 | 5.189021 | false | false | false | false |
tensorflow/swift-models | Datasets/MNIST/FashionMNIST.swift | 1 | 4446 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Original source:
// "Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms"
// Han Xiao and Kashif Rasul and Roland Vollgraf
// https://arxiv.org/abs/1708.07747
import Foundation
import TensorFlow
public struct FashionMNIST<Entropy: RandomNumberGenerator> {
/// Type of the collection of non-collated batches.
public typealias Batches = Slices<Sampling<[(data: [UInt8], label: Int32)], ArraySlice<Int>>>
/// The type of the training data, represented as a sequence of epochs, which
/// are collection of batches.
public typealias Training = LazyMapSequence<
TrainingEpochs<[(data: [UInt8], label: Int32)], Entropy>,
LazyMapSequence<Batches, LabeledImage>
>
/// The type of the validation data, represented as a collection of batches.
public typealias Validation = LazyMapSequence<Slices<[(data: [UInt8], label: Int32)]>, LabeledImage>
/// The training epochs.
public let training: Training
/// The validation batches.
public let validation: Validation
/// Creates an instance with `batchSize`.
///
/// - Parameter entropy: a source of randomness used to shuffle sample
/// ordering. It will be stored in `self`, so if it is only pseudorandom
/// and has value semantics, the sequence of epochs is deterministic and not
/// dependent on other operations.
public init(batchSize: Int, entropy: Entropy, device: Device) {
self.init(batchSize: batchSize, device: device, entropy: entropy,
flattening: false, normalizing: false)
}
/// Creates an instance with `batchSize` on `device`.
///
/// - Parameters:
/// - entropy: a source of randomness used to shuffle sample ordering. It
/// will be stored in `self`, so if it is only pseudorandom and has value
/// semantics, the sequence of epochs is deterministic and not dependent
/// on other operations.
/// - flattening: flattens the data to be a 2d-tensor iff `true. The default value
/// is `false`.
/// - normalizing: normalizes the batches to have values from -1.0 to 1.0 iff `true`.
/// The default value is `false`.
/// - localStorageDirectory: the directory in which the dataset is stored.
public init(
batchSize: Int, device: Device, entropy: Entropy, flattening: Bool = false,
normalizing: Bool = false,
localStorageDirectory: URL = DatasetUtilities.defaultDirectory
.appendingPathComponent("FashionMNIST", isDirectory: true)
) {
training = TrainingEpochs(
samples: fetchMNISTDataset(
localStorageDirectory: localStorageDirectory,
remoteBaseDirectory: "http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/",
imagesFilename: "train-images-idx3-ubyte",
labelsFilename: "train-labels-idx1-ubyte"),
batchSize: batchSize, entropy: entropy
).lazy.map { (batches: Batches) -> LazyMapSequence<Batches, LabeledImage> in
return batches.lazy.map{ makeMNISTBatch(
samples: $0, flattening: flattening, normalizing: normalizing, device: device
)}
}
validation = fetchMNISTDataset(
localStorageDirectory: localStorageDirectory,
remoteBaseDirectory: "http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/",
imagesFilename: "t10k-images-idx3-ubyte",
labelsFilename: "t10k-labels-idx1-ubyte"
).inBatches(of: batchSize).lazy.map {
makeMNISTBatch(samples: $0, flattening: flattening, normalizing: normalizing,
device: device)
}
}
}
extension FashionMNIST: ImageClassificationData where Entropy == SystemRandomNumberGenerator {
/// Creates an instance with `batchSize`.
public init(batchSize: Int, on device: Device = Device.default) {
self.init(batchSize: batchSize, entropy: SystemRandomNumberGenerator(), device: device)
}
}
| apache-2.0 | 89dafef98284808b8198279f40ca78f2 | 44.367347 | 102 | 0.708952 | 4.254545 | false | false | false | false |
thislooksfun/Tavi | Tavi/API/GitHub/GithubAPIAuthorization.swift | 1 | 5349 | //
// GithubAPIAuthorization.swift
// Tavi
//
// Copyright (C) 2016 thislooksfun
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
/// A class for storing and retrieving a [GitHub](https://github.com) authorization token
class GithubAPIAuthorization
{
// MARK: Variables
let id: Int
let note: String
let user: String
let token: String
let scopes: [String]
let tokenHash: String
let fingerprint: String
// MARK: - Initalizers
/// Creates an instance from a `JSON` object and a token
///
/// - Parameters:
/// - json: The `JSON` object to load from
/// - token: The authorization token
private init(id: Int, note: String, user: String, token: String, scopes: [String], tokenHash: String, fingerprint: String)
{
self.id = id
self.note = note
self.user = user
self.token = token
self.scopes = scopes
self.tokenHash = tokenHash
self.fingerprint = fingerprint
}
// MARK: - Functions -
// MARK: Static
/// Creates an instance from a `JSON` object
///
/// - Parameters:
/// - json: The `JSON` object to load from
/// - cb: The callback to execute upon completion
static func makeInstanceFromJson(json: JSON, cb: (GithubAPIAuthorization?) -> Void) {
let tok = json.getString("token")
guard tok != nil && tok != "" else {
cb(nil)
return
}
makeInstanceFromJson(json, andToken: tok!, cb: cb)
}
/// Creates an instance from a `JSON` object and a token
///
/// - Parameters:
/// - json: The `JSON` object to load from
/// - token: The authorization token
/// - cb: The callback to execute upon completion
static func makeInstanceFromJson(json: JSON, andToken token: String, cb: (GithubAPIAuthorization?) -> Void)
{
Logger.trace("Loading JSON:\n\(json)\nWith token: '\(token)'")
var user: String?
if let msg = json.getString("message") {
Logger.warn("Msg: "+msg)
}
user = json.getJson("user")?.getString("login")
Logger.info(user)
let id = json.getInt("id")!
let note = json.getString("note") ?? ""
let token = token
let scopes = json.getKey("scopes") as! [String]
let tokenHash = json.getString("hashed_token")!
let fingerprint = json.getString("fingerprint") ?? ""
let authString = AuthHelper.generateAuthString(clientID, pass: clientSecret)
if user == nil {
GithubAPIBackend.apiCall("applications/\(clientID)/tokens/\(token)", method: .GET, headers: ["Authorization": authString])
{ (errMsg: String?, json: JSON?, _) in
if errMsg != nil {
Logger.info(errMsg!)
cb(nil)
} else {
user = json?.getJson("user")?.getString("login") ?? ""
if user != "" {
cb(GithubAPIAuthorization(id: id, note: note, user: user!, token: token, scopes: scopes, tokenHash: tokenHash, fingerprint: fingerprint))
}
}
}
} else {
cb(GithubAPIAuthorization(id: id, note: note, user: user!, token: token, scopes: scopes, tokenHash: tokenHash, fingerprint: fingerprint))
}
}
/// Attempts to load a `GithubAPIAuthorization` instance from the stored information
///
/// - Parameter cb: The callback to execute upon completion
static func load(cb: (GithubAPIAuthorization?) -> Void)
{
let token = Settings.GitHub_Token.get()
Logger.trace("Token = \(token)")
guard token != nil && token != "" else { return cb(nil) }
let authString = AuthHelper.generateAuthString(clientID, pass: clientSecret)
GithubAPIBackend.apiCall("applications/\(clientID)/tokens/\(token!)", method: .GET, headers: ["Authorization": authString])
{ (errMsg: String?, json: JSON?, _) in
if errMsg != nil {
Logger.info(errMsg!)
cb(nil)
} else if json == nil {
Logger.info("JSON is nil!")
cb(nil)
} else {
if let s = json!.getString("message") {
Logger.error("Message: \(s)")
cb(nil)
} else {
makeInstanceFromJson(json!, andToken: token!, cb: cb)
}
}
}
}
// MARK: Internal
/// Saves the authorization information
func save() {
Settings.GitHub_Token.set(self.token)
Settings.GitHub_User.set(self.user)
}
/// Deletes the authorization information
///
/// - Warning: This is permanent. The only way to undo this is to re-authorize with [GitHub](https://github.com)
func delete() {
deleteToken()
Settings.GitHub_User.set(nil)
}
/// Deletes the authorization token
///
/// - Warning: This is permanent. The only way to undo this is to re-authorize with [GitHub](https://github.com)
func deleteToken() {
GithubAPIBackend.apiCall("/authorizations/\(self.id)", method: .DELETE)
{ (errMsg: String?, _, httpResponse: NSHTTPURLResponse?) in
Settings.GitHub_Token.set(nil)
}
}
} | gpl-3.0 | cb56a5d8c55708c98ddd544b8cd5e6ed | 28.888268 | 143 | 0.652085 | 3.500654 | false | false | false | false |
biohazardlover/NintendoEverything | Pods/ImageViewer/ImageViewer/Source/GalleryViewController.swift | 2 | 28411 | //
// GalleryViewController.swift
// ImageViewer
//
// Created by Kristian Angyal on 01/07/2016.
// Copyright © 2016 MailOnline. All rights reserved.
//
import UIKit
import AVFoundation
open class GalleryViewController: UIPageViewController, ItemControllerDelegate {
// UI
fileprivate let overlayView = BlurView()
/// A custom view on the top of the gallery with layout using default (or custom) pinning settings for header.
open var headerView: UIView?
/// A custom view at the bottom of the gallery with layout using default (or custom) pinning settings for footer.
open var footerView: UIView?
fileprivate var closeButton: UIButton? = UIButton.closeButton()
fileprivate var seeAllCloseButton: UIButton? = nil
fileprivate var thumbnailsButton: UIButton? = UIButton.thumbnailsButton()
fileprivate var deleteButton: UIButton? = UIButton.deleteButton()
fileprivate let scrubber = VideoScrubber()
fileprivate weak var initialItemController: ItemController?
// LOCAL STATE
// represents the current page index, updated when the root view of the view controller representing the page stops animating inside visible bounds and stays on screen.
public var currentIndex: Int
// Picks up the initial value from configuration, if provided. Subsequently also works as local state for the setting.
fileprivate var decorationViewsHidden = false
fileprivate var isAnimating = false
fileprivate var initialPresentationDone = false
// DATASOURCE/DELEGATE
fileprivate let itemsDelegate: GalleryItemsDelegate?
fileprivate let itemsDataSource: GalleryItemsDataSource
fileprivate let pagingDataSource: GalleryPagingDataSource
// CONFIGURATION
fileprivate var spineDividerWidth: Float = 10
fileprivate var galleryPagingMode = GalleryPagingMode.standard
fileprivate var headerLayout = HeaderLayout.center(25)
fileprivate var footerLayout = FooterLayout.center(25)
fileprivate var closeLayout = ButtonLayout.pinRight(8, 16)
fileprivate var seeAllCloseLayout = ButtonLayout.pinRight(8, 16)
fileprivate var thumbnailsLayout = ButtonLayout.pinLeft(8, 16)
fileprivate var deleteLayout = ButtonLayout.pinRight(8, 66)
fileprivate var statusBarHidden = true
fileprivate var overlayAccelerationFactor: CGFloat = 1
fileprivate var rotationDuration = 0.15
fileprivate var rotationMode = GalleryRotationMode.always
fileprivate let swipeToDismissFadeOutAccelerationFactor: CGFloat = 6
fileprivate var decorationViewsFadeDuration = 0.15
/// COMPLETION BLOCKS
/// If set, the block is executed right after the initial launch animations finish.
open var launchedCompletion: (() -> Void)?
/// If set, called every time ANY animation stops in the page controller stops and the viewer passes a page index of the page that is currently on screen
open var landedPageAtIndexCompletion: ((Int) -> Void)?
/// If set, launched after all animations finish when the close button is pressed.
open var closedCompletion: (() -> Void)?
/// If set, launched after all animations finish when the close() method is invoked via public API.
open var programmaticallyClosedCompletion: (() -> Void)?
/// If set, launched after all animations finish when the swipe-to-dismiss (applies to all directions and cases) gesture is used.
open var swipedToDismissCompletion: (() -> Void)?
@available(*, unavailable)
required public init?(coder: NSCoder) { fatalError() }
public init(startIndex: Int, itemsDataSource: GalleryItemsDataSource, itemsDelegate: GalleryItemsDelegate? = nil, displacedViewsDataSource: GalleryDisplacedViewsDataSource? = nil, configuration: GalleryConfiguration = []) {
self.currentIndex = startIndex
self.itemsDelegate = itemsDelegate
self.itemsDataSource = itemsDataSource
var continueNextVideoOnFinish: Bool = false
///Only those options relevant to the paging GalleryViewController are explicitly handled here, the rest is handled by ItemViewControllers
for item in configuration {
switch item {
case .imageDividerWidth(let width): spineDividerWidth = Float(width)
case .pagingMode(let mode): galleryPagingMode = mode
case .headerViewLayout(let layout): headerLayout = layout
case .footerViewLayout(let layout): footerLayout = layout
case .closeLayout(let layout): closeLayout = layout
case .thumbnailsLayout(let layout): thumbnailsLayout = layout
case .statusBarHidden(let hidden): statusBarHidden = hidden
case .hideDecorationViewsOnLaunch(let hidden): decorationViewsHidden = hidden
case .decorationViewsFadeDuration(let duration): decorationViewsFadeDuration = duration
case .rotationDuration(let duration): rotationDuration = duration
case .rotationMode(let mode): rotationMode = mode
case .overlayColor(let color): overlayView.overlayColor = color
case .overlayBlurStyle(let style): overlayView.blurringView.effect = UIBlurEffect(style: style)
case .overlayBlurOpacity(let opacity): overlayView.blurTargetOpacity = opacity
case .overlayColorOpacity(let opacity): overlayView.colorTargetOpacity = opacity
case .blurPresentDuration(let duration): overlayView.blurPresentDuration = duration
case .blurPresentDelay(let delay): overlayView.blurPresentDelay = delay
case .colorPresentDuration(let duration): overlayView.colorPresentDuration = duration
case .colorPresentDelay(let delay): overlayView.colorPresentDelay = delay
case .blurDismissDuration(let duration): overlayView.blurDismissDuration = duration
case .blurDismissDelay(let delay): overlayView.blurDismissDelay = delay
case .colorDismissDuration(let duration): overlayView.colorDismissDuration = duration
case .colorDismissDelay(let delay): overlayView.colorDismissDelay = delay
case .continuePlayVideoOnEnd(let enabled): continueNextVideoOnFinish = enabled
case .seeAllCloseLayout(let layout): seeAllCloseLayout = layout
case .videoControlsColor(let color): scrubber.tintColor = color
case .closeButtonMode(let buttonMode):
switch buttonMode {
case .none: closeButton = nil
case .custom(let button): closeButton = button
case .builtIn: break
}
case .seeAllCloseButtonMode(let buttonMode):
switch buttonMode {
case .none: seeAllCloseButton = nil
case .custom(let button): seeAllCloseButton = button
case .builtIn: break
}
case .thumbnailsButtonMode(let buttonMode):
switch buttonMode {
case .none: thumbnailsButton = nil
case .custom(let button): thumbnailsButton = button
case .builtIn: break
}
case .deleteButtonMode(let buttonMode):
switch buttonMode {
case .none: deleteButton = nil
case .custom(let button): deleteButton = button
case .builtIn: break
}
default: break
}
}
pagingDataSource = GalleryPagingDataSource(itemsDataSource: itemsDataSource, displacedViewsDataSource: displacedViewsDataSource, scrubber: scrubber, configuration: configuration)
super.init(transitionStyle: UIPageViewControllerTransitionStyle.scroll,
navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal,
options: [UIPageViewControllerOptionInterPageSpacingKey : NSNumber(value: spineDividerWidth as Float)])
pagingDataSource.itemControllerDelegate = self
///This feels out of place, one would expect even the first presented(paged) item controller to be provided by the paging dataSource but there is nothing we can do as Apple requires the first controller to be set via this "setViewControllers" method.
let initialController = pagingDataSource.createItemController(startIndex, isInitial: true)
self.setViewControllers([initialController], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil)
if let controller = initialController as? ItemController {
initialItemController = controller
}
///This less known/used presentation style option allows the contents of parent view controller presenting the gallery to "bleed through" the blurView. Otherwise we would see only black color.
self.modalPresentationStyle = .overFullScreen
self.dataSource = pagingDataSource
UIApplication.applicationWindow.windowLevel = (statusBarHidden) ? UIWindowLevelStatusBar + 1 : UIWindowLevelNormal
NotificationCenter.default.addObserver(self, selector: #selector(GalleryViewController.rotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
if continueNextVideoOnFinish {
NotificationCenter.default.addObserver(self, selector: #selector(didEndPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func didEndPlaying() {
page(toIndex: currentIndex+1)
}
fileprivate func configureOverlayView() {
overlayView.bounds.size = UIScreen.main.bounds.insetBy(dx: -UIScreen.main.bounds.width / 2, dy: -UIScreen.main.bounds.height / 2).size
overlayView.center = CGPoint(x: (UIScreen.main.bounds.width / 2), y: (UIScreen.main.bounds.height / 2))
self.view.addSubview(overlayView)
self.view.sendSubview(toBack: overlayView)
}
fileprivate func configureHeaderView() {
if let header = headerView {
header.alpha = 0
self.view.addSubview(header)
}
}
fileprivate func configureFooterView() {
if let footer = footerView {
footer.alpha = 0
self.view.addSubview(footer)
}
}
fileprivate func configureCloseButton() {
if let closeButton = closeButton {
closeButton.addTarget(self, action: #selector(GalleryViewController.closeInteractively), for: .touchUpInside)
closeButton.alpha = 0
self.view.addSubview(closeButton)
}
}
fileprivate func configureThumbnailsButton() {
if let thumbnailsButton = thumbnailsButton {
thumbnailsButton.addTarget(self, action: #selector(GalleryViewController.showThumbnails), for: .touchUpInside)
thumbnailsButton.alpha = 0
self.view.addSubview(thumbnailsButton)
}
}
fileprivate func configureDeleteButton() {
if let deleteButton = deleteButton {
deleteButton.addTarget(self, action: #selector(GalleryViewController.deleteItem), for: .touchUpInside)
deleteButton.alpha = 0
self.view.addSubview(deleteButton)
}
}
fileprivate func configureScrubber() {
scrubber.alpha = 0
self.view.addSubview(scrubber)
}
open override func viewDidLoad() {
super.viewDidLoad()
configureHeaderView()
configureFooterView()
configureCloseButton()
configureThumbnailsButton()
configureDeleteButton()
configureScrubber()
self.view.clipsToBounds = false
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard initialPresentationDone == false else { return }
///We have to call this here (not sooner), because it adds the overlay view to the presenting controller and the presentingController property is set only at this moment in the VC lifecycle.
configureOverlayView()
///The initial presentation animations and transitions
presentInitially()
initialPresentationDone = true
}
fileprivate func presentInitially() {
isAnimating = true
///Animates decoration views to the initial state if they are set to be visible on launch. We do not need to do anything if they are set to be hidden because they are already set up as hidden by default. Unhiding them for the launch is part of chosen UX.
initialItemController?.presentItem(alongsideAnimation: { [weak self] in
self?.overlayView.present()
}, completion: { [weak self] in
if let strongSelf = self {
if strongSelf.decorationViewsHidden == false {
strongSelf.animateDecorationViews(visible: true)
}
strongSelf.isAnimating = false
strongSelf.launchedCompletion?()
}
})
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if rotationMode == .always && UIApplication.isPortraitOnly {
let transform = windowRotationTransform()
let bounds = rotationAdjustedBounds()
self.view.transform = transform
self.view.bounds = bounds
}
overlayView.frame = view.bounds.insetBy(dx: -UIScreen.main.bounds.width * 2, dy: -UIScreen.main.bounds.height * 2)
layoutButton(closeButton, layout: closeLayout)
layoutButton(thumbnailsButton, layout: thumbnailsLayout)
layoutButton(deleteButton, layout: deleteLayout)
layoutHeaderView()
layoutFooterView()
layoutScrubber()
}
fileprivate func layoutButton(_ button: UIButton?, layout: ButtonLayout) {
guard let button = button else { return }
switch layout {
case .pinRight(let marginTop, let marginRight):
button.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin]
button.frame.origin.x = self.view.bounds.size.width - marginRight - button.bounds.size.width
button.frame.origin.y = marginTop
case .pinLeft(let marginTop, let marginLeft):
button.autoresizingMask = [.flexibleBottomMargin, .flexibleRightMargin]
button.frame.origin.x = marginLeft
button.frame.origin.y = marginTop
}
}
fileprivate func layoutHeaderView() {
guard let header = headerView else { return }
switch headerLayout {
case .center(let marginTop):
header.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin]
header.center = self.view.boundsCenter
header.frame.origin.y = marginTop
case .pinBoth(let marginTop, let marginLeft,let marginRight):
header.autoresizingMask = [.flexibleBottomMargin, .flexibleWidth]
header.bounds.size.width = self.view.bounds.width - marginLeft - marginRight
header.sizeToFit()
header.frame.origin = CGPoint(x: marginLeft, y: marginTop)
case .pinLeft(let marginTop, let marginLeft):
header.autoresizingMask = [.flexibleBottomMargin, .flexibleRightMargin]
header.frame.origin = CGPoint(x: marginLeft, y: marginTop)
case .pinRight(let marginTop, let marginRight):
header.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin]
header.frame.origin = CGPoint(x: self.view.bounds.width - marginRight - header.bounds.width, y: marginTop)
}
}
fileprivate func layoutFooterView() {
guard let footer = footerView else { return }
switch footerLayout {
case .center(let marginBottom):
footer.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin]
footer.center = self.view.boundsCenter
footer.frame.origin.y = self.view.bounds.height - footer.bounds.height - marginBottom
case .pinBoth(let marginBottom, let marginLeft,let marginRight):
footer.autoresizingMask = [.flexibleTopMargin, .flexibleWidth]
footer.frame.size.width = self.view.bounds.width - marginLeft - marginRight
footer.sizeToFit()
footer.frame.origin = CGPoint(x: marginLeft, y: self.view.bounds.height - footer.bounds.height - marginBottom)
case .pinLeft(let marginBottom, let marginLeft):
footer.autoresizingMask = [.flexibleTopMargin, .flexibleRightMargin]
footer.frame.origin = CGPoint(x: marginLeft, y: self.view.bounds.height - footer.bounds.height - marginBottom)
case .pinRight(let marginBottom, let marginRight):
footer.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin]
footer.frame.origin = CGPoint(x: self.view.bounds.width - marginRight - footer.bounds.width, y: self.view.bounds.height - footer.bounds.height - marginBottom)
}
}
fileprivate func layoutScrubber() {
scrubber.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: self.view.bounds.width, height: 40))
scrubber.center = self.view.boundsCenter
scrubber.frame.origin.y = (footerView?.frame.origin.y ?? self.view.bounds.maxY) - scrubber.bounds.height
}
@objc fileprivate func deleteItem() {
deleteButton?.isEnabled = false
view.isUserInteractionEnabled = false
itemsDelegate?.removeGalleryItem(at: currentIndex)
removePage(atIndex: currentIndex) {
[weak self] in
self?.deleteButton?.isEnabled = true
self?.view.isUserInteractionEnabled = true
}
}
//ThumbnailsimageBlock
@objc fileprivate func showThumbnails() {
let thumbnailsController = ThumbnailsViewController(itemsDataSource: self.itemsDataSource)
if let closeButton = seeAllCloseButton {
thumbnailsController.closeButton = closeButton
thumbnailsController.closeLayout = seeAllCloseLayout
} else if let closeButton = closeButton {
let seeAllCloseButton = UIButton(frame: CGRect(origin: CGPoint.zero, size: closeButton.bounds.size))
seeAllCloseButton.setImage(closeButton.image(for: UIControlState()), for: UIControlState())
seeAllCloseButton.setImage(closeButton.image(for: .highlighted), for: .highlighted)
thumbnailsController.closeButton = seeAllCloseButton
thumbnailsController.closeLayout = closeLayout
}
thumbnailsController.onItemSelected = { [weak self] index in
self?.page(toIndex: index)
}
present(thumbnailsController, animated: true, completion: nil)
}
open func page(toIndex index: Int) {
guard currentIndex != index && index >= 0 && index < self.itemsDataSource.itemCount() else { return }
let imageViewController = self.pagingDataSource.createItemController(index)
let direction: UIPageViewControllerNavigationDirection = index > currentIndex ? .forward : .reverse
// workaround to make UIPageViewController happy
if direction == .forward {
let previousVC = self.pagingDataSource.createItemController(index - 1)
setViewControllers([previousVC], direction: direction, animated: true, completion: { finished in
DispatchQueue.main.async(execute: { [weak self] in
self?.setViewControllers([imageViewController], direction: direction, animated: false, completion: nil)
})
})
} else {
let nextVC = self.pagingDataSource.createItemController(index + 1)
setViewControllers([nextVC], direction: direction, animated: true, completion: { finished in
DispatchQueue.main.async(execute: { [weak self] in
self?.setViewControllers([imageViewController], direction: direction, animated: false, completion: nil)
})
})
}
}
func removePage(atIndex index: Int, completion: @escaping () -> Void) {
// If removing last item, go back, otherwise, go forward
let direction: UIPageViewControllerNavigationDirection = index < self.itemsDataSource.itemCount() ? .forward : .reverse
let newIndex = direction == .forward ? index : index - 1
if newIndex < 0 { close(); return }
let vc = self.pagingDataSource.createItemController(newIndex)
setViewControllers([vc], direction: direction, animated: true) { _ in completion() }
}
open func reload(atIndex index: Int) {
guard index >= 0 && index < self.itemsDataSource.itemCount() else { return }
guard let firstVC = viewControllers?.first, let itemController = firstVC as? ItemController else { return }
itemController.fetchImage()
}
// MARK: - Animations
@objc fileprivate func rotate() {
/// If the app supports rotation on global level, we don't need to rotate here manually because the rotation
/// of key Window will rotate all app's content with it via affine transform and from the perspective of the
/// gallery it is just a simple relayout. Allowing access to remaining code only makes sense if the app is
/// portrait only but we still want to support rotation inside the gallery.
guard UIApplication.isPortraitOnly else { return }
guard UIDevice.current.orientation.isFlat == false &&
isAnimating == false else { return }
isAnimating = true
UIView.animate(withDuration: rotationDuration, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: { [weak self] () -> Void in
self?.view.transform = windowRotationTransform()
self?.view.bounds = rotationAdjustedBounds()
self?.view.setNeedsLayout()
self?.view.layoutIfNeeded()
})
{ [weak self] finished in
self?.isAnimating = false
}
}
/// Invoked when closed programmatically
open func close() {
closeDecorationViews(programmaticallyClosedCompletion)
}
/// Invoked when closed via close button
@objc fileprivate func closeInteractively() {
closeDecorationViews(closedCompletion)
}
fileprivate func closeDecorationViews(_ completion: (() -> Void)?) {
guard isAnimating == false else { return }
isAnimating = true
if let itemController = self.viewControllers?.first as? ItemController {
itemController.closeDecorationViews(decorationViewsFadeDuration)
}
UIView.animate(withDuration: decorationViewsFadeDuration, animations: { [weak self] in
self?.headerView?.alpha = 0.0
self?.footerView?.alpha = 0.0
self?.closeButton?.alpha = 0.0
self?.thumbnailsButton?.alpha = 0.0
self?.deleteButton?.alpha = 0.0
self?.scrubber.alpha = 0.0
}, completion: { [weak self] done in
if let strongSelf = self,
let itemController = strongSelf.viewControllers?.first as? ItemController {
itemController.dismissItem(alongsideAnimation: {
strongSelf.overlayView.dismiss()
}, completion: { [weak self] in
self?.isAnimating = true
self?.closeGallery(false, completion: completion)
})
}
})
}
func closeGallery(_ animated: Bool, completion: (() -> Void)?) {
self.overlayView.removeFromSuperview()
self.modalTransitionStyle = .crossDissolve
self.dismiss(animated: animated) {
UIApplication.applicationWindow.windowLevel = UIWindowLevelNormal
completion?()
}
}
fileprivate func animateDecorationViews(visible: Bool) {
let targetAlpha: CGFloat = (visible) ? 1 : 0
UIView.animate(withDuration: decorationViewsFadeDuration, animations: { [weak self] in
self?.headerView?.alpha = targetAlpha
self?.footerView?.alpha = targetAlpha
self?.closeButton?.alpha = targetAlpha
self?.thumbnailsButton?.alpha = targetAlpha
self?.deleteButton?.alpha = targetAlpha
if let _ = self?.viewControllers?.first as? VideoViewController {
UIView.animate(withDuration: 0.3, animations: { [weak self] in
self?.scrubber.alpha = targetAlpha
})
}
})
}
public func itemControllerWillAppear(_ controller: ItemController) {
if let videoController = controller as? VideoViewController {
scrubber.player = videoController.player
}
}
public func itemControllerWillDisappear(_ controller: ItemController) {
if let _ = controller as? VideoViewController {
scrubber.player = nil
UIView.animate(withDuration: 0.3, animations: { [weak self] in
self?.scrubber.alpha = 0
})
}
}
public func itemControllerDidAppear(_ controller: ItemController) {
self.currentIndex = controller.index
self.landedPageAtIndexCompletion?(self.currentIndex)
self.headerView?.sizeToFit()
self.footerView?.sizeToFit()
if let videoController = controller as? VideoViewController {
scrubber.player = videoController.player
if scrubber.alpha == 0 && decorationViewsHidden == false {
UIView.animate(withDuration: 0.3, animations: { [weak self] in
self?.scrubber.alpha = 1
})
}
}
}
open func itemControllerDidSingleTap(_ controller: ItemController) {
self.decorationViewsHidden.flip()
animateDecorationViews(visible: !self.decorationViewsHidden)
}
open func itemControllerDidLongPress(_ controller: ItemController, in item: ItemView) {
switch (controller, item) {
case (_ as ImageViewController, let item as UIImageView):
guard let image = item.image else { return }
let activityVC = UIActivityViewController(activityItems: [image], applicationActivities: nil)
self.present(activityVC, animated: true)
case (_ as VideoViewController, let item as VideoView):
guard let videoUrl = ((item.player?.currentItem?.asset) as? AVURLAsset)?.url else { return }
let activityVC = UIActivityViewController(activityItems: [videoUrl], applicationActivities: nil)
self.present(activityVC, animated: true)
default: return
}
}
public func itemController(_ controller: ItemController, didSwipeToDismissWithDistanceToEdge distance: CGFloat) {
if decorationViewsHidden == false {
let alpha = 1 - distance * swipeToDismissFadeOutAccelerationFactor
closeButton?.alpha = alpha
thumbnailsButton?.alpha = alpha
deleteButton?.alpha = alpha
headerView?.alpha = alpha
footerView?.alpha = alpha
if controller is VideoViewController {
scrubber.alpha = alpha
}
}
self.overlayView.blurringView.alpha = 1 - distance
self.overlayView.colorView.alpha = 1 - distance
}
public func itemControllerDidFinishSwipeToDismissSuccessfully() {
self.swipedToDismissCompletion?()
self.overlayView.removeFromSuperview()
self.dismiss(animated: false, completion: nil)
}
}
| mit | 9177717d9312223e7252e3ba303b1224 | 39.527817 | 262 | 0.651214 | 5.425898 | false | false | false | false |
Lebron1992/SlackTextViewController-Swift | SlackTextViewController-Swift/Examples/Messenger/MessageViewController.swift | 1 | 25602 | //
// MessageViewController.swift
// SlackTextViewController-Swift
//
// Created by Lebron on 21/08/2017.
// Copyright © 2017 hacknocraft. All rights reserved.
//
import UIKit
import LoremIpsum
import SlackTextViewController_Swift
let DEBUG_CUSTOM_TYPING_INDICATOR = false
class MessageViewController: SLKTextViewController {
var messages = [Message]()
var users = ["Allen", "Anna", "Alicia", "Arnold", "Armando", "Antonio", "Brad", "Catalaya", "Christoph", "Emerson", "Eric", "Everyone", "Steve"]
var channels = ["General", "Random", "iOS", "Bugs", "Sports", "Android", "UI", "SSB"]
var emojis = ["-1", "m", "man", "machine", "block-a", "block-b", "bowtie", "boar", "boat", "book", "bookmark", "neckbeard", "metal", "fu", "feelsgood"]
var commands = ["msg", "call", "text", "skype", "kick", "invite"]
var searchResult: [String]?
var pipWindow: UIWindow?
var editingMessage = Message(username: "", text: "")
override var tableView: UITableView? {
return super.tableView
}
// MARK: - Initialization
override func viewDidLoad() {
// Register a SLKTextView subclass, if you need any special appearance and/or behavior customisation.
registerClassForTextView(aClass: MessageTextView.self)
if DEBUG_CUSTOM_TYPING_INDICATOR == true {
// Register a UIView subclass, conforming to SLKTypingIndicatorProtocol, to use a custom typing indicator view.
registerClassForTypingIndicatorView(aClass: TypingIndicatorView.self)
}
super.viewDidLoad()
commonInit()
// Example's configuration
configureDataSource()
configureActionItems()
// SLKTVC's configuration
bounces = true
shakeToClearEnabled = true
isKeyboardPanningEnabled = true
shouldScrollToBottomAfterKeyboardShows = false
isInverted = true
leftButton.setImage(UIImage(named: "icn_upload"), for: UIControlState())
leftButton.tintColor = UIColor.gray
rightButton.setTitle(NSLocalizedString("Send", comment: ""), for: UIControlState())
textInputbar.autoHideRightButton = true
textInputbar.maxCharCount = 256
textInputbar.counterStyle = .split
textInputbar.counterPosition = .top
textInputbar.editorTitle.textColor = UIColor.darkGray
textInputbar.editorLeftButton.tintColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1)
textInputbar.editorRightButton.tintColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1)
if DEBUG_CUSTOM_TYPING_INDICATOR == false {
typingIndicatorView!.canResignByTouch = true
}
tableView?.separatorStyle = .none
tableView?.register(MessageTableViewCell.self, forCellReuseIdentifier: MessageTableViewCell.kMessengerCellIdentifier)
autoCompletionView?.register(MessageTableViewCell.self, forCellReuseIdentifier: MessageTableViewCell.kAutoCompletionCellIdentifier)
registerPrefixesForAutoCompletion(prefixes: ["@", "#", ":", "+:", "/"])
textView.placeholder = "Message"
textView.registerMarkdownFormattingSymbol("*", title: "Bold")
textView.registerMarkdownFormattingSymbol("~", title: "Strike")
textView.registerMarkdownFormattingSymbol("`", title: "Code")
textView.registerMarkdownFormattingSymbol("```", title: "Preformatted")
textView.registerMarkdownFormattingSymbol(">", title: "Quote")
}
func commonInit() {
if let tableView = tableView {
NotificationCenter.default.addObserver(tableView, selector: #selector(UITableView.reloadData), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
}
NotificationCenter.default.addObserver(self, selector: #selector(MessageViewController.textInputbarDidMove(_:)), name: NSNotification.Name(rawValue: SLKTextInputbarDidMoveNotification), object: nil)
}
override class func tableViewStyle(for decoder: NSCoder) -> UITableViewStyle {
return .plain
}
// MARK: - Lifeterm
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Overriden Methods
override func ignoreTextInputbarAdjustment() -> Bool {
return super.ignoreTextInputbarAdjustment()
}
override func forceTextInputbarAdjustment(for responder: UIResponder!) -> Bool {
if #available(iOS 8.0, *) {
guard responder is UIAlertController else {
// On iOS 9, returning YES helps keeping the input view visible when the keyboard if presented from another app when using multi-tasking on iPad.
return UIDevice.current.userInterfaceIdiom == .pad
}
return true
} else {
return UIDevice.current.userInterfaceIdiom == .pad
}
}
// Notifies the view controller that the keyboard changed status.
override func didChangeKeyboardStatus(_ status: SLKKeyboardStatus) {
switch status {
case .willShow:
print("Will Show")
case .didShow:
print("Did Show")
case .willHide:
print("Will Hide")
case .didHide:
print("Did Hide")
default:
break
}
}
// Notifies the view controller that the text will update.
override func textWillUpdate() {
super.textWillUpdate()
}
// Notifies the view controller that the text did update.
override func textDidUpdate(animated: Bool) {
super.textDidUpdate(animated: animated)
}
// Notifies the view controller when the left button's action has been triggered, manually.
override func didPressLeftButton(sender: Any!) {
super.didPressLeftButton(sender: sender)
dismissKeyboard(animated: true)
// performSegue(withIdentifier: "Push", sender: nil)
}
// Notifies the view controller when the right button's action has been triggered, manually or by using the keyboard return key.
override func didPressRightButton(sender: Any!) {
// This little trick validates any pending auto-correction or auto-spelling just after hitting the 'Send' button
textView.refreshFirstResponder()
let message = Message(username: LoremIpsum.name(), text: textView.text)
let indexPath = IndexPath(row: 0, section: 0)
let rowAnimation: UITableViewRowAnimation = isInverted ? .bottom : .top
let scrollPosition: UITableViewScrollPosition = isInverted ? .bottom : .top
tableView?.beginUpdates()
messages.insert(message, at: 0)
tableView?.insertRows(at: [indexPath], with: rowAnimation)
tableView?.endUpdates()
tableView?.scrollToRow(at: indexPath, at: scrollPosition, animated: true)
// Fixes the cell from blinking (because of the transform, when using translucent cells)
// See https://github.com/slackhq/SlackTextViewController/issues/94#issuecomment-69929927
tableView?.reloadRows(at: [indexPath], with: .automatic)
super.didPressRightButton(sender: sender)
}
override func didPressArrowKey(keyCommand: UIKeyCommand?) {
guard let keyCommand = keyCommand else { return }
if keyCommand.input == UIKeyInputUpArrow && textView.text.characters.count == 0 {
editLastMessage(nil)
} else {
super.didPressArrowKey(keyCommand: keyCommand)
}
}
override func keyForTextCaching() -> String? {
return Bundle.main.bundleIdentifier
}
// Notifies the view controller when the user has pasted a media (image, video, etc) inside of the text view.
override func didPasteMediaContent(userInfo: [AnyHashable: Any]) {
super.didPasteMediaContent(userInfo: userInfo)
let mediaType = (userInfo[SLKTextViewPastedItemMediaType] as? NSNumber)?.intValue
let contentType = userInfo[SLKTextViewPastedItemContentType]
let data = userInfo[SLKTextViewPastedItemData]
print("didPasteMediaContent : \(String(describing: contentType)) (type = \(String(describing: mediaType)) | data : \(String(describing: data)))")
}
// Notifies the view controller when a user did shake the device to undo the typed text
override func willRequestUndo() {
super.willRequestUndo()
}
// Notifies the view controller when tapped on the right "Accept" button for commiting the edited text
override func didCommitTextEditing(sender: Any) {
editingMessage.text = textView.text
tableView?.reloadData()
super.didCommitTextEditing(sender: sender)
}
// Notifies the view controller when tapped on the left "Cancel" button
override func didCancelTextEditing(sender: Any) {
super.didCancelTextEditing(sender: sender)
}
override func canPressRightButton() -> Bool {
return super.canPressRightButton()
}
override func canShowTypingIndicator() -> Bool {
if DEBUG_CUSTOM_TYPING_INDICATOR == true {
return true
} else {
return super.canShowTypingIndicator()
}
}
override func shouldProcessTextForAutoCompletion() -> Bool {
return true
}
override func didChangeAutoCompletion(prefix: String, word: String) {
var array: [String] = []
let wordPredicate = NSPredicate(format: "self BEGINSWITH[c] %@", word)
searchResult = nil
if prefix == "@" {
if word.characters.count > 0 {
array = users.filter { wordPredicate.evaluate(with: $0) }
} else {
array = users
}
} else if prefix == "#" {
if word.characters.count > 0 {
array = channels.filter { wordPredicate.evaluate(with: $0) }
} else {
array = channels
}
} else if (prefix == ":" || prefix == "+:") && word.characters.count > 0 {
array = emojis.filter { wordPredicate.evaluate(with: $0) }
} else if prefix == "/" && foundPrefixRange.location == 0 {
if word.characters.count > 0 {
array = commands.filter { wordPredicate.evaluate(with: $0) }
} else {
array = commands
}
}
var show = false
if array.count > 0 {
let sortedArray = array.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
searchResult = sortedArray
show = sortedArray.count > 0
}
showAutoCompletionView(show: show)
}
override func heightForAutoCompletionView() -> CGFloat {
guard let searchResult = searchResult else {
return 0
}
guard let autoCompletionView = self.autoCompletionView,
let cellHeight = autoCompletionView.delegate?.tableView?(autoCompletionView, heightForRowAt: IndexPath(row: 0, section: 0)) else {
return 0
}
return cellHeight * CGFloat(searchResult.count)
}
}
// MARK: - Example's Configuration
extension MessageViewController {
func configureDataSource() {
var array = [Message]()
for _ in 0..<100 {
let words = Int((arc4random() % 40)+1)
guard let name = LoremIpsum.name(),
let text = LoremIpsum.words(withNumber: words) else {
continue
}
let message = Message(username: name, text: text)
array.append(message)
}
let reversed = array.reversed()
messages.append(contentsOf: reversed)
}
func configureActionItems() {
let arrowItem = UIBarButtonItem(image: UIImage(named: "icn_arrow_down"), style: .plain, target: self, action: #selector(MessageViewController.hideOrShowTextInputbar(_:)))
let editItem = UIBarButtonItem(image: UIImage(named: "icn_editing"), style: .plain, target: self, action: #selector(MessageViewController.editRandomMessage(_:)))
let typeItem = UIBarButtonItem(image: UIImage(named: "icn_typing"), style: .plain, target: self, action: #selector(MessageViewController.simulateUserTyping(_:)))
let appendItem = UIBarButtonItem(image: UIImage(named: "icn_append"), style: .plain, target: self, action: #selector(MessageViewController.fillWithText(_:)))
let pipItem = UIBarButtonItem(image: UIImage(named: "icn_pic"), style: .plain, target: self, action: #selector(MessageViewController.togglePIPWindow(_:)))
navigationItem.rightBarButtonItems = [arrowItem, pipItem, editItem, appendItem, typeItem]
}
// MARK: - Action Methods
func hideOrShowTextInputbar(_ sender: AnyObject) {
guard let buttonItem = sender as? UIBarButtonItem else {
return
}
let hide = !isTextInputbarHidden
let image = hide ? UIImage(named: "icn_arrow_up") : UIImage(named: "icn_arrow_down")
setTextInputbarHidden(hide, animated: true)
buttonItem.image = image
}
func fillWithText(_ sender: AnyObject) {
if textView.text.characters.count == 0 {
var sentences = Int(arc4random() % 4)
if sentences <= 1 {
sentences = 1
}
textView.text = LoremIpsum.sentences(withNumber: sentences)
} else {
textView.slk_insertTextAtCaretRange(" " + LoremIpsum.word())
}
}
func simulateUserTyping(_ sender: AnyObject) {
if !canShowTypingIndicator() {
return
}
if DEBUG_CUSTOM_TYPING_INDICATOR == true {
guard let indicatorView = typingIndicatorProxyView as? TypingIndicatorView else {
return
}
let scale = UIScreen.main.scale
let imgSize = CGSize(width: kTypingIndicatorViewAvatarHeight * scale, height: kTypingIndicatorViewAvatarHeight * scale)
// This will cause the typing indicator to show after a delay ¯\_(ツ)_/¯
LoremIpsum.asyncPlaceholderImage(with: imgSize, completion: { (image) -> Void in
guard let cgImage = image?.cgImage else {
return
}
let thumbnail = UIImage(cgImage: cgImage, scale: scale, orientation: .up)
indicatorView.presentIndicator(name: LoremIpsum.name(), image: thumbnail)
})
} else {
typingIndicatorView?.insertUsername(LoremIpsum.name())
}
}
func didLongPressCell(_ gesture: UIGestureRecognizer) {
guard let view = gesture.view else {
return
}
if gesture.state != .began {
return
}
if #available(iOS 8, *) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.modalPresentationStyle = .popover
alertController.popoverPresentationController?.sourceView = view.superview
alertController.popoverPresentationController?.sourceRect = view.frame
alertController.addAction(UIAlertAction(title: "Edit Message", style: .default, handler: { [unowned self] (_) -> Void in
self.editCellMessage(gesture)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
navigationController?.present(alertController, animated: true, completion: nil)
} else {
editCellMessage(gesture)
}
}
func editCellMessage(_ gesture: UIGestureRecognizer) {
guard let messageCell = gesture.view as? MessageTableViewCell,
let indexPath = messageCell.indexPath else {
return
}
editingMessage = messages[indexPath.row]
editText(editingMessage.text)
tableView?.scrollToRow(at: indexPath, at: .bottom, animated: true)
}
func editRandomMessage(_ sender: AnyObject) {
var sentences = Int(arc4random() % 10)
if sentences <= 1 {
sentences = 1
}
editText(LoremIpsum.sentences(withNumber: sentences))
}
func editLastMessage(_ sender: AnyObject?) {
if textView.text.characters.count > 0 {
return
}
guard let tableView = tableView,
textView.text.characters.count == 0 else {
return
}
let lastSectionIndex = tableView.numberOfSections-1
let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex)-1
let lastMessage = messages[lastRowIndex]
editText(lastMessage.text)
tableView.scrollToRow(at: IndexPath(row: lastRowIndex, section: lastSectionIndex), at: .bottom, animated: true)
}
func togglePIPWindow(_ sender: AnyObject) {
if pipWindow == nil {
showPIPWindow(sender)
} else {
hidePIPWindow(sender)
}
}
func showPIPWindow(_ sender: AnyObject) {
var frame = CGRect(x: view.frame.width - 60.0, y: 0.0, width: 50.0, height: 50.0)
frame.origin.y = textInputbar.frame.minY - 60.0
pipWindow = UIWindow(frame: frame)
pipWindow?.backgroundColor = UIColor.black
pipWindow?.layer.cornerRadius = 10
pipWindow?.layer.masksToBounds = true
pipWindow?.isHidden = false
pipWindow?.alpha = 0.0
UIApplication.shared.keyWindow?.addSubview(pipWindow!)
UIView.animate(withDuration: 0.25, animations: { [unowned self] () -> Void in
self.pipWindow?.alpha = 1.0
})
}
func hidePIPWindow(_ sender: AnyObject) {
UIView.animate(withDuration: 0.3, animations: { [unowned self] () -> Void in
self.pipWindow?.alpha = 0.0
}, completion: { [unowned self] (_) -> Void in
self.pipWindow?.isHidden = true
self.pipWindow = nil
})
}
func textInputbarDidMove(_ note: Notification) {
guard let pipWindow = pipWindow else {
return
}
guard let userInfo = (note as NSNotification).userInfo else {
return
}
guard let value = userInfo["origin"] as? NSValue else {
return
}
var frame = pipWindow.frame
frame.origin.y = value.cgPointValue.y - 60.0
pipWindow.frame = frame
}
}
// MARK: - UITableViewDataSource & UIScrollViewDelegate
extension MessageViewController {
// MARK: - UITableViewDataSource Methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == tableView {
return messages.count
} else {
if let searchResult = searchResult {
return searchResult.count
}
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == tableView {
return messageCellForRowAtIndexPath(indexPath)
} else {
return autoCompletionCellForRowAtIndexPath(indexPath)
}
}
func messageCellForRowAtIndexPath(_ indexPath: IndexPath) -> MessageTableViewCell {
guard let cell = tableView?.dequeueReusableCell(withIdentifier: MessageTableViewCell.kMessengerCellIdentifier) as? MessageTableViewCell else {
return MessageTableViewCell()
}
if cell.gestureRecognizers?.count == nil {
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(MessageViewController.didLongPressCell(_:)))
cell.addGestureRecognizer(longPress)
}
let message = messages[indexPath.row]
cell.titleLabel.text = message.username
cell.bodyLabel.text = message.text
cell.indexPath = indexPath
cell.isUsedForMessage = true
// Cells must inherit the table view's transform
// This is very important, since the main table view may be inverted
if let tableView = tableView {
cell.transform = tableView.transform
}
return cell
}
func autoCompletionCellForRowAtIndexPath(_ indexPath: IndexPath) -> MessageTableViewCell {
guard let cell = autoCompletionView?.dequeueReusableCell(withIdentifier: MessageTableViewCell.kAutoCompletionCellIdentifier) as? MessageTableViewCell else {
return MessageTableViewCell()
}
cell.indexPath = indexPath
cell.selectionStyle = .default
guard let searchResult = searchResult else {
return cell
}
guard let prefix = foundPrefix else {
return cell
}
var text = searchResult[(indexPath as NSIndexPath).row]
if prefix == "#" {
text = "# " + text
} else if prefix == ":" || prefix == "+:" {
text = ":\(text):"
}
cell.titleLabel.text = text
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == tableView {
let message = messages[(indexPath as NSIndexPath).row]
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .left
let pointSize = MessageTableViewCell.defaultFontSize
let attributes = [
NSFontAttributeName: UIFont.systemFont(ofSize: pointSize),
NSParagraphStyleAttributeName: paragraphStyle
]
var width = tableView.frame.width-kMessageTableViewCellAvatarHeight
width -= 25.0
let titleBounds = (message.username as NSString).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
let bodyBounds = (message.text as NSString).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
if message.text.isEmpty {
return 0
}
var height = titleBounds.height
height += bodyBounds.height
height += 40
if height < kMessageTableViewCellMinimumHeight {
height = kMessageTableViewCellMinimumHeight
}
return height
} else {
return kMessageTableViewCellMinimumHeight
}
}
// MARK: - UITableViewDelegate Methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == autoCompletionView {
guard let searchResult = searchResult else {
return
}
var item = searchResult[(indexPath as NSIndexPath).row]
if foundPrefix == "@" && foundPrefixRange.location == 0 {
item += ":"
} else if foundPrefix == ":" || foundPrefix == "+:" {
item += ":"
}
item += " "
acceptAutoCompletion(string: item, keepPrefix: true)
}
}
}
// MARK: - UIScrollViewDelegate Methods
extension MessageViewController {
// Since SLKTextViewController uses UIScrollViewDelegate to update a few things, it is important that if you override this method, to call super.
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
super.scrollViewDidScroll(scrollView)
}
}
// MARK: - UITextViewDelegate Methods
extension MessageViewController {
override func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return true
}
override func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
// Since SLKTextViewController uses UIScrollViewDelegate to update a few things, it is important that if you override this method, to call super.
return true
}
override func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return super.textView(textView, shouldChangeTextIn: range, replacementText: text)
}
override func textView(_ textView: SLKTextView, shouldOfferFormattingFor symbol: String) -> Bool {
if symbol == ">" {
let selection = textView.selectedRange
// The Quote formatting only applies new paragraphs
if selection.location == 0 && selection.length > 0 {
return true
}
// or older paragraphs too
let prevString = (textView.text as NSString).substring(with: NSRange(location: selection.location-1, length: 1))
if CharacterSet.newlines.contains(UnicodeScalar((prevString as NSString).character(at: 0))!) {
return true
}
return false
}
return super.textView(textView, shouldOfferFormattingFor: symbol)
}
override func textView(_ textView: SLKTextView, shouldInsertSuffixForFormattingWith symbol: String, prefixRange: NSRange) -> Bool {
if symbol == ">" {
return false
}
return super.textView(textView, shouldInsertSuffixForFormattingWith: symbol, prefixRange: prefixRange)
}
}
| mit | 85d0782cb42109f57ca3cc652eb1f16b | 33.220588 | 214 | 0.634059 | 5.053702 | false | false | false | false |
Tomikes/eidolon | Kiosk/Auction Listings/ListingsCountdownManager.swift | 6 | 2280 | import UIKit
import ReactiveCocoa
class ListingsCountdownManager: NSObject {
@IBOutlet weak var countdownLabel: UILabel!
@IBOutlet weak var countdownContainerView: UIView!
let formatter = NSNumberFormatter()
dynamic var sale: Sale?
let time = SystemTime()
override func awakeFromNib() {
super.awakeFromNib()
formatter.minimumIntegerDigits = 2
time.syncSignal().dispatchAsyncMainScheduler().take(1).subscribeNext { [weak self] (_) in
self?.startTimer()
self?.setLabelsHidden(false)
}
}
func setFonts() {
(countdownContainerView.subviews).forEach{ (view) -> () in
if let label = view as? UILabel {
label.font = UIFont.serifFontWithSize(15)
}
}
countdownLabel.font = UIFont.sansSerifFontWithSize(20)
}
func setLabelsHidden(hidden: Bool) {
countdownContainerView.hidden = hidden
}
func setLabelsHiddenIfSynced(hidden: Bool) {
if time.inSync() {
setLabelsHidden(hidden)
}
}
func hideDenomenatorLabels() {
for subview in countdownContainerView.subviews {
subview.hidden = subview != countdownLabel
}
}
func startTimer() {
let timer = NSTimer(timeInterval: 0.49, target: self, selector: "tick:", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
self.tick(timer)
}
func tick(timer: NSTimer) {
if let sale = sale {
if time.inSync() == false { return }
if sale.id == "" { return }
if sale.isActive(time) {
let now = time.date()
let components = NSCalendar.currentCalendar().components([.Hour, .Minute, .Second], fromDate: now, toDate: sale.endDate, options: [])
self.countdownLabel.text = "\(formatter.stringFromNumber(components.hour)!) : \(formatter.stringFromNumber(components.minute)!) : \(formatter.stringFromNumber(components.second)!)"
} else {
self.countdownLabel.text = "CLOSED"
hideDenomenatorLabels()
timer.invalidate()
}
}
}
}
| mit | 9ed9a4090a499a0c371a4d6175b16f60 | 29.810811 | 196 | 0.593421 | 4.861407 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.