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
|
---|---|---|---|---|---|
eb1e47fe18170b924889672f01ec35ab78ec485f | 5,823 | //
// Interpreter.swift
// BF-Interpreter
//
// Created by Eita Yamaguchi on 2020/06/02.
// Copyright © 2020 Eita Yamaguchi. All rights reserved.
//
import Foundation
// This source code is written by nst and other contributors
// https://github.com/nst/Brainfuck
class Brainfuck: NSObject {
enum Instruction {
case moveRight
case moveLeft
case increment
case decrement
case put
case get
case loopStart(to:Int)
case loopStop(from:Int)
init?(rawValue c: Character) {
switch c {
case ">": self = .moveRight
case "<": self = .moveLeft
case "+": self = .increment
case "-": self = .decrement
case ".": self = .put
case ",": self = .get
case "[": self = .loopStart(to:0)
case "]": self = .loopStop(from:0)
default: return nil
}
}
func description(showLoopMatch:Bool = false) -> String {
switch self {
case .moveRight: return ">"
case .moveLeft: return "<"
case .increment: return "+"
case .decrement: return "-"
case .put: return "."
case .get: return ","
case let .loopStart(to): return showLoopMatch ? "[\(to)" : "["
case let .loopStop(from): return showLoopMatch ? "\(from)]" : "]"
}
}
}
var stepCounter : Int = 0
// program
var instructions : [Instruction] = []
var ip : Int = 0 // instruction pointer
// data
var data : [UInt8] = []
var dp : Int = 0 // data pointer
// I/O
var input = [UInt8]("".utf8)
var output = [UInt8]("".utf8)
enum BFError: Error {
case LoopStartUnbalanced(index:Int)
case LoopStopUnbalanced(index:Int)
case DataPointerBelowZero(ip:Int)
case DataPointerBeyondBounds(ip:Int)
case CannotReadEmptyInputBuffer(ip:Int)
}
init(_ s: String, userInput: String = "", dataSize: Int = 30000) throws {
// 1. initialize data
self.data = Array(repeating: 0, count: dataSize)
// 2. sanitize instructions
self.instructions = s.compactMap { Instruction(rawValue:$0) }
// 3. store user input
self.input = [UInt8](userInput.utf8)
// 4. associate matching indices to loops start and end
var loopStartStack : [Int] = []
for (i, instruction) in instructions.enumerated() {
switch instruction {
case .loopStart:
loopStartStack.append(i)
case .loopStop:
guard let loopStartIndex = loopStartStack.popLast() else { throw BFError.LoopStopUnbalanced(index:i) }
instructions[loopStartIndex] = .loopStart(to: i)
instructions[i] = .loopStop(from: loopStartIndex)
default:
()
}
}
// 5. throw if unbalanced brackets
if let unmatchedStartIndex = loopStartStack.first {
throw BFError.LoopStartUnbalanced(index: unmatchedStartIndex)
}
}
func canRun() -> Bool {
return ip < instructions.count
}
func run() throws -> String {
while self.canRun() {
_ = try self.step()
}
return self.outputString()
}
func step() throws -> UInt8? {
assert(ip < instructions.count)
stepCounter += 1
var putByte : UInt8? = nil
let i = instructions[ip]
switch i {
case .moveRight:
dp += 1
case .moveLeft:
dp -= 1
case .increment:
data[dp] = data[dp] &+ 1
case .decrement:
data[dp] = data[dp] &- 1
case .put:
let byte = data[dp]
output.append(byte)
putByte = byte
case .get:
guard input.count > 0 else { throw BFError.CannotReadEmptyInputBuffer(ip:ip) } // TODO: be interactive instead?
data[dp] = input.removeFirst()
case let .loopStart(to):
if data[dp] == 0 {
ip = to
}
case let .loopStop(from):
ip = from - 1
}
ip += 1
if dp < 0 {
throw BFError.DataPointerBelowZero(ip:ip)
} else if dp >= data.count {
throw BFError.DataPointerBeyondBounds(ip:ip)
}
return putByte
}
}
// DEBUG extension
extension Brainfuck {
func printStep() {
print("STEP:", stepCounter)
}
func printData(upToIndex: Int? = nil) {
var subData = data
if let upIndex = upToIndex {
subData = Array(data[0...upIndex])
}
print("DATA:", subData.map { String(format: "%02X", $0) }.joined(separator: " "))
print("".padding(toLength: 6 + 3*dp, withPad: " ", startingAt: 0) + "^^ \(dp)")
}
func printInstructions() {
print("PROG:", instructions.map { $0.description(showLoopMatch:false) }.joined())
print("".padding(toLength: 6 + ip, withPad: " ", startingAt: 0) + "^ \(ip)")
}
func printExecutionSummary() {
print("SUMMARY: program stopped after \(stepCounter) step(s) with output:")
let s = output.map { String(format: "%02X", $0) }.joined(separator: " ")
print(" HEX: \(s)")
print(" STR: \(outputString())")
}
func outputBuffer() -> [UInt8] {
return output
}
func outputString() -> String {
return output.map { String(UnicodeScalar(Int($0))!) }.joined()
}
}
| 28.544118 | 123 | 0.51142 |
fca29fd558f16396c51b9a7dafa03c1fece89db5 | 464 | //
// BalanceType.swift
// Stripe
//
// Created by Anthony Castelli on 4/16/17.
//
//
import Foundation
public enum BalanceType: String {
case charge = "charge"
case refund = "refund"
case adjustment = "adjustment"
case applicationFee = "application_fee"
case applicationFeeRefund = "application_fee_refund"
case transfer = "transfer"
case payment = "payment"
case payout = "payout"
case payoutFailure = "payout_failure"
}
| 21.090909 | 56 | 0.681034 |
f886bd41a8ebb0db573a580eff8f1d2e26de21cd | 401 | //
// DateExtension.swift
// WithBook-Development
//
// Created by shintykt on 2020/05/04.
// Copyright © 2020 Takaya Shinto. All rights reserved.
//
import Foundation
extension Date {
var string: String {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "ja_JP")
formatter.dateStyle = .medium
return formatter.string(from: self)
}
}
| 21.105263 | 56 | 0.658354 |
0e35c686b12f4ceb61121db1d44fb8c771aeaa3e | 985 | //
// RepositoriesTableViewCell.swift
// BitbucketAsList
//
// Created by Samrez Ikram on 03/07/2021.
//
import UIKit
public class RepositoriesTableViewCell: UITableViewCell {
@IBOutlet weak var repositoriesOwnerTitleLabel: UILabel!
@IBOutlet weak var repositoriesOwnerTypeLabel: UILabel!
@IBOutlet weak var repositoriesCreationDdate: UILabel!
@IBOutlet weak var ownerAvater: UIImageViewAsync!
var repo : Values? {
didSet {
repositoriesOwnerTitleLabel.text = repo?.owner?.display_name
repositoriesOwnerTypeLabel.text = repo?.owner?.type
repositoriesCreationDdate.text = repo?.created_on
}
}
public override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
public override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 28.970588 | 72 | 0.684264 |
2078bc1e7b0b9a56c25beab9d3de80e1b6fa48c2 | 4,648 | //
// HeartRate.swift
// Data Integration
//
// Created by Bryan Nova on 6/19/18.
// Copyright © 2018 Bryan Nova. All rights reserved.
//
import Foundation
import HealthKit
import Attributes
import Common
import DependencyInjection
public final class HeartRate: HealthKitQuantitySample {
private typealias Me = HeartRate
// MARK: - HealthKit Stuff
public static let quantityType: HKQuantityType = HKQuantityType.quantityType(forIdentifier: .heartRate)!
public static let sampleType: HKSampleType = quantityType
public static let readPermissions: Set<HKObjectType> = Set([sampleType])
public static let writePermissions: Set<HKSampleType> = Set([sampleType])
public static var unit: HKUnit = HKUnit(from: "count/min")
public final var unitString: String {
Me.unit.unitString
}
public static func initUnits() {
unit = injected(HealthKitUtil.self).preferredUnitFor(.heartRate) ?? HKUnit(from: "count/min")
}
// MARK: - Display Information
public static let name: String = "Heart Rate"
public final let attributedName: String = Me.name
public static let description: String = "A measurement of how fast your heart is beating (in beats per minute)."
public final let description: String = Me.description
// MARK: - Attributes
public static let heartRate = DoubleAttribute(
name: "Heart rate",
pluralName: "Heart rates",
variableName: HKPredicateKeyPathQuantity
)
public static let attributes: [Attribute] = [CommonSampleAttributes.healthKitTimestamp, heartRate]
public static var dateAttributes: [DateType: DateAttribute] = [
.start: CommonSampleAttributes.healthKitTimestamp,
]
public static let defaultDependentAttribute: Attribute = heartRate
public static let defaultIndependentAttribute: Attribute = CommonSampleAttributes.healthKitTimestamp
public final var attributes: [Attribute] { Me.attributes }
// MARK: - Instance Variables
public final var timestamp: Date
public final var heartRate: Double
// MARK: - Initializers
public init(_ value: Double = Double(), _ timestamp: Date = Date()) {
heartRate = value
self.timestamp = timestamp
}
public required init(_ sample: HKQuantitySample) {
heartRate = sample.quantity.doubleValue(for: Me.unit)
timestamp = sample.startDate
injected(HealthKitUtil.self).setTimeZoneIfApplicable(for: ×tamp, from: sample)
}
// MARK: - HealthKitSample Functions
public func hkSample() -> HKSample {
let quantity = HKQuantity(unit: Me.unit, doubleValue: quantityValue())
return HKQuantitySample(
type: Me.quantityType,
quantity: quantity,
start: timestamp,
end: timestamp,
metadata: [HKMetadataKeyTimeZone: TimeZone.autoupdatingCurrent.identifier]
)
}
// MARK: - HealthKitQuantitySample Functions
public func quantityValue() -> Double {
heartRate
}
// MARK: - Sample Functions
public final func dates() -> [DateType: Date] {
[.start: timestamp]
}
// MARK: - Attributed Functions
public final func value(of attribute: Attribute) throws -> Any? {
if attribute.equalTo(Me.heartRate) {
return heartRate
}
if attribute.equalTo(CommonSampleAttributes.healthKitTimestamp) {
return timestamp
}
throw UnknownAttributeError(attribute: attribute, for: self)
}
public final func set(attribute: Attribute, to value: Any?) throws {
if attribute.equalTo(Me.heartRate) {
guard let castedValue = value as? Double else {
throw TypeMismatchError(attribute: attribute, of: self, wasA: type(of: value))
}
heartRate = castedValue
return
}
if attribute.equalTo(CommonSampleAttributes.healthKitTimestamp) {
guard let castedValue = value as? Date else {
throw TypeMismatchError(attribute: attribute, of: self, wasA: type(of: value))
}
timestamp = castedValue
return
}
throw UnknownAttributeError(attribute: attribute, for: self)
}
}
// MARK: - Equatable
extension HeartRate: Equatable {
public static func == (lhs: HeartRate, rhs: HeartRate) -> Bool {
lhs.equalTo(rhs)
}
public final func equalTo(_ otherAttributed: Attributed) -> Bool {
if !(otherAttributed is HeartRate) { return false }
let other = otherAttributed as! HeartRate
return equalTo(other)
}
public final func equalTo(_ otherSample: Sample) -> Bool {
if !(otherSample is HeartRate) { return false }
let other = otherSample as! HeartRate
return equalTo(other)
}
public final func equalTo(_ other: HeartRate) -> Bool {
timestamp == other.timestamp && heartRate == other.heartRate
}
}
// MARK: - Debug
extension HeartRate: CustomDebugStringConvertible {
public final var debugDescription: String {
"HeartRate of \(heartRate) at " + timestamp.debugDescription
}
}
| 28.869565 | 113 | 0.74204 |
1159ad56be592dd59d9e1682cdbf266b43c381a9 | 3,813 | import UIKit
import SnapKit
import SkeletonView
open class Right14View: UIView {
private let topLabel = UILabel()
private let stackView = UIStackView()
private let bottomLabel = UILabel()
private let bottomTitleLabel = UILabel()
override public init(frame: CGRect) {
super.init(frame: frame)
isSkeletonable = true
addSubview(topLabel)
topLabel.snp.makeConstraints { maker in
maker.leading.trailing.equalToSuperview()
maker.top.equalToSuperview().offset(13)
}
topLabel.textAlignment = .right
topLabel.font = .body
topLabel.textColor = .themeLeah
topLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
topLabel.isHiddenWhenSkeletonIsActive = true
topLabel.isSkeletonable = true
addSubview(stackView)
stackView.snp.makeConstraints { maker in
maker.leading.trailing.equalToSuperview()
maker.top.equalTo(topLabel.snp.bottom).offset(CGFloat.margin2)
}
stackView.axis = .horizontal
stackView.distribution = .fill
stackView.alignment = .center
stackView.spacing = .margin4
stackView.isHiddenWhenSkeletonIsActive = true
stackView.isSkeletonable = true
stackView.addArrangedSubview(UIView())
stackView.addArrangedSubview(bottomTitleLabel)
bottomTitleLabel.font = .caption
bottomTitleLabel.textColor = .themeJacob
bottomTitleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
stackView.addArrangedSubview(bottomLabel)
bottomLabel.font = .caption
bottomLabel.textColor = .themeGray
bottomLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
buildSkeleton()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func buildSkeleton() {
let topSkeleton = UIView()
addSubview(topSkeleton)
topSkeleton.snp.makeConstraints { maker in
maker.trailing.equalToSuperview()
maker.top.equalToSuperview().offset(CGFloat.margin12)
maker.width.equalTo(88)
maker.height.equalTo(16)
}
topSkeleton.isSkeletonable = true
topSkeleton.skeletonCornerRadius = 8
let bottomValueSkeleton = UIView()
addSubview(bottomValueSkeleton)
bottomValueSkeleton.snp.makeConstraints { maker in
maker.trailing.equalToSuperview()
maker.top.equalTo(topSkeleton.snp.bottom).offset(6)
maker.width.equalTo(32)
maker.height.equalTo(14)
}
bottomValueSkeleton.isSkeletonable = true
bottomValueSkeleton.skeletonCornerRadius = 7
let bottomTitleSkeleton = UIView()
addSubview(bottomTitleSkeleton)
bottomTitleSkeleton.snp.makeConstraints { maker in
maker.trailing.equalTo(bottomValueSkeleton.snp.leading).offset(-6)
maker.top.equalTo(bottomValueSkeleton)
maker.width.equalTo(32)
maker.height.equalTo(14)
}
bottomTitleSkeleton.isSkeletonable = true
bottomTitleSkeleton.skeletonCornerRadius = 7
}
public var topText: String? {
get { topLabel.text }
set { topLabel.text = newValue }
}
public var bottomTitleText: String? {
get { bottomTitleLabel.text }
set { bottomTitleLabel.text = newValue }
}
public var bottomText: String? {
get { bottomLabel.text }
set { bottomLabel.text = newValue }
}
public var bottomTextColor: UIColor {
get { bottomLabel.textColor }
set { bottomLabel.textColor = newValue }
}
}
| 31 | 93 | 0.65775 |
50904c28cd528a4dda1a0243620e25fed83d5d0e | 1,149 | //
// RegionCoordinator.swift
// iVote
//
// Created by Hasan Sa on 09/10/2018.
// Copyright © 2018 Hasan Sa. All rights reserved.
//
import Foundation
import UIKit
protocol RegionCoordinatorDelegate: AnyObject {
func regionCoordinatorDidFinish(regionCoordinator: RegionCoordinator)
}
class RegionCoordinator: Coordinator {
weak var delegate: RegionCoordinatorDelegate?
let window: UIWindow
init(window: UIWindow) {
self.window = window
}
func start() {
if let navigationController = mainStoryBoard?.instantiateViewController(withIdentifier: "RegionNavigationViewController") as? UINavigationController,
let regionViewCintroller = navigationController.topViewController as? RegionViewController {
let viewModel = RegionViewModel()
viewModel.coordinatorDelegate = self
regionViewCintroller.viewModel = viewModel
window.rootViewController = navigationController
}
}
}
extension RegionCoordinator: RegionViewModelCoordinatorDelegate {
func regionViewModelCoordinatorDidFinish(viewModel: RegionViewModel) {
self.delegate?.regionCoordinatorDidFinish(regionCoordinator: self)
}
}
| 28.02439 | 153 | 0.777198 |
18151b65b2c3a030d1cb46774d3e3a21dfb14819 | 2,202 | //
// CategoryRequests.swift
// SwiftYNAB
//
// Created by Andre Bocchini on 5/4/19.
// Copyright © 2019 Andre Bocchini. All rights reserved.
//
import Foundation
struct CategoriesRequest {
let budgetId: String
let lastKnowledgeOfServer: Int?
init(budgetId: String, lastKnowledgeOfServer: Int? = nil) {
self.budgetId = budgetId
self.lastKnowledgeOfServer = lastKnowledgeOfServer
}
}
extension CategoriesRequest: Request {
var path: String {
return "/v1/budgets/\(self.budgetId)/categories"
}
var query: [URLQueryItem]? {
guard let lastKnowledgeOfServer = self.lastKnowledgeOfServer else {
return nil
}
return [URLQueryItem(name: "last_knowledge_of_server",
value: "\(lastKnowledgeOfServer)")]
}
}
struct CategoryRequest {
let budgetId: String
let categoryId: String
}
extension CategoryRequest: Request {
var path: String {
return "/v1/budgets/\(self.budgetId)/categories/\(self.categoryId)"
}
}
struct CategoryByMonthRequest {
let budgetId: String
let month: String
let categoryId: String
}
extension CategoryByMonthRequest: Request {
var path: String {
return "/v1/budgets/\(self.budgetId)/months/\(self.month)/categories/\(self.categoryId)"
}
}
struct SaveMonthCategoryRequest {
let budgetId: String
let month: String
let categoryId: String
let budgeted: Int
}
extension SaveMonthCategoryRequest: Request {
var path: String {
return "/v1/budgets/\(self.budgetId)/months/\(self.month)/categories/\(self.categoryId)"
}
var method: String {
return "PATCH"
}
var body: Data? {
let categoryUpdate = SaveMonthCategory(budgeted: self.budgeted)
let wrapper = SaveMonthCategoryRequestWrapper(with: categoryUpdate)
return try? Serializer.encode(wrapper)
}
}
struct SaveMonthCategoryRequestWrapper: Codable {
let category: SaveMonthCategory
init(with category: SaveMonthCategory) {
self.category = category
}
}
| 19.837838 | 96 | 0.637602 |
f8776921f0e3c5bdfa911364da06c5d42c1babff | 1,275 | //
// IntervalViewController.swift
// JWSRxSwiftBeginningSample
//
// Created by Clint on 20/11/2018.
// Copyright © 2018 clintjang. All rights reserved.
//
import UIKit
final class IntervalViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("===============================")
print("첫번째 Interval 실행")
print("서브스크라이브 되서, 2초 후 부터 반복")
print("\n\n")
let intervalFirst = 2 // 2초에 한번씩
Observable<Int>.interval(RxTimeInterval(intervalFirst), scheduler: MainScheduler.instance)
// .debug()
.subscribe({ print("첫번째:\($0)") })
.disposed(by: disposeBag)
print("===============================")
print("두번째 Interval 실행")
print("서브스크라이브 되서, 3초 후 부터 반복, 5회만 반복")
print("\n\n")
let intervalSecond = 3 // 3초에 한번씩
Observable<Int>.interval(RxTimeInterval(intervalSecond), scheduler: MainScheduler.instance)
.map({ $0 + 1000 }) // 1000, 1001, 1002...
.take(5) // 5회
.subscribe({ print("두번째:\($0)") })
.disposed(by: disposeBag)
print("===============================")
print("\n\n")
}
}
| 28.333333 | 99 | 0.506667 |
8918e6bb45dbb0e8c644825904dc66c95ee85edb | 2,459 | //
// ViewController.swift
// WKNative
//
// Created by Justin Bush on 2020-08-09.
//
import Cocoa
import WebKit
class ViewController: NSViewController, WKUIDelegate, WKNavigationDelegate {
@IBOutlet weak var webView: WKWebView! // Main WebView
@IBOutlet weak var titleBar: NSTextField! // Main Window Title
@IBOutlet weak var topConstraint: NSLayoutConstraint! // Top Window Constraint
// WebView Observers
var webViewTitleObserver: NSKeyValueObservation? // Observer for Web Player Title
var webViewURLObserver: NSKeyValueObservation? // Observer for Web Player URL
var webViewProgressObserver: NSKeyValueObservation? // Observer for Web Player Progress
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// MARK:- WebView Setup
func initWebView() {
webView.navigationDelegate = self
webView.uiDelegate = self
webView.setValue(false, forKey: "drawsBackground") // Hide WebView Background
webView.allowsLinkPreview = false // Disable Link Previews
webView.allowsMagnification = false // Disable Magnification (CSS Handled)
webView.allowsBackForwardNavigationGestures = true // Disable Back-Forward Navigation
webView.customUserAgent = Client.userAgent // WebView Browser UserAgent
// WebKit Preferences & Configuration
let preferences = WKPreferences() // WebKit Preferences
preferences.javaScriptEnabled = true // Enable JavaScript
preferences.javaScriptCanOpenWindowsAutomatically = true
let configuration = WKWebViewConfiguration() // WebKit Configuration
configuration.preferences = preferences
configuration.allowsAirPlayForMediaPlayback = true // Enable WebKit AirPlay
configuration.applicationNameForUserAgent = Client.name // App Name
let webController = WKUserContentController()
webView.configuration.userContentController = webController
//webView.load(User.service.url)
webView.load(Service.apple.url)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| 36.161765 | 102 | 0.645791 |
6a6f9feac8e474339e01f1880b5426fbed17b867 | 682 | import Anchorage
import Shared
import UIKit
/**
A custom, rounded button.
*/
public class RoundedButton: UIButton {
public init() {
super.init(frame: .zero)
configureView()
}
@available(*, deprecated, message: "Use `init()` instead.")
override init(frame: CGRect) {
// Needed to render in InterfaceBuilder.
super.init(frame: frame)
configureView()
}
@available(*, unavailable, message: "Instantiating via Xib & Storyboard is prohibited.")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
Builds up the view hierarchy and applies the layout.
*/
func configureView() {
apply(.roundedAndFilled)
}
}
| 20.666667 | 89 | 0.702346 |
d9d23a8d616a1b5b2f01600c562d035ce88bbcda | 5,047 | //
// AgendaListViewController.swift
// prkng-ios
//
// Created by Antonino Urbano on 2015-07-07.
// Copyright (c) 2015 PRKNG. All rights reserved.
//
import UIKit
class AgendaListViewController: PRKModalViewControllerChild, UITableViewDataSource, UITableViewDelegate {
private var agendaItems : Array<AgendaItem>
private var tableView: UITableView
private(set) var HEADER_HEIGHT : CGFloat = Styles.Sizes.modalViewHeaderHeight
override init(spot: ParkingSpot, view: UIView) {
agendaItems = []
tableView = UITableView()
super.init(spot: spot, view: view)
agendaItems = ScheduleHelper.getAgendaItems(spot, respectDoNotProcess: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
self.screenName = "Agenda List View"
}
override func loadView() {
view = UIView()
view.backgroundColor = Styles.Colors.stone
setupViews()
setupConstraints()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func setupViews() {
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.backgroundColor = Styles.Colors.cream2
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
}
func setupConstraints() {
tableView.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.view).offset(Styles.Sizes.modalViewHeaderHeight)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
make.bottom.equalTo(self.view)
}
}
//MARK: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return agendaItems.count
}
let identifier = "AgendaTableViewCell"
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let agendaItem = agendaItems[indexPath.row]
var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? AgendaTableViewCell
if cell == nil {
cell = AgendaTableViewCell(agendaItem: agendaItem, style: .Default, reuseIdentifier: identifier)
} else {
cell?.setupSubviews(agendaItem)
}
return cell!
}
//MARK: UITableViewDelegate
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let useableHeight = UIScreen.mainScreen().bounds.height - Styles.Sizes.modalViewHeaderHeight - CGFloat(Styles.Sizes.tabbarHeight)
let height = useableHeight / 7 > 60 ? Int(useableHeight / 7) : 60
return CGFloat(height)
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
}
class AgendaItem {
var startTime : NSTimeInterval
var endTime : NSTimeInterval
var dayIndex : Int //0 means today, 1 means tomorrow, etc
var timeLimit : Int
var rule : ParkingRule
init(startTime: NSTimeInterval, endTime: NSTimeInterval, dayIndex: Int, timeLimit: Int, rule: ParkingRule) {
self.startTime = startTime
self.endTime = endTime
self.dayIndex = dayIndex
self.timeLimit = timeLimit
self.rule = rule
}
func isToday() -> Bool {
return dayIndex == 0
}
func dayText() -> String {
let days = DateUtil.sortedDays()
if dayIndex < days.count && dayIndex > -1 {
return days[dayIndex]
}
return ""
}
func timeText() -> NSAttributedString {
let firstPartFont = Styles.FontFaces.regular(14)
let secondPartFont = Styles.FontFaces.light(14)
if self.rule.ruleType == .Free {
let attrs = [NSFontAttributeName: firstPartFont]
let attributedString = NSMutableAttributedString(string: "24 H", attributes: attrs)
return attributedString
}
let fromTime = self.startTime.toAttributedString(condensed: false, firstPartFont: firstPartFont, secondPartFont: secondPartFont)
let toTime = self.endTime.toAttributedString(condensed: false, firstPartFont: firstPartFont, secondPartFont: secondPartFont)
let attributedString = NSMutableAttributedString(attributedString: fromTime)
attributedString.appendAttributedString(NSAttributedString(string: "\n"))
attributedString.appendAttributedString(toTime)
return attributedString
}
}
| 31.347826 | 137 | 0.648504 |
902b9fb8e87154b3a41e9ac08b57a5475d4aaa46 | 1,344 | //
// TasksRow.swift
// SwiftUI-Todo-Redux
//
// Created by moflo on 6/22/19.
// Copyright © 2019 Mobile Flow LLC. All rights reserved.
//
import SwiftUI
struct TasksRow: View {
@EnvironmentObject var store: AppState
let task: Task
var body: some View {
HStack {
if task.isDone {
Image(systemName: "checkmark.circle.fill")
// .font(.largeTitle)
.imageScale(.large)
.foregroundColor(.green)
} else {
Image(systemName: "checkmark.circle")
// .font(.largeTitle)
.imageScale(.large)
.foregroundColor(.gray)
}
VStack(alignment: .leading, spacing: CGFloat(8.0)) {
Text(task.title).font(.title)
Text(task.id)
.foregroundColor(.secondary)
}.padding(.leading, CGFloat(8.0))
}.padding(8)
}
}
#if DEBUG
struct TasksRow_Previews: PreviewProvider {
static var previews: some View {
Group {
TasksRow(task: Task(title: "New Task", isDone: true)).environmentObject(sampleStore)
TasksRow(task: Task(title: "New Task", isDone: false)).environmentObject(sampleStore)
}
}
}
#endif
| 28 | 101 | 0.52381 |
bb17bd774b4ca76ce4ea42f4f780a528d438f9c4 | 6,377 | //
// CEFDOMNode.swift
// CEF.swift
//
// Created by Tamas Lustyik on 2015. 07. 29..
// Copyright © 2015. Tamas Lustyik. All rights reserved.
//
import Foundation
public extension CEFDOMNode {
/// Returns the type for this node.
public var type: CEFDOMNodeType {
let cefType = cefObject.get_type(cefObjectPtr)
return CEFDOMNodeType.fromCEF(cefType)
}
/// Returns true if this is a text node.
public var isText: Bool {
return cefObject.is_text(cefObjectPtr) != 0
}
/// Returns true if this is an element node.
public var isElement: Bool {
return cefObject.is_element(cefObjectPtr) != 0
}
/// Returns true if this is an editable node.
public var isEditable: Bool {
return cefObject.is_editable(cefObjectPtr) != 0
}
/// Returns true if this is a form control element node.
public var isFormControlElement: Bool {
return cefObject.is_form_control_element(cefObjectPtr) != 0
}
/// Returns the type of this form control element node.
public var formControlElementType: String {
let cefStrPtr = cefObject.get_form_control_element_type(cefObjectPtr)
defer { CEFStringPtrRelease(cefStrPtr) }
return CEFStringToSwiftString(cefStrPtr.memory)
}
/// Returns true if this object is pointing to the same handle as |that|
/// object.
public func isSameAs(other: CEFDOMNode) -> Bool {
return cefObject.is_same(cefObjectPtr, other.toCEF()) != 0
}
/// Returns the name of this node.
public var name: String {
let cefStrPtr = cefObject.get_name(cefObjectPtr)
defer { CEFStringPtrRelease(cefStrPtr) }
return CEFStringToSwiftString(cefStrPtr.memory)
}
/// Returns the value of this node.
public var stringValue: String {
let cefStrPtr = cefObject.get_value(cefObjectPtr)
defer { CEFStringPtrRelease(cefStrPtr) }
return CEFStringToSwiftString(cefStrPtr.memory)
}
/// Set the value of this node. Returns true on success.
public func setStringValue(value: String) -> Bool {
let cefStrPtr = CEFStringPtrCreateFromSwiftString(value)
defer { CEFStringPtrRelease(cefStrPtr) }
return cefObject.set_value(cefObjectPtr, cefStrPtr) != 0
}
/// Returns the contents of this node as markup.
public var markupValue: String {
let cefStrPtr = cefObject.get_as_markup(cefObjectPtr)
defer { CEFStringPtrRelease(cefStrPtr) }
return CEFStringToSwiftString(cefStrPtr.memory)
}
/// Returns the document associated with this node.
public var document: CEFDOMDocument {
let cefDoc = cefObject.get_document(cefObjectPtr)
return CEFDOMDocument.fromCEF(cefDoc)!
}
/// Returns the parent node.
public var parent: CEFDOMNode? {
let cefNode = cefObject.get_parent(cefObjectPtr)
return CEFDOMNode.fromCEF(cefNode)
}
/// Returns the previous sibling node.
public var previousSibling: CEFDOMNode? {
let cefNode = cefObject.get_previous_sibling(cefObjectPtr)
return CEFDOMNode.fromCEF(cefNode)
}
/// Returns the next sibling node.
public var nextSibling: CEFDOMNode? {
let cefNode = cefObject.get_next_sibling(cefObjectPtr)
return CEFDOMNode.fromCEF(cefNode)
}
/// Returns true if this node has child nodes.
public var hasChildren: Bool {
return cefObject.has_children(cefObjectPtr) != 0
}
/// Return the first child node.
public var firstChild: CEFDOMNode? {
let cefNode = cefObject.get_first_child(cefObjectPtr)
return CEFDOMNode.fromCEF(cefNode)
}
/// Returns the last child node.
public var lastChild: CEFDOMNode? {
let cefNode = cefObject.get_last_child(cefObjectPtr)
return CEFDOMNode.fromCEF(cefNode)
}
// The following methods are valid only for element nodes.
/// Returns the tag name of this element.
public var elementTagName: String? {
let cefStrPtr = cefObject.get_element_tag_name(cefObjectPtr)
defer { CEFStringPtrRelease(cefStrPtr) }
return cefStrPtr != nil ? CEFStringToSwiftString(cefStrPtr.memory) : nil
}
/// Returns true if this element has attributes.
public var hasElementAttributes: Bool {
return cefObject.has_element_attributes(cefObjectPtr) != 0
}
/// Returns true if this element has an attribute named |attrName|.
public func hasElementAttributeNamed(name: String) -> Bool {
let cefStrPtr = CEFStringPtrCreateFromSwiftString(name)
defer { CEFStringPtrRelease(cefStrPtr) }
return cefObject.has_element_attribute(cefObjectPtr, cefStrPtr) != 0
}
/// Returns the element attribute named |attrName|.
public func elementAttributeNamed(name: String) -> String {
let cefNamePtr = CEFStringPtrCreateFromSwiftString(name)
let cefValuePtr = cefObject.get_element_attribute(cefObjectPtr, cefNamePtr)
defer {
CEFStringPtrRelease(cefNamePtr)
CEFStringPtrRelease(cefValuePtr)
}
return CEFStringToSwiftString(cefValuePtr.memory)
}
/// Returns a map of all element attributes.
public var elementAttributes: [String: String] {
let cefMap = cef_string_map_alloc()
defer { cef_string_map_free(cefMap) }
cefObject.get_element_attributes(cefObjectPtr, cefMap)
return CEFStringMapToSwiftDictionary(cefMap)
}
/// Set the value for the element attribute named |attrName|. Returns true on
/// success.
public func setElementAttribute(value: String, forName name: String) -> Bool {
let cefNamePtr = CEFStringPtrCreateFromSwiftString(name)
let cefValuePtr = CEFStringPtrCreateFromSwiftString(value)
defer {
CEFStringPtrRelease(cefNamePtr)
CEFStringPtrRelease(cefValuePtr)
}
return cefObject.set_element_attribute(cefObjectPtr, cefNamePtr, cefValuePtr) != 0
}
/// Returns the inner text of the element.
public var elementInnerText: String? {
let cefStrPtr = cefObject.get_element_inner_text(cefObjectPtr)
defer { CEFStringPtrRelease(cefStrPtr) }
return cefStrPtr != nil ? CEFStringToSwiftString(cefStrPtr.memory) : nil
}
}
| 34.846995 | 90 | 0.680257 |
56d194f1882ac01c718a4f362c4fc10223e8af67 | 7,575 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_existential
// RUN: %target-codesign %t/reflect_existential
// Link %target-swift-reflection-test into %t to convince %target-run to copy
// it.
// RUN: ln -s %target-swift-reflection-test %t/swift-reflection-test
// RUN: %target-run %t/swift-reflection-test %t/reflect_existential | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
import SwiftReflectionTest
class TestGeneric<T> {
var t: T
init(_ t: T) {
self.t = t
}
}
protocol P {}
protocol CP : class {}
class C : CP {}
class D : C, P {}
reflect(object: TestGeneric(D() as Any))
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_class reflect_existential.TestGeneric
// CHECK-64: (protocol_composition))
// CHECK-64: Type info:
// CHECK-64: (class_instance size=48 alignment=8 stride=48 num_extra_inhabitants=0
// CHECK-64: (field name=t offset=16
// CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=0
// CHECK-64: (field name=metadata offset=24
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647)))))
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_class reflect_existential.TestGeneric
// CHECK-32: (protocol_composition))
// CHECK-32: Type info:
// CHECK-32: (class_instance size=24 alignment=4 stride=24 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=8
// CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-32: (field name=metadata offset=12
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096)))))
reflect(object: TestGeneric(D() as P))
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_class reflect_existential.TestGeneric
// CHECK-64: (protocol_composition
// CHECK-64: (protocol reflect_existential.P)))
// CHECK-64: Type info:
// CHECK-64: (class_instance size=56 alignment=8 stride=56 num_extra_inhabitants=0
// CHECK-64: (field name=t offset=16
// CHECK-64: (opaque_existential size=40 alignment=8 stride=40 num_extra_inhabitants=0
// CHECK-64: (field name=metadata offset=24
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647))
// CHECK-64: (field name=wtable offset=32
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1)))))
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_class reflect_existential.TestGeneric
// CHECK-32: (protocol_composition
// CHECK-32: (protocol reflect_existential.P)))
// CHECK-32: Type info:
// CHECK-32: (class_instance size=28 alignment=4 stride=28 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=8
// CHECK-32: (opaque_existential size=20 alignment=4 stride=20 num_extra_inhabitants=0
// CHECK-32: (field name=metadata offset=12
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32: (field name=wtable offset=16
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1)))))
reflect(object: TestGeneric(D() as (P & AnyObject)))
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_class reflect_existential.TestGeneric
// CHECK-64: (protocol_composition any_object
// CHECK-64: (protocol reflect_existential.P)))
// CHECK-64: Type info:
// CHECK-64: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0
// CHECK-64: (field name=t offset=16
// CHECK-64: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=2147483647
// CHECK-64: (field name=object offset=0
// CHECK-64: (reference kind=strong refcounting=unknown))
// CHECK-64: (field name=wtable offset=8
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1)))))
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_class reflect_existential.TestGeneric
// CHECK-32: (protocol_composition any_object
// CHECK-32: (protocol reflect_existential.P)))
// CHECK-32: Type info:
// CHECK-32: (class_instance size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=8
// CHECK-32: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32: (field name=object offset=0
// CHECK-32: (reference kind=strong refcounting=unknown))
// CHECK-32: (field name=wtable offset=4
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1)))))
reflect(object: TestGeneric(D() as CP))
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_class reflect_existential.TestGeneric
// CHECK-64: (protocol_composition any_object
// CHECK-64: (protocol reflect_existential.CP)))
// CHECK-64: Type info:
// CHECK-64: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0
// CHECK-64: (field name=t offset=16
// CHECK-64: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=2147483647
// CHECK-64: (field name=object offset=0
// CHECK-64: (reference kind=strong refcounting=unknown))
// CHECK-64: (field name=wtable offset=8
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1)))))
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_class reflect_existential.TestGeneric
// CHECK-32: (protocol_composition any_object
// CHECK-32: (protocol reflect_existential.CP)))
// CHECK-32: Type info:
// CHECK-32: (class_instance size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=8
// CHECK-32: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32: (field name=object offset=0
// CHECK-32: (reference kind=strong refcounting=unknown))
// CHECK-32: (field name=wtable offset=4
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1)))))
reflect(object: TestGeneric(D() as (C & P)))
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_class reflect_existential.TestGeneric
// CHECK-64: (protocol_composition any_object
// CHECK-64: (class reflect_existential.C)
// CHECK-64: (protocol reflect_existential.P)))
// CHECK-64: Type info:
// CHECK-64: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0
// CHECK-64: (field name=t offset=16
// CHECK-64: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=2147483647
// CHECK-64: (field name=object offset=0
// CHECK-64: (reference kind=strong refcounting=native))
// CHECK-64: (field name=wtable offset=8
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1)))))
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_class reflect_existential.TestGeneric
// CHECK-32: (protocol_composition any_object
// CHECK-32: (class reflect_existential.C)
// CHECK-32: (protocol reflect_existential.P)))
// CHECK-32: Type info:
// CHECK-32: (class_instance size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=8
// CHECK-32: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32: (field name=object offset=0
// CHECK-32: (reference kind=strong refcounting=native))
// CHECK-32: (field name=wtable offset=4
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1)))))
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| 42.318436 | 120 | 0.714059 |
e92d5b2839ac293dc80ab957c809be8a48497de3 | 1,389 | //
// Copyright (C) 2016-present Instructure, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
import SoGrey
import EarlGrey
import CanvasCore
import SoSeedySwift
@testable import CanvasKeymaster
class DashboardTests: StudentUITest {
func testCourseList() {
dashboardPage.assertCourseExists(self.courses.first!)
dashboardPage.assertCourseDoesNotExist(self.courses.last!)
}
func testCourseFavoriteList() {
dashboardPage.openCourseFavoritesEditPage(false)
editDashboardPage.assertPageObjects()
editDashboardPage.assertHasCourses(self.courses)
}
func testAllCoursesList() {
dashboardPage.openAllCoursesPage()
allCourseListPage.assertPageObjects()
}
func testProfileOpens() {
dashboardPage.openProfile()
profilePage.assertPageObjects()
}
}
| 29.553191 | 75 | 0.726422 |
094423cf2d35c4f51c6f3bb10bff6859d33c42dd | 5,983 | import Dispatch
/// A DatabaseSnapshot sees an unchanging database content, as it existed at the
/// moment it was created.
///
/// See DatabasePool.makeSnapshot()
///
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
public class DatabaseSnapshot: DatabaseReader {
private var serializedDatabase: SerializedDatabase
/// The database configuration
public var configuration: Configuration {
return serializedDatabase.configuration
}
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
var configuration = configuration
configuration.readonly = true
configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction
serializedDatabase = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: SimpleDatabaseSchemaCache(),
defaultLabel: defaultLabel,
purpose: purpose)
try serializedDatabase.sync { db in
// Assert WAL mode
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode")
guard journalMode == "wal" else {
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
}
try db.beginSnapshotIsolation()
}
}
deinit {
// Leave snapshot isolation
serializedDatabase.sync { db in
try? db.commit()
}
}
}
// DatabaseReader
extension DatabaseSnapshot {
// MARK: - Reading from Database
/// Synchronously executes a read-only block that takes a database
/// connection, and returns its result.
///
/// let players = try snapshot.read { db in
/// try Player.fetchAll(...)
/// }
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
}
#if compiler(>=5.0)
/// Asynchronously executes a read-only block in a protected dispatch queue.
///
/// let players = try snapshot.asyncRead { result in
/// do {
/// let db = try result.get()
/// let count = try Player.fetchCount(db)
/// } catch {
/// // Handle error
/// }
/// }
///
/// - parameter block: A block that accesses the database.
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
serializedDatabase.async { block(.success($0)) }
}
#endif
/// Alias for `read`. See `DatabaseReader.unsafeRead`.
///
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
}
/// Alias for `read`. See `DatabaseReader.unsafeReentrantRead`.
///
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try serializedDatabase.sync(block)
}
// MARK: - Functions
public func add(function: DatabaseFunction) {
serializedDatabase.sync { $0.add(function: function) }
}
public func remove(function: DatabaseFunction) {
serializedDatabase.sync { $0.remove(function: function) }
}
// MARK: - Collations
public func add(collation: DatabaseCollation) {
serializedDatabase.sync { $0.add(collation: collation) }
}
public func remove(collation: DatabaseCollation) {
serializedDatabase.sync { $0.remove(collation: collation) }
}
// MARK: - Value Observation
public func add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> TransactionObserver
{
// TODO: fetch asynchronously when possible
do {
// Deal with initial value
switch observation.scheduling {
case .mainQueue:
if let value = try unsafeReentrantRead(observation.fetchFirst) {
if DispatchQueue.isMain {
onChange(value)
} else {
DispatchQueue.main.async {
onChange(value)
}
}
}
case let .async(onQueue: queue, startImmediately: startImmediately):
if startImmediately {
if let value = try unsafeReentrantRead(observation.fetchFirst) {
queue.async {
onChange(value)
}
}
}
case let .unsafe(startImmediately: startImmediately):
if startImmediately {
if let value = try unsafeReentrantRead(observation.fetchFirst) {
onChange(value)
}
}
}
} catch {
onError(error)
}
// Return a dummy observer, because snapshots never change
return SnapshotValueObserver()
}
public func remove(transactionObserver: TransactionObserver) {
// Can't remove an observer which could not be added :-)
}
}
/// An observer that does nothing, support for
/// `DatabaseSnapshot.add(observation:onError:onChange:)`.
private class SnapshotValueObserver: TransactionObserver {
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
func databaseDidChange(with event: DatabaseEvent) { }
func databaseDidCommit(_ db: Database) { }
func databaseDidRollback(_ db: Database) { }
}
| 34.188571 | 118 | 0.579308 |
e4a2c2d9f3e3e5ebb64ee8eb1e3622713c989401 | 876 | //
// DYZBTests.swift
// DYZBTests
//
// Created by 牛田田 on 2019/2/26.
// Copyright © 2019年 牛田田. All rights reserved.
//
import XCTest
@testable import DYZB
class DYZBTests: 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.
}
}
}
| 25.028571 | 111 | 0.644977 |
fe3ad9bef5ae6825a64acffc58546e6354419124 | 2,059 | //
// AppDelegate.swift
// DatebuttonsScrolls
//
// Created by Douglas Barreto on 2/19/16.
// Copyright © 2016 Douglas. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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:.
}
}
| 43.808511 | 279 | 0.789218 |
90c8462604fd3c60db2a37a5b127937742cbeb58 | 219 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let:{
struct B<d where I=c
func b<b>:A?
func b<T:B | 27.375 | 87 | 0.744292 |
76a8c8b667c780f5f9787ca9d64b92e2e8a33241 | 738 | import UIKit
import Flutter
import flutter_downloader
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
FlutterDownloaderPlugin.setPluginRegistrantCallback(registerPlugins)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
private func registerPlugins(registry: FlutterPluginRegistry) {
if (!registry.hasPlugin("FlutterDownloaderPlugin")) {
FlutterDownloaderPlugin.register(with: registry.registrar(forPlugin: "FlutterDownloaderPlugin")!)
}
} | 35.142857 | 104 | 0.800813 |
0997932e939a34f0f111b68a7c785654d69a45a1 | 1,759 | //
// AKMIDIEndpointInfo.swift
// AudioKit
//
// Created by dejaWorks on 06/05/2017.
// Copyright © 2017 AudioKit. All rights reserved.
//
public struct EndpointInfo {
public var name = ""
public var displayName = ""
public var model = ""
public var manufacturer = ""
public var image = ""
public var driverOwner = ""
}
extension Collection where Iterator.Element == MIDIEndpointRef {
var endpointInfos: [EndpointInfo] {
let name = map { GetMIDIObjectStringProperty(ref: $0, property: kMIDIPropertyName) }
let displayName = map { GetMIDIObjectStringProperty(ref: $0, property: kMIDIPropertyDisplayName) }
let manufacturer = map { GetMIDIObjectStringProperty(ref: $0, property: kMIDIPropertyModel) }
let model = map { GetMIDIObjectStringProperty(ref: $0, property: kMIDIPropertyManufacturer) }
let image = map { GetMIDIObjectStringProperty(ref: $0, property: kMIDIPropertyImage) }
let driverOwner = map { GetMIDIObjectStringProperty(ref: $0, property: kMIDIPropertyDriverOwner) }
var ei = [EndpointInfo]()
for i in 0 ..< displayName.count {
ei.append(EndpointInfo(name: name[i],
displayName: displayName[i],
model: model[i],
manufacturer: manufacturer[i],
image: image[i],
driverOwner: driverOwner[i]))
}
return ei
}
}
extension AKMIDI {
public var destinationInfos: [EndpointInfo] {
return MIDIDestinations().endpointInfos
}
// Array
public var inputInfos: [EndpointInfo] {
return MIDISources().endpointInfos
}
}
| 33.826923 | 106 | 0.609437 |
bb623c73cfdc0f5b90e8a1687d6c51cfb5f8e4f5 | 1,717 | //
// Copyright (c) 2020 Related Code - http://relatedcode.com
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import AVFoundation
//-------------------------------------------------------------------------------------------------------------------------------------------------
class Video: NSObject {
//---------------------------------------------------------------------------------------------------------------------------------------------
class func thumbnail(path: String) -> UIImage {
let asset = AVURLAsset(url: URL(fileURLWithPath: path), options: nil)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
var time: CMTime = asset.duration
time.value = CMTimeValue(0)
var actualTime = CMTimeMake(value: 0, timescale: 0)
if let cgImage = try? generator.copyCGImage(at: time, actualTime: &actualTime) {
return UIImage(cgImage: cgImage)
}
return UIImage()
}
//---------------------------------------------------------------------------------------------------------------------------------------------
class func duration(path: String) -> Int {
let asset = AVURLAsset(url: URL(fileURLWithPath: path), options: nil)
return Int(round(CMTimeGetSeconds(asset.duration)))
}
}
| 39.930233 | 147 | 0.552708 |
0a6e8fb6e15a34dc95beac769fd2c8a6d4a1aa9f | 2,128 | //
// PlanetListTableViewController.swift
// SolarSystem
//
// Created by lijia xu on 7/15/21.
//
import UIKit
class PlanetListTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(PlanetListTopHeader.self, forHeaderFooterViewReuseIdentifier: "planetListHeader")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
// MARK: - Header View
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch section {
case 0:
guard let topHeaderView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "planetListHeader") as? PlanetListTopHeader else {return nil}
topHeaderView.image.image = UIImage(named: "solarSystem")
return topHeaderView
default:
return nil
}
}
// MARK: - Rows
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return PlanetController.planets.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "planetCell", for: indexPath)
let planet = PlanetController.planets[indexPath.row]
let planetImageName = planet.planetImageName
cell.imageView?.image = UIImage(named: planetImageName)
cell.textLabel?.text = planet.planetName
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toPlanetDetails" {
guard let selectedIndexPath = tableView.indexPathForSelectedRow, let destination = segue.destination as? PlanetDetailViewController else { return}
let planetToSend = PlanetController.planets[selectedIndexPath.row]
destination.planet = planetToSend
}
}
}
| 29.971831 | 158 | 0.650376 |
1c1ded63ad0271534ccb4238fecfd1c1368f0500 | 1,762 | //
// AppDelegate.swift
// ViuMiddlewareDemo
//
// Created by JNWHYJ on 2021/5/17.
//
import UIKit
@main
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 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.
}
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.
}
}
| 42.97561 | 285 | 0.751419 |
5d5028fec291ffd3f97399e40a7f3642f1be6ea5 | 2,160 | //
// FocusCheckingTextField.swift
// InputFields
//
// Created by József Vesza on 2018. 11. 25..
// Copyright © 2018. József Vesza. All rights reserved.
//
import Cocoa
///
/// Custom `NSTextField` subclass which updates its editing status when it becomes focused.
///
/// Once in focus, `FocusCheckingTextField` will notify its delegate via `controlTextDidBeginEditing(_:)`
///
public class FocusCheckingTextField: NSTextField {
private(set) var isInFocus: Bool = false {
didSet {
/// `currentEditor()` gets queried frequently, but only change is important to the observer
guard isInFocus != oldValue, let fieldEditor = currentEditor() else {
return
}
let notification = Notification(
name: NSControl.textDidBeginEditingNotification,
object: self,
userInfo: [
"NSFieldEditor": fieldEditor
])
textDidBeginEditing(notification)
}
}
/// By default, `NSTextField` receives `textDidBeginEditing(_:)` once the user starts typing text,
/// then it notifies its delegate about the editing status. `FocusCheckingTextFields` already
/// notifies its delegate when it gets in focus, so this override is necessary to prevent duplicate notifications.
public override func textDidBeginEditing(_ notification: Notification) {
guard let sender = notification.object as? NSTextField, sender.stringValue == stringValue else { return }
return super.textDidBeginEditing(notification)
}
/// `NSTextField` doesn't become the first responder once it gets focus. Instead it uses
/// the window's field editor (shared between all the text fields in a given window).
/// Once a text field has the field editor, it is certainly in focus.
override public func currentEditor() -> NSText? {
let currentEditor = super.currentEditor()
if currentEditor == nil {
isInFocus = false
} else {
isInFocus = true
}
return currentEditor
}
}
| 36 | 118 | 0.640741 |
bf744d17d69414ce7be328dd649ec2b707182fd1 | 1,132 | //
// NavigationTitleItem.swift
// SwiftTool
//
// Created by galaxy on 2021/5/24.
// Copyright © 2021 yinhe. All rights reserved.
//
import Foundation
import UIKit
public final class NavigationTitleItem {
public typealias LabelConfigure = ((UILabel) -> Void)
public enum ConstraintsType {
/// 居中显示,会做一系列的动态判断
case center(width: NavigationSize, height: NavigationSize)
/// 填充完`items`之外的所有空间
case fill
}
/// 自定义`View`
public var customView: UIView?
/// 布局类型
public var constraintsType: ConstraintsType = .center(width: .auto, height: .auto)
public init(customView: UIView?, constraintsType: ConstraintsType) {
self.customView = customView
self.constraintsType = constraintsType
}
public init() { }
}
extension NavigationTitleItem {
/// Label
public class func label(constraintsType: ConstraintsType, configure: LabelConfigure?) -> NavigationTitleItem {
let label = UILabel()
configure?(label)
return NavigationTitleItem(customView: label, constraintsType: constraintsType)
}
}
| 25.727273 | 114 | 0.665194 |
3a5b8e5644a6a45d9f89c9f761fd04947d4cba43 | 5,006 | //
// SavedContentCell.swift
// NetflixClone
//
// Created by 양중창 on 2020/04/09.
// Copyright © 2020 Netflex. All rights reserved.
//
import UIKit
class SavedContentCell: UITableViewCell {
static let identifier = "SavedContentCell"
private let thumbnailView = UIButton()
private let playImageView = UIImageView(image: UIImage(systemName: "play.fill"))
private let playImageBackgroundView = CircleView()
private let summaryLabel = UILabel()
private let titleLabel = UILabel()
private let descriptionLabel = UILabel()
private let statusView: SaveContentStatusView
init(id: Int, style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
self.statusView = SaveContentStatusView(id: id, status: .saved)
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUI()
setConstraint()
// test()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setUI() {
backgroundColor = .setNetfilxColor(name: .black)
[summaryLabel, thumbnailView, titleLabel, descriptionLabel, statusView].forEach({
contentView.addSubview($0)
})
// let sizeGuide = UIScreen.main.bounds.height / 7
selectionStyle = .none
thumbnailView.addSubview(playImageBackgroundView)
playImageBackgroundView.addSubview(playImageView)
thumbnailView.contentMode = .scaleAspectFill
playImageView.contentMode = .scaleAspectFit
playImageView.tintColor = .setNetfilxColor(name: .white)
thumbnailView.backgroundColor = .blue
playImageBackgroundView.layer.borderColor = UIColor.setNetfilxColor(name: .white).cgColor
playImageBackgroundView.layer.borderWidth = 1
playImageBackgroundView.backgroundColor = UIColor.setNetfilxColor(name: .black).withAlphaComponent(0.3)
let titleFontSize: CGFloat = 20
titleLabel.font = .dynamicFont(fontSize: titleFontSize, weight: .heavy)
titleLabel.textColor = .setNetfilxColor(name: .white)
descriptionLabel.font = .dynamicFont(fontSize: titleFontSize * 0.7, weight: .light)
descriptionLabel.textColor = .setNetfilxColor(name: .netflixLightGray)
summaryLabel.textColor = .setNetfilxColor(name: .netflixLightGray)
summaryLabel.font = .dynamicFont(fontSize: titleFontSize * 0.8, weight: .regular)
summaryLabel.numberOfLines = 0
}
private func setConstraint() {
let xMargin = CGFloat.dynamicXMargin(margin: 16)
let yMargin = CGFloat.dynamicYMargin(margin: 8)
let xPading = CGFloat.dynamicXMargin(margin: 8)
thumbnailView.snp.makeConstraints({
$0.leading.equalToSuperview().offset(xMargin)
$0.top.equalToSuperview().offset(yMargin)
$0.width.equalToSuperview().multipliedBy(0.3)
$0.height.equalTo(thumbnailView.snp.width).multipliedBy(0.6)
})
playImageBackgroundView.snp.makeConstraints({
$0.center.equalToSuperview()
$0.width.height.equalTo(thumbnailView.snp.height).multipliedBy(0.5)
})
playImageView.snp.makeConstraints({
$0.center.equalToSuperview()
$0.width.height.equalTo(playImageBackgroundView.snp.height).multipliedBy(0.5)
})
titleLabel.snp.makeConstraints({
$0.leading.equalTo(thumbnailView.snp.trailing).offset(xPading)
$0.trailing.equalTo(statusView.snp.leading).offset(-xPading)
$0.bottom.equalTo(thumbnailView.snp.centerY)
})
descriptionLabel.snp.makeConstraints({
$0.leading.equalTo(thumbnailView.snp.trailing).offset(xPading)
$0.trailing.equalTo(statusView.snp.leading).offset(-xPading)
$0.top.equalTo(thumbnailView.snp.centerY)
})
statusView.snp.makeConstraints({
$0.trailing.equalToSuperview().offset(-xMargin)
$0.centerY.equalTo(thumbnailView)
$0.height.width.equalTo(thumbnailView.snp.height).multipliedBy(0.5)
})
summaryLabel.snp.makeConstraints({
$0.leading.trailing.equalToSuperview().inset(xMargin)
$0.top.equalTo(thumbnailView.snp.bottom)
$0.bottom.equalToSuperview()
})
}
private func setImage(stringURL: String) {
}
func configure(title: String, description: String, stringImageURL: String, summary: String) {
titleLabel.text = title
descriptionLabel.text = description
setImage(stringURL: stringImageURL)
summaryLabel.text = summary
}
func insertSummary(summary: String) {
summaryLabel.text = summary
}
}
| 34.054422 | 111 | 0.634439 |
9141c467614b322d27a4e1b8cabadfb82eb9140e | 523 | //
// SuggestedPrductCollectionCell.swift
// Opencart
//
// Created by kunal on 30/07/18.
// Copyright © 2018 kunal. All rights reserved.
//
import UIKit
class SuggestedPrductCollectionCell: UICollectionViewCell {
@IBOutlet var productImage: UIImageView!
@IBOutlet var name: UILabel!
@IBOutlet var price: UILabel!
@IBOutlet var specialPrice: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
specialPrice.textColor = UIColor.lightGray
}
}
| 18.678571 | 59 | 0.671128 |
6a5e492b70c484fcd963ea248427a056a57e9786 | 2,203 | //
//===----------------------------------------------------------------------===//
//
// ObjectBinding.swift
//
// Created by Steven Grosmark on 6/5/19.
//
//
// This source file is part of the Lasso open source project
//
// https://github.com/ww-tech/lasso
//
// Copyright © 2019-2020 WW International, Inc.
//
//===----------------------------------------------------------------------===//
//
import UIKit
/// Objects that can hold strong references to other objects
public protocol ObjectBindable: AnyObject {
func holdReference(to object: AnyObject)
func releaseReference(to object: AnyObject)
}
// This is a common ancestor to UIGestureRecognizers, as well as all other UIKit classes
extension NSObject: ObjectBindable { }
extension ObjectBindable {
/// Hold a strong reference to `object`.
/// The reference will be released when the target ObjectBindable is released.
///
/// - Parameter object: The instance to hold a strong reference to.
public func holdReference(to object: AnyObject) {
var boundObjects = objc_getAssociatedObject(self, &BoundObjects.associationKey) as? BoundObjects.Dictionary ?? [:]
boundObjects[ObjectIdentifier(object)] = object
objc_setAssociatedObject(self, &BoundObjects.associationKey, boundObjects, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
/// Release a previously held strong reference to `object`
///
/// - Parameter object: The instance to let go of.
public func releaseReference(to object: AnyObject) {
guard var boundObjects = objc_getAssociatedObject(self, &BoundObjects.associationKey) as? BoundObjects.Dictionary else { return }
boundObjects.removeValue(forKey: ObjectIdentifier(object))
if boundObjects.isEmpty {
objc_setAssociatedObject(self, &BoundObjects.associationKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
else {
objc_setAssociatedObject(self, &BoundObjects.associationKey, boundObjects, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
private enum BoundObjects {
typealias Dictionary = [ObjectIdentifier: AnyObject]
static var associationKey: Int = 0
}
| 34.421875 | 137 | 0.657739 |
67c945d97b5c248e80d5fdb9492455a5469ecf16 | 5,823 | //
// MNBaseViewController.swift
// MonoFake
//
// Created by tommy on 2017/12/18.
// Copyright © 2017年 TommyStudio. All rights reserved.
//
import Foundation
import SnapKit
import RxCocoa
import RxSwift
open class EvaBaseViewController: UIViewController {
public var disposeBag = DisposeBag()
//MARK: - 生命周期方法
open override func viewDidLoad() {
super.viewDidLoad()
//设置背景色
self.view.backgroundColor = GlobalProperties.COLOR_BG
self.whiteNavigationBarSetting()
}
deinit {
print("\(type(of: self)) destory")
}
//MARK: - 导航栏设置
public func normalNavigationBarSetting() {
let titleAttr = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont.lf_systemMediumFont(size: 18)]
navigationController?.navigationBar.titleTextAttributes = titleAttr
let item = UIBarButtonItem.appearance()
item.tintColor = UIColor.white
let itemAttr = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont.lf_systemMediumFont(size: 16)]
item.setTitleTextAttributes(itemAttr, for: .normal)
navigationController?.navigationBar.setBackgroundImage(UIImage.getImage(color: GlobalProperties.COLOR_MAIN_1, size: CGSize.init(width: CGFloat(1), height: CGFloat(1)), cornerRadius: 0), for: UIBarMetrics.default)
navigationController?.navigationBar.shadowImage = UIImage.init()
navigationController?.navigationBar.tintColor = UIColor.white;
if self.navigationController != nil {
let line = UIView.init()
line.isHidden = true
line.backgroundColor = GlobalProperties.COLOR_LINE
navigationController!.navigationBar.addSubview(line)
line.snp.makeConstraints { (make: ConstraintMaker) in
make.left.bottom.equalTo(navigationController!.navigationBar)
make.size.equalTo(CGSize.init(width: GlobalProperties.SCREEN_WIDTH, height: 0.5))
}
}
}
public func whiteNavigationBarSetting() {
let titleAttr = [NSAttributedString.Key.foregroundColor: GlobalProperties.COLOR_B80, NSAttributedString.Key.font: UIFont.lf_systemMediumFont(size: 18)]
navigationController?.navigationBar.titleTextAttributes = titleAttr
let item = UIBarButtonItem.appearance()
item.tintColor = GlobalProperties.COLOR_B80
let itemAttr = [NSAttributedString.Key.foregroundColor: GlobalProperties.COLOR_B80, NSAttributedString.Key.font: UIFont.lf_systemMediumFont(size: 16)]
item.setTitleTextAttributes(itemAttr, for: .normal)
navigationController?.navigationBar.setBackgroundImage(UIImage.getImage(color: UIColor.white, size: CGSize.init(width: CGFloat(1), height: CGFloat(1)), cornerRadius: 0), for: UIBarMetrics.default)
navigationController?.navigationBar.shadowImage = UIImage.init()
navigationController?.navigationBar.tintColor = UIColor.white;
if self.navigationController != nil {
let line = UIView.init()
line.isHidden = true
line.backgroundColor = GlobalProperties.COLOR_LINE
navigationController!.navigationBar.addSubview(line)
line.snp.makeConstraints { (make: ConstraintMaker) in
make.left.bottom.equalTo(navigationController!.navigationBar)
make.size.equalTo(CGSize.init(width: GlobalProperties.SCREEN_WIDTH, height: 0.5))
}
}
}
public func setupMainNavBack() {
let arrowImage = UIImage.ipzbase_image(named: "nav_back")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
let backButton = UIButton.init()
backButton.setImage(arrowImage, for: .normal)
backButton.addTarget(self, action: #selector(handleNavBack), for: UIControl.Event.touchUpInside)
if GlobalProperties.iOS11Later {
backButton.frame = CGRect.init(x: CGFloat(0), y: CGFloat(0), width: backButton.intrinsicContentSize.width, height: backButton.intrinsicContentSize.height)
let leftItem = UIBarButtonItem.init(customView: backButton)
navigationItem.leftBarButtonItems = [leftItem]
} else {
backButton.frame = CGRect.init(x: CGFloat(0), y: CGFloat(0), width: backButton.intrinsicContentSize.width, height: backButton.intrinsicContentSize.height)
let leftItem = UIBarButtonItem.init(customView: backButton)
let leftNegativeSpacer = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
leftNegativeSpacer.width = -5
navigationItem.leftBarButtonItems = [leftNegativeSpacer, leftItem]
}
}
@objc open func handleNavBack() {
self.navigationController?.popViewController(animated: true)
}
public override func forceEnableInteractivePopGestureRecognizer() -> Bool {
return true
}
public override func viewDidLayoutSubviews() {
if self.navigationController != nil {
self.clearImageView(view: self.navigationController!.navigationBar)
}
}
public func clearImageView(view: UIView) {
for imageView in view.subviews {
if imageView.isKind(of: UIImageView.self) && imageView.height < 5 {
imageView.isHidden = true
}
self.clearImageView(view: imageView)
}
}
public override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
public override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return UIInterfaceOrientation.portrait
}
public override var shouldAutorotate: Bool {
return false
}
}
| 39.883562 | 220 | 0.69672 |
cc3451c0ea0584c15e140dcb21b111d4d297d18e | 1,731 | //
// UIView.swift
// Example
//
// Created by Ade Septiadi on 5/8/17.
// Copyright © 2017 Ade Septiadi. All rights reserved.
//
import Foundation
import UIKit
extension UIView{
class func loadNib<T: UIView>(_ viewType: T.Type) -> T {
let className = String.className(viewType)
return Bundle(for: viewType).loadNibNamed(className, owner: nil, options: nil)!.first as! T
}
class func loadNib() -> Self {
return loadNib(self)
}
/*
Fungsi untuk membuat shadow pada view(seperti tampilan cardview pada android)
*/
func dropShadow(scale: Bool = true) {
self.layer.masksToBounds = false
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 0.3
self.layer.shadowOffset = CGSize(width: -1, height: 1)
self.layer.shadowRadius = 2
self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
/*
Fungsi untuk membuat corner dari view berbentuk rounded
Parameter :
@param rectCorner = object untuk menentuka sisi mana saja yang akan diround. contoh [.topLeft, .bottomRight]
@param size = ukuran lengkung yang diinginkan. contoh : 1,2,..
*/
func setRounded(_ rectCorner:UIRectCorner, _ size: CGFloat){
let rectShape = CAShapeLayer()
rectShape.bounds = self.frame
rectShape.position = self.center
rectShape.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: rectCorner, cornerRadii: CGSize(width: size, height: size)).cgPath
self.layer.mask = rectShape
}
}
| 32.660377 | 149 | 0.652802 |
9082b0b1c547ee7bdc94f16e2839b0bcd859b940 | 323 | //
// User.swift
// GithubAccounts
//
// Created by Kenneth James Uy on 4/29/21.
//
import Foundation
class User: Codable {
var id: Int
var username: String
var avatarUrl: String
private enum CodingKeys: String, CodingKey {
case id
case username = "login"
case avatarUrl = "avatar_url"
}
}
| 14.681818 | 46 | 0.650155 |
fce1df17bd9fdd7a5bf6e8be6de001e9820d35c5 | 4,330 | //
// DetailViewController.swift
// twitter_alamofire_demo
//
// Created by Brandon Shimizu on 10/12/18.
// Copyright © 2018 Charles Hieger. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
var tweet: Tweet!
@IBOutlet weak var detailImage: UIImageView!
@IBOutlet weak var detailNameLabel: UILabel!
@IBOutlet weak var detailHandleLabel: UILabel!
@IBOutlet weak var detailDateLabel: UILabel!
@IBOutlet weak var detailTweetLabel: UILabel!
@IBOutlet weak var detailRetweetBtn: UIButton!
@IBOutlet weak var detailFavoriteBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
refreshData()
// if let tweet = tweet {
// let profileImage = NSURL(string: tweet.user!.profileImage!)
// detailImage.setImageWith(profileImage! as URL)
// detailNameLabel.text = tweet.user!.name
// detailHandleLabel.text = "@" + tweet.user!.screenName!
// detailTweetLabel.text = tweet.text
// detailDateLabel.text = tweet.createdAtString
//
// }
}
@IBAction func onRetweet(_ sender: AnyObject) {
//
if(tweet.retweeted == false){
tweet.retweeted = true
//tweet.retweetCount += 1
refreshData()
APIManager.shared.retweet(with: tweet) { (tweet: Tweet?, error: Error?) in
if let error = error {
print("Error Retweeting tweet: \(error.localizedDescription)")
} else if let tweet = tweet {
print("Successfully Retweeted the following Tweet: \n\(tweet.text)")
}
}
}
else{
tweet.retweeted = false
//tweet.retweetCount -= 1
refreshData()
APIManager.shared.untweet(with: tweet) { (tweet: Tweet?, error: Error?) in
if let error = error {
print("Error Unretweeting tweet: \(error.localizedDescription)")
} else if let tweet = tweet {
print("Successfully Unretweeted the following Tweet: \n\(tweet.text)")
}
}
}
}
@IBAction func onFavorite(_ sender: AnyObject) {
if(tweet.favorited == false){
tweet.favorited = true
//tweet.favoriteCount += 1
refreshData()
APIManager.shared.favorite( tweet) { (tweet: Tweet?, error: Error?) in
if let error = error {
print("Error favoriting tweet: \(error.localizedDescription)")
} else if let tweet = tweet {
print("Successfully favorited the following Tweet: \n\(tweet.text)")
}
}
}
else{
tweet.favorited = false
//tweet.favoriteCount -= 1
refreshData()
APIManager.shared.favorite(tweet) { (tweet: Tweet?, error: Error?) in
if let error = error {
print("Error unfavoriting tweet: \(error.localizedDescription)")
} else if let tweet = tweet {
print("Successfully unfavorited the following Tweet: \n\(tweet.text)")
}
}
}
}
func refreshData(){
if let tweet = tweet {
let profileImage = NSURL(string: tweet.user!.profileImage!)
self.detailImage.setImageWith(profileImage! as URL)
detailNameLabel.text = tweet.user!.name
detailHandleLabel.text = "@" + tweet.user!.screenName!
detailTweetLabel.text = tweet.text
detailDateLabel.text = tweet.createdAtString
}
if(tweet.favorited!){
detailFavoriteBtn.setImage(#imageLiteral(resourceName: "favor-icon-red"), for: .normal)
}
if(tweet.favorited == false){
detailFavoriteBtn.setImage(#imageLiteral(resourceName: "favor-icon"), for: .normal)
}
if(tweet.retweeted!){
detailRetweetBtn.setImage(#imageLiteral(resourceName: "retweet-icon-green"), for: .normal)
}
if(tweet.retweeted==false){
detailRetweetBtn.setImage(#imageLiteral(resourceName: "retweet-icon"), for: .normal)
}
}
}
| 34.64 | 102 | 0.563741 |
e61148df845eddd8f94f4d1cd3fabaea6c2034de | 13,535 | import Foundation
typealias JSONDictionary = [String: Any]
/// The Mapbox access token specified in the main application bundle’s Info.plist.
let defaultAccessToken = Bundle.main.object(forInfoDictionaryKey: "MGLMapboxAccessToken") as? String
/// The user agent string for any HTTP requests performed directly within this library.
let userAgent: String = {
var components: [String] = []
if let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String {
let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
components.append("\(appName)/\(version)")
}
let libraryBundle: Bundle? = Bundle(for: SpeechSynthesizer.self)
if let libraryName = libraryBundle?.infoDictionary?["CFBundleName"] as? String, let version = libraryBundle?.infoDictionary?["CFBundleShortVersionString"] as? String {
components.append("\(libraryName)/\(version)")
}
// `ProcessInfo().operatingSystemVersionString` can replace this when swift-corelibs-foundaton is next released:
// https://github.com/apple/swift-corelibs-foundation/blob/main/Sources/Foundation/ProcessInfo.swift#L104-L202
let system: String
#if os(macOS)
system = "macOS"
#elseif os(iOS)
system = "iOS"
#elseif os(watchOS)
system = "watchOS"
#elseif os(tvOS)
system = "tvOS"
#elseif os(Linux)
system = "Linux"
#else
system = "unknown"
#endif
let systemVersion = ProcessInfo().operatingSystemVersion
components.append("\(system)/\(systemVersion.majorVersion).\(systemVersion.minorVersion).\(systemVersion.patchVersion)")
let chip: String
#if arch(x86_64)
chip = "x86_64"
#elseif arch(arm)
chip = "arm"
#elseif arch(arm64)
chip = "arm64"
#elseif arch(i386)
chip = "i386"
#else
// Maybe fall back on `uname(2).machine`?
chip = "unrecognized"
#endif
components.append("(\(chip))")
return components.joined(separator: " ")
}()
var skuToken: String? {
guard let mbx: AnyClass = NSClassFromString("MBXAccounts") else { return nil }
guard mbx.responds(to: Selector(("serviceSkuToken"))) else { return nil }
return mbx.value(forKeyPath: "serviceSkuToken") as? String
}
/**
A `SpeechSynthesizer` object converts text into spoken audio. Unlike `AVSpeechSynthesizer`, a `SpeechSynthesizer` object produces audio by sending an HTTP request to the Mapbox Voice API, which produces more natural-sounding audio in various languages. With a speech synthesizer object, you can asynchronously generate audio data based on the `SpeechOptions` object you provide, or you can get the URL used to make this request.
Use `AVAudioPlayer` to play the audio that a speech synthesizer object produces.
*/
open class SpeechSynthesizer {
public typealias CompletionHandler = (_ data: Data?, _ error: SpeechError?) -> Void
// MARK: Creating a Speech Object
/**
The shared speech synthesizer object.
To use this object, specify a Mapbox [access token](https://www.mapbox.com/help/define-access-token/) in the `MGLMapboxAccessToken` key in the main application bundle’s Info.plist.
*/
public static let shared = SpeechSynthesizer(accessToken: nil)
/// The API endpoint to request the audio from.
public private(set) var apiEndpoint: URL
/// The Mapbox access token to associate the request with.
public let accessToken: String
/**
Initializes a newly created speech synthesizer object with an optional access token and host.
- parameter accessToken: A Mapbox [access token](https://www.mapbox.com/help/define-access-token/). If an access token is not specified when initializing the speech synthesizer object, it should be specified in the `MGLMapboxAccessToken` key in the main application bundle’s Info.plist.
- parameter host: An optional hostname to the server API. The Mapbox Voice API endpoint is used by default.
*/
public init(accessToken: String?, host: String?) {
let accessToken = accessToken ?? defaultAccessToken
assert(accessToken != nil && !accessToken!.isEmpty, "A Mapbox access token is required. Go to <https://www.mapbox.com/studio/account/tokens/>. In Info.plist, set the MGLMapboxAccessToken key to your access token, or use the Speech(accessToken:host:) initializer.")
self.accessToken = accessToken!
var baseURLComponents = URLComponents()
baseURLComponents.scheme = "https"
baseURLComponents.host = host ?? "api.mapbox.com"
self.apiEndpoint = baseURLComponents.url!
}
/**
Initializes a newly created speech synthesizer object with an optional access token.
- parameter accessToken: A Mapbox [access token](https://www.mapbox.com/help/define-access-token/). If an access token is not specified when initializing the speech synthesizer object, it should be specified in the `MGLMapboxAccessToken` key in the main application bundle’s Info.plist.
*/
public convenience init(accessToken: String?) {
self.init(accessToken: accessToken, host: nil)
}
// MARK: Getting Speech
/**
Begins asynchronously fetching the audio file.
This method retrieves the audio asynchronously over a network connection. If a connection error or server error occurs, details about the error are passed into the given completion handler in lieu of the audio file.
- parameter options: A `SpeechOptions` object specifying the requirements for the resulting audio file.
- parameter completionHandler: The closure (block) to call with the resulting audio. This closure is executed on the application’s main thread.
- returns: The data task used to perform the HTTP request. If, while waiting for the completion handler to execute, you no longer want the resulting audio, cancel this task.
*/
@discardableResult open func audioData(with options: SpeechOptions, completionHandler: @escaping CompletionHandler) -> URLSessionDataTask {
let url = self.url(forSynthesizing: options)
let task = dataTask(with: url, completionHandler: { (data) in
completionHandler(data, nil)
}) { (error) in
completionHandler(nil, error)
}
task.resume()
return task
}
/**
Returns a URL session task for the given URL that will run the given closures on completion or error.
- parameter url: The URL to request.
- parameter completionHandler: The closure to call with the parsed JSON response dictionary.
- parameter errorHandler: The closure to call when there is an error.
- returns: The data task for the URL.
- postcondition: The caller must resume the returned task.
*/
fileprivate func dataTask(with url: URL, completionHandler: @escaping (_ data: Data) -> Void, errorHandler: @escaping (_ error: SpeechError) -> Void) -> URLSessionDataTask {
var request = URLRequest(url: url)
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
let task = URLSession.shared.dataTask(with: request as URLRequest) { (possibleData, possibleResponse, possibleError) in
if let error = possibleError {
errorHandler(.unknown(response: possibleResponse, underlying: error, code: nil, message: nil))
return
}
guard let data = possibleData else {
errorHandler(.noData)
return
}
guard let response = possibleResponse else {
errorHandler(.invalidResponse)
return
}
// Parse error object
if response.mimeType == "application/json" {
var errorJSON: JSONDictionary = [:]
do {
errorJSON = try JSONSerialization.jsonObject(with: data, options: []) as! JSONDictionary
} catch {
errorHandler(SpeechSynthesizer.informativeError(code: nil, message: nil, response: response, underlyingError: error))
}
let apiStatusCode = errorJSON["code"] as? String
let apiMessage = errorJSON["message"] as? String
guard (apiStatusCode == nil && apiMessage == nil) || apiStatusCode == "Ok" else {
let apiError = SpeechSynthesizer.informativeError(code: apiStatusCode, message: apiMessage, response: response, underlyingError: possibleError)
DispatchQueue.main.async {
errorHandler(apiError)
}
return
}
}
DispatchQueue.main.async {
completionHandler(data)
}
}
task.resume()
return task
}
/**
The HTTP URL used to fetch audio from the API.
*/
open func url(forSynthesizing options: SpeechOptions) -> URL {
var params = options.params
params += [URLQueryItem(name: "access_token", value: accessToken)]
if let skuToken = skuToken {
params += [URLQueryItem(name: "sku", value: skuToken)]
}
let unparameterizedURL = URL(string: options.path, relativeTo: apiEndpoint)!
var components = URLComponents(url: unparameterizedURL, resolvingAgainstBaseURL: true)!
components.queryItems = params
return components.url!
}
/**
Returns an error that supplements the given underlying error with additional information from the an HTTP response’s body or headers.
*/
static func informativeError(code: String?, message: String?, response: URLResponse?, underlyingError error: Error?) -> SpeechError {
if let response = response as? HTTPURLResponse {
switch (response.statusCode, code ?? "") {
case (429, _):
return .rateLimited(rateLimitInterval: response.rateLimitInterval, rateLimit: response.rateLimit, resetTime: response.rateLimitResetTime)
default:
return .unknown(response: response, underlying: error, code: code, message: message)
}
}
return .unknown(response: response, underlying: error, code: code, message: message)
}
}
public enum SpeechError: LocalizedError {
case noData
case invalidResponse
case rateLimited(rateLimitInterval: TimeInterval?, rateLimit: UInt?, resetTime: Date?)
case unknown(response: URLResponse?, underlying: Error?, code: String?, message: String?)
public var failureReason: String? {
switch self {
case .noData:
return "The server returned an empty response."
case .invalidResponse:
return "The server returned a response that isn’t correctly formatted."
case let .rateLimited(rateLimitInterval: interval, rateLimit: limit, _):
let intervalFormatter = DateComponentsFormatter()
intervalFormatter.unitsStyle = .full
guard let interval = interval, let limit = limit else {
return "Too many requests."
}
let formattedInterval = intervalFormatter.string(from: interval) ?? "\(interval) seconds"
let formattedCount = NumberFormatter.localizedString(from: NSNumber(value: limit), number: .decimal)
return "More than \(formattedCount) requests have been made with this access token within a period of \(formattedInterval)."
case let .unknown(_, underlying: error, _, message):
return message
?? (error as NSError?)?.userInfo[NSLocalizedFailureReasonErrorKey] as? String
?? HTTPURLResponse.localizedString(forStatusCode: (error as NSError?)?.code ?? -1)
}
}
public var recoverySuggestion: String? {
switch self {
case .noData:
return nil
case .invalidResponse:
return nil
case let .rateLimited(rateLimitInterval: _, rateLimit: _, resetTime: rolloverTime):
guard let rolloverTime = rolloverTime else {
return nil
}
let formattedDate: String = DateFormatter.localizedString(from: rolloverTime, dateStyle: .long, timeStyle: .long)
return "Wait until \(formattedDate) before retrying."
case let .unknown(_, underlying: error, _, _):
return (error as NSError?)?.userInfo[NSLocalizedRecoverySuggestionErrorKey] as? String
}
}
}
extension HTTPURLResponse {
var rateLimit: UInt? {
guard let limit = allHeaderFields["X-Rate-Limit-Limit"] as? String else {
return nil
}
return UInt(limit)
}
var rateLimitInterval: TimeInterval? {
guard let interval = allHeaderFields["X-Rate-Limit-Interval"] as? String else {
return nil
}
return TimeInterval(interval)
}
var rateLimitResetTime: Date? {
guard let resetTime = allHeaderFields["X-Rate-Limit-Reset"] as? String else {
return nil
}
guard let resetTimeNumber = Double(resetTime) else {
return nil
}
return Date(timeIntervalSince1970: resetTimeNumber)
}
}
| 45.116667 | 429 | 0.650979 |
29348957804bfad5c635879d283f348d669f4e17 | 2,215 | //
// BetaAppReviewSubmission.swift
// AppStoreConnect-Swift-SDK
//
// Created by Pascal Edmond on 12/11/2018.
//
import Foundation
/// The data structure that represents the resource.
public struct BetaAppReviewSubmission: Decodable {
/// The resource's attributes.
public let attributes: BetaAppReviewSubmission.Attributes?
/// (Required) The opaque resource ID that uniquely identifies the resource.
public let `id`: String
/// (Required) Navigational links that include the self-link.
public let links: ResourceLinks
/// Navigational links to related data and included resource types and IDs.
public let relationships: BetaAppReviewSubmission.Relationships?
/// (Required) The resource type.Value: betaAppReviewSubmissions
public let type: String
/// Attributes that describe a resource.
public struct Attributes: Decodable {
/// A state that indicates the current status of the beta app review submission.
public let betaReviewState: BetaReviewState?
}
public struct Relationships: Decodable {
/// BetaAppReviewSubmission.Relationships.Build
public let build: BetaAppReviewSubmission.Relationships.Build?
}
}
/// MARK: BetaAppReviewSubmission.Relationships
extension BetaAppReviewSubmission.Relationships {
public struct Build: Decodable {
/// BetaAppReviewSubmission.Relationships.Build.Data
public let data: BetaAppReviewSubmission.Relationships.Build.Data?
/// BetaAppReviewSubmission.Relationships.Build.Links
public let links: BetaAppReviewSubmission.Relationships.Build.Links?
}
}
/// MARK: BetaAppReviewSubmission.Relationships.Build
extension BetaAppReviewSubmission.Relationships.Build {
public struct Data: Decodable {
/// (Required) The opaque resource ID that uniquely identifies the resource.
public let `id`: String
/// (Required) The resource type.Value: builds
public let type: String
}
public struct Links: Decodable {
/// uri-reference
public let related: URL?
/// uri-reference
public let `self`: URL?
}
}
| 29.144737 | 88 | 0.697968 |
9118b22384895f7a21febc13caad6bf229ecaf98 | 550 | //
// HomepageItemCollectionViewCell.swift
// Peekazoo
//
// Created by Thomas Sherwood on 15/05/2017.
// Copyright © 2017 Peekazoo. All rights reserved.
//
import UIKit
public class HomepageItemCollectionViewCell: UICollectionViewCell {
@IBOutlet public weak var itemTitleLabel: UILabel!
@IBOutlet public weak var itemCreationDateLabel: UILabel!
func configure(with viewModel: HomepageInterfaceItemViewModel?) {
itemTitleLabel.text = viewModel?.title
itemCreationDateLabel.text = viewModel?.creationDate
}
}
| 25 | 69 | 0.747273 |
ded78a4ba53da89615dbe22c1e36d2772dff7f36 | 617 | //
// ImageRecordModel.swift
// Archive
//
// Created by hanwe on 2021/10/24.
//
import UIKit
protocol ImageRecordModelProtocol {
var imageInfo: [ImageInfo] { get set }
}
class ImageRecordModel: ImageRecordModelProtocol {
// MARK: outlet
// MARK: private property
// MARK: property
var imageInfo: [ImageInfo] = []
// MARK: lifeCycle
init() {
}
// MARK: private func
// MARK: func
// MARK: action
}
struct ImageInfo: Equatable {
var image: UIImage
var backgroundColor: UIColor
var contents: String?
}
| 14.690476 | 50 | 0.583468 |
38aa822ee349936b3ed86b1aca25129ee85d1e8d | 5,653 | //
// UIViewController+Show.swift
// Pods
//
// Created by FOLY on 7/14/17.
//
//
import Foundation
import UIKit
extension UIViewController {
open func show(on baseViewController: UIViewController,
embedIn NavigationType: UINavigationController.Type = UINavigationController.self,
closeButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop),
position: CloseButtonPosition = .left,
animated: Bool = true,
completion: (() -> Void)? = nil) {
if let navigation = baseViewController as? UINavigationController {
navigation.pushViewController(self, animated: animated)
if let completion = completion {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25, execute: completion)
}
} else {
baseViewController.present(self, embedIn: NavigationType, closeButton: closeButton, position: position, animated: animated, completion: completion)
}
}
open func show(viewController: UIViewController,
from baseviewController: UIViewController? = nil,
embedIn NavigationType: UINavigationController.Type = UINavigationController.self,
closeButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop),
position: CloseButtonPosition = .left,
animated: Bool = true,
completion: (() -> Void)? = nil) {
guard let base = baseviewController else {
if let navigation = self.navigationController {
viewController.show(on: navigation, embedIn: NavigationType, closeButton: closeButton, position: position, animated: animated, completion: completion)
} else {
viewController.show(on: self, embedIn: NavigationType, closeButton: closeButton, position: position, animated: animated, completion: completion)
}
return
}
viewController.show(on: base, embedIn: NavigationType, closeButton: closeButton, position: position, animated: animated, completion: completion)
}
open func backToPrevious(animated: Bool = true, completion: (() -> Void)? = nil) {
if let navigation = self.navigationController {
if navigation.viewControllers.first != self {
navigation.popViewController(animated: animated)
if let completion = completion {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25, execute: completion)
}
} else {
if let _ = navigation.presentingViewController {
navigation.dismiss(animated: animated, completion: completion)
} else {
assertionFailure("Previous page not found")
}
}
} else if let _ = self.presentingViewController {
dismiss(animated: animated, completion: completion)
} else {
assertionFailure("Previous page not found")
}
}
open func forceDismiss(animated: Bool = true, completion: (() -> Void)? = nil) {
if let _ = self.presentingViewController {
dismiss(animated: animated, completion: completion)
} else if let navigation = navigationController, let _ = navigation.presentingViewController {
navigation.dismiss(animated: animated, completion: completion)
} else if let presented = self.presentedViewController {
presented.dismiss(animated: animated, completion: completion)
} else {
assertionFailure("Presenting page not found")
}
}
open func present(_ vc: UIViewController, embedIn NavigationType: UINavigationController.Type = UINavigationController.self, closeButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop), position: CloseButtonPosition = .left, animated: Bool = true, completion: (() -> Void)? = nil) {
if let nav = vc as? UINavigationController {
nav.topViewController?.showCloseButton(closeButton, at: position)
present(nav, animated: animated, completion: completion)
} else {
vc.showCloseButton(at: position)
let nav = NavigationType.init(rootViewController: vc)
present(nav, animated: animated, completion: completion)
}
}
}
extension UIViewController {
public enum CloseButtonPosition {
case left
case right
}
open func showCloseButton(_ barButtonItem: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop), at position: CloseButtonPosition = .left) {
barButtonItem.action = #selector(dismissButtonDidTap(_:))
barButtonItem.target = self
switch position {
case .left:
navigationItem.leftBarButtonItem = barButtonItem
case .right:
navigationItem.rightBarButtonItem = barButtonItem
}
}
open func showCloseButtonIfNeeded(_ barButtonItem: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop), at position: CloseButtonPosition = .left) {
if isPresentedInNavigation, isRootOfNavigation {
showCloseButton(barButtonItem, at: position)
}
}
@IBAction private func dismissButtonDidTap(_ sender: Any) {
forceDismiss()
}
var isRootOfNavigation: Bool {
return navigationController?.viewControllers.first == self
}
var isPresentedInNavigation: Bool {
return navigationController?.presentingViewController != nil
}
}
| 44.164063 | 301 | 0.643729 |
ed3ba1233d5b8b744473772eb2cd9ba5f55f490c | 2,722 | //
// SheetsListViewController.swift
// Castle
//
// Created by Ian Ynda-Hummel on 9/19/17.
// Copyright © 2017 Ian Ynda-Hummel. All rights reserved.
//
import RealmSwift
import UIKit
class SheetsListViewController: UITableViewController {
private lazy var realm = try! Realm()
private lazy var sheets: Results<SpreadsheetObject> = {
return self.realm.objects(SpreadsheetObject.self).sorted(byKeyPath: "title")
}()
private var sheetObjects: [SpreadsheetObject] = [] {
didSet {
tableView.reloadData()
}
}
private var token: NotificationToken?
private let searchViewController = SearchViewController()
private lazy var searchController = UISearchController(searchResultsController: self.searchViewController)
init() {
super.init(style: .plain)
searchController.searchBar.autocapitalizationType = .words
searchController.searchResultsUpdater = searchViewController
navigationItem.hidesSearchBarWhenScrolling = false
navigationItem.searchController = searchController
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Archive"
token = sheets.observe { results in
switch results {
case let .initial(sheets):
self.sheetObjects = Array(sheets)
case let .update(sheets, _, _, _):
self.sheetObjects = Array(sheets)
case let .error(error):
print(error)
}
}
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sheetObjects.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let sheet = sheetObjects[indexPath.row]
cell.textLabel!.text = sheet.title
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let sheet = sheetObjects[indexPath.row]
let sheetViewController = SheetViewController(sheet: sheet)
navigationController?.pushViewController(sheetViewController, animated: true)
}
}
| 31.651163 | 110 | 0.652829 |
ab72005459b23d17072d627b1e5a1e6ffa848872 | 14,414 | //
// ViewController.swift
// aem-manager-osx
//
// Created by Peter Mannel-Wiedemann on 27.11.15.
//
//
import Cocoa
class ViewController: NSViewController {
// MARK: properties
@IBOutlet weak var table: NSTableView!
var instances = AEMInstance.loadAEMInstances()
var selectedInstance: AEMInstance?
var menuInstance: AEMInstance?
var guiarray:[NSWindowController] = []
var items: [NSStatusItem] = []
func backgroundThread(delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)) {
if(background != nil){ background!(); }
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
if(completion != nil){ completion!(); }
}
}
}
override func viewDidAppear() {
}
override func viewDidLoad() {
super.viewDidLoad()
table.setDataSource(self)
table.setDelegate(self)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadTableData:", name: "reload", object: nil)
let app = NSApplication.sharedApplication().delegate as! AppDelegate
app.mainVC = self
for instance in instances{
if instance.showIcon {
let statusBarItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
items.append(statusBarItem)
let icon = NSImage(named: String(instance.icon.characters.last!))
statusBarItem.image = icon
let menu : NSMenu = NSMenu()
menu.autoenablesItems = false
let startInstanceMenuItem = InstanceMenuItem(t: "Start Instance", a: "startInstance2:", k: "",instance: instance)
menu.addItem(startInstanceMenuItem)
let stopInstanceMenuItem = InstanceMenuItem(t: "Stop Instance", a: "stopInstance2:", k: "",instance: instance)
menu.addItem(stopInstanceMenuItem)
menu.addItem(NSMenuItem.separatorItem())
let openAuthorMenuItem = InstanceMenuItem(t: "Open Author/Publish", a: "openAuthor2:", k: "",instance: instance)
menu.addItem(openAuthorMenuItem)
let openCRX = InstanceMenuItem(t: "Open CRX", a: "openCRX2:", k: "",instance: instance)
menu.addItem(openCRX)
let openCRXContentExplorer = InstanceMenuItem(t: "Open CRX Content Explorer", a: "openCRXContentExplorer2:", k: "",instance: instance)
menu.addItem(openCRXContentExplorer)
let openCRXDE = InstanceMenuItem(t: "Open CRXDE Lite", a: "openCRXDE2:", k: "",instance: instance)
menu.addItem(openCRXDE)
let openFelixConsole = InstanceMenuItem(t: "Open Felix Console", a: "openFelixConsole2:", k: "",instance: instance)
menu.addItem(openFelixConsole)
menu.addItem(NSMenuItem.separatorItem())
let eLog = InstanceMenuItem(t: "Error Log", a: "openErrorLog2:", k: "",instance: instance)
menu.addItem(eLog)
let rLog = InstanceMenuItem(t: "Request Log", a: "openRequestLog2:", k: "",instance: instance)
menu.addItem(rLog)
statusBarItem.menu = menu
}
}
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func editInstance(sender: NSMenuItem) {
if table.selectedRow < 0 {
performSegueWithIdentifier("noInstance",sender: self)
}else{
// open preferences dialog with instance
if let winCrtl = storyboard!.instantiateControllerWithIdentifier("aemInstanceGUI") as? NSWindowController {
if let aemInstanceGui = winCrtl.contentViewController as? AemInstanceController{
// add data
print("Selected Instance in table with id \(selectedInstance?.id) and name \(selectedInstance?.name)")
aemInstanceGui.aeminstance = selectedInstance
aemInstanceGui.instances = instances
print("Edit Instance with name : \(aemInstanceGui.aeminstance!.name) and id: \(aemInstanceGui.aeminstance!.id)")
}
winCrtl.showWindow(self)
guiarray.append(winCrtl)
}
}
}
@IBAction func newInstance(sender: NSMenuItem) {
// open new preferences dialog
if let winCrtl = storyboard!.instantiateControllerWithIdentifier("aemInstanceGUI") as? NSWindowController {
if let aemInstanceGui = winCrtl.contentViewController as? AemInstanceController{
// add data
aemInstanceGui.aeminstance = AEMInstance()
aemInstanceGui.instances = instances
print("New Instance with id \(aemInstanceGui.aeminstance!.id)")
}
winCrtl.showWindow(self)
guiarray.append(winCrtl)
}
}
@IBAction func startInstance(sender: NSMenuItem) {
if table.selectedRow < 0 {
performSegueWithIdentifier("noInstance",sender: self)
}else{
backgroundThread(background: {
AemActions.startInstance(self.selectedInstance!)
//NSNotificationCenter.defaultCenter().postNotificationName("reload", object: nil)
},completion: {
// A function to run in the foreground when the background thread is complete
// NSNotificationCenter.defaultCenter().postNotificationName("reload", object: nil)
})
}
}
func startInstance2(sender: InstanceMenuItem) -> Void {
backgroundThread(background: {
AemActions.startInstance(sender.ins)
//NSNotificationCenter.defaultCenter().postNotificationName("reload", object: nil)
},completion: {
// A function to run in the foreground when the background thread is complete
// NSNotificationCenter.defaultCenter().postNotificationName("reload", object: nil)
})
}
@IBAction func stopInstance(sender: NSMenuItem) {
if table.selectedRow < 0 {
performSegueWithIdentifier("noInstance",sender: self)
}else{
print("Stop Instance")
AemActions.stopInstance(selectedInstance!)
}
}
func stopInstance2(sender: InstanceMenuItem) {
AemActions.stopInstance(sender.ins)
}
@IBAction func openAuthor(sender: NSMenuItem) {
if table.selectedRow < 0 {
performSegueWithIdentifier("noInstance",sender: self)
}else{
print("Open Author/Publish")
if let url = NSURL(string: AEMInstance.getUrlWithContextPath(selectedInstance!)){
NSWorkspace.sharedWorkspace().openURL(url)
}
}
}
func openAuthor2(sender: InstanceMenuItem) {
if let url = NSURL(string: AEMInstance.getUrlWithContextPath(sender.ins)){
NSWorkspace.sharedWorkspace().openURL(url)
}
}
@IBAction func openCRX(sender: NSMenuItem) {
if table.selectedRow < 0 {
performSegueWithIdentifier("noInstance",sender: self)
}else{
print("Open CRX")
openFuncCRX(selectedInstance!)
}
}
func openCRX2(sender: InstanceMenuItem) {
print("Open CRX")
openFuncCRX(sender.ins)
}
func openFuncCRX(instace: AEMInstance){
var url = AEMInstance.getUrlWithContextPath(instace)
url.appendContentsOf("/crx/explorer/")
if(selectedInstance?.type != AEMInstance.defaultType){
url = AEMInstance.getUrl(instace)
url.appendContentsOf("/crx/")
}
if let openUrl = NSURL(string:url){
NSWorkspace.sharedWorkspace().openURL(openUrl)
}
}
@IBAction func openCRXContentExplorer(sender: NSMenuItem) {
if table.selectedRow < 0 {
performSegueWithIdentifier("noInstance",sender: self)
}else{
openCRXContentExplorerFunc(selectedInstance!)
}
}
func openCRXContentExplorer2(sender: InstanceMenuItem) {
openCRXContentExplorerFunc(sender.ins)
}
func openCRXContentExplorerFunc(instance: AEMInstance) {
print("Open CRX Content Explorer")
var url = AEMInstance.getUrlWithContextPath(instance)
url.appendContentsOf("/crx/explorer/browser/")
if(selectedInstance?.type != AEMInstance.defaultType){
url = AEMInstance.getUrl(instance)
url.appendContentsOf("/crx/browser/index.jsp")
}
if let openUrl = NSURL(string:url){
NSWorkspace.sharedWorkspace().openURL(openUrl)
}
}
@IBAction func openCRXDE(sender: NSMenuItem) {
if table.selectedRow < 0 {
performSegueWithIdentifier("noInstance",sender: self)
}else{
openCRXDEFunc(selectedInstance!)
}
}
func openCRXDEFunc(instance : AEMInstance) {
var url = AEMInstance.getUrlWithContextPath(instance)
url.appendContentsOf("/crx/de/")
if selectedInstance?.type != AEMInstance.defaultType {
url = AEMInstance.getUrl(instance)
url.appendContentsOf("/crxde")
}
if let openUrl = NSURL(string: url){
NSWorkspace.sharedWorkspace().openURL(openUrl)
}
}
func openCRXDE2(sender: InstanceMenuItem) {
openCRXDEFunc(sender.ins)
}
@IBAction func openFelixConsole(sender: NSMenuItem) {
if table.selectedRow < 0 {
performSegueWithIdentifier("noInstance",sender: self)
}else{
openFelixConsoleFunc(selectedInstance!)
}
}
func openFelixConsoleFunc(instance: AEMInstance){
print("Open Felix Console")
var url = AEMInstance.getUrlWithContextPath(instance)
url.appendContentsOf("/system/console")
if let openUrl = NSURL(string: url){
NSWorkspace.sharedWorkspace().openURL(openUrl)
}
}
func openFelixConsole2(sender: InstanceMenuItem) {
openFelixConsoleFunc(sender.ins)
}
func reloadTableData(notification: NSNotification){
instances = AEMInstance.loadAEMInstances()
table.reloadData()
}
@IBAction func openErrorLog(sender: NSMenuItem) {
if table.selectedRow < 0 {
performSegueWithIdentifier("noInstance",sender: self)
}else{
openErrorLogFunc(selectedInstance!)
}
}
func openErrorLog2(sender: InstanceMenuItem) {
print("open Error Log")
openErrorLogFunc(sender.ins)
}
func openErrorLogFunc(instance: AEMInstance){
openLogFile(instance, log: "error.log")
}
func openLogFile(instance:AEMInstance, log: String){
var url = AEMInstance.getLogBaseFolder(instance)
url.appendContentsOf(log)
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(url){
NSWorkspace.sharedWorkspace().openFile(url)
}
}
@IBAction func openRequestLog(sender: NSMenuItem) {
if table.selectedRow < 0 {
performSegueWithIdentifier("noInstance",sender: self)
}else{
openRequestLogFunc(selectedInstance!)
}
}
func openRequestLog2(sender: InstanceMenuItem) {
openRequestLogFunc(sender.ins)
}
func openRequestLogFunc(instance: AEMInstance){
openLogFile(instance, log: "request.log")
}
}
extension ViewController: NSTableViewDataSource , NSTableViewDelegate {
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return instances.count
}
func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
if let coid = tableColumn?.identifier {
switch coid {
case "name": return instances[row].name
case "path": return instances[row].path
case "type": return instances[row].type
/* case "status":
let status = instances[row].status
switch status {
case .Running: return "Running"
case .Starting_Stopping: return "Starting/Stopping"
case .Unknown: return "Unknown"
case .NotActive: return "Not active"
case .Disabled: return "Disabled"
}
*/
case "url": return AEMInstance.getUrl(instances[row])
default: break
}
}
return nil
}
func tableViewSelectionDidChange(notification: NSNotification) {
if table.selectedRow >= 0 {
print("Selected instance in table with name : \(instances[table.selectedRow].name) and id: \(instances[table.selectedRow].id)")
// set seletected instance
selectedInstance = instances[table.selectedRow]
}
}
}
class InstanceMenuItem : NSMenuItem {
var ins: AEMInstance
init(t: String, a:Selector, k: String,instance:AEMInstance) {
ins = instance
super.init(title: t, action: a, keyEquivalent: k)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 33.915294 | 150 | 0.58124 |
ccdb5670c9c4f65296801db6df65cf69201b866a | 2,565 | /*:
## Exercise - Functions and Optionals
If an app asks for a user's age, it may be because the app requires a user to be over a certain age to use some of the services it provides. Write a function called `checkAge` that takes one parameter of type `String`. The function should try to convert this parameter into an `Int` value and then check if the user is over 18 years old. If he/she is old enough, print "Welcome!", otherwise print "Sorry, but you aren't old enough to use our app." If the `String` parameter cannot be converted into an `Int` value, print "Sorry, something went wrong. Can you please re-enter your age?" Call the function and pass in `userInputAge` below as the single parameter. Then call the function and pass in a string that can be converted to an integer.
*/
let userInputAge: String = "34e"
func checkAge(_ ageString: String) -> Int? {
if let age = Int(ageString) {
if age > 18 {
print("Welcome!")
} else {
print("Sorry, but you aren't old enough to use our app.")
}
return age
} else {
print("Sorry, something went wrong. Can you please re-enter your age?")
return nil
}
}
checkAge(userInputAge)
checkAge("34")
//: Go back and update your function to return the age as an integer. Will your function always return a value? Make sure your return type accurately reflects this. Call the function and print the return value.
let returnValue = checkAge("16")
print(returnValue)
//: Imagine you are creating an app for making purchases. Write a function that will take in the name of an item for purchase as a `String` and will return the cost of that item as an optional `Double`. In the body of the function, check to see if the item is in stock by accessing it in the dictionary `stock`. If it is, return the price of the item by accessing it in the dictionary `prices`. If the item is out of stock, return `nil`. Call the function and pass in a `String` that exists in the dictionaries below. Print the return value.
var prices = ["Chips": 2.99, "Donuts": 1.89, "Juice": 3.99, "Apple": 0.50, "Banana": 0.25, "Broccoli": 0.99]
var stock = ["Chips": 4, "Donuts": 0, "Juice": 12, "Apple": 6, "Banana": 6, "Broccoli": 3]
func getCost(_ itemName: String) -> Double? {
if let itemsLeft = stock[itemName] {
if itemsLeft > 0 {
return prices[itemName]
}
}
return nil
}
print(getCost("Chips"))
print(getCost("Donuts"))
/*:
[Previous](@previous) | page 3 of 6 | [Next: App Exercise - Food Functions](@next)
*/
| 59.651163 | 743 | 0.689279 |
e27f8fd6f68274277c426f101135df91e187d668 | 1,327 | /**
* Question Link: https://leetcode.com/problems/evaluate-reverse-polish-notation/
* Primary idea: Push a number to a stack and pop two for operation when encounters a operator
* Time Complexity: O(n), Space Complexity: O(n)
*/
class EvaluateReversePolishNotation {
func evalRPN(_ tokens: [String]) -> Int {
var stack = [Int]()
for token in tokens {
if let num = Int(token) {
stack.append(num)
} else {
guard let postNum = stack.popLast(), let prevNum = stack.popLast() else {
fatalError("Invalid Input")
}
stack.append(operate(token, prevNum, postNum))
}
}
if let last = stack.last {
return last
} else {
fatalError("Invalid Input")
}
}
private func operate(_ token: String, _ prevNum: Int, _ postNum: Int) -> Int {
switch token {
case "+":
return prevNum + postNum
case "-":
return prevNum - postNum
case "*":
return prevNum * postNum
case "/":
return prevNum / postNum
default:
fatalError("Invalid Input")
}
}
}
| 29.488889 | 94 | 0.49058 |
0166991ff5fffd7c96b7ec1047cf08714831123f | 1,182 | import XCTest
import HWKit
import HighwayCore
import TestKit
import FileSystem
import Url
final class HighwayBundleCreatorTests: XCTestCase {
func testSuccess() {
let fs = InMemoryFileSystem()
let url = Absolute("/highway-go")
let homeUrl = Absolute("/.highway")
XCTAssertNoThrow(try fs.createDirectory(at: url))
XCTAssertNoThrow(try fs.createDirectory(at: homeUrl))
let bundle: HighwayBundle
let config = HighwayBundle.Configuration.standard
do {
bundle = try HighwayBundle(creatingInParent: .root,
fileSystem: fs,
configuration: config,
homeBundleConfiguration: .standard)
} catch {
XCTFail(error.localizedDescription)
return
}
XCTAssertTrue(fs.file(at: bundle.mainSwiftFileUrl).isExistingFile)
XCTAssertTrue(fs.file(at: bundle.packageFileUrl).isExistingFile)
XCTAssertTrue(fs.file(at: bundle.xcconfigFileUrl).isExistingFile)
XCTAssertTrue(fs.file(at: bundle.gitignoreFileUrl).isExistingFile)
}
}
| 35.818182 | 74 | 0.620981 |
f490db46121b32484467e172cfab04d71fe7cc0e | 1,792 | //
// ApplicationVersionRepository.swift
// WavesWallet-iOS
//
// Created by rprokofev on 30/05/2019.
// Copyright © 2019 Waves Platform. All rights reserved.
//
import Foundation
import RxSwift
import RxSwiftExt
import Moya
import DomainLayer
private struct Constants {
static let lastVersion: String = "last_version"
static let forceUpdateVersion: String = "force_update_version"
}
final class ApplicationVersionRepository: ApplicationVersionRepositoryProtocol {
private let applicationVersionService: MoyaProvider<GitHub.Service.ApplicationVersion> = .anyMoyaProvider()
func version() -> Observable<String> {
return versionByMappingKey(key: Constants.lastVersion)
}
func forceUpdateVersion() -> Observable<String> {
return versionByMappingKey(key: Constants.forceUpdateVersion)
}
}
private extension ApplicationVersionRepository {
func versionByMappingKey(key: String) -> Observable<String> {
return applicationVersionService
.rx
.request(.get(isDebug: ApplicationDebugSettings.isEnableVersionUpdateTest, hasProxy: true))
.catchError({ [weak self] (_) -> PrimitiveSequence<SingleTrait, Response> in
guard let self = self else { return Single.never() }
return self
.applicationVersionService
.rx
.request(.get(isDebug: ApplicationDebugSettings.isEnableVersionUpdateTest, hasProxy: false))
})
.map([String: String].self)
.map { $0[key] }
.asObservable()
.flatMap({ (version) -> Observable<String> in
guard let version = version else { return Observable.error(RepositoryError.fail) }
return Observable.just(version)
})
}
}
| 32 | 111 | 0.677455 |
1ed271dabc57d651bf74ffd950cb1d2a9846460c | 598 | //
// AppStoryBoard.swift
// Rocket.Chat
//
// Created by Anil Kukadeja on 08/05/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
// swiftlint:disable <vertical_whitespace> ,<vertical_parameter_alignment>,<trailing_whitespace>,<trailing_newline>,<trailing_semicolon>]
enum AppStoryboard:String {
case Authentication
case Tabbar
case Messages
case Schedule
case CarePlan
case CareNote
case Menu
case More
var instance:UIStoryboard {
return UIStoryboard(name: self.rawValue, bundle: Bundle.main)
}
}
| 20.62069 | 137 | 0.697324 |
3a36be408a002ca79d2f1691c88351401cc5a60c | 223 | //
// HomeRouterInput.swift
// viperCleanArchi
//
// Created by Ilan Z on 17/01/2019.
// Copyright © 2019 Ilan Z. All rights reserved.
//
import Foundation
/// sourcery: AutoMockable
protocol HomeRouterInput {
}
| 14.866667 | 49 | 0.686099 |
7aad7c9a1c8be64a38bdc51fa16a8a81b9b47825 | 666 | //
// BaseViewControllerModels.swift
// {{ cookiecutter.project_name | replace(' ', '') }}
//
// Created by {{ cookiecutter.lead_dev }} on 03/06/2017.
// Copyright © 2017 {{ cookiecutter.company_name }}. All rights reserved.
//
import Foundation
import UIKit
protocol BaseViewControllerProtocol {
func showError(error: BaseError)
func showLoadingIndicator()
func hideLoadingIndicator()
func transtitionToNextViewController(fromViewController: UIViewController, destinationViewController: UIViewController?, transitionType: ViewControllerPresentationType?)
}
protocol BasePresenterProtocol {
func bindUI(viewController: UIViewController)
}
| 30.272727 | 173 | 0.768769 |
9069a8a4fe16346114bf3f85d46837392313a9f1 | 9,680 | //
// Option.swift
// Commandant
//
// Created by Justin Spahr-Summers on 2014-11-21.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import Result
/// Represents a record of options for a command, which can be parsed from
/// a list of command-line arguments.
///
/// This is most helpful when used in conjunction with the `Option` and `Switch`
/// types, and `<*>` and `<|` combinators.
///
/// Example:
///
/// struct LogOptions: OptionsProtocol {
/// let verbosity: Int
/// let outputFilename: String
/// let shouldDelete: Bool
/// let logName: String
///
/// static func create(_ verbosity: Int) -> (String) -> (Bool) -> (String) -> LogOptions {
/// return { outputFilename in { shouldDelete in { logName in LogOptions(verbosity: verbosity, outputFilename: outputFilename, shouldDelete: shouldDelete, logName: logName) } } }
/// }
///
/// static func evaluate(_ m: CommandMode) -> Result<LogOptions, CommandantError<YourErrorType>> {
/// return create
/// <*> m <| Option(key: "verbose", defaultValue: 0, usage: "the verbosity level with which to read the logs")
/// <*> m <| Option(key: "outputFilename", defaultValue: "", usage: "a file to print output to, instead of stdout")
/// <*> m <| Switch(flag: "d", key: "delete", usage: "delete the logs when finished")
/// <*> m <| Argument(usage: "the log to read")
/// }
/// }
public protocol OptionsProtocol {
associatedtype ClientError: Error
/// Evaluates this set of options in the given mode.
///
/// Returns the parsed options or a `UsageError`.
static func evaluate(_ m: CommandMode) -> Result<Self, CommandantError<ClientError>>
}
/// An `OptionsProtocol` that has no options.
public struct NoOptions<ClientError: Error>: OptionsProtocol {
public init() {}
public static func evaluate(_ m: CommandMode) -> Result<NoOptions, CommandantError<ClientError>> {
return .success(NoOptions())
}
}
/// Describes an option that can be provided on the command line.
public struct Option<T> {
/// The key that controls this option. For example, a key of `verbose` would
/// be used for a `--verbose` option.
public let key: String
/// The default value for this option. This is the value that will be used
/// if the option is never explicitly specified on the command line.
public let defaultValue: T
/// A human-readable string describing the purpose of this option. This will
/// be shown in help messages.
///
/// For boolean operations, this should describe the effect of _not_ using
/// the default value (i.e., what will happen if you disable/enable the flag
/// differently from the default).
public let usage: String
public init(key: String, defaultValue: T, usage: String) {
self.key = key
self.defaultValue = defaultValue
self.usage = usage
}
}
extension Option: CustomStringConvertible {
public var description: String {
return "--\(key)"
}
}
// MARK: - Operators
// Inspired by the Argo library:
// https://github.com/thoughtbot/Argo
/*
Copyright (c) 2014 thoughtbot, inc.
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
infix operator <*> : LogicalDisjunctionPrecedence
infix operator <| : MultiplicationPrecedence
/// Applies `f` to the value in the given result.
///
/// In the context of command-line option parsing, this is used to chain
/// together the parsing of multiple arguments. See OptionsProtocol for an example.
public func <*> <T, U, ClientError>(f: (T) -> U, value: Result<T, CommandantError<ClientError>>) -> Result<U, CommandantError<ClientError>> {
return value.map(f)
}
/// Applies the function in `f` to the value in the given result.
///
/// In the context of command-line option parsing, this is used to chain
/// together the parsing of multiple arguments. See OptionsProtocol for an example.
public func <*> <T, U, ClientError>(f: Result<((T) -> U), CommandantError<ClientError>>, value: Result<T, CommandantError<ClientError>>) -> Result<U, CommandantError<ClientError>> {
switch (f, value) {
case let (.failure(left), .failure(right)):
return .failure(combineUsageErrors(left, right))
case let (.failure(left), .success):
return .failure(left)
case let (.success, .failure(right)):
return .failure(right)
case let (.success(f), .success(value)):
let newValue = f(value)
return .success(newValue)
}
}
extension CommandMode {
/// Evaluates the given option in the given mode.
///
/// If parsing command line arguments, and no value was specified on the command
/// line, the option's `defaultValue` is used.
public static func <| <T: ArgumentProtocol, ClientError>(mode: CommandMode, option: Option<T>) -> Result<T, CommandantError<ClientError>> {
let wrapped = Option<T?>(key: option.key, defaultValue: option.defaultValue, usage: option.usage)
// Since we are passing a non-nil default value, we can safely unwrap the
// result.
return (mode <| wrapped).map { $0! }
}
/// Evaluates the given option in the given mode.
///
/// If parsing command line arguments, and no value was specified on the command
/// line, `nil` is used.
public static func <| <T: ArgumentProtocol, ClientError>(mode: CommandMode, option: Option<T?>) -> Result<T?, CommandantError<ClientError>> {
let key = option.key
switch mode {
case let .arguments(arguments):
var stringValue: String?
switch arguments.consumeValue(forKey: key) {
case let .success(value):
stringValue = value
case let .failure(error):
switch error {
case let .usageError(description):
return .failure(.usageError(description: description))
case .commandError:
fatalError("CommandError should be impossible when parameterized over NoError")
}
}
if let stringValue = stringValue {
if let value = T.from(string: stringValue) {
return .success(value)
}
let description = "Invalid value for '--\(key)': \(stringValue)"
return .failure(.usageError(description: description))
} else {
return .success(option.defaultValue)
}
case .usage:
return .failure(informativeUsageError(option))
}
}
/// Evaluates the given option in the given mode.
///
/// If parsing command line arguments, and no value was specified on the command
/// line, the option's `defaultValue` is used.
public static func <| <T: ArgumentProtocol, ClientError>(mode: CommandMode, option: Option<[T]>) -> Result<[T], CommandantError<ClientError>> {
let wrapped = Option<[T]?>(key: option.key, defaultValue: option.defaultValue, usage: option.usage)
// Since we are passing a non-nil default value, we can safely unwrap the
// result.
return (mode <| wrapped).map { $0! }
}
/// Evaluates the given option in the given mode.
///
/// If parsing command line arguments, and no value was specified on the command
/// line, `nil` is used.
public static func <| <T: ArgumentProtocol, ClientError>(mode: CommandMode, option: Option<[T]?>) -> Result<[T]?, CommandantError<ClientError>> {
let key = option.key
switch mode {
case let .arguments(arguments):
let stringValue: String?
switch arguments.consumeValue(forKey: key) {
case let .success(value):
stringValue = value
case let .failure(error):
switch error {
case let .usageError(description):
return .failure(.usageError(description: description))
case .commandError:
fatalError("CommandError should be impossible when parameterized over NoError")
}
}
guard let unwrappedStringValue = stringValue else {
return .success(option.defaultValue)
}
let components = unwrappedStringValue.split(
omittingEmptySubsequences: true,
whereSeparator: [",", " "].contains
)
var resultValues: [T] = []
for component in components {
guard let value = T.from(string: String(component)) else {
let description = "Invalid value for '--\(key)': \(unwrappedStringValue)"
return .failure(.usageError(description: description))
}
resultValues.append(value)
}
return .success(resultValues)
case .usage:
return .failure(informativeUsageError(option))
}
}
/// Evaluates the given boolean option in the given mode.
///
/// If parsing command line arguments, and no value was specified on the command
/// line, the option's `defaultValue` is used.
public static func <| <ClientError>(mode: CommandMode, option: Option<Bool>) -> Result<Bool, CommandantError<ClientError>> {
switch mode {
case let .arguments(arguments):
if let value = arguments.consumeBoolean(forKey: option.key) {
return .success(value)
} else {
return .success(option.defaultValue)
}
case .usage:
return .failure(informativeUsageError(option))
}
}
}
| 35.2 | 181 | 0.705165 |
f41edf0b589c955a96004bc849205df5ec9f90a0 | 1,192 | import Darwin
let tests: [(before: String, after: String)] = [
("", ""),
("a", "dd"),
("b", ""),
("acd", "ddcd"),
("cda", "cddd"),
("cdaef", "cdddef"),
("bcd", "cd"),
("cdb", "cd"),
("cdbef", "cdef"),
("cdabef", "cdddef"),
("cdbaef", "cdddef"),
]
for test in tests {
let beforeCharacters = [Character](test.before)
let beforeCount = beforeCharacters.count
let afterCount = test.after.count
var actualCharacters = beforeCharacters
if afterCount > beforeCount {
actualCharacters += [Character](repeating: " ", count: afterCount - beforeCount)
}
let actualCount = replaceAndRemove(characters: &actualCharacters, count: beforeCount)
let actualString = String(actualCharacters.prefix(actualCount))
guard actualCount == afterCount && actualString == test.after else {
print("For characters '\(test.before)' and count \(beforeCount), " +
"expected final characters to be '\(test.after)' " +
"and returned count to be \(afterCount), " +
"but final characters were '\(actualString)' " +
"and returned count was \(actualCount)")
exit(1)
}
}
| 30.564103 | 89 | 0.592282 |
163442ac2e29d28ed66d0d3e92590961cbf45c7b | 584 | //
// FourthTableViewCell.swift
// iLearn c++ official
//
// Created by Wirstblase on 03/05/2018.
// Copyright © 2018 Wirstblase. All rights reserved.
//
import UIKit
class FourthTableViewCell: UITableViewCell {
@IBOutlet weak var lbl4: UILabel!
@IBOutlet weak var Viewwww: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 21.62963 | 65 | 0.674658 |
87299a559cacb094905d84f1547253c2de5dcba8 | 776 | //
// BlueBorder.swift
// Hex
//
// Created by Giang Nguyenn on 2/18/21.
//
import SwiftUI
import UIKit
struct BlueBorder: View {
var cols: Int
var frameHeight: CGFloat
var frameWidth: CGFloat
var lineWidth: CGFloat = 10
var body: some View {
let backgroundBlue = Color(red: 0.2, green: 0.2549, blue: 0.584314, opacity: 1)
Rectangle()
.frame(width: frameHeight * (CGFloat(cols) - 1), height: frameHeight / 2)
.rotationEffect(Angle.degrees(60.3))
.offset(x: cols % 2 == 0 ? xOffset - frameHeight/4 : xOffset)
.foregroundColor(backgroundBlue)
}
var xOffset: CGFloat {
(CGFloat(cols / 2) * frameHeight / 2 - frameWidth/5 - CGFloat(cols / 2) * frameWidth)
}
}
| 25.032258 | 93 | 0.597938 |
75124a521b19021b6922daf3c1e264a15a3506b3 | 1,459 | //
// Created by martin on 15.09.19.
// Copyright © 2019 Martin Hartl. All rights reserved.
//
import UIKit
import AppDelegateComponent
import Client
final class NotificationComponent: AppDelegateComponent {
private let client: Client
init(client: Client = URLSession.shared) {
self.client = client
}
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
application.applicationIconBadgeNumber = 0
registerForPushNotifications(application: application)
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
let pushRegistration = PushRegistration(token: token)
client.load(resource: pushRegistration.register()) { _ in }
print("Device Token: \(token)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
}
// MARK: - Notifications
func registerForPushNotifications(application: UIApplication) {
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) { _, _ in }
application.registerForRemoteNotifications()
}
}
| 33.930233 | 120 | 0.707334 |
5d2010d8245fe1a21753dd2eef10581db1dc9a5a | 357 | // Copyright © 2017 Schibsted. All rights reserved.
public extension Layout {
/// Clear all Layout caches
static func clearAllCaches() {
Expression.clearCache()
clearParsedExpressionCache()
clearLayoutExpressionCache()
clearRuntimeTypeCache()
clearExpressionTypes()
clearLayoutLoaderCache()
}
}
| 25.5 | 52 | 0.669468 |
e050ffb4161a28b9b40d1091439b077ac695ef19 | 11,616 | //
// DiscoverMovie.swift
// TheMovieDBWrapperSwift
//
// Created by George Kye on 2016-02-05.
// Copyright © 2016 George Kye. All rights reserved.
//
import Foundation
public enum MovieGenres: String{
case Action = "28";
case Adventure = "12";
case Animation = "16";
case Comedy = "35";
case Crime = "80";
case Documentary = "99";
case Drama = "18";
case Family = "10751";
case Fantasy = "14";
case Foreign = "10769";
case History = "36";
case Horror = "27";
case Music = "10402";
case Mystery = "9648";
case Romance = "10749";
case ScienceFiction = "878";
case TvMovie = "10770";
case Thriller = "53";
case War = "10752";
case Western = "37";
}
public enum DiscoverSortByMovie: String {
//FIND WAY TO INHERIT FROM MAIN
case popularity_asc = "popularity.asc";
case popularity_desc = "popularity.desc";
case vote_average_asc = "vote_average.asc";
case vote_average_desc = "vote_average.desc";
case release_date_asc = "release_date.asc";
case release_date_desc = "release_date.desc";
case revenue_asc = "revenue.asc";
case revenue_desc = "revenue.desc";
case primary_release_date_asc = "primary_release_date.asc";
case primary_release_date_desc = "primary_release_date.desc";
case original_title_asc = "original_title.asc";
case original_title_desc = "original_title.desc";
case vote_count_asc = "vote_count.asc";
case vote_count_desc = "vote_count.desc";
}
open class DiscoverMovieMDB: DiscoverMDB{
open var title: String?
open var video: Bool?
open var release_date: String?
open var original_title: String?
open var genreIds: [Int]?
public required init(results: JSON) {
super.init(results: results)
title = results["title"].string
video = results["video"].bool
adult = results["adult"].bool
release_date = results["release_date"].string
original_title = results["original_title"].string
genreIds = results["genre_ids"].arrayObject as? [Int]
}
/// Discover movies by different types of data like average rating, number of votes, genres and certifications. You can get a valid list of certifications from the /certifications method. Please note, when using certification \ certification.lte you must also specify certification_country. These two parameters work together in order to filter the results.
open class func discoverMovies(params: [DiscoverParam], completion: @escaping (_ clientReturn: ClientReturn, _ data: [MovieMDB]?) -> ()) -> (){
Client.discover(baseURL: "movie", params: params, completion: {
apiReturn in
var data: [MovieMDB]?
if(apiReturn.error == nil){ data = MovieMDB.initialize(json: apiReturn.json!["results"]) }
completion(apiReturn, data)
})
}
/// Discover movies by different types of data like average rating, number of votes, genres and certifications. You can get a valid list of certifications from the /certifications method. Please note, when using certification \ certification.lte you must also specify certification_country. These two parameters work together in order to filter the results.
/// - parameter language: Specify a language to query translatable fields with.
/// - parameter page: Specify the page of results to query.
/// - parameter sort_by: Choose from one of the many available sort options (DiscoverSortByMovie)
/// - parameter year: <#year description#>
/// - parameter certification_country: Used in conjunction with the certification filter, use this to specify a country with a valid certification.
/// - parameter certification: Filter results with a valid certification from the 'certification_country' field.
/// - parameter certification_lte: Filter and only include movies that have a certification that is less than or equal to the specified value.
/// - parameter include_adult: A filter and include or exclude adult movies.
/// - parameter include_video: A filter to include or exclude videos.
/// - parameter timezone: <#timezone description#>
/// - parameter primary_release_year: A filter to limit the results to a specific primary release year.
/// - parameter primary_release_date_gte: Filter and only include movies that have a primary release date that is greater or equal to the specified value.
/// - parameter primary_release_date_lte: Filter and only include movies that have a primary release date that is less than or equal to the specified value.
/// - parameter release_date_gte: Filter and only include movies that have a release date (looking at all release dates) that is greater or equal to the specified value.
/// - parameter release_date_lte: Filter and only include movies that have a release date (looking at all release dates) that is less than or equal to the specified value.
/// - parameter vote_average_gte: Filter and only include movies that have a rating that is greater or equal to the specified value.
/// - parameter vote_average_lte: Filter and only include movies that have a rating that is less than or equal to the specified value.
/// - parameter vote_count_gte: Filter and only include movies that have a vote count that is greater or equal to the specified value.
/// - parameter vote_count_lte: Filter and only include movies that have a vote count that is less than or equal to the specified value.
/// - parameter with_genres: Comma separated value of genre ids that you want to include in the results.
/// - parameter with_cast: A comma separated list of person ID's. Only include movies that have one of the ID's added as an actor.
/// - parameter with_crew: A comma separated list of person ID's. Only include movies that have one of the ID's added as a crew member.
/// - parameter with_companies: A comma separated list of production company ID's. Only include movies that have one of the ID's added as a production company.
/// - parameter with_keywords: A comma separated list of keyword ID's. Only include movies that have one of the ID's added as a keyword.
/// - parameter with_people: A comma separated list of person ID's. Only include movies that have one of the ID's added as a either a actor or a crew member.
/// - parameter completion: Returns pageResults, the json and array of MovieMDB
@available(*, deprecated, message: "Will be removed next release. Please use `discover(params: [DiscoverParam])` instead")
open class func discoverMovies(language: String? = nil, page: Int, sort_by: DiscoverSortByMovie? = nil, year: Int? = nil, certification_country: String? = nil, certification: String? = nil, certification_lte: String? = nil, include_adult: Bool? = nil, include_video: Bool? = nil, timezone: String? = nil, primary_release_year: Int? = nil, primary_release_date_gte: String? = nil, primary_release_date_lte: String? = nil, release_date_gte: String? = nil, release_date_lte: String? = nil,vote_average_gte: Double? = nil, vote_average_lte: Double? = nil, vote_count_gte: Int? = nil, vote_count_lte: Int? = nil, with_genres: String? = nil, with_cast: String? = nil, with_crew: String? = nil, with_companies: String? = nil, with_keywords: String? = nil, with_people: String? = nil, completion: @escaping (_ clientReturn: ClientReturn, _ data: [MovieMDB]?) -> ()) -> (){
Client.discover(baseURL: "movie", sort_by: sort_by?.rawValue, certification_country: certification_country, certification: certification, certification_lte: certification_lte, include_adult: include_adult, include_video: include_video, primary_release_year: primary_release_year, primary_release_date_gte: primary_release_date_gte, primary_release_date_lte: primary_release_date_lte, release_date_gte: release_date_gte, release_date_lte: release_date_lte, air_date_gte: nil, air_date_lte: nil, first_air_date_gte: nil, first_air_date_lte: nil, first_air_date_year: nil, language: language, page: page, timezone: timezone, vote_average_gte: vote_average_gte, vote_average_lte: vote_average_lte, vote_count_gte: vote_count_gte, vote_count_lte: vote_count_lte, with_genres: with_genres, with_cast: with_cast, with_crew: with_crew, with_companies: with_companies, with_keywords: with_keywords, with_people: with_people, with_networks: nil, year: year, certification_gte: nil, completion: {
apiReturn in
var data: [MovieMDB]?
if(apiReturn.error == nil){ data = MovieMDB.initialize(json: apiReturn.json!["results"]) }
completion(apiReturn, data)
})
}
///all `_with` values-> comma separated indicates an 'AND' query, while a pipe (|) separated value indicates an 'OR'. ALL parameters are optional
@available(*, deprecated, message: "Will be removed next release. Please use `discover(params: [DiscoverParam])` instead")
open class func discoverMoviesWith(with_genres: String? = nil, with_cast: String? = nil, with_crew: String? = nil, with_companies: String? = nil, with_keywords: String? = nil, with_people: String? = nil, with_networks: String? = nil, year: Int? = nil, sort_by: DiscoverSortByMovie? = nil, page: Int, language: String, completion: @escaping (_ clientReturn: ClientReturn, _ data: [MovieMDB]?) -> ()) -> (){
Client.discover(baseURL:"movie", sort_by: sort_by?.rawValue, certification_country: nil, certification: nil, certification_lte: nil, include_adult: nil, include_video: nil, primary_release_year: nil, primary_release_date_gte: nil, primary_release_date_lte: nil, release_date_gte: nil, release_date_lte: nil, air_date_gte: nil, air_date_lte: nil, first_air_date_gte: nil, first_air_date_lte: nil, first_air_date_year: nil, language: language, page: page, timezone: nil, vote_average_gte: nil, vote_average_lte: nil, vote_count_gte: nil, vote_count_lte: nil, with_genres: with_genres, with_cast: with_cast, with_crew: with_crew, with_companies: with_companies , with_keywords: with_keywords, with_people: with_people, with_networks: with_networks , year: year, certification_gte: nil){
apiReturn in
var data: [MovieMDB]?
if(apiReturn.error == nil){ data = MovieMDB.initialize(json: apiReturn.json!["results"]) }
completion(apiReturn, data)
}
}
///Get the list of movies associated with a particular company.
open class func companyMovies(companyId: Int!, language: String?, page: Int?, completion: @escaping (_ clientReturn: ClientReturn, _ data: [MovieMDB]?) -> ()) -> (){
Client.Company(companyId: companyId!, language: language, page: page){
apiReturn in
var data: [MovieMDB]?
if(apiReturn.error == nil){ data = MovieMDB.initialize(json: apiReturn.json!["results"]) }
completion(apiReturn, data)
}
}
///Get the list of movies for a particular genre by id. By default, only movies with 10 or more votes are included.
open class func genreList(genreId: Int, page: Double?, include_all_movies: Bool? = nil, include_adult: Bool? = nil, movieList: Bool? = nil, completion: @escaping (_ clientReturn: ClientReturn, _ data: [MovieMDB]?) -> ()) -> (){
Client.Genres(listType: "movie", language: nil, genreId: genreId, page: page, include_all_movies: include_all_movies, include_adult: nil, movieList: true){
apiReturn in
var data: [MovieMDB]?
if(apiReturn.error == nil){ data = MovieMDB.initialize(json: apiReturn.json!["results"]) }
completion(apiReturn, data)
}
}
}
| 68.733728 | 989 | 0.72116 |
b90cbee4458b503980f83581409452296e7260f7 | 2,013 | import XCTest
import Nimble
import BowLaws
import Bow
extension MoorePartial: EquatableK {
public static func eq<A>(_ lhs: Kind<MoorePartial<E>, A>, _ rhs: Kind<MoorePartial<E>, A>) -> Bool where A : Equatable {
return Moore.fix(lhs).extract() == Moore.fix(rhs).extract()
}
}
class MooreTest: XCTestCase {
func testFunctorLaws() {
FunctorLaws<MoorePartial<Int>>.check()
}
func testComonadLaws() {
ComonadLaws<MoorePartial<Int>>.check()
}
func handleRoute(_ route : String) -> Moore<String, Id<String>> {
switch route {
case "About": return Moore(view: Id("About"), handle: handleRoute)
case "Home": return Moore(view: Id("Home"), handle: handleRoute)
default: return Moore(view: Id("???"), handle: handleRoute)
}
}
var routerMoore : Moore<String, Id<String>>!
override func setUp() {
routerMoore = Moore(view: Id("???"), handle: handleRoute)
}
func testViewAfterHandle() {
let currentRoute = routerMoore.handle("About").extract().extract()
expect(currentRoute).to(equal("About"))
}
func testViewAfterSeveralHandle() {
let currentRoute = routerMoore.handle("About").handle("Home").extract().extract()
expect(currentRoute).to(equal("Home"))
}
func testViewAfterCoflatMap() {
let currentRoute = routerMoore!.coflatMap { (view) -> Int in
switch view.extract().extract() {
case "About": return 1
case "Home": return 2
default: return 0
}
}.extract()
expect(currentRoute).to(equal(0))
}
func testViewAfterMap() {
let currentRoute = routerMoore.map { (view : Id<String>) -> Int in
switch view.extract() {
case "About": return 1
case "Home": return 2
default: return 0
}
}.extract()
expect(currentRoute).to(equal(0))
}
}
| 29.602941 | 124 | 0.577745 |
4be3813976be7c9af6baa88a39f806d6e61b9d27 | 1,533 | //
// DatabaseManager.swift
// Messenger Clone
//
// Created by Vaishant Makan on 01/09/21.
//
import Foundation
import FirebaseDatabase
//final indicates that this class cant be subclassed
final class DatabaseManager {
static let shared = DatabaseManager()
private let database = Database.database().reference()
}
//MARK: - Account Management
extension DatabaseManager {
public func userExists(with email: String,
completion: @escaping ((Bool) -> Void)) {
var safeEmail = email.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "@", with: "-")
database.child(safeEmail).observeSingleEvent(of: .value, with: { snapshot in
guard snapshot.exists() else {
completion(false)
return
}
completion(true)
})
}
/// Inserts new user to database
public func insertUser(with user: ChatAppUser) {
database.child(user.safeEmail).setValue([
"first_name": user.firstName,
"last_name": user.lastName
])
}
}
struct ChatAppUser {
let firstName: String
let lastName: String
let emailAddress: String
// let profilePictureUrl: String
var safeEmail: String {
var safeEmail = emailAddress.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "@", with: "-")
return safeEmail
}
}
| 25.983051 | 84 | 0.601435 |
fcce0ae0ff39ad8cd55ea3df80389cad7cb8f3dd | 282 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<T where T:a{class T{struct E{class A{func a{a{}}}}}}print{
| 40.285714 | 87 | 0.734043 |
4a06c6f0b3613362a4b78b30b9b7bcbfa0273df0 | 1,791 |
//
// ScrollableSelector.swift
// MovieSwift
//
// Created by Thomas Ricouard on 22/07/2019.
// Copyright © 2019 Thomas Ricouard. All rights reserved.
//
import SwiftUI
struct ScrollableSelector: View {
let items: [String]
@Binding var selection: Int
func text(for index: Int) -> some View {
Group {
if index == selection {
Text(items[index])
.foregroundColor(.white)
.font(.headline)
.fontWeight(.heavy)
.padding(4)
.background(Color.steam_gold)
.cornerRadius(8)
.onTapGesture {
self.selection = index
}
} else {
Text(items[index])
.font(.headline)
.foregroundColor(.primary)
.onTapGesture {
self.selection = index
}
}
}
}
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .center, spacing: 12) {
ForEach(0 ..< items.count) {
self.text(for: $0)
}
}
.padding([.leading, .trailing], 4)
}
.frame(height: 36)
.background(Color.steam_background)
.cornerRadius(8)
}
}
#if DEBUG
struct ScrollableSelector_Previews: PreviewProvider {
static var previews: some View {
ScrollableSelector(items: ["Menu 1", "Menu 2", "Menu 3",
"Menu 4", "Menu 5", "Menu 6",
"Menu 7", "Menu 8"],
selection: .constant(1))
}
}
#endif
| 27.553846 | 64 | 0.455053 |
14b4cc1614375b9ccbe46f2a96c8048219541af9 | 3,380 | import SwiftUI
/// Modular `Grid` style.
public struct ModularGridStyle: GridStyle {
public var columns: Tracks
public var rows: Tracks
public var axis: Axis
public var spacing: CGFloat
public var padding: EdgeInsets
public var autoWidth: Bool = true
public var autoHeight: Bool = true
public init(columns: Tracks, rows: Tracks, axis: Axis = .vertical, spacing: CGFloat = 8, padding: EdgeInsets = .init(top: 8, leading: 8, bottom: 8, trailing: 8)) {
self.columns = columns
self.rows = rows
self.axis = axis
self.spacing = spacing
self.padding = padding
}
public func transform(preferences: inout [GridItemPreferences], in size: CGSize) {
let computedTracksCount = self.axis == .vertical ?
tracksCount(
tracks: self.columns,
spacing: self.spacing,
padding: self.padding.leading + self.padding.trailing,
availableLength: size.width
) :
tracksCount(
tracks: self.rows,
spacing: self.spacing,
padding: self.padding.top + self.padding.bottom,
availableLength: size.height
)
let itemSize = CGSize(
width: itemLength(
tracks: self.columns,
spacing: self.spacing,
padding: self.padding.leading + self.padding.trailing,
availableLength: size.width
),
height: itemLength(
tracks: self.rows,
spacing: self.spacing,
padding: self.padding.top + self.padding.bottom,
availableLength: size.height
)
)
preferences = layoutPreferences(
tracks: computedTracksCount,
spacing: self.spacing,
axis: self.axis,
itemSize: itemSize,
preferences: preferences
)
}
private func layoutPreferences(tracks: Int, spacing: CGFloat, axis: Axis, itemSize: CGSize, preferences: [GridItemPreferences]) -> [GridItemPreferences] {
var tracksLengths = Array(repeating: CGFloat(0.0), count: tracks)
var newPreferences: [GridItemPreferences] = []
preferences.forEach { preference in
if let minValue = tracksLengths.min(), let indexMin = tracksLengths.firstIndex(of: minValue) {
let itemSizeWidth = itemSize.width
let itemSizeHeight = itemSize.height
let width = axis == .vertical ? itemSizeWidth * CGFloat(indexMin) + CGFloat(indexMin) * spacing : tracksLengths[indexMin]
let height = axis == .vertical ? tracksLengths[indexMin] : itemSizeHeight * CGFloat(indexMin) + CGFloat(indexMin) * spacing
let origin = CGPoint(x: 0 - width, y: 0 - height)
tracksLengths[indexMin] += (axis == .vertical ? itemSizeHeight : itemSizeWidth) + spacing
newPreferences.append(
GridItemPreferences(
id: preference.id,
bounds: CGRect(origin: origin, size: CGSize(width: itemSizeWidth, height: itemSizeHeight))
)
)
}
}
return newPreferences
}
}
| 39.302326 | 167 | 0.563905 |
91da8187069918d8440b5874fe9408e3c3852125 | 886 | //
// BravoTests.swift
// BravoTests
//
// Created by DawAyush on 9/4/19.
// Copyright © 2019 DawAyush. All rights reserved.
//
import XCTest
@testable import Bravo
class BravoTests: 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.
}
}
}
| 25.314286 | 111 | 0.648984 |
4abab2e33cdfb6fd970a5dd0f89e33d402bd08fe | 1,277 | /**
* @name MaximumLogLevelFilter.swift
* @partof zucred AG
* @description
* @author Vasco Mouta
* @created 21/11/15
*
* Copyright (c) 2015 zucred AG All rights reserved.
* This material, including documentation and any related
* computer programs, is protected by copyright controlled by
* zucred AG. All rights are reserved. Copying,
* including reproducing, storing, adapting or translating, any
* or all of this material requires the prior written consent of
* zucred AG. This material also contains confidential
* information which may not be disclosed to others without the
* prior written consent of zucred AG.
*/
import Foundation
/**
A `LogFilter` implementation that filters out any `LogEntry` with a
`LogSeverity` less than a specified value.
*/
open class MaximumLogLevelFilter: LogLevelFilter
{
/**
Called to determine whether the given `LogEntry` should be recorded.
:param: entry The `LogEntry` to be evaluated by the filter.
:returns: `true` if `entry.severity` is as or more severe than the
receiver's `severity` property; `false` otherwise.
*/
open override func shouldRecordLogEntry(_ entry: LogEntry) -> Bool
{
return entry.logLevel <= severity
}
}
| 31.925 | 72 | 0.703994 |
916e4c4c8c48e3986ba09875a7e805aa2563b1d2 | 4,621 | // Copyright 2020 Tokamak contributors
//
// 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.
//
// Created by Max Desiatov on 11/04/2020.
//
import TokamakCore
/** Represents an attribute of an HTML tag. To consume updates from updated attributes, the DOM
renderer needs to know whether the attribute should be assigned via a DOM element property or the
[`setAttribute`](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute) function.
The `isUpdatedAsProperty` flag is used to disambiguate between these two cases.
*/
public struct HTMLAttribute: Hashable {
public let value: String
public let isUpdatedAsProperty: Bool
public init(_ value: String, isUpdatedAsProperty: Bool) {
self.value = value
self.isUpdatedAsProperty = isUpdatedAsProperty
}
public static let value = HTMLAttribute("value", isUpdatedAsProperty: true)
public static let checked = HTMLAttribute("checked", isUpdatedAsProperty: true)
}
extension HTMLAttribute: CustomStringConvertible {
public var description: String { value }
}
extension HTMLAttribute: ExpressibleByStringLiteral {
public init(stringLiteral: String) {
self.init(stringLiteral, isUpdatedAsProperty: false)
}
}
public protocol AnyHTML {
func innerHTML(shouldSortAttributes: Bool) -> String?
var tag: String { get }
var attributes: [HTMLAttribute: String] { get }
}
public extension AnyHTML {
func outerHTML(
shouldSortAttributes: Bool,
additonalAttributes: [HTMLAttribute: String] = [:],
children: [HTMLTarget]
) -> String {
let attributes = attributes.merging(additonalAttributes, uniquingKeysWith: +)
let renderedAttributes: String
if attributes.isEmpty {
renderedAttributes = ""
} else {
let mappedAttributes = attributes
// Exclude empty values to avoid waste of space with `class=""`
.filter { !$1.isEmpty }
.map { #"\#($0)="\#($1)""# }
if shouldSortAttributes {
renderedAttributes = mappedAttributes.sorted().joined(separator: " ")
} else {
renderedAttributes = mappedAttributes.joined(separator: " ")
}
}
return """
<\(tag)\(attributes.isEmpty ? "" : " ")\
\(renderedAttributes)>\
\(innerHTML(shouldSortAttributes: shouldSortAttributes) ?? "")\
\(children.map { $0.outerHTML(shouldSortAttributes: shouldSortAttributes) }
.joined(separator: "\n"))\
</\(tag)>
"""
}
}
public struct HTML<Content>: View, AnyHTML {
public let tag: String
public let attributes: [HTMLAttribute: String]
let content: Content
fileprivate let cachedInnerHTML: String?
public func innerHTML(shouldSortAttributes: Bool) -> String? {
cachedInnerHTML
}
@_spi(TokamakCore)
public var body: Never {
neverBody("HTML")
}
}
public extension HTML where Content: StringProtocol {
init(
_ tag: String,
_ attributes: [HTMLAttribute: String] = [:],
content: Content
) {
self.tag = tag
self.attributes = attributes
self.content = content
cachedInnerHTML = String(content)
}
}
extension HTML: ParentView where Content: View {
public init(
_ tag: String,
_ attributes: [HTMLAttribute: String] = [:],
@ViewBuilder content: () -> Content
) {
self.tag = tag
self.attributes = attributes
self.content = content()
cachedInnerHTML = nil
}
@_spi(TokamakCore)
public var children: [AnyView] {
[AnyView(content)]
}
}
public extension HTML where Content == EmptyView {
init(
_ tag: String,
_ attributes: [HTMLAttribute: String] = [:]
) {
self = HTML(tag, attributes) { EmptyView() }
}
}
public protocol StylesConvertible {
var styles: [String: String] { get }
}
public extension Dictionary
where Key: Comparable & CustomStringConvertible, Value: CustomStringConvertible
{
func inlineStyles(shouldSortDeclarations: Bool = false) -> String {
let declarations = map { "\($0.key): \($0.value);" }
if shouldSortDeclarations {
return declarations
.sorted()
.joined(separator: " ")
} else {
return declarations.joined(separator: " ")
}
}
}
| 28.349693 | 98 | 0.689245 |
8a6f7cb693ba1653625c9795bd8a88ca8034ab05 | 2,185 | /*
* Copyright (c) 2020 Elastos Foundation
*
* 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
extension HiveAPi {
func getPackageInfo() -> String {
return self.baseURL + self.apiPath + "/payment/vault_package_info"
}
func getPricingPlan(_ name: String) -> String {
return self.baseURL + self.apiPath + "/payment/vault_pricing_plan?name=\(name)"
}
func createOrder() -> String {
return self.baseURL + self.apiPath + "/payment/create_vault_package_order"
}
public var payOrder: String {
return self.baseURL + self.apiPath + "/payment/pay_vault_package_order"
}
func orderInfo(_ orderId: String) -> String {
return self.baseURL + self.apiPath + "/payment/vault_package_order?order_id=\(orderId)"
}
func getOrderList() -> String {
return self.baseURL + self.apiPath + "/payment/vault_package_order_list"
}
func getServiceInfo() -> String {
return self.baseURL + self.apiPath + "/service/vault"
}
func getPaymentVersion() -> String {
return self.baseURL + self.apiPath + "/payment/version"
}
}
| 37.672414 | 95 | 0.705263 |
cc64b6362b678e95b940fd386820a75c5ab12876 | 4,809 | //
// HTMLTreeBuilder.swift
// HTNSwift
//
// Created by DaiMing on 2017/10/11.
// Copyright © 2017年 Starming. All rights reserved.
//
import Foundation
public class HTMLTreeBuilder {
var tokenizer: HTMLTokenizer
public var doc: Document
public var currentToken: HTMLToken?
private var _lastElement: Element //TODO: 上一个元素,暂时无用
private var _currentElement: Element //当前元素
private var _currentParent: Element? //当前元素父元素
public init(_ input: String) {
doc = Document()
tokenizer = HTMLTokenizer(input)
_lastElement = Element()
_currentElement = Element()
}
public func parse() -> [HTMLToken] {
let tks = tokenizer.parse() //词法分析
var stackElement = [Element]() //为了父子级别而记录深度的堆栈
let stateMachine = HTNStateMachine<S,E>(S.BeforeHTMLState)
stateMachine.listen(E.StartTagEvent, transit: S.InitialModeState, to: S.BeforeHTMLState) { (t) in
//TODO:暂时只支持 html 标签内,所以外部的定义先不处理
}
stateMachine.listen(E.StartTagEvent, transit: S.BeforeHTMLState, to: S.BeforeHeadState) { (t) in
//TODO:根 Node Document
}
stateMachine.listen(E.StartTagEvent, transit: S.BeforeHeadState, to: S.InHeadState) { (t) in
//
}
stateMachine.listen(E.CharEvent, transit: S.InHeadState, to: S.InHeadState) { (t) in
//在 head 里
if self._currentParent?.startTagToken?.data == "style" {
self.doc.styleList.append(self._currentElement)
}
if self._currentParent?.startTagToken?.data == "script" {
self.doc.scriptList.append(self._currentElement)
}
}
//InHeadState
stateMachine.listen(E.EndHeadTagEvent, transit: S.InHeadState, to: S.AfterHeadState) { (t) in
//
}
//AfterHeadState
stateMachine.listen(E.StartTagEvent, transit: S.AfterHeadState, to: S.InBodyState) { (t) in
//
}
stateMachine.listen(E.StartTagEvent, transit: S.InBodyState, to: S.InBodyState) { (t) in
//TODO: 处理 inline style
}
//TODO: AfterBodyState 和 AfterAfterBodyState 的情况
for tk in tks {
var hasTrigger = false
//TODO:现将无关的过滤之,以后再做处理
if tk.type == .StartTag || tk.type == .Char || tk.type == .EndTag {
} else {
continue
}
_currentElement = Element(token: tk)
//根元素的处理
if tk.data == "html" && tk.type == .StartTag {
_currentElement = Document(token: tk)
doc = _currentElement as! Document
}
//StartTag
if tk.type == .StartTag {
stackElement.append(_currentElement) //堆栈添加
//子关闭标签的情况
if tk.selfClosing {
_ = stackElement.popLast()
_currentParent = stackElement.last
self.parentAppendChild()
} else {
self.parentAppendChild()
_currentParent = _currentElement
}
hasTrigger = stateMachine.trigger(E.StartTagEvent)
}
//Char
if tk.type == .Char {
//添加子结点
self.parentAppendChild()
hasTrigger = stateMachine.trigger(E.CharEvent)
}
//EndTag
if tk.type == .EndTag {
//pop 出堆栈
_ = stackElement.popLast()
_currentParent = stackElement.last
if tk.data == "head" {
hasTrigger = stateMachine.trigger(E.EndHeadTagEvent)
} else {
hasTrigger = stateMachine.trigger(E.EndTagEvent)
}
}
if hasTrigger {
}
}
return tks
}
func parentAppendChild() {
_currentElement.parent = _currentParent
_currentParent?.children.append(_currentElement)
}
//TODO: 按照 w3c 的状态来。
//w3c 的定义:https://www.w3.org/TR/html5/syntax.html#html-parser
enum S: HTNStateType {
case InitialModeState
case BeforeHTMLState
case BeforeHeadState
case InHeadState
case AfterHeadState
case InBodyState
case AfterBodyState
case AfterAfterBodyState
}
enum E: HTNEventType {
case StartTagEvent
case CharEvent
case EndTagEvent
case EndHeadTagEvent // </head>
case EndBodyTagEvent //TODO: 先不处理 </body> 标签后的情况
}
}
| 31.638158 | 105 | 0.530672 |
755addfd3a3891303f06399156e6114873aeb41b | 5,489 | //
// HardwareFormatter.swift
// Trace
//
// Created by Shams Ahmed on 11/06/2019.
// Copyright © 2020 Bitrise. All rights reserved.
//
import Foundation
/// Formatter to get hold of all hardware metrics
internal struct HardwareFormatter: JSONEncodable {
// MARK: - Property
private let cpu: CPU
private let memory: Memory
private let connectivity: Connectivity
private let timestamp = Time.timestamp
// MARK: - Init
internal init(cpu: CPU, memory: Memory, connectivity: Connectivity) {
self.cpu = cpu
self.memory = memory
self.connectivity = connectivity
setup()
}
// MARK: - Setup
private func setup() {
}
// MARK: - Details
internal var details: OrderedDictionary<String, String> {
var details = detailsForSystemCPU
details.merge(detailsForApplicationCPU)
details.merge(detailsForApplicationMemory)
return OrderedDictionary<String, String>(uniqueKeysWithValues: details)
}
private var detailsForSystemCPU: OrderedDictionary<String, String> {
var timestamp = ""
if let usage = cpu.systemUsage.timestamp.jsonString() {
timestamp = usage
}
return [
"system": String(cpu.systemUsage.system),
"user": String(cpu.systemUsage.user),
"idle": String(cpu.systemUsage.idle),
"nice": String(cpu.systemUsage.nice),
"timestamp": timestamp
]
}
private var detailsForApplicationCPU: OrderedDictionary<String, String> {
var timestamp = ""
if let usage = cpu.applicationUsage.timestamp.jsonString() {
timestamp = usage
}
var model = OrderedDictionary<String, String>()
model["overall"] = String(cpu.applicationUsage.overall)
model["timestamp"] = timestamp
cpu.perThreadUsage.forEach { model[$0.name] = String($0.usage) }
return model
}
private var detailsForApplicationMemory: OrderedDictionary<String, String> {
var timestamp = ""
if let usage = memory.applicationUsage.timestamp.jsonString() {
timestamp = usage
}
return [
"res": String(memory.applicationUsage.used),
"timestamp": timestamp
]
}
}
extension HardwareFormatter: Metricable {
// MARK: - Metric
internal var metrics: Metrics {
return Metrics([systemMetric, applicationMetric, applicationMemoryUsage])
}
private var applicationMemoryUsage: Metric {
var keys = [Metric.Descriptor.Key]()
var timeseries = [Metric.Timeseries]()
let value = memory.applicationUsage
keys.append(.init("memory.state"))
timeseries.append(Metric.Timeseries(
.value("res"),
points: [.point(seconds: value.timestamp.seconds, nanos: value.timestamp.nanos, value: value.used.rounded(to: 1))])
)
let descriptor = Metric.Descriptor(
name: .appMemoryBytes,
description: "App Memory Usage",
unit: .bytes,
type: .int64,
keys: keys
)
let metric = Metric(descriptor: descriptor, timeseries: timeseries)
return metric
}
private var applicationMetric: Metric {
let value = cpu.applicationUsage
let timeseries = Metric.Timeseries(
[],
points: [.point(seconds: value.timestamp.seconds, nanos: value.timestamp.nanos, value: value.overall.rounded(to: 2))]
)
let descriptor = Metric.Descriptor(
name: .processCpuPct,
description: "Application CPU Usage",
unit: .percent,
type: .double,
keys: []
)
let metric = Metric(descriptor: descriptor, timeseries: timeseries)
return metric
}
private var systemMetric: Metric {
var keys = [Metric.Descriptor.Key]()
var timeseries = [Metric.Timeseries]()
let value = cpu.systemUsage
keys.append(.init("cpu.state"))
timeseries.append(Metric.Timeseries(
.value("system"),
points: [.point(seconds: value.timestamp.seconds, nanos: value.timestamp.nanos, value: value.system.rounded(to: 1))])
)
timeseries.append(Metric.Timeseries(
.value("user"),
points: [.point(seconds: value.timestamp.seconds, nanos: value.timestamp.nanos, value: value.user.rounded(to: 1))])
)
timeseries.append(Metric.Timeseries(
.value("idle"),
points: [.point(seconds: value.timestamp.seconds, nanos: value.timestamp.nanos, value: value.idle.rounded(to: 1))])
)
timeseries.append(Metric.Timeseries(
.value("nice"),
points: [.point(seconds: value.timestamp.seconds, nanos: value.timestamp.nanos, value: value.nice.rounded(to: 1))])
)
let descriptor = Metric.Descriptor(
name: .systemCpuPct,
description: "System CPU Usage",
unit: .percent,
type: .double,
keys: keys
)
let metric = Metric(descriptor: descriptor, timeseries: timeseries)
return metric
}
}
| 30.494444 | 129 | 0.57843 |
0e1c88101f41336cf24ada31bcceef87f8629f99 | 2,176 | /*
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
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 OWNER 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.
*/
#if !os(watchOS)
import OTFCareKitStore
import OTFCareKitUI
import Foundation
/// A synchronizer that creates and updates an `OCKButtonLogTaskView`.
open class OCKButtonLogTaskViewSynchronizer: OCKTaskViewSynchronizerProtocol {
public init() {}
open func updateView(_ view: OCKButtonLogTaskView, context: OCKSynchronizationContext<OCKTaskEvents>) {
view.updateWith(event: context.viewModel.first?.first, animated: context.animated)
}
open func makeView() -> OCKButtonLogTaskView {
return .init()
}
}
#endif
| 44.408163 | 107 | 0.787684 |
283eb948cbcc140db83a4146b61a239ec790b982 | 7,981 | //
// NetworkReachabilityManager.swift
// ElastosCarrierDemo
//
// Created by user150313 on 2/23/19.
// Copyright © 2019 Elastos. All rights reserved.
//
#if !os(watchOS)
import Foundation
import SystemConfiguration
import ElastosCarrierSDK
/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
/// WiFi network interfaces.
///
/// Reachability can be used to determine background information about why a network operation failed, or to retry
/// network requests when a connection is established. It should not be used to prevent a user from initiating a network
/// request, as it's possible that an initial request may be required to establish reachability.
public class NetworkReachabilityManager {
/// Defines the various states of network reachability.
///
/// - unknown: It is unknown whether the network is reachable.
/// - notReachable: The network is not reachable.
/// - reachable: The network is reachable.
public enum NetworkReachabilityStatus {
case unknown
case notReachable
case reachable(ConnectionType)
}
/// Defines the various connection types detected by reachability flags.
///
/// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi.
/// - wwan: The connection type is a WWAN connection.
public enum ConnectionType {
case ethernetOrWiFi
case wwan
}
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
/// network reachability status.
public typealias Listener = (NetworkReachabilityStatus) -> Void
// MARK: - Properties
/// Whether the network is currently reachable.
public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
/// Whether the network is currently reachable over the WWAN interface.
public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) }
/// Whether the network is currently reachable over Ethernet or WiFi interface.
public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) }
/// The current network reachability status.
public var networkReachabilityStatus: NetworkReachabilityStatus {
guard let flags = self.flags else { return .unknown }
return networkReachabilityStatusForFlags(flags)
}
/// The dispatch queue to execute the `listener` closure on.
public var listenerQueue: DispatchQueue = DispatchQueue.main
/// A closure executed when the network reachability status changes.
public var listener: Listener?
private var flags: SCNetworkReachabilityFlags? {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(reachability, &flags) {
return flags
}
return nil
}
private let reachability: SCNetworkReachability
private var previousFlags: SCNetworkReachabilityFlags
// MARK: - Initialization
/// Creates a `NetworkReachabilityManager` instance with the specified host.
///
/// - parameter host: The host used to evaluate network reachability.
///
/// - returns: The new `NetworkReachabilityManager` instance.
public convenience init?(host: String) {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
self.init(reachability: reachability)
}
/// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
///
/// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
/// status of the device, both IPv4 and IPv6.
///
/// - returns: The new `NetworkReachabilityManager` instance.
public convenience init?() {
var address = sockaddr_in()
address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
address.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(to: &address, { pointer in
return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) {
return SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else { return nil }
self.init(reachability: reachability)
}
private init(reachability: SCNetworkReachability) {
self.reachability = reachability
self.previousFlags = SCNetworkReachabilityFlags()
}
deinit {
stopListening()
}
// MARK: - Listening
/// Starts listening for changes in network reachability status.
///
/// - returns: `true` if listening was started successfully, `false` otherwise.
@discardableResult
public func startListening() -> Bool {
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = Unmanaged.passUnretained(self).toOpaque()
let callbackEnabled = SCNetworkReachabilitySetCallback(
reachability,
{ (_, flags, info) in
let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info!).takeUnretainedValue()
reachability.notifyListener(flags)
},
&context
)
let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
listenerQueue.async {
self.previousFlags = SCNetworkReachabilityFlags()
self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
}
return callbackEnabled && queueEnabled
}
/// Stops listening for changes in network reachability status.
public func stopListening() {
SCNetworkReachabilitySetCallback(reachability, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
}
// MARK: - Internal - Listener Notification
func notifyListener(_ flags: SCNetworkReachabilityFlags) {
guard previousFlags != flags else { return }
previousFlags = flags
listener?(networkReachabilityStatusForFlags(flags))
}
// MARK: - Internal - Network Reachability Status
func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
guard flags.contains(.reachable) else { return .notReachable }
var networkStatus: NetworkReachabilityStatus = .notReachable
if !flags.contains(.connectionRequired) { networkStatus = .reachable(.ethernetOrWiFi) }
if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) {
if !flags.contains(.interventionRequired) { networkStatus = .reachable(.ethernetOrWiFi) }
}
#if os(iOS)
if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) }
#endif
return networkStatus
}
}
// MARK: -
extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
/// Returns whether the two network reachability status values are equal.
///
/// - parameter lhs: The left-hand side value to compare.
/// - parameter rhs: The right-hand side value to compare.
///
/// - returns: `true` if the two values are equal, `false` otherwise.
public func ==(
lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
-> Bool
{
switch (lhs, rhs) {
case (.unknown, .unknown):
return true
case (.notReachable, .notReachable):
return true
case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)):
return lhsConnectionType == rhsConnectionType
default:
return false
}
}
#endif
| 37.469484 | 122 | 0.680616 |
4a51a5caba597d99c86930414906ca231d8fc549 | 33,722 | //
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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
/// MXSpaceService error
public enum MXSpaceServiceError: Int, Error {
case spaceNotFound
case unknown
}
// MARK: - MXSpaceService errors
extension MXSpaceServiceError: CustomNSError {
public static let errorDomain = "org.matrix.sdk.spaceService"
public var errorCode: Int {
return Int(rawValue)
}
public var errorUserInfo: [String: Any] {
return [:]
}
}
// MARK: - MXSpaceService notification constants
extension MXSpaceService {
/// Posted once the first graph as been built or loaded
public static let didInitialise = Notification.Name("MXSpaceServiceDidInitialise")
/// Posted once the graph of rooms is up and running
public static let didBuildSpaceGraph = Notification.Name("MXSpaceServiceDidBuildSpaceGraph")
}
/// MXSpaceService enables to handle spaces.
@objcMembers
public class MXSpaceService: NSObject {
// MARK: - Properties
private unowned let session: MXSession
private lazy var stateEventBuilder: MXRoomInitialStateEventBuilder = {
return MXRoomInitialStateEventBuilder()
}()
private let roomTypeMapper: MXRoomTypeMapper
private let processingQueue: DispatchQueue
private let sdkProcessingQueue: DispatchQueue
private let completionQueue: DispatchQueue
private var graph: MXSpaceGraphData = MXSpaceGraphData() {
didSet {
var spacesPerId: [String:MXSpace] = [:]
self.graph.spaceRoomIds.forEach { spaceId in
if let space = self.getSpace(withId: spaceId) {
spacesPerId[spaceId] = space
}
}
self.spacesPerId = spacesPerId
}
}
private var spacesPerId: [String:MXSpace] = [:]
private var isGraphBuilding = false;
public let notificationCounter: MXSpaceNotificationCounter
public var rootSpaceSummaries: [MXRoomSummary] {
return self.graph.rootSpaceIds.compactMap { spaceId in
self.session.roomSummary(withRoomId: spaceId)
}
}
public private(set) var needsUpdate: Bool = true
public var graphUpdateEnabled = true
private var sessionStateDidChangeObserver: Any?
public var ancestorsPerRoomId: [String:Set<String>] {
return graph.ancestorsPerRoomId
}
public private(set) var isInitialised = false {
didSet {
if !oldValue && isInitialised {
self.completionQueue.async {
NotificationCenter.default.post(name: MXSpaceService.didInitialise, object: self)
}
}
}
}
// MARK: - Setup
public init(session: MXSession) {
self.session = session
self.notificationCounter = MXSpaceNotificationCounter(session: session)
self.roomTypeMapper = MXRoomTypeMapper(defaultRoomType: .room)
self.processingQueue = DispatchQueue(label: "org.matrix.sdk.MXSpaceService.processingQueue", attributes: .concurrent)
self.completionQueue = DispatchQueue.main
self.sdkProcessingQueue = DispatchQueue.main
super.init()
self.registerNotificationObservers()
}
deinit {
unregisterNotificationObservers()
}
// MARK: - Public
/// close the service and free all data
public func close() {
self.isGraphBuilding = true
self.graph = MXSpaceGraphData()
self.notificationCounter.close()
self.isGraphBuilding = false
self.isInitialised = false
self.completionQueue.async {
NotificationCenter.default.post(name: MXSpaceService.didBuildSpaceGraph, object: self)
}
}
/// Loads graph from the given store
public func loadData() {
self.processingQueue.async {
let store = MXSpaceFileStore(userId: self.session.myUserId, deviceId: self.session.myDeviceId)
if let loadedGraph = store.loadSpaceGraphData() {
self.graph = loadedGraph
self.completionQueue.async {
self.isInitialised = true
self.notificationCounter.computeNotificationCount()
NotificationCenter.default.post(name: MXSpaceService.didBuildSpaceGraph, object: self)
}
}
}
}
/// Allows to know if a given room is a descendant of a given space
/// - Parameters:
/// - roomId: ID of the room
/// - spaceId: ID of the space
/// - Returns: `true` if the room with the given ID is an ancestor of the space with the given ID .`false` otherwise
public func isRoom(withId roomId: String, descendantOf spaceId: String) -> Bool {
return self.graph.descendantsPerRoomId[spaceId]?.contains(roomId) ?? false
}
/// Allows to know if the room is oprhnaed (e.g. has no ancestor)
/// - Parameters:
/// - roomId: ID of the room
/// - Returns: `true` if the room with the given ID is orphaned .`false` otherwise
public func isOrphanedRoom(withId roomId: String) -> Bool {
return self.graph.orphanedRoomIds.contains(roomId) || self.graph.orphanedDirectRoomIds.contains(roomId)
}
/// Handle a sync response
/// - Parameters:
/// - syncResponse: The sync response object
public func handleSyncResponse(_ syncResponse: MXSyncResponse) {
guard self.needsUpdate || !(syncResponse.rooms?.join?.isEmpty ?? true) || !(syncResponse.rooms?.invite?.isEmpty ?? true) || !(syncResponse.rooms?.leave?.isEmpty ?? true) || !(syncResponse.toDevice?.events.isEmpty ?? true) else
{
return
}
self.buildGraph()
}
/// Create a space.
/// - Parameters:
/// - parameters: The parameters for space creation.
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
public func createSpace(with parameters: MXSpaceCreationParameters, completion: @escaping (MXResponse<MXSpace>) -> Void) -> MXHTTPOperation {
return self.session.createRoom(parameters: parameters) { (response) in
switch response {
case .success(let room):
let space: MXSpace = MXSpace(roomId: room.roomId, session:self.session)
self.completionQueue.async {
completion(.success(space))
}
case .failure(let error):
self.completionQueue.async {
completion(.failure(error))
}
}
}
}
/// Create a space shortcut.
/// - Parameters:
/// - name: The space name.
/// - topic: The space topic.
/// - isPublic: true to indicate to use public chat presets and join the space without invite or false to use private chat presets and join the space on invite.
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
public func createSpace(withName name: String, topic: String?, isPublic: Bool, completion: @escaping (MXResponse<MXSpace>) -> Void) -> MXHTTPOperation {
let parameters = MXSpaceCreationParameters()
parameters.name = name
parameters.topic = topic
parameters.preset = isPublic ? kMXRoomPresetPublicChat : kMXRoomPresetPrivateChat
if isPublic {
let guestAccessStateEvent = self.stateEventBuilder.buildGuestAccessEvent(withAccess: .canJoin)
let historyVisibilityStateEvent = self.stateEventBuilder.buildHistoryVisibilityEvent(withVisibility: .worldReadable)
parameters.addOrUpdateInitialStateEvent(guestAccessStateEvent)
parameters.addOrUpdateInitialStateEvent(historyVisibilityStateEvent)
}
return self.createSpace(with: parameters, completion: completion)
}
/// Get a space from a roomId.
/// - Parameter spaceId: The id of the space.
/// - Returns: A MXSpace with the associated roomId or null if room doesn't exists or the room type is not space.
public func getSpace(withId spaceId: String) -> MXSpace? {
var space = self.spacesPerId[spaceId]
if space == nil, let newSpace = self.session.room(withRoomId: spaceId)?.toSpace() {
space = newSpace
self.spacesPerId[spaceId] = newSpace
}
return space
}
/// Get the space children informations of a given space from the server.
/// - Parameters:
/// - spaceId: The room id of the queried space.
/// - suggestedOnly: If `true`, return only child events and rooms where the `m.space.child` event has `suggested: true`.
/// - limit: Optional. A limit to the maximum number of children to return per space. `-1` for no limit
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
public func getSpaceChildrenForSpace(withId spaceId: String,
suggestedOnly: Bool,
limit: Int?,
completion: @escaping (MXResponse<MXSpaceChildrenSummary>) -> Void) -> MXHTTPOperation {
return self.session.matrixRestClient.getSpaceChildrenForSpace(withId: spaceId, suggestedOnly: suggestedOnly, limit: limit) { (response) in
switch response {
case .success(let spaceChildrenResponse):
self.processingQueue.async { [weak self] in
guard let self = self else {
return
}
guard let rooms = spaceChildrenResponse.rooms else {
// We should have at least one room for the requested space
self.completionQueue.async {
completion(.failure(MXSpaceServiceError.spaceNotFound))
}
return
}
guard let rootSpaceChildSummaryResponse = rooms.first(where: { spaceResponse -> Bool in
return spaceResponse.roomId == spaceId
}) else {
// Fail to find root child. We should have at least one room for the requested space
self.completionQueue.async {
completion(.failure(MXSpaceServiceError.spaceNotFound))
}
return
}
// Build the queried space summary
let spaceSummary = self.createRoomSummary(with: rootSpaceChildSummaryResponse)
// Build room hierarchy and events
var childrenIdsPerChildRoomId: [String: [String]] = [:]
var parentIdsPerChildRoomId: [String:Set<String>] = [:]
var spaceChildEventsPerChildRoomId: [String:[String:Any]] = [:]
for event in spaceChildrenResponse.events ?? [] where event.type == kMXEventTypeStringSpaceChild && event.wireContent.count > 0 {
spaceChildEventsPerChildRoomId[event.stateKey] = event.wireContent
var parentIds = parentIdsPerChildRoomId[event.stateKey] ?? Set()
parentIds.insert(event.roomId)
parentIdsPerChildRoomId[event.stateKey] = parentIds
var childrenIds = childrenIdsPerChildRoomId[event.roomId] ?? []
childrenIds.append(event.stateKey)
childrenIdsPerChildRoomId[event.roomId] = childrenIds
}
// Build the child summaries of the queried space
let childInfos = self.spaceChildInfos(from: spaceChildrenResponse, excludedSpaceId: spaceId, childrenIdsPerChildRoomId: childrenIdsPerChildRoomId, parentIdsPerChildRoomId: parentIdsPerChildRoomId, spaceChildEventsPerChildRoomId: spaceChildEventsPerChildRoomId)
let spaceChildrenSummary = MXSpaceChildrenSummary(spaceSummary: spaceSummary, childInfos: childInfos)
self.completionQueue.async {
completion(.success(spaceChildrenSummary))
}
}
case .failure(let error):
self.completionQueue.async {
completion(.failure(error))
}
}
}
}
// MARK: - Space graph computation
private class PrepareDataResult {
private var _spaces: [MXSpace] = []
private var _spacesPerId: [String : MXSpace] = [:]
private var _directRoomIdsPerMemberId: [String: [String]] = [:]
private var computingSpaces: Set<String> = Set()
private var computingDirectRooms: Set<String> = Set()
var spaces: [MXSpace] {
var result: [MXSpace] = []
self.serialQueue.sync {
result = self._spaces
}
return result
}
var spacesPerId: [String : MXSpace] {
var result: [String : MXSpace] = [:]
self.serialQueue.sync {
result = self._spacesPerId
}
return result
}
var directRoomIdsPerMemberId: [String: [String]] {
var result: [String: [String]] = [:]
self.serialQueue.sync {
result = self._directRoomIdsPerMemberId
}
return result
}
var isPreparingData = true
var isComputing: Bool {
var isComputing = false
self.serialQueue.sync {
isComputing = !self.computingSpaces.isEmpty || !self.computingDirectRooms.isEmpty
}
return isComputing
}
private let serialQueue = DispatchQueue(label: "org.matrix.sdk.MXSpaceService.PrepareDataResult.serialQueue")
func add(space: MXSpace) {
self.serialQueue.sync {
self._spaces.append(space)
self._spacesPerId[space.spaceId] = space
}
}
func add(directRoom: MXRoom, toUserWithId userId: String) {
self.serialQueue.sync {
var rooms = self._directRoomIdsPerMemberId[userId] ?? []
rooms.append(directRoom.roomId)
self._directRoomIdsPerMemberId[userId] = rooms
}
}
func setComputing(_ isComputing: Bool, forSpace space: MXSpace) {
self.serialQueue.sync {
if isComputing {
computingSpaces.insert(space.spaceId)
} else {
computingSpaces.remove(space.spaceId)
}
}
}
func setComputing(_ isComputing: Bool, forDirectRoom room: MXRoom) {
self.serialQueue.sync {
if isComputing {
computingDirectRooms.insert(room.roomId)
} else {
computingDirectRooms.remove(room.roomId)
}
}
}
}
/// Build the graph of rooms
private func buildGraph() {
guard !self.isGraphBuilding && self.graphUpdateEnabled else {
MXLog.debug("[MXSpaceService] buildGraph: aborted: graph is building or disabled")
self.needsUpdate = true
return
}
self.isGraphBuilding = true
self.needsUpdate = false
let startDate = Date()
MXLog.debug("[MXSpaceService] buildGraph: started")
var directRoomIds = Set<String>()
let roomIds: [String] = self.session.rooms.compactMap { room in
if room.isDirect {
directRoomIds.insert(room.roomId)
}
return room.roomId
}
let output = PrepareDataResult()
MXLog.debug("[MXSpaceService] buildGraph: preparing data for \(roomIds.count) rooms")
self.prepareData(with: roomIds, index: 0, output: output) { result in
MXLog.debug("[MXSpaceService] buildGraph: data prepared in \(Date().timeIntervalSince(startDate))")
self.computSpaceGraph(with: result, roomIds: roomIds, directRoomIds: directRoomIds) { graph in
self.graph = graph
MXLog.debug("[MXSpaceService] buildGraph: ended after \(Date().timeIntervalSince(startDate))s")
self.isGraphBuilding = false
self.isInitialised = true
NotificationCenter.default.post(name: MXSpaceService.didBuildSpaceGraph, object: self)
self.processingQueue.async {
let store = MXSpaceFileStore(userId: self.session.myUserId, deviceId: self.session.myDeviceId)
if !store.store(spaceGraphData: self.graph) {
MXLog.error("[MXSpaceService] buildGraph: failed to store space graph")
}
// TODO improve updateNotificationsCount and call the method to all spaces once subspaces will be supported
self.notificationCounter.computeNotificationCount()
}
}
}
}
private func prepareData(with roomIds:[String], index: Int, output: PrepareDataResult, completion: @escaping (_ result: PrepareDataResult) -> Void) {
self.processingQueue.async {
guard index < roomIds.count else {
self.completionQueue.async {
output.isPreparingData = false
if !output.isComputing {
completion(output)
}
}
return
}
self.sdkProcessingQueue.async {
guard let room = self.session.room(withRoomId: roomIds[index]) else {
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
return
}
let space = self.spacesPerId[room.roomId] ?? room.toSpace()
self.prepareData(with: roomIds, index: index, output: output, room: room, space: space, isRoomDirect: room.isDirect, directUserId: room.directUserId, completion: completion)
}
}
}
private func prepareData(with roomIds:[String], index: Int, output: PrepareDataResult, room: MXRoom, space _space: MXSpace?, isRoomDirect:Bool, directUserId _directUserId: String?, completion: @escaping (_ result: PrepareDataResult) -> Void) {
self.processingQueue.async {
if let space = _space {
output.setComputing(true, forSpace: space)
space.readChildRoomsAndMembers {
output.setComputing(false, forSpace: space)
if !output.isPreparingData && !output.isComputing {
completion(output)
}
}
output.add(space: space)
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
} else if isRoomDirect {
if let directUserId = _directUserId {
output.add(directRoom: room, toUserWithId: directUserId)
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
} else {
self.sdkProcessingQueue.async {
output.setComputing(true, forDirectRoom: room)
room.members { response in
guard let members = response.value as? MXRoomMembers else {
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
return
}
let membersId = members.members?.compactMap({ roomMember in
return roomMember.userId != self.session.myUserId ? roomMember.userId : nil
}) ?? []
self.processingQueue.async {
membersId.forEach { memberId in
output.add(directRoom: room, toUserWithId: memberId)
}
output.setComputing(false, forDirectRoom: room)
if !output.isPreparingData && !output.isComputing {
completion(output)
}
}
}
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
}
}
} else {
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
}
}
}
private func computSpaceGraph(with result: PrepareDataResult, roomIds: [String], directRoomIds: Set<String>, completion: @escaping (_ graph: MXSpaceGraphData) -> Void) {
let startDate = Date()
MXLog.debug("[MXSpaceService] computSpaceGraph: started")
self.processingQueue.async {
var parentIdsPerRoomId: [String : Set<String>] = [:]
result.spaces.forEach { space in
space.updateChildSpaces(with: result.spacesPerId)
space.updateChildDirectRooms(with: result.directRoomIdsPerMemberId)
space.childRoomIds.forEach { roomId in
var parentIds = parentIdsPerRoomId[roomId] ?? Set<String>()
parentIds.insert(space.spaceId)
parentIdsPerRoomId[roomId] = parentIds
}
space.childSpaces.forEach { childSpace in
var parentIds = parentIdsPerRoomId[childSpace.spaceId] ?? Set<String>()
parentIds.insert(space.spaceId)
parentIdsPerRoomId[childSpace.spaceId] = parentIds
}
}
let rootSpaces = result.spaces.filter { space in
return parentIdsPerRoomId[space.spaceId] == nil
}
var ancestorsPerRoomId: [String: Set<String>] = [:]
var descendantsPerRoomId: [String: Set<String>] = [:]
rootSpaces.forEach { space in
self.buildRoomHierarchy(with: space, visitedSpaceIds: [], ancestorsPerRoomId: &ancestorsPerRoomId, descendantsPerRoomId: &descendantsPerRoomId)
}
var orphanedRoomIds: Set<String> = Set<String>()
var orphanedDirectRoomIds: Set<String> = Set<String>()
for roomId in roomIds {
let isRoomDirect = directRoomIds.contains(roomId)
if !isRoomDirect && parentIdsPerRoomId[roomId] == nil {
orphanedRoomIds.insert(roomId)
} else if isRoomDirect && parentIdsPerRoomId[roomId] == nil {
orphanedDirectRoomIds.insert(roomId)
}
}
let graph = MXSpaceGraphData(
spaceRoomIds: result.spaces.map({ space in
space.spaceId
}),
parentIdsPerRoomId: parentIdsPerRoomId,
ancestorsPerRoomId: ancestorsPerRoomId,
descendantsPerRoomId: descendantsPerRoomId,
rootSpaceIds: rootSpaces.map({ space in
space.spaceId
}),
orphanedRoomIds: orphanedRoomIds,
orphanedDirectRoomIds: orphanedDirectRoomIds)
MXLog.debug("[MXSpaceService] computSpaceGraph: space graph computed in \(Date().timeIntervalSince(startDate))s")
self.completionQueue.async {
completion(graph)
}
}
}
private func buildRoomHierarchy(with space: MXSpace, visitedSpaceIds: [String], ancestorsPerRoomId: inout [String: Set<String>], descendantsPerRoomId: inout [String: Set<String>]) {
var visitedSpaceIds = visitedSpaceIds
visitedSpaceIds.append(space.spaceId)
space.childRoomIds.forEach { roomId in
var parentIds = ancestorsPerRoomId[roomId] ?? Set<String>()
visitedSpaceIds.forEach { spaceId in
parentIds.insert(spaceId)
var descendantIds = descendantsPerRoomId[spaceId] ?? Set<String>()
descendantIds.insert(roomId)
descendantsPerRoomId[spaceId] = descendantIds
}
ancestorsPerRoomId[roomId] = parentIds
}
space.childSpaces.forEach { childSpace in
buildRoomHierarchy(with: childSpace, visitedSpaceIds: visitedSpaceIds, ancestorsPerRoomId: &ancestorsPerRoomId, descendantsPerRoomId: &descendantsPerRoomId)
}
}
// MARK: - Notification handling
private func registerNotificationObservers() {
self.sessionStateDidChangeObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.mxSessionStateDidChange, object: session, queue: nil) { [weak self] notification in
guard let session = self?.session, session.state == .storeDataReady else {
return
}
self?.loadData()
}
}
private func unregisterNotificationObservers() {
if let observer = self.sessionStateDidChangeObserver {
NotificationCenter.default.removeObserver(observer)
}
}
// MARK: - Private
private func createRoomSummary(with spaceChildSummaryResponse: MXSpaceChildSummaryResponse) -> MXRoomSummary {
let roomId = spaceChildSummaryResponse.roomId
let roomTypeString = spaceChildSummaryResponse.roomType
let roomSummary: MXRoomSummary = MXRoomSummary(roomId: roomId, andMatrixSession: nil)
roomSummary.roomTypeString = roomTypeString
roomSummary.roomType = self.roomTypeMapper.roomType(from: roomTypeString)
let joinedMembersCount = UInt(spaceChildSummaryResponse.numJoinedMembers)
let membersCount = MXRoomMembersCount()
membersCount.joined = joinedMembersCount
membersCount.members = joinedMembersCount
roomSummary.membersCount = membersCount
roomSummary.displayname = spaceChildSummaryResponse.name
roomSummary.topic = spaceChildSummaryResponse.topic
roomSummary.avatar = spaceChildSummaryResponse.avatarUrl
roomSummary.isEncrypted = false
return roomSummary
}
private func spaceChildInfos(from spaceChildrenResponse: MXSpaceChildrenResponse, excludedSpaceId: String, childrenIdsPerChildRoomId: [String: [String]], parentIdsPerChildRoomId: [String:Set<String>], spaceChildEventsPerChildRoomId: [String:[String:Any]]) -> [MXSpaceChildInfo] {
guard let spaceChildSummaries = spaceChildrenResponse.rooms else {
return []
}
let childInfos: [MXSpaceChildInfo] = spaceChildSummaries.compactMap { (spaceChildSummaryResponse) -> MXSpaceChildInfo? in
let spaceId = spaceChildSummaryResponse.roomId
guard spaceId != excludedSpaceId else {
return nil
}
let childStateEvent = spaceChildrenResponse.events?.first(where: { (event) -> Bool in
return event.stateKey == spaceId && event.eventType == .spaceChild
})
return self.createSpaceChildInfo(with: spaceChildSummaryResponse, and: childStateEvent, parentIds: parentIdsPerChildRoomId[spaceId], childrenIds: childrenIdsPerChildRoomId[spaceId], childEvents: spaceChildEventsPerChildRoomId[spaceId])
}
return childInfos
}
private func createSpaceChildInfo(with spaceChildSummaryResponse: MXSpaceChildSummaryResponse, and spaceChildStateEvent: MXEvent?, parentIds: Set<String>?, childrenIds: [String]?, childEvents: [String:Any]?) -> MXSpaceChildInfo {
var spaceChildContent: MXSpaceChildContent?
if let stateEventContent = spaceChildStateEvent?.content {
spaceChildContent = MXSpaceChildContent(fromJSON: stateEventContent)
}
let roomTypeString = spaceChildSummaryResponse.roomType
let roomType = self.roomTypeMapper.roomType(from: roomTypeString)
return MXSpaceChildInfo(childRoomId: spaceChildSummaryResponse.roomId,
isKnown: true,
roomTypeString: roomTypeString,
roomType: roomType,
name: spaceChildSummaryResponse.name,
topic: spaceChildSummaryResponse.topic,
canonicalAlias: spaceChildSummaryResponse.canonicalAlias,
avatarUrl: spaceChildSummaryResponse.avatarUrl,
order: spaceChildContent?.order,
activeMemberCount: spaceChildSummaryResponse.numJoinedMembers,
autoJoin: childEvents?[kMXEventTypeStringAutoJoinKey] as? Bool ?? false,
suggested: childEvents?[kMXEventTypeStringSuggestedKey] as? Bool ?? false,
parentIds: parentIds ?? Set(),
childrenIds: childrenIds ?? [],
viaServers: spaceChildContent?.via ?? [],
parentRoomId: spaceChildStateEvent?.roomId)
}
}
// MARK: - Objective-C interface
extension MXSpaceService {
/// Create a space.
/// - Parameters:
/// - parameters: The parameters for space creation.
/// - success: A closure called when the operation is complete.
/// - failure: A closure called when the operation fails.
/// - Returns: a `MXHTTPOperation` instance.
@objc public func createSpace(with parameters: MXSpaceCreationParameters, success: @escaping (MXSpace) -> Void, failure: @escaping (Error) -> Void) -> MXHTTPOperation {
return self.createSpace(with: parameters) { (response) in
uncurryResponse(response, success: success, failure: failure)
}
}
/// Create a space shortcut.
/// - Parameters:
/// - name: The space name.
/// - topic: The space topic.
/// - isPublic: true to indicate to use public chat presets and join the space without invite or false to use private chat presets and join the space on invite.
/// - success: A closure called when the operation is complete.
/// - failure: A closure called when the operation fails.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
@objc public func createSpace(withName name: String, topic: String?, isPublic: Bool, success: @escaping (MXSpace) -> Void, failure: @escaping (Error) -> Void) -> MXHTTPOperation {
return self.createSpace(withName: name, topic: topic, isPublic: isPublic) { (response) in
uncurryResponse(response, success: success, failure: failure)
}
}
/// Get the space children informations of a given space from the server.
/// - Parameters:
/// - spaceId: The room id of the queried space.
/// - suggestedOnly: If `true`, return only child events and rooms where the `m.space.child` event has `suggested: true`.
/// - limit: Optional. A limit to the maximum number of children to return per space. `-1` for no limit
/// - success: A closure called when the operation is complete.
/// - failure: A closure called when the operation fails.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
@objc public func getSpaceChildrenForSpace(withId spaceId: String, suggestedOnly: Bool, limit: Int, success: @escaping (MXSpaceChildrenSummary) -> Void, failure: @escaping (Error) -> Void) -> MXHTTPOperation {
return self.getSpaceChildrenForSpace(withId: spaceId, suggestedOnly: suggestedOnly, limit: limit) { (response) in
uncurryResponse(response, success: success, failure: failure)
}
}
}
// MARK: - Internal room additions
extension MXRoom {
func toSpace() -> MXSpace? {
guard let summary = self.summary, summary.roomType == .space else {
return nil
}
return MXSpace(roomId: self.roomId, session: self.mxSession)
}
}
| 44.312746 | 283 | 0.594923 |
d9f2a77dcfceb623e25fb993b60ffe28dc8e8ebc | 5,083 | /// Copyright (c) 2021 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// 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 CardDetailView: View {
@EnvironmentObject var viewState: ViewState
@Environment(\.scenePhase) private var scenePhase
@State private var currentModal: CardModal?
@Binding var card: Card
var body: some View {
RenderableView(card: $card) {
GeometryReader { proxy in
content(size: proxy.size)
.onChange(of: scenePhase) { newScenePhase in
if newScenePhase == .inactive {
card.save()
}
}
.onDisappear {
card.save()
}
.onDrop(
of: [.image],
delegate: CardDrop(
card: $card,
size: proxy.size,
frame: proxy.frame(in: .global)))
.frame(
width: calculateSize(proxy.size).width ,
height: calculateSize(proxy.size).height)
.clipped()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.modifier(CardToolbar(currentModal: $currentModal))
.cardModals(card: $card, currentModal: $currentModal)
}
func content(size: CGSize) -> some View {
ZStack {
card.backgroundColor
.edgesIgnoringSafeArea(.all)
.onTapGesture {
viewState.selectedElement = nil
}
ForEach(card.elements, id: \.id) { element in
CardElementView(
element: element,
selected: viewState.selectedElement?.id == element.id)
.contextMenu {
// swiftlint:disable:next multiple_closures_with_trailing_closure
Button(action: { card.remove(element) }) {
Label("Delete", systemImage: "trash")
}
}
.resizableView(
transform: bindingTransform(for: element),
viewScale: calculateScale(size))
.frame(
width: element.transform.size.width,
height: element.transform.size.height)
.onTapGesture {
viewState.selectedElement = element
}
}
}
}
func bindingTransform(for element: CardElement)
-> Binding<Transform> {
guard let index = element.index(in: card.elements) else {
fatalError("Element does not exist")
}
return $card.elements[index].transform
}
func calculateSize(_ size: CGSize) -> CGSize {
var newSize = size
let ratio =
Settings.cardSize.width / Settings.cardSize.height
if size.width < size.height {
newSize.height = min(size.height, newSize.width / ratio)
newSize.width = min(size.width, newSize.height * ratio)
} else {
newSize.width = min(size.width, newSize.height * ratio)
newSize.height = min(size.height, newSize.width / ratio)
}
return newSize
}
func calculateScale(_ size: CGSize) -> CGFloat {
let newSize = calculateSize(size)
return newSize.width / Settings.cardSize.width
}
}
struct CardDetailView_Previews: PreviewProvider {
struct CardDetailPreview: View {
@State private var card = initialCards[0]
var body: some View {
CardDetailView(card: $card)
.environmentObject(ViewState(card: card))
}
}
static var previews: some View {
CardDetailPreview()
}
}
| 36.049645 | 83 | 0.659453 |
9ceb0b23cdb95ed974c28e6127b76757bca5084e | 1,731 | // MIT License
//
// Copyright (c) 2017 Wesley Wickwire
//
// 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 RelativePointer<Offset: FixedWidthInteger, Pointee> {
var offset: Offset
mutating func pointee() -> Pointee {
return advanced().pointee
}
mutating func advanced() -> UnsafeMutablePointer<Pointee> {
let offset = self.offset
return withUnsafePointer(to: &self) { p in
return p.raw.advanced(by: numericCast(offset))
.assumingMemoryBound(to: Pointee.self)
.mutable
}
}
}
extension RelativePointer: CustomStringConvertible {
var description: String {
return "\(offset)"
}
}
| 38.466667 | 81 | 0.710572 |
284bd4da24228a0b8e78e7a338ebaded39f7d023 | 3,417 | //
// FileHelper.swift
// HostsX
//
// Created by zm on 2021/12/20.
//
import Foundation
import AppKit
struct FileHelper {
static func localUpdate(completion: @escaping FailureClosure) {
guard let url = open() else {
return completion(HostsError.cancelled)
}
read(url, failure: completion) {
do {
try check($0)
try write(to: .temp, contents: $0)
try copy(atPath: HostsPath.temp, toPath: HostsPath.hosts)
completion(.none)
} catch {
completion(error)
}
}
}
static func remoteUpdate(completion: @escaping FailureClosure) {
guard let url = URL(string: RemoteSource.originUrl) else {
return completion(HostsError.invalidURL)
}
read(url, failure: completion) {
do {
try check($0)
try write(to: .temp, contents: join($0))
try copy(atPath: HostsPath.temp, toPath: HostsPath.hosts)
completion(.none)
} catch {
completion(error)
}
}
}
}
extension FileHelper {
private static func write(to url: URL, contents: String) throws {
try contents.write(to: url, atomically: true, encoding: .utf8)
}
private static func remove(at url: URL) throws {
try FileManager.default.removeItem(at: url)
}
private static func read(_ url: URL,
failure: @escaping FailureClosure,
success: @escaping ReusltClosure) {
DispatchQueue.global().async {
do {
//sleep(5)
let content = try String(contentsOf: url)
DispatchQueue.main.async {
success(content)
}
} catch {
DispatchQueue.main.async {
failure(error)
}
}
}
}
private static func open() -> URL? {
let _openPanel = NSOpenPanel()
_openPanel.allowsMultipleSelection = false
_openPanel.canChooseDirectories = false
_openPanel.canCreateDirectories = false
_openPanel.canChooseFiles = true
return _openPanel.runModal() == .OK ? _openPanel.url : .none
}
private static func copy(atPath: String, toPath: String) throws {
let appleScript = NSAppleScript(command: "cp -f \(atPath) \(toPath)")
try appleScript.doShell()
}
private static func check(_ content: String) throws {
guard content.contains("localhost"), content.contains("127.0.0.1") else {
throw HostsError.invalidHosts
}
}
private static func join(_ content: String) throws -> String {
let joined = """
\(HostsTag.start)
\(HostsTag.flag)
\(HostsTag.end)
\(content)
"""
guard
let hosts = try? String(contentsOfFile: HostsPath.hosts),
let startIndex = hosts.range(of: HostsTag.start)?.upperBound,
let endIndex = hosts.range(of: HostsTag.end)?.lowerBound else{
return joined
}
let myHosts = hosts[startIndex..<endIndex].trimmingCharacters(in: .whitespacesAndNewlines)
return joined.replacingOccurrences(of: HostsTag.flag, with: myHosts)
}
}
| 28.008197 | 98 | 0.550483 |
76cbefbc4096ee0b7e1874b47485b0e2a6fcf044 | 1,127 | //
// pushAnimation.swift
// movieCatalog
//
// Created by Edwin Sierra on 2/21/18.
// Copyright © 2018 Edwin Sierra. All rights reserved.
//
import UIKit
/// Animacion que se ejecuta al momento de hacer un push dando un tap a una pelicula o serie
class pushAnimation: NSObject, UIViewControllerAnimatedTransitioning {
var operation: UINavigationControllerOperation = .push
var thumbnailFrame = CGRect.zero
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5;
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let toView = transitionContext.viewController(forKey: .to)!.view!
transitionContext.containerView.addSubview(toView)
toView.alpha = 0.0
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
toView.alpha = 1.0
}, completion: { finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
| 32.2 | 109 | 0.700089 |
14577d41d95ce10944fb0c64eb43c168d8a6c053 | 394 | //
// AuthProtocols.swift
// Travelly
//
// Created by Георгий Куликов on 16.02.2021.
//
import Foundation
protocol AuthPresenterProtocol: AnyObject {
func login()
func register()
}
protocol AuthRouterProtocol: AnyObject {
func presentLoginWindow()
func presentRegisterWindow()
}
protocol AuthAssemblyProtocol: AnyObject {
func createModule() -> AuthViewController
}
| 17.130435 | 45 | 0.728426 |
20a64f54ff53bbe2605ccfb4aad133a7c8c0f802 | 3,344 | import UIKit
/**
You can implement button as delegate pattern.
```swift
class CustomViewController: UIViewController, ButtonDelegate {
//MARK:- Components
private lazy var button = HDDelegateButton()
//MARK:- Life cycle events
override func viewDidLoad()
{
super.viewDidLoad()
self.view.addSubView(self.button)
self.button.delegate = self
}
//MARK:- ButtonDelegate
func touchUpInside(sender: UIButton)
{
print("Tapped!!!")
}
}
```
*/
open class HDDelegateButton: UIButton {
//MARK:- Properties
open weak var delegate: ButtonDelegate? {
get
{
return self.delegatePointer
}
set {
self.delegatePointer = newValue
super.addTarget(self,
action: #selector(self.touchDownRepeat(sender:)),
for: .touchDownRepeat)
super.addTarget(self,
action: #selector(self.touchDragEnter(sender:)),
for: .touchDragEnter)
super.addTarget(self,
action: #selector(self.touchDragExit(sender:)),
for: .touchDragExit)
super.addTarget(self,
action: #selector(self.touchDragInside(sender:)),
for: .touchDragInside)
super.addTarget(self,
action: #selector(self.touchDragOutside(sender:)),
for: .touchDragOutside)
super.addTarget(self,
action: #selector(self.touchUpInside(sender:)),
for: .touchUpInside)
super.addTarget(self,
action: #selector(self.touchUpOutside(sender:)),
for: .touchUpOutside)
}
}
//MARK:- Methods
open override func addTarget(_ target: Any?,
action: Selector,
for controlEvents: UIControlEvents)
{
super.addTarget(target, action: action, for: controlEvents)
print("It is prefer to set action through ButtonDelegate than through addTarget.")
return
}
//MARK:- Privates
private weak var delegatePointer: ButtonDelegate?
@objc private func touchDownRepeat(sender: UIButton)
{
self.delegate?.touchDownRepeat(sender: sender)
}
@objc private func touchDragEnter(sender: UIButton)
{
self.delegate?.touchDragEnter(sender: sender)
return
}
@objc private func touchDragExit(sender: UIButton)
{
self.delegate?.touchDragExit(sender: sender)
return
}
@objc private func touchDragInside(sender: UIButton)
{
self.delegate?.touchDragInside(sender: sender)
return
}
@objc private func touchDragOutside(sender: UIButton)
{
self.delegate?.touchDragOutside(sender: sender)
return
}
@objc private func touchUpInside(sender: UIButton)
{
self.delegate?.touchUpInside(sender: sender)
return
}
@objc private func touchUpOutside(sender: UIButton)
{
self.delegate?.touchUpOutside(sender: sender)
return
}
}
| 29.333333 | 90 | 0.554426 |
e60cfd29eb96b49fde4a6b6f244410ff28b05a97 | 2,010 | import UIKit
enum Direction {
case leftToRight
case rightToLeft
}
class StoryAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
let direction: Direction
init(direction: Direction) {
self.direction = direction
super.init()
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let inView = transitionContext.containerView
guard let toView = transitionContext.view(forKey: .to),
let fromView = transitionContext.view(forKey: .from) else { return }
let frame = inView.bounds
let padding: CGFloat = 100
switch direction {
case .leftToRight:
fromView.transform = .identity
toView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8).translatedBy(x: -frame.size.width - padding, y: 0)
inView.insertSubview(toView, belowSubview: fromView)
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
toView.transform = .identity
fromView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8).translatedBy(x: frame.size.width + padding, y: 0)
}, completion: { finished in
fromView.transform = .identity
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
case .rightToLeft:
inView.insertSubview(toView, belowSubview: fromView)
fromView.transform = .identity
toView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8).translatedBy(x: frame.size.width + padding, y: 0)
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
toView.transform = CGAffineTransform.identity
fromView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8).translatedBy(x: -frame.size.width - padding, y: 0)
}, completion: { finished in
fromView.transform = .identity
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
}
| 35.263158 | 114 | 0.752736 |
d570b90243ca18847c5d99faeb223f05daecb34f | 3,308 | //
// SuperheroViewController.swift
// flix
//
// Created by Ali Fenton on 2/7/18.
// Copyright © 2018 Ali Fenton. All rights reserved.
//
import UIKit
class SuperheroViewController: UIViewController, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var movies: [[String: Any]] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumInteritemSpacing = 5
layout.minimumLineSpacing = layout.minimumInteritemSpacing
let cellsPerLine: CGFloat = 2
let interItemSpacingTotal = layout.minimumInteritemSpacing * (cellsPerLine - 1)
let width = collectionView.frame.size.width / cellsPerLine - interItemSpacingTotal / cellsPerLine
layout.itemSize = CGSize(width: width, height: width * 3 / 2)
fetchMvoies()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return movies.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PosterCell", for: indexPath) as! PosterCell
let movie = movies[indexPath.item]
if let posterPathString = movie["poster_path"] as? String{
let baseURLString = "https://image.tmdb.org/t/p/w500"
let posterURL = URL(string: baseURLString + posterPathString)!
cell.posterImageView.af_setImage(withURL: posterURL)
}
return cell
}
func fetchMvoies(){
let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed")!
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
//this will run when the network request returns
if let error = error {
print(error.localizedDescription)
}else if let data = data {
let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as![String:Any]
let movies = dataDictionary["results"] as! [[String: Any]]
self.movies = movies
self.collectionView.reloadData()
//self.refreshControl.endRefreshing()
}
}
task.resume()
}
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.
}
*/
}
| 38.022989 | 121 | 0.656288 |
0112ca85fd8f5bf4d01f053e517cfbfa45cd1680 | 2,181 | //
// AppDelegate.swift
// ICSosialShare
//
// Created by fajarbrother on 06/07/2017.
// Copyright (c) 2017 fajarbrother. 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.404255 | 285 | 0.755617 |
8f2725cc029e995f11ea94b83ce87cbbdeaf67a1 | 3,111 | // RUN: %target-swift-frontend -typecheck -verify -swift-version 4 %s
let s = "Hello"
let ss = s[s.startIndex..<s.endIndex]
// CTP_Initialization
do {
let s1: String = { return ss }() // expected-error {{cannot convert value of type 'Substring' to closure result type 'String'}} {{29-29=String(}} {{31-31=)}}
_ = s1
}
// CTP_ReturnStmt
do {
func returnsAString() -> String {
return ss // expected-error {{cannot convert return expression of type 'Substring' to return type 'String'}} {{12-12=String(}} {{14-14=)}}
}
}
// CTP_ThrowStmt
// Doesn't really make sense for this fix-it - see case in diagnoseContextualConversionError:
// The conversion destination of throw is always ErrorType (at the moment)
// if this ever expands, this should be a specific form like () is for
// return.
// CTP_EnumCaseRawValue
// Substrings can't be raw values because they aren't literals.
// CTP_DefaultParameter
do {
func foo(x: String = ss) {} // expected-error {{default argument value of type 'Substring' cannot be converted to type 'String'}} {{24-24=String(}} {{26-26=)}}
}
// CTP_CalleeResult
do {
func getSubstring() -> Substring { return ss }
let gottenString : String = getSubstring() // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{31-31=String(}} {{45-45=)}}
_ = gottenString
}
// CTP_CallArgument
do {
func takesAString(_ s: String) {}
takesAString(ss) // expected-error {{cannot convert value of type 'Substring' to expected argument type 'String'}} {{16-16=String(}} {{18-18=)}}
}
// CTP_ClosureResult
do {
[ss].map { (x: Substring) -> String in x } // expected-error {{declared closure result 'String' is incompatible with return type 'Substring'}} {{32-38=Substring}}
}
// CTP_ArrayElement
do {
let a: [String] = [ ss ] // expected-error {{cannot convert value of type 'Substring' to expected element type 'String'}} {{23-23=String(}} {{25-25=)}}
_ = a
}
// CTP_DictionaryKey
do {
let d: [ String : String ] = [ ss : s ] // expected-error {{cannot convert value of type 'Substring' to expected dictionary key type 'String'}} {{34-34=String(}} {{36-36=)}}
_ = d
}
// CTP_DictionaryValue
do {
let d: [ String : String ] = [ s : ss ] // expected-error {{cannot convert value of type 'Substring' to expected dictionary value type 'String'}} {{38-38=String(}} {{40-40=)}}
_ = d
}
// CTP_CoerceOperand
do {
let s1: String = ss as String // expected-error {{cannot convert value of type 'Substring' to type 'String' in coercion}} {{20-20=String(}} {{22-22=)}}
_ = s1
}
// CTP_AssignSource
do {
let s1: String = ss // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{20-20=String(}} {{22-22=)}}
_ = s1
}
// Substring-to-String via subscripting in a context expecting String
func takesString(_ s: String) {}
// rdar://33474838
protocol Derivable {
func derive() -> Substring
}
func foo<T: Derivable>(t: T) -> String {
return t.derive() // expected-error {{cannot convert return expression of type 'Substring' to return type 'String'}} {{10-10=String(}} {{20-20=)}}
}
| 34.186813 | 177 | 0.672131 |
3866159ee09240f24424c64024a193f9bfc2fd0f | 325 | import Foundation
public class ViewRouter<T: ViewRoute>: Routable {
private let routable: ViewRoutable
open func route(to route: T) {
routable.anyRoute(to: route)
}
public init<U: ViewCoordinatable>(_ coordinator: U) {
self.routable = ViewRoutable(coordinator: coordinator)
}
}
| 23.214286 | 62 | 0.664615 |
339cb5aa5a51d99d3f7f11c608840c5750dfda02 | 1,513 | //
// SegmentTableViewCell.swift
// Pesequel
//
// Created by Ghost on 29.09.2019.
// Copyright © 2019 Ghost. All rights reserved.
//
import UIKit
class SegmentTableViewCell: BasicTableViewCell, NibLoadable {
@IBOutlet weak var segmentControl: UISegmentedControl!
enum PickupType: String {
case inPlace
case outside
}
var pickupSelected: ItemClosure<PickupType>?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func layoutSubviews() {
super.layoutSubviews()
segmentControl.round()
segmentControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0, green: 0.4823529412, blue: 1, alpha: 1)], for: .normal)
segmentControl.layer.borderColor = #colorLiteral(red: 0, green: 0.4823529412, blue: 1, alpha: 1).withAlphaComponent(0.15).cgColor
segmentControl.tintColor = #colorLiteral(red: 0, green: 0.4823529412, blue: 1, alpha: 1).withAlphaComponent(0.15)
segmentControl.layer.borderWidth = 1
segmentControl.layer.masksToBounds = true
segmentControl.addTarget(self, action: #selector(segmentedControl(sender:)), for: .valueChanged)
}
@objc private func segmentedControl(sender: UISegmentedControl) {
pickupSelected?(sender.selectedSegmentIndex == 0 ? .inPlace : .outside)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 31.520833 | 160 | 0.72505 |
8a6343eadd6a95e0425ffdebdcdd68aa16c141e9 | 1,506 | //
// InterfaceController.swift
// EFWforWatch WatchKit Extension
//
// Created by Ryan Callery on 10/23/18.
// Copyright © 2018 Ryan Callery. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
@IBOutlet var weekTable: WKInterfaceTable!
var weeksArray = [Int]()
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
weeksArray = Array(gestationalWeight.keys)
weeksArray.sort()
weekTable.setNumberOfRows(weeksArray.count, withRowType: "Row")
for i in 0 ..< weeksArray.count {
let rowController = weekTable.rowController(at: i) as? WeekSelectRow
let weekString = String(weeksArray[i])
rowController?.weeksLabel.setText(weekString)
}
}
override func contextForSegue(withIdentifier segueIdentifier: String, in table: WKInterfaceTable, rowIndex: Int) -> Any? {
let weeks = weeksArray[rowIndex]
return [weeks : gestationalWeight[weeks] ]
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| 25.965517 | 126 | 0.636786 |
3a59ac5c669cd3147f547ae36a440dd3f23fe1e3 | 3,062 | //
// AppDelegate.swift
// Twitter
//
// Created by Victor Li Wang on 2/14/16.
// Copyright © 2016 Victor Li Wang. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if User.currentUser != nil {
print("current user detected")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("TweetsNavigationController")
window?.rootViewController = vc
}
NSNotificationCenter.defaultCenter().addObserverForName(User.userDidLogoutNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (NSNotification) -> Void in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateInitialViewController()
self.window?.rootViewController = vc
}
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:.
}
func application(application: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
TwitterClient.sharedInstance.openURL(url)
return true
}
}
| 44.376812 | 285 | 0.707054 |
186eba28768030e2d3bc6bb0ec89667abe5dc872 | 1,309 | import Foundation
// 定数定義ファイル
struct Constants {
/// HTTP通信関連の定数定義
// 通信タイムアウト時間設定
static let TIME_OUT = 2000
// 通信結果の真偽返り値の設定(PHPのboolは1,0なので)
static let RETURN_HTTP_TRUE = "1"
static let RETURN_HTTP_FALSE = "0"
// 出席管理システムのドメイン IPアドレス+階層を記述
static let URL_DOMAIN = "hoge" // "http://IP address/attendancesystem/android/"
// 各処理で接続するURLの定数
static let URL_GET_POSSIBLE_ATTEND_LIST = "get-possible-attend-list.php"
static let URL_CHECK_ALREADY_ATTEND = "check-already-attend.php"
static let URL_GET_SEAT_NUM = "get-seat-num.php"
static let URL_CHECK_EMPTY_SEAT = "check-empty-seat.php"
static let URL_SEND_ATTEND = "send-attendance.php"
/// NFCタグ関連の定数定義
// NFCタグ毎の処理分岐条件定数 読取タグにこの文字列が記録されていなければ各処理を行わない
static let TYPE_STUDENT_ID_TAG = "IbarakiUnivStudentIdTag"
static let TYPE_SEAT_ID_TAG = "IbarakiUnivSeatIdTag"
/// FeliCa読取関連の定数定義
// FeliCaカードタイプ
static let TYPE_STUDENT_ID_CARD = "IbarakiUnivStudentIdCard"
static let TYPE_SEAT_ID_CARD = "IbarakiUnivSeadIdCard"
static let TYPE_UNKNOWN_CARD = "UnknownCard"
// FeliCaシステムコード
static let SYSTEMCODE_STUDENT_ID_CARD = "81f8"
static let SYSTENCODE_SEAT_ID_CARD = "88b4"
// FeliCaサービスコード
static let SERVICECODE_STUDENT_ID_CARD = "100b"
}
| 36.361111 | 83 | 0.73262 |
292333ddaa979ede82315f3230ea24c589be8fec | 1,007 | import ReactiveSwift
import UIKit
private enum Associations {
fileprivate static var alignment = 0
fileprivate static var axis = 1
}
public extension Rac where Object: UIStackView {
var axis: Signal<NSLayoutConstraint.Axis, Never> {
nonmutating set {
let prop: MutableProperty<NSLayoutConstraint.Axis> = lazyMutableProperty(
object, key: &Associations.axis,
setter: { [weak object] in object?.axis = $0 },
getter: { [weak object] in object?.axis ?? .horizontal })
prop <~ newValue.observeForUI()
}
get {
return .empty
}
}
var alignment: Signal<UIStackView.Alignment, Never> {
nonmutating set {
let prop: MutableProperty<UIStackView.Alignment> = lazyMutableProperty(
object, key: &Associations.alignment,
setter: { [weak object] in object?.alignment = $0 },
getter: { [weak object] in object?.alignment ?? .fill })
prop <~ newValue.observeForUI()
}
get {
return .empty
}
}
}
| 26.5 | 79 | 0.647468 |
0e98f2a9a1ef77298485e8dc81dd165bb5ba3e70 | 521 | //
// AttributedStringParser.swift
// Pods
//
// Created by Bartosz Tułodziecki on 24/10/2016.
//
//
import Foundation
public struct AttributtedStringParser {
// Required for Test target
public init() {}
public func tagWith(string: String, range: NSRange, attributes: [NSAttributedString.Key: Any]) -> Tag? {
let factory = TagFactory.factory(attributes: attributes)
let tag = factory.generateTag(content: string, range: range, attributes: attributes)
return tag
}
}
| 23.681818 | 108 | 0.673704 |
bba7e1d5a97a3d18dbc9951daeab0ccb81297ab5 | 2,502 | //
// WVBUColorScheme.swift
// WVBU
//
// Created by Joe Duvall on 5/1/16.
// Copyright © 2016 Joe Duvall. All rights reserved.
//
import UIKit
class WVBUColorScheme {
enum ColorMode {
case lightMode
case darkMode
}
static let shared = WVBUColorScheme()
var currentMode: ColorMode = .lightMode
func textColor() -> UIColor {
switch currentMode {
case .darkMode:
return UIColor(hexValue: 0xFFFFFF)
case .lightMode:
return UIColor(hexValue: 0x000000)
}
}
func buttonColor() -> UIColor {
switch currentMode {
case .darkMode:
return UIColor(hexValue: 0xFFFFFF)
case .lightMode:
return UIColor(hexValue: 0x004B8E)
}
}
func backgroundColor() -> UIColor {
switch currentMode {
case .darkMode:
return UIColor(hexValue: 0x505050)
case .lightMode:
return UIColor(hexValue: 0xFFFFFF)
}
}
func navigationBarColor() -> UIColor {
switch currentMode {
case .darkMode:
return UIColor(hexValue: 0x4A4A4A)
case .lightMode:
return UIColor(hexValue: 0xFFFFFF)
}
}
func statusBarColor() -> UIColor {
switch currentMode {
case .darkMode:
return UIColor(hexValue: 0xFFFFFF)
case .lightMode:
return UIColor(hexValue: 0x000000)
}
}
}
extension UIColor {
///
/// Initializes and returns a color object using the specified opacity and hex value.
/// - Parameter hexValue: The color's hex value.
/// - Parameter alpha: The color's alpha value. Valid values range from 0.0 to 1.0. This parameter defaults to 1.0 if omitted.
/// - Returns: An initialized color object.
/// - Note: [Credit to mbigatti on GitHub Gist.](https://gist.github.com/mbigatti/c6be210a6bbc0ff25972)
///
convenience init(hexValue: UInt, alpha: CGFloat = 1.0) {
let red = CGFloat((hexValue & 0xFF0000) >> 16) / 255
let green = CGFloat((hexValue & 0xFF00) >> 8) / 255
let blue = CGFloat(hexValue & 0xFF) / 255
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
convenience init(redValue: CGFloat, greenValue: CGFloat, blueValue: CGFloat, alpha: CGFloat) {
self.init(red: redValue/255.0, green: greenValue/255.0, blue: blueValue/255.0, alpha: alpha)
}
}
| 28.11236 | 130 | 0.592726 |
114c8315e7d977e39335b703ce813edf6bf67deb | 384 | //
// RNCoreFileViewerModule.swift
// RNCoreFileViewerModule
//
// Copyright © 2022 Catalin Cor. All rights reserved.
//
import Foundation
@objc(RNCoreFileViewerModule)
class RNCoreFileViewerModule: NSObject {
@objc
func constantsToExport() -> [AnyHashable : Any]! {
return ["count": 1]
}
@objc
static func requiresMainQueueSetup() -> Bool {
return true
}
}
| 17.454545 | 54 | 0.695313 |
691f3e5c6caa7504eb844afa83fd98eea842ae93 | 956 | //
// EveryTests.swift
// EveryTests
//
// Created by Samhan on 05/01/16.
// Copyright © 2016 Samhan. All rights reserved.
//
import XCTest
@testable import Every
class EveryTests: 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.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 25.837838 | 111 | 0.628661 |
d684c6427fe16ec672f36c2bf4bdb659b62130e2 | 712 | //
// NavigateOption.swift
// PokeDemo
//
// Created by Guerson on 2020-09-01.
// Copyright © 2020 Itandehui. All rights reserved.
//
import Foundation
import UIKit
enum NavigateOption {
case login
case home
}
extension NavigateOption: StoryboardIdentifiable {
func getStoryboardName() -> String {
switch self {
case .login:
return "Login"
case .home:
return "Home"
}
}
}
extension NavigateOption: ViewControllerIdentifiable {
func getViewController() -> UIViewController? {
let storyBoard = UIStoryboard(name: self.getStoryboardName(), bundle: nil)
return storyBoard.instantiateInitialViewController()
}
}
| 20.342857 | 82 | 0.655899 |
334d1205c9a4d4330f1050c750980fe9fc8cdf37 | 19,172 | //
// MarketResearchViewController.swift
// Entreprenetwork
//
// Created by IPS on 11/03/21.
// Copyright © 2021 Sujal Adhia. All rights reserved.
//
import UIKit
import CoreLocation
class MarketResearchViewController: UIViewController {
@IBOutlet weak var buttonBack:UIButton!
@IBOutlet weak var tableViewMarketResearch:UITableView!
//job keywords
@IBOutlet weak var txtJOBKeywords:UITextField!
//job category
@IBOutlet weak var txtJOBCategory:UITextField!
var businessCategoryPicker:UIPickerView = UIPickerView()
var businessCategoryToolbar:UIToolbar = UIToolbar()
var arrayOfCategory:[GeneralList] = []
var businessCategory = "Automotive"
var currentbusinessCategory:String{
get{
return businessCategory
}
set{
self.businessCategory = newValue
}
}
//job ranges in miles
@IBOutlet fileprivate weak var distanceMilesSlider:RangeSeekSlider!
//minimum and maximum value
@IBOutlet fileprivate weak var minimumAndMaimmumValueSlider:RangeSeekSlider!
//Select Type
@IBOutlet fileprivate weak var buttonInprogressLocation:UIButton!
@IBOutlet fileprivate weak var buttonWaitingLocation:UIButton!
@IBOutlet fileprivate weak var buttonCompletedLocation:UIButton!
var searchTypeSet:NSMutableSet = NSMutableSet()//completed","pending","progress
@IBOutlet fileprivate weak var buttonHomeLocation:UIButton!
@IBOutlet fileprivate weak var buttonCurrentLocation:UIButton!
var isHome:Bool = true
var isHomeLocation:Bool {
get{
return isHome
}
set{
self.isHome = newValue
//Configure isHome
DispatchQueue.main.async {
self.configureHomeLocationSelector()
}
}
}
var marketSearchParmaters:[String:Any] = [:]
var location = CLLocationCoordinate2D()
var locationManager: CLLocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.buttonInprogressLocation.isSelected = true
self.buttonWaitingLocation.isSelected = false
self.buttonCompletedLocation.isSelected = true
self.isHomeLocation = true
//setup
self.setup()
//configure tableview
self.configureTableView()
//setup picker
self.configureCategoryPicker()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.locationManager.stopUpdatingLocation()
}
//Setup
func setup(){
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
//
if let pi: Double = Double("\(appDelegate.minMiles)"){
let strMinMiles = String(format:"%.2f", pi)
self.distanceMilesSlider.minValue = CGFloat((strMinMiles as NSString).floatValue)
self.distanceMilesSlider.selectedMinValue = CGFloat((strMinMiles as NSString).floatValue)
}
if let pi: Double = Double("\(appDelegate.maxMiles)"){
let strMaxMiles = String(format:"%.2f", pi)
self.distanceMilesSlider.maxValue = CGFloat((strMaxMiles as NSString).floatValue)
self.distanceMilesSlider.selectedMaxValue = CGFloat((strMaxMiles as NSString).floatValue)
}
//
if let pi: Double = Double("\(appDelegate.jobMinPrice)"){
let strMinPrice = String(format:"%.2f", pi)
self.minimumAndMaimmumValueSlider.minValue = CGFloat((strMinPrice as NSString).floatValue)
self.minimumAndMaimmumValueSlider.selectedMinValue = CGFloat((strMinPrice as NSString).floatValue)
}
if let pi: Double = Double("\(appDelegate.jobMaxPrice)"){
let strMaxPrice = String(format:"%.2f", pi)
self.minimumAndMaimmumValueSlider.maxValue = CGFloat((strMaxPrice as NSString).floatValue)
self.minimumAndMaimmumValueSlider.selectedMaxValue = CGFloat((strMaxPrice as NSString).floatValue)
}
self.minimumAndMaimmumValueSlider.delegate = self
self.distanceMilesSlider.handleDiameter = 20.0
self.minimumAndMaimmumValueSlider.handleDiameter = 20.0
}
}
func mylocation() {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
// Ask for Authorisation from the User.
// For use in foreground
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}
func configureHomeLocationSelector(){
if self.isHomeLocation{
self.buttonHomeLocation.isSelected = false
self.buttonCurrentLocation.isSelected = true
}else{
self.buttonHomeLocation.isSelected = true
self.buttonCurrentLocation.isSelected = false
}
}
//Configure TableView
func configureTableView(){
//self.tableViewMarketResearch.sizeHeaderFit()
self.tableViewMarketResearch.scrollEnableIfTableViewContentIsLarger()
self.tableViewMarketResearch.hideFooter()
}
func resentAllFields(){
//self.setup()
self.txtJOBKeywords.text = ""
self.txtJOBCategory.text = ""
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let pi: Double = Double("\(appDelegate.maxMiles)"){
let strMaxMiles = String(format:"%.2f", pi)
self.distanceMilesSlider.selectedMaxValue = CGFloat((strMaxMiles as NSString).floatValue)
}
if let pi: Double = Double("\(appDelegate.jobMinPrice)"){
let strMinPrice = String(format:"%.2f", pi)
self.minimumAndMaimmumValueSlider.selectedMinValue = CGFloat((strMinPrice as NSString).floatValue)
}
if let pi: Double = Double("\(appDelegate.jobMaxPrice)"){
let strMaxPrice = String(format:"%.2f", pi)
self.minimumAndMaimmumValueSlider.selectedMaxValue = CGFloat((strMaxPrice as NSString).floatValue)
}
}
self.minimumAndMaimmumValueSlider.setNeedsLayout()
self.minimumAndMaimmumValueSlider.layoutSubviews()
self.distanceMilesSlider.setNeedsLayout()
self.distanceMilesSlider.layoutSubviews()
self.buttonInprogressLocation.isSelected = true
self.buttonWaitingLocation.isSelected = false
self.buttonCompletedLocation.isSelected = true
self.isHomeLocation = true
}
//isValid Data
func isValidData()->Bool {
/*guard let keyword = self.txtJOBKeywords.text?.trimmingCharacters(in: .whitespacesAndNewlines),keyword.count > 0 else{
DispatchQueue.main.async {
SAAlertBar.show(.error, message:"Please enter JOB Keyword".localizedLowercase)
}
return false
}
*/
if let keyword = self.txtJOBKeywords.text?.trimmingCharacters(in: .whitespacesAndNewlines){
self.marketSearchParmaters["job_keyword"] = "\(keyword)"
}
guard let category = self.txtJOBCategory.text?.trimmingCharacters(in: .whitespacesAndNewlines),category.count > 0 else{
DispatchQueue.main.async {
SAAlertBar.show(.error, message:"Please enter JOB Category".localizedLowercase)
}
return false
}
let filterArray2 = self.arrayOfCategory.filter{$0.name == category}
if filterArray2.count > 0{
self.marketSearchParmaters["category"] = filterArray2.first!.id
}
if let value = self.distanceMilesSlider.selectedMaxValue as? CGFloat{
self.marketSearchParmaters["miles"] = "\(value)"
}
if let value = self.minimumAndMaimmumValueSlider.selectedMinValue as? CGFloat{
self.marketSearchParmaters["min_price"] = "\(value)"
}
if let value = self.minimumAndMaimmumValueSlider.selectedMaxValue as? CGFloat{
self.marketSearchParmaters["max_price"] = "\(value)"
}
var arrayOfStatus:[String] = []
if !self.buttonInprogressLocation.isSelected{
arrayOfStatus.append("progress")
}
if !self.buttonWaitingLocation.isSelected{
arrayOfStatus.append("pending")
}
if !self.buttonCompletedLocation.isSelected{
arrayOfStatus.append("completed")
}
self.marketSearchParmaters["status"] = arrayOfStatus
if self.isHomeLocation{
self.marketSearchParmaters["lat"] = ""
self.marketSearchParmaters["lng"] = ""
}
return true
}
//Configure Category Picker
func configureCategoryPicker(){
let doneBusinesCategoryPicker = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(MarketResearchViewController.doneBusinesCategoryPicker))
let title2 = UILabel.init()
title2.attributedText = NSAttributedString.init(string: "Category", attributes:[NSAttributedString.Key.font:UIFont.init(name:"Avenir-Heavy", size: 15.0)!])
title2.sizeToFit()
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton2 = UIBarButtonItem(title:"Cancel", style: UIBarButtonItem.Style.plain, target: self, action: #selector(MarketResearchViewController.cancelFormDatePicker))
self.businessCategoryToolbar.setItems([cancelButton2,spaceButton,UIBarButtonItem.init(customView: title2),spaceButton,doneBusinesCategoryPicker], animated: false)
self.businessCategoryToolbar.sizeToFit()
self.businessCategoryToolbar.layer.borderColor = UIColor.clear.cgColor
self.businessCategoryToolbar.layer.borderWidth = 1.0
self.businessCategoryToolbar.clipsToBounds = true
self.businessCategoryToolbar.backgroundColor = UIColor.white
self.businessCategoryPicker.delegate = self
self.businessCategoryPicker.dataSource = self
self.businessCategoryPicker.tag = 2
self.txtJOBCategory.inputView = self.businessCategoryPicker
self.txtJOBCategory.inputAccessoryView = self.businessCategoryToolbar
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
self.arrayOfCategory = appDelegate.arrayCategory
if self.arrayOfCategory.count > 0{
//self.currentbusinessCategory = self.arrayOfCategory[0].name
//self.txtJOBCategory.text = self.currentbusinessCategory
let filterArray = self.arrayOfCategory.filter{$0.name == self.currentbusinessCategory}
if filterArray.count > 0{
//self.marketSearchParmaters["category"] = filterArray.first!.id
}
}
}
}
@objc func doneBusinesCategoryPicker(){
self.configureSelectedBusinessCategoryActive()
DispatchQueue.main.async {
self.view.endEditing(true)
}
}
@objc func cancelFormDatePicker(){
DispatchQueue.main.async {
self.view.endEditing(true)
}
}
func configureSelectedBusinessCategoryActive(){
DispatchQueue.main.async {
self.txtJOBCategory.text = self.currentbusinessCategory
let filterArray = self.arrayOfCategory.filter{$0.name == self.currentbusinessCategory}
if filterArray.count > 0{
self.marketSearchParmaters["category"] = filterArray.first!.id
}
}
}
// MARK: - Selector Methods
@IBAction func buttonBackSelector(sender:UIButton){
self.navigationController?.popViewController(animated: true)
}
@IBAction func buttonResetSelector(sender:UIButton){
DispatchQueue.main.async {
self.resentAllFields()
}
}
@IBAction func buttonInprogressSelector(sender:UIButton){
self.buttonInprogressLocation.isSelected = !self.buttonInprogressLocation.isSelected
}
@IBAction func buttonWaitingsSelector(sender:UIButton){
self.buttonWaitingLocation.isSelected = !self.buttonWaitingLocation.isSelected
}
@IBAction func buttonCompletedSelector(sender:UIButton){
if self.buttonCompletedLocation.isSelected{
self.buttonCompletedLocation.isSelected = !self.buttonCompletedLocation.isSelected
}
}
@IBAction func buttonHomeCurrentLocationSelector(sender:UIButton){
self.isHomeLocation = !self.isHomeLocation
}
@IBAction func buttonSearchSelector(sender:UIButton){
if self.isValidData(){
self.searchMarketResearchAPIRequest()
}
}
// MARK: - API Request
func searchMarketResearchAPIRequest(){
print(self.marketSearchParmaters)
APIRequestClient.shared.sendAPIRequest(requestType: .POST, queryString:kJOBMarketSearch , parameter: self.marketSearchParmaters as [String : AnyObject], isHudeShow: true, success: { (responseSuccess) in
if let success = responseSuccess as? [String:Any],let arrayJOBResult = success["success_data"] as? [[String:Any]]{
self.pushToMarketResearchViewController(result: arrayJOBResult)
}else{
DispatchQueue.main.async {
// SAAlertBar.show(.error, message:"\(kCommonError)".localizedLowercase)
}
}
}) { (responseFail) in
if let failResponse = responseFail as? [String:Any],let errorMessage = failResponse["error_data"] as? [String]{
DispatchQueue.main.async {
if errorMessage.count > 0{
SAAlertBar.show(.error, message:"\(errorMessage.first!)".localizedLowercase)
}
}
}else{
DispatchQueue.main.async {
// SAAlertBar.show(.error, message:"\(kCommonError)".localizedLowercase)
}
}
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
func pushToMarketResearchViewController(result:[[String:Any]]){
DispatchQueue.main.async {
self.resentAllFields()
if let resultViewController = UIStoryboard.main.instantiateViewController(withIdentifier: "MarketResearchResultViewController") as? MarketResearchResultViewController{
resultViewController.hidesBottomBarWhenPushed = true
resultViewController.arrayOfResult = result
self.navigationController?.pushViewController(resultViewController, animated: true)
}
}
}
}
extension MarketResearchViewController:RangeSeekSliderDelegate{
fileprivate func priceString(value: CGFloat) -> String {
if let pi: Double = Double("\(value)"){
let price = String(format:"%.f", pi)
return "$\(price)"
}
/*
if value == .leastNormalMagnitude {
return "min $ \(value)"
} else if value == .greatestFiniteMagnitude {
return "max $ \(value)"
} else {
return "$ \(value)"
}*/
return "$\(value)"
}
func rangeSeekSlider(_ slider: RangeSeekSlider, stringForMinValue minValue: CGFloat) -> String? {
return priceString(value: minValue)
}
func rangeSeekSlider(_ slider: RangeSeekSlider, stringForMaxValue maxValue: CGFloat) -> String? {
return priceString(value: maxValue)
}
}
extension MarketResearchViewController:UIPickerViewDelegate,UIPickerViewDataSource, CLLocationManagerDelegate{
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.arrayOfCategory[row].name
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return UIScreen.main.bounds.width
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 30.0
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.arrayOfCategory.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.currentbusinessCategory = self.arrayOfCategory[row].name
}
//MARK: - Location Manager Delegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let latestLocation: AnyObject = locations[locations.count - 1]
let mystartLocation = latestLocation as! CLLocation;
UserJob.Shared.lat = String(mystartLocation.coordinate.latitude)
UserJob.Shared.long = String(mystartLocation.coordinate.longitude)
self.marketSearchParmaters["lat"] = String(mystartLocation.coordinate.latitude)
self.marketSearchParmaters["lng"] = String(mystartLocation.coordinate.longitude)
}
}
| 43.375566 | 210 | 0.614907 |
fc47787237955feed5e0a215756f2ba9573c38fa | 6,915 | //===--- DropLast.swift ---------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is manually generated from .gyb template and should not
// be directly modified. Instead, make changes to DropLast.swift.gyb and run
// scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
import TestsUtils
let sequenceCount = 4096
let prefixCount = 1024
let dropCount = sequenceCount - prefixCount
let sumCount = prefixCount * (prefixCount - 1) / 2
public let DropLast = [
BenchmarkInfo(
name: "DropLastCountableRange",
runFunction: run_DropLastCountableRange,
tags: [.validation, .api, .unstable]),
BenchmarkInfo(
name: "DropLastSequence",
runFunction: run_DropLastSequence,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropLastAnySequence",
runFunction: run_DropLastAnySequence,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropLastAnySeqCntRange",
runFunction: run_DropLastAnySeqCntRange,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropLastAnySeqCRangeIter",
runFunction: run_DropLastAnySeqCRangeIter,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropLastAnyCollection",
runFunction: run_DropLastAnyCollection,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropLastArray",
runFunction: run_DropLastArray,
tags: [.validation, .api, .Array, .unstable]),
BenchmarkInfo(
name: "DropLastCountableRangeLazy",
runFunction: run_DropLastCountableRangeLazy,
tags: [.validation, .api, .unstable]),
BenchmarkInfo(
name: "DropLastSequenceLazy",
runFunction: run_DropLastSequenceLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropLastAnySequenceLazy",
runFunction: run_DropLastAnySequenceLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropLastAnySeqCntRangeLazy",
runFunction: run_DropLastAnySeqCntRangeLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropLastAnySeqCRangeIterLazy",
runFunction: run_DropLastAnySeqCRangeIterLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropLastAnyCollectionLazy",
runFunction: run_DropLastAnyCollectionLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropLastArrayLazy",
runFunction: run_DropLastArrayLazy,
tags: [.validation, .api, .Array, .unstable]),
]
@inline(never)
public func run_DropLastCountableRange(_ N: Int) {
let s = 0..<sequenceCount
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastSequence(_ N: Int) {
let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySequence(_ N: Int) {
let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySeqCntRange(_ N: Int) {
let s = AnySequence(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySeqCRangeIter(_ N: Int) {
let s = AnySequence((0..<sequenceCount).makeIterator())
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnyCollection(_ N: Int) {
let s = AnyCollection(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastArray(_ N: Int) {
let s = Array(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastCountableRangeLazy(_ N: Int) {
let s = (0..<sequenceCount).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastSequenceLazy(_ N: Int) {
let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySequenceLazy(_ N: Int) {
let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySeqCntRangeLazy(_ N: Int) {
let s = (AnySequence(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySeqCRangeIterLazy(_ N: Int) {
let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnyCollectionLazy(_ N: Int) {
let s = (AnyCollection(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastArrayLazy(_ N: Int) {
let s = (Array(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
// Local Variables:
// eval: (read-only-mode 1)
// End:
| 28.45679 | 91 | 0.640347 |
03309de5ffc3695c57daf650810825c088c222ba | 19,552 | //——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// THIS FILE IS GENERATED BY EASY BINDINGS, DO NOT MODIFY IT
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
import Cocoa
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ReadOnlyObject_PadProxyInDevice
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
class ReadOnlyObject_PadProxyInDevice : ReadOnlyAbstractObjectProperty <PadProxyInDevice> {
//····················································································································
internal override func notifyModelDidChangeFrom (oldValue inOldValue : PadProxyInDevice?) {
super.notifyModelDidChangeFrom (oldValue: inOldValue)
//--- Remove observers from removed objects
if let oldValue = inOldValue {
oldValue.mPinInstanceName_property.removeEBObserver (self.mPinInstanceName_property) // Stored property
oldValue.mPadName_property.removeEBObserver (self.mPadName_property) // Stored property
oldValue.mIsNC_property.removeEBObserver (self.mIsNC_property) // Stored property
oldValue.isConnected_property.removeEBObserver (self.isConnected_property) // Transient property
oldValue.symbolName_property.removeEBObserver (self.symbolName_property) // Transient property
}
//--- Add observers to added objects
if let newValue = self.mInternalValue {
newValue.mPinInstanceName_property.addEBObserver (self.mPinInstanceName_property) // Stored property
newValue.mPadName_property.addEBObserver (self.mPadName_property) // Stored property
newValue.mIsNC_property.addEBObserver (self.mIsNC_property) // Stored property
newValue.isConnected_property.addEBObserver (self.isConnected_property) // Transient property
newValue.symbolName_property.addEBObserver (self.symbolName_property) // Transient property
}
}
//····················································································································
// Observers of 'mPinInstanceName' stored property
//····················································································································
final let mPinInstanceName_property = EBGenericTransientProperty <String?> ()
//····················································································································
// Observers of 'mPadName' stored property
//····················································································································
final let mPadName_property = EBGenericTransientProperty <String?> ()
//····················································································································
// Observers of 'mIsNC' stored property
//····················································································································
final let mIsNC_property = EBGenericTransientProperty <Bool?> ()
//····················································································································
// Observers of 'isConnected' transient property
//····················································································································
final let isConnected_property = EBGenericTransientProperty <Bool?> ()
//····················································································································
// Observers of 'symbolName' transient property
//····················································································································
final let symbolName_property = EBGenericTransientProperty <String?> ()
//····················································································································
// INIT
//····················································································································
override init () {
super.init ()
//--- Configure mPinInstanceName simple stored property
self.mPinInstanceName_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.mPinInstanceName_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure mPadName simple stored property
self.mPadName_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.mPadName_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure mIsNC simple stored property
self.mIsNC_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.mIsNC_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure isConnected transient property
self.isConnected_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.isConnected_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure symbolName transient property
self.symbolName_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.symbolName_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
}
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// TransientObject PadProxyInDevice
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
final class TransientObject_PadProxyInDevice : ReadOnlyObject_PadProxyInDevice {
//····················································································································
// Data provider
//····················································································································
private var mDataProvider : ReadOnlyObject_PadProxyInDevice? = nil
private var mTransientKind : PropertyKind = .empty
//····················································································································
func setDataProvider (_ inProvider : ReadOnlyObject_PadProxyInDevice?) {
if self.mDataProvider !== inProvider {
self.mDataProvider?.detachClient (self)
self.mDataProvider = inProvider
self.mDataProvider?.attachClient (self)
}
}
//····················································································································
override func notifyModelDidChange () {
let newObject : PadProxyInDevice?
if let dataProvider = self.mDataProvider {
switch dataProvider.selection {
case .empty :
newObject = nil
self.mTransientKind = .empty
case .single (let v) :
newObject = v
self.mTransientKind = .single
case .multiple :
newObject = nil
self.mTransientKind = .empty
}
}else{
newObject = nil
self.mTransientKind = .empty
}
self.mInternalValue = newObject
super.notifyModelDidChange ()
}
//····················································································································
override var selection : EBSelection < PadProxyInDevice? > {
switch self.mTransientKind {
case .empty :
return .empty
case .single :
if let internalValue = self.mInternalValue {
return .single (internalValue)
}else{
return .empty
}
case .multiple :
return .multiple
}
}
//····················································································································
override var propval : PadProxyInDevice? { return self.mInternalValue }
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ReadWriteObject_PadProxyInDevice
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
class ReadWriteObject_PadProxyInDevice : ReadOnlyObject_PadProxyInDevice {
//····················································································································
func setProp (_ inValue : PadProxyInDevice?) { } // Abstract method
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// Proxy: ProxyObject_PadProxyInDevice
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
final class ProxyObject_PadProxyInDevice : ReadWriteObject_PadProxyInDevice {
//····················································································································
private var mModel : ReadWriteObject_PadProxyInDevice? = nil
//····················································································································
func setModel (_ inModel : ReadWriteObject_PadProxyInDevice?) {
if self.mModel !== inModel {
self.mModel?.detachClient (self)
self.mModel = inModel
self.mModel?.attachClient (self)
}
}
//····················································································································
override func notifyModelDidChange () {
let newModel : PadProxyInDevice?
if let model = self.mModel {
switch model.selection {
case .empty :
newModel = nil
case .single (let v) :
newModel = v
case .multiple :
newModel = nil
}
}else{
newModel = nil
}
self.mInternalValue = newModel
super.notifyModelDidChange ()
}
//····················································································································
override func setProp (_ inValue : PadProxyInDevice?) {
self.mModel?.setProp (inValue)
}
//····················································································································
override var selection : EBSelection < PadProxyInDevice? > {
if let model = self.mModel {
return model.selection
}else{
return .empty
}
}
//····················································································································
override var propval : PadProxyInDevice? {
if let model = self.mModel {
switch model.selection {
case .empty, .multiple :
return nil
case .single (let v) :
return v
}
}else{
return nil
}
}
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// StoredObject_PadProxyInDevice
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
final class StoredObject_PadProxyInDevice : ReadWriteObject_PadProxyInDevice, EBSignatureObserverProtocol, EBObservableObjectProtocol {
//····················································································································
init (usedForSignature inUsedForSignature : Bool) {
mUsedForSignature = inUsedForSignature
super.init ()
}
//····················································································································
// Signature ?
//····················································································································
private let mUsedForSignature : Bool
//····················································································································
// Undo manager
//····················································································································
weak final var ebUndoManager : EBUndoManager? = nil // SOULD BE WEAK
//····················································································································
// Opposite relationship management
//····················································································································
private var mSetOppositeRelationship : Optional < (_ inManagedObject : PadProxyInDevice) -> Void > = nil
private var mResetOppositeRelationship : Optional < (_ inManagedObject : PadProxyInDevice) -> Void > = nil
//····················································································································
func setOppositeRelationShipFunctions (setter inSetter : @escaping (_ inManagedObject : PadProxyInDevice) -> Void,
resetter inResetter : @escaping (_ inManagedObject : PadProxyInDevice) -> Void) {
self.mSetOppositeRelationship = inSetter
self.mResetOppositeRelationship = inResetter
}
//····················································································································
#if BUILD_OBJECT_EXPLORER
var mValueExplorer : NSButton? {
didSet {
if let unwrappedExplorer = self.mValueExplorer {
switch self.selection {
case .empty, .multiple :
break ;
case .single (let v) :
updateManagedObjectToOneRelationshipDisplay (object: v, button: unwrappedExplorer)
}
}
}
}
#endif
//····················································································································
// Model will change
//····················································································································
override func notifyModelDidChangeFrom (oldValue inOldValue : PadProxyInDevice?) {
//--- Register old value in undo manager
self.ebUndoManager?.registerUndo (withTarget: self) { $0.mInternalValue = inOldValue }
//---
if let object = inOldValue {
if self.mUsedForSignature {
object.setSignatureObserver (observer: nil)
}
self.mResetOppositeRelationship? (object)
}
//---
if let object = self.mInternalValue {
if self.mUsedForSignature {
object.setSignatureObserver (observer: self)
}
self.mSetOppositeRelationship? (object)
}
//---
super.notifyModelDidChangeFrom (oldValue: inOldValue)
}
//····················································································································
// Model did change
//····················································································································
override func notifyModelDidChange () {
//--- Update explorer
#if BUILD_OBJECT_EXPLORER
if let valueExplorer = self.mValueExplorer {
updateManagedObjectToOneRelationshipDisplay (object: self.mInternalValue, button: valueExplorer)
}
#endif
//--- Notify observers
self.postEvent ()
self.clearSignatureCache ()
//---
super.notifyModelDidChange ()
}
//····················································································································
override var selection : EBSelection < PadProxyInDevice? > {
if let object = self.mInternalValue {
return .single (object)
}else{
return .empty
}
}
//····················································································································
override func setProp (_ inValue : PadProxyInDevice?) { self.mInternalValue = inValue }
//····················································································································
override var propval : PadProxyInDevice? { return self.mInternalValue }
//····················································································································
// signature
//····················································································································
private weak var mSignatureObserver : EBSignatureObserverProtocol? = nil // SOULD BE WEAK
//····················································································································
private var mSignatureCache : UInt32? = nil
//····················································································································
final func setSignatureObserver (observer inObserver : EBSignatureObserverProtocol?) {
self.mSignatureObserver?.clearSignatureCache ()
self.mSignatureObserver = inObserver
inObserver?.clearSignatureCache ()
self.clearSignatureCache ()
}
//····················································································································
final func signature () -> UInt32 {
let computedSignature : UInt32
if let s = self.mSignatureCache {
computedSignature = s
}else{
computedSignature = self.computeSignature ()
self.mSignatureCache = computedSignature
}
return computedSignature
}
//····················································································································
final private func computeSignature () -> UInt32 {
var crc : UInt32 = 0
if let object = self.mInternalValue {
crc.accumulateUInt32 (object.signature ())
}
return crc
}
//····················································································································
final func clearSignatureCache () {
if self.mSignatureCache != nil {
self.mSignatureCache = nil
self.mSignatureObserver?.clearSignatureCache ()
}
}
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
| 40.065574 | 135 | 0.391725 |
bb46f7edc9c18e607a1e57bb9409842a7898c5ce | 5,808 | //
// UIImage+StripeCore.swift
// StripeCore
//
// Created by Brian Dorfman on 4/25/17.
// Copyright © 2017 Stripe, Inc. All rights reserved.
//
import AVFoundation
import UIKit
@_spi(STP) public typealias ImageDataAndSize = (imageData: Data, imageSize: CGSize)
extension UIImage {
@_spi(STP) public static let defaultCompressionQuality: CGFloat = 0.5
/**
Encodes the image to jpeg at the specified compression quality. The image
will be scaled down, if needed, to ensure its size does not exceed
`maxBytes`.
:nodoc:
- Parameters:
- maxBytes: The maximum size of the allowed file. If value is nil, then
the image will not be scaled down.
- compressionQuality: The compression quality to use when encoding the jpeg.
- Returns: A tuple containing the following properties.
- `imageData`: Data object of the jpeg encoded image.
- `imageSize`: The dimensions of the the image that was encoded.
This size may be smaller than the original image size if the image
needed to be scaled down to fit the specified `maxBytes`.
*/
@_spi(STP) public func jpegDataAndDimensions(
maxBytes: Int? = nil,
compressionQuality: CGFloat = defaultCompressionQuality
) -> ImageDataAndSize {
dataAndDimensions(maxBytes: maxBytes, compressionQuality: compressionQuality) { image, quality in
image.jpegData(compressionQuality: quality)
}
}
/**
Encodes the image to heic at the specified compression quality. The image
will be scaled down, if needed, to ensure its size does not exceed
`maxBytes`.
:nodoc:
- Parameters:
- maxBytes: The maximum size of the allowed file. If value is nil, then
the image will not be scaled down.
- compressionQuality: The compression quality to use when encoding the jpeg.
- Returns: A tuple containing the following properties.
- `imageData`: Data object of the jpeg encoded image.
- `imageSize`: The dimensions of the the image that was encoded.
This size may be smaller than the original image size if the image
needed to be scaled down to fit the specified `maxBytes`.
*/
@_spi(STP) public func heicDataAndDimensions(
maxBytes: Int? = nil,
compressionQuality: CGFloat = defaultCompressionQuality
) -> ImageDataAndSize {
dataAndDimensions(maxBytes: maxBytes, compressionQuality: compressionQuality) { image, quality in
image.heicData(compressionQuality: quality)
}
}
@_spi(STP) public func resized(to scale: CGFloat) -> UIImage? {
let newImageSize = CGSize(
width: CGFloat(floor(size.width * scale)),
height: CGFloat(floor(size.height * scale))
)
UIGraphicsBeginImageContextWithOptions(newImageSize, false, self.scale)
defer {
UIGraphicsEndImageContext()
}
draw(in: CGRect(x: 0, y: 0, width: newImageSize.width, height: newImageSize.height))
return UIGraphicsGetImageFromCurrentImageContext()
}
private func heicData(compressionQuality: CGFloat = UIImage.defaultCompressionQuality) -> Data? {
[self].heicData(compressionQuality: compressionQuality)
}
private func dataAndDimensions(
maxBytes: Int? = nil,
compressionQuality: CGFloat = defaultCompressionQuality,
imageDataProvider: ((_ image: UIImage, _ quality: CGFloat) -> Data?)
) -> ImageDataAndSize {
var imageData = imageDataProvider(self, compressionQuality)
guard let _ = imageData else {
return (imageData: Data(), imageSize: .zero)
}
var newImageSize = self.size
// Try something smarter first
if let maxBytes = maxBytes,
(imageData?.count ?? 0) > maxBytes {
var scale = CGFloat(1.0)
// Assuming jpeg file size roughly scales linearly with area of the image
// which is ~correct (although breaks down at really small file sizes)
let percentSmallerNeeded = CGFloat(maxBytes) / CGFloat((imageData?.count ?? 0))
// Shrink to a little bit less than we need to try to ensure we're under
// (otherwise its likely our first pass will be over the limit due to
// compression variance and floating point rounding)
scale = scale * (percentSmallerNeeded - (percentSmallerNeeded * 0.05))
repeat {
if let newImage = resized(to: scale) {
newImageSize = newImage.size
imageData = imageDataProvider(newImage, compressionQuality)
}
// If the smart thing doesn't work, just start scaling down a bit on a loop until we get there
scale = scale * 0.7
} while (imageData?.count ?? 0) > maxBytes
}
return (imageData: imageData!, imageSize: newImageSize)
}
}
extension Array where Element: UIImage {
@_spi(STP) public func heicData(compressionQuality: CGFloat = UIImage.defaultCompressionQuality) -> Data? {
guard let mutableData = CFDataCreateMutable(nil, 0) else {
return nil
}
guard let destination = CGImageDestinationCreateWithData(mutableData, AVFileType.heic as CFString, self.count, nil) else {
return nil
}
let properties = [kCGImageDestinationLossyCompressionQuality: compressionQuality] as CFDictionary
for image in self {
let cgImage = image.cgImage!
CGImageDestinationAddImage(destination, cgImage, properties)
}
if CGImageDestinationFinalize(destination) {
return mutableData as Data
}
return nil
}
}
| 37.470968 | 130 | 0.649966 |
21c8409dadf4277e9f46494aca48a3b765b381f1 | 326 | //: [Previous](@previous)
/*:
# Contiguous Strings
Proposal: [SE-0247](https://github.com/apple/swift-evolution/blob/master/proposals/0247-contiguous-strings.md)
“Contiguous strings” are strings that are capable of providing a pointer and length to validly encoded UTF-8 contents in constant time.
*/
//: [Next](@next)
| 29.636364 | 136 | 0.739264 |
08ca12e6044e1abdb00b8aa92d3fbdd9afaaf8c4 | 8,696 | // NotificationView.swift
// biin
// Created by Esteban Padilla on 3/6/15.
// Copyright (c) 2015 Esteban Padilla. All rights reserved.
import Foundation
import UIKit
class NotificationView: BNView {
var delegate:NotificationView_Delegate?
// var gift:BNGift?
var image:BNUIImageView?
var imageRequested = false
var removeItButton:BNUIButton_Delete?
var titleLbl:UILabel?
var messageLbl:UILabel?
var receivedLbl:UILabel?
//weak var notification:BNNotification?
var background:UIView?
var showSwipe:UISwipeGestureRecognizer?
var hideSwipe:UISwipeGestureRecognizer?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect, father:BNView?) {
super.init(frame: frame, father:father )
}
convenience init(frame:CGRect, father:BNView?, notification:BNNotification?){
self.init(frame: frame, father:father )
// self.notification = notification
self.model = notification
var xpos:CGFloat = 5
var ypos:CGFloat = 5
var width:CGFloat = 1
let height:CGFloat = 1
self.backgroundColor = UIColor.whiteColor()
self.layer.masksToBounds = true
var decorationColor:UIColor?
decorationColor = UIColor.bnRed()
// var white:CGFloat = 0.0
// var alpha:CGFloat = 0.0
// _ = gift!.primaryColor!.getWhite(&white, alpha: &alpha)
//
// if white >= 0.95 {
// print("Is white - \(gift!.name!)")
// decorationColor = gift!.primaryColor
// } else {
// decorationColor = gift!.secondaryColor
// }
removeItButton = BNUIButton_Delete(frame: CGRectMake((frame.width - SharedUIManager.instance.notificationView_height), 0, SharedUIManager.instance.notificationView_height, SharedUIManager.instance.notificationView_height), iconColor: UIColor.whiteColor())
removeItButton!.backgroundColor = UIColor.redColor()
removeItButton!.icon!.position = CGPoint(x: ((SharedUIManager.instance.notificationView_height / 2) - 6), y: ((SharedUIManager.instance.notificationView_height / 2) - 6))
removeItButton!.addTarget(self, action: #selector(self.removeBtnAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(removeItButton!)
background = UIView(frame: frame)
background!.backgroundColor = UIColor.whiteColor()
self.addSubview(background!)
// if (model as! BNGift).media!.count > 0 {
image = BNUIImageView(frame: CGRectMake(xpos, ypos, SharedUIManager.instance.notificationView_imageSize, SharedUIManager.instance.notificationView_imageSize), color:UIColor.bnGrayLight())
background!.addSubview(image!)
image!.layer.cornerRadius = 3
image!.layer.masksToBounds = true
requestImage()
// }
xpos = (SharedUIManager.instance.notificationView_imageSize + 10)
ypos = 5
receivedLbl = UILabel(frame: CGRect(x: xpos, y: ypos, width: frame.width, height: height))
receivedLbl!.text = notification!.receivedDate!.bnDisplayDateFormatt_by_Day().uppercaseString
receivedLbl!.textColor = UIColor.bnGray()
receivedLbl!.font = UIFont(name: "Lato-Regular", size: 10)
receivedLbl!.textAlignment = NSTextAlignment.Left
receivedLbl!.numberOfLines = 0
receivedLbl!.sizeToFit()
background!.addSubview(receivedLbl!)
ypos += (receivedLbl!.frame.height)
width = (frame.width - (xpos + 5))
titleLbl = UILabel(frame: CGRect(x: xpos, y: ypos, width: width, height: height))
titleLbl!.text = notification!.title!
titleLbl!.textColor = decorationColor
titleLbl!.font = UIFont(name: "Lato-Black", size: SharedUIManager.instance.notificationView_TitleSize)
titleLbl!.textAlignment = NSTextAlignment.Left
titleLbl!.numberOfLines = 1
titleLbl!.sizeToFit()
background!.addSubview(titleLbl!)
ypos += (titleLbl!.frame.height)
width = (frame.width - (xpos + 5))
messageLbl = UILabel(frame: CGRect(x: xpos, y: ypos, width:width, height: height))
messageLbl!.text = notification!.text!
messageLbl!.textColor = UIColor.bnGrayDark()
messageLbl!.font = UIFont(name: "Lato-Regular", size: SharedUIManager.instance.notificationView_TextSize)
messageLbl!.textAlignment = NSTextAlignment.Left
messageLbl!.numberOfLines = 2
messageLbl!.sizeToFit()
background!.addSubview(messageLbl!)
showSwipe = UISwipeGestureRecognizer(target: self, action: #selector(self.showRemoveBtn(_:)))
showSwipe!.direction = UISwipeGestureRecognizerDirection.Left
background!.addGestureRecognizer(showSwipe!)
hideSwipe = UISwipeGestureRecognizer(target: self, action: #selector(self.hideRemoveBtn(_:)))
hideSwipe!.direction = UISwipeGestureRecognizerDirection.Right
hideSwipe!.enabled = false
background!.addGestureRecognizer(hideSwipe!)
}
func showRemoveBtn(sender:UISwipeGestureRecognizer) {
delegate!.hideOtherViewsOpen!(self)
sender.enabled = false
UIView.animateWithDuration(0.25, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {() -> Void in
self.background?.frame.origin.x -= SharedUIManager.instance.notificationView_height
}, completion: {(completed:Bool) -> Void in
self.hideSwipe!.enabled = true
})
}
func hideRemoveBtn(sender:UISwipeGestureRecognizer) {
delegate!.removeFromOtherViewsOpen!(self)
sender.enabled = false
UIView.animateWithDuration(0.25, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 5.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {() -> Void in
self.background?.frame.origin.x += SharedUIManager.instance.notificationView_height
}, completion: {(completed:Bool) -> Void in
self.showSwipe!.enabled = true
})
}
override func transitionIn() {
}
override func transitionOut( state:BNState? ) {
}
override func setNextState(goto:BNGoto){
//Start transition on root view controller
father!.setNextState(goto)
}
override func showUserControl(value:Bool, son:BNView, point:CGPoint){
if father == nil {
}else{
father!.showUserControl(value, son:son, point:point)
}
}
override func updateUserControl(position:CGPoint){
if father == nil {
}else{
father!.updateUserControl(position)
}
}
func requestImage(){
if imageRequested { return }
imageRequested = true
// if (model as! BNGift).media!.count > 0 {
BNAppSharedManager.instance.networkManager.requestImageData("https://biinapp.blob.core.windows.net/dev-biinmedia/e7071cce-36c1-4511-aca7-3f2c59835834/ca17d10603e5-4e5d-bf20-65f1ccf20ede.jpeg", image: image)
// } else {
// image!.image = UIImage(named: "noImage.jpg")
// image!.showAfterDownload()
// }
}
override func refresh() {
}
override func clean(){
delegate = nil
model = nil
image?.removeFromSuperview()
image = nil
removeItButton?.removeFromSuperview()
removeItButton = nil
titleLbl!.removeFromSuperview()
titleLbl = nil
messageLbl!.removeFromSuperview()
messageLbl = nil
receivedLbl!.removeFromSuperview()
receivedLbl = nil
}
func removeBtnAction(sender:UIButton){
self.delegate!.resizeScrollOnRemoved!(self.model!.identifier!)
BNAppSharedManager.instance.updateNotificationCounter()
}
func showAsRead(){
titleLbl!.textColor = UIColor.bnGray()
messageLbl!.textColor = UIColor.bnGray()
}
}
@objc protocol NotificationView_Delegate:NSObjectProtocol {
optional func resizeScrollOnRemoved(identifier:String)
optional func hideOtherViewsOpen(view:NotificationView)
optional func removeFromOtherViewsOpen(view:NotificationView)
} | 37.162393 | 263 | 0.641674 |
f4c6271a3877044b2c513a79118398b9c2fd0f54 | 4,322 | //
// Assert No Failure.swift
// PublisherKit
//
// Created by Raghav Ahuja on 29/03/20.
//
extension Publisher {
/// Raises a fatal error when its upstream publisher fails, and otherwise republishes all received input.
///
/// Use this function for internal sanity checks that are active during testing but do not impact performance of shipping code.
///
/// - Parameters:
/// - prefix: A string used at the beginning of the fatal error message.
/// - file: A filename used in the error message. This defaults to `#file`.
/// - line: A line number used in the error message. This defaults to `#line`.
/// - Returns: A publisher that raises a fatal error when its upstream publisher fails.
public func assertNoFailure(_ prefix: String = "", file: StaticString = #file, line: UInt = #line) -> Publishers.AssertNoFailure<Self> {
Publishers.AssertNoFailure(upstream: self, prefix: prefix, file: file, line: line)
}
}
extension Publishers {
/// A publisher that raises a fatal error upon receiving any failure, and otherwise republishes all received input.
///
/// Use this function for internal sanity checks that are active during testing but do not impact performance of shipping code.
public struct AssertNoFailure<Upstream: Publisher>: Publisher {
public typealias Output = Upstream.Output
public typealias Failure = Never
/// The publisher from which this publisher receives elements.
public let upstream: Upstream
/// The string used at the beginning of the fatal error message.
public let prefix: String
/// The filename used in the error message.
public let file: StaticString
/// The line number used in the error message.
public let line: UInt
public init(upstream: Upstream, prefix: String, file: StaticString, line: UInt) {
self.upstream = upstream
self.prefix = prefix
self.file = file
self.line = line
}
public func receive<S: Subscriber>(subscriber: S) where Output == S.Input, Failure == S.Failure {
upstream.subscribe(Inner(downstream: subscriber, prefix: prefix, file: file, line: line))
}
}
}
extension Publishers.AssertNoFailure {
// MARK: ASSERT NO FAILURE SINK
private struct Inner<Downstream: Subscriber>: Subscriber, CustomStringConvertible, CustomPlaygroundDisplayConvertible, CustomReflectable where Output == Downstream.Input, Failure == Downstream.Failure {
typealias Input = Upstream.Output
typealias Failure = Upstream.Failure
private let downstream: Downstream
private let prefix: String
private let file: StaticString
private let line: UInt
let combineIdentifier = CombineIdentifier()
init(downstream: Downstream, prefix: String, file: StaticString, line: UInt) {
self.downstream = downstream
self.prefix = prefix
self.file = file
self.line = line
}
func receive(subscription: Subscription) {
downstream.receive(subscription: subscription)
}
func receive(_ input: Input) -> Subscribers.Demand {
downstream.receive(input)
}
func receive(completion: Subscribers.Completion<Failure>) {
switch completion {
case .finished:
downstream.receive(completion: .finished)
case .failure(let error):
let prefixString = prefix.isEmpty ? "" : "\(prefix): "
preconditionFailure("\(prefixString)\(error)", file: file, line: line)
}
}
var description: String {
"AssertNoFailure"
}
var playgroundDescription: Any { return description }
var customMirror: Mirror {
let children: [Mirror.Child] = [
("file", file),
("line", line),
("prefix", prefix)
]
return Mirror(self, children: children)
}
}
}
| 36.016667 | 206 | 0.599954 |
2917c35da2d40285003558d27f3ef32281341837 | 5,687 | #if MIXBOX_ENABLE_IN_APP_SERVICES
import UIKit
public extension CGSize {
// MARK: - Insets
// Shrink size with insets, resulting size will be smaller
func mb_shrinked(_ insets: UIEdgeInsets) -> CGSize {
return CGSize(
width: width - insets.mb_width,
height: height - insets.mb_height
)
}
// Extend size with insets, resulting size will be bigger
func mb_extended(_ insets: UIEdgeInsets) -> CGSize {
return mb_shrinked(insets.mb_inverted())
}
// MARK: - Intersection
// Intersect two sizes (imagine intersection between two rectangles with x = width, y = height)
// Resulting size will be smaller than self and other or equal
func mb_intersection(_ other: CGSize) -> CGSize {
return CGSize(
width: min(width, other.width),
height: min(height, other.height)
)
}
func mb_intersectionHeight(_ height: CGFloat) -> CGSize {
return CGSize(
width: width,
height: min(self.height, height)
)
}
func mb_intersectionWidth(_ width: CGFloat) -> CGSize {
return CGSize(
width: min(self.width, width),
height: height
)
}
func mb_intersectionHeight(_ other: CGSize) -> CGSize {
return mb_intersectionHeight(other.height)
}
func mb_intersectionWidth(_ other: CGSize) -> CGSize {
return mb_intersectionWidth(other.width)
}
// MARK: - Union
// Resulting size will be bigger than self and other or equal
func mb_union(_ other: CGSize) -> CGSize {
return CGSize(
width: max(width, other.width),
height: max(height, other.height)
)
}
func mb_unionWidth(_ width: CGFloat) -> CGSize {
return CGSize(
width: max(self.width, width),
height: height
)
}
func mb_unionHeight(_ height: CGFloat) -> CGSize {
return CGSize(
width: width,
height: max(self.height, height)
)
}
func mb_unionWidth(_ other: CGSize) -> CGSize {
return mb_unionWidth(other.width)
}
func mb_unionHeight(_ other: CGSize) -> CGSize {
return mb_unionHeight(other.height)
}
// MARK: - Substraction
// Substract components of CGSize (width and height)
func mb_minus(_ other: CGSize) -> CGSize {
return CGSize(width: width - other.width, height: height - other.height)
}
func mb_minusHeight(_ height: CGFloat) -> CGSize {
return CGSize(width: width, height: self.height - height)
}
func mb_minusWidth(_ width: CGFloat) -> CGSize {
return CGSize(width: self.width - width, height: height)
}
func mb_minusHeight(_ other: CGSize) -> CGSize {
return mb_minusHeight(other.height)
}
func mb_minusWidth(_ other: CGSize) -> CGSize {
return mb_minusWidth(other.width)
}
// MARK: - Multiplication
func mb_multiply(_ factor: CGFloat) -> CGSize {
return CGSize(width: width * factor, height: height * factor)
}
// MARK: - Addition
// Sum components of CGSize (width and height)
func mb_plus(_ other: CGSize) -> CGSize {
return CGSize(
width: width + other.width,
height: height + other.height
)
}
func mb_plusHeight(_ height: CGFloat) -> CGSize {
return CGSize(
width: width,
height: self.height + height
)
}
func mb_plusWidth(_ width: CGFloat) -> CGSize {
return CGSize(
width: self.width + width,
height: height
)
}
func mb_plusHeight(_ other: CGSize) -> CGSize {
return mb_plusHeight(other.height)
}
func mb_plusWidth(_ other: CGSize) -> CGSize {
return mb_plusWidth(other.width)
}
// MARK: - Rounding
func mb_ceil() -> CGSize {
return CGSize(
width: CoreGraphics.ceil(width),
height: CoreGraphics.ceil(height)
)
}
func mb_floor() -> CGSize {
return CGSize(
width: CoreGraphics.floor(width),
height: CoreGraphics.floor(height)
)
}
var mb_area: CGFloat {
return width * height
}
func mb_hasZeroArea() -> Bool {
return width == 0 || height == 0
}
}
public func +(left: CGSize, right: CGSize) -> CGSize {
return CGSize(
width: left.width + right.width,
height: left.height + right.height
)
}
public func -(left: CGSize, right: CGSize) -> CGSize {
return CGSize(
width: left.width - right.width,
height: left.height - right.height
)
}
public func +(left: CGVector, right: CGSize) -> CGSize {
return CGSize(
width: left.dx + right.width,
height: left.dy + right.height
)
}
@_transparent
public func +(left: CGSize, right: CGVector) -> CGSize {
return right + left
}
public func *(left: CGFloat, right: CGSize) -> CGSize {
return CGSize(
width: left * right.width,
height: left * right.height
)
}
@_transparent
public func *(left: CGSize, right: CGFloat) -> CGSize {
return right * left
}
public func /(left: CGSize, right: CGFloat) -> CGSize {
return CGSize(
width: left.width / right,
height: left.height / right
)
}
public func /(left: CGSize, right: CGSize) -> CGVector {
return CGVector(
dx: left.width / right.width,
dy: left.height / right.height
)
}
#endif
| 25.275556 | 99 | 0.576226 |
fe384f9f5e324ce1b6c58cca9357a18ef23f7257 | 590 | //
// BoolExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 07/12/2016.
// Copyright © 2016 SwifterSwift
//
// MARK: - Properties
public extension Bool {
/// SwifterSwift: Return 1 if true, or 0 if false.
///
/// false.int -> 0
/// true.int -> 1
///
var int: Int {
return self ? 1 : 0
}
/// SwifterSwift: Return "true" if true, or "false" if false.
///
/// false.string -> "false"
/// true.string -> "true"
///
var string: String {
return self ? "true" : "false"
}
}
| 19.032258 | 65 | 0.50339 |
715f935f1b028eb10df280e941909538dc0f1c54 | 553 | //
// VenueViewModel.swift
// FoursquarePlaces
//
// Created by Ali Elsokary on 23/12/2021.
//
//
import Foundation
class VenueViewModel: Equatable {
let id: String
let name: String
let address: String
let distance: Int
let category: String
init(id: String, name: String, address: String, distance: Int, category: String) {
self.id = id
self.name = name
self.address = address
self.distance = distance
self.category = category
}
static func == (lhs: VenueViewModel, rhs: VenueViewModel) -> Bool {
lhs.name == rhs.name
}
}
| 17.83871 | 83 | 0.687161 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.