hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
2216f4163073c2fbacf32ca3c34eebefab924252 | 2,538 | //
// ViewController.swift
// ImageCaptureSession
//
// Created by Gustavo Barcena on 5/27/15.
// Copyright (c) 2015 Gustavo Barcena. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var previewView : PreviewView!
var captureSession : ImageCaptureSession?
override func viewDidLoad() {
super.viewDidLoad()
setupCameraView()
}
deinit {
captureSession?.stop()
}
func setupCameraView() {
let cameraPosition : AVCaptureDevicePosition
if (ImageCaptureSession.hasFrontCamera()) {
cameraPosition = .front
}
else if (ImageCaptureSession.hasBackCamera()) {
cameraPosition = .back
}
else {
cameraPosition = .unspecified
assertionFailure("Device needs to have a camera for this demo")
}
captureSession = ImageCaptureSession(position: cameraPosition, previewView: previewView)
captureSession?.start()
}
@IBAction func takePhotoPressed(_ sender:AnyObject) {
captureSession?.captureImage({ (image, error) -> Void in
if (error == nil) {
if let imageVC = self.storyboard?.instantiateViewController(withIdentifier: "ImageViewController") as? ImageViewController {
imageVC.image = image
self.present(imageVC, animated: true, completion: nil)
}
return
}
let alertController = UIAlertController(title: "Oh no!", message: "Failed to take a photo.", preferredStyle: .alert)
self.present(alertController, animated: true, completion: nil)
})
}
@IBAction func switchCamerasPressed(_ sender:AnyObject) {
let stillFrame = previewView.snapshotView(afterScreenUpdates: false)
stillFrame?.frame = previewView.frame
view.insertSubview(stillFrame!, aboveSubview: previewView)
UIView.animate(withDuration: 0.05,
animations: {
self.captureSession?.previewLayer.opacity = 0
}, completion: { (finished) in
self.captureSession?.switchCameras()
UIView.animate(withDuration: 0.05,
animations: {
self.captureSession?.previewLayer.opacity = 1
}, completion: { (finished) in
stillFrame?.removeFromSuperview()
})
})
}
}
| 33.84 | 140 | 0.598503 |
d79b8a068028549a16541ee3266c775716b64597 | 5,573 | //
// ContentView.swift
// Spandex
//
// Created by Tristan Warner-Smith on 15/03/2021.
//
import Combine
import SwiftUI
struct ContentView<LoaderProvider>: View where LoaderProvider: ImageLoaderProviding {
let imageLoaderProvider: LoaderProvider
@EnvironmentObject var search: SearchViewModel
@EnvironmentObject var favourites: FavouriteStore
@State var selectedCharacter: CharacterState?
@State var showDetails: Bool = false
var body: some View {
ZStack {
Color(.systemBackground).ignoresSafeArea()
VStack {
header
SearchBar(search: search, placeholder: "Find a character by name or details")
.padding([.top, .horizontal])
GroupingListView().padding(.vertical, 8)
if search.matchingCharacters.isEmpty {
EmptyCharacterListView(searchTerm: search.searchTerm)
Spacer()
} else {
CharacterListView(
characters: search.matchingCharacters,
imageLoaderProvider: imageLoaderProvider,
select: { character in
withAnimation {
selectedCharacter = character
}
}
)
.padding(.horizontal, 16)
}
}
.transition(.slide)
}
.sheet(isPresented: $showDetails) {
detailsOverlay
.ignoresSafeArea(.container, edges: .bottom)
}
.onChange(of: selectedCharacter) { character in
withAnimation {
showDetails = character != nil
}
}
.onChange(of: showDetails) { show in
if !show && selectedCharacter != nil {
selectedCharacter = nil
}
}
}
@ViewBuilder var detailsOverlay: some View {
if let selected = selectedCharacter {
CharacterDetailView(character: selected, imageLoader: imageLoaderProvider.provide(url: selected.imageURL))
.padding([.bottom])
Spacer()
}
}
var dragHandle: some View {
HStack {
Spacer()
RoundedRectangle(cornerRadius: 25.0)
.fill(Color(.gray))
.frame(width: 35, height: 6)
.padding(.top, 8)
Spacer()
}
}
var header: some View {
HStack(alignment: .top) {
Text("Explore the world of ") + Text("Spandex").bold()
Spacer()
favouriteIndicator
}
.padding(.horizontal)
.font(.system(.largeTitle, design: .rounded))
}
@ViewBuilder var favouriteIndicator: some View {
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(Color(.systemBackground))
.aspectRatio(contentMode: .fit)
.frame(width: 44)
.overlay(
Image(systemName: "bookmark.fill")
.foregroundColor(Color(.systemGray4))
.shadow(color: Color.black.opacity(0.2), radius: 0, x: 2, y: 1)
)
.overlay(
Group {
if favourites.favourites.isEmpty {
EmptyView()
} else {
Text("\(favourites.favourites.count)")
.foregroundColor(.white)
.font(Font.body.monospacedDigit())
.padding(6)
.background(Circle().fill(Color.red))
.offset(x: 9, y: -13)
}
}
)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let characters = PreviewCharacterStateProvider().provide()
let imageLoaderProvider = PreviewImageLoaderProvider<PreviewImageLoader>()
let search = SearchViewModel(characters: characters)
let emptySearch = SearchViewModel(characters: [])
let favourites = FavouriteStore()
favourites.toggle(id: characters.first!.id)
return Group {
ContentView(imageLoaderProvider: imageLoaderProvider)
.environmentObject(search)
.previewDisplayName("Populated")
ContentView(imageLoaderProvider: imageLoaderProvider)
.environmentObject(search)
.colorScheme(.dark)
.previewDisplayName("Populated - Dark")
ContentView(imageLoaderProvider: imageLoaderProvider)
.environmentObject(emptySearch)
.previewDisplayName("Empty")
ContentView(imageLoaderProvider: imageLoaderProvider)
.environmentObject(emptySearch)
.colorScheme(.dark)
.previewDisplayName("Empty - Dark")
ContentView(imageLoaderProvider: imageLoaderProvider)
.environmentObject(search)
.environmentObject(FavouriteStore())
.previewDisplayName("No favourites")
ContentView(imageLoaderProvider: imageLoaderProvider)
.environmentObject(search)
.environmentObject(FavouriteStore())
.colorScheme(.dark)
.previewDisplayName("No favourites - Dark")
}
.environmentObject(favourites)
}
}
| 32.028736 | 118 | 0.533465 |
48582c05c7b837a5aef54c3b61000814341f7b9e | 825 | //
// TopBarView.swift
// FundTransferApp
//
// Created by Luan Nguyen on 24/12/2020.
//
import SwiftUI
struct TopBarView: View {
// MARK: - BODY
var body: some View {
HStack(spacing: 20) {
Circle()
.frame(width: 50, height: 50)
Spacer()
ZStack {
Circle()
.fill(Color.white)
.frame(width: 50, height: 50)
Image(systemName: "bell")
} //: ZSTACK
ZStack {
Circle()
.fill(Color.white)
.frame(width: 50, height: 50)
Image(systemName: "ellipsis")
.rotationEffect(.degrees(90))
} //: ZSTACK
} //: HSTACK
}
}
| 22.916667 | 49 | 0.408485 |
c1e1b8d536c8afbb97915fe03344645792c4df3d | 1,585 | //
// TFImageView.swift
// TFImageView
//
// Created by Toseef Khilji on 31/01/19.
// Copyright © 2019 AS Apps. All rights reserved.
//
import UIKit
@IBDesignable
open class TFImageView: UIImageView {
@IBInspectable var X_Image:UIImage? {
didSet {
if let img = X_Image {
updateConstant(size: .iPhoneXs, image: img)
}
}
}
@IBInspectable var XR_Image:UIImage? {
didSet {
if let img = XR_Image {
updateConstant(size: .iPhoneXr, image: img)
}
}
}
@IBInspectable var XSMax_Image:UIImage? {
didSet {
if let img = XSMax_Image {
updateConstant(size: .iPhoneXsMax, image: img)
}
}
}
var tempConst: CGFloat = 0
fileprivate func updateConstant(size: Device, image: UIImage) {
print("updateConstant:\(size), self:\(Device())")
print("realdevice:\(Device.realDevice(from: Device()))")
let realDevice = Device.realDevice(from: Device())
if size == realDevice {
self.image = image
}
}
override open func layoutSubviews() {
super.layoutSubviews()
print("layoutSubviews")
}
override open func awakeFromNib() {
super.awakeFromNib()
print("awakeFromNib")
}
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
super.layoutSubviews()
}
}
//fileprivate extension Device {
// static let deviceSize = Device.size()
//}
| 23.308824 | 67 | 0.570978 |
71116efc516812c2bac927d126086d89ad246b69 | 3,626 | /*:
[Previous Challenge](@previous)
## 3. Minimum Recharge Stops
Swift-la is a new electric car company that is looking to add a new feature into their vehicles. They want to add the ability for their customers to check if the car can reach a given destination. Since the journey to the destination may be far, there are charging stations that the car can recharge at. The company wants to find the **minimum number of charging stops** needed for the vehicle to reach its destination.
You're given the following information:
- The `target` distance the vehicle needs to travel.
- The `startCharge`, how much charge the car has to begin the journey.
- An ordered list of `stations` that the car can potentially stop at to charge along the way.
Each `ChargingStation` has a `distance` from the start location and a `chargeCapacity`. This is the amount of charge a station can add to the car.
You may assume the following:
1. An electric car has an **infinite** charge capacity.
2. One charge capacity is equivalent to one mile.
3. The list of `stations` is sorted by distance from the start location:
```swift
stations[0].distance < stations[1].distance < stations[k].distance
```
*/
struct ChargingStation {
/// Distance from start location.
let distance: Int
/// The amount of electricity the station has to charge a car.
/// 1 capacity = 1 mile
let chargeCapacity: Int
}
enum DestinationResult {
/// Able to reach your destination with the minimum number of stops.
case reachable(rechargeStops: Int)
/// Unable to reach your destination.
case unreachable
}
/// Returns the minimum number of charging stations an electric vehicle needs to reach it's destination.
/// - Parameter target: the distance in miles the vehicle needs to travel.
/// - Parameter startCharge: the starting charge you have to start the journey.
/// - Parameter stations: the charging stations along the way.
func minRechargeStops(target: Int, startCharge: Int, stations: [ChargingStation]) -> DestinationResult {
guard startCharge <= target else { return .reachable(rechargeStops: 0) }
// Keeps track of the minimum number of stops needed to reach destination
var minStops = -1
// Keeps track of the vehicle's current charge on the journey.
var currentCharge = 0
// Tracks the number of stations passed.
var currentStation = 0
// Keeps track of all the station's charge capacity.
// Responsibility for provide us the station with the highest charging capacity.
// Initialize the priority queue with the vehicle's starting charge capacity.
// The priority queue represents all the charging stations that is reachable.
var chargePriority = PriorityQueue(sort: >, elements: [startCharge])
while !chargePriority.isEmpty {
guard let charge = chargePriority.dequeue() else {
return .unreachable
}
currentCharge += charge
minStops += 1
if currentCharge >= target {
return .reachable(rechargeStops: minStops)
}
while currentStation < stations.count &&
currentCharge >= stations[currentStation].distance {
let distance = stations[currentStation].chargeCapacity
_ = chargePriority.enqueue(distance)
currentStation += 1
}
}
return .unreachable
}
// Sample Tests
let stations = [ChargingStation(distance: 10, chargeCapacity: 60),
ChargingStation(distance: 20, chargeCapacity: 30),
ChargingStation(distance: 30, chargeCapacity: 30),
ChargingStation(distance: 60, chargeCapacity: 40)]
minRechargeStops(target: 100, startCharge: 10, stations: stations)
| 40.741573 | 421 | 0.728902 |
d7c87cfd44e18a3e772e1a22fc6eea0307d6b659 | 1,372 | // RUN: %target-swift-frontend -O -primary-file %s -emit-sil -enable-experimental-distributed | %FileCheck %s --dump-input=fail
// REQUIRES: concurrency
import _Distributed
class SomeClass {}
@available(SwiftStdlib 5.5, *)
actor SimpleActor {
let someFieldInLocalActor: SomeClass
init(field: SomeClass) {
self.someFieldInLocalActor = field
}
}
// ==== ------------------------------------------------------------------------
// ==== Check that a normal local only actor is left unchanged
// CHECK: // SimpleActor.deinit
// CHECK: sil hidden{{.*}} @$s42distributed_actor_remote_deinit_sil_normal11SimpleActorCfd : $@convention(method) (@guaranteed SimpleActor) -> @owned Builtin.NativeObject {
// CHECK: // %0 "self" // users: %6, %5, %2, %1
// CHECK: bb0(%0 : $SimpleActor):
// CHECK: debug_value %0 : $SimpleActor, let, name "self", argno 1, implicit
// CHECK: %2 = ref_element_addr %0 : $SimpleActor, #SimpleActor.someFieldInLocalActor
// CHECK: %3 = load %2 : $*SomeClass // user: %4
// CHECK: strong_release %3 : $SomeClass // id: %4
// CHECK: %5 = builtin "destroyDefaultActor"(%0 : $SimpleActor) : $()
// CHECK: %6 = unchecked_ref_cast %0 : $SimpleActor to $Builtin.NativeObject // user: %7
// CHECK: return %6 : $Builtin.NativeObject // id: %7
// CHECK: } // end sil function '$s42distributed_actor_remote_deinit_sil_normal11SimpleActorCfd'
| 41.575758 | 172 | 0.657434 |
0a79278368084121f141859538a62777ef9240ba | 246 | //
// CompanyLogoImageLoader.swift
// iosJobFinder
//
// Created by Hardik Trivedi on 23/11/2020.
// Copyright © 2020 orgName. All rights reserved.
//
import Foundation
struct CompanyLogoImageLoader {
func loadImage(){
}
}
| 15.375 | 50 | 0.670732 |
8a5f1b1986125902096ecf615dc7abb0ad411db4 | 1,271 | //
// JSONEncoder+Additions
// Copyright © 2020 Observant. All rights reserved.
//
import Foundation
public extension JSONEncoder {
static func ft_safeEncoder() -> JSONEncoder {
let encoder = JSONEncoder()
encoder.nonConformingFloatEncodingStrategy = .ft_convertToString
return encoder
}
/// by default, rails apps use IOS 8601 for date encoding,
/// and snake_case JSON keys
static func ft_safeRailsEncoder() -> JSONEncoder {
let encoder = ft_safeEncoder()
encoder.dateEncodingStrategy = .ft_iso8601Full
encoder.keyEncodingStrategy = .convertToSnakeCase
return encoder
}
func ft_encode<T: Encodable>(_ value: T) -> Result<Data, JSONError> {
do {
let result = try encode(value)
return .success(result)
} catch {
if let encodingError = error as? EncodingError {
return .failure(.encodingError(encodingError))
} else {
return .failure(.miscellaneous(error))
}
}
}
}
public extension Data {
func ft_decodedJSON<T: Decodable>() -> Result<T, JSONError> {
let decoder = JSONDecoder.ft_safeDecoder()
return decoder.ft_decode(self)
}
}
| 28.886364 | 73 | 0.620771 |
56468c049bdfe7ef636c31af07dbd1800714e96a | 1,638 | import RIBs
// MARK: - RegisterDependency
protocol RegisterDependency: Dependency {
}
// MARK: - RegisterComponent
final class RegisterComponent: Component<RegisterDependency> {
fileprivate var mediaPickerUseCase: MediaPickerUseCase {
UIMediaPickerPlatformUseCase()
}
fileprivate var authenticationUseCase: AuthenticationUseCase {
FirebaseAuthenticationUseCase(
authenticating: FirebaseAuthentication(),
mediaUploading: FirebaseMediaUploader(),
apiNetworking: FirebaseAPINetwork())
}
fileprivate var initialState: RegisterDisplayModel.State {
RegisterDisplayModel.State.initialState()
}
}
// MARK: - RegisterBuildable
protocol RegisterBuildable: Buildable {
func build(withListener listener: RegisterListener) -> RegisterRouting
}
// MARK: - RegisterBuilder
final class RegisterBuilder: Builder<RegisterDependency> {
override init(dependency: RegisterDependency) {
super.init(dependency: dependency)
}
deinit {
print("RegisterBuilder deinit...")
}
}
// MARK: RegisterBuildable
extension RegisterBuilder: RegisterBuildable {
func build(withListener listener: RegisterListener) -> RegisterRouting {
let component = RegisterComponent(dependency: dependency)
let viewController = RegisterViewController(mediaPickerUseCase: component.mediaPickerUseCase)
let interactor = RegisterInteractor(
presenter: viewController,
initialState: component.initialState,
authenticationUseCase: component.authenticationUseCase)
interactor.listener = listener
return RegisterRouter(interactor: interactor, viewController: viewController)
}
}
| 26.419355 | 97 | 0.774115 |
d716fb7ee9db023948a5bb2dbbbd39bc2a93e6a8 | 1,784 | //
// CountryListView.swift
// watch Extension
//
// Created by kf on 7/12/19.
// Copyright © 2019 kf. All rights reserved.
//
import SwiftUI
struct CountryListView: View {
let defaults = UserDefaults.standard
let countries: Countries = [
Country(
id: 0,
code: "twn",
lat: 0,
lon: 0,
zoom: 0,
name: "Taiwan",
nameLocal: "台灣"
),
Country(
id: 1,
code: "hkg",
lat: 0,
lon: 0,
zoom: 0,
name: "Hong Kong",
nameLocal: "香港"
),
Country(
id: 2,
code: "tha",
lat: 0,
lon: 0,
zoom: 0,
name: "Thailand",
nameLocal: "泰國"
),
Country(
id: 3,
code: "ind",
lat: 0,
lon: 0,
zoom: 0,
name: "India",
nameLocal: "印度"
),
]
var body: some View {
List {
ForEach(countries, id: \.self) {country in
NavigationLink(
destination: StationListView(country: country)) {
Button(action: {
print(country.nameLocal)
ComplicationManager.reloadComplications()
self.defaults.setStruct(country, forKey: "closestCountry")
}) {
Text(Locale.isChinese ? country.nameLocal : country.name)
}
}
}
}
}
}
struct CountryListView_Previews: PreviewProvider {
static var previews: some View {
CountryListView()
}
}
| 23.473684 | 86 | 0.411996 |
5056ce9dfa58adc859102b96aa575662e40481bf | 23,761 | import Foundation
extension HTTPHeaders {
/// Add a header name/value pair to the block.
///
/// This method is strictly additive: if there are other values for the given header name
/// already in the block, this will add a new entry. `add` performs case-insensitive
/// comparisons on the header field name.
///
/// - Parameter name: The header field name. For maximum compatibility this should be an
/// ASCII string. For future-proofing with HTTP/2 lowercase header names are strongly
// recommended.
/// - Parameter value: The header field value to add for the given name.
public mutating func add(name: HTTPHeaderName, value: String) {
add(name: name.lowercased, value: value)
}
/// Add a header name/value pair to the block, replacing any previous values for the
/// same header name that are already in the block.
///
/// This is a supplemental method to `add` that essentially combines `remove` and `add`
/// in a single function. It can be used to ensure that a header block is in a
/// well-defined form without having to check whether the value was previously there.
/// Like `add`, this method performs case-insensitive comparisons of the header field
/// names.
///
/// - Parameter name: The header field name. For maximum compatibility this should be an
/// ASCII string. For future-proofing with HTTP/2 lowercase header names are strongly
// recommended.
/// - Parameter value: The header field value to add for the given name.
public mutating func replaceOrAdd(name: HTTPHeaderName, value: String) {
replaceOrAdd(name: name.lowercased, value: value)
}
/// Remove all values for a given header name from the block.
///
/// This method uses case-insensitive comparisons for the header field name.
///
/// - Parameter name: The name of the header field to remove from the block.
public mutating func remove(name: HTTPHeaderName) {
remove(name: name.lowercased)
}
/// Retrieve all of the values for a given header field name from the block.
///
/// This method uses case-insensitive comparisons for the header field name. It
/// does not return a maximally-decomposed list of the header fields, but instead
/// returns them in their original representation: that means that a comma-separated
/// header field list may contain more than one entry, some of which contain commas
/// and some do not. If you want a representation of the header fields suitable for
/// performing computation on, consider `getCanonicalForm`.
///
/// - Parameter name: The header field name whose values are to be retrieved.
/// - Returns: A list of the values for that header field name.
public subscript(name: HTTPHeaderName) -> [String] {
return self[name.lowercased]
}
/// https://tools.ietf.org/html/rfc2616#section-3.6
///
/// "Parameters are in the form of attribute/value pairs."
///
/// From a header + attribute, this subscript will fetch a value
public subscript(name: HTTPHeaderName, attribute: String) -> String? {
get {
guard let header = self[name].first else { return nil }
guard let range = header.range(of: "\(attribute)=") else { return nil }
let remainder = header[range.upperBound...]
var string: String
if let end = remainder.index(of: ";") {
string = String(remainder[remainder.startIndex..<end])
} else {
string = String(remainder[remainder.startIndex...])
}
if string.first == "\"", string.last == "\"", string.count > 1 {
string.removeFirst()
string.removeLast()
}
return string
}
}
}
extension HTTPHeaders: ExpressibleByDictionaryLiteral {
/// See `ExpressibleByDictionaryLiteral.init`
public init(dictionaryLiteral elements: (String, String)...) {
var headers = HTTPHeaders()
for (key, val) in elements {
headers.add(name: key, value: val)
}
self = headers
}
}
/// Type used for the name of a HTTP header in the `HTTPHeaders` storage.
public struct HTTPHeaderName: Codable, Hashable, CustomStringConvertible {
/// See `Hashable.hashValue`
public var hashValue: Int {
return lowercased.hashValue
}
/// Lowercased-ASCII version of the header.
internal let lowercased: String
/// Create a HTTP header name with the provided String.
public init(_ name: String) {
lowercased = name.lowercased()
}
/// See `ExpressibleByStringLiteral.init(stringLiteral:)`
public init(stringLiteral: String) {
self.init(stringLiteral)
}
/// See `ExpressibleByStringLiteral.init(unicodeScalarLiteral:)`
public init(unicodeScalarLiteral: String) {
self.init(unicodeScalarLiteral)
}
/// See `ExpressibleByStringLiteral.init(extendedGraphemeClusterLiteral:)`
public init(extendedGraphemeClusterLiteral: String) {
self.init(extendedGraphemeClusterLiteral)
}
/// See `CustomStringConvertible.description`
public var description: String {
return lowercased
}
/// See `Equatable.==`
public static func ==(lhs: HTTPHeaderName, rhs: HTTPHeaderName) -> Bool {
return lhs.lowercased == rhs.lowercased
}
// https://www.iana.org/assignments/message-headers/message-headers.xhtml
// Permanent Message Header Field Names
/// A-IM header.
public static let aIM = HTTPHeaderName("A-IM")
/// Accept header.
public static let accept = HTTPHeaderName("Accept")
/// Accept-Additions header.
public static let acceptAdditions = HTTPHeaderName("Accept-Additions")
/// Accept-Charset header.
public static let acceptCharset = HTTPHeaderName("Accept-Charset")
/// Accept-Datetime header.
public static let acceptDatetime = HTTPHeaderName("Accept-Datetime")
/// Accept-Encoding header.
public static let acceptEncoding = HTTPHeaderName("Accept-Encoding")
/// Accept-Features header.
public static let acceptFeatures = HTTPHeaderName("Accept-Features")
/// Accept-Language header.
public static let acceptLanguage = HTTPHeaderName("Accept-Language")
/// Accept-Patch header.
public static let acceptPatch = HTTPHeaderName("Accept-Patch")
/// Accept-Post header.
public static let acceptPost = HTTPHeaderName("Accept-Post")
/// Accept-Ranges header.
public static let acceptRanges = HTTPHeaderName("Accept-Ranges")
/// Accept-Age header.
public static let age = HTTPHeaderName("Age")
/// Accept-Allow header.
public static let allow = HTTPHeaderName("Allow")
/// ALPN header.
public static let alpn = HTTPHeaderName("ALPN")
/// Alt-Svc header.
public static let altSvc = HTTPHeaderName("Alt-Svc")
/// Alt-Used header.
public static let altUsed = HTTPHeaderName("Alt-Used")
/// Alternates header.
public static let alternates = HTTPHeaderName("Alternates")
/// Apply-To-Redirect-Ref header.
public static let applyToRedirectRef = HTTPHeaderName("Apply-To-Redirect-Ref")
/// Authentication-Control header.
public static let authenticationControl = HTTPHeaderName("Authentication-Control")
/// Authentication-Info header.
public static let authenticationInfo = HTTPHeaderName("Authentication-Info")
/// Authorization header.
public static let authorization = HTTPHeaderName("Authorization")
/// C-Ext header.
public static let cExt = HTTPHeaderName("C-Ext")
/// C-Man header.
public static let cMan = HTTPHeaderName("C-Man")
/// C-Opt header.
public static let cOpt = HTTPHeaderName("C-Opt")
/// C-PEP header.
public static let cPEP = HTTPHeaderName("C-PEP")
/// C-PEP-Info header.
public static let cPEPInfo = HTTPHeaderName("C-PEP-Info")
/// Cache-Control header.
public static let cacheControl = HTTPHeaderName("Cache-Control")
/// CalDav-Timezones header.
public static let calDAVTimezones = HTTPHeaderName("CalDAV-Timezones")
/// Close header.
public static let close = HTTPHeaderName("Close")
/// Connection header.
public static let connection = HTTPHeaderName("Connection")
/// Content-Base header.
public static let contentBase = HTTPHeaderName("Content-Base")
/// Content-Disposition header.
public static let contentDisposition = HTTPHeaderName("Content-Disposition")
/// Content-Encoding header.
public static let contentEncoding = HTTPHeaderName("Content-Encoding")
/// Content-ID header.
public static let contentID = HTTPHeaderName("Content-ID")
/// Content-Language header.
public static let contentLanguage = HTTPHeaderName("Content-Language")
/// Content-Length header.
public static let contentLength = HTTPHeaderName("Content-Length")
/// Content-Location header.
public static let contentLocation = HTTPHeaderName("Content-Location")
/// Content-MD5 header.
public static let contentMD5 = HTTPHeaderName("Content-MD5")
/// Content-Range header.
public static let contentRange = HTTPHeaderName("Content-Range")
/// Content-Script-Type header.
public static let contentScriptType = HTTPHeaderName("Content-Script-Type")
/// Content-Style-Type header.
public static let contentStyleType = HTTPHeaderName("Content-Style-Type")
/// Content-Type header.
public static let contentType = HTTPHeaderName("Content-Type")
/// Content-Version header.
public static let contentVersion = HTTPHeaderName("Content-Version")
/// Cookie header.
public static let cookie = HTTPHeaderName("Cookie")
/// Cookie2 header.
public static let cookie2 = HTTPHeaderName("Cookie2")
/// DASL header.
public static let dasl = HTTPHeaderName("DASL")
/// DASV header.
public static let dav = HTTPHeaderName("DAV")
/// Date header.
public static let date = HTTPHeaderName("Date")
/// Default-Style header.
public static let defaultStyle = HTTPHeaderName("Default-Style")
/// Delta-Base header.
public static let deltaBase = HTTPHeaderName("Delta-Base")
/// Depth header.
public static let depth = HTTPHeaderName("Depth")
/// Derived-From header.
public static let derivedFrom = HTTPHeaderName("Derived-From")
/// Destination header.
public static let destination = HTTPHeaderName("Destination")
/// Differential-ID header.
public static let differentialID = HTTPHeaderName("Differential-ID")
/// Digest header.
public static let digest = HTTPHeaderName("Digest")
/// ETag header.
public static let eTag = HTTPHeaderName("ETag")
/// Expect header.
public static let expect = HTTPHeaderName("Expect")
/// Expires header.
public static let expires = HTTPHeaderName("Expires")
/// Ext header.
public static let ext = HTTPHeaderName("Ext")
/// Forwarded header.
public static let forwarded = HTTPHeaderName("Forwarded")
/// From header.
public static let from = HTTPHeaderName("From")
/// GetProfile header.
public static let getProfile = HTTPHeaderName("GetProfile")
/// Hobareg header.
public static let hobareg = HTTPHeaderName("Hobareg")
/// Host header.
public static let host = HTTPHeaderName("Host")
/// HTTP2-Settings header.
public static let http2Settings = HTTPHeaderName("HTTP2-Settings")
/// IM header.
public static let im = HTTPHeaderName("IM")
/// If header.
public static let `if` = HTTPHeaderName("If")
/// If-Match header.
public static let ifMatch = HTTPHeaderName("If-Match")
/// If-Modified-Since header.
public static let ifModifiedSince = HTTPHeaderName("If-Modified-Since")
/// If-None-Match header.
public static let ifNoneMatch = HTTPHeaderName("If-None-Match")
/// If-Range header.
public static let ifRange = HTTPHeaderName("If-Range")
/// If-Schedule-Tag-Match header.
public static let ifScheduleTagMatch = HTTPHeaderName("If-Schedule-Tag-Match")
/// If-Unmodified-Since header.
public static let ifUnmodifiedSince = HTTPHeaderName("If-Unmodified-Since")
/// Keep-Alive header.
public static let keepAlive = HTTPHeaderName("Keep-Alive")
/// Label header.
public static let label = HTTPHeaderName("Label")
/// Last-Modified header.
public static let lastModified = HTTPHeaderName("Last-Modified")
/// Link header.
public static let link = HTTPHeaderName("Link")
/// Location header.
public static let location = HTTPHeaderName("Location")
/// Lock-Token header.
public static let lockToken = HTTPHeaderName("Lock-Token")
/// Man header.
public static let man = HTTPHeaderName("Man")
/// Max-Forwards header.
public static let maxForwards = HTTPHeaderName("Max-Forwards")
/// Memento-Datetime header.
public static let mementoDatetime = HTTPHeaderName("Memento-Datetime")
/// Meter header.
public static let meter = HTTPHeaderName("Meter")
/// MIME-Version header.
public static let mimeVersion = HTTPHeaderName("MIME-Version")
/// Negotiate header.
public static let negotiate = HTTPHeaderName("Negotiate")
/// Opt header.
public static let opt = HTTPHeaderName("Opt")
/// Optional-WWW-Authenticate header.
public static let optionalWWWAuthenticate = HTTPHeaderName("Optional-WWW-Authenticate")
/// Ordering-Type header.
public static let orderingType = HTTPHeaderName("Ordering-Type")
/// Origin header.
public static let origin = HTTPHeaderName("Origin")
/// Overwrite header.
public static let overwrite = HTTPHeaderName("Overwrite")
/// P3P header.
public static let p3p = HTTPHeaderName("P3P")
/// PEP header.
public static let pep = HTTPHeaderName("PEP")
/// PICS-Label header.
public static let picsLabel = HTTPHeaderName("PICS-Label")
/// Pep-Info header.
public static let pepInfo = HTTPHeaderName("Pep-Info")
/// Position header.
public static let position = HTTPHeaderName("Position")
/// Pragma header.
public static let pragma = HTTPHeaderName("Pragma")
/// Prefer header.
public static let prefer = HTTPHeaderName("Prefer")
/// Preference-Applied header.
public static let preferenceApplied = HTTPHeaderName("Preference-Applied")
/// ProfileObject header.
public static let profileObject = HTTPHeaderName("ProfileObject")
/// Protocol header.
public static let `protocol` = HTTPHeaderName("Protocol")
/// Protocol-Info header.
public static let protocolInfo = HTTPHeaderName("Protocol-Info")
/// Protocol-Query header.
public static let protocolQuery = HTTPHeaderName("Protocol-Query")
/// Protocol-Request header.
public static let protocolRequest = HTTPHeaderName("Protocol-Request")
/// Proxy-Authenticate header.
public static let proxyAuthenticate = HTTPHeaderName("Proxy-Authenticate")
/// Proxy-Authentication-Info header.
public static let proxyAuthenticationInfo = HTTPHeaderName("Proxy-Authentication-Info")
/// Proxy-Authorization header.
public static let proxyAuthorization = HTTPHeaderName("Proxy-Authorization")
/// Proxy-Features header.
public static let proxyFeatures = HTTPHeaderName("Proxy-Features")
/// Proxy-Instruction header.
public static let proxyInstruction = HTTPHeaderName("Proxy-Instruction")
/// Public header.
public static let `public` = HTTPHeaderName("Public")
/// Public-Key-Pins header.
public static let publicKeyPins = HTTPHeaderName("Public-Key-Pins")
/// Public-Key-Pins-Report-Only header.
public static let publicKeyPinsReportOnly = HTTPHeaderName("Public-Key-Pins-Report-Only")
/// Range header.
public static let range = HTTPHeaderName("Range")
/// Redirect-Ref header.
public static let redirectRef = HTTPHeaderName("Redirect-Ref")
/// Referer header.
public static let referer = HTTPHeaderName("Referer")
/// Retry-After header.
public static let retryAfter = HTTPHeaderName("Retry-After")
/// Safe header.
public static let safe = HTTPHeaderName("Safe")
/// Schedule-Reply header.
public static let scheduleReply = HTTPHeaderName("Schedule-Reply")
/// Schedule-Tag header.
public static let scheduleTag = HTTPHeaderName("Schedule-Tag")
/// Sec-WebSocket-Accept header.
public static let secWebSocketAccept = HTTPHeaderName("Sec-WebSocket-Accept")
/// Sec-WebSocket-Extensions header.
public static let secWebSocketExtensions = HTTPHeaderName("Sec-WebSocket-Extensions")
/// Sec-WebSocket-Key header.
public static let secWebSocketKey = HTTPHeaderName("Sec-WebSocket-Key")
/// Sec-WebSocket-Protocol header.
public static let secWebSocketProtocol = HTTPHeaderName("Sec-WebSocket-Protocol")
/// Sec-WebSocket-Version header.
public static let secWebSocketVersion = HTTPHeaderName("Sec-WebSocket-Version")
/// Security-Scheme header.
public static let securityScheme = HTTPHeaderName("Security-Scheme")
/// Server header.
public static let server = HTTPHeaderName("Server")
/// Set-Cookie header.
public static let setCookie = HTTPHeaderName("Set-Cookie")
/// Set-Cookie2 header.
public static let setCookie2 = HTTPHeaderName("Set-Cookie2")
/// SetProfile header.
public static let setProfile = HTTPHeaderName("SetProfile")
/// SLUG header.
public static let slug = HTTPHeaderName("SLUG")
/// SoapAction header.
public static let soapAction = HTTPHeaderName("SoapAction")
/// Status-URI header.
public static let statusURI = HTTPHeaderName("Status-URI")
/// Strict-Transport-Security header.
public static let strictTransportSecurity = HTTPHeaderName("Strict-Transport-Security")
/// Surrogate-Capability header.
public static let surrogateCapability = HTTPHeaderName("Surrogate-Capability")
/// Surrogate-Control header.
public static let surrogateControl = HTTPHeaderName("Surrogate-Control")
/// TCN header.
public static let tcn = HTTPHeaderName("TCN")
/// TE header.
public static let te = HTTPHeaderName("TE")
/// Timeout header.
public static let timeout = HTTPHeaderName("Timeout")
/// Topic header.
public static let topic = HTTPHeaderName("Topic")
/// Trailer header.
public static let trailer = HTTPHeaderName("Trailer")
/// Transfer-Encoding header.
public static let transferEncoding = HTTPHeaderName("Transfer-Encoding")
/// TTL header.
public static let ttl = HTTPHeaderName("TTL")
/// Urgency header.
public static let urgency = HTTPHeaderName("Urgency")
/// URI header.
public static let uri = HTTPHeaderName("URI")
/// Upgrade header.
public static let upgrade = HTTPHeaderName("Upgrade")
/// User-Agent header.
public static let userAgent = HTTPHeaderName("User-Agent")
/// Variant-Vary header.
public static let variantVary = HTTPHeaderName("Variant-Vary")
/// Vary header.
public static let vary = HTTPHeaderName("Vary")
/// Via header.
public static let via = HTTPHeaderName("Via")
/// WWW-Authenticate header.
public static let wwwAuthenticate = HTTPHeaderName("WWW-Authenticate")
/// Want-Digest header.
public static let wantDigest = HTTPHeaderName("Want-Digest")
/// Warning header.
public static let warning = HTTPHeaderName("Warning")
/// X-Frame-Options header.
public static let xFrameOptions = HTTPHeaderName("X-Frame-Options")
// https://www.iana.org/assignments/message-headers/message-headers.xhtml
// Provisional Message Header Field Names
/// Access-Control header.
public static let accessControl = HTTPHeaderName("Access-Control")
/// Access-Control-Allow-Credentials header.
public static let accessControlAllowCredentials = HTTPHeaderName("Access-Control-Allow-Credentials")
/// Access-Control-Allow-Headers header.
public static let accessControlAllowHeaders = HTTPHeaderName("Access-Control-Allow-Headers")
/// Access-Control-Allow-Methods header.
public static let accessControlAllowMethods = HTTPHeaderName("Access-Control-Allow-Methods")
/// Access-Control-Allow-Origin header.
public static let accessControlAllowOrigin = HTTPHeaderName("Access-Control-Allow-Origin")
/// Access-Control-Expose-Headers header.
public static let accessControlExpose = HTTPHeaderName("Access-Control-Expose-Headers")
/// Access-Control-Max-Age header.
public static let accessControlMaxAge = HTTPHeaderName("Access-Control-Max-Age")
/// Access-Control-Request-Method header.
public static let accessControlRequestMethod = HTTPHeaderName("Access-Control-Request-Method")
/// Access-Control-Request-Headers header.
public static let accessControlRequestHeaders = HTTPHeaderName("Access-Control-Request-Headers")
/// Compliance header.
public static let compliance = HTTPHeaderName("Compliance")
/// Content-Transfer-Encoding header.
public static let contentTransferEncoding = HTTPHeaderName("Content-Transfer-Encoding")
/// Cost header.
public static let cost = HTTPHeaderName("Cost")
/// EDIINT-Features header.
public static let ediintFeatures = HTTPHeaderName("EDIINT-Features")
/// Message-ID header.
public static let messageID = HTTPHeaderName("Message-ID")
/// Method-Check header.
public static let methodCheck = HTTPHeaderName("Method-Check")
/// Method-Check-Expires header.
public static let methodCheckExpires = HTTPHeaderName("Method-Check-Expires")
/// Non-Compliance header.
public static let nonCompliance = HTTPHeaderName("Non-Compliance")
/// Optional header.
public static let optional = HTTPHeaderName("Optional")
/// Referer-Root header.
public static let refererRoot = HTTPHeaderName("Referer-Root")
/// Resolution-Hint header.
public static let resolutionHint = HTTPHeaderName("Resolution-Hint")
/// Resolver-Location header.
public static let resolverLocation = HTTPHeaderName("Resolver-Location")
/// SubOK header.
public static let subOK = HTTPHeaderName("SubOK")
/// Subst header.
public static let subst = HTTPHeaderName("Subst")
/// Title header.
public static let title = HTTPHeaderName("Title")
/// UA-Color header.
public static let uaColor = HTTPHeaderName("UA-Color")
/// UA-Media header.
public static let uaMedia = HTTPHeaderName("UA-Media")
/// UA-Pixels header.
public static let uaPixels = HTTPHeaderName("UA-Pixels")
/// UA-Resolution header.
public static let uaResolution = HTTPHeaderName("UA-Resolution")
/// UA-Windowpixels header.
public static let uaWindowpixels = HTTPHeaderName("UA-Windowpixels")
/// Version header.
public static let version = HTTPHeaderName("Version")
/// X-Device-Accept header.
public static let xDeviceAccept = HTTPHeaderName("X-Device-Accept")
/// X-Device-Accept-Charset header.
public static let xDeviceAcceptCharset = HTTPHeaderName("X-Device-Accept-Charset")
/// X-Device-Accept-Encoding header.
public static let xDeviceAcceptEncoding = HTTPHeaderName("X-Device-Accept-Encoding")
/// X-Device-Accept-Language header.
public static let xDeviceAcceptLanguage = HTTPHeaderName("X-Device-Accept-Language")
/// X-Device-User-Agent header.
public static let xDeviceUserAgent = HTTPHeaderName("X-Device-User-Agent")
/// X-Requested-With header.
public static let xRequestedWith = HTTPHeaderName("X-Requested-With")
}
| 45.34542 | 104 | 0.697572 |
9b88cf22b6e833266882699dfd021dfa0b54f718 | 339 | //
// ViewController.swift
// testRepoPush
//
// Created by sachin shinde on 02/01/20.
// Copyright © 2020 sachin shinde. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 16.142857 | 58 | 0.666667 |
8f6ee1cdad7e58608d715af34141b739d5b6e65e | 2,626 | import UIKit
import Anchors
import Omnia
// Drag from left to right for now
class ViewController: UIViewController, UICollectionViewDropDelegate, UICollectionViewDragDelegate {
let leftController = CollectionController()
let rightController = CollectionController()
override func viewDidLoad() {
super.viewDidLoad()
[leftController, rightController].forEach {
omnia_add(childController: $0)
$0.collectionView.dragDelegate = self
$0.collectionView.dropDelegate = self
}
leftController.cellColor = UIColor(hex: "#3498db")
rightController.cellColor = UIColor(hex: "#2ecc71")
let centerXGuide = UILayoutGuide()
view.addLayoutGuide(centerXGuide)
activate(
centerXGuide.anchor.centerX,
leftController.view.anchor.top.left.constant(10),
leftController.view.anchor.bottom.constant(-10),
leftController.view.anchor.right.equal.to(centerXGuide.anchor.left).constant(-30),
rightController.view.anchor.top.constant(10),
rightController.view.anchor.right.bottom.constant(-10),
rightController.view.anchor.left.equal.to(centerXGuide.anchor.right).constant(30)
)
leftController.update(items: Array(0..<100).map(String.init))
rightController.update(items: Array(100..<200).map(String.init))
}
// MARK: - UICollectionViewDragDelegate
func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
let controller = leftController
let provider = NSItemProvider(
object: controller.imageForCell(indexPath: indexPath)
)
let dragItem = UIDragItem(itemProvider: provider)
dragItem.localObject = indexPath
return [dragItem]
}
// MARK: - UICollectionViewDropDelegate
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
let destinationIndexPath: IndexPath
if let indexPath = coordinator.destinationIndexPath {
destinationIndexPath = indexPath
} else {
destinationIndexPath = IndexPath(row: 0, section: 0)
}
let controller = rightController
let dragItemIndexPath = coordinator.items.last?.dragItem.localObject as! IndexPath
let draggedItem = leftController.items[dragItemIndexPath.item]
// remove
leftController.items.remove(at: dragItemIndexPath.item)
leftController.collectionView.deleteItems(at: [dragItemIndexPath])
// insert
controller.items.insert(draggedItem, at: destinationIndexPath.item)
controller.collectionView.insertItems(at: [destinationIndexPath])
}
}
| 32.419753 | 142 | 0.746382 |
e0b018d145f4a2dbee69e687ad5e4db8eb31168a | 8,511 | //
// GPLevelMeterView.swift
// GPLevelMeterViewSample
//
// Created by shinichi teshirogi on 2020/10/10.
//
import Foundation
import UIKit
@IBDesignable final class GPLevelMeterView: UIView {
enum Orientation: Int {
case landscape = 0, portrait
}
enum MeterType: Int {
case fill = 0, slice
}
enum ScalePosition: Int {
case none = 0, left, top, right, bottom
}
var orientation: Orientation = .landscape
@IBInspectable var zeroCenter: Bool = false
var meterType: MeterType = .fill
var meterColor: [UIColor] = [.red, .red, .red,
.yellow, .yellow, .yellow, .yellow,
.green, .green, .green]
var meterResolution: CGFloat {
return CGFloat(meterColor.count)
}
var scalePosition: ScalePosition = .none
@IBInspectable var scaleResolution: CGFloat = 10
@IBInspectable var scaleHeight: CGFloat = 8
var barHeight: CGFloat {
return (isLandscape ? bounds.height : bounds.width) - scaleHeight
}
var isLandscape: Bool {
return orientation == .landscape
}
var value: CGFloat = 0.0 {
didSet {
if self.value > 1 {
self.value = 1
}
else if self.value < -1 {
self.value = -1
}
update()
}
}
var scaleRect: CGRect {
return scalePosition == .none ?
CGRect.zero :
bounds.inset(by: UIEdgeInsets(top: scalePosition == .bottom ? barHeight : 0,
left: scalePosition == .right ? barHeight : 0,
bottom: scalePosition == .top ? barHeight : 0,
right: scalePosition == .left ? barHeight : 0))
}
var barRect: CGRect {
return bounds.inset(by: UIEdgeInsets(
top: isLandscape && scalePosition == .top ? scaleHeight : 0,
left: !isLandscape && scalePosition == .left ? scaleHeight : 0,
bottom: isLandscape && scalePosition == .bottom ? scaleHeight : 0,
right: !isLandscape && scalePosition == .right ? scaleHeight : 0))
}
var sliceSize: CGFloat {
let fullSize = (isLandscape ? barRect.width : barRect.height)
return (zeroCenter ? fullSize / 2 : fullSize) / meterResolution
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
init(frame: CGRect,
orientation: Orientation = .landscape,
scalePosition: ScalePosition = .top,
zeroCenter: Bool = false) {
super.init(frame: frame)
self.orientation = orientation
self.scalePosition = scalePosition
self.zeroCenter = zeroCenter
self.backgroundColor = UIColor.systemBackground
}
override func draw(_ rect: CGRect) {
if scalePosition != .none {
drawScale()
}
drawBar()
}
private func drawScale() {
self.tintColor.setStroke()
let bp = UIBezierPath()
bp.lineWidth = 1.0
let stepSize = (isLandscape ? scaleRect.width : scaleRect.height) / scaleResolution
for i in 0...Int(scaleResolution) {
let x = scaleRect.origin.x + (isLandscape ? CGFloat(i) * stepSize : 0)
let y = scaleRect.origin.y + (isLandscape ? 0 : CGFloat(i) * stepSize)
let point = CGPoint(x: x, y: y)
bp.move(to: point)
let lineTo = CGPoint(x: x + (isLandscape ? 0 : scaleHeight),
y: y + (isLandscape ? scaleHeight : 0))
bp.addLine(to: lineTo)
}
bp.close()
bp.stroke()
}
private func drawBar() {
clearBar()
switch meterType {
case .fill:
drawFixBar()
case .slice:
drawSliceBar()
}
}
private func clearBar() {
self.backgroundColor?.setFill()
UIBezierPath(rect: barRect).fill()
}
private func drawFixBar() {
calcDrawColor(at: value).setFill()
let drawRect = zeroCenter ? calcZeroCenterRect() : barRect
let framePath = UIBezierPath(rect: calcDrawRect(drawRect))
framePath.fill()
}
private func calcDrawColor(at value: CGFloat) -> UIColor {
let size = (meterResolution - 1) * abs(value)
return meterColor[Int(size)]
}
private func calcZeroCenterRect() -> CGRect {
let size = (isLandscape ? barRect.width : barRect.height) / 2
let zeroCenterRect = barRect.inset(by: UIEdgeInsets(
top: value < 0 && !isLandscape ? size : 0,
left: value > 0 && isLandscape ? size : 0,
bottom: value > 0 && !isLandscape ? size : 0,
right: value < 0 && isLandscape ? size : 0))
return zeroCenterRect
}
private func calcDrawRect(_ barRect: CGRect) -> CGRect {
let insetValue = isLandscape ? barRect.width * (1 - abs(value)) : barRect.height * (1 - abs(value))
return value == 0 ?
CGRect.zero :
barRect.inset(by: UIEdgeInsets(
top: !isLandscape && value > 0 ? insetValue : 0,
left: isLandscape && value < 0 ? insetValue : 0,
bottom: !isLandscape && value < 0 ? insetValue : 0,
right: isLandscape && value > 0 ? insetValue : 0))
}
private func drawSliceBar() {
let rect = zeroCenter ? calcZeroCenterRect() : barRect
drawSliceBar(at: rect)
}
private func drawSliceBar(at barRect: CGRect) {
for i in 0..<Int(meterResolution) {
if i >= Int(abs(value) * meterResolution) {
break
}
calcDrawColor(at: CGFloat(i+1) / meterResolution).setFill()
let (x, y) = calcSlicedBarOrigin(at: i, sliceSize: sliceSize, rect: barRect)
let origin = CGPoint(x: x, y: y)
let size = CGSize(width: (isLandscape ? sliceSize : barRect.width), height: (isLandscape ? barRect.height : sliceSize))
let sliceBarRect = CGRect(origin: origin, size: size)
let framePath = UIBezierPath(rect: sliceBarRect.insetBy(dx: 1.0, dy: 1.0))
framePath.fill()
}
}
private func calcSlicedBarOrigin(at i: Int, sliceSize: CGFloat, rect: CGRect) -> (CGFloat, CGFloat) {
if value > 0 {
let x = isLandscape ? rect.origin.x + CGFloat(i) * sliceSize : rect.origin.x
let y = isLandscape ? rect.origin.y : (rect.origin.y + rect.height - (CGFloat(i) + 1) * sliceSize)
return (x, y)
}
else {
let x = isLandscape ? rect.origin.x + rect.width - ((CGFloat(i) + 1) * sliceSize) : barRect.origin.x
let y = isLandscape ? rect.origin.y : rect.origin.y + CGFloat(i) * sliceSize
return (x, y)
}
}
private func update() {
setNeedsDisplay()
}
}
extension GPLevelMeterView {
@available(*, unavailable, message: "This property is reserved for IB. Use 'meterType' instead.", renamed: "meterType")
@IBInspectable var meterTypeValue: Int {
get {
return self.meterType.rawValue
}
set(newValue) {
self.meterType = MeterType(rawValue: newValue) ?? .fill
}
}
@available(*, unavailable, message: "This property is reserved for IB. Use 'orientation' instead.", renamed: "orientation")
@IBInspectable var orientationValue: Int {
get {
return self.orientation.rawValue
}
set(newValue) {
self.orientation = Orientation(rawValue: newValue) ?? .landscape
}
}
@available(*, unavailable, message: "This property is reserved for IB. Use 'scalePosition' instead.", renamed: "scalePosition")
@IBInspectable var scalePositionValue: Int {
get {
return self.scalePosition.rawValue
}
set(newValue) {
self.scalePosition = ScalePosition(rawValue: newValue) ?? .none
}
}
}
| 35.169421 | 131 | 0.540007 |
e2c60a5fbb74ed1ea8054db7bc47049f85c4c938 | 1,249 | //
// ContentView.swift
// SidebarToggle
//
// Created by Gavin Wiggins on 5/13/21.
//
import SwiftUI
struct Sidebar: View {
var body: some View {
List {
Label("Books", systemImage: "book.closed")
Label("Tutorials", systemImage: "list.bullet.rectangle")
Label("Video Tutorials", systemImage: "tv")
Label("Contacts", systemImage: "mail.stack")
Label("Search", systemImage: "magnifyingglass")
}
.listStyle(SidebarListStyle())
.toolbar {
Button(action: toggleSidebar, label: {
Image(systemName: "sidebar.left").help("Toggle Sidebar")
})
}
.frame(minWidth: 150)
}
}
private func toggleSidebar() {
NSApp.keyWindow?.contentViewController?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
}
struct ContentView: View {
var body: some View {
NavigationView {
Sidebar()
Text("Use button to toggle sidebar.")
.frame(minWidth: 200)
}
.frame(width: 500, height: 300)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 24.490196 | 119 | 0.580464 |
6454b823e14e5116b023f225fb3a22b28687763e | 969 | //
// NYPLAxisContentProtection.swift
// Open eBooks
//
// Created by Raman Singh on 2021-05-18.
// Copyright © 2021 NYPL Labs. All rights reserved.
//
import Foundation
import R2Shared
import R2Streamer
struct NYPLAxisContentProtection: ContentProtection {
let protectedAssetOpener: NYPLAxisProtectedAssetOpening
func open(asset: PublicationAsset, fetcher: Fetcher, credentials: String?,
allowUserInteraction: Bool, sender: Any?,
completion: @escaping (
CancellableResult<ProtectedAsset?, Publication.OpeningError>) -> Void) {
guard let asset = asset as? FileAsset else {
completion(.failure(.notFound))
return
}
protectedAssetOpener.openAsset(asset, fetcher: fetcher) { result in
switch result {
case .success(let protectedAsset):
completion(.success(protectedAsset))
case .failure(let error):
completion(.failure(error))
}
}
}
}
| 25.5 | 86 | 0.674923 |
d5ae836db38971a7718121060e7b8e3d8c8c757f | 1,470 | //
// KeychainStore.swift
// Wei
//
// Created by yuzushioh on 2018/03/15.
// Copyright © 2018 popshoot. All rights reserved.
//
import KeychainAccess
final class KeychainStore {
enum Service: String {
case seed = "com.popshoot.seed"
case mnemonic = "com.popshoot.mnemonic"
case accessToken = "com.popshoot.accessToken"
case isAlreadyBackup = "com.popshoot.isAlreadyBackup"
}
private let environment: Environment
init(environment: Environment) {
self.environment = environment
}
private static var accessGroup: String {
guard let prefix = Bundle.main.object(forInfoDictionaryKey: "AppIdentifierPrefix") as? String else {
fatalError("AppIdentifierPrefix is not found in Info.plist")
}
return prefix + Environment.current.appGroupID
}
private static func keychain(forService service: Service) -> Keychain {
return Keychain(service: service.rawValue, accessGroup: accessGroup)
}
subscript(service: Service) -> String? {
get {
return KeychainStore.keychain(forService: service)[environment.appGroupID]
}
set {
KeychainStore.keychain(forService: service)[environment.appGroupID] = newValue
}
}
func clearKeychain() {
self[.seed] = nil
self[.mnemonic] = nil
self[.accessToken] = nil
self[.isAlreadyBackup] = nil
}
}
| 28.269231 | 108 | 0.636735 |
22c23de5135e328087a7565fec6cbaedf93d2bc5 | 1,522 | //
// CraftSummaryCollectionViewCell.swift
// PrincessGuide
//
// Created by zzk on 2018/5/3.
// Copyright © 2018 zzk. All rights reserved.
//
import UIKit
import Gestalt
class CraftSummaryCollectionViewCell: UICollectionViewCell {
let icon = IconImageView()
let numberLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
ThemeManager.default.apply(theme: Theme.self, to: self) { (themeable, theme) in
themeable.numberLabel.textColor = theme.color.caption
}
contentView.addSubview(icon)
icon.snp.makeConstraints { (make) in
make.height.width.equalTo(64)
make.top.equalToSuperview()
make.centerX.equalToSuperview()
make.left.right.equalToSuperview()
}
contentView.addSubview(numberLabel)
numberLabel.snp.makeConstraints { (make) in
make.top.equalTo(icon.snp.bottom)
make.centerX.equalToSuperview()
make.bottom.equalToSuperview()
}
numberLabel.font = UIFont.systemFont(ofSize: 12)
// UIFont.scaledFont(forTextStyle: .caption1, ofSize: 12)
}
func configure(url: URL, number: Int) {
icon.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "icon_placeholder"))
numberLabel.text = String(number)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 29.269231 | 97 | 0.626807 |
395b1a57fc32891a2aa5b34fac0a05e96021b1b3 | 1,104 | //
// BaseTabBarControllerViewController.swift
// App
//
// Created by Zarko Popovski on 11/13/18.
// Copyright © 2018 App. All rights reserved.
//
import UIKit
class BaseTabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController?.navigationBar.isHidden = true
self.tabBar.unselectedItemTintColor = UIColor.black
self.tabBar.backgroundColor = UIColor.white
self.selectedIndex = 2
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 26.926829 | 106 | 0.673007 |
4b8c7cd681d405ff5fdf04359720a03825699cb7 | 453 | //
// BaseView.swift
// teacher
//
// Created by yueji Jia on 2018/12/5.
// Copyright © 2018年 charles. All rights reserved.
//
import UIKit
class BaseView: UIView {
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init() {
self.init(frame: CGRect.zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
initView()
}
// MARK: - view
func initView() {
}
}
| 14.612903 | 53 | 0.649007 |
d6f993f791ce2230da34820396ab6b7066e73a32 | 3,293 | //
// FontExtension.swift
// TemplateProject
//
// Created by Nikhil Patel on 27/05/19.
// Copyright © 2019 Nikhil Patel. All rights reserved.
//
import Foundation
import UIKit
extension UIFont {
enum FontStandardSize {
case size9
case size11
case size12
case size15
case size17
case size20
case size24
var size: CGFloat {
switch self {
case .size9:
return 9
case .size11:
return 11
case .size12:
return 12
case .size15:
return 15
case .size17:
return 17
case .size20:
return 20
case .size24:
return 24
}
}
}
enum Font {
case SanFranciscoDisplayLight
case SanFranciscoDisplayRegular
case SanFranciscoDisplayMedium
case SanFranciscoDisplaySemiBold
case SanFranciscoDisplayBold
var name: String {
switch self {
case .SanFranciscoDisplayLight: return "SanFranciscoDisplay-Light"
case .SanFranciscoDisplayRegular: return "SanFranciscoDisplay-Regular"
case .SanFranciscoDisplayMedium: return "SanFranciscoDisplay-Medium"
case .SanFranciscoDisplaySemiBold: return "SanFranciscoDisplay-Semibold"
case .SanFranciscoDisplayBold: return "SanFranciscoDisplay-Bold"
}
}
}
class func font(_ font: Font, fontStandardSize: FontStandardSize) -> UIFont? {
return UIFont.init(name: font.name, size: fontStandardSize.size)
}
class func font(_ font: Font, fontSize: CGFloat) -> UIFont? {
switch font {
case .SanFranciscoDisplayLight: return UIFont.systemFont(ofSize: fontSize, weight: UIFont.Weight.light)
case .SanFranciscoDisplayRegular: return UIFont.systemFont(ofSize: fontSize, weight: UIFont.Weight.regular)
case .SanFranciscoDisplayMedium: return UIFont.systemFont(ofSize: fontSize, weight: UIFont.Weight.medium)
case .SanFranciscoDisplaySemiBold: return UIFont.systemFont(ofSize: fontSize, weight: UIFont.Weight.semibold)
case .SanFranciscoDisplayBold: return UIFont.systemFont(ofSize: fontSize, weight: UIFont.Weight.bold)
}
// return UIFont.init(name: font.name, size: fontSize)
}
class func logAllAvailableFonts() {
for family in UIFont.familyNames {
print("\(family)")
for name in UIFont.fontNames(forFamilyName: family) {
print(" -> \(name)")
}
}
}
}
extension UIFont {
fileprivate func withTraits(traits:UIFontDescriptor.SymbolicTraits) -> UIFont {
let descriptor = fontDescriptor.withSymbolicTraits(traits)
return UIFont(descriptor: descriptor!, size: 0) //size 0 means keep the size as it is
}
func bold() -> UIFont {
return withTraits(traits: .traitBold)
}
func italic() -> UIFont {
return withTraits(traits: .traitItalic)
}
}
| 29.936364 | 121 | 0.582448 |
2072ad1d8866c5c6246591d25cfb9152e9eb9cc7 | 347 | import Foundation
public protocol DiffCalculator: AnyObject {
func calculate<N>(
oldItems: [ReloadableSection<N>],
newItems: [ReloadableSection<N>]
) -> SectionChanges
func calculate<N>(
oldItems: [ReloadableCell<N>],
newItems: [ReloadableCell<N>],
in sectionIndex: Int
) -> CellChanges
}
| 23.133333 | 43 | 0.636888 |
ed71df1685fc4dc0be3be9f7093abf276c3e6da7 | 1,635 | import Debugging
/// Errors that can be thrown while working with Vapor.
public struct DatabaseKitError: Debuggable {
/// See `Debuggable`.
public static let readableName = "DatabaseKit Error"
/// See `Debuggable`.
public let identifier: String
/// See `Debuggable`.
public var reason: String
/// See `Debuggable`.
public var sourceLocation: SourceLocation?
/// See `Debuggable`.
public var stackTrace: [String]
/// See `Debuggable`.
public var suggestedFixes: [String]
/// See `Debuggable`.
public var possibleCauses: [String]
/// Creates a new `DatabaseKitError`.
init(
identifier: String,
reason: String,
suggestedFixes: [String] = [],
possibleCauses: [String] = [],
file: String = #file,
function: String = #function,
line: UInt = #line,
column: UInt = #column
) {
self.identifier = identifier
self.reason = reason
self.sourceLocation = SourceLocation(file: file, function: function, line: line, column: column, range: nil)
self.stackTrace = DatabaseKitError.makeStackTrace()
self.suggestedFixes = suggestedFixes
self.possibleCauses = possibleCauses
}
}
/// For printing un-handleable errors.
func ERROR(_ string: @autoclosure () -> String, file: StaticString = #file, line: Int = #line) {
print("[DatabaseKit] \(string()) [\(file.description.split(separator: "/").last!):\(line)]")
}
/// Only includes the supplied closure in non-release builds.
internal func debugOnly(_ body: () -> Void) {
assert({ body(); return true }())
}
| 29.727273 | 116 | 0.636086 |
6187f2081805d880c9dd6a7f0ac1bbfc0e54cfb9 | 537 | //
// SendViewSectionHeaderViewModel.swift
// AlphaWallet
//
// Created by Vladyslav Shepitko on 01.06.2020.
//
import UIKit
struct SendViewSectionHeaderViewModel {
let text: String
var showTopSeparatorLine: Bool = true
var font: UIFont {
return Fonts.bold(size: 15)
}
var textColor: UIColor {
return Colors.headerThemeColor
}
var backgroundColor: UIColor {
return Colors.clear
}
var separatorBackgroundColor: UIColor {
return Colors.clear
}
}
| 17.9 | 48 | 0.646182 |
9bee741326331e7a738d5666d101666cf394ad6a | 5,018 | import SwiftUI
import Shapes
public struct ColumnChartStyle<Column: View>: ChartStyle {
private let column: Column
private let spacing: CGFloat
public func makeBody(configuration: Self.Configuration) -> some View {
let data: [ColumnData] = configuration.dataMatrix
.map { $0.reduce(0, +) }
.enumerated()
.map { ColumnData(id: $0.offset, data: $0.element) }
let hasNegativeValues = data.contains(where: {$0.data < 0})
return GeometryReader { geometry in
self.columnChart(in: geometry, data: data, hasNegativeValues: hasNegativeValues)
}
}
private func columnChart(in geometry: GeometryProxy, data: [ColumnData], hasNegativeValues: Bool) -> some View {
let columnWidth = (geometry.size.width - (CGFloat(data.count - 1) * spacing)) / CGFloat(data.count)
return ZStack(alignment: .center) {
HStack(alignment: hasNegativeValues ? .center : .bottom, spacing: spacing) {
ForEach(data) { element in
self.column
.frame(width: columnWidth, height: self.columnHeight(data: element.data, in: geometry.size.height, hasNegativeValues: hasNegativeValues))
.offset(self.offset(for: element, geometry: geometry, columnWidth: columnWidth, dataCount: data.count, hasNegativeValues: hasNegativeValues))
}
}
}
.frame(width: geometry.size.width, height: geometry.size.height, alignment: hasNegativeValues ? .center : .bottom)
.background(ZStack {
if hasNegativeValues {
Path { path in
path.addLine(from: CGPoint(x: 0, y:geometry.size.height/2), to: CGPoint(x: geometry.size.width, y: geometry.size.height/2))
}
.stroke(Color.gray.opacity(0.8), style: .init(lineWidth: 1, lineCap: .round))
}
})
}
private func offset(for element: ColumnData, geometry: GeometryProxy, columnWidth: CGFloat, dataCount: Int, hasNegativeValues: Bool) -> CGSize {
let x: CGFloat = 0
var y: CGFloat = 0
let height = self.columnHeight(data: element.data, in: geometry.size.height, hasNegativeValues: hasNegativeValues)
if hasNegativeValues {
if element.data > 0 {
y = -height/2
}else {
y = height/2
}
}
return CGSize(width: x, height: y)
}
private func columnHeight(data: CGFloat, in availableHeight: CGFloat, hasNegativeValues: Bool) -> CGFloat {
let height = availableHeight * abs(data)
if hasNegativeValues {
return height/2
}
return height
}
private func bottomAlignmentGuide(dimension: ViewDimensions, for data:CGFloat, in availableHeight: CGFloat, hasNegativeValues: Bool) -> CGFloat {
let height = self.columnHeight(data: data, in: availableHeight, hasNegativeValues: hasNegativeValues)
if data < 0 {
return availableHeight/2 - height
}else if hasNegativeValues {
return availableHeight/2 + height
}
return height
}
private func leadingAlignmentGuide(for index: Int, in availableWidth: CGFloat, dataCount: Int) -> CGFloat {
let columnWidth = (availableWidth - (CGFloat(dataCount - 1) * spacing)) / CGFloat(dataCount)
return availableWidth - (CGFloat(index) * columnWidth) + (CGFloat(index - 1) * spacing)
}
public init(column: Column, spacing: CGFloat = 8) {
self.column = column
self.spacing = spacing
}
}
struct ColumnData: Identifiable {
let id: Int
let data: CGFloat
}
public struct DefaultColumnView: View {
public var body: some View {
Rectangle().foregroundColor(.accentColor)
}
}
public extension ColumnChartStyle where Column == DefaultColumnView {
init(spacing: CGFloat = 8) {
self.init(column: DefaultColumnView(), spacing: spacing)
}
}
struct ColumnChartPreview: PreviewProvider {
@State static var data3: [CGFloat] = [-0.5,-0.2,-0.1,0.1,0.2,0.5,1]
@State static var data4: [CGFloat] = [0.1,0.2,0.5,0.9]
static var previews: some View {
Group {
Chart(data: data3)
.chartStyle(
ColumnChartStyle(column: Capsule().foregroundColor(.green), spacing: 2)
)
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(16)
.padding()
Chart(data: data4)
.chartStyle(
ColumnChartStyle(column: Capsule().foregroundColor(.green), spacing: 2)
)
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(16)
.padding()
}
}
}
| 36.362319 | 165 | 0.584097 |
f82758d171a28d277ea0de77317a32d6a6e5b2ac | 1,441 | //
// OKScene+Keyboard.swift
// OctopusKit
//
// Created by [email protected] on 2019/11/17.
// Copyright © 2020 Invading Octopus. Licensed under Apache License v2.0 (see LICENSE.txt)
//
#if canImport(AppKit)
import AppKit
extension OKScene: KeyboardEventProvider {
// TODO: Eliminate code duplication between OKScene+Keyboard and OKSubscene+Keyboard
// MARK: - Player Input (macOS Keyboard)
/// Relays keyboard-input events to the scene's `KeyboardEventComponent`.
open override func keyDown(with event: NSEvent) {
#if LOGINPUTEVENTS
debugLog()
#endif
self.entity?[KeyboardEventComponent]?.keyDown = KeyboardEventComponent.KeyboardEvent(event: event, node: self)
}
/// Relays keyboard-input events to the scene's `KeyboardEventComponent`.
open override func keyUp(with event: NSEvent) {
#if LOGINPUTEVENTS
debugLog()
#endif
self.entity?[KeyboardEventComponent]?.keyUp = KeyboardEventComponent.KeyboardEvent(event: event, node: self)
}
/// Relays keyboard-input events to the scene's `KeyboardEventComponent`.
open override func flagsChanged(with event: NSEvent) {
#if LOGINPUTEVENTS
debugLog()
#endif
self.entity?[KeyboardEventComponent]?.flagsChanged = KeyboardEventComponent.KeyboardEvent(event: event, node: self)
}
}
#endif
| 29.408163 | 123 | 0.679389 |
e58bd3d0b78dc08e6ed09b2c41cd2f2551679177 | 3,077 |
import UIKit
import SwiftUI
import SpotifyService
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first(where: { $0.url.absoluteString.contains(Auth.callBackURI) })?.url {
guard let code = Auth.parseCallback(url: url) else {
assertionFailure("Auth Error")
return
}
if let current = BackendStackManager.shared.current {
current.receiveAuthCode(code)
} else {
assertionFailure("No current active.")
}
}
}
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let viewModel = AppContainerViewModel()
let contentView = AppContainerView(viewModel: viewModel)
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 41.026667 | 143 | 0.729282 |
2f320ca7e1ee578b6c009cf4be6e64e7b3850b45 | 8,705 | //
// DownView.swift
// Down
//
// Created by Rob Phillips on 6/1/16.
// Copyright © 2016 Glazed Donut, LLC. All rights reserved.
//
import WebKit
import Highlightr
// MARK: - Public API
public typealias DownViewClosure = () -> ()
open class MarkdownView: WKWebView {
/**
Initializes a web view with the results of rendering a CommonMark Markdown string
- parameter frame: The frame size of the web view
- parameter markdownString: A string containing CommonMark Markdown
- parameter openLinksInBrowser: Whether or not to open links using an external browser
- parameter templateBundle: Optional custom template bundle. Leaving this as `nil` will use the bundle included with Down.
- parameter didLoadSuccessfully: Optional callback for when the web content has loaded successfully
- returns: An instance of Self
*/
public init(imagesStorage: URL? = nil, frame: CGRect, markdownString: String, openLinksInBrowser: Bool = true, css: String, templateBundle: Bundle? = nil, didLoadSuccessfully: DownViewClosure? = nil) throws {
self.didLoadSuccessfully = didLoadSuccessfully
if let templateBundle = templateBundle {
self.bundle = templateBundle
} else {
let classBundle = Bundle(for: MarkdownView.self)
let url = classBundle.url(forResource: "DownView", withExtension: "bundle")!
self.bundle = Bundle(url: url)!
}
let userContentController = WKUserContentController()
#if os(OSX)
userContentController.add(HandlerCopyCode(), name: "notification")
userContentController.add(HandlerMouseOver(), name: "mouseover")
userContentController.add(HandlerMouseOut(), name: "mouseout")
#endif
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
super.init(frame: frame, configuration: configuration)
if openLinksInBrowser || didLoadSuccessfully != nil { navigationDelegate = self }
try loadHTMLView(markdownString, css: getPreviewStyle(), imagesStorage: imagesStorage)
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - API
/**
Renders the given CommonMark Markdown string into HTML and updates the DownView while keeping the style intact
- parameter markdownString: A string containing CommonMark Markdown
- parameter didLoadSuccessfully: Optional callback for when the web content has loaded successfully
- throws: `DownErrors` depending on the scenario
*/
public func update(markdownString: String, didLoadSuccessfully: DownViewClosure? = nil) throws {
// Note: As the init method takes this callback already, we only overwrite it here if
// a non-nil value is passed in
if let didLoadSuccessfully = didLoadSuccessfully {
self.didLoadSuccessfully = didLoadSuccessfully
}
try loadHTMLView(markdownString, css: "")
}
private func getPreviewStyle() -> String {
var codeStyle = ""
if let hgPath = Bundle(for: Highlightr.self).path(forResource: UserDefaultsManagement.codeTheme + ".min", ofType: "css") {
codeStyle = try! String.init(contentsOfFile: hgPath)
}
let familyName = UserDefaultsManagement.noteFont.familyName
#if os(iOS)
if #available(iOS 11.0, *) {
if let font = UserDefaultsManagement.noteFont {
let fontMetrics = UIFontMetrics(forTextStyle: .body)
let fontSize = fontMetrics.scaledFont(for: font).pointSize
let fs = Int(fontSize) - 2
return "body {font: \(fs)px '\(familyName)'; } code, pre {font: \(fs)px Courier New; font-weight: bold; } img {display: block; margin: 0 auto;} \(codeStyle)"
}
}
#endif
return "body {font: \(UserDefaultsManagement.fontSize)px \(familyName); } code, pre {font: \(UserDefaultsManagement.fontSize)px Source Code Pro;} img {display: block; margin: 0 auto;} \(codeStyle)"
}
// MARK: - Private Properties
let bundle: Bundle
fileprivate lazy var baseURL: URL = {
return self.bundle.url(forResource: "index", withExtension: "html")!
}()
fileprivate var didLoadSuccessfully: DownViewClosure?
}
// MARK: - Private API
private extension MarkdownView {
func loadHTMLView(_ markdownString: String, css: String, imagesStorage: URL? = nil) throws {
var htmlString = try markdownString.toHTML()
if let imagesStorage = imagesStorage {
htmlString = loadImages(imagesStorage: imagesStorage, html: htmlString)
}
let pageHTMLString = try htmlFromTemplate(htmlString, css: css)
loadHTMLString(pageHTMLString, baseURL: baseURL)
}
private func loadImages(imagesStorage: URL, html: String) -> String {
var htmlString = html
do {
let regex = try NSRegularExpression(pattern: "<img.*?src=\"([^\"]*)\"")
let results = regex.matches(in: html, range: NSRange(html.startIndex..., in: html))
let images = results.map {
String(html[Range($0.range, in: html)!])
}
for image in images {
let localPath = image.replacingOccurrences(of: "<img src=\"", with: "").dropLast()
if localPath.starts(with: "/") || localPath.starts(with: "assets/") {
let fullImageURL = imagesStorage
let imageURL = fullImageURL.appendingPathComponent(String(localPath.removingPercentEncoding!))
let imageData = try Data(contentsOf: imageURL)
let base64prefix = "<img class=\"center\" src=\"data:image;base64," + imageData.base64EncodedString() + "\""
htmlString = htmlString.replacingOccurrences(of: image, with: base64prefix)
}
}
} catch let error {
print("Images regex: \(error.localizedDescription)")
}
return htmlString
}
func htmlFromTemplate(_ htmlString: String, css: String) throws -> String {
var template = try NSString(contentsOf: baseURL, encoding: String.Encoding.utf8.rawValue)
template = template.replacingOccurrences(of: "DOWN_CSS", with: css) as NSString
return template.replacingOccurrences(of: "DOWN_HTML", with: htmlString)
}
}
// MARK: - WKNavigationDelegate
extension MarkdownView: WKNavigationDelegate {
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else { return }
switch navigationAction.navigationType {
case .linkActivated:
decisionHandler(.cancel)
#if os(iOS)
UIApplication.shared.openURL(url)
#elseif os(OSX)
NSWorkspace.shared.open(url)
#endif
default:
decisionHandler(.allow)
}
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
didLoadSuccessfully?()
}
}
#if os(OSX)
class HandlerCopyCode: NSObject, WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
let message = (message.body as! String).trimmingCharacters(in: .whitespacesAndNewlines)
let pasteboard = NSPasteboard.general
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
pasteboard.setString(message, forType: NSPasteboard.PasteboardType.string)
}
}
class HandlerMouseOver: NSObject, WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
NSCursor.pointingHand.set()
}
}
class HandlerMouseOut: NSObject, WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
NSCursor.arrow.set()
}
}
#endif
| 39.38914 | 212 | 0.630902 |
cc13ec54c0ae9bc88ab7c562bc3c4c423df74da4 | 14,911 | //
// BleManager.swift
// BleManager
//
// Created by Antonio García on 13/10/2016.
// Copyright © 2016 Adafruit. All rights reserved.
//
import Foundation
import CoreBluetooth
#if COMMANDLINE
#else
import MSWeakTimer
#endif
class BleManager: NSObject {
// Configuration
fileprivate static let kStopScanningWhenConnectingToPeripheral = false
fileprivate static let kAlwaysAllowDuplicateKeys = true
// Singleton
static let shared = BleManager()
// Ble
var centralManager: CBCentralManager?
fileprivate var centralManagerPoweredOnSemaphore = DispatchSemaphore(value: 1)
// Scanning
var isScanning = false
fileprivate var isScanningWaitingToStart = false
fileprivate var scanningServicesFilter: [CBUUID]?
fileprivate var peripheralsFound = [UUID: BlePeripheral]()
fileprivate var peripheralsFoundLock = NSLock()
// Connecting
fileprivate var connectionTimeoutTimers = [UUID: MSWeakTimer]()
// Notifications
enum NotificationUserInfoKey: String {
case uuid = "uuid"
}
override init() {
super.init()
centralManagerPoweredOnSemaphore.wait()
centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.global(qos: .background), options: [:])
// centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main, options: [:])
}
deinit {
scanningServicesFilter?.removeAll()
peripheralsFound.removeAll()
}
func restoreCentralManager() {
DLog("Restoring central manager")
/*
guard centralManager?.delegate !== self else {
DLog("No need to restore it. It it still ours")
return
}*/
// Restore peripherals status
peripheralsFoundLock.lock()
for (_, blePeripheral) in peripheralsFound {
blePeripheral.peripheral.delegate = nil
}
let knownIdentifiers = Array(peripheralsFound.keys)
let knownPeripherals = centralManager?.retrievePeripherals(withIdentifiers: knownIdentifiers)
peripheralsFound.removeAll()
if let knownPeripherals = knownPeripherals {
for peripheral in knownPeripherals {
DLog("Adding prediscovered peripheral: \(peripheral.name ?? peripheral.identifier.uuidString)")
discovered(peripheral: peripheral)
}
}
peripheralsFoundLock.unlock()
// Restore central manager delegate if was changed
centralManager?.delegate = self
if isScanning {
startScan()
}
}
// MARK: - Scan
func startScan(withServices services: [CBUUID]? = nil) {
centralManagerPoweredOnSemaphore.wait()
centralManagerPoweredOnSemaphore.signal()
isScanningWaitingToStart = true
guard let centralManager = centralManager, centralManager.state != .poweredOff && centralManager.state != .unauthorized && centralManager.state != .unsupported else {
DLog("startScan failed because central manager is not ready")
return
}
scanningServicesFilter = services
guard centralManager.state == .poweredOn else {
DLog("startScan failed because central manager is not powered on")
return
}
// DLog("start scan")
isScanning = true
NotificationCenter.default.post(name: .didStartScanning, object: nil)
let options = BleManager.kAlwaysAllowDuplicateKeys ? [CBCentralManagerScanOptionAllowDuplicatesKey: true] : nil
centralManager.scanForPeripherals(withServices: services, options: options)
isScanningWaitingToStart = false
}
func stopScan() {
// DLog("stop scan")
centralManager?.stopScan()
isScanning = false
isScanningWaitingToStart = false
NotificationCenter.default.post(name: .didStopScanning, object: nil)
}
func peripherals() -> [BlePeripheral] {
peripheralsFoundLock.lock(); defer { peripheralsFoundLock.unlock() }
return Array(peripheralsFound.values)
}
func connectedPeripherals() -> [BlePeripheral] {
return peripherals().filter {$0.state == .connected}
}
func connectingPeripherals() -> [BlePeripheral] {
return peripherals().filter {$0.state == .connecting}
}
func connectedOrConnectingPeripherals() -> [BlePeripheral] {
return peripherals().filter {$0.state == .connected || $0.state == .connecting}
}
func refreshPeripherals() {
stopScan()
peripheralsFoundLock.lock()
// Don't remove connnected or connecting peripherals
for (identifier, peripheral) in peripheralsFound {
if peripheral.state != .connected && peripheral.state != .connecting {
peripheralsFound.removeValue(forKey: identifier)
}
}
peripheralsFoundLock.unlock()
//
NotificationCenter.default.post(name: .didUnDiscoverPeripheral, object: nil)
startScan(withServices: scanningServicesFilter)
}
// MARK: - Connection Management
func connect(to peripheral: BlePeripheral, timeout: TimeInterval? = nil, shouldNotifyOnConnection: Bool = false, shouldNotifyOnDisconnection: Bool = false, shouldNotifyOnNotification: Bool = false) {
centralManagerPoweredOnSemaphore.wait()
centralManagerPoweredOnSemaphore.signal()
// Stop scanning when connecting to a peripheral
if BleManager.kStopScanningWhenConnectingToPeripheral {
stopScan()
}
// Connect
NotificationCenter.default.post(name: .willConnectToPeripheral, object: nil, userInfo: [NotificationUserInfoKey.uuid.rawValue: peripheral.identifier])
//DLog("connect")
var options: [String: Bool]?
#if os(OSX)
#else
if shouldNotifyOnConnection || shouldNotifyOnDisconnection || shouldNotifyOnDisconnection {
options = [CBConnectPeripheralOptionNotifyOnConnectionKey: shouldNotifyOnConnection, CBConnectPeripheralOptionNotifyOnDisconnectionKey: shouldNotifyOnDisconnection, CBConnectPeripheralOptionNotifyOnNotificationKey: shouldNotifyOnDisconnection]
}
#endif
if let timeout = timeout {
connectionTimeoutTimers[peripheral.identifier] = MSWeakTimer.scheduledTimer(withTimeInterval: timeout, target: self, selector: #selector(connectionTimeoutFired), userInfo: peripheral.identifier, repeats: false, dispatchQueue: .global(qos: .background))
}
centralManager?.connect(peripheral.peripheral, options: options)
}
@objc func connectionTimeoutFired(timer: MSWeakTimer) {
let peripheralIdentifier = timer.userInfo() as! UUID
DLog("connection timeout fired: \(peripheralIdentifier)")
connectionTimeoutTimers[peripheralIdentifier] = nil
NotificationCenter.default.post(name: .willDisconnectFromPeripheral, object: nil, userInfo: [NotificationUserInfoKey.uuid.rawValue: peripheralIdentifier])
if let blePeripheral = peripheralsFound[peripheralIdentifier] {
centralManager?.cancelPeripheralConnection(blePeripheral.peripheral)
} else {
DLog("simulate disconnection")
// The blePeripheral is available on peripheralsFound, so simulate the disconnection
NotificationCenter.default.post(name: .didDisconnectFromPeripheral, object: nil, userInfo: [NotificationUserInfoKey.uuid.rawValue: peripheralIdentifier])
}
}
func disconnect(from peripheral: BlePeripheral) {
DLog("disconnect")
NotificationCenter.default.post(name: .willDisconnectFromPeripheral, object: nil, userInfo: [NotificationUserInfoKey.uuid.rawValue: peripheral.identifier])
centralManager?.cancelPeripheralConnection(peripheral.peripheral)
}
func reconnecToPeripherals(withIdentifiers identifiers: [UUID], withServices services: [CBUUID], timeout: Double? = nil) -> Bool {
var reconnecting = false
let knownPeripherals = centralManager?.retrievePeripherals(withIdentifiers: identifiers)
if let peripherals = knownPeripherals?.filter({identifiers.contains($0.identifier)}) {
for peripheral in peripherals {
discovered(peripheral: peripheral)
if let blePeripheral = peripheralsFound[peripheral.identifier] {
connect(to: blePeripheral, timeout: timeout)
reconnecting = true
}
}
} else {
let connectedPeripherals = centralManager?.retrieveConnectedPeripherals(withServices: services)
if let peripherals = connectedPeripherals?.filter({identifiers.contains($0.identifier)}) {
for peripheral in peripherals {
discovered(peripheral: peripheral)
if let blePeripheral = peripheralsFound[peripheral.identifier] {
connect(to: blePeripheral, timeout: timeout)
reconnecting = true
}
}
}
}
return reconnecting
}
fileprivate func discovered(peripheral: CBPeripheral, advertisementData: [String: Any]? = nil, rssi: Int? = nil) {
if let existingPeripheral = peripheralsFound[peripheral.identifier] {
existingPeripheral.lastSeenTime = CFAbsoluteTimeGetCurrent()
if let rssi = rssi, rssi != 127 { // only update rssi value if is defined ( 127 means undefined )
existingPeripheral.rssi = rssi
}
if let advertisementData = advertisementData {
for (key, value) in advertisementData {
existingPeripheral.advertisement.advertisementData.updateValue(value, forKey: key)
}
}
peripheralsFound[peripheral.identifier] = existingPeripheral
} else { // New peripheral found
let blePeripheral = BlePeripheral(peripheral: peripheral, advertisementData: advertisementData, rssi: rssi)
peripheralsFound[peripheral.identifier] = blePeripheral
}
}
// MARK: - Notifications
func peripheral(from notification: Notification) -> BlePeripheral? {
guard let uuid = notification.userInfo?[NotificationUserInfoKey.uuid.rawValue] as? UUID else {
return nil
}
return peripheral(with: uuid)
}
func peripheral(with uuid: UUID) -> BlePeripheral? {
return peripheralsFound[uuid]
}
}
// MARK: - CBCentralManagerDelegate
extension BleManager: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
DLog("centralManagerDidUpdateState: \(central.state.rawValue)")
// Unlock state lock if we have a known state
if central.state == .poweredOn || central.state == .poweredOff || central.state == .unsupported || central.state == .unauthorized {
centralManagerPoweredOnSemaphore.signal()
}
// Scanning
if central.state == .poweredOn {
if isScanningWaitingToStart {
startScan(withServices: scanningServicesFilter) // Continue scanning now that bluetooth is back
}
} else {
if isScanning {
isScanningWaitingToStart = true
}
isScanning = false
}
NotificationCenter.default.post(name: .didUpdateBleState, object: nil)
}
/*
func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
}*/
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
// DLog("didDiscover: \(peripheral.name ?? peripheral.identifier.uuidString)")
let rssi = RSSI.intValue
DispatchQueue.main.async { // This Fixes iOS12 race condition on cached filtered peripherals. TODO: investigate
self.discovered(peripheral: peripheral, advertisementData: advertisementData, rssi: rssi)
NotificationCenter.default.post(name: .didDiscoverPeripheral, object: nil, userInfo: [NotificationUserInfoKey.uuid.rawValue: peripheral.identifier])
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
DLog("didConnect: \(peripheral.identifier)")
// Remove connection timeout if exists
if let timer = connectionTimeoutTimers[peripheral.identifier] {
timer.invalidate()
connectionTimeoutTimers[peripheral.identifier] = nil
}
// Send notification
NotificationCenter.default.post(name: .didConnectToPeripheral, object: nil, userInfo: [NotificationUserInfoKey.uuid.rawValue: peripheral.identifier])
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
DLog("didFailToConnect")
NotificationCenter.default.post(name: .didDisconnectFromPeripheral, object: nil, userInfo: [NotificationUserInfoKey.uuid.rawValue: peripheral.identifier])
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
DLog("didDisconnectPeripheral")
// Clean
peripheralsFound[peripheral.identifier]?.reset()
// Notify
NotificationCenter.default.post(name: .didDisconnectFromPeripheral, object: nil, userInfo: [NotificationUserInfoKey.uuid.rawValue: peripheral.identifier])
// Remove from peripheral list (after sending notification so the receiving objects can query about the peripheral before being removed)
peripheralsFoundLock.lock()
peripheralsFound.removeValue(forKey: peripheral.identifier)
peripheralsFoundLock.unlock()
}
}
// MARK: - Custom Notifications
extension Notification.Name {
private static let kPrefix = Bundle.main.bundleIdentifier!
static let didUpdateBleState = Notification.Name(kPrefix+".didUpdateBleState")
static let didStartScanning = Notification.Name(kPrefix+".didStartScanning")
static let didStopScanning = Notification.Name(kPrefix+".didStopScanning")
static let didDiscoverPeripheral = Notification.Name(kPrefix+".didDiscoverPeripheral")
static let didUnDiscoverPeripheral = Notification.Name(kPrefix+".didUnDiscoverPeripheral")
static let willConnectToPeripheral = Notification.Name(kPrefix+".willConnectToPeripheral")
static let didConnectToPeripheral = Notification.Name(kPrefix+".didConnectToPeripheral")
static let willDisconnectFromPeripheral = Notification.Name(kPrefix+".willDisconnectFromPeripheral")
static let didDisconnectFromPeripheral = Notification.Name(kPrefix+".didDisconnectFromPeripheral")
}
| 40.629428 | 264 | 0.681376 |
2f17bf130dbc0763bb1c89ef2cad4932feb3d51e | 9,374 | //
// ViewController.swift
// SwiftyHue
//
// Created by Marcel Dittmann on 04/21/2016.
// Copyright (c) 2016 Marcel Dittmann. All rights reserved.
//
import UIKit
import SwiftyHue
import Gloss
var swiftyHue: SwiftyHue = SwiftyHue();
class ViewController: UIViewController, BridgeFinderDelegate, BridgeAuthenticatorDelegate {
fileprivate let bridgeAccessConfigUserDefaultsKey = "BridgeAccessConfig"
fileprivate let bridgeFinder = BridgeFinder()
fileprivate var bridgeAuthenticator: BridgeAuthenticator?
override func viewDidLoad() {
super.viewDidLoad()
swiftyHue.enableLogging(true)
//swiftyHue.setMinLevelForLogMessages(.info)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if readBridgeAccessConfig() != nil {
runTestCode()
} else {
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CreateBridgeAccessController") as! CreateBridgeAccessController
controller.bridgeAccessCreationDelegate = self;
self.present(controller, animated: false, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destController = segue.destination as! BridgeResourceTableViewController
if segue.identifier == "LightsSegue" {
destController.resourceTypeToDisplay = .lights
} else if segue.identifier == "GroupsSegue" {
destController.resourceTypeToDisplay = .groups
} else if segue.identifier == "ScenesSegue" {
destController.resourceTypeToDisplay = .scenes
} else if segue.identifier == "SensorsSegue" {
destController.resourceTypeToDisplay = .sensors
} else if segue.identifier == "SchedulesSegue" {
destController.resourceTypeToDisplay = .schedules
} else if segue.identifier == "RulesSegue" {
destController.resourceTypeToDisplay = .rules
} else if segue.identifier == "ConfigSegue" {
destController.resourceTypeToDisplay = .config
}
}
}
// MARK: BridgeAccessConfig
extension ViewController {
func readBridgeAccessConfig() -> BridgeAccessConfig? {
let userDefaults = UserDefaults.standard
let bridgeAccessConfigJSON = userDefaults.object(forKey: bridgeAccessConfigUserDefaultsKey) as? JSON
var bridgeAccessConfig: BridgeAccessConfig?
if let bridgeAccessConfigJSON = bridgeAccessConfigJSON {
bridgeAccessConfig = BridgeAccessConfig(json: bridgeAccessConfigJSON)
}
return bridgeAccessConfig
}
func writeBridgeAccessConfig(bridgeAccessConfig: BridgeAccessConfig) {
let userDefaults = UserDefaults.standard
let bridgeAccessConfigJSON = bridgeAccessConfig.toJSON()
userDefaults.set(bridgeAccessConfigJSON, forKey: bridgeAccessConfigUserDefaultsKey)
}
}
// MARK: CreateBridgeAccessControllerDelegate
extension ViewController: CreateBridgeAccessControllerDelegate {
func bridgeAccessCreated(bridgeAccessConfig: BridgeAccessConfig) {
writeBridgeAccessConfig(bridgeAccessConfig: bridgeAccessConfig)
}
}
// MARK: - Playground
extension ViewController {
func runTestCode() {
let bridgeAccessConfig = self.readBridgeAccessConfig()!
swiftyHue.setBridgeAccessConfig(bridgeAccessConfig)
swiftyHue.setLocalHeartbeatInterval(10, forResourceType: .lights)
swiftyHue.setLocalHeartbeatInterval(10, forResourceType: .groups)
swiftyHue.setLocalHeartbeatInterval(10, forResourceType: .rules)
swiftyHue.setLocalHeartbeatInterval(10, forResourceType: .scenes)
swiftyHue.setLocalHeartbeatInterval(10, forResourceType: .schedules)
swiftyHue.setLocalHeartbeatInterval(10, forResourceType: .sensors)
swiftyHue.setLocalHeartbeatInterval(10, forResourceType: .config)
swiftyHue.startHeartbeat();
// var lightState = LightState()
// lightState.on = false;
// swiftyHue.bridgeSendAPI.setLightStateForGroupWithId("1", withLightState: lightState) { (errors) in
//
// print(errors)
// }
// var beatManager = BeatManager(bridgeAccessConfig: bridgeAccessConfig)
// beatManager.setLocalHeartbeatInterval(3, forResourceType: .Lights)
// beatManager.setLocalHeartbeatInterval(3, forResourceType: .Groups)
// beatManager.setLocalHeartbeatInterval(3, forResourceType: .Rules)
// beatManager.setLocalHeartbeatInterval(3, forResourceType: .Scenes)
// beatManager.setLocalHeartbeatInterval(3, forResourceType: .Schedules)
// beatManager.setLocalHeartbeatInterval(3, forResourceType: .Sensors)
// beatManager.setLocalHeartbeatInterval(3, forResourceType: .Config)
//
// beatManager.startHeartbeat()
//
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.lightChanged), name: NSNotification.Name(rawValue: ResourceCacheUpdateNotification.lightsUpdated.rawValue), object: nil)
// var lightState = LightState()
// lightState.on = true
// BridgeSendAPI.updateLightStateForId("324325675tzgztztut1234434334", withLightState: lightState) { (errors) in
// print(errors)
// }
// BridgeSendAPI.setLightStateForGroupWithId("huuuuuuu1", withLightState: lightState) { (errors) in
//
// print(errors)
// }
// BridgeSendAPI.createGroupWithName("TestRoom", andType: GroupType.LightGroup, includeLightIds: ["1","2"]) { (errors) in
//
// print(errors)
// }
// BridgeSendAPI.removeGroupWithId("11") { (errors) in
//
// print(errors)
// }
// BridgeSendAPI.updateGroupWithId("11", newName: "TestRoom234", newLightIdentifiers: nil) { (errors) in
//
// print(errors)
// }
//TestRequester.sharedInstance.requestScenes()
//TestRequester.sharedInstance.requestSchedules()
// BridgeSendAPI.createSceneWithName("MeineTestScene", includeLightIds: ["1"]) { (errors) in
//
// print(errors)
// }
//TestRequester.sharedInstance.requestLights()
//TestRequester.sharedInstance.getConfig()
//TestRequester.sharedInstance.requestError()
// BridgeSendAPI.activateSceneWithIdentifier("14530729836055") { (errors) in
// print(errors)
// }
// BridgeSendAPI.recallSceneWithIdentifier("14530729836055", inGroupWithIdentifier: "2") { (errors) in
//
// print(errors)
// }
// let xy = Utilities.calculateXY(UIColor.greenColor(), forModel: "LST001")
//
// var lightState = LightState()
// lightState.on = true
// lightState.xy = [Float(xy.x), Float(xy.y)]
// lightState.brightness = 254
//
// BridgeSendAPI.updateLightStateForId("6", withLightState: lightState) { (errors) in
// print(errors)
// }
}
@objc public func lightChanged() {
print("Changed")
// var cache = BridgeResourcesCacheManager.sharedInstance.cache
// var light = cache.groups["1"]!
// print(light.name)
}
// MARK: - BridgeFinderDelegate
func bridgeFinder(_ finder: BridgeFinder, didFinishWithResult bridges: [HueBridge]) {
print(bridges)
guard let bridge = bridges.first else {
return
}
bridgeAuthenticator = BridgeAuthenticator(bridge: bridge, uniqueIdentifier: "example#simulator")
bridgeAuthenticator!.delegate = self
bridgeAuthenticator!.start()
}
// MARK: - BridgeAuthenticatorDelegate
func bridgeAuthenticatorDidTimeout(_ authenticator: BridgeAuthenticator) {
print("Timeout")
}
func bridgeAuthenticator(_ authenticator: BridgeAuthenticator, didFailWithError error: NSError) {
print("Error while authenticating: \(error)")
}
func bridgeAuthenticatorRequiresLinkButtonPress(_ authenticator: BridgeAuthenticator, secondsLeft: TimeInterval) {
print("Press link button")
}
func bridgeAuthenticator(_ authenticator: BridgeAuthenticator, didFinishAuthentication username: String) {
print("Authenticated, hello \(username)")
}
}
| 35.778626 | 208 | 0.619693 |
799f1c2ad7f9aaa0924158ff393a3e17e0e5ce99 | 1,019 | // swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "EasyText",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "EasyText",
targets: ["EasyText"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "EasyText",
dependencies: []),
.testTarget(
name: "EasyTextTests",
dependencies: ["EasyText"]),
]
)
| 35.137931 | 122 | 0.618253 |
56a50498ecc6d640c759fc8156cb5866ff144ec1 | 1,025 | //
// MachineLearningSqueezeTests.swift
// MachineLearningSqueezeTests
//
// Created by Sandeep N on 08/04/18.
// Copyright © 2018 Sandeep N. All rights reserved.
//
import XCTest
@testable import MachineLearningSqueeze
class MachineLearningSqueezeTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.702703 | 111 | 0.651707 |
69b6d4f6441a4eefa1c8d133574994f15eb4a970 | 3,053 | //
// SocketProxy.swift
// freechat-swift
//
// Created by Dzung on 10/05/2021.
// Copyright © 2021 Young Monkeys. All rights reserved.
//
import Foundation
public let ZONE_NAME = "example"
public let APP_NAME = "hello-world"
public class SocketProxy {
private let client: EzyClient
private static let INSTANCE = SocketProxy()
private init() {
let config = EzyClientConfig()
.setClientName(clientName: ZONE_NAME)
.setZoneName(zoneName: ZONE_NAME)
.setEnableSSL()
// .setEnableDebug()
_ = config.ping
.setPingPeriod(pingPeriod: 3000)
.setMaxLostPingCount(maxLostPingCount: 3)
_ = config.reconnect
.setReconnectPeriod(reconnectPeriod: 1000)
.setMaxReconnectCount(maxReconnectCount: 10)
let clients = EzyClients.getInstance()!
client = clients.newClient(config: config)
let setup = client.setup!
.addEventHandler(eventType: EzyEventType.CONNECTION_SUCCESS, handler: ExConnectionSuccessHandler())
.addEventHandler(eventType: EzyEventType.CONNECTION_FAILURE, handler: EzyConnectionFailureHandler())
.addEventHandler(eventType: EzyEventType.DISCONNECTION, handler: ExDisconnectionHandler())
.addDataHandler(cmd: EzyCommand.LOGIN, handler: ExLoginSuccessHandler())
.addDataHandler(cmd: EzyCommand.APP_ACCESS, handler: ExAppAccessHandler())
.addDataHandler(cmd: EzyCommand.HANDSHAKE, handler: ExHandshakeHandler())
_ = setup.setupApp(appName: APP_NAME)
Thread.current.name = "main";
clients.processEvents()
}
public static func getInstance() -> SocketProxy {
return INSTANCE
}
public func connectToServer() {
// let host = "127.0.0.1"
let host = "ws.tvd12.com"
client.connect(host: host, port: 3005)
}
}
class ExConnectionSuccessHandler: EzyConnectionSuccessHandler {
}
class ExDisconnectionHandler: EzyDisconnectionHandler {
override func postHandle(event: NSDictionary) {
// do something here
}
}
class ExHandshakeHandler : EzyHandshakeHandler {
override func getLoginRequest() -> NSArray {
let array = NSMutableArray()
array.add(ZONE_NAME)
array.add("swift123")
array.add("12345678912")
return array
}
override func encryptedLoginRequest() -> Bool {
return true;
}
};
class ExLoginSuccessHandler : EzyLoginSuccessHandler {
override func handleLoginSuccess(responseData: NSObject) {
let array = NSMutableArray()
array.add(APP_NAME)
array.add(NSDictionary())
client!.send(cmd: EzyCommand.APP_ACCESS, data: array)
}
};
class ExAppAccessHandler : EzyAppAccessHandler {
override func postHandle(app: EzyApp, data: NSObject) -> Void {
let requestData = NSMutableDictionary()
requestData["who"] = "Swift"
app.send(cmd: "secureChat", data: requestData, encrypted: true)
}
};
| 32.136842 | 112 | 0.660007 |
1e0a8772016e42501ec372d783be6c9e4e05f441 | 1,826 | //
// BoxedBorderView.swift
// MondrianSandbox
//
// Created by Sean Reed on 7/7/15.
// Copyright (c) 2015 Sean Reed. All rights reserved.
// Xcode 6.4, Swift 1.2
//
import UIKit
import QuartzCore
@IBDesignable
class BoxedBorderView : UIView {
//equal border width on all sides
@IBInspectable var borderWidth:CGFloat = 3.0 {
didSet{
layer.borderWidth = borderWidth
setNeedsDisplay()
}
}
override func drawRect(rect: CGRect) {
var context:CGContextRef = UIGraphicsGetCurrentContext()
//initialize border color and line width
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
CGContextSetLineWidth(context, borderWidth)
// border on top
CGContextMoveToPoint(context, CGRectGetMinX(rect), CGRectGetMinY(rect))
CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMinY(rect))
CGContextStrokePath(context)
// border on left side
CGContextMoveToPoint(context, CGRectGetMinX(rect), CGRectGetMinY(rect))
CGContextAddLineToPoint(context, CGRectGetMinX(rect), CGRectGetMaxY(rect))
CGContextStrokePath(context)
//border on right side
CGContextMoveToPoint(context, CGRectGetMaxX(rect), CGRectGetMinY(rect))
CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMaxY(rect))
CGContextStrokePath(context)
//border on bottom
CGContextMoveToPoint(context, CGRectGetMinX(rect), CGRectGetMaxY(rect))
CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMaxY(rect))
CGContextStrokePath(context)
}
// override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
// //
// }
} | 30.433333 | 84 | 0.670865 |
71244c2385a655a38cfe72b3cc73b20e46d3c583 | 2,278 | //
// AppDelegate.swift
// SSDDemo
//
// Created by Nicky Chan on 11/6/17.
// Copyright © 2017 PaddlePaddle. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//avoid screen off timer kicks off
UIApplication.shared.isIdleTimerDisabled = true
//init paddle libraries for one time
PaddleHelper.init_paddle()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.489796 | 285 | 0.750219 |
0997dfe90b4c2d8372bda046bf606e42add6dfd3 | 24,590 | import UIKit
// MARK: - TabViewDelegate
public protocol TabViewDelegate: AnyObject {
/// Called before selecting the tab.
func tabView(_ tabView: TabView, willSelectTabAt index: Int)
/// Called after selecting the tab.
func tabView(_ tabView: TabView, didSelectTabAt index: Int)
}
extension TabViewDelegate {
public func tabView(_ tabView: TabView, willSelectTabAt index: Int) {}
public func tabView(_ tabView: TabView, didSelectTabAt index: Int) {}
}
// MARK: - TabViewDataSource
public protocol TabViewDataSource: AnyObject {
/// Return the number of Items in `TabView`.
func numberOfItems(in tabView: TabView) -> Int
/// Return strings to be displayed at the tab in `TabView`.
func tabView(_ tabView: TabView, titleForItemAt index: Int) -> String?
/// Return views to be displayed at the tab in `TabView`.
func tabView(_ tabView: TabView, viewForItemAt index: Int) -> TabItemViewProtocol?
}
open class TabView: UIScrollView {
open weak var tabViewDelegate: TabViewDelegate?
open weak var dataSource: TabViewDataSource?
var itemViews: [TabItemViewProtocol] = []
fileprivate let containerView: UIStackView = UIStackView()
fileprivate var additionView: UIView = .init()
fileprivate var currentIndex: Int = 0
fileprivate(set) var options: SwipeMenuViewOptions.TabView = SwipeMenuViewOptions.TabView()
private var leftMarginConstraint: NSLayoutConstraint = .init()
private var widthConstraint: NSLayoutConstraint = .init()
public init(frame: CGRect, options: SwipeMenuViewOptions.TabView? = nil) {
super.init(frame: frame)
if let options = options {
self.options = options
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func didMoveToSuperview() {
reloadData()
}
open override func layoutSubviews() {
super.layoutSubviews()
resetAdditionViewPosition(index: currentIndex)
}
@available(iOS 11.0, *)
open override func safeAreaInsetsDidChange() {
super.safeAreaInsetsDidChange()
leftMarginConstraint.constant = options.margin + safeAreaInsets.left
if options.style == .segmented {
widthConstraint.constant = options.margin * -2 - safeAreaInsets.left - safeAreaInsets.right
}
layoutIfNeeded()
}
fileprivate func focus(on target: UIView, animated: Bool = true) {
if options.style == .segmented { return }
let offset: CGFloat
let contentWidth: CGFloat
if #available(iOS 11.0, *), options.isSafeAreaEnabled {
offset = target.center.x + options.margin + safeAreaInsets.left - self.frame.width / 2
contentWidth = containerView.frame.width + options.margin * 2 + safeAreaInsets.left + safeAreaInsets.right
} else {
offset = target.center.x + options.margin - self.frame.width / 2
contentWidth = containerView.frame.width + options.margin * 2
}
if offset < 0 || self.frame.width > contentWidth {
self.setContentOffset(CGPoint(x: 0, y: 0), animated: animated)
} else if contentWidth - self.frame.width < offset {
self.setContentOffset(CGPoint(x: contentWidth - self.frame.width, y: 0), animated: animated)
} else {
self.setContentOffset(CGPoint(x: offset, y: 0), animated: animated)
}
}
// MARK: - Setup
/// Reloads all `TabView` item views with the dataSource and refreshes the display.
public func reloadData(options: SwipeMenuViewOptions.TabView? = nil,
default defaultIndex: Int? = nil,
animated: Bool = true) {
if let options = options {
self.options = options
}
reset()
guard let dataSource = dataSource,
dataSource.numberOfItems(in: self) > 0 else { return }
setupScrollView()
setupContainerView(dataSource: dataSource)
setupTabItemViews(dataSource: dataSource)
setupAdditionView()
if let defaultIndex = defaultIndex {
moveTabItem(index: defaultIndex, animated: animated)
}
}
func reset() {
currentIndex = 0
itemViews.forEach { $0.removeFromSuperview() }
additionView.removeFromSuperview()
containerView.removeFromSuperview()
itemViews = []
}
func update(_ index: Int) {
if currentIndex == index { return }
currentIndex = index
updateSelectedItem(by: currentIndex)
}
fileprivate func setupScrollView() {
backgroundColor = options.backgroundColor
showsHorizontalScrollIndicator = false
showsVerticalScrollIndicator = false
isScrollEnabled = true
isDirectionalLockEnabled = true
alwaysBounceHorizontal = false
scrollsToTop = false
bouncesZoom = false
translatesAutoresizingMaskIntoConstraints = false
}
fileprivate func setupContainerView(dataSource: TabViewDataSource) {
containerView.alignment = .leading
switch options.style {
case .flexible:
containerView.distribution = .fill
case .segmented:
containerView.distribution = .fillEqually
}
let itemCount = dataSource.numberOfItems(in: self)
var containerHeight: CGFloat = 0.0
switch options.addition {
case .underline:
containerHeight = frame.height - options.additionView.underline.height - options.additionView.padding.bottom
case .none, .circle:
containerHeight = frame.height
}
switch options.style {
case .flexible:
let containerWidth = options.itemView.width * CGFloat(itemCount)
if #available(iOS 11.0, *), options.isSafeAreaEnabled {
contentSize = CGSize(width: containerWidth + options.margin * 2 + safeAreaInsets.left + safeAreaInsets.right, height: options.height)
containerView.frame = CGRect(x: 0, y: options.margin + safeAreaInsets.left, width: containerWidth, height: containerHeight)
} else {
contentSize = CGSize(width: containerWidth + options.margin * 2, height: options.height)
containerView.frame = CGRect(x: 0, y: options.margin, width: containerWidth, height: containerHeight)
}
case .segmented:
if #available(iOS 11.0, *), options.isSafeAreaEnabled {
contentSize = CGSize(width: frame.width, height: options.height)
containerView .frame = CGRect(x: 0, y: options.margin + safeAreaInsets.left, width: frame.width - options.margin * 2 - safeAreaInsets.left - safeAreaInsets.right, height: containerHeight)
} else {
contentSize = CGSize(width: frame.width, height: options.height)
containerView .frame = CGRect(x: 0, y: options.margin, width: frame.width - options.margin * 2, height: containerHeight)
}
}
containerView.backgroundColor = .clear
addSubview(containerView)
}
fileprivate func setupTabItemViews(dataSource: TabViewDataSource) {
itemViews = []
let itemCount = dataSource.numberOfItems(in: self)
var xPosition: CGFloat = 0
for index in 0..<itemCount {
let tabItemViewFrame = CGRect(x: xPosition, y: 0, width: options.itemView.width, height: containerView.frame.size.height)
let tabItemView: TabItemViewProtocol
if let originalItemView = dataSource.tabView(self, viewForItemAt: index) {
tabItemView = originalItemView
tabItemView.frame = tabItemViewFrame
} else {
tabItemView = TabItemView(frame: tabItemViewFrame)
}
tabItemView.translatesAutoresizingMaskIntoConstraints = false
tabItemView.clipsToBounds = options.clipsToBounds
if let title = dataSource.tabView(self, titleForItemAt: index) {
let attributedTitle: NSMutableAttributedString = .init(string: title)
attributedTitle.addAttribute(.font, value: options.itemView.font, range: .init(location: 0, length: title.count))
attributedTitle.addAttribute(.kern, value: options.itemView.kern, range: .init(location: 0, length: title.count))
tabItemView.titleLabel.attributedText = attributedTitle
tabItemView.textColor = options.itemView.textColor
tabItemView.selectedTextColor = options.itemView.selectedTextColor
}
tabItemView.notificationBadgeColor = options.itemView.notificationBadgeColor
tabItemView.isSelected = index == currentIndex
switch options.style {
case .flexible:
if options.needsAdjustItemViewWidth {
var adjustCellSize = tabItemView.frame.size
adjustCellSize.width = tabItemView.titleLabel.sizeThatFits(containerView.frame.size).width + options.itemView.margin * 2
tabItemView.frame.size = adjustCellSize
containerView.addArrangedSubview(tabItemView)
NSLayoutConstraint.activate([
tabItemView.widthAnchor.constraint(equalToConstant: adjustCellSize.width)
])
} else {
containerView.addArrangedSubview(tabItemView)
NSLayoutConstraint.activate([
tabItemView.widthAnchor.constraint(equalToConstant: options.itemView.width)
])
}
case .segmented:
let adjustCellSize: CGSize
if #available(iOS 11.0, *), options.isSafeAreaEnabled {
adjustCellSize = CGSize(width: (frame.width - options.margin * 2 - safeAreaInsets.left - safeAreaInsets.right) / CGFloat(itemCount), height: tabItemView.frame.size.height)
} else {
adjustCellSize = CGSize(width: (frame.width - options.margin * 2) / CGFloat(itemCount), height: tabItemView.frame.size.height)
}
tabItemView.frame.size = adjustCellSize
if let title = dataSource.tabView(self, titleForItemAt: index) {
let textFrame = (title as NSString).boundingRect(with: tabItemView.titleLabel.frame.size,
options: .usesLineFragmentOrigin,
attributes: [NSAttributedString.Key.font: options.itemView.font],
context: nil)
tabItemView.notificationBadgeViewFrame = .init(x: textFrame.width + (adjustCellSize.width - textFrame.width) / 2 + 6,
y: adjustCellSize.height / 2 - tabItemView.notificationBadgeViewSize.height,
width: tabItemView.notificationBadgeViewSize.width,
height: tabItemView.notificationBadgeViewSize.height)
}
containerView.addArrangedSubview(tabItemView)
}
itemViews.append(tabItemView)
NSLayoutConstraint.activate([
tabItemView.topAnchor.constraint(equalTo: containerView.topAnchor),
tabItemView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
])
xPosition += tabItemView.frame.size.width
}
layout(containerView: containerView, containerWidth: xPosition)
addTabItemGestures()
animateAdditionView(index: currentIndex, animated: false)
}
private func layout(containerView: UIView, containerWidth: CGFloat) {
containerView.frame.size.width = containerWidth
containerView.translatesAutoresizingMaskIntoConstraints = false
let heightConstraint: NSLayoutConstraint
switch options.addition {
case .underline:
heightConstraint = containerView.heightAnchor.constraint(equalToConstant: options.height - options.additionView.underline.height - options.additionView.padding.bottom)
case .circle, .none:
heightConstraint = containerView.heightAnchor.constraint(equalToConstant: options.height)
}
switch options.style {
case .flexible:
if #available(iOS 11.0, *), options.isSafeAreaEnabled {
leftMarginConstraint = containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: options.margin + safeAreaInsets.left)
NSLayoutConstraint.activate([
containerView.topAnchor.constraint(equalTo: self.topAnchor),
leftMarginConstraint,
containerView.widthAnchor.constraint(equalToConstant: containerWidth),
heightConstraint
])
contentSize.width = containerWidth + options.margin * 2 + safeAreaInsets.left - safeAreaInsets.right
} else {
leftMarginConstraint = containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: options.margin)
NSLayoutConstraint.activate([
containerView.topAnchor.constraint(equalTo: self.topAnchor),
leftMarginConstraint,
containerView.widthAnchor.constraint(equalToConstant: containerWidth),
heightConstraint
])
contentSize.width = containerWidth + options.margin * 2
}
case .segmented:
if #available(iOS 11.0, *), options.isSafeAreaEnabled {
leftMarginConstraint = containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: options.margin + safeAreaInsets.left)
widthConstraint = containerView.widthAnchor.constraint(equalTo: self.widthAnchor, constant: options.margin * -2 - safeAreaInsets.left - safeAreaInsets.right)
NSLayoutConstraint.activate([
containerView.topAnchor.constraint(equalTo: self.topAnchor),
leftMarginConstraint,
widthConstraint,
heightConstraint
])
} else {
leftMarginConstraint = containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: options.margin)
widthConstraint = containerView.widthAnchor.constraint(equalTo: self.widthAnchor, constant: options.margin * -2)
NSLayoutConstraint.activate([
containerView.topAnchor.constraint(equalTo: self.topAnchor),
leftMarginConstraint,
widthConstraint,
heightConstraint
])
}
contentSize = .zero
}
}
private func updateSelectedItem(by newIndex: Int) {
for (i, itemView) in itemViews.enumerated() {
itemView.isSelected = i == newIndex
}
}
}
// MARK: - AdditionView
extension TabView {
public enum Direction {
case forward
case reverse
}
fileprivate func setupAdditionView() {
if itemViews.isEmpty { return }
switch options.addition {
case .underline:
let itemView = itemViews[currentIndex]
additionView = UIView(frame: CGRect(x: itemView.frame.origin.x + options.additionView.padding.left, y: itemView.frame.height - options.additionView.padding.vertical, width: itemView.frame.width - options.additionView.padding.horizontal, height: options.additionView.underline.height))
additionView.backgroundColor = options.additionView.backgroundColor
containerView.addSubview(additionView)
case .circle:
let itemView = itemViews[currentIndex]
let height = itemView.bounds.height - options.additionView.padding.vertical
additionView = UIView(frame: CGRect(x: itemView.frame.origin.x + options.additionView.padding.left, y: 0, width: itemView.frame.width - options.additionView.padding.horizontal, height: height))
additionView.layer.position.y = itemView.layer.position.y
additionView.layer.cornerRadius = options.additionView.circle.cornerRadius ?? additionView.frame.height / 2
additionView.backgroundColor = options.additionView.backgroundColor
if #available(iOS 11.0, *) {
if let m = options.additionView.circle.maskedCorners {
additionView.layer.maskedCorners = m
}
} else {
var cornerMask = UIRectCorner()
if let maskedCorners = options.additionView.circle.maskedCorners
{
if(maskedCorners.contains(.layerMinXMinYCorner)){
cornerMask.insert(.topLeft)
}
if(maskedCorners.contains(.layerMaxXMinYCorner)){
cornerMask.insert(.topRight)
}
if(maskedCorners.contains(.layerMinXMaxYCorner)){
cornerMask.insert(.bottomLeft)
}
if(maskedCorners.contains(.layerMaxXMaxYCorner)){
cornerMask.insert(.bottomRight)
}
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: cornerMask, cornerRadii: CGSize(width: options.additionView.circle.cornerRadius ?? additionView.frame.height / 2, height: options.additionView.circle.cornerRadius ?? additionView.frame.height / 2))
let mask = CAShapeLayer()
mask.path = path.cgPath
additionView.layer.mask = mask
}
}
containerView.addSubview(additionView)
containerView.sendSubviewToBack(additionView)
case .none:
additionView.backgroundColor = .clear
}
jump(to: currentIndex)
}
private func updateAdditionViewPosition(index: Int) {
guard let target = currentItem else { return }
additionView.frame.origin.x = target.frame.origin.x + options.additionView.padding.left
if options.needsAdjustItemViewWidth {
let cellWidth = itemViews[index].frame.width
additionView.frame.size.width = cellWidth - options.additionView.padding.horizontal
}
focus(on: target)
}
fileprivate func resetAdditionViewPosition(index: Int) {
guard options.style == .segmented,
let dataSource = dataSource,
dataSource.numberOfItems(in: self) > 0 else { return }
let adjustCellWidth: CGFloat
if #available(iOS 11.0, *), options.isSafeAreaEnabled && safeAreaInsets != .zero {
adjustCellWidth = (frame.width - options.margin * 2 - safeAreaInsets.left - safeAreaInsets.right) / CGFloat(dataSource.numberOfItems(in: self)) - options.additionView.padding.horizontal
} else {
adjustCellWidth = (frame.width - options.margin * 2) / CGFloat(dataSource.numberOfItems(in: self)) - options.additionView.padding.horizontal
}
additionView.frame.origin.x = adjustCellWidth * CGFloat(index) - options.additionView.padding.left
additionView.frame.size.width = adjustCellWidth
}
fileprivate func animateAdditionView(index: Int, animated: Bool, completion: ((Bool) -> Swift.Void)? = nil) {
update(index)
if animated {
UIView.animate(withDuration: options.additionView.animationDuration, animations: {
self.updateAdditionViewPosition(index: index)
}, completion: completion)
} else {
updateAdditionViewPosition(index: index)
}
}
func moveAdditionView(index: Int, ratio: CGFloat, direction: Direction) {
update(index)
guard let currentItem = currentItem else { return }
if options.additionView.isAnimationOnSwipeEnable {
switch direction {
case .forward:
additionView.frame.origin.x = currentItem.frame.origin.x + (nextItem.frame.origin.x - currentItem.frame.origin.x) * ratio + options.additionView.padding.left
additionView.frame.size.width = currentItem.frame.size.width + (nextItem.frame.size.width - currentItem.frame.size.width) * ratio - options.additionView.padding.horizontal
if options.needsConvertTextColorRatio {
nextItem.titleLabel.textColor = options.itemView.textColor.convert(to: options.itemView.selectedTextColor, multiplier: ratio)
currentItem.titleLabel.textColor = options.itemView.selectedTextColor.convert(to: options.itemView.textColor, multiplier: ratio)
}
case .reverse:
additionView.frame.origin.x = previousItem.frame.origin.x + (currentItem.frame.origin.x - previousItem.frame.origin.x) * ratio + options.additionView.padding.left
additionView.frame.size.width = previousItem.frame.size.width + (currentItem.frame.size.width - previousItem.frame.size.width) * ratio - options.additionView.padding.horizontal
if options.needsConvertTextColorRatio {
previousItem.titleLabel.textColor = options.itemView.selectedTextColor.convert(to: options.itemView.textColor, multiplier: ratio)
currentItem.titleLabel.textColor = options.itemView.textColor.convert(to: options.itemView.selectedTextColor, multiplier: ratio)
}
}
} else {
moveTabItem(index: index, animated: true)
}
if options.itemView.selectedTextColor.convert(to: options.itemView.textColor, multiplier: ratio) == nil {
updateSelectedItem(by: currentIndex)
}
focus(on: additionView, animated: false)
}
}
extension TabView {
var currentItem: TabItemViewProtocol? {
return currentIndex < itemViews.count ? itemViews[currentIndex] : nil
}
var nextItem: TabItemViewProtocol {
if currentIndex < itemViews.count - 1 {
return itemViews[currentIndex + 1]
}
return itemViews[currentIndex]
}
var previousItem: TabItemViewProtocol {
if currentIndex > 0 {
return itemViews[currentIndex - 1]
}
return itemViews[currentIndex]
}
func jump(to index: Int) {
update(index)
guard let currentItem = currentItem else { return }
if options.addition == .underline {
additionView.frame.origin.x = currentItem.frame.origin.x + options.additionView.padding.left
additionView.frame.size.width = currentItem.frame.size.width - options.additionView.padding.horizontal
}
focus(on: currentItem, animated: false)
}
}
// MARK: - GestureRecognizer
extension TabView {
fileprivate var tapGestureRecognizer: UITapGestureRecognizer {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapItemView(_:)))
gestureRecognizer.numberOfTapsRequired = 1
gestureRecognizer.cancelsTouchesInView = false
return gestureRecognizer
}
fileprivate func addTabItemGestures() {
itemViews.forEach {
$0.addGestureRecognizer(tapGestureRecognizer)
}
}
@objc func tapItemView(_ recognizer: UITapGestureRecognizer) {
guard let itemView = recognizer.view,
let index: Int = (itemViews as [UIView]).firstIndex(of: itemView),
currentIndex != index else { return }
tabViewDelegate?.tabView(self, willSelectTabAt: index)
moveTabItem(index: index, animated: true)
update(index)
tabViewDelegate?.tabView(self, didSelectTabAt: index)
}
private func moveTabItem(index: Int, animated: Bool) {
switch options.addition {
case .underline, .circle:
animateAdditionView(index: index, animated: animated, completion: nil)
case .none:
update(index)
}
}
}
| 42.839721 | 296 | 0.628752 |
8f2084b5bc2b7189c5bc53dca862e4268139bde5 | 3,047 | //
// ImageSectionView.swift
// 0610
//
// Created by Chris on 2019/6/11.
// Copyright © 2019 user. All rights reserved.
//
import UIKit
//import Kingfisher
import SwifterSwift
import Alamofire
import AlamofireImage
protocol ImageSectionViewDelegate: class {
func sectionView(_ sectionView: ImageSectionView, _ didPressTag: Int, _ isExpand: Bool)
}
class ImageSectionView: UITableViewHeaderFooterView {
weak var delegate: ImageSectionViewDelegate?
var buttonTag: Int!
var isExpand: Bool! // cell 的狀態(展開/縮合)
var imageStr: String? {
didSet {
if let imageStr = imageStr, let url = URL(string: imageStr) {
//
// let imageView = UIImageView(frame: frame)
// let placeholderImage = UIImage(named: "placeholder")!
let filter = ScaledToSizeFilter(size: sectionImageView.frame.size)
// let filter = AspectScaledToFillSizeWithRoundedCornersFilter(
// size: cellImageView.frame.size,
// radius: 20.0
// )
sectionImageView.af_setImage(
withURL: url,
placeholderImage: UIImage.init(color: .white, size: CGSize.zero),
filter: filter,
imageTransition: .crossDissolve(0.2)
)
// let processor = DownsamplingImageProcessor(size: sectionImageView.frame.size)
//
// sectionImageView.kf.indicatorType = .activity
// sectionImageView.kf.setImage(
// with: url,
// placeholder: nil,
// options: [
// .processor(processor),
// .scaleFactor(UIScreen.main.scale),
// .transition(.fade(1)),
// .cacheOriginalImage
// ])
// {
// result in
// switch result {
// case .success(let value):
// log.info("Task done for: \(value.source.url?.absoluteString ?? "")")
// case .failure(let error):
// log.error("Job failed: \(error.localizedDescription)")
// }
// }
} else {
sectionImageView.image = UIImage(named: "image-placeholder-icon")
}
}
}
@IBOutlet weak var sectionImageView: UIImageView!
@IBAction func clickImageButton(_ sender: UIButton) {
self.delegate?.sectionView(self, self.buttonTag, self.isExpand)
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override func prepareForReuse() {
super.prepareForReuse()
}
}
| 32.073684 | 95 | 0.519856 |
4b6f780fa34fec3e829174dcc009542bef225696 | 316 | //
// ImageStylerApp.swift
// ImageStyler
//
// Created by Roman Mazeev on 06.03.2020.
// Copyright © 2020 Roman Mazeev. All rights reserved.
//
import SwiftUI
@main
struct ImageStylerApp: App {
var body: some Scene {
WindowGroup {
ContentView(viewModel: ViewModel())
}
}
}
| 16.631579 | 55 | 0.623418 |
623023401344d2b57a74968612877067454bc87e | 3,790 | //
// CategoriesView.swift
// SubscriptionManager
//
// Created by Aitor Zubizarreta Perez on 02/01/2021.
// Copyright © 2021 Aitor Zubizarreta. All rights reserved.
//
import SwiftUI
struct CategoriesView: View {
// MARK: - Properties
@Binding var selectedCategory: SubscriptionsViewModel.subscriptionCategory
@State private var selectedCategoryIndex: Int
private var categoryList: [String]
private var navBarTitle: String = ""
// MARK: - Methods
init(value: Binding<SubscriptionsViewModel.subscriptionCategory>) {
self._selectedCategory = value
self._selectedCategoryIndex = State(wrappedValue: -1)
self.categoryList = []
for category in SubscriptionsViewModel.subscriptionCategory.allCases {
self.categoryList.append(category.rawValue)
}
self.localizeText()
}
///
/// Localize UI text elements.
///
private mutating func localizeText() {
// Get strings from localizable.
self.navBarTitle = NSLocalizedString("categories", comment: "")
}
///
/// Checks if category is selected and returns a boolean.
/// - Parameter index : The index
/// - Returns : True if the category is selected and false otherwise.
///
private func isSelected(index: Int) -> Bool {
if self.selectedCategory.rawValue == self.categoryList[index] {
return true
} else {
return false
}
}
///
/// Updates the index of the selected category.
/// - Parameter newIndex : The new index of the selected category.
///
private func updateCategory(newIndex: Int) {
self.selectedCategoryIndex = newIndex
switch self.selectedCategoryIndex {
case 1:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.video
case 2:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.music
case 3:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.software
case 4:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.gaming
case 5:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.news
case 6:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.ecommerce
case 7:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.phone
case 8:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.internet
case 9:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.rent
case 10:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.gym
case 11:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.education
default:
self.selectedCategory = SubscriptionsViewModel.subscriptionCategory.video
}
}
// MARK: - View
var body: some View {
ScrollView {
ForEach(1..<self.categoryList.count, id: \.self) { index in
Button(action: {
self.selectedCategoryIndex = index
self.updateCategory(newIndex: index)
}) {
CategoryElement(text: self.categoryList[index], selected: self.isSelected(index: index))
}
}
}
.navigationBarTitle(self.navBarTitle)
}
}
struct CategoriesView_Previews: PreviewProvider {
static var previews: some View {
CategoriesView(value: .constant(SubscriptionsViewModel.subscriptionCategory(rawValue: "video")!))
}
}
| 33.539823 | 108 | 0.641161 |
eb921013bf3c5ca08b9bb2c5cb991246daf48a7f | 1,091 | //
// SmallToolbarItem.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2016-09-05.
//
// ---------------------------------------------------------------------------
//
// © 2016-2018 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
class SmallToolbarItem: NSToolbarItem {
// MARK: Toolbar Item Properties
override var minSize: NSSize {
get {
return NSSize(width: 24, height: 24)
}
set {
super.minSize = newValue
}
}
}
| 24.795455 | 79 | 0.595784 |
21a91471bbfa00ff2c54c9d787bae0066ae3e28d | 5,937 | // autogenerated
// swiftlint:disable all
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
extension V1.Apps.ById.PerfPowerMetrics {
public struct GET: Endpoint {
public typealias Response = Data
public var path: String {
"/v1/apps/\(id)/perfPowerMetrics"
}
/// the id of the requested resource
public var id: String
public var parameters: Parameters = Parameters()
public init(id: String) {
self.id = id
}
public func request(with baseURL: URL) throws -> URLRequest? {
var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true)
components?.path = path
components?.queryItems = [
URLQueryItem(name: "filter[deviceType]",
value: parameters.filter[.deviceType]?.map { "\($0)" }.joined(separator: ",")),
URLQueryItem(name: "filter[metricType]",
value: parameters.filter[.metricType]?.map { "\($0)" }.joined(separator: ",")),
URLQueryItem(name: "filter[platform]",
value: parameters.filter[.platform]?.map { "\($0)" }.joined(separator: ","))
].filter { $0.value != nil }
if components?.queryItems?.isEmpty ?? false {
components?.queryItems = nil
}
var urlRequest = components?.url.map { URLRequest(url: $0) }
urlRequest?.httpMethod = "GET"
return urlRequest
}
/// - Returns: **200**, List of PerfPowerMetrics as `Data`
/// - Throws: **400**, Parameter error(s) as `ErrorResponse`
/// - Throws: **403**, Forbidden error as `ErrorResponse`
/// - Throws: **404**, Not found error as `ErrorResponse`
public static func response(from data: Data, urlResponse: HTTPURLResponse) throws -> Response {
var jsonDecoder: JSONDecoder {
let decoder = JSONDecoder()
return decoder
}
switch urlResponse.statusCode {
case 200:
return data
case 400:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
case 403:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
case 404:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
default:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
}
}
}
}
extension V1.Apps.ById.PerfPowerMetrics.GET {
public struct Parameters: Hashable {
public var filter: Filter = Filter()
public struct Filter: Hashable {
public subscript <T: Hashable>(_ relation: Relation<T>) -> T {
get { values[relation]?.base as! T }
set { values[relation] = AnyHashable(newValue) }
}
private var values: [AnyHashable: AnyHashable] = [:]
public enum MetricType: Hashable, Codable, RawRepresentable {
case animation
case battery
case disk
case hang
case launch
case memory
case termination
case unknown(String)
public var rawValue: String {
switch self {
case .animation: return "ANIMATION"
case .battery: return "BATTERY"
case .disk: return "DISK"
case .hang: return "HANG"
case .launch: return "LAUNCH"
case .memory: return "MEMORY"
case .termination: return "TERMINATION"
case .unknown(let rawValue): return rawValue
}
}
public init(rawValue: String) {
switch rawValue {
case "ANIMATION": self = .animation
case "BATTERY": self = .battery
case "DISK": self = .disk
case "HANG": self = .hang
case "LAUNCH": self = .launch
case "MEMORY": self = .memory
case "TERMINATION": self = .termination
default: self = .unknown(rawValue)
}
}
}
public enum Platform: Hashable, Codable, RawRepresentable {
case iOS
case unknown(String)
public var rawValue: String {
switch self {
case .iOS: return "IOS"
case .unknown(let rawValue): return rawValue
}
}
public init(rawValue: String) {
switch rawValue {
case "IOS": self = .iOS
default: self = .unknown(rawValue)
}
}
}
public struct Relation<T>: Hashable {
/// filter by attribute 'deviceType'
public static var deviceType: Relation<[String]?> {
.init(key: "filter[deviceType]")
}
/// filter by attribute 'metricType'
public static var metricType: Relation<[MetricType]?> {
.init(key: "filter[metricType]")
}
/// filter by attribute 'platform'
public static var platform: Relation<[Platform]?> {
.init(key: "filter[platform]")
}
internal let key: String
public func hash(into hasher: inout Hasher) {
hasher.combine(key)
}
}
}
}
}
// swiftlint:enable all
| 34.517442 | 108 | 0.492336 |
bf3794bb2d17769a43f595629309c21e73fdaf35 | 20,524 | /*
Copyright (c) 2017, Tribal Worldwide London
Copyright (c) 2015, Alex Birkett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of kiwi-java nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
// MARK: - Variable *, /, and unary invert
public func * (_ variable: Variable, _ coefficient: Double) -> Term {
return Term(variable: variable, coefficient: coefficient)
.addingDebugDescription("\(variable.name) * \(coefficient)")
}
public func / (_ variable: Variable, _ denominator: Double) -> Term {
return (variable * (1.0 / denominator))
.addingDebugDescription("\(variable.name) / \(denominator)")
}
public prefix func - (_ variable: Variable) -> Term {
return (variable * -1.0)
.addingDebugDescription("-\(variable.name)")
}
// Term *, /, and unary invert
public func * (_ term: Term, _ coefficient: Double) -> Term {
return Term(variable: term.variable, coefficient: term.coefficient * coefficient)
.addingDebugDescription("(\(term.debugDescription)) * \(coefficient)")
}
public func / (_ term: Term, _ denominator: Double) -> Term {
return (term * (1.0 / denominator))
.addingDebugDescription("(\(term.debugDescription)) / \(denominator)")
}
public prefix func - (_ term: Term) -> Term {
return (term * -1.0)
.addingDebugDescription("-(\(term.debugDescription))")
}
// MARK: - Expression *, /, and unary invert
public func * (_ expression: Expression, _ coefficient: Double) -> Expression {
var terms = [Term]()
for term in expression.terms {
terms.append(term * coefficient)
}
// TODO: Do we need to make a copy of the term objects in the array?
return Expression(terms: terms, constant: expression.constant * coefficient)
.addingDebugDescription("(\(expression.debugDescription)) * \(coefficient)")
}
public func * (_ expression1: Expression, _ expression2: Expression) throws -> Expression {
if expression1.isConstant {
return expression1.constant * expression2
} else if expression2.isConstant {
return expression2.constant * expression1
} else {
throw CassowaryError.nonLinear
}
}
public func / (_ expression: Expression, _ denominator: Double) -> Expression {
return (expression * (1.0 / denominator))
.addingDebugDescription("(\(expression.debugDescription)) / \(denominator)")
}
public func / (_ expression1: Expression, _ expression2: Expression) throws -> Expression {
if expression2.isConstant {
return expression1 / expression2.constant
} else {
throw CassowaryError.nonLinear
}
}
public prefix func - (_ expression: Expression) -> Expression {
return (expression * -1.0)
.addingDebugDescription("-(\(expression.debugDescription))")
}
// MARK: - Double *
public func * (_ coefficient: Double, _ expression: Expression) -> Expression {
return (expression * coefficient)
.addingDebugDescription("(\(expression.debugDescription)) * \(coefficient)")
}
public func * (_ coefficient: Double, _ term: Term) -> Term {
return (term * coefficient)
.addingDebugDescription("\(coefficient) * (\(term.debugDescription))")
}
public func * (_ coefficient: Double, _ variable: Variable) -> Term {
return (variable * coefficient)
.addingDebugDescription("\(coefficient) * \(variable.name)")
}
// MARK: - Expression + and -
public func + (_ first: Expression, _ second: Expression) -> Expression {
// TODO: do we need to copy term objects?
var terms = [Term]()
terms.append(contentsOf: first.terms)
terms.append(contentsOf: second.terms)
return Expression(terms: terms, constant: first.constant + second.constant)
.addingDebugDescription("(\(first.debugDescription)) + (\(second.debugDescription))")
}
public func + (_ first: Expression, _ second: Term) -> Expression {
// TODO: do we need to copy term objects?
var terms = [Term]()
terms.append(contentsOf: first.terms)
terms.append(second)
return Expression(terms: terms, constant: first.constant)
.addingDebugDescription("(\(first.debugDescription)) + (\(second.debugDescription))")
}
public func + (_ expression: Expression, _ variable: Variable) -> Expression {
return (expression + Term(variable: variable))
.addingDebugDescription("(\(expression.debugDescription)) + \(variable.name)")
}
public func + (_ expression: Expression, _ constant: Double) -> Expression {
return Expression(terms: expression.terms, constant: expression.constant + constant)
.addingDebugDescription("(\(expression.debugDescription))¨ + \(constant)")
}
public func - (_ first: Expression, _ second: Expression) -> Expression {
return (first + -second)
.addingDebugDescription("(\(first.debugDescription)) - (\(second.debugDescription))")
}
public func - (_ expression: Expression, _ term: Term) -> Expression {
return (expression + -term)
.addingDebugDescription("(\(expression.debugDescription)) - (\(term.debugDescription))")
}
public func - (_ expression: Expression, _ variable: Variable) -> Expression{
return (expression + -variable)
.addingDebugDescription("(\(expression.debugDescription)) - \(variable.name)")
}
public func - (_ expression: Expression, _ constant: Double) -> Expression{
return (expression + -constant)
.addingDebugDescription("(\(expression.debugDescription)) - \(constant)")
}
// MARK: - Term + and -
public func + (_ term: Term, _ expression: Expression) -> Expression {
return (expression + term)
.addingDebugDescription("(\(term.debugDescription)) + (\(expression.debugDescription))")
}
public func + (_ first: Term, _ second: Term) -> Expression {
var terms = [Term]()
terms.append(first)
terms.append(second)
return Expression(terms: terms)
.addingDebugDescription("(\(first.debugDescription)) + (\(second.debugDescription))")
}
public func + (_ term: Term, _ variable: Variable) -> Expression {
return (term + Term(variable: variable))
.addingDebugDescription("(\(term.debugDescription)) + \(variable.name)")
}
public func + (_ term: Term, _ constant: Double) -> Expression {
return Expression(term: term, constant: constant)
.addingDebugDescription("(\(term.debugDescription)) + \(constant)")
}
public func - (_ term: Term, _ expression: Expression) -> Expression {
return (-expression + term)
.addingDebugDescription("(\(term.debugDescription)) - (\(expression.debugDescription))")
}
public func - (_ first: Term, _ second: Term) -> Expression {
return (first + -second)
.addingDebugDescription("(\(first.debugDescription)) - (\(second.debugDescription))")
}
public func - (_ term: Term, _ variable: Variable) -> Expression {
return (term + -variable)
.addingDebugDescription("(\(term.debugDescription)) - \(variable.name)")
}
public func - (_ term: Term, _ constant: Double) -> Expression {
return (term + -constant)
.addingDebugDescription("(\(term.debugDescription)) - \(constant)")
}
// MARK: - Variable + and -
public func + (_ variable: Variable, _ expression: Expression) -> Expression {
return (expression + variable)
.addingDebugDescription("\(variable.name) + (\(expression.debugDescription))")
}
public func + (_ variable: Variable, _ term: Term) -> Expression {
return (term + variable)
.addingDebugDescription("\(variable.name) + (\(term.debugDescription))")
}
public func + (_ first: Variable, _ second: Variable) -> Expression {
return (Term(variable: first) + second)
.addingDebugDescription("\(first.name) + \(second.name)")
}
public func + (_ variable: Variable, _ constant: Double) -> Expression {
return (Term(variable: variable) + constant)
.addingDebugDescription("\(variable.name) + \(constant)")
}
public func - (_ variable: Variable, _ expression: Expression) -> Expression {
return (variable + -expression)
.addingDebugDescription("\(variable.name) - (\(expression.debugDescription))")
}
public func - (_ variable: Variable, _ term: Term) -> Expression {
return (variable + -term)
.addingDebugDescription("\(variable.name) - (\(term.debugDescription))")
}
public func - (_ first: Variable, _ second: Variable) -> Expression {
return (first + -second)
.addingDebugDescription("\(first.name) - \(second.name)")
}
public func - (_ variable: Variable, _ constant: Double) -> Expression {
return (variable + -constant)
.addingDebugDescription("\(variable.name) - \(constant)")
}
// MARK: - Double + and -
public func + (_ constant: Double, _ expression: Expression) -> Expression {
return (expression + constant)
.addingDebugDescription("\(constant) + (\(expression.debugDescription))")
}
public func + (_ constant: Double, _ term: Term) -> Expression {
return (term + constant)
.addingDebugDescription("\(constant) + (\(term.debugDescription))")
}
public func + (_ constant: Double, _ variable: Variable) -> Expression {
return (variable + constant)
.addingDebugDescription("\(constant) + \(variable.name)")
}
public func - (_ constant: Double, _ expression: Expression) -> Expression {
return (-expression + constant)
.addingDebugDescription("\(constant) - (\(expression.debugDescription))")
}
public func - (_ constant: Double, _ term: Term) -> Expression {
return (-term + constant)
.addingDebugDescription("\(constant) - (\(term.debugDescription))")
}
public func - (_ constant: Double, _ variable: Variable) -> Expression {
return (-variable + constant)
.addingDebugDescription("\(constant) - \(variable.name)")
}
// MARK: - Expression relations
public func == (_ first: Expression, _ second: Expression) -> Constraint {
return Constraint(expr: first - second, op: .equal)
.addingDebugDescription("\(first.debugDescription) == \(second.debugDescription)")
}
public func == (_ expression: Expression, _ term: Term) -> Constraint {
return (expression == Expression(term: term))
.addingDebugDescription("\(expression.debugDescription) == \(term.debugDescription)")
}
public func == (_ expression: Expression, _ variable: Variable) -> Constraint {
return (expression == Term(variable: variable))
.addingDebugDescription("\(expression.debugDescription) == \(variable.name)")
}
public func == (_ expression: Expression, _ constant: Double) -> Constraint {
return (expression == Expression(constant: constant))
.addingDebugDescription("\(expression.debugDescription) == \(constant)")
}
public func <= (_ first: Expression, _ second: Expression) -> Constraint {
return Constraint(expr: first - second, op: .lessThanOrEqual)
.addingDebugDescription("\(first.debugDescription) <= \(second.debugDescription)")
}
public func <= (_ expression: Expression, _ term: Term) -> Constraint {
return (expression <= Expression(term: term))
.addingDebugDescription("\(expression.debugDescription) <=>= \(term.debugDescription)")
}
public func <= (_ expression: Expression, _ variable: Variable) -> Constraint {
return (expression <= Term(variable: variable))
.addingDebugDescription("\(expression.debugDescription) <= \(variable.name)")
}
public func <= (_ expression: Expression, _ constant: Double) -> Constraint {
return (expression <= Expression(constant: constant))
.addingDebugDescription("\(expression.debugDescription) <= \(constant)")
}
public func >= (_ first: Expression, _ second: Expression) -> Constraint {
return (Constraint(expr: first - second, op: .greaterThanOrEqual))
.addingDebugDescription("\(first.debugDescription) >= \(second.debugDescription)")
}
public func >= (_ expression: Expression, _ term: Term) -> Constraint {
return (expression >= Expression(term: term))
.addingDebugDescription("\(expression.debugDescription) >= \(term.debugDescription)")
}
public func >= (_ expression: Expression, _ variable: Variable) -> Constraint {
return (expression >= Term(variable: variable))
.addingDebugDescription("\(expression.debugDescription) >= \(variable.name)")
}
public func >= (_ expression: Expression, _ constant: Double) -> Constraint {
return (expression >= Expression(constant: constant))
.addingDebugDescription("\(expression.debugDescription) >= \(constant)")
}
// MARK: - Term relations
public func == (_ term: Term, _ expression: Expression) -> Constraint {
return (expression == term)
.addingDebugDescription("\(term.debugDescription) == \(expression.debugDescription)")
}
public func == (_ first: Term, _ second: Term) -> Constraint {
return (Expression(term: first) == second)
.addingDebugDescription("\(first.debugDescription) == \(second.debugDescription)")
}
public func == (_ term: Term, _ variable: Variable) -> Constraint {
return (Expression(term: term) == variable)
.addingDebugDescription("\(term.debugDescription) == \(variable.value)")
}
public func == (_ term: Term, _ constant: Double) -> Constraint {
return (Expression(term: term) == constant)
.addingDebugDescription("\(term.debugDescription) == \(constant)")
}
public func <= (_ term: Term, _ expression: Expression) -> Constraint {
return (Expression(term: term) <= expression)
.addingDebugDescription("\(term.debugDescription) <= \(expression.debugDescription)")
}
public func <= (_ first: Term, _ second: Term) -> Constraint {
return (Expression(term: first) <= second)
.addingDebugDescription("\(first.debugDescription) <= \(second.debugDescription)")
}
public func <= (_ term: Term, _ variable: Variable) -> Constraint {
return (Expression(term: term) <= variable)
.addingDebugDescription("\(term.debugDescription) <= \(variable.name)")
}
public func <= (_ term: Term, _ constant: Double) -> Constraint {
return (Expression(term: term) <= constant)
.addingDebugDescription("\(term.debugDescription) <= \(constant))")
}
public func >= (_ term: Term, _ expression: Expression) -> Constraint {
return (Expression(term: term) >= expression)
.addingDebugDescription("\(term.debugDescription) >= \(expression.debugDescription)")
}
public func >= (_ first: Term, _ second: Term) -> Constraint {
return (Expression(term: first) >= second)
.addingDebugDescription("\(first.debugDescription) >= \(second.debugDescription)")
}
public func >= (_ term: Term, _ variable: Variable) -> Constraint {
return (Expression(term: term) >= variable)
.addingDebugDescription("\(term.debugDescription) >= \(variable.name)")
}
public func >= (_ term: Term, _ constant: Double) -> Constraint {
return (Expression(term: term) >= constant)
.addingDebugDescription("\(term.debugDescription) >= \(constant)")
}
// MARK: - Variable relations
public func == (_ variable: Variable, _ expression: Expression) -> Constraint {
return (expression == variable)
.addingDebugDescription("\(variable.name) == \(expression.debugDescription)")
}
public func == (_ variable: Variable, _ term: Term) -> Constraint {
return (term == variable)
.addingDebugDescription("\(variable.name) == \(term.debugDescription)")
}
public func == (_ first: Variable, _ second: Variable) -> Constraint {
return (Term(variable: first) == second)
.addingDebugDescription("\(first.name) == \(second.name)")
}
public func == (_ variable: Variable, _ constant: Double) -> Constraint{
return (Term(variable: variable) == constant)
.addingDebugDescription("\(variable.name) == \(constant)")
}
public func <= (_ variable: Variable, _ expression: Expression) -> Constraint {
return (Term(variable: variable) <= expression)
.addingDebugDescription("\(variable.name) <= \(expression.debugDescription)")
}
public func <= (_ variable: Variable, _ term: Term) -> Constraint {
return (Term(variable: variable) <= term)
.addingDebugDescription("\(variable.name) <= \(term.debugDescription)")
}
public func <= (_ first: Variable, _ second: Variable) -> Constraint {
return (Term(variable: first) <= second)
.addingDebugDescription("\(first.name) <= \(second.name)")
}
public func <= (_ variable: Variable, _ constant: Double) -> Constraint {
return (Term(variable: variable) <= constant)
.addingDebugDescription("\(variable.name) <= \(constant)")
}
public func >= (_ variable: Variable, _ expression: Expression) -> Constraint {
return (Term(variable: variable) >= expression)
.addingDebugDescription("\(variable.name) >= \(expression.debugDescription)")
}
public func >= (_ variable: Variable, _ term: Term) -> Constraint {
return (term >= variable)
.addingDebugDescription("\(variable.name) >= \(term.debugDescription)")
}
public func >= (_ first: Variable, _ second: Variable) -> Constraint {
return (Term(variable: first) >= second)
.addingDebugDescription("\(first.name) >= \(second.name)")
}
public func >= (_ variable: Variable, _ constant: Double) -> Constraint {
return (Term(variable: variable) >= constant)
.addingDebugDescription("\(variable.name) >= \(constant)")
}
// MARK: - Double relations
public func == (_ constant: Double, _ expression: Expression) -> Constraint {
return (expression == constant)
.addingDebugDescription("\(constant) == \(expression.debugDescription)")
}
public func == (_ constant: Double, _ term: Term) -> Constraint {
return (term == constant)
.addingDebugDescription("\(constant) == \(term.debugDescription)")
}
public func == (_ constant: Double, _ variable: Variable) -> Constraint {
return (variable == constant)
.addingDebugDescription("\(constant) == \(variable.name)")
}
public func <= (_ constant: Double, _ expression: Expression) -> Constraint {
return (Expression(constant: constant) <= expression)
.addingDebugDescription("\(constant) <= \(expression.debugDescription)")
}
public func <= (_ constant: Double, _ term: Term) -> Constraint {
return (constant <= Expression(term: term))
.addingDebugDescription("\(constant) <= \(term.debugDescription)")
}
public func <= (_ constant: Double, _ variable: Variable) -> Constraint {
return (constant <= Term(variable: variable))
.addingDebugDescription("\(constant) <= \(variable.name)")
}
public func >= (_ constant: Double, _ term: Term) -> Constraint {
return (Expression(constant: constant) >= term)
.addingDebugDescription("\(constant) >= \(term.debugDescription)")
}
public func >= (_ constant: Double, _ variable: Variable) -> Constraint {
return (constant >= Term(variable: variable))
.addingDebugDescription("\(constant) >= \(variable.name)")
}
// MARK: - Constraint strength modifier
public func modifyStrength(_ constraint: Constraint, _ strength: Double) -> Constraint {
return Constraint(other: constraint, strength: strength)
}
public func modifyStrength(_ strength: Double, _ constraint: Constraint) -> Constraint {
return modifyStrength(constraint, strength)
}
| 38.797732 | 96 | 0.684175 |
0981ec0f840f1bc2eb0e96af472978ca85b17659 | 6,387 | import Foundation
import Kitura
import KituraMarkdown
import NaamioCore
/// Routers contains the different types of routers usable
/// within a Naamio application.
struct Routers {
/// The view router manages all of the renderable web
/// pages within an application, including components.
let view: Router
init() {
view = Router()
// Set default view path to template path.
view.viewsPath = Templating.default.path
}
}
/// Routes provides the mechanism for defining routes through
/// context.
class Routes {
static let routers = Routers()
class func defineRoutes() {
let router = Routes.routers.view
let routeHandler = RouteHandler(withRouter: router)
defineAuthMiddleware()
defineHeadersMiddleware()
defineTemplateRoutes()
definePostsRoutes()
defineAssetsRoutes()
defineContentRoutes()
/*
if (FileManager.default.fileExists(atPath: sourcePath)) {
router.all("/", middleware: StaticFileServer(path: sourcePath))
}*/
router.setDefault(templateEngine: Templating.default.engine)
router.add(templateEngine: KituraMarkdown())
Log.trace("\(Templating.default.templates!.routable.count) templates found")
for template in Templating.default.templates!.routable {
let templateName = template.nameWithoutExtension
let path = "\(template.location!)/\(templateName)"
routeHandler.get(template: template)
/*router.get("/\(path)/:id") { request, response, next in
defer {
next()
}
do {
let context: [String: Any] = [
"meta": [
"title": "Naamio"
],
"page": [
"title": templateName
],
"partials": [
"header": true,
"footer": true
],
"data": [
"id": request.parameters["id"]
]
]
try response.render(templateName, context: context).end()
} catch {
Log.error("Failed to render id template \(error)")
}
}*/
}
defineExceptionalRoutes()
}
class func defineAuthMiddleware() {
// This route executes the echo middleware
Routes.routers.view.all(middleware: BasicAuthMiddleware())
}
class func defineHeadersMiddleware() {
Routes.routers.view.all("/*", middleware: HeadersMiddleware())
}
class func defineTemplateRoutes() {
let templatesPath = Configuration.settings.web.templates
if (FileManager.default.fileExists(atPath: templatesPath)) {
Log.info("Templates folder '\(templatesPath)' found. Loading templates")
Routes.routers.view.setDefault(templateEngine: Templating.default.engine)
}
}
private func definePagesRoutes() {
let sourcePath = Configuration.settings.web.source
let pagesPath = sourcePath + "_/pages"
if (FileManager.default.fileExists(atPath: pagesPath)) {
Log.info("Pages folder '\(pagesPath)' found. Loading pages at '/'")
}
}
class func definePostsRoutes() {
let sourcePath = Configuration.settings.web.source
let postsPath = sourcePath + "_/posts"
if (FileManager.default.fileExists(atPath: postsPath)) {
Log.info("Posts folder '\(postsPath)' found. Loading posts at '/posts'")
}
}
class func defineAssetsRoutes() {
let sourcePath = Configuration.settings.web.source
let assetsPath = sourcePath + "/assets"
if (FileManager.default.fileExists(atPath: assetsPath)) {
Log.info("Assets folder '\(assetsPath)' found. Loading static file server at '/assets'")
Routes.routers.view.all("/assets", middleware: StaticFileServer(path: assetsPath))
}
}
class func defineContentRoutes() {
let sourcePath = Configuration.settings.web.source
if (FileManager.default.fileExists(atPath: sourcePath + "/content")) {
Log.info("Content folder /content found. Loading static file server at '/content'")
Routes.routers.view.all("/", middleware: StaticFileServer(path: sourcePath + "/content"))
}
}
class func defineStaticRoutes() {
}
class func defineExceptionalRoutes() {
// Handles any errors that get set
Routes.routers.view.error { request, response, next in
response.headers["content-type"] = "text/plain; charset=utf-8"
let errorDescription: String
if let error = response.error {
errorDescription = "\(error)"
} else {
errorDescription = "Unknown error"
}
try response.send("Caught the error: \(errorDescription)").end()
}
// A custom Not found handler
Routes.routers.view.all { request, response, next in
if response.statusCode == .unknown {
// Remove this wrapping if statement, if you want to handle requests to / as well
if request.originalURL != "/" && request.originalURL != "" {
let context: [String: Any] = [
"meta": [
"title": "Oops!"
],
"not-found": request.originalURL,
"page": [
"title": "404"
],
"partials": [
"header": true,
"footer": true
]
]
Log.trace("404'd on URL: \(request.originalURL)")
try response.status(.notFound).render("40x", context: context).end()
}
}
next()
}
}
init() {
self.definePagesRoutes()
}
}
| 33.265625 | 101 | 0.527478 |
bf659031f6a7fab0fe4e33828de110f9cc40fd06 | 4,184 | //
// Progress+Convenience.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// 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
// MARK: - Progress
public extension Progress {
/**
Sets a closure that the `Progress` calls whenever its `fractionCompleted` changes. You can use this instead of setting up KVO.
- parameter closure: the closure to execute on progress change
*/
@nonobjc
public func setProgressHandler(_ closure: ((_ progress: Progress) -> Void)?) {
self.progressObserver.progressHandler = closure
}
// MARK: Private
private struct PropertyKeys {
static var progressObserver: Void?
}
@nonobjc
private var progressObserver: ProgressObserver {
get {
let object: ProgressObserver? = cs_getAssociatedObjectForKey(&PropertyKeys.progressObserver, inObject: self)
if let observer = object {
return observer
}
let observer = ProgressObserver(self)
cs_setAssociatedRetainedObject(
observer,
forKey: &PropertyKeys.progressObserver,
inObject: self
)
return observer
}
}
}
// MARK: - ProgressObserver
@objc
private final class ProgressObserver: NSObject {
private unowned let progress: Progress
fileprivate var progressHandler: ((_ progress: Progress) -> Void)? {
didSet {
let progressHandler = self.progressHandler
if (progressHandler == nil) == (oldValue == nil) {
return
}
if let _ = progressHandler {
self.progress.addObserver(
self,
forKeyPath: #keyPath(Progress.fractionCompleted),
options: [.initial, .new],
context: nil
)
}
else {
self.progress.removeObserver(self, forKeyPath: #keyPath(Progress.fractionCompleted))
}
}
}
fileprivate init(_ progress: Progress) {
self.progress = progress
super.init()
}
deinit {
if let _ = self.progressHandler {
self.progressHandler = nil
self.progress.removeObserver(self, forKeyPath: #keyPath(Progress.fractionCompleted))
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let progress = object as? Progress,
progress == self.progress,
keyPath == #keyPath(Progress.fractionCompleted) else {
return
}
DispatchQueue.main.async { [weak self] () -> Void in
self?.progressHandler?(progress)
}
}
}
| 30.100719 | 151 | 0.587476 |
6abf44a5efb27824b6667fec135fcdb27fdbac52 | 1,402 | import XCTest
class TODOerUITests: XCTestCase {
override func setUpWithError() throws {
try super.setUpWithError()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
try super.tearDownWithError()
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 36.894737 | 182 | 0.655492 |
d5335f82c97de82dd0f8634031b9373af6db7a9c | 17,463 | // Copyright (c) Mustafa Khalil. and contributors.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
import LCLabel
import SnapshotTesting
import XCTest
// Screenshots taken on an iPhone 13
final class LCLabelTests: XCTestCase {
func testTextCenterAlignment() {
let attStr = NSMutableAttributedString(
string: "LCLabel is a low cost label",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: 300, height: 40))
label.numberOfLines = 1
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testTextTopAlignment() {
let attStr = NSMutableAttributedString(
string: "LCLabel is a low cost label",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: 300, height: 40))
label.numberOfLines = 1
label.textAlignment = .top
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testTextBottomAlignment() {
let attStr = NSMutableAttributedString(
string: "LCLabel is a low cost label",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: 300, height: 40))
label.numberOfLines = 1
label.textAlignment = .bottom
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testLongText() {
let attStr = NSMutableAttributedString(
string: "LCLabel is a low cost label with long text that is supposed to trunculate",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: 300, height: 40))
label.numberOfLines = 1
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testLongTextWithDifferentLineBreakMode() {
let attStr = NSMutableAttributedString(
string: "LCLabel is a low cost label with long text that is supposed to trunculate",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: 300, height: 40))
label.numberOfLines = 1
label.lineBreakMode = .byTruncatingMiddle
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testTextPadding() {
let attStr = NSMutableAttributedString(
string: "LCLabel is a low cost label that can be padded",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: 300, height: 40))
label.numberOfLines = 1
label.textInsets = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30)
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testInstagramLabelMimic() {
let attStr = NSMutableAttributedString(
string: "LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
attStr.append(NSAttributedString(
string: "\nOpen Source",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 8),
]))
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: 300, height: 40))
label.numberOfLines = 2
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testLineFragmentPadding() {
let attStr = NSMutableAttributedString(
string: "LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
attStr.append(NSAttributedString(
string: "\nOpen Source",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 8),
]))
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: 300, height: 40))
label.lineFragmentPadding = 10
label.numberOfLines = 0
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testTwitterLabelMimic() {
let attStr = NSMutableAttributedString(
string: "LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
attStr.append(NSAttributedString(
string: "\n@LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 10),
]))
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: 300, height: 40))
label.numberOfLines = 2
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testLinkEnsure() {
let attStr = NSMutableAttributedString(
string: "LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
attStr.append(NSAttributedString(
string: "\n@LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 10),
.link: URL(string: "lclabel://welcome")!,
]))
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: 300, height: 40))
label.numberOfLines = 2
label.linkStyleValidation = .ensure
let text = label.attributedText
let range = NSRange(location: 0, length: attStr.length)
text?.enumerateAttribute(.link, in: range, using: { value, range, _ in
XCTAssertNil(value, "Should never return anything here!")
})
}
func testLinkEnsureWithLinkAttributes() {
let attStr = NSMutableAttributedString(
string: "LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
attStr.append(NSAttributedString(
string: "\n@LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 10),
.link: URL(string: "lclabel://welcome")!,
]))
let label = LCLabel(frame: .zero)
label.frame = CGRect(x: 0, y: 0, width: 300, height: 40)
label.textAlignment = .center
label.numberOfLines = 2
label.linkStyleValidation = .ensure
label.attributedText = attStr
label.linkAttributes = [
.foregroundColor: UIColor.green,
.font: UIFont.systemFont(ofSize: 12),
]
let text = label.attributedText
let range = (text!.string as NSString).range(of: "@LCLabel")
text?.enumerateAttributes(in: range, using: { attr, range, _ in
XCTAssertEqual(
(attr[.font] as? UIFont)?.pointSize, 12.0)
})
}
func testSettingAttributesFirst() {
let attStr = NSMutableAttributedString(
string: "LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
attStr.append(NSAttributedString(
string: "\n@LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 10),
.link: URL(string: "lclabel://welcome")!,
]))
let label = LCLabel(frame: .zero)
label.frame = CGRect(x: 0, y: 0, width: 300, height: 40)
label.textAlignment = .center
label.numberOfLines = 2
label.linkStyleValidation = .ensure
label.linkAttributes = [
.foregroundColor: UIColor.green,
.font: UIFont.systemFont(ofSize: 12),
]
label.attributedText = attStr
let text = label.attributedText
let range = (text!.string as NSString).range(of: "@LCLabel")
text?.enumerateAttributes(in: range, using: { attr, range, _ in
XCTAssertEqual(
(attr[.font] as? UIFont)?.pointSize, 12.0)
XCTAssertEqual(
(attr[.lclabelLink] as? URL)?.absoluteString, "lclabel://welcome")
})
}
func testString() {
let attStr = NSMutableAttributedString(
string: "LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
attStr.append(NSAttributedString(
string: "\n@LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 10),
.link: "lclabel://welcome",
]))
let label = LCLabel(frame: .zero)
label.frame = CGRect(x: 0, y: 0, width: 300, height: 40)
label.textAlignment = .center
label.numberOfLines = 2
label.linkStyleValidation = .ensure
label.linkAttributes = [
.foregroundColor: UIColor.green,
.font: UIFont.systemFont(ofSize: 12),
]
label.attributedText = attStr
label.shouldExcludeUnderlinesFromText = true
let text = label.attributedText
let range = (text!.string as NSString).range(of: "@LCLabel")
text?.enumerateAttributes(in: range, using: { attr, range, _ in
XCTAssertEqual(
attr[.lclabelLink] as? String, "lclabel://welcome")
})
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testStringWithoutValidations() {
let attStr = NSMutableAttributedString(
string: "LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
attStr.append(NSAttributedString(
string: "\n@LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 10),
.link: "lclabel://welcome",
]))
let label = LCLabel(frame: .zero)
label.frame = CGRect(x: 0, y: 0, width: 300, height: 40)
label.textAlignment = .center
label.numberOfLines = 2
label.shouldExcludeUnderlinesFromText = false
label.linkStyleValidation = .skip
label.linkAttributes = [
.foregroundColor: UIColor.green,
.font: UIFont.systemFont(ofSize: 12),
]
label.attributedText = attStr
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testSuperLongText() {
let text = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Aliquet bibendum enim facilisis gravida neque. Orci a scelerisque purus semper eget duis at. Viverra justo nec ultrices dui sapien eget mi proin. Etiam non quam lacus suspendisse faucibus. Vel fringilla est ullamcorper eget nulla facilisi etiam. Donec enim diam vulputate ut pharetra sit amet aliquam id. Ipsum faucibus vitae aliquet nec ullamcorper sit amet risus. Ultrices gravida dictum fusce ut. Nulla aliquet porttitor lacus luctus accumsan tortor posuere ac. Turpis egestas sed tempus urna et pharetra. Pellentesque nec nam aliquam sem et tortor consequat. Risus sed vulputate odio ut enim blandit volutpat maecenas. Ullamcorper velit sed ullamcorper morbi tincidunt ornare massa. Blandit massa enim nec dui nunc mattis enim ut. Tristique sollicitudin nibh sit amet.
"""
let attr: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
]
let attStr = NSMutableAttributedString(
string: text,
attributes: attr)
let width: CGFloat = 300
let size = (attStr.string as NSString).boundingRect(
with: CGSize(width: width, height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: attr,
context: nil)
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: width, height: size.height))
label.numberOfLines = 0
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testWithinStackView() {
let attStr = NSMutableAttributedString(
string: "LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
attStr.append(NSAttributedString(
string: "\n@LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 10),
.link: "lclabel://welcome",
]))
let label = LCLabel(frame: .zero)
label.textAlignment = .center
label.numberOfLines = 2
label.backgroundColor = .green
label.linkStyleValidation = .ensure
label.linkAttributes = [
.foregroundColor: UIColor.green,
.font: UIFont.systemFont(ofSize: 12),
]
label.attributedText = attStr
label.shouldExcludeUnderlinesFromText = true
let purpleView = UIView()
purpleView.backgroundColor = .systemPurple
let stackView = UIStackView(arrangedSubviews: [
label,
purpleView,
])
stackView.distribution = .fillEqually
stackView.translatesAutoresizingMaskIntoConstraints = false
let view = UIView(
frame: CGRect(
x: 0,
y: 0,
width: 300,
height: 40))
view.addSubview(stackView)
view.backgroundColor = .red
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: view.topAnchor),
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
let failure = verifySnapshot(
matching: view,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
func testHiddingView() {
let attStr = NSMutableAttributedString(
string: "LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
])
attStr.append(NSAttributedString(
string: "\n@LCLabel",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 10),
.link: "lclabel://welcome",
]))
let label = LCLabel(frame: .zero)
label.textAlignment = .center
label.numberOfLines = 2
label.backgroundColor = .green
label.linkStyleValidation = .ensure
label.linkAttributes = [
.foregroundColor: UIColor.green,
.font: UIFont.systemFont(ofSize: 12),
]
label.attributedText = attStr
label.shouldExcludeUnderlinesFromText = true
let purpleView = UIView()
purpleView.backgroundColor = .systemPurple
let stackView = UIStackView(arrangedSubviews: [
label,
purpleView,
])
stackView.translatesAutoresizingMaskIntoConstraints = false
let view = UIView(
frame: CGRect(
x: 0,
y: 0,
width: 300,
height: 40))
view.addSubview(stackView)
view.backgroundColor = .red
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: view.topAnchor),
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
label.attributedText = nil
let failure = verifySnapshot(
matching: view,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}
private func createLabel(
text: NSMutableAttributedString,
frame: CGRect,
alignment: LCLabel.Alignment = .center,
numberOfLines: Int = 1) -> LCLabel
{
let label = LCLabel(frame: .zero)
label.frame = frame
label.textAlignment = alignment
label.isUserInteractionEnabled = true
label.numberOfLines = 1
label.attributedText = text
return label
}
}
extension XCTestCase {
var path: String {
let fileUrl = URL(fileURLWithPath: #file, isDirectory: false)
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
return "\(fileUrl.path)/Sources/LCLabel/LCLabel.docc/Resources/__snapshots__"
}
}
| 32.398887 | 900 | 0.649831 |
9c33634b5ce4caa823107d2ab637a8203ee3237c | 361 | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "LibraryName",
// platforms: [.iOS("8.0"), .tvOS("9.0")],
products: [
.library(name: "LKAlertController", targets: ["LKAlertController"])
],
targets: [
.target(
name: "LKAlertController",
path: "Pod"
)
]
)
| 21.235294 | 75 | 0.542936 |
01e9ced9c8f0462f2b0d9363ff2ddaee62f42e1c | 1,438 | //
// UIAlertController+.swift
// Elegant
//
// Created by Steve on 2017/5/24.
// Copyright © 2017年 KingCQ. All rights reserved.
//
import UIKit
/// Show alert
///
/// - Parameters:
/// - title: message title
/// - message: message content
/// - cancelAction: cancel callback
/// - okAction: okcallback
public func alert(
title: String,
message: String,
cancelAction: ((UIAlertAction?) -> Void)? = nil,
okAction: ((UIAlertAction?) -> Void)? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
if let ok = okAction {
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: ok))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: cancelAction))
} else {
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: cancelAction))
}
UIWindow.visibleViewController.present(alert, animated: true, completion: nil)
}
/// Show actionSheet
///
/// - Parameters:
/// - title: message title
/// - message: message content
/// - actions: The set of the actions
public func actionSheet(
title: String,
message: String,
actions: [UIAlertAction]) {
let sheet = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
actions.forEach({ sheet.addAction($0) })
UIWindow.visibleViewController.present(sheet, animated: true, completion: nil)
}
| 30.595745 | 95 | 0.668985 |
d554adfbb2d7bb320714220e7f18a6cadc0ebfd3 | 608 | //
// ViewController.swift
// UISliderExample
//
// Created by Soeng Saravit on 11/14/18.
// Copyright © 2018 Soeng Saravit. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var valueLabel: UILabel!
@IBOutlet weak var slider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func sliderValueChanged(_ sender: Any) {
let value = slider.value
valueLabel.text = String(format: "%.2f", value)
}
}
| 21.714286 | 80 | 0.65625 |
2351a68fd9eef13f512f1b2b9702f2f2c3bf826b | 2,432 | //
// RestCall.swift
// IBMFlightTracker
//
// Created by Sanjeev Ghimire on 3/14/17.
// Copyright © 2017 Sanjeev Ghimire. All rights reserved.
//
import Foundation
import SwiftyJSON
class RestCall {
private static let WEATHER_API_USERNAME : String = "<username>"
private static let WEATHER_API_PASSWORD : String = "<password>"
func fetchWeatherBasedOnCurrentLocation(latitude: String, longitude: String, completion: @escaping (_ result: [String: Any]) -> Void){
var weatherData : [String : Any] = [:]
let url:String = self.getURL(latitude: latitude, longitude: longitude)
guard let endpointURL = URL(string: url) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: endpointURL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling weather api")
print(error!)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
let weatherJson = JSON(data: responseData)
let observation : [String : Any] = weatherJson["observation"].dictionaryObject!
weatherData["city"] = observation["obs_name"]
weatherData["temperature"] = observation["temp"]
weatherData["description"] = observation["wx_phrase"]
let weatherIconUrl:String = "http://weather-company-data-demo.mybluemix.net/images/weathericons/icon\(observation["wx_icon"]!).png"
weatherData["weatherIconUrl"] = weatherIconUrl
completion(weatherData)
}
task.resume()
}
func getURL(latitude: String, longitude: String) -> String{
let url: String = "https://\(RestCall.WEATHER_API_USERNAME):\(RestCall.WEATHER_API_PASSWORD)@twcservice.mybluemix.net/api/weather/v1/geocode/\(latitude)/\(longitude)/observations.json?units=e&language=en-US"
return url
}
}
| 31.584416 | 216 | 0.564145 |
ef524d8329a75b5094b4f6a27e0803bfc6e3fa75 | 618 | import ImSDK_Smart;
// 朋友实体
public class FriendInfoResultEntity : NSObject{
/**
* ID
*/
var resultCode : Int32?;
var resultInfo : String?;
var relation : Int?;
var friendInfo : [String: Any]?;
override init() {
}
init(friendInfoResult : V2TIMFriendInfoResult) {
super.init();
self.resultCode = friendInfoResult.resultCode;
self.resultInfo = friendInfoResult.resultInfo;
self.relation = friendInfoResult.relation.rawValue;
self.friendInfo = V2FriendInfoEntity.getDict(info: friendInfoResult.friendInfo);
}
}
| 22.888889 | 89 | 0.634304 |
280a39f57b8dff61bcc7288888809158c142c97a | 3,455 | //
// TypeInstanceCache.swift
// FastAdapter
//
// Created by Fabian Terhorst on 12.07.18.
// Copyright © 2018 everHome. All rights reserved.
//
public class TypeInstanceCache<Itm: Item> {
weak var fastAdapter: FastAdapter<Itm>?
var typeInstances = [String: Itm]()
var supplementaryViewTypeInstances = [String: [String: Itm]]()
public init() {
}
public func register(items: [Itm]) -> Bool {
var allRegistered = true
for item in items {
if !register(item: item) {
allRegistered = false
}
}
return allRegistered
}
public func register(item: Itm) -> Bool {
let typeId = item.getType()
if typeInstances.index(forKey: typeId) == nil {
typeInstances[typeId] = item
_register(typeId: typeId, item: item)
return true
}
return false
}
public func register(item: Itm, forSupplementaryViewOfKind: String) -> Bool {
let typeId = item.getType()
let typeInstances = supplementaryViewTypeInstances[forSupplementaryViewOfKind]
if typeInstances == nil {
supplementaryViewTypeInstances[forSupplementaryViewOfKind] = [String: Itm]()
}
if typeInstances?.index(forKey: typeId) == nil {
supplementaryViewTypeInstances[forSupplementaryViewOfKind]?[typeId] = item
_register(typeId: typeId, item: item, forSupplementaryViewOfKind: forSupplementaryViewOfKind)
return true
}
return false
}
private func _register(typeId: String, item: Itm) {
if let listView = fastAdapter?.listView {
if let nib = item.getNib() {
listView.registerCell(nib, forCellWithReuseIdentifier: typeId)
} else {
listView.registerCell(item.getViewClass(), forCellWithReuseIdentifier: typeId)
}
}
}
private func _register(typeId: String, item: Itm, forSupplementaryViewOfKind: String) {
if let listView = fastAdapter?.listView {
if let nib = item.getNib() {
listView.registerCell(nib, forSupplementaryViewOfKind: forSupplementaryViewOfKind, withReuseIdentifier: typeId)
} else {
listView.registerCell(item.getViewClass(), forSupplementaryViewOfKind: forSupplementaryViewOfKind, withReuseIdentifier: typeId)
}
}
}
public subscript(typeId: String) -> Item? {
return typeInstances[typeId]
}
func clear() {
typeInstances.removeAll()
supplementaryViewTypeInstances.removeAll()
}
func renew() {
var registeredCells = fastAdapter?.listView?.registeredCells
for (typeId, item) in typeInstances {
if registeredCells == nil || registeredCells?.contains(typeId) == false {
if registeredCells == nil {
registeredCells = Set<String>()
}
registeredCells?.insert(typeId)
_register(typeId: typeId, item: item)
}
}
fastAdapter?.listView?.registeredCells = registeredCells
for (kind, typeInstances) in supplementaryViewTypeInstances {
for (typeId, item) in typeInstances {
_register(typeId: typeId, item: item, forSupplementaryViewOfKind: kind)
}
}
}
}
| 34.207921 | 143 | 0.601447 |
5b6858e3427e56985b8374be7da9ee9dd2f0e259 | 271 | //
// CGRect+Center.swift
// MaterialActivityIndicator
//
// Created by Jans Pavlovs on 13.02.18.
// Copyright (c) 2018 Jans Pavlovs. All rights reserved.
//
import UIKit
extension CGRect {
var center: CGPoint {
return CGPoint(x: midX, y: midY)
}
}
| 16.9375 | 57 | 0.653137 |
ac4a6eb10324293ca3165e6f554448557db3af20 | 710 | //
// TimersList.swift
// MultiTimer WatchKit Extension
//
// Created by Michael Salmon on 2019-08-27.
// Copyright © 2019 mesme. All rights reserved.
//
import SwiftUI
class TimersList: ObservableObject, Identifiable {
let id = UUID()
@Published
var list: [SingleTimer]
func addTimer(_ duration: TimeInterval, _ color: Color = .clear) {
list.append(SingleTimer(duration, color).resume())
}
func rmTimer(_ timer: SingleTimer) {
for index in list.indices where timer.id == list[index].id {
timer.passivate()
list.remove(at: index)
break
}
}
init(_ list: [SingleTimer] = []) {
self.list = list
}
}
| 21.515152 | 70 | 0.605634 |
756192c450e42fbd7b410e000d86f2e2d11c333a | 5,953 | //
// ReviewViewController.swift
// WeScan
//
// Created by Boris Emorine on 2/25/18.
// Copyright © 2018 WeTransfer. All rights reserved.
//
import UIKit
/// The `ReviewViewController` offers an interface to review the image after it has been cropped and deskwed according to the passed in quadrilateral.
final class ReviewViewController: UIViewController {
private var rotationAngle = Measurement<UnitAngle>(value: 0, unit: .degrees)
private var enhancedImageIsAvailable = false
private var isCurrentlyDisplayingEnhancedImage = false
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.clipsToBounds = true
imageView.isOpaque = true
imageView.image = results.scannedImage
imageView.backgroundColor = .black
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
lazy private var enhanceButton: UIBarButtonItem = {
let image = UIImage(named: "enhance", in: Bundle(for: ScannerViewController.self), compatibleWith: nil)
let button = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(toggleEnhancedImage))
button.tintColor = .white
return button
}()
lazy private var rotateButton: UIBarButtonItem = {
let image = UIImage(named: "rotate", in: Bundle(for: ScannerViewController.self), compatibleWith: nil)
let button = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(rotateImage))
button.tintColor = .white
return button
}()
lazy private var doneButton: UIBarButtonItem = {
let button = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(finishScan))
button.tintColor = navigationController?.navigationBar.tintColor
return button
}()
private let results: ImageScannerResults
// MARK: - Life Cycle
init(results: ImageScannerResults) {
self.results = results
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
enhancedImageIsAvailable = results.enhancedImage != nil
setupViews()
setupToolbar()
setupConstraints()
title = NSLocalizedString("wescan.review.title", tableName: nil, bundle: Bundle(for: ReviewViewController.self), value: "Review", comment: "The review title of the ReviewController")
navigationItem.rightBarButtonItem = doneButton
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// We only show the toolbar (with the enhance button) if the enhanced image is available.
if enhancedImageIsAvailable {
navigationController?.setToolbarHidden(false, animated: true)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setToolbarHidden(true, animated: true)
}
// MARK: Setups
private func setupViews() {
view.addSubview(imageView)
}
private func setupToolbar() {
guard enhancedImageIsAvailable else { return }
navigationController?.toolbar.barStyle = .blackTranslucent
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbarItems = [fixedSpace, enhanceButton, flexibleSpace, rotateButton, fixedSpace]
}
private func setupConstraints() {
let imageViewConstraints = [
imageView.topAnchor.constraint(equalTo: view.topAnchor),
imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
view.bottomAnchor.constraint(equalTo: imageView.bottomAnchor),
view.leadingAnchor.constraint(equalTo: imageView.leadingAnchor)
]
NSLayoutConstraint.activate(imageViewConstraints)
}
// MARK: - Actions
@objc private func reloadImage() {
if enhancedImageIsAvailable, isCurrentlyDisplayingEnhancedImage {
imageView.image = results.enhancedImage?.rotated(by: rotationAngle) ?? results.enhancedImage
} else {
imageView.image = results.scannedImage.rotated(by: rotationAngle) ?? results.scannedImage
}
}
@objc private func toggleEnhancedImage() {
guard enhancedImageIsAvailable else { return }
reloadImage()
if isCurrentlyDisplayingEnhancedImage {
enhanceButton.tintColor = .white
} else {
enhanceButton.tintColor = UIColor(red: 64 / 255, green: 159 / 255, blue: 255 / 255, alpha: 1.0)
}
isCurrentlyDisplayingEnhancedImage.toggle()
}
@objc func rotateImage() {
rotationAngle.value += 90
if rotationAngle.value == 360 {
rotationAngle.value = 0
}
reloadImage()
}
@objc private func finishScan() {
guard let imageScannerController = navigationController as? ImageScannerController else { return }
var newResults = results
newResults.scannedImage = results.scannedImage.rotated(by: rotationAngle) ?? results.scannedImage
newResults.enhancedImage = results.enhancedImage?.rotated(by: rotationAngle) ?? results.enhancedImage
newResults.doesUserPreferEnhancedImage = isCurrentlyDisplayingEnhancedImage
imageScannerController.imageScannerDelegate?.imageScannerController(imageScannerController, didFinishScanningWithResults: newResults)
}
}
| 37.20625 | 190 | 0.670082 |
2260ba754a99d846587bf7535c0df30f16792054 | 882 | //
// OBOtherFeeChargeDetailType.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Other Fee/charge type which is not available in the standard code set */
public struct OBOtherFeeChargeDetailType: Codable {
public var code: OBCodeMnemonic?
public var feeCategory: OBFeeCategory1Code
public var name: Name3
public var _description: Description3
public init(code: OBCodeMnemonic?, feeCategory: OBFeeCategory1Code, name: Name3, _description: Description3) {
self.code = code
self.feeCategory = feeCategory
self.name = name
self._description = _description
}
public enum CodingKeys: String, CodingKey {
case code = "Code"
case feeCategory = "FeeCategory"
case name = "Name"
case _description = "Description"
}
}
| 23.837838 | 114 | 0.689342 |
9b2721e7a5be0bb2ff7e8ffd0615d48fb01c8f9e | 687 | //
// AutoTextView.swift
// SpringApp
//
// Created by Meng To on 2015-03-27.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
public class AutoTextView: UITextView {
public override var intrinsicContentSize: CGSize {
get {
var size = self.sizeThatFits(CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
size.width = self.frame.size.width
if text.count == 0 {
size.height = 0
}
contentInset = UIEdgeInsets(top: -4, left: -4, bottom: -4, right: -4)
layoutIfNeeded()
return size
}
}
}
| 24.535714 | 119 | 0.561863 |
c1e6ef30b1db860b395ebd309c0abf661d22ee0a | 204 | //
// Interactorable.swift
// RxSwiftVIPER
//
// Created by 林 翼 on 2018/11/20.
// Copyright © 2018年 Tsubasa Hayashi. All rights reserved.
//
import Foundation
protocol Interactorable {
// nop
}
| 14.571429 | 59 | 0.676471 |
0856361d8a0bbdc6f190e23558b8a54ab436b729 | 4,471 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
// The version number for the regex. This gets emitted as an argument to the
// Regex(_regexString:version:) initializer and should be bumped if the format
// of the regex string needs to be changed in such a that requires the runtime
// to updated.
public let currentRegexLiteralFormatVersion = 1
@_spi(CompilerInterface)
public struct CompilerLexError: Error {
public var message: String
public var location: UnsafeRawPointer
public var completelyErroneous: Bool
}
/// Interface for the Swift compiler.
///
/// Attempt to lex a regex literal string.
///
/// - Parameters:
/// - start: The pointer at which to start lexing the literal.
/// - bufferEnd: A pointer to the end of the buffer, which should not be lexed
/// past.
/// - mustBeRegex: Whether we expect a regex literal to be lexed here. If
/// `false`, a regex literal will only be lexed if it does not
/// produce an error.
///
/// - Returns: If a regex literal was lexed, `resumePtr` specifies where to
/// resume lexing and `error` specifies a lexing error to emit. If
/// a regex literal was not lexed, `nil` is returned.
///
@_spi(CompilerInterface)
public func swiftCompilerLexRegexLiteral(
start: UnsafeRawPointer, bufferEnd: UnsafeRawPointer, mustBeRegex: Bool
) -> (resumePtr: UnsafeRawPointer, error: CompilerLexError?)? {
do {
let (_, _, endPtr) = try lexRegex(start: start, end: bufferEnd)
return (resumePtr: endPtr, error: nil)
} catch let error as DelimiterLexError {
if !mustBeRegex {
// This token can be something else. Let the client fallback.
return nil
}
let completelyErroneous: Bool
switch error.kind {
case .unterminated, .multilineClosingNotOnNewline:
// These can be recovered from.
completelyErroneous = false
case .unprintableASCII, .invalidUTF8:
// We don't currently have good recovery behavior for these.
completelyErroneous = true
case .unknownDelimiter:
// An unknown delimiter should be recovered from, as we may want to try
// lex something else.
return nil
}
// For now every lexer error is emitted at the starting delimiter.
let compilerError = CompilerLexError(
message: "\(error)", location: start,
completelyErroneous: completelyErroneous
)
return (error.resumePtr, compilerError)
} catch {
fatalError("Should be a DelimiterLexError")
}
}
@_spi(CompilerInterface)
public struct CompilerParseError: Error {
public var message: String
public var location: String.Index?
}
/// Interface for the Swift compiler.
///
/// Attempt to parse a regex literal string.
///
/// - Parameters:
/// - input: The regex input string, including delimiters.
/// - captureBufferOut: A buffer into which the captures of the regex will
/// be encoded into upon a successful parse.
///
/// - Returns: The string to emit along with its version number.
/// - Throws: `CompilerParseError` if there was a parsing error.
@_spi(CompilerInterface)
public func swiftCompilerParseRegexLiteral(
_ input: String, captureBufferOut: UnsafeMutableRawBufferPointer
) throws -> (regexToEmit: String, version: Int) {
do {
let ast = try parseWithDelimiters(input)
// Serialize the capture structure for later type inference.
assert(captureBufferOut.count >= input.utf8.count)
ast.captureStructure.encode(to: captureBufferOut)
// For now we just return the input as the regex to emit. This could be
// changed in the future if need to back-deploy syntax to something already
// known to the matching engine, or otherwise change the format. Note
// however that it will need plumbing through on the compiler side.
return (regexToEmit: input, version: currentRegexLiteralFormatVersion)
} catch {
throw CompilerParseError(
message: "cannot parse regular expression: \(String(describing: error))",
location: (error as? LocatedErrorProtocol)?.location.start
)
}
}
| 38.543103 | 80 | 0.679714 |
675d84aab16069be3f5eb48d90c9cc81dabea4e7 | 861 | import Foundation
/// https://developer.twitter.com/en/docs/twitter-api/v1/direct-messages/typing-indicator-and-read-receipts/api-reference/new-read-receipt
open class PostDirectMessagesMarkReadRequestV1: TwitterAPIRequest {
/// Message ID
public let lastReadEventID: String
/// User ID
public let recipientID: String
public var method: HTTPMethod {
return .post
}
public var path: String {
return "/1.1/direct_messages/mark_read.json"
}
open var parameters: [String: Any] {
var p = [String: Any]()
p["last_read_event_id"] = lastReadEventID
p["recipient_id"] = recipientID
return p
}
public init(
lastReadEventID: String,
recipientID: String
) {
self.lastReadEventID = lastReadEventID
self.recipientID = recipientID
}
}
| 23.27027 | 138 | 0.652729 |
9b6462589651f3780b54fd2222cbd619b10c6b5d | 1,684 | // The MIT License (MIT)
//
// Copyright (c) 2020 Reflect Code Technologies (OPC) Pvt. Ltd. (http://ReflectCode.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public class ImageData {
private var image_title: String? = ""
private var image_id: Int? = 0
open func getImage_title() -> String?{
return self.image_title
}
open func setImage_title(_ image_name: String?) -> Void {
self.image_title = image_name!
}
open func getImage_ID() -> Int?{
return self.image_id
}
open func setImage_ID(_ android_image_url: Int?) -> Void {
self.image_id = android_image_url!
}
}
| 38.272727 | 100 | 0.72209 |
29c877739c290e97525bdcfba0143ba757bfb70b | 8,444 | /*
This source file is part of the Swift.org open source project
Copyright 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 Swift project authors
*/
import libc
import func POSIX.getenv
import class Foundation.FileHandle
import class Foundation.FileManager
public enum TempFileError: Swift.Error {
/// Could not create a unique temporary filename.
case couldNotCreateUniqueName
/// Some error thrown defined by posix's open().
// FIXME: This should be factored out into a open error enum.
case other(Int32)
}
private extension TempFileError {
init(errno: Int32) {
switch errno {
case libc.EEXIST:
self = .couldNotCreateUniqueName
default:
self = .other(errno)
}
}
}
/// Determines the directory in which the temporary file should be created. Also makes
/// sure the returning path has a trailing forward slash.
///
/// - Parameters:
/// - dir: If present this will be the temporary directory.
///
/// - Returns: Path to directory in which temporary file should be created.
private func determineTempDirectory(_ dir: AbsolutePath? = nil) -> AbsolutePath {
// FIXME: Add other platform specific locations.
let tmpDir = dir ?? cachedTempDirectory
// FIXME: This is a runtime condition, so it should throw and not crash.
precondition(localFileSystem.isDirectory(tmpDir))
return tmpDir
}
/// Returns temporary directory location by searching relevant env variables.
/// Evaluates once per execution.
private var cachedTempDirectory: AbsolutePath = {
return AbsolutePath(getenv("TMPDIR") ?? getenv("TEMP") ?? getenv("TMP") ?? "/tmp/")
}()
/// This class is basically a wrapper over posix's mkstemps() function to creates disposable files.
/// The file is deleted as soon as the object of this class is deallocated.
public final class TemporaryFile {
/// If specified during init, the temporary file name begins with this prefix.
let prefix: String
/// If specified during init, the temporary file name ends with this suffix.
let suffix: String
/// The directory in which the temporary file is created.
public let dir: AbsolutePath
/// The full path of the temporary file. For safety file operations should be done via the fileHandle instead of using this path.
public let path: AbsolutePath
/// The file descriptor of the temporary file. It is used to create NSFileHandle which is exposed to clients.
private let fd: Int32
/// FileHandle of the temporary file, can be used to read/write data.
public let fileHandle: FileHandle
/// Creates an instance of Temporary file. The temporary file will live on disk until the instance
/// goes out of scope.
///
/// - Parameters:
/// - dir: If specified the temporary file will be created in this directory otherwise enviornment variables
/// TMPDIR, TEMP and TMP will be checked for a value (in that order). If none of the env variables are
/// set, dir will be set to `/tmp/`.
/// - prefix: The prefix to the temporary file name.
/// - suffix: The suffix to the temporary file name.
///
/// - Throws: TempFileError
public init(dir: AbsolutePath? = nil, prefix: String = "TemporaryFile", suffix: String = "") throws {
self.suffix = suffix
self.prefix = prefix
// Determine in which directory to create the temporary file.
self.dir = determineTempDirectory(dir)
// Construct path to the temporary file.
let path = self.dir.appending(RelativePath(prefix + ".XXXXXX" + suffix))
// Convert path to a C style string terminating with null char to be an valid input
// to mkstemps method. The XXXXXX in this string will be replaced by a random string
// which will be the actual path to the temporary file.
var template = [UInt8](path.asString.utf8).map{ Int8($0) } + [Int8(0)]
fd = libc.mkstemps(&template, Int32(suffix.utf8.count))
// If mkstemps failed then throw error.
if fd == -1 { throw TempFileError(errno: errno) }
self.path = AbsolutePath(String(cString: template))
fileHandle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
}
/// Remove the temporary file before deallocating.
deinit {
unlink(path.asString)
}
}
extension TemporaryFile: CustomStringConvertible {
public var description: String {
return "<TemporaryFile: \(path)>"
}
}
/// Contains the error which can be thrown while creating a directory using POSIX's mkdir.
//
// FIXME: This isn't right place to declare this, probably POSIX or merge with FileSystemError?
public enum MakeDirectoryError: Swift.Error {
/// The given path already exists as a directory, file or symbolic link.
case pathExists
/// The path provided was too long.
case pathTooLong
/// Process does not have permissions to create directory.
/// Note: Includes read-only filesystems or if file system does not support directory creation.
case permissionDenied
/// The path provided is unresolvable because it has too many symbolic links or a path component is invalid.
case unresolvablePathComponent
/// Exceeded user quota or kernel is out of memory.
case outOfMemory
/// All other system errors with their value.
case other(Int32)
}
private extension MakeDirectoryError {
init(errno: Int32) {
switch errno {
case libc.EEXIST:
self = .pathExists
case libc.ENAMETOOLONG:
self = .pathTooLong
case libc.EACCES, libc.EFAULT, libc.EPERM, libc.EROFS:
self = .permissionDenied
case libc.ELOOP, libc.ENOENT, libc.ENOTDIR:
self = .unresolvablePathComponent
case libc.ENOMEM, libc.EDQUOT:
self = .outOfMemory
default:
self = .other(errno)
}
}
}
/// A class to create disposable directories using POSIX's mkdtemp() method.
public final class TemporaryDirectory {
/// If specified during init, the temporary directory name begins with this prefix.
let prefix: String
/// The full path of the temporary directory.
public let path: AbsolutePath
/// If true, try to remove the whole directory tree before deallocating.
let removeTreeOnDeinit: Bool
/// Creates a temporary directory which is automatically removed when the object of this class goes out of scope.
///
/// - Parameters:
/// - dir: If specified the temporary directory will be created in this directory otherwise enviornment variables
/// TMPDIR, TEMP and TMP will be checked for a value (in that order). If none of the env variables are
/// set, dir will be set to `/tmp/`.
/// - prefix: The prefix to the temporary file name.
/// - removeTreeOnDeinit: If enabled try to delete the whole directory tree otherwise remove only if its empty.
///
/// - Throws: MakeDirectoryError
public init(dir: AbsolutePath? = nil, prefix: String = "TemporaryDirectory", removeTreeOnDeinit: Bool = false) throws {
self.removeTreeOnDeinit = removeTreeOnDeinit
self.prefix = prefix
// Construct path to the temporary directory.
let path = determineTempDirectory(dir).appending(RelativePath(prefix + ".XXXXXX"))
// Convert path to a C style string terminating with null char to be an valid input
// to mkdtemp method. The XXXXXX in this string will be replaced by a random string
// which will be the actual path to the temporary directory.
var template = [UInt8](path.asString.utf8).map{ Int8($0) } + [Int8(0)]
if libc.mkdtemp(&template) == nil {
throw MakeDirectoryError(errno: errno)
}
self.path = AbsolutePath(String(cString: template))
}
/// Remove the temporary file before deallocating.
deinit {
if removeTreeOnDeinit {
let _ = try? FileManager.default.removeItem(atPath: path.asString)
} else {
rmdir(path.asString)
}
}
}
extension TemporaryDirectory: CustomStringConvertible {
public var description: String {
return "<TemporaryDirectory: \(path)>"
}
}
| 39.643192 | 133 | 0.679417 |
220df4fd69489a5738b0c2a9235021a9be483635 | 38,367 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
import BuildServerProtocol
import Dispatch
import Foundation
import IndexStoreDB
import LanguageServerProtocol
import LSPLogging
import SKCore
import SKSupport
import TSCBasic
import TSCLibc
import TSCUtility
public typealias URL = Foundation.URL
/// The SourceKit language server.
///
/// This is the client-facing language server implementation, providing indexing, multiple-toolchain
/// and cross-language support. Requests may be dispatched to language-specific services or handled
/// centrally, but this is transparent to the client.
public final class SourceKitServer: LanguageServer {
struct LanguageServiceKey: Hashable {
var toolchain: String
var language: Language
}
let options: Options
let toolchainRegistry: ToolchainRegistry
var languageService: [LanguageServiceKey: ToolchainLanguageServer] = [:]
/// Documents that are ready for requests and notifications.
/// This generally means that the `BuildSystem` has notified of us of build settings.
var documentsReady: Set<DocumentURI> = []
private var documentToPendingQueue: [DocumentURI: DocumentNotificationRequestQueue] = [:]
public var workspace: Workspace?
let fs: FileSystem
var onExit: () -> Void
/// Creates a language server for the given client.
public init(client: Connection, fileSystem: FileSystem = localFileSystem, options: Options, onExit: @escaping () -> Void = {}) {
self.fs = fileSystem
self.toolchainRegistry = ToolchainRegistry.shared
self.options = options
self.onExit = onExit
super.init(client: client)
}
public override func _registerBuiltinHandlers() {
_register(SourceKitServer.initialize)
_register(SourceKitServer.clientInitialized)
_register(SourceKitServer.cancelRequest)
_register(SourceKitServer.shutdown)
_register(SourceKitServer.exit)
registerWorkspaceNotfication(SourceKitServer.openDocument)
registerWorkspaceNotfication(SourceKitServer.closeDocument)
registerWorkspaceNotfication(SourceKitServer.changeDocument)
registerToolchainTextDocumentNotification(SourceKitServer.willSaveDocument)
registerToolchainTextDocumentNotification(SourceKitServer.didSaveDocument)
registerWorkspaceRequest(SourceKitServer.workspaceSymbols)
registerWorkspaceRequest(SourceKitServer.pollIndex)
registerWorkspaceRequest(SourceKitServer.executeCommand)
registerToolchainTextDocumentRequest(SourceKitServer.completion,
CompletionList(isIncomplete: false, items: []))
registerToolchainTextDocumentRequest(SourceKitServer.hover, nil)
registerToolchainTextDocumentRequest(SourceKitServer.definition, .locations([]))
registerToolchainTextDocumentRequest(SourceKitServer.references, [])
registerToolchainTextDocumentRequest(SourceKitServer.implementation, .locations([]))
registerToolchainTextDocumentRequest(SourceKitServer.symbolInfo, [])
registerToolchainTextDocumentRequest(SourceKitServer.documentSymbolHighlight, nil)
registerToolchainTextDocumentRequest(SourceKitServer.foldingRange, nil)
registerToolchainTextDocumentRequest(SourceKitServer.documentSymbol, nil)
registerToolchainTextDocumentRequest(SourceKitServer.documentColor, [])
registerToolchainTextDocumentRequest(SourceKitServer.colorPresentation, [])
registerToolchainTextDocumentRequest(SourceKitServer.codeAction, nil)
}
/// Register a `TextDocumentRequest` that requires a valid `Workspace`, `ToolchainLanguageServer`,
/// and open file with resolved (yet potentially invalid) build settings.
func registerToolchainTextDocumentRequest<PositionRequest: TextDocumentRequest>(
_ requestHandler: @escaping (SourceKitServer) ->
(Request<PositionRequest>, Workspace, ToolchainLanguageServer) -> Void,
_ fallback: PositionRequest.Response
) {
_register { [unowned self] (req: Request<PositionRequest>) in
guard let workspace = self.workspace else {
return req.reply(.failure(.serverNotInitialized))
}
let doc = req.params.textDocument.uri
// This should be created as soon as we receive an open call, even if the document
// isn't yet ready.
guard let languageService = workspace.documentService[doc] else {
return req.reply(fallback)
}
// If the document is ready, we can handle it right now.
guard !self.documentsReady.contains(doc) else {
requestHandler(self)(req, workspace, languageService)
return
}
// Not ready to handle it, we'll queue it and handle it later.
self.documentToPendingQueue[doc, default: DocumentNotificationRequestQueue()].add(operation: {
[weak self] in
guard let self = self else { return }
requestHandler(self)(req, workspace, languageService)
}, cancellationHandler: {
req.reply(fallback)
})
}
}
/// Register a `TextDocumentNotification` that requires a valid
/// `ToolchainLanguageServer` and open file with resolved (yet
/// potentially invalid) build settings.
func registerToolchainTextDocumentNotification<TextNotification: TextDocumentNotification>(
_ notificationHandler: @escaping (SourceKitServer) ->
(Notification<TextNotification>, ToolchainLanguageServer) -> Void
) {
_register { [unowned self] (note: Notification<TextNotification>) in
guard let workspace = self.workspace else {
return
}
let doc = note.params.textDocument.uri
// This should be created as soon as we receive an open call, even if the document
// isn't yet ready.
guard let languageService = workspace.documentService[doc] else {
return
}
// If the document is ready, we can handle it right now.
guard !self.documentsReady.contains(doc) else {
notificationHandler(self)(note, languageService)
return
}
// Not ready to handle it, we'll queue it and handle it later.
self.documentToPendingQueue[doc, default: DocumentNotificationRequestQueue()].add(operation: {
[weak self] in
guard let self = self else { return }
notificationHandler(self)(note, languageService)
})
}
}
/// Register a request handler which requires a valid `Workspace`. If called before a valid
/// `Workspace` exists, this will immediately fail the request.
func registerWorkspaceRequest<R>(
_ requestHandler: @escaping (SourceKitServer) -> (Request<R>, Workspace) -> Void)
{
_register { [unowned self] (req: Request<R>) in
guard let workspace = self.workspace else {
return req.reply(.failure(.serverNotInitialized))
}
requestHandler(self)(req, workspace)
}
}
/// Register a notification handler which requires a valid `Workspace`. If called before a
/// valid `Workspace` exists, the notification is ignored and an error is logged.
func registerWorkspaceNotfication<N>(
_ noteHandler: @escaping (SourceKitServer) -> (Notification<N>, Workspace) -> Void)
{
_register { [unowned self] (note: Notification<N>) in
guard let workspace = self.workspace else {
log("received notification before \"initialize\", ignoring...", level: .error)
return
}
noteHandler(self)(note, workspace)
}
}
public override func _handleUnknown<R>(_ req: Request<R>) {
if req.clientID == ObjectIdentifier(client) {
return super._handleUnknown(req)
}
// Unknown requests from a language server are passed on to the client.
let id = client.send(req.params, queue: queue) { result in
req.reply(result)
}
req.cancellationToken.addCancellationHandler {
self.client.send(CancelRequestNotification(id: id))
}
}
/// Handle an unknown notification.
public override func _handleUnknown<N>(_ note: Notification<N>) {
if note.clientID == ObjectIdentifier(client) {
return super._handleUnknown(note)
}
// Unknown notifications from a language server are passed on to the client.
client.send(note.params)
}
func toolchain(for uri: DocumentURI, _ language: Language) -> Toolchain? {
let supportsLang = { (toolchain: Toolchain) -> Bool in
// FIXME: the fact that we're looking at clangd/sourcekitd instead of the compiler indicates this method needs a parameter stating what kind of tool we're looking for.
switch language {
case .swift:
return toolchain.sourcekitd != nil
case .c, .cpp, .objective_c, .objective_cpp:
return toolchain.clangd != nil
default:
return false
}
}
if let toolchain = toolchainRegistry.default, supportsLang(toolchain) {
return toolchain
}
for toolchain in toolchainRegistry.toolchains {
if supportsLang(toolchain) {
return toolchain
}
}
return nil
}
func languageService(
for toolchain: Toolchain,
_ language: Language,
in workspace: Workspace
) -> ToolchainLanguageServer? {
let key = LanguageServiceKey(toolchain: toolchain.identifier, language: language)
if let service = languageService[key] {
return service
}
// Start a new service.
return orLog("failed to start language service", level: .error) {
guard let service = try SourceKitLSP.languageService(
for: toolchain, language, options: options, client: self, in: workspace)
else {
return nil
}
let pid = Int(ProcessInfo.processInfo.processIdentifier)
let resp = try service.initializeSync(InitializeRequest(
processId: pid,
rootPath: nil,
rootURI: workspace.rootUri,
initializationOptions: nil,
capabilities: workspace.clientCapabilities,
trace: .off,
workspaceFolders: nil))
// FIXME: store the server capabilities.
let syncKind = resp.capabilities.textDocumentSync?.change ?? .incremental
guard syncKind == .incremental else {
fatalError("non-incremental update not implemented")
}
service.clientInitialized(InitializedNotification())
languageService[key] = service
return service
}
}
func languageService(for uri: DocumentURI, _ language: Language, in workspace: Workspace) -> ToolchainLanguageServer? {
if let service = workspace.documentService[uri] {
return service
}
guard let toolchain = toolchain(for: uri, language),
let service = languageService(for: toolchain, language, in: workspace)
else {
return nil
}
log("Using toolchain \(toolchain.displayName) (\(toolchain.identifier)) for \(uri)")
workspace.documentService[uri] = service
return service
}
}
// MARK: - Build System Delegate
extension SourceKitServer: BuildSystemDelegate {
public func buildTargetsChanged(_ changes: [BuildTargetEvent]) {
// TODO: do something with these changes once build target support is in place
}
private func affectedOpenDocumentsForChangeSet(
_ changes: Set<DocumentURI>,
_ documentManager: DocumentManager
) -> Set<DocumentURI> {
// An empty change set is treated as if all open files have been modified.
guard !changes.isEmpty else {
return documentManager.openDocuments
}
return documentManager.openDocuments.intersection(changes)
}
/// Handle a build settings change notification from the `BuildSystem`.
/// This has two primary cases:
/// - Initial settings reported for a given file, now we can fully open it
/// - Changed settings for an already open file
public func fileBuildSettingsChanged(
_ changedFiles: [DocumentURI: FileBuildSettingsChange]
) {
queue.async {
guard let workspace = self.workspace else {
return
}
let documentManager = workspace.documentManager
let openDocuments = documentManager.openDocuments
for (uri, change) in changedFiles {
// Non-ready documents should be considered open even though we haven't
// opened it with the language service yet.
guard openDocuments.contains(uri) else { continue }
guard self.documentsReady.contains(uri) else {
// Case 1: initial settings for a given file. Now we can process our backlog.
log("Initial build settings received for opened file \(uri)")
guard let service = workspace.documentService[uri] else {
// Unexpected: we should have an existing language service if we've registered for
// change notifications for an opened but non-ready document.
log("No language service for build settings change to non-ready file \(uri)",
level: .error)
// We're in an odd state, cancel pending requests if we have any.
self.documentToPendingQueue[uri]?.cancelAll()
self.documentToPendingQueue[uri] = nil
continue
}
// Notify the language server so it can apply the proper arguments.
service.documentUpdatedBuildSettings(uri, change: change)
// Catch up on any queued notifications and requests.
self.documentToPendingQueue[uri]?.handleAll()
self.documentToPendingQueue[uri] = nil
self.documentsReady.insert(uri)
continue
}
// Case 2: changed settings for an already open file.
log("Build settings changed for opened file \(uri)")
if let service = workspace.documentService[uri] {
service.documentUpdatedBuildSettings(uri, change: change)
}
}
}
}
/// Handle a dependencies updated notification from the `BuildSystem`.
/// We inform the respective language services as long as the given file is open
/// (not queued for opening).
public func filesDependenciesUpdated(_ changedFiles: Set<DocumentURI>) {
queue.async {
guard let workspace = self.workspace else {
return
}
for uri in self.affectedOpenDocumentsForChangeSet(changedFiles, workspace.documentManager) {
// Make sure the document is ready - otherwise the language service won't
// know about the document yet.
guard self.documentsReady.contains(uri) else {
continue
}
log("Dependencies updated for opened file \(uri)")
if let service = workspace.documentService[uri] {
service.documentDependenciesUpdated(uri)
}
}
}
}
}
// MARK: - Request and notification handling
extension SourceKitServer {
// MARK: - General
func initialize(_ req: Request<InitializeRequest>) {
var indexOptions = self.options.indexOptions
if case .dictionary(let options) = req.params.initializationOptions {
if case .bool(let listenToUnitEvents) = options["listenToUnitEvents"] {
indexOptions.listenToUnitEvents = listenToUnitEvents
}
}
// Any messages sent before initialize returns are expected to fail, so this will run before
// the first "supported" request. Run asynchronously to hide the latency of setting up the
// build system and index.
queue.async {
if let uri = req.params.rootURI {
self.workspace = try? Workspace(
rootUri: uri,
clientCapabilities: req.params.capabilities,
toolchainRegistry: self.toolchainRegistry,
buildSetup: self.options.buildSetup,
indexOptions: indexOptions)
} else if let path = req.params.rootPath {
self.workspace = try? Workspace(
rootUri: DocumentURI(URL(fileURLWithPath: path)),
clientCapabilities: req.params.capabilities,
toolchainRegistry: self.toolchainRegistry,
buildSetup: self.options.buildSetup,
indexOptions: indexOptions)
}
if self.workspace == nil {
log("no workspace found", level: .warning)
self.workspace = Workspace(
rootUri: req.params.rootURI,
clientCapabilities: req.params.capabilities,
toolchainRegistry: self.toolchainRegistry,
buildSetup: self.options.buildSetup,
underlyingBuildSystem: nil,
index: nil,
indexDelegate: nil)
}
assert(self.workspace != nil)
self.workspace?.buildSystemManager.delegate = self
}
req.reply(InitializeResult(capabilities: ServerCapabilities(
textDocumentSync: TextDocumentSyncOptions(
openClose: true,
change: .incremental,
willSave: true,
willSaveWaitUntil: false,
save: .value(TextDocumentSyncOptions.SaveOptions(includeText: false))
),
hoverProvider: true,
completionProvider: CompletionOptions(
resolveProvider: false,
triggerCharacters: ["."]
),
definitionProvider: true,
implementationProvider: .bool(true),
referencesProvider: true,
documentHighlightProvider: true,
documentSymbolProvider: true,
workspaceSymbolProvider: true,
codeActionProvider: .value(CodeActionServerCapabilities(
clientCapabilities: req.params.capabilities.textDocument?.codeAction,
codeActionOptions: CodeActionOptions(codeActionKinds: nil),
supportsCodeActions: true
)),
colorProvider: .bool(true),
foldingRangeProvider: .bool(true),
executeCommandProvider: ExecuteCommandOptions(
commands: builtinSwiftCommands // FIXME: Clangd commands?
)
)))
}
func clientInitialized(_: Notification<InitializedNotification>) {
// Nothing to do.
}
func cancelRequest(_ notification: Notification<CancelRequestNotification>) {
let key = RequestCancelKey(client: notification.clientID, request: notification.params.id)
requestCancellation[key]?.cancel()
}
/// The server is about to exit, and the server should flush any buffered state.
///
/// The server shall not be used to handle more requests (other than possibly
/// `shutdown` and `exit`) and should attempt to flush any buffered state
/// immediately, such as sending index changes to disk.
public func prepareForExit() {
// Note: this method should be safe to call multiple times, since we want to
// be resilient against multiple possible shutdown sequences, including
// pipe failure.
// Close the index, which will flush to disk.
self.queue.sync {
self._prepareForExit()
}
}
func _prepareForExit() {
// Note: this method should be safe to call multiple times, since we want to
// be resilient against multiple possible shutdown sequences, including
// pipe failure.
// Close the index, which will flush to disk.
self.workspace?.index = nil
}
func shutdown(_ request: Request<ShutdownRequest>) {
_prepareForExit()
for service in languageService.values {
service.shutdown()
}
languageService = [:]
request.reply(VoidResponse())
}
func exit(_ notification: Notification<ExitNotification>) {
// Should have been called in shutdown, but allow misbehaving clients.
_prepareForExit()
// Call onExit only once, and hop off queue to allow the handler to call us back.
let onExit = self.onExit
self.onExit = {}
DispatchQueue.global().async {
onExit()
}
}
// MARK: - Text synchronization
func openDocument(_ note: Notification<DidOpenTextDocumentNotification>, workspace: Workspace) {
// Immediately open the document even if the build system isn't ready. This is important since
// we check that the document is open when we receive messages from the build system.
workspace.documentManager.open(note.params)
let textDocument = note.params.textDocument
let uri = textDocument.uri
let language = textDocument.language
// If we can't create a service, this document is unsupported and we can bail here.
guard let service = languageService(for: uri, language, in: workspace) else {
return
}
workspace.buildSystemManager.registerForChangeNotifications(for: uri, language: language)
// If the document is ready, we can immediately send the notification.
guard !documentsReady.contains(uri) else {
service.openDocument(note.params)
return
}
// Need to queue the open call so we can handle it when ready.
self.documentToPendingQueue[uri, default: DocumentNotificationRequestQueue()].add(operation: {
service.openDocument(note.params)
})
}
func closeDocument(_ note: Notification<DidCloseTextDocumentNotification>, workspace: Workspace) {
// Immediately close the document. We need to be sure to clear our pending work queue in case
// the build system still isn't ready.
workspace.documentManager.close(note.params)
let uri = note.params.textDocument.uri
workspace.buildSystemManager.unregisterForChangeNotifications(for: uri)
// If the document is ready, we can close it now.
guard !documentsReady.contains(uri) else {
self.documentsReady.remove(uri)
workspace.documentService[uri]?.closeDocument(note.params)
return
}
// Clear any queued notifications via their cancellation handlers.
// No need to send the notification since it was never considered opened.
self.documentToPendingQueue[uri]?.cancelAll()
self.documentToPendingQueue[uri] = nil
}
func changeDocument(_ note: Notification<DidChangeTextDocumentNotification>, workspace: Workspace) {
let uri = note.params.textDocument.uri
// If the document is ready, we can handle the change right now.
guard !documentsReady.contains(uri) else {
workspace.documentManager.edit(note.params)
workspace.documentService[uri]?.changeDocument(note.params)
return
}
// Need to queue the change call so we can handle it when ready.
self.documentToPendingQueue[uri, default: DocumentNotificationRequestQueue()].add(operation: {
workspace.documentManager.edit(note.params)
workspace.documentService[uri]?.changeDocument(note.params)
})
}
func willSaveDocument(
_ note: Notification<WillSaveTextDocumentNotification>,
languageService: ToolchainLanguageServer
) {
languageService.willSaveDocument(note.params)
}
func didSaveDocument(
_ note: Notification<DidSaveTextDocumentNotification>,
languageService: ToolchainLanguageServer
) {
languageService.didSaveDocument(note.params)
}
// MARK: - Language features
func completion(
_ req: Request<CompletionRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer
) {
languageService.completion(req)
}
func hover(
_ req: Request<HoverRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer
) {
languageService.hover(req)
}
/// Find all symbols in the workspace that include a string in their name.
/// - returns: An array of SymbolOccurrences that match the string.
func findWorkspaceSymbols(matching: String) -> [SymbolOccurrence] {
var symbolOccurenceResults: [SymbolOccurrence] = []
workspace?.index?.forEachCanonicalSymbolOccurrence(
containing: matching,
anchorStart: false,
anchorEnd: false,
subsequence: true,
ignoreCase: true
) {symbol in
if !symbol.location.isSystem && !symbol.roles.contains(.accessorOf) {
symbolOccurenceResults.append(symbol)
}
return true
}
return symbolOccurenceResults
}
/// Handle a workspace/symbols request, returning the SymbolInformation.
/// - returns: An array with SymbolInformation for each matching symbol in the workspace.
func workspaceSymbols(_ req: Request<WorkspaceSymbolsRequest>, workspace: Workspace) {
let symbols = findWorkspaceSymbols(
matching: req.params.query
).map({symbolOccurrence -> SymbolInformation in
let symbolPosition = Position(
line: symbolOccurrence.location.line - 1, // 1-based -> 0-based
// FIXME: we need to convert the utf8/utf16 column, which may require reading the file!
utf16index: symbolOccurrence.location.utf8Column - 1)
let symbolLocation = Location(
uri: DocumentURI(URL(fileURLWithPath: symbolOccurrence.location.path)),
range: Range(symbolPosition))
return SymbolInformation(
name: symbolOccurrence.symbol.name,
kind: symbolOccurrence.symbol.kind.asLspSymbolKind(),
deprecated: nil,
location: symbolLocation,
containerName: symbolOccurrence.getContainerName()
)
})
req.reply(symbols)
}
/// Forwards a SymbolInfoRequest to the appropriate toolchain service for this document.
func symbolInfo(
_ req: Request<SymbolInfoRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer
) {
languageService.symbolInfo(req)
}
func documentSymbolHighlight(
_ req: Request<DocumentHighlightRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer
) {
languageService.documentSymbolHighlight(req)
}
func foldingRange(
_ req: Request<FoldingRangeRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer) {
languageService.foldingRange(req)
}
func documentSymbol(
_ req: Request<DocumentSymbolRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer
) {
languageService.documentSymbol(req)
}
func documentColor(
_ req: Request<DocumentColorRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer
) {
languageService.documentColor(req)
}
func colorPresentation(
_ req: Request<ColorPresentationRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer
) {
languageService.colorPresentation(req)
}
func executeCommand(_ req: Request<ExecuteCommandRequest>, workspace: Workspace) {
guard let uri = req.params.textDocument?.uri else {
log("attempted to perform executeCommand request without an url!", level: .error)
req.reply(nil)
return
}
guard let languageService = workspace.documentService[uri] else {
req.reply(nil)
return
}
// If the document isn't yet ready, queue the request.
guard self.documentsReady.contains(uri) else {
self.documentToPendingQueue[uri, default: DocumentNotificationRequestQueue()].add(operation: {
[weak self] in
guard let self = self else { return }
self.fowardExecuteCommand(req, languageService: languageService)
}, cancellationHandler: {
req.reply(nil)
})
return
}
self.fowardExecuteCommand(req, languageService: languageService)
}
func fowardExecuteCommand(
_ req: Request<ExecuteCommandRequest>,
languageService: ToolchainLanguageServer
) {
let params = req.params
let executeCommand = ExecuteCommandRequest(command: params.command,
arguments: params.argumentsWithoutSourceKitMetadata)
let callback = callbackOnQueue(self.queue) { (result: Result<ExecuteCommandRequest.Response, ResponseError>) in
req.reply(result)
}
let request = Request(executeCommand, id: req.id, clientID: ObjectIdentifier(self),
cancellation: req.cancellationToken, reply: callback)
languageService.executeCommand(request)
}
func codeAction(
_ req: Request<CodeActionRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer
) {
let codeAction = CodeActionRequest(range: req.params.range, context: req.params.context,
textDocument: req.params.textDocument)
let callback = callbackOnQueue(self.queue) { (result: Result<CodeActionRequest.Response, ResponseError>) in
switch result {
case .success(let reply):
req.reply(req.params.injectMetadata(toResponse: reply))
default:
req.reply(result)
}
}
let request = Request(codeAction, id: req.id, clientID: ObjectIdentifier(self),
cancellation: req.cancellationToken, reply: callback)
languageService.codeAction(request)
}
func definition(
_ req: Request<DefinitionRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer
) {
let symbolInfo = SymbolInfoRequest(textDocument: req.params.textDocument, position: req.params.position)
let index = self.workspace?.index
// If we're unable to handle the definition request using our index, see if the
// language service can handle it (e.g. clangd can provide AST based definitions).
let resultHandler: ([Location], ResponseError?) -> Void = { (locs, error) in
guard locs.isEmpty else {
req.reply(.locations(locs))
return
}
let handled = languageService.definition(req)
guard !handled else { return }
if let error = error {
req.reply(.failure(error))
} else {
req.reply(.locations([]))
}
}
let callback = callbackOnQueue(self.queue) { (result: Result<SymbolInfoRequest.Response, ResponseError>) in
guard let symbols: [SymbolDetails] = result.success ?? nil, let symbol = symbols.first else {
resultHandler([], result.failure)
return
}
let fallbackLocation = [symbol.bestLocalDeclaration].compactMap { $0 }
guard let usr = symbol.usr, let index = index else {
resultHandler(fallbackLocation, nil)
return
}
log("performing indexed jump-to-def with usr \(usr)")
var occurs = index.occurrences(ofUSR: usr, roles: [.definition])
if occurs.isEmpty {
occurs = index.occurrences(ofUSR: usr, roles: [.declaration])
}
// FIXME: overrided method logic
let locations = occurs.compactMap { occur -> Location? in
if occur.location.path.isEmpty {
return nil
}
return Location(
uri: DocumentURI(URL(fileURLWithPath: occur.location.path)),
range: Range(Position(
line: occur.location.line - 1, // 1-based -> 0-based
// FIXME: we need to convert the utf8/utf16 column, which may require reading the file!
utf16index: occur.location.utf8Column - 1
))
)
}
resultHandler(locations.isEmpty ? fallbackLocation : locations, nil)
}
let request = Request(symbolInfo, id: req.id, clientID: ObjectIdentifier(self),
cancellation: req.cancellationToken, reply: callback)
languageService.symbolInfo(request)
}
// FIXME: a lot of duplication with definition request
func implementation(
_ req: Request<ImplementationRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer
) {
let symbolInfo = SymbolInfoRequest(textDocument: req.params.textDocument, position: req.params.position)
let index = self.workspace?.index
let callback = callbackOnQueue(self.queue) { (result: Result<SymbolInfoRequest.Response, ResponseError>) in
guard let symbols: [SymbolDetails] = result.success ?? nil, let symbol = symbols.first else {
if let error = result.failure {
req.reply(.failure(error))
} else {
req.reply(.locations([]))
}
return
}
guard let usr = symbol.usr, let index = index else {
return req.reply(.locations([]))
}
var occurs = index.occurrences(ofUSR: usr, roles: .baseOf)
if occurs.isEmpty {
occurs = index.occurrences(relatedToUSR: usr, roles: .overrideOf)
}
let locations = occurs.compactMap { occur -> Location? in
if occur.location.path.isEmpty {
return nil
}
return Location(
uri: DocumentURI(URL(fileURLWithPath: occur.location.path)),
range: Range(Position(
line: occur.location.line - 1, // 1-based -> 0-based
// FIXME: we need to convert the utf8/utf16 column, which may require reading the file!
utf16index: occur.location.utf8Column - 1
))
)
}
req.reply(.locations(locations))
}
let request = Request(symbolInfo, id: req.id, clientID: ObjectIdentifier(self),
cancellation: req.cancellationToken, reply: callback)
languageService.symbolInfo(request)
}
// FIXME: a lot of duplication with definition request
func references(
_ req: Request<ReferencesRequest>,
workspace: Workspace,
languageService: ToolchainLanguageServer
) {
let symbolInfo = SymbolInfoRequest(textDocument: req.params.textDocument, position: req.params.position)
let callback = callbackOnQueue(self.queue) { (result: Result<SymbolInfoRequest.Response, ResponseError>) in
guard let symbols: [SymbolDetails] = result.success ?? nil, let symbol = symbols.first else {
if let error = result.failure {
req.reply(.failure(error))
} else {
req.reply([])
}
return
}
guard let usr = symbol.usr, let index = workspace.index else {
req.reply([])
return
}
log("performing indexed jump-to-def with usr \(usr)")
var roles: SymbolRole = [.reference]
if req.params.context.includeDeclaration {
roles.formUnion([.declaration, .definition])
}
let occurs = index.occurrences(ofUSR: usr, roles: roles)
let locations = occurs.compactMap { occur -> Location? in
if occur.location.path.isEmpty {
return nil
}
return Location(
uri: DocumentURI(URL(fileURLWithPath: occur.location.path)),
range: Range(Position(
line: occur.location.line - 1, // 1-based -> 0-based
// FIXME: we need to convert the utf8/utf16 column, which may require reading the file!
utf16index: occur.location.utf8Column - 1
))
)
}
req.reply(locations)
}
let request = Request(symbolInfo, id: req.id, clientID: ObjectIdentifier(self),
cancellation: req.cancellationToken, reply: callback)
languageService.symbolInfo(request)
}
func pollIndex(_ req: Request<PollIndexRequest>, workspace: Workspace) {
workspace.index?.pollForUnitChangesAndWait()
req.reply(VoidResponse())
}
}
private func callbackOnQueue<R: ResponseType>(
_ queue: DispatchQueue,
_ callback: @escaping (LSPResult<R>) -> Void
) -> (LSPResult<R>) -> Void {
return { (result: LSPResult<R>) in
queue.async {
callback(result)
}
}
}
/// Creates a new connection from `client` to a service for `language` if available, and launches
/// the service. Does *not* send the initialization request.
///
/// - returns: The connection, if a suitable language service is available; otherwise nil.
/// - throws: If there is a suitable service but it fails to launch, throws an error.
public func languageService(
for toolchain: Toolchain,
_ language: Language,
options: SourceKitServer.Options,
client: MessageHandler,
in workspace: Workspace) throws -> ToolchainLanguageServer?
{
switch language {
case .c, .cpp, .objective_c, .objective_cpp:
guard toolchain.clangd != nil else { return nil }
return try makeJSONRPCClangServer(client: client, toolchain: toolchain, clangdOptions: options.clangdOptions)
case .swift:
guard let sourcekitd = toolchain.sourcekitd else { return nil }
return try makeLocalSwiftServer(client: client, sourcekitd: sourcekitd, clientCapabilities: workspace.clientCapabilities)
default:
return nil
}
}
public typealias Notification = LanguageServerProtocol.Notification
public typealias Diagnostic = LanguageServerProtocol.Diagnostic
extension IndexSymbolKind {
func asLspSymbolKind() -> SymbolKind {
switch self {
case .class:
return .class
case .classMethod, .instanceMethod, .staticMethod:
return .method
case .instanceProperty, .staticProperty, .classProperty:
return .property
case .enum:
return .enum
case .enumConstant:
return .enumMember
case .protocol:
return .interface
case .function, .conversionFunction:
return .function
case .variable:
return .variable
case .struct:
return .struct
case .parameter:
return .typeParameter
default:
return .null
}
}
}
extension SymbolOccurrence {
/// Get the name of the symbol that is a parent of this symbol, if one exists
func getContainerName() -> String? {
return relations.first(where: { $0.roles.contains(.childOf) })?.symbol.name
}
}
/// Simple struct for pending notifications/requests, including a cancellation handler.
/// For convenience the notifications/request handlers are type erased via wrapping.
private struct NotificationRequestOperation {
let operation: () -> Void
let cancellationHandler: (() -> Void)?
}
/// Used to queue up notifications and requests for documents which are blocked
/// on `BuildSystem` operations such as fetching build settings.
///
/// Note: This is not thread safe. Must be called from the `SourceKitServer.queue`.
private struct DocumentNotificationRequestQueue {
private var queue = [NotificationRequestOperation]()
/// Add an operation to the end of the queue.
mutating func add(operation: @escaping () -> Void, cancellationHandler: (() -> Void)? = nil) {
queue.append(NotificationRequestOperation(operation: operation, cancellationHandler: cancellationHandler))
}
/// Invoke all operations in the queue.
mutating func handleAll() {
for task in queue {
task.operation()
}
queue = []
}
/// Cancel all operations in the queue. No-op for operations without a cancellation
/// handler.
mutating func cancelAll() {
for task in queue {
if let cancellationHandler = task.cancellationHandler {
cancellationHandler()
}
}
queue = []
}
}
| 35.393911 | 173 | 0.688951 |
217bf2ee49aac849b5117056d2d13c5cd408a680 | 19,827 | //
// LocationsViewController.swift
// NoticeMe
//
// Created by 管 皓 on 2018/2/20.
// Copyright © 2018年 Hao Guan. All rights reserved.
//
import UIKit
import RealmSwift
import GoogleMaps
import UserNotifications
class LocationsViewController: UIViewController, UITextFieldDelegate {
let realm = try! Realm()
var currentNotice: Notice? {
didSet {
loadSavedLocations()
}
}
var mapView: GMSMapView?
var locationManager = CLLocationManager()
var markers = [GMSMarker]()
var graphs = [GMSPolygon]()
var graphCreated = false
var savedLocations: Results<CustomLocation>?
@IBOutlet var basicView: UIView!
@IBOutlet var createGraphButton: UIButton!
@IBOutlet var saveButton: UIButton!
@IBOutlet var undoButton: UIButton!
@IBOutlet var lockMapButtonIndicator: UISwitch!
@IBOutlet var locationsTableView: UITableView!
var nextAdded: UITextField!
// MARK: - Congigure the whole UIView.
override func viewDidLoad() {
super.viewDidLoad()
locationsTableView.backgroundView = UIImageView(image: UIImage(named: "background"))
locationsTableView.delegate = self
locationsTableView.dataSource = self
locationsTableView.register(UINib(nibName: "LocationsTableViewCell", bundle: nil), forCellReuseIdentifier: "locationTableViewCell")
locationsTableView.rowHeight = 50
configureMapView()
updateEditButtonsStatus(enabled: false)
let longTap = UILongPressGestureRecognizer(target: self, action: #selector(longPressOnTableView))
longTap.minimumPressDuration = 0.5
locationsTableView.addGestureRecognizer(longTap)
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.allowsBackgroundLocationUpdates = true
locationManager.activityType = .fitness
locationManager.startUpdatingLocation()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func configureMapView() {
let mapWidth = basicView.frame.width
let mapHeight = basicView.frame.height
mapView = GMSMapView.map(withFrame: CGRect(x: 0, y: 0, width: mapWidth, height: mapHeight), camera: GMSCameraPosition.camera(withLatitude: 0, longitude: 0, zoom: 15))
mapView!.settings.myLocationButton = true
mapView!.isMyLocationEnabled = true
mapView!.delegate = self
basicView.addSubview(mapView!)
mapView!.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.leadingMargin, relatedBy: NSLayoutRelation.equal, toItem: basicView, attribute: NSLayoutAttribute.leadingMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.trailingMargin, relatedBy: NSLayoutRelation.equal, toItem: basicView, attribute: NSLayoutAttribute.trailingMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.topMargin, relatedBy: NSLayoutRelation.equal, toItem: basicView, attribute: NSLayoutAttribute.topMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.bottomMargin, relatedBy: NSLayoutRelation.equal, toItem: basicView, attribute: NSLayoutAttribute.bottomMargin, multiplier: 1, constant: 0).isActive = true
if let location = locationManager.location {
let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: 15)
mapView!.animate(to: camera)
}
lockMapButtonIndicator.isOn = false
mapView!.settings.setAllGesturesEnabled(!lockMapButtonIndicator.isOn)
}
func updateEditButtonsStatus(enabled: Bool) {
createGraphButton.isEnabled = enabled
saveButton.isEnabled = enabled
undoButton.isEnabled = enabled
locationsTableView.isUserInteractionEnabled = !enabled
}
func loadSavedLocations() {
savedLocations = currentNotice?.locations.sorted(byKeyPath: "modifiedTime", ascending: false)
}
// MARK: - Edit buttons pressed.
@IBAction func drawOnMap(_ : UISwitch) {
clearMarkers()
clearGraphs()
lockMapButtonIndicator.isOn = !lockMapButtonIndicator.isOn
mapView!.settings.setAllGesturesEnabled(!lockMapButtonIndicator.isOn)
updateEditButtonsStatus(enabled: lockMapButtonIndicator.isOn)
graphCreated = false
}
@IBAction func undoButtonPressed(_ sender: UIButton) {
removePreviousMarkers()
clearGraphs()
graphCreated = false
}
func removePreviousMarkers() {
if markers.count != 0 {
markers[markers.count-1].map = nil
markers.remove(at: markers.count - 1)
}
}
func clearMarkers() {
for marker in self.markers {
marker.map = nil
}
self.markers = [GMSMarker]()
}
func clearGraphs() {
if self.graphs.count != 0 {
self.graphs[self.graphs.count - 1].map = nil
self.graphs.remove(at: self.graphs.count - 1)
}
}
@IBAction func createGraphButtonPressed(_ sender: UIButton) {
createGraph(zoom: mapView!.camera.zoom)
graphCreated = true
}
func createGraph(zoom: Float) {
if markers.count != 4 {
let alert = UIAlertController(title: "Cannot Create Graph", message: "Make sure you create a rectangular area on the map.", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
return
}
let (path, center) = createGMSMutablePathFromMarkers(marker: markers)
clearGraphs()
let camera = GMSCameraPosition.camera(withTarget: center, zoom: zoom)
mapView!.animate(to: camera)
let area = GMSPolygon(path: path)
area.map = mapView
graphs.append(area)
}
func createGMSMutablePathFromMarkers(marker: [GMSMarker]) -> (GMSMutablePath, CLLocationCoordinate2D) {
let path = GMSMutablePath()
var maxLat = Double(markers[0].position.latitude)
var minLat = maxLat
var maxLon = Double(markers[0].position.longitude)
var minLon = maxLon
for marker in markers {
path.add(CLLocationCoordinate2D(latitude: marker.position.latitude, longitude: marker.position.longitude))
maxLat = max(maxLat, Double(marker.position.latitude))
minLat = min(minLat, Double(marker.position.latitude))
maxLon = max(maxLon, Double(marker.position.longitude))
minLon = min(minLon, Double(marker.position.longitude))
}
let center = CLLocationCoordinate2D(latitude: (maxLat + minLat) / 2, longitude: (maxLon + minLon) / 2)
return (path, center)
}
@IBAction func saveButtonPressed(_ sender: UIButton) {
if !graphCreated {
let alert = UIAlertController(title: "No Graph Created", message: "Press 'Create Graph' before you save.", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
} else {
let currentDate = "Location alert on \(getCurrentTime(date: Date()))"
let alert = createOrModifiyLocationInfo(name: currentDate, status: "New Location", locationData: nil)
present(alert, animated: true, completion: nil)
}
}
func createOrModifiyLocationInfo(name: String, status: String, locationData: CustomLocation?) -> UIAlertController {
let alert = UIAlertController(title: "\(status)", message: "", preferredStyle: .alert)
alert.addTextField { (alertTextField) in
alertTextField.text = name
self.nextAdded = alertTextField
self.nextAdded.delegate = self
}
alert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: { (alertAction) in
if let savedLocation = locationData {
do {
try self.realm.write {
savedLocation.locationName = self.nextAdded.text!
}
} catch {
print(error)
}
} else {
let newLocation = self.nextAdded.text!
let location = CustomLocation()
location.locationName = newLocation
location.setTime(date: Date())
self.save(location: location)
self.clearGraphs()
self.clearMarkers()
}
self.locationsTableView.reloadData()
self.graphCreated = false
self.locationManager.startUpdatingLocation()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
return alert
}
// MARK: - Utility functions and textField delegate function.
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)
textField.becomeFirstResponder()
}
func save(location: CustomLocation) {
if let selectedNotice = self.currentNotice {
do {
try self.realm.write {
for marker in self.markers {
location.locationData.append(Double(marker.position.latitude))
location.locationData.append(Double(marker.position.longitude))
}
location.zoom = mapView!.camera.zoom
selectedNotice.locations.append(location)
drawOnMap(lockMapButtonIndicator)
}
} catch {
print(error)
}
}
}
func getCurrentTime(date: Date) -> String {
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd' 'HH:mm:ss"
let currentDate = formatter.string(from: date)
return currentDate
}
func allLocationsUntouched() {
do {
try realm.write {
for location in self.savedLocations! {
location.isDisplaying = false
}
}
} catch {
print(error)
}
}
}
// MARK: - UITableView delegate and datasource.
extension LocationsViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return savedLocations!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = locationsTableView.dequeueReusableCell(withIdentifier: "locationTableViewCell", for: indexPath) as! LocationsTableViewCell
cell.backgroundColor = UIColor.clear
cell.nameLabel.text = savedLocations![indexPath.row].locationName
cell.modifiedTimeLabel.text = "Last modified on \(savedLocations![indexPath.row].modifiedTime)"
if savedLocations![indexPath.row].notified {
cell.alarmButton.setImage(UIImage(named: "alarmOff"), for: .normal)
} else {
cell.alarmButton.setImage(UIImage(named: "alarmOn"), for: .normal)
}
cell.deletebuttonPresedCallBack = {
let alert = UIAlertController(title: "Delete This Location Alert?", message: cell.nameLabel.text, preferredStyle: .alert)
let confirm = UIAlertAction(title: "Confirm", style: .default, handler: { (action) in
if let deleteCell = self.savedLocations?[indexPath.row] {
if deleteCell.isDisplaying {
self.clearGraphs()
self.clearMarkers()
}
let identifier = "\(self.currentNotice!.noticeName):\(self.savedLocations![indexPath.row].locationName)"
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])
do {
try self.realm.write {
self.realm.delete(deleteCell)
self.locationsTableView.reloadData()
self.locationManager.startUpdatingLocation()
}
} catch {
print(error)
}
}
})
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(confirm)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
cell.locationAlarmButtonPressedCallBack = {
do {
try self.realm.write {
self.savedLocations![indexPath.row].notified = !self.savedLocations![indexPath.row].notified
}
} catch {
print(error)
}
self.locationsTableView.reloadData()
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
clearGraphs()
clearMarkers()
let selectedLocation = savedLocations![indexPath.row]
if !selectedLocation.isDisplaying {
for i in stride(from: 0, to: selectedLocation.locationData.count, by: 2) {
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: selectedLocation.locationData[i], longitude: selectedLocation.locationData[i+1])
marker.icon = UIImage(named: "marker")
marker.map = mapView
markers.append(marker)
}
createGraph(zoom: selectedLocation.zoom)
} else {
let cell = locationsTableView.cellForRow(at: indexPath)
cell?.isSelected = false
}
do {
try realm.write {
let flag = selectedLocation.isDisplaying
for location in self.savedLocations! {
location.isDisplaying = false
}
selectedLocation.isDisplaying = !flag
}
} catch {
print(error)
}
}
}
// MARK: - Google Map and location degelate
extension LocationsViewController: CLLocationManagerDelegate, GMSMapViewDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let currentLocation = locations.last!
var bounds = [GMSCoordinateBounds]()
var names = [String]()
for location in savedLocations! {
let path = GMSMutablePath()
for i in stride(from: 0, to: location.locationData.count, by: 2) {
path.add(CLLocationCoordinate2D(latitude: location.locationData[i], longitude: location.locationData[i+1]))
}
bounds.append(GMSCoordinateBounds(path: path))
names.append(location.locationName)
}
for i in stride(from: 0, to: bounds.count, by: 1) {
let bound = bounds[i]
if bound.contains(CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)) && !savedLocations![i].notified {
self.locationManager.startUpdatingLocation()
if bound.contains(CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)) {
let content = UNMutableNotificationContent()
content.title = "Are you in \(names[i]) area?"
content.body = "Don't forget to check your notice \(self.currentNotice!.noticeName)"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let identifier = "\(currentNotice!.noticeName):\(names[i])"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger:trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
do {
try self.realm.write {
self.savedLocations![i].notified = !self.savedLocations![i].notified
}
} catch {
print(error)
}
}
}
}
locationManager.stopUpdatingLocation()
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
if lockMapButtonIndicator.isOn {
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
marker.icon = UIImage(named: "marker")
marker.map = mapView
markers.append(marker)
}
}
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
mapView.selectedMarker = marker
return true
}
@objc func longPressOnTableView(longTap: UILongPressGestureRecognizer) {
let touchPoint = longTap.location(in: locationsTableView)
if let indexPath = locationsTableView.indexPathForRow(at: touchPoint) {
let locationData = savedLocations![indexPath.row]
if presentedViewController == nil {
let alert = createOrModifiyLocationInfo(name: locationData.locationName, status: "Modify Location", locationData: locationData)
present(alert, animated: true, completion: nil)
}
}
}
func didTapMyLocationButton(for mapView: GMSMapView) -> Bool {
let location = mapView.myLocation!
let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: 15)
if mapView.isHidden {
mapView.isHidden = false
mapView.camera = camera
} else {
mapView.animate(to: camera)
}
return false
}
// Handle authorization for the location manager.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
print("Location access was restricted.")
case .denied:
print("User denied access to location.")
// Display the map using the default location.
mapView!.isHidden = false
case .notDetermined:
print("Location status not determined.")
case .authorizedAlways: fallthrough
case .authorizedWhenInUse:
print("Location status is OK.")
}
}
// Handle location manager errors.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locationManager.stopUpdatingLocation()
print("Error: \(error)")
}
}
| 42.456103 | 230 | 0.621476 |
7a5803d615ef818034c6adcf5bb62b2bdf238c33 | 1,683 | import Foundation
import CoreLocation
import UIKit
public struct CameraState: Hashable {
public var center: CLLocationCoordinate2D
public var padding: UIEdgeInsets
public var zoom: CGFloat
public var bearing: CLLocationDirection
public var pitch: CGFloat
public init(center: CLLocationCoordinate2D,
padding: UIEdgeInsets,
zoom: CGFloat,
bearing: CLLocationDirection,
pitch: CGFloat) {
self.center = center
self.padding = padding
self.zoom = zoom
self.bearing = bearing
self.pitch = pitch
}
internal init(_ objcValue: MapboxCoreMaps.CameraState) {
self.center = objcValue.center
self.padding = objcValue.padding.toUIEdgeInsetsValue()
self.zoom = CGFloat(objcValue.zoom)
self.bearing = CLLocationDirection(objcValue.bearing)
self.pitch = CGFloat(objcValue.pitch)
}
public static func == (lhs: CameraState, rhs: CameraState) -> Bool {
return lhs.center.latitude == rhs.center.latitude
&& lhs.center.longitude == rhs.center.longitude
&& lhs.padding == rhs.padding
&& lhs.zoom == rhs.zoom
&& lhs.bearing == rhs.bearing
&& lhs.pitch == rhs.pitch
}
public func hash(into hasher: inout Hasher) {
hasher.combine(center.latitude)
hasher.combine(center.longitude)
hasher.combine(padding.top)
hasher.combine(padding.left)
hasher.combine(padding.bottom)
hasher.combine(padding.right)
hasher.combine(zoom)
hasher.combine(bearing)
hasher.combine(pitch)
}
}
| 31.754717 | 72 | 0.629828 |
8978df5bc48a43beb1a1675089e47e78f2778e62 | 4,709 | //
// ViewController.swift
// Todays_Cafe
//
// Created by SeungMin on 2021/07/16.
//
import UIKit
import FSPagerView
class HomeViewController: UIViewController {
let bannerViewModel = BannerViewModel()
let tagViewModel = TagViewModel()
@IBOutlet weak var tagCollectionView: UICollectionView!
@IBOutlet weak var tagSearchBtn: UIButton! {
didSet {
self.tagSearchBtn.setTitle("원하는 테마를 검색해보세요!", for: .normal)
self.tagSearchBtn.setTitleColor(.gray, for: .normal)
self.tagSearchBtn.titleLabel?.font = .boldSystemFont(ofSize: 17)
self.tagSearchBtn.setImage(UIImage(systemName: "magnifyingglass"), for: .normal)
self.tagSearchBtn.contentHorizontalAlignment = .left
self.tagSearchBtn.titleEdgeInsets.left = 30
self.tagSearchBtn.imageEdgeInsets.left = 20
self.tagSearchBtn.tintColor = .gray
self.tagSearchBtn.layer.cornerRadius = 10
self.tagSearchBtn.layer.borderWidth = 1.5
self.tagSearchBtn.layer.borderColor = UIColor.lightGray.cgColor
}
}
@IBOutlet weak var myPagerView: FSPagerView! {
didSet {
self.myPagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
self.myPagerView.itemSize = FSPagerViewAutomaticSize
self.myPagerView.automaticSlidingInterval = 4.0
}
}
@IBOutlet weak var myPageControl: FSPageControl! {
didSet {
self.myPageControl.numberOfPages = self.bannerViewModel.countBannerList
self.myPageControl.contentHorizontalAlignment = .center
self.myPageControl.itemSpacing = 15
}
}
// MARK: - ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
self.myPagerView.dataSource = self
self.myPagerView.delegate = self
self.tagCollectionView.dataSource = self
self.tagCollectionView.delegate = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let areaSearchViewController = segue.destination as? AreaSearchViewController else { return }
if let tagInfo = sender as? Tag {
areaSearchViewController.tagName = tagInfo.tagName
}
}
fileprivate func saveNewTag(_ tagId: String, _ tagName: String) {
CoreDataManager.shared.saveRecentTag(tagId, tagName)
}
}
// MARK: - FSPagerViewDataSource
extension HomeViewController: FSPagerViewDataSource {
func numberOfItems(in pagerView: FSPagerView) -> Int {
return self.bannerViewModel.countBannerList
}
func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
cell.imageView?.image = UIImage(named: self.bannerViewModel.bannerInfo(at: index).bannerImageName)
cell.textLabel?.text = self.bannerViewModel.bannerInfo(at: index).bannerText
cell.textLabel?.numberOfLines = 2
return cell
}
}
// MARK: - FSPagerViewDelegate
extension HomeViewController: FSPagerViewDelegate {
func pagerViewWillEndDragging(_ pagerView: FSPagerView, targetIndex: Int) {
self.myPageControl.currentPage = targetIndex
}
func pagerViewDidEndScrollAnimation(_ pagerView: FSPagerView) {
self.myPageControl.currentPage = pagerView.currentIndex
}
func pagerView(_ pagerView: FSPagerView, shouldHighlightItemAt index: Int) -> Bool {
return false
}
}
// MARK: - UICollectionViewDataSource
extension HomeViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tagViewModel.countTagList
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "tagCollectionViewCell", for: indexPath) as? TagCollectionViewCell else {
return UICollectionViewCell()
}
let tagInfo = tagViewModel.tagInfo(at: indexPath.item)
cell.update(tagInfo: tagInfo)
return cell
}
}
// MARK: - UICollectionViewDelegate
extension HomeViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let tagInfo = tagViewModel.tagInfo(at: indexPath.item)
performSegue(withIdentifier: "homeVCToAreaSearchVC", sender: tagInfo)
saveNewTag(tagInfo.tagId, tagInfo.tagName)
}
}
| 37.975806 | 154 | 0.69484 |
61e7f10818e13925fbcc9bbca253af5c5eec8bbb | 1,808 | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// For more information on setting up and running this sample code, see
// https://firebase.google.com/docs/analytics/ios/start
//
import Foundation
import FirebaseAnalytics
@objc(FoodPickerViewController) // match the ObjC symbol name inside Storyboard
class FoodPickerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let foodStuffs = ["Hot Dogs", "Hamburger", "Pizza"]
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let food = foodStuffs[row]
UserDefaults.standard.setValue(food, forKey: "favorite_food")
UserDefaults.standard.synchronize()
// [START user_property]
FIRAnalytics.setUserPropertyString(food, forName: "favorite_food")
// [END user_property]
performSegue(withIdentifier: "unwindToHome", sender: self)
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return foodStuffs.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return foodStuffs[row];
}
}
| 31.719298 | 109 | 0.740044 |
d9f05bd0e35a068f75ba325e15a99cb7ac897b41 | 797 | //
// HomeNavigationController.swift
// MyTouch
//
// Created by Tommy Lin on 2019/1/16.
// Copyright © 2019 NTU HCI Lab. All rights reserved.
//
import UIKit
class HomeNavigationController: UINavigationController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 13.0, *) {
overrideUserInterfaceStyle = .light
}
navigationBar.isTranslucent = false
navigationBar.shadowImage = UIImage()
navigationBar.barTintColor = UIColor(hex: 0x00b894)
navigationBar.tintColor = UIColor.white
navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
}
}
| 25.709677 | 99 | 0.673777 |
8a3dc109208d55281c9f2cdfa8395b3ee9c99b09 | 1,333 | //----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.7.0.0
//
// Created by Quasar Development
//
//---------------------------------------------------
import Foundation
/**
* abstDomain: A17245 (C-0-T14581-A17021-A17245-cpt)
*/
public enum EPA_FdV_AUTHZ_LacrimalPunctaRoute:Int,CustomStringConvertible
{
case LPINS
static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_LacrimalPunctaRoute?
{
return createWithString(value: node.stringValue!)
}
static func createWithString(value:String) -> EPA_FdV_AUTHZ_LacrimalPunctaRoute?
{
var i = 0
while let item = EPA_FdV_AUTHZ_LacrimalPunctaRoute(rawValue: i)
{
if String(describing: item) == value
{
return item
}
i += 1
}
return nil
}
public var stringValue : String
{
return description
}
public var description : String
{
switch self
{
case .LPINS: return "LPINS"
}
}
public func getValue() -> Int
{
return rawValue
}
func serialize(__parent:DDXMLNode)
{
__parent.stringValue = stringValue
}
}
| 20.19697 | 85 | 0.507877 |
0347d3b8a1908a5c070d5edba442744742563e86 | 2,173 | //
// AppDelegate.swift
// FayeSwift
//
// Created by Haris Amin on 01/25/2016.
// Copyright (c) 2016 Haris Amin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.234043 | 285 | 0.753797 |
14810bae2bf1660f9bfebc1dc7b6b4c239af19b9 | 708 | import Foundation
public struct ProductWrapperData : ProductWrapperProtocol {
public var property: WrappedProductProtocol?
enum CodingKeys: String, CodingKey {
case property = "property"
}
public init() {
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if container.contains(.property) {
property = try container.decode(WrappedProductData?.self, forKey: .property)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if self.property != nil {try container.encode(property as! WrappedProductData?, forKey: .property)}
}
}
| 29.5 | 103 | 0.713277 |
2107ff7bc391648dfc3f48d4e51fea2d79c0b3a1 | 2,174 | //
// AppDelegate.swift
// MLMNetWork
//
// Created by MengLiMing on 07/06/2020.
// Copyright (c) 2020 MengLiMing. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.255319 | 285 | 0.75483 |
1dd13a5f011f95a5887d6520e60e6ad7360d8169 | 2,609 | //
// TabCollectionCell.swift
// TabPageViewController
//
// Created by EndouMari on 2016/02/24.
// Copyright © 2016年 EndouMari. All rights reserved.
//
import UIKit
class TabCollectionCell: UICollectionViewCell {
var tabItemButtonPressedBlock: (() -> Void)?
var option: TabPageOption = TabPageOption() {
didSet {
currentBarViewHeightConstraint.constant = option.currentBarHeight
}
}
var item: String = "" {
didSet {
itemLabel.text = item
itemLabel.invalidateIntrinsicContentSize()
invalidateIntrinsicContentSize()
}
}
var isCurrent: Bool = false {
didSet {
currentBarView.isHidden = !isCurrent
if isCurrent {
highlightTitle()
} else {
unHighlightTitle()
}
currentBarView.backgroundColor = option.currentColor
layoutIfNeeded()
}
}
@IBOutlet fileprivate weak var itemLabel: UILabel!
@IBOutlet fileprivate weak var currentBarView: UIView!
@IBOutlet fileprivate weak var currentBarViewHeightConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
currentBarView.isHidden = true
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
if item.characters.count == 0 {
return CGSize.zero
}
return intrinsicContentSize
}
class func cellIdentifier() -> String {
return "TabCollectionCell"
}
}
// MARK: - View
extension TabCollectionCell {
override var intrinsicContentSize : CGSize {
let width: CGFloat
if let tabWidth = option.tabWidth , tabWidth > 0.0 {
width = tabWidth
} else {
width = itemLabel.intrinsicContentSize.width + option.tabMargin * 2
}
let size = CGSize(width: width, height: option.tabHeight)
return size
}
func hideCurrentBarView() {
currentBarView.isHidden = true
}
func showCurrentBarView() {
currentBarView.isHidden = false
}
func highlightTitle() {
itemLabel.textColor = option.currentColor
itemLabel.font = UIFont.boldSystemFont(ofSize: option.fontSize)
}
func unHighlightTitle() {
itemLabel.textColor = option.defaultColor
itemLabel.font = UIFont.systemFont(ofSize: option.fontSize)
}
}
// MARK: - IBAction
extension TabCollectionCell {
@IBAction fileprivate func tabItemTouchUpInside(_ button: UIButton) {
tabItemButtonPressedBlock?()
}
}
| 24.847619 | 86 | 0.625144 |
bfd7aace439a9358e866d147dbfbe62f8867e151 | 9,555 | import Storage
import UserDefault
import XCTest
enum UserDefaultsCodable: String, Codable {
case test
}
let userDefaultsTagStorage = SecureUserDefaultsStorage(authenticationTag: Data())
final class SecureUserDefaultTests: XCTestCase {
@Store(userDefaultsTagStorage, "userDefaultsTagStore")
var userDefaultsTagStore: String?
@Store(SecureUserDefaultsStorage.standard, "userDefaultsStore")
var userDefaultsStore: String?
@SecureUserDefault("userDefaults")
var userDefaults: String?
@Store(userDefaultsTagStorage, "userDefaultsTagDefault")
var userDefaultsTagDefault = "tagDefault"
@SecureUserDefault("userDefaultsDefault")
var userDefaultsDefault = "default"
@CodableStore(userDefaultsTagStorage, "userDefaultsTagCodable")
var userDefaultsTagCodable = UserDefaultsCodable.test
@CodableUserDefault("userDefaultsCodable")
var userDefaultsCodable = UserDefaultsCodable.test
@UnwrappedStore(userDefaultsTagStorage, "unwrappedUserDefaultsTagDefault")
var unwrappedUserDefaultsTagDefault = "tagDefault"
@UnwrappedUserDefault("unwrappedUserDefaultsDefault")
var unwrappedUserDefaultsDefault = "default"
@UnwrappedCodableStore(userDefaultsTagStorage, "unwrappedUserDefaultsTagCodable")
var unwrappedUserDefaultsTagCodable = UserDefaultsCodable.test
@UnwrappedCodableUserDefault("unwrappedUserDefaultsCodable")
var unwrappedUserDefaultsCodable = UserDefaultsCodable.test
func testUserDefault() {
userDefaultsStore = nil
XCTAssertNil(userDefaultsStore)
let test = "testUserDefault"
userDefaults = test
userDefaultsTagStore = test
XCTAssertEqual(userDefaults, test)
XCTAssertEqual(userDefaults, userDefaultsTagStore)
let testRegister = "testRegister"
SecureUserDefaultsStorage.standard.register(defaults: ["userDefaults": testRegister,
"userDefaultsStore": testRegister])
XCTAssertNotEqual(userDefaults, testRegister)
XCTAssertEqual(userDefaultsStore, testRegister)
XCTAssertEqual(userDefaults, userDefaultsTagStore)
userDefaultsStore = test
XCTAssertEqual(userDefaults, userDefaultsStore)
XCTAssertEqual(userDefaults, userDefaultsTagStore)
userDefaults = nil
XCTAssertNil(userDefaults)
XCTAssertNotEqual(userDefaults, userDefaultsTagStore)
XCTAssertEqual(userDefaultsTagDefault, "tagDefault")
XCTAssertEqual(userDefaultsDefault, "default")
userDefaultsDefault = nil
XCTAssertNil(userDefaultsDefault)
XCTAssertEqual(userDefaultsTagCodable, .test)
XCTAssertEqual(userDefaultsCodable, .test)
userDefaultsCodable = nil
XCTAssertNil(userDefaultsCodable)
XCTAssertEqual(unwrappedUserDefaultsTagDefault, "tagDefault")
XCTAssertEqual(unwrappedUserDefaultsDefault, "default")
XCTAssertEqual(unwrappedUserDefaultsTagCodable, .test)
XCTAssertEqual(unwrappedUserDefaultsCodable, .test)
}
func testUserDefaultArray() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testArray"
let value = [1]
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.array(forKey: key) as? [Int], value)
}
func testUserDefaultDictionary() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testDictionary"
let value = [key: 1]
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.dictionary(forKey: key) as? [String: Int], value)
}
func testUserDefaultStringArray() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testStringArray"
let value = [key]
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.stringArray(forKey: key), value)
}
func testUserDefaultInteger() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testInteger"
let value = 1
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.integer(forKey: key), value)
}
func testUserDefaultFloat() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testFloat"
let value: Float = 1
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.float(forKey: key), value)
}
func testUserDefaultDouble() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testDouble"
let value: Double = 1
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.double(forKey: key), value)
}
func testUserDefaultBool() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testBool"
let value = true
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.bool(forKey: key), value)
}
func testUserDefaultString() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testURL"
let value = "testString"
XCTAssertNotNil(value)
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.string(forKey: key), value)
}
func testUserDefaultURL() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testURL"
let value = URL(string: "https://github.com/alexruperez")
XCTAssertNotNil(value)
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.url(forKey: key), value)
}
func testUserDefaultArrayNil() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testArray"
let value: [Any]? = nil
XCTAssertNil(value)
userDefaults.set(value, forKey: key)
XCTAssertNil(userDefaults.array(forKey: key))
}
func testUserDefaultDictionaryNil() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testDictionary"
let value: [String: Any]? = nil
XCTAssertNil(value)
userDefaults.set(value, forKey: key)
XCTAssertNil(userDefaults.dictionary(forKey: key))
}
func testUserDefaultStringArrayNil() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testStringArray"
let value: [String]? = nil
XCTAssertNil(value)
userDefaults.set(value, forKey: key)
XCTAssertNil(userDefaults.stringArray(forKey: key))
}
func testUserDefaultIntegerNil() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testInteger"
let value: Int? = nil
XCTAssertNil(value)
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.integer(forKey: key), 0)
}
func testUserDefaultFloatNil() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testFloat"
let value: Float? = nil
XCTAssertNil(value)
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.float(forKey: key), 0)
}
func testUserDefaultDoubleNil() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testDouble"
let value: Double? = nil
XCTAssertNil(value)
userDefaults.set(value, forKey: key)
XCTAssertEqual(userDefaults.double(forKey: key), 0)
}
func testUserDefaultBoolNil() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testBool"
let value: Bool? = nil
XCTAssertNil(value)
userDefaults.set(value, forKey: key)
XCTAssertFalse(userDefaults.bool(forKey: key))
}
func testUserDefaultStringNil() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testString"
let value: String? = nil
XCTAssertNil(value)
userDefaults.set(value, forKey: key)
XCTAssertNil(userDefaults.string(forKey: key))
}
func testUserDefaultURLNil() {
let userDefaults = SecureUserDefaultsStorage.standard
let key = "testURL"
let value: URL? = nil
XCTAssertNil(value)
userDefaults.set(value, forKey: key)
XCTAssertNil(userDefaults.url(forKey: key))
}
static var allTests = [
("testUserDefault", testUserDefault),
("testUserDefaultArray", testUserDefaultArray),
("testUserDefaultDictionary", testUserDefaultDictionary),
("testUserDefaultStringArray", testUserDefaultStringArray),
("testUserDefaultInteger", testUserDefaultInteger),
("testUserDefaultFloat", testUserDefaultFloat),
("testUserDefaultDouble", testUserDefaultDouble),
("testUserDefaultBool", testUserDefaultBool),
("testUserDefaultString", testUserDefaultString),
("testUserDefaultURL", testUserDefaultURL),
("testUserDefaultArrayNil", testUserDefaultArrayNil),
("testUserDefaultDictionaryNil", testUserDefaultDictionaryNil),
("testUserDefaultStringArrayNil", testUserDefaultStringArrayNil),
("testUserDefaultIntegerNil", testUserDefaultIntegerNil),
("testUserDefaultFloatNil", testUserDefaultFloatNil),
("testUserDefaultDoubleNil", testUserDefaultDoubleNil),
("testUserDefaultBoolNil", testUserDefaultBoolNil),
("testUserDefaultStringNil", testUserDefaultStringNil),
("testUserDefaultURLNil", testUserDefaultURLNil)
]
}
| 38.841463 | 98 | 0.692308 |
eb8879edf16bdbad9bbd719de4d5788a3fb74091 | 3,263 | //
// SphericalHarmonicsTests.swift
// VidTestsTests
//
// Created by David Gavilan on 2019/02/18.
// Copyright © 2019 David Gavilan. All rights reserved.
//
import XCTest
import simd
import VidFramework
@testable import VidTests
func assertAlmostEqual(_ expected: SHSample, _ actual: SHSample) {
assertAlmostEqual(expected.sph, actual.sph)
assertAlmostEqual(expected.vec, actual.vec)
assertAlmostEqual(expected.coeff, actual.coeff)
}
func checkIrradiance(_ sh: SphericalHarmonics, color: simd_float3, irradiance: simd_float3, normal: simd_float3) {
// every run the samples are random, so we make the epsilon a bit big
let e: Float = 0.5
assertAlmostEqual(color, sh.reconstruct(direction: normal), epsilon: e)
assertAlmostEqual(irradiance, sh.getIrradianceApproximation(normal: normal), epsilon: e)
}
func colorFromPolarCoordinates(θ: Float, φ: Float) -> Vec3 {
let s = Spherical(r: 1, θ: θ, φ: φ)
let c = s.toCartesian()
let ax = fabsf(c.x)
let ay = fabsf(c.y)
let az = fabsf(c.z)
if ay >= ax && ay >= az {
if c.y > 0 {
// up is cyan
return Vec3(0, 1, 1)
}
// down is green
return Vec3(0, 1, 0)
}
if ax >= az {
if c.x > 0 {
// right is red
return Vec3(1, 0, 0)
}
// left is yellow
return Vec3(1, 1, 0)
}
if c.z > 0 {
// front is magenta
return Vec3(1, 0, 1)
}
// back is white
return Vec3(1, 1, 1)
}
class SphericalHarmonicsTests: XCTestCase {
func testStorage() {
let storage: SHStorage = SphericalHarmonicsArrays(numBands: 3, sqrtSamples: 5)
XCTAssertEqual(3, storage.numBands)
XCTAssertEqual(25, storage.numSamples)
XCTAssertEqual(5, storage.sqrtSamples)
XCTAssertEqual(9, storage.numCoeffs)
let coefficients = [Double](repeating: 0, count: 9)
let emptySample = SHSample(sph: Spherical(), vec: .zero, coeff: coefficients)
assertAlmostEqual(emptySample, storage.getSample(i: 24))
assertAlmostEqual(Vec3.zero, storage.getCoefficient(i: 8))
assertAlmostEqual(float4x4(), storage.getIrradiance(i: 2))
}
func testIrradiance() {
let storage: SHStorage = SphericalHarmonicsArrays(numBands: 3, sqrtSamples: 10)
XCTAssertEqual(100, storage.numSamples)
let sh = SphericalHarmonics(storage)
var i = 0
while !sh.isInit {
sh.initNextSphericalSample()
i += 1
}
XCTAssertEqual(100, i)
sh.projectPolarFn(colorFromPolarCoordinates)
// irradiance is the integral in the hemisphere, so a brighter value
checkIrradiance(sh, color: simd_float3(-0.2, 1.05, 0.85), irradiance: simd_float3(1.46, 2.37, 2.41), normal: simd_float3(0, 1, 0))
checkIrradiance(sh, color: simd_float3(-0.23, 1.0, 0.07), irradiance: simd_float3(1.43, 2.46, 0.85), normal: simd_float3(0, -1, 0))
checkIrradiance(sh, color: simd_float3(1.14, 0.05, -0.04), irradiance: simd_float3(2.43, 1.18, 1.33), normal: simd_float3(1, 0, 0))
checkIrradiance(sh, color: simd_float3(1, 1, 1), irradiance: simd_float3(2.48, 2.65, 1.9), normal: simd_float3(0, 0, -1))
}
}
| 35.467391 | 139 | 0.634386 |
de6b7aab881ed5a24769b5cc167968ba50f55472 | 4,828 | //
// DynamicEditProductViewModel.swift
// CleanArchitecture
//
// Created by Tuan Truong on 9/10/18.
// Copyright © 2018 Sun Asterisk. All rights reserved.
//
struct DynamicEditProductViewModel {
let navigator: DynamicEditProductNavigatorType
let useCase: DynamicEditProductUseCaseType
let product: Product
}
// MARK: - ViewModelType
extension DynamicEditProductViewModel: ViewModelType {
struct Input {
let loadTrigger: Driver<TriggerType>
let updateTrigger: Driver<Void>
let cancelTrigger: Driver<Void>
let dataTrigger: Driver<DataType>
}
struct Output {
let nameValidation: Driver<ValidationResult>
let priceValidation: Driver<ValidationResult>
let isUpdateEnabled: Driver<Bool>
let updatedProduct: Driver<Void>
let cancel: Driver<Void>
let error: Driver<Error>
let isLoading: Driver<Bool>
let cells: Driver<([CellType], Bool)>
}
enum DataType {
case name(String)
case price(String)
}
struct CellType {
let dataType: DataType
let validationResult: ValidationResult
}
enum TriggerType {
case load
case endEditing
}
func transform(_ input: Input) -> Output {
let errorTracker = ErrorTracker()
let activityIndicator = ActivityIndicator()
let name = input.dataTrigger
.map { data -> String? in
if case let DataType.name(name) = data {
return name
}
return nil
}
.unwrap()
.startWith(self.product.name)
let price = input.dataTrigger
.map { data -> String? in
if case let DataType.price(price) = data {
return price
}
return nil
}
.unwrap()
.startWith(String(self.product.price))
let nameValidation = validate(object: name,
trigger: input.updateTrigger,
validator: useCase.validate(name:))
let priceValidation = validate(object: price,
trigger: input.updateTrigger,
validator: useCase.validate(price:))
let isUpdateEnabled = Driver.combineLatest([
nameValidation,
priceValidation
])
.map {
$0.reduce(true) { result, validation -> Bool in
result && validation.isValid
}
}
.startWith(true)
let product = Driver.combineLatest(name, price)
.map { name, price in
Product(
id: self.product.id,
name: name,
price: Double(price) ?? 0.0
)
}
let cells = input.loadTrigger
.withLatestFrom(Driver.combineLatest(product, nameValidation, priceValidation))
.map { product, nameValidation, priceValidation -> [CellType] in
return [
CellType(dataType: .name(product.name), validationResult: nameValidation),
CellType(dataType: .price(String(product.price)), validationResult: priceValidation)
]
}
.withLatestFrom(input.loadTrigger) {
($0, $1 == .load)
}
let cancel = input.cancelTrigger
.do(onNext: navigator.dismiss)
let updatedProduct = input.updateTrigger
.withLatestFrom(isUpdateEnabled)
.filter { $0 }
.withLatestFrom(product)
.flatMapLatest { product in
self.useCase.update(product)
.trackError(errorTracker)
.trackActivity(activityIndicator)
.asDriverOnErrorJustComplete()
.map { _ in product }
}
.do(onNext: { product in
print(Notification.Name.updatedProduct.rawValue)
NotificationCenter.default.post(name: Notification.Name.updatedProduct, object: product)
self.navigator.dismiss()
})
.mapToVoid()
let error = errorTracker.asDriver()
let isLoading = activityIndicator.asDriver()
return Output(
nameValidation: nameValidation,
priceValidation: priceValidation,
isUpdateEnabled: isUpdateEnabled,
updatedProduct: updatedProduct,
cancel: cancel,
error: error,
isLoading: isLoading,
cells: cells
)
}
}
| 32.186667 | 104 | 0.532726 |
f8bbf9093500c93cd1d2af561f15d5ebcbd19b8b | 1,634 | import DefaultCodable
import Foundation
/// An unknown card element. Unknown card elements are discarded or replaced
/// by their `fallback`, in case one is provided.
public struct UnknownCardElement: CardElementProtocol, Codable, Equatable {
/// A unique identifier associated with the item.
@ItemIdentifier public var id: String
/// If `false`, this item will be removed from the visual tree.
@Default<True> public var isVisible: Bool
/// When `true`, draw a separating line at the top of the element.
@Default<False> public var separator: Bool
/// Controls the amount of spacing between this element and the preceding element.
@Default<FirstCase> public var spacing: Spacing
/// Describes what to do when an unknown element is encountered or the requires of this or any children can’t be met.
@Default<Fallback.None> public var fallback: Fallback<CardElement>
/// A series of key/value pairs indicating features that the item requires with corresponding minimum version.
/// When a feature is missing or of insufficient version, fallback is triggered.
@Default<EmptyDictionary> public var requires: [String: SemanticVersion]
public init(
id: String = "",
isVisible: Bool = true,
separator: Bool = false,
spacing: Spacing = .default,
fallback: Fallback<CardElement> = .none,
requires: [String: SemanticVersion] = [:]
) {
self.id = id
self.isVisible = isVisible
self.separator = separator
self.spacing = spacing
self.fallback = fallback
self.requires = requires
}
}
| 38.904762 | 121 | 0.692778 |
ff76e19f66b2a63070266f3003ea775bf3611efc | 1,745 | let tags: [Tag] = [.tree, .string]
final class StreamChecker {
let root = Trie()
var history = ""
init(_ words: [String]) {
for word in words { root.insert(word.reversed()) }
}
func query(_ letter: Character) -> Bool {
history.append(letter)
var p = root
for letter in history.reversed() {
guard let next = p.children[letter] else { break }
if next.isEnd { return true }
p = next
}
return false
}
}
let streamChecker = StreamChecker(["cd", "f", "kl"]) // init the dictionary.
streamChecker.query("a") // return false
streamChecker.query("b") // return false
streamChecker.query("c") // return false
streamChecker.query("d") // return true, because "cd" is in the wordlist
streamChecker.query("e") // return false
streamChecker.query("f") // return true, because "f" is in the wordlist
streamChecker.query("g") // return false
streamChecker.query("h") // return false
streamChecker.query("i") // return false
streamChecker.query("j") // return false
streamChecker.query("k") // return false
streamChecker.query("l") // return true, because "kl" is in the wordlist
final class StreamCheckerMultiplePointers {
let root = Trie()
var finders = [Trie]()
init(_ words: [String]) {
for word in words { root.insert(word) }
finders.append(root)
}
func query(_ letter: Character) -> Bool {
var newFinders = [root]
var found = false
for finder in finders {
if let next = finder.children[letter] {
if next.isEnd { found = true }
newFinders.append(next)
}
}
finders = newFinders
return found
}
}
| 27.698413 | 76 | 0.601146 |
cc5ee43a3dec6e5f98a4630d59ffc953173353db | 4,417 | //
// MainSearchViewController.swift
// Recast
//
// Created by Jack Thompson on 9/25/18.
// Copyright © 2018 Cornell AppDev. All rights reserved.
//
import UIKit
import SnapKit
protocol SearchTableViewDelegate: class {
func refreshController()
func didPress(_ partialPodcast: PartialPodcast)
}
class MainSearchViewController: ViewController {
// MARK: - Variables
var searchController: UISearchController!
var searchResultsTableView: UITableView!
var tableViewData: MainSearchDataSourceDelegate!
var searchDelayTimer: Timer?
var searchText: String = ""
var discoverContainerView: UIView!
var discoverVC: DiscoverViewController!
// MARK: - Constants
let podcastCellReuseId = PodcastTableViewCell.cellReuseId
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Search"
searchController = UISearchController(searchResultsController: nil)
searchController.hidesNavigationBarDuringPresentation = false
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search"
searchController.searchBar.barStyle = .black
searchController.searchBar.delegate = self
navigationItem.hidesSearchBarWhenScrolling = false
definesPresentationContext = true
let searchField = searchController?.searchBar.value(forKey: "searchField") as? UITextField
searchField?.textColor = .white
searchField?.backgroundColor = #colorLiteral(red: 0.09749762056, green: 0.09749762056, blue: 0.09749762056, alpha: 1)
searchController?.searchBar.barTintColor = .black
searchController?.searchBar.barStyle = .black
searchController?.searchBar.tintColor = .white
navigationItem.titleView = searchController.searchBar
tableViewData = MainSearchDataSourceDelegate()
tableViewData.delegate = self
searchResultsTableView = UITableView(frame: .zero, style: .plain)
searchResultsTableView.dataSource = tableViewData
searchResultsTableView.delegate = tableViewData
searchResultsTableView.register(PodcastTableViewCell.self, forCellReuseIdentifier: podcastCellReuseId)
view.addSubview(searchResultsTableView)
discoverContainerView = UIView()
discoverContainerView.isUserInteractionEnabled = true
view.addSubview(discoverContainerView)
discoverVC = DiscoverViewController()
addChild(discoverVC)
discoverContainerView.addSubview(discoverVC.view)
setUpConstraints()
}
func setUpConstraints() {
searchResultsTableView.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.bottom.equalToSuperview()
}
discoverContainerView.snp.makeConstraints { make in
make.edges.equalTo(searchResultsTableView)
}
discoverVC.view.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.prefersLargeTitles = false
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
searchController.searchBar.delegate = self
}
}
// MARK: - searchResultsTableView Delegate
extension MainSearchViewController: SearchTableViewDelegate {
func refreshController() {
searchResultsTableView.reloadData()
searchResultsTableView.layoutIfNeeded()
}
func didPress(_ partialPodcast: PartialPodcast) {
let podcastDetailVC = PodcastDetailViewController(partialPodcast: partialPodcast)
navigationController?.pushViewController(podcastDetailVC, animated: true)
}
}
// MARK: UISearchBarDelegate
extension MainSearchViewController: UISearchBarDelegate {
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
discoverContainerView.isHidden = false
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
discoverContainerView.isHidden = true
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
guard let searchText = searchController.searchBar.text else {
return
}
tableViewData.fetchData(query: searchText)
}
}
| 34.779528 | 125 | 0.724926 |
dd6c5fae5a85e29e8f6ba43b03ba53407b65af70 | 2,686 | //
// PeopleAndAppleStockPricesTests.swift
// PeopleAndAppleStockPricesTests
//
// Created by Anthony Gonzalez on 8/30/19.
// Copyright © 2019 Pursuit. All rights reserved.
//
import XCTest
class PeopleAndAppleStockPricesTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
func testDoesUserDataExist() { //Tests that data exists
let data = getUserDataFromJSON()
XCTAssertNotNil(data) //Stating, "I AM NOT NIL!!!"
}
func testDoesDataReturnUserResultsArray() { //Specifically tests if data gives back an array of userResults
guard let data = getUserDataFromJSON() else { XCTFail(); return }
do {
let users = try usersModel.getUsers(from: data)
XCTAssert(type(of: users) == [userResults].self, "You do not have a userResults object, idiot")
} catch {
fatalError()
}
}
private func getUserDataFromJSON() -> Data? {
guard let pathToData = Bundle.main.path(forResource: "userinfo", ofType: "json") else {return nil}
let url = URL(fileURLWithPath: pathToData)
do {
let data = try Data(contentsOf: url)
return data
} catch let jsonError {
fatalError("\(jsonError)")
}
}
func testGetsFullNameCapitalized(){
let randomPersonName = userNameWrapper(first: "david", last: "rifkin")
let randomPersonLocation = locationWrapper(street: "Elmo's World", city: "Harlem", state: "NY")
let randomPersonPicture = pictureWrapper(large: "Embarassing Photo of David at the Christmas Party.jpg")
let randomPersonDOB = dobWrapper(date: "01-02-3456")
let randomUser = userResults(name: randomPersonName, location: randomPersonLocation, phone: "1-800-TESTDEEZ", dob: randomPersonDOB, picture: randomPersonPicture, email: "")
let name = randomUser.getFullName()
XCTAssert(name == "David Rifkin", "Function is not capitalizing properly, bruh. I'm scared...")
}
}
| 37.305556 | 180 | 0.641847 |
5dae54cff78a43180e742afc356f22cbc5bd7fbc | 9,490 | //
// NecessaryObjects.swift
// Strafen
//
// Created by Steven on 10/15/20.
//
import SwiftUI
/// Typealias for a handler to dimiss from a subview to the previous view.
///
/// Optional closure with no parameters and no return value.
typealias DismissHandler = (() -> Void)?
struct CustomNavigationLink<Label, Destination, V>: View where Label: View, Destination: View, V: Hashable {
private struct SelectionTag {
let tag: V
let selection: Binding<V?>
}
private let swipeBack: Bool
private let destination: Destination
private let label: Label
private let isActive: Binding<Bool>?
private let selectionTag: SelectionTag?
/// Creates an instance that presents `destination` when `selection` is set to `tag`.
public init(swipeBack: Bool = true, destination: Destination, tag: V, selection: Binding<V?>, @ViewBuilder label: () -> Label) {
self.swipeBack = swipeBack
self.destination = destination
self.label = label()
self.isActive = nil
self.selectionTag = SelectionTag(tag: tag, selection: selection)
}
var body: some View {
if let isActive = isActive {
NavigationLink(destination:
destination
.navigationTitle("Title")
.navigationBarHidden(true)
.onAppear {
UINavigationController.swipeBack = swipeBack
},
isActive: isActive) {
label
}
} else if let selectionTag = selectionTag {
NavigationLink(destination:
destination
.navigationTitle("Title")
.navigationBarHidden(true)
.onAppear {
UINavigationController.swipeBack = swipeBack
},
tag: selectionTag.tag, selection: selectionTag.selection) {
label
}
} else {
NavigationLink(destination:
destination
.navigationTitle("Title")
.navigationBarHidden(true)
.onAppear {
UINavigationController.swipeBack = swipeBack
}) {
label
}
}
}
}
extension CustomNavigationLink where V == Bool {
init(swipeBack: Bool = true, destination: Destination, @ViewBuilder label: () -> Label) {
self.swipeBack = swipeBack
self.destination = destination
self.label = label()
self.isActive = nil
self.selectionTag = nil
}
/// Creates an instance that presents `destination` when active.
init(swipeBack: Bool = true, destination: Destination, isActive: Binding<Bool>, @ViewBuilder label: () -> Label) {
self.swipeBack = swipeBack
self.destination = destination
self.label = label()
self.isActive = isActive
self.selectionTag = nil
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension CustomNavigationLink where Label == Text {
/// Creates an instance that presents `destination` when `selection` is set to `tag`, with a `Text` label generated from a title string.
init(swipeBack: Bool = true, _ titleKey: LocalizedStringKey, destination: Destination, tag: V, selection: Binding<V?>) {
self.init(swipeBack: swipeBack, destination: destination, tag: tag, selection: selection) { Text(titleKey) }
}
/// Creates an instance that presents `destination` when `selection` is set to `tag`, with a `Text` label generated from a title string.
init<S>(swipeBack: Bool = true, _ title: S, destination: Destination, tag: V, selection: Binding<V?>) where S: StringProtocol {
self.init(swipeBack: swipeBack, destination: destination, tag: tag, selection: selection) { Text(title) }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension CustomNavigationLink where Label == Text, V == Bool {
/// Creates an instance that presents `destination`, with a `Text` label generated from a title string.
init(swipeBack: Bool = true, _ titleKey: LocalizedStringKey, destination: Destination) {
self.init(swipeBack: swipeBack, destination: destination) { Text(titleKey) }
}
/// Creates an instance that presents `destination`, with a `Text` label generated from a title string.
init<S>(swipeBack: Bool = true, _ title: S, destination: Destination) where S : StringProtocol {
self.init(swipeBack: swipeBack, destination: destination) { Text(title) }
}
/// Creates an instance that presents `destination` when active, with a `Text` label generated from a title string.
init(swipeBack: Bool = true, _ titleKey: LocalizedStringKey, destination: Destination, isActive: Binding<Bool>) {
self.init(swipeBack: swipeBack, destination: destination, isActive: isActive) { Text(titleKey) }
}
/// Creates an instance that presents `destination` when active, with a `Text` label generated from a title string.
init<S>(swipeBack: Bool = true, _ title: S, destination: Destination, isActive: Binding<Bool>) where S: StringProtocol {
self.init(swipeBack: swipeBack, destination: destination, isActive: isActive) { Text(title) }
}
}
/// Empty Navigation Link
struct EmptyNavigationLink<Destination>: View where Destination: View {
/// Destination of navigation link
var destination: Destination
/// Indicates wheater navigation link is active
@Binding var isActive: Bool
/// Possibility to swipe back
let swipeBack: Bool
init(swipeBack: Bool = true, isActive: Binding<Bool>, @ViewBuilder destination: () -> Destination) {
self.destination = destination()
self._isActive = isActive
self.swipeBack = swipeBack
}
init(swipeBack: Bool = true, isActive: Binding<Bool>, destination: Destination) {
self.destination = destination
self._isActive = isActive
self.swipeBack = swipeBack
}
var body: some View {
CustomNavigationLink(swipeBack: swipeBack, destination: destination, isActive: $isActive) { EmptyView() }.frame(size: .zero)
}
}
/// Empty Sheet Link
struct EmptySheetLink<Content, Item>: View where Content: View, Item: Identifiable {
/// Sheet types
private enum SheetType {
/// with bool and content
case withBool(isPresented: Binding<Bool>, content: () -> Content)
/// with item and content
case withItem(item: Binding<Item?>, content: (Item) -> Content)
}
/// Sheet type
private let sheetType: SheetType
/// On dismiss handler
private let onDismissHandler: (() -> Void)?
/// Init with item and content
init(item: Binding<Item?>, @ViewBuilder content: @escaping (Item) -> Content, onDismiss onDismissHandler: (() -> Void)? = nil) {
self.sheetType = .withItem(item: item, content: content)
self.onDismissHandler = onDismissHandler
}
var body: some View {
switch sheetType {
case .withBool(isPresented: let isPresented, content: let content):
EmptyView()
.frame(size: .zero)
.sheet(isPresented: isPresented, onDismiss: onDismissHandler, content: content)
case .withItem(item: let item, content: let content):
EmptyView()
.frame(size: .zero)
.sheet(item: item, onDismiss: onDismissHandler, content: content)
}
}
}
// Extention of EmptySheetLink to init with bool and content
extension EmptySheetLink where Item == Bool {
/// Init with bool and content
init(isPresented: Binding<Bool>, @ViewBuilder content: @escaping () -> Content, onDismiss onDismissHandler: (() -> Void)? = nil) {
self.sheetType = .withBool(isPresented: isPresented, content: content)
self.onDismissHandler = onDismissHandler
}
}
/// State of data task
enum TaskState {
/// Data task passed
case passed
/// Data task failed
case failed
}
/// State of internet connection
enum ConnectionState {
/// Still loading
case loading
/// No connection
case failed
/// All loaded
case passed
/// Set state to loading and returns true if state wasn't already loading
mutating func start() -> Bool {
guard self != .loading else { return false }
self = .loading
return true
}
mutating func failed() {
self = .failed
}
mutating func passed() {
self = .passed
}
}
/// Type of the change
enum ChangeType: String {
/// Adds item
case add
/// Updates item
case update
/// Deletes item
case delete
}
// Extension of Change Type to confirm to ParameterableObject
extension ChangeType: ParameterableObject {
// Object call with Firebase function as Parameter
var parameterableObject: _ParameterableObject {
rawValue
}
}
| 34.889706 | 140 | 0.601686 |
287ded4dc9346e139f776b8fa32cf4ddf8a0f0de | 8,396 | //
// ImagePickerViewController.swift
// UiApp
//
// Created by Николай Спиридонов on 13.11.2019.
// Copyright © 2019 Artem Esolnyak. All rights reserved.
//
import AVFoundation
import Photos
import UIKit
protocol ImagePickerDelegate {
func imagePickerDelegate(canUseCamera accessIsAllowed: Bool, delegatedForm: ImagePicker)
func imagePickerDelegate(canUseGallery accessIsAllowed: Bool, delegatedForm: ImagePicker)
func imagePickerDelegate(didSelect image: UIImage, delegatedForm: ImagePicker)
func imagePickerDelegate(didCancel delegatedForm: ImagePicker)
}
class ImagePicker: NSObject {
weak var controller: UIImagePickerController?
var cellIndex: Int?
var delegate: ImagePickerDelegate?
var imageIndicator = UIActivityIndicatorView(style: .gray)
func present(parent viewController: UIViewController, sourceType: UIImagePickerController.SourceType) {
let controller = UIImagePickerController()
controller.delegate = self
controller.sourceType = sourceType
self.controller = controller
DispatchQueue.main.async {
viewController.present(controller, animated: true, completion: nil)
}
}
func dismiss() { controller?.dismiss(animated: true, completion: nil) }
}
extension ImagePicker {
private func showAlert(targetName: String, completion: @escaping (Bool)->()) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
let alertVC = UIAlertController(title: "Access to the \(targetName)",
message: "Please provide access to your \(targetName)",
preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Settings", style: .default, handler: { action in
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString),
UIApplication.shared.canOpenURL(settingsUrl) else { completion(false); return }
UIApplication.shared.open(settingsUrl, options: [:]) {
[weak self] _ in self?.showAlert(targetName: targetName, completion: completion)
}
}))
alertVC.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in completion(false) }))
UIApplication.shared.delegate?.window??.rootViewController?.present(alertVC, animated: true, completion: nil)
}
}
func cameraAsscessRequest(cellIndex: Int?) {
self.cellIndex = cellIndex
if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
delegate?.imagePickerDelegate(canUseCamera: true, delegatedForm: self)
} else {
AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
guard let self = self else { return }
if granted {
self.delegate?.imagePickerDelegate(canUseCamera: granted, delegatedForm: self)
} else {
self.showAlert(targetName: "camera") { self.delegate?.imagePickerDelegate(canUseCamera: $0, delegatedForm: self) }
}
}
}
}
func photoGalleryAsscessRequest(cellIndex: Int?) {
self.cellIndex = cellIndex
PHPhotoLibrary.requestAuthorization { [weak self] result in
guard let self = self else { return }
if result == .authorized {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.imagePickerDelegate(canUseGallery: result == .authorized, delegatedForm: self)
}
} else {
self.showAlert(targetName: "photo gallery") { self.delegate?.imagePickerDelegate(canUseCamera: $0, delegatedForm: self) }
}
}
}
}
extension ImagePicker: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
self.controller?.view.addSubview(imageIndicator)
imageIndicator.translatesAutoresizingMaskIntoConstraints = false
imageIndicator.centerXAnchor.constraint(equalTo: self.controller!.view.centerXAnchor).isActive = true
imageIndicator.centerYAnchor.constraint(equalTo: self.controller!.view.centerYAnchor).isActive = true
imageIndicator.startAnimating()
if let image = info[.editedImage] as? UIImage, let index = self.cellIndex {
if image.pngData()!.getSizeInMB() > 15.0 {
print("wrong size")
delegate?.imagePickerDelegate(didCancel: self)
return
}
NotesDataModel.shared.dataModel[index].image = image
setNetworking(image: image, index: index) {
DispatchQueue.main.async {
self.imageIndicator.stopAnimating()
self.delegate?.imagePickerDelegate(didSelect: image, delegatedForm: self)
}
}
return
}
if let image = info[.originalImage] as? UIImage, let index = self.cellIndex {
if image.pngData()!.getSizeInMB() > 15.0 {
print("wrong size")
delegate?.imagePickerDelegate(didCancel: self)
return
}
NotesDataModel.shared.dataModel[index].image = image
setNetworking(image: image, index: index) {
DispatchQueue.main.async {
self.imageIndicator.stopAnimating()
self.delegate?.imagePickerDelegate(didSelect: image, delegatedForm: self)
}
}
}
}
func setNetworking(image: UIImage, index: Int, _ callback: @escaping() -> ()){
let config = URLSessionConfiguration.default
var request = URLRequest(url: URL(string: "https://api.imgbb.com/1/upload?key=7285e498926e9680f20c71e000616bc4")!)
request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
try! request.setMultipartFormData(["image" : image.pngData()!.base64EncodedString(options: .lineLength64Characters)], encoding: .utf8)
URLSession(configuration: config).dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
do {
let json = try JSONDecoder().decode(JSONDecodable.self, from: data)
NotesDataModel.shared.dataModel[index].imageURL = json.data.url
NotesDataModel.uploadNotesToFirebase { (_) in }
} catch {
print(error.localizedDescription)
}
callback()
}.resume()
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
delegate?.imagePickerDelegate(didCancel: self)
}
// MARK: - DecodeJSON
struct JSONDecodable: Codable {
let data: DataClass
let success: Bool
let status: Int
}
// MARK: - DataClass
struct DataClass: Codable {
let id: String
let urlViewer: String
let url, displayURL: String
let title, time: String
let image: Image
let thumb, medium: Medium
let deleteURL: String
enum CodingKeys: String, CodingKey {
case id
case urlViewer = "url_viewer"
case url
case displayURL = "display_url"
case title, time, image, thumb, medium
case deleteURL = "delete_url"
}
}
// MARK: - Image
struct Image: Codable {
let filename, name, mime, imageExtension: String
let url: String
let size: Int
enum CodingKeys: String, CodingKey {
case filename, name, mime
case imageExtension = "extension"
case url, size
}
}
// MARK: - Medium
struct Medium: Codable {
let filename, name, mime, mediumExtension: String
let url: String
let size: String
enum CodingKeys: String, CodingKey {
case filename, name, mime
case mediumExtension = "extension"
case url, size
}
}
}
| 39.603774 | 144 | 0.616008 |
506ee426cc4d850f9fa6a94a65becd214e552df0 | 2,925 | //
// MuteChecker.swift
// xDrip
//
// Created by Ivan Skoryk on 30.06.2020.
// Copyright © 2020 Faifly. All rights reserved.
//
import Foundation
import UIKit
import AudioToolbox
@objcMembers
final class MuteChecker: NSObject {
typealias MuteNotificationCompletion = ((_ mute: Bool) -> Void)
// MARK: Properties
/// Shared instance
static let shared = MuteChecker()
/// Sound ID for mute sound
private let soundUrl = MuteChecker.muteSoundUrl
/// Should notify every second or only when changes?
/// True will notify every second of the state, false only when it changes
var alwaysNotify = true
/// Notification handler to be triggered when mute status changes
/// Triggered every second if alwaysNotify=true, otherwise only when it switches state
var notify: MuteNotificationCompletion?
/// Current mute state
private(set) var isMute = false
/// Silent sound (0.5 sec)
private var soundId: SystemSoundID = 0
/// Time difference between start and finish of mute sound
private var interval: TimeInterval = 0
// MARK: Resources
/// Mute sound url path
private static var muteSoundUrl: URL {
guard let muteSoundUrl = Bundle.main.url(forResource: "mute", withExtension: "aiff") else {
fatalError("mute.aiff not found")
}
return muteSoundUrl
}
// MARK: Init
func checkMute(_ completion: @escaping MuteNotificationCompletion) {
notify = completion
self.soundId = 1
if AudioServicesCreateSystemSoundID(self.soundUrl as CFURL, &self.soundId) == kAudioServicesNoError {
var yes: UInt32 = 1
AudioServicesSetProperty(kAudioServicesPropertyIsUISound,
UInt32(MemoryLayout.size(ofValue: self.soundId)),
&self.soundId,
UInt32(MemoryLayout.size(ofValue: yes)),
&yes)
playSound()
} else {
print("Failed to setup sound player")
self.soundId = 0
}
}
deinit {
if self.soundId != 0 {
AudioServicesRemoveSystemSoundCompletion(self.soundId)
AudioServicesDisposeSystemSoundID(self.soundId)
}
}
// MARK: Methods
/// If not paused, playes mute sound
private func playSound() {
self.interval = Date.timeIntervalSinceReferenceDate
AudioServicesPlaySystemSoundWithCompletion(self.soundId) { [weak self] in
self?.soundFinishedPlaying()
}
}
/// Called when AudioService finished playing sound
private func soundFinishedPlaying() {
let elapsed = Date.timeIntervalSinceReferenceDate - self.interval
let isMute = elapsed < 0.1
DispatchQueue.main.async { [weak self] in
self?.notify?(isMute)
}
}
}
| 30.154639 | 109 | 0.625983 |
d5eb918c5dedef4a4cc1ec2e66c5952697d24ef6 | 742 | //
// StoreConstant.swift
// psr_api_framework
//
// Created by Mouhamed Camara on 9/17/20.
// Copyright © 2020 PayDunya. All rights reserved.
//
import Foundation
public final class StoreConstant
{
public let name: String
public let tagline: String
public let postal_address: String
public let phone: Int
public let logo_url: String
public let website_url: String
public init(name: String, tagline: String, postal_address: String, phone: Int, logo_url: String, website_url: String)
{
self.name = name
self.tagline = tagline
self.postal_address = postal_address
self.phone = phone
self.logo_url = logo_url
self.website_url = website_url
}
}
| 23.935484 | 122 | 0.671159 |
898cdb4870eb3ee9aba713ab0fbdc745cb696cab | 551 | //
// Day20Tests.swift
// AdventOfCode2020
//
// Created by Bo Oelkers on 11/29/20.
//
import XCTest
import AdventOfCode2020
final class Day20Tests: XCTestCase {
private let test = Day20()
func testFirst() throws {
let proposedSolution = test.runProblem(.first, solution: test.first(_:))
print(proposedSolution)
}
func testSecond() throws {
let proposedSolution = test.runProblem(.second, solution: test.second(_:))
print(proposedSolution)
}
static var allTests = [
("testFirst", testFirst),
("testSecond", testSecond)
]
}
| 19.678571 | 76 | 0.707804 |
ccfe94610be42f889f7e952c29cfb5f2c9daba26 | 1,099 | //
// Retry.swift
// NetService
//
// Created by steven on 2021/1/7.
//
import Foundation
public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void
public protocol Retryable {
var retryCount: Int { get set }
mutating func prepareRetry() -> Void
mutating func resetRetry() -> Void
}
public protocol RetryPolicyProtocol {
var retryCount: Int { get }
var timeDelay: TimeInterval { get set }
func retry(_ request: Retryable, with error: Error, completion: RequestRetryCompletion)
}
public struct DefaultRetryPolicy: RetryPolicyProtocol {
public var retryCount: Int {
return 3
}
public var timeDelay: TimeInterval = 0.0
public func retry(_ request: Retryable, with error: Error, completion: RequestRetryCompletion) {
var service = request
if request.retryCount < retryCount {
completion(true, timeDelay)
service.prepareRetry()
} else {
completion(false, timeDelay)
service.resetRetry()
}
}
}
| 23.382979 | 100 | 0.647862 |
5df76a17fc434ad69ad53e03786ff9d8d1bc3e6c | 3,767 | //
// SBTableVC.swift
// SBDropDown
//
// Created by Shashikant's Mac on 7/29/19.
// Copyright © 2019 redbytes. All rights reserved.
//
import UIKit
public protocol SBTableProtocol: class {
func configCellFor(currentIndex: Int, arrSelectedIndex: [Int], currentData: Any, cell: SBTableCell, key: Any?)
func didSelectCell(currentIndex: Int, arrSelectedIndex: [Int], currentData: Any, key: Any?)
func btnSelectSBProtocolPressed(arrSelectedIndex: [Int], arrElements: [Any], key: Any?)
} //protocol
internal class SBTableVC: UIViewController {
// MARK:- Outlets
@IBOutlet weak public var btnSelect : UIButton!
@IBOutlet weak private var tableView : UITableView!
@IBOutlet weak private var lblSeperator : UILabel!
@IBOutlet weak private var alWidthBtnSelect : NSLayoutConstraint! //180
// MARK:- Variables
/// Public Variables
var key : Any?
var arrElement = [Any]()
var arrSelectedIndex = [Int]()
var strSelectBtnTitle = "Select" {
didSet {
if btnSelect != nil {
btnSelect.setTitle(strSelectBtnTitle, for: .normal)
}
}
}
var heightForRow: CGFloat = 50.0
var isShowSelectButton = true
var isReloadAfterSelection = true
var isClearOnDoubleTab = true
var isMultiSelect = true
var isClearData = false
var isDismissOnSelection = false
/// Internal Variables
weak var delegate : SBTableProtocol?
/// Private Variables
private var isReloadNeeded = false
// MARK:- ViewLifeCycle
override public func viewDidLoad() {
super.viewDidLoad()
setUpView()
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if isClearData {
clearSelection()
}
if isMultiSelect {
isClearOnDoubleTab = isMultiSelect
isDismissOnSelection = !isMultiSelect
}
if isReloadNeeded {
isReloadNeeded.toggle()
self.tableView.reloadData()
}
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
isReloadNeeded.toggle()
}
// MARK:- SetUpView
private func setUpView() {
setUpCell()
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
lblSeperator.isHidden = isDismissOnSelection
btnSelect.isHidden = isDismissOnSelection
}
private func setUpCell() {
let bundle = Bundle(for: SBTableVC.self)
let cellNib = UINib.init(nibName: String(describing: SBTableCell.self), bundle: bundle)
tableView.register(cellNib, forCellReuseIdentifier: String(describing: SBTableCell.self))
}
// MARK:- Button Actions
@IBAction private func btnSelectPressed(_ sender: UIButton) {
delegate?.btnSelectSBProtocolPressed(arrSelectedIndex: arrSelectedIndex, arrElements: arrElement, key: key)
self.dismiss(animated: true, completion: nil)
}
// MARK:- Custom Methods
private func clearSelection() {
arrSelectedIndex.removeAll()
self.tableView.reloadData()
}
// MARK:- Receive Memory Warning
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
debugPrint("Receive Memory Warning in \(String(describing: self))")
}
// MARK:- Deinit
deinit {
debugPrint("\(String(describing: self)) controller removed...")
}
} //class
| 31.132231 | 115 | 0.615344 |
d61726cb1668f010ef88717b3efada1a12785297 | 1,127 | /**
* Publish
* Copyright (c) John Sundell 2019
* MIT license, see LICENSE file for details
*/
import Codextended
/// Protocol adopted by types that act as type-safe wrappers around strings.
public protocol StringWrapper: CustomStringConvertible,
ExpressibleByStringInterpolation,
Codable,
Hashable,
Comparable {
/// The underlying string value backing this instance.
var string: String { get }
/// Initialize a new instance with an underlying string value.
/// - parameter string: The string to form a new value from.
init(_ string: String)
}
public extension StringWrapper {
static func <(lhs: Self, rhs: Self) -> Bool {
lhs.string < rhs.string
}
var description: String { string }
init(stringLiteral value: String) {
self.init(value)
}
init(from decoder: Decoder) throws {
try self.init(decoder.decodeSingleValue())
}
func encode(to encoder: Encoder) throws {
try encoder.encodeSingleValue(string)
}
}
| 27.487805 | 76 | 0.611358 |
3825624fbe3a7860f38229ef339e7deb2327f34b | 1,032 | // RUN: %target-typecheck-verify-swift
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(WASI)
import WASILibc
#elseif os(Windows)
import MSVCRT
#else
#error("Unsupported platform")
#endif
_ = FLT_RADIX // expected-warning {{is deprecated}}
_ = FLT_MANT_DIG // expected-warning {{is deprecated}}
_ = FLT_MIN_EXP // expected-warning {{is deprecated}}
_ = FLT_MAX_EXP // expected-warning {{is deprecated}}
_ = FLT_MAX // expected-warning {{is deprecated}}
_ = FLT_EPSILON // expected-warning {{is deprecated}}
_ = FLT_MIN // expected-warning {{is deprecated}}
_ = FLT_TRUE_MIN // expected-warning {{is deprecated}}
_ = DBL_MANT_DIG // expected-warning {{is deprecated}}
_ = DBL_MIN_EXP // expected-warning {{is deprecated}}
_ = DBL_MAX_EXP // expected-warning {{is deprecated}}
_ = DBL_MAX // expected-warning {{is deprecated}}
_ = DBL_EPSILON // expected-warning {{is deprecated}}
_ = DBL_MIN // expected-warning {{is deprecated}}
_ = DBL_TRUE_MIN // expected-warning {{is deprecated}}
| 32.25 | 54 | 0.722868 |
b9c3dd66bacaf1fa76ba9d15da7c0f365ab48907 | 12,691 | //
// StoryViewModel.swift
// SimplifiedIgStories
//
// Created by Tsz-Lung on 08/03/2022.
//
import Foundation
import SwiftUI
import Combine
enum PortionTransitionDirection {
case none, start, forward, backward
}
enum BarPortionAnimationStatus {
case inital, start, restart, pause, resume, finish
}
final class StoryViewModel: ObservableObject {
@Published private(set) var currentStoryPortionId: Int = -1
@Published private(set) var portionTransitionDirection: PortionTransitionDirection = .none
// The key is portionId.
@Published var barPortionAnimationStatuses: [Int: BarPortionAnimationStatus] = [:]
@Published var showConfirmationDialog = false
@Published private(set) var isLoading = false
@Published private(set) var showNoticeLabel = false
@Published private(set) var noticeMsg = ""
private var subscriptions = Set<AnyCancellable>()
let storyId: Int
let storiesViewModel: StoriesViewModel // parent ViewModel
init(storyId: Int, storiesViewModel: StoriesViewModel) {
self.storyId = storyId
self.storiesViewModel = storiesViewModel
self.initCurrentStoryPortionId()
// Reference: https://stackoverflow.com/a/58406402
// Trigger current ViewModel objectWillChange when parent's published property changed.
storiesViewModel.objectWillChange.sink { [weak self] in
self?.objectWillChange.send()
}
.store(in: &subscriptions)
}
}
// MARK: computed variables
extension StoryViewModel {
var story: Story {
// *** All the stories are from local JSON, not from API,
// so I use force unwarp. Don't do this in real environment!
storiesViewModel.stories.first(where: { $0.id == storyId })!
}
var currentPortionAnimationStatus: BarPortionAnimationStatus? {
barPortionAnimationStatuses[currentStoryPortionId]
}
var isCurrentPortionAnimating: Bool {
currentPortionAnimationStatus == .start ||
currentPortionAnimationStatus == .restart ||
currentPortionAnimationStatus == .resume
}
var firstPortionId: Int? {
story.portions.first?.id
}
}
// MARK: functions
extension StoryViewModel {
private func initCurrentStoryPortionId() {
guard let firstPortionId = firstPortionId else { return }
currentStoryPortionId = firstPortionId
}
private func setCurrentBarPortionAnimationStatus(to status: BarPortionAnimationStatus) {
barPortionAnimationStatuses[currentStoryPortionId] = status
}
}
// MARK: functions for StoyView
extension StoryViewModel {
func initStoryAnimation(by storyId: Int) {
if storiesViewModel.currentStoryId == storyId && portionTransitionDirection == .none {
print("StoryId: \(storyId) animation Init!!")
portionTransitionDirection = .start
}
}
func decidePortionTransitionDirection(by point: CGPoint) {
portionTransitionDirection = point.x <= .screenWidth / 2 ? .backward : .forward
}
func deleteCurrentPortion() {
guard
let portionIdx =
story.portions.firstIndex(where: { $0.id == currentStoryPortionId })
else {
return
}
let portions = story.portions
// If next portionIdx within the portions, go next
if portionIdx + 1 < portions.count {
deletePortionFromStory(by: portionIdx)
currentStoryPortionId = portions[portionIdx + 1].id
setCurrentBarPortionAnimationStatus(to: .start)
} else {
storiesViewModel.closeStoryContainer()
deletePortionFromStory(by: portionIdx)
}
}
// *** In real environment, the photo or video should be deleted in server side,
// this is a demo app, however, deleting them from temp directory.
private func deletePortionFromStory(by portionIdx: Int) {
guard
let storyIdx =
storiesViewModel.stories.firstIndex(where: { $0.id == storyId })
else {
return
}
let portion = story.portions[portionIdx]
if let fileUrl = portion.imageUrl ?? portion.videoUrl {
LocalFileManager.shared.deleteFileBy(url: fileUrl)
}
storiesViewModel.stories[storyIdx].portions.remove(at: portionIdx)
}
func savePortionImageVideo() {
guard
let portion =
story.portions.first(where: { $0.id == currentStoryPortionId })
else {
return
}
var publisher: AnyPublisher<String, ImageVideoSaveError>?
if let imageUrl = portion.imageUrl, let uiImage = LocalFileManager.shared.getImageBy(url: imageUrl) {
isLoading = true
publisher = ImageSaver().saveToAlbum(uiImage)
} else if let videoUrl = portion.videoUrlFromCam {
isLoading = true
publisher = VideoSaver().saveToAlbum(videoUrl)
}
publisher?
.receive(on: DispatchQueue.main)
.sink { [weak self] completion in
self?.isLoading = false
switch completion {
case .finished:
break
case .failure(let imageVideoError):
switch imageVideoError {
case .noAddPhotoPermission:
self?.showNotice(withMsg: "Couldn't save. No add photo permission.")
case .saveError(let err):
self?.showNotice(withMsg: "ERROR: \(err.localizedDescription)")
}
}
} receiveValue: { [weak self] msg in
self?.showNotice(withMsg: msg)
}
.store(in: &subscriptions)
}
func showNotice(withMsg msg: String) {
noticeMsg = msg
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
self?.showNoticeLabel = true
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in
self?.showNoticeLabel = false
}
}
}
func pauseAndResumePortion(shouldPause: Bool) {
if shouldPause {
if isCurrentPortionAnimating {
setCurrentBarPortionAnimationStatus(to: .pause)
}
} else {
if currentPortionAnimationStatus == .pause {
setCurrentBarPortionAnimationStatus(to: .resume)
}
}
}
}
// MARK: functions for ProgressBar
extension StoryViewModel {
func performProgressBarTransition(to transitionDirection: PortionTransitionDirection) {
// Not in current story, ignore.
guard storiesViewModel.currentStoryId == story.id else { return }
switch transitionDirection {
case .none: // For continue tap forward/backward to trigger onChange.
break
case .start:
// No first portion, should not be happened.
guard let firstPortionId = firstPortionId else { return }
currentStoryPortionId = firstPortionId
setCurrentBarPortionAnimationStatus(to: .start)
case .forward:
setCurrentBarPortionAnimationStatus(to: .finish)
// Will trigger the onChange of currentPortionAnimationStatus in ProgressBar.
case .backward:
// No first portion, should not happen.
guard let firstPortionId = firstPortionId else { return }
// At the first portion and
if currentStoryPortionId == firstPortionId {
// at the first story,
if story.id == storiesViewModel.currentStories.first?.id {
// just start the animation.
setCurrentBarPortionAnimationStatus(to: currentPortionAnimationStatus == .start ? .restart : .start)
} else { // Not at the first story (that means previous story must exist.),
// go to previous story.
setCurrentBarPortionAnimationStatus(to: .inital)
let currentStories = storiesViewModel.currentStories
guard
let currentStoryIdx =
currentStories.firstIndex(where: { $0.id == story.id })
else {
return
}
let prevStoryIdx = currentStoryIdx - 1
if prevStoryIdx >= 0 { // If within the boundary,
// go previous.
storiesViewModel.currentStoryId = currentStories[prevStoryIdx].id
}
}
} else { // Not at the first story,
// go back to previous portion normally.
setCurrentBarPortionAnimationStatus(to: .inital)
guard
let currentStoryPortionIdx =
story.portions.firstIndex(where: { $0.id == currentStoryPortionId })
else {
return
}
let prevStoryPortionIdx = currentStoryPortionIdx - 1
if prevStoryPortionIdx >= 0 {
currentStoryPortionId = story.portions[prevStoryPortionIdx].id
}
setCurrentBarPortionAnimationStatus(to: .start)
}
portionTransitionDirection = .none // reset
}
}
func performNextProgressBarPortionAnimationWhenFinished(_ portionAnimationStatus: BarPortionAnimationStatus?) {
// Start next portion's animation when current bar portion finished.
guard portionAnimationStatus == .finish else { return }
guard
let currentStoryPortionIdx =
story.portions.firstIndex(where: { $0.id == currentStoryPortionId })
else {
return
}
// At last portion now,
if currentStoryPortionIdx + 1 > story.portions.count - 1 {
let currentStories = storiesViewModel.currentStories
guard
let currentStoryIdx =
currentStories.firstIndex(where: { $0.id == storiesViewModel.currentStoryId })
else {
return
}
// It's the last story now, close StoryContainer.
if currentStoryIdx + 1 > currentStories.count - 1 {
storiesViewModel.closeStoryContainer()
} else { // Not the last stroy now, go to next story.
storiesViewModel.currentStoryId = currentStories[currentStoryIdx + 1].id
}
} else { // Not the last portion, go to next portion.
currentStoryPortionId = story.portions[currentStoryPortionIdx + 1].id
setCurrentBarPortionAnimationStatus(to: .start)
}
portionTransitionDirection = .none // reset
}
func performProgressBarTransitionWhen(isDragging: Bool) {
guard storiesViewModel.currentStoryId == story.id else { return }
if isDragging {
// Pause the animation when dragging.
if isCurrentPortionAnimating {
setCurrentBarPortionAnimationStatus(to: .pause)
}
} else { // Dragged.
if !isCurrentPortionAnimating && !storiesViewModel.isSameStoryAfterDragged {
setCurrentBarPortionAnimationStatus(to: .start)
} else if currentPortionAnimationStatus == .pause {
setCurrentBarPortionAnimationStatus(to: .resume)
}
}
}
func startProgressBarAnimation() {
guard storiesViewModel.currentStoryId == story.id else { return }
// After went to the next story, start its animation.
if !isCurrentPortionAnimating {
setCurrentBarPortionAnimationStatus(to: .start)
}
}
func pasuseOrResumeProgressBarAnimationDepends(on scenePhase: ScenePhase) {
guard storiesViewModel.currentStoryId == story.id else { return }
if scenePhase == .active && currentPortionAnimationStatus == .pause {
setCurrentBarPortionAnimationStatus(to: .resume)
} else if scenePhase == .inactive && isCurrentPortionAnimating {
setCurrentBarPortionAnimationStatus(to: .pause)
}
}
}
| 37.217009 | 120 | 0.589236 |
0e64e4b8d6cd7e4da961e5ce7a4f63c7f0508ef1 | 3,140 | //
// AppDelegate.swift
// SwiftLook
//
// Created by Marko Tadić on 2/17/19.
// Copyright © 2019 AE. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ app: UIApplication, open inputURL: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
// Ensure the URL is a file URL
guard inputURL.isFileURL else { return false }
// Reveal / import the document at the URL
guard let documentBrowserViewController = window?.rootViewController as? DocumentBrowserViewController else { return false }
documentBrowserViewController.revealDocument(at: inputURL, importIfNeeded: true) { (revealedDocumentURL, error) in
if let error = error {
// Handle the error appropriately
print("Failed to reveal the document at URL \(inputURL) with error: '\(error)'")
return
}
// Present the Document View Controller for the revealed URL
documentBrowserViewController.presentDocument(at: revealedDocumentURL!)
}
return true
}
}
| 46.176471 | 285 | 0.715287 |
22fb0703a1b324f23e400dd8914267015d7adfe8 | 5,907 | //
// SplitTraining.swift
// ImageSetDownloader
//
// Created by Zeke Snider on 6/5/18.
// Copyright © 2018 Zeke Snider. All rights reserved.
//
import Foundation
class SplitTraining {
private let testingDirName = "Testing Data"
private let trainingDirName = "Training Data"
private let dsStoreName = ".DS_Store"
private let trainingTestingSplit = 0.8
//Copy contents of the from folders to folders of the same number under
//the to folder
private func copyOut(from folders: [URL], to parentFolderDirectory: URL) {
let myFileManager = FileManager.default
for folder in folders {
let invalidPaths = [dsStoreName]
guard !invalidPaths.contains(folder.lastPathComponent) else {
continue
}
//Get path of where the folder would be located without testing/training subfolders, create the dir
let thisOriginalDir = parentFolderDirectory.appendingPathComponent(folder.lastPathComponent, isDirectory: true)
try! myFileManager.createDirectory(at: thisOriginalDir, withIntermediateDirectories: true, attributes: nil)
//Get all the images in this folder
let imageURLs: [URL] = try! myFileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)
//Move each of the images
for image in imageURLs {
let newImageLocation = thisOriginalDir.appendingPathComponent(image.lastPathComponent, isDirectory: false)
try! myFileManager.moveItem(at: image, to: newImageLocation)
}
//Remove the empty folder
try! myFileManager.removeItem(at: folder)
}
}
public func combine(directory: String) {
combine(parentFolderDirectory: URL(fileURLWithPath: directory))
}
public func combine(parentFolderDirectory: URL) {
print("Combinging folders...")
let myFileManager = FileManager.default
let trainingDirectory = parentFolderDirectory.appendingPathComponent(trainingDirName, isDirectory: true)
let testingDirectory = parentFolderDirectory.appendingPathComponent(testingDirName, isDirectory: true)
let testingFolders: [URL] = try! myFileManager.contentsOfDirectory(at: testingDirectory, includingPropertiesForKeys: nil)
let trainingFolders: [URL] = try! myFileManager.contentsOfDirectory(at: trainingDirectory, includingPropertiesForKeys: nil)
self.copyOut(from: testingFolders, to: parentFolderDirectory)
self.copyOut(from: trainingFolders, to: parentFolderDirectory)
try! myFileManager.removeItem(at: testingDirectory)
try! myFileManager.removeItem(at: trainingDirectory)
print("Done combining folders!")
}
public func split(directory: String) {
split(parentFolderDirectory: URL(fileURLWithPath: directory))
}
public func split(parentFolderDirectory: URL) {
let myFileManager = FileManager.default
let trainingDirectory = parentFolderDirectory.appendingPathComponent(trainingDirName, isDirectory: true)
let testingDirectory = parentFolderDirectory.appendingPathComponent(testingDirName, isDirectory: true)
let folderURLs: [URL] = try! myFileManager.contentsOfDirectory(at: parentFolderDirectory, includingPropertiesForKeys: nil)
for folder in folderURLs {
// We only operate on folders
guard folder.hasDirectoryPath else {
continue
}
//Skip if this is an invalid filename
let invalidPaths = [testingDirName, trainingDirName, dsStoreName]
guard !invalidPaths.contains(folder.lastPathComponent) else {
continue
}
print("Splitting \(folder.lastPathComponent)")
//Create testing/training subfolders for this folder
let thisTrainingDir = trainingDirectory.appendingPathComponent(folder.lastPathComponent, isDirectory: true)
let thisTestingDir = testingDirectory.appendingPathComponent(folder.lastPathComponent, isDirectory: true)
try! myFileManager.createDirectory(at: thisTrainingDir, withIntermediateDirectories: true, attributes: nil)
try! myFileManager.createDirectory(at: thisTestingDir, withIntermediateDirectories: true, attributes: nil)
var imageURLs: [URL] = try! myFileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)
//Shuffle the array and determine the split point for how many files to copy to test/training
//The array is shuffled to ensure that the testing/training sets are randomized from the data set
imageURLs.shuffle()
let imageSplitLocation = Int(round(Double(imageURLs.count) * trainingTestingSplit))
//Loop over all images
for (index, image) in imageURLs.enumerated() {
//If this is before the split point, move the file to the training dir, otherwise
//copy to the testing dir.
let thisFileNewLocation: URL!
if (index <= imageSplitLocation - 1) {
thisFileNewLocation = thisTrainingDir.appendingPathComponent(image.lastPathComponent, isDirectory: false)
} else {
thisFileNewLocation = thisTestingDir.appendingPathComponent(image.lastPathComponent, isDirectory: false)
}
try! myFileManager.moveItem(at: image, to: thisFileNewLocation)
}
//Remove the now empty folder
try! myFileManager.removeItem(at: folder)
}
print("Done splitting!")
}
}
| 47.637097 | 131 | 0.659387 |
23eb269773c719b5cdf3ee2091c1c2157f4e96a7 | 3,762 | //
// SFNTFEAT.swift
//
// The MIT License
// Copyright (c) 2015 - 2019 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
struct SFNTFEAT: RandomAccessCollection {
var version: BEUInt32
var featureNameCount: BEUInt16
var reserved1: BEUInt16
var reserved2: BEUInt32
var data: Data
init(_ data: Data) throws {
var data = data
self.version = try data.decode(BEUInt32.self)
self.featureNameCount = try data.decode(BEUInt16.self)
self.reserved1 = try data.decode(BEUInt16.self)
self.reserved2 = try data.decode(BEUInt32.self)
self.data = data
}
var startIndex: Int {
return 0
}
var endIndex: Int {
return Int(featureNameCount)
}
subscript(position: Int) -> Name? {
precondition(position < count, "Index out of range.")
var data = self.data.dropFirst(12 * position)
guard let feature = try? data.decode(BEUInt16.self) else { return nil }
guard let nSettings = try? data.decode(BEUInt16.self) else { return nil }
guard let settingTable = try? data.decode(BEUInt32.self), settingTable >= 12 else { return nil }
guard let featureFlags = try? data.decode(BEUInt16.self) else { return nil }
guard let nameIndex = try? data.decode(BEInt16.self) else { return nil }
return Name(feature: feature, nSettings: nSettings, settingTable: settingTable, featureFlags: featureFlags, nameIndex: nameIndex, data: self.data.dropFirst(Int(settingTable) - 12))
}
}
extension SFNTFEAT {
struct Name {
var feature: BEUInt16
var nSettings: BEUInt16
var settingTable: BEUInt32
var featureFlags: BEUInt16
var nameIndex: BEInt16
var data: Data
}
}
extension SFNTFEAT.Name {
var isExclusive: Bool {
return featureFlags & 0x8000 != 0
}
var defaultSetting: Int {
let index = featureFlags & 0x4000 == 0 ? 0 : Int(featureFlags & 0xff)
return index < nSettings ? index : 0
}
}
extension SFNTFEAT.Name: RandomAccessCollection {
struct Setting {
var setting: BEUInt16
var nameIndex: BEInt16
}
var startIndex: Int {
return 0
}
var endIndex: Int {
return Int(nSettings)
}
subscript(position: Int) -> Setting? {
precondition(position < count, "Index out of range.")
var data = self.data.dropFirst(4 * position)
guard let setting = try? data.decode(BEUInt16.self) else { return nil }
guard let nameIndex = try? data.decode(BEInt16.self) else { return nil }
return Setting(setting: setting, nameIndex: nameIndex)
}
}
| 30.33871 | 188 | 0.67092 |
e043902c47e00451bb8ffff4d0327e5ab8b48c2b | 18,453 | //
// CalendarDateRangePickerViewController.swift
// CalendarDateRangePickerViewController
//
// Created by Miraan on 15/10/2017.
// Improved and maintaining by Ljuka
// Copyright © 2017 Miraan. All rights reserved.
//
import UIKit
@objc public protocol CalendarDateRangePickerViewControllerDelegate: class {
func didCancelPickingDateRange()
func didPickDateRange(startDate: Date!, endDate: Date!)
func didSelectStartDate(startDate: Date!)
func didSelectEndDate(endDate: Date!)
}
@objcMembers public class CalendarDateRangePickerViewController: UICollectionViewController {
let cellReuseIdentifier = "CalendarDateRangePickerCell"
let headerReuseIdentifier = "CalendarDateRangePickerHeaderView"
weak public var delegate: CalendarDateRangePickerViewControllerDelegate!
let itemsPerRow = 7
let itemHeight: CGFloat = 40
let collectionViewInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
public var minimumDate: Date!
public var maximumDate: Date!
public var locale: Locale?
public var selectedStartDate: Date?
public var selectedEndDate: Date?
var selectedStartCell: IndexPath?
var selectedEndCell: IndexPath?
public var disabledDates: [Date]?
public var cellHighlightedColor = UIColor(white: 0.9, alpha: 1.0)
public static let defaultCellFontSize: CGFloat = 15.0
public static let defaultHeaderFontSize: CGFloat = 17.0
public var cellFont: UIFont = UIFont(name: "HelveticaNeue", size: CalendarDateRangePickerViewController.defaultCellFontSize)!
public var headerFont: UIFont = UIFont(name: "HelveticaNeue-Light", size: CalendarDateRangePickerViewController.defaultHeaderFontSize)!
public var selectedColor = UIColor(red: 66 / 255.0, green: 150 / 255.0, blue: 240 / 255.0, alpha: 1.0)
public var selectedLabelColor = UIColor(red: 255 / 255.0, green: 255 / 255.0, blue: 255 / 255.0, alpha: 1.0)
public var highlightedLabelColor = UIColor(red: 255 / 255.0, green: 255 / 255.0, blue: 255 / 255.0, alpha: 1.0)
public var titleText = "Select Dates"
public var cancelText = "Cancel"
public var doneText = "Done"
public var selectionMode: SelectionMode = .range
public var firstDayOfWeek: DayOfWeek = .sunday
@objc public enum SelectionMode: Int {
case range = 0
case single = 1
}
@objc public enum DayOfWeek: Int {
case monday = 0
case sunday = 1
}
override public func viewDidLoad() {
super.viewDidLoad()
self.title = self.titleText
collectionView?.dataSource = self
collectionView?.delegate = self
if #available(iOS 13.0, *) {
collectionView?.backgroundColor = UIColor.systemBackground
} else {
collectionView?.backgroundColor = UIColor.white
}
collectionView?.register(CalendarDateRangePickerCell.self, forCellWithReuseIdentifier: cellReuseIdentifier)
collectionView?.register(CalendarDateRangePickerHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerReuseIdentifier)
collectionView?.contentInset = collectionViewInsets
if minimumDate == nil {
minimumDate = Date()
}
if maximumDate == nil {
maximumDate = Calendar.current.date(byAdding: .year, value: 3, to: minimumDate)
}
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: cancelText, style: .plain, target: self, action: #selector(CalendarDateRangePickerViewController.didTapCancel))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: doneText, style: .done, target: self, action: #selector(CalendarDateRangePickerViewController.didTapDone))
self.navigationItem.rightBarButtonItem?.isEnabled = selectedStartDate != nil && selectedEndDate != nil
}
@objc func didTapCancel() {
delegate.didCancelPickingDateRange()
}
@objc func didTapDone() {
if selectedStartDate == nil || selectedEndDate == nil {
return
}
delegate.didPickDateRange(startDate: selectedStartDate!, endDate: selectedEndDate!)
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if selectedStartDate != nil {
self.scrollToSelection()
}
}
}
extension CalendarDateRangePickerViewController {
// UICollectionViewDataSource
override public func numberOfSections(in collectionView: UICollectionView) -> Int {
let difference = Calendar.current.dateComponents([.month], from: minimumDate, to: maximumDate)
return difference.month! + 1
}
override public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let firstDateForSection = getFirstDateForSection(section: section)
let weekdayRowItems = 7
let blankItems = getWeekday(date: firstDateForSection) - 1
let daysInMonth = getNumberOfDaysInMonth(date: firstDateForSection)
return weekdayRowItems + blankItems + daysInMonth
}
override public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) as! CalendarDateRangePickerCell
cell.highlightedColor = self.cellHighlightedColor
cell.selectedColor = self.selectedColor
cell.selectedLabelColor = self.selectedLabelColor
cell.highlightedLabelColor = self.highlightedLabelColor
cell.font = self.cellFont
cell.reset()
let blankItems = getWeekday(date: getFirstDateForSection(section: indexPath.section)) - 1
if indexPath.item < 7 {
cell.label.text = getWeekdayLabel(weekday: indexPath.item + 1)
} else if indexPath.item < 7 + blankItems {
cell.label.text = ""
} else {
let dayOfMonth = indexPath.item - (7 + blankItems) + 1
let date = getDate(dayOfMonth: dayOfMonth, section: indexPath.section)
cell.date = date
cell.label.text = "\(dayOfMonth)"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let datePreFormatted = dateFormatter.string(from: date)
let dateFormatted = dateFormatter.date(from: datePreFormatted)
if disabledDates != nil {
if (disabledDates?.contains(cell.date!))! {
cell.disable()
}
}
if isBefore(dateA: date, dateB: minimumDate) {
cell.disable()
}
if selectedStartDate != nil && selectedEndDate != nil && isBefore(dateA: selectedStartDate!, dateB: date) && isBefore(dateA: date, dateB: selectedEndDate!) {
// Cell falls within selected range
if dayOfMonth == 1 {
if #available(iOS 9.0, *) {
if UIView.appearance().semanticContentAttribute == .forceRightToLeft {
cell.highlightLeft()
}
else {
cell.highlightRight()
}
} else {
// Use the previous technique
if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft {
cell.highlightLeft()
}
else {
cell.highlightRight()
}
}
} else if dayOfMonth == getNumberOfDaysInMonth(date: date) {
if #available(iOS 9.0, *) {
if UIView.appearance().semanticContentAttribute == .forceRightToLeft {
cell.highlightRight()
}
else {
cell.highlightLeft()
}
} else {
// Use the previous technique
if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft {
cell.highlightRight()
}
else {
cell.highlightLeft()
}
}
} else {
cell.highlight()
}
} else if selectedStartDate != nil && areSameDay(dateA: date, dateB: selectedStartDate!) {
// Cell is selected start date
cell.select()
if selectedEndDate != nil {
if #available(iOS 9.0, *) {
if UIView.appearance().semanticContentAttribute == .forceRightToLeft {
cell.highlightLeft()
}
else {
cell.highlightRight()
}
} else {
// Use the previous technique
if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft {
cell.highlightLeft()
}
else {
cell.highlightRight()
}
}
}
} else if selectedEndDate != nil && areSameDay(dateA: date, dateB: selectedEndDate!) {
cell.select()
if #available(iOS 9.0, *) {
if UIView.appearance().semanticContentAttribute == .forceRightToLeft {
cell.highlightRight()
}
else {
cell.highlightLeft()
}
} else {
// Use the previous technique
if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft {
cell.highlightRight()
}
else {
cell.highlightLeft()
}
}
}
}
return cell
}
override public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerReuseIdentifier, for: indexPath) as! CalendarDateRangePickerHeaderView
headerView.label.text = getMonthLabel(date: getFirstDateForSection(section: indexPath.section))
headerView.font = headerFont
return headerView
default:
fatalError("Unexpected element kind")
}
}
}
extension CalendarDateRangePickerViewController: UICollectionViewDelegateFlowLayout {
override public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! CalendarDateRangePickerCell
if cell.date == nil {
return
}
if isBefore(dateA: cell.date!, dateB: minimumDate) {
return
}
if disabledDates != nil {
if (disabledDates?.contains(cell.date!))! {
return
}
}
if selectedStartDate == nil || selectionMode == .single {
selectedStartDate = cell.date
selectedStartCell = indexPath
delegate.didSelectStartDate(startDate: selectedStartDate)
} else if selectedEndDate == nil {
if isBefore(dateA: selectedStartDate!, dateB: cell.date!) && !isBetween(selectedStartCell!, and: indexPath) {
selectedEndDate = cell.date
delegate.didSelectEndDate(endDate: selectedEndDate)
self.navigationItem.rightBarButtonItem?.isEnabled = true
} else {
// If a cell before the currently selected start date is selected then just set it as the new start date
selectedStartDate = cell.date
selectedStartCell = indexPath
delegate.didSelectStartDate(startDate: selectedStartDate)
}
} else {
selectedStartDate = cell.date
selectedStartCell = indexPath
delegate.didSelectStartDate(startDate: selectedStartDate)
selectedEndDate = nil
}
collectionView.reloadData()
}
public func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let padding = collectionViewInsets.left + collectionViewInsets.right
let availableWidth = view.frame.width - padding
let itemWidth = availableWidth / CGFloat(itemsPerRow)
return CGSize(width: itemWidth, height: itemHeight)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: view.frame.size.width, height: 50)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
extension CalendarDateRangePickerViewController {
// Helper functions
private func scrollToSelection() {
if let uCollectionView = collectionView {
if let date = self.selectedStartDate {
let calendar = Calendar.current
let yearDiff = calendar.component(.year, from: date) - calendar.component(.year, from: minimumDate)
let selectedMonth = calendar.component(.month, from: date) + yearDiff * 12
uCollectionView.scrollToItem(at: IndexPath(row: calendar.component(.day, from: date), section: selectedMonth - 1), at: UICollectionView.ScrollPosition.centeredVertically, animated: false)
}
}
}
@objc func getFirstDate() -> Date {
var components = Calendar.current.dateComponents([.month, .year], from: minimumDate)
components.day = 1
return Calendar.current.date(from: components)!
}
@objc func getFirstDateForSection(section: Int) -> Date {
return Calendar.current.date(byAdding: .month, value: section, to: getFirstDate())!
}
@objc func getMonthLabel(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM yyyy"
if let locale = locale {dateFormatter.locale = locale}
return dateFormatter.string(from: date).capitalized
}
@objc func getWeekdayLabel(weekday: Int) -> String {
var components = DateComponents()
components.calendar = Calendar.current
components.weekday = weekday
if(firstDayOfWeek == .monday) {
if(weekday == 7) {
components.weekday = 1
}
else {
components.weekday = weekday + 1
}
}
let date = Calendar.current.nextDate(after: Date(), matching: components, matchingPolicy: Calendar.MatchingPolicy.strict)
if date == nil {
return "E"
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEEE"
if let locale = locale {dateFormatter.locale = locale}
return dateFormatter.string(from: date!).uppercased()
}
@objc func getWeekday(date: Date) -> Int {
let weekday = Calendar.current.dateComponents([.weekday], from: date).weekday!
if(firstDayOfWeek == .monday) {
if(weekday == 1) {
return 7
}
else {
return weekday - 1
}
}
else {
return weekday
}
}
@objc func getNumberOfDaysInMonth(date: Date) -> Int {
return Calendar.current.range(of: .day, in: .month, for: date)!.count
}
@objc func getDate(dayOfMonth: Int, section: Int) -> Date {
var components = Calendar.current.dateComponents([.month, .year], from: getFirstDateForSection(section: section))
components.day = dayOfMonth
return Calendar.current.date(from: components)!
}
@objc func areSameDay(dateA: Date, dateB: Date) -> Bool {
return Calendar.current.compare(dateA, to: dateB, toGranularity: .day) == ComparisonResult.orderedSame
}
@objc func isBefore(dateA: Date, dateB: Date) -> Bool {
return Calendar.current.compare(dateA, to: dateB, toGranularity: .day) == ComparisonResult.orderedAscending
}
@objc func isBetween(_ startDateCellIndex: IndexPath, and endDateCellIndex: IndexPath) -> Bool {
if disabledDates == nil {
return false
}
var index = startDateCellIndex.row
var section = startDateCellIndex.section
var currentIndexPath: IndexPath
var cell: CalendarDateRangePickerCell?
while !(index == endDateCellIndex.row && section == endDateCellIndex.section) {
currentIndexPath = IndexPath(row: index, section: section)
cell = collectionView?.cellForItem(at: currentIndexPath) as? CalendarDateRangePickerCell
if cell?.date == nil {
section = section + 1
let blankItems = getWeekday(date: getFirstDateForSection(section: section)) - 1
index = 7 + blankItems
currentIndexPath = IndexPath(row: index, section: section)
cell = collectionView?.cellForItem(at: currentIndexPath) as? CalendarDateRangePickerCell
}
if cell != nil && (disabledDates?.contains((cell!.date)!))! {
return true
}
index = index + 1
}
return false
}
}
| 41.467416 | 203 | 0.610361 |
bff20697e89c2bde64f84ab6b6193eba0d0b45b7 | 1,693 | //
// Mastering SwiftUI
// Copyright (c) KxCoding <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import SwiftUI
struct TextFieldStyles: View {
@State private var email: String = ""
@State private var password: String = ""
@State private var favoriteNumber: Int = 0
var body: some View {
Form {
TextField("Email", text: $email, prompt: Text("Input Email"))
SecureField("Password", text: $password, prompt: Text("Input Password"))
}
}
}
struct TextFieldStyles_Previews: PreviewProvider {
static var previews: some View {
TextFieldStyles()
}
}
| 38.477273 | 84 | 0.709982 |
79a7a045481ef1644a1992c0a2360fb73417cb37 | 1,295 | import Quick
import Nimble
@testable import Shuffle
struct MockCardAnimator: CardAnimatable {
static var resetCalled: Bool = false
static func reset(_ card: SwipeCard) {
resetCalled = true
}
static var swipeCalled: Bool = false
static var swipeDirection: SwipeDirection?
static var swipeForced: Bool?
static func swipe(_ card: SwipeCard, direction: SwipeDirection, forced: Bool) {
swipeCalled = true
swipeDirection = direction
swipeForced = forced
}
static var reverseSwipeCalled: Bool = false
static var reverseSwipeDirection: SwipeDirection?
static func reverseSwipe(_ card: SwipeCard, from direction: SwipeDirection) {
reverseSwipeCalled = true
reverseSwipeDirection = direction
}
static var removeAllAnimationsCalled: Bool = false
static func removeAllAnimations(on card: SwipeCard) {
removeAllAnimationsCalled = true
}
// MARK: - Test Helpers
static func reset() {
resetCalled = false
swipeCalled = false
swipeDirection = nil
swipeForced = nil
reverseSwipeCalled = false
reverseSwipeDirection = nil
removeAllAnimationsCalled = false
}
}
| 25.392157 | 83 | 0.649421 |
64d90223bb9a8ff61c7e0971a7563d9b2da43534 | 15,113 | //
// MonthlyDataSource.swift
// Stamps
//
// Created by Alexander on 16.05.2020.
// Copyright © 2020 Vladimir Svidersky. All rights reserved.
//
import Foundation
import UIKit
class CalendarDataBuilder {
private let repository: DataRepository
private let calendar: CalendarHelper
init(repository: DataRepository, calendar: CalendarHelper) {
self.repository = repository
self.calendar = calendar
self.localCache = [:]
}
// MARK: - Today View data building
/// Build data model for the single week for Today view
func weekDataModel(for week: CalendarHelper.Week) -> [[StickerData]] {
return weekStickers(week: week).map { $0.map {
StickerData(
stampId: $0.id,
label: $0.label,
color: $0.color,
isUsed: false
)
}}
}
/// Retrieve monthly and weeky awards for the week
func awards(for week: CalendarHelper.Week) -> [Award] {
return repository
.awardsInInterval(from: week.firstDay, to: week.lastDay)
}
// MARK: - Navigation viability
static let secondsInDay = (60 * 60 * 24)
// We allow to move one week forward from the week with last entry (i.e. showing next empty week)
func canMoveForward(_ week: CalendarHelper.Week) -> Bool {
let lastEntryDate = repository.getLastDiaryDate() ?? Date()
let nextWeekFirstDay = week.firstDay.byAddingWeek(1)
let distance = Int(nextWeekFirstDay.timeIntervalSince(lastEntryDate))
return !(distance > (7 * CalendarDataBuilder.secondsInDay))
}
// We allow to move one week back from the week with last entry (i.e. showing one empty week)
func canMoveBackward(_ week: CalendarHelper.Week) -> Bool {
let firstEntryDate = repository.getFirstDiaryDate() ?? Date()
let prevWeekLastDay = week.lastDay.byAddingWeek(-1)
let distance = Int(firstEntryDate.timeIntervalSince(prevWeekLastDay))
return !(distance > (7 * CalendarDataBuilder.secondsInDay))
}
// Don't allow to move to the next month if there is no data for the next month
func canMoveForward(_ month: CalendarHelper.Month) -> Bool {
let lastEntryDate = repository.getLastDiaryDate() ?? Date()
let nextMonthFirstDay = month.firstDay.byAddingMonth(1)
let distance = Int(nextMonthFirstDay.timeIntervalSince(lastEntryDate))
return !(distance > 0)
}
// Don't allow to move to the previous month if there is no data for the next month
func canMoveBackward(_ month: CalendarHelper.Month) -> Bool {
let firstEntryDate = repository.getFirstDiaryDate() ?? Date()
let nextMonthLastDay = month.lastDay.byAddingMonth(-1)
let distance = Int(firstEntryDate.timeIntervalSince(nextMonthLastDay))
return !(distance > 0)
}
// Don't allow to move to the next year if there is no data for the next month
func canMoveForward(_ year: CalendarHelper.Year) -> Bool {
let lastEntryDate = repository.getLastDiaryDate() ?? Date()
let nextYearFirstDay = year.firstDay.byAddingMonth(12)
let distance = Int(nextYearFirstDay.timeIntervalSince(lastEntryDate))
return !(distance > 0)
}
// Don't allow to move to the previous year if there is no data for the next month
func canMoveBackward(_ year: CalendarHelper.Year) -> Bool {
let firstEntryDate = repository.getFirstDiaryDate() ?? Date()
let nextYearLastDay = year.lastDay.byAddingMonth(-12)
let distance = Int(firstEntryDate.timeIntervalSince(nextYearLastDay))
return !(distance > 0)
}
// MARK: - Stats page data building
/// Retrieve weekly stats for specific week for list of stamps - synchroniously
func weeklyStats(for week: CalendarHelper.Week, allStamps: [Stamp]) -> [WeekLineData] {
let diary = repository.diaryForDateInterval(from: week.firstDay, to: week.lastDay)
return allStamps.compactMap({
guard let stampId = $0.id else { return nil }
let bits = (0..<7).map({
let date = week.firstDay.byAddingDays($0)
return diary.contains(where: {
$0.date.databaseKey == date.databaseKey && $0.stampId == stampId }) ? "1" : "0"
}).joined(separator: "|")
return WeekLineData(
stampId: stampId,
label: $0.label,
color: $0.color,
bitsAsString: bits)
})
}
/// Creates Monthly stats empty data - actual statistics will be loaded asynchrouniously
func emptyStatsData(for month: CalendarHelper.Month, stamps: [Stamp]) -> [MonthBoxData] {
let weekdayHeaders = CalendarHelper.Week(Date()).weekdayLettersForWeek()
return stamps.compactMap({
guard let stampId = $0.id else { return nil }
// Create empty bits array for number of days in the month. Actual data will
// be loaded asynchroniously using `monthlyStatsForStampAsync` call
let bits = String(repeating: "0|", count: month.numberOfDays-1) + "0"
return MonthBoxData(
primaryKey: UUID(),
stampId: stampId,
label: $0.label,
name: $0.name,
color: $0.color,
weekdayHeaders: weekdayHeaders,
firstDayKey: month.firstDay.databaseKey,
numberOfWeeks: month.numberOfWeeks,
firstDayOffset: month.firstIndex,
bitsAsString: bits
)
})
}
/// Creates Year stats empty data - actual statistics will be loaded asynchrouniously
func emptyStatsData(for year: CalendarHelper.Year, stamps: [Stamp]) -> [YearBoxData] {
let weekdayHeaders = CalendarHelper.Week(Date()).weekdayLettersForWeek()
return stamps.compactMap({
guard let stampId = $0.id else { return nil }
// Create empty bits array for number of days in the month. Actual data will
// be loaded asynchroniously using `monthlyStatsForStampAsync` call
let bits = String(repeating: "0|", count: year.numberOfDays-1) + "0"
return YearBoxData(
primaryKey: UUID(),
stampId: stampId,
label: $0.label,
name: $0.name,
color: $0.color,
weekdayHeaders: weekdayHeaders,
monthHeaders: [""],
year: year.year,
numberOfWeeks: year.numberOfWeeks,
firstDayOffset: year.firstIndex,
bitsAsString: bits
)
})
}
/// Local cache to store already calculated monthly stats
var localCache: [String:String]
// TODO: Come up with cache invalidating logic
/// Asynchronously returns monthly statistics as bit string by stampId and month
func monthlyStatsForStampAsync(stampId: Int64, month: CalendarHelper.Month,
completion: @escaping (String) -> Void)
{
let key = "\(stampId)-\(month.firstDay.databaseKey)"
if let local = localCache[key] {
completion(local)
return
}
DispatchQueue.global().async {
let diary = self.repository.diaryForDateInterval(
from: month.firstDay, to: month.lastDay, stampId: stampId)
let bits = (0..<month.numberOfDays).map({
let date = month.firstDay.byAddingDays($0)
return diary.contains(where: {
$0.date.databaseKey == date.databaseKey && $0.stampId == stampId }) ? "1" : "0"
}).joined(separator: "|")
// Update local cache before returning
self.localCache[key] = bits
completion(bits)
}
}
// TODO: !!!! Need to be optimized a lot
/// Asynchronously returns monthly statistics as bit string by stampId and month
func yearlyStatsForStampAsync(stampId: Int64, year: CalendarHelper.Year,
completion: @escaping (String) -> Void)
{
let key = "\(stampId)-\(year.year)"
if let local = localCache[key] {
completion(local)
return
}
DispatchQueue.global().async {
let diary = self.repository.diaryForDateInterval(
from: year.firstDay, to: year.lastDay, stampId: stampId)
let bits = (0..<year.numberOfDays).map({
let date = year.firstDay.byAddingDays($0)
return diary.contains(where: {
$0.date.databaseKey == date.databaseKey && $0.stampId == stampId }) ? "1" : "0"
}).joined(separator: "|")
// Update local cache before returning
self.localCache[key] = bits
completion(bits)
}
}
/// Builds history for a given sticker (including how many time it's been reached and what is the average
func historyFor(sticker id: Int64?) -> StickerUsedData? {
guard let id = id,
let sticker = repository.stampBy(id: id),
let first = repository.getFirstDateFor(sticker: id) else { return nil }
let weeksFromToday = abs(Date().distance(to: first) / (7 * 24 * 60 * 60))
var average = Double(sticker.count) / weeksFromToday
var averageText = "sticker_average_per_week".localized(String(format: "%.1f", average))
if weeksFromToday < 2 {
averageText = "sticker_average_too_early".localized
} else if average < 1 {
// Update from weekly average to monthly
average = average * (30 / 7)
averageText = "sticker_average_per_month".localized(String(format: "%.1f", average))
}
return StickerUsedData(
count: sticker.count,
lastUsed: sticker.lastUsed,
onAverage: averageText
)
}
/// Builds history for a give goal (including how many time it's been reached and what is the current streak
func historyFor(goal id: Int64?, limit: Int) -> GoalHistoryData? {
guard let goal = repository.goalBy(id: id),
let first = goal.stamps
.compactMap({ return repository.getFirstDateFor(sticker: $0) })
.min() else { return nil }
var points = [GoalChartPoint]()
var streak = 0
var streakRunning = true
var headerText = ""
switch goal.period {
case .week:
headerText = "last_x_weeks".localized(limit)
var week = CalendarHelper.Week(Date().byAddingWeek(-1))
while (week.lastDay > first) {
if let award = repository.awardsInInterval(from: week.firstDay, to: week.lastDay).first(where: { $0.goalId == goal.id }) {
if points.count < limit {
points.append(
GoalChartPoint(
weekStart: week.firstDay,
award: award,
goal: goal
)
)
}
if award.reached && streakRunning {
streak = streak + 1
} else if !award.reached {
streakRunning = false
if points.count >= limit {
break
}
}
} else {
if points.count < limit {
points.append(
GoalChartPoint(
weekStart: week.firstDay,
goal: goal
)
)
}
streakRunning = false
}
print("streak \(streak)")
week = CalendarHelper.Week(week.firstDay.byAddingWeek(-1))
}
// Check current week to see if we need to increase the streak
week = CalendarHelper.Week(Date())
if (repository.awardsInInterval(from: week.firstDay, to: week.lastDay).first(where: { $0.goalId == goal.id && $0.reached == true }) != nil) {
streak += 1
}
case .month:
headerText = "last_x_months".localized(limit)
var month = CalendarHelper.Month(Date().byAddingMonth(-1))
while (month.lastDay > first) {
if let award = repository.awardsInInterval(from: month.firstDay, to: month.lastDay).first(where: { $0.goalId == goal.id }) {
if points.count < limit {
points.append(
GoalChartPoint(
weekStart: month.firstDay,
award: award,
goal: goal
)
)
}
if award.reached && streakRunning {
streak = streak + 1
} else if !award.reached {
streakRunning = false
if points.count >= limit {
break
}
}
} else {
if points.count < limit {
points.append(
GoalChartPoint(
weekStart: month.firstDay,
goal: goal
)
)
}
streakRunning = false
}
month = CalendarHelper.Month(month.firstDay.byAddingMonth(-1))
}
// Check current week to see if we need to increase the streak
month = CalendarHelper.Month(Date())
if (repository.awardsInInterval(from: month.firstDay, to: month.lastDay).first(where: { $0.goalId == goal.id && $0.reached == true }) != nil) {
streak += 1
}
default:
break
}
return GoalHistoryData(
reached: GoalReachedData(
count: goal.count,
lastUsed: goal.lastUsed,
streak: streak
),
chart: GoalChartData(
header: headerText,
points: points
)
)
}
// MARK: - Helpers
// Returns a list of Stamps grouped by day for a given week.
func weekStickers(week: CalendarHelper.Week) -> [[Stamp]] {
return (0...6)
.map({
let date = week.firstDay.byAddingDays($0)
return repository.stampsFor(day: date)
})
}
}
| 39.562827 | 155 | 0.538344 |
f7d48dadf847addf4b6065067f0e87c4c0b5ada8 | 2,096 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
Additional detailed information about a message response and how it was generated.
*/
public struct MessageOutputDebug: Decodable {
/**
When `branch_exited` is set to `true` by the Assistant, the `branch_exited_reason` specifies whether the dialog
completed by itself or got interrupted.
*/
public enum BranchExitedReason: String {
case completed = "completed"
case fallback = "fallback"
}
/**
An array of objects containing detailed diagnostic information about the nodes that were triggered during
processing of the input message.
*/
public var nodesVisited: [DialogNodesVisited]?
/**
An array of up to 50 messages logged with the request.
*/
public var logMessages: [DialogLogMessage]?
/**
Assistant sets this to true when this message response concludes or interrupts a dialog.
*/
public var branchExited: Bool?
/**
When `branch_exited` is set to `true` by the Assistant, the `branch_exited_reason` specifies whether the dialog
completed by itself or got interrupted.
*/
public var branchExitedReason: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case nodesVisited = "nodes_visited"
case logMessages = "log_messages"
case branchExited = "branch_exited"
case branchExitedReason = "branch_exited_reason"
}
}
| 32.75 | 116 | 0.707061 |
f75267667e63f8f27bfc620f897d8a6f8d53575c | 7,211 | //
// ItemLargeTableViewController.swift
// Acornote
//
// Created by Tonny on 29/10/2016.
// Copyright © 2016 Tonny&Sunm. All rights reserved.
//
import UIKit
import SafariServices
import AVFoundation
class ItemLargeTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var item: Item?
@IBOutlet weak var tableView: UITableView!
//
@IBOutlet weak var audioBtn: UIButton!
@IBOutlet weak var linkBtn: UIButton!
@IBOutlet weak var tagBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
updateBtns()
NotificationCenter.default.addObserver(self, selector: .itemChanged, name: .itemChanged, object: nil)
}
@objc func itemChanged(noti: Notification) {
tableView.reloadData()
}
func updateBtns() {
audioBtn.isHidden = item?.folder?.playable == false
linkBtn.isHidden = item?.url == nil
tagBtn.isSelected = item?.taged == true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
@IBAction func speak(_ sender: AnyObject) {
guard let item = self.item else {
return
}
if speecher.isSpeaking {
speecher.stopSpeaking(at: .immediate)
}
if item.fliped == false {
let utterence = AVSpeechUtterance(string: item.title!.replacingOccurrences(of: "\n", with: ", "))
utterence.voice = AVSpeechSynthesisVoice(language: item.title!.voiceLanguage)
speecher.speak(utterence)
}else {
if let des = item.des {
let utterence = AVSpeechUtterance(string: des.replacingOccurrences(of: "\n", with: ", "))
utterence.voice = AVSpeechSynthesisVoice(language: des.voiceLanguage)
speecher.speak(utterence)
}
}
}
@IBAction func link(_ sender: AnyObject) {
guard let path = self.item?.url, let url = URL(string: path) else {
return
}
let svc = storyboard!.instantiateViewController(withIdentifier:"WebViewController") as! WebViewController
svc.url = url
svc.folder = self.item?.folder
navigationController?.pushViewController(svc, animated: true)
}
@IBAction func bing(_ sender: AnyObject) {
guard let item = self.item, let title = item.title, let path = "https://www.bing.com/images/search?q=\(title)&FORM=HDRSC2".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: path) else {
return
}
let svc = storyboard!.instantiateViewController(withIdentifier:"WebViewController") as! WebViewController
svc.url = url
svc.item = item
navigationController?.pushViewController(svc, animated: true)
}
@IBAction func edit(_ sender: AnyObject) {
// pageVC.
let sb:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier:"EditItemViewController") as! EditItemViewController
vc.folder = self.item?.folder
vc.item = self.item
let nav = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController
nav?.present(vc, animated: true, completion: nil)
}
@IBAction func tag(_ sender: UIButton) {
item?.update(update: { (obj) in
let item = obj as! Item
item.taged = !item.taged
}, callback: nil)
sender.isSelected = !sender.isSelected
}
}
extension Selector {
static let itemChanged = #selector(ItemLargeTableViewController.itemChanged(noti:))
}
extension Notification.Name {
static let itemChanged = NSNotification.Name("itemChanged")
}
extension ItemLargeTableViewController {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return item == nil ? 0 : 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ItemLargeTableViewCell
cell.item = item!
return cell
}
static let titleFont = UIFont(name: "Arial-BoldMT", size: 40) ?? UIFont.systemFont(ofSize: 40)
static let desFont = UIFont(name: "Arial", size: 20) ?? UIFont.systemFont(ofSize: 20)
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return item?.largeCellHeight ?? 0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if item?.folder?.quizlet == true {
let cell = tableView.cellForRow(at: indexPath) as! ItemLargeTableViewCell
if cell.item.fliped == false {
cell.titleTxtView.isHidden = true
cell.desTxtView.superview?.isHidden = false
}else {
cell.titleTxtView.isHidden = false
cell.desTxtView.superview?.isHidden = true
}
UIView.transition(with: cell, duration: 0.3, options: [.transitionFlipFromLeft, .overrideInheritedOptions], animations: {
}, completion: { (_) in
cell.item.fliped = !cell.item.fliped
})
}
}
}
extension ItemLargeTableViewController {
override func encodeRestorableState(with coder: NSCoder) {
debugPrint("encode large")
super.encodeRestorableState(with: coder)
coder.encode(item!.folder!.title, forKey: "folderTitle")
coder.encode(item!.title, forKey: "itemTitle")
coder.encode(item!.des, forKey: "itemDes")
}
override func decodeRestorableState(with coder: NSCoder) {
debugPrint("decode large")
//important: viewDidLoad before than decodeRestorableState, so frc, folder should be optional
guard let title = coder.decodeObject(forKey: "folderTitle") as? String,
let itemTitle = coder.decodeObject(forKey: "itemTitle") as? String,
let itemDes = coder.decodeObject(forKey: "itemDes") as? String else {
return
}
let pre = NSPredicate(format: "title == %@", title)
if let folder = try! cdStore.mainContext.request(Folder.self).filtered(with: pre).fetch().first {
let pre1 = NSPredicate(format: "folder == %@ AND title == %@ AND des = %@", folder, itemTitle, itemDes)
if let item = try! cdStore.mainContext.request(Item.self).filtered(with: pre1).fetch().first {
self.item = item
self.tableView.reloadData()
updateBtns()
}
}
super.decodeRestorableState(with: coder)
}
}
| 34.668269 | 229 | 0.612398 |
615e3f8c57837b006c77273a15e8c78fae006ff3 | 2,259 | //
// SettingsView.swift
// UI Master
//
// Created by Ian Kohlert on 2017-07-03.
// Copyright © 2017 aestusLabs. All rights reserved.
//
import Foundation
import UIKit
class SettingsView: UIView {
var viewTitle = UILabel()
var gradientLine = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = appColours.getBackgroundColour()
let titleWidth = getWidthOf(title: "Settings")
viewTitle = UILabel(frame: CGRect(x: self.frame.width - 20 - titleWidth, y: 30, width: titleWidth, height: 48))
viewTitle = titleLabel(label: viewTitle, text: "Settings")
self.addSubview(viewTitle)
let gradientLineWidth: CGFloat = titleWidth + 20 //titleLabel.bounds.width
gradientLine = UIView(frame: CGRect(x: self.frame.width - gradientLineWidth, y: 75, width: gradientLineWidth, height: 5))
gradientLine.backgroundColor = UIColor.gray
let gradient = CAGradientLayer()
gradient.frame = gradientLine.bounds
let left = appColours.appColourLeft //UIColor(red: 1.0, green: 0.325490196, blue: 0.541176471, alpha: 1.0)
let right = appColours.appColourRight //UIColor(red: 1.0, green: 0.494117647, blue: 0.435294118, alpha: 1.0)
gradient.colors = [left.cgColor, right.cgColor]
gradient.startPoint = CGPoint.zero
gradient.endPoint = CGPoint(x: 1, y: 1)
gradientLine.layer.insertSublayer(gradient, at: 0)
self.addSubview(gradientLine)
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
// func changeColourTheme() {
// self.backgroundColor = appColours.getBackgroundColour()
// viewTitle.textColor = appColours.getTextColour()
// timeLabel.textColor = appColours.getTextColour()
// helperBar.backgroundColor = appColours.getHelperBarBackgroundColour()
// }
}
func setUpSettingsView(screenHeight: CGFloat, screenWidth: CGFloat) -> SettingsView {
let view = SettingsView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))
return view
}
| 32.271429 | 129 | 0.645861 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.