repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Pluto-Y/SwiftyEcharts | SwiftyEcharts/Models/Axis/RadiusAxis.swift | 1 | 9127 | //
// RadiusAxis.swift
// SwiftyEcharts
//
// Created by Pluto Y on 05/02/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
/// 极坐标系的径向轴。
public final class RadiusAxis: Zable {
/// 径向轴所在的极坐标系的索引,默认使用第一个极坐标系。
public var polarIndex: UInt8?
/// 坐标轴类型。
public var type: AxisType?
/// 坐标轴名称。
public var name: String?
/// 坐标轴名称显示位置。
public var nameLocation: Position?
/// 坐标轴名称的文字样式。
public var nameTextStyle: TextStyle?
/// 坐标轴名称与轴线之间的距离。
public var nameGap: Float?
/// 坐标轴名字旋转,角度值。
public var nameRotate: Float?
/// 是否是反向坐标轴。ECharts 3 中新加。
public var inverse: Bool?
/// 坐标轴两边留白策略,类目轴和非类目轴的设置和表现不一样。
///
/// 类目轴中 boundaryGap 可以配置为 true 和 false。默认为 true,这时候刻度只是作为分隔线,标签和数据点都会在两个刻度之间的带(band)中间。
///
/// 非类目轴,包括时间,数值,对数轴,boundaryGap是一个两个值的数组,分别表示数据最小值和最大值的延伸范围,可以直接设置数值或者相对的百分比,在设置 min 和 max 后无效。 示例:
///
/// boundaryGap: ['20%', '20%']
public var boundaryGap: BoundaryGap?
/// 坐标轴刻度最小值。
///
/// 可以设置成特殊值 'dataMin',此时取数据在该轴上的最小值作为最小刻度。
///
/// 不设置时会自动计算最小值保证坐标轴刻度的均匀分布。
///
/// 在类目轴中,也可以设置为类目的序数(如类目轴 data: ['类A', '类B', '类C'] 中,序数 2 表示 '类C'。也可以设置为负数,如 -3)。
public var min: Float?
/// 坐标轴刻度最大值。
///
/// 可以设置成特殊值 'dataMax',此时取数据在该轴上的最大值作为最大刻度。
///
/// 不设置时会自动计算最大值保证坐标轴刻度的均匀分布。
///
/// 在类目轴中,也可以设置为类目的序数(如类目轴 data: ['类A', '类B', '类C'] 中,序数 2 表示 '类C'。也可以设置为负数,如 -3)。
public var max: Float?
/// 只在数值轴中(type: 'value')有效。
///
/// 是否是脱离 0 值比例。设置成 true 后坐标刻度不会强制包含零刻度。在双数值轴的散点图中比较有用。
///
/// 在设置 min 和 max 之后该配置项无效。
public var scale: Bool?
/// 坐标轴的分割段数,需要注意的是这个分割段数只是个预估值,最后实际显示的段数会在这个基础上根据分割后坐标轴刻度显示的易读程度作调整。
///
/// 在类目轴中无效。
public var splitNumber: UInt8?
/// 自动计算的坐标轴最小间隔大小。
///
/// 例如可以设置成1保证坐标轴分割刻度显示成整数。
///
/// {
/// minInterval: 1
/// }
///
/// 只在数值轴中(type: 'value')有效。
public var minInterval: Float?
/// 强制设置坐标轴分割间隔。
///
/// 因为 splitNumber 是预估的值,实际根据策略计算出来的刻度可能无法达到想要的效果,这时候可以使用 interval 配合 min、max 强制设定刻度划分,一般不建议使用。
///
/// 无法在类目轴中使用。在时间轴(type: 'time')中需要传时间戳,在对数轴(type: 'log')中需要传指数值。
public var interval: Float?
/// 对数轴的底数,只在对数轴中(type: 'log')有效。
public var logBase: Float?
/// 坐标轴是否是静态无法交互。
public var silent: Bool?
/// 坐标轴的标签是否响应和触发鼠标事件,默认不响应。
/// 事件参数如下:
/// {
/// // 组件类型,xAxis, yAxis, radiusAxis, angleAxis
/// // 对应组件类型都会有一个属性表示组件的 index,例如 xAxis 就是 xAxisIndex
/// componentType: string,
/// // 未格式化过的刻度值, 点击刻度标签有效
/// value: '',
/// // 坐标轴名称, 点击坐标轴名称有效
/// name: ''
/// }
public var triggerEvent: Bool?
/// 坐标轴轴线相关设置。
public var axisLine: AxisLine?
/// 坐标轴刻度相关设置。
public var axisTick: AxisTick?
/// 坐标轴刻度标签的相关设置。
public var axisLabel: AxisLabel?
/// 坐标轴在 grid 区域中的分隔线。
public var splitLine: SplitLine?
/// 坐标轴在 grid 区域中的分隔区域,默认不显示。
public var splitArea: SplitArea?
public var data: [Jsonable]?
public var axisPointer: AxisPointerForAxis?
/// MARK: - Zable
public var zlevel: Float?
public var z: Float?
}
extension RadiusAxis: Enumable {
public enum Enums {
case polarIndex(UInt8), type(AxisType), name(String), nameLocation(Position), nameTextStyle(TextStyle), nameGap(Float), nameRotate(Float), inverse(Bool), boundaryGap(BoundaryGap), min(Float), max(Float), scale(Bool), splitNumber(UInt8), minInterval(Float), interval(Float), logBase(Float), silent(Bool), triggerEvent(Bool), axisLine(AxisLine), axisTick(AxisTick), axisLabel(AxisLabel), splitLine(SplitLine), splitArea(SplitArea), data([Jsonable]), axisPointer(AxisPointerForAxis), zlevel(Float), z(Float)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .polarIndex(polarIndex):
self.polarIndex = polarIndex
case let .type(type):
self.type = type
case let .name(name):
self.name = name
case let .nameLocation(nameLocation):
self.nameLocation = nameLocation
case let .nameTextStyle(nameTextStyle):
self.nameTextStyle = nameTextStyle
case let .nameGap(nameGap):
self.nameGap = nameGap
case let .nameRotate(nameRotate):
self.nameRotate = nameRotate
case let .inverse(inverse):
self.inverse = inverse
case let .boundaryGap(boundaryGap):
self.boundaryGap = boundaryGap
case let .min(min):
self.min = min
case let .max(max):
self.max = max
case let .scale(scale):
self.scale = scale
case let .splitNumber(splitNumber):
self.splitNumber = splitNumber
case let .minInterval(minInterval):
self.minInterval = minInterval
case let .interval(interval):
self.interval = interval
case let .logBase(logBase):
self.logBase = logBase
case let .silent(silent):
self.silent = silent
case let .triggerEvent(triggerEvent):
self.triggerEvent = triggerEvent
case let .axisLine(axisLine):
self.axisLine = axisLine
case let .axisTick(axisTick):
self.axisTick = axisTick
case let .axisLabel(axisLabel):
self.axisLabel = axisLabel
case let .splitLine(splitLine):
self.splitLine = splitLine
case let .splitArea(splitArea):
self.splitArea = splitArea
case let .data(data):
self.data = data
case let .axisPointer(axisPointer):
self.axisPointer = axisPointer
case let .zlevel(zlevel):
self.zlevel = zlevel
case let .z(z):
self.z = z
}
}
}
}
extension RadiusAxis: Mappable {
public func mapping(_ map: Mapper) {
map["polarIndex"] = polarIndex
map["type"] = type
map["name"] = name
map["nameLocation"] = nameLocation
map["nameTextStyle"] = nameTextStyle
map["nameGap"] = nameGap
map["nameRotate"] = nameRotate
map["inverse"] = inverse
map["boundaryGap"] = boundaryGap
map["min"] = min
map["max"] = max
map["scale"] = scale
map["splitNumber"] = splitNumber
map["minInterval"] = minInterval
map["interval"] = interval
map["logBase"] = logBase
map["silent"] = silent
map["triggerEvent"] = triggerEvent
map["axisLine"] = axisLine
map["axisTick"] = axisTick
map["axisLabel"] = axisLabel
map["splitLine"] = splitLine
map["splitArea"] = splitArea
map["data"] = data
map["axisPointer"] = axisPointer
map["zlevel"] = zlevel
map["z"] = z
}
}
| mit | b1c28c3518b4942753fe1475be872150 | 33.037736 | 512 | 0.571369 | 3.760292 | false | false | false | false |
krzysztofzablocki/Sourcery | SourceryRuntime/Sources/Log.swift | 1 | 1939 | import Darwin
import Foundation
/// :nodoc:
public enum Log {
public enum Level: Int {
case errors
case warnings
case info
case verbose
}
public static var level: Level = .warnings
public static var logBenchmarks: Bool = false
public static var logAST: Bool = false
public static var stackMessages: Bool = false
public private(set) static var messagesStack = [String]()
public static func error(_ message: Any) {
log(level: .errors, "error: \(message)")
// to return error when running swift templates which is done in a different process
if ProcessInfo().processName != "Sourcery" {
fputs("\(message)", stderr)
}
}
public static func warning(_ message: Any) {
log(level: .warnings, "warning: \(message)")
}
public static func astWarning(_ message: Any) {
guard logAST else { return }
log(level: .warnings, "ast warning: \(message)")
}
public static func astError(_ message: Any) {
guard logAST else { return }
log(level: .errors, "ast error: \(message)")
}
public static func verbose(_ message: Any) {
log(level: .verbose, message)
}
public static func info(_ message: Any) {
log(level: .info, message)
}
public static func benchmark(_ message: Any) {
guard logBenchmarks else { return }
if stackMessages {
messagesStack.append("\(message)")
} else {
print(message)
}
}
private static func log(level logLevel: Level, _ message: Any) {
guard logLevel.rawValue <= Log.level.rawValue else { return }
if stackMessages {
messagesStack.append("\(message)")
} else {
print(message)
}
}
public static func output(_ message: String) {
print(message)
}
}
extension String: Error {}
| mit | ad28f067a3959ca1c666a569ad8226b2 | 25.202703 | 92 | 0.588448 | 4.49884 | false | false | false | false |
El-Fitz/ImageSlideshow | Pod/Classes/InputSources/AFURLSource.swift | 1 | 967 | //
// AFURLSource.swift
// ImageSlideshow
//
// Created by Petr Zvoníček on 30.07.15.
//
import AFNetworking
public class AFURLSource: NSObject, InputSource {
var url: URL
var placeholder: UIImage?
public init(url: URL) {
self.url = url
super.init()
}
public init(url: URL, placeholder: UIImage) {
self.url = url
self.placeholder = placeholder
super.init()
}
public init?(urlString: String) {
if let validUrl = URL(string: urlString) {
self.url = validUrl
super.init()
} else {
return nil
}
}
public func load(to imageView: UIImageView, with callback: @escaping (UIImage) -> ()) {
imageView.setImageWith(URLRequest(url: url), placeholderImage: self.placeholder, success: { (_, _, image: UIImage) in
imageView.image = image
callback(image)
}, failure: nil)
}
}
| mit | 86409f7d9b9579cf22e76067131c113d | 23.125 | 125 | 0.568912 | 4.159483 | false | false | false | false |
lanjing99/RxSwiftDemo | 13-intermediate-rxcocoa/challenges/Wundercast/Controllers/ApiController.swift | 1 | 7878 | /*
* Copyright (c) 2014-2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import RxSwift
import RxCocoa
import SwiftyJSON
import CoreLocation
import MapKit
class ApiController {
/// The shared instance
static var shared = ApiController()
/// The api key to communicate with openweathermap.org
/// Create you own on https://home.openweathermap.org/users/sign_up
private let apiKey = "b7df09399978c6080aa16b2af36a5f32"//"[YOUR KEY]"
/// API base URL
let baseURL = URL(string: "http://api.openweathermap.org/data/2.5")!
init() {
Logging.URLRequests = { request in
return true
}
}
//MARK: - Api Calls
func currentWeather(city: String) -> Observable<Weather> {
return buildRequest(pathComponent: "weather", params: [("q", city)]).map() { json in
return Weather(
cityName: json["name"].string ?? "Unknown",
temperature: json["main"]["temp"].int ?? -1000,
humidity: json["main"]["humidity"].int ?? 0,
icon: iconNameToChar(icon: json["weather"][0]["icon"].string ?? "e"),
lat: json["coord"]["lat"].double ?? 0,
lon: json["coord"]["lon"].double ?? 0
)
}
}
func currentWeather(lat: Double, lon: Double) -> Observable<Weather> {
return buildRequest(pathComponent: "weather", params: [("lat", "\(lat)"), ("lon", "\(lon)")]).map() { json in
return Weather(
cityName: json["name"].string ?? "Unknown",
temperature: json["main"]["temp"].int ?? -1000,
humidity: json["main"]["humidity"].int ?? 0,
icon: iconNameToChar(icon: json["weather"][0]["icon"].string ?? "e"),
lat: json["coord"]["lat"].double ?? 0,
lon: json["coord"]["lon"].double ?? 0
)
}
}
func currentWeatherAround(lat: Double, lon: Double) -> Observable<[Weather]> {
var weathers = [Observable<Weather>]()
for i in -1...1 {
for j in -1...1 {
weathers.append(currentWeather(lat: lat + Double(i), lon: lon + Double(j)))
}
}
return Observable.from(weathers)
.merge()
.toArray()
}
//MARK: - Private Methods
/**
* Private method to build a request with RxCocoa
*/
private func buildRequest(method: String = "GET", pathComponent: String, params: [(String, String)]) -> Observable<JSON> {
let url = baseURL.appendingPathComponent(pathComponent)
var request = URLRequest(url: url)
let keyQueryItem = URLQueryItem(name: "appid", value: apiKey)
let unitsQueryItem = URLQueryItem(name: "units", value: "metric")
let urlComponents = NSURLComponents(url: url, resolvingAgainstBaseURL: true)!
if method == "GET" {
var queryItems = params.map { URLQueryItem(name: $0.0, value: $0.1) }
queryItems.append(keyQueryItem)
queryItems.append(unitsQueryItem)
urlComponents.queryItems = queryItems
} else {
urlComponents.queryItems = [keyQueryItem, unitsQueryItem]
let jsonData = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request.httpBody = jsonData
}
request.url = urlComponents.url!
request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
return session.rx.data(request: request).map { JSON(data: $0) }
}
/**
* Weather information and map overlay
*/
struct Weather {
let cityName: String
let temperature: Int
let humidity: Int
let icon: String
let lat: Double
let lon: Double
static let empty = Weather(
cityName: "Unknown",
temperature: -1000,
humidity: 0,
icon: iconNameToChar(icon: "e"),
lat: 0,
lon: 0
)
static let dummy = Weather(
cityName: "RxCity",
temperature: 20,
humidity: 90,
icon: iconNameToChar(icon: "01d"),
lat: 0,
lon: 0
)
var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: lat, longitude: lon)
}
func overlay() -> Overlay {
let coordinates: [CLLocationCoordinate2D] = [
CLLocationCoordinate2D(latitude: lat - 0.25, longitude: lon - 0.25),
CLLocationCoordinate2D(latitude: lat + 0.25, longitude: lon + 0.25)
]
let points = coordinates.map { MKMapPointForCoordinate($0) }
let rects = points.map { MKMapRect(origin: $0, size: MKMapSize(width: 0, height: 0)) }
let fittingRect = rects.reduce(MKMapRectNull, MKMapRectUnion)
return Overlay(icon: icon, coordinate: coordinate, boundingMapRect: fittingRect)
}
public class Overlay: NSObject, MKOverlay {
var coordinate: CLLocationCoordinate2D
var boundingMapRect: MKMapRect
let icon: String
init(icon: String, coordinate: CLLocationCoordinate2D, boundingMapRect: MKMapRect) {
self.coordinate = coordinate
self.boundingMapRect = boundingMapRect
self.icon = icon
}
}
public class OverlayView: MKOverlayRenderer {
var overlayIcon: String
init(overlay:MKOverlay, overlayIcon:String) {
self.overlayIcon = overlayIcon
super.init(overlay: overlay)
}
public override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
let imageReference = imageFromText(text: overlayIcon as NSString, font: UIFont(name: "Flaticon", size: 32.0)!).cgImage
let theMapRect = overlay.boundingMapRect
let theRect = rect(for: theMapRect)
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0.0, y: -theRect.size.height)
context.draw(imageReference!, in: theRect)
}
}
}
}
/**
* Maps an icon information from the API to a local char
* Source: http://openweathermap.org/weather-conditions
*/
public func iconNameToChar(icon: String) -> String {
switch icon {
case "01d":
return "\u{f11b}"
case "01n":
return "\u{f110}"
case "02d":
return "\u{f112}"
case "02n":
return "\u{f104}"
case "03d", "03n":
return "\u{f111}"
case "04d", "04n":
return "\u{f111}"
case "09d", "09n":
return "\u{f116}"
case "10d", "10n":
return "\u{f113}"
case "11d", "11n":
return "\u{f10d}"
case "13d", "13n":
return "\u{f119}"
case "50d", "50n":
return "\u{f10e}"
default:
return "E"
}
}
fileprivate func imageFromText(text: NSString, font: UIFont) -> UIImage {
let size = text.size(attributes: [NSFontAttributeName: font])
if (UIGraphicsBeginImageContextWithOptions != nil) {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
} else {
UIGraphicsBeginImageContext(size)
}
text.draw(at: CGPoint(x: 0, y:0), withAttributes: [NSFontAttributeName: font])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image ?? UIImage()
}
| mit | 527c8844ef6bcbaec679932e3a8767dc | 30.386454 | 126 | 0.656131 | 4.069215 | false | false | false | false |
Alecrim/AlecrimCoreData | Sources/Core/Persistent Container/PersistentContainerType.swift | 1 | 3406 | //
// PersistentContainerType.swift
// AlecrimCoreData
//
// Created by Vanderlei Martinelli on 20/05/18.
// Copyright © 2018 Alecrim. All rights reserved.
//
import Foundation
import CoreData
// MARK: -
public protocol PersistentContainerType: AnyObject {
associatedtype ManagedObjectContextType: ManagedObjectContext
var viewContext: ManagedObjectContextType { get }
var backgroundContext: ManagedObjectContextType { get }
}
extension PersistentContainer: PersistentContainerType {}
extension CustomPersistentContainer: PersistentContainerType {}
// MARK: - helper static methods
extension PersistentContainerType {
public static func managedObjectModel(withName name: String? = nil, in bundle: Bundle? = nil) throws -> NSManagedObjectModel {
let bundle = bundle ?? Bundle(for: Self.self)
let name = name ?? bundle.bundleURL.deletingPathExtension().lastPathComponent
let managedObjectModelURL = try self.managedObjectModelURL(withName: name, in: bundle)
guard let managedObjectModel = NSManagedObjectModel(contentsOf: managedObjectModelURL) else {
throw PersistentContainerError.managedObjectModelNotFound
}
return managedObjectModel
}
private static func managedObjectModelURL(withName name: String, in bundle: Bundle) throws -> URL {
let resourceURL = bundle.url(forResource: name, withExtension: "momd") ?? bundle.url(forResource: name, withExtension: "mom")
guard let managedObjectModelURL = resourceURL else {
throw PersistentContainerError.invalidManagedObjectModelURL
}
return managedObjectModelURL
}
}
extension PersistentContainerType {
public static func persistentStoreURL(withName name: String? = nil, inPath path: String? = nil) throws -> URL {
guard let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).last else {
throw PersistentContainerError.applicationSupportDirectoryNotFound
}
let name = name ?? Bundle.main.bundleURL.deletingPathExtension().lastPathComponent
let path = path ?? name
let persistentStoreURL = applicationSupportURL
.appendingPathComponent(path, isDirectory: true)
.appendingPathComponent("CoreData", isDirectory: true)
.appendingPathComponent(name, isDirectory: false)
.appendingPathExtension("sqlite")
return persistentStoreURL
}
public static func persistentStoreURL(withName name: String, inPath path: String? = nil, forSecurityApplicationGroupIdentifier applicationGroupIdentifier: String) throws -> URL {
guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: applicationGroupIdentifier) else {
throw PersistentContainerError.invalidGroupContainerURL
}
let path = path ?? name
let persistentStoreURL = containerURL
.appendingPathComponent("Library", isDirectory: true)
.appendingPathComponent("Application Support", isDirectory: true)
.appendingPathComponent(path, isDirectory: true)
.appendingPathComponent("CoreData", isDirectory: true)
.appendingPathComponent(name, isDirectory: false)
.appendingPathExtension("sqlite")
return persistentStoreURL
}
}
| mit | 6c64fdfd66ed82ba9f8b2fa880c3161d | 36.417582 | 182 | 0.724816 | 6.026549 | false | false | false | false |
ngageoint/mage-ios | Mage/LocationUtilities.swift | 1 | 11839 | //
// CoordinateDisplay.swift
// MAGE
//
// Created by Daniel Barela on 7/10/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import CoreLocation
struct DMSCoordinate {
var degrees: Int?
var minutes: Int?
var seconds: Int?
var direction: String?
}
public class LocationUtilities: NSObject {
override public init() { }
// Need to parse the following formats:
// 1. 112233N 0112244W
// 2. N 11 ° 22'33 "- W 11 ° 22'33
// 3. 11 ° 22'33 "N - 11 ° 22'33" W
// 4. 11° 22'33 N 011° 22'33 W
static func parseDMS(coordinate: String, addDirection: Bool = false, latitude: Bool = false) -> DMSCoordinate {
var dmsCoordinate: DMSCoordinate = DMSCoordinate()
var coordinateToParse = coordinate.trimmingCharacters(in: .whitespacesAndNewlines)
if addDirection {
// check if the first character is negative
if coordinateToParse.firstIndex(of: "-") == coordinateToParse.startIndex {
dmsCoordinate.direction = latitude ? "S" : "W"
} else {
dmsCoordinate.direction = latitude ? "N" : "E"
}
}
var charactersToKeep = CharacterSet()
charactersToKeep.formUnion(.decimalDigits)
charactersToKeep.insert(charactersIn: ".NSEWnsew")
coordinateToParse = coordinate.components(separatedBy: charactersToKeep.inverted).joined()
if let direction = coordinateToParse.last {
// the last character might be a direction not a number
if let _ = direction.wholeNumberValue {
} else {
dmsCoordinate.direction = "\(direction)".uppercased()
coordinateToParse = "\(coordinateToParse.dropLast(1))"
}
}
if let direction = coordinateToParse.first {
// the first character might be a direction not a number
if let _ = direction.wholeNumberValue {
} else {
dmsCoordinate.direction = "\(direction)".uppercased()
coordinateToParse = "\(coordinateToParse.dropFirst(1))"
}
}
// remove all characers except numbers and decimal points
charactersToKeep = CharacterSet()
charactersToKeep.formUnion(.decimalDigits)
charactersToKeep.insert(charactersIn: ".")
coordinateToParse = coordinate.components(separatedBy: charactersToKeep.inverted).joined()
// split the numbers before the decimal seconds
if coordinateToParse.isEmpty {
return dmsCoordinate
}
let split = coordinateToParse.split(separator: ".")
coordinateToParse = "\(split[0])"
let decimalSeconds = split.count == 2 ? Int(split[1]) : nil
dmsCoordinate.seconds = Int(coordinateToParse.suffix(2))
coordinateToParse = "\(coordinateToParse.dropLast(2))"
dmsCoordinate.minutes = Int(coordinateToParse.suffix(2))
dmsCoordinate.degrees = Int(coordinateToParse.dropLast(2))
if dmsCoordinate.degrees == nil {
if dmsCoordinate.minutes == nil {
dmsCoordinate.degrees = dmsCoordinate.seconds
dmsCoordinate.seconds = nil
} else {
dmsCoordinate.degrees = dmsCoordinate.minutes
dmsCoordinate.minutes = dmsCoordinate.seconds
dmsCoordinate.seconds = nil
}
}
if dmsCoordinate.minutes == nil && dmsCoordinate.seconds == nil && decimalSeconds != nil {
// this would be the case if a decimal degrees was passed in ie 11.123
let decimal = Double(".\(decimalSeconds ?? 0)") ?? 0.0
dmsCoordinate.minutes = Int(abs((decimal.truncatingRemainder(dividingBy: 1) * 60.0)))
let seconds = abs(((decimal.truncatingRemainder(dividingBy: 1) * 60.0).truncatingRemainder(dividingBy: 1) * 60.0))
dmsCoordinate.seconds = Int(seconds.rounded())
if dmsCoordinate.seconds == 60 {
dmsCoordinate.minutes = (dmsCoordinate.minutes ?? 0) + 1
dmsCoordinate.seconds = 0
}
if dmsCoordinate.minutes == 60 {
dmsCoordinate.degrees = (dmsCoordinate.degrees ?? 0) + 1
dmsCoordinate.minutes = 0
}
} else if let decimalSeconds = decimalSeconds {
// add the decimal seconds to seconds and round
dmsCoordinate.seconds = Int(Double("\((dmsCoordinate.seconds ?? 0)).\(decimalSeconds)")?.rounded() ?? 0)
}
return dmsCoordinate
}
@objc public static func validateLatitudeFromDMS(latitude: String?) -> Bool {
return validateCoordinateFromDMS(coordinate: latitude, latitude: true)
}
@objc public static func validateLongitudeFromDMS(longitude: String?) -> Bool {
return validateCoordinateFromDMS(coordinate: longitude, latitude: false)
}
@objc public static func validateCoordinateFromDMS(coordinate: String?, latitude: Bool) -> Bool {
guard let coordinate = coordinate else {
return false
}
var validCharacters = CharacterSet()
validCharacters.formUnion(.decimalDigits)
validCharacters.insert(charactersIn: ".NSEWnsew °\'\"")
if coordinate.rangeOfCharacter(from: validCharacters.inverted) != nil {
return false
}
var charactersToKeep = CharacterSet()
charactersToKeep.formUnion(.decimalDigits)
charactersToKeep.insert(charactersIn: ".NSEWnsew")
var coordinateToParse = coordinate.components(separatedBy: charactersToKeep.inverted).joined()
// There must be a direction as the last character
if let direction = coordinateToParse.last {
// the last character must be either N or S not a number
if let _ = direction.wholeNumberValue {
return false
} else {
if latitude && direction.uppercased() != "N" && direction.uppercased() != "S" {
return false
}
if !latitude && direction.uppercased() != "E" && direction.uppercased() != "W" {
return false
}
coordinateToParse = "\(coordinateToParse.dropLast(1))"
}
} else {
return false
}
// split the numbers before the decimal seconds
let split = coordinateToParse.split(separator: ".")
if split.isEmpty {
return false
}
coordinateToParse = "\(split[0])"
// there must be either 5 or 6 digits for latitude (1 or 2 degrees, 2 minutes, 2 seconds)
// or 5, 6, 7 digits for longitude
if latitude && (coordinateToParse.count < 5 || coordinateToParse.count > 6) {
return false
}
if !latitude && (coordinateToParse.count < 5 || coordinateToParse.count > 7) {
return false
}
var decimalSeconds = 0
if split.count == 2 {
if let decimalSecondsInt = Int(split[1]) {
decimalSeconds = decimalSecondsInt
} else {
return false
}
}
let seconds = Int(coordinateToParse.suffix(2))
coordinateToParse = "\(coordinateToParse.dropLast(2))"
let minutes = Int(coordinateToParse.suffix(2))
let degrees = Int(coordinateToParse.dropLast(2))
if let degrees = degrees {
if latitude && (degrees < 0 || degrees > 90) {
return false
}
if !latitude && (degrees < 0 || degrees > 180) {
return false
}
} else {
return false
}
if let minutes = minutes, let degrees = degrees {
if (minutes < 0 || minutes > 59) || (latitude && degrees == 90 && minutes != 0) || (!latitude && degrees == 180 && minutes != 0) {
return false
}
} else {
return false
}
if let seconds = seconds, let degrees = degrees {
if (seconds < 0 || seconds > 59) || (latitude && degrees == 90 && (seconds != 0 || decimalSeconds != 0)) || (!latitude && degrees == 180 && (seconds != 0 || decimalSeconds != 0)) {
return false
}
} else {
return false
}
return true
}
// attempts to parse what was passed in to DDD° MM' SS.sss" (NS) or returns "" if unparsable
@objc public static func parseToDMSString(_ string: String?, addDirection: Bool = false, latitude: Bool = false) -> String? {
guard let string = string else {
return nil
}
if string.isEmpty {
return ""
}
let parsed = parseDMS(coordinate: string, addDirection: addDirection, latitude: latitude)
let direction = parsed.direction ?? ""
var seconds = ""
if let parsedSeconds = parsed.seconds {
seconds = String(format: "%02d", parsedSeconds)
}
var minutes = ""
if let parsedMinutes = parsed.minutes {
minutes = String(format: "%02d", parsedMinutes)
}
var degrees = ""
if let parsedDegrees = parsed.degrees {
if string.starts(with: "0") && parsedDegrees != 0 {
degrees = "0\(parsedDegrees)"
} else {
degrees = "\(parsedDegrees)"
}
}
if !degrees.isEmpty {
degrees = "\(degrees)° "
}
if !minutes.isEmpty {
minutes = "\(minutes)\' "
}
if !seconds.isEmpty {
seconds = "\(seconds)\" "
}
return "\(degrees)\(minutes)\(seconds)\(direction)"
}
// TODO: update this when non @objc to take an optional and return nil
@objc public static func latitudeDMSString(coordinate: CLLocationDegrees) -> String {
let nf = NumberFormatter()
nf.maximumFractionDigits = 0
nf.minimumIntegerDigits = 2
var latDegrees: Int = Int(coordinate)
var latMinutes = Int(abs((coordinate.truncatingRemainder(dividingBy: 1) * 60.0)))
var latSeconds = abs(((coordinate.truncatingRemainder(dividingBy: 1) * 60.0).truncatingRemainder(dividingBy: 1) * 60.0)).rounded()
if latSeconds == 60 {
latSeconds = 0
latMinutes += 1
}
if latMinutes == 60 {
latDegrees += 1
latMinutes = 0
}
return "\(abs(latDegrees))° \(nf.string(for: latMinutes) ?? "")\' \(nf.string(for: latSeconds) ?? "")\" \(latDegrees >= 0 ? "N" : "S")"
}
@objc public static func longitudeDMSString(coordinate: CLLocationDegrees) -> String {
let nf = NumberFormatter()
nf.maximumFractionDigits = 0
nf.minimumIntegerDigits = 2
var lonDegrees: Int = Int(coordinate)
var lonMinutes = Int(abs((coordinate.truncatingRemainder(dividingBy: 1) * 60.0)))
var lonSeconds = abs(((coordinate.truncatingRemainder(dividingBy: 1) * 60.0).truncatingRemainder(dividingBy: 1) * 60.0)).rounded()
if lonSeconds == 60 {
lonSeconds = 0
lonMinutes += 1
}
if lonMinutes == 60 {
lonDegrees += 1
lonMinutes = 0
}
return "\(abs(lonDegrees))° \(nf.string(for: lonMinutes) ?? "")\' \(nf.string(for: lonSeconds) ?? "")\" \(lonDegrees >= 0 ? "E" : "W")"
}
}
| apache-2.0 | 93096ae620d3057f10a60f40d8a16a86 | 37.399351 | 192 | 0.561427 | 5.187281 | false | false | false | false |
fqhuy/minimind | minimind/random.swift | 1 | 3787 | //
// SwiftRandom.swift
//
// Created by Furkan Yilmaz on 7/10/15.
// Copyright (c) 2015 Furkan Yilmaz. All rights reserved.
//
//import UIKit
import Foundation
public func rand<T: BinaryFloatingPoint>(_ lower: T = 0.0, _ upper: T = 1.0) -> T {
return (T(arc4random()) / 0xFFFFFFFF) * (upper - lower) + lower
}
public extension Bool {
/// SwiftRandom extension
public static func random() -> Bool {
return Int.random() % 2 == 0
}
}
public extension Int {
/// SwiftRandom extension
public static func random(_ range: Range<Int>) -> Int {
#if swift(>=3)
return random(range.lowerBound, range.upperBound - 1)
#else
return random(range.upperBound, range.lowerBound)
#endif
}
/// SwiftRandom extension
public static func random(_ range: ClosedRange<Int>) -> Int {
return random(range.lowerBound, range.upperBound)
}
/// SwiftRandom extension
public static func random(_ lower: Int = 0, _ upper: Int = 100) -> Int {
return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
}
}
public extension Int32 {
/// SwiftRandom extension
public static func random(_ range: Range<Int>) -> Int32 {
return random(range.upperBound, range.lowerBound)
}
/// SwiftRandom extension
///
/// - note: Using `Int` as parameter type as we usually just want to write `Int32.random(13, 37)` and not `Int32.random(Int32(13), Int32(37))`
public static func random(_ lower: Int = 0, _ upper: Int = 100) -> Int32 {
let r = arc4random_uniform(UInt32(Int64(upper) - Int64(lower)))
return Int32(Int64(r) + Int64(lower))
}
}
public extension Double {
/// SwiftRandom extension
public static func random(_ lower: Double = 0, _ upper: Double = 100) -> Double {
return (Double(arc4random()) / 0xFFFFFFFF) * (upper - lower) + lower
}
}
public extension Float {
/// SwiftRandom extension
public static func random(_ lower: Float = 0, _ upper: Float = 100) -> Float {
return (Float(arc4random()) / 0xFFFFFFFF) * (upper - lower) + lower
}
}
public extension Array {
/// SwiftRandom extension
public func randomItem() -> Element? {
guard self.count > 0 else {
return nil
}
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
}
public extension ArraySlice {
/// SwiftRandom extension
public func randomItem() -> Element? {
guard self.count > 0 else {
return nil
}
#if swift(>=3)
let index = Int.random(self.startIndex, self.count - 1)
#else
let index = Int.random(self.startIndex, self.endIndex)
#endif
return self[index]
}
}
public struct Randoms {
public static func randomBool() -> Bool {
return Bool.random()
}
public static func randomInt(_ range: Range<Int>) -> Int {
return Int.random(range)
}
public static func randomInt(_ lower: Int = 0, _ upper: Int = 100) -> Int {
return Int.random(lower, upper)
}
public static func randomInt32(_ range: Range<Int>) -> Int32 {
return Int32.random(range)
}
public static func randomInt32(_ lower: Int = 0, _ upper: Int = 100) -> Int32 {
return Int32.random(lower, upper)
}
public static func randomPercentageisOver(_ percentage: Int) -> Bool {
return Int.random() > percentage
}
public static func randomDouble(_ lower: Double = 0, _ upper: Double = 100) -> Double {
return Double.random(lower, upper)
}
public static func randomFloat(_ lower: Float = 0, _ upper: Float = 100) -> Float {
return Float.random(lower, upper)
}
}
| mit | 23112283cd48f65b9f0cabfb3731c912 | 26.845588 | 146 | 0.605228 | 3.948905 | false | false | false | false |
Diego5529/tcc-swift3 | tcc-swift3/src/controllers/InviteFormViewController.swift | 1 | 10648 | //
// InviteFormViewController.swift
// tcc-swift3
//
// Created by Diego Oliveira on 27/05/17.
// Copyright © 2017 DO. All rights reserved.
//
import UIKit
import Former
import CoreData
class InviteFormViewController : FormViewController {
var delegate: AppDelegate!
var context: NSManagedObjectContext!
var companyEvent: CompanyBean!
var eventClass: EventBean!
var invitationClass: InvitationBean!
var userClass: UserBean!
override func viewDidLoad() {
super.viewDidLoad()
delegate = UIApplication.shared.delegate as! AppDelegate
context = self.delegate.managedObjectContext
if invitationClass == nil && eventClass != nil {
invitationClass = InvitationBean.init()
invitationClass.event_id = eventClass.event_id
invitationClass.host_user_id = (delegate.genericUser?.user_id)!
configureInviteRows()
addSaveButton()
}else {
self.dismiss(animated: true, completion: nil)
}
}
func addSaveButton(){
let addButton = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
}
func insertNewObject(_ sender: Any) {
if self.invitationClass?.created_at == nil {
invitationClass?.created_at = NSDate.init()
}
DispatchQueue.global(qos: .default).async(execute: {() -> Void in
//
var idMaxUser = 0
let userBean = UserBean.getUserByEmail(context: self.context, email: self.invitationClass.email)
if (userBean.id == 0) {
let sync = Sync.init()
sync.getUserEmailOrID(user: userBean, email: self.invitationClass.email, id: self.invitationClass.id)
}
DispatchQueue.main.async(execute: {() -> Void in
//
if userBean.id > 0 {
self.invitationClass.guest_user_id = userBean.id
}else{
let userObj: NSManagedObject = NSEntityDescription.insertNewObject(forEntityName: "User", into: self.context)
idMaxUser = Int(UserBean.getMaxUser(context: self.context))
userObj.setValue(self.invitationClass.email, forKey: "email")
userObj.setValue(idMaxUser, forKey: "user_id")
self.invitationClass.guest_user_id = Int16(idMaxUser)
}
let message = self.invitationClass?.validateCreateInvitation()
if (message?.isEmpty)! {
self.navigationItem.rightBarButtonItem?.isEnabled = false
let idMaxInvitation = InvitationBean.getMaxInvitation(context: self.context)
self.invitationClass.invitation_id = idMaxInvitation
self.invitationClass.event_id = self.eventClass.event_id
self.invitationClass.host_user_id = (self.delegate.genericUser?.id)!
self.invitationClass.updated_at = NSDate.init()
do {
InvitationBean.saveInvitation(context: self.context, invitation: self.invitationClass)
try self.context.save()
print("save success!")
OperationQueue.main.addOperation {
}
}catch{
print("Salvou")
}
}else{
self.showMessage(message: message!, title: "Error", cancel: "")
}
})
})
}
override func viewDidAppear(_ animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func configureInviteRows (){
// Create RowFormers
// InviteRows
let inputAccessoryView = FormerInputAccessoryView(former: former)
// Create Headers and Footers
let createHeader: ((String) -> ViewFormer) = { text in
return LabelViewFormer<FormLabelHeaderView>()
.configure {
$0.text = text
$0.viewHeight = 44
}
}
//Create Rows
//User
let textFieldUserEvent = TextFieldRowFormer<FormTextFieldCell>() {
$0.titleLabel.text = "User"
$0.textField.keyboardType = .emailAddress
}.configure {
$0.placeholder = "Email"
}.onTextChanged {
print($0)
self.navigationItem.rightBarButtonItem?.isEnabled = true
self.invitationClass?.email = $0.lowercased()
}.onUpdate{
$0.text = self.invitationClass.email.lowercased()
}
//Invitation Type
let selectorInvitationTypePickerRow = SelectorPickerRowFormer<FormSelectorPickerCell, Any>() {
$0.titleLabel.text = "Invitation Type"
}.configure {
$0.pickerItems = [SelectorPickerItem(
title: "",
displayTitle: NSAttributedString(string: "Normal"),
value: nil)]
+ (1...20).map { SelectorPickerItem(title: "Type \($0)") }
}
// Create SectionFormers
let section0 = SectionFormer(rowFormer: textFieldUserEvent, selectorInvitationTypePickerRow)
.set(headerViewFormer: createHeader("Invite"))
former.append(sectionFormer: section0
).onCellSelected { _ in
inputAccessoryView.update()
}
}
private enum InsertPosition: Int {
case Below, Above
}
private var insertRowAnimation = UITableViewRowAnimation.left
private var insertSectionAnimation = UITableViewRowAnimation.fade
private var insertRowPosition: InsertPosition = .Below
private var insertSectionPosition: InsertPosition = .Below
private lazy var subRowFormers: [RowFormer] = {
return (1...2).map { index -> RowFormer in
return CheckRowFormer<FormCheckCell>() {
$0.titleLabel.text = "Check\(index)"
$0.titleLabel.textColor = .formerColor()
$0.titleLabel.font = .boldSystemFont(ofSize: 16)
$0.tintColor = .formerSubColor()
}
}
}()
private lazy var subSectionFormer: SectionFormer = {
return SectionFormer(rowFormers: [
CheckRowFormer<FormCheckCell>() {
$0.titleLabel.text = "Check3"
$0.titleLabel.textColor = .formerColor()
$0.titleLabel.font = .boldSystemFont(ofSize: 16)
$0.tintColor = .formerSubColor()
}
])
}()
private func insertRows(sectionTop: RowFormer, sectionBottom: RowFormer) -> (Bool) -> Void {
return { [weak self] insert in
guard let `self` = self else { return }
if insert {
if self.insertRowPosition == .Below {
self.former.insertUpdate(rowFormers: self.subRowFormers, below: sectionBottom, rowAnimation: self.insertRowAnimation)
} else if self.insertRowPosition == .Above {
self.former.insertUpdate(rowFormers: self.subRowFormers, above: sectionTop, rowAnimation: self.insertRowAnimation)
}
} else {
self.former.removeUpdate(rowFormers: self.subRowFormers, rowAnimation: self.insertRowAnimation)
}
}
}
private func insertSection(relate: SectionFormer) -> (Bool) -> Void {
return { [weak self] insert in
guard let `self` = self else { return }
if insert {
if self.insertSectionPosition == .Below {
self.former.insertUpdate(sectionFormers: [self.subSectionFormer], below: relate, rowAnimation: self.insertSectionAnimation)
} else if self.insertSectionPosition == .Above {
self.former.insertUpdate(sectionFormers: [self.subSectionFormer], above: relate, rowAnimation: self.insertSectionAnimation)
}
} else {
self.former.removeUpdate(sectionFormers: [self.subSectionFormer], rowAnimation: self.insertSectionAnimation)
}
}
}
private func sheetSelectorRowSelected(options: [String]) -> (RowFormer) -> Void {
return { [weak self] rowFormer in
if let rowFormer = rowFormer as? LabelRowFormer<FormLabelCell> {
let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
options.forEach { title in
sheet.addAction(UIAlertAction(title: title, style: .default, handler: { [weak rowFormer] _ in
rowFormer?.subText = title
rowFormer?.update()
})
)
}
sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self?.present(sheet, animated: true, completion: nil)
self?.former.deselect(animated: true)
}
}
}
//AlertView
func showMessage(message: String, title: String, cancel: String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
if cancel.characters.count > 0 {
let DestructiveAction = UIAlertAction(title: cancel, style: UIAlertActionStyle.destructive) {
(result : UIAlertAction) -> Void in
print("Destructive")
}
alertController.addAction(DestructiveAction)
}
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
(result : UIAlertAction) -> Void in
}
alertController.addAction(okAction)
OperationQueue.main.addOperation {
self.present(alertController, animated: false, completion: nil)
}
}
}
| mit | 4dac10e0b4675cb7ab864f6a4138f00e | 38.287823 | 143 | 0.55471 | 5.553991 | false | false | false | false |
kickerchen/KCPutton | Putton/ViewController.swift | 1 | 2569 | //
// ViewController.swift
// Putton
//
// Created by CHENCHIAN on 7/22/15.
// Copyright (c) 2015 KICKERCHEN. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let startButton = PuttonItem(image: UIImage(named: "mushroom")!)
let itemButton1 = PuttonItem(image: UIImage(named: "mario")!)
itemButton1.addTarget(self, action: "hitOnMario1:", forControlEvents: .TouchUpInside)
let itemButton2 = PuttonItem(image: UIImage(named: "mario")!)
itemButton2.addTarget(self, action: "hitOnMario2:", forControlEvents: .TouchUpInside)
let itemButton3 = PuttonItem(image: UIImage(named: "mario")!)
itemButton3.addTarget(self, action: "hitOnMario3:", forControlEvents: .TouchUpInside)
let itemButton4 = PuttonItem(image: UIImage(named: "mario")!)
itemButton4.addTarget(self, action: "hitOnMario4:", forControlEvents: .TouchUpInside)
let itemButton5 = PuttonItem(image: UIImage(named: "mario")!)
itemButton5.addTarget(self, action: "hitOnMario5:", forControlEvents: .TouchUpInside)
let itemButton6 = PuttonItem(image: UIImage(named: "mario")!)
itemButton6.addTarget(self, action: "hitOnMario6:", forControlEvents: .TouchUpInside)
let items = NSArray(array: [itemButton1, itemButton2, itemButton3, itemButton4, itemButton5, itemButton6])
let putton = Putton(frame: CGRectMake(CGRectGetWidth(UIScreen.mainScreen().bounds)/2-26, CGRectGetHeight(UIScreen.mainScreen().bounds)/2-26, 52, 52), startItem: startButton, expandItems: items)
self.view.addSubview(putton)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func hitOnMario1(sender: UIButton!){
println("Mario 1 is hit")
}
func hitOnMario2(sender: UIButton!){
println("Mario 2 is hit")
}
func hitOnMario3(sender: UIButton!){
println("Mario 3 is hit")
}
func hitOnMario4(sender: UIButton!){
println("Mario 4 is hit")
}
func hitOnMario5(sender: UIButton!){
println("Mario 5 is hit")
}
func hitOnMario6(sender: UIButton!){
println("Mario 6 is hit")
}
}
| mit | 5f7bb3ab8c8ca40df8e3d067f48c5d21 | 34.191781 | 201 | 0.657454 | 4.603943 | false | false | false | false |
SwiftAndroid/swift | test/Driver/linker.swift | 4 | 11078 | // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt
// RUN: FileCheck %s < %t.simple.txt
// RUN: FileCheck -check-prefix SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios7.1 %s 2>&1 > %t.simple.txt
// RUN: FileCheck -check-prefix IOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-tvos9.0 %s 2>&1 > %t.simple.txt
// RUN: FileCheck -check-prefix tvOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target i386-apple-watchos2.0 %s 2>&1 > %t.simple.txt
// RUN: FileCheck -check-prefix watchOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: FileCheck -check-prefix LINUX-x86_64 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv6-unknown-linux-gnueabihf -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: FileCheck -check-prefix LINUX-armv6 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: FileCheck -check-prefix LINUX-armv7 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target thumbv7-unknown-linux-gnueabihf -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: FileCheck -check-prefix LINUX-thumbv7 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-none-linux-androideabi -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.android.txt
// RUN: FileCheck -check-prefix ANDROID-armv7 %s < %t.android.txt
// RUN: FileCheck -check-prefix ANDROID-armv7-NEGATIVE %s < %t.android.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-cygnus -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.cygwin.txt
// RUN: FileCheck -check-prefix CYGWIN-x86_64 %s < %t.cygwin.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-apple-macosx10.9.1 %s -sdk %S/../Inputs/clang-importer-sdk -lfoo -framework bar -Lbaz -Fgarply -Xlinker -undefined -Xlinker dynamic_lookup -o sdk.out 2>&1 > %t.complex.txt
// RUN: FileCheck %s < %t.complex.txt
// RUN: FileCheck -check-prefix COMPLEX %s < %t.complex.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -g %s | FileCheck -check-prefix DEBUG %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.10 %s | FileCheck -check-prefix NO_ARCLITE %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios8.0 %s | FileCheck -check-prefix NO_ARCLITE %s
// RUN: rm -rf %t && mkdir %t
// RUN: touch %t/a.o
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -o linker 2>&1 | FileCheck -check-prefix COMPILE_AND_LINK %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -driver-use-filelists -o linker 2>&1 | FileCheck -check-prefix FILELIST %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -module-name LINKER | FileCheck -check-prefix INFERRED_NAME %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -o libLINKER.dylib | FileCheck -check-prefix INFERRED_NAME %s
// There are more RUN lines further down in the file.
// REQUIRES: X86
// FIXME: Need to set up a sysroot for osx so the DEBUG checks work on linux/freebsd
// rdar://problem/19692770
// XFAIL: freebsd, linux
// CHECK: swift
// CHECK: -o [[OBJECTFILE:.*]]
// CHECK-NEXT: bin/ld{{"? }}
// CHECK-DAG: [[OBJECTFILE]]
// CHECK-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift/macosx]]
// CHECK-DAG: -rpath [[STDLIB_PATH]]
// CHECK-DAG: -lSystem
// CHECK-DAG: -arch x86_64
// CHECK-DAG: -force_load {{[^ ]+/lib/arc/libarclite_macosx.a}} -framework CoreFoundation
// CHECK: -o {{[^ ]+}}
// SIMPLE: bin/ld{{"? }}
// SIMPLE-NOT: -syslibroot
// SIMPLE-DAG: -macosx_version_min 10.{{[0-9]+}}.{{[0-9]+}}
// SIMPLE-NOT: -syslibroot
// SIMPLE: -o linker
// IOS_SIMPLE: swift
// IOS_SIMPLE: -o [[OBJECTFILE:.*]]
// IOS_SIMPLE: bin/ld{{"? }}
// IOS_SIMPLE-DAG: [[OBJECTFILE]]
// IOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/iphonesimulator}}
// IOS_SIMPLE-DAG: -lSystem
// IOS_SIMPLE-DAG: -arch x86_64
// IOS_SIMPLE-DAG: -ios_simulator_version_min 7.1.{{[0-9]+}}
// IOS_SIMPLE: -o linker
// tvOS_SIMPLE: swift
// tvOS_SIMPLE: -o [[OBJECTFILE:.*]]
// tvOS_SIMPLE: bin/ld{{"? }}
// tvOS_SIMPLE-DAG: [[OBJECTFILE]]
// tvOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/appletvsimulator}}
// tvOS_SIMPLE-DAG: -lSystem
// tvOS_SIMPLE-DAG: -arch x86_64
// tvOS_SIMPLE-DAG: -tvos_simulator_version_min 9.0.{{[0-9]+}}
// tvOS_SIMPLE: -o linker
// watchOS_SIMPLE: swift
// watchOS_SIMPLE: -o [[OBJECTFILE:.*]]
// watchOS_SIMPLE: bin/ld{{"? }}
// watchOS_SIMPLE-DAG: [[OBJECTFILE]]
// watchOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/watchsimulator}}
// watchOS_SIMPLE-DAG: -lSystem
// watchOS_SIMPLE-DAG: -arch i386
// watchOS_SIMPLE-DAG: -watchos_simulator_version_min 2.0.{{[0-9]+}}
// watchOS_SIMPLE: -o linker
// LINUX-x86_64: swift
// LINUX-x86_64: -o [[OBJECTFILE:.*]]
// LINUX-x86_64: clang++{{"? }}
// LINUX-x86_64-DAG: [[OBJECTFILE]]
// LINUX-x86_64-DAG: -lswiftCore
// LINUX-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-x86_64-DAG: -F foo
// LINUX-x86_64-DAG: -framework bar
// LINUX-x86_64-DAG: -L baz
// LINUX-x86_64-DAG: -lboo
// LINUX-x86_64-DAG: -Xlinker -undefined
// LINUX-x86_64: -o linker
// LINUX-armv6: swift
// LINUX-armv6: -o [[OBJECTFILE:.*]]
// LINUX-armv6: clang++{{"? }}
// LINUX-armv6-DAG: [[OBJECTFILE]]
// LINUX-armv6-DAG: -lswiftCore
// LINUX-armv6-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-armv6-DAG: -target armv6-unknown-linux-gnueabihf
// LINUX-armv6-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv6-DAG: -F foo
// LINUX-armv6-DAG: -framework bar
// LINUX-armv6-DAG: -L baz
// LINUX-armv6-DAG: -lboo
// LINUX-armv6-DAG: -Xlinker -undefined
// LINUX-armv6: -o linker
// LINUX-armv7: swift
// LINUX-armv7: -o [[OBJECTFILE:.*]]
// LINUX-armv7: clang++{{"? }}
// LINUX-armv7-DAG: [[OBJECTFILE]]
// LINUX-armv7-DAG: -lswiftCore
// LINUX-armv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-armv7-DAG: -target armv7-unknown-linux-gnueabihf
// LINUX-armv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv7-DAG: -F foo
// LINUX-armv7-DAG: -framework bar
// LINUX-armv7-DAG: -L baz
// LINUX-armv7-DAG: -lboo
// LINUX-armv7-DAG: -Xlinker -undefined
// LINUX-armv7: -o linker
// LINUX-thumbv7: swift
// LINUX-thumbv7: -o [[OBJECTFILE:.*]]
// LINUX-thumbv7: clang++{{"? }}
// LINUX-thumbv7-DAG: [[OBJECTFILE]]
// LINUX-thumbv7-DAG: -lswiftCore
// LINUX-thumbv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-thumbv7-DAG: -target thumbv7-unknown-linux-gnueabihf
// LINUX-thumbv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-thumbv7-DAG: -F foo
// LINUX-thumbv7-DAG: -framework bar
// LINUX-thumbv7-DAG: -L baz
// LINUX-thumbv7-DAG: -lboo
// LINUX-thumbv7-DAG: -Xlinker -undefined
// LINUX-thumbv7: -o linker
// ANDROID-armv7: swift
// ANDROID-armv7: -o [[OBJECTFILE:.*]]
// ANDROID-armv7: clang++{{"? }}
// ANDROID-armv7-DAG: [[OBJECTFILE]]
// ANDROID-armv7-DAG: -lswiftCore
// ANDROID-armv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// ANDROID-armv7-DAG: -target armv7-none-linux-androideabi
// ANDROID-armv7-DAG: -F foo
// ANDROID-armv7-DAG: -framework bar
// ANDROID-armv7-DAG: -L baz
// ANDROID-armv7-DAG: -lboo
// ANDROID-armv7-DAG: -Xlinker -undefined
// ANDROID-armv7: -o linker
// ANDROID-armv7-NEGATIVE-NOT: -Xlinker -rpath
// CYGWIN-x86_64: swift
// CYGWIN-x86_64: -o [[OBJECTFILE:.*]]
// CYGWIN-x86_64: clang++{{"? }}
// CYGWIN-x86_64-DAG: [[OBJECTFILE]]
// CYGWIN-x86_64-DAG: -lswiftCore
// CYGWIN-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// CYGWIN-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// CYGWIN-x86_64-DAG: -F foo
// CYGWIN-x86_64-DAG: -framework bar
// CYGWIN-x86_64-DAG: -L baz
// CYGWIN-x86_64-DAG: -lboo
// CYGWIN-x86_64-DAG: -Xlinker -undefined
// CYGWIN-x86_64: -o linker
// COMPLEX: bin/ld{{"? }}
// COMPLEX-DAG: -dylib
// COMPLEX-DAG: -syslibroot {{.*}}/Inputs/clang-importer-sdk
// COMPLEX-DAG: -lfoo
// COMPLEX-DAG: -framework bar
// COMPLEX-DAG: -L baz
// COMPLEX-DAG: -F garply
// COMPLEX-DAG: -undefined dynamic_lookup
// COMPLEX-DAG: -macosx_version_min 10.9.1
// COMPLEX: -o sdk.out
// DEBUG: bin/swift
// DEBUG-NEXT: bin/swift
// DEBUG-NEXT: bin/ld{{"? }}
// DEBUG: -add_ast_path {{.*}}/{{[^/]+}}.swiftmodule
// DEBUG: -o linker
// DEBUG-NEXT: bin/dsymutil
// DEBUG: linker
// DEBUG: -o linker.dSYM
// NO_ARCLITE: bin/ld{{"? }}
// NO_ARCLITE-NOT: arclite
// NO_ARCLITE: -o {{[^ ]+}}
// COMPILE_AND_LINK: bin/swift
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK: linker.swift
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK-NEXT: bin/ld{{"? }}
// COMPILE_AND_LINK-DAG: /a.o
// COMPILE_AND_LINK-DAG: .o
// COMPILE_AND_LINK: -o linker
// FILELIST: bin/ld{{"? }}
// FILELIST-NOT: .o
// FILELIST: -filelist {{"?[^-]}}
// FILELIST-NOT: .o
// FILELIST: /a.o
// FILELIST-NOT: .o
// FILELIST: -o linker
// INFERRED_NAME: bin/swift
// INFERRED_NAME: -module-name LINKER
// INFERRED_NAME: bin/ld{{"? }}
// INFERRED_NAME: -o libLINKER.dylib
// Test ld detection. We use hard links to make sure
// the Swift driver really thinks it's been moved.
// RUN: rm -rf %t
// RUN: mkdir -p %t/DISTINCTIVE-PATH/usr/bin/
// RUN: touch %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: chmod +x %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: ln %swift_driver_plain %t/DISTINCTIVE-PATH/usr/bin/swiftc
// RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc %s -### | FileCheck -check-prefix=RELATIVE-LINKER %s
// RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/swift
// RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/ld
// RELATIVE-LINKER: -o {{[^ ]+}}
// Also test arclite detection. This uses xcrun to find arclite when it's not
// next to Swift.
// RUN: mkdir -p %t/ANOTHER-DISTINCTIVE-PATH/usr/bin
// RUN: mkdir -p %t/ANOTHER-DISTINCTIVE-PATH/usr/lib/arc
// RUN: cp %S/Inputs/xcrun-return-self.sh %t/ANOTHER-DISTINCTIVE-PATH/usr/bin/xcrun
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | FileCheck -check-prefix=XCRUN_ARCLITE %s
// XCRUN_ARCLITE: bin/ld{{"? }}
// XCRUN_ARCLITE: /ANOTHER-DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a
// XCRUN_ARCLITE: -o {{[^ ]+}}
// RUN: mkdir -p %t/DISTINCTIVE-PATH/usr/lib/arc
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | FileCheck -check-prefix=RELATIVE_ARCLITE %s
// RELATIVE_ARCLITE: bin/ld{{"? }}
// RELATIVE_ARCLITE: /DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a
// RELATIVE_ARCLITE: -o {{[^ ]+}}
// Clean up the test executable because hard links are expensive.
// RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
| apache-2.0 | df192d6d1b7a9a332bc28d58cc897632 | 36.425676 | 242 | 0.670789 | 2.860315 | false | false | false | false |
ustwo/formvalidator-swift | Example/macOS/FormAccessibility.swift | 1 | 717 | //
// FormAccessibility.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 06/01/2017.
// Copyright © 2017 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
enum FormAccessibility {
enum Identifiers {
static let EmailLabel = "EMAIL_LABEL"
static let EmailTextField = "EMAIL_TEXTFIELD"
static let ErrorLabel = "ERROR_LABEL"
static let NameLabel = "NAME_LABEL"
static let NameTextField = "NAME_TEXTFIELD"
static let TitleLabel = "TITLE_LABEL"
static let TitleTextField = "TITLE_TEXTFIELD"
static let SubmitButton = "SUBMIT_BUTTON"
}
}
| mit | 17d2d1c02dca76fc8df14f1c94d9f1d4 | 24.571429 | 60 | 0.593575 | 4.475 | false | false | false | false |
tidepool-org/nutshell-ios | Nutshell/ViewControllers/EventAddOrEditViewController.swift | 1 | 48054 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* 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 License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import UIKit
import CoreData
import Photos
import MobileCoreServices
class EventAddOrEditViewController: BaseUIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var eventItem: NutEventItem?
var eventGroup: NutEvent?
var newEventItem: EventItem?
fileprivate var editExistingEvent = false
fileprivate var isWorkout: Bool = false
@IBOutlet weak var titleTextField: NutshellUITextField!
@IBOutlet weak var titleHintLabel: NutshellUILabel!
@IBOutlet weak var notesTextField: NutshellUITextField!
@IBOutlet weak var notesHintLabel: NutshellUILabel!
@IBOutlet weak var placeIconButton: UIButton!
@IBOutlet weak var photoIconButton: UIButton!
@IBOutlet weak var calendarIconButton: UIButton!
@IBOutlet weak var placeControlContainer: UIView!
@IBOutlet weak var calendarControlContainer: UIView!
@IBOutlet weak var photoControlContainer: UIView!
@IBOutlet weak var workoutCalorieContainer: UIView!
@IBOutlet weak var caloriesLabel: NutshellUILabel!
@IBOutlet weak var workoutDurationContainer: UIView!
@IBOutlet weak var durationLabel: NutshellUILabel!
@IBOutlet weak var headerForModalView: NutshellUIView!
@IBOutlet weak var sceneContainer: UIView!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var addSuccessView: NutshellUIView!
@IBOutlet weak var addSuccessImageView: UIImageView!
@IBOutlet weak var datePickerView: UIView!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var date1Label: NutshellUILabel!
@IBOutlet weak var date2Label: NutshellUILabel!
@IBOutlet weak var picture0Image: UIImageView!
@IBOutlet weak var picture1Image: UIImageView!
@IBOutlet weak var picture2Image: UIImageView!
fileprivate var eventTime = Date()
// Note: time zone offset is only used for display; new items are always created with the offset for the current calendar time zone, and time zones are not editable!
fileprivate var eventTimeOffsetSecs: Int = 0
fileprivate var pictureImageURLs: [String] = []
@IBOutlet weak var bottomSectionContainer: UIView!
//
// MARK: - Base methods
//
override func viewDidLoad() {
super.viewDidLoad()
var saveButtonTitle = NSLocalizedString("saveButtonTitle", comment:"Save")
if let eventItem = eventItem {
editExistingEvent = true
eventTime = eventItem.time as Date
eventTimeOffsetSecs = eventItem.tzOffsetSecs
// hide location and photo controls for workouts
if let workout = eventItem as? NutWorkout {
isWorkout = true
placeControlContainer.isHidden = true
photoControlContainer.isHidden = true
if workout.duration > 0 {
workoutDurationContainer.isHidden = false
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.abbreviated
durationLabel.text = dateComponentsFormatter.string(from: workout.duration)
}
if let calories = workout.calories {
if Int(calories) > 0 {
workoutCalorieContainer.isHidden = false
caloriesLabel.text = String(Int(calories)) + " Calories"
}
}
}
// hide modal header when used as a nav view
for c in headerForModalView.constraints {
if c.firstAttribute == NSLayoutAttribute.height {
c.constant = 0.0
break
}
}
} else {
eventTimeOffsetSecs = NSCalendar.current.timeZone.secondsFromGMT()
locationTextField.text = Styles.placeholderLocationString
saveButtonTitle = NSLocalizedString("saveAndEatButtonTitle", comment:"Save and eat!")
}
saveButton.setTitle(saveButtonTitle, for: UIControlState())
configureInfoSection()
titleHintLabel.text = Styles.titleHintString
notesHintLabel.text = Styles.noteHintString
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(EventAddOrEditViewController.textFieldDidChange), name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
notificationCenter.addObserver(self, selector: #selector(EventAddOrEditViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(EventAddOrEditViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
deinit {
let nc = NotificationCenter.default
nc.removeObserver(self, name: nil, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
APIConnector.connector().trackMetric("Viewed Edit Screen (Edit Screen)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//
// MARK: - Navigation
//
@IBAction func done(_ segue: UIStoryboardSegue) {
print("unwind segue to eventAddOrEdit done")
// Deal with possible delete/edit of photo from viewer...
if segue.identifier == EventViewStoryboard.SegueIdentifiers.UnwindSegueFromShowPhoto {
if let photoVC = segue.source as? ShowPhotoViewController {
// handle the case of a new photo replacing a new (not yet saved) photo: the older one should be immediately deleted since will be no reference to it left!
for url in pictureImageURLs {
if !preExistingPhoto(url) {
if !photoVC.photoURLs.contains(url) {
NutUtils.deleteLocalPhoto(url)
}
}
}
// new pending list of photos...
pictureImageURLs = photoVC.photoURLs
configurePhotos()
updateSaveButtonState()
}
}
}
//
// MARK: - Configuration
//
fileprivate func configureInfoSection() {
var titleText = Styles.placeholderTitleString
var notesText = Styles.placeholderNotesString
if let eventItem = eventItem {
if eventItem.title.characters.count > 0 {
titleText = eventItem.title
}
if eventItem.notes.characters.count > 0 {
notesText = eventItem.notes
}
picture0Image.isHidden = true
picture1Image.isHidden = true
picture2Image.isHidden = true
if let mealItem = eventItem as? NutMeal {
if !mealItem.location.isEmpty {
locationTextField.text = mealItem.location
} else {
locationTextField.text = Styles.placeholderLocationString
}
pictureImageURLs = mealItem.photoUrlArray()
} else {
// Add workout-specific items...
}
} else if let eventGroup = eventGroup {
titleText = eventGroup.title
locationTextField.text = eventGroup.location
}
titleTextField.text = titleText
notesTextField.text = notesText
configureTitleHint()
configureNotesHint()
configureDateView()
configurePhotos()
updateSaveButtonState()
}
fileprivate func configureTitleHint() {
let isBeingEdited = titleTextField.isFirstResponder
if isBeingEdited {
titleHintLabel.isHidden = false
} else {
let titleIsSet = titleTextField.text != "" && titleTextField.text != Styles.placeholderTitleString
titleHintLabel.isHidden = titleIsSet
}
}
fileprivate func configureNotesHint() {
let isBeingEdited = notesTextField.isFirstResponder
if isBeingEdited {
notesHintLabel.isHidden = false
} else {
let notesIsSet = notesTextField.text != "" && notesTextField.text != Styles.placeholderNotesString
notesHintLabel.isHidden = notesIsSet
}
}
fileprivate func configurePhotos() {
for item in 0...2 {
let picture = itemToPicture(item)
let url = itemToImageUrl(item)
if url.isEmpty {
picture.isHidden = true
} else {
picture.isHidden = false
NutUtils.loadImage(url, imageView: picture)
}
}
}
fileprivate func updateSaveButtonState() {
if !datePickerView.isHidden {
saveButton.isHidden = true
return
}
if editExistingEvent {
saveButton.isHidden = !existingEventChanged()
} else {
if !newEventChanged() || titleTextField.text?.characters.count == 0 || titleTextField.text == Styles.placeholderTitleString {
saveButton.isHidden = true
} else {
saveButton.isHidden = false
}
}
}
// When the keyboard is up, the save button moves up
fileprivate var viewAdjustAnimationTime: Float = 0.25
fileprivate func configureSaveViewPosition(_ bottomOffset: CGFloat) {
for c in sceneContainer.constraints {
if c.firstAttribute == NSLayoutAttribute.bottom {
if let secondItem = c.secondItem {
if secondItem as! NSObject == saveButton {
c.constant = bottomOffset
break
}
}
}
}
UIView.animate(withDuration: TimeInterval(viewAdjustAnimationTime), animations: {
self.saveButton.layoutIfNeeded()
})
}
fileprivate func hideDateIfOpen() {
if !datePickerView.isHidden {
cancelDatePickButtonHandler(self)
}
}
// Bold all but last suffixCnt characters of string (Note: assumes date format!
fileprivate func boldFirstPartOfDateString(_ dateStr: String, suffixCnt: Int) -> NSAttributedString {
let attrStr = NSMutableAttributedString(string: dateStr, attributes: [NSFontAttributeName: Styles.smallBoldFont, NSForegroundColorAttributeName: Styles.whiteColor])
attrStr.addAttribute(NSFontAttributeName, value: Styles.smallRegularFont, range: NSRange(location: attrStr.length - suffixCnt, length: suffixCnt))
return attrStr
}
fileprivate func updateDateLabels() {
let df = DateFormatter()
// Note: Time zones created with this method never have daylight savings, and the offset is constant no matter the date
df.timeZone = TimeZone(secondsFromGMT:eventTimeOffsetSecs)
df.dateFormat = "MMM d, yyyy"
date1Label.attributedText = boldFirstPartOfDateString(df.string(from: eventTime), suffixCnt: 6)
df.dateFormat = "h:mm a"
date2Label.attributedText = boldFirstPartOfDateString(df.string(from: eventTime), suffixCnt: 2)
}
fileprivate func configureDateView() {
updateDateLabels()
datePicker.date = eventTime
// Note: Time zones created with this method never have daylight savings, and the offset is constant no matter the date
datePicker.timeZone = TimeZone(secondsFromGMT: eventTimeOffsetSecs)
datePickerView.isHidden = true
}
// UIKeyboardWillShowNotification
func keyboardWillShow(_ notification: Notification) {
// adjust save button up when keyboard is up
let keyboardFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
viewAdjustAnimationTime = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Float
self.configureSaveViewPosition(keyboardFrame.height)
}
// UIKeyboardWillHideNotification
func keyboardWillHide(_ notification: Notification) {
// reposition save button view if needed
self.configureSaveViewPosition(0.0)
}
//
// MARK: - Button and text field handlers
//
@IBAction func dismissKeyboard(_ sender: AnyObject) {
titleTextField.resignFirstResponder()
notesTextField.resignFirstResponder()
locationTextField.resignFirstResponder()
hideDateIfOpen()
}
@IBAction func titleTextLargeHitAreaButton(_ sender: AnyObject) {
titleTextField.becomeFirstResponder()
}
func textFieldDidChange() {
updateSaveButtonState()
}
@IBAction func titleEditingDidBegin(_ sender: AnyObject) {
hideDateIfOpen()
configureTitleHint()
if titleTextField.text == Styles.placeholderTitleString {
titleTextField.text = ""
}
if editExistingEvent {
APIConnector.connector().trackMetric("Edited Meal Name (Edit Screen)")
} else {
APIConnector.connector().trackMetric("Clicked to Add Meal Name (Add Meal Screen)")
}
}
@IBAction func titleEditingDidEnd(_ sender: AnyObject) {
updateSaveButtonState()
configureTitleHint()
if titleTextField.text == "" {
titleTextField.text = Styles.placeholderTitleString
}
}
@IBAction func notesTextLargeHitAreaButton(_ sender: AnyObject) {
notesTextField.becomeFirstResponder()
}
@IBAction func notesEditingDidBegin(_ sender: AnyObject) {
hideDateIfOpen()
configureNotesHint()
if notesTextField.text == Styles.placeholderNotesString {
notesTextField.text = ""
}
if editExistingEvent {
APIConnector.connector().trackMetric("Edited Notes (Edit Screen)")
} else {
APIConnector.connector().trackMetric("Clicked to Add Notes (Add Meal Screen)")
}
}
@IBAction func notesEditingDidEnd(_ sender: AnyObject) {
updateSaveButtonState()
configureNotesHint()
if notesTextField.text == "" {
notesTextField.text = Styles.placeholderNotesString
}
}
@IBAction func locationButtonHandler(_ sender: AnyObject) {
locationTextField.becomeFirstResponder()
}
@IBAction func locationEditingDidBegin(_ sender: AnyObject) {
hideDateIfOpen()
if locationTextField.text == Styles.placeholderLocationString {
locationTextField.text = ""
}
if editExistingEvent {
APIConnector.connector().trackMetric("Edited Location (Edit Screen)")
} else {
APIConnector.connector().trackMetric("Clicked to Add Location (Add Meal Screen)")
}
}
@IBAction func locationEditingDidEnd(_ sender: AnyObject) {
updateSaveButtonState()
locationTextField.resignFirstResponder()
if locationTextField.text == "" {
locationTextField.text = Styles.placeholderLocationString
}
}
@IBAction func saveButtonHandler(_ sender: AnyObject) {
if editExistingEvent {
updateCurrentEvent()
self.performSegue(withIdentifier: "unwindSegueToDone", sender: self)
return
} else {
updateNewEvent()
}
}
@IBAction func backButtonHandler(_ sender: AnyObject) {
// this is a cancel for the role of addEvent and editEvent
// for viewEvent, we need to check whether the title has changed
if editExistingEvent {
// cancel of edit
APIConnector.connector().trackMetric("Clicked Cancel (Edit Screen)")
if existingEventChanged() {
var alertString = NSLocalizedString("discardMealEditsAlertMessage", comment:"If you press discard, your changes to this meal will be lost.")
if let _ = eventItem as? NutWorkout {
alertString = NSLocalizedString("discardWorkoutEditsAlertMessage", comment:"If you press discard, your changes to this workout will be lost.")
}
alertOnCancelAndReturn(NSLocalizedString("discardEditsAlertTitle", comment:"Discard changes?"), alertMessage: alertString, okayButtonString: NSLocalizedString("discardAlertOkay", comment:"Discard"))
} else {
self.performSegue(withIdentifier: "unwindSegueToCancel", sender: self)
}
} else {
// cancel of add
APIConnector.connector().trackMetric("Clicked ‘X’ to Close (Add Screen)")
if newEventChanged() {
var alertTitle = NSLocalizedString("deleteMealAlertTitle", comment:"Are you sure?")
var alertMessage = NSLocalizedString("deleteMealAlertMessage", comment:"If you delete this meal, it will be gone forever.")
if let _ = eventItem as? NutWorkout {
alertTitle = NSLocalizedString("deleteWorkoutAlertTitle", comment:"Discard workout?")
alertMessage = NSLocalizedString("deleteWorkoutAlertMessage", comment:"If you close this workout, your workout will be lost.")
}
alertOnCancelAndReturn(alertTitle, alertMessage: alertMessage, okayButtonString: NSLocalizedString("deleteAlertOkay", comment:"Delete"))
} else {
self.performSegue(withIdentifier: "unwindSegueToCancel", sender: self)
}
}
}
@IBAction func deleteButtonHandler(_ sender: AnyObject) {
// this is a delete for the role of editEvent
APIConnector.connector().trackMetric("Clicked Trashcan to Discard (Edit Screen)")
alertOnDeleteAndReturn()
}
fileprivate func pictureUrlEmptySlots() -> Int {
return 3 - pictureImageURLs.count
}
fileprivate func itemToImageUrl(_ itemNum: Int) -> String {
if itemNum >= pictureImageURLs.count {
return ""
} else {
return pictureImageURLs[itemNum]
}
}
fileprivate func itemToPicture(_ itemNum: Int) -> UIImageView {
switch itemNum {
case 0:
return picture0Image
case 1:
return picture1Image
case 2:
return picture2Image
default:
NSLog("Error: asking for out of range picture image!")
return picture0Image
}
}
fileprivate func appendPictureUrl(_ url: String) {
if pictureImageURLs.count < 3 {
pictureImageURLs.append(url)
if !editExistingEvent {
switch pictureImageURLs.count {
case 1: APIConnector.connector().trackMetric("First Photo Added (Add Meal Screen)")
case 2: APIConnector.connector().trackMetric("Second Photo Added (Add Meal Screen)")
case 3: APIConnector.connector().trackMetric("Third Photo Added (Add Meal Screen)")
default: break
}
}
}
}
fileprivate func showPicture(_ itemNum: Int) -> Bool {
let pictureUrl = itemToImageUrl(itemNum)
if !pictureUrl.isEmpty {
if editExistingEvent {
APIConnector.connector().trackMetric("Clicked Photos (Edit Screen)")
}
let storyboard = UIStoryboard(name: "EventView", bundle: nil)
let photoVC = storyboard.instantiateViewController(withIdentifier: "ShowPhotoViewController") as! ShowPhotoViewController
photoVC.photoURLs = pictureImageURLs
photoVC.mealTitle = titleTextField.text
photoVC.imageIndex = itemNum
photoVC.editAllowed = true
if editExistingEvent {
self.navigationController?.pushViewController(photoVC, animated: true)
} else {
photoVC.modalPresentation = true
self.present(photoVC, animated: true, completion: nil)
}
return true
} else {
return false
}
}
@IBAction func picture0ButtonHandler(_ sender: AnyObject) {
if !showPicture(0) {
photoButtonHandler(sender)
}
}
@IBAction func picture1ButtonHandler(_ sender: AnyObject) {
if !showPicture(1) {
photoButtonHandler(sender)
}
}
@IBAction func picture2ButtonHandler(_ sender: AnyObject) {
if !showPicture(2) {
photoButtonHandler(sender)
}
}
@IBAction func photoButtonHandler(_ sender: AnyObject) {
if pictureUrlEmptySlots() == 0 {
simpleInfoAlert(NSLocalizedString("photoSlotsFullTitle", comment:"No empty photo slot"), alertMessage: NSLocalizedString("photoSlotsFullMessage", comment:"Three photos are supported. Please discard one before adding a new photo."))
} else {
if !editExistingEvent {
switch pictureImageURLs.count {
case 0: APIConnector.connector().trackMetric("Clicked to Add First Photo (Add Meal Screen)")
case 1: APIConnector.connector().trackMetric("Clicked to Add Second Photo (Add Meal Screen)")
case 2: APIConnector.connector().trackMetric("Clicked to Add Third Photo (Add Meal Screen)")
default: break
}
}
showPhotoActionSheet()
}
}
func showPhotoActionSheet() {
let photoActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
photoActionSheet.modalPresentationStyle = .popover
photoActionSheet.addAction(UIAlertAction(title: NSLocalizedString("discardAlertCancel", comment:"Cancel"), style: .cancel, handler: { Void in
return
}))
photoActionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { Void in
let pickerC = UIImagePickerController()
pickerC.delegate = self
self.present(pickerC, animated: true, completion: nil)
}))
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
photoActionSheet.addAction(UIAlertAction(title: "Take Photo", style: .default, handler: { Void in
let pickerC = UIImagePickerController()
pickerC.delegate = self
pickerC.sourceType = UIImagePickerControllerSourceType.camera
pickerC.mediaTypes = [kUTTypeImage as String]
self.present(pickerC, animated: true, completion: nil)
}))
}
if let popoverController = photoActionSheet.popoverPresentationController {
popoverController.sourceView = self.photoIconButton
popoverController.sourceRect = self.photoIconButton.bounds
}
self.present(photoActionSheet, animated: true, completion: nil)
}
//
// MARK: - UIImagePickerControllerDelegate
//
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.dismiss(animated: true, completion: nil)
print(info)
if let photoImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
//let compressedImage = NutUtils.compressImage(photoImage)
let photoUrl = NutUtils.urlForNewPhoto()
if let filePath = NutUtils.filePathForPhoto(photoUrl) {
// NOTE: we save photo with high compression, typically 0.2 to 0.4 MB
if let photoData = UIImageJPEGRepresentation(photoImage, 0.1) {
let savedOk = (try? photoData.write(to: URL(fileURLWithPath: filePath), options: [.atomic])) != nil
if !savedOk {
NSLog("Failed to save photo successfully!")
}
appendPictureUrl(photoUrl)
updateSaveButtonState()
configurePhotos()
}
}
}
}
//
// MARK: - Event updating
//
fileprivate func newEventChanged() -> Bool {
if let _ = eventGroup {
// for "eat again" new events, we already have a title and location from the NutEvent, so consider this "changed"
return true
}
if titleTextField.text != Styles.placeholderTitleString {
return true
}
if locationTextField.text != Styles.placeholderLocationString {
return true
}
if notesTextField.text != Styles.placeholderNotesString {
return true
}
if !pictureImageURLs.isEmpty {
return true
}
return false
}
fileprivate func existingEventChanged() -> Bool {
if let eventItem = eventItem {
if eventItem.title != titleTextField.text {
NSLog("title changed, enabling save")
return true
}
if eventItem.notes != notesTextField.text && notesTextField.text != Styles.placeholderNotesString {
NSLog("notes changed, enabling save")
return true
}
if eventItem.time as Date != eventTime {
NSLog("event time changed, enabling save")
return true
}
if let meal = eventItem as? NutMeal {
if meal.location != locationTextField.text && locationTextField.text != Styles.placeholderLocationString {
NSLog("location changed, enabling save")
return true
}
if meal.photo != itemToImageUrl(0) {
NSLog("photo1 changed, enabling save")
return true
}
if meal.photo2 != itemToImageUrl(1) {
NSLog("photo2 changed, enabling save")
return true
}
if meal.photo3 != itemToImageUrl(2) {
NSLog("photo3 changed, enabling save")
return true
}
}
}
return false
}
fileprivate func filteredLocationText() -> String {
var location = ""
if let locationText = locationTextField.text {
if locationText != Styles.placeholderLocationString {
location = locationText
}
}
return location
}
fileprivate func filteredNotesText() -> String {
var notes = ""
if let notesText = notesTextField.text {
if notesText != Styles.placeholderNotesString {
notes = notesText
}
}
return notes
}
fileprivate func updateCurrentEvent() {
if let mealItem = eventItem as? NutMeal {
let location = filteredLocationText()
let notes = filteredNotesText()
mealItem.title = titleTextField.text!
mealItem.time = eventTime
mealItem.notes = notes
mealItem.location = location
// first delete any photos going away...
for url in mealItem.photoUrlArray() {
if !pictureImageURLs.contains(url) {
NutUtils.deleteLocalPhoto(url)
}
}
// now update the event...
mealItem.photo = itemToImageUrl(0)
mealItem.photo2 = itemToImageUrl(1)
mealItem.photo3 = itemToImageUrl(2)
// Save the database
if mealItem.saveChanges() {
// note event changed as "new" event
newEventItem = mealItem.eventItem
updateItemAndGroupForNewEventItem()
} else {
newEventItem = nil
}
} else if let workoutItem = eventItem as? NutWorkout {
let location = filteredLocationText()
let notes = filteredNotesText()
workoutItem.title = titleTextField.text!
workoutItem.time = eventTime
workoutItem.notes = notes
workoutItem.location = location
// Save the database
if workoutItem.saveChanges() {
// note event changed as "new" event
newEventItem = workoutItem.eventItem
updateItemAndGroupForNewEventItem()
} else {
newEventItem = nil
}
}
}
var crashValue: String?
func testCrash() {
// force crash to test crash reporting...
if crashValue! == "crash" {
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
}
}
fileprivate func updateNewEvent() {
if titleTextField.text!.localizedCaseInsensitiveCompare("test mode") == ComparisonResult.orderedSame {
AppDelegate.testMode = !AppDelegate.testMode
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
}
// This is a good place to splice in demo and test data. For now, entering "demo" as the title will result in us adding a set of demo events to the model, and "delete" will delete all food events.
if titleTextField.text!.localizedCaseInsensitiveCompare("demo") == ComparisonResult.orderedSame {
DatabaseUtils.deleteAllNutEvents()
addDemoData()
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
} else if titleTextField.text!.localizedCaseInsensitiveCompare("no demo") == ComparisonResult.orderedSame {
DatabaseUtils.deleteAllNutEvents()
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
} else if titleTextField.text!.localizedCaseInsensitiveCompare("kill token") == ComparisonResult.orderedSame {
APIConnector.connector().sessionToken = "xxxx"
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
}
if titleTextField.text!.localizedCaseInsensitiveCompare("test crash") == ComparisonResult.orderedSame {
self.testCrash()
}
// Note: we only create meal events in this app - workout events come from other apps via HealthKit...
newEventItem = NutEvent.createMealEvent(titleTextField.text!, notes: filteredNotesText(), location: filteredLocationText(), photo: itemToImageUrl(0), photo2: itemToImageUrl(1), photo3: itemToImageUrl(2), time: eventTime, timeZoneOffset: eventTimeOffsetSecs)
if newEventItem != nil {
if eventGroup == nil {
APIConnector.connector().trackMetric("New Meal Added (Add Meal Screen)")
} else {
APIConnector.connector().trackMetric("New Instance of Existing Meal (Add Meal Screen)")
}
updateItemAndGroupForNewEventItem()
showSuccessView()
} else {
// TODO: handle internal error...
NSLog("Error: Failed to save new event!")
}
}
fileprivate func updateItemAndGroupForNewEventItem() {
// Update eventGroup and eventItem based on new event created, for return values to calling VC
if let eventGroup = eventGroup, let newEventItem = newEventItem {
if newEventItem.nutEventIdString() == eventGroup.nutEventIdString() {
if let currentItem = eventItem {
// if we're editing an existing item...
if currentItem.nutEventIdString() == eventGroup.nutEventIdString() {
// if title/location haven't changed, we're done...
return
}
}
self.eventItem = eventGroup.addEvent(newEventItem)
} else {
// eventGroup is no longer valid, create a new one!
self.eventGroup = NutEvent(firstEvent: newEventItem)
self.eventItem = self.eventGroup?.itemArray[0]
}
}
}
fileprivate func preExistingPhoto(_ url: String) -> Bool {
var preExisting = false
// if we are editing a current event, don't delete the photo if it already exists in the event
if let eventItem = eventItem {
preExisting = eventItem.photoUrlArray().contains(url)
}
return preExisting
}
/// Delete new photos we may have created so we don't leave them orphaned in the local file system.
fileprivate func deleteNewPhotos() {
for url in pictureImageURLs {
if !preExistingPhoto(url) {
NutUtils.deleteLocalPhoto(url)
}
}
pictureImageURLs = []
}
fileprivate func deleteItemAndReturn() {
// first delete any new photos user may have added
deleteNewPhotos()
if let eventItem = eventItem, let eventGroup = eventGroup {
if eventItem.deleteItem() {
// now remove it from the group
eventGroup.itemArray = eventGroup.itemArray.filter() {
$0 != eventItem
}
// mark it as deleted so controller we return to can handle correctly...
self.eventItem = nil
if eventGroup.itemArray.isEmpty {
self.eventGroup = nil
// segue back to home as there are no events remaining...
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
} else {
// segue back to home or group list viewer depending...
self.performSegue(withIdentifier: "unwindSegueToDoneItemDeleted", sender: self)
}
} else {
// TODO: handle delete error?
NSLog("Error: Failed to delete item!")
// segue back to home as this event probably was deleted out from under us...
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
}
}
}
//
// MARK: - Alerts
//
fileprivate func simpleInfoAlert(_ alertTitle: String, alertMessage: String) {
// use dialog to confirm cancel with user!
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("notifyAlertOkay", comment:"OK"), style: .cancel, handler: { Void in
return
}))
self.present(alert, animated: true, completion: nil)
}
fileprivate func alertOnCancelAndReturn(_ alertTitle: String, alertMessage: String, okayButtonString: String) {
// use dialog to confirm cancel with user!
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("discardAlertCancel", comment:"Cancel"), style: .cancel, handler: { Void in
if self.editExistingEvent {
APIConnector.connector().trackMetric("Clicked Cancel Cancel to Stay on Edit (Edit Screen)")
}
return
}))
alert.addAction(UIAlertAction(title: okayButtonString, style: .default, handler: { Void in
if self.editExistingEvent {
APIConnector.connector().trackMetric("Clicked Discard Changes to Cancel (Edit Screen)")
}
self.deleteNewPhotos()
self.performSegue(withIdentifier: "unwindSegueToCancel", sender: self)
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
fileprivate func alertOnDeleteAndReturn() {
if let nutItem = eventItem {
// use dialog to confirm delete with user!
var titleString = NSLocalizedString("deleteMealAlertTitle", comment:"Are you sure?")
var messageString = NSLocalizedString("deleteMealAlertMessage", comment:"If you delete this meal, it will be gone forever..")
if let _ = nutItem as? NutWorkout {
titleString = NSLocalizedString("deleteWorkoutAlertTitle", comment:"Are you sure?")
messageString = NSLocalizedString("deleteWorkoutAlertMessage", comment:"If you delete this workout, it will be gone forever.")
}
let alert = UIAlertController(title: titleString, message: messageString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("deleteAlertCancel", comment:"Cancel"), style: .cancel, handler: { Void in
APIConnector.connector().trackMetric("Clicked Cancel Discard (Edit Screen)")
return
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("deleteAlertOkay", comment:"Delete"), style: .default, handler: { Void in
APIConnector.connector().trackMetric("Clicked Confirmed Delete (Edit Screen)")
self.deleteItemAndReturn()
}))
self.present(alert, animated: true, completion: nil)
}
}
//
// MARK: - Misc private funcs
//
fileprivate func showSuccessView() {
dismissKeyboard(self)
let animations: [UIImage]? = [UIImage(named: "addAnimation-01")!,
UIImage(named: "addAnimation-02")!,
UIImage(named: "addAnimation-03")!,
UIImage(named: "addAnimation-04")!,
UIImage(named: "addAnimation-05")!,
UIImage(named: "addAnimation-06")!]
addSuccessImageView.animationImages = animations
addSuccessImageView.animationDuration = 1.0
addSuccessImageView.animationRepeatCount = 1
addSuccessImageView.startAnimating()
addSuccessView.isHidden = false
NutUtils.delay(1.25) {
if let newEventItem = self.newEventItem, let eventGroup = self.eventGroup {
if newEventItem.nutEventIdString() != eventGroup.nutEventIdString() {
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
}
}
self.performSegue(withIdentifier: "unwindSegueToDone", sender: self)
}
}
//
// MARK: - Date picking
//
fileprivate var savedTime: Date?
@IBAction func dateButtonHandler(_ sender: AnyObject) {
// user tapped on date, bring up date picker
if datePickerView.isHidden {
dismissKeyboard(self)
datePickerView.isHidden = false
savedTime = eventTime
updateSaveButtonState()
if editExistingEvent {
APIConnector.connector().trackMetric("Edited Datetime (Edit Screen)")
} else {
APIConnector.connector().trackMetric("Clicked to Update Datetime (Add Meal Screen)")
}
} else {
cancelDatePickButtonHandler(self)
}
}
@IBAction func cancelDatePickButtonHandler(_ sender: AnyObject) {
if let savedTime = savedTime {
eventTime = savedTime
}
configureDateView()
}
@IBAction func doneDatePickButtonHandler(_ sender: AnyObject) {
eventTime = datePicker.date
// Note: for new events, if the user creates a time in the past that crosses a daylight savings time zone boundary, we want to adjust the time zone offset from the local one, ASSUMING THE USER IS EDITING IN THE SAME TIME ZONE IN WHICH THEY HAD THE MEAL.
// Without this adjustment, they would create the time in the past, say at 9 pm, and return to the meal view and see it an hour different, because we show event times in the UI in the time zone offset in which the event is created.
// This is the one case we are basically allowing an event to be created in a different time zone offset from the present: if we provided a UI to allow the user to select a time zone, this might be handled more easily.
// We truly only know the actual time zone of meals when they are created and their times are not edited (well, unless they are on a plane): allowing this edit, while practical, does put in some question the actual time zone of the event! What is key is the GMT time since that is what will be used to show the meal relatively to the blood glucose and insulin events.
if !editExistingEvent {
let dstAdjust = NutUtils.dayLightSavingsAdjust(datePicker.date)
eventTimeOffsetSecs = NSCalendar.current.timeZone.secondsFromGMT() + dstAdjust
}
configureDateView()
updateSaveButtonState()
}
@IBAction func datePickerValueChanged(_ sender: AnyObject) {
eventTime = datePicker.date
updateDateLabels()
}
//
// MARK: - Test code!
//
// TODO: Move to NutshellTests!
fileprivate func addDemoData() {
let demoMeals = [
// brandon account
["Extended Bolus", "100% extended", "2015-10-30T03:03:00.000Z", "brandon", ""],
["Extended Bolus", "2% extended", "2015-10-31T08:08:00.000Z", "brandon", ""],
["Extended Bolus", "various extended", "2015-10-29T03:08:00.000Z", "brandon", ""],
["Extended Bolus", "various extended", "2015-10-28T21:00:00.000Z", "brandon", ""],
["Temp Basal", "Higher than scheduled", "2015-12-14T18:57:00.000Z", "brandon", ""],
["Temp Basal", "Shift in scheduled during temp", "2015-12-16T05:00:00.000Z", "brandon", ""],
["Interrupted Bolus", "Both regular and extended", "2015-11-17T04:00:00.000Z", "brandon", ""],
["Interrupted Bolus", "Extended, only 2%", "2015-10-11T08:00:00.000Z", "brandon", ""],
["Interrupted Bolus", "Extended, 63% delivered", "2015-10-10T04:00:00.000Z", "brandon", ""],
// larry account
["Overridden Bolus", "Suggested .15, delivered 1, suggested .2, delivered 2.5", "2015-08-15T04:47:00.000Z", "larry", ""],
["Overridden Bolus", "Suggested 1.2, overrode to .6, suggested 1.2, overrode to .8", "2015-08-09T19:14:00.000Z", "larry", ""],
["Interrupted Bolus", "3.8 delivered, 4.0 expected", "2015-08-09T11:03:21.000Z", "larry", ""],
["Interrupted Bolus", "Two 60 wizard bolus events, 1.4 (expected 6.1), 2.95", "2015-05-27T03:03:21.000Z", "larry", ""],
["Interrupted Bolus", "2.45 delivered, 2.5 expected", "2014-06-26T06:45:21.000Z", "larry", ""],
// Demo
["Three tacos", "with 15 chips & salsa", "2015-08-20T10:03:21.000Z", "238 Garrett St", "ThreeTacosDemoPic"],
["Three tacos", "after ballet", "2015-08-09T19:42:40.000Z", "238 Garrett St", "applejuicedemopic"],
["Three tacos", "Apple Juice before", "2015-07-29T04:55:27.000Z", "238 Garrett St", "applejuicedemopic"],
["Three tacos", "and horchata", "2015-07-28T14:25:21.000Z", "238 Garrett St", "applejuicedemopic"],
["CPK 5 cheese margarita", "", "2015-07-27T12:25:21.000Z", "", ""],
["Bagel & cream cheese fruit", "", "2015-07-27T16:25:21.000Z", "", ""],
["Birthday Party", "", "2015-07-26T14:25:21.000Z", "", ""],
["This is a meal with a very long title that should wrap onto multiple lines in most devices", "And these are notes about this meal, which are also very long and should certainly wrap as well. It might be more usual to see long notes!", "2015-07-26T14:25:21.000Z", "This is a long place name, something like Taco Place at 238 Garrett St, San Francisco, California", ""],
]
func addMeal(_ me: Meal, event: [String]) {
me.title = event[0]
me.notes = event[1]
if (event[2] == "") {
me.time = Date()
} else {
me.time = NutUtils.dateFromJSON(event[2])
}
me.location = event[3]
me.photo = event[4]
me.type = "meal"
me.id = ("demo" + UUID().uuidString) as NSString? // required!
me.userid = NutDataController.controller().currentUserId // required!
let now = Date()
me.createdTime = now
me.modifiedTime = now
// TODO: really should specify time zone offset in the data so we can test some time zone related issues
me.timezoneOffset = NSNumber(value: NSCalendar.current.timeZone.secondsFromGMT()/60)
}
let demoWorkouts = [
["Runs", "regular 3 mile", "2015-07-28T12:25:21.000Z", "6000"],
["Workout", "running in park", "2015-07-27T04:23:20.000Z", "2100"],
["Workout", "running around the neighborhood", "2015-07-24T02:43:20.000Z", "2100"],
["Workout", "running at Rancho San Antonio", "2015-07-21T03:53:20.000Z", "2100"],
["PE class", "some notes for this one", "2015-07-27T08:25:21.000Z", "3600"],
["Soccer Practice", "", "2015-07-25T14:25:21.000Z", "4800"],
]
func addWorkout(_ we: Workout, event: [String]) {
we.title = event[0]
we.notes = event[1]
if (event[2] == "") {
we.time = Date().addingTimeInterval(-60*60)
we.duration = NSNumber(value: (-60*60))
} else {
we.time = NutUtils.dateFromJSON(event[2])
we.duration = TimeInterval(event[3]) as NSNumber?
}
we.type = "workout"
we.id = ("demo" + UUID().uuidString) as NSString // required!
we.userid = NutDataController.controller().currentUserId // required!
let now = Date()
we.createdTime = now
we.modifiedTime = now
we.timezoneOffset = NSNumber(value: NSCalendar.current.timeZone.secondsFromGMT()/60)
}
let moc = NutDataController.controller().mocForNutEvents()!
if let entityDescription = NSEntityDescription.entity(forEntityName: "Meal", in: moc) {
for event in demoMeals {
let me = NSManagedObject(entity: entityDescription, insertInto: nil) as! Meal
addMeal(me, event: event)
moc.insert(me)
}
}
if AppDelegate.healthKitUIEnabled {
if let entityDescription = NSEntityDescription.entity(forEntityName: "Workout", in: moc) {
for event in demoWorkouts {
let we = NSManagedObject(entity: entityDescription, insertInto: nil) as! Workout
addWorkout(we, event: event)
moc.insert(we)
}
}
}
_ = DatabaseUtils.databaseSave(moc)
}
}
| bsd-2-clause | d65d8c0cb7636ff8834d0d0ab160715b | 42.249325 | 382 | 0.60768 | 5.430606 | false | false | false | false |
mrchenhao/VPNOn | VPNOnKit/VPNManager.swift | 1 | 6605 | //
// VPNManager.swift
// VPNOn
//
// Created by Lex Tang on 12/5/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import Foundation
import NetworkExtension
import CoreData
let kAppGroupIdentifier = "group.VPNOn"
final public class VPNManager
{
lazy var _manager: NEVPNManager = {
return NEVPNManager.sharedManager()!
}()
lazy var _defaults: NSUserDefaults = {
return NSUserDefaults(suiteName: kAppGroupIdentifier)!
}()
public var status: NEVPNStatus {
get {
return _manager.connection.status
}
}
public class var sharedManager : VPNManager
{
struct Static
{
static let sharedInstance : VPNManager = {
let instance = VPNManager()
instance._manager.loadFromPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
println("Failed to load preferences: \(err.localizedDescription)")
}
}
instance._manager.localizedDescription = "VPN On"
instance._manager.enabled = true
return instance
}()
}
return Static.sharedInstance
}
public func connectIPSec(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) {
// TODO: Add a tailing closure for callback.
let p = NEVPNProtocolIPSec()
p.authenticationMethod = NEVPNIKEAuthenticationMethod.None
p.useExtendedAuthentication = true
p.serverAddress = server
p.disconnectOnSleep = !alwaysOn
_manager.localizedDescription = "VPN On - \(title)"
if let grp = group {
p.localIdentifier = grp
} else {
p.localIdentifier = "VPN"
}
if let username = account {
p.username = username
}
if let password = passwordRef {
p.passwordReference = password
}
if let secret = secretRef {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret
p.sharedSecretReference = secret
}
if let certficiateData = certificate {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate
p.identityData = certficiateData
}
_manager.enabled = true
_manager.`protocol` = p
configOnDemand()
_manager.saveToPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
println("Failed to save profile: \(err.localizedDescription)")
} else {
var connectError : NSError?
self._manager.connection.startVPNTunnelAndReturnError(&connectError)
if let connectErr = connectError {
// println("Failed to start tunnel: \(connectErr.localizedDescription)")
} else {
// println("VPN tunnel started.")
}
}
}
}
public func connectIKEv2(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) {
let p = NEVPNProtocolIKEv2()
p.authenticationMethod = NEVPNIKEAuthenticationMethod.None
p.useExtendedAuthentication = true
p.serverAddress = server
p.remoteIdentifier = server
p.disconnectOnSleep = !alwaysOn
p.deadPeerDetectionRate = NEVPNIKEv2DeadPeerDetectionRate.Medium
// TODO: Add an option into config page
_manager.localizedDescription = "VPN On - \(title)"
if let grp = group {
p.localIdentifier = grp
} else {
p.localIdentifier = "VPN"
}
if let username = account {
p.username = username
}
if let password = passwordRef {
p.passwordReference = password
}
if let secret = secretRef {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret
p.sharedSecretReference = secret
}
if let certficiateData = certificate {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate
p.serverCertificateCommonName = server
p.serverCertificateIssuerCommonName = server
p.identityData = certficiateData
}
_manager.enabled = true
_manager.`protocol` = p
configOnDemand()
_manager.saveToPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
println("Failed to save profile: \(err.localizedDescription)")
} else {
var connectError : NSError?
if self._manager.connection.startVPNTunnelAndReturnError(&connectError) {
if let connectErr = connectError {
println("Failed to start IKEv2 tunnel: \(connectErr.localizedDescription)")
} else {
println("IKEv2 tunnel started.")
}
} else {
println("Failed to connect: \(connectError?.localizedDescription)")
}
}
}
}
public func configOnDemand() {
if onDemandDomainsArray.count > 0 && onDemand {
let connectionRule = NEEvaluateConnectionRule(
matchDomains: onDemandDomainsArray,
andAction: NEEvaluateConnectionRuleAction.ConnectIfNeeded
)
let ruleEvaluateConnection = NEOnDemandRuleEvaluateConnection()
ruleEvaluateConnection.connectionRules = [connectionRule]
_manager.onDemandRules = [ruleEvaluateConnection]
_manager.onDemandEnabled = true
} else {
_manager.onDemandRules = [AnyObject]()
_manager.onDemandEnabled = false
}
}
public func disconnect() {
_manager.connection.stopVPNTunnel()
}
public func removeProfile() {
_manager.removeFromPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
}
}
}
| mit | 3c67878edf38fd43529eb874b48e9f74 | 32.025 | 182 | 0.56109 | 5.659811 | false | false | false | false |
sarvex/SwiftRecepies | Data/Using Custom Data Types in Your Core Data Model/Using Custom Data Types in Your Core Data Model/ColorTransformer.swift | 1 | 1371 | //
// ColorTransformer.swift
// Using Custom Data Types in Your Core Data Model
//
// Created by vandad on 167//14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
import UIKit
class ColorTransformer: NSValueTransformer {
override class func allowsReverseTransformation() -> Bool{
return true
}
override class func transformedValueClass() -> AnyClass{
return NSData.classForCoder()
}
override func transformedValue(value: AnyObject!) -> AnyObject {
/* Transform color to data */
let color = value as! UIColor
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
var components = [red, green, blue, alpha]
let dataFromColors = NSData(bytes: components,
length: sizeofValue(components))
return dataFromColors
}
override func reverseTransformedValue(value: AnyObject!) -> AnyObject {
/* Transform data to color */
let data = value as! NSData
var components = [CGFloat](count: 4, repeatedValue: 0.0)
data.getBytes(&components, length: sizeofValue(components))
let color = UIColor(red: components[0],
green: components[1],
blue: components[2],
alpha: components[3])
return color
}
}
| isc | af55fa01660189c268fc902e261d7087 | 23.052632 | 73 | 0.648432 | 4.480392 | false | false | false | false |
jasnig/ScrollPageView | ScrollViewController/可以在初始化或者返回页面的时候设置当前页为其他页/Vc9Controller.swift | 1 | 4855 | //
// Vc9Controller.swift
// ScrollViewController
//
// Created by jasnig on 16/4/22.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class Vc9Controller: UIViewController {
var scrollPageView: ScrollPageView!
override func viewDidLoad() {
super.viewDidLoad()
// 这个是必要的设置
automaticallyAdjustsScrollViewInsets = false
var style = SegmentStyle()
// 缩放文字
style.scaleTitle = true
// 颜色渐变
style.gradualChangeTitleColor = true
// 显示滚动条
style.showLine = true
// 天使遮盖
style.showCover = true
// segment可以滚动
style.scrollTitle = true
let titles = ["国内头条", "国际要闻", "趣事", "囧图", "明星八卦", "爱车", "国防要事", "科技频道", "手机专页", "风景图", "段子"]
scrollPageView = ScrollPageView(frame: CGRect(x: 0, y: 64, width: view.bounds.size.width, height: view.bounds.size.height - 64), segmentStyle: style, titles: titles, childVcs: setChildVcs(), parentViewController: self)
// 设置默认下标
scrollPageView.selectedIndex(2, animated: true)
view.addSubview(scrollPageView)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scrollPageView.frame = CGRect(x: 0, y: 64, width: view.bounds.size.width, height: view.bounds.size.height - 64)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
print(navigationController?.interactivePopGestureRecognizer)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
print(navigationController?.interactivePopGestureRecognizer)
}
func setChildVcs() -> [UIViewController] {
let vc1 = storyboard!.instantiateViewControllerWithIdentifier("test")
let vc2 = UIViewController()
vc2.view.backgroundColor = UIColor.greenColor()
let vc3 = UIViewController()
vc3.view.backgroundColor = UIColor.redColor()
let vc4 = storyboard!.instantiateViewControllerWithIdentifier("test")
vc4.view.backgroundColor = UIColor.yellowColor()
let vc5 = UIViewController()
vc5.view.backgroundColor = UIColor.lightGrayColor()
let vc6 = UIViewController()
vc6.view.backgroundColor = UIColor.brownColor()
let vc7 = UIViewController()
vc7.view.backgroundColor = UIColor.orangeColor()
let vc8 = UIViewController()
vc8.view.backgroundColor = UIColor.blueColor()
let vc9 = UIViewController()
vc9.view.backgroundColor = UIColor.brownColor()
let vc10 = UIViewController()
vc10.view.backgroundColor = UIColor.orangeColor()
let vc11 = UIViewController()
vc11.view.backgroundColor = UIColor.blueColor()
return [vc1, vc2, vc3,vc4, vc5, vc6, vc7, vc8, vc9, vc10, vc11]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | bdc597057378496b9a55ba90956dfc81 | 35.78125 | 226 | 0.66695 | 4.588694 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS | SmartReceipts/Modules/Edit Distance/EditDistanceView.swift | 2 | 2357 | //
// EditDistanceView.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 01/06/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import UIKit
import Viperit
import RxSwift
import RxCocoa
//MARK: - Public Interface Protocol
protocol EditDistanceViewInterface {
func setup(trip: WBTrip, distance: Distance?)
}
//MARK: EditDistance View
final class EditDistanceView: UserInterface {
private var formView: EditDistanceFormView!
override func viewDidLoad() {
super.viewDidLoad()
formView = EditDistanceFormView(trip: displayData.trip!, distance: displayData.distance)
addChild(formView)
formView.view.frame = view.bounds
view.addSubview(formView.view)
setupInitialState()
}
private func setupInitialState() {
let isEdit = displayData.distance != nil
navigationItem.title = isEdit ?
LocalizedString("dialog_mileage_title_update") :
LocalizedString("dialog_mileage_title_create")
}
//MARK: Actions
@IBAction private func onSaveTap() {
let errorsDescription = formView.validate()
if errorsDescription.isEmpty {
let distance = formView!.changedDistance!
presenter.save(distance: distance, asNewDistance: displayData.distance == nil)
} else {
let title = LocalizedString("generic_error_alert_title")
let alert = UIAlertController(title: title, message: errorsDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: LocalizedString("generic_button_title_ok"), style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
}
@IBAction private func onCancelTap() {
presenter.close()
}
}
//MARK: - Public interface
extension EditDistanceView: EditDistanceViewInterface {
func setup(trip: WBTrip, distance: Distance?) {
displayData.trip = trip
displayData.distance = distance
}
}
// MARK: - VIPER COMPONENTS API (Auto-generated code)
private extension EditDistanceView {
var presenter: EditDistancePresenter {
return _presenter as! EditDistancePresenter
}
var displayData: EditDistanceDisplayData {
return _displayData as! EditDistanceDisplayData
}
}
| agpl-3.0 | fb005ac0a621362b049e7eabb913841e | 29.205128 | 123 | 0.66893 | 4.887967 | false | false | false | false |
gregomni/swift | stdlib/public/core/UIntBuffer.swift | 10 | 6397 | //===--- UIntBuffer.swift - Bounded Collection of Unsigned Integer --------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Stores a smaller unsigned integer type inside a larger one, with a limit of
// 255 elements.
//
//===----------------------------------------------------------------------===//
@frozen
public struct _UIntBuffer<Element: UnsignedInteger & FixedWidthInteger> {
public typealias Storage = UInt32
public var _storage: Storage
public var _bitCount: UInt8
@inlinable
@inline(__always)
public init(_storage: Storage, _bitCount: UInt8) {
self._storage = _storage
self._bitCount = _bitCount
}
@inlinable
@inline(__always)
public init(containing e: Element) {
_storage = Storage(truncatingIfNeeded: e)
_bitCount = UInt8(truncatingIfNeeded: Element.bitWidth)
}
}
extension _UIntBuffer: Sequence {
public typealias SubSequence = Slice<_UIntBuffer>
@frozen
public struct Iterator: IteratorProtocol, Sequence {
public var _impl: _UIntBuffer
@inlinable
@inline(__always)
public init(_ x: _UIntBuffer) { _impl = x }
@inlinable
@inline(__always)
public mutating func next() -> Element? {
if _impl._bitCount == 0 { return nil }
defer {
_impl._storage = _impl._storage &>> Element.bitWidth
_impl._bitCount = _impl._bitCount &- _impl._elementWidth
}
return Element(truncatingIfNeeded: _impl._storage)
}
}
@inlinable
@inline(__always)
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension _UIntBuffer: Collection {
@frozen
public struct Index: Comparable {
@usableFromInline
internal var bitOffset: UInt8
@inlinable
internal init(bitOffset: UInt8) { self.bitOffset = bitOffset }
@inlinable
public static func == (lhs: Index, rhs: Index) -> Bool {
return lhs.bitOffset == rhs.bitOffset
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
return lhs.bitOffset < rhs.bitOffset
}
}
@inlinable
public var startIndex: Index {
@inline(__always)
get { return Index(bitOffset: 0) }
}
@inlinable
public var endIndex: Index {
@inline(__always)
get { return Index(bitOffset: _bitCount) }
}
@inlinable
@inline(__always)
public func index(after i: Index) -> Index {
return Index(bitOffset: i.bitOffset &+ _elementWidth)
}
@inlinable
internal var _elementWidth: UInt8 {
return UInt8(truncatingIfNeeded: Element.bitWidth)
}
@inlinable
public subscript(i: Index) -> Element {
@inline(__always)
get {
return Element(truncatingIfNeeded: _storage &>> i.bitOffset)
}
}
}
extension _UIntBuffer: BidirectionalCollection {
@inlinable
@inline(__always)
public func index(before i: Index) -> Index {
return Index(bitOffset: i.bitOffset &- _elementWidth)
}
}
extension _UIntBuffer: RandomAccessCollection {
public typealias Indices = DefaultIndices<_UIntBuffer>
@inlinable
@inline(__always)
public func index(_ i: Index, offsetBy n: Int) -> Index {
let x = Int(i.bitOffset) &+ n &* Element.bitWidth
return Index(bitOffset: UInt8(truncatingIfNeeded: x))
}
@inlinable
@inline(__always)
public func distance(from i: Index, to j: Index) -> Int {
return (Int(j.bitOffset) &- Int(i.bitOffset)) / Element.bitWidth
}
}
extension FixedWidthInteger {
@inline(__always)
@inlinable
internal func _fullShiftLeft<N: FixedWidthInteger>(_ n: N) -> Self {
return (self &<< ((n &+ 1) &>> 1)) &<< (n &>> 1)
}
@inline(__always)
@inlinable
internal func _fullShiftRight<N: FixedWidthInteger>(_ n: N) -> Self {
return (self &>> ((n &+ 1) &>> 1)) &>> (n &>> 1)
}
@inline(__always)
@inlinable
internal static func _lowBits<N: FixedWidthInteger>(_ n: N) -> Self {
return ~((~0 as Self)._fullShiftLeft(n))
}
}
extension Range {
@inline(__always)
@inlinable
internal func _contains_(_ other: Range) -> Bool {
return other.clamped(to: self) == other
}
}
extension _UIntBuffer: RangeReplaceableCollection {
@inlinable
@inline(__always)
public init() {
_storage = 0
_bitCount = 0
}
@inlinable
public var capacity: Int {
return Storage.bitWidth / Element.bitWidth
}
@inlinable
@inline(__always)
public mutating func append(_ newElement: Element) {
_debugPrecondition(count + 1 <= capacity)
_storage &= ~(Storage(Element.max) &<< _bitCount)
_storage |= Storage(newElement) &<< _bitCount
_bitCount = _bitCount &+ _elementWidth
}
@inlinable
@inline(__always)
@discardableResult
public mutating func removeFirst() -> Element {
_debugPrecondition(!isEmpty)
let result = Element(truncatingIfNeeded: _storage)
_bitCount = _bitCount &- _elementWidth
_storage = _storage._fullShiftRight(_elementWidth)
return result
}
@inlinable
@inline(__always)
public mutating func replaceSubrange<C: Collection>(
_ target: Range<Index>, with replacement: C
) where C.Element == Element {
_debugPrecondition(
(0..<_bitCount)._contains_(
target.lowerBound.bitOffset..<target.upperBound.bitOffset))
let replacement1 = _UIntBuffer(replacement)
let targetCount = distance(
from: target.lowerBound, to: target.upperBound)
let growth = replacement1.count &- targetCount
_debugPrecondition(count + growth <= capacity)
let headCount = distance(from: startIndex, to: target.lowerBound)
let tailOffset = distance(from: startIndex, to: target.upperBound)
let w = Element.bitWidth
let headBits = _storage & ._lowBits(headCount &* w)
let tailBits = _storage._fullShiftRight(tailOffset &* w)
_storage = headBits
_storage |= replacement1._storage &<< (headCount &* w)
_storage |= tailBits &<< ((tailOffset &+ growth) &* w)
_bitCount = UInt8(
truncatingIfNeeded: Int(_bitCount) &+ growth &* w)
}
}
extension _UIntBuffer: Sendable where Element: Sendable { }
| apache-2.0 | 4a677ddb7a50b1b0ce28f87592dc922f | 26.337607 | 80 | 0.641863 | 4.239231 | false | false | false | false |
yingDev/QingDict | QingDict/WordbookViewController.swift | 1 | 3114 | //
// WordbookController.swift
// QingDict
//
// Created by Ying on 15/12/10.
// Copyright © 2015年 YingDev.com. All rights reserved.
//
import Cocoa
class WordbookViewController : NSObject, NSTableViewDataSource, NSTableViewDelegate
{
private let dataController = WordbookDataController()
private var entries: [WordbookEntry]!
var view: NSTableView! = nil
{
didSet
{
view.setDataSource(self)
view.setDelegate(self)
reload()
}
}
var entryDoubleClickHandler: ((WordbookEntry)->())? = nil
//kvo compatible
dynamic private(set) var entryCount: Int = 0
func containsWord(word: String) -> Bool
{
return entries == nil ? false : entries.contains({ e -> Bool in
return word == e.keyword
})
}
func addEntry(entry: WordbookEntry)
{
dataController.add(entry)
reload()
}
func removeEntry(word: String)
{
dataController.remove(word)
reload()
}
func reload()
{
entries = dataController.fetchAll()
entryCount = entries.count
view.reloadData()
}
func clearSelection()
{
if view.selectedRow >= 0
{
let lastSelectedRow = view.rowViewAtRow(view.selectedRow, makeIfNecessary: false)! as! WordbookRowView;
lastSelectedRow.txtTrans.hidden = true;
lastSelectedRow.contentView.constraints.filter({ cons in cons.identifier == "centerY" })[0].priority = 751;
lastSelectedRow.txtTittle.textColor = NSColor.darkGrayColor();
view.selectRowIndexes(NSIndexSet(), byExtendingSelection: false)
}
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int
{
return entryCount
}
func tableView(tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView?
{
let rowView = tableView.makeViewWithIdentifier("mainCell", owner: nil) as! WordbookRowView
let model = entries![row]
rowView.txtTittle.stringValue = model.keyword;
rowView.txtTrans.stringValue = model.trans == nil ? "" : model.trans!
rowView.txtTrans.hidden = true;
rowView.onSwiped = self.handleRowSwiped
rowView.onClicked = self.handleRowClicked
return rowView;
}
private func handleRowClicked(sender: WordbookRowView, clickCount: Int)
{
if clickCount == 1
{
clearSelection()
let indexes = NSIndexSet(index: view.rowForView(sender));
view.selectRowIndexes(indexes, byExtendingSelection: false);
sender.txtTrans.hidden = false;
sender.txtTittle.textColor = NSColor.blackColor()
sender.contentView.constraints.filter({ cons in cons.identifier == "centerY" })[0].priority = 749;
}else if clickCount == 2 //双击
{
let r = view.rowForView(sender)
self.entryDoubleClickHandler?(self.entries[r]);
print("double Click")
}
}
private func handleRowSwiped(sender: WordbookRowView)
{
let r = view.rowForView(sender)
let indexes = NSIndexSet(index: r);
view.removeRowsAtIndexes(indexes, withAnimation: [.EffectFade, .SlideUp])
self.dataController.remove(self.entries[r].keyword)
self.entries.removeAtIndex(r)
self.entryCount = self.entries.count
}
func selectionShouldChangeInTableView(tableView: NSTableView) -> Bool
{
return false;
}
}
| gpl-3.0 | dbffc4dc5f725893f184ba23679d2b26 | 21.845588 | 110 | 0.710975 | 3.655294 | false | false | false | false |
alvinvarghese/ScaledVisibleCellsCollectionView | ScaledVisibleCellsCollectionViewExample/Tests/Tests.swift | 3 | 1199 | // https://github.com/Quick/Quick
import Quick
import Nimble
import ScaledVisibleCellsCollectionView
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | 6e3ea518f5e52068c4fa003c0ae38e0f | 22.86 | 63 | 0.375524 | 5.548837 | false | false | false | false |
zning1994/practice | Swift学习/code4xcode6/ch11/11.7.3统一性原则-4.playground/section-1.swift | 1 | 294 |
public class Employee {
var no : Int = 0
var name : String = ""
var job : String?
var salary : Double = 0
var dept : Department?
}
struct Department {
var no : Int = 0
var name : String = ""
}
func getEmpDept(emp : Employee)-> Department? {
return emp.dept
}
| gpl-2.0 | 2034ab6afe49a21e53feab038e4ec6f7 | 16.294118 | 47 | 0.585034 | 3.542169 | false | false | false | false |
Kruks/FindViewControl | FindViewControl/FindViewControl/VIewController/FindFilterTableViewController.swift | 1 | 5188 | //
// FindFilterTableViewController.swift
// MyCity311
//
// Created by Krutika Mac Mini on 12/23/16.
// Copyright © 2016 Kahuna Systems. All rights reserved.
//
import UIKit
import MFSideMenu
@objc protocol FindFilterTableViewControllerDelegate: class {
@objc optional func filtersTableViewController(selectedFilters: [FilterObject])
}
class FindFilterTableViewController: UITableViewController {
var filterArray: [FilterObject]!
var selectedFiltersArray: [FilterObject]!
@IBOutlet weak var barButtonItem: UIBarButtonItem!
@IBOutlet weak var barButtonItem1: UIBarButtonItem!
@IBOutlet weak var selectAll: UIBarButtonItem!
@IBOutlet weak var unselectAll: UIBarButtonItem!
weak var delegate: FindFilterTableViewControllerDelegate?
@IBOutlet weak var navTitleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if (selectedFiltersArray == nil) {
selectedFiltersArray = [FilterObject]()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setToolbarHidden(false, animated: false)
self.navigationController?.toolbar.setBackgroundImage(UIImage(named: "header_bg.png"), forToolbarPosition: .bottom, barMetrics: .default)
self.navigationController?.toolbar.tintColor = UIColor.white
self.navigationController?.toolbar.barTintColor = UIColor.darkGray
self.navTitleLabel.text = "filtersNavTitle".localized
let button1 = barButtonItem!.customView as! UIButton
button1.setTitle("CancelButtonLabel".localized, for: .normal)
let button2 = barButtonItem1!.customView as! UIButton
button2.setTitle("doneBtnTitle".localized, for: .normal)
self.selectAll.title = "selectAllButtonTitle".localized
self.unselectAll.title = "unselectAllButtonTitle".localized
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filterArray.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "Cell")
let bundle = Bundle(identifier: FindConstants.findBundleID)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
let nib = bundle?.loadNibNamed("FilterCell", owner: self, options: nil)
if nib!.count > 0 {
cell = nib![0] as? UITableViewCell
}
}
let titleLabel: UILabel = cell!.viewWithTag(1) as! UILabel
let iconImage: UIImageView = cell!.viewWithTag(2) as! UIImageView
let filterType: FilterObject = self.filterArray[indexPath.row]
titleLabel.text = filterType.filterValue
if selectedFiltersArray.contains(filterType) {
iconImage.image = UIImage(named: "tick.png", in: bundle, compatibleWith: nil)
}
else {
iconImage.image = UIImage(named: "untick.png", in: bundle, compatibleWith: nil)
}
cell?.selectionStyle = UITableViewCellSelectionStyle.none
return cell!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let bundle = Bundle(identifier: FindConstants.findBundleID)
let filterType: FilterObject = self.filterArray[indexPath.row]
let cell: UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
let iconImage: UIImageView = cell.viewWithTag(2) as! UIImageView
if selectedFiltersArray.contains(filterType) {
iconImage.image = UIImage(named: "untick.png", in: bundle, compatibleWith: nil)
if let index = selectedFiltersArray.index(of: filterType) {
selectedFiltersArray.remove(at: index)
}
}
else {
iconImage.image = UIImage(named: "tick.png", in: bundle, compatibleWith: nil)
selectedFiltersArray.append(filterType)
}
}
@IBAction func selectAllClicked() {
selectedFiltersArray.removeAll()
selectedFiltersArray = [FilterObject]()
selectedFiltersArray.append(contentsOf: self.filterArray)
self.tableView.reloadData()
}
@IBAction func unselectAllClicked() {
selectedFiltersArray.removeAll()
self.tableView.reloadData()
}
@IBAction func done_button_clicked() {
self.menuContainerViewController.toggleRightSideMenuCompletion({
DispatchQueue.main.async {
self.delegate?.filtersTableViewController!(selectedFilters: self.selectedFiltersArray)
}
})
}
@IBAction func cancel_button_clicked() {
self.menuContainerViewController.toggleRightSideMenuCompletion(nil)
}
}
| mit | d655b61089e62d30406a78913c605b83 | 33.58 | 145 | 0.682668 | 5.176647 | false | false | false | false |
ricardorachaus/pingaudio | Pingaudio/Pingaudio/PAAudioManager.swift | 1 | 1490 | //
// PAAudioManager.swift
// Pingaudio
//
// Created by Rachaus on 31/05/17.
// Copyright © 2017 Rachaus. All rights reserved.
//
import AVFoundation
public class PAAudioManager: PAAudioManagerDelegate {
var exporter: PAExporter!
init() {
exporter = PAExporter()
}
public func merge(audios: [PAAudio], completion: @escaping (_ output: URL?) -> Void) {
let composition = AVMutableComposition()
var time = kCMTimeZero
for audio in audios {
let asset = AVAsset(url: audio.path)
PAAudioManager.add(asset: asset, ofType: AVMediaTypeAudio, to: composition, at: time)
time = CMTimeAdd(time, asset.duration)
}
exporter.export(composition: composition) { (output: URL?) -> Void in
if let result = output {
completion(result)
} else {
completion(nil)
}
}
}
static func add(asset: AVAsset, ofType type: String, to composition: AVMutableComposition, at time: CMTime) {
let track = composition.addMutableTrack(withMediaType: type, preferredTrackID: kCMPersistentTrackID_Invalid)
let assetTrack = asset.tracks(withMediaType: type).first!
do {
try track.insertTimeRange(CMTimeRange(start: kCMTimeZero, duration: asset.duration), of: assetTrack, at: time)
} catch _ {
print("falha ao adicionar track a composition")
}
}
}
| mit | 1518d94de2451a566ddf6186a2e4ea24 | 32.088889 | 122 | 0.611148 | 4.567485 | false | false | false | false |
buyiyang/iosstar | iOSStar/Other/AppDelegate.swift | 3 | 13935 | //
// AppDelegate.swift
// iosblackcard
//
// Created by J-bb on 17/4/13.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
import UserNotifications
import RealmSwift
import Alamofire
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate ,WXApiDelegate,GeTuiSdkDelegate,UNUserNotificationCenterDelegate{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
AppConfigHelper.shared().registerServers()
// 个推
let mediaType = AVMediaTypeVideo
AVCaptureDevice.requestAccess(forMediaType: mediaType) { (result) in
}
let videoType = AVMediaTypeAudio
AVCaptureDevice.requestAccess(forMediaType: videoType) { (result) in
}
AppConfigHelper.shared().setupGeTuiSDK(sdkDelegate: self)
UIApplication.shared.statusBarStyle = .default
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if (url.host == "safepay") {
AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: { (result) in
if let dataDic = result as? [String : AnyObject] {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.aliPay.aliPayCode), object:(Int.init((dataDic["resultStatus"] as! String))), userInfo:nil)
}
})
}else{
WXApi.handleOpen(url, delegate: self)
}
return true
}
func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
WXApi.handleOpen(url, delegate: self)
return true
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
if (url.host == "safepay") {
AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: { (result) in
if let dataDic = result as? [String : AnyObject]{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.aliPay.aliPayCode), object:(Int.init((dataDic["resultStatus"] as! String))), userInfo:nil)
}
})
}
else {
WXApi.handleOpen(url, delegate: self)
}
return true
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// 支付返回
func onResp(_ resp: BaseResp!) {
//微信登录返回
if resp.isKind(of: SendAuthResp.classForCoder()) {
let authResp:SendAuthResp = resp as! SendAuthResp
if authResp.errCode == 0{
accessToken(code: authResp.code)
}
return
}
else{
if resp.isKind(of: PayResp.classForCoder()) {
let authResp:PayResp = resp as! PayResp
NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.WechatPay.WechatKeyErrorCode), object: NSNumber.init(value: authResp.errCode), userInfo:nil)
return
}
}
}
func accessToken(code: String)
{
let param = [SocketConst.Key.appid : AppConst.WechatKey.Appid,
"code" : code,
SocketConst.Key.secret : AppConst.WechatKey.Secret,
SocketConst.Key.grant_type : "authorization_code"]
Alamofire.request(AppConst.WechatKey.AccessTokenUrl, method: .get, parameters: param).responseJSON { [weak self](result) in
if let resultJson = result.result.value as? [String: AnyObject] {
if let errCode = resultJson["errcode"] as? Int{
print(errCode)
}
if let access_token = resultJson[SocketConst.Key.accessToken] as? String {
if let openid = resultJson[SocketConst.Key.openid] as? String{
self?.wechatUserInfo(token: access_token, openid: openid)
}
}
}
}
}
func wechatUserInfo(token: String, openid: String)
{
let param = [SocketConst.Key.accessToken : token,
SocketConst.Key.openid : openid]
Alamofire.request(AppConst.WechatKey.wechetUserInfo, method: .get, parameters: param).responseJSON {(result) in
guard let resultJson = result.result.value as? [String: AnyObject] else{return}
if let errCode = resultJson["errcode"] as? Int{
print(errCode)
}
if let nickname = resultJson[SocketConst.Key.nickname] as? String {
ShareDataModel.share().wechatUserInfo[SocketConst.Key.nickname] = nickname
}
if let openid = resultJson[SocketConst.Key.openid] as? String{
ShareDataModel.share().wechatUserInfo[SocketConst.Key.openid] = openid
}
if let headimgurl = resultJson[SocketConst.Key.headimgurl] as? String{
ShareDataModel.share().wechatUserInfo[SocketConst.Key.headimgurl] = headimgurl
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.WechatKey.ErrorCode), object: nil, userInfo:nil)
}
}
// MARK: - 远程通知(推送)回调
/** 远程通知注册成功委托 */
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceToken_ns = NSData.init(data: deviceToken); // 转换成NSData类型
var token = deviceToken_ns.description.trimmingCharacters(in: CharacterSet(charactersIn: "<>"));
token = token.replacingOccurrences(of: " ", with: "")
UserDefaults.standard.setValue(token, forKey: AppConst.Text.deviceToken)
print(token)
// [ GTSdk ]:向个推服务器注册deviceToken
GeTuiSdk.registerDeviceToken(token);
// 向云信服务注册deviceToken
NIMSDK.shared().updateApnsToken(deviceToken)
}
/** 远程通知注册失败委托 */
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("\n>>>[DeviceToken Error]:%@\n\n",error.localizedDescription);
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// 唤醒
GeTuiSdk.resume()
completionHandler(UIBackgroundFetchResult.newData)
}
// MARK: - APP运行中接收到通知(推送)处理 - iOS 10 以下
/** APP已经接收到“远程”通知(推送) - (App运行在后台) */
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
application.applicationIconBadgeNumber = 0; // 标签
let vc = UIStoryboard.init(name: "Exchange", bundle: nil).instantiateViewController(withIdentifier: "SystemMessageVC")
let nav = UINavigationController.init(rootViewController: vc)
UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let vc = UIStoryboard.init(name: "Exchange", bundle: nil).instantiateViewController(withIdentifier: "SystemMessageVC")
let nav = UINavigationController.init(rootViewController: vc)
UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
// [ GTSdk ]:将收到的APNs信息传给个推统计
GeTuiSdk.handleRemoteNotification(userInfo);
NSLog("\n>>>[Receive RemoteNotification]:%@\n\n",userInfo);
completionHandler(UIBackgroundFetchResult.newData);
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("willPresentNotification: %@",notification.request.content.userInfo);
completionHandler([.badge,.sound,.alert]);
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// 此处接收到通知的userInfo
print("didReceiveNotificationResponse: %@",response.notification.request.content.userInfo);
UIApplication.shared.applicationIconBadgeNumber = 0;
// [ GTSdk ]:将收到的APNs信息传给个推统计
GeTuiSdk.handleRemoteNotification(response.notification.request.content.userInfo);
completionHandler();
}
// MARK: - GeTuiSdkDelegate
/** SDK启动成功返回cid */
func geTuiSdkDidRegisterClient(_ clientId: String!) {
// [4-EXT-1]: 个推SDK已注册,返回clientId
NSLog("\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}
/** SDK遇到错误回调 */
func geTuiSdkDidOccurError(_ error: Error!) {
// [EXT]:个推错误报告,集成步骤发生的任何错误都在这里通知,如果集成后,无法正常收到消息,查看这里的通知。
NSLog("\n>>>[GeTuiSdk error]:%@\n\n", error.localizedDescription);
}
/** SDK收到sendMessage消息回调 */
func geTuiSdkDidSendMessage(_ messageId: String!, result: Int32) {
// [4-EXT]:发送上行消息结果反馈
let msg:String = "sendmessage=\(messageId),result=\(result)";
NSLog("\n>>>[GeTuiSdk DidSendMessage]:%@\n\n",msg);
}
/** SDK收到透传消息回调 */
func geTuiSdkDidReceivePayloadData(_ payloadData: Data!, andTaskId taskId: String!, andMsgId msgId: String!, andOffLine offLine: Bool, fromGtAppId appId: String!) {
if((payloadData) != nil) {
if let msgDic = try? JSONSerialization.jsonObject(with: payloadData, options: .mutableContainers) as? NSDictionary{
if let starId = msgDic?["starId"] as? String{
if offLine{
self.geTuiPushStar(starId)
}else{
let alertView: TradingAlertView = Bundle.main.loadNibNamed("TradingAlertView", owner: nil, options: nil)?.first as! TradingAlertView
alertView.str = "有最新明星消息,请点击查看。"
alertView.showAlertView()
alertView.messageAction = {
self.geTuiPushStar(starId)
}
}
}
}
}
}
func geTuiPushStar(_ starId: String){
let param = StarRealtimeRequestModel()
param.starcode = starId
AppAPIHelper.marketAPI().requestStarRealTime(requestModel: param, complete: { (response) in
if let model = response as? StarSortListModel{
if model.pushlish_type == 0 || model.pushlish_type == 1{
if let controller = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: "SellingViewController") as? SellingViewController{
controller.starModel = model
let nav = BaseNavigationController.init(rootViewController: controller)
UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
}
}else{
if let controller = UIStoryboard.init(name: "Heat", bundle: nil).instantiateViewController(withIdentifier: "HeatDetailViewController") as? HeatDetailViewController{
let nav = BaseNavigationController.init(rootViewController: controller)
controller.starListModel = model
UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
}
}
}
}, error: nil)
}
func geTuiSdkDidAliasAction(_ action: String!, result isSuccess: Bool, sequenceNum aSn: String!, error aError: Error!) {
if action == kGtResponseBindType{
if isSuccess {
print("绑定成功")
}else{
print(aError)
}
}
}
//
}
| gpl-3.0 | 15a60e5ee184378bb1c7600ea0d0a75c | 42.387097 | 207 | 0.620446 | 5.135548 | false | false | false | false |
lllyyy/LY | U17-master/U17/Pods/Then/Sources/Then/Then.swift | 6 | 2692 | // The MIT License (MIT)
//
// Copyright (c) 2015 Suyeol Jeon (xoul.kr)
//
// 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 CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit.UIGeometry
#endif
public protocol Then {}
extension Then where Self: Any {
/// Makes it available to set properties with closures just after initializing and copying the value types.
///
/// let frame = CGRect().with {
/// $0.origin.x = 10
/// $0.size.width = 100
/// }
public func with(_ block: (inout Self) throws -> Void) rethrows -> Self {
var copy = self
try block(©)
return copy
}
/// Makes it available to execute something with closures.
///
/// UserDefaults.standard.do {
/// $0.set("devxoul", forKey: "username")
/// $0.set("[email protected]", forKey: "email")
/// $0.synchronize()
/// }
public func `do`(_ block: (Self) throws -> Void) rethrows {
try block(self)
}
}
extension Then where Self: AnyObject {
/// Makes it available to set properties with closures just after initializing.
///
/// let label = UILabel().then {
/// $0.textAlignment = .Center
/// $0.textColor = UIColor.blackColor()
/// $0.text = "Hello, World!"
/// }
public func then(_ block: (Self) throws -> Void) rethrows -> Self {
try block(self)
return self
}
}
extension NSObject: Then {}
extension CGPoint: Then {}
extension CGRect: Then {}
extension CGSize: Then {}
extension CGVector: Then {}
#if os(iOS) || os(tvOS)
extension UIEdgeInsets: Then {}
extension UIOffset: Then {}
extension UIRectEdge: Then {}
#endif
| mit | 7cf1b2423cd40a933c9576c7cc25831f | 30.670588 | 109 | 0.67422 | 4.091185 | false | false | false | false |
wchen02/Swift-2.0-learning-app | test/SearchResultsViewController.swift | 1 | 5781 | //
// SearchResultsViewController.swift
// test
//
// Created by nluo on 5/14/15.
// Copyright (c) 2015 nluo. All rights reserved.
//
import UIKit
import GoogleMobileAds
class SearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol, UISearchBarDelegate {
var api : APIController!
@IBOutlet var appsTableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var menuButton: UIBarButtonItem!
var interstitial: GADInterstitial?
var albums = [Album]()
let kCellIdentifier: String = "SearchResultCell"
var imageCache = [String:UIImage]()
override func viewDidLoad() {
print("view did load")
super.viewDidLoad()
interstitial = DFPInterstitial(adUnitID: "/6499/example/interstitial")
let request = DFPRequest()
request.testDevices = [ kGADSimulatorID ];
interstitial!.loadRequest(request)
// Do any additional setup after loading the view, typically from a nib.
api = APIController(delegate: self)
searchBar.delegate = self
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
api.searchItunesFor("Lady Gaga")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.albums.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier)!
let album: Album = self.albums[indexPath.row]
// Get the formatted price string for display in the subtitle
cell.detailTextLabel?.text = album.price
// Update the textLabel text to use the title from the Album model
cell.textLabel?.text = album.title
// Start by setting the cell's image to a static file
// Without this, we will end up without an image view!
cell.imageView?.image = UIImage(named: "Blank52")
let thumbnailURLString = album.thumbnailImageURL
let thumbnailURL = NSURL(string: thumbnailURLString)!
// If this image is already cached, don't re-download
if let img = imageCache[thumbnailURLString] {
cell.imageView?.image = img
}
else {
// The image isn't cached, download the img data
// We should perform this in a background thread
let request: NSURLRequest = NSURLRequest(URL: thumbnailURL)
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
// Convert the downloaded data in to a UIImage object
let image = UIImage(data: data!)
// Store the image in to our cache
self.imageCache[thumbnailURLString] = image
// Update the cell
dispatch_async(dispatch_get_main_queue(), {
if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cellToUpdate.imageView?.image = image
}
})
}
else {
print("Error: \(error!.localizedDescription)")
}
})
}
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1)
UIView.animateWithDuration(0.25, animations: {
cell.layer.transform = CATransform3DMakeScale(1,1,1)
})
}
func didReceiveAPIResults(results: NSArray) {
dispatch_async(dispatch_get_main_queue(), {
self.albums = Album.albumsWithJSON(results)
self.appsTableView!.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (interstitial!.isReady) {
interstitial!.presentFromRootViewController(self)
}
if let detailsViewController: DetailsViewController = segue.destinationViewController as? DetailsViewController {
let albumIndex = appsTableView!.indexPathForSelectedRow!.row
let selectedAlbum = self.albums[albumIndex]
detailsViewController.album = selectedAlbum
}
}
//func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
self.filterContentForSearchText(searchBar.text!)
}
func filterContentForSearchText(searchText: String) {
// Filter the array using the filter method
api.searchItunesFor(searchText)
}
func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
let scope = searchBar.scopeButtonTitles as [String]!
api.searchItunesFor(scope[selectedScope])
}
}
| mit | 8b2959241dd6ed44a17a96d28d93e534 | 38.868966 | 141 | 0.640028 | 5.673209 | false | false | false | false |
nahive/spotify-notify | SpotifyNotify/Models/NotificationViewModel.swift | 1 | 2201 | //
// Notification.swift
// SpotifyNotify
//
// Created by Paul Williamson on 07/03/2019.
// Copyright © 2019 Szymon Maślanka. All rights reserved.
//
import Foundation
/// A notification view model for setting up a notification
struct NotificationViewModel {
let identifier = NSUUID().uuidString
let title: String
let subtitle: String
let body: String
let artworkURL: URL?
/// Defaults to show if, for any reason, Spotify returns nil
private let unknownArtist = "Unknown Artist"
private let unknownAlbum = "Unknown Album"
private let unknownTrack = "Unknown Track"
init(track: Track, showSongProgress: Bool, songProgress: Double?) {
func progress(for track: Track) -> String {
guard let songProgress = songProgress, let duration = track.duration else {
return "00:00/00:00"
}
let percentage = songProgress / (Double(duration) / 1000.0)
let progressMax = 14
let currentProgress = Int(Double(progressMax) * percentage)
let progressString = "▪︎".repeated(currentProgress) + "⁃".repeated(progressMax - currentProgress)
let now = Int(songProgress).minutesSeconds
let length = (duration / 1000).minutesSeconds
let nowS = "\(now.minutes)".withLeadingZeroes + ":" + "\(now.seconds)".withLeadingZeroes
let lengthS = "\(length.minutes)".withLeadingZeroes + ":" + "\(length.seconds)".withLeadingZeroes
return "\(nowS) \(progressString) \(lengthS)"
}
let name = track.name ?? unknownTrack
let artist = track.artist ?? unknownArtist
let album = track.album ?? unknownAlbum
title = name
subtitle = showSongProgress ? "\(artist) - \(album)" : artist
body = showSongProgress ? progress(for: track) : album
artworkURL = track.artworkURL
}
}
private extension Int {
var minutesSeconds: (minutes: Int, seconds: Int) {
((self % 3600) / 60, (self % 3600) % 60)
}
}
private extension String {
func repeated(_ count: Int) -> String {
String(repeating: self, count: count)
}
}
| unlicense | 66c0263dea296821bebbf777bbd34a1c | 31.25 | 110 | 0.622891 | 4.421371 | false | false | false | false |
ben-ng/swift | test/SILGen/init_ref_delegation.swift | 1 | 8663 | // RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
struct X { }
// Initializer delegation within a struct.
struct S {
// CHECK-LABEL: sil hidden @_TFV19init_ref_delegation1SC{{.*}} : $@convention(method) (@thin S.Type) -> S {
init() {
// CHECK: bb0([[SELF_META:%[0-9]+]] : $@thin S.Type):
// CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <S>
// CHECK-NEXT: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*S
// CHECK: [[S_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1SC{{.*}} : $@convention(method) (X, @thin S.Type) -> S
// CHECK: [[X_CTOR:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X
// CHECK-NEXT: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK-NEXT: [[X:%[0-9]+]] = apply [[X_CTOR]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK-NEXT: [[REPLACEMENT_SELF:%[0-9]+]] = apply [[S_DELEG_INIT]]([[X]], [[SELF_META]]) : $@convention(method) (X, @thin S.Type) -> S
self.init(x: X())
// CHECK-NEXT: assign [[REPLACEMENT_SELF]] to [[SELF]] : $*S
// CHECK-NEXT: [[SELF_BOX1:%[0-9]+]] = load [trivial] [[SELF]] : $*S
// CHECK-NEXT: destroy_value [[SELF_BOX]] : $<τ_0_0> { var τ_0_0 } <S>
// CHECK-NEXT: return [[SELF_BOX1]] : $S
}
init(x: X) { }
}
// Initializer delegation within an enum
enum E {
// We don't want the enum to be uninhabited
case Foo
// CHECK-LABEL: sil hidden @_TFO19init_ref_delegation1EC{{.*}} : $@convention(method) (@thin E.Type) -> E
init() {
// CHECK: bb0([[E_META:%[0-9]+]] : $@thin E.Type):
// CHECK: [[E_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <E>
// CHECK: [[PB:%.*]] = project_box [[E_BOX]]
// CHECK: [[E_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*E
// CHECK: [[X_INIT:%[0-9]+]] = function_ref @_TFO19init_ref_delegation1EC{{.*}} : $@convention(method) (X, @thin E.Type) -> E
// CHECK: [[E_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK: [[X:%[0-9]+]] = apply [[E_DELEG_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK: [[S:%[0-9]+]] = apply [[X_INIT]]([[X]], [[E_META]]) : $@convention(method) (X, @thin E.Type) -> E
// CHECK: assign [[S:%[0-9]+]] to [[E_SELF]] : $*E
// CHECK: [[E_BOX1:%[0-9]+]] = load [trivial] [[E_SELF]] : $*E
self.init(x: X())
// CHECK: destroy_value [[E_BOX]] : $<τ_0_0> { var τ_0_0 } <E>
// CHECK: return [[E_BOX1:%[0-9]+]] : $E
}
init(x: X) { }
}
// Initializer delegation to a generic initializer
struct S2 {
// CHECK-LABEL: sil hidden @_TFV19init_ref_delegation2S2C{{.*}} : $@convention(method) (@thin S2.Type) -> S2
init() {
// CHECK: bb0([[S2_META:%[0-9]+]] : $@thin S2.Type):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <S2>
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*S2
// CHECK: [[S2_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation2S2C{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2
// CHECK: [[X_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X_BOX:%[0-9]+]] = alloc_stack $X
// CHECK: store [[X]] to [trivial] [[X_BOX]] : $*X
// CHECK: [[SELF_BOX1:%[0-9]+]] = apply [[S2_DELEG_INIT]]<X>([[X_BOX]], [[S2_META]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2
// CHECK: assign [[SELF_BOX1]] to [[SELF]] : $*S2
// CHECK: dealloc_stack [[X_BOX]] : $*X
// CHECK: [[SELF_BOX4:%[0-9]+]] = load [trivial] [[SELF]] : $*S2
self.init(t: X())
// CHECK: destroy_value [[SELF_BOX]] : $<τ_0_0> { var τ_0_0 } <S2>
// CHECK: return [[SELF_BOX4]] : $S2
}
init<T>(t: T) { }
}
class C1 {
var ivar: X
// CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C1c{{.*}} : $@convention(method) (X, @owned C1) -> @owned C1
convenience init(x: X) {
// CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C1):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <C1>
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*C1
// CHECK: store [[ORIG_SELF]] to [init] [[SELF]] : $*C1
// CHECK: [[SELF_FROM_BOX:%[0-9]+]] = load_borrow [[SELF]] : $*C1
// CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_FROM_BOX]] : $C1, #C1.init!initializer.1 : (C1.Type) -> (X, X) -> C1 , $@convention(method) (X, X, @owned C1) -> @owned C1
// CHECK: [[SELFP:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF_FROM_BOX]]) : $@convention(method) (X, X, @owned C1) -> @owned C1
// CHECK: store [[SELFP]] to [init] [[SELF]] : $*C1
// CHECK: [[SELFP:%[0-9]+]] = load [copy] [[SELF]] : $*C1
// CHECK: destroy_value [[SELF_BOX]] : $<τ_0_0> { var τ_0_0 } <C1>
// CHECK: return [[SELFP]] : $C1
self.init(x1: x, x2: x)
}
init(x1: X, x2: X) { ivar = x1 }
}
@objc class C2 {
var ivar: X
// CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C2c{{.*}} : $@convention(method) (X, @owned C2) -> @owned C2
convenience init(x: X) {
// CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C2):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <C2>
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*C2
// CHECK: store [[ORIG_SELF]] to [init] [[UNINIT_SELF]] : $*C2
// SEMANTIC ARC TODO: Another case of us doing a borrow and passing
// something in @owned. I think we will need some special help for
// definite-initialization.
// CHECK: [[SELF:%[0-9]+]] = load_borrow [[UNINIT_SELF]] : $*C2
// CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF]] : $C2, #C2.init!initializer.1 : (C2.Type) -> (X, X) -> C2 , $@convention(method) (X, X, @owned C2) -> @owned C2
// CHECK: [[REPLACE_SELF:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF]]) : $@convention(method) (X, X, @owned C2) -> @owned C2
// CHECK: store [[REPLACE_SELF]] to [init] [[UNINIT_SELF]] : $*C2
// CHECK: [[VAR_15:%[0-9]+]] = load [copy] [[UNINIT_SELF]] : $*C2
// CHECK: destroy_value [[SELF_BOX]] : $<τ_0_0> { var τ_0_0 } <C2>
// CHECK: return [[VAR_15]] : $C2
self.init(x1: x, x2: x)
// CHECK-NOT: sil hidden @_TToFC19init_ref_delegation2C2c{{.*}} : $@convention(objc_method) (X, @owned C2) -> @owned C2 {
}
// CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C2C{{.*}} : $@convention(method) (X, X, @thick C2.Type) -> @owned C2 {
// CHECK-NOT: sil @_TToFC19init_ref_delegation2C2c{{.*}} : $@convention(objc_method) (X, X, @owned C2) -> @owned C2 {
init(x1: X, x2: X) { ivar = x1 }
}
var x: X = X()
class C3 {
var i: Int = 5
// CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C3c{{.*}} : $@convention(method) (@owned C3) -> @owned C3
convenience init() {
// CHECK: mark_uninitialized [delegatingself]
// CHECK-NOT: integer_literal
// CHECK: class_method [[SELF:%[0-9]+]] : $C3, #C3.init!initializer.1 : (C3.Type) -> (X) -> C3 , $@convention(method) (X, @owned C3) -> @owned C3
// CHECK-NOT: integer_literal
// CHECK: return
self.init(x: x)
}
init(x: X) { }
}
// Initializer delegation from a constructor defined in an extension.
class C4 { }
extension C4 {
convenience init(x1: X) {
self.init()
}
// CHECK: sil hidden @_TFC19init_ref_delegation2C4c{{.*}}
// CHECK: [[PEER:%[0-9]+]] = function_ref @_TFC19init_ref_delegation2C4c{{.*}}
// CHECK: apply [[PEER]]([[X:%[0-9]+]], [[OBJ:%[0-9]+]])
convenience init(x2: X) {
self.init(x1: x2)
}
}
// Initializer delegation to a constructor defined in a protocol extension.
protocol Pb {
init()
}
extension Pb {
init(d: Int) { }
}
class Sn : Pb {
required init() { }
convenience init(d3: Int) {
self.init(d: d3)
}
}
// Same as above but for a value type.
struct Cs : Pb {
init() { }
init(d3: Int) {
self.init(d: d3)
}
}
| apache-2.0 | 61760af7277e7092013aa4ed4bc4f609 | 41.767327 | 183 | 0.533742 | 2.749523 | false | false | false | false |
adrfer/swift | test/decl/inherit/inherit.swift | 18 | 1297 | // RUN: %target-parse-verify-swift
class A { }
protocol P { }
// Duplicate inheritance
class B : A, A { } // expected-error{{duplicate inheritance from 'A'}}{{12-15=}}
// Duplicate inheritance from protocol
class B2 : P, P { } // expected-error{{duplicate inheritance from 'P'}}{{13-16=}}
// Multiple inheritance
class C : B, A { } // expected-error{{multiple inheritance from classes 'B' and 'A'}}
// Superclass in the wrong position
class D : P, A { } // expected-error{{superclass 'A' must appear first in the inheritance clause}}{{12-15=}}{{11-11=A, }}
// Struct inheriting a class
struct S : A { } // expected-error{{non-class type 'S' cannot inherit from class 'A'}}
// Protocol inheriting a class
protocol Q : A { } // expected-error{{non-class type 'Q' cannot inherit from class 'A'}}
// Extension inheriting a class
extension C : A { } // expected-error{{extension of type 'C' cannot inherit from class 'A'}}
class GenericBase<T> {}
class GenericSub<T> : GenericBase<T> {} // okay
class InheritGenericParam<T> : T {} // expected-error {{inheritance from non-protocol, non-class type 'T'}}
class InheritBody : T { // expected-error {{use of undeclared type 'T'}}
typealias T = A
}
class InheritBodyBad : fn { // expected-error {{use of undeclared type 'fn'}}
func fn() {}
}
| apache-2.0 | 29a3773f8da97d666413ca0bb4cbb5fc | 33.131579 | 121 | 0.673092 | 3.553425 | false | false | false | false |
YasumasaSewake/cssButton | cssButton/cssButton.swift | 1 | 5536 | //
// cssButton.swift
// cssButton
//
// Created by sewakeyasumasa on 2016/05/01.
// Copyright © 2016年 Yasumasa Sewake. All rights reserved.
//
import Foundation
import UIKit
class cssButton : UIButton
{
private static let speed : CGFloat = 0.1
var annimationLayer : AnimationLayer = AnimationLayer()
var bottomLayer : BotLayer = BotLayer()
var _direction : Direction = .None
var _progress : CGFloat = 0
var _buttonStyle : Style = .FadeIn
var defaultColor : RGBA = RGBA( r:0.0, g:0.0, b:0.0, a:0.0)
private var _displayLink : CADisplayLink? = nil
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
self.layer.insertSublayer(annimationLayer, atIndex:1)
self.layer.insertSublayer(bottomLayer, atIndex:0)
// ここをコメントアウトして動かすとおおよそがわかるかも
self.layer.masksToBounds = true
// 基準の色として保存
self.titleLabel!.textColor!.getRed(&defaultColor.r, green:&defaultColor.g, blue:&defaultColor.b, alpha:&defaultColor.a)
_initDisplayLink()
}
override func layoutSubviews() {
super.layoutSubviews()
annimationLayer.frame = self.bounds
bottomLayer.frame = self.bounds
// 回転の時に必要(この処理がないと文字色が更新されなくなる)
self.setNeedsDisplay()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if nil != touches.first?.locationInView(self)
{
_transition( Direction.Normal )
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if nil != touches.first?.locationInView(self)
{
_transition( Direction.Reverse )
}
}
override func drawRect(rect: CGRect)
{
super.drawRect(rect)
// タイトルカラーを変える
// ベースの色の調整
let p : CGFloat = _calcProgress(_progress)
let baseRgb : RGBA = RGBA(r:self.defaultColor.r - (self.defaultColor.r * p),
g:self.defaultColor.g - (self.defaultColor.g * p),
b:self.defaultColor.b - (self.defaultColor.b * p),
a:1)
let rgb : RGBA = self._getTextColor()
let goalRgb : RGBA = RGBA(r:rgb.r - (rgb.r * (1 - p)),
g:rgb.g - (rgb.g * (1 - p)),
b:rgb.b - (rgb.b * (1 - p)),
a:1)
let fixColor : UIColor = UIColor(red:baseRgb.r + goalRgb.r, green:baseRgb.g + goalRgb.g, blue:baseRgb.b + goalRgb.b, alpha:1)
self.titleLabel?.textColor = fixColor
}
func _getTextColor() -> RGBA
{
switch ( _buttonStyle )
{
case .FadeIn:
return ColorMap.white
case .FadeIn_Border:
return ColorMap.blue
case .Split_Vertical:
return ColorMap.blue
case .Split_Horizontal:
return ColorMap.blue
case .Slide_Upper:
return ColorMap.white
case .Slide_UpperLeft:
return ColorMap.white
case .Zoom:
return ColorMap.white
case .Spin:
return ColorMap.white
}
}
func _transition( direction : Direction )
{
self._direction = direction
_startDisplayLink()
}
func buttonStyle( style : Style )
{
_buttonStyle = style
annimationLayer.buttonStyle(style)
bottomLayer.buttonStyle(style)
}
//MARK:DisplayLink
private func _initDisplayLink()
{
self._displayLink = CADisplayLink.init(target:self, selector:#selector(cssButton._displayRefresh(_:)))
self._displayLink?.frameInterval = 1
self._displayLink?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode:NSRunLoopCommonModes)
self._displayLink?.paused = true
}
private func _startDisplayLink()
{
self._displayLink?.paused = false
}
private func _stopDisplayLink()
{
self._displayLink?.paused = true
}
@objc private func _displayRefresh(displayLink:CADisplayLink)
{
var stop : Bool = false
if self._direction == .Normal
{
_progress += cssButton.speed
if _progress >= 1.0
{
_progress = 1.0
stop = true
}
}
else if self._direction == .Reverse
{
_progress -= cssButton.speed
if _progress <= 0.0
{
_progress = 0.0
stop = true
}
}
self.bottomLayer.progress = _progress
self.annimationLayer.progress = _calcProgress(_progress)
self.annimationLayer.setNeedsDisplay()
self.setNeedsDisplay()
switch ( _buttonStyle )
{
case .Split_Vertical:
bottomLayer.setNeedsDisplay()
case .Split_Horizontal:
bottomLayer.setNeedsDisplay()
case .Slide_Upper:
bottomLayer.setNeedsDisplay()
case .Slide_UpperLeft:
bottomLayer.setNeedsDisplay()
case .Zoom:
bottomLayer.setNeedsDisplay()
case .Spin:
bottomLayer.setNeedsDisplay()
default:
break;
}
if stop == true
{
_stopDisplayLink()
}
}
func _calcProgress( x : CGFloat ) -> CGFloat
{
let x1 : CGFloat = 0
let y1 : CGFloat = 0
let x2 : CGFloat = 0.4
let y2 : CGFloat = 0.7
let x3 : CGFloat = 1
let y3 : CGFloat = 1
let a : CGFloat = ((y1 - y2) * (x1 - x3) - (y1 - y3) * (x1 - x2)) / ((x1 - x2) * (x1 - x3) * (x2 - x3))
let b : CGFloat = (y1 - y2) / (x1 - x2) - a * (x1 + x2);
let c : CGFloat = y1 - a * x1 * x1 - b * x1;
let y : CGFloat = a * (x * x) + b * x + c
return y
}
} | mit | fe1e44c47025e98bbf41d8f21262885f | 23.737327 | 129 | 0.598845 | 3.774262 | false | false | false | false |
KrishMunot/swift | test/Constraints/members.swift | 1 | 14892 | // RUN: %target-parse-verify-swift
import Swift
////
// Members of structs
////
struct X {
func f0(_ i: Int) -> X { }
func f1(_ i: Int) { }
mutating func f1(_ f: Float) { }
func f2<T>(_ x: T) -> T { }
}
struct Y<T> {
func f0(_: T) -> T {}
func f1<U>(_ x: U, y: T) -> (T, U) {}
}
var i : Int
var x : X
var yf : Y<Float>
func g0(_: (inout X) -> (Float) -> ()) {}
x.f0(i)
x.f0(i).f1(i)
g0(X.f1)
x.f0(x.f2(1))
x.f0(1).f2(i)
yf.f0(1)
yf.f1(i, y: 1)
// Members referenced from inside the struct
struct Z {
var i : Int
func getI() -> Int { return i }
mutating func incI() {}
func curried(_ x: Int) -> (Int) -> Int { return { y in x + y } }
subscript (k : Int) -> Int {
get {
return i + k
}
mutating
set {
i -= k
}
}
}
struct GZ<T> {
var i : T
func getI() -> T { return i }
func f1<U>(_ a: T, b: U) -> (T, U) {
return (a, b)
}
func f2() {
var f : Float
var t = f1(i, b: f)
f = t.1
var zi = Z.i; // expected-error{{instance member 'i' cannot be used on type 'Z'}}
var zj = Z.asdfasdf // expected-error {{type 'Z' has no member 'asdfasdf'}}
}
}
var z = Z(i: 0)
var getI = z.getI
var incI = z.incI // expected-error{{partial application of 'mutating'}}
var zi = z.getI()
var zcurried1 = z.curried
var zcurried2 = z.curried(0)
var zcurriedFull = z.curried(0)(1)
////
// Members of modules
////
// Module
Swift.print(3, terminator: "")
var format : String
format._splitFirstIf({ $0.isASCII })
////
// Unqualified references
////
////
// Members of literals
////
// FIXME: Crappy diagnostic
"foo".lower() // expected-error{{value of type 'String' has no member 'lower'}}
var tmp = "foo".debugDescription
////
// Members of enums
////
enum W {
case Omega
func foo(_ x: Int) {}
func curried(_ x: Int) -> (Int) -> () {}
}
var w = W.Omega
var foo = w.foo
var fooFull : () = w.foo(0)
var wcurried1 = w.curried
var wcurried2 = w.curried(0)
var wcurriedFull : () = w.curried(0)(1)
// Member of enum Type
func enumMetatypeMember(_ opt: Int?) {
opt.none // expected-error{{static member 'none' cannot be used on instance of type 'Int?'}}
}
////
// Nested types
////
// Reference a Type member. <rdar://problem/15034920>
class G<T> {
class In { // expected-error{{nested in generic type}}
class func foo() {}
}
}
func goo() {
G<Int>.In.foo()
}
////
// Members of archetypes
////
func id<T>(_ t: T) -> T { return t }
func doGetLogicValue<T : Boolean>(_ t: T) {
t.boolValue
}
protocol P {
init()
func bar(_ x: Int)
mutating func mut(_ x: Int)
static func tum()
}
extension P {
func returnSelfInstance() -> Self {
return self
}
func returnSelfOptionalInstance(_ b: Bool) -> Self? {
return b ? self : nil
}
func returnSelfIUOInstance(_ b: Bool) -> Self! {
return b ? self : nil
}
static func returnSelfStatic() -> Self {
return Self()
}
static func returnSelfOptionalStatic(_ b: Bool) -> Self? {
return b ? Self() : nil
}
static func returnSelfIUOStatic(_ b: Bool) -> Self! {
return b ? Self() : nil
}
}
protocol ClassP : class {
func bas(_ x: Int)
}
func generic<T: P>(_ t: T) {
var t = t
// Instance member of archetype
let _: Int -> () = id(t.bar)
let _: () = id(t.bar(0))
// Static member of archetype metatype
let _: () -> () = id(T.tum)
// Instance member of archetype metatype
let _: T -> Int -> () = id(T.bar)
let _: Int -> () = id(T.bar(t))
_ = t.mut // expected-error{{partial application of 'mutating' method is not allowed}}
_ = t.tum // expected-error{{static member 'tum' cannot be used on instance of type 'T'}}
// Instance member of extension returning Self)
let _: T -> () -> T = id(T.returnSelfInstance)
let _: () -> T = id(T.returnSelfInstance(t))
let _: T = id(T.returnSelfInstance(t)())
let _: () -> T = id(t.returnSelfInstance)
let _: T = id(t.returnSelfInstance())
let _: T -> Bool -> T? = id(T.returnSelfOptionalInstance)
let _: Bool -> T? = id(T.returnSelfOptionalInstance(t))
let _: T? = id(T.returnSelfOptionalInstance(t)(false))
let _: Bool -> T? = id(t.returnSelfOptionalInstance)
let _: T? = id(t.returnSelfOptionalInstance(true))
let _: T -> Bool -> T! = id(T.returnSelfIUOInstance)
let _: Bool -> T! = id(T.returnSelfIUOInstance(t))
let _: T! = id(T.returnSelfIUOInstance(t)(true))
let _: Bool -> T! = id(t.returnSelfIUOInstance)
let _: T! = id(t.returnSelfIUOInstance(true))
// Static member of extension returning Self)
let _: () -> T = id(T.returnSelfStatic)
let _: T = id(T.returnSelfStatic())
let _: Bool -> T? = id(T.returnSelfOptionalStatic)
let _: T? = id(T.returnSelfOptionalStatic(false))
let _: Bool -> T! = id(T.returnSelfIUOStatic)
let _: T! = id(T.returnSelfIUOStatic(true))
}
func genericClassP<T: ClassP>(_ t: T) {
// Instance member of archetype)
let _: Int -> () = id(t.bas)
let _: () = id(t.bas(0))
// Instance member of archetype metatype)
let _: T -> Int -> () = id(T.bas)
let _: Int -> () = id(T.bas(t))
let _: () = id(T.bas(t)(1))
}
////
// Members of existentials
////
func existential(_ p: P) {
var p = p
// Fully applied mutating method
p.mut(1)
_ = p.mut // expected-error{{partial application of 'mutating' method is not allowed}}
// Instance member of existential)
let _: Int -> () = id(p.bar)
let _: () = id(p.bar(0))
// Static member of existential metatype)
let _: () -> () = id(p.dynamicType.tum)
// Instance member of extension returning Self
let _: () -> P = id(p.returnSelfInstance)
let _: P = id(p.returnSelfInstance())
let _: P? = id(p.returnSelfOptionalInstance(true))
let _: P! = id(p.returnSelfIUOInstance(true))
}
func staticExistential(_ p: P.Type, pp: P.Protocol) {
let ppp: P = p.init()
_ = pp.init() // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}}
_ = P() // expected-error{{protocol type 'P' cannot be instantiated}}
// Instance member of metatype
let _: P -> Int -> () = P.bar
let _: Int -> () = P.bar(ppp)
P.bar(ppp)(5)
// Instance member of metatype value
let _: P -> Int -> () = pp.bar
let _: Int -> () = pp.bar(ppp)
pp.bar(ppp)(5)
// Static member of existential metatype value
let _: () -> () = p.tum
// Instance member of existential metatype -- not allowed
_ = p.bar // expected-error{{instance member 'bar' cannot be used on type 'P'}}
_ = p.mut // expected-error{{instance member 'mut' cannot be used on type 'P'}}
// Static member of metatype -- not allowed
_ = pp.tum // expected-error{{static member 'tum' cannot be used on instance of type 'P.Protocol'}}
_ = P.tum // expected-error{{static member 'tum' cannot be used on instance of type 'P.Protocol'}}
// Static member of extension returning Self)
let _: () -> P = id(p.returnSelfStatic)
let _: P = id(p.returnSelfStatic())
let _: Bool -> P? = id(p.returnSelfOptionalStatic)
let _: P? = id(p.returnSelfOptionalStatic(false))
let _: Bool -> P! = id(p.returnSelfIUOStatic)
let _: P! = id(p.returnSelfIUOStatic(true))
}
func existentialClassP(_ p: ClassP) {
// Instance member of existential)
let _: Int -> () = id(p.bas)
let _: () = id(p.bas(0))
// Instance member of existential metatype)
let _: ClassP -> Int -> () = id(ClassP.bas)
let _: Int -> () = id(ClassP.bas(p))
let _: () = id(ClassP.bas(p)(1))
}
// Partial application of curried protocol methods
protocol Scalar {}
protocol Vector {
func scale(_ c: Scalar) -> Self
}
protocol Functional {
func apply(_ v: Vector) -> Scalar
}
protocol Coalgebra {
func coproduct(_ f: Functional) -> (v1: Vector, v2: Vector) -> Scalar
}
// Make sure existential is closed early when we partially apply
func wrap<T>(_ t: T) -> T {
return t
}
func exercise(_ c: Coalgebra, f: Functional, v: Vector) {
let _: (Vector, Vector) -> Scalar = wrap(c.coproduct(f))
let _: Scalar -> Vector = v.scale
}
// Make sure existential isn't closed too late
protocol Copyable {
func copy() -> Self
}
func copyTwice(_ c: Copyable) -> Copyable {
return c.copy().copy()
}
////
// Misc ambiguities
////
// <rdar://problem/15537772>
struct DefaultArgs {
static func f(_ a: Int = 0) -> DefaultArgs {
return DefaultArgs()
}
init() {
self = .f()
}
}
class InstanceOrClassMethod {
func method() -> Bool { return true }
class func method(_ other: InstanceOrClassMethod) -> Bool { return false }
}
func testPreferClassMethodToCurriedInstanceMethod(_ obj: InstanceOrClassMethod) {
let result = InstanceOrClassMethod.method(obj)
let _: Bool = result // no-warning
let _: () -> Bool = InstanceOrClassMethod.method(obj)
}
protocol Numeric {
func +(x: Self, y: Self) -> Self
}
func acceptBinaryFunc<T>(_ x: T, _ fn: (T, T) -> T) { }
func testNumeric<T : Numeric>(_ x: T) {
acceptBinaryFunc(x, +)
}
/* FIXME: We can't check this directly, but it can happen with
multiple modules.
class PropertyOrMethod {
func member() -> Int { return 0 }
let member = false
class func methodOnClass(_ obj: PropertyOrMethod) -> Int { return 0 }
let methodOnClass = false
}
func testPreferPropertyToMethod(_ obj: PropertyOrMethod) {
let result = obj.member
let resultChecked: Bool = result
let called = obj.member()
let calledChecked: Int = called
let curried = obj.member as () -> Int
let methodOnClass = PropertyOrMethod.methodOnClass
let methodOnClassChecked: (PropertyOrMethod) -> Int = methodOnClass
}
*/
struct Foo { var foo: Int }
protocol ExtendedWithMutatingMethods { }
extension ExtendedWithMutatingMethods {
mutating func mutatingMethod() {}
var mutableProperty: Foo {
get { }
set { }
}
var nonmutatingProperty: Foo {
get { }
nonmutating set { }
}
var mutatingGetProperty: Foo {
mutating get { }
set { }
}
}
class ClassExtendedWithMutatingMethods: ExtendedWithMutatingMethods {}
class SubclassExtendedWithMutatingMethods: ClassExtendedWithMutatingMethods {}
func testClassExtendedWithMutatingMethods(_ c: ClassExtendedWithMutatingMethods, // expected-note* {{}}
sub: SubclassExtendedWithMutatingMethods) { // expected-note* {{}}
c.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'c' is a 'let' constant}}
c.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
c.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
c.nonmutatingProperty = Foo(foo: 0)
c.nonmutatingProperty.foo = 0
c.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
c.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = c.mutableProperty
_ = c.mutableProperty.foo
_ = c.nonmutatingProperty
_ = c.nonmutatingProperty.foo
// FIXME: diagnostic nondeterministically says "member" or "getter"
_ = c.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = c.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
sub.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'sub' is a 'let' constant}}
sub.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
sub.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
sub.nonmutatingProperty = Foo(foo: 0)
sub.nonmutatingProperty.foo = 0
sub.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
sub.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = sub.mutableProperty
_ = sub.mutableProperty.foo
_ = sub.nonmutatingProperty
_ = sub.nonmutatingProperty.foo
_ = sub.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = sub.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
var mutableC = c
mutableC.mutatingMethod()
mutableC.mutableProperty = Foo(foo: 0)
mutableC.mutableProperty.foo = 0
mutableC.nonmutatingProperty = Foo(foo: 0)
mutableC.nonmutatingProperty.foo = 0
mutableC.mutatingGetProperty = Foo(foo: 0)
mutableC.mutatingGetProperty.foo = 0
_ = mutableC.mutableProperty
_ = mutableC.mutableProperty.foo
_ = mutableC.nonmutatingProperty
_ = mutableC.nonmutatingProperty.foo
_ = mutableC.mutatingGetProperty
_ = mutableC.mutatingGetProperty.foo
var mutableSub = sub
mutableSub.mutatingMethod()
mutableSub.mutableProperty = Foo(foo: 0)
mutableSub.mutableProperty.foo = 0
mutableSub.nonmutatingProperty = Foo(foo: 0)
mutableSub.nonmutatingProperty.foo = 0
_ = mutableSub.mutableProperty
_ = mutableSub.mutableProperty.foo
_ = mutableSub.nonmutatingProperty
_ = mutableSub.nonmutatingProperty.foo
_ = mutableSub.mutatingGetProperty
_ = mutableSub.mutatingGetProperty.foo
}
// <rdar://problem/18879585> QoI: error message for attempted access to instance properties in static methods are bad.
enum LedModules: Int {
case WS2811_1x_5V
}
extension LedModules {
static var watts: Double {
return [0.30][self.rawValue] // expected-error {{instance member 'rawValue' cannot be used on type 'LedModules'}}
}
}
// <rdar://problem/15117741> QoI: calling a static function on an instance produces a non-helpful diagnostic
class r15117741S {
static func g() {}
}
func test15117741(_ s: r15117741S) {
s.g() // expected-error {{static member 'g' cannot be used on instance of type 'r15117741S'}}
}
// <rdar://problem/22491394> References to unavailable decls sometimes diagnosed as ambiguous
struct UnavailMember {
@available(*, unavailable)
static var XYZ : X { get {} } // expected-note {{'XYZ' has been explicitly marked unavailable here}}
}
let _ : [UnavailMember] = [.XYZ] // expected-error {{'XYZ' is unavailable}}
let _ : [UnavailMember] = [.ABC] // expected-error {{type 'UnavailMember' has no member 'ABC'}}
// <rdar://problem/22490787> QoI: Poor error message iterating over property with non-sequence type that defines an Iterator type alias
struct S22490787 {
typealias Iterator = AnyIterator<Int>
}
func f22490787() {
var path: S22490787 = S22490787()
for p in path { // expected-error {{type 'S22490787' does not conform to protocol 'Sequence'}}
}
}
// <rdar://problem/23942743> [QoI] Bad diagnostic when errors inside enum constructor
enum r23942743 {
case Tomato(cloud: String)
}
let _ = .Tomato(cloud: .none) // expected-error {{reference to member 'Tomato' cannot be resolved without a contextual type}}
// SR-650: REGRESSION: Assertion failed: (baseTy && "Couldn't find appropriate context"), function getMemberSubstitutions
enum SomeErrorType {
case StandaloneError
case UnderlyingError(String)
static func someErrorFromString(_ str: String) -> SomeErrorType? {
if str == "standalone" { return .StandaloneError }
if str == "underlying" { return .UnderlyingError } // expected-error {{contextual member 'UnderlyingError' expects argument of type 'String'}}
return nil
}
}
| apache-2.0 | 7ba329f0e661146221e2d7c13c1c8efe | 25.832432 | 147 | 0.652431 | 3.582391 | false | false | false | false |
tensorflow/swift-models | Models/Text/WordSeg/SemiRing.swift | 1 | 4029 | // Copyright 2020 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.
import _Differentiation
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
import Darwin
#elseif os(Windows)
#if canImport(CRT)
import CRT
#else
import MSVCRT
#endif
#else
import Glibc
#endif
/// Returns a single tensor containing the log of the sum of the exponentials
/// in `x`.
///
/// Used for numerical stability when dealing with very small values.
@differentiable
public func logSumExp(_ x: [Float]) -> Float {
if x.count == 0 { return -Float.infinity}
let maxVal = x.max()!
let exps = x.map { exp($0 - maxVal) }
return maxVal + log(exps.reduce(into: 0, +=))
}
@derivative(of: logSumExp)
public func vjpLogSumExp(_ x: [Float]) -> (
value: Float,
pullback: (Float) -> (Array<Float>.TangentVector)
) {
func pb(v: Float) -> (Array<Float>.TangentVector) {
if x.count == 0 { return Array<Float>.TangentVector([]) }
let maxVal = x.max()!
let exps = x.map { exp($0 - maxVal) }
let sumExp = exps.reduce(into: 0, +=)
return Array<Float>.TangentVector(exps.map{ v * $0 / sumExp })
}
return (logSumExp(x), pb)
}
/// Returns a single tensor containing the log of the sum of the exponentials
/// in `lhs` and `rhs`.
///
/// Used for numerical stability when dealing with very small values.
@differentiable
public func logSumExp(_ lhs: Float, _ rhs: Float) -> Float {
return logSumExp([lhs, rhs])
}
/// A storage mechanism for scoring inside a lattice.
public struct SemiRing: Differentiable {
/// The log likelihood.
public var logp: Float
/// The regularization factor.
public var logr: Float
/// Creates an instance with log likelihood `logp` and regularization
/// factor `logr`.
@differentiable
public init(logp: Float, logr: Float) {
self.logp = logp
self.logr = logr
}
/// The baseline score of zero.
static var zero: SemiRing { SemiRing(logp: -Float.infinity, logr: -Float.infinity) }
/// The baseline score of one.
static var one: SemiRing { SemiRing(logp: 0.0, logr: -Float.infinity) }
}
/// Multiplies `lhs` by `rhs`.
///
/// Since scores are on a logarithmic scale, products become sums.
@differentiable
func * (_ lhs: SemiRing, _ rhs: SemiRing) -> SemiRing {
return SemiRing(
logp: lhs.logp + rhs.logp,
logr: logSumExp(lhs.logp + rhs.logr, rhs.logp + lhs.logr))
}
/// Sums `lhs` by `rhs`.
@differentiable
func + (_ lhs: SemiRing, _ rhs: SemiRing) -> SemiRing {
return SemiRing(
logp: logSumExp(lhs.logp, rhs.logp),
logr: logSumExp(lhs.logr, rhs.logr))
}
extension Array where Element == SemiRing {
/// Returns a sum of all scores in the collection.
@differentiable
func sum() -> SemiRing {
return SemiRing(
logp: logSumExp(differentiableMap { $0.logp }),
logr: logSumExp(differentiableMap { $0.logr }))
}
}
extension SemiRing {
/// The plain text description of this instance with score details.
var shortDescription: String {
"(\(logp), \(logr))"
}
}
extension SemiRing {
/// Returns true when `self` is within `tolerance` of `other`.
///
/// - Note: This behavior is modeled after SE-0259.
// TODO(abdulras) see if we can use ulp as a default tolerance
@inlinable
public func isAlmostEqual(to other: Self, tolerance: Float) -> Bool {
let diffP = abs(self.logp - other.logp)
let diffR = abs(self.logp - other.logp)
return (diffP <= tolerance || diffP.isNaN)
&& (diffR <= tolerance || diffR.isNaN)
}
}
| apache-2.0 | fbe69ec48be207ab49bee5a8d4cac205 | 27.778571 | 86 | 0.672375 | 3.672744 | false | false | false | false |
Baichenghui/TestCode | 16-计步器OneHourWalker-master/OneHourWalker/TimerViewController.swift | 1 | 5128 | //
// TimerViewController.swift
// OneHourWalker
//
// Created by Matthew Maher on 2/18/16.
// Copyright © 2016 Matt Maher. All rights reserved.
//
import UIKit
import CoreLocation
import HealthKit
class TimerViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var milesLabel: UILabel!
@IBOutlet weak var heightLabel: UILabel!
var zeroTime = NSTimeInterval()
var timer : NSTimer = NSTimer()
let locationManager = CLLocationManager()
var startLocation: CLLocation!
var lastLocation: CLLocation!
var distanceTraveled = 0.0
let healthManager:HealthKitManager = HealthKitManager()
var height: HKQuantitySample?
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
} else {
print("Need to Enable Location")
}
// We cannot access the user's HealthKit data without specific permission.
getHealthKitPermission()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getHealthKitPermission() {
// Seek authorization in HealthKitManager.swift.
healthManager.authorizeHealthKit { (authorized, error) -> Void in
if authorized {
// Get and set the user's height.
self.setHeight()
} else {
if error != nil {
print(error)
}
print("Permission denied.")
}
}
}
@IBAction func startTimer(sender: AnyObject) {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
zeroTime = NSDate.timeIntervalSinceReferenceDate()
distanceTraveled = 0.0
startLocation = nil
lastLocation = nil
locationManager.startUpdatingLocation()
}
@IBAction func stopTimer(sender: AnyObject) {
timer.invalidate()
locationManager.stopUpdatingLocation()
}
func updateTime() {
let currentTime = NSDate.timeIntervalSinceReferenceDate()
var timePassed: NSTimeInterval = currentTime - zeroTime
let minutes = UInt8(timePassed / 60.0)
timePassed -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(timePassed)
timePassed -= NSTimeInterval(seconds)
let millisecsX10 = UInt8(timePassed * 100)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strMSX10 = String(format: "%02d", millisecsX10)
timerLabel.text = "\(strMinutes):\(strSeconds):\(strMSX10)"
if timerLabel.text == "60:00:00" {
timer.invalidate()
locationManager.stopUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if startLocation == nil {
startLocation = locations.first as CLLocation!
} else {
let lastDistance = lastLocation.distanceFromLocation(locations.last as CLLocation!)
distanceTraveled += lastDistance * 0.000621371
let trimmedDistance = String(format: "%.2f", distanceTraveled)
milesLabel.text = "\(trimmedDistance) Miles"
}
lastLocation = locations.last as CLLocation!
}
func setHeight() {
// Create the HKSample for Height.
let heightSample = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
// Call HealthKitManager's getSample() method to get the user's height.
self.healthManager.getHeight(heightSample!, completion: { (userHeight, error) -> Void in
if( error != nil ) {
print("Error: \(error.localizedDescription)")
return
}
var heightString = ""
self.height = userHeight as? HKQuantitySample
// The height is formatted to the user's locale.
if let meters = self.height?.quantity.doubleValueForUnit(HKUnit.meterUnit()) {
let formatHeight = NSLengthFormatter()
formatHeight.forPersonHeightUse = true
heightString = formatHeight.stringFromMeters(meters)
}
// Set the label to reflect the user's height.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.heightLabel.text = heightString
})
})
}
@IBAction func share(sender: AnyObject) {
healthManager.saveDistance(distanceTraveled, date: NSDate())
}
}
| mit | 1497897b13ae79b7726bd7b9aab26658 | 32.077419 | 138 | 0.600741 | 5.652701 | false | false | false | false |
Raizlabs/RIGImageGallery | RIGImageGalleryTests/TestingExtensions.swift | 1 | 997 | //
// TestingExtensions.swift
// RIGImageGallery
//
// Created by Michael Skiba on 7/12/16.
// Copyright © 2016 Raizlabs. All rights reserved.
//
import UIKit
extension CGSize {
static let wide = CGSize(width: 1920, height: 1080)
static let tall = CGSize(width: 480, height: 720)
static let smallWide = CGSize(width: 480, height: 270)
static let smallTall = CGSize(width: 207, height: 368)
}
extension UIImage {
static var allGenerics: [UIImage] {
return [UIImage.genericImage(.wide), UIImage.genericImage(.tall), UIImage.genericImage(.smallWide), UIImage.genericImage(.smallTall)]
}
static func genericImage(_ size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, true, 0)
let fillPath = UIBezierPath(rect: CGRect(origin: CGPoint(), size: size))
fillPath.fill()
let genericImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return genericImage!
}
}
| mit | bb02e81d8490b054ca9c09baa51516de | 28.294118 | 141 | 0.689759 | 4.274678 | false | false | false | false |
programersun/HiChongSwift | HiChongSwift/SquareCommentViewController.swift | 1 | 6971 | //
// SquareCommentViewController.swift
// HiChongSwift
//
// Created by eagle on 14/12/15.
// Copyright (c) 2014年 Duostec. All rights reserved.
//
import UIKit
class SquareCommentViewController: UITableViewController {
var businessID: String?
var businessName: String?
weak var delegate: SquareCommentDelegate?
private var cellOnceToken: dispatch_once_t = 0
private weak var starCell: SquareAddStarCell?
private weak var icyTextView: UITextView?
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()
self.tableView.hideExtraSeprator()
self.tableView.backgroundColor = UIColor.LCYThemeColor()
self.title = "评价"
if businessID == nil {
alert("无法加载商家信息,请退回重试")
} else {
// 添加一个确定按钮
self.addRightButton("确定", action: "rightButtonPressed:")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func rightButtonPressed(sender: AnyObject) {
if let textView = icyTextView {
if count(textView.text) == 0 {
alert("请填写评论内容")
return
} else {
if let starCell = starCell {
if let scoreText = starCell.scoreLabel.text {
let parameter: [String: String] = [
"user_id": LCYCommon.sharedInstance.userName!,
"business_id": businessID!,
"content": textView.text,
"score": scoreText
]
LCYNetworking.sharedInstance.POST(LCYApi.SquareCommentAdd, parameters: parameter, success: { [weak self](object) -> Void in
if let result = object["result"] as? NSNumber {
if result.boolValue {
self?.alertWithDelegate("评论成功", tag: 2001, delegate: self)
} else {
self?.alert("评论失败")
}
} else {
self?.alert("评论解析失败")
}
return
}, failure: { [weak self](error) -> Void in
self?.alert("网络连接异常,请检查网络状态")
return
})
} else {
// 这条语句应该不会执行
alert("请打分,丷丷")
}
} else {
alert("内部错误,无法加载评论分数,请尝试重新打开评论页面")
}
}
} else {
alert("内部错误,无法加载评论内容,请尝试重新打开评论页面")
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return 3
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell!
switch indexPath.row {
case 0:
cell = tableView.dequeueReusableCellWithIdentifier("title") as! UITableViewCell
dispatch_once(&cellOnceToken)
{ () -> Void in
cell.textLabel?.textColor = UIColor.whiteColor()
cell.backgroundColor = UIColor.LCYThemeColor()
return
}
if let name = businessName {
cell.textLabel?.text = name
} else {
cell.textLabel?.textColor = UIColor.lightGrayColor()
cell.textLabel?.text = "未能获取商家名称"
}
case 1:
cell = tableView.dequeueReusableCellWithIdentifier(SquareAddStarCell.identifier()) as! SquareAddStarCell
let cell = cell as! SquareAddStarCell
self.starCell = cell
case 2:
cell = tableView.dequeueReusableCellWithIdentifier(SquareAddCommentCell.identifier()) as! UITableViewCell
let cell = cell as! SquareAddCommentCell
icyTextView = cell.icyTextView
default:
break
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch indexPath.row {
case 0:
return 44.0
case 1:
return 44.0
case 2:
return 170.0
default:
return 44.0
}
}
}
extension SquareCommentViewController: UIGestureRecognizerDelegate {
@IBAction func panGestureHandler(sender: UIPanGestureRecognizer) {
let xInView = sender.locationInView(sender.view).x
if (xInView < 14.0) || (xInView > 180.0) {
return
}
if xInView > 144.0 {
self.starCell?.imageWidth = 144.0
} else {
self.starCell?.imageWidth = xInView
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
let xInView = touch.locationInView(gestureRecognizer.view).x
if (xInView < 14.0) || (xInView > 180.0) {
if xInView < 14.0 {
self.starCell?.imageWidth = 16.0
}
return true
}
if xInView > 144.0 {
self.starCell?.imageWidth = 144.0
} else {
self.starCell?.imageWidth = xInView
}
return true
}
}
extension SquareCommentViewController: UIAlertViewDelegate {
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if alertView.tag == 2001 {
delegate?.squareDidAddComment()
navigationController?.popViewControllerAnimated(true)
}
}
}
protocol SquareCommentDelegate: class {
func squareDidAddComment()
}
| apache-2.0 | a0d2881dcb0aab26096fc66ab0022a53 | 32.495 | 147 | 0.531273 | 5.424291 | false | false | false | false |
Mattmlm/codepathtwitter | Codepath Twitter/Codepath Twitter/TweetDateFormatter.swift | 1 | 850 | //
// TweetDateFormatter.swift
// Codepath Twitter
//
// Created by admin on 10/2/15.
// Copyright © 2015 mattmo. All rights reserved.
//
import UIKit
class TweetDateFormatter : NSObject {
class var sharedInstance : NSDateFormatter {
struct Static {
static var token : dispatch_once_t = 0
static var instance : NSDateFormatter? = nil
}
dispatch_once(&Static.token) {
Static.instance = NSDateFormatter()
Static.instance!.dateFormat = "EEE MMM d HH:mm:ss Z y"
}
return Static.instance!
}
class func setDateFormatterForInterpretingJSON() {
sharedInstance.dateFormat = "EEE MMM d HH:mm:ss Z y"
}
class func setDateFormatterForTweetDetails() {
sharedInstance.dateFormat = "M/d/yy, h:mm a"
}
} | mit | 3b0dea548bb66e072229d10407d6f40b | 24.757576 | 66 | 0.606596 | 4.287879 | false | false | false | false |
rdlester/simply-giphy | Pods/ReactiveSwift/Sources/Observer.swift | 1 | 2740 | //
// Observer.swift
// ReactiveSwift
//
// Created by Andy Matuschak on 10/2/15.
// Copyright © 2015 GitHub. All rights reserved.
//
/// A protocol for type-constrained extensions of `Observer`.
@available(*, deprecated, message: "The protocol will be removed in a future version of ReactiveSwift. Use Observer directly.")
public protocol ObserverProtocol {
associatedtype Value
associatedtype Error: Swift.Error
/// Puts a `value` event into `self`.
func send(value: Value)
/// Puts a failed event into `self`.
func send(error: Error)
/// Puts a `completed` event into `self`.
func sendCompleted()
/// Puts an `interrupted` event into `self`.
func sendInterrupted()
}
/// An Observer is a simple wrapper around a function which can receive Events
/// (typically from a Signal).
public final class Observer<Value, Error: Swift.Error> {
public typealias Action = (Event<Value, Error>) -> Void
/// An action that will be performed upon arrival of the event.
public let action: Action
/// An initializer that accepts a closure accepting an event for the
/// observer.
///
/// - parameters:
/// - action: A closure to lift over received event.
public init(_ action: @escaping Action) {
self.action = action
}
/// An initializer that accepts closures for different event types.
///
/// - parameters:
/// - value: Optional closure executed when a `value` event is observed.
/// - failed: Optional closure that accepts an `Error` parameter when a
/// failed event is observed.
/// - completed: Optional closure executed when a `completed` event is
/// observed.
/// - interruped: Optional closure executed when an `interrupted` event is
/// observed.
public convenience init(
value: ((Value) -> Void)? = nil,
failed: ((Error) -> Void)? = nil,
completed: (() -> Void)? = nil,
interrupted: (() -> Void)? = nil
) {
self.init { event in
switch event {
case let .value(v):
value?(v)
case let .failed(error):
failed?(error)
case .completed:
completed?()
case .interrupted:
interrupted?()
}
}
}
/// Puts a `value` event into `self`.
///
/// - parameters:
/// - value: A value sent with the `value` event.
public func send(value: Value) {
action(.value(value))
}
/// Puts a failed event into `self`.
///
/// - parameters:
/// - error: An error object sent with failed event.
public func send(error: Error) {
action(.failed(error))
}
/// Puts a `completed` event into `self`.
public func sendCompleted() {
action(.completed)
}
/// Puts an `interrupted` event into `self`.
public func sendInterrupted() {
action(.interrupted)
}
}
extension Observer: ObserverProtocol {}
| apache-2.0 | 08aba31c3b2bf95f6bbc68185cfe63c8 | 25.085714 | 127 | 0.656444 | 3.63745 | false | false | false | false |
apple/swift-nio | IntegrationTests/tests_04_performance/test_01_resources/test_1000_copying_circularbuffer_to_array.swift | 1 | 805 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
func run(identifier: String) {
let data = CircularBuffer(repeating: UInt8(0xfe), count: 1024)
measure(identifier: identifier) {
var count = 0
for _ in 0..<1_000 {
let copy = Array(data)
count &+= copy.count
}
return count
}
}
| apache-2.0 | 82b38db7d4140c7ced6ee9f26eba0d27 | 26.758621 | 80 | 0.515528 | 4.878788 | false | false | false | false |
kjantzer/FolioReaderKit | Source/FolioReaderAudioPlayer.swift | 1 | 16544 | //
// FolioReaderAudioPlayer.swift
// FolioReaderKit
//
// Created by Kevin Jantzer on 1/4/16.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
public class FolioReaderAudioPlayer: NSObject {
var isTextToSpeech = false
var synthesizer: AVSpeechSynthesizer!
var playing = false
var player: AVAudioPlayer?
var currentHref: String!
var currentFragment: String!
var currentSmilFile: FRSmilFile!
var currentAudioFile: String!
var currentBeginTime: Double!
var currentEndTime: Double!
var playingTimer: NSTimer!
var registeredCommands = false
var completionHandler: () -> Void = {}
var utteranceRate: Float = 0
// MARK: Init
override init() {
super.init()
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
// this is needed to the audio can play even when the "silent/vibrate" toggle is on
let session:AVAudioSession = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayback)
try! session.setActive(true)
updateNowPlayingInfo()
}
deinit {
UIApplication.sharedApplication().endReceivingRemoteControlEvents()
}
// MARK: Reading speed
func setRate(rate: Int) {
if let player = player {
switch rate {
case 0:
player.rate = 0.5
break
case 1:
player.rate = 1.0
break
case 2:
player.rate = 1.5
break
case 3:
player.rate = 2
break
default:
break
}
updateNowPlayingInfo()
}
if synthesizer != nil {
// Need to change between version IOS
// http://stackoverflow.com/questions/32761786/ios9-avspeechutterance-rate-for-avspeechsynthesizer-issue
if #available(iOS 9, *) {
switch rate {
case 0:
utteranceRate = 0.42
break
case 1:
utteranceRate = 0.5
break
case 2:
utteranceRate = 0.53
break
case 3:
utteranceRate = 0.56
break
default:
break
}
} else {
switch rate {
case 0:
utteranceRate = 0
break
case 1:
utteranceRate = 0.06
break
case 2:
utteranceRate = 0.15
break
case 3:
utteranceRate = 0.23
break
default:
break
}
}
updateNowPlayingInfo()
}
}
// MARK: Play, Pause, Stop controls
func stop(immediate immediate: Bool = false) {
playing = false
if !isTextToSpeech {
if let player = player where player.playing {
player.stop()
}
} else {
stopSynthesizer(immediate: immediate, completion: nil)
}
// UIApplication.sharedApplication().idleTimerDisabled = false
}
func stopSynthesizer(immediate immediate: Bool = false, completion: (() -> Void)? = nil) {
synthesizer.stopSpeakingAtBoundary(immediate ? .Immediate : .Word)
completion?()
}
func pause() {
playing = false
if !isTextToSpeech {
if let player = player where player.playing {
player.pause()
}
} else {
if synthesizer.speaking {
synthesizer.pauseSpeakingAtBoundary(.Word)
}
}
// UIApplication.sharedApplication().idleTimerDisabled = false
}
func togglePlay() {
isPlaying() ? pause() : play()
}
func play() {
if book.hasAudio() {
guard let currentPage = FolioReader.sharedInstance.readerCenter.currentPage else { return }
currentPage.webView.js("playAudio()")
} else {
readCurrentSentence()
}
// UIApplication.sharedApplication().idleTimerDisabled = true
}
func isPlaying() -> Bool {
return playing
}
/**
Play Audio (href/fragmentID)
Begins to play audio for the given chapter (href) and text fragment.
If this chapter does not have audio, it will delay for a second, then attempt to play the next chapter
*/
func playAudio(href: String, fragmentID: String) {
isTextToSpeech = false
stop()
let smilFile = book.smilFileForHref(href)
// if no smil file for this href and the same href is being requested, we've hit the end. stop playing
if smilFile == nil && currentHref != nil && href == currentHref {
return
}
playing = true
currentHref = href
currentFragment = "#"+fragmentID
currentSmilFile = smilFile
// if no smil file, delay for a second, then move on to the next chapter
if smilFile == nil {
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(_autoPlayNextChapter), userInfo: nil, repeats: false)
return
}
let fragment = smilFile.parallelAudioForFragment(currentFragment)
if fragment != nil {
if _playFragment(fragment) {
startPlayerTimer()
}
}
}
func _autoPlayNextChapter() {
// if user has stopped playing, dont play the next chapter
if isPlaying() == false { return }
playNextChapter()
}
func playPrevChapter() {
stopPlayerTimer()
// Wait for "currentPage" to update, then request to play audio
FolioReader.sharedInstance.readerCenter.changePageToPrevious {
if self.isPlaying() {
self.play()
} else {
self.pause()
}
}
}
func playNextChapter() {
stopPlayerTimer()
// Wait for "currentPage" to update, then request to play audio
FolioReader.sharedInstance.readerCenter.changePageToNext {
if self.isPlaying() {
self.play()
}
}
}
/**
Play Fragment of audio
Once an audio fragment begins playing, the audio clip will continue playing until the player timer detects
the audio is out of the fragment timeframe.
*/
private func _playFragment(smil: FRSmilElement!) -> Bool {
if smil == nil {
print("no more parallel audio to play")
stop()
return false
}
let textFragment = smil.textElement().attributes["src"]
let audioFile = smil.audioElement().attributes["src"]
currentBeginTime = smil.clipBegin()
currentEndTime = smil.clipEnd()
// new audio file to play, create the audio player
if player == nil || (audioFile != nil && audioFile != currentAudioFile) {
currentAudioFile = audioFile
let fileURL = currentSmilFile.resource.basePath().stringByAppendingString("/"+audioFile!)
let audioData = NSData(contentsOfFile: fileURL)
do {
player = try AVAudioPlayer(data: audioData!)
guard let player = player else { return false }
setRate(FolioReader.currentAudioRate)
player.enableRate = true
player.prepareToPlay()
player.delegate = self
updateNowPlayingInfo()
} catch {
print("could not read audio file:", audioFile)
return false
}
}
// if player is initialized properly, begin playing
guard let player = player else { return false }
// the audio may be playing already, so only set the player time if it is NOT already within the fragment timeframe
// this is done to mitigate milisecond skips in the audio when changing fragments
if player.currentTime < currentBeginTime || ( currentEndTime > 0 && player.currentTime > currentEndTime) {
player.currentTime = currentBeginTime;
updateNowPlayingInfo()
}
player.play()
// get the fragment ID so we can "mark" it in the webview
let textParts = textFragment!.componentsSeparatedByString("#")
let fragmentID = textParts[1];
FolioReader.sharedInstance.readerCenter.audioMark(href: currentHref, fragmentID: fragmentID)
return true
}
/**
Next Audio Fragment
Gets the next audio fragment in the current smil file, or moves on to the next smil file
*/
private func nextAudioFragment() -> FRSmilElement! {
let smilFile = book.smilFileForHref(currentHref)
if smilFile == nil { return nil }
let smil = currentFragment == nil ? smilFile.parallelAudioForFragment(nil) : smilFile.nextParallelAudioForFragment(currentFragment)
if smil != nil {
currentFragment = smil.textElement().attributes["src"]
return smil
}
currentHref = book.spine.nextChapter(currentHref)!.href
currentFragment = nil
currentSmilFile = smilFile
if currentHref == nil {
return nil
}
return nextAudioFragment()
}
func playText(href: String, text: String) {
isTextToSpeech = true
playing = true
currentHref = href
if synthesizer == nil {
synthesizer = AVSpeechSynthesizer()
synthesizer.delegate = self
setRate(FolioReader.currentAudioRate)
}
let utterance = AVSpeechUtterance(string: text)
utterance.rate = utteranceRate
utterance.voice = AVSpeechSynthesisVoice(language: book.metadata.language)
if synthesizer.speaking {
stopSynthesizer()
}
synthesizer.speakUtterance(utterance)
updateNowPlayingInfo()
}
// MARK: TTS Sentence
func speakSentence() {
guard let currentPage = FolioReader.sharedInstance.readerCenter.currentPage else { return }
let sentence = currentPage.webView.js("getSentenceWithIndex('\(book.playbackActiveClass())')")
if sentence != nil {
let chapter = FolioReader.sharedInstance.readerCenter.getCurrentChapter()
let href = chapter != nil ? chapter!.href : "";
playText(href, text: sentence!)
} else {
if FolioReader.sharedInstance.readerCenter.isLastPage() {
stop()
} else {
FolioReader.sharedInstance.readerCenter.changePageToNext()
}
}
}
func readCurrentSentence() {
guard synthesizer != nil else { return speakSentence() }
if synthesizer.paused {
playing = true
synthesizer.continueSpeaking()
} else {
if synthesizer.speaking {
stopSynthesizer(immediate: false, completion: {
if let currentPage = FolioReader.sharedInstance.readerCenter.currentPage {
currentPage.webView.js("resetCurrentSentenceIndex()")
}
self.speakSentence()
})
} else {
speakSentence()
}
}
}
// MARK: - Audio timing events
private func startPlayerTimer() {
// we must add the timer in this mode in order for it to continue working even when the user is scrolling a webview
playingTimer = NSTimer(timeInterval: 0.01, target: self, selector: #selector(playerTimerObserver), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(playingTimer, forMode: NSRunLoopCommonModes)
}
private func stopPlayerTimer() {
if playingTimer != nil {
playingTimer.invalidate()
playingTimer = nil
}
}
func playerTimerObserver() {
guard let player = player else { return }
if currentEndTime != nil && currentEndTime > 0 && player.currentTime > currentEndTime {
_playFragment(nextAudioFragment())
}
}
// MARK: - Now Playing Info and Controls
/**
Update Now Playing info
Gets the book and audio information and updates on Now Playing Center
*/
func updateNowPlayingInfo() {
var songInfo = [String: AnyObject]()
// Get book Artwork
if let coverImage = book.coverImage, let artwork = UIImage(contentsOfFile: coverImage.fullHref) {
let albumArt = MPMediaItemArtwork(image: artwork)
songInfo[MPMediaItemPropertyArtwork] = albumArt
}
// Get book title
if let title = book.title() {
songInfo[MPMediaItemPropertyAlbumTitle] = title
}
// Get chapter name
if let chapter = getCurrentChapterName() {
songInfo[MPMediaItemPropertyTitle] = chapter
}
// Get author name
if let author = book.metadata.creators.first {
songInfo[MPMediaItemPropertyArtist] = author.name
}
// Set player times
if let player = player where !isTextToSpeech {
songInfo[MPMediaItemPropertyPlaybackDuration] = player.duration
songInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
songInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime ] = player.currentTime
}
// Set Audio Player info
MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = songInfo
registerCommandsIfNeeded()
}
/**
Get Current Chapter Name
This is done here and not in ReaderCenter because even though `currentHref` is accurate,
the `currentPage` in ReaderCenter may not have updated just yet
*/
func getCurrentChapterName() -> String? {
guard let chapter = FolioReader.sharedInstance.readerCenter.getCurrentChapter() else {
return nil
}
currentHref = chapter.href
for item in book.flatTableOfContents {
if let resource = item.resource where resource.href == currentHref {
return item.title
}
}
return nil
}
/**
Register commands if needed, check if it's registered to avoid register twice.
*/
func registerCommandsIfNeeded() {
guard !registeredCommands else { return }
let command = MPRemoteCommandCenter.sharedCommandCenter()
command.previousTrackCommand.enabled = true
command.previousTrackCommand.addTarget(self, action: #selector(playPrevChapter))
command.nextTrackCommand.enabled = true
command.nextTrackCommand.addTarget(self, action: #selector(playNextChapter))
command.pauseCommand.enabled = true
command.pauseCommand.addTarget(self, action: #selector(pause))
command.playCommand.enabled = true
command.playCommand.addTarget(self, action: #selector(play))
command.togglePlayPauseCommand.enabled = true
command.togglePlayPauseCommand.addTarget(self, action: #selector(togglePlay))
registeredCommands = true
}
}
// MARK: AVSpeechSynthesizerDelegate
extension FolioReaderAudioPlayer: AVSpeechSynthesizerDelegate {
public func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didCancelSpeechUtterance utterance: AVSpeechUtterance) {
completionHandler()
}
public func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didFinishSpeechUtterance utterance: AVSpeechUtterance) {
if isPlaying() {
readCurrentSentence()
}
}
}
// MARK: AVAudioPlayerDelegate
extension FolioReaderAudioPlayer: AVAudioPlayerDelegate {
public func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
_playFragment(nextAudioFragment())
}
} | bsd-3-clause | 6d1d677091d84319d4f8f0b601f794f0 | 30.634799 | 141 | 0.580754 | 5.625298 | false | false | false | false |
scihant/CTShowcase | Example/Example/ViewController.swift | 1 | 882 | //
// ViewController.swift
// CTShowcase
//
// Created by Cihan Tek on 17/12/15.
// Copyright © 2015 Cihan Tek. All rights reserved.
//
import UIKit
import CTShowcase
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
override func viewDidAppear(_ animated: Bool) {
let showcase = CTShowcaseView(title: "New Feature!", message: "Here's a brand new button you can tap!", key: nil) { () -> Void in
print("dismissed")
}
let highlighter = CTDynamicGlowHighlighter()
highlighter.highlightColor = UIColor.yellow
highlighter.animDuration = 0.5
highlighter.glowSize = 5
highlighter.maxOffset = 10
showcase.highlighter = highlighter
showcase.setup(for: self.button, offset: CGPoint.zero, margin: 0)
showcase.show()
}
}
| mit | 5f7cd965d405f3018ff51839817b9b90 | 25.69697 | 137 | 0.632236 | 4.449495 | false | false | false | false |
milseman/swift | test/SILGen/opaque_ownership.swift | 4 | 4974 | // RUN: %target-swift-frontend -enable-sil-opaque-values -enable-sil-ownership -emit-sorted-sil -Xllvm -sil-full-demangle -emit-silgen -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s
public protocol UnkeyedDecodingContainer {
var isAtEnd: Builtin.Int1 { get }
}
public protocol Decoder {
func unkeyedContainer() throws -> UnkeyedDecodingContainer
}
// Test open_existential_value ownership
// ---
// CHECK-LABEL: sil @_T0s11takeDecoderBi1_s0B0_p4from_tKF : $@convention(thin) (@in Decoder) -> (Builtin.Int1, @error Builtin.NativeObject) {
// CHECK: bb0(%0 : @owned $Decoder):
// CHECK: [[BORROW1:%.*]] = begin_borrow %0 : $Decoder
// CHECK: [[OPENED:%.*]] = open_existential_value [[BORROW1]] : $Decoder to $@opened("{{.*}}") Decoder
// CHECK: [[WT:%.*]] = witness_method $@opened("{{.*}}") Decoder, #Decoder.unkeyedContainer!1 : <Self where Self : Decoder> (Self) -> () throws -> UnkeyedDecodingContainer, %4 : $@opened("{{.*}}") Decoder : $@convention(witness_method) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Builtin.NativeObject)
// CHECK: try_apply [[WT]]<@opened("{{.*}}") Decoder>([[OPENED]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Builtin.NativeObject), normal bb2, error bb1
//
// CHECK:bb{{.*}}([[RET1:%.*]] : @owned $UnkeyedDecodingContainer):
// CHECK: end_borrow [[BORROW1]] from %0 : $Decoder, $Decoder
// CHECK: [[BORROW2:%.*]] = begin_borrow [[RET1]] : $UnkeyedDecodingContainer
// CHECK: [[OPENED2:%.*]] = open_existential_value [[BORROW2]] : $UnkeyedDecodingContainer to $@opened("{{.*}}") UnkeyedDecodingContainer
// CHECK: [[WT2:%.*]] = witness_method $@opened("{{.*}}") UnkeyedDecodingContainer, #UnkeyedDecodingContainer.isAtEnd!getter.1 : <Self where Self : UnkeyedDecodingContainer> (Self) -> () -> Builtin.Int1, [[OPENED2]] : $@opened("{{.*}}") UnkeyedDecodingContainer : $@convention(witness_method) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1
// CHECK: [[RET2:%.*]] = apply [[WT2]]<@opened("{{.*}}") UnkeyedDecodingContainer>([[OPENED2]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1
// CHECK: end_borrow [[BORROW2]] from [[RET1]] : $UnkeyedDecodingContainer, $UnkeyedDecodingContainer
// CHECK: destroy_value [[RET1]] : $UnkeyedDecodingContainer
// CHECK: destroy_value %0 : $Decoder
// CHECK: return [[RET2]] : $Builtin.Int1
// CHECK-LABEL: } // end sil function '_T0s11takeDecoderBi1_s0B0_p4from_tKF'
public func takeDecoder(from decoder: Decoder) throws -> Builtin.Int1 {
let container = try decoder.unkeyedContainer()
return container.isAtEnd
}
public enum Optional<Wrapped> {
case none
case some(Wrapped)
}
public protocol IP {}
public protocol Seq {
associatedtype Iterator : IP
func makeIterator() -> Iterator
}
extension Seq where Self.Iterator == Self {
public func makeIterator() -> Self {
return self
}
}
public struct EnumIter<Base : IP> : IP, Seq {
internal var _base: Base
public typealias Iterator = EnumIter<Base>
}
// Test passing a +1 RValue to @in_guaranteed.
// ---
// CHECK-LABEL: sil @_T0s7EnumSeqV12makeIterators0A4IterVy0D0QzGyF : $@convention(method) <Base where Base : Seq> (@in_guaranteed EnumSeq<Base>) -> @out EnumIter<Base.Iterator> {
// CHECK: bb0(%0 : @guaranteed $EnumSeq<Base>):
// CHECK: [[FN:%.*]] = function_ref @_T0s8EnumIterVAByxGx5_base_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0>
// CHECK: [[MT:%.*]] = metatype $@thin EnumIter<Base.Iterator>.Type
// CHECK: [[WT:%.*]] = witness_method $Base, #Seq.makeIterator!1 : <Self where Self : Seq> (Self) -> () -> Self.Iterator : $@convention(witness_method) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator
// CHECK: [[FIELD:%.*]] = struct_extract %0 : $EnumSeq<Base>, #EnumSeq._base
// CHECK: [[COPY:%.*]] = copy_value [[FIELD]] : $Base
// CHECK: [[BORROW:%.*]] = begin_borrow [[COPY]] : $Base
// CHECK: [[ITER:%.*]] = apply [[WT]]<Base>([[BORROW]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator
// CHECK: end_borrow [[BORROW]] from [[COPY]] : $Base, $Base
// CHECK: destroy_value [[COPY]] : $Base
// CHECK: [[RET:%.*]] = apply [[FN]]<Base.Iterator>([[ITER]], [[MT]]) : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0>
// CHECK: return [[RET]] : $EnumIter<Base.Iterator>
// CHECK-LABEL: } // end sil function '_T0s7EnumSeqV12makeIterators0A4IterVy0D0QzGyF'
public struct EnumSeq<Base : Seq> : Seq {
public typealias Iterator = EnumIter<Base.Iterator>
internal var _base: Base
public func makeIterator() -> Iterator {
return EnumIter(_base: _base.makeIterator())
}
}
| apache-2.0 | 7eb8180d22ffe712a11a0cf57791d634 | 57.164706 | 379 | 0.664442 | 3.426195 | false | false | false | false |
jianghongfei/HidingNavigationBar | HidingNavigationBarSample/HidingNavigationBarSample/HidingNavToolbarViewController.swift | 3 | 2492 | //
// TableViewController.swift
// HidingNavigationBarSample
//
// Created by Tristan Himmelman on 2015-05-01.
// Copyright (c) 2015 Tristan Himmelman. All rights reserved.
//
import UIKit
class HidingNavToolbarViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let identifier = "cell"
var hidingNavBarManager: HidingNavigationBarManager?
var tableView: UITableView!
var toolbar: UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds)
tableView.dataSource = self
tableView.delegate = self
tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: identifier)
view.addSubview(tableView)
toolbar = UIToolbar(frame: CGRectMake(0, view.bounds.size.height - 44, view.bounds.width, 44))
toolbar.barTintColor = UIColor(white: 230/255, alpha: 1)
view.addSubview(toolbar)
hidingNavBarManager = HidingNavigationBarManager(viewController: self, scrollView: tableView)
hidingNavBarManager?.manageBottomBar(toolbar)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
hidingNavBarManager?.viewWillAppear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
hidingNavBarManager?.viewDidLayoutSubviews()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
hidingNavBarManager?.viewWillDisappear(animated)
}
// MARK: UITableViewDelegate
func scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool {
hidingNavBarManager?.shouldScrollToTop()
return true
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 100
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell.textLabel?.text = "row \(indexPath.row)"
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
}
| mit | 4a269fb5e6da21bbf825014539d62974 | 29.390244 | 119 | 0.748395 | 4.954274 | false | false | false | false |
OldBulls/swift-weibo | ZNWeibo/ZNWeibo/Classes/Compose/PicPickerCollectionView/PicPickerViewCell.swift | 1 | 1139 | //
// PicPickerViewCell.swift
// ZNWeibo
//
// Created by 金宝和信 on 16/7/14.
// Copyright © 2016年 zn. All rights reserved.
//
import UIKit
class PicPickerViewCell: UICollectionViewCell {
// MARK:- 控件的属性
@IBOutlet weak var addPhotoBtn: UIButton!
@IBOutlet weak var removePhotoBtn: UIButton!
@IBOutlet weak var imageView: UIImageView!
var image : UIImage? {
didSet {
if image != nil {
imageView.image = image
addPhotoBtn.userInteractionEnabled = false
removePhotoBtn.hidden = false
} else {
imageView.image = nil
addPhotoBtn.userInteractionEnabled = true
removePhotoBtn.hidden = true
}
}
}
// MARK:- 事件监听
@IBAction func addPhotoClick() {
NSNotificationCenter.defaultCenter().postNotificationName(PicPickerAddPhotoNote, object: nil)
}
@IBAction func removePhotoClick() {
NSNotificationCenter.defaultCenter().postNotificationName(PicPickerRemovePhotoNote, object: imageView.image)
}
}
| mit | 82f9edd610d86729ba29b8f7ba8bd3e8 | 26.073171 | 116 | 0.618018 | 5.045455 | false | false | false | false |
gegeburu3308119/ZCweb | ZCwebo/ZCwebo/Classes/Tools/Extensions/String+Extensions.swift | 1 | 1068 | //
// String+Extensions.swift
// 002-正则表达式
//
// Created by apple on 16/7/10.
// Copyright © 2016年 itcast. All rights reserved.
//
import Foundation
extension String {
/// 从当前字符串中,提取链接和文本
/// Swift 提供了`元组`,同时返回多个值
/// 如果是 OC,可以返回字典/自定义对象/指针的指针
func cz_href() -> (link: String, text: String)? {
// 0. 匹配方案
let pattern = "<a href=\"(.*?)\".*?>(.*?)</a>"
// 1. 创建正则表达式,并且匹配第一项
guard let regx = try? NSRegularExpression(pattern: pattern, options: []),
let result = regx.firstMatch(in: self, options: [], range: NSRange(location: 0, length: characters.count))
else {
return nil
}
// 2. 获取结果
let link = (self as NSString).substring(with: result.range)
let text = (self as NSString).substring(with: result.range)
return (link, text)
}
}
| apache-2.0 | 820fcb80d62db28ab0f4ab6baed03696 | 25.735294 | 118 | 0.540154 | 3.665323 | false | false | false | false |
juancruzmdq/LocationRequestManager | Example/Tests/Tests.swift | 1 | 3783 | // https://github.com/Quick/Quick
import Quick
import Nimble
import LocationRequestManager
class LocationRequestManagerSpec: QuickSpec {
override func spec() {
describe("LocationRequestManager") {
it("Constructor") {
let lm = LocationRequestManager()
expect(lm).toNot(beNil())
}
}
describe("LocationRequest") {
it("Constructor") {
let lr = LocationRequest({ (currentLocation, error) in
print("empty")
})
expect(lr).toNot(beNil())
expect(lr.status == .Pending).to(beTruthy())
}
}
describe("ManageRequests") {
var locationManager:LocationRequestManager!
beforeEach{
locationManager = LocationRequestManager()
}
it("Simple Add") {
let lr1 = LocationRequest(nil)
let lr2 = LocationRequest(nil)
locationManager.addRequest(request: lr1)
locationManager.addRequest(request: lr2)
expect(locationManager.requests.count).to(equal(2))
// Should avoid duplication of references
locationManager.addRequest(request: lr1)
locationManager.addRequest(request: lr2)
expect(locationManager.requests.count).to(equal(2))
}
it("Multiple Add") {
let lr1 = LocationRequest(nil)
let lr2 = LocationRequest(nil)
locationManager.addRequests(requests: [lr1,lr2])
expect(locationManager.requests.count).to(equal(2))
// Should avoid duplication of references
locationManager.addRequests(requests: [lr1,lr2])
expect(locationManager.requests.count).to(equal(2))
}
it("Simple Remove") {
let lr1 = LocationRequest(nil)
let lr2 = LocationRequest(nil)
locationManager.addRequest(request: lr1)
locationManager.addRequest(request: lr2)
expect(locationManager.requests.count).to(equal(2))
locationManager.removeRequest(request: lr2)
expect(locationManager.requests.count).to(equal(1))
}
it("Multiple Remove") {
let lr1 = LocationRequest(nil)
let lr2 = LocationRequest(nil)
let lr3 = LocationRequest(nil)
locationManager.addRequests(requests: [lr1,lr2,lr3])
expect(locationManager.requests.count).to(equal(3))
// Should avoid duplication of references
locationManager.removeRequests(requests: [lr1,lr3])
expect(locationManager.requests.count).to(equal(1))
}
it("Remove all") {
let lr1 = LocationRequest(nil)
let lr2 = LocationRequest(nil)
let lr3 = LocationRequest(nil)
locationManager.addRequests(requests: [lr1,lr2,lr3])
expect(locationManager.requests.count).to(equal(3))
// Should avoid duplication of references
locationManager.removeAllRequests()
expect(locationManager.requests.count).to(equal(0))
}
}
}
}
| mit | 074911bb59e7e7e11677a23eae4570c8 | 35.028571 | 70 | 0.492466 | 5.828968 | false | false | false | false |
KimDarren/allkfb | Allkdic/Models/KeyBinding.swift | 1 | 3661 | // The MIT License (MIT)
//
// Copyright (c) 2015 Suyeol Jeon (http://xoul.kr)
//
// 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.
private let _dictionaryKeys = ["keyCode", "shift", "control", "option", "command"]
public func ==(left: KeyBinding, right: KeyBinding) -> Bool {
for key in _dictionaryKeys {
if left.valueForKey(key) as? Int != right.valueForKey(key) as? Int {
return false
}
}
return true
}
@objc public class KeyBinding: NSObject {
var keyCode: Int = 0
var shift: Bool = false
var control: Bool = false
var option: Bool = false
var command: Bool = false
override public var description: String {
var keys = [String]()
if self.shift {
keys.append("Shift")
}
if self.control {
keys.append("Control")
}
if self.option {
keys.append("Option")
}
if self.command {
keys.append("Command")
}
if let keyString = self.dynamicType.keyStringFormKeyCode(self.keyCode) {
keys.append(keyString.capitalizedString)
}
return " + ".join(keys)
}
@objc public override init() {
super.init()
}
@objc public init(keyCode: Int, flags: Int) {
super.init()
self.keyCode = keyCode
for i in 0...6 {
if flags & (1 << i) != 0 {
if i == 0 {
self.control = true
} else if i == 1 {
self.shift = true
} else if i == 3 {
self.command = true
} else if i == 5 {
self.option = true
}
}
}
}
@objc public init(dictionary: [NSObject: AnyObject]?) {
super.init()
if dictionary == nil {
return
}
for key in _dictionaryKeys {
if let value = dictionary![key] as? Int {
self.setValue(value, forKey: key)
}
}
}
public func toDictionary() -> [String: Int] {
var dictionary = [String: Int]()
for key in _dictionaryKeys {
dictionary[key] = self.valueForKey(key)!.integerValue
}
return dictionary
}
public class func keyStringFormKeyCode(keyCode: Int) -> String? {
return keyMap[keyCode]
}
public class func keyCodeFormKeyString(string: String) -> Int {
for (keyCode, keyString) in keyMap {
if keyString == string {
return keyCode
}
}
return NSNotFound
}
}
| mit | 4d7b017427efd4025af8fc70a05dbeee | 30.025424 | 82 | 0.580443 | 4.57625 | false | false | false | false |
skylib/SnapImagePicker | SnapImagePicker/Categories/UIScrollView+fakeBounce.swift | 1 | 1520 | import UIKit
extension UIScrollView {
fileprivate func calculateOffsetFromVelocity(_ velocity: CGPoint) -> CGPoint {
var offset = CGPoint.zero
let x = Double(velocity.x / abs(velocity.x)) * pow(Double(28 * log(abs(velocity.x)) + 25), 1.2) * 0.6
let y = Double(velocity.y / abs(velocity.y)) * pow(Double(28 * log(abs(velocity.y)) + 25), 1.2) * 0.6
if !x.isNaN {
offset.x = CGFloat(x)
}
if !y.isNaN {
offset.y = CGFloat(y)
}
return offset
}
func manuallyBounceBasedOnVelocity(_ velocity: CGPoint, withAnimationDuration duration: Double = 0.2) {
let originalOffset = contentOffset
let offset = calculateOffsetFromVelocity(velocity)
UIView.animate(withDuration: duration, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: {
[weak self] in
if let strongSelf = self {
strongSelf.setContentOffset(CGPoint(x: originalOffset.x + offset.x, y: originalOffset.y + offset.y), animated: false)
}
}, completion: {
[weak self] (_) in
UIView.animate(withDuration: duration, delay: 0.0, options: UIViewAnimationOptions(), animations: {
if let strongSelf = self {
strongSelf.setContentOffset(originalOffset, animated: false)
}
}, completion: nil)
})
}
}
| bsd-3-clause | b007cc4a365db94141d188d74ac647bc | 40.081081 | 133 | 0.5625 | 4.648318 | false | false | false | false |
miguelgutierrez/Curso-iOS-Swift-Programming-Netmind | newsApp 1.9/newsApp/DetalleArticuloViewController.swift | 1 | 6554 | //
// DetalleArticuloViewController.swift
// newsApp
//
// Created by Miguel Gutiérrez Moreno on 23/1/15.
// Copyright (c) 2015 MGM. All rights reserved.
//
// v 1.8: permite compartir por email y Twitter
import UIKit
import MessageUI
import Social
class DetalleArticuloViewController: UIViewController, MFMailComposeViewControllerDelegate, UISplitViewControllerDelegate {
// MARK: properties
@IBOutlet weak var articuloTextView: UITextView!
var articulo : Articulo? {
didSet {
// Update the view.
if isViewLoaded() {
muestraInformacion()
}
}
}
weak var delegate : ArticulosTableViewController?
weak var masterPopoverController : UIPopoverController?
// MARK: life cicle
override func viewDidLoad() {
super.viewDidLoad()
muestraInformacion()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - MFMailComposeViewControllerDelegate
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - eventos
@IBAction func compartir(sender: UIButton) {
let titulo = NSLocalizedString("Compártelo", comment: "")
let mailButtonTitle = NSLocalizedString("Mail", comment: "")
let twitterButtonTitle = NSLocalizedString("Twitter", comment: "")
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
let alertController = UIAlertController(title: titulo, message: nil, preferredStyle: .ActionSheet)
// Create the action.
let mailAction = UIAlertAction(title: mailButtonTitle, style: .Default) {
[unowned self]
action in
self.enviarMail()
}
let twitterAction = UIAlertAction(title: twitterButtonTitle, style: .Default) {
[unowned self]
action in
self.compartirTwitter()
}
let destructiveAction = UIAlertAction(title: cancelButtonTitle, style: .Destructive, handler: nil)
// Add the action.
alertController.addAction(mailAction)
alertController.addAction(twitterAction)
alertController.addAction(destructiveAction)
// necesario para el iPAD
if let popover = alertController.popoverPresentationController{
popover.sourceView = sender
popover.sourceRect = sender.bounds
popover.permittedArrowDirections = UIPopoverArrowDirection.Any
}
presentViewController(alertController, animated: true, completion: nil)
}
// MARK: - UISplitViewControllerDelegate
// sustituir están deprecated en iOS 8
/*
func splitViewController(svc: UISplitViewController, willHideViewController aViewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController pc: UIPopoverController) {
barButtonItem.title = "Artículos"
navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
masterPopoverController = pc
}
func splitViewController(svc: UISplitViewController, willShowViewController aViewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
navigationItem.setLeftBarButtonItem(nil, animated: true)
masterPopoverController = nil
}
func splitViewController(svc: UISplitViewController, shouldHideViewController vc: UIViewController, inOrientation orientation: UIInterfaceOrientation) -> Bool {
if orientation == UIInterfaceOrientation.LandscapeLeft || orientation == UIInterfaceOrientation.LandscapeRight {
return false
}
else {
return true
}
}
*/
func muestraInformacion() {
if let articulo = self.articulo {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = FormatoFecha.formatoGeneral
if let fecha = articulo.fecha {
let fechaStr = dateFormatter.stringFromDate(fecha)
if let nombre = articulo.nombre {
navigationItem.title = "Artículo de \(nombre)"
if let texto = articulo.texto{
articuloTextView.text = "Nombre: \(nombre)\n Fecha: \(fechaStr)\n Texto: \(texto)"
}
}
}
}
if let masterPopoverController = masterPopoverController {
masterPopoverController.dismissPopoverAnimated(true)
}
}
// MARK: - funciones auxiliares
private func enviarMail() {
if MFMailComposeViewController.canSendMail() {
if let articulo = articulo {
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
if let nombre=articulo.nombre, texto=articulo.texto, fecha=articulo.fecha { mailComposer.setToRecipients(["[email protected]","[email protected]"])
let asunto = NSString(format: "Escritor: %@ Fecha: %@ \n Artículo: %@", nombre,fecha,texto)
mailComposer.setSubject("Artículo de " + articulo.nombre!)
mailComposer.setMessageBody(asunto as String, isHTML: false)
mailComposer.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
presentViewController(mailComposer, animated: true, completion: nil)
}
}
}
}
private func compartirTwitter() {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {
if let articulo = articulo {
let tweetSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
tweetSheet.setInitialText("Lee el artículo de: "+articulo.nombre!)
presentViewController(tweetSheet, animated: true, completion: nil)
}
}
}
}
| mit | 03d615ce0c7a7485b40dde2f14ef339a | 38.433735 | 212 | 0.640697 | 5.798051 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Card/Detail/Controller/GalleryImageItemBaseController.swift | 1 | 1471 | //
// GalleryImageItemBaseController.swift
// DereGuide
//
// Created by zzk on 2017/8/29.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import ImageViewer
import AudioToolbox
class GalleryImageItemBaseController: ItemBaseController<UIImageView> {
override func viewDidLoad() {
super.viewDidLoad()
itemView.isUserInteractionEnabled = true
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(_:)))
itemView.addGestureRecognizer(longPress)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let size = itemView.image?.size {
if size.width < view.bounds.width && size.height < view.bounds.height {
itemView.contentMode = .center
} else {
itemView.contentMode = .scaleAspectFit
}
}
}
@objc func handleLongPressGesture(_ longPress: UILongPressGestureRecognizer) {
guard let image = itemView.image else {
return
}
switch longPress.state {
case .began:
let point = longPress.location(in: itemView)
// play sound like pop(3d touch)
AudioServicesPlaySystemSound(1520)
UIActivityViewController.show(images: [image], pointTo: itemView, rect: CGRect(origin: point, size: .zero), in: self)
default:
break
}
}
}
| mit | bc08b7001fe1944f4c9c158b15048749 | 30.234043 | 129 | 0.632834 | 5.114983 | false | false | false | false |
frankeh/swift-corelibs-libdispatch | src/swift/Queue.swift | 1 | 11219 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// dispatch/queue.h
import CDispatch
public final class DispatchSpecificKey<T> {
public init() {}
}
internal class _DispatchSpecificValue<T> {
internal let value: T
internal init(value: T) { self.value = value }
}
public extension DispatchQueue {
public struct Attributes : OptionSet {
public let rawValue: UInt64
public init(rawValue: UInt64) { self.rawValue = rawValue }
public static let concurrent = Attributes(rawValue: 1<<1)
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public static let initiallyInactive = Attributes(rawValue: 1<<2)
fileprivate func _attr() -> dispatch_queue_attr_t? {
var attr: dispatch_queue_attr_t? = nil
if self.contains(.concurrent) {
attr = _swift_dispatch_queue_concurrent()
}
if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
if self.contains(.initiallyInactive) {
attr = CDispatch.dispatch_queue_attr_make_initially_inactive(attr)
}
}
return attr
}
}
public enum GlobalQueuePriority {
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
case high
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
case `default`
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
case low
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
case background
internal var _translatedValue: Int {
switch self {
case .high: return 2 // DISPATCH_QUEUE_PRIORITY_HIGH
case .default: return 0 // DISPATCH_QUEUE_PRIORITY_DEFAULT
case .low: return -2 // DISPATCH_QUEUE_PRIORITY_LOW
case .background: return Int(Int16.min) // DISPATCH_QUEUE_PRIORITY_BACKGROUND
}
}
}
public enum AutoreleaseFrequency {
case inherit
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
case workItem
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
case never
internal func _attr(attr: dispatch_queue_attr_t?) -> dispatch_queue_attr_t? {
if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
switch self {
case .inherit:
// DISPATCH_AUTORELEASE_FREQUENCY_INHERIT
return CDispatch.dispatch_queue_attr_make_with_autorelease_frequency(attr, dispatch_autorelease_frequency_t(0))
case .workItem:
// DISPATCH_AUTORELEASE_FREQUENCY_WORK_ITEM
return CDispatch.dispatch_queue_attr_make_with_autorelease_frequency(attr, dispatch_autorelease_frequency_t(1))
case .never:
// DISPATCH_AUTORELEASE_FREQUENCY_NEVER
return CDispatch.dispatch_queue_attr_make_with_autorelease_frequency(attr, dispatch_autorelease_frequency_t(2))
}
} else {
return attr
}
}
}
public class func concurrentPerform(iterations: Int, execute work: (Int) -> Void) {
_swift_dispatch_apply_current(iterations, work)
}
public class var main: DispatchQueue {
return DispatchQueue(queue: _swift_dispatch_get_main_queue())
}
@available(OSX, deprecated: 10.10, message: "")
@available(*, deprecated: 8.0, message: "")
public class func global(priority: GlobalQueuePriority) -> DispatchQueue {
return DispatchQueue(queue: CDispatch.dispatch_get_global_queue(priority._translatedValue, 0))
}
@available(OSX 10.10, iOS 8.0, *)
public class func global(qos: DispatchQoS.QoSClass = .default) -> DispatchQueue {
return DispatchQueue(queue: CDispatch.dispatch_get_global_queue(Int(qos.rawValue.rawValue), 0))
}
public class func getSpecific<T>(key: DispatchSpecificKey<T>) -> T? {
let k = Unmanaged.passUnretained(key).toOpaque()
if let p = CDispatch.dispatch_get_specific(k) {
let v = Unmanaged<_DispatchSpecificValue<T>>
.fromOpaque(p)
.takeUnretainedValue()
return v.value
}
return nil
}
public convenience init(
label: String,
qos: DispatchQoS = .unspecified,
attributes: Attributes = [],
autoreleaseFrequency: AutoreleaseFrequency = .inherit,
target: DispatchQueue? = nil)
{
var attr = attributes._attr()
if autoreleaseFrequency != .inherit {
attr = autoreleaseFrequency._attr(attr: attr)
}
if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified {
attr = CDispatch.dispatch_queue_attr_make_with_qos_class(attr, qos.qosClass.rawValue.rawValue, Int32(qos.relativePriority))
}
if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
self.init(__label: label, attr: attr, queue: target)
} else {
self.init(__label: label, attr: attr)
if let tq = target { self.setTarget(queue: tq) }
}
}
public var label: String {
return String(validatingUTF8: dispatch_queue_get_label(self.__wrapped))!
}
@available(OSX 10.10, iOS 8.0, *)
public func sync(execute workItem: DispatchWorkItem) {
CDispatch.dispatch_sync(self.__wrapped, workItem._block)
}
@available(OSX 10.10, iOS 8.0, *)
public func async(execute workItem: DispatchWorkItem) {
CDispatch.dispatch_async(self.__wrapped, workItem._block)
}
@available(OSX 10.10, iOS 8.0, *)
public func async(group: DispatchGroup, execute workItem: DispatchWorkItem) {
CDispatch.dispatch_group_async(group.__wrapped, self.__wrapped, workItem._block)
}
public func async(
group: DispatchGroup? = nil,
qos: DispatchQoS = .unspecified,
flags: DispatchWorkItemFlags = [],
execute work: @escaping @convention(block) () -> Void)
{
if group == nil && qos == .unspecified && flags.isEmpty {
// Fast-path route for the most common API usage
CDispatch.dispatch_async(self.__wrapped, work)
return
}
var block: @convention(block) () -> Void = work
if #available(OSX 10.10, iOS 8.0, *), (qos != .unspecified || !flags.isEmpty) {
let workItem = DispatchWorkItem(qos: qos, flags: flags, block: work)
block = workItem._block
}
if let g = group {
CDispatch.dispatch_group_async(g.__wrapped, self.__wrapped, block)
} else {
CDispatch.dispatch_async(self.__wrapped, block)
}
}
private func _syncBarrier(block: () -> ()) {
CDispatch.dispatch_barrier_sync(self.__wrapped, block)
}
private func _syncHelper<T>(
fn: (() -> ()) -> (),
execute work: () throws -> T,
rescue: ((Swift.Error) throws -> (T))) rethrows -> T
{
var result: T?
var error: Swift.Error?
fn {
do {
result = try work()
} catch let e {
error = e
}
}
if let e = error {
return try rescue(e)
} else {
return result!
}
}
@available(OSX 10.10, iOS 8.0, *)
private func _syncHelper<T>(
fn: (DispatchWorkItem) -> (),
flags: DispatchWorkItemFlags,
execute work: () throws -> T,
rescue: @escaping ((Swift.Error) throws -> (T))) rethrows -> T
{
var result: T?
var error: Swift.Error?
let workItem = DispatchWorkItem(flags: flags, noescapeBlock: {
do {
result = try work()
} catch let e {
error = e
}
})
fn(workItem)
if let e = error {
return try rescue(e)
} else {
return result!
}
}
public func sync<T>(execute work: () throws -> T) rethrows -> T {
return try self._syncHelper(fn: sync, execute: work, rescue: { throw $0 })
}
public func sync<T>(flags: DispatchWorkItemFlags, execute work: () throws -> T) rethrows -> T {
if flags == .barrier {
return try self._syncHelper(fn: _syncBarrier, execute: work, rescue: { throw $0 })
} else if #available(OSX 10.10, iOS 8.0, *), !flags.isEmpty {
return try self._syncHelper(fn: sync, flags: flags, execute: work, rescue: { throw $0 })
} else {
return try self._syncHelper(fn: sync, execute: work, rescue: { throw $0 })
}
}
public func asyncAfter(
deadline: DispatchTime,
qos: DispatchQoS = .unspecified,
flags: DispatchWorkItemFlags = [],
execute work: @escaping @convention(block) () -> Void)
{
if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty {
let item = DispatchWorkItem(qos: qos, flags: flags, block: work)
CDispatch.dispatch_after(deadline.rawValue, self.__wrapped, item._block)
} else {
CDispatch.dispatch_after(deadline.rawValue, self.__wrapped, work)
}
}
public func asyncAfter(
wallDeadline: DispatchWallTime,
qos: DispatchQoS = .unspecified,
flags: DispatchWorkItemFlags = [],
execute work: @escaping @convention(block) () -> Void)
{
if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty {
let item = DispatchWorkItem(qos: qos, flags: flags, block: work)
CDispatch.dispatch_after(wallDeadline.rawValue, self.__wrapped, item._block)
} else {
CDispatch.dispatch_after(wallDeadline.rawValue, self.__wrapped, work)
}
}
@available(OSX 10.10, iOS 8.0, *)
public func asyncAfter(deadline: DispatchTime, execute: DispatchWorkItem) {
CDispatch.dispatch_after(deadline.rawValue, self.__wrapped, execute._block)
}
@available(OSX 10.10, iOS 8.0, *)
public func asyncAfter(wallDeadline: DispatchWallTime, execute: DispatchWorkItem) {
CDispatch.dispatch_after(wallDeadline.rawValue, self.__wrapped, execute._block)
}
@available(OSX 10.10, iOS 8.0, *)
public var qos: DispatchQoS {
var relPri: Int32 = 0
let cls = DispatchQoS.QoSClass(rawValue: _OSQoSClass(qosClass: dispatch_queue_get_qos_class(self.__wrapped, &relPri))!)!
return DispatchQoS(qosClass: cls, relativePriority: Int(relPri))
}
public func getSpecific<T>(key: DispatchSpecificKey<T>) -> T? {
let k = Unmanaged.passUnretained(key).toOpaque()
if let p = dispatch_queue_get_specific(self.__wrapped, k) {
let v = Unmanaged<_DispatchSpecificValue<T>>
.fromOpaque(p)
.takeUnretainedValue()
return v.value
}
return nil
}
public func setSpecific<T>(key: DispatchSpecificKey<T>, value: T) {
let v = _DispatchSpecificValue(value: value)
let k = Unmanaged.passUnretained(key).toOpaque()
let p = Unmanaged.passRetained(v).toOpaque()
dispatch_queue_set_specific(self.__wrapped, k, p, _destructDispatchSpecificValue)
}
}
private func _destructDispatchSpecificValue(ptr: UnsafeMutableRawPointer?) {
if let p = ptr {
Unmanaged<AnyObject>.fromOpaque(p).release()
}
}
@_silgen_name("_swift_dispatch_queue_concurrent")
internal func _swift_dispatch_queue_concurrent() -> dispatch_queue_attr_t
@_silgen_name("_swift_dispatch_get_main_queue")
internal func _swift_dispatch_get_main_queue() -> dispatch_queue_t
@_silgen_name("_swift_dispatch_apply_current_root_queue")
internal func _swift_dispatch_apply_current_root_queue() -> dispatch_queue_t
@_silgen_name("_swift_dispatch_apply_current")
internal func _swift_dispatch_apply_current(_ iterations: Int, _ block: @convention(block) (Int) -> Void)
| apache-2.0 | f1e6df15e884934aa0e13aa0eaf08a8a | 31.424855 | 126 | 0.681344 | 3.401759 | false | false | false | false |
guillermo-ag-95/App-Development-with-Swift-for-Students | 4 - Tables and Persistence/7 - Saving Data/lab/EmojiDictionary/EmojiDictionary/EmojiTableViewController.swift | 1 | 5023 |
import UIKit
class EmojiTableViewController: UITableViewController {
var emojis = [Emoji(symbol: "😀", name: "Grinning Face", detailDescription: "A typical smiley face.", usage: "happiness"),
Emoji(symbol: "😕", name: "Confused Face", detailDescription: "A confused, puzzled face.", usage: "unsure what to think; displeasure"),
Emoji(symbol: "😍", name: "Heart Eyes", detailDescription: "A smiley face with hearts for eyes.", usage: "love of something; attractive"),
Emoji(symbol: "👮", name: "Police Officer", detailDescription: "A police officer wearing a blue cap with a gold badge. He is smiling, and eager to help.", usage: "person of authority"),
Emoji(symbol: "🐢", name: "Turtle", detailDescription: "A cute turtle.", usage: "Something slow"),
Emoji(symbol: "🐘", name: "Elephant", detailDescription: "A gray elephant.", usage: "good memory"),
Emoji(symbol: "🍝", name: "Spaghetti", detailDescription: "A plate of spaghetti.", usage: "spaghetti"),
Emoji(symbol: "🎲", name: "Die", detailDescription: "A single die.", usage: "taking a risk, chance; game"),
Emoji(symbol: "⛺️", name: "Tent", detailDescription: "A small tent.", usage: "camping"),
Emoji(symbol: "📚", name: "Stack of Books", detailDescription: "Three colored books stacked on each other.", usage: "homework, studying"),
Emoji(symbol: "💔", name: "Broken Heart", detailDescription: "A red, broken heart.", usage: "extreme sadness"),
Emoji(symbol: "💤", name: "Snore", detailDescription: "Three blue \'z\'s.", usage: "tired, sleepiness"),
Emoji(symbol: "🏁", name: "Checkered Flag", detailDescription: "A black and white checkered flag.", usage: "completion")]
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return emojis.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "EmojiCell", for: indexPath) as! EmojiTableViewCell
let emoji = emojis[indexPath.row]
cell.update(with: emoji)
cell.showsReorderControl = true
return cell
}
@IBAction func editButtonTapped(_ sender: UIBarButtonItem) {
let tableViewEditingMode = tableView.isEditing
tableView.setEditing(!tableViewEditingMode, animated: true)
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .delete
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
emojis.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
let movedEmoji = emojis.remove(at: fromIndexPath.row)
emojis.insert(movedEmoji, at: to.row)
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0
}
// MARK: - Navigation
@IBAction func unwindToEmojiTableView(segue: UIStoryboardSegue) {
guard segue.identifier == "saveUnwind" else { return }
let sourceViewController = segue.source as! AddEditEmojiTableViewController
if let emoji = sourceViewController.emoji {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
emojis[selectedIndexPath.row] = emoji
tableView.reloadRows(at: [selectedIndexPath], with: .none)
} else {
let newIndexPath = IndexPath(row: emojis.count, section: 0)
emojis.append(emoji)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "EditEmoji" {
let indexPath = tableView.indexPathForSelectedRow!
let emoji = emojis[indexPath.row]
let navController = segue.destination as! UINavigationController
let addEditEmojiTableViewController = navController.topViewController as! AddEditEmojiTableViewController
addEditEmojiTableViewController.emoji = emoji
}
}
}
| mit | 5c656c93fba90de7452c409b24b44c21 | 44.715596 | 202 | 0.634758 | 5.058883 | false | false | false | false |
Bizzi-Body/ParseTutorialPart8---CompleteSolution | ParseTutorial/SignUpInViewController.swift | 1 | 6631 | //
// SignUpInViewController.swift
// ParseTutorial
//
// Created by Ian Bradbury on 10/02/2015.
// Copyright (c) 2015 bizzi-body. All rights reserved.
//
import UIKit
class SignUpInViewController: UIViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var message: UILabel!
@IBOutlet weak var emailAddress: UITextField!
@IBOutlet weak var password: UITextField!
@IBAction func forgottenPassword(sender: AnyObject) {
let targetEmailAddress = emailAddress.text.lowercaseString
// Create an alert - tell the user they need to provide an email address
if targetEmailAddress == "" {
let alertController = UIAlertController(title: "Missing Email Address",
message: "Please provide an email address so that we can process your password request.",
preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: nil)
)
self.presentViewController(
alertController,
animated: true,
completion: nil
)
} else {
// We have an email address - attempt to initiate a password reset request on the parse platform
// For security - We do not let the user know if the request to reset their password was successful or not
let didSendForgottenEmail = PFUser.requestPasswordResetForEmail(targetEmailAddress)
// Create an alert - tell the user an email has been sent - maybe
let alertController = UIAlertController(title: "Password Reset",
message: "If an account with that email address exists - we have sent an email containing instructions on how to complete your request.",
preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: nil)
)
self.presentViewController(
alertController,
animated: true,
completion: nil
)
}
}
@IBAction func signUp(sender: AnyObject) {
// Build the terms and conditions alert
let alertController = UIAlertController(title: "Agree to terms and conditions",
message: "Click I AGREE to signal that you agree to the End User Licence Agreement.",
preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "I AGREE",
style: UIAlertActionStyle.Default,
handler: { alertController in self.processSignUp()})
)
alertController.addAction(UIAlertAction(title: "I do NOT agree",
style: UIAlertActionStyle.Default,
handler: nil)
)
// Display alert
self.presentViewController(alertController, animated: true, completion: nil)
}
@IBAction func signIn(sender: AnyObject) {
activityIndicator.hidden = false
activityIndicator.startAnimating()
// Clear an previous sign in message
message.text = ""
var userEmailAddress = emailAddress.text
userEmailAddress = userEmailAddress.lowercaseString
var userPassword = password.text
PFUser.logInWithUsernameInBackground(userEmailAddress, password:userPassword) {
(user: PFUser?, error: NSError?) -> Void in
// If there is a user
if let user = user {
if user["emailVerified"] as! Bool == true {
// Update last signed in value
user["lastSignIn"] = NSDate()
user.saveEventually()
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier(
"signInToNavigation",
sender: self
)
}
} else {
// User needs to verify email address before continuing
let alertController = UIAlertController(
title: "Email address verification",
message: "We have sent you an email that contains a link - you must click this link before you can continue.",
preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "OKAY",
style: UIAlertActionStyle.Default,
handler: { alertController in self.processSignOut()})
)
// Display alert
self.presentViewController(
alertController,
animated: true,
completion: nil
)
}
} else {
// User authentication failed, present message to the user
self.message.text = "Sign In failed. The email address and password combination were not recognised."
// Remove the activity indicator
self.activityIndicator.hidden = true
self.activityIndicator.stopAnimating()
}
}
}
// Main viewDidLoad method
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.hidden = true
activityIndicator.hidesWhenStopped = true
}
// Sign the current user OUT of the app
func processSignOut() {
// // Sign out
PFUser.logOut()
// Display sign in / up view controller
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("SignUpInViewController") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}
// Sign UP method that is called when once a user has accepted the terms and conditions
func processSignUp() {
var userEmailAddress = emailAddress.text
var userPassword = password.text
// Ensure username is lowercase
userEmailAddress = userEmailAddress.lowercaseString
// Add email address validation
// Start activity indicator
activityIndicator.hidden = false
activityIndicator.startAnimating()
// Create the user
var user = PFUser()
user.username = userEmailAddress
user.password = userPassword
user.email = userEmailAddress
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if error == nil {
// User needs to verify email address before continuing
let alertController = UIAlertController(title: "Email address verification",
message: "We have sent you an email that contains a link - you must click this link before you can continue.",
preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "OKAY",
style: UIAlertActionStyle.Default,
handler: { alertController in self.processSignOut()})
)
// Display alert
self.presentViewController(alertController, animated: true, completion: nil)
} else {
self.activityIndicator.stopAnimating()
if let message: AnyObject = error!.userInfo!["error"] {
self.message.text = "\(message)"
}
}
}
}
}
| mit | d006baeb509bc8eb4c28c9b77758eab5 | 29.84186 | 145 | 0.696124 | 4.702837 | false | false | false | false |
muenzpraeger/salesforce-einstein-vision-swift | SalesforceEinsteinVision/Classes/http/parts/MultiPartPrediction.swift | 1 | 1677 | //
// MultiPartPrediction.swift
// Pods
//
// Created by René Winkelmeyer on 02/28/2017.
//
//
import Alamofire
import Foundation
public enum SourceType {
case file
case base64
case url
}
public struct MultiPartPrediction : MultiPart {
private var _modelId:String?
private var _data:String?
private var _sampleId:String?
private var _sourceType:SourceType?
public init() {}
public mutating func build(modelId: String, data: String, sampleId: String?, type: SourceType) {
_modelId = modelId
_data = data
if let sampleId = sampleId, !sampleId.isEmpty {
_sampleId = sampleId
}
_sourceType = type
}
public func form(multipart: MultipartFormData) {
let modelId = _modelId?.data(using: String.Encoding.utf8)
multipart.append(modelId!, withName: "modelId")
if let id = _sampleId, !id.isEmpty {
let sampleId = id.data(using: String.Encoding.utf8)!
multipart.append(sampleId, withName: "sampleId")
}
switch(_sourceType!) {
case .base64:
let dataPrediction = _data?.data(using: String.Encoding.utf8)
multipart.append(dataPrediction!, withName: "sampleBase64Content")
break
case .file:
let url = URL(string: _data!)
multipart.append(url!, withName: "sampleContent")
break
case .url:
let dataPrediction = _data?.data(using: String.Encoding.utf8)
multipart.append(dataPrediction!, withName: "sampleLocation")
}
}
}
| apache-2.0 | 44f93f5630e19fa315992306049c53e6 | 24.393939 | 100 | 0.586516 | 4.410526 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/DataAccess/QuestRenditionDA.swift | 1 | 3959 | //
// QuestRenditionDA.swift
// AwesomeCore
//
// Created by Antonio on 12/19/17.
//
//import Foundation
//
//class QuestRenditionDA {
//
// // MARK: - Parser
//
// public func parseToCoreData(_ questRendition: QuestRendition, completion: @escaping (CDAssetRendition) -> Void) {
// AwesomeCoreDataAccess.shared.backgroundContext.perform {
// let cdRendition = self.parseToCoreData(questRendition)
// completion(cdRendition)
// }
// }
//
// private func parseToCoreData(_ questRendition: QuestRendition) -> CDAssetRendition {
//
// guard let renditionId = questRendition.id else {
// fatalError("CDAssetRendition object can't be created without id.")
// }
// let p = predicate(renditionId, questRendition.assetId ?? "")
// let cdRendition = CDAssetRendition.getObjectAC(predicate: p, createIfNil: true) as! CDAssetRendition
//
// cdRendition.contentType = questRendition.contentType
// cdRendition.duration = questRendition.duration ?? 0
// cdRendition.edgeUrl = questRendition.edgeUrl
// cdRendition.filesize = Int64(questRendition.filesize ?? 0)
// cdRendition.id = questRendition.id
// cdRendition.name = questRendition.name
// cdRendition.overmindId = questRendition.overmindId
// cdRendition.secure = questRendition.secure ?? false
// cdRendition.status = questRendition.status
// cdRendition.thumbnailUrl = questRendition.thumbnailUrl
// cdRendition.url = questRendition.url
// return cdRendition
// }
//
// func parseFromCoreData(_ cdAssetRendition: CDAssetRendition) -> QuestRendition {
// return QuestRendition(
// contentType: cdAssetRendition.contentType,
// duration: cdAssetRendition.duration,
// edgeUrl: cdAssetRendition.edgeUrl,
// filesize: Int(cdAssetRendition.filesize),
// id: cdAssetRendition.id,
// name: cdAssetRendition.name,
// overmindId: cdAssetRendition.overmindId,
// secure: cdAssetRendition.secure,
// status: cdAssetRendition.status,
// thumbnailUrl: cdAssetRendition.thumbnailUrl,
// url: cdAssetRendition.url,
// assetId: cdAssetRendition.asset?.id
// )
// }
//
// // MARK: - Fetch
//
// func loadBy(renditionId: String, assetId: String, completion: @escaping (CDAssetRendition?) -> Void) {
// func perform() {
// let p = predicate(renditionId, assetId)
// guard let cdMarker = CDAssetRendition.listAC(predicate: p).first as? CDAssetRendition else {
// completion(nil)
// return
// }
// completion(cdMarker)
// }
// AwesomeCoreDataAccess.shared.performBackgroundBatchOperation({ (workerContext) in
// perform()
// })
// }
//
// // MARK: - Helpers
//
// func extractQuestRenditions(_ questRenditions: [QuestRendition]?) -> NSSet {
// var renditions = NSSet()
// guard let questRenditions = questRenditions else {
// return renditions
// }
// for qr in questRenditions {
// renditions = renditions.adding(parseToCoreData(qr)) as NSSet
// }
// return renditions
// }
//
// func extractCDAssetRendition(_ questRenditions: NSSet?) -> [QuestRendition]? {
// guard let questRenditions = questRenditions else {
// return nil
// }
// var renditions = [QuestRendition]()
// for qr in questRenditions {
// renditions.append(parseFromCoreData(qr as! CDAssetRendition))
// }
// return renditions
// }
//
// private func predicate(_ markerId: String, _ assetId: String) -> NSPredicate {
// return NSPredicate(format: "id == %@ AND asset.id == %@", markerId, assetId)
// }
//}
| mit | da82f25a822459636929e5a3d3550552 | 37.436893 | 119 | 0.607982 | 4.503982 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/SwiftUI/Components/Popup/View+Popup.swift | 1 | 9043 | //
// Xcore
// Copyright © 2021 Xcore
// MIT license, see LICENSE file for details
//
import SwiftUI
// MARK: - View Extension
extension View {
/// Presents a popup when a binding to a Boolean value that you provide is
/// `true`.
///
/// Use this method when you want to present a popup view to the user when a
/// Boolean value you provide is `true`. The example below displays a popup view
/// of the mockup for a software license agreement when the user toggles the
/// `isShowingPopup` variable by clicking or tapping on the "Show License
/// Agreement" button:
///
/// ```swift
/// struct ShowLicenseAgreement: View {
/// @State private var isShowingPopup = false
///
/// var body: some View {
/// Button {
/// isShowingPopup.toggle()
/// } label: {
/// Text("Show License Agreement")
/// }
/// .popup(isPresented: $isShowingPopup) {
/// VStack {
/// Text("License Agreement")
/// Text("Terms and conditions go here.")
/// Button("Dismiss") {
/// isShowingPopup.toggle()
/// }
/// }
/// }
/// }
/// }
/// ```
///
/// - Parameters:
/// - isPresented: A binding to a Boolean value that determines whether to
/// present the popup that you create in the modifier's `content` closure.
/// - style: The style of the popup.
/// - dismissMethods: An option set specifying the dismissal methods for the
/// popup.
/// - content: A closure returning the content of the popup.
public func popup<Content>(
isPresented: Binding<Bool>,
style: Popup.Style = .alert,
dismissMethods: Popup.DismissMethods = [.tapOutside],
@ViewBuilder content: @escaping () -> Content
) -> some View where Content: View {
modifier(PopupViewModifier(
isPresented: isPresented,
style: style,
dismissMethods: dismissMethods,
content: content
))
}
/// Presents a popup using the given item as a data source for the popup's
/// content.
///
/// Use this method when you need to present a popup view with content from a
/// custom data source. The example below shows a custom data source
/// `InventoryItem` that the `content` closure uses to populate the display the
/// action popup shows to the user:
///
/// ```swift
/// struct ShowPartDetail: View {
/// @State var popupDetail: InventoryItem?
///
/// var body: some View {
/// Button("Show Part Details") {
/// popupDetail = InventoryItem(
/// id: "0123456789",
/// partNumber: "Z-1234A",
/// quantity: 100,
/// name: "Widget"
/// )
/// }
/// .popup(item: $popupDetail) { detail in
/// VStack(alignment: .leading, spacing: 20) {
/// Text("Part Number: \(detail.partNumber)")
/// Text("Name: \(detail.name)")
/// Text("Quantity On-Hand: \(detail.quantity)")
/// }
/// .onTapGesture {
/// popupDetail = nil
/// }
/// }
/// }
/// }
///
/// struct InventoryItem: Identifiable {
/// var id: String
/// let partNumber: String
/// let quantity: Int
/// let name: String
/// }
/// ```
///
/// - Parameters:
/// - item: A binding to an optional source of truth for the popup. When
/// `item` is non-`nil`, the system passes the item's content to the
/// modifier's closure. You display this content in a popup that you create
/// that the system displays to the user. If `item` changes, the system
/// dismisses the popup and replaces it with a new one using the same
/// process.
/// - style: The style of the popup.
/// - dismissMethods: An option set specifying the dismissal methods for the
/// popup.
/// - content: A closure returning the content of the popup.
public func popup<Item, Content>(
item: Binding<Item?>,
style: Popup.Style = .alert,
dismissMethods: Popup.DismissMethods = [.tapOutside],
@ViewBuilder content: @escaping (Item) -> Content
) -> some View where Content: View {
modifier(PopupViewModifier(
isPresented: .init {
item.wrappedValue != nil
} set: { isPresented in
if !isPresented {
item.wrappedValue = nil
}
},
style: style,
dismissMethods: dismissMethods,
content: {
if let item = item.wrappedValue {
content(item)
}
}
))
}
public func popup<F>(
_ title: Text,
message: Text?,
isPresented: Binding<Bool>,
dismissMethods: Popup.DismissMethods = [.tapOutside],
@ViewBuilder footer: @escaping () -> F
) -> some View where F: View {
popup(
isPresented: isPresented,
style: .alert,
dismissMethods: dismissMethods,
content: {
StandardPopupAlert(title, message: message, footer: footer)
}
)
}
public func popup<F, S1, S2>(
_ title: S1,
message: S2?,
isPresented: Binding<Bool>,
dismissMethods: Popup.DismissMethods = [.tapOutside],
@ViewBuilder footer: @escaping () -> F
) -> some View where F: View, S1: StringProtocol, S2: StringProtocol {
popup(
Text(title),
message: message.map { Text($0) },
isPresented: isPresented,
dismissMethods: dismissMethods,
footer: footer
)
}
}
// MARK: - View Modifier
private struct PopupViewModifier<PopupContent>: ViewModifier where PopupContent: View {
init(
isPresented: Binding<Bool>,
style: Popup.Style,
dismissMethods: Popup.DismissMethods,
@ViewBuilder content: @escaping () -> PopupContent
) {
self._isPresented = isPresented
self.style = style
self.dismissMethods = dismissMethods
self.content = content
}
@State private var workItem: DispatchWorkItem?
/// A Boolean value that indicates whether the popup associated with this
/// environment is currently being presented.
@Binding private var isPresented: Bool
/// A property indicating the popup style.
private let style: Popup.Style
/// A closure containing the content of popup.
private let content: () -> PopupContent
/// A property indicating all of the ways popup can be dismissed.
private let dismissMethods: Popup.DismissMethods
func body(content: Content) -> some View {
content
.window(isPresented: $isPresented, style: style.windowStyle) {
popupContent
}
.onChange(of: isPresented) { isPresented in
if isPresented {
setupAutomaticDismissalIfNeeded()
}
}
}
private var popupContent: some View {
ZStack {
if isPresented {
if style.allowDimming {
// Host Content Dim Overlay
Color(white: 0, opacity: 0.20)
.frame(max: .infinity)
.ignoresSafeArea()
.onTapGestureIf(dismissMethods.contains(.tapOutside)) {
isPresented = false
}
.zIndex(1)
.transition(.opacity)
}
content()
.frame(max: .infinity, alignment: style.alignment)
.ignoresSafeArea(edges: style.ignoresSafeAreaEdges)
.onTapGestureIf(dismissMethods.contains(.tapInside)) {
isPresented = false
}
.zIndex(2)
.transition(style.transition)
}
}
.animation(style.animation, value: isPresented)
.popupDismissAction(
dismissMethods.contains(.xmark) ? PopupDismissAction { isPresented = false } : nil
)
}
private func setupAutomaticDismissalIfNeeded() {
guard let duration = style.dismissAfter else {
return
}
workItem?.cancel()
workItem = DispatchWorkItem {
isPresented = false
}
if isPresented, let work = workItem {
DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: work)
}
}
}
| mit | 3ec63a86ee50c482f8b2f78ac146d951 | 33.25 | 94 | 0.528534 | 5.048576 | false | false | false | false |
SeriousChoice/SCSwift | Example/Pods/Cache/Source/Shared/Storage/SyncStorage.swift | 1 | 1528 | import Foundation
import Dispatch
/// Manipulate storage in a "all sync" manner.
/// Block the current queue until the operation completes.
public class SyncStorage<Key: Hashable, Value> {
public let innerStorage: HybridStorage<Key, Value>
public let serialQueue: DispatchQueue
public init(storage: HybridStorage<Key, Value>, serialQueue: DispatchQueue) {
self.innerStorage = storage
self.serialQueue = serialQueue
}
}
extension SyncStorage: StorageAware {
public func entry(forKey key: Key) throws -> Entry<Value> {
var entry: Entry<Value>!
try serialQueue.sync {
entry = try innerStorage.entry(forKey: key)
}
return entry
}
public func removeObject(forKey key: Key) throws {
try serialQueue.sync {
try self.innerStorage.removeObject(forKey: key)
}
}
public func setObject(_ object: Value, forKey key: Key, expiry: Expiry? = nil) throws {
try serialQueue.sync {
try innerStorage.setObject(object, forKey: key, expiry: expiry)
}
}
public func removeAll() throws {
try serialQueue.sync {
try innerStorage.removeAll()
}
}
public func removeExpiredObjects() throws {
try serialQueue.sync {
try innerStorage.removeExpiredObjects()
}
}
}
public extension SyncStorage {
func transform<U>(transformer: Transformer<U>) -> SyncStorage<Key, U> {
let storage = SyncStorage<Key, U>(
storage: innerStorage.transform(transformer: transformer),
serialQueue: serialQueue
)
return storage
}
}
| mit | 2ad21378e3d280d0098a1117870ab5b6 | 24.466667 | 89 | 0.695681 | 4.416185 | false | false | false | false |
YuAo/WAKeyValuePersistenceStore | WAKeyValuePersistenceStoreDemo/WAKeyValuePersistenceStoreDemo/ViewController.swift | 1 | 1021 | //
// ViewController.swift
// WAKeyValuePersistenceStoreDemo
//
// Created by YuAo on 5/22/15.
// Copyright (c) 2015 YuAo. All rights reserved.
//
import UIKit
import WAKeyValuePersistenceStore
private let ViewControllerTextCacheKey = "ViewControllerTextCacheKey"
class ViewController: UIViewController {
private let cacheStore = WAKeyValuePersistenceStore(directory: NSSearchPathDirectory.CachesDirectory, name: "CacheStore", objectSerializer: WAPersistenceObjectSerializer.keyedArchiveSerializer())
@IBOutlet private weak var textField: UITextField!
@IBOutlet private weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.textField.text = self.cacheStore[ViewControllerTextCacheKey] as? String
}
@IBAction private func textFieldChanged(sender: UITextField) {
self.cacheStore[ViewControllerTextCacheKey] = sender.text
self.label.text = "Saved! See WAKeyValuePersistenceStoreDemoTests for more usage."
}
}
| mit | a2a2b77fa2638c2b1a328b45d778d61f | 30.90625 | 199 | 0.750245 | 4.816038 | false | false | false | false |
matsprea/omim | iphone/Maps/UI/Downloader/DownloadMapsViewController.swift | 1 | 18868 | @objc(MWMDownloadMapsViewController)
class DownloadMapsViewController: MWMViewController {
// MARK: - Types
private enum NodeAction {
case showOnMap
case download
case update
case cancelDownload
case retryDownload
case delete
}
private enum AllMapsButtonState {
case none
case download(String)
case cancel(String)
}
// MARK: - Outlets
@IBOutlet var tableView: UITableView!
@IBOutlet var searchBar: UISearchBar!
@IBOutlet var statusBarBackground: UIView!
@IBOutlet var noMapsContainer: UIView!
@IBOutlet var searchBarTopOffset: NSLayoutConstraint!
@IBOutlet var downloadAllViewContainer: UIView!
// MARK: - Properties
var dataSource: IDownloaderDataSource!
@objc var mode: MWMMapDownloaderMode = .downloaded
private var skipCountryEvent = false
private var hasAddMapSection: Bool { dataSource.isRoot && mode == .downloaded }
private let allMapsViewBottomOffsetConstant: CGFloat = 64
lazy var noSerchResultViewController: SearchNoResultsViewController = {
let vc = storyboard!.instantiateViewController(ofType: SearchNoResultsViewController.self)
view.insertSubview(vc.view, belowSubview: statusBarBackground)
vc.view.alignToSuperview()
vc.view.isHidden = true
addChild(vc)
vc.didMove(toParent: self)
return vc
}()
lazy var downloadAllView: DownloadAllView = {
let view = Bundle.main.load(viewClass: DownloadAllView.self)?.first as! DownloadAllView
view.delegate = self
downloadAllViewContainer.addSubview(view)
view.alignToSuperview()
return view
}()
// MARK: - Methods
override func viewDidLoad() {
super.viewDidLoad()
if dataSource == nil {
switch mode {
case .downloaded:
dataSource = DownloadedMapsDataSource()
case .available:
dataSource = AvailableMapsDataSource(location: MWMLocationManager.lastLocation()?.coordinate)
@unknown default:
fatalError()
}
}
tableView.registerNib(cell: MWMMapDownloaderTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderPlaceTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderLargeCountryTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderSubplaceTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderButtonTableViewCell.self)
title = dataSource.title
if mode == .downloaded {
let addMapsButton = button(with: UIImage(named: "ic_nav_bar_add"), action: #selector(onAddMaps))
navigationItem.rightBarButtonItem = addMapsButton
}
Storage.shared().add(self)
noMapsContainer.isHidden = !dataSource.isEmpty || Storage.shared().downloadInProgress()
if !dataSource.isRoot {
searchBarTopOffset.constant = -searchBar.frame.height
} else {
searchBar.placeholder = L("downloader_search_field_hint")
}
configButtons()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
configButtons()
}
fileprivate func showChildren(_ nodeAttrs: MapNodeAttributes) {
let vc = storyboard!.instantiateViewController(ofType: DownloadMapsViewController.self)
vc.mode = mode
vc.dataSource = dataSource.dataSourceFor(nodeAttrs.countryId)
navigationController?.pushViewController(vc, animated: true)
}
fileprivate func showActions(_ nodeAttrs: MapNodeAttributes, in cell: UITableViewCell) {
let menuTitle = nodeAttrs.nodeName
let multiparent = nodeAttrs.parentInfo.count > 1
let message = dataSource.isRoot || multiparent ? nil : nodeAttrs.parentInfo.first?.countryName
let actionSheet = UIAlertController(title: menuTitle, message: message, preferredStyle: .actionSheet)
actionSheet.popoverPresentationController?.sourceView = cell
actionSheet.popoverPresentationController?.sourceRect = cell.bounds
let actions: [NodeAction]
switch nodeAttrs.nodeStatus {
case .undefined:
actions = []
case .downloading, .applying, .inQueue:
actions = [.cancelDownload]
case .error:
actions = nodeAttrs.downloadedMwmCount > 0 ? [.retryDownload, .delete] : [.retryDownload]
case .onDiskOutOfDate:
actions = [.showOnMap, .update, .delete]
case .onDisk:
actions = [.showOnMap, .delete]
case .notDownloaded:
actions = [.download]
case .partly:
actions = [.download, .delete]
@unknown default:
fatalError()
}
addActions(actions, for: nodeAttrs, to: actionSheet)
actionSheet.addAction(UIAlertAction(title: L("cancel"), style: .cancel))
present(actionSheet, animated: true)
}
private func addActions(_ actions: [NodeAction], for nodeAttrs: MapNodeAttributes, to actionSheet: UIAlertController) {
actions.forEach { [unowned self] in
let action: UIAlertAction
switch $0 {
case .showOnMap:
action = UIAlertAction(title: L("zoom_to_country"), style: .default, handler: { _ in
Storage.shared().showNode(nodeAttrs.countryId)
self.navigationController?.popToRootViewController(animated: true)
})
case .download:
let prefix = nodeAttrs.totalMwmCount == 1 ? L("downloader_download_map") : L("downloader_download_all_button")
action = UIAlertAction(title: "\(prefix) (\(formattedSize(nodeAttrs.totalSize)))",
style: .default,
handler: { _ in
Storage.shared().downloadNode(nodeAttrs.countryId)
})
case .update:
let size = formattedSize(nodeAttrs.totalUpdateSizeBytes)
let title = "\(L("downloader_status_outdated")) \(size)"
action = UIAlertAction(title: title, style: .default, handler: { _ in
Storage.shared().updateNode(nodeAttrs.countryId)
})
case .cancelDownload:
action = UIAlertAction(title: L("cancel_download"), style: .destructive, handler: { _ in
Storage.shared().cancelDownloadNode(nodeAttrs.countryId)
Statistics.logEvent(kStatDownloaderDownloadCancel, withParameters: [kStatFrom: kStatMap])
})
case .retryDownload:
action = UIAlertAction(title: L("downloader_retry"), style: .destructive, handler: { _ in
Storage.shared().retryDownloadNode(nodeAttrs.countryId)
})
case .delete:
action = UIAlertAction(title: L("downloader_delete_map"), style: .destructive, handler: { _ in
Storage.shared().deleteNode(nodeAttrs.countryId)
})
}
actionSheet.addAction(action)
}
}
fileprivate func reloadData() {
tableView.reloadData()
configButtons()
}
fileprivate func configButtons() {
downloadAllView.state = .none
downloadAllView.isSizeHidden = false
let parentAttributes = dataSource.parentAttributes()
let error = parentAttributes.nodeStatus == .error || parentAttributes.nodeStatus == .undefined
let downloading = parentAttributes.nodeStatus == .downloading || parentAttributes.nodeStatus == .inQueue || parentAttributes.nodeStatus == .applying
switch mode {
case .available:
if dataSource.isRoot {
break
}
if error {
downloadAllView.state = .error
} else if downloading {
downloadAllView.state = .dowloading
} else if parentAttributes.downloadedMwmCount < parentAttributes.totalMwmCount {
downloadAllView.state = .ready
downloadAllView.style = .download
downloadAllView.downloadSize = parentAttributes.totalSize - parentAttributes.downloadedSize
}
case .downloaded:
let isUpdate = parentAttributes.totalUpdateSizeBytes > 0
let size = isUpdate ? parentAttributes.totalUpdateSizeBytes : parentAttributes.downloadingSize
if error {
downloadAllView.state = dataSource.isRoot ? .none : .error
downloadAllView.downloadSize = parentAttributes.downloadingSize
} else if downloading && dataSource is DownloadedMapsDataSource {
downloadAllView.state = .dowloading
if dataSource.isRoot {
downloadAllView.style = .download
downloadAllView.isSizeHidden = true
}
} else if isUpdate {
downloadAllView.state = .ready
downloadAllView.style = .update
downloadAllView.downloadSize = size
}
@unknown default:
fatalError()
}
}
@objc func onAddMaps() {
let vc = storyboard!.instantiateViewController(ofType: DownloadMapsViewController.self)
if !dataSource.isRoot {
vc.dataSource = AvailableMapsDataSource(dataSource.parentAttributes().countryId)
}
vc.mode = .available
navigationController?.pushViewController(vc, animated: true)
}
}
// MARK: - UITableViewDataSource
extension DownloadMapsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
dataSource.numberOfSections() + (hasAddMapSection ? 1 : 0)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if hasAddMapSection && section == dataSource.numberOfSections() {
return 1
}
return dataSource.numberOfItems(in: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if hasAddMapSection && indexPath.section == dataSource.numberOfSections() {
let cellType = MWMMapDownloaderButtonTableViewCell.self
let buttonCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
return buttonCell
}
let nodeAttrs = dataSource.item(at: indexPath)
let cell: MWMMapDownloaderTableViewCell
if nodeAttrs.hasChildren {
let cellType = MWMMapDownloaderLargeCountryTableViewCell.self
let largeCountryCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
cell = largeCountryCell
} else if let matchedName = dataSource.matchedName(at: indexPath), matchedName != nodeAttrs.nodeName {
let cellType = MWMMapDownloaderSubplaceTableViewCell.self
let subplaceCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
subplaceCell.setSubplaceText(matchedName)
cell = subplaceCell
} else if !nodeAttrs.hasParent {
let cellType = MWMMapDownloaderTableViewCell.self
let downloaderCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
cell = downloaderCell
} else {
let cellType = MWMMapDownloaderPlaceTableViewCell.self
let placeCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
cell = placeCell
}
cell.mode = dataSource.isSearching ? .available : mode
cell.config(nodeAttrs, searchQuery: searchBar.text)
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
dataSource.title(for: section)
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
dataSource.indexTitles()
}
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
index
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == dataSource.numberOfSections() {
return false
}
let nodeAttrs = dataSource.item(at: indexPath)
switch nodeAttrs.nodeStatus {
case .onDisk, .onDiskOutOfDate, .partly:
return true
default:
return false
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let nodeAttrs = dataSource.item(at: indexPath)
Storage.shared().deleteNode(nodeAttrs.countryId)
}
}
}
// MARK: - UITableViewDelegate
extension DownloadMapsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = MWMMapDownloaderCellHeader()
if section != dataSource.numberOfSections() {
headerView.text = dataSource.title(for: section)
}
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
28
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
section == dataSource.numberOfSections() - 1 ? 68 : 0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == dataSource.numberOfSections() {
onAddMaps()
return
}
let nodeAttrs = dataSource.item(at: indexPath)
if nodeAttrs.hasChildren {
showChildren(dataSource.item(at: indexPath))
return
}
showActions(nodeAttrs, in: tableView.cellForRow(at: indexPath)!)
}
}
// MARK: - UIScrollViewDelegate
extension DownloadMapsViewController: UIScrollViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
searchBar.resignFirstResponder()
}
}
// MARK: - MWMMapDownloaderTableViewCellDelegate
extension DownloadMapsViewController: MWMMapDownloaderTableViewCellDelegate {
func mapDownloaderCellDidPressProgress(_ cell: MWMMapDownloaderTableViewCell) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
let nodeAttrs = dataSource.item(at: indexPath)
switch nodeAttrs.nodeStatus {
case .undefined, .error:
Storage.shared().retryDownloadNode(nodeAttrs.countryId)
case .downloading, .applying, .inQueue:
Storage.shared().cancelDownloadNode(nodeAttrs.countryId)
Statistics.logEvent(kStatDownloaderDownloadCancel, withParameters: [kStatFrom: kStatMap])
case .onDiskOutOfDate:
Storage.shared().updateNode(nodeAttrs.countryId)
case .onDisk:
// do nothing
break
case .notDownloaded, .partly:
if nodeAttrs.hasChildren {
showChildren(nodeAttrs)
} else {
Storage.shared().downloadNode(nodeAttrs.countryId)
}
@unknown default:
fatalError()
}
}
func mapDownloaderCellDidLongPress(_ cell: MWMMapDownloaderTableViewCell) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
let nodeAttrs = dataSource.item(at: indexPath)
showActions(nodeAttrs, in: cell)
}
}
// MARK: - StorageObserver
extension DownloadMapsViewController: StorageObserver {
func processCountryEvent(_ countryId: String) {
if skipCountryEvent && countryId == dataSource.parentAttributes().countryId {
return
}
dataSource.reload {
reloadData()
noMapsContainer.isHidden = !dataSource.isEmpty || Storage.shared().downloadInProgress()
}
if countryId == dataSource.parentAttributes().countryId {
configButtons()
}
for cell in tableView.visibleCells {
guard let downloaderCell = cell as? MWMMapDownloaderTableViewCell else { continue }
if downloaderCell.nodeAttrs.countryId != countryId { continue }
guard let indexPath = tableView.indexPath(for: downloaderCell) else { return }
downloaderCell.config(dataSource.item(at: indexPath), searchQuery: searchBar.text)
}
}
func processCountry(_ countryId: String, downloadedBytes: UInt64, totalBytes: UInt64) {
for cell in tableView.visibleCells {
guard let downloaderCell = cell as? MWMMapDownloaderTableViewCell else { continue }
if downloaderCell.nodeAttrs.countryId != countryId { continue }
downloaderCell.setDownloadProgress(CGFloat(downloadedBytes) / CGFloat(totalBytes))
}
let parentAttributes = dataSource.parentAttributes()
if countryId == parentAttributes.countryId {
downloadAllView.downloadProgress = CGFloat(downloadedBytes) / CGFloat(totalBytes)
downloadAllView.downloadSize = totalBytes
} else if dataSource.isRoot && dataSource is DownloadedMapsDataSource {
downloadAllView.state = .dowloading
downloadAllView.isSizeHidden = true
}
}
}
// MARK: - UISearchBarDelegate
extension DownloadMapsViewController: UISearchBarDelegate {
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(true, animated: true)
navigationController?.setNavigationBarHidden(true, animated: true)
tableView.contentInset = .zero
tableView.scrollIndicatorInsets = .zero
return true
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(false, animated: true)
navigationController?.setNavigationBarHidden(false, animated: true)
tableView.contentInset = .zero
tableView.scrollIndicatorInsets = .zero
return true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = nil
searchBar.resignFirstResponder()
dataSource.cancelSearch()
reloadData()
noSerchResultViewController.view.isHidden = true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let locale = searchBar.textInputMode?.primaryLanguage
dataSource.search(searchText, locale: locale ?? "") { [weak self] finished in
guard let self = self else { return }
self.reloadData()
self.noSerchResultViewController.view.isHidden = !self.dataSource.isEmpty
}
}
}
// MARK: - UIBarPositioningDelegate
extension DownloadMapsViewController: UIBarPositioningDelegate {
func position(for bar: UIBarPositioning) -> UIBarPosition {
.topAttached
}
}
// MARK: - DownloadAllViewDelegate
extension DownloadMapsViewController: DownloadAllViewDelegate {
func onStateChanged(state: DownloadAllView.State) {
if state == .none {
downloadAllViewContainer.isHidden = true
tableView.contentInset = UIEdgeInsets.zero
} else {
downloadAllViewContainer.isHidden = false
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: allMapsViewBottomOffsetConstant, right: 0)
}
}
func onDownloadButtonPressed() {
skipCountryEvent = true
if mode == .downloaded {
Storage.shared().updateNode(dataSource.parentAttributes().countryId)
} else {
Storage.shared().downloadNode(dataSource.parentAttributes().countryId)
}
skipCountryEvent = false
processCountryEvent(dataSource.parentAttributes().countryId)
}
func onRetryButtonPressed() {
skipCountryEvent = true
Storage.shared().retryDownloadNode(dataSource.parentAttributes().countryId)
skipCountryEvent = false
processCountryEvent(dataSource.parentAttributes().countryId)
}
func onCancelButtonPressed() {
skipCountryEvent = true
Storage.shared().cancelDownloadNode(dataSource.parentAttributes().countryId)
Statistics.logEvent(kStatDownloaderDownloadCancel, withParameters: [kStatFrom: kStatMap])
skipCountryEvent = false
processCountryEvent(dataSource.parentAttributes().countryId)
reloadData()
}
}
| apache-2.0 | 0441f63fd6ac4d91e2af31285d144c74 | 35.779727 | 152 | 0.716451 | 5.104978 | false | false | false | false |
TeamGlobalApps/peace-corps-iOS | PeaceCorps Openings/PeaceCorps Openings/ListTableController.swift | 2 | 6775 | //
// ListTableController.swift
// PeaceCorps Openings
//
// Created by Patrick Crawford on 5/13/15.
// Copyright (c) 2015 GAI. All rights reserved.
//
import UIKit
let single = Singleton()
//class ListTable: UIViewController, UITableViewDelegate, UITableViewDataSource {
class ListTableController: UITableViewController {
// getting data from segue
var urlString:String!
var showingOnlyFavorites:Bool!
// at first, cap the number of responses to return for faster viewing
var loadLimited = false
var temp: Job!
var tempIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
if self.showingOnlyFavorites == false{
loadLimited=true
// show a "load all button", only when pulling from website / when something has loaded
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "refreshButton")
// this actually grabs the results! And can be SLOW (hence initially limiting to 25)
single.filter(self.urlString, limitload: loadLimited)
}
else{
single.showFavorites()
}
//println("it's loaded...kinda b")
}
// pressing the icon to refresh all
func refreshButton() {
loadLimited = false
single.filter(self.urlString, limitload: loadLimited)
self.tableView.reloadData()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "refreshButton")
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//let shared = single.numOfElements()
if self.showingOnlyFavorites == false{
if single.numOfElements()==0{
self.title = "No results found"
}
else if (single.numOfElements()==25 && loadLimited){
self.title = "25+ openings"
if self.showingOnlyFavorites == false{
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Load All", style: UIBarButtonItemStyle.Plain, target: self, action: "refreshButton")
}
}
else if single.numOfElements()==1{
self.title = "Found \(single.numOfElements()) opening"
}
// else if single.numOfElements()==99{
// self.title = "Found \(single.numOfElements())+ openings"
// }
else{
self.title = "Found \(single.numOfElements()) openings"
}
if Reachability.isConnectedToNetwork()==false{
self.title="No connection"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "refreshButton")
}
}
else{
self.title = "Stored Favorites"
}
return single.numOfElements()
}
override func viewWillAppear(animated: Bool) {
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: tempIndex, inSection: 0)], withRowAnimation: UITableViewRowAnimation.None)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// set the type of cell based on the storyboard cell prototype and associated class
let cell:resultsCellView = tableView.dequeueReusableCellWithIdentifier("ResultsCell", forIndexPath: indexPath) as! resultsCellView
if single.numOfElements()==0{
cell.titleLabel!.text = "No results found"
return cell
}
temp = single.getJobFromIndex(indexPath.row) //jobArray[indexPath.row]
//
// HERE we should take the information for the ith back end element of the list (i=indexPath.row)
// and set the following elements to show this.
//
// set fields from passed in data
cell.titleLabel!.text = temp.title
cell.sectorLabel!.text = temp.sector
cell.countryRegionLabel!.text = (temp.country+", "+temp.region).capitalizedString
cell.departByLabel!.text = "Departs: "+temp.staging_start_date
cell.index = indexPath.row
if temp.favorited{
cell.favButton.setImage(UIImage(named:"Star-Favorites"), forState: .Normal)
}
else{
cell.favButton.setImage(UIImage(named:"star_none"), forState: .Normal)
}
cell.backgroundColor = UIColor(red:225/256, green:223/256,blue:198/256,alpha:1)
// temporary test variable, should read from the passed in data
// also set the favorites button state.
// arrays for checking and setting which image to use
let sectormatcharray = ["Agriculture","Community","Education","Environment","Health","Youth","Youth in Development","Community Economic Development"]
let sectorimgsarray = ["sectoragriculture.jpg","sectorcommunity.jpg","sectoreducation.jpg","sectorenvironment.jpg","sectorhealth.jpg","sectoryouth.jpg","sectoryouth.jpg","sectorcommunity.jpg"]
// make similar arrays for the region.. then make background of cell colored and the actual
// image be the region
// set the correct sector image icon
for i in 0...(sectormatcharray.count-1){
//println(i)
if temp.sector == sectormatcharray[i]{
cell.imgView.image = UIImage(named:sectorimgsarray[i])
}
}
// default case = no image, if there isn't a match
return cell
}
// run the segue transition on tapping an entry
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tempIndex = indexPath.row // set this so we know how many in the linked list to move through // was before
self.performSegueWithIdentifier("toResult", sender: indexPath);
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "toResult") {
// Assign the variable to the value from the node here
// instead of all this.. just pass the job INDEX in the singleton.
var destinationVC:ResultEntryController = ResultEntryController()
destinationVC = segue.destinationViewController as! ResultEntryController
destinationVC.indexRow = tempIndex
}
}
}
| mit | 8d4b75cc3531a8a4138c7fb3d4190900 | 38.852941 | 200 | 0.622435 | 5.163872 | false | false | false | false |
bouwman/LayoutResearch | LayoutResearch/Model/Study/StudyService.swift | 1 | 18659 | //
// StudyService.swift
// LayoutResearch
//
// Created by Tassilo Bouwman on 25.07.17.
// Copyright © 2017 Tassilo Bouwman. All rights reserved.
//
import ResearchKit
import GameplayKit
enum OrganisationType {
case random, stable
}
class SearchItem: NSObject, SearchItemProtocol, NSCoding {
var identifier: String
var colorId: Int
var shapeId: Int
var sharedColorCount: Int
init(identifier: String, colorId: Int, shapeId: Int, sharedColorCount: Int) {
self.identifier = identifier
self.colorId = colorId
self.shapeId = shapeId
self.sharedColorCount = sharedColorCount
super.init()
}
override var description: String {
return identifier
}
// MARK: - NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(identifier, forKey: "identifier")
aCoder.encode(colorId, forKey: "colorId")
aCoder.encode(shapeId, forKey: "shapeId")
aCoder.encode(sharedColorCount, forKey: "sharedColorCount")
}
required init?(coder aDecoder: NSCoder) {
identifier = aDecoder.decodeObject(forKey: "identifier") as! String
colorId = aDecoder.decodeInteger(forKey: "colorId")
shapeId = aDecoder.decodeInteger(forKey: "shapeId")
sharedColorCount = aDecoder.decodeInteger(forKey: "sharedColorCount")
super.init()
}
}
class StudyService {
var steps: [ORKStep] = []
var activityNumber: Int
var settings: StudySettings
private var searchItems: [[SearchItemProtocol]] = []
private var targetItems: [SearchItemProtocol] = []
init(settings: StudySettings, activityNumber: Int) {
self.settings = settings
self.activityNumber = activityNumber
// Random shapes
var shapeIDs: [Int] = []
if activityNumber == 0 || settings.group.organisation == .random {
for i in 1...24 {
shapeIDs.append(i)
}
shapeIDs.shuffle()
UserDefaults.standard.set(shapeIDs, forKey: SettingsString.lastUsedShapeIDs.rawValue)
} else {
shapeIDs = UserDefaults.standard.array(forKey: SettingsString.lastUsedShapeIDs.rawValue) as! [Int]
}
// Create base item array
var counter = 1
for row in 0..<settings.rowCount {
var rowItems: [SearchItemProtocol] = []
for column in 0..<settings.columnCount {
let colorId = staticColors[row][column]
let shapeId = shapeIDs[counter-1]
let sharedColorCount = countColorsIn(colorArray: staticColors, colorId: colorId)
let item = SearchItem(identifier: "\(counter)", colorId: colorId, shapeId: shapeId, sharedColorCount: sharedColorCount)
rowItems.append(item)
targetItems.append(item)
// Counters
counter += 1
}
searchItems.append(rowItems)
}
// Create targets
targetItems = settings.group.targetItemsFrom(searchItems: searchItems)
// Shuffle if not using designed layout
if settings.group.isDesignedLayout == false {
if activityNumber == 0 || settings.group.organisation == .random {
searchItems.shuffle()
store(searchItems: searchItems)
} else {
searchItems = loadSearchItems(rowCount: settings.rowCount, columnCount: settings.columnCount)
}
}
// Create intro step
var trialCounter = 0
let layouts = settings.group.layouts
let randomGen = GKShuffledDistribution(lowestValue: 0, highestValue: 2)
let introStep = ORKInstructionStep(identifier: "IntroStep")
introStep.title = "Introduction"
introStep.text = "Please read this carefully.\n\nTry to find an icon as quickly as possible.\n\nAt the start of each trial, you are told which icon you are looking for.\n\nYou start a trial by clicking on the 'Next' button shown under the description. The 'Next' button will appear after 1 second. On pressing the button, the icon image will disappear, and the menu appears.\nTry to locate the item as quickly as possible and click on it.\n\nAs soon as you select the correct item you are taken to the next trial. If you selected the wrong trial, the description of the item will be shown again."
steps.append(introStep)
// Practice steps
// Create practice intro step
let practiceIntroStep = ORKActiveStep(identifier: "PracticeIntroStep")
practiceIntroStep.title = "Practice"
practiceIntroStep.text = "Use the next few trials to become familiar with the search task. Press next to begin."
steps.append(practiceIntroStep)
// Create practice steps
let practiceTargets = settings.group.practiceTargetItemsFrom(searchItems: searchItems)
for i in 0..<settings.practiceTrialCount {
addTrialStepsFor(index: trialCounter, layout: layouts.first!, target: practiceTargets[i], targetDescriptionPosition: randomGen.nextInt(), isPractice: true)
trialCounter += 1
}
// Create experiment start step
let normalIntroStep = ORKActiveStep(identifier: "NormalIntroStep")
normalIntroStep.title = "Start of Experiment"
normalIntroStep.text = "You have completed the practice trials. Press next to begin the experiment."
steps.append(normalIntroStep)
// Create normal steps
for (i, layout) in layouts.enumerated() {
// Not add layout intro after intro
if i != 0 {
// Take a break
// let waitStep = ORKCountdownStep(identifier: "CountdownStep\(layouts.count + i)")
// waitStep.title = "Break"
// waitStep.text = "Take a short break before you continue."
// waitStep.stepDuration = 15
// waitStep.shouldStartTimerAutomatically = true
// waitStep.shouldShowDefaultTimer = true
// steps.append(waitStep)
// Introduce new layout
let itemDistance = itemDistanceWithEqualWhiteSpaceFor(layout: layout, itemDiameter: settings.itemDiameter, itemDistance: settings.group.itemDistance)
let newLayoutStep = LayoutIntroStep(identifier: "NewLayoutStep\(layouts.count + i)", layout: layout, itemDiameter: settings.itemDiameter, itemDistance: itemDistance)
newLayoutStep.title = "New Layout"
newLayoutStep.text = "The next layout will be different but the task is the same: Locate the target as quickly as possible."
steps.append(newLayoutStep)
}
// Create steps for every target
for i in 0..<targetItems.count {
addTrialStepsFor(index: trialCounter, layout: layout, target: targetItems[i], targetDescriptionPosition: randomGen.nextInt(), isPractice: false)
trialCounter += 1
}
}
// Add thank you step
let completionStep = ORKCompletionStep(identifier: "CompletionStep")
completionStep.title = "Thank you!"
completionStep.text = "Thank you for completing the task."
steps.append(completionStep)
}
private func addTrialStepsFor(index: Int, layout: LayoutType, target: SearchItemProtocol, targetDescriptionPosition: Int, isPractice: Bool) {
// Shuffle layout for every trial if random
if settings.group.organisation == .random {
if settings.group.isDesignedLayout == false {
shuffle2dArray(&searchItems)
} else {
shuffle2dArrayMaintainingColorDistance(&searchItems)
// Shuffle again if target has not the distance it should have
shuffleSearchItemsIfNeededFor(target: target)
}
}
let targetsBeforeIndex = targetItems[0...(index % targetItems.count)]
let targetsOfTargetType = targetsBeforeIndex.filter { $0.colorId == target.colorId && $0.shapeId == target.shapeId }
let targetTrialNumber = targetsOfTargetType.count
let searchStepIdentifier = "\(index)"
let itemDistance = itemDistanceWithEqualWhiteSpaceFor(layout: layout, itemDiameter: settings.itemDiameter, itemDistance: settings.group.itemDistance)
let stepSettings = StepSettings(activityNumber: activityNumber, trialNumber: index, targetItem: target, targetDescriptionPosition: targetDescriptionPosition, targetTrialNumber: targetTrialNumber, layout: layout, organisation: settings.group.organisation, participantGroup: settings.group, itemCount: settings.rowCount * settings.columnCount, itemDiameter: settings.itemDiameter, itemDistance: itemDistance, isPractice: isPractice)
let descriptionStep = SearchDescriptionStep(identifier: "SearchDescription\(searchStepIdentifier)", settings: stepSettings)
let searchStep = SearchStep(identifier: searchStepIdentifier, participantIdentifier: settings.participant, items: searchItems, targetFrequency: countFrequencyOf(target: target), settings: stepSettings)
steps.append(descriptionStep)
steps.append(searchStep)
}
private func shuffle2dArrayMaintainingColorDistance(_ array: inout [[SearchItemProtocol]]) {
// Rows must be even
guard array.count % 2 == 0 else { return }
let half = array.count / 2
// Swap first half with second half
for i in 0..<half {
array.swapAt(i, half + i)
// TODO: Xcode 9
// array.swapAt(i, half + i)
}
// Shuffle all rows
for (row, rowItems) in array.enumerated() {
let shuffledRow = rowItems.shuffled()
array[row] = shuffledRow
}
var middleRowItemsGrouped = false
repeat {
let middleUpperRow = array[half - 1]
let middleLowerRow = array[half]
// Make sure two items are grouped in the middle
let upperItemColumn = middleUpperRow.firstIndex(where: { $0.sharedColorCount == settings.distractorColorLowCount })
let lowerItemColumn = middleLowerRow.firstIndex(where: { $0.sharedColorCount == settings.distractorColorLowCount })
// Stop if on top of each other
if upperItemColumn == lowerItemColumn {
middleRowItemsGrouped = true
} else { // Shuffle a
array[half - 1] = middleUpperRow.shuffled()
array[half] = middleLowerRow.shuffled()
}
} while (middleRowItemsGrouped == false)
var apartItemsUpOnSameColumn = true
var apartItemsDownOnSameColumn = true
repeat {
let apartId = Const.StudyParameters.colorIdApartCondition
let itemIndexRow1 = array[0].firstIndex(where: { $0.colorId == apartId })
let itemIndexRow2 = array[1].firstIndex(where: { $0.colorId == apartId })
let itemIndexRow3 = array[2].firstIndex(where: { $0.colorId == apartId })
let itemIndexRowLast3 = array[array.count - 3].firstIndex(where: { $0.colorId == apartId })
let itemIndexRowLast2 = array[array.count - 2].firstIndex(where: { $0.colorId == apartId })
let itemIndexRowLast1 = array[array.count - 1].firstIndex(where: { $0.colorId == apartId })
if itemIndexRow2 == itemIndexRow1 || itemIndexRow2 == itemIndexRow3 {
array[1].shuffle()
apartItemsUpOnSameColumn = true
} else {
apartItemsUpOnSameColumn = false
}
if itemIndexRowLast2 == itemIndexRowLast3 || itemIndexRowLast2 == itemIndexRowLast1 {
array[array.count - 2].shuffle()
apartItemsDownOnSameColumn = true
} else {
apartItemsDownOnSameColumn = false
}
} while (apartItemsUpOnSameColumn || apartItemsDownOnSameColumn)
}
private func shuffle2dArray(_ array: inout [[SearchItemProtocol]]) {
let flatMap = array.flatMap { $0 }
let itemsShuffled = flatMap.shuffled()
var itemCounter = 0
for (row, rowItems) in array.enumerated() {
for (column, _) in rowItems.enumerated() {
array[row][column] = itemsShuffled[itemCounter]
itemCounter += 1
}
}
}
var isColorFarApartCondition1LastFarApart = false
var isColorFarApartCondition2LastFarApart = false
private func countFrequencyOf(target: SearchItemProtocol) -> Int {
return (targetItems.filter { $0.colorId == target.colorId && $0.shapeId == target.shapeId }).count * settings.group.layouts.count
}
private func shuffleSearchItemsIfNeededFor(target: SearchItemProtocol) {
if target.sharedColorCount == settings.distractorColorLowCount {
for (row, rowItems) in searchItems.enumerated() {
for item in rowItems {
// Found the target item
if item.colorId == target.colorId {
let isFarApart = row == 0
let isGrouped = row == (searchItems.count / 2 - 1)
let isColorCondition1 = target.colorId == Const.StudyParameters.colorIdFarApartCondition1
let isColorCondition2 = target.colorId == Const.StudyParameters.colorIdFarApartCondition2
if isColorCondition1 {
if isGrouped && isColorFarApartCondition1LastFarApart {
isColorFarApartCondition1LastFarApart = false
} else if isGrouped && !isColorFarApartCondition1LastFarApart {
isColorFarApartCondition1LastFarApart = true
shuffle2dArrayMaintainingColorDistance(&searchItems)
} else if isFarApart && isColorFarApartCondition1LastFarApart {
isColorFarApartCondition1LastFarApart = false
shuffle2dArrayMaintainingColorDistance(&searchItems)
} else if isFarApart && !isColorFarApartCondition1LastFarApart {
isColorFarApartCondition1LastFarApart = true
}
} else if isColorCondition2 {
if isGrouped && isColorFarApartCondition2LastFarApart {
isColorFarApartCondition2LastFarApart = false
} else if isGrouped && !isColorFarApartCondition2LastFarApart {
isColorFarApartCondition2LastFarApart = true
shuffle2dArrayMaintainingColorDistance(&searchItems)
} else if isFarApart && isColorFarApartCondition2LastFarApart {
isColorFarApartCondition2LastFarApart = false
shuffle2dArrayMaintainingColorDistance(&searchItems)
} else if isFarApart && !isColorFarApartCondition2LastFarApart {
isColorFarApartCondition2LastFarApart = true
}
}
break
}
}
}
}
}
private func otherColorDistractorCountLowId(colorId: Int) -> Int {
if colorId == Const.StudyParameters.colorIdFarApartCondition1 {
return Const.StudyParameters.colorIdFarApartCondition2
} else {
return Const.StudyParameters.colorIdFarApartCondition1
}
}
private var staticColors: [[Int]] {
var colors: [[Int]] = []
let c = Const.StudyParameters.colorIdFarApartCondition1 // 5
let d = Const.StudyParameters.colorIdFarApartCondition2 // 6
let a = Const.StudyParameters.colorIdApartCondition // 2
let colorRow1 = [1, 1, c, a, 0, 0, 0, 0, 0, 0]
let colorRow2 = [1, a, 3, 1, 0, 0, 0, 0, 0, 0]
let colorRow3 = [a, 1, d, 1, 0, 0, 0, 0, 0, 0]
let colorRow4 = [4, a, d, 4, 0, 0, 0, 0, 0, 0]
let colorRow5 = [4, 3, 4, a, 0, 0, 0, 0, 0, 0]
let colorRow6 = [a, c, 4, 4, 0, 0, 0, 0, 0, 0]
let colorRow7 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let colorRow8 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let colorRow9 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let colorRow10 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
colors.append(colorRow1)
colors.append(colorRow2)
colors.append(colorRow3)
colors.append(colorRow4)
colors.append(colorRow5)
colors.append(colorRow6)
colors.append(colorRow7)
colors.append(colorRow8)
colors.append(colorRow9)
colors.append(colorRow10)
return colors
}
private func countColorsIn(colorArray: [[Int]], colorId: Int) -> Int {
var counter = 0
for itemRow in colorArray {
for item in itemRow {
if item == colorId {
counter += 1
}
}
}
return counter
}
private func store(searchItems: [[SearchItemProtocol]]) {
for (i, row) in searchItems.enumerated() {
for (j, column) in row.enumerated() {
let encodedData = NSKeyedArchiver.archivedData(withRootObject: column)
UserDefaults.standard.set(encodedData, forKey: SettingsString.lastUsedSearchItems.rawValue + "\(i)\(j)")
}
}
}
private func loadSearchItems(rowCount: Int, columnCount: Int) -> [[SearchItemProtocol]] {
var searchItems: [[SearchItemProtocol]] = []
for i in 0..<rowCount {
var row: [SearchItemProtocol] = []
for j in 0..<columnCount {
let encodedData = UserDefaults.standard.object(forKey: SettingsString.lastUsedSearchItems.rawValue + "\(i)\(j)") as! Data
let searchItem = NSKeyedUnarchiver.unarchiveObject(with: encodedData) as! SearchItemProtocol
row.append(searchItem)
}
searchItems.append(row)
}
return searchItems
}
}
| mit | 48b79c9863c8c617f3025a1e3970a082 | 45.879397 | 604 | 0.602959 | 5.217562 | false | false | false | false |
lstanii-magnet/ChatKitSample-iOS | ChatMessenger/Pods/ChatKit/ChatKit/source/ChatKit/DefaultChatListControllerDatasource.swift | 1 | 5173 | /*
* Copyright (c) 2016 Magnet Systems, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import UIKit
import CocoaLumberjack
import MagnetMax
public class DefaultChatListControllerDatasource : NSObject, ChatListControllerDatasource {
//MARK : Public Variables
public weak var controller : MMXChatListViewController?
public var hasMoreUsers : Bool = true
public private(set) var channels : [MMXChannel] = []
public let limit = 30
// Public Functions
public func createChat(from subscribers : [MMUser]) {
let id = NSUUID().UUIDString
MMXChannel.createWithName(id, summary: id, isPublic: false, publishPermissions: .Anyone, subscribers: Set(subscribers), success: { (channel) -> Void in
self.controller?.reloadData()
DDLogVerbose("[Channel Created] - (\(channel.name))")
}) { (error) -> Void in
DDLogError("[Error] - \(error.localizedDescription)")
}
}
public func subscribedChannels(completion : ((channels : [MMXChannel]) -> Void)) {
MMXChannel.subscribedChannelsWithSuccess({ ch in
self.channels = ch
completion(channels: self.channels)
DDLogVerbose("[Retireved] - Channels (\(self.channels.count))")
}) { error in
completion(channels: [])
DDLogError("[Error] - \(error.localizedDescription)")
}
}
//Mark: ChatListControllerDatasource
public func mmxControllerHasMore() -> Bool {
return self.hasMoreUsers
}
public func mmxControllerSearchUpdatesContinuously() ->Bool {
return true
}
public func mmxControllerLoadMore(searchText : String?, offset : Int) {
self.hasMoreUsers = offset == 0 ? true : self.hasMoreUsers
//get request context
let loadingContext = controller?.loadingContext()
subscribedChannels({ channels in
if loadingContext != self.controller?.loadingContext() {
return
}
var offsetChannels : [MMXChannel] = []
if offset < channels.count {
offsetChannels = Array(channels[offset..<min((offset + self.limit), channels.count)])
} else {
self.hasMoreUsers = false
}
self.controller?.append(offsetChannels)
})
}
public func mmxListImageForChannelDetails(imageView: UIImageView, channelDetails: MMXChannelDetailResponse) {
if channelDetails.subscriberCount > 2 {
let image = UIImage(named: "user_group_clear.png", inBundle: NSBundle(forClass: DefaultChatListControllerDatasource.self), compatibleWithTraitCollection: nil)
imageView.backgroundColor = controller?.appearance.tintColor
imageView.image = image
} else {
var subscribers = channelDetails.subscribers.filter({$0.userId != MMUser.currentUser()?.userID})
if subscribers.count == 0 {
subscribers = channelDetails.subscribers
}
if let userProfile = subscribers.first {
let tmpUser = MMUser()
tmpUser.extras = ["hasAvatar" : "true"]
var fName : String?
var lName : String?
let nameComponents = userProfile.displayName.componentsSeparatedByString(" ")
if let lastName = nameComponents.last where nameComponents.count > 1 {
lName = lastName
}
if let firstName = nameComponents.first {
fName = firstName
}
tmpUser.firstName = ""
tmpUser.lastName = ""
tmpUser.userName = userProfile.displayName
tmpUser.userID = userProfile.userId
let defaultImage = Utils.noAvatarImageForUser(fName, lastName: lName)
Utils.loadImageWithUrl(tmpUser.avatarURL(), toImageView: imageView, placeholderImage:defaultImage)
}
}
}
public func mmxListCellForMMXChannel(tableView : UITableView,channel : MMXChannel, channelDetails : MMXChannelDetailResponse, row : Int) -> UITableViewCell? {
return nil
}
public func mmxListCellHeightForMMXChannel(channel : MMXChannel, channelDetails : MMXChannelDetailResponse, row : Int) -> CGFloat {
return 80
}
public func mmxListRegisterCells(tableView : UITableView) {
//using standard cells
}
}
| apache-2.0 | 3ee873e11221cbb6c2e63613fa1cbd2c | 36.485507 | 170 | 0.613957 | 5.411088 | false | false | false | false |
plivesey/SwiftGen | Pods/PathKit/Sources/PathKit.swift | 2 | 19773 | // PathKit - Effortless path operations
#if os(Linux)
import Glibc
let system_glob = Glibc.glob
#else
import Darwin
let system_glob = Darwin.glob
#endif
import Foundation
/// Represents a filesystem path.
public struct Path {
/// The character used by the OS to separate two path elements
public static let separator = "/"
/// The underlying string representation
internal var path: String
internal static var fileManager = FileManager.default
// MARK: Init
public init() {
self.path = ""
}
/// Create a Path from a given String
public init(_ path: String) {
self.path = path
}
/// Create a Path by joining multiple path components together
public init<S : Collection>(components: S) where S.Iterator.Element == String {
if components.isEmpty {
path = "."
} else if components.first == Path.separator && components.count > 1 {
let p = components.joined(separator: Path.separator)
path = p.substring(from: p.characters.index(after: p.startIndex))
} else {
path = components.joined(separator: Path.separator)
}
}
}
// MARK: StringLiteralConvertible
extension Path : ExpressibleByStringLiteral {
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public typealias UnicodeScalarLiteralType = StringLiteralType
public init(extendedGraphemeClusterLiteral path: StringLiteralType) {
self.init(stringLiteral: path)
}
public init(unicodeScalarLiteral path: StringLiteralType) {
self.init(stringLiteral: path)
}
public init(stringLiteral value: StringLiteralType) {
self.path = value
}
}
// MARK: CustomStringConvertible
extension Path : CustomStringConvertible {
public var description: String {
return self.path
}
}
// MARK: Hashable
extension Path : Hashable {
public var hashValue: Int {
return path.hashValue
}
}
// MARK: Path Info
extension Path {
/// Test whether a path is absolute.
///
/// - Returns: `true` iff the path begings with a slash
///
public var isAbsolute: Bool {
return path.hasPrefix(Path.separator)
}
/// Test whether a path is relative.
///
/// - Returns: `true` iff a path is relative (not absolute)
///
public var isRelative: Bool {
return !isAbsolute
}
/// Concatenates relative paths to the current directory and derives the normalized path
///
/// - Returns: the absolute path in the actual filesystem
///
public func absolute() -> Path {
if isAbsolute {
return normalize()
}
return (Path.current + self).normalize()
}
/// Normalizes the path, this cleans up redundant ".." and ".", double slashes
/// and resolves "~".
///
/// - Returns: a new path made by removing extraneous path components from the underlying String
/// representation.
///
public func normalize() -> Path {
return Path(NSString(string: self.path).standardizingPath)
}
/// De-normalizes the path, by replacing the current user home directory with "~".
///
/// - Returns: a new path made by removing extraneous path components from the underlying String
/// representation.
///
public func abbreviate() -> Path {
#if os(Linux)
// TODO: actually de-normalize the path
return self
#else
return Path(NSString(string: self.path).abbreviatingWithTildeInPath)
#endif
}
/// Returns the path of the item pointed to by a symbolic link.
///
/// - Returns: the path of directory or file to which the symbolic link refers
///
public func symlinkDestination() throws -> Path {
let symlinkDestination = try Path.fileManager.destinationOfSymbolicLink(atPath: path)
let symlinkPath = Path(symlinkDestination)
if symlinkPath.isRelative {
return self + ".." + symlinkPath
} else {
return symlinkPath
}
}
}
// MARK: Path Components
extension Path {
/// The last path component
///
/// - Returns: the last path component
///
public var lastComponent: String {
return NSString(string: path).lastPathComponent
}
/// The last path component without file extension
///
/// - Note: This returns "." for "..".
///
/// - Returns: the last path component without file extension
///
public var lastComponentWithoutExtension: String {
return NSString(string: lastComponent).deletingPathExtension
}
/// Splits the string representation on the directory separator.
/// Absolute paths remain the leading slash as first component.
///
/// - Returns: all path components
///
public var components: [String] {
return NSString(string: path).pathComponents
}
/// The file extension behind the last dot of the last component.
///
/// - Returns: the file extension
///
public var `extension`: String? {
let pathExtension = NSString(string: path).pathExtension
if pathExtension.isEmpty {
return nil
}
return pathExtension
}
}
// MARK: File Info
extension Path {
/// Test whether a file or directory exists at a specified path
///
/// - Returns: `false` iff the path doesn't exist on disk or its existence could not be
/// determined
///
public var exists: Bool {
return Path.fileManager.fileExists(atPath: self.path)
}
/// Test whether a path is a directory.
///
/// - Returns: `true` if the path is a directory or a symbolic link that points to a directory;
/// `false` if the path is not a directory or the path doesn't exist on disk or its existence
/// could not be determined
///
public var isDirectory: Bool {
var directory = ObjCBool(false)
guard Path.fileManager.fileExists(atPath: normalize().path, isDirectory: &directory) else {
return false
}
#if os(Linux)
return directory
#else
return directory.boolValue
#endif
}
/// Test whether a path is a regular file.
///
/// - Returns: `true` if the path is neither a directory nor a symbolic link that points to a
/// directory; `false` if the path is a directory or a symbolic link that points to a
/// directory or the path doesn't exist on disk or its existence
/// could not be determined
///
public var isFile: Bool {
var directory = ObjCBool(false)
guard Path.fileManager.fileExists(atPath: normalize().path, isDirectory: &directory) else {
return false
}
#if os(Linux)
return !directory
#else
return !directory.boolValue
#endif
}
/// Test whether a path is a symbolic link.
///
/// - Returns: `true` if the path is a symbolic link; `false` if the path doesn't exist on disk
/// or its existence could not be determined
///
public var isSymlink: Bool {
do {
let _ = try Path.fileManager.destinationOfSymbolicLink(atPath: path)
return true
} catch {
return false
}
}
/// Test whether a path is readable
///
/// - Returns: `true` if the current process has read privileges for the file at path;
/// otherwise `false` if the process does not have read privileges or the existence of the
/// file could not be determined.
///
public var isReadable: Bool {
return Path.fileManager.isReadableFile(atPath: self.path)
}
/// Test whether a path is writeable
///
/// - Returns: `true` if the current process has write privileges for the file at path;
/// otherwise `false` if the process does not have write privileges or the existence of the
/// file could not be determined.
///
public var isWritable: Bool {
return Path.fileManager.isWritableFile(atPath: self.path)
}
/// Test whether a path is executable
///
/// - Returns: `true` if the current process has execute privileges for the file at path;
/// otherwise `false` if the process does not have execute privileges or the existence of the
/// file could not be determined.
///
public var isExecutable: Bool {
return Path.fileManager.isExecutableFile(atPath: self.path)
}
/// Test whether a path is deletable
///
/// - Returns: `true` if the current process has delete privileges for the file at path;
/// otherwise `false` if the process does not have delete privileges or the existence of the
/// file could not be determined.
///
public var isDeletable: Bool {
return Path.fileManager.isDeletableFile(atPath: self.path)
}
}
// MARK: File Manipulation
extension Path {
/// Create the directory.
///
/// - Note: This method fails if any of the intermediate parent directories does not exist.
/// This method also fails if any of the intermediate path elements corresponds to a file and
/// not a directory.
///
public func mkdir() throws -> () {
try Path.fileManager.createDirectory(atPath: self.path, withIntermediateDirectories: false, attributes: nil)
}
/// Create the directory and any intermediate parent directories that do not exist.
///
/// - Note: This method fails if any of the intermediate path elements corresponds to a file and
/// not a directory.
///
public func mkpath() throws -> () {
try Path.fileManager.createDirectory(atPath: self.path, withIntermediateDirectories: true, attributes: nil)
}
/// Delete the file or directory.
///
/// - Note: If the path specifies a directory, the contents of that directory are recursively
/// removed.
///
public func delete() throws -> () {
try Path.fileManager.removeItem(atPath: self.path)
}
/// Move the file or directory to a new location synchronously.
///
/// - Parameter destination: The new path. This path must include the name of the file or
/// directory in its new location.
///
public func move(_ destination: Path) throws -> () {
try Path.fileManager.moveItem(atPath: self.path, toPath: destination.path)
}
/// Copy the file or directory to a new location synchronously.
///
/// - Parameter destination: The new path. This path must include the name of the file or
/// directory in its new location.
///
public func copy(_ destination: Path) throws -> () {
try Path.fileManager.copyItem(atPath: self.path, toPath: destination.path)
}
/// Creates a hard link at a new destination.
///
/// - Parameter destination: The location where the link will be created.
///
public func link(_ destination: Path) throws -> () {
try Path.fileManager.linkItem(atPath: self.path, toPath: destination.path)
}
/// Creates a symbolic link at a new destination.
///
/// - Parameter destintation: The location where the link will be created.
///
public func symlink(_ destination: Path) throws -> () {
try Path.fileManager.createSymbolicLink(atPath: self.path, withDestinationPath: destination.path)
}
}
// MARK: Current Directory
extension Path {
/// The current working directory of the process
///
/// - Returns: the current working directory of the process
///
public static var current: Path {
get {
return self.init(Path.fileManager.currentDirectoryPath)
}
set {
_ = Path.fileManager.changeCurrentDirectoryPath(newValue.description)
}
}
/// Changes the current working directory of the process to the path during the execution of the
/// given block.
///
/// - Note: The original working directory is restored when the block returns or throws.
/// - Parameter closure: A closure to be executed while the current directory is configured to
/// the path.
///
public func chdir(closure: () throws -> ()) rethrows {
let previous = Path.current
Path.current = self
defer { Path.current = previous }
try closure()
}
}
// MARK: Temporary
extension Path {
/// - Returns: the path to either the user’s or application’s home directory,
/// depending on the platform.
///
public static var home: Path {
return Path(NSHomeDirectory())
}
/// - Returns: the path of the temporary directory for the current user.
///
public static var temporary: Path {
return Path(NSTemporaryDirectory())
}
/// - Returns: the path of a temporary directory unique for the process.
/// - Note: Based on `NSProcessInfo.globallyUniqueString`.
///
public static func processUniqueTemporary() throws -> Path {
let path = temporary + ProcessInfo.processInfo.globallyUniqueString
if !path.exists {
try path.mkdir()
}
return path
}
/// - Returns: the path of a temporary directory unique for each call.
/// - Note: Based on `NSUUID`.
///
public static func uniqueTemporary() throws -> Path {
let path = try processUniqueTemporary() + UUID().uuidString
try path.mkdir()
return path
}
}
// MARK: Contents
extension Path {
/// Reads the file.
///
/// - Returns: the contents of the file at the specified path.
///
public func read() throws -> Data {
return try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions(rawValue: 0))
}
/// Reads the file contents and encoded its bytes to string applying the given encoding.
///
/// - Parameter encoding: the encoding which should be used to decode the data.
/// (by default: `NSUTF8StringEncoding`)
///
/// - Returns: the contents of the file at the specified path as string.
///
public func read(_ encoding: String.Encoding = String.Encoding.utf8) throws -> String {
return try NSString(contentsOfFile: path, encoding: encoding.rawValue).substring(from: 0) as String
}
/// Write a file.
///
/// - Note: Works atomically: the data is written to a backup file, and then — assuming no
/// errors occur — the backup file is renamed to the name specified by path.
///
/// - Parameter data: the contents to write to file.
///
public func write(_ data: Data) throws {
try data.write(to: URL(fileURLWithPath: normalize().path), options: .atomic)
}
/// Reads the file.
///
/// - Note: Works atomically: the data is written to a backup file, and then — assuming no
/// errors occur — the backup file is renamed to the name specified by path.
///
/// - Parameter string: the string to write to file.
///
/// - Parameter encoding: the encoding which should be used to represent the string as bytes.
/// (by default: `NSUTF8StringEncoding`)
///
/// - Returns: the contents of the file at the specified path as string.
///
public func write(_ string: String, encoding: String.Encoding = String.Encoding.utf8) throws {
try string.write(toFile: normalize().path, atomically: true, encoding: encoding)
}
}
// MARK: Traversing
extension Path {
/// Get the parent directory
///
/// - Returns: the normalized path of the parent directory
///
public func parent() -> Path {
return self + ".."
}
/// Performs a shallow enumeration in a directory
///
/// - Returns: paths to all files, directories and symbolic links contained in the directory
///
public func children() throws -> [Path] {
return try Path.fileManager.contentsOfDirectory(atPath: path).map {
self + Path($0)
}
}
/// Performs a deep enumeration in a directory
///
/// - Returns: paths to all files, directories and symbolic links contained in the directory or
/// any subdirectory.
///
public func recursiveChildren() throws -> [Path] {
return try Path.fileManager.subpathsOfDirectory(atPath: path).map {
self + Path($0)
}
}
}
// MARK: Globbing
extension Path {
public static func glob(_ pattern: String) -> [Path] {
var gt = glob_t()
let cPattern = strdup(pattern)
defer {
globfree(>)
free(cPattern)
}
let flags = GLOB_TILDE | GLOB_BRACE | GLOB_MARK
if system_glob(cPattern, flags, nil, >) == 0 {
#if os(Linux)
let matchc = gt.gl_pathc
#else
let matchc = gt.gl_matchc
#endif
return (0..<Int(matchc)).flatMap { index in
if let path = String(validatingUTF8: gt.gl_pathv[index]!) {
return Path(path)
}
return nil
}
}
// GLOB_NOMATCH
return []
}
public func glob(_ pattern: String) -> [Path] {
return Path.glob((self + pattern).description)
}
}
// MARK: SequenceType
extension Path : Sequence {
/// Enumerates the contents of a directory, returning the paths of all files and directories
/// contained within that directory. These paths are relative to the directory.
public struct DirectoryEnumerator : IteratorProtocol {
public typealias Element = Path
let path: Path
let directoryEnumerator: FileManager.DirectoryEnumerator
init(path: Path) {
self.path = path
self.directoryEnumerator = Path.fileManager.enumerator(atPath: path.path)!
}
public func next() -> Path? {
if let next = directoryEnumerator.nextObject() as! String? {
return path + next
}
return nil
}
/// Skip recursion into the most recently obtained subdirectory.
public func skipDescendants() {
directoryEnumerator.skipDescendants()
}
}
/// Perform a deep enumeration of a directory.
///
/// - Returns: a directory enumerator that can be used to perform a deep enumeration of the
/// directory.
///
public func makeIterator() -> DirectoryEnumerator {
return DirectoryEnumerator(path: self)
}
}
// MARK: Equatable
extension Path : Equatable {}
/// Determines if two paths are identical
///
/// - Note: The comparison is string-based. Be aware that two different paths (foo.txt and
/// ./foo.txt) can refer to the same file.
///
public func ==(lhs: Path, rhs: Path) -> Bool {
return lhs.path == rhs.path
}
// MARK: Pattern Matching
/// Implements pattern-matching for paths.
///
/// - Returns: `true` iff one of the following conditions is true:
/// - the paths are equal (based on `Path`'s `Equatable` implementation)
/// - the paths can be normalized to equal Paths.
///
public func ~=(lhs: Path, rhs: Path) -> Bool {
return lhs == rhs
|| lhs.normalize() == rhs.normalize()
}
// MARK: Comparable
extension Path : Comparable {}
/// Defines a strict total order over Paths based on their underlying string representation.
public func <(lhs: Path, rhs: Path) -> Bool {
return lhs.path < rhs.path
}
// MARK: Operators
/// Appends a Path fragment to another Path to produce a new Path
public func +(lhs: Path, rhs: Path) -> Path {
return lhs.path + rhs.path
}
/// Appends a String fragment to another Path to produce a new Path
public func +(lhs: Path, rhs: String) -> Path {
return lhs.path + rhs
}
/// Appends a String fragment to another String to produce a new Path
internal func +(lhs: String, rhs: String) -> Path {
if rhs.hasPrefix(Path.separator) {
// Absolute paths replace relative paths
return Path(rhs)
} else {
var lSlice = NSString(string: lhs).pathComponents.fullSlice
var rSlice = NSString(string: rhs).pathComponents.fullSlice
// Get rid of trailing "/" at the left side
if lSlice.count > 1 && lSlice.last == Path.separator {
lSlice.removeLast()
}
// Advance after the first relevant "."
lSlice = lSlice.filter { $0 != "." }.fullSlice
rSlice = rSlice.filter { $0 != "." }.fullSlice
// Eats up trailing components of the left and leading ".." of the right side
while lSlice.last != ".." && rSlice.first == ".." {
if (lSlice.count > 1 || lSlice.first != Path.separator) && !lSlice.isEmpty {
// A leading "/" is never popped
lSlice.removeLast()
}
if !rSlice.isEmpty {
rSlice.removeFirst()
}
switch (lSlice.isEmpty, rSlice.isEmpty) {
case (true, _):
break
case (_, true):
break
default:
continue
}
}
return Path(components: lSlice + rSlice)
}
}
extension Array {
var fullSlice: ArraySlice<Element> {
return self[self.indices.suffix(from: 0)]
}
}
| mit | 3497303cda23e0cd64fc55562ca37492 | 27.029787 | 112 | 0.668134 | 4.308984 | false | false | false | false |
CatchChat/Yep | Yep/Views/Cells/SearchedMessage/SearchedMessageCell.swift | 1 | 3057 | //
// SearchedMessageCell.swift
// Yep
//
// Created by NIX on 16/4/5.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
final class SearchedMessageCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var messageLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
separatorInset = YepConfig.SearchedItemCell.separatorInset
}
override func prepareForReuse() {
super.prepareForReuse()
avatarImageView.image = nil
nicknameLabel.text = nil
timeLabel.text = nil
messageLabel.text = nil
}
func configureWithMessage(message: Message, keyword: String?) {
guard let user = message.fromFriend else {
return
}
let userAvatar = UserAvatar(userID: user.userID, avatarURLString: user.avatarURLString, avatarStyle: miniAvatarStyle)
avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
nicknameLabel.text = user.nickname
if let keyword = keyword {
messageLabel.attributedText = message.textContent.yep_hightlightSearchKeyword(keyword, baseFont: YepConfig.SearchedItemCell.messageFont, baseColor: YepConfig.SearchedItemCell.messageColor)
} else {
messageLabel.text = message.textContent
}
timeLabel.text = NSDate(timeIntervalSince1970: message.createdUnixTime).timeAgo.lowercaseString
}
func configureWithUserMessages(userMessages: SearchConversationsViewController.UserMessages, keyword: String?) {
let user = userMessages.user
let userAvatar = UserAvatar(userID: user.userID, avatarURLString: user.avatarURLString, avatarStyle: nanoAvatarStyle)
avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
nicknameLabel.text = user.nickname
let count = userMessages.messages.count
if let message = userMessages.messages.first {
if count > 1 {
messageLabel.textColor = UIColor.yepTintColor()
messageLabel.text = String(format: NSLocalizedString("countMessages%d", comment: ""), count)
timeLabel.hidden = true
timeLabel.text = nil
} else {
messageLabel.textColor = UIColor.blackColor()
if let keyword = keyword {
messageLabel.attributedText = message.textContent.yep_hightlightSearchKeyword(keyword, baseFont: YepConfig.SearchedItemCell.messageFont, baseColor: YepConfig.SearchedItemCell.messageColor)
} else {
messageLabel.text = message.textContent
}
timeLabel.hidden = false
timeLabel.text = NSDate(timeIntervalSince1970: message.createdUnixTime).timeAgo.lowercaseString
}
}
}
}
| mit | a429d6aed486e19a3eab2778c11ba85b | 32.56044 | 208 | 0.676162 | 5.532609 | false | true | false | false |
mrakowski/RRRUtilities | UIColor+Utilities.swift | 1 | 3347 | //
// UIColor+Utilities.swift
// RRRUtilities
//
// Created by Michael Rakowski on 8/7/16.
// Copyright © 2016 Constant Practice Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
extension UIColor {
// MARK:
class func desaturate(color: UIColor) -> UIColor {
var desaturatedColor = color
var hue : CGFloat = 0.0
var sat : CGFloat = 0.0
var bri : CGFloat = 0.0
var alp : CGFloat = 0.0
let gotHSB = color.getHue(&hue,
saturation: &sat,
brightness: &bri,
alpha: &alp)
if (gotHSB) {
desaturatedColor = UIColor.init(hue: hue/2,
saturation: sat/2,
brightness: bri/2,
alpha: alp)
}
return desaturatedColor
}
class func brighten(color: UIColor) -> UIColor {
return self.brighten(color: color, multiplier: 1.2)
}
/**
Brighten a color (modifies the brightness component in HSB color format).
# Parameters:
- color: The color to brighten
- multiplier: The brightening factor (to multiply the brightness component by)
- Returns: A brighter version of the input color (if there was an error computing the HSB representation of the color, the original color will be returned).
*/
class func brighten(color: UIColor, multiplier: CGFloat) -> UIColor {
var brighterColor = color
var hue : CGFloat = 0.0
var sat : CGFloat = 0.0
var bri : CGFloat = 0.0
var alp : CGFloat = 0.0
let gotHSB = color.getHue(&hue,
saturation: &sat,
brightness: &bri,
alpha: &alp)
if (gotHSB) {
brighterColor = UIColor.init(hue: hue,
saturation: sat,
brightness: bri*multiplier,
alpha: alp)
}
return brighterColor
}
}
| mit | 2fc1ceb5d887b24efcff9ae1fc526a44 | 34.595745 | 161 | 0.566647 | 4.898975 | false | false | false | false |
EstefaniaGilVaquero/ciceIOS | App_MVC_INTRO_WEB_SERVICE/ICOModel.swift | 1 | 654 | //
// ICOModel.swift
// App_MVC_INTRO_WEB_SERVICE
//
// Created by cice on 20/7/16.
// Copyright © 2016 cice. All rights reserved.
//
import UIKit
class ICOModel: NSObject {
var estado : String?
var jugador1 : String?
var jugador2 : String?
var resultados : String?
var resultados2 : String?
init(pEstado : String, pJugador1 : String, pJugador2 : String, pResultados : String, pResultados2 : String) {
self.estado = pEstado
self.jugador1 = pJugador1
self.jugador2 = pJugador2
self.resultados = pResultados
self.resultados2 = pResultados2
super.init()
}
}
| apache-2.0 | e4cbde69f355b3d6b0565d807a8492bf | 21.517241 | 113 | 0.627871 | 3.314721 | false | false | false | false |
cinco-interactive/BluetoothKit | Source/BKSendDataTask.swift | 1 | 2530 | //
// BluetoothKit
//
// Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth
//
// 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
internal func ==(lhs: BKSendDataTask, rhs: BKSendDataTask) -> Bool {
return lhs.destination == rhs.destination && lhs.data.isEqualToData(rhs.data)
}
internal class BKSendDataTask: Equatable {
// MARK: Properties
internal let data: NSData
internal let destination: BKRemotePeer
internal let completionHandler: BKSendDataCompletionHandler?
internal var offset = 0
internal var maximumPayloadLength: Int {
return destination.maximumUpdateValueLength
}
internal var lengthOfRemainingData: Int {
return data.length - offset
}
internal var sentAllData: Bool {
return lengthOfRemainingData == 0
}
internal var rangeForNextPayload: NSRange {
let lenghtOfNextPayload = maximumPayloadLength <= lengthOfRemainingData ? maximumPayloadLength : lengthOfRemainingData
return NSMakeRange(offset, lenghtOfNextPayload)
}
internal var nextPayload: NSData {
return data.subdataWithRange(rangeForNextPayload)
}
// MARK: Initialization
internal init(data: NSData, destination: BKRemotePeer, completionHandler: BKSendDataCompletionHandler?) {
self.data = data
self.destination = destination
self.completionHandler = completionHandler
}
}
| mit | 4bc9fc3bac33097e2ef7ccfbbe78d43e | 35.666667 | 126 | 0.72253 | 4.88417 | false | false | false | false |
apple/swift | test/attr/attr_marker_protocol.swift | 1 | 2133 | // RUN: %target-typecheck-verify-swift
// Marker protocol definition
@_marker protocol P1 {
func f() // expected-error{{marker protocol 'P1' cannot have any requirements}}
}
@_marker protocol P2 {
associatedtype AT // expected-error{{marker protocol 'P2' cannot have any requirements}}
}
@_marker protocol P3 {
typealias A = Int
}
protocol P4 { } // expected-note{{'P4' declared here}}
@_marker protocol P5: P4 { } // expected-error{{marker protocol 'P5' cannot inherit non-marker protocol 'P4'}}
class C { }
@_marker protocol P5a: AnyObject { } // okay
@_marker protocol P5b: C { } // expected-error{{marker protocol 'P5b' cannot inherit class 'C'}}
// Legitimate uses of marker protocols.
extension P3 {
func f() { }
}
extension Int: P3 { }
extension Array: P3 where Element: P3 { } // expected-note{{requirement from conditional conformance of '[Double]' to 'P3'}}
protocol P6: P3 { } // okay
@_marker protocol P7: P3 { } // okay
func genericOk<T: P3>(_: T) { }
func testGenericOk(i: Int, arr: [Int], nope: [Double], p3: P3, p3array: [P3]) {
genericOk(i)
genericOk(arr)
genericOk(nope) // expected-error{{global function 'genericOk' requires that 'Double' conform to 'P3'}}
genericOk(p3)
genericOk(p3array)
}
// Incorrect uses of marker protocols in types.
func testNotOkay(a: Any) {
var mp1: P3 = 17
_ = mp1
mp1 = 17
if let mp2 = a as? P3 { _ = mp2 } // expected-error{{marker protocol 'P3' cannot be used in a conditional cast}}
if let mp3 = a as? AnyObject & P3 { _ = mp3 } // expected-error{{marker protocol 'P3' cannot be used in a conditional cast}}
if a is AnyObject & P3 { } // expected-error{{marker protocol 'P3' cannot be used in a conditional cast}}
func inner(p3: P3) { }
}
@_marker protocol P8 { }
protocol P9: P8 { }
// Implied conditional conformance to P8 is okay because P8 is a marker
// protocol.
extension Array: P9 where Element: P9 { }
protocol P10 { }
extension Array: P10 where Element: P10, Element: P8 { }
// expected-error@-1{{conditional conformance to non-marker protocol 'P10' cannot depend on conformance of 'Element' to marker protocol 'P8'}}
| apache-2.0 | 8cfdacdfb4f0c0f03cf177f8a5148a8f | 29.913043 | 142 | 0.680263 | 3.271472 | false | false | false | false |
apple/swift | test/SILGen/objc_final.swift | 5 | 1246 | // RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-verbose-sil | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
final class Foo {
@objc func foo() {}
// CHECK-LABEL: sil private [thunk] [ossa] @$s10objc_final3FooC3foo{{[_0-9a-zA-Z]*}}FTo
@objc var prop: Int = 0
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s10objc_final3FooC4propSivgTo
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s10objc_final3FooC4propSivsTo
}
// CHECK-LABEL: sil hidden [ossa] @$s10objc_final7callFooyyAA0D0CF
func callFoo(_ x: Foo) {
// Calls to the final @objc method statically reference the native entry
// point.
// CHECK: function_ref @$s10objc_final3FooC3foo{{[_0-9a-zA-Z]*}}F
x.foo()
// Final @objc properties are still accessed directly.
// CHECK: [[PROP:%.*]] = ref_element_addr {{%.*}} : $Foo, #Foo.prop
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[PROP]] : $*Int
// CHECK: load [trivial] [[READ]] : $*Int
let prop = x.prop
// CHECK: [[PROP:%.*]] = ref_element_addr {{%.*}} : $Foo, #Foo.prop
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[PROP]] : $*Int
// CHECK: assign {{%.*}} to [[WRITE]] : $*Int
x.prop = prop
}
| apache-2.0 | 4ad16fd48ce7d5f3de403bc4215dafae | 37.9375 | 120 | 0.630016 | 3.115 | false | false | false | false |
LiulietLee/BilibiliCD | BCD/Model/CoreData/SettingManager.swift | 1 | 1369 | //
// SettingManager.swift
// BCD
//
// Created by Liuliet.Lee on 27/6/2018.
// Copyright © 2018 Liuliet.Lee. All rights reserved.
//
import Foundation
import CoreData
class SettingManager: CoreDataModel {
private func initSetting() {
let initHistoryNum: Int16 = 120
let entity = NSEntityDescription.entity(forEntityName: "Setting", in: context)!
let newItem = Setting(entity: entity, insertInto: context)
newItem.historyNumber = initHistoryNum
saveContext()
}
private var setting: Setting? {
do {
let searchResults = try context.fetch(Setting.fetchRequest())
if searchResults.count == 0 {
initSetting()
return self.setting
} else {
return searchResults[0] as? Setting
}
} catch {
print(error)
}
return nil
}
var historyItemLimit: Int! {
get {
return Int(setting?.historyNumber ?? 0)
}
set {
setting?.historyNumber = Int16(newValue)
saveContext()
}
}
var isSaveOriginImageData: Bool! {
get {
return Bool(setting?.saveOrigin ?? true)
} set {
setting?.saveOrigin = newValue
saveContext()
}
}
}
| gpl-3.0 | c9e0ba919801dee3f160593f110b6cae | 23 | 87 | 0.539474 | 4.833922 | false | false | false | false |
appcompany/SwiftSky | Sources/SwiftSky/Temperature.swift | 1 | 4457 | //
// Temperature.swift
// SwiftSky
//
// Created by Luca Silverentand on 11/04/2017.
// Copyright © 2017 App Company.io. All rights reserved.
//
import Foundation
/// Contains a value, unit and a label describing temperature
public struct Temperature {
/// `Double` representing temperature
private(set) public var value : Double = 0
/// `TemperatureUnit` of the value
public let unit : TemperatureUnit
/// Human-readable representation of the value and unit together
public var label : String { return label(as: unit) }
/**
Same as `Temperature.label`, but converted to a specific unit
- parameter unit: `TemperatureUnit` to convert label to
- returns: String
*/
public func label(as unit : TemperatureUnit) -> String {
let converted = (self.unit == unit ? value : convert(value, from: self.unit, to: unit))
switch unit {
case .fahrenheit:
return "\(converted.noDecimal)℉"
case .celsius:
return "\(converted.noDecimal)℃"
case .kelvin:
return "\(converted.noDecimal)K"
}
}
/**
Same as `Temperature.value`, but converted to a specific unit
- parameter unit: `TemperatureUnit` to convert value to
- returns: Float
*/
public func value(as unit : TemperatureUnit) -> Double {
return convert(value, from: self.unit, to: unit)
}
private func convert(_ value : Double, from : TemperatureUnit, to : TemperatureUnit) -> Double {
switch from {
case .fahrenheit:
switch to {
case .fahrenheit:
return value
case .celsius:
return (value - 32) * (5/9)
case .kelvin:
return (value + 459.67) * (5/9)
}
case .celsius:
switch to {
case .celsius:
return value
case .fahrenheit:
return value * (9/5) + 32
case .kelvin:
return value + 273.15
}
case .kelvin:
switch to {
case .kelvin:
return value
case .fahrenheit:
return ((value - 273.15) * 1.8) + 32
case .celsius:
return value - 273.15
}
}
}
/// :nodoc:
public init(_ value : Double, withUnit : TemperatureUnit) {
unit = SwiftSky.units.temperature
self.value = convert(value, from: withUnit, to: unit)
}
}
/// Contains real-feel current, maximum and minimum `Temperature` values
public struct ApparentTemperature {
/// Current real-feel `Temperature`
public let current : Temperature?
/// Maximum value of real-feel `Temperature` during a given day
public let max : Temperature?
/// Time when `ApparentTemperature.max` occurs during a given day
public let maxTime : Date?
/// Minimum value of real-feel `Temperature` during a given day
public let min : Temperature?
/// Time when `ApparentTemperature.min` occurs during a given day
public let minTime : Date?
var hasData : Bool {
if current != nil { return true }
if max != nil { return true }
if maxTime != nil { return true }
if min != nil { return true }
if minTime != nil { return true }
return false
}
}
/// Contains current, maximum, minimum and apparent `Temperature` values
public struct Temperatures {
/// Current `Temperature`
public let current : Temperature?
/// Maximum value of `Temperature` during a given day
public let max : Temperature?
/// Time when `Temperatures.max` occurs during a given day
public let maxTime : Date?
/// Minimum value of `Temperature` during a given day
public let min : Temperature?
/// Time when `Temperatures.min` occurs during a given day
public let minTime : Date?
/// `ApparentTemperature` value with real-feel `Temperature`s
public let apparent : ApparentTemperature?
var hasData : Bool {
if current != nil { return true }
if max != nil { return true }
if maxTime != nil { return true }
if min != nil { return true }
if minTime != nil { return true }
if apparent?.hasData == true { return true }
return false
}
}
| mit | 8b6a2feb406bf910efe8b2926e1c8dc7 | 29.081081 | 100 | 0.57637 | 4.666667 | false | false | false | false |
cnoon/swift-compiler-crashes | fixed/23792-no-stacktrace.swift | 10 | 2200 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol c : b { func b{
}
let start = [Void{let end = [Void{
let ) -> c : Any) -> Void{
let f = compose([Void{
func b
class d
var b{
class
let a {
{
b { func b<U : a<T>()?
}
let a{
struct A<Int>: A
}{func c
import c
func b{init(object1: a<T where S<T>: Any)
{
protocol c : b { e{{
}}
class A{
class A<Int>()?
= [Void{
class
}
{
{
class d<U : (false)
{
{
func c
case c,
struct c
0.C
}}
let a {
case c}{
i> c {
i> c : d = B<T where S<Int>(false)?
class B<T where g:e) -
class B<T where g:A{
}}
0.C
func a
}class B<T>: a {
0.C("\()
let a {
var e{H:A
class A
{
let a<T where k:a
let f = [c
0.C
{let:a{
func b
let ) -> c { {
B :a
protocol c : d = T>(object1: e) -> Void{
class d<T where T>(){
func a<T where H{
let a
Void{{
var e{
}{
func c
class B<Int>: a {
protocol e : (e : S<e) -> Void{}
0.C
protocol c {
protocol e : e>("\([Void{
protocol e = B<Int>
}
}{
"
let a
class B{
let a {let f = [Void{
enum b
class
struct S<c,
protocol c : a
protocol e : ()
let end = compose(e : b l
struct A{
{let end = []
let start = c : S
class d
class B<U : e) -> Void{
}
i> c {
}
0.C
class c
let f = T>()?
protocol c {
class B<Int>
let end = B<T where S<U : ([Void{
{}{
struct A {
func a
enum b=c,
func a
var e) -> Void{
i> c {{
i> Void{}{
Void{let f = B<T>
class
struct Q<T where S<T where T: (object1: Any)?
func b(().e : (object1: (f: S<e) -> c { func c
i> c : A{
protocol c {
i> c : d = [Void{
}{let:a
{
func a
class B<T where S<T: Any) -
"\(object1: Any)?
}
protocol c {let a {
protocol A {
class A{
protocol b { class c
}
let start = B{for b{}enum S {{}
func b<U : (e : d
{}
func b=b<T : b { {let f = [ {class B<T>
func b
import c:A
let end = compose()?
= [1
{let f = [Void{
{
"
{
struct A {{
}class B<T: b { func a
}
b : c : d = T>(object1: e) -> Void{
0.e : S<T : b : S<c,
((()?
class
i> Void{
protocol e : e) -> c : b : Any)?
func a
{
}}
{
= c : e{H:a
class B<T: e>
import c
struct A {}}
{let f = compose((([]
Void{
let a {init(){{
let end = T>: b { func o<T {
0.C
0.C
let a
func a{
protocol A
class
{
struct Q<e) -> Void{protocol c {
i> 1
| mit | e187e2a4261b5d5467d70eff5aab4aba | 11.941176 | 87 | 0.563636 | 2.228977 | false | false | false | false |
rodrigoruiz/SwiftUtilities | SwiftUtilities/Lite/Foundation/Data+Extension.swift | 1 | 780 | //
// Data+Extension.swift
// SwiftUtilities
//
// Created by Rodrigo Ruiz on 4/25/17.
// Copyright © 2017 Rodrigo Ruiz. All rights reserved.
//
extension Data {
public func split(maximumSizeInBytes: Int) -> [Data] {
let fullChunks = count / maximumSizeInBytes
let result = (0..<fullChunks).map({ i -> Data in
let location = i * maximumSizeInBytes
return subdata(in: location..<location + maximumSizeInBytes)
})
let finalChunkSize = count % maximumSizeInBytes
if finalChunkSize == 0 {
return result
}
let location = fullChunks * maximumSizeInBytes
return result + [subdata(in: location..<location + finalChunkSize)]
}
}
| mit | 85e88458d12558d4c1d042cdb8b8de00 | 25.862069 | 75 | 0.58665 | 4.899371 | false | false | false | false |
AliSoftware/SwiftGen | SwiftGen.playground/Pages/Fonts-Demo.xcplaygroundpage/Contents.swift | 1 | 3276 | //: #### Other pages
//:
//: * [Demo for `colors` parser](Colors-Demo)
//: * [Demo for `coredata` parser](CoreData-Demo)
//: * Demo for `fonts` parser
//: * [Demo for `files` parser](Files-Demo)
//: * [Demo for `ib` parser](InterfaceBuilder-Demo)
//: * [Demo for `json` parser](JSON-Demo)
//: * [Demo for `plist` parser](Plist-Demo)
//: * [Demo for `strings` parser](Strings-Demo)
//: * [Demo for `xcassets` parser](XCAssets-Demo)
//: * [Demo for `yaml` parser](YAML-Demo)
//: #### Example of code generated by `fonts` parser with "swift5" template
#if os(macOS)
import AppKit.NSFont
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIFont
#endif
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// MARK: - Fonts
// swiftlint:disable identifier_name line_length type_body_length
internal enum FontFamily {
internal enum Avenir {
internal static let black = FontConvertible(name: "Avenir-Black", family: "Avenir", path: "Avenir.ttc")
internal static let blackOblique = FontConvertible(name: "Avenir-BlackOblique", family: "Avenir", path: "Avenir.ttc")
internal static let book = FontConvertible(name: "Avenir-Book", family: "Avenir", path: "Avenir.ttc")
internal static let bookOblique = FontConvertible(name: "Avenir-BookOblique", family: "Avenir", path: "Avenir.ttc")
internal static let heavy = FontConvertible(name: "Avenir-Heavy", family: "Avenir", path: "Avenir.ttc")
internal static let heavyOblique = FontConvertible(name: "Avenir-HeavyOblique", family: "Avenir", path: "Avenir.ttc")
internal static let light = FontConvertible(name: "Avenir-Light", family: "Avenir", path: "Avenir.ttc")
internal static let lightOblique = FontConvertible(name: "Avenir-LightOblique", family: "Avenir", path: "Avenir.ttc")
internal static let medium = FontConvertible(name: "Avenir-Medium", family: "Avenir", path: "Avenir.ttc")
internal static let mediumOblique = FontConvertible(name: "Avenir-MediumOblique", family: "Avenir", path: "Avenir.ttc")
internal static let oblique = FontConvertible(name: "Avenir-Oblique", family: "Avenir", path: "Avenir.ttc")
internal static let roman = FontConvertible(name: "Avenir-Roman", family: "Avenir", path: "Avenir.ttc")
internal static let all: [FontConvertible] = [black, blackOblique, book, bookOblique, heavy, heavyOblique, light, lightOblique, medium, mediumOblique, oblique, roman]
}
internal enum ZapfDingbats {
internal static let regular = FontConvertible(name: "ZapfDingbatsITC", family: "Zapf Dingbats", path: "ZapfDingbats.ttf")
internal static let all: [FontConvertible] = [regular]
}
internal static let allCustomFonts: [FontConvertible] = [Avenir.all, ZapfDingbats.all].flatMap { $0 }
internal static func registerAllCustomFonts() {
allCustomFonts.forEach { $0.register() }
}
}
// swiftlint:enable identifier_name line_length type_body_length
//: #### Usage Example
// Using the UIFont constructor…
let body = UIFont(font: FontFamily.Avenir.light, size: 20.0)
// Or using the enum value and its `font` method
let title = FontFamily.ZapfDingbats.regular.font(size: 20.0)
let bodyHuge = FontFamily.Avenir.black.font(size: 100.0)
let titleTiny = UIFont(font: FontFamily.ZapfDingbats.regular, size: 8.0)
| mit | c08636d370a837a5ed9268014811f0d9 | 51.806452 | 170 | 0.717471 | 3.838218 | false | false | false | false |
marklin2012/iOS_Animation | Section4/Chapter23/O2Logo_starter/O2Logo/RWLogoLayer.swift | 4 | 1332 | //
// RWLogoLayer.swift
// O2Logo
//
// Created by O2.LinYi on 16/3/21.
// Copyright © 2016年 jd.com. All rights reserved.
//
import UIKit
import QuartzCore
class RWLogoLayer {
class func logoLayer() -> CAShapeLayer {
let layer = CAShapeLayer()
layer.geometryFlipped = true
// the RW bezier
let bezier = UIBezierPath()
bezier.moveToPoint(CGPoint(x: 0.0, y: 0.0))
bezier.addCurveToPoint(CGPoint(x: 0.0, y: 66.97), controlPoint1:CGPoint(x: 0.0, y: 0.0), controlPoint2:CGPoint(x: 0.0, y: 57.06))
bezier.addCurveToPoint(CGPoint(x: 16.0, y: 39.0), controlPoint1: CGPoint(x: 27.68, y: 66.97), controlPoint2:CGPoint(x: 42.35, y: 52.75))
bezier.addCurveToPoint(CGPoint(x: 26.0, y: 17.0), controlPoint1: CGPoint(x: 17.35, y: 35.41), controlPoint2:CGPoint(x: 26, y: 17))
bezier.addLineToPoint(CGPoint(x: 38.0, y: 34.0))
bezier.addLineToPoint(CGPoint(x: 49.0, y: 17.0))
bezier.addLineToPoint(CGPoint(x: 67.0, y: 51.27))
bezier.addLineToPoint(CGPoint(x: 67.0, y: 0.0))
bezier.addLineToPoint(CGPoint(x: 0.0, y: 0.0))
bezier.closePath()
// create a shape layer
layer.path = bezier.CGPath
layer.bounds = CGPathGetBoundingBox(layer.path)
return layer
}
}
| mit | 05deb823df75947910924c5806d05711 | 33.973684 | 144 | 0.613243 | 3.265356 | false | false | false | false |
pendowski/PopcornTimeIOS | Popcorn Time/UI/Collection View Controllers/TVShowsCollectionViewController.swift | 1 | 8240 |
import UIKit
import AlamofireImage
class TVShowsCollectionViewController: ItemOverview, UIPopoverPresentationControllerDelegate, GenresDelegate, ItemOverviewDelegate {
var shows = [PCTShow]()
var currentGenre = TVAPI.genres.All {
didSet {
shows.removeAll()
collectionView?.reloadData()
currentPage = 1
loadNextPage(currentPage)
}
}
var currentFilter = TVAPI.filters.Trending {
didSet {
shows.removeAll()
collectionView?.reloadData()
currentPage = 1
loadNextPage(currentPage)
}
}
@IBAction func searchBtnPressed(sender: UIBarButtonItem) {
presentViewController(searchController, animated: true, completion: nil)
}
@IBAction func filter(sender: AnyObject) {
self.collectionView?.performBatchUpdates({
self.filterHeader!.hidden = !self.filterHeader!.hidden
}, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
loadNextPage(currentPage)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if let collectionView = object as? UICollectionView where collectionView == self.collectionView! && keyPath! == "frame" {
collectionView.performBatchUpdates(nil, completion: nil)
}
}
func segmentedControlDidChangeSegment(segmentedControl: UISegmentedControl) {
currentFilter = TVAPI.filters.arrayValue[segmentedControl.selectedSegmentIndex]
}
// MARK: - ItemOverviewDelegate
func loadNextPage(pageNumber: Int, searchTerm: String? = nil, removeCurrentData: Bool = false) {
guard isLoading else {
isLoading = true
hasNextPage = false
TVAPI.sharedInstance.load(currentPage, filterBy: currentFilter, genre: currentGenre, searchTerm: searchTerm) { result in
self.isLoading = false
guard case .success(let items) = result else {
return
}
if removeCurrentData {
self.shows.removeAll()
}
self.shows += items
if items.isEmpty // If the array passed in is empty, there are no more results so the content inset of the collection view is reset.
{
self.collectionView?.contentInset = UIEdgeInsetsMake(69, 0, 0, 0)
} else {
self.hasNextPage = true
}
self.collectionView?.reloadData()
}
return
}
}
func didDismissSearchController(searchController: UISearchController) {
self.shows.removeAll()
collectionView?.reloadData()
self.currentPage = 1
loadNextPage(self.currentPage)
}
func search(text: String) {
self.shows.removeAll()
collectionView?.reloadData()
self.currentPage = 1
self.loadNextPage(self.currentPage, searchTerm: text)
}
func shouldRefreshCollectionView() -> Bool {
return shows.isEmpty
}
// MARK: - Navigation
@IBAction func genresButtonTapped(sender: UIBarButtonItem) {
let controller = cache.objectForKey(TraktTVAPI.type.Shows.rawValue) as? UINavigationController ?? (storyboard?.instantiateViewControllerWithIdentifier("GenresNavigationController"))! as! UINavigationController
cache.setObject(controller, forKey: TraktTVAPI.type.Shows.rawValue)
controller.modalPresentationStyle = .Popover
controller.popoverPresentationController?.barButtonItem = sender
controller.popoverPresentationController?.backgroundColor = UIColor(red: 30.0/255.0, green: 30.0/255.0, blue: 30.0/255.0, alpha: 1.0)
(controller.viewControllers[0] as! GenresTableViewController).delegate = self
presentViewController(controller, animated: true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
fixIOS9PopOverAnchor(segue)
if segue.identifier == "showDetail" {
let showDetail = segue.destinationViewController as! TVShowDetailViewController
let cell = sender as! CoverCollectionViewCell
showDetail.currentItem = shows[(collectionView?.indexPathForCell(cell)?.row)!]
}
}
// MARK: - Collection view data source
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
collectionView.backgroundView = nil
if shows.count == 0 {
if error != nil {
let background = NSBundle.mainBundle().loadNibNamed("TableViewBackground", owner: self, options: nil).first as! TableViewBackground
background.setUpView(error: error!)
collectionView.backgroundView = background
} else if isLoading {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .White)
indicator.center = collectionView.center
collectionView.backgroundView = indicator
indicator.sizeToFit()
indicator.startAnimating()
} else {
let background = NSBundle.mainBundle().loadNibNamed("TableViewBackground", owner: self, options: nil).first as! TableViewBackground
background.setUpView(image: UIImage(named: "Search")!, title: "No results found.", description: "No search results found for \(searchController.searchBar.text!). Please check the spelling and try again.")
collectionView.backgroundView = background
}
}
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return shows.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CoverCollectionViewCell
cell.titleLabel.text = shows[indexPath.row].title
cell.yearLabel.text = String(shows[indexPath.row].year)
cell.coverImage.af_setImageWithURL(NSURL(string: shows[indexPath.row].coverImageAsString)!, placeholderImage: UIImage(named: "Placeholder"), imageTransition: .CrossDissolve(animationLength))
return cell
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
filterHeader = filterHeader ?? {
let reuseableView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "filter", forIndexPath: indexPath) as! FilterCollectionReusableView
reuseableView.segmentedControl?.removeAllSegments()
for (index, filterValue) in TVAPI.filters.arrayValue.enumerate() {
reuseableView.segmentedControl?.insertSegmentWithTitle(filterValue.title, atIndex: index, animated: false)
}
reuseableView.hidden = true
reuseableView.segmentedControl?.addTarget(self, action: #selector(segmentedControlDidChangeSegment(_:)), forControlEvents: .ValueChanged)
reuseableView.segmentedControl?.selectedSegmentIndex = 0
return reuseableView
}()
return filterHeader!
}
// MARK: - GenresDelegate
func finished(genreArrayIndex: Int) {
navigationItem.title = TVAPI.genres.arrayValue[genreArrayIndex].rawValue
if TVAPI.genres.arrayValue[genreArrayIndex] == .All {
navigationItem.title = "Shows"
}
currentGenre = TVAPI.genres.arrayValue[genreArrayIndex]
}
func populateDataSourceArray(inout array: [String]) {
for genre in TVAPI.genres.arrayValue {
array.append(genre.rawValue)
}
}
}
| gpl-3.0 | 27860f861d14052a2afa327e2f216f14 | 43.064171 | 220 | 0.654369 | 5.823322 | false | false | false | false |
eoger/firefox-ios | Shared/RollingFileLogger.swift | 14 | 4158 | /* 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 XCGLogger
//// A rolling file logger that saves to a different log file based on given timestamp.
open class RollingFileLogger: XCGLogger {
public static let TwoMBsInBytes: Int64 = 2 * 100000
fileprivate let sizeLimit: Int64
fileprivate let logDirectoryPath: String?
let fileLogIdentifierPrefix = "com.mozilla.firefox.filelogger."
fileprivate static let DateFormatter: DateFormatter = {
let formatter = Foundation.DateFormatter()
formatter.dateFormat = "yyyyMMdd'T'HHmmssZ"
return formatter
}()
let root: String
public init(filenameRoot: String, logDirectoryPath: String?, sizeLimit: Int64 = TwoMBsInBytes) {
root = filenameRoot
self.sizeLimit = sizeLimit
self.logDirectoryPath = logDirectoryPath
super.init()
}
/**
Create a new log file with the given timestamp to log events into
:param: date Date for with to start and mark the new log file
*/
open func newLogWithDate(_ date: Date) {
// Don't start a log if we don't have a valid log directory path
if logDirectoryPath == nil {
return
}
if let filename = filenameWithRoot(root, withDate: date) {
remove(destinationWithIdentifier: fileLogIdentifierWithRoot(root))
add(destination: FileDestination(owner: self, writeToFile: filename, identifier: fileLogIdentifierWithRoot(root)))
info("Created file destination for logger with root: \(self.root) and timestamp: \(date)")
} else {
error("Failed to create a new log with root name: \(self.root) and timestamp: \(date)")
}
}
open func deleteOldLogsDownToSizeLimit() {
// Check to see we haven't hit our size limit and if we did, clear out some logs to make room.
while sizeOfAllLogFilesWithPrefix(self.root, exceedsSizeInBytes: sizeLimit) {
deleteOldestLogWithPrefix(self.root)
}
}
open func logFilenamesAndURLs() throws -> [(String, URL)] {
guard let logPath = logDirectoryPath else {
return []
}
let files = try FileManager.default.contentsOfDirectoryAtPath(logPath, withFilenamePrefix: root)
return files.compactMap { filename in
if let url = URL(string: "\(logPath)/\(filename)") {
return (filename, url)
}
return nil
}
}
fileprivate func deleteOldestLogWithPrefix(_ prefix: String) {
if logDirectoryPath == nil {
return
}
do {
let logFiles = try FileManager.default.contentsOfDirectoryAtPath(logDirectoryPath!, withFilenamePrefix: prefix)
if let oldestLogFilename = logFiles.first {
try FileManager.default.removeItem(atPath: "\(logDirectoryPath!)/\(oldestLogFilename)")
}
} catch _ as NSError {
error("Shouldn't get here")
return
}
}
fileprivate func sizeOfAllLogFilesWithPrefix(_ prefix: String, exceedsSizeInBytes threshold: Int64) -> Bool {
guard let path = logDirectoryPath else {
return false
}
let logDirURL = URL(fileURLWithPath: path)
do {
return try FileManager.default.allocatedSizeOfDirectoryAtURL(logDirURL, forFilesPrefixedWith: prefix, isLargerThanBytes: threshold)
} catch let errorValue as NSError {
error("Error determining log directory size: \(errorValue)")
}
return false
}
fileprivate func filenameWithRoot(_ root: String, withDate date: Date) -> String? {
if let dir = logDirectoryPath {
return "\(dir)/\(root).\(RollingFileLogger.DateFormatter.string(from: date)).log"
}
return nil
}
fileprivate func fileLogIdentifierWithRoot(_ root: String) -> String {
return "\(fileLogIdentifierPrefix).\(root)"
}
}
| mpl-2.0 | fcb21e5fb44d4b602b76850443383b74 | 35.156522 | 143 | 0.643579 | 4.944114 | false | false | false | false |
benlangmuir/swift | test/decl/var/lazy_properties.swift | 4 | 6681 | // RUN: %target-typecheck-verify-swift -parse-as-library
lazy func lazy_func() {} // expected-error {{'lazy' may only be used on 'var' declarations}} {{1-6=}}
lazy var b = 42 // expected-error {{'lazy' cannot be used on an already-lazy global}} {{1-6=}}
struct S {
lazy static var lazy_global = 42 // expected-error {{'lazy' cannot be used on an already-lazy global}} {{3-8=}}
}
protocol SomeProtocol {
lazy var x : Int // expected-error {{'lazy' cannot be used on a protocol requirement}} {{3-8=}}
// expected-error@-1 {{property in protocol must have explicit { get } or { get set } specifier}} {{19-19= { get <#set#> \}}}
// expected-error@-2 {{lazy properties must have an initializer}}
lazy var y : Int { get } // expected-error {{'lazy' cannot be used on a protocol requirement}} {{3-8=}}
// expected-error@-1 {{'lazy' cannot be used on a computed property}}
// expected-error@-2 {{lazy properties must have an initializer}}
}
class TestClass {
lazy var a = 42
lazy var a1 : Int = 42
lazy let b = 42 // expected-error {{'lazy' cannot be used on a let}} {{3-8=}}
lazy var c : Int { return 42 } // expected-error {{'lazy' cannot be used on a computed property}} {{3-8=}}
// expected-error@-1 {{lazy properties must have an initializer}}
lazy var d : Int // expected-error {{lazy properties must have an initializer}} {{3-8=}}
lazy var (e, f) = (1,2) // expected-error 2{{'lazy' cannot destructure an initializer}} {{3-8=}}
lazy var g = { 0 }() // single-expr closure
lazy var h : Int = { 0 }() // single-expr closure
lazy var i = { () -> Int in return 0 }()+1 // multi-stmt closure
lazy var j : Int = { return 0 }()+1 // multi-stmt closure
lazy var k : Int = { () -> Int in return 0 }()+1 // multi-stmt closure
lazy var l : Int = 42 { // Okay
didSet {}
willSet {}
}
lazy var m : Int = 42 { // Okay
didSet {}
}
lazy var n : Int = 42 {
willSet {} // Okay
}
init() {
lazy var localvar = 42 // Okay
localvar += 1
_ = localvar
}
}
struct StructTest {
lazy var p1 : Int = 42
mutating func f1() -> Int {
return p1
}
// expected-note @+1 {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }}
func f2() -> Int {
return p1 // expected-error {{cannot use mutating getter on immutable value: 'self' is immutable}}
}
static func testStructInits() {
let a = StructTest() // default init
let b = StructTest(p1: 42) // Override the lazily init'd value.
_ = a; _ = b
}
}
// <rdar://problem/16889110> capture lists in lazy member properties cannot use self
class CaptureListInLazyProperty {
lazy var closure1 = { [weak self] in return self!.i }
lazy var closure2: () -> Int = { [weak self] in return self!.i }
var i = 42
}
// Crash when initializer expression is type-checked both to infer the
// property type and also as part of the getter
class WeShouldNotReTypeCheckStatements {
lazy var firstCase = {
_ = nil // expected-error{{'nil' requires a contextual type}}
_ = ()
}
lazy var secondCase = {
_ = ()
_ = ()
}
}
protocol MyProtocol {
func f() -> Int
}
struct MyStruct : MyProtocol {
func f() -> Int { return 0 }
}
struct Outer {
static let p: MyProtocol = MyStruct()
struct Inner {
lazy var x = p.f()
lazy var y = {_ = 3}()
// expected-warning@-1 {{variable 'y' inferred to have type '()', which may be unexpected}}
// expected-note@-2 {{add an explicit type annotation to silence this warning}} {{15-15=: ()}}
}
}
// https://github.com/apple/swift/issues/45221
struct Construction {
init(x: Int, y: Int? = 42) { }
}
class Constructor {
lazy var myQ = Construction(x: 3)
}
// Problems with self references
class BaseClass {
var baseInstanceProp = 42
static var baseStaticProp = 42
}
class ReferenceSelfInLazyProperty : BaseClass {
lazy var refs = (i, f())
lazy var trefs: (Int, Int) = (i, f())
lazy var qrefs = (self.i, self.f())
lazy var qtrefs: (Int, Int) = (self.i, self.f())
lazy var crefs = { (i, f()) }()
lazy var ctrefs: (Int, Int) = { (i, f()) }()
lazy var cqrefs = { (self.i, self.f()) }()
lazy var cqtrefs: (Int, Int) = { (self.i, self.f()) }()
lazy var mrefs = { () -> (Int, Int) in return (i, f()) }()
lazy var mtrefs: (Int, Int) = { return (i, f()) }()
lazy var mqrefs = { () -> (Int, Int) in (self.i, self.f()) }()
lazy var mqtrefs: (Int, Int) = { return (self.i, self.f()) }()
lazy var lcqrefs = { [unowned self] in (self.i, self.f()) }()
lazy var lcqtrefs: (Int, Int) = { [unowned self] in (self.i, self.f()) }()
lazy var lmrefs = { [unowned self] () -> (Int, Int) in return (i, f()) }()
lazy var lmtrefs: (Int, Int) = { [unowned self] in return (i, f()) }()
lazy var lmqrefs = { [unowned self] () -> (Int, Int) in (self.i, self.f()) }()
lazy var lmqtrefs: (Int, Int) = { [unowned self] in return (self.i, self.f()) }()
var i = 42
func f() -> Int { return 0 }
lazy var refBaseClassProp = baseInstanceProp
}
class ReferenceStaticInLazyProperty {
lazy var refs1 = i
// expected-error@-1 {{static member 'i' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}}
lazy var refs2 = f()
// expected-error@-1 {{static member 'f' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}}
lazy var trefs1: Int = i
// expected-error@-1 {{static member 'i' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}}
lazy var trefs2: Int = f()
// expected-error@-1 {{static member 'f' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}}
static var i = 42
static func f() -> Int { return 0 }
}
// Explicit access to the lazy variable storage
class LazyVarContainer {
lazy var foo: Int = {
return 0
}()
func accessLazyStorage() {
$__lazy_storage_$_foo = nil // expected-error {{access to the underlying storage of a lazy property is not allowed}}
print($__lazy_storage_$_foo!) // expected-error {{access to the underlying storage of a lazy property is not allowed}}
_ = $__lazy_storage_$_foo == nil // expected-error {{access to the underlying storage of a lazy property is not allowed}}
}
}
// Make sure we can still access a synthesized variable with the same name as a lazy storage variable
// i.e. $__lazy_storage_$_{property_name} when using property wrapper where the property name is
// '__lazy_storage_$_{property_name}'.
@propertyWrapper
struct Wrapper {
var wrappedValue: Int { 1 }
var projectedValue: Int { 1 }
}
struct PropertyWrapperContainer {
@Wrapper var __lazy_storage_$_foo
func test() {
_ = $__lazy_storage_$_foo // This is okay.
}
}
| apache-2.0 | d4f73ff6c0f84dcd1c51827eacb699b1 | 29.230769 | 127 | 0.624158 | 3.476067 | false | false | false | false |
google/iosched-ios | Source/IOsched/Common/CollectionViewHeaderCell.swift | 1 | 1363 | //
// Copyright (c) 2016 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 MaterialComponents
class CollectionViewHeaderCell: UICollectionViewCell {
var textLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
textLabel = UILabel(frame: CGRect(x: 20, y: 10, width: frame.size.width - 40, height: frame.size.height/3))
textLabel.font = UIFont.mdc_preferredFont(forMaterialTextStyle: .subheadline)
textLabel.alpha = MDCTypography.subheadFontOpacity()
textLabel.textAlignment = .natural
textLabel.enableAdjustFontForContentSizeCategory()
textLabel.lineBreakMode = .byTruncatingTail
contentView.addSubview(textLabel)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | c19a427866515957fc77e178ab6512b8 | 32.243902 | 111 | 0.738811 | 4.246106 | false | false | false | false |
li1024316925/Swift-TimeMovie | Swift-TimeMovie/Swift-TimeMovie/RatingView.swift | 1 | 2043 | //
// RatingView.swift
// SwiftTimeMovie
//
// Created by DahaiZhang on 16/10/18.
// Copyright © 2016年 LLQ. All rights reserved.
//
import UIKit
class RatingView: UIView {
var yellowView:UIView?
//评分属性,复写set方法,在赋值完成后调用
var rating:CGFloat?{
didSet{
yellowView?.frame = CGRect(x: 0, y: 0, width: frame.size.width * rating! / 10.0, height: frame.size.height)
}
}
override func awakeFromNib() {
loadSubViews()
}
func loadSubViews() -> Void {
//获取图片
let gray = UIImage(named: "gray")!
let yellow = UIImage(named: "yellow")!
//图片大小
let imgHeight = gray.size.height
let imgWidth = gray.size.width * 5.0
//创建视图
let grayView = UIView(frame: CGRect(x: 0, y: 0, width: imgWidth, height: imgHeight))
yellowView = UIView(frame: CGRect(x: 0, y: 0, width: imgWidth, height: imgHeight))
//设置背景图片,以平铺的方式
grayView.backgroundColor = UIColor.init(patternImage: gray)
yellowView?.backgroundColor = UIColor.init(patternImage: yellow)
self.addSubview(grayView)
self.addSubview(yellowView!)
//获取View的frame之前,要调用此方法,否则获取不到
//立即进行布局
layoutIfNeeded()
//计算放大倍数
let scaleX = frame.size.width/imgWidth
let scaleY = frame.size.height/imgHeight
//调整大小
grayView.transform = CGAffineTransform(scaleX: scaleX, y: scaleY)
yellowView?.transform = CGAffineTransform(scaleX: scaleX, y: scaleY)
//重定视图位置
grayView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
yellowView?.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
}
}
| apache-2.0 | f7ad375e8d435c8e6e8b4fa94d71d698 | 26.130435 | 119 | 0.571047 | 3.974522 | false | false | false | false |
sydvicious/firefox-ios | Client/Frontend/UIConstants.swift | 6 | 2596 | /* 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 Shared
public struct UIConstants {
static let AboutHomeURL = NSURL(string: "\(WebServer.sharedInstance.base)/about/home/#panel=0")!
static let AppBackgroundColor = UIColor.blackColor()
static let ToolbarHeight: CGFloat = 44
static let DefaultRowHeight: CGFloat = 58
static let DefaultPadding: CGFloat = 10
static let DefaultMediumFontSize: CGFloat = 14
static let DefaultMediumFont = UIFont.systemFontOfSize(DefaultMediumFontSize, weight: UIFontWeightRegular)
static let DefaultMediumBoldFont = UIFont.boldSystemFontOfSize(DefaultMediumFontSize)
static let DefaultSmallFontSize: CGFloat = 11
static let DefaultSmallFont = UIFont.systemFontOfSize(DefaultSmallFontSize, weight: UIFontWeightRegular)
static let DefaultSmallFontBold = UIFont.systemFontOfSize(DefaultSmallFontSize, weight: UIFontWeightBold)
static let DefaultStandardFontSize: CGFloat = 17
static let DefaultStandardFontBold = UIFont.boldSystemFontOfSize(DefaultStandardFontSize)
// These highlight colors are currently only used on Snackbar buttons when they're pressed
static let HighlightColor = UIColor(red: 205/255, green: 223/255, blue: 243/255, alpha: 0.9)
static let HighlightText = UIColor(red: 42/255, green: 121/255, blue: 213/255, alpha: 1.0)
static let PanelBackgroundColor = DeviceInfo.isBlurSupported() ? UIColor.whiteColor().colorWithAlphaComponent(0.6) : UIColor.whiteColor()
static let SeparatorColor = UIColor(rgb: 0xcccccc)
static let HighlightBlue = UIColor(red:0.3, green:0.62, blue:1, alpha:1)
static let DestructiveRed = UIColor(red: 255/255, green: 64/255, blue: 0/255, alpha: 1.0)
static let BorderColor = UIColor.blackColor().colorWithAlphaComponent(0.25)
static let BackgroundColor = UIColor(red: 0.21, green: 0.23, blue: 0.25, alpha: 1)
// settings
static let TableViewHeaderBackgroundColor = UIColor(red: 242/255, green: 245/255, blue: 245/255, alpha: 1.0)
static let TableViewHeaderTextColor = UIColor(red: 130/255, green: 135/255, blue: 153/255, alpha: 1.0)
static let TableViewRowTextColor = UIColor(red: 53.55/255, green: 53.55/255, blue: 53.55/255, alpha: 1.0)
static let TableViewSeparatorColor = UIColor(rgb: 0xD1D1D4)
// Firefox Orange
static let ControlTintColor = UIColor(red: 240.0 / 255, green: 105.0 / 255, blue: 31.0 / 255, alpha: 1)
} | mpl-2.0 | 42adfefe98344d147a5a1283fdc7f348 | 56.711111 | 141 | 0.748074 | 4.1536 | false | false | false | false |
ntnmrndn/R.swift | Sources/RswiftCore/ResourceTypes/ResourceFile.swift | 4 | 1149 | //
// ResourceFile.swift
// R.swift
//
// Created by Mathijs Kadijk on 09-12-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
struct ResourceFile {
// These are all extensions of resources that are passed to some special compiler step and not directly available runtime
static let unsupportedExtensions: Set<String> = [
AssetFolder.supportedExtensions,
Storyboard.supportedExtensions,
Nib.supportedExtensions,
LocalizableStrings.supportedExtensions,
]
.reduce([]) { $0.union($1) }
let fullname: String
let filename: String
let pathExtension: String
init(url: URL) throws {
pathExtension = url.pathExtension
if ResourceFile.unsupportedExtensions.contains(pathExtension) {
throw ResourceParsingError.unsupportedExtension(givenExtension: pathExtension, supportedExtensions: ["*"])
}
let fullname = url.lastPathComponent
guard let filename = url.filename else {
throw ResourceParsingError.parsingFailed("Couldn't extract filename from URL: \(url)")
}
self.fullname = fullname
self.filename = filename
}
}
| mit | a09ddd55c4923b357f310d1d2f18fa12 | 27.725 | 123 | 0.719756 | 4.505882 | false | false | false | false |
ShenghaiWang/FolioReaderKit | Source/FolioReaderPage.swift | 1 | 20128 | //
// FolioReaderPage.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 10/04/15.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
import SafariServices
import MenuItemKit
import JSQWebViewController
/// Protocol which is used from `FolioReaderPage`s.
@objc public protocol FolioReaderPageDelegate: class {
/**
Notify that the page will be loaded. Note: The webview content itself is already loaded at this moment. But some java script operations like the adding of class based on click listeners will happen right after this method. If you want to perform custom java script before this happens this method is the right choice. If you want to modify the html content (and not run java script) you have to use `htmlContentForPage()` from the `FolioReaderCenterDelegate`.
- parameter page: The loaded page
*/
@objc optional func pageWillLoad(_ page: FolioReaderPage)
/**
Notifies that page did load. A page load doesn't mean that this page is displayed right away, use `pageDidAppear` to get informed about the appearance of a page.
- parameter page: The loaded page
*/
@objc optional func pageDidLoad(_ page: FolioReaderPage)
}
open class FolioReaderPage: UICollectionViewCell, UIWebViewDelegate, UIGestureRecognizerDelegate {
weak var delegate: FolioReaderPageDelegate?
/// The index of the current page. Note: The index start at 1!
open var pageNumber: Int!
public var webView: FolioReaderWebView!
fileprivate var colorView: UIView!
fileprivate var shouldShowBar = true
fileprivate var menuIsVisible = false
// MARK: - View life cicle
override public init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
// TODO: Put the notification name in a Constants file
NotificationCenter.default.addObserver(self, selector: #selector(refreshPageMode), name: NSNotification.Name(rawValue: "needRefreshPageMode"), object: nil)
if webView == nil {
webView = FolioReaderWebView(frame: webViewFrame())
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.dataDetectorTypes = .link
webView.scrollView.showsVerticalScrollIndicator = false
webView.scrollView.showsHorizontalScrollIndicator = false
webView.backgroundColor = UIColor.clear
self.contentView.addSubview(webView)
}
webView.delegate = self
if colorView == nil {
colorView = UIView()
colorView.backgroundColor = readerConfig.nightModeBackground
webView.scrollView.addSubview(colorView)
}
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
tapGestureRecognizer.numberOfTapsRequired = 1
tapGestureRecognizer.delegate = self
webView.addGestureRecognizer(tapGestureRecognizer)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("storyboards are incompatible with truth and beauty")
}
deinit {
webView.scrollView.delegate = nil
NotificationCenter.default.removeObserver(self)
}
override open func layoutSubviews() {
super.layoutSubviews()
webView.setupScrollDirection()
webView.frame = webViewFrame()
}
func webViewFrame() -> CGRect {
guard readerConfig.hideBars == false else {
return bounds
}
let statusbarHeight = UIApplication.shared.statusBarFrame.size.height
let navBarHeight = FolioReader.shared.readerCenter?.navigationController?.navigationBar.frame.size.height ?? CGFloat(0)
let navTotal = readerConfig.shouldHideNavigationOnTap ? 0 : statusbarHeight + navBarHeight
let paddingTop: CGFloat = 20
let paddingBottom: CGFloat = 30
let paddingleft: CGFloat = 40
let paddingright: CGFloat = 40
return CGRect(
x: bounds.origin.x + paddingleft,
y: isDirection(bounds.origin.y + navTotal, bounds.origin.y + navTotal + paddingTop),
width: bounds.width - paddingleft - paddingright,
height: isDirection(bounds.height - navTotal, bounds.height - navTotal - paddingTop - paddingBottom)
)
}
func loadHTMLString(_ htmlContent: String!, baseURL: URL!) {
// Insert the stored highlights to the HTML
let tempHtmlContent = htmlContentWithInsertHighlights(htmlContent)
// Load the html into the webview
webView.alpha = 0
webView.loadHTMLString(tempHtmlContent, baseURL: baseURL)
}
func load(data: Data, mimeType: String, textEncodingName: String, baseURL: URL) {
//need right mime type to make some epub file to be rendered right
webView.alpha = 0
webView.load(data, mimeType: mimeType, textEncodingName: textEncodingName, baseURL: baseURL)
}
// MARK: - Highlights
fileprivate func htmlContentWithInsertHighlights(_ htmlContent: String) -> String {
var tempHtmlContent = htmlContent as NSString
// Restore highlights
let highlights = Highlight.allByBookId((kBookId as NSString).deletingPathExtension, andPage: pageNumber as NSNumber?)
if highlights.count > 0 {
for item in highlights {
let style = HighlightStyle.classForStyle(item.type)
let tag = "<highlight id=\"\(item.highlightId!)\" onclick=\"callHighlightURL(this);\" class=\"\(style)\">\(item.content!)</highlight>"
var locator = item.contentPre + item.content
locator += item.contentPost
locator = Highlight.removeSentenceSpam(locator) /// Fix for Highlights
let range: NSRange = tempHtmlContent.range(of: locator, options: .literal)
if range.location != NSNotFound {
let newRange = NSRange(location: range.location + item.contentPre.characters.count, length: item.content.characters.count)
tempHtmlContent = tempHtmlContent.replacingCharacters(in: newRange, with: tag) as NSString
}
else {
print("highlight range not found")
}
}
}
return tempHtmlContent as String
}
// MARK: - UIWebView Delegate
open func webViewDidFinishLoad(_ webView: UIWebView) {
guard let webView = webView as? FolioReaderWebView else {
return
}
delegate?.pageWillLoad?(self)
// Add the custom class based onClick listener
self.setupClassBasedOnClickListeners()
refreshPageMode()
if readerConfig.enableTTS && !book.hasAudio() {
webView.js("wrappingSentencesWithinPTags()")
if let audioPlayer = FolioReader.shared.readerAudioPlayer , audioPlayer.isPlaying() {
audioPlayer.readCurrentSentence()
}
}
let direction: ScrollDirection = FolioReader.needsRTLChange ? .positive() : .negative()
if pageScrollDirection == direction && readerConfig.scrollDirection != .horizontalWithVerticalContent {
scrollPageToBottom()
}
UIView.animate(withDuration: 0.2, animations: {webView.alpha = 1}, completion: { finished in
webView.isColors = false
self.webView.createMenu(options: false)
})
delegate?.pageDidLoad?(self)
}
open func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
guard
let webView = webView as? FolioReaderWebView,
let scheme = request.url?.scheme else {
return true
}
guard let url = request.url else { return false }
if scheme == "highlight" {
shouldShowBar = false
guard let decoded = url.absoluteString.removingPercentEncoding else { return false }
let rect = CGRectFromString(decoded.substring(from: decoded.index(decoded.startIndex, offsetBy: 12)))
webView.createMenu(options: true)
webView.setMenuVisible(true, andRect: rect)
menuIsVisible = true
return false
} else if scheme == "play-audio" {
guard let decoded = url.absoluteString.removingPercentEncoding else { return false }
let playID = decoded.substring(from: decoded.index(decoded.startIndex, offsetBy: 13))
let chapter = FolioReader.shared.readerCenter?.getCurrentChapter()
let href = chapter?.href ?? ""
FolioReader.shared.readerAudioPlayer?.playAudio(href, fragmentID: playID)
return false
} else if scheme == "file" {
let anchorFromURL = url.fragment
// Handle internal url
if (url.path as NSString).pathExtension != "" {
let base = (book.opfResource.href as NSString).deletingLastPathComponent
let path = url.path
let splitedPath = path.components(separatedBy: base.isEmpty ? kBookId : base)
// Return to avoid crash
if splitedPath.count <= 1 || splitedPath[1].isEmpty {
return true
}
let href = splitedPath[1].trimmingCharacters(in: CharacterSet(charactersIn: "/"))
let hrefPage = (FolioReader.shared.readerCenter?.findPageByHref(href) ?? 0) + 1
if hrefPage == pageNumber {
// Handle internal #anchor
if anchorFromURL != nil {
handleAnchor(anchorFromURL!, avoidBeginningAnchors: false, animated: true)
return false
}
} else {
FolioReader.shared.readerCenter?.changePageWith(href: href, animated: true)
}
return false
}
// Handle internal #anchor
if anchorFromURL != nil {
handleAnchor(anchorFromURL!, avoidBeginningAnchors: false, animated: true)
return false
}
return true
} else if scheme == "mailto" {
print("Email")
return true
} else if url.absoluteString != "about:blank" && scheme.contains("http") && navigationType == .linkClicked {
if #available(iOS 9.0, *) {
let safariVC = SFSafariViewController(url: request.url!)
safariVC.view.tintColor = readerConfig.tintColor
FolioReader.shared.readerCenter?.present(safariVC, animated: true, completion: nil)
} else {
let webViewController = WebViewController(url: request.url!)
let nav = UINavigationController(rootViewController: webViewController)
nav.view.tintColor = readerConfig.tintColor
FolioReader.shared.readerCenter?.present(nav, animated: true, completion: nil)
}
return false
} else {
// Check if the url is a custom class based onClick listerner
var isClassBasedOnClickListenerScheme = false
for listener in readerConfig.classBasedOnClickListeners {
if
(scheme == listener.schemeName),
let absoluteURLString = request.url?.absoluteString,
let range = absoluteURLString.range(of: "/clientX=") {
let baseURL = absoluteURLString.substring(to: range.lowerBound)
let positionString = absoluteURLString.substring(from: range.lowerBound)
if let point = getEventTouchPoint(fromPositionParameterString: positionString) {
let attributeContentString = (baseURL.replacingOccurrences(of: "\(scheme)://", with: "").removingPercentEncoding)
// Call the on click action block
listener.onClickAction(attributeContentString, point)
// Mark the scheme as class based click listener scheme
isClassBasedOnClickListenerScheme = true
}
}
}
if isClassBasedOnClickListenerScheme == false {
// Try to open the url with the system if it wasn't a custom class based click listener
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
return false
}
} else {
return false
}
}
return true
}
fileprivate func getEventTouchPoint(fromPositionParameterString positionParameterString: String) -> CGPoint? {
// Remove the parameter names: "/clientX=188&clientY=292" -> "188&292"
var positionParameterString = positionParameterString.replacingOccurrences(of: "/clientX=", with: "")
positionParameterString = positionParameterString.replacingOccurrences(of: "clientY=", with: "")
// Separate both position values into an array: "188&292" -> [188],[292]
let positionStringValues = positionParameterString.components(separatedBy: "&")
// Multiply the raw positions with the screen scale and return them as CGPoint
if
positionStringValues.count == 2,
let xPos = Int(positionStringValues[0]),
let yPos = Int(positionStringValues[1]) {
return CGPoint(x: xPos, y: yPos)
}
return nil
}
// MARK: Gesture recognizer
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.view is FolioReaderWebView {
if otherGestureRecognizer is UILongPressGestureRecognizer {
if UIMenuController.shared.isMenuVisible {
webView.setMenuVisible(false)
}
return false
}
return true
}
return false
}
open func handleTapGesture(_ recognizer: UITapGestureRecognizer) {
// webView.setMenuVisible(false)
if let _navigationController = FolioReader.shared.readerCenter?.navigationController , _navigationController.isNavigationBarHidden {
let menuIsVisibleRef = menuIsVisible
let selected = webView.js("getSelectedText()")
if selected == nil || selected!.characters.count == 0 {
let seconds = 0.4
let delay = seconds * Double(NSEC_PER_SEC) // nanoseconds per seconds
let dispatchTime = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: {
if self.shouldShowBar && !menuIsVisibleRef {
FolioReader.shared.readerCenter?.toggleBars()
}
self.shouldShowBar = true
})
}
} else if readerConfig.shouldHideNavigationOnTap == true {
FolioReader.shared.readerCenter?.hideBars()
}
// Reset menu
menuIsVisible = false
}
// MARK: - Public scroll postion setter
/**
Scrolls the page to a given offset
- parameter offset: The offset to scroll
- parameter animated: Enable or not scrolling animation
*/
open func scrollPageToOffset(_ offset: CGFloat, animated: Bool) {
let pageOffsetPoint = isDirection(CGPoint(x: 0, y: offset), CGPoint(x: offset, y: 0))
webView.scrollView.setContentOffset(pageOffsetPoint, animated: animated)
}
/**
Scrolls the page to bottom
*/
open func scrollPageToBottom() {
let bottomOffset = isDirection(
CGPoint(x: 0, y: webView.scrollView.contentSize.height - webView.scrollView.bounds.height),
CGPoint(x: webView.scrollView.contentSize.width - webView.scrollView.bounds.width, y: 0),
CGPoint(x: webView.scrollView.contentSize.width - webView.scrollView.bounds.width, y: 0)
)
if bottomOffset.forDirection() >= 0 {
DispatchQueue.main.async(execute: {
self.webView.scrollView.setContentOffset(bottomOffset, animated: false)
})
}
}
/**
Handdle #anchors in html, get the offset and scroll to it
- parameter anchor: The #anchor
- parameter avoidBeginningAnchors: Sometimes the anchor is on the beggining of the text, there is not need to scroll
- parameter animated: Enable or not scrolling animation
*/
open func handleAnchor(_ anchor: String, avoidBeginningAnchors: Bool, animated: Bool) {
if !anchor.isEmpty {
let offset = getAnchorOffset(anchor)
switch readerConfig.scrollDirection {
case .vertical, .defaultVertical:
let isBeginning = offset < frame.forDirection()/2
if !avoidBeginningAnchors {
scrollPageToOffset(offset, animated: animated)
} else if avoidBeginningAnchors && !isBeginning {
scrollPageToOffset(offset, animated: animated)
}
case .horizontal, .horizontalWithVerticalContent:
scrollPageToOffset(offset, animated: animated)
}
}
}
// MARK: Helper
/**
Get the #anchor offset in the page
- parameter anchor: The #anchor id
- returns: The element offset ready to scroll
*/
func getAnchorOffset(_ anchor: String) -> CGFloat {
let horizontal = readerConfig.scrollDirection == .horizontal
if let strOffset = webView.js("getAnchorOffset('\(anchor)', \(horizontal.description))") {
return CGFloat((strOffset as NSString).floatValue)
}
return CGFloat(0)
}
// MARK: Mark ID
/**
Audio Mark ID - marks an element with an ID with the given class and scrolls to it
- parameter ID: The ID
*/
func audioMarkID(_ ID: String) {
guard let currentPage = FolioReader.shared.readerCenter?.currentPage else { return }
currentPage.webView.js("audioMarkID('\(book.playbackActiveClass())','\(ID)')")
}
// MARK: UIMenu visibility
override open func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if UIMenuController.shared.menuItems?.count == 0 {
webView.isColors = false
webView.createMenu(options: false)
}
if !webView.isShare && !webView.isColors {
if let result = webView.js("getSelectedText()") , result.components(separatedBy: " ").count == 1 {
webView.isOneWord = true
webView.createMenu(options: false)
} else {
webView.isOneWord = false
}
}
return super.canPerformAction(action, withSender: sender)
}
// MARK: ColorView fix for horizontal layout
func refreshPageMode() {
if FolioReader.nightMode {
// omit create webView and colorView
let script = "document.documentElement.offsetHeight"
let contentHeight = webView.stringByEvaluatingJavaScript(from: script)
let frameHeight = webView.frame.height
let lastPageHeight = frameHeight * CGFloat(webView.pageCount) - CGFloat(Double(contentHeight!)!)
colorView.frame = CGRect(x: webView.frame.width * CGFloat(webView.pageCount-1), y: webView.frame.height - lastPageHeight, width: webView.frame.width, height: lastPageHeight)
} else {
colorView.frame = CGRect.zero
}
}
// MARK: - Class based click listener
fileprivate func setupClassBasedOnClickListeners() {
for listener in readerConfig.classBasedOnClickListeners {
self.webView.js("addClassBasedOnClickListener(\"\(listener.schemeName)\", \"\(listener.querySelector)\", \"\(listener.attributeName)\", \"\(listener.selectAll)\")");
}
}
// MARK: - Public Java Script injection
/**
Runs a JavaScript script and returns it result. The result of running the JavaScript script passed in the script parameter, or nil if the script fails.
- returns: The result of running the JavaScript script passed in the script parameter, or nil if the script fails.
*/
open func performJavaScript(_ javaScriptCode: String) -> String? {
return webView.js(javaScriptCode)
}
}
| bsd-3-clause | 01de00bafcdca23c0e710878b7501927 | 38.622047 | 461 | 0.644674 | 5.124236 | false | false | false | false |
Ezfen/iOS.Apprentice.1-4 | Checklists/Checklists/ListDetailViewController.swift | 1 | 3626 | //
// ListDetailViewController.swift
// Checklists
//
// Created by ezfen on 16/8/11.
// Copyright © 2016年 Ezfen lnc. All rights reserved.
//
import UIKit
protocol ListDetailViewControllerDelegate: class {
func listDetailViewControllerDidCancel(controller: ListDetailViewController)
func listDetailViewController(controller: ListDetailViewController, didFinishAddingChecklist checklist: Checklist)
func listDetailViewController(controller: ListDetailViewController,didFinishEditingChecklist checklist: Checklist)
}
class ListDetailViewController: UITableViewController, UITextFieldDelegate, IconPickerViewControllerDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var doneBarButton: UIBarButtonItem!
@IBOutlet weak var iconImageView: UIImageView!
var iconName = "Folder"
weak var delegate: ListDetailViewControllerDelegate?
var checklistToEdit: Checklist?
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()
if let checklist = checklistToEdit {
title = "Edit Checklist"
textField.text = checklist.name
doneBarButton.enabled = true
iconName = checklist.iconName
}
iconImageView.image = UIImage(named: iconName)
}
override func viewWillAppear(animated: Bool) {
super.viewDidAppear(animated)
textField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancel() {
delegate?.listDetailViewControllerDidCancel(self)
}
@IBAction func done() {
if let checklist = checklistToEdit {
checklist.name = textField.text!
checklist.iconName = iconName
delegate?.listDetailViewController(self, didFinishEditingChecklist: checklist)
} else {
let checklist = Checklist(name: textField.text!)
checklist.iconName = iconName
delegate?.listDetailViewController(self, didFinishAddingChecklist: checklist)
}
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if indexPath.section == 1 {
return indexPath
} else {
return nil
}
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let oldText: NSString = textField.text!
let newText: NSString = oldText.stringByReplacingCharactersInRange(range, withString: string)
doneBarButton.enabled = (newText.length > 0)
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "PickIcon" {
let controller = segue.destinationViewController as! IconPickerViewController
controller.delegate = self
}
}
func iconPicker(picker: IconPickerViewController, didPickIcon iconName: String) {
self.iconName = iconName
iconImageView.image = UIImage(named: iconName)
navigationController?.popViewControllerAnimated(true)
}
}
| mit | 56b30461154c8a74e7361d0d99e5229c | 35.59596 | 132 | 0.691968 | 5.949097 | false | false | false | false |
insidegui/WWDC | WWDC/ActionLabel.swift | 1 | 1154 | //
// ActionLabel.swift
// WWDC
//
// Created by Guilherme Rambo on 28/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
final class ActionLabel: NSTextField {
private var cursorTrackingArea: NSTrackingArea!
override func updateTrackingAreas() {
super.updateTrackingAreas()
if cursorTrackingArea != nil {
removeTrackingArea(cursorTrackingArea)
}
cursorTrackingArea = NSTrackingArea(rect: bounds,
options: [.cursorUpdate, .inVisibleRect, .activeInActiveApp],
owner: self,
userInfo: nil)
addTrackingArea(cursorTrackingArea)
}
override func cursorUpdate(with event: NSEvent) {
if event.trackingArea == cursorTrackingArea {
NSCursor.pointingHand.push()
} else {
super.cursorUpdate(with: event)
}
}
override func mouseDown(with event: NSEvent) {
if let action = action {
NSApp.sendAction(action, to: target, from: self)
}
}
}
| bsd-2-clause | 9857c91710aeaef1444ec23dd17d04ce | 25.813953 | 105 | 0.57242 | 5.170404 | false | false | false | false |
karstengresch/rw_studies | StackReview/StackReview/PancakeHouse.swift | 1 | 4216 | /*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import CoreLocation
enum PriceGuide : Int {
case Unknown = 0
case Low = 1
case Medium = 2
case High = 3
}
extension PriceGuide : CustomStringConvertible {
var description : String {
switch self {
case .Unknown:
return "?"
case .Low:
return "$"
case .Medium:
return "$$"
case .High:
return "$$$"
}
}
}
enum PancakeRating {
case Unknown
case Rating(Int)
}
extension PancakeRating {
init?(value: Int) {
if value > 0 && value <= 5 {
self = .Rating(value)
} else {
self = .Unknown
}
}
}
extension PancakeRating {
var ratingImage : UIImage? {
guard let baseName = ratingImageName else {
return nil
}
return UIImage(named: baseName)
}
var smallRatingImage : UIImage? {
guard let baseName = ratingImageName else {
return nil
}
return UIImage(named: "\(baseName)_small")
}
private var ratingImageName : String? {
switch self {
case .Unknown:
return nil
case .Rating(let value):
return "pancake_rate_\(value)"
}
}
}
struct PancakeHouse {
let name: String
let photo: UIImage?
let thumbnail: UIImage?
let priceGuide: PriceGuide
let location: CLLocationCoordinate2D?
let details: String
let rating: PancakeRating
}
extension PancakeHouse {
init?(dict: [String : AnyObject]) {
guard let name = dict["name"] as? String,
let priceGuideRaw = dict["priceGuide"] as? Int,
let priceGuide = PriceGuide(rawValue: priceGuideRaw),
let details = dict["details"] as? String,
let ratingRaw = dict["rating"] as? Int,
let rating = PancakeRating(value: ratingRaw) else {
return nil
}
self.name = name
self.priceGuide = priceGuide
self.details = details
self.rating = rating
if let imageName = dict["imageName"] as? String where !imageName.isEmpty {
photo = UIImage(named: imageName)
} else {
photo = nil
}
if let thumbnailName = dict["thumbnailName"] as? String where !thumbnailName.isEmpty {
thumbnail = UIImage(named: thumbnailName)
} else {
thumbnail = nil
}
if let latitude = dict["latitude"] as? Double,
let longitude = dict["longitude"] as? Double {
location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
} else {
location = nil
}
}
}
extension PancakeHouse {
static func loadDefaultPancakeHouses() -> [PancakeHouse]? {
return self.loadPancakeHousesFromPlistNamed("pancake_houses")
}
static func loadPancakeHousesFromPlistNamed(plistName: String) -> [PancakeHouse]? {
guard let path = NSBundle.mainBundle().pathForResource(plistName, ofType: "plist"),
let array = NSArray(contentsOfFile: path) as? [[String : AnyObject]] else {
return nil
}
return array.map { PancakeHouse(dict: $0) }
.filter { $0 != nil }
.map { $0! }
}
}
extension PancakeHouse : CustomStringConvertible {
var description : String {
return "\(name) :: \(details)"
}
}
| unlicense | ddd2b646f6d045fa886da0a5324fecbf | 25.186335 | 90 | 0.66129 | 4.258586 | false | false | false | false |
joerocca/GitHawk | Pods/Pageboy/Sources/Pageboy/Utilities/ViewUtilities/UIView+AutoLayout.swift | 1 | 1302 | //
// UIView+AutoLayout.swift
// Pageboy
//
// Created by Merrick Sapsford on 15/02/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
internal extension UIView {
@discardableResult func pinToSuperviewEdges() -> [NSLayoutConstraint]? {
guard self.superview != nil else {
fatalError("superview can not be nil")
}
self.translatesAutoresizingMaskIntoConstraints = false
let views = ["view" : self]
var constraints = [NSLayoutConstraint]()
let xConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|",
options: NSLayoutFormatOptions(),
metrics: nil, views: views)
let yConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|",
options: NSLayoutFormatOptions(),
metrics: nil, views: views)
constraints.append(contentsOf: xConstraints)
constraints.append(contentsOf: yConstraints)
self.superview?.addConstraints(constraints)
return constraints
}
}
| mit | 0f0606bbcb7b45adbd60a4b8d28584ca | 37.264706 | 95 | 0.549577 | 6.051163 | false | false | false | false |
coffee-cup/solis | SunriseSunset/SunType.swift | 1 | 5747 | //
// SunType.swift
// SunriseSunset
//
// Created by Jake Runzer on 2016-07-17.
// Copyright © 2016 Puddllee. All rights reserved.
//
import Foundation
import UIKit
enum SunType {
case astronomicalDawn
case nauticalDawn
case civilDawn
case sunrise
case sunset
case civilDusk
case nauticalDusk
case astronomicalDusk
case middleNight
var description: String {
switch self {
case .astronomicalDawn: return "Astronomical Dawn";
case .nauticalDawn: return "Nautical Dawn";
case .civilDawn: return "Civil Dawn";
case .sunrise: return "Sunrise";
case .sunset: return "Sunset";
case .civilDusk: return "Civil Dusk";
case .nauticalDusk: return "Nautical Dusk";
case .astronomicalDusk: return "Astronomical Dusk";
case .middleNight: return "Middle of Night";
}
}
var marker: Bool {
switch self {
case .astronomicalDawn: return true;
case .nauticalDawn: return false;
case .civilDawn: return false;
case .sunrise: return true;
case .sunset: return true;
case .civilDusk: return false;
case .nauticalDusk: return false;
case .astronomicalDusk: return true;
case .middleNight: return false;
}
}
var colour: CGColor {
switch self {
case .astronomicalDawn: return astronomicalColour.cgColor as CGColor
case .nauticalDawn: return nauticalColour.cgColor as CGColor
case .civilDawn: return civilColour.cgColor as CGColor
case .sunrise: return risesetColour.cgColor as CGColor
case .civilDusk: return civilColour.cgColor as CGColor
case .nauticalDusk: return nauticalColour.cgColor as CGColor
case .sunset: return risesetColour.cgColor as CGColor
case .astronomicalDusk: return astronomicalColour.cgColor as CGColor
case .middleNight: return astronomicalColour.cgColor as CGColor
}
}
var lineColour: UIColor {
switch self {
case .astronomicalDawn: return lightLineColour;
case .nauticalDawn: return lightLineColour;
case .civilDawn: return lightLineColour;
case .sunrise: return lightLineColour;
case .sunset: return darkLineColour;
case .civilDusk: return darkLineColour;
case .nauticalDusk: return darkLineColour;
case .astronomicalDusk: return darkLineColour;
case .middleNight: return middleLineColour;
}
}
var message: String {
var message = ""
if self == .astronomicalDawn || self == .nauticalDawn || self == .civilDawn {
message = "The sun is awake now ☀️ Have a good day"
} else if self == .sunrise {
message = "The sun has risen 🌄"
} else if self == .sunset {
message = "The sun has set 🌇"
} else if self == .civilDusk || self == .nauticalDusk || self == .astronomicalDusk {
message = "The sun has gone to sleep for the night 🌚 Goodnight"
}
return message
}
var event: String {
var message = ""
if self == .astronomicalDawn || self == .nauticalDawn || self == .civilDawn {
message = "First Light"
} else if self == .sunrise {
message = "Sunrise"
} else if self == .sunset {
message = "Sunset"
} else if self == .civilDusk || self == .nauticalDusk || self == .astronomicalDusk {
message = "Last Light"
}
return message
}
var twilightDawn: Bool {
switch self {
case .astronomicalDawn: return true;
case .nauticalDawn: return true;
case .civilDawn: return true;
case .sunrise: return false;
case .sunset: return false;
case .civilDusk: return false;
case .nauticalDusk: return false;
case .astronomicalDusk: return false;
case .middleNight: return false;
}
}
var twilightDusk: Bool {
switch self {
case .astronomicalDawn: return false;
case .nauticalDawn: return false;
case .civilDawn: return false;
case .sunrise: return false;
case .sunset: return false;
case .civilDusk: return true;
case .nauticalDusk: return true;
case .astronomicalDusk: return true;
case .middleNight: return false;
}
}
var morning: Bool {
switch self {
case .astronomicalDawn: return true;
case .nauticalDawn: return true;
case .civilDawn: return true;
case .sunrise: return true;
case .sunset: return false;
case .civilDusk: return false;
case .nauticalDusk: return false;
case .astronomicalDusk: return false;
case .middleNight: return false;
}
}
var night: Bool {
switch self {
case .astronomicalDawn: return false;
case .nauticalDawn: return false;
case .civilDawn: return false;
case .sunrise: return false;
case .sunset: return true;
case .civilDusk: return true;
case .nauticalDusk: return true;
case .astronomicalDusk: return true;
case .middleNight: return false;
}
}
var degrees: Float {
switch self {
case .astronomicalDawn: return 18;
case .nauticalDawn: return 12;
case .civilDawn: return 6;
case .sunrise: return 0;
case .sunset: return 0;
case .civilDusk: return 6;
case .nauticalDusk: return 12;
case .astronomicalDusk: return 18;
case .middleNight: return 270;
}
}
}
| mit | 8f43a8382ff450395f8e6dcec0721794 | 31.573864 | 92 | 0.603175 | 4.850254 | false | false | false | false |
J3D1-WARR10R/WikiRaces | Mac Utils/WKRRaceLiveViewer/WKRRaceLiveViewer/Model.swift | 2 | 1405 | //
// Model.swift
// WKRRaceLiveViewer
//
// Created by Andrew Finke on 7/2/20.
//
import CloudKit
import WKRKitCore
class Model: ObservableObject {
// MARK: - Properties -
private let raceCode: String
@Published var host: String?
@Published var state: WKRGameState?
@Published var resultsInfo: WKRResultsInfo?
// MARK: - Initalization -
init(raceCode: String) {
self.raceCode = raceCode
update()
Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in
self.update()
}
}
// MARK: - Helpers -
func update() {
let predicate = NSPredicate(format: "Code == %@", raceCode)
let sort = NSSortDescriptor(key: "modificationDate", ascending: false)
let query = CKQuery(recordType: "RaceActive", predicate: predicate)
query.sortDescriptors = [sort]
let operation = CKQueryOperation(query: query)
operation.resultsLimit = 1
operation.recordFetchedBlock = { record in
let wrapper = WKRRaceActiveRecordWrapper(record: record)
DispatchQueue.main.async {
self.host = wrapper.host()
self.state = wrapper.state()
self.resultsInfo = wrapper.resultsInfo()
}
}
CKContainer(identifier: "iCloud.com.andrewfinke.wikiraces").publicCloudDatabase.add(operation)
}
}
| mit | a3c4faec9abc35151759763f3631c527 | 26.019231 | 102 | 0.618505 | 4.404389 | false | false | false | false |
nnianhou-/M-Vapor | Sources/App/Models/Video.swift | 1 | 6239 | //
// Video.swift
// App
//
// Created by N年後 on 2017/10/20.
//
import Vapor
import FluentProvider
import HTTP
final class Video:Model{
static let idKey = "id"
static let videoHallIdKey = "videoHallId"
static let titleKey = "title"
static let coverKey = "cover"
static let coverIdKey = "coverId"
static let createdAtKey = "createdAt"
static let videoIdKey = "videoId"
static let durationKey = "duration"
static let playUrlKey = "playUrl"
static let statusKey = "status"
static let sourceKey = "source"
var videoHallId: String
var title: String
var cover: String
var coverId: String
var createdAt: String
var videoId: String
var duration: String
var playUrl: String
var status : String
var source : String
let storage = Storage()
/// 常规的构造器
init(videoHallId: String,title:String,cover:String,coverId:String,createdAt:String,videoId:String,duration:String,playUrl:String,status:String,source:String) {
self.videoHallId = videoHallId
self.title = title
self.cover = cover
self.coverId = coverId
self.createdAt = createdAt
self.videoId = videoId
self.duration = duration
self.playUrl = playUrl
self.status = status
self.source = source
}
// MARK: Fluent 序列化构造器
/// 通过这个构造器你可以使用数据库中的一行生成一个对应的对象
init(row: Row) throws {
videoHallId = try row.get(Video.videoHallIdKey)
title = try row.get(Video.titleKey)
cover = try row.get(Video.coverKey)
coverId = try row.get(Video.coverIdKey)
createdAt = try row.get(Video.createdAtKey)
videoId = try row.get(Video.videoIdKey)
duration = try row.get(Video.durationKey)
playUrl = try row.get(Video.playUrlKey)
status = try row.get(Video.statusKey)
source = try row.get(Video.sourceKey)
}
// 把一个对象存储到数据库当中
func makeRow() throws -> Row {
var row = Row()
try row.set(Video.videoHallIdKey, videoHallId)
try row.set(Video.titleKey, title)
try row.set(Video.coverKey, cover)
try row.set(Video.coverIdKey, coverId)
try row.set(Video.createdAtKey, createdAt)
try row.set(Video.videoIdKey, videoId)
try row.set(Video.durationKey, duration)
try row.set(Video.playUrlKey, playUrl)
try row.set(Video.statusKey, status)
try row.set(Video.sourceKey, source)
return row
}
}
extension Video:Preparation {
static func prepare(_ database: Database) throws {
try database.create(self, closure: { Videos in
Videos.id()
Videos.string(Video.videoHallIdKey)
Videos.string(Video.titleKey)
Videos.string(Video.coverKey)
Videos.string(Video.coverIdKey)
Videos.string(Video.createdAtKey)
Videos.string(Video.videoIdKey)
Videos.string(Video.durationKey)
Videos.string(Video.playUrlKey)
Videos.string(Video.statusKey)
Videos.string(Video.sourceKey)
})
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
extension Video: JSONRepresentable {
convenience init(json: JSON) throws {
try self.init(
videoHallId:json.get(Video.videoHallIdKey),
title:json.get(Video.titleKey),
cover:json.get(Video.coverKey),
coverId:json.get(Video.coverIdKey),
createdAt:json.get(Video.createdAtKey),
videoId:json.get(Video.videoIdKey),
duration:json.get(Video.durationKey),
playUrl:json.get(Video.playUrlKey),
status:json.get(Video.statusKey),
source:json.get(Video.sourceKey)
)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set(Video.idKey, id)
try json.set(Video.videoHallIdKey, videoHallId)
try json.set(Video.titleKey, title)
try json.set(Video.coverKey, cover)
try json.set(Video.coverIdKey, coverId)
try json.set(Video.createdAtKey, createdAt)
try json.set(Video.videoIdKey, videoId)
try json.set(Video.durationKey, duration)
try json.set(Video.playUrlKey, playUrl)
try json.set(Video.statusKey, status)
try json.set(Video.sourceKey, source)
return json
}
}
extension Video: Updateable {
public static var updateableKeys: [UpdateableKey<Video>] {
return [
UpdateableKey(Video.videoHallIdKey, String.self) { Video, videoHallId in
Video.videoHallId = videoHallId
},
UpdateableKey(Video.titleKey, String.self) { Video, title in
Video.title = title
},
UpdateableKey(Video.coverKey, String.self) { Video, cover in
Video.cover = cover
},
UpdateableKey(Video.coverIdKey, String.self) { Video, coverId in
Video.coverId = coverId
},
UpdateableKey(Video.createdAtKey, String.self) { Video, createdAt in
Video.createdAt = createdAt
},
UpdateableKey(Video.videoIdKey, String.self) { Video, videoId in
Video.videoId = videoId
}, UpdateableKey(Video.durationKey, String.self) { Video, duration in
Video.duration = duration
},
UpdateableKey(Video.playUrlKey, String.self) { Video, playUrl in
Video.playUrl = playUrl
},
UpdateableKey(Video.statusKey, String.self) { Video, status in
Video.status = status
},
UpdateableKey(Video.sourceKey, String.self) { Video, source in
Video.source = source
}
]
}
}
extension Video: ResponseRepresentable { }
| mit | 41a26c78a8de8f121c5ada757f499808 | 28.897561 | 163 | 0.591287 | 4.556877 | false | false | false | false |
xiaoxionglaoshi/SwiftProgramming | 003 StringsAndCharacters.playground/Contents.swift | 1 | 1227 |
// 字符串字面量
let someString = "some string literal value"
// 初始化空字符串
var emptyString = ""
var anotherEmptyString = String()
// 字符串可变性
var variableString = "hello"
variableString += " swift"
// 字符串值类型
for character in variableString.characters {
print(character)
}
// 字符集合转字符串
let strCharacters: [Character] = ["h", "e", "l", "l", "o"]
let str = String(strCharacters)
// 字符串索引
let greeting = "guten tag"
greeting[greeting.startIndex]
greeting[greeting.index(after: greeting.startIndex)]
greeting[greeting.index(greeting.endIndex, offsetBy: -2)]
for index in greeting.characters.indices {
print(greeting[index], terminator: ",")
}
// 插入和删除
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
welcome.insert(contentsOf: " swift".characters, at: welcome.index(before: welcome.endIndex))
welcome.remove(at: welcome.startIndex)
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// 前缀/后缀判断
let messageStr = "hello swift"
if messageStr.hasPrefix("he") {
print("存在he的前缀")
}
if messageStr.hasSuffix("ft") {
print("存在ft的后缀")
}
| apache-2.0 | cd18a3e48d8a64229d6cde0d4612d807 | 21.632653 | 92 | 0.720469 | 3.350453 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/Demo/Modules/Demos/UIKit/QDNavigationListViewController.swift | 1 | 1861 | //
// QDNavigationListViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/23.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDNavigationListViewController: QDCommonListViewController {
override func initDataSource() {
super.initDataSource()
dataSourceWithDetailText = QMUIOrderedDictionary(
dictionaryLiteral:
("拦截系统navBar返回按钮事件", "例如询问已输入的内容要不要保存"),
("感知系统的手势返回", "可感知到是否成功手势返回或者中断了"),
("方便控制界面导航栏样式", "方便控制前后两个界面的导航栏和状态栏样式"),
("优化导航栏在转场时的样式", "优化系统navController只有一个navBar带来的问题"))
}
override func didSelectCell(_ title: String) {
var viewController: UIViewController?
if title == "拦截系统navBar返回按钮事件" {
viewController = QDInterceptBackButtonEventViewController()
}
if title == "感知系统的手势返回" {
viewController = QDNavigationTransitionViewController()
}
if title == "方便控制界面导航栏样式" {
viewController = QDChangeNavBarStyleViewController()
}
if title == "优化导航栏在转场时的样式" {
viewController = QDChangeNavBarStyleViewController()
if let viewController = viewController as? QDChangeNavBarStyleViewController {
viewController.customNavBarTransition = true
}
}
if let viewController = viewController {
viewController.title = title
navigationController?.pushViewController(viewController, animated: true)
}
}
}
| mit | a85a2e4e041b9e143ff090c5a5dbd374 | 31.375 | 90 | 0.633205 | 4.766871 | false | false | false | false |
kzaher/RxFirebase | RxFirebase/Classes/Extensions.swift | 2 | 2138 | //
// RxFirebase.swift
// Pods
//
// Created by Krunoslav Zaher on 12/7/16.
//
//
import Foundation
import RxSwift
public struct UnknownFirebaseError: Error {
}
func parseFirebaseResponse<T>(_ observer: AnyObserver<T>) -> (T?, Error?) -> () {
return { value, error in
if let value = value {
observer.on(.next(value))
observer.on(.completed)
}
else if let error = error {
observer.on(.error(error))
}
else {
observer.on(.error(UnknownFirebaseError()))
}
}
}
func parseFirebaseResponse<T>(_ observer: AnyObserver<StorageObservableTask<T>>) -> (T?, Error?) -> () {
return { value, error in
if let value = value {
observer.on(.next(StorageObservableTask(result: value)))
observer.on(.completed)
}
else if let error = error {
observer.on(.error(error))
}
else {
observer.on(.error(UnknownFirebaseError()))
}
}
}
func parseFirebaseResponse<T>(_ observer: AnyObserver<T>) -> (Error?, T?) -> () {
return { error, value in
if let value = value {
observer.on(.next(value))
observer.on(.completed)
}
else if let error = error {
observer.on(.error(error))
}
else {
observer.on(.error(UnknownFirebaseError()))
}
}
}
func parseFirebaseResponse<T, T2>(_ observer: AnyObserver<(T2, T)>) -> (Error?, T2, T?) -> () {
return { error, value2, value in
if let value = value {
observer.on(.next((value2, value)))
observer.on(.completed)
}
else if let error = error {
observer.on(.error(error))
}
else {
observer.on(.error(UnknownFirebaseError()))
}
}
}
func parseFirebaseResponse(_ observer: AnyObserver<()>) -> (Error?) -> () {
return { error in
if let error = error {
observer.on(.error(error))
}
else {
observer.on(.next())
observer.on(.completed)
}
}
}
| mit | bac655fd5bf3480a16acfef1c1b1abfd | 23.860465 | 104 | 0.523386 | 4.135397 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/ApplicationDiscoveryService/ApplicationDiscoveryService_Paginator.swift | 1 | 6345 | //===----------------------------------------------------------------------===//
//
// 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
// MARK: Paginators
extension ApplicationDiscoveryService {
/// Lists exports as specified by ID. All continuous exports associated with your user account can be listed if you call DescribeContinuousExports as is without passing any parameters.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func describeContinuousExportsPaginator<Result>(
_ input: DescribeContinuousExportsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, DescribeContinuousExportsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: describeContinuousExports,
tokenKey: \DescribeContinuousExportsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func describeContinuousExportsPaginator(
_ input: DescribeContinuousExportsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeContinuousExportsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: describeContinuousExports,
tokenKey: \DescribeContinuousExportsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns an array of import tasks for your account, including status information, times, IDs, the Amazon S3 Object URL for the import file, and more.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func describeImportTasksPaginator<Result>(
_ input: DescribeImportTasksRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, DescribeImportTasksResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: describeImportTasks,
tokenKey: \DescribeImportTasksResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func describeImportTasksPaginator(
_ input: DescribeImportTasksRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeImportTasksResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: describeImportTasks,
tokenKey: \DescribeImportTasksResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension ApplicationDiscoveryService.DescribeContinuousExportsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ApplicationDiscoveryService.DescribeContinuousExportsRequest {
return .init(
exportIds: self.exportIds,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension ApplicationDiscoveryService.DescribeImportTasksRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ApplicationDiscoveryService.DescribeImportTasksRequest {
return .init(
filters: self.filters,
maxResults: self.maxResults,
nextToken: token
)
}
}
| apache-2.0 | 350dbbbe794f2031338c3956bdb49fbe | 43.370629 | 189 | 0.653743 | 5.2875 | false | false | false | false |
functionaldude/XLPagerTabStrip | Example/Example/Spotify/SpotifyExampleViewController.swift | 2 | 3463 | // SpotifyExampleViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import XLPagerTabStrip
class SpotifyExampleViewController: ButtonBarPagerTabStripViewController {
@IBOutlet weak var shadowView: UIView!
let graySpotifyColor = UIColor(red: 21/255.0, green: 21/255.0, blue: 24/255.0, alpha: 1.0)
let darkGraySpotifyColor = UIColor(red: 19/255.0, green: 20/255.0, blue: 20/255.0, alpha: 1.0)
override func viewDidLoad() {
// change selected bar color
settings.style.buttonBarBackgroundColor = graySpotifyColor
settings.style.buttonBarItemBackgroundColor = graySpotifyColor
settings.style.selectedBarBackgroundColor = UIColor(red: 33/255.0, green: 174/255.0, blue: 67/255.0, alpha: 1.0)
settings.style.buttonBarItemFont = UIFont(name: "HelveticaNeue-Light", size:14) ?? UIFont.systemFont(ofSize: 14)
settings.style.selectedBarHeight = 3.0
settings.style.buttonBarMinimumLineSpacing = 0
settings.style.buttonBarItemTitleColor = .black
settings.style.buttonBarItemsShouldFillAvailableWidth = true
settings.style.buttonBarLeftContentInset = 20
settings.style.buttonBarRightContentInset = 20
changeCurrentIndexProgressive = { (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
guard changeCurrentIndex == true else { return }
oldCell?.label.textColor = UIColor(red: 138/255.0, green: 138/255.0, blue: 144/255.0, alpha: 1.0)
newCell?.label.textColor = .white
}
super.viewDidLoad()
}
// MARK: - PagerTabStripDataSource
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
let child_1 = TableChildExampleViewController(style: .plain, itemInfo: IndicatorInfo(title: "FRIENDS"))
child_1.blackTheme = true
let child_2 = TableChildExampleViewController(style: .plain, itemInfo: IndicatorInfo(title: "FEATURED"))
child_2.blackTheme = true
return [child_1, child_2]
}
// MARK: - Actions
@IBAction func closeAction(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
| mit | 7ca9cd312b356201ca738dd124a7472e | 47.097222 | 182 | 0.725383 | 4.642091 | false | false | false | false |
charmaex/JDSegues | JDSegues/JDSegueScaleIn.swift | 1 | 1836 | //
// JDSegueScaleIn.swift
// JDSegues
//
// Created by Jan Dammshäuser on 28.08.16.
// Copyright © 2016 Jan Dammshäuser. All rights reserved.
//
import UIKit
/// Segue where the next screen scales in from a point or the center of the screen.
@objc
public class JDSegueScaleIn: UIStoryboardSegue, JDSegueDelayable, JDSegueOriginable {
/// Defines at which point the animation should start
/// - parameter Default: center of the screen
public var animationOrigin: CGPoint?
/// Time the transition animation takes
/// - parameter Default: 0.5 seconds
public var transitionTime: NSTimeInterval = 0.5
/// Time the transition animation is delayed after calling
/// - parameter Default: 0 seconds
public var transitionDelay: NSTimeInterval = 0
/// Animation Curve
/// - parameter Default: CurveLinear
public var animationOption: UIViewAnimationOptions = .CurveLinear
public override func perform() {
let sourceVC = sourceViewController
let destinationVC = destinationViewController
let destCenter = sourceVC.view.center
setupScreens()
destinationVC.view.transform = CGAffineTransformMakeScale(0.05, 0.05)
if let center = animationOrigin {
destinationVC.view.center = center
}
delay() {
sourceVC.view.addSubview(destinationVC.view)
UIView.animateWithDuration(self.transitionTime, delay: 0, options: self.animationOption, animations: {
destinationVC.view.transform = CGAffineTransformMakeScale(1, 1)
destinationVC.view.center = destCenter
}) { finished in
self.finishSegue(nil)
}
}
}
} | mit | f3c0aa36512e38ee1921734acd0d7ff2 | 30.62069 | 114 | 0.633388 | 5.40708 | false | false | false | false |
JaySonGD/SwiftDayToDay | 获取通信录2/获取通信录2/ViewController.swift | 1 | 2269 | //
// ViewController.swift
// 获取通信录2
//
// Created by czljcb on 16/3/18.
// Copyright © 2016年 lQ. All rights reserved.
//
import UIKit
import AddressBook
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if ABAddressBookGetAuthorizationStatus() == ABAuthorizationStatus.NotDetermined{
let book = ABAddressBookCreate().takeRetainedValue()
ABAddressBookRequestAccessWithCompletion(book, { (flag: Bool,error: CFError!) -> Void in
if flag {
print("授权成功")
}else{
print("授权失败")
}
})
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if ABAddressBookGetAuthorizationStatus() != ABAuthorizationStatus.Authorized{
print("用户没有授权")
return
}
let book = ABAddressBookCreate().takeRetainedValue()
let peoples = ABAddressBookCopyArrayOfAllPeople(book).takeRetainedValue()
let count = CFArrayGetCount(peoples)
for i in 0..<count {
let record =
unsafeBitCast(CFArrayGetValueAtIndex(peoples, i)
, ABRecordRef.self)
let name = (ABRecordCopyValue(record, kABPersonFirstNameProperty).takeRetainedValue() as! String) +
(ABRecordCopyValue(record, kABPersonLastNameProperty).takeRetainedValue() as! String)
print(name)
let phones: ABMultiValueRef = ABRecordCopyValue(record, kABPersonPhoneProperty).takeRetainedValue() as ABMultiValueRef
let count = ABMultiValueGetCount(phones)
for i in 0..<count{
print( ABMultiValueCopyLabelAtIndex(phones, i).takeRetainedValue() )
print( ABMultiValueCopyValueAtIndex(phones, i).takeRetainedValue() )
}
}
}
}
| mit | aa5ecfb3d6987954657de8ce92d9b6de | 29.520548 | 130 | 0.556104 | 5.863158 | false | false | false | false |
PairOfNewbie/BeautifulDay | BeautifulDay/View/MusicBar/MusicPlayBar.swift | 1 | 8848 | //
// MusicPlayBar.swift
// BeautifulDay
//
// Created by DaiFengyi on 16/4/11.
// Copyright © 2016年 PairOfNewbie. All rights reserved.
//
import UIKit
import DOUAudioStreamer
class MusicPlayBar: UIView {
var trk: Track? {
didSet {
if trk?.audioFileURL == BDAudioService.shareManager.trk?.audioFileURL {
BDAudioService.shareManager.updateAction = { [unowned self](type) in
switch type {
case .Status:
self.updateStatus()
case .Duration:
self.updateProgress()
case .BufferingRatio:
self.updateBufferingStatus()
}
}
if BDAudioService.shareManager.streamer?.status == .Some(.Playing) {
rotate()
self.updateProgress()
}
}
}
}
var timer: NSTimer?
// var animateProgress : Double = 0 {
// didSet {
// rotateIcon.layer.timeOffset = animateProgress
// }
// }
var streamer: DOUAudioStreamer? {
get {
return BDAudioService.shareManager.streamer
}
}
lazy var rotateImages : [UIImage] = {
var arr = [UIImage]()
for index in 0...126 {
arr.append(UIImage(named: "cd_\(index)")!)
}
return arr
}()
@IBOutlet weak var rotateIcon: UIImageView!
@IBOutlet weak var remainingLabel: UILabel!
@IBOutlet weak var artistLabel: UILabel!
@IBOutlet weak var progressView: UIProgressView!
//MARK:- Initial
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
deinit {
timer?.invalidate()
}
private func commonInit() {
let tapGesture = UITapGestureRecognizer(target: self, action: NSSelectorFromString("onTap:"))
addGestureRecognizer(tapGesture)
}
// func setupSubviews() {
// let fromPoint = rotateIcon.center
// let toPoint = self.center
// let movePath = UIBezierPath()
// movePath.moveToPoint(fromPoint)
// movePath.addLineToPoint(toPoint)
// let animation = CAKeyframeAnimation(keyPath: "position")
// animation.path = movePath.CGPath
// // animation.duration = 1
// // animation.removedOnCompletion = false
// // animation.fillMode = kCAFillModeForwards
// // animation.autoreverses = false
//
// let animation1 = CABasicAnimation(keyPath: "transform.scale")
// animation1.fromValue = NSValue(CATransform3D: CATransform3DIdentity)
// animation1.toValue = NSValue(CATransform3D: CATransform3DMakeScale(3, 3, 1))
// // animation1.removedOnCompletion = false
// // animation1.duration = 1
// // animation1.fillMode = kCAFillModeForwards
// // animation1.autoreverses = false
//
// let animationGroup = CAAnimationGroup()
// animationGroup.animations = [animation, animation1]
// animationGroup.removedOnCompletion = false
// animationGroup.duration = 1
// animationGroup.fillMode = kCAFillModeForwards
// animationGroup.autoreverses = false
//
// rotateIcon.layer.addAnimation(animationGroup, forKey: "rotateIcon")
// }
//MAKR:- Action
func onTap(tapGesture: UITapGestureRecognizer) {
print("onTap:")
if streamer?.status == .Playing {// 正在播放
if trk?.audioFileURL == BDAudioService.shareManager.trk?.audioFileURL {// 当前音乐,则暂停播放
BDAudioService.shareManager.pause()
}else {// 非当前音乐,切歌
if let trk = self.trk {
BDAudioService.shareManager.resetStreamer(trk, updateAction: { [unowned self](type) in
switch type {
case .Status:
self.updateStatus()
case .Duration:
self.updateProgress()
case .BufferingRatio:
self.updateBufferingStatus()
}
})
}
}
}else if streamer?.status == .Paused {// 正在暂停
if let trk = self.trk {
if trk.audioFileURL != BDAudioService.shareManager.trk?.audioFileURL {// 不是当前音乐,切歌
BDAudioService.shareManager.resetStreamer(trk, updateAction: { [unowned self](type) in
switch type {
case .Status:
self.updateStatus()
case .Duration:
self.updateProgress()
case .BufferingRatio:
self.updateBufferingStatus()
}
})
}else {// 当前音乐,播放
BDAudioService.shareManager.play()
}
}
}else {
if let trk = self.trk {
BDAudioService.shareManager.resetStreamer(trk, updateAction: { [unowned self](type) in
switch type {
case .Status:
self.updateStatus()
case .Duration:
self.updateProgress()
case .BufferingRatio:
self.updateBufferingStatus()
}
})
}
}
}
//MARK:- Public
func updateBufferingStatus() {
remainingLabel.text = String(format: "Received %.2f/%.2f MB (%.2f %%), Speed %.2f MB/s", Float(streamer!.receivedLength) / 1024 / 1024, Float(streamer!.expectedLength) / 1024 / 1024, streamer!.bufferingRatio * 100.0, Float(streamer!.downloadSpeed) / 1024 / 1024)
}
func updateStatus() {
//todo
/**
*
switch ([_streamer status]) {
case DOUAudioStreamerPlaying:
[_statusLabel setText:@"playing"];
[_buttonPlayPause setTitle:@"Pause" forState:UIControlStateNormal];
break;
case DOUAudioStreamerPaused:
[_statusLabel setText:@"paused"];
[_buttonPlayPause setTitle:@"Play" forState:UIControlStateNormal];
break;
case DOUAudioStreamerIdle:
[_statusLabel setText:@"idle"];
[_buttonPlayPause setTitle:@"Play" forState:UIControlStateNormal];
break;
case DOUAudioStreamerFinished:
[_statusLabel setText:@"finished"];
[self _actionNext:nil];
break;
case DOUAudioStreamerBuffering:
[_statusLabel setText:@"buffering"];
break;
case DOUAudioStreamerError:
[_statusLabel setText:@"error"];
break;
}
*/
let status = streamer!.status
if status == .Playing {
if rotateIcon.isAnimating() {
resumeLayer(rotateIcon.layer)
}else {
rotate()
}
}else if status == .Paused {
pauseLayer(rotateIcon.layer)
}else if status == .Idle {
rotateIcon.stopAnimating()
}else if status == .Finished {
rotateIcon.stopAnimating()
}else if status == .Buffering {
}else if status == .Error {
rotateIcon.stopAnimating()
}
}
func updateProgress() {
if streamer!.duration == 0{
progressView.setProgress(0, animated: false)
}else {
progressView.setProgress(Float(streamer!.currentTime / streamer!.duration), animated: true)
}
}
//MARK: Animation
func rotate() {
rotateIcon.animationImages = rotateImages
rotateIcon.startAnimating()
}
func pauseLayer(layer: CALayer) {
let pauseTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
layer.speed = 0
layer.timeOffset = pauseTime
}
func resumeLayer(layer: CALayer) {
if layer.speed == 1 {
return
}
let pausedTime = layer.timeOffset
layer.speed = 1
layer.timeOffset = 0
layer.beginTime = 0
let timeSicePause = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime
layer.beginTime = timeSicePause
}
}
| mit | 6c5eec3043a155e72d25b2d2bda3abba | 34.326613 | 270 | 0.522543 | 5.418058 | false | false | false | false |
kreshikhin/scituner | SciTuner/ViewControllers/TunerViewController.swift | 1 | 8336 | //
// TunerViewController.swift
// SciTuner
//
// Created by Denis Kreshikhin on 25.02.15.
// Copyright (c) 2015 Denis Kreshikhin. All rights reserved.
//
import UIKit
import SpriteKit
import RealmSwift
class TunerViewController: UIViewController {
typealias `Self` = TunerViewController
let realm = try! Realm()
var settingsViewController = SettingsViewController()
var instrumentsAlertController = InstrumentsAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
var fretsAlertController = FretsAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
var filtersAlertController = FiltersAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
var tuner = Tuner.sharedInstance
var tubeView: SKView?
var tubeScene: TubeScene?
let processing = Processing(pointCount: Settings.processingPointCount)
var microphone: Microphone?
let stackView = UIStackView()
let tuningView = TuningView()
let modebar = ModebarView()
let fineTuningView = FineTuningView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Style.background
customizeNavigationBar()
addStackView()
customizeDelegates()
addTubeView()
addNoteBar()
addTuningView()
addModeBar()
microphone = Microphone(sampleRate: Settings.sampleRate, sampleCount: Settings.sampleCount)
microphone?.delegate = self
microphone?.activate()
switch tuner.filter {
case .on:
processing.enableFilter()
case .off:
processing.disableFilter()
}
modebar.fret = tuner.fret
modebar.filter = tuner.filter
}
func customizeDelegates() {
tuner.delegate = self
instrumentsAlertController.parentDelegate = self
fretsAlertController.parentDelegate = self
filtersAlertController.parentDelegate = self
}
func customizeNavigationBar() {
self.navigationItem.title = "SciTuner".localized()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(
title: tuner.instrument.localized(),
style: UIBarButtonItemStyle.plain,
target: self,
action: #selector(Self.showInstrumentsAlertController))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "settings".localized(),
style: UIBarButtonItemStyle.plain,
target: self,
action: #selector(Self.showSettingsViewController))
}
func addStackView() {
stackView.frame = view.bounds
stackView.axis = .vertical
stackView.distribution = .equalSpacing
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true
stackView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
}
func addTubeView() {
tubeView = SKView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.width))
tubeView?.translatesAutoresizingMaskIntoConstraints = false
tubeView?.heightAnchor.constraint(equalTo: tubeView!.widthAnchor, multiplier: 1.0).isActive = true
stackView.addArrangedSubview(tubeView!)
if let tb = tubeView {
tb.showsFPS = Settings.showFPS
tubeScene = TubeScene(size: tb.bounds.size)
tb.presentScene(tubeScene)
tb.ignoresSiblingOrder = true
tubeScene?.customDelegate = self
}
}
func addModeBar() {
modebar.fretMode.addTarget(self, action: #selector(TunerViewController.showFrets), for: .touchUpInside)
modebar.filterMode.addTarget(self, action: #selector(TunerViewController.showFilters), for: .touchUpInside)
stackView.addArrangedSubview(modebar)
}
func addNoteBar() {
stackView.addArrangedSubview(fineTuningView)
}
func addTuningView() {
stackView.addArrangedSubview(tuningView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tuningView.tuning = tuner.tuning
}
func showSettingsViewController() {
navigationController?.pushViewController(settingsViewController, animated: true)
}
func showInstrumentsAlertController() {
present(instrumentsAlertController, animated: true, completion: nil)
}
func showFrets() {
present(fretsAlertController, animated: true, completion: nil)
}
func showFilters() {
present(filtersAlertController, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension TunerViewController: TunerDelegate {
func didSettingsUpdate() {
switch tuner.filter {
case .on: processing.enableFilter()
case .off: processing.disableFilter()
}
}
func didFrequencyChange() {
//panel?.targetFrequency?.text = String(format: "%.2f %@", tuner.targetFrequency(), "Hz".localized())
}
func didStatusChange() {
if tuner.isActive {
microphone?.activate()
} else {
microphone?.inactivate()
}
}
}
extension TunerViewController: MicrophoneDelegate {
func microphone(_ microphone: Microphone?, didReceive data: [Double]?) {
if tuner.isPaused {
return
}
if let tf = tuner.targetFrequency() {
processing.setTargetFrequency(tf)
}
guard let micro = microphone else {
return
}
var wavePoints = [Double](repeating: 0, count: Int(processing.pointCount-1))
let band = tuner.band()
processing.setBand(fmin: band.fmin, fmax: band.fmax)
processing.push(µ.sample)
processing.savePreview(µ.preview)
processing.recalculate()
processing.buildSmoothStandingWave2(&wavePoints, length: wavePoints.count)
tuner.frequency = processing.getFrequency()
tuner.updateTargetFrequency()
tubeScene?.draw(wave: wavePoints)
//panel?.actualFrequency?.text = String(format: "%.2f %@", tuner.frequency, "Hz".localized())
//panel?.frequencyDeviation!.text = String(format: "%.0fc", tuner.frequencyDeviation())
//self.panel?.notebar?.pointerPosition = self.tuner.stringPosition()
fineTuningView.pointerPosition = tuner.noteDeviation()
//print("f dev:", tuner.frequencyDeviation())
tuningView.notePosition = CGFloat(tuner.stringPosition())
if processing.pulsation() > 3 {
tuningView.showPointer()
fineTuningView.showPointer()
} else {
tuningView.hidePointer()
fineTuningView.hidePointer()
}
}
}
extension TunerViewController: InstrumentsAlertControllerDelegate {
func didChange(instrument: Instrument) {
try! realm.write {
tuner.instrument = instrument
}
tuningView.tuning = tuner.tuning
navigationItem.leftBarButtonItem?.title = tuner.instrument.localized()
}
}
extension TunerViewController: FretsAlertControllerDelegate {
func didChange(fret: Fret) {
try! realm.write {
tuner.fret = fret
}
modebar.fret = fret
}
}
extension TunerViewController: FiltersAlertControllerDelegate {
func didChange(filter: Filter) {
try! realm.write {
tuner.filter = filter
}
modebar.filter = filter
}
}
extension TunerViewController: TubeSceneDelegate {
func getNotePosition() -> CGFloat {
return CGFloat(tuner.notePosition())
}
func getPulsation() -> CGFloat {
return CGFloat(processing.pulsation())
}
}
| mit | 78c046d7e3ac5d64c78c2e66d36aee6a | 29.874074 | 119 | 0.633757 | 5.232894 | false | false | false | false |
googlemaps/last-mile-fleet-solution-samples | ios_driverapp_samples/LMFSDriverSampleApp/ListTab/StopList.swift | 1 | 2515 | /*
* Copyright 2022 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import SwiftUI
/// This view shows a list of stops that the vehicle will navigate to in order. Each stop is
/// represented by a `StopListRow`.
struct StopList: View {
@EnvironmentObject var modelData: ModelData
@State private var editMode = EditMode.inactive
var body: some View {
NavigationView {
VStack(alignment: .leading) {
List {
ForEach(modelData.stops) { stop in
StopListRow(stop: stop)
.moveDisabled(stop.taskStatus != .pending)
}
.onMove { source, destination in
modelData.moveStops(source: source, destination: destination)
}
}
.environment(\.editMode, $editMode)
VStack(alignment: .leading) {
HStack {
Text("ID: \(modelData.manifest.vehicle.vehicleId)")
Spacer()
Button(action: {
UIPasteboard.general.string = modelData.manifest.vehicle.vehicleId
}) {
Image(systemName: "doc.on.doc")
}
}
Text("Total tasks: \(modelData.manifest.tasks.count)")
}
.foregroundColor(.gray)
.padding(EdgeInsets(top: 0, leading: 20, bottom: 10, trailing: 20))
}
.navigationTitle("Your itinerary")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(editMode == .inactive ? "Reorder Stops" : "Done") {
editMode = (editMode == .inactive ? .active : .inactive)
}
}
}
}
.navigationViewStyle(StackNavigationViewStyle())
.navigationBarTitleDisplayMode(.inline)
.ignoresSafeArea(edges: .top)
}
}
struct StopList_Previews: PreviewProvider {
static var previews: some View {
let _ = LMFSDriverSampleApp.googleMapsInited
StopList()
.environmentObject(ModelData(filename: "test_manifest"))
}
}
| apache-2.0 | b4021b4bcdc7ff2244967255fec64684 | 32.986486 | 92 | 0.627038 | 4.597806 | false | false | false | false |
aleffert/dials | Desktop/Source/FormattingUtilities.swift | 1 | 1470 | //
// FormattingUtilities.swift
// Dials-Desktop
//
// Created by Akiva Leffert on 3/22/15.
//
//
import Foundation
func stringFromNumber(_ value : Float, requireIntegerPart : Bool = false) -> String {
return stringFromNumber(NSNumber(value: value as Float), requireIntegerPart : requireIntegerPart)
}
func stringFromNumber(_ value : CGFloat, requireIntegerPart : Bool = false) -> String {
return stringFromNumber(NSNumber(value: Double(value)), requireIntegerPart : requireIntegerPart)
}
func stringFromNumber(_ value : Double, requireIntegerPart : Bool = false) -> String {
return stringFromNumber(NSNumber(value: value as Double), requireIntegerPart : requireIntegerPart)
}
func stringFromNumber(_ value : NSNumber, requireIntegerPart : Bool = false) -> String {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.alwaysShowsDecimalSeparator = false
formatter.minimumIntegerDigits = requireIntegerPart ? 1 : 0
return formatter.string(from: value)!
}
extension String {
func formatWithParameters(_ parameters : [String:Any]) -> String {
let result = self.mutableCopy() as! NSMutableString
for (key, value) in parameters {
let range = NSMakeRange(0, result.length)
let token = "{\(key)}"
result.replaceOccurrences(of: token, with: "\(value)", options: NSString.CompareOptions(), range: range)
}
return result as String
}
}
| mit | 44a8ba4e273f1b5b5cee40558ae2526c | 34.853659 | 116 | 0.704082 | 4.883721 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/Controllers/DisappearingNavBarViewController.swift | 1 | 10020 | // Copyright (c) 2018 Token Browser, Inc
//
// 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 TinyConstraints
import SweetUIKit
import UIKit
/// A base view controller which has a scroll view and a navigation bar whose contents disappear
/// when the bar is scrolled. Handles setup of the scroll view and disappearing navigation bar.
///
/// Subclasses are required to override:
/// - backgroundTriggerView
/// - titleTriggerView
/// - addScrollableContent(to:)
///
/// Note that all conformances are on the main class since methods in extensions cannot be overridden.
class DisappearingNavBarViewController: UIViewController, DisappearingBackgroundNavBarDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate {
/// If disappearing is enabled at present.
var disappearingEnabled: Bool {
return true
}
/// The current height of the disappearing nav bar.
var navBarHeight: CGFloat = DisappearingBackgroundNavBar.defaultHeight
/// The height of the top spacer which can be scrolled under the nav bar. Defaults to the nav bar height.
var topSpacerHeight: CGFloat {
return navBarHeight
}
/// The view to use as the trigger to show or hide the background.
var backgroundTriggerView: UIView {
fatalError("Must be overridden by subclass")
}
/// The view to use as the trigger to show or hide the title.
var titleTriggerView: UIView {
fatalError("Must be overridden by subclass")
}
/// True if the left button of the nav bar should be set up as a back button, false if not.
var leftAsBackButton: Bool {
return true
}
/// The nav bar to adjust
lazy var navBar: DisappearingBackgroundNavBar = {
let navBar = DisappearingBackgroundNavBar(delegate: self)
if leftAsBackButton {
navBar.setupLeftAsBackButton()
}
return navBar
}()
private lazy var defaultScrollView = UIScrollView()
/// Note that by default, this is a vanilla UIScrollView. If this is overridden
/// with a UITableView or UICollectionView in a subclass, the methods to set up
/// a content view and content within that view will not be called.
var scrollingView: UIScrollView {
return defaultScrollView
}
private var navBarTargetHeight: CGFloat {
if #available(iOS 11, *) {
return view.safeAreaInsets.top + DisappearingBackgroundNavBar.defaultHeight
} else {
return DisappearingBackgroundNavBar.defaultHeight
}
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupNavBarAndScrollingContent()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
// Keep the pop gesture recognizer working
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
}
@available(iOS 11.0, *)
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
updateNavBarHeightIfNeeded()
}
override func viewWillDisappear(_ animated: Bool) {
if self.presentedViewController == nil {
navigationController?.setNavigationBarHidden(false, animated: animated)
}
super.viewWillDisappear(animated)
}
// MARK: - View Setup
/// Sets up the navigation bar and all scrolling content.
/// NOTE: Should be set up before any other views are added to the Nav + Scroll parent or there's some weirdness with the scroll view offset.
func setupNavBarAndScrollingContent() {
view.addSubview(scrollingView)
scrollingView.delegate = self
scrollingView.edgesToSuperview()
view.addSubview(navBar)
navBar.edgesToSuperview(excluding: .bottom)
updateNavBarHeightIfNeeded()
navBar.heightConstraint = navBar.height(navBarHeight)
if !(scrollingView is UITableView) && !(scrollingView is UICollectionView) {
setupContentView(in: scrollingView)
} // else, it's something else that we don't want a content view in
}
private func setupContentView(in scrollView: UIScrollView) {
let contentView = UIView(withAutoLayout: false)
scrollView.addSubview(contentView)
contentView.edgesToSuperview()
contentView.width(to: scrollView)
addScrollableContent(to: contentView)
}
/// Called when scrollable content should be programmatically added to the given container view, which
/// has already been added to the scrollView.
///
/// Use autolayout to add views to the container, making sure to pin the bottom of the bottom view to the bottom
/// of the container. Autolayout will then automatically figure out the height of the container, and then use
/// the container's size as the scrollable content size.
///
/// - Parameter contentView: The content view to add scrollable content to.
func addScrollableContent(to contentView: UIView) {
fatalError("Subclasses using the content view must override and not call super")
}
/// Adds and returns a spacer view to the top of the scroll view's content view the same height as the nav bar (so content can scroll under it)
///
/// - Parameter contentView: The content view to add the spacer to
/// - Returns: The spacer view so other views can be constrained to it.
func addTopSpacer(to contentView: UIView) -> UIView {
let spacer = UIView(withAutoLayout: false)
spacer.backgroundColor = Theme.viewBackgroundColor
contentView.addSubview(spacer)
spacer.edgesToSuperview(excluding: .bottom)
spacer.height(topSpacerHeight)
return spacer
}
// MARK: - Nav Bar Updating
/// Updates the height of the nav bar to account for changes to the Safe Area insets.
func updateNavBarHeightIfNeeded() {
guard navBarHeight != navBarTargetHeight else { /* we're good */ return }
guard
let heightConstraint = navBar.heightConstraint,
heightConstraint.constant != navBarTargetHeight
else { return }
navBarHeight = navBarTargetHeight
heightConstraint.constant = navBarHeight
}
/// Updates the state of the nav bar based on where the target views are in relation to the bottom of the nav bar.
/// NOTE: This should generally be called from `scrollViewDidScroll`.
func updateNavBarAppearance() {
guard disappearingEnabled else { return }
guard !scrollingView.frame.equalTo(.zero) else { /* View hasn't been set up yet. */ return }
updateBackgroundAlpha()
updateTitleAlpha()
}
private func updateBackgroundAlpha() {
let targetInParentBounds = backgroundTriggerView.convert(backgroundTriggerView.bounds, to: view)
let topOfTarget = targetInParentBounds.midY
let centerOfTarget = targetInParentBounds.maxY
let differenceFromTop = navBarHeight - topOfTarget
let differenceFromCenter = navBarHeight - centerOfTarget
if differenceFromCenter > 0 {
navBar.setBackgroundAlpha(1)
} else if differenceFromTop < 0 {
navBar.setBackgroundAlpha(0)
} else {
let betweenTopAndCenter = centerOfTarget - topOfTarget
let percentage = differenceFromTop / betweenTopAndCenter
navBar.setBackgroundAlpha(percentage)
}
}
private func updateTitleAlpha() {
let targetInParentBounds = titleTriggerView.convert(titleTriggerView.bounds, to: view)
let centerOfTarget = targetInParentBounds.midY
let bottomOfTarget = targetInParentBounds.maxY
let threeQuartersOfTarget = (centerOfTarget + bottomOfTarget) / 2
let differenceFromThreeQuarters = navBarHeight - threeQuartersOfTarget
let differenceFromBottom = navBarHeight - bottomOfTarget
if differenceFromBottom > 0 {
navBar.setTitleAlpha(1)
navBar.setTitleOffsetPercentage(from: 1)
} else if differenceFromThreeQuarters < 0 {
navBar.setTitleAlpha(0)
navBar.setTitleOffsetPercentage(from: 0)
} else {
let betweenThreeQuartersAndBottom = bottomOfTarget - threeQuartersOfTarget
let percentageComplete = differenceFromThreeQuarters / betweenThreeQuartersAndBottom
navBar.setTitleAlpha(percentageComplete)
navBar.setTitleOffsetPercentage(from: percentageComplete)
}
}
// MARK: - Disappearing Background Nav Bar Delegate
func didTapRightButton(in navBar: DisappearingBackgroundNavBar) {
assertionFailure("If you want this to do something, override it in the subclass")
}
func didTapLeftButton(in navBar: DisappearingBackgroundNavBar) {
self.navigationController?.popViewController(animated: true)
}
// MARK: - Scroll View Delegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
updateNavBarAppearance()
}
// MARK: - Gesture Recognizer Delegate
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// Allow the pop gesture to be recognized
return true
}
}
| gpl-3.0 | fbc1c3b8243d1086bb626c4263194393 | 36.669173 | 157 | 0.697305 | 5.407447 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.