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
ed8b2bedd4a70d186df3673b20442b3d806964d5
2,383
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public extension UIImage { /** Creates a new image with the passed in color. - Parameter color: The UIColor to create the image from. - Returns: A UIImage that is the color passed in. */ public func tintWithColor(color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, MaterialDevice.scale) let context = UIGraphicsGetCurrentContext() CGContextScaleCTM(context, 1.0, -1.0) CGContextTranslateCTM(context, 0.0, -size.height) CGContextSetBlendMode(context, .Multiply) let rect = CGRectMake(0, 0, size.width, size.height) CGContextClipToMask(context, rect, CGImage) color.setFill() CGContextFillRect(context, rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
41.086207
86
0.772556
2273cbaebdeea2dfba08eff20ea12653e0c6196f
398
// // ViewController.swift // GooeyEffectSampleDEMO // // Created by Anton Nechayuk on 17.07.18. // Copyright © 2018 Anton Nechayuk. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let movementShow = GooeyMovementShower(frame: self.view.frame) view.addSubview(movementShow) } }
19.9
70
0.693467
08f03a1ae498df56653dd5272a2ceb98c9d29c66
4,259
// // ViewController.swift // SwiftToolbox // // Created by Lucas Costa Araujo on 11/06/2021. // Copyright (c) 2021 Lucas Costa Araujo. All rights reserved. // import UIKit import LASwiftToolbox class ViewController: STGenericTableViewController { lazy var viewModel: ViewModel? = { let viewModel = ViewModel() viewModel.controller = self return viewModel }() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewModel?.loadInfo() } override func buildTable() { super.buildTable() // Build methods, it helps to see the which comes first buildSideButtonsExample() buildOptionalCell() buildTableExample() reload() } func buildOptionalCell() { add(cell: STBaseGenericCell.self) { cell in let isOn = self.viewModel?.isTurnedOn ?? false cell.textLabel?.textAlignment = .center cell.textLabel?.numberOfLines = 0 cell.textLabel?.text = isOn ? "This is on 🌞 \n(click me!)" : "This is off 🌚 \n(click me!)" cell.didClick = { _ in // toggle logic self.viewModel?.isTurnedOn = !(self.viewModel?.isTurnedOn ?? false) // Rebuild the whole table self.buildTable() } } if viewModel?.isTurnedOn == true { add(cell: STBaseGenericCell.self) { cell in cell.textLabel?.text = "This cell is optional :), if the condition does not succeed, you can build again and this will not be on the table anymore." cell.textLabel?.numberOfLines = 0 cell.textLabel?.textAlignment = .center } } } func buildTableExample() { if viewModel?.messages.isEmpty == true { add(cell: STBaseGenericCell.self) { cell in cell.textLabel?.text = "Loading fake messages... :)" cell.textLabel?.numberOfLines = 0 cell.textLabel?.textAlignment = .center } } else { addSection(height: 50) { section in let customHeader = UIView() customHeader.backgroundColor = .systemBlue.withAlphaComponent(0.35) let label = UILabel(frame: CGRect(x: 24, y: 0, width: 200, height: 50)) customHeader.addSubview(label) label.textColor = .white label.text = "Custom header view" return customHeader } addTable(cell: UITableViewCell.self, count: viewModel?.messages.count ?? 0) { index, cell in let msg = self.viewModel?.messages[index.row] cell.textLabel?.text = msg cell.textLabel?.numberOfLines = 0 } } } func buildSideButtonsExample() { // System Section addSection(title: "As a System Section", height: 40) let builder = add(cell: UITableViewCell.self) // Separate config block builder.buildCell = { cell in cell.textLabel?.text = "Side buttons example (swipe both sides <- ->)" cell.textLabel?.numberOfLines = 0 cell.contentView.backgroundColor = .systemGreen.withAlphaComponent(0.2) } // Separate config block builder.leadingEdit = { let action = UIContextualAction(style: .normal, title: "Print") { _, _, completion in debugPrint("Hello world") completion(true) } let actions = UISwipeActionsConfiguration(actions: [action]) return actions } // Separate config block builder.trailingEdit = { let action = UIContextualAction(style: .normal, title: "Another Print") { _, _, completion in debugPrint("Hello world2") completion(true) } let actions = UISwipeActionsConfiguration(actions: [action]) return actions } } }
33.273438
164
0.54379
01b8a4b54052bda9b3f84f59c1ed1244570c65b9
1,790
// // URLSessionBasedCallOperation.swift // PCloudSDKSwift // // Created by Todor Pitekov on 03/01/2017 // Copyright © 2017 pCloud LTD. All rights reserved. // import Foundation /// Concrete implementation of `CallOperation` backed by a `URLSessionDataTask`. public final class URLSessionBasedCallOperation: URLSessionBasedNetworkOperation<Call.Response> { /// Initializes an operation with a task. /// /// - parameter task: A backing data task in a suspended state. public init(task: URLSessionDataTask) { super.init(task: task) // Assign callbacks. var responseBody = Data() didReceiveData = { data in // Build response data. responseBody.append(data) } didComplete = { [weak self] error in guard let me = self, !me.isCancelled else { return } if let error = error, me.errorIsCancellation(error) { return } // Compute response. let response: Call.Response = { if let error = error { return .failure(.clientError(error)) } do { let json = try JSONSerialization.jsonObject(with: responseBody, options: []) as! [String: Any] return .success(json) } catch { return .failure(.clientError(error)) } }() // Complete. me.complete(response: response) } } } extension URLSessionBasedCallOperation: CallOperation { public var response: Call.Response? { return taskResponse } @discardableResult public func addCompletionBlock(with queue: DispatchQueue?, _ block: @escaping (Call.Response) -> Void) -> URLSessionBasedCallOperation { addCompletionHandler((block, queue)) return self } } extension URLSessionBasedCallOperation: CustomStringConvertible { public var description: String { return "\(state), id=\(id), response=\(response as Any)" } }
23.866667
137
0.691061
b9c727479e990ef4a5aa32e5e26a0a7e3d95c701
5,518
// // PickerViewController+TimeAndSecond.swift // XBDatePicker // // Created by xiaobin liu on 2020/3/26. // Copyright © 2020 CocoaPods. All rights reserved. // import UIKit /// MARK - PickerViewController + TimeAndSecond extension PickerViewController { /// TimeAndSecond final class TimeAndSecond: NSObject {} } /// MARK - PickerViewControllerDataSource extension PickerViewController.TimeAndSecond: PickerViewControllerDataSource { /// 初始化 /// - Parameter contentView: <#contentView description#> public func initData(_ contentView: PickerViewController) { contentView.calculateHoursList() guard let temSelectDate = contentView.selectDate else { contentView.calculateMinuteList() contentView.calculateSecondList() return } do { contentView.calculateHoursIndex(temSelectDate) contentView.calculateMinuteList() contentView.calculateMinuteIndex(temSelectDate) contentView.calculateSecondList() contentView.calculateSecondIndex(temSelectDate) } } /// 默认选中 public func pickerDefaultSelected(_ contentView: PickerViewController) { contentView.selectRow(contentView.hoursIndex, inComponent: 0, animated: true) contentView.selectRow(contentView.minuteIndex, inComponent: 1, animated: true) contentView.selectRow(contentView.secondIndex, inComponent: 2, animated: true) } /// 选择器宽度 /// - Parameters: /// - contentView: contentView /// - component: component public func pickerContentView(_ contentView: PickerViewController, widthForComponent component: Int) -> CGFloat { return 100 } /// 每列多少个 /// /// - Parameters: /// - contentView: contentView description /// - component: component description /// - Returns: return value description public func pickerContentView(_ contentView: PickerViewController, numberOfRowsInComponent component: Int) -> Int { switch component { case 0: return contentView.hoursList.count case 1: return contentView.minuteList.count default: return contentView.secondList.count } } /// 每一列展示的内容 /// /// - Parameters: /// - contentView: contentView description /// - row: row description /// - component: component description /// - Returns: return value description public func pickerContentView(_ contentView: PickerViewController, titleForRow row: Int, forComponent component: Int) -> String { switch component { case 0: return contentView.hoursList[row].name case 1: return contentView.minuteList[row].name default: return contentView.secondList[row].name } } } /// MARK - PickerViewControllerDelegate extension PickerViewController.TimeAndSecond: PickerViewControllerDelegate { /// 选中索引 /// /// - Parameters: /// - contentView: contentView description /// - row: row description /// - component: component description public func pickerContentView(_ contentView: PickerViewController, didSelectRow row: Int, inComponent component: Int) { switch component { case 0: let minuteString = contentView.minuteList[contentView.minuteIndex].id let secondString = contentView.secondList[contentView.secondIndex].id contentView.hoursIndex = row do { /// 重新计算分数组以及索引 contentView.calculateMinuteList() contentView.reloadComponent(1) contentView.minuteIndex = contentView.minuteList.firstIndex(of: PickerDateModel(id: minuteString, name: "")) ?? 0 contentView.selectRow(contentView.minuteIndex, inComponent: 1, animated: false) } do { /// 重新计算秒数组以及索引 contentView.calculateSecondList() contentView.reloadComponent(2) contentView.secondIndex = contentView.secondList.firstIndex(of: PickerDateModel(id: secondString, name: "")) ?? 0 contentView.selectRow(contentView.secondIndex, inComponent: 2, animated: false) } case 1: let secondString = contentView.secondList[contentView.secondIndex].id contentView.minuteIndex = row do { /// 重新计算秒数组以及索引 contentView.calculateSecondList() contentView.reloadComponent(2) contentView.secondIndex = contentView.secondList.firstIndex(of: PickerDateModel(id: secondString, name: "")) ?? 0 contentView.selectRow(contentView.secondIndex, inComponent: 2, animated: false) } default: contentView.secondIndex = row } } /// 获取日期字符串 /// /// - Parameters: /// - contentView: contentView description /// - row: row description /// - component: component description func pickerContentView(_ contentView: PickerViewController) -> String { return "\(contentView.hoursList[contentView.hoursIndex].id):\(contentView.minuteList[contentView.minuteIndex].id):\(contentView.secondList[contentView.secondIndex].id)" } }
34.704403
176
0.624139
bb3f18d0133e82d16c9c16b2f20676f0b40d5ef0
31,585
// Created by Bryan Keller on 2/6/20. // Copyright © 2020 Airbnb Inc. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit // MARK: - VisibleItemsProvider /// Provides details about the current set of visible items. final class VisibleItemsProvider { // MARK: Lifecycle init( calendar: Calendar, content: CalendarViewContent, size: CGSize, scale: CGFloat, monthHeaderHeight: CGFloat) { self.content = content layoutItemTypeEnumerator = LayoutItemTypeEnumerator( calendar: calendar, monthsLayout: content.monthsLayout, monthRange: content.monthRange) frameProvider = FrameProvider( content: content, size: size, scale: scale, monthHeaderHeight: monthHeaderHeight) } // MARK: Internal let content: CalendarViewContent var size: CGSize { frameProvider.size } var scale: CGFloat { frameProvider.scale } func anchorMonthHeaderItem( for month: Month, offset: CGPoint, scrollPosition: CalendarViewScrollPosition) -> LayoutItem { let baseMonthFrame = frameProvider.frameOfMonth(month, withOrigin: offset) let finalMonthFrame = translatedFrame(baseMonthFrame, for: scrollPosition, offset: offset) let finalFrame = frameProvider.frameOfMonthHeader(inMonthWithOrigin: finalMonthFrame.origin) return LayoutItem(itemType: .monthHeader(month), frame: finalFrame) } func anchorDayItem( for day: Day, offset: CGPoint, scrollPosition: CalendarViewScrollPosition) -> LayoutItem { let baseFrame = frameProvider.frameOfDay(day, inMonthWithOrigin: offset) let finalFrame = translatedFrame(baseFrame, for: scrollPosition, offset: offset) return LayoutItem(itemType: .day(day), frame: finalFrame) } func detailsForVisibleItems( surroundingPreviouslyVisibleLayoutItem previouslyVisibleLayoutItem: LayoutItem, inBounds bounds: CGRect) -> VisibleItemsDetails { var visibleItems = Set<VisibleCalendarItem>() var centermostLayoutItem = previouslyVisibleLayoutItem var firstVisibleDay: Day? var lastVisibleDay: Day? var framesForVisibleMonths = [Month: CGRect]() var framesForVisibleDays = [Day: CGRect]() var minimumScrollOffset: CGFloat? var maximumScrollOffset: CGFloat? var heightOfPinnedContent = CGFloat(0) // Default the initial capacity to 100, which is approximately enough room for 3 months worth of // calendar items. var calendarItemCache = Dictionary<VisibleCalendarItem.ItemType, AnyCalendarItem>( minimumCapacity: previousCalendarItemCache?.capacity ?? 100) // `extendedBounds` is used to make sure that we're always laying out a continuous set of items, // even if the last anchor item is completely off screen. // // When scrolling at a normal speed, the `bounds` will intersect with the // `previouslyVisibleLayoutItem`. When scrolling extremely fast, however, it's possible for the // `bounds` to have moved far enough in one frame that `previouslyVisibleLayoutItem` does not // intersect with it. // // One can think of `extendedBounds`'s purpose as increasing the layout region to compensate // for extremely fast scrolling / large per-frame bounds differences. let minX = min(bounds.minX, previouslyVisibleLayoutItem.frame.minX) let minY = min(bounds.minY, previouslyVisibleLayoutItem.frame.minY) let maxX = max(bounds.maxX, previouslyVisibleLayoutItem.frame.maxX) let maxY = max(bounds.maxY, previouslyVisibleLayoutItem.frame.maxY) let extendedBounds = CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY) var numberOfConsecutiveNonIntersectingItems = 0 var handledDayRanges = Set<DayRange>() var originsForMonths = [Month: CGPoint]() var lastHandledLayoutItemEnumeratingBackwards = previouslyVisibleLayoutItem var lastHandledLayoutItemEnumeratingForwards = previouslyVisibleLayoutItem layoutItemTypeEnumerator.enumerateItemTypes( startingAt: previouslyVisibleLayoutItem.itemType, itemTypeHandlerLookingBackwards: { itemType, shouldStop in let layoutItem = self.layoutItem( for: itemType, lastHandledLayoutItem: lastHandledLayoutItemEnumeratingBackwards, originsForMonths: &originsForMonths) lastHandledLayoutItemEnumeratingBackwards = layoutItem handleLayoutItem( layoutItem, inBounds: bounds, extendedBounds: extendedBounds, isLookingBackwards: true, numberOfConsecutiveNonIntersectingItems: &numberOfConsecutiveNonIntersectingItems, centermostLayoutItem: &centermostLayoutItem, firstVisibleDay: &firstVisibleDay, lastVisibleDay: &lastVisibleDay, framesForVisibleMonths: &framesForVisibleMonths, framesForVisibleDays: &framesForVisibleDays, minimumScrollOffset: &minimumScrollOffset, maximumScrollOffset: &maximumScrollOffset, visibleItems: &visibleItems, calendarItemCache: &calendarItemCache, originsForMonths: &originsForMonths, handledDayRanges: &handledDayRanges, shouldStop: &shouldStop) }, itemTypeHandlerLookingForwards: { itemType, shouldStop in let layoutItem = self.layoutItem( for: itemType, lastHandledLayoutItem: lastHandledLayoutItemEnumeratingForwards, originsForMonths: &originsForMonths) lastHandledLayoutItemEnumeratingForwards = layoutItem handleLayoutItem( layoutItem, inBounds: bounds, extendedBounds: extendedBounds, isLookingBackwards: false, numberOfConsecutiveNonIntersectingItems: &numberOfConsecutiveNonIntersectingItems, centermostLayoutItem: &centermostLayoutItem, firstVisibleDay: &firstVisibleDay, lastVisibleDay: &lastVisibleDay, framesForVisibleMonths: &framesForVisibleMonths, framesForVisibleDays: &framesForVisibleDays, minimumScrollOffset: &minimumScrollOffset, maximumScrollOffset: &maximumScrollOffset, visibleItems: &visibleItems, calendarItemCache: &calendarItemCache, originsForMonths: &originsForMonths, handledDayRanges: &handledDayRanges, shouldStop: &shouldStop) }) // Handle pinned day-of-week layout items if case .vertical(pinDaysOfWeekToTop: true) = content.monthsLayout { handlePinnedDaysOfWeekIfNeeded( yContentOffset: bounds.minY, calendarItemCache: &calendarItemCache, visibleItems: &visibleItems, heightOfPinnedContent: &heightOfPinnedContent) } let visibleDayRange: DayRange? if let firstVisibleDay = firstVisibleDay, let lastVisibleDay = lastVisibleDay { visibleDayRange = DayRange(uncheckedBounds: (firstVisibleDay, lastVisibleDay)) } else { visibleDayRange = nil } // Handle overlay items handleOverlayItemsIfNeeded( bounds: bounds, framesForVisibleMonths: framesForVisibleMonths, framesForVisibleDays: framesForVisibleDays, visibleItems: &visibleItems) previousCalendarItemCache = calendarItemCache return VisibleItemsDetails( visibleItems: visibleItems, centermostLayoutItem: centermostLayoutItem, visibleDayRange: visibleDayRange, framesForVisibleMonths: framesForVisibleMonths, framesForVisibleDays: framesForVisibleDays, minimumScrollOffset: minimumScrollOffset, maximumScrollOffset: maximumScrollOffset, heightOfPinnedContent: heightOfPinnedContent) } func visibleItemsForAccessibilityElements( surroundingPreviouslyVisibleLayoutItem previouslyVisibleLayoutItem: LayoutItem, visibleMonthRange: MonthRange) -> [VisibleCalendarItem] { var visibleItems = [VisibleCalendarItem]() let monthRange = MonthRange( uncheckedBounds: ( lower: calendar.month(byAddingMonths: -1, to: visibleMonthRange.lowerBound), upper: calendar.month(byAddingMonths: 1, to: visibleMonthRange.upperBound))) let handleItem: (LayoutItem, Bool, inout Bool) -> Void = { layoutItem, isLookingBackwards, shouldStop in let month: Month let calendarItem: AnyCalendarItem switch layoutItem.itemType { case .monthHeader(let _month): month = _month calendarItem = self.content.monthHeaderItemProvider(month) case .day(let day): month = day.month calendarItem = self.content.dayItemProvider(day) case .dayOfWeekInMonth: return } guard monthRange.contains(month) else { shouldStop = true return } let item = VisibleCalendarItem( calendarItem: calendarItem, itemType: .layoutItemType(layoutItem.itemType), frame: layoutItem.frame) if isLookingBackwards { visibleItems.insert(item, at: 0) } else { visibleItems.append(item) } } var originsForMonths = [Month: CGPoint]() var lastHandledLayoutItemEnumeratingBackwards = previouslyVisibleLayoutItem var lastHandledLayoutItemEnumeratingForwards = previouslyVisibleLayoutItem layoutItemTypeEnumerator.enumerateItemTypes( startingAt: previouslyVisibleLayoutItem.itemType, itemTypeHandlerLookingBackwards: { itemType, shouldStop in let layoutItem = self.layoutItem( for: itemType, lastHandledLayoutItem: lastHandledLayoutItemEnumeratingBackwards, originsForMonths: &originsForMonths) lastHandledLayoutItemEnumeratingBackwards = layoutItem handleItem(layoutItem, true, &shouldStop) }, itemTypeHandlerLookingForwards: { itemType, shouldStop in let layoutItem = self.layoutItem( for: itemType, lastHandledLayoutItem: lastHandledLayoutItemEnumeratingForwards, originsForMonths: &originsForMonths) lastHandledLayoutItemEnumeratingForwards = layoutItem handleItem(layoutItem, false, &shouldStop) }) return visibleItems } // MARK: Private // For horizontally laid out calendars, we will encounter off-screen items before once again // encountering on-screen items. For example, when the edge of a month becomes visible on the // trailing edge of the screen, only the first day of each week in that month will intersect the // visible bounds. This constant is used to ensure that we don't stop looking for visible items // too early. private static let numberOfConsecutiveNonIntersectingItemsToConsider = 12 private let layoutItemTypeEnumerator: LayoutItemTypeEnumerator private let frameProvider: FrameProvider private var previousCalendarItemCache: [VisibleCalendarItem.ItemType: AnyCalendarItem]? private var calendar: Calendar { content.calendar } // Returns the layout item closest to the center of `bounds`. private func centermostLayoutItem( comparing item: LayoutItem, to otherItem: LayoutItem, inBounds bounds: CGRect) -> LayoutItem { let itemMidpoint = CGPoint(x: item.frame.midX, y: item.frame.midY) let otherItemMidpoint = CGPoint(x: otherItem.frame.midX, y: otherItem.frame.midY) let boundsMidpoint = CGPoint(x: bounds.midX, y: bounds.midY) let itemDistance = itemMidpoint.distance(to: boundsMidpoint) let otherItemDistance = otherItemMidpoint.distance(to: boundsMidpoint) return itemDistance < otherItemDistance ? item : otherItem } private func monthOrigin( forMonthContaining layoutItem: LayoutItem, originsForMonths: inout [Month: CGPoint]) -> CGPoint { let monthOrigin: CGPoint if let origin = originsForMonths[layoutItem.itemType.month] { monthOrigin = origin } else { monthOrigin = frameProvider.originOfMonth(containing: layoutItem) } originsForMonths[layoutItem.itemType.month] = monthOrigin return monthOrigin } private func monthOrigin( for itemType: LayoutItem.ItemType, lastHandledLayoutItem: LayoutItem, originsForMonths: inout [Month: CGPoint]) -> CGPoint { // Cache the month origin for `lastHandledLayoutItem`, if necessary if originsForMonths[lastHandledLayoutItem.itemType.month] == nil { let monthOrigin = frameProvider.originOfMonth(containing: lastHandledLayoutItem) originsForMonths[lastHandledLayoutItem.itemType.month] = monthOrigin } // Get (and cache) the month origin for the current item let monthOrigin: CGPoint if let origin = originsForMonths[itemType.month] { monthOrigin = origin } else if itemType.month < lastHandledLayoutItem.itemType.month, let origin = originsForMonths[lastHandledLayoutItem.itemType.month] { monthOrigin = frameProvider.originOfMonth(itemType.month, beforeMonthWithOrigin: origin) } else if itemType.month > lastHandledLayoutItem.itemType.month, let origin = originsForMonths[lastHandledLayoutItem.itemType.month] { monthOrigin = frameProvider.originOfMonth(itemType.month, afterMonthWithOrigin: origin) } else { preconditionFailure(""" Could not determine the origin of the month containing the layout item type \(itemType). """) } originsForMonths[itemType.month] = monthOrigin return monthOrigin } private func layoutItem( for itemType: LayoutItem.ItemType, lastHandledLayoutItem: LayoutItem, originsForMonths: inout [Month: CGPoint]) -> LayoutItem { let monthOrigin = self.monthOrigin( for: itemType, lastHandledLayoutItem: lastHandledLayoutItem, originsForMonths: &originsForMonths) // Get the frame for the current item let frame: CGRect switch itemType { case .monthHeader: frame = frameProvider.frameOfMonthHeader(inMonthWithOrigin: monthOrigin) case .dayOfWeekInMonth(let position, _): frame = frameProvider.frameOfDayOfWeek(at: position, inMonthWithOrigin: monthOrigin) case .day(let day): // If we're laying out a day in the same month as a previously laid out day, we can use the // faster `frameOfDay(_:adjacentTo:withFrame:inMonthWithOrigin:)` function. if case .day(let lastHandledDay) = lastHandledLayoutItem.itemType, day.month == lastHandledDay.month, abs(day.day - lastHandledDay.day) == 1 { frame = frameProvider.frameOfDay( day, adjacentTo: lastHandledDay, withFrame: lastHandledLayoutItem.frame, inMonthWithOrigin: monthOrigin) } else { frame = frameProvider.frameOfDay(day, inMonthWithOrigin: monthOrigin) } } return LayoutItem(itemType: itemType, frame: frame) } // Builds a `DayRangeLayoutContext` by getting frames for each day layout item in the prodvided // `dayRange`, using the provided `day` and `frame` as a starting point. private func dayRangeLayoutContext( for dayRange: DayRange, containing day: Day, withFrame frame: CGRect, originsForMonths: inout [Month: CGPoint]) -> DayRangeLayoutContext { guard dayRange.contains(day) else { preconditionFailure(""" Cannot create day range items if the provided `day` (\(day)) is not contained in `dayRange` (\(dayRange)). """) } var daysAndFrames = [(day: Day, frame: CGRect)]() var boundingUnionRectOfDayFrames = frame let handleItem: (LayoutItem, Bool, inout Bool) -> Void = { layoutItem, isLookingBackwards, shouldStop in guard case .day(let day) = layoutItem.itemType else { return } guard dayRange.contains(day) else { shouldStop = true return } let frame = layoutItem.frame if isLookingBackwards { daysAndFrames.insert((day, frame), at: 0) } else { daysAndFrames.append((day, frame)) } boundingUnionRectOfDayFrames = boundingUnionRectOfDayFrames.union(frame) } let dayLayoutItem = LayoutItem(itemType: .day(day), frame: frame) var lastHandledLayoutItemEnumeratingBackwards = dayLayoutItem var lastHandledLayoutItemEnumeratingForwards = dayLayoutItem layoutItemTypeEnumerator.enumerateItemTypes( startingAt: dayLayoutItem.itemType, itemTypeHandlerLookingBackwards: { itemType, shouldStop in let layoutItem = self.layoutItem( for: itemType, lastHandledLayoutItem: lastHandledLayoutItemEnumeratingBackwards, originsForMonths: &originsForMonths) lastHandledLayoutItemEnumeratingBackwards = layoutItem handleItem(layoutItem, true, &shouldStop) }, itemTypeHandlerLookingForwards: { itemType, shouldStop in let layoutItem = self.layoutItem( for: itemType, lastHandledLayoutItem: lastHandledLayoutItemEnumeratingForwards, originsForMonths: &originsForMonths) lastHandledLayoutItemEnumeratingForwards = layoutItem handleItem(layoutItem, false, &shouldStop) }) let frameToBoundsTransform = CGAffineTransform( translationX: -boundingUnionRectOfDayFrames.minX, y: -boundingUnionRectOfDayFrames.minY) return DayRangeLayoutContext( daysAndFrames: daysAndFrames.map { ( $0.day, $0.frame.applying(frameToBoundsTransform).alignedToPixels(forScreenWithScale: scale) ) }, boundingUnionRectOfDayFrames: boundingUnionRectOfDayFrames .applying(frameToBoundsTransform) .alignedToPixels(forScreenWithScale: scale), frame: boundingUnionRectOfDayFrames) } private func overlayLayoutContext( for overlaidItemLocation: CalendarViewContent.OverlaidItemLocation, inBounds bounds: CGRect, framesForVisibleMonths: [Month: CGRect], framesForVisibleDays: [Day: CGRect]) -> CalendarViewContent.OverlayLayoutContext? { let itemFrame: CGRect switch overlaidItemLocation { case .monthHeader(let date): let month = calendar.month(containing: date) guard let monthFrame = framesForVisibleMonths[month] else { return nil } itemFrame = frameProvider.frameOfMonthHeader(inMonthWithOrigin: monthFrame.origin) case .day(let date): let day = calendar.day(containing: date) guard let dayFrame = framesForVisibleDays[day] else { return nil } itemFrame = dayFrame } return .init( overlaidItemLocation: overlaidItemLocation, overlaidItemFrame: CGRect( origin: CGPoint(x: itemFrame.minX - bounds.minX, y: itemFrame.minY - bounds.minY), size: itemFrame.size) .alignedToPixels(forScreenWithScale: scale), availableBounds: CGRect(origin: .zero, size: bounds.size)) } // Handles a layout item by creating a visible calendar item and adding it to the `visibleItems` // set if it's in `bounds`. This function also handles any visible items associated with the // provided `layoutItem`. For example, an individual `day` layout item may also have an associated // selection layer visible item, or a day range visible item. private func handleLayoutItem( _ layoutItem: LayoutItem, inBounds bounds: CGRect, extendedBounds: CGRect, isLookingBackwards: Bool, numberOfConsecutiveNonIntersectingItems: inout Int, centermostLayoutItem: inout LayoutItem, firstVisibleDay: inout Day?, lastVisibleDay: inout Day?, framesForVisibleMonths: inout [Month: CGRect], framesForVisibleDays: inout [Day: CGRect], minimumScrollOffset: inout CGFloat?, maximumScrollOffset: inout CGFloat?, visibleItems: inout Set<VisibleCalendarItem>, calendarItemCache: inout [VisibleCalendarItem.ItemType: AnyCalendarItem], originsForMonths: inout [Month: CGPoint], handledDayRanges: inout Set<DayRange>, shouldStop: inout Bool) { if layoutItem.frame.intersects(extendedBounds) { numberOfConsecutiveNonIntersectingItems = 0 handleBoundaryItemsIfNeeded( for: layoutItem, minimumScrollOffset: &minimumScrollOffset, maximumScrollOffset: &maximumScrollOffset) // Handle items that actually intersect the visible bounds if layoutItem.frame.intersects(bounds) { let itemType = VisibleCalendarItem.ItemType.layoutItemType(layoutItem.itemType) let calendarItem: AnyCalendarItem switch layoutItem.itemType { case .monthHeader(let month): calendarItem = calendarItemCache.value( for: itemType, missingValueProvider: { previousCalendarItemCache?[itemType] ?? content.monthHeaderItemProvider(month) }) case let .dayOfWeekInMonth(dayOfWeekPosition, month): calendarItem = calendarItemCache.value( for: itemType, missingValueProvider: { let weekdayIndex = calendar.weekdayIndex(for: dayOfWeekPosition) return previousCalendarItemCache?[itemType] ?? content.dayOfWeekItemProvider(month, weekdayIndex) }) case .day(let day): calendarItem = calendarItemCache.value( for: itemType, missingValueProvider: { previousCalendarItemCache?[itemType] ?? content.dayItemProvider(day) }) handleDayRangesContaining( day, withFrame: layoutItem.frame, inBounds: bounds, visibleItems: &visibleItems, handledDayRanges: &handledDayRanges, originsForMonths: &originsForMonths) // Take into account the pinned days of week header when determining the first visible day if !content.monthsLayout.pinDaysOfWeekToTop || layoutItem.frame.maxY > (bounds.minY + frameProvider.daySize.height) { firstVisibleDay = min(firstVisibleDay ?? day, day) } lastVisibleDay = max(lastVisibleDay ?? day, day) if framesForVisibleMonths[day.month] == nil { let monthOrigin = frameProvider.originOfMonth(containing: layoutItem) let monthFrame = frameProvider.frameOfMonth(day.month, withOrigin: monthOrigin) framesForVisibleMonths[day.month] = monthFrame } if framesForVisibleDays[day] == nil { framesForVisibleDays[day] = layoutItem.frame } } let visibleItem = VisibleCalendarItem( calendarItem: calendarItem, itemType: .layoutItemType(layoutItem.itemType), frame: layoutItem.frame) visibleItems.insert(visibleItem) centermostLayoutItem = self.centermostLayoutItem( comparing: layoutItem, to: centermostLayoutItem, inBounds: bounds) } } else { numberOfConsecutiveNonIntersectingItems += 1 switch content.monthsLayout { case .vertical: shouldStop = true case .horizontal: if numberOfConsecutiveNonIntersectingItems > Self.numberOfConsecutiveNonIntersectingItemsToConsider { shouldStop = true } } } } private func handleBoundaryItemsIfNeeded( for layoutItem: LayoutItem, minimumScrollOffset: inout CGFloat?, maximumScrollOffset: inout CGFloat?) { switch content.monthsLayout { case .vertical(let pinDaysOfWeekToTop): switch layoutItem.itemType { case .monthHeader(let monthAndYear): if monthAndYear == content.monthRange.lowerBound { // The month header of the first month will determine our minimum scroll offset minimumScrollOffset = layoutItem.frame.minY - (pinDaysOfWeekToTop ? frameProvider.daySize.height : 0) } case .day(let day): // The last day of the last month will determine our maximum scroll offset let lastDate = calendar.lastDate(of: content.monthRange.upperBound) if day == calendar.day(containing: lastDate) { maximumScrollOffset = layoutItem.frame.maxY + content.monthDayInsets.bottom } default: break } case .horizontal: switch layoutItem.itemType { case .monthHeader(let monthAndYear): if monthAndYear == content.monthRange.lowerBound { // The month header of the first month will determine our minimum scroll offset minimumScrollOffset = layoutItem.frame.minX } if monthAndYear == content.monthRange.upperBound { // The month header of the last month will determine our minimum scroll offset maximumScrollOffset = layoutItem.frame.maxX } default: break } } } // Handles each unhandled day range containing the provided `day` from // `content.dayRangesWithCalendarItems`. private func handleDayRangesContaining( _ day: Day, withFrame frame: CGRect, inBounds bounds: CGRect, visibleItems: inout Set<VisibleCalendarItem>, handledDayRanges: inout Set<DayRange>, originsForMonths: inout [Month: CGPoint]) { // Handle day ranges that start or end with the current day. for dayRange in content.dayRangesAndItemProvider?.dayRanges ?? [] { guard !handledDayRanges.contains(dayRange), dayRange.contains(day) else { continue } let layoutContext = dayRangeLayoutContext( for: dayRange, containing: day, withFrame: frame, originsForMonths: &originsForMonths) handleDayRange(dayRange, with: layoutContext, inBounds: bounds, visibleItems: &visibleItems) handledDayRanges.insert(dayRange) } } // Handles a day range item by creating a visible calendar item and adding it to the // `visibleItems` set. private func handleDayRange( _ dayRange: DayRange, with dayRangeLayoutContext: DayRangeLayoutContext, inBounds bounds: CGRect, visibleItems: inout Set<VisibleCalendarItem>) { guard let dayRangeItemProvider = content.dayRangesAndItemProvider?.dayRangeItemProvider else { preconditionFailure( "`content.dayRangesAndItemProvider` cannot be nil when handling a day range.") } let frame = dayRangeLayoutContext.frame let dayRangeLayoutContext = CalendarViewContent.DayRangeLayoutContext( daysAndFrames: dayRangeLayoutContext.daysAndFrames, boundingUnionRectOfDayFrames: dayRangeLayoutContext.boundingUnionRectOfDayFrames) visibleItems.insert( VisibleCalendarItem( calendarItem: dayRangeItemProvider(dayRangeLayoutContext) , itemType: .dayRange(dayRange), frame: frame)) } private func handlePinnedDaysOfWeekIfNeeded( yContentOffset: CGFloat, calendarItemCache: inout [VisibleCalendarItem.ItemType: AnyCalendarItem], visibleItems: inout Set<VisibleCalendarItem>, heightOfPinnedContent: inout CGFloat) { var hasUpdatesHeightOfPinnedContent = false for dayOfWeekPosition in DayOfWeekPosition.allCases { let itemType = VisibleCalendarItem.ItemType.pinnedDayOfWeek(dayOfWeekPosition) let frame = frameProvider.frameOfPinnedDayOfWeek( at: dayOfWeekPosition, yContentOffset: yContentOffset) visibleItems.insert( VisibleCalendarItem( calendarItem: calendarItemCache.value( for: itemType, missingValueProvider: { let weekdayIndex = calendar.weekdayIndex(for: dayOfWeekPosition) return previousCalendarItemCache?[itemType] ?? content.dayOfWeekItemProvider(nil, weekdayIndex) }), itemType: itemType, frame: frame)) if !hasUpdatesHeightOfPinnedContent { heightOfPinnedContent += frame.height hasUpdatesHeightOfPinnedContent = true } } } private func handleOverlayItemsIfNeeded( bounds: CGRect, framesForVisibleMonths: [Month: CGRect], framesForVisibleDays: [Day: CGRect], visibleItems: inout Set<VisibleCalendarItem>) { guard let (overlaidItemLocations, itemProvider) = content.overlaidItemLocationsAndItemProvider else { return } for overlaidItemLocation in overlaidItemLocations { guard let layoutContext = overlayLayoutContext( for: overlaidItemLocation, inBounds: bounds, framesForVisibleMonths: framesForVisibleMonths, framesForVisibleDays: framesForVisibleDays) else { continue } visibleItems.insert( VisibleCalendarItem( calendarItem: itemProvider(layoutContext), itemType: .overlayItem(overlaidItemLocation), frame: bounds)) } } private func translatedFrame( _ frame: CGRect, for scrollPosition: CalendarViewScrollPosition, offset: CGPoint) -> CGRect { switch content.monthsLayout { case .vertical(let pinDaysOfWeekToTop): let additionalOffset = (pinDaysOfWeekToTop ? frameProvider.daySize.height : 0) let minY = offset.y + additionalOffset let maxY = offset.y + size.height let firstFullyVisibleY = minY let lastFullyVisibleY = maxY - frame.height let y: CGFloat switch scrollPosition { case .centered: y = minY + ((maxY - minY) / 2) - (frame.height / 2) case .firstFullyVisiblePosition(let padding): y = firstFullyVisibleY + padding case .lastFullyVisiblePosition(let padding): y = lastFullyVisibleY - padding } return CGRect(x: frame.minX, y: y, width: frame.width, height: frame.height) case .horizontal: let minX = offset.x let maxX = offset.x + size.width let firstFullyVisibleX = minX let lastFullyVisibleX = maxX - frame.width let x: CGFloat switch scrollPosition { case .centered: x = minX + ((maxX - minX) / 2) - (frame.width / 2) case .firstFullyVisiblePosition(let padding): x = firstFullyVisibleX + padding case .lastFullyVisiblePosition(let padding): x = lastFullyVisibleX - padding } return CGRect(x: x, y: frame.minY, width: frame.width, height: frame.height) } } } // MARK: - VisibleItemsDetails struct VisibleItemsDetails { let visibleItems: Set<VisibleCalendarItem> let centermostLayoutItem: LayoutItem let visibleDayRange: DayRange? let framesForVisibleMonths: [Month: CGRect] let framesForVisibleDays: [Day: CGRect] let minimumScrollOffset: CGFloat? let maximumScrollOffset: CGFloat? let heightOfPinnedContent: CGFloat } // MARK: - DayRangeLayoutContext /// Similar to `CalendarViewContent.DayRangeLayoutContext`, but also includes the `frame` of the day range visible item. private struct DayRangeLayoutContext { let daysAndFrames: [(day: Day, frame: CGRect)] let boundingUnionRectOfDayFrames: CGRect let frame: CGRect } // MARK: CGPoint Distance Extension private extension CGPoint { func distance(to otherPoint: CGPoint) -> CGFloat { sqrt(pow(otherPoint.x - x, 2) + pow(otherPoint.y - y, 2)) } }
36.055936
120
0.700712
62ba450f120fde25716b91faee821370516678c6
1,327
// // Created by Anton Spivak. // import Foundation import TSCBasic enum ProcessError: LocalizedError { case signalled(signal: Int32) case terminated(code: Int32, message: String) var errorDescription: String? { switch self { case .signalled(let signal): return "Process was killed by system: \(signal)" case .terminated(let code, let message): return "Process did exit with code: \(code), message: \(message)" } } static func rethrowIfNeeded(_ result: ProcessResult) throws { switch result.exitStatus { case let .signalled(signal): throw ProcessError.signalled(signal: signal) case let .terminated(code): guard code == 0 else { let message: String if let stderr = try? result.utf8stderrOutput(), !stderr.isEmpty { message = stderr } else if let output = try? result.utf8Output() { message = output } else { message = "No ouput." } throw ProcessError.terminated( code: code, message: message ) } break } } }
28.234043
81
0.508666
acbd03bc63303f4d539bed3c975c6b39310b1e70
1,268
// // Signature.swift // readium-lcp-swift // // Created by Alexandre Camilleri on 9/11/17. // // Copyright 2018 Readium Foundation. All rights reserved. // Use of this source code is governed by a BSD-style license which is detailed // in the LICENSE file present in the project repository where this source code is maintained. // import Foundation /// Signature allowing to certify the License Document integrity. public struct Signature { /// Algorithm used to calculate the signature, identified using the URIs given in [XML-SIG]. This MUST match the signature algorithm named in the Encryption Profile identified in `encryption/profile`. public let algorithm: String /// The Provider Certificate: an X509 certificate used by the Content Provider. public let certificate: String /// Value of the signature. public let value: String init(json: [String: Any]) throws { guard let algorithm = json["algorithm"] as? String, let certificate = json["certificate"] as? String, let value = json["value"] as? String else { throw ParsingError.signature } self.algorithm = algorithm self.certificate = certificate self.value = value } }
34.27027
204
0.682965
6220e862d0f7e934f2ceb1ff7d0c9b6cf496bf44
3,972
// // RecurrenceRule.swift // RRuleSwift // // Created by Xin Hong on 16/3/28. // Copyright © 2016年 Teambition. All rights reserved. // import EventKit import Foundation public struct RecurrenceRule { /// The calendar of recurrence rule. public var calendar: Calendar = Calendar.current /// The frequency of the recurrence rule. public var frequency: RecurrenceFrequency /// Specifies how often the recurrence rule repeats over the component of time indicated by its frequency. For example, a recurrence rule with a frequency type of RecurrenceFrequency.weekly and an interval of 2 repeats every two weeks. /// /// The default value of this property is 1. public var interval: Int = 1 /// Indicates which day of the week the recurrence rule treats as the first day of the week. /// /// The default value of this property is EKWeekday.monday. public var firstDayOfWeek: EKWeekday = .monday /// Indicates when the recurrence rule ends. This can be represented by an end date or a number of occurrences. public var recurrenceEnd: EKRecurrenceEnd? /// An array of ordinal integers that filters which recurrences to include in the recurrence rule’s frequency. Values can be from 1 to 366 and from -1 to -366. /// /// For example, if a bysetpos of -1 is combined with a RecurrenceFrequency.monthly frequency, and a byweekday of (EKWeekday.monday, EKWeekday.tuesday, EKWeekday.wednesday, EKWeekday.thursday, EKWeekday.friday), will result in the last work day of every month. /// /// Negative values indicate counting backwards from the end of the recurrence rule’s frequency. public var bysetpos: [Int] = [] /// The days of the year associated with the recurrence rule, as an array of integers. Values can be from 1 to 366 and from -1 to -366. /// /// Negative values indicate counting backwards from the end of the year. public var byyearday: [Int] = [] /// The months of the year associated with the recurrence rule, as an array of integers. Values can be from 1 to 12. public var bymonth: [Int] = [] /// The weeks of the year associated with the recurrence rule, as an array of integers. Values can be from 1 to 53 and from -1 to -53. According to ISO8601, the first week of the year is that containing at least four days of the new year. /// /// Negative values indicate counting backwards from the end of the year. public var byweekno: [Int] = [] /// The days of the month associated with the recurrence rule, as an array of integers. Values can be from 1 to 31 and from -1 to -31. /// /// Negative values indicate counting backwards from the end of the month. public var bymonthday: [Int] = [] /// The days of the week associated with the recurrence rule, as an array of EKWeekday objects. public var byweekday: [EKWeekday] = [] /// The hours of the day associated with the recurrence rule, as an array of integers. public var byhour: [Int] = [] /// The minutes of the hour associated with the recurrence rule, as an array of integers. public var byminute: [Int] = [] /// The seconds of the minute associated with the recurrence rule, as an array of integers. public var bysecond: [Int] = [] /// The inclusive dates of the recurrence rule. public var rdate: InclusionDate? /// The exclusion dates of the recurrence rule. The dates of this property will not be generated, even if some inclusive rdate matches the recurrence rule. public var exdate: ExclusionDate? public init(frequency: RecurrenceFrequency) { self.frequency = frequency } public init?(rruleString: String) { if let recurrenceRule: RecurrenceRule = RRule.ruleFromString(rruleString) { self = recurrenceRule } else { return nil } } public func toRRuleString() -> String { return RRule.stringFromRule(self) } }
43.173913
264
0.700151
e04ac52a4b8d8fac95f8eaebe4bc981088966be5
917
/// ``TheError`` for internal application state issues. /// /// ``InternalInconsistency`` error can occur when application state is invalid. public struct InternalInconsistency: TheError { /// Create instance of ``InternalInconsistency`` error. /// /// - Parameters: /// - message: Message associated with this error. /// - file: Source code file identifier. /// Filled automatically based on compile time constants. /// - line: Line in given source code file. /// Filled automatically based on compile time constants. /// - Returns: New instance of ``InternalInconsistency`` error with given context. public static func error( message: StaticString, file: StaticString = #fileID, line: UInt = #line ) -> Self { Self( context: .context( message: message, file: file, line: line ) ) } /// Source code context of this error. public var context: SourceCodeContext }
28.65625
83
0.689204
f91818caaa1bb4e2820e7c8c980af676ffcd4a26
1,372
// // ColorTheme.swift // TipCalculatorStarter // // Created by Tareq Mia on 7/26/20. // Copyright © 2020 Make School. All rights reserved. // import Foundation import UIKit struct ColorTheme { let isDefaultStatusBar: Bool let viewControllerBackgroundColor: UIColor let primaryColor: UIColor let primaryTextColor: UIColor let secondaryColor: UIColor let accentColor: UIColor let outputTextColor: UIColor static let light = ColorTheme(isDefaultStatusBar: true, viewControllerBackgroundColor: .tcOffWhite, primaryColor: .tcWhite, primaryTextColor: .tcSeafoamGreen, secondaryColor: .tcSeafoamGreen, accentColor: .tcSeafoamGreen, outputTextColor: .tcAlmostBlack) static let dark = ColorTheme(isDefaultStatusBar: false, viewControllerBackgroundColor: .tcAlmostBlack, primaryColor: .tcMediumBlack, primaryTextColor: .tcWhite, secondaryColor: .tcBlueBlack, accentColor: .tcSeafoamGreen, outputTextColor: .tcWhite) }
32.666667
79
0.544461
01204aa536c87c961a6061cbe79f5a9248a688d7
12,014
import EngagementSDK import UIKit public class WidgetTimelineViewController: UIViewController { struct Section { static let widgets = 0 static let loadMoreControl = 1 } private let cellReuseIdentifer: String = "myCell" public var session: ContentSession? { didSet { widgetModels.removeAll() self.tableView.reloadData() session?.getPostedWidgetModels(page: .first) { result in switch result { case let .success(widgetModels): guard let widgetModels = widgetModels else { return } self.widgetModels.append(contentsOf: widgetModels) widgetModels.forEach { self.widgetIsInteractableByID[$0.id] = false } DispatchQueue.main.async { self.tableView.reloadData() self.tableView.isHidden = false } case let .failure(error): print(error) } self.session?.delegate = self } } } public let tableView: UITableView = { let tableView = UITableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.allowsSelection = false tableView.separatorStyle = .none tableView.isHidden = true return tableView }() private let snapToLiveButton: UIImageView = { let snapToLiveButton = UIImageView() snapToLiveButton.translatesAutoresizingMaskIntoConstraints = false snapToLiveButton.alpha = 0.0 return snapToLiveButton }() private var snapToLiveBottomConstraint: NSLayoutConstraint! // Determines if the displayed widget should be interactable or not private var widgetIsInteractableByID: [String: Bool] = [:] private var widgetModels: [WidgetModel] = [] private let loadMoreCell: LoadMoreCell = { let loadMoreCell = LoadMoreCell() loadMoreCell.translatesAutoresizingMaskIntoConstraints = false loadMoreCell.activityIndicator.hidesWhenStopped = true loadMoreCell.button.setTitle("Load More...", for: .normal) return loadMoreCell }() public init() { super.init(nibName: nil, bundle: nil) } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func loadView() { super.loadView() view.addSubview(tableView) view.addSubview(snapToLiveButton) snapToLiveBottomConstraint = snapToLiveButton.bottomAnchor.constraint( equalTo: view.bottomAnchor, constant: -16 ) NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), snapToLiveButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16), snapToLiveBottomConstraint ]) } public override func viewDidLoad() { super.viewDidLoad() tableView.register(WidgetTableViewCell.self, forCellReuseIdentifier: cellReuseIdentifer) tableView.dataSource = self tableView.delegate = self loadMoreCell.button.addTarget(self, action: #selector(loadMoreButtonPressed), for: .touchUpInside) snapToLiveButton.addGestureRecognizer({ let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(snapToLive)) tapGestureRecognizer.numberOfTapsRequired = 1 return tapGestureRecognizer }()) } public func makeWidget(_ widgetModel: WidgetModel) -> Widget? { guard let widget = DefaultWidgetFactory.makeWidget(from: widgetModel) else { return nil } widget.delegate = self if widgetIsInteractableByID[widgetModel.id] ?? false { widget.moveToNextState() } else { widget.currentState = .finished } return widget } private func snapToLiveIsHidden(_ isHidden: Bool) { view.layoutIfNeeded() UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseInOut, animations: { self.snapToLiveBottomConstraint?.constant = isHidden ? self.snapToLiveButton.bounds.height : -16 self.view.layoutIfNeeded() self.snapToLiveButton.alpha = isHidden ? 0 : 1 }, completion: nil) } @objc func snapToLive() { tableView.scrollToRow(at: IndexPath(row: 0, section: Section.widgets), at: .top, animated: true) } } extension WidgetTimelineViewController: ContentSessionDelegate { public func playheadTimeSource(_ session: ContentSession) -> Date? { return nil } public func session(_ session: ContentSession, didChangeStatus status: SessionStatus) {} public func session(_ session: ContentSession, didReceiveError error: Error) {} public func chat(session: ContentSession, roomID: String, newMessage message: ChatMessage) {} public func widget(_ session: ContentSession, didBecomeReady widget: Widget) {} public func contentSession(_ session: ContentSession, didReceiveWidget widget: WidgetModel) { DispatchQueue.main.async { self.widgetModels.insert(widget, at: 0) self.widgetIsInteractableByID[widget.id] = true self.tableView.insertRows(at: [IndexPath(row: 0, section: Section.widgets)], with: .top) } } } extension WidgetTimelineViewController: UITableViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { if let firstVisibleRow = self.tableView.indexPathsForVisibleRows?.first?.row, firstVisibleRow > 0 { self.snapToLiveIsHidden(false) } else { self.snapToLiveIsHidden(true) } } } extension WidgetTimelineViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return 2 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == Section.widgets { return widgetModels.count } else { return 1 } } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == Section.widgets { guard let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifer) as? WidgetTableViewCell else { return UITableViewCell() } // prepare for reuse cell.widget?.removeFromParentViewController() cell.widget?.view.removeFromSuperview() cell.widget = nil let widgetModel = widgetModels[indexPath.row] if let widget = self.makeWidget(widgetModel) { addChildViewController(widget) widget.didMove(toParentViewController: self) widget.view.translatesAutoresizingMaskIntoConstraints = false cell.contentView.addSubview(widget.view) NSLayoutConstraint.activate([ widget.view.topAnchor.constraint(equalTo: cell.contentView.topAnchor), widget.view.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor), widget.view.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor), widget.view.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor) ]) widgetIsInteractableByID[widgetModel.id] = false cell.widget = widget } return cell } else { return loadMoreCell } } @objc private func loadMoreButtonPressed() { loadMoreCell.button.isHidden = true loadMoreCell.activityIndicator.startAnimating() session?.getPostedWidgetModels(page: .next) { result in switch result { case let .success(widgetModels): guard let widgetModels = widgetModels else { return } DispatchQueue.main.async { let indexPaths: [IndexPath] = widgetModels.enumerated().map { return IndexPath(row: self.widgetModels.count + $0.offset, section: Section.widgets) } self.widgetModels.append(contentsOf: widgetModels) widgetModels.forEach { self.widgetIsInteractableByID[$0.id] = false } self.tableView.insertRows(at: indexPaths, with: .none) self.loadMoreCell.button.isHidden = false self.loadMoreCell.activityIndicator.stopAnimating() } case let .failure(error): print(error) self.loadMoreCell.button.isHidden = false self.loadMoreCell.activityIndicator.stopAnimating() } } } } class WidgetTableViewCell: UITableViewCell { var widget: UIViewController? } extension WidgetTimelineViewController: WidgetViewDelegate { public func widgetDidEnterState(widget: WidgetViewModel, state: WidgetState) { switch state { case .ready: break case .interacting: widget.addTimer(seconds: widget.interactionTimeInterval ?? 5) { _ in widget.moveToNextState() } case .results: break case .finished: break } } public func widgetStateCanComplete(widget: WidgetViewModel, state: WidgetState) { switch state { case .ready: break case .interacting: break case .results: if widget.kind == .imagePredictionFollowUp || widget.kind == .textPredictionFollowUp { widget.addTimer(seconds: widget.interactionTimeInterval ?? 5) { _ in widget.moveToNextState() } } else { widget.moveToNextState() } case .finished: break } } public func userDidInteract(_ widget: WidgetViewModel) { } } class LoadMoreCell: UITableViewCell { let activityIndicator: UIActivityIndicatorView = { let activityIndicator = UIActivityIndicatorView() activityIndicator.translatesAutoresizingMaskIntoConstraints = false return activityIndicator }() let button: UIButton = { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false return button }() init() { super.init(style: .default, reuseIdentifier: nil) contentView.addSubview(activityIndicator) contentView.addSubview(button) NSLayoutConstraint.activate([ activityIndicator.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10), activityIndicator.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), activityIndicator.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), activityIndicator.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10), button.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10), button.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), button.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), button.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
37.661442
125
0.633095
eb164ba9e3f3e59cbc861eaa94965a9f8f161f62
2,707
/*: # Goat Latin https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/539/week-1-june-1st-june-7th/3350/ --- ### Problem Statement: A sentence `S` is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: + If a word begins with a vowel (a, e, i, o, or u), append `"ma"` to the end of the word. For example, the word 'apple' becomes 'applema'. + If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add `"ma"`. For example, the word` "goat"` becomes `"oatgma"`. + Add one letter `'a'` to the end of each word per its word index in the sentence, starting with 1. For example, the first word gets `"a"` added to the end, the second word gets `"aa"` added to the end and so on. Return the final sentence representing the conversion from `S` to Goat Latin. ### Example: ``` Input: "I speak Goat Latin" Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" Input: "The quick brown fox jumped over the lazy dog" Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" ``` ### Constraints: + S contains only uppercase, lowercase and spaces. Exactly one space between each word. + 1 <= S.length <= 150. */ import UIKit extension Character { var isVowel: Bool { switch self { case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U": return true default: return false } } } // 99 / 99 test cases passed. // Status: Accepted // Runtime: 16 ms // Memory Usage: 21.7 MB class Solution { func toGoatLatin(_ S: String) -> String { let words = S.components(separatedBy: " ") var resultString = "" var extraWord = "" for word in words { extraWord += "a" var convertedWord = word if !(word.first!.isVowel) { let first = convertedWord.removeFirst() convertedWord += String(first) } resultString += "\(convertedWord)ma\(extraWord) " } resultString.removeLast() return resultString } } let sol = Solution() sol.toGoatLatin("I speak Goat Latin") // Imaa peaksmaaa oatGmaaaa atinLmaaaaa // Output: // heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa sol.toGoatLatin("The quick brown fox jumped over the lazy dog")
29.423913
213
0.636129
140c051d0c702405db14dc58fdef00abd8057c47
1,359
// // AppDelegate.swift // Magic Ball 8 // // Created by Bülent Barış Kılıç on 3.08.2021. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.72973
179
0.745401
264d8723346d1496cc90f18cd9374fa5e4cad098
15,329
// // _TabBar.swift // // Created by Vincent Li on 2017/2/8. // Copyright (c) 2013-2017 _TabBarController (https://github.com/eggswift/_TabBarController) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit /// 对原生的UITabBarItemPositioning进行扩展,通过UITabBarItemPositioning设置时,系统会自动添加insets,这使得添加背景样式的需求变得不可能实现。_TabBarItemPositioning完全支持原有的item Position 类型,除此之外还支持完全fill模式。 /// /// - automatic: UITabBarItemPositioning.automatic /// - fill: UITabBarItemPositioning.fill /// - centered: UITabBarItemPositioning.centered /// - fillExcludeSeparator: 完全fill模式,布局不覆盖tabBar顶部分割线 /// - fillIncludeSeparator: 完全fill模式,布局覆盖tabBar顶部分割线 public enum _TabBarItemPositioning : Int { case automatic case fill case centered case fillExcludeSeparator case fillIncludeSeparator } /// 对UITabBarDelegate进行扩展,以支持UITabBarControllerDelegate的相关方法桥接 internal protocol _TabBarDelegate: NSObjectProtocol { /// 当前item是否支持选中 /// /// - Parameters: /// - tabBar: tabBar /// - item: 当前item /// - Returns: Bool func tabBar(_ tabBar: UITabBar, shouldSelect item: UITabBarItem) -> Bool /// 当前item是否需要被劫持 /// /// - Parameters: /// - tabBar: tabBar /// - item: 当前item /// - Returns: Bool func tabBar(_ tabBar: UITabBar, shouldHijack item: UITabBarItem) -> Bool /// 当前item的点击被劫持 /// /// - Parameters: /// - tabBar: tabBar /// - item: 当前item /// - Returns: Void func tabBar(_ tabBar: UITabBar, didHijack item: UITabBarItem) } /// _TabBar是高度自定义的UITabBar子类,通过添加UIControl的方式实现自定义tabBarItem的效果。目前支持tabBar的大部分属性的设置,例如delegate,items,selectedImge,itemPositioning,itemWidth,itemSpacing等,以后会更加细致的优化tabBar原有属性的设置效果。 open class _TabBar: UITabBar { internal weak var customDelegate: _TabBarDelegate? /// tabBar中items布局偏移量 public var itemEdgeInsets = UIEdgeInsets.zero /// 是否设置为自定义布局方式,默认为空。如果为空,则通过itemPositioning属性来设置。如果不为空则忽略itemPositioning,所以当tabBar的itemCustomPositioning属性不为空时,如果想改变布局规则,请设置此属性而非itemPositioning。 public var itemCustomPositioning: _TabBarItemPositioning? { didSet { if let itemCustomPositioning = itemCustomPositioning { switch itemCustomPositioning { case .fill: itemPositioning = .fill case .automatic: itemPositioning = .automatic case .centered: itemPositioning = .centered default: break } } self.reload() } } /// tabBar自定义item的容器view internal var containers = [_TabBarItemContainer]() /// 缓存当前tabBarController用来判断是否存在"More"Tab internal weak var tabBarController: UITabBarController? /// 自定义'More'按钮样式,继承自_TabBarItemContentView open var moreContentView: _TabBarItemContentView? = _TabBarItemMoreContentView.init() { didSet { self.reload() } } open override var items: [UITabBarItem]? { didSet { self.reload() } } open var isEditing: Bool = false { didSet { if oldValue != isEditing { self.updateLayout() } } } open override func setItems(_ items: [UITabBarItem]?, animated: Bool) { super.setItems(items, animated: animated) self.reload() } open override func beginCustomizingItems(_ items: [UITabBarItem]) { _TabBarController.printError("beginCustomizingItems(_:) is unsupported in _TabBar.") super.beginCustomizingItems(items) } open override func endCustomizing(animated: Bool) -> Bool { _TabBarController.printError("endCustomizing(_:) is unsupported in _TabBar.") return super.endCustomizing(animated: animated) } open override func layoutSubviews() { super.layoutSubviews() self.updateLayout() } open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { var b = super.point(inside: point, with: event) if !b { for container in containers { if container.point(inside: CGPoint.init(x: point.x - container.frame.origin.x, y: point.y - container.frame.origin.y), with: event) { b = true } } } return b } } internal extension _TabBar /* Layout */ { internal func updateLayout() { guard let tabBarItems = self.items else { _TabBarController.printError("empty items") return } let tabBarButtons = subviews.filter { subview -> Bool in if let cls = NSClassFromString("UITabBarButton") { return subview.isKind(of: cls) } return false } .sorted { (subview1, subview2) -> Bool in return subview1.frame.origin.x < subview2.frame.origin.x } if isCustomizing { for (idx, _) in tabBarItems.enumerated() { tabBarButtons[idx].isHidden = false moreContentView?.isHidden = true } for (_, container) in containers.enumerated(){ container.isHidden = true } } else { for (idx, item) in tabBarItems.enumerated() { if let _ = item as? _TabBarItem { tabBarButtons[idx].isHidden = true } else { tabBarButtons[idx].isHidden = false } if isMoreItem(idx), let _ = moreContentView { tabBarButtons[idx].isHidden = true } } for (_, container) in containers.enumerated(){ container.isHidden = false } } var layoutBaseSystem = true if let itemCustomPositioning = itemCustomPositioning { switch itemCustomPositioning { case .fill, .automatic, .centered: break case .fillIncludeSeparator, .fillExcludeSeparator: layoutBaseSystem = false } } if layoutBaseSystem { // System itemPositioning for (idx, container) in containers.enumerated(){ container.frame = tabBarButtons[idx].frame } } else { // Custom itemPositioning var x: CGFloat = itemEdgeInsets.left var y: CGFloat = itemEdgeInsets.top switch itemCustomPositioning! { case .fillExcludeSeparator: if y <= 0.0 { y += 1.0 } default: break } let width = bounds.size.width - itemEdgeInsets.left - itemEdgeInsets.right let height = bounds.size.height - y - itemEdgeInsets.bottom let eachWidth = itemWidth == 0.0 ? width / CGFloat(containers.count) : itemWidth let eachSpacing = itemSpacing == 0.0 ? 0.0 : itemSpacing for container in containers { container.frame = CGRect.init(x: x, y: y, width: eachWidth, height: height) x += eachWidth x += eachSpacing } } } } internal extension _TabBar /* Actions */ { internal func isMoreItem(_ index: Int) -> Bool { return _TabBarController.isShowingMore(tabBarController) && (index == (items?.count ?? 0) - 1) } internal func removeAll() { for container in containers { container.removeFromSuperview() } containers.removeAll() } internal func reload() { removeAll() guard let tabBarItems = self.items else { _TabBarController.printError("empty items") return } for (idx, item) in tabBarItems.enumerated() { let container = _TabBarItemContainer.init(self, tag: 1000 + idx) self.addSubview(container) self.containers.append(container) if let item = item as? _TabBarItem, let contentView = item.contentView { container.addSubview(contentView) } if self.isMoreItem(idx), let moreContentView = moreContentView { container.addSubview(moreContentView) } } self.setNeedsLayout() } internal func highlightAction(_ sender: AnyObject?) { guard let container = sender as? _TabBarItemContainer else { return } let newIndex = max(0, container.tag - 1000) guard newIndex < items?.count ?? 0, let item = self.items?[newIndex], item.isEnabled == true else { return } if (customDelegate?.tabBar(self, shouldSelect: item) ?? true) == false { return } if let item = item as? _TabBarItem { item.contentView?.highlight(animated: true, completion: nil) } else if self.isMoreItem(newIndex) { moreContentView?.highlight(animated: true, completion: nil) } } internal func dehighlightAction(_ sender: AnyObject?) { guard let container = sender as? _TabBarItemContainer else { return } let newIndex = max(0, container.tag - 1000) guard newIndex < items?.count ?? 0, let item = self.items?[newIndex], item.isEnabled == true else { return } if (customDelegate?.tabBar(self, shouldSelect: item) ?? true) == false { return } if let item = item as? _TabBarItem { item.contentView?.dehighlight(animated: true, completion: nil) } else if self.isMoreItem(newIndex) { moreContentView?.dehighlight(animated: true, completion: nil) } } internal func selectAction(_ sender: AnyObject?) { guard let container = sender as? _TabBarItemContainer else { return } select(itemAtIndex: container.tag - 1000, animated: true) } internal func select(itemAtIndex idx: Int, animated: Bool) { let newIndex = max(0, idx) let currentIndex = (selectedItem != nil) ? (items?.index(of: selectedItem!) ?? -1) : -1 guard newIndex < items?.count ?? 0, let item = self.items?[newIndex], item.isEnabled == true else { return } if (customDelegate?.tabBar(self, shouldSelect: item) ?? true) == false { return } if (customDelegate?.tabBar(self, shouldHijack: item) ?? false) == true { customDelegate?.tabBar(self, didHijack: item) if animated { if let item = item as? _TabBarItem { item.contentView?.select(animated: animated, completion: { item.contentView?.deselect(animated: false, completion: nil) }) } else if self.isMoreItem(newIndex) { moreContentView?.select(animated: animated, completion: { self.moreContentView?.deselect(animated: animated, completion: nil) }) } } return } if currentIndex != newIndex { if currentIndex != -1 && currentIndex < items?.count ?? 0{ if let currentItem = items?[currentIndex] as? _TabBarItem { currentItem.contentView?.deselect(animated: animated, completion: nil) } else if self.isMoreItem(currentIndex) { moreContentView?.deselect(animated: animated, completion: nil) } } if let item = item as? _TabBarItem { item.contentView?.select(animated: animated, completion: nil) } else if self.isMoreItem(newIndex) { moreContentView?.select(animated: animated, completion: nil) } delegate?.tabBar?(self, didSelect: item) } else if currentIndex == newIndex { if let item = item as? _TabBarItem { item.contentView?.reselect(animated: animated, completion: nil) } else if self.isMoreItem(newIndex) { moreContentView?.reselect(animated: animated, completion: nil) } if let tabBarController = tabBarController, let navVC = tabBarController.selectedViewController as? UINavigationController { if navVC.viewControllers.contains(tabBarController) { if navVC.viewControllers.count > 1 && navVC.viewControllers.last != tabBarController { navVC.popToViewController(tabBarController, animated: true); } } else { if navVC.viewControllers.count > 1 { navVC.popToRootViewController(animated: animated) } } } } self.updateAccessibilityLabels() } internal func updateAccessibilityLabels() { guard let tabBarItems = self.items, tabBarItems.count == self.containers.count else { return } for (idx, item) in tabBarItems.enumerated() { let container = self.containers[idx] var accessibilityTitle = "" if let item = item as? _TabBarItem { accessibilityTitle = item.title ?? "" } if self.isMoreItem(idx) { accessibilityTitle = NSLocalizedString("More_TabBarItem", bundle: Bundle(for:_TabBarController.self), comment: "") } let formatString = NSLocalizedString(item == selectedItem ? "TabBarItem_Selected_AccessibilityLabel" : "TabBarItem_AccessibilityLabel", bundle: Bundle(for: _TabBarController.self), comment: "") container.accessibilityLabel = String(format: formatString, accessibilityTitle, idx + 1, tabBarItems.count) } } }
37.02657
179
0.582099
39a7b0f7f186856b36512cb2ca370e788f9794a6
8,773
// // CameraController.swift // monly-demo // // Created by studium on 09.06.19. // Copyright © 2019 codefuse. All rights reserved. // import AVFoundation import UIKit class CameraController: NSObject { var captureSession: AVCaptureSession? var currentCameraPosition: CameraPosition? var frontCamera: AVCaptureDevice? var frontCameraInput: AVCaptureDeviceInput? var photoOutput: AVCapturePhotoOutput? var rearCamera: AVCaptureDevice? var rearCameraInput: AVCaptureDeviceInput? var previewLayer: AVCaptureVideoPreviewLayer? var flashMode = AVCaptureDevice.FlashMode.off var photoCaptureCompletionBlock: ((UIImage?, Error?) -> Void)? } extension CameraController { func prepare(completionHandler: @escaping (Error?) -> Void) { func createCaptureSession() { self.captureSession = AVCaptureSession() } func configureCaptureDevices() throws { let session = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified) let cameras = session.devices guard !cameras.isEmpty else { throw CameraControllerError.noCamerasAvailable } for camera in cameras { if camera.position == .front { self.frontCamera = camera } if camera.position == .back { self.rearCamera = camera try camera.lockForConfiguration() camera.focusMode = .continuousAutoFocus camera.unlockForConfiguration() } } } func configureDeviceInputs() throws { guard let captureSession = self.captureSession else { throw CameraControllerError.captureSessionIsMissing } if let rearCamera = self.rearCamera { self.rearCameraInput = try AVCaptureDeviceInput(device: rearCamera) if captureSession.canAddInput(self.rearCameraInput!) { captureSession.addInput(self.rearCameraInput!) } self.currentCameraPosition = .rear } else if let frontCamera = self.frontCamera { self.frontCameraInput = try AVCaptureDeviceInput(device: frontCamera) if captureSession.canAddInput(self.frontCameraInput!) { captureSession.addInput(self.frontCameraInput!) } else { throw CameraControllerError.inputsAreInvalid } self.currentCameraPosition = .front } else { throw CameraControllerError.noCamerasAvailable } } func configurePhotoOutput() throws { guard let captureSession = self.captureSession else { throw CameraControllerError.captureSessionIsMissing } self.photoOutput = AVCapturePhotoOutput() self.photoOutput!.setPreparedPhotoSettingsArray([AVCapturePhotoSettings(format: [AVVideoCodecKey : AVVideoCodecJPEG])], completionHandler: nil) if captureSession.canAddOutput(self.photoOutput!) { captureSession.addOutput(self.photoOutput!) } captureSession.startRunning() } DispatchQueue(label: "prepare").async { do { createCaptureSession() try configureCaptureDevices() try configureDeviceInputs() try configurePhotoOutput() } catch { DispatchQueue.main.async { completionHandler(error) } return } DispatchQueue.main.async { completionHandler(nil) } } } func displayPreview(on view: UIView) throws { guard let captureSession = self.captureSession, captureSession.isRunning else { throw CameraControllerError.captureSessionIsMissing } self.previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) self.previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill self.previewLayer?.connection?.videoOrientation = .portrait view.layer.insertSublayer(self.previewLayer!, at: 0) self.previewLayer?.frame = view.frame } func switchCameras() throws { guard let currentCameraPosition = currentCameraPosition, let captureSession = self.captureSession, captureSession.isRunning else { throw CameraControllerError.captureSessionIsMissing } switch currentCameraPosition { case .front: try switchToRearCamera() case .rear: try switchToFrontCamera() } } func switchToFrontCamera() throws { guard let currentCameraPosition = currentCameraPosition, let captureSession = self.captureSession, captureSession.isRunning else { throw CameraControllerError.captureSessionIsMissing } captureSession.beginConfiguration() guard let rearCameraInput = self.rearCameraInput, captureSession.inputs.contains(rearCameraInput), let frontCamera = self.frontCamera else { throw CameraControllerError.invalidOperation } self.frontCameraInput = try AVCaptureDeviceInput(device: frontCamera) captureSession.removeInput(rearCameraInput) if captureSession.canAddInput(self.frontCameraInput!) { captureSession.addInput(self.frontCameraInput!) self.currentCameraPosition = .front } else { throw CameraControllerError.invalidOperation } captureSession.commitConfiguration() } func switchToRearCamera() throws { guard let currentCameraPosition = currentCameraPosition, let captureSession = self.captureSession, captureSession.isRunning else { throw CameraControllerError.captureSessionIsMissing } captureSession.beginConfiguration() guard let frontCameraInput = self.frontCameraInput, captureSession.inputs.contains(frontCameraInput), let rearCamera = self.rearCamera else { throw CameraControllerError.invalidOperation } self.rearCameraInput = try AVCaptureDeviceInput(device: rearCamera) captureSession.removeInput(frontCameraInput) if captureSession.canAddInput(self.rearCameraInput!) { captureSession.addInput(self.rearCameraInput!) self.currentCameraPosition = .rear } else { throw CameraControllerError.invalidOperation } captureSession.commitConfiguration() } func captureImage(completion: @escaping (UIImage?, Error?) -> Void) { guard let captureSession = captureSession, captureSession.isRunning else { completion(nil, CameraControllerError.captureSessionIsMissing); return } let settings = AVCapturePhotoSettings() settings.flashMode = self.flashMode self.photoOutput?.capturePhoto(with: settings, delegate: self) self.photoCaptureCompletionBlock = completion } } extension CameraController: AVCapturePhotoCaptureDelegate { public func photoOutput(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Swift.Error?) { if let error = error { self.photoCaptureCompletionBlock?(nil, error) } else if let buffer = photoSampleBuffer, let data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: buffer, previewPhotoSampleBuffer: nil), let image = UIImage(data: data) { self.photoCaptureCompletionBlock?(image, nil) } else { self.photoCaptureCompletionBlock?(nil, CameraControllerError.unknown) } } } extension CameraController { enum CameraControllerError: Swift.Error { case captureSessionAlreadyRunning case captureSessionIsMissing case inputsAreInvalid case invalidOperation case noCamerasAvailable case unknown } public enum CameraPosition { case front case rear } }
37.978355
192
0.633535
0a8d7b7f0cc03935eb41bc483e8b5e5b9a7840e4
2,072
import UIKit // this is an iOS playground //: ## SYNOPSIS // import PONS // Not needed because it is directly linked //: BigInt included. Enjoy unlimited! let bn = BigInt(1)<<64 + 1 // 18446744073709551617 bn.asUInt64 // nil; bn > UIntMax.max (bn - 2).asUInt64 // 18446744073709551615 == UIntMax.max bn + bn // 36893488147419103234 bn - bn // 0 bn * bn // 340282366920938463500268095579187314689 bn / bn // 1 //: Rational (number type) is also included. let bq = BigInt(1).over(bn) // (1/18446744073709551617) bq + bq // (2/18446744073709551617) bq - bq // (0/1) bq * bq // (1/340282366920938463500268095579187314689) bq / bq // (1/1) bq.denominator == bn // true, of course! bq.reciprocal.numerator == bn // so is this //: Complex numbers. How can we live without them? let bz = bq + bq.i // ((1/18446744073709551617)+(1/18446744073709551617).i) bz + bz // ((2/18446744073709551617)+(2/18446744073709551617).i) bz - bz // ((0/1)+(0/1).i) bz * bz // ((0/1)+(2/340282366920938463500268095579187314689).i) bz / bz // ((1/1)+(0/1).i) /*: [Elementary function]s (as in `<math.h>`) are supported as static functions. `POReal` has defalut implementations so you don't have to implement them for your new number types! `Darwin` and `Glibc` implementations are attached to `Double` as static functions, too. [Elementary function]: https://en.wikipedia.org/wiki/Elementary_function */ Double.sqrt(-1) // sadly NaN Rational.sqrt(bq) // (1/4294967296) == yes, works with Rational, too! Complex.sqrt(-1) // (0.0+1.0.i) // as it should be Complex.log(-1) // (0.0+3.14159265358979.i) // Yes, πi Complex.exp(Double.PI.i) // (-1.0+1.22464679914735e-16.i) != (-1.0+0.0.i) // :( // default 64-bit precision is still not good enough… Complex.exp(BigRat.pi().i) // (-(1/1)-(1/4722366482869645213696).i) // but with 128-bit precision… Complex.exp(BigRat.pi(128).i) // (-(1/1)+(0/1).i) // as it should be! //: [Next](@next)
37.672727
99
0.625965
1af968f8a1c5fec2de463bd876b82f86dbc7898d
1,102
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { guard let approvalRequestUUID = userInfo["approval_request_uuid"] as? String, let notificationType = userInfo["type"] as? String, notificationType == "onetouch_approval_request" else { return } let twilioAuth = TwilioAuth.sharedInstance() as! TwilioAuth // Since the approval request has sensitive data, we'll fetch it in background with the // request uuid instead of delivering the information within the userInfo. twilioAuth.getRequestWithUUID(approvalRequestUUID) { request, error in if error != nil { // Error fetching approval request return } guard let request = request else { return } if request.uuid == approvalRequestUUID { // Do something with the pendingRequest print(request) } } }
33.393939
195
0.644283
561cf96e8a2a7076943306474c954cc463a84f2f
15,731
// // TestData.swift // DataMapper // // Created by Filip Dolnik on 01.01.17. // Copyright © 2017 Brightify. All rights reserved. // import DataMapper import Nimble struct TestData { static let deserializableStruct = DeserializableStruct(number: 1, text: "a", points: [2], children: []) static let mappableStruct = MappableStruct(number: 1, text: "a", points: [2], children: []) static let mappableClass = MappableClass(number: 1, text: "a", points: [2], children: []) static let serializableStruct = SerializableStruct(number: 1, text: "a", points: [2], children: []) static let type = SupportedType.dictionary(["number": .int(1), "text": .string("a"), "points": .array([.double(2)]), "children": .array([])]) static let invalidType = SupportedType.dictionary(["number": .int(1)]) // Returned elements == Floor[ x! * e ] static func generate(x: Int) -> PerformanceStruct { var object = PerformanceStruct(number: 0, text: "0", points: [], children: [], dictionary: ["A": false, "B": true]) for i in 1...x { object = PerformanceStruct(number: i, text: "\(i)", points: (1...i).map { Double($0) }, children: (1...i).map { _ in object }, dictionary: ["A": false, "B": true]) } return object } struct PerformanceStruct: Mappable, Codable { private(set) var number: Int? private(set) var text: String = "" private(set) var points: [Double] = [] private(set) var children: [PerformanceStruct] = [] let dictionary: [String: Bool] init(number: Int?, text: String, points: [Double], children: [PerformanceStruct], dictionary: [String: Bool]) { self.number = number self.text = text self.points = points self.children = children self.dictionary = dictionary } init(_ data: DeserializableData) throws { dictionary = try data["dictionary"].get() try mapping(data) } func serialize(to data: inout SerializableData) { data["dictionary"].set(dictionary) mapping(&data) } mutating func mapping(_ data: inout MappableData) throws { data["number"].map(&number) try data["text"].map(&text) data["points"].map(&points, or: []) data["children"].map(&children, or: []) } } struct DeserializableStruct: Deserializable { let number: Int? let text: String let points: [Double] let children: [MappableStruct] init(number: Int?, text: String, points: [Double], children: [MappableStruct]) { self.number = number self.text = text self.points = points self.children = children } init(_ data: DeserializableData) throws { number = data["number"].get() text = try data["text"].get() points = data["points"].get(or: []) children = data["children"].get(or: []) } } struct MappableStruct: Mappable { private(set) var number: Int? private(set) var text: String = "" private(set) var points: [Double] = [] private(set) var children: [MappableStruct] = [] init(number: Int?, text: String, points: [Double], children: [MappableStruct]) { self.number = number self.text = text self.points = points self.children = children } init(_ data: DeserializableData) throws { try mapping(data) } mutating func mapping(_ data: inout MappableData) throws { data["number"].map(&number) try data["text"].map(&text) data["points"].map(&points, or: []) data["children"].map(&children, or: []) } } class MappableClass: Mappable { let number: Int? private(set) var text: String = "" private(set) var points: [Double] = [] private(set) var children: [MappableStruct] = [] init(number: Int?, text: String, points: [Double], children: [MappableStruct]) { self.number = number self.text = text self.points = points self.children = children } required init(_ data: DeserializableData) throws { number = data["number"].get() try mapping(data) } func serialize(to data: inout SerializableData) { mapping(&data) data["number"].set(number) } func mapping(_ data: inout MappableData) throws { try data["text"].map(&text) data["points"].map(&points, or: []) data["children"].map(&children, or: []) } } struct SerializableStruct: Serializable { let number: Int? let text: String let points: [Double] let children: [MappableStruct] init(number: Int?, text: String, points: [Double], children: [MappableStruct]) { self.number = number self.text = text self.points = points self.children = children } func serialize(to data: inout SerializableData) { data["number"].set(number) data["text"].set(text) data["points"].set(points) data["children"].set(children) } } struct Map { static let validType = SupportedType.dictionary([ "value": .int(1), "array": .array([.int(1), .int(2)]), "dictionary": .dictionary(["a": .int(1), "b": .int(2)]), "optionalArray": .array([.int(1), .null]), "optionalDictionary": .dictionary(["a": .int(1), "b": .null]), ]) static let invalidType = SupportedType.dictionary([ "value": .double(1), "array": .array([.double(1), .int(2)]), "dictionary": .dictionary(["a": .double(1), "b": .int(2)]), "optionalArray": .double(1), "optionalDictionary": .null ]) static let nullType = SupportedType.dictionary([ "value": .null, "array": .null, "dictionary": .null, "optionalArray": .null, "optionalDictionary": .null, ]) static let pathType = SupportedType.dictionary(["a": .dictionary(["b": .int(1)])]) static func assertValidType(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?, _ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) { expect(value, file: file, line: line) == 1 expect(array, file: file, line: line) == [1, 2] expect(dictionary, file: file, line: line) == ["a": 1, "b": 2] expect(areEqual(optionalArray, [1, nil]), file: file, line: line).to(beTrue()) expect(areEqual(optionalDictionary, ["a": 1, "b": nil]), file: file, line: line).to(beTrue()) } static func assertValidTypeUsingTransformation(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?, _ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) { expect(value, file: file, line: line) == 2 expect(array, file: file, line: line) == [2, 4] expect(dictionary, file: file, line: line) == ["a": 2, "b": 4] expect(areEqual(optionalArray, [2, nil]), file: file, line: line).to(beTrue()) expect(areEqual(optionalDictionary, ["a": 2, "b": nil]), file: file, line: line).to(beTrue()) } static func assertInvalidTypeOr(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?, _ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) { expect(value, file: file, line: line) == 0 expect(array, file: file, line: line) == [0] expect(dictionary, file: file, line: line) == ["a": 0] expect(areEqual(optionalArray, [0]), file: file, line: line).to(beTrue()) expect(areEqual(optionalDictionary, ["a": 0]), file: file, line: line).to(beTrue()) } static func assertInvalidType(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?, _ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) { expect(value, file: file, line: line).to(beNil()) expect(array, file: file, line: line).to(beNil()) expect(dictionary, file: file, line: line).to(beNil()) expect(optionalArray, file: file, line: line).to(beNil()) expect(optionalDictionary, file: file, line: line).to(beNil()) } } struct StaticPolymorph { class A: Polymorphic { class var polymorphicKey: String { return "K" } class var polymorphicInfo: PolymorphicInfo { return createPolymorphicInfo().with(subtype: B.self) } } class B: A { override class var polymorphicInfo: PolymorphicInfo { // D is intentionally registered here. return createPolymorphicInfo().with(subtypes: C.self, D.self) } } class C: B { override class var polymorphicKey: String { return "C" } } class D: C { override class var polymorphicInfo: PolymorphicInfo { return createPolymorphicInfo(name: "D2") } } // Intentionally not registered. class E: D { } class X { } } struct PolymorphicTypes { static let a = A(id: 1) static let b = B(id: 2, name: "name") static let c = C(id: 3, number: 0) static let aType = SupportedType.dictionary(["id": .int(1), "type": .string("A")]) static let bType = SupportedType.dictionary(["id": .int(2), "name": .string("name"), "type": .string("B")]) static let cType = SupportedType.dictionary(["id": .int(3), "number": .int(0), "type": .string("C")]) static let aTypeWithoutPolymorphicData = SupportedType.dictionary(["id": .int(1)]) static let bTypeWithoutPolymorphicData = SupportedType.dictionary(["id": .int(2), "name": .string("name")]) static let cTypeWithoutPolymorphicData = SupportedType.dictionary(["id": .int(3), "number": .int(0)]) class A: PolymorphicMappable { static var polymorphicKey = "type" static var polymorphicInfo: PolymorphicInfo { return createPolymorphicInfo().with(subtypes: B.self, C.self) } let id: Int init(id: Int) { self.id = id } required init(_ data: DeserializableData) throws { id = try data["id"].get() try mapping(data) } func serialize(to data: inout SerializableData) { data["id"].set(id) mapping(&data) } func mapping(_ data: inout MappableData) throws { } } class B: A { var name: String? init(id: Int, name: String?) { super.init(id: id) self.name = name } required init(_ data: DeserializableData) throws { try super.init(data) } override func mapping(_ data: inout MappableData) throws { try super.mapping(&data) data["name"].map(&name) } } class C: A { var number: Int? init(id: Int, number: Int?) { super.init(id: id) self.number = number } required init(_ data: DeserializableData) throws { try super.init(data) } override func mapping(_ data: inout MappableData) throws { try super.mapping(&data) data["number"].map(&number) } } } struct CustomIntTransformation: Transformation { typealias Object = Int func transform(from value: SupportedType) -> Int? { return value.int.map { $0 * 2 } ?? nil } func transform(object: Int?) -> SupportedType { return object.map { .int($0 / 2) } ?? .null } } } extension TestData.PerformanceStruct: Equatable { } func ==(lhs: TestData.PerformanceStruct, rhs: TestData.PerformanceStruct) -> Bool { return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children && lhs.dictionary == rhs.dictionary } extension TestData.DeserializableStruct: Equatable { } func ==(lhs: TestData.DeserializableStruct, rhs: TestData.DeserializableStruct) -> Bool { return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children } extension TestData.MappableStruct: Equatable { } func ==(lhs: TestData.MappableStruct, rhs: TestData.MappableStruct) -> Bool { return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children } extension TestData.MappableClass: Equatable { } func ==(lhs: TestData.MappableClass, rhs: TestData.MappableClass) -> Bool { return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children } extension TestData.SerializableStruct: Equatable { } func ==(lhs: TestData.SerializableStruct, rhs: TestData.SerializableStruct) -> Bool { return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children } func areEqual(_ lhs: [Int?]?, _ rhs: [Int?]?) -> Bool { if let lhs = lhs, let rhs = rhs { if lhs.count == rhs.count { for i in lhs.indices { if lhs[i] != rhs[i] { return false } } return true } } return lhs == nil && rhs == nil } func areEqual(_ lhs: [String: Int?]?, _ rhs: [String: Int?]?) -> Bool { if let lhs = lhs, let rhs = rhs { if lhs.count == rhs.count { for i in lhs.keys { if let lValue = lhs[i], let rValue = rhs[i], lValue == rValue { continue } else { return false } } return true } } return lhs == nil && rhs == nil }
35.350562
155
0.510521
16f99abafb8b1f0f690bf27bf4d3a3538efa65e8
380
// // String+Bae64.swift // KeyprApi // // Created by Nicholas Mata on 11/28/18. // Copyright © 2018 Nicholas Mata. All rights reserved. // import Foundation extension String { internal func addBas64Padding() -> String { return self.padding(toLength: ((self.count+3)/4)*4, withPad: "=", startingAt: 0) } }
21.111111
59
0.563158
4ab747017bf4fbf8d9f58fa4ed617bcdf686c064
1,310
// The MIT License (MIT) // // Copyright (c) 2021 theScore Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension OperationQueue: Scheduler { public func schedule(_ action: @escaping () -> Void) { addOperation(action) } }
43.666667
81
0.740458
5089f907a421ff7febd44c2219d9ced27d569124
500
import UIKit import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) if #available(iOS 10.0, *) { UNUserNotificationCenter.current().delegate = self } return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
29.411765
87
0.762
03efca4d066193e331831b1cfee4e0bc0eb7f566
69
import Day04Lib class Main { func run() { } } Main().run()
7.666667
16
0.536232
62c5d54d5de6dfb830563e3160ebda80ba2da4ec
33,260
// swiftlint:disable file_length import Swinject import Foundation import BTKit import RuuviLocal import RuuviPool import RuuviContext import RuuviVirtual import RuuviStorage import RuuviService import RuuviDFU import RuuviMigration import RuuviPersistence import RuuviReactor import RuuviCloud import RuuviUser import RuuviDaemon import RuuviNotifier import RuuviNotification import RuuviRepository import RuuviLocation import RuuviCore #if canImport(RuuviCloudPure) import RuuviCloudPure #endif #if canImport(RuuviVirtualOWM) import RuuviVirtualOWM #endif #if canImport(RuuviContextRealm) import RuuviContextRealm #endif #if canImport(RuuviContextSQLite) import RuuviContextSQLite #endif #if canImport(RuuviPersistenceRealm) import RuuviPersistenceRealm #endif #if canImport(RuuviPersistenceSQLite) import RuuviPersistenceSQLite #endif #if canImport(RuuviStorageCoordinator) import RuuviStorageCoordinator #endif #if canImport(RuuviPoolCoordinator) import RuuviPoolCoordinator #endif #if canImport(RuuviLocalUserDefaults) import RuuviLocalUserDefaults #endif #if canImport(RuuviPoolCoordinator) import RuuviPoolCoordinator #endif #if canImport(RuuviReactorImpl) import RuuviReactorImpl #endif #if canImport(RuuviDFUImpl) import RuuviDFUImpl #endif #if canImport(RuuviMigrationImpl) import RuuviMigrationImpl #endif #if canImport(RuuviVirtualPersistence) import RuuviVirtualPersistence #endif #if canImport(RuuviVirtualReactor) import RuuviVirtualReactor #endif #if canImport(RuuviVirtualRepository) import RuuviVirtualRepository #endif #if canImport(RuuviVirtualStorage) import RuuviVirtualStorage #endif #if canImport(RuuviDaemonOperation) import RuuviDaemonOperation #endif #if canImport(RuuviDaemonBackground) import RuuviDaemonBackground #endif #if canImport(RuuviDaemonRuuviTag) import RuuviDaemonRuuviTag #endif #if canImport(RuuviDaemonVirtualTag) import RuuviDaemonVirtualTag #endif #if canImport(RuuviServiceGATT) import RuuviServiceGATT #endif #if canImport(RuuviAnalytics) import RuuviAnalytics #endif #if canImport(RuuviAnalyticsImpl) import RuuviAnalyticsImpl #endif #if canImport(RuuviServiceExport) import RuuviServiceExport #endif #if canImport(RuuviNotifierImpl) import RuuviNotifierImpl #endif #if canImport(RuuviServiceFactory) import RuuviServiceFactory #endif #if canImport(RuuviDaemonCloudSync) import RuuviDaemonCloudSync #endif #if canImport(RuuviRepositoryCoordinator) import RuuviRepositoryCoordinator #endif #if canImport(RuuviUserCoordinator) import RuuviUserCoordinator #endif #if canImport(RuuviCoreLocation) import RuuviCoreLocation #endif #if canImport(RuuviLocationService) import RuuviLocationService #endif #if canImport(RuuviVirtualOWM) import RuuviVirtualOWM #endif #if canImport(RuuviVirtualService) import RuuviVirtualService #endif #if canImport(RuuviNotificationLocal) import RuuviNotificationLocal #endif #if canImport(RuuviCoreImage) import RuuviCoreImage #endif #if canImport(RuuviCoreLocation) import RuuviCoreLocation #endif #if canImport(RuuviLocationService) import RuuviLocationService #endif #if canImport(RuuviCorePN) import RuuviCorePN #endif #if canImport(RuuviCorePermission) import RuuviCorePermission #endif #if canImport(RuuviServiceMeasurement) import RuuviServiceMeasurement #endif final class AppAssembly { static let shared = AppAssembly() var assembler: Assembler init() { assembler = Assembler( [ BusinessAssembly(), CoreAssembly(), DaemonAssembly(), MigrationAssembly(), NetworkingAssembly(), PersistenceAssembly(), PresentationAssembly(), DfuAssembly(), VirtualAssembly() ]) } } private final class DfuAssembly: Assembly { func assemble(container: Container) { container.register(RuuviDFU.self) { _ in return RuuviDFUImpl.shared }.inObjectScope(.container) } } private final class MigrationAssembly: Assembly { func assemble(container: Container) { container.register(RuuviMigration.self, name: "realm") { r in let localImages = r.resolve(RuuviLocalImages.self)! let settings = r.resolve(RuuviLocalSettings.self)! return MigrationManagerToVIPER(localImages: localImages, settings: settings) } container.register(RuuviMigrationFactory.self) { r in let settings = r.resolve(RuuviLocalSettings.self)! let idPersistence = r.resolve(RuuviLocalIDs.self)! let realmContext = r.resolve(RealmContext.self)! let ruuviPool = r.resolve(RuuviPool.self)! let virtualStorage = r.resolve(VirtualStorage.self)! let ruuviStorage = r.resolve(RuuviStorage.self)! let ruuviAlertService = r.resolve(RuuviServiceAlert.self)! let ruuviOffsetCalibrationService = r.resolve(RuuviServiceOffsetCalibration.self)! return RuuviMigrationFactoryImpl( settings: settings, idPersistence: idPersistence, realmContext: realmContext, ruuviPool: ruuviPool, virtualStorage: virtualStorage, ruuviStorage: ruuviStorage, ruuviAlertService: ruuviAlertService, ruuviOffsetCalibrationService: ruuviOffsetCalibrationService ) } } } private final class PersistenceAssembly: Assembly { // swiftlint:disable:next function_body_length func assemble(container: Container) { container.register(RealmContextFactory.self) { _ in let factory = RealmContextFactoryImpl() return factory }.inObjectScope(.container) container.register(RealmContext.self) { r in let factory = r.resolve(RealmContextFactory.self)! return factory.create() }.inObjectScope(.container) container.register(RuuviLocalConnections.self) { r in let factory = r.resolve(RuuviLocalFactory.self)! return factory.createLocalConnections() } container.register(RuuviLocalImages.self) { r in let factory = r.resolve(RuuviLocalFactory.self)! return factory.createLocalImages() } container.register(RuuviLocalSyncState.self) { r in let factory = r.resolve(RuuviLocalFactory.self)! return factory.createLocalSyncState() }.inObjectScope(.container) container.register(RuuviPoolFactory.self) { _ in return RuuviPoolFactoryCoordinator() } container.register(RuuviPool.self) { r in let factory = r.resolve(RuuviPoolFactory.self)! let realm = r.resolve(RuuviPersistence.self, name: "realm")! let sqlite = r.resolve(RuuviPersistence.self, name: "sqlite")! let localIDs = r.resolve(RuuviLocalIDs.self)! let localSettings = r.resolve(RuuviLocalSettings.self)! let localConnections = r.resolve(RuuviLocalConnections.self)! return factory.create( sqlite: sqlite, realm: realm, idPersistence: localIDs, settings: localSettings, connectionPersistence: localConnections ) } container.register(RuuviReactorFactory.self) { _ in return RuuviReactorFactoryImpl() } container.register(RuuviReactor.self) { r in let factory = r.resolve(RuuviReactorFactory.self)! let sqliteContext = r.resolve(SQLiteContext.self)! let realmContext = r.resolve(RealmContext.self)! let sqltePersistence = r.resolve(RuuviPersistence.self, name: "sqlite")! let realmPersistence = r.resolve(RuuviPersistence.self, name: "realm")! return factory.create( sqliteContext: sqliteContext, realmContext: realmContext, sqlitePersistence: sqltePersistence, realmPersistence: realmPersistence ) }.inObjectScope(.container) container.register(RuuviStorageFactory.self) { _ in let factory = RuuviStorageFactoryCoordinator() return factory } container.register(RuuviPersistence.self, name: "realm") { r in let context = r.resolve(RealmContext.self)! return RuuviPersistenceRealm(context: context) }.inObjectScope(.container) container.register(RuuviPersistence.self, name: "sqlite") { r in let context = r.resolve(SQLiteContext.self)! return RuuviPersistenceSQLite(context: context) }.inObjectScope(.container) container.register(RuuviStorage.self) { r in let factory = r.resolve(RuuviStorageFactory.self)! let sqlite = r.resolve(RuuviPersistence.self, name: "sqlite")! let realm = r.resolve(RuuviPersistence.self, name: "realm")! return factory.create(realm: realm, sqlite: sqlite) }.inObjectScope(.container) container.register(RuuviLocalFactory.self) { _ in let factory = RuuviLocalFactoryUserDefaults() return factory } container.register(RuuviLocalSettings.self) { r in let factory = r.resolve(RuuviLocalFactory.self)! return factory.createLocalSettings() } container.register(RuuviLocalIDs.self) { r in let factory = r.resolve(RuuviLocalFactory.self)! return factory.createLocalIDs() } container.register(SQLiteContextFactory.self) { _ in let factory = SQLiteContextFactoryGRDB() return factory } container.register(SQLiteContext.self) { r in let factory = r.resolve(SQLiteContextFactory.self)! return factory.create() }.inObjectScope(.container) } } private final class NetworkingAssembly: Assembly { func assemble(container: Container) { container.register(OpenWeatherMapAPI.self) { r in let apiKey: String = AppAssemblyConstants.openWeatherMapApiKey let api = OpenWeatherMapAPIURLSession(apiKey: apiKey) return api } container.register(RuuviCloud.self) { r in let user = r.resolve(RuuviUser.self)! let baseUrlString: String = AppAssemblyConstants.ruuviCloudUrl let baseUrl = URL(string: baseUrlString)! let cloud = r.resolve(RuuviCloudFactory.self)!.create( baseUrl: baseUrl, user: user ) return cloud } container.register(RuuviCloudFactory.self) { _ in return RuuviCloudFactoryPure() } } } private final class VirtualAssembly: Assembly { func assemble(container: Container) { container.register(VirtualPersistence.self) { r in let context = r.resolve(RealmContext.self)! let settings = r.resolve(RuuviLocalSettings.self)! return VirtualPersistenceRealm(context: context, settings: settings) } container.register(VirtualReactor.self) { r in let context = r.resolve(RealmContext.self)! let persistence = r.resolve(VirtualPersistence.self)! return VirtualReactorImpl(context: context, persistence: persistence) }.inObjectScope(.container) container.register(VirtualRepository.self) { r in let persistence = r.resolve(VirtualPersistence.self)! return VirtualRepositoryCoordinator(persistence: persistence) } container.register(VirtualStorage.self) { r in let persistence = r.resolve(VirtualPersistence.self)! return VirtualStorageCoordinator(persistence: persistence) } } } private final class DaemonAssembly: Assembly { // swiftlint:disable:next function_body_length func assemble(container: Container) { container.register(BackgroundProcessService.self) { r in let dataPruningOperationsManager = r.resolve(DataPruningOperationsManager.self)! let service = BackgroundProcessServiceiOS13( dataPruningOperationsManager: dataPruningOperationsManager ) return service }.inObjectScope(.container) container.register(BackgroundTaskService.self) { r in let webTagOperationsManager = r.resolve(WebTagOperationsManager.self)! let service = BackgroundTaskServiceiOS13( webTagOperationsManager: webTagOperationsManager ) return service }.inObjectScope(.container) container.register(DataPruningOperationsManager.self) { r in let settings = r.resolve(RuuviLocalSettings.self)! let ruuviStorage = r.resolve(RuuviStorage.self)! let virtualStorage = r.resolve(VirtualStorage.self)! let virtualRepository = r.resolve(VirtualRepository.self)! let ruuviPool = r.resolve(RuuviPool.self)! let manager = DataPruningOperationsManager( settings: settings, virtualStorage: virtualStorage, virtualRepository: virtualRepository, ruuviStorage: ruuviStorage, ruuviPool: ruuviPool ) return manager } container.register(PullWebDaemon.self) { r in let settings = r.resolve(RuuviLocalSettings.self)! let webTagOperationsManager = r.resolve(WebTagOperationsManager.self)! let daemon = PullWebDaemonOperations( settings: settings, webTagOperationsManager: webTagOperationsManager ) return daemon }.inObjectScope(.container) container.register(RuuviTagAdvertisementDaemon.self) { r in let settings = r.resolve(RuuviLocalSettings.self)! let foreground = r.resolve(BTForeground.self)! let ruuviPool = r.resolve(RuuviPool.self)! let ruuviReactor = r.resolve(RuuviReactor.self)! let ruuviStorage = r.resolve(RuuviStorage.self)! let daemon = RuuviTagAdvertisementDaemonBTKit( ruuviPool: ruuviPool, ruuviStorage: ruuviStorage, ruuviReactor: ruuviReactor, foreground: foreground, settings: settings ) return daemon }.inObjectScope(.container) container.register(RuuviTagHeartbeatDaemon.self) { r in let background = r.resolve(BTBackground.self)! let localNotificationsManager = r.resolve(RuuviNotificationLocal.self)! let connectionPersistence = r.resolve(RuuviLocalConnections.self)! let ruuviPool = r.resolve(RuuviPool.self)! let ruuviReactor = r.resolve(RuuviReactor.self)! let ruuviStorage = r.resolve(RuuviStorage.self)! let alertHandler = r.resolve(RuuviNotifier.self)! let alertService = r.resolve(RuuviServiceAlert.self)! let settings = r.resolve(RuuviLocalSettings.self)! let pullWebDaemon = r.resolve(PullWebDaemon.self)! let daemon = RuuviTagHeartbeatDaemonBTKit( background: background, localNotificationsManager: localNotificationsManager, connectionPersistence: connectionPersistence, ruuviPool: ruuviPool, ruuviStorage: ruuviStorage, ruuviReactor: ruuviReactor, alertService: alertService, alertHandler: alertHandler, settings: settings, pullWebDaemon: pullWebDaemon, titles: HeartbeatDaemonTitles() ) return daemon }.inObjectScope(.container) container.register(RuuviTagPropertiesDaemon.self) { r in let ruuviReactor = r.resolve(RuuviReactor.self)! let ruuviPool = r.resolve(RuuviPool.self)! let foreground = r.resolve(BTForeground.self)! let idPersistence = r.resolve(RuuviLocalIDs.self)! let realmPersistence = r.resolve(RuuviPersistence.self, name: "realm")! let sqiltePersistence = r.resolve(RuuviPersistence.self, name: "sqlite")! let daemon = RuuviTagPropertiesDaemonBTKit( ruuviPool: ruuviPool, ruuviReactor: ruuviReactor, foreground: foreground, idPersistence: idPersistence, realmPersistence: realmPersistence, sqiltePersistence: sqiltePersistence ) return daemon }.inObjectScope(.container) container.register(VirtualTagDaemon.self) { r in let virtualService = r.resolve(VirtualService.self)! let settings = r.resolve(RuuviLocalSettings.self)! let virtualPersistence = r.resolve(VirtualPersistence.self)! let alertService = r.resolve(RuuviNotifier.self)! let virtualReactor = r.resolve(VirtualReactor.self)! let daemon = VirtualTagDaemonImpl( virtualService: virtualService, settings: settings, virtualPersistence: virtualPersistence, alertService: alertService, virtualReactor: virtualReactor ) return daemon }.inObjectScope(.container) container.register(WebTagOperationsManager.self) { r in let alertService = r.resolve(RuuviServiceAlert.self)! let ruuviNotifier = r.resolve(RuuviNotifier.self)! let virtualProviderService = r.resolve(VirtualProviderService.self)! let virtualStorage = r.resolve(VirtualStorage.self)! let virtualPersistence = r.resolve(VirtualPersistence.self)! let manager = WebTagOperationsManager( virtualProviderService: virtualProviderService, alertService: alertService, alertHandler: ruuviNotifier, virtualStorage: virtualStorage, virtualPersistence: virtualPersistence ) return manager } } } // swiftlint:disable:next type_body_length private final class BusinessAssembly: Assembly { // swiftlint:disable:next function_body_length func assemble(container: Container) { container.register(RuuviNotifier.self) { r in let notificationLocal = r.resolve(RuuviNotificationLocal.self)! let ruuviAlertService = r.resolve(RuuviServiceAlert.self)! let titles = RuuviNotifierTitlesImpl() let service = RuuviNotifierImpl( ruuviAlertService: ruuviAlertService, ruuviNotificationLocal: notificationLocal, titles: titles ) return service }.inObjectScope(.container) container.register(AppStateService.self) { r in let service = AppStateServiceImpl() service.settings = r.resolve(RuuviLocalSettings.self) service.advertisementDaemon = r.resolve(RuuviTagAdvertisementDaemon.self) service.propertiesDaemon = r.resolve(RuuviTagPropertiesDaemon.self) service.webTagDaemon = r.resolve(VirtualTagDaemon.self) service.cloudSyncDaemon = r.resolve(RuuviDaemonCloudSync.self) service.heartbeatDaemon = r.resolve(RuuviTagHeartbeatDaemon.self) service.ruuviUser = r.resolve(RuuviUser.self) service.pullWebDaemon = r.resolve(PullWebDaemon.self) service.backgroundTaskService = r.resolve(BackgroundTaskService.self) service.backgroundProcessService = r.resolve(BackgroundProcessService.self) #if canImport(RuuviAnalytics) service.userPropertiesService = r.resolve(RuuviAnalytics.self) #endif service.universalLinkCoordinator = r.resolve(UniversalLinkCoordinator.self) return service }.inObjectScope(.container) container.register(RuuviServiceExport.self) { r in let ruuviStorage = r.resolve(RuuviStorage.self)! let measurementService = r.resolve(RuuviServiceMeasurement.self)! let service = RuuviServiceExportImpl( ruuviStorage: ruuviStorage, measurementService: measurementService, headersProvider: ExportHeadersProvider(), emptyValueString: "N/A".localized() ) return service } container.register(FallbackFeatureToggleProvider.self) { _ in let provider = FallbackFeatureToggleProvider() return provider }.inObjectScope(.container) container.register(FeatureToggleService.self) { r in let service = FeatureToggleService() service.firebaseProvider = r.resolve(FirebaseFeatureToggleProvider.self) service.fallbackProvider = r.resolve(FallbackFeatureToggleProvider.self) service.localProvider = r.resolve(LocalFeatureToggleProvider.self) return service }.inObjectScope(.container) container.register(FirebaseFeatureToggleProvider.self) { r in let provider = FirebaseFeatureToggleProvider() provider.remoteConfigService = r.resolve(RemoteConfigService.self) return provider }.inObjectScope(.container) container.register(GATTService.self) { r in let ruuviPool = r.resolve(RuuviPool.self)! let background = r.resolve(BTBackground.self)! let service = GATTServiceQueue( ruuviPool: ruuviPool, background: background ) return service }.inObjectScope(.container) container.register(LocalFeatureToggleProvider.self) { _ in let provider = LocalFeatureToggleProvider() return provider }.inObjectScope(.container) container.register(RuuviLocationService.self) { _ in let service = RuuviLocationServiceApple() return service } container.register(RemoteConfigService.self) { _ in let service = FirebaseRemoteConfigService() return service }.inObjectScope(.container) container.register(RuuviDaemonFactory.self) { _ in return RuuviDaemonFactoryImpl() } container.register(RuuviDaemonCloudSync.self) { r in let factory = r.resolve(RuuviDaemonFactory.self)! let localSettings = r.resolve(RuuviLocalSettings.self)! let localSyncState = r.resolve(RuuviLocalSyncState.self)! let cloudSyncService = r.resolve(RuuviServiceCloudSync.self)! return factory.createCloudSync( localSettings: localSettings, localSyncState: localSyncState, cloudSyncService: cloudSyncService ) }.inObjectScope(.container) container.register(RuuviRepositoryFactory.self) { _ in return RuuviRepositoryFactoryCoordinator() } container.register(RuuviRepository.self) { r in let factory = r.resolve(RuuviRepositoryFactory.self)! let pool = r.resolve(RuuviPool.self)! let storage = r.resolve(RuuviStorage.self)! return factory.create( pool: pool, storage: storage ) } container.register(RuuviServiceFactory.self) { _ in return RuuviServiceFactoryImpl() } container.register(RuuviServiceAlert.self) { r in let factory = r.resolve(RuuviServiceFactory.self)! let cloud = r.resolve(RuuviCloud.self)! let localIDs = r.resolve(RuuviLocalIDs.self)! return factory.createAlert( ruuviCloud: cloud, ruuviLocalIDs: localIDs ) } container.register(RuuviServiceOffsetCalibration.self) { r in let factory = r.resolve(RuuviServiceFactory.self)! let cloud = r.resolve(RuuviCloud.self)! let pool = r.resolve(RuuviPool.self)! return factory.createOffsetCalibration( ruuviCloud: cloud, ruuviPool: pool ) } container.register(RuuviServiceAppSettings.self) { r in let factory = r.resolve(RuuviServiceFactory.self)! let cloud = r.resolve(RuuviCloud.self)! let localSettings = r.resolve(RuuviLocalSettings.self)! return factory.createAppSettings( ruuviCloud: cloud, ruuviLocalSettings: localSettings ) } container.register(RuuviServiceAuth.self) { r in let factory = r.resolve(RuuviServiceFactory.self)! let user = r.resolve(RuuviUser.self)! let pool = r.resolve(RuuviPool.self)! let storage = r.resolve(RuuviStorage.self)! let propertiesService = r.resolve(RuuviServiceSensorProperties.self)! let localIDs = r.resolve(RuuviLocalIDs.self)! let localSyncState = r.resolve(RuuviLocalSyncState.self)! return factory.createAuth( ruuviUser: user, pool: pool, storage: storage, propertiesService: propertiesService, localIDs: localIDs, localSyncState: localSyncState ) } container.register(RuuviServiceCloudSync.self) { r in let factory = r.resolve(RuuviServiceFactory.self)! let storage = r.resolve(RuuviStorage.self)! let cloud = r.resolve(RuuviCloud.self)! let pool = r.resolve(RuuviPool.self)! let localSettings = r.resolve(RuuviLocalSettings.self)! let localSyncState = r.resolve(RuuviLocalSyncState.self)! let localImages = r.resolve(RuuviLocalImages.self)! let repository = r.resolve(RuuviRepository.self)! let localIDs = r.resolve(RuuviLocalIDs.self)! let alertService = r.resolve(RuuviServiceAlert.self)! return factory.createCloudSync( ruuviStorage: storage, ruuviCloud: cloud, ruuviPool: pool, ruuviLocalSettings: localSettings, ruuviLocalSyncState: localSyncState, ruuviLocalImages: localImages, ruuviRepository: repository, ruuviLocalIDs: localIDs, ruuviAlertService: alertService ) } container.register(RuuviServiceOwnership.self) { r in let factory = r.resolve(RuuviServiceFactory.self)! let pool = r.resolve(RuuviPool.self)! let cloud = r.resolve(RuuviCloud.self)! let propertiesService = r.resolve(RuuviServiceSensorProperties.self)! let localIDs = r.resolve(RuuviLocalIDs.self)! let localImages = r.resolve(RuuviLocalImages.self)! let storage = r.resolve(RuuviStorage.self)! let alertService = r.resolve(RuuviServiceAlert.self)! let user = r.resolve(RuuviUser.self)! return factory.createOwnership( ruuviCloud: cloud, ruuviPool: pool, propertiesService: propertiesService, localIDs: localIDs, localImages: localImages, storage: storage, alertService: alertService, ruuviUser: user ) } container.register(RuuviServiceSensorProperties.self) { r in let factory = r.resolve(RuuviServiceFactory.self)! let pool = r.resolve(RuuviPool.self)! let cloud = r.resolve(RuuviCloud.self)! let coreImage = r.resolve(RuuviCoreImage.self)! let localImages = r.resolve(RuuviLocalImages.self)! return factory.createSensorProperties( ruuviPool: pool, ruuviCloud: cloud, ruuviCoreImage: coreImage, ruuviLocalImages: localImages ) } container.register(RuuviServiceSensorRecords.self) { r in let factory = r.resolve(RuuviServiceFactory.self)! let pool = r.resolve(RuuviPool.self)! let syncState = r.resolve(RuuviLocalSyncState.self)! return factory.createSensorRecords( ruuviPool: pool, ruuviLocalSyncState: syncState ) } container.register(RuuviUserFactory.self) { _ in return RuuviUserFactoryCoordinator() } container.register(RuuviUser.self) { r in let factory = r.resolve(RuuviUserFactory.self)! return factory.createUser() }.inObjectScope(.container) container.register(VirtualProviderService.self) { r in let owmApi = r.resolve(OpenWeatherMapAPI.self)! let locationManager = r.resolve(RuuviCoreLocation.self)! let locationService = r.resolve(RuuviLocationService.self)! let service = VirtualProviderServiceImpl( owmApi: owmApi, ruuviCoreLocation: locationManager, ruuviLocationService: locationService ) return service } container.register(VirtualService.self) { r in let virtualPersistence = r.resolve(VirtualPersistence.self)! let weatherProviderService = r.resolve(VirtualProviderService.self)! let ruuviLocalImages = r.resolve(RuuviLocalImages.self)! let service = VirtualServiceImpl( ruuviLocalImages: ruuviLocalImages, virtualPersistence: virtualPersistence, virtualProviderService: weatherProviderService ) return service } #if canImport(RuuviAnalytics) container.register(RuuviAnalytics.self) { r in let ruuviStorage = r.resolve(RuuviStorage.self)! let settings = r.resolve(RuuviLocalSettings.self)! let service = RuuviAnalyticsImpl( ruuviStorage: ruuviStorage, settings: settings ) return service } #endif container.register(UniversalLinkCoordinator.self, factory: { r in let coordinator = UniversalLinkCoordinatorImpl() let router = UniversalLinkRouterImpl() coordinator.ruuviUser = r.resolve(RuuviUser.self) coordinator.router = router return coordinator }) } } private final class CoreAssembly: Assembly { // swiftlint:disable:next function_body_length func assemble(container: Container) { container.register(BTForeground.self) { _ in return BTKit.foreground }.inObjectScope(.container) container.register(BTBackground.self) { _ in return BTKit.background }.inObjectScope(.container) container.register(InfoProvider.self) { _ in let provider = InfoProviderImpl() return provider } container.register(RuuviNotificationLocal.self) { r in let settings = r.resolve(RuuviLocalSettings.self)! let ruuviStorage = r.resolve(RuuviStorage.self)! let virtualTagTrunk = r.resolve(VirtualStorage.self)! let idPersistence = r.resolve(RuuviLocalIDs.self)! let ruuviAlertService = r.resolve(RuuviServiceAlert.self)! let manager = RuuviNotificationLocalImpl( ruuviStorage: ruuviStorage, virtualTagTrunk: virtualTagTrunk, idPersistence: idPersistence, settings: settings, ruuviAlertService: ruuviAlertService ) return manager }.inObjectScope(.container) container.register(RuuviCoreLocation.self) { _ in let manager = RuuviCoreLocationImpl() return manager } container.register(RuuviCorePermission.self) { r in let locationManager = r.resolve(RuuviCoreLocation.self)! let manager = RuuviCorePermissionImpl(locationManager: locationManager) return manager }.inObjectScope(.container) container.register(RuuviCorePN.self) { _ in let manager = RuuviCorePNImpl() return manager } container.register(RuuviCoreImage.self) { _ in return RuuviCoreImageImpl() } container.register(RuuviServiceMeasurement.self, factory: { r in let settings = r.resolve(RuuviLocalSettings.self)! let service = RuuviServiceMeasurementImpl( settings: settings, emptyValueString: "N/A".localized(), percentString: "%".localized() ) return service }) } } // swiftlint:enable file_length
38.011429
94
0.642784
f9429f3297d677345829b0a3e5a27b58c97c736b
3,282
// // ViewController.swift // DataList // // Created by Nic Ollis on 12/15/17. // Copyright © 2017 Ollis. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBAction func addName(_ sender: Any) { let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] (action) in guard let textField = alert.textFields?.first, let nameToSave = textField.text else { return } self.save(name: nameToSave) self.tableView.reloadData() } let cancelAction = UIAlertAction(title: "Cancel", style: .default) alert.addTextField() alert.addAction(saveAction) alert.addAction(cancelAction) present(alert, animated: true, completion: nil) } var people: [NSManagedObject] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let managedContex = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person") do { people = try managedContex.fetch(fetchRequest) } catch let error as NSError { print("Could not fetch, \(error), \(error.userInfo)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func save(name: String) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let managedContext = appDelegate.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)! let person = NSManagedObject(entity: entity, insertInto: managedContext) person.setValue(name, forKey: "name") do { try managedContext.save() people.append(person) } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } } } // MARK: UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let person = people[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = person.value(forKey: "name") as? String return cell } }
31.557692
107
0.621268
ffda0a1fbfd325361be12ce54fc0d45530a10fac
2,319
// // SceneDelegate.swift // KWLazyPresentSwiftExample // // Created by Kawa on 2020/10/19. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
42.944444
147
0.709357
91fa7044d71a806d03edf88c254975a1b689b34c
4,695
import Vapor import XCTest @testable import Bugsnag extension Application { public static func test() throws -> Application { var services = Services() try services.register(BugsnagProvider(config: BugsnagConfig( apiKey: "e9792272fae71a3b869a1152008f7f0f", releaseStage: "development" ))) var middlewaresConfig = MiddlewareConfig() middlewaresConfig.use(BugsnagMiddleware.self) services.register(middlewaresConfig) let sharedThreadPool = BlockingIOThreadPool(numberOfThreads: 2) sharedThreadPool.start() services.register(sharedThreadPool) return try Application(config: Config(), environment: .testing, services: services) } } final class TestErrorReporter: ErrorReporter { var capturedReportParameters: ( error: Error, severity: Severity, userId: CustomStringConvertible?, metadata: [String: CustomDebugStringConvertible], file: String, function: String, line: Int, column: Int, container: Container )? func report( _ error: Error, severity: Severity, userId: CustomStringConvertible?, metadata: [String: CustomDebugStringConvertible], file: String, function: String, line: Int, column: Int, on container: Container ) -> Future<Void> { capturedReportParameters = ( error, severity, userId, metadata, file, function, line, column, container ) return container.future() } } final class TestResponder: Responder { var mockErrorToThrow: Error? var mockErrorToReturnInFuture: Error? func respond(to req: Request) throws -> Future<Response> { if let error = mockErrorToThrow { throw error } else if let error = mockErrorToReturnInFuture { return req.future(error: error) } else { return req.future(Response(using: req)) } } } final class MiddlewareTests: XCTestCase { var application: Application! var request: Request! var middleware: BugsnagMiddleware! let errorReporter = TestErrorReporter() let responder = TestResponder() override func setUp() { application = try! Application.test() request = Request(using: application) middleware = BugsnagMiddleware(reporter: errorReporter) } func testNoErrorReportedByDefault() throws { _ = try middleware.respond(to: request, chainingTo: responder).wait() // expect no error reported when response is successful XCTAssertNil(errorReporter.capturedReportParameters) } func testRespondErrorsAreCaptured() throws { responder.mockErrorToThrow = NotFound() _ = try? middleware.respond(to: request, chainingTo: responder).wait() // expect an error to be reported when responder throws XCTAssertNotNil(errorReporter.capturedReportParameters) } func testErrorsInFutureAreCaptured() throws { errorReporter.capturedReportParameters = nil responder.mockErrorToReturnInFuture = NotFound() _ = try? middleware.respond(to: request, chainingTo: responder).wait() // expect an error to be reported when responder returns an errored future XCTAssertNotNil(errorReporter.capturedReportParameters) } func testReportableErrorPropertiesAreRespected() throws { struct MyError: ReportableError { let severity = Severity.info let userId: CustomStringConvertible? = 123 let metadata: [String: CustomDebugStringConvertible] = ["meta": "data"] } let error = MyError() responder.mockErrorToThrow = error _ = try? middleware.respond(to: request, chainingTo: responder).wait() guard let params = errorReporter.capturedReportParameters else { XCTFail("No error was thrown") return } XCTAssertNotNil(params.error as? MyError) XCTAssertEqual(params.metadata as? [String: String], ["meta": "data"]) XCTAssertEqual(params.severity.value, "info") XCTAssertEqual(params.userId as? Int, 123) } func testOptOutOfErrorReporting() throws { struct MyError: ReportableError { let shouldReport = false } responder.mockErrorToThrow = MyError() _ = try? middleware.respond(to: request, chainingTo: responder).wait() XCTAssertNil(errorReporter.capturedReportParameters) } }
30.290323
91
0.64196
e847bc6cd00f71c716d4cc926b91214b1ce4a021
7,297
// // JRefreshComponent.swift // JRefreshExanple // // Created by LEE on 2018/8/18. // Copyright © 2018年 LEE. All rights reserved. // import UIKit /// 刷新控件的状态 /// /// - Idle: 普通闲置状态 /// - Pulling: 松开就可以进行刷新的状态 /// - Refreshing: 正在刷新中的状态 /// - WillRefresh: 即将刷新的状态 /// - NoMoreData: 所有数据加载完毕,没有更多的数据了 public enum JRefreshState: Int { case Idle = 1 case Pulling case Refreshing case WillRefresh case NoMoreData } open class JRefreshComponent: UIView { public typealias Block = (() -> ())? //MARK: - 刷新回调 /// 正在刷新的回调 var refreshingBlock: Block? /// 回调对象 var refreshingTarget: Any? /// 回调方法 var refreshingAction: Selector? //MARK: - 刷新状态控制 ///开始刷新后的回调(进入刷新状态后的回调) var beginRefreshingCompletionBlock: Block? ///结束刷新的回调 var endRefreshingCompletionBlock: Block? ///是否正在刷新 public var refreshing: Bool { return self.state == .Refreshing || self.state == .WillRefresh } /// 刷新状态 一般交给子类内部实现 open var state: JRefreshState { didSet { // 加入主队列的目的是等setState:方法调用完毕、设置完文字后再去布局子控件 DispatchQueue.main.async { [weak self] in self?.setNeedsLayout() } } } //MARK: - 交给子类去访问 /// 记录scrollView刚开始的inset var scrollViewOriginalInset: UIEdgeInsets? ///父控件 private(set) var scrollView: UIScrollView? //MARK: - 其他 ///拉拽的百分比(交给子类重写) open var pullingPercent: CGFloat? { didSet { if self.refreshing { return } if self.automaticallyChangeAlpha ?? false { self.alpha = pullingPercent ?? 0 } } } ///根据拖拽比例自动切换透明度 public var automaticallyChangeAlpha: Bool? { willSet(_automaticallyChangeAlpha) { self.automaticallyChangeAlpha = _automaticallyChangeAlpha if self.refreshing { return } if _automaticallyChangeAlpha ?? false { self.alpha = self.pullingPercent ?? 0 } else { self.alpha = 1.0 } } } var pan: UIPanGestureRecognizer? //MARK: - 初始化 override public init(frame: CGRect) { // 默认是普通状态 state = .Idle super.init(frame: frame) // 准备工作 prepare() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func layoutSubviews() { placeSubviews() super.layoutSubviews() } override open func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) //如果不是UIScrollView,不做任何事情 guard let newSuperview = newSuperview, newSuperview.isKind(of: UIScrollView.self) else { return } // 旧的父控件移除监听 removeObservers() //设置宽度 width = newSuperview.width //设置位置 x = -(scrollView?.insetLeft ?? 0) // 记录UIScrollView scrollView = newSuperview as? UIScrollView // 设置永远支持垂直弹簧效果 scrollView?.alwaysBounceVertical = true // 记录UIScrollView最开始的contentInset scrollViewOriginalInset = scrollView?.inset //添加监听 addObservers() } override open func draw(_ rect: CGRect) { super.draw(rect) if state == .WillRefresh { // 预防view还没显示出来就调用了beginRefreshing state = .Refreshing } } } extension JRefreshComponent { //MARK: - 刷新状态控制 /// 进入刷新状态 @objc public func beginRefreshing() { UIView.animate(withDuration: JRefreshConst.fastAnimationDuration) { self.alpha = 1.0 } self.pullingPercent = 1.0 // 只要正在刷新,就完全显示 if window != nil { state = .Refreshing } else { // 预防正在刷新中时,调用本方法使得header inset回置失败 if state != .Refreshing { state = .WillRefresh // 刷新(预防从另一个控制器回到这个控制器的情况,回来要重新刷新一下) setNeedsDisplay() } } } public func beginRefreshingWithCompletionBlock(_ completionBlock: Block) { beginRefreshingCompletionBlock = completionBlock beginRefreshing() } public func endRefreshing() { DispatchQueue.main.async { [weak self] in self?.state = .Idle } } public func endRefreshingWithCompletionBlock(_ completionBlock: Block) { endRefreshingCompletionBlock = completionBlock endRefreshing() } } //MARK: - 交给子类们去实现 extension JRefreshComponent { ///初始化 @objc open func prepare() { // 基本属性 autoresizingMask = .flexibleWidth backgroundColor = UIColor.clear } ///摆放子控件frame @objc open func placeSubviews() { } ///当scrollView的contentOffset发生改变的时候调用 @objc open func scrollViewContentOffsetDidChange(_ change: [NSKeyValueChangeKey : Any]?) { } ///当scrollView的contentSize发生改变的时候调用 @objc open func scrollViewContentSizeDidChange(_ change: [NSKeyValueChangeKey : Any]?) { } ///当scrollView的拖拽状态发生改变的时候调用 @objc open func scrollViewPanStateDidChange(_ change: [NSKeyValueChangeKey : Any]?) { } } //MARK: - KVO监听 extension JRefreshComponent { func addObservers() { let options: NSKeyValueObservingOptions = [.new, .old] scrollView?.addObserver(self, forKeyPath: JRefreshKeyPath.contentOffset, options: options, context: nil) scrollView?.addObserver(self, forKeyPath: JRefreshKeyPath.contentSize, options: options, context: nil) pan = scrollView?.panGestureRecognizer pan?.addObserver(self, forKeyPath: JRefreshKeyPath.panState, options: options, context: nil) } func removeObservers() { superview?.removeObserver(self, forKeyPath: JRefreshKeyPath.contentOffset) superview?.removeObserver(self, forKeyPath: JRefreshKeyPath.contentSize) pan?.removeObserver(self, forKeyPath: JRefreshKeyPath.panState) pan = nil } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // 遇到这些情况就直接返回 if !isUserInteractionEnabled { return } // 这个就算看不见也需要处理 if keyPath == JRefreshKeyPath.contentSize { scrollViewContentSizeDidChange(change) } //看不见 if isHidden { return } if keyPath == JRefreshKeyPath.contentOffset { scrollViewContentOffsetDidChange(change) } else if keyPath == JRefreshKeyPath.panState { scrollViewPanStateDidChange(change) } } } //MARK: - 公共方法 //MARK: - 设置回调对象和回调方法 extension JRefreshComponent { /// 设置回调对象和回调方法 func setRefreshing(_ target: Any?, _ action: Selector?) { refreshingTarget = target refreshingAction = action } /// 触发回调(交给子类去调用) func executeRefreshingCallback() { DispatchQueue.main.async { [weak self] in self?.refreshingBlock??() //###消息发送无法用swift表示,objc_msgsend self?.beginRefreshingCompletionBlock??() } } }
28.282946
156
0.602028
bb43a5a88a4dedb6981cb1e4fba3b6c6dd23021f
1,099
// // AnimeCast.swift // AnimeNow // // Created by Paul Chavarria Podoliako on 6/11/15. // Copyright (c) 2015 AnyTap. All rights reserved. // import Foundation import Parse public class AnimeCast: PFObject, PFSubclassing { override public class func initialize() { struct Static { static var onceToken : dispatch_once_t = 0; } dispatch_once(&Static.onceToken) { self.registerSubclass() } } public class func parseClassName() -> String { return "AnimeCast" } @NSManaged public var cast: [[String:AnyObject]] public struct Cast { public var castID: Int = 0 public var image: String = "" public var name: String = "" public var job: String = "" } public func castAtIndex(index: Int) -> Cast { let data = cast[index] return Cast( castID: (data["id"] as! Int), image: (data["image"] as! String), name: (data["name"] as! String), job: (data["rank"] as! String) ) } }
23.891304
55
0.55323
6742bbf69eb8e59156039de8ee38b31f2ebc0e23
3,026
// // Bumper.swift // Pods // // Created by Eli Kohen on 21/09/16. // Copyright © 2016 Letgo. All rights reserved. // import Foundation import RxSwift public class Bumper { // MARK: - Public static public static var enabled: Bool { return Bumper.sharedInstance.enabled } public static func initialize(_ bumperFeatures: [BumperFeature.Type]) { Bumper.sharedInstance.initialize(bumperFeatures) } public static func value(for key: String) -> String? { return Bumper.sharedInstance.value(for: key) } // MARK: - Internal static let sharedInstance: Bumper = Bumper(bumperDAO: UserDefaults.standard) private static let bumperEnabledKey = "bumper_enabled" private static let bumperPrefix = "bumper_" var enabled: Bool = false { didSet { bumperDAO.set(enabled, forKey: Bumper.bumperEnabledKey) } } private var cache = [String: String]() private var features: [BumperFeature.Type] = [] var bumperViewData: [BumperViewData] { return features.flatMap { featureType in let value = self.value(for: featureType.key) ?? featureType.defaultValue return BumperViewData(key: featureType.key, description: featureType.description, value: value, options: featureType.values) } } private let bumperDAO: BumperDAO init(bumperDAO: BumperDAO) { self.bumperDAO = bumperDAO } func initialize(_ bumperFeatures: [BumperFeature.Type]) { enabled = bumperDAO.bool(forKey: Bumper.bumperEnabledKey) cache.removeAll() features = bumperFeatures features.forEach({ guard let value = bumperDAO.string(forKey: Bumper.bumperPrefix + $0.key) else { return } cache[$0.key] = $0.values.contains(value) ? value : $0.defaultValue }) } func update(with values: [[String: Any]]) { values.forEach { dict in guard let value = dict["value"] as? String, let key = dict["key"] as? String else { return } cache[key] = value } } func value(for key: String) -> String? { return cache[key] } func setValue(for key: String, value: String) { cache[key] = value bumperDAO.set(value, forKey: Bumper.bumperPrefix + key) } } extension Bumper { public static var enabledObservable: Observable<Bool> { return Bumper.sharedInstance.enabledObservable } public static func observeValue(for key: String) -> Observable<String?> { return Bumper.sharedInstance.observeValue(for: key) } var enabledObservable: Observable<Bool> { return bumperDAO.boolObservable(for: Bumper.bumperEnabledKey).map { $0 ?? false } } func observeValue(for key: String) -> Observable<String?> { return bumperDAO.stringObservable(for: Bumper.bumperPrefix + key) } }
28.018519
100
0.61996
fcdd2247b32da52af06b0f57c179813902b96a99
866
// // ManualLayout.swift // // // Created by Artur Carneiro on 28/09/20. // import UIKit /** Property wrapper used to make it easier to instantiate a `UIView` or its subclasses ready for Auto layout. - important: You should only use this property wrapper if you only need the object to be initialized with the following init: `init(frame: .zero)`. */ @propertyWrapper final class ManualLayout<View: UIView> { /** A lazily instantiated `UIView` or `UIView` subclass with the `translatesAutoresizingMaskIntoConstraints` property set as `false`. */ private lazy var view: View = { let view = View(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false return view }() /// The read-only wrapped `UIView` or `UIView` subclass. var wrappedValue: View { return view } }
24.742857
69
0.67321
018e5d8534c1895b889094ec9e0bc94b152cd726
1,109
// // ExamHistoryModel.swift // Hyakuninisshu // // Created by Rei Matsushita on 2021/01/11. // import Combine import Foundation protocol ExamHistoryModelProtocol: AnyObject { func fetchScores() -> AnyPublisher<[PlayScore], PresentationError> } class ExamHistoryModel: ExamHistoryModelProtocol { private let examHistoryRepository: ExamHistoryRepository init(examHistoryRepository: ExamHistoryRepository) { self.examHistoryRepository = examHistoryRepository } func fetchScores() -> AnyPublisher<[PlayScore], PresentationError> { let publisher = examHistoryRepository.findCollection().map { examHistoryCollection -> [PlayScore] in return examHistoryCollection.values.map { examHistory in let score = Score( denominator: examHistory.score.totalQuestionCount, numerator: examHistory.score.correctCount) return PlayScore( tookDate: examHistory.tookDate, score: score, averageAnswerSec: examHistory.score.averageAnswerSec) } } return publisher.mapError { PresentationError($0) }.eraseToAnyPublisher() } }
29.972973
77
0.7367
dd21bdda581f66d5f595596c14c4ca8a712b95fc
2,133
// // GameViewController.swift // first game // // Created by 王培英 on 15/7/20. // Copyright (c) 2015年 王培英. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : String) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
30.471429
104
0.62166
14d0c9f8e22f666dc025cca90bc8a497254e0b08
921
import Foundation import UIKit extension DeliveryListViewController: UITableViewDelegate, UIScrollViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let delivery = deliveryListViewModel.getDeliveryFor(index: indexPath.row) let viewModel = DeliveryDetailsViewModel(delivery: delivery) let deliveryDetails = DeliveryDetailsViewController(deliveryDetailsViewModel: viewModel) navigationController?.pushViewController(deliveryDetails, animated: true) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if deliveryListViewModel.shouldFetchNextData(index: indexPath.row) { tableView.tableFooterView = self.tableViewFooterRefresh self.tableViewFooterRefresh.startAnimating() deliveryListViewModel.getNextPageData() } } }
43.857143
112
0.762215
751dfe0f5a4397d095a988a42d532012f3e9ca02
549
// // GetFolderRequest.swift // zScanner // // Created by Jakub Skořepa on 11/08/2019. // Copyright © 2019 Institut klinické a experimentální medicíny. All rights reserved. // import Foundation struct SearchFoldersRequest: Request, ParametersURLEncoded { typealias DataType = [FolderNetworkModel] var endpoint: Endpoint = MedicalcEndpoint.folderSearch var method: HTTPMethod = .get var parameters: Parameters? var headers: HTTPHeaders = [:] init(query: String) { parameters = ["query": query] } }
23.869565
86
0.693989
d9c9709092ef6fdd6465dcd81ab94a29a24586c4
5,907
// // MethodParser.swift // XCodePlugin // // Created by Александр Кравченков on 21/10/2018. // Copyright © 2018 Александр Кравченков. All rights reserved. // import Foundation extension AccessType { static var allCAses: [AccessType] { return [.private, .public, .internal, .fileprivate] } static var stringCases: [String] { return allCAses.map { "\($0) " } } } public class MethodParser { public enum ParseError: Error, LocalizedError { case cantParseMethod case cantParseMethodReturnTypeExpression case cantParseAccessType case cantParseMetaMethodInformation case cantParseName } public static func parse(sources: [String]) throws { for line in sources { let trimmedLine = line.trimmed let regExpPattern = "\(AccessType.stringCases)?func\\(.*\\) ?(-> ?([A-Z,a-z]+)?)? *{" let regExp = try! NSRegularExpression(pattern: regExpPattern, options: []) let matches = regExp.matches(in: trimmedLine, options: [.anchored], range: NSRange(0..<trimmedLine.count)) guard matches.count == 1, let firstMathed = matches.first, let stringRange = Range<String.Index>(firstMathed.range, in: line) else { throw ParseError.cantParseMethod } let decalration = trimmedLine.substring(with: stringRange) var needsToMatch = false var saveSymbols = false var searchStart = true var searchEnd = false var openBraketsCount = 0 var resultString = "" for character in decalration { if searchStart { if character == "<" { needsToMatch = true } else if character == ">" { needsToMatch = false } else if character == "(" && !needsToMatch { saveSymbols = true searchEnd = true searchStart = false } } else if searchEnd { if character == "(" { openBraketsCount += 1 } else if character == ")" { if openBraketsCount == 0 { break } else { openBraketsCount-=1 } } resultString.append(character) } } let parameters = try parseParameters(string: resultString) let returnType = try parseReturnType(string: decalration) let splitedByWhitespace = decalration.split(separator: " ") // private static func blablabla() -> dfsdf var accessType: AccessType var isStatic = false if splitedByWhitespace[0] == "static" { isStatic = true if splitedByWhitespace[1] == "func" { accessType = .private } else if let guardedAccessType = AccessType(rawValue: String(splitedByWhitespace[1])) { accessType = guardedAccessType } else { throw ParseError.cantParseAccessType } } else if let guardedAccessType = AccessType(rawValue: String(splitedByWhitespace[0])) { accessType = guardedAccessType if splitedByWhitespace[1] == "static" { isStatic = true } } else { throw ParseError.cantParseMetaMethodInformation } let splitedByOpenBraket = decalration.split(separator: "(") guard let itemBeforeBrakets = decalration.split(separator: "(").first else { throw ParseError.cantParseName } var nameDeclaration = String(itemBeforeBrakets).trimmed.reversed() var name = "" for character in nameDeclaration { if character == " " { break } else { name.append(character) } } return Function(parameters: parameters, returnType: returnType, name: name, accessType: accessType, isStatic: isStatic) } } /// Expected method arguments like this: `var: Type, var: Type` public static func parseParameters(string: String) throws -> [Parameter] { let delimeter: Character = "," let splitedByDeclaration = string.split(separator: delimeter) var parameters = [Parameter]() for item in splitedByDeclaration { let parameter = try ParameterParser.parse(from: String(item)) parameters.append(parameter) } return parameters } /// Excpected function declaration like 'private func(foo: Bar) -> Type {' public static func parseReturnType(string: String) throws -> String { var findFlag = false // index of '>' character var lastIndex = 0 for (index, character) in string.enumerated() { if character == "-" { findFlag = true } else if findFlag && character == ">" { lastIndex = index break } else { findFlag = false } } guard findFlag else { return "Void" } let startIndex = string.index(string.startIndex, offsetBy: lastIndex) let currentIndex = string.index(after: startIndex) let typeDeclaration = string[currentIndex...] let replaced = typeDeclaration .replacingOccurrences(of: "{", with: "") .replacingOccurrences(of: "}", with: "") return String(replaced).trimmed } }
33.185393
131
0.531065
1472faa738695ec969a2926c90caff3446b60dbf
1,866
// // EventDetailView.swift // SwiftySeatGeek // import SwiftUI struct EventDetailView: View { @ObservedObject var viewModel: EventViewModel var body: some View { VStack(alignment: .leading) { HStack(alignment: .top) { Text(viewModel.title) .font(.title) .fontWeight(.bold) Spacer() if viewModel.favorite { Image("HeartFilled") .resizable() .frame(width: 25, height: 25) .onTapGesture { viewModel.favorite = false } } else { Image("HeartHollow") .resizable() .frame(width: 25, height: 25) .onTapGesture { viewModel.favorite = true } } } .padding(.top) AsyncImageView(url: viewModel.image) .aspectRatio(contentMode: .fit) .padding(.leading) .padding(.trailing) .padding(.bottom) Text(viewModel.showtime) .font(.title2) .fontWeight(.bold) Text(viewModel.location) .font(.title3) .fontWeight(.semibold) .foregroundColor(.secondary) Spacer() } .padding(.leading) .padding(.trailing) .navigationTitle("Details") .navigationBarTitleDisplayMode(.inline) } } struct EventDetailView_Previews: PreviewProvider { static var previews: some View { NavigationView { EventDetailView(viewModel: EventViewModel(event: Event.mocks.first!)) } } }
29.619048
81
0.457663
dbe68b4b56c83d0052fac8117cfd1b6cd48917f2
6,264
// License Agreement for FDA MyStudies // Copyright © 2017-2019 Harvard Pilgrim Health Care Institute (HPHCI) and its Contributors. Permission is // hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the &quot;Software&quot;), 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. // Funding Source: Food and Drug Administration (“Funding Agency”) effective 18 September 2014 as // Contract no. HHSF22320140030I/HHSF22301006T (the “Prime Contract”). // THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT // OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. import SlideMenuControllerSwift import UIKit let kStudyListViewControllerIdentifier = "StudyListViewController" let kStudyHomeViewControllerIdentifier = "StudyHomeNavigationController" let kLeftMenuViewControllerIdentifier = "LeftMenuViewController" open class FDASlideMenuViewController: SlideMenuController { override open var preferredStatusBarStyle: UIStatusBarStyle { return .default } override open func awakeFromNib() { SlideMenuOptions.leftViewWidth = UIScreen.main.bounds.size.width * 0.81 let storyboard = UIStoryboard(name: kStoryboardIdentifierGateway, bundle: nil) if Utilities.isStandaloneApp() { let studyStoryBoard = UIStoryboard.init(name: kStudyStoryboard, bundle: Bundle.main) if Study.currentStudy?.userParticipateState.status == .inProgress { let studyTabBarController = studyStoryBoard.instantiateViewController( withIdentifier: kStudyDashboardTabbarControllerIdentifier ) as! StudyDashboardTabbarViewController self.mainViewController = studyTabBarController } else { let studyHomeViewController = studyStoryBoard.instantiateViewController( withIdentifier: String(describing: kStudyHomeViewControllerIdentifier) ) as! UINavigationController self.mainViewController = studyHomeViewController } } else { // Gateway- Studylist let controller = storyboard.instantiateViewController( withIdentifier: kStudyListViewControllerIdentifier ) self.mainViewController = controller } let controller2 = storyboard.instantiateViewController( withIdentifier: kLeftMenuViewControllerIdentifier ) self.leftViewController = controller2 super.awakeFromNib() } override open func isTagetViewController() -> Bool { if let vc = UIApplication.topViewController() { if Utilities.isStandaloneApp() { if vc is StudyHomeViewController || vc is NotificationViewController || vc is GatewayResourcesListViewController || vc is ProfileViewController { return true } } else { if vc is StudyListViewController || vc is NotificationViewController || vc is GatewayResourcesListViewController || vc is ProfileViewController { return true } } } return false } override open func track(_ trackAction: TrackAction) { switch trackAction { case .leftTapOpen: break case .leftTapClose: break case .leftFlickOpen: break case .leftFlickClose: break case .rightTapOpen: break case .rightTapClose: break case .rightFlickOpen: break case .rightFlickClose: break } } /// Take user to Home after they Sign out. func navigateToHomeAfterSignout() { self.leftViewController?.view.isHidden = true _ = self.navigationController?.popToRootViewController(animated: true) let navVC: UINavigationController = UIApplication.shared.keyWindow?.rootViewController as! UINavigationController if navVC.viewControllers.count > 0 { let splashVC: SplashViewController = navVC.viewControllers.first as! SplashViewController splashVC.navigateToGatewayDashboard() } } /// This method will delete all the DB data and logout user after unauthorized access. func navigateToHomeAfterUnauthorizedAccess() { User.resetCurrentUser() // Delete from database DBHandler.deleteAll() if ORKPasscodeViewController.isPasscodeStoredInKeychain() { ORKPasscodeViewController.removePasscodeFromKeychain() } // Cancel all local notification LocalNotification.cancelAllLocalNotification() let ud = UserDefaults.standard ud.removeObject(forKey: kUserAuthToken) ud.removeObject(forKey: kUserId) ud.synchronize() let appDomain = Bundle.main.bundleIdentifier! UserDefaults.standard.removePersistentDomain(forName: appDomain) UserDefaults.standard.synchronize() self.leftViewController?.view.isHidden = true _ = self.navigationController?.popToRootViewController(animated: true) } // MARK: - Unwind Actions func navigateToHomeControllerForSignin() { self.performSegue(withIdentifier: "unwindToHomeSignin", sender: self) } func navigateToHomeControllerForRegister() { self.performSegue(withIdentifier: "unwindToHomeRegister", sender: self) } } extension UIViewController { public func fdaSlideMenuController() -> FDASlideMenuViewController? { var viewController: UIViewController? = self while viewController != nil { if viewController is FDASlideMenuViewController { return viewController as? FDASlideMenuViewController } viewController = viewController?.parent } return nil } }
34.607735
113
0.732918
9cf39022ebb54df53e7021be55e2914f0de30d1a
1,033
import UIKit protocol ThemeProtocol { var backgroundColor: UIColor { get } var textColor: UIColor { get } } class Theme: ThemeProtocol { var backgroundColor: UIColor var textColor: UIColor init(backgroundColor: UIColor, textColor: UIColor) { self.backgroundColor = backgroundColor self.textColor = textColor } } protocol ThemeBuilderProtocol { func setBackground(color: UIColor) func setText(color: UIColor) func createTheme() -> ThemeProtocol? } class ThemeBuilder: ThemeBuilderProtocol { private var backgroundColor: UIColor? private var textColor: UIColor? func setBackground(color: UIColor) { backgroundColor = color } func setText(color: UIColor) { textColor = color } func createTheme() -> ThemeProtocol? { guard let backgroundColor = backgroundColor, let textColor = textColor else { return nil } return Theme(backgroundColor: backgroundColor, textColor: textColor) } }
18.122807
98
0.672798
f9db7a9fb8c8278679d56f3eccaf5c98966434b2
14,492
// // The MIT License (MIT) // // Copyright (c) 2018 DeclarativeHub/Bond // // 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 OrderedCollectionDiff where Index == IndexPath { /// Calculates diff from the given patch. /// - complexity: O(Nˆ2) where N is the number of patch operations. public init<T>(from patch: [OrderedCollectionOperation<T, IndexPath>]) { self.init(from: patch.map { $0.asAnyOrderedCollectionOperation }) } /// Calculates diff from the given patch. /// - complexity: O(Nˆ2) where N is the number of patch operations. public init(from patch: [AnyOrderedCollectionOperation<Index>]) { self.init() guard !patch.isEmpty else { return } for patchSoFar in (1...patch.count).map({ patch.prefix(upTo: $0) }) { let patchToUndo = Array(patchSoFar.dropLast()) switch patchSoFar.last! { case .insert(let atIndex): recordInsertion(at: atIndex, patch: patchToUndo) case .delete(let atIndex): let sourceIndex = AnyOrderedCollectionOperation<Index>.undo(patch: patchToUndo, on: atIndex) recordDeletion(at: atIndex, sourceIndex: sourceIndex, patch: patchToUndo) case .update(let atIndex): let sourceIndex = AnyOrderedCollectionOperation<Index>.undo(patch: patchToUndo, on: atIndex) recordUpdate(at: atIndex, sourceIndex: sourceIndex, patch: patchToUndo) case .move(let fromIndex, let toIndex): let sourceIndex = AnyOrderedCollectionOperation<Index>.undo(patch: patchToUndo, on: fromIndex) recordMove(from: fromIndex, to: toIndex, sourceIndex: sourceIndex, patch: patchToUndo) } } } private func updatesInFinalCollection(given patch: [AnyOrderedCollectionOperation<Index>]) -> [Index?] { return updates.map { AnyOrderedCollectionOperation.simulate(patch: patch, on: $0) } } private mutating func recordInsertion(at insertionIndex: Index, patch: [AnyOrderedCollectionOperation<Index>]) { // If inserting into an inserted subtree, skip if inserts.contains(where: { $0.isAncestor(of: insertionIndex) }) { return } // If inserting into an updated subtree, skip if updatesInFinalCollection(given: patch).contains(where: { $0 != nil && $0!.isAncestor(of: insertionIndex) }) { return } forEachDestinationIndex { (index) in if index.isAffectedByDeletionOrInsertion(at: insertionIndex) { index = index.shifted(by: 1, atLevelOf: insertionIndex) } } inserts.append(insertionIndex) } private mutating func recordDeletion(at deletionIndex: Index, sourceIndex: Index?, patch: [AnyOrderedCollectionOperation<Index>]) { func adjustDestinationIndices() { forEachDestinationIndex { (index) in if index.isAffectedByDeletionOrInsertion(at: deletionIndex) { index = index.shifted(by: -1, atLevelOf: deletionIndex) } } } let _updatesInFinalCollection = updatesInFinalCollection(given: patch) // If deleting from an updated subtree, skip if _updatesInFinalCollection.contains(where: { $0 != nil && $0!.isAncestor(of: deletionIndex) }) { return } // If deleting from a previously inserted subtree, skip if inserts.contains(where: { $0.isAncestor(of: deletionIndex) }) { return } // If deleting previously inserted subtree, undo insertion if let index = inserts.firstIndex(where: { $0 == deletionIndex }) { inserts.remove(at: index) adjustDestinationIndices() return } guard let sourceIndex = sourceIndex else { // All possible reason for sourceIndex being nil should have been handled by now fatalError() } // If there are moves into the deleted subtree, replaces them with deletions for (i, move) in moves.enumerated().filter({ deletionIndex.isAncestor(of: $0.element.to) }).reversed() { deletes.append(move.from) moves.remove(at: i) } // If deleting an update or a parent of an update, remove the update for index in _updatesInFinalCollection.indices(where: { $0 == deletionIndex || ($0 != nil && deletionIndex.isAncestor(of: $0!)) }).reversed() { updates.remove(at: index) } // If there are insertions within deleted subtree, remove them inserts.removeAll(where: { deletionIndex.isAncestor(of: $0) }) // If deleting previously moved element, replace move with deletion if let index = moves.firstIndex(where: { $0.to == deletionIndex }) { let move = moves[index] moves.remove(at: index) deletes.append(move.from) adjustDestinationIndices() return } deletes.append(sourceIndex) adjustDestinationIndices() } private mutating func recordUpdate(at updateIndex: Index, sourceIndex: Index?, patch: [AnyOrderedCollectionOperation<Index>]) { // If updating an inserted index or in a such subtree if inserts.contains(where: { $0 == updateIndex || $0.isAncestor(of: updateIndex) }) { return } // If updating an updated index or in a such subtree if updatesInFinalCollection(given: patch).compactMap({ $0 }).contains(where: { $0 == updateIndex || $0.isAncestor(of: updateIndex) }) { return } // If there are insertions within the updated subtree, remove them inserts.removeAll(where: { updateIndex.isAncestor(of: $0) }) // If there are moves into the updated subtree, replaces them with deletions var additionalPatch: [AnyOrderedCollectionOperation<Index>] = [] while let move = moves.first(where: { updateIndex.isAncestor(of: $0.to) }) { recordDeletion(at: move.to, sourceIndex: move.from, patch: patch + additionalPatch) additionalPatch.append(.delete(at: move.to)) } // If updating previously moved index, replace move with delete+insert if let index = moves.firstIndex(where: { $0.to == updateIndex }) { replaceMoveWithDeleteInsert(atIndex: index) return } guard let sourceIndex = sourceIndex else { // All possible reason for sourceIndex being nil should have been handled by now fatalError() } updates.removeAll(where: { sourceIndex.isAncestor(of: $0) }) deletes.removeAll(where: { sourceIndex.isAncestor(of: $0) }) // If there are moves from the updated tree, remove them and their dependencies var isObliterated = false while let index = moves.firstIndex(where: { sourceIndex.isAncestor(of: $0.from) }) { let move = moves[index] moves.remove(at: index) if !inserts.contains(where: { $0.isAncestor(of: move.to) }) { inserts.append(move.to) inserts.removeAll(where: { move.to.isAncestor(of: $0) }) } while let index = moves.firstIndex(where: { move.to.isAncestor(of: $0.to) }) { let move = moves[index] moves.remove(at: index) if !sourceIndex.isAncestor(of: move.from) { deletes.append(move.from) updates.removeAll(where: { update in move.from.isAncestor(of: update) }) isObliterated = isObliterated || move.from.isAncestor(of: sourceIndex) } } } if !isObliterated { updates.append(sourceIndex) } } private mutating func recordMove(from fromIndex: Index, to toIndex: Index, sourceIndex: Index?, patch: [AnyOrderedCollectionOperation<Index>]) { guard fromIndex != toIndex else { return } // If moving previously inserted subtree, replace with the insertion at the new index if inserts.contains(where: { $0 == fromIndex }) { recordDeletion(at: fromIndex, sourceIndex: sourceIndex, patch: patch) recordInsertion(at: toIndex, patch: patch + [.delete(at: fromIndex)]) return } // If moving previously updated subtree, replace with the insertion at the new index if updatesInFinalCollection(given: patch).contains(where: { $0 == fromIndex }) { recordDeletion(at: fromIndex, sourceIndex: sourceIndex, patch: patch) recordInsertion(at: toIndex, patch: patch + [.delete(at: fromIndex)]) return } // If moving from a previously inserted subtree, replace with insert if inserts.contains(where: { $0.isAncestor(of: fromIndex) }) { recordInsertion(at: toIndex, patch: patch) return } // If moving from a previously updated subtree, replace with insert if updatesInFinalCollection(given: patch).contains(where: { $0?.isAncestor(of: fromIndex) ?? false }) { recordInsertion(at: toIndex, patch: patch) return } // If moving into a previously updated subtree, replace with delete if updatesInFinalCollection(given: patch + [.delete(at: fromIndex)]).contains(where: { $0?.isAncestor(of: toIndex) ?? false }) { recordDeletion(at: fromIndex, sourceIndex: sourceIndex, patch: patch) return } // If moving previously updated element if let i = updatesInFinalCollection(given: patch).firstIndex(where: { $0 == fromIndex }) { updates.remove(at: i) recordDeletion(at: fromIndex, sourceIndex: sourceIndex, patch: patch) recordInsertion(at: toIndex, patch: patch) return } let offsetInserts: [Index] = inserts.map { index in if fromIndex.isAncestor(of: index) { return index.replacingAncestor(fromIndex, with: toIndex) } else if index.isAffectedByDeletionOrInsertion(at: fromIndex) { return index.shifted(by: -1, atLevelOf: fromIndex) } else { return index } } // If moving into a previously inserted subtree, replace with delete if offsetInserts.contains(where: { $0.isAncestor(of: toIndex) }) { recordDeletion(at: fromIndex, sourceIndex: sourceIndex, patch: patch) return } var insertsIntoSubtree: [Int] = [] var movesIntoSubtree: [Int] = [] func adjustDestinationIndices() { forEachDestinationIndex(insertsToSkip: Set(insertsIntoSubtree), movesToSkip: Set(movesIntoSubtree)) { (index) in if index.isAffectedByDeletionOrInsertion(at: fromIndex) { index = index.shifted(by: -1, atLevelOf: fromIndex) } } forEachDestinationIndex(insertsToSkip: Set(insertsIntoSubtree), movesToSkip: Set(movesIntoSubtree)) { (index) in if index.isAffectedByDeletionOrInsertion(at: toIndex) { index = index.shifted(by: 1, atLevelOf: toIndex) } } } // If there are inserts into a moved subtree, update them for i in inserts.indices(where: { fromIndex.isAncestor(of: $0) }) { inserts[i] = inserts[i].replacingAncestor(fromIndex, with: toIndex) insertsIntoSubtree.append(i) } // If there are moves into a moved subtree, update them for i in moves.indices(where: { fromIndex.isAncestor(of: $0.to) }) { moves[i].to = moves[i].to.replacingAncestor(fromIndex, with: toIndex) movesIntoSubtree.append(i) } // If moving previously moved element, update move to index (subtrees should be handled at this point) if let i = moves.indices.filter({ moves[$0].to == fromIndex && !movesIntoSubtree.contains($0) }).first { adjustDestinationIndices() moves[i].to = toIndex return } adjustDestinationIndices() moves.append((from: sourceIndex!, to: toIndex)) } private mutating func replaceMoveWithDeleteInsert(atIndex index: Int) { let move = moves[index] moves.remove(at: index) while let index = moves.firstIndex(where: { move.from.isAncestor(of: $0.from) || move.to.isAncestor(of: $0.to) }) { replaceMoveWithDeleteInsert(atIndex: index) } updates.removeAll(where: { move.from.isAncestor(of: $0) }) deletes.removeAll(where: { move.from.isAncestor(of: $0) }) inserts.removeAll(where: { move.to.isAncestor(of: $0 )}) deletes.append(move.from) if !inserts.contains(where: { $0.isAncestor(of: move.to) }) { inserts.append(move.to) } } private mutating func forEachDestinationIndex(insertsToSkip: Set<Int> = [], movesToSkip: Set<Int> = [], apply: (inout Index) -> Void) { for i in 0..<inserts.count where !insertsToSkip.contains(i) { apply(&inserts[i]) } for i in 0..<moves.count where !movesToSkip.contains(i) { apply(&moves[i].to) } } }
43.51952
151
0.622343
4692d3b493fb4b049a9f358aadc1e42b521f82ee
1,811
import Combine import SwiftUI import PlaygroundSupport let source = Timer .publish(every: 1.0, on: .main, in: .common) .autoconnect() .scan(0) { (counter, _) in counter + 1 } <# Add code here #> //: [Next](@next) /*: 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. 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. */
42.116279
80
0.775262
d959de51469b1cd5767c72378c1b658af561ff19
3,410
// // KinTestService.swift // KinBase // // Created by Kik Interactive Inc. // Copyright © 2020 Kin Foundation. All rights reserved. // import Foundation import Promises public protocol KinTestServiceType { func fundAccount(_ accountId: KinAccount.Id) -> Promise<Void> } public class KinTestService: KinTestServiceType { public enum Errors: Error { case unknown case transientFailure(error: Error) } private let friendBotApi: FriendBotApi private let networkOperationHandler: NetworkOperationHandler init(friendBotApi: FriendBotApi, networkOperationHandler: NetworkOperationHandler) { self.friendBotApi = friendBotApi self.networkOperationHandler = networkOperationHandler } public func fundAccount(_ accountId: KinAccount.Id) -> Promise<Void> { return networkOperationHandler.queueWork { [weak self] respond in guard let self = self else { respond.onError?(Errors.unknown) return } self.friendBotApi.fundAccount(request: CreateAccountRequest(accountId: accountId)) { (response) in switch response.result { case .ok: respond.onSuccess(()) default: var error = Errors.unknown if let transientError = response.error { error = Errors.transientFailure(error: transientError) } respond.onError?(error) } } } } } public class KinTestServiceV4: KinTestServiceType { public enum Errors: Error { case unknown case transientFailure(error: Error) } private let airdropApi: KinAirdropApi private let networkOperationHandler: NetworkOperationHandler private let kinService: KinServiceV4 init(airdropApi: KinAirdropApi, kinService: KinServiceV4, networkOperationHandler: NetworkOperationHandler) { self.airdropApi = airdropApi self.networkOperationHandler = networkOperationHandler self.kinService = kinService } public func fundAccount(_ accountId: KinAccount.Id) -> Promise<Void> { return networkOperationHandler.queueWork { [weak self] respond in guard let self = self else { respond.onError?(Errors.unknown) return } self.airdropApi.airdrop(request: AirdropRequest(accountId: accountId, kin: 10)) { (response) in switch response.result { case .ok: respond.onSuccess(()) default: self.kinService.resolveTokenAccounts(accountId: accountId) .then { accounts in self.airdropApi.airdrop(request: AirdropRequest(accountId: accounts.first?.accountId ?? accountId, kin: 10)) { (response) in switch response.result { case .ok: respond.onSuccess(()) default: respond.onError?(Errors.unknown) } } } respond.onError?(Errors.unknown) } } } } }
34.444444
152
0.567742
4894dca817f093fecdb5db6d69b0ac8bca51e0e3
5,582
import Git import UIKit final class Cloud: Sheet, UITextFieldDelegate { private weak var field: UITextField! private weak var loading: UIImageView! private weak var button: Button.Yes! private weak var cancel: Button.No! required init?(coder: NSCoder) { return nil } @discardableResult override init() { super.init() let border = UIView() border.isUserInteractionEnabled = true border.translatesAutoresizingMaskIntoConstraints = false border.backgroundColor = .halo base.addSubview(border) let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = .systemFont(ofSize: 13, weight: .medium) label.textColor = .halo label.text = .key("Cloud.field") base.addSubview(label) let field = UITextField() field.translatesAutoresizingMaskIntoConstraints = false field.tintColor = .white field.textColor = .white field.delegate = self field.font = .systemFont(ofSize: 15, weight: .regular) field.autocorrectionType = .no field.autocapitalizationType = .none field.spellCheckingType = .no field.clearButtonMode = .never field.keyboardAppearance = .dark field.keyboardType = .URL base.addSubview(field) self.field = field let button = Button.Yes(app.repository == nil ? .key("Cloud.clone.button") : .key("Cloud.synch.button")) button.addTarget(self, action: #selector(make), for: .touchUpInside) base.addSubview(button) self.button = button let cancel = Button.No(.key("Cloud.cancel")) cancel.addTarget(self, action: #selector(close), for: .touchUpInside) base.addSubview(cancel) self.cancel = cancel let loading = UIImageView(image: UIImage(named: "loading")) loading.translatesAutoresizingMaskIntoConstraints = false loading.clipsToBounds = true loading.contentMode = .center loading.isHidden = true base.addSubview(loading) self.loading = loading label.topAnchor.constraint(equalTo: field.topAnchor).isActive = true label.leftAnchor.constraint(equalTo: base.leftAnchor, constant: 20).isActive = true label.heightAnchor.constraint(equalTo: field.heightAnchor).isActive = true field.topAnchor.constraint(equalTo: base.topAnchor, constant: 30).isActive = true field.heightAnchor.constraint(equalToConstant: 50).isActive = true field.leftAnchor.constraint(equalTo: base.leftAnchor, constant: 70).isActive = true field.rightAnchor.constraint(equalTo: base.rightAnchor, constant: -20).isActive = true border.topAnchor.constraint(equalTo: field.bottomAnchor).isActive = true border.leftAnchor.constraint(equalTo: base.leftAnchor, constant: 20).isActive = true border.rightAnchor.constraint(equalTo: base.rightAnchor, constant: -20).isActive = true border.heightAnchor.constraint(equalToConstant: 1).isActive = true button.topAnchor.constraint(equalTo: border.bottomAnchor, constant: 20).isActive = true button.centerXAnchor.constraint(equalTo: base.centerXAnchor).isActive = true loading.widthAnchor.constraint(equalToConstant: 100).isActive = true loading.heightAnchor.constraint(equalToConstant: 40).isActive = true loading.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true loading.centerYAnchor.constraint(equalTo: button.centerYAnchor).isActive = true cancel.topAnchor.constraint(equalTo: button.bottomAnchor, constant: 20).isActive = true cancel.centerXAnchor.constraint(equalTo: base.centerXAnchor).isActive = true cancel.bottomAnchor.constraint(equalTo: base.bottomAnchor, constant: -20).isActive = true app.repository?.remote { [weak self] in self?.field.text = $0 } } func textFieldDidEndEditing(_: UITextField) { app.repository?.remote(field.text!) } func textFieldShouldReturn(_: UITextField) -> Bool { field.resignFirstResponder() return true } private func ready() { button.isHidden = false loading.isHidden = true field.isEnabled = true } @objc private func make() { field.resignFirstResponder() button.isHidden = true loading.isHidden = false field.isEnabled = false if app.repository == nil { Hub.clone(field.text!, local: Hub.session.url, error: { [weak self] in app.alert(.key("Alert.error"), message: $0.localizedDescription) self?.ready() }) { [weak self] in app.alert(.key("Alert.success"), message: .key("Cloud.clone.success")) app.load() self?.close() } } else { app.repository!.pull({ [weak self] in app.alert(.key("Alert.error"), message: $0.localizedDescription) self?.ready() }) { [weak self] in app.repository!.push({ [weak self] in app.alert(.key("Alert.error"), message: $0.localizedDescription) self?.ready() }) { [weak self] in app.alert(.key("Alert.success"), message: .key("Cloud.synch.success")) self?.close() } } } } }
42.610687
112
0.629165
1d8c5a52ab773927be5d28f291acece754b739d0
7,758
// // VehicleDataManager.swift // SmartDeviceLink // // Created by Nicole on 4/13/18. // Copyright © 2018 smartdevicelink. All rights reserved. // import Foundation import SmartDeviceLink import SmartDeviceLinkSwift class VehicleDataManager: NSObject { fileprivate let sdlManager: SDLManager! fileprivate var refreshUIHandler: RefreshUIHandler? public fileprivate(set) var vehicleOdometerData: String init(sdlManager: SDLManager, refreshUIHandler: RefreshUIHandler? = nil) { self.sdlManager = sdlManager self.refreshUIHandler = refreshUIHandler self.vehicleOdometerData = "" super.init() resetOdometer() NotificationCenter.default.addObserver(self, selector: #selector(vehicleDataNotification(_:)), name: .SDLDidReceiveVehicleData, object: nil) } } // MARK: - Subscribe Vehicle Data extension VehicleDataManager { /// Subscribes to odometer data. You must subscribe to a notification with name `SDLDidReceiveVehicleData` to get the new data when the odometer data changes. func subscribeToVehicleOdometer() { let subscribeToVehicleOdometer = SDLSubscribeVehicleData() subscribeToVehicleOdometer.odometer = true sdlManager.send(request: subscribeToVehicleOdometer) { [unowned self] (request, response, error) in guard let result = response?.resultCode else { return } if error != nil { SDLLog.e("Error sending Get Vehicle Data RPC: \(error!.localizedDescription)") } var message = "\(VehicleDataOdometerName): " switch result { case .success: SDLLog.d("Subscribed to vehicle odometer data") message += "Subscribed" case .disallowed: SDLLog.d("Access to vehicle data disallowed") message += "Disallowed" case .userDisallowed: SDLLog.d("Vehicle user disabled access to vehicle data") message += "Disabled" case .ignored: SDLLog.d("Already subscribed to odometer data") message += "Subscribed" case .dataNotAvailable: SDLLog.d("You have permission to access to vehicle data, but the vehicle you are connected to did not provide any data") message += "Unknown" default: SDLLog.e("Unknown reason for failure to get vehicle data: \(error != nil ? error!.localizedDescription : "no error message")") message += "Unsubscribed" return } self.vehicleOdometerData = message guard let handler = self.refreshUIHandler else { return } handler() } } /// Unsubscribes to vehicle odometer data. func unsubscribeToVehicleOdometer() { let unsubscribeToVehicleOdometer = SDLUnsubscribeVehicleData() unsubscribeToVehicleOdometer.odometer = true sdlManager.send(request: unsubscribeToVehicleOdometer) { (request, response, error) in guard let response = response, response.resultCode == .success else { return } self.resetOdometer() } } /// Notification containing the updated vehicle data. /// /// - Parameter notification: A SDLOnVehicleData notification func vehicleDataNotification(_ notification: SDLRPCNotificationNotification) { guard let handler = refreshUIHandler, let onVehicleData = notification.notification as? SDLOnVehicleData, let odometer = onVehicleData.odometer else { return } vehicleOdometerData = "\(VehicleDataOdometerName): \(odometer) km" handler() } /// Resets the odometer data fileprivate func resetOdometer() { vehicleOdometerData = "\(VehicleDataOdometerName): Unsubscribed" } } // MARK: - Get Vehicle Data extension VehicleDataManager { /// Retreives the current vehicle speed /// /// - Parameter manager: The SDL manager class func getVehicleSpeed(with manager: SDLManager) { SDLLog.d("Checking if app has permission to access vehicle data...") guard manager.permissionManager.isRPCAllowed("GetVehicleData") else { let alert = AlertManager.alertWithMessageAndCloseButton("This app does not have the required permissions to access vehicle data") manager.send(request: alert) return } SDLLog.d("App has permission to access vehicle data. Requesting vehicle speed data...") let getVehicleSpeed = SDLGetVehicleData() getVehicleSpeed.speed = true manager.send(request: getVehicleSpeed) { (request, response, error) in guard let response = response, error == nil else { let alert = AlertManager.alertWithMessageAndCloseButton("Something went wrong while getting vehicle speed") manager.send(request: alert) return } var alertMessage = "\(VehicleDataSpeedName): " switch response.resultCode { case .rejected: SDLLog.d("The request for vehicle speed was rejected") alertMessage += "Rejected" case .disallowed: SDLLog.d("This app does not have the required permissions to access vehicle data") alertMessage += "Disallowed" case .success: if let vehicleData = response as? SDLGetVehicleDataResponse, let speed = vehicleData.speed { SDLLog.d("Request for vehicle speed successful: \(speed)") alertMessage += "\(speed) kph" } else { SDLLog.e("Request for vehicle speed successful but no data returned") alertMessage += "Unknown" } default: break } let alert = AlertManager.alertWithMessageAndCloseButton(alertMessage) manager.send(request: alert) } } } // MARK: - Phone Calls extension VehicleDataManager { /// Checks if the head unit has the ability and/or permissions to make a phone call. If it does, the phone number is dialed. /// /// - Parameter manager: The SDL manager /// - phoneNumber: A phone number to dial class func checkPhoneCallCapability(manager: SDLManager, phoneNumber: String) { SDLLog.d("Checking phone call capability") manager.systemCapabilityManager.updateCapabilityType(.phoneCall, completionHandler: { (error, systemCapabilityManager) in guard let phoneCapability = systemCapabilityManager.phoneCapability else { manager.send(AlertManager.alertWithMessageAndCloseButton("The head unit does not support the phone call capability")) return } if phoneCapability.dialNumberEnabled?.boolValue ?? false { SDLLog.d("Dialing phone number \(phoneNumber)...") dialPhoneNumber(phoneNumber, manager: manager) } else { manager.send(AlertManager.alertWithMessageAndCloseButton("A phone call can not be made")) } }) } /// Dials a phone number. /// /// - Parameters: /// - phoneNumber: A phone number to dial /// - manager: The SDL manager private class func dialPhoneNumber(_ phoneNumber: String, manager: SDLManager) { let dialNumber = SDLDialNumber(number: phoneNumber) manager.send(request: dialNumber) { (requst, response, error) in guard let success = response?.resultCode else { return } SDLLog.d("Sent dial number request: \(success == .success ? "successfully" : "unsuccessfully").") } } }
41.935135
162
0.636891
4842fa4b719b6ac8ebf0a1da18bd92d26302b250
2,878
// // GraphDefinitionTests.swift // SwiftFHIR // // Generated from FHIR 3.0.0.11832 on 2017-03-22. // 2017, SMART Health IT. // import XCTest #if !NO_MODEL_IMPORT import Models typealias SwiftFHIRGraphDefinition = Models.GraphDefinition #else import SwiftFHIR typealias SwiftFHIRGraphDefinition = SwiftFHIR.GraphDefinition #endif class GraphDefinitionTests: XCTestCase { func instantiateFrom(filename: String) throws -> SwiftFHIRGraphDefinition { return try instantiateFrom(json: try readJSONFile(filename)) } func instantiateFrom(json: FHIRJSON) throws -> SwiftFHIRGraphDefinition { return try SwiftFHIRGraphDefinition(json: json) } func testGraphDefinition1() { do { let instance = try runGraphDefinition1() try runGraphDefinition1(instance.asJSON()) } catch let error { XCTAssertTrue(false, "Must instantiate and test GraphDefinition successfully, but threw:\n---\n\(error)\n---") } } @discardableResult func runGraphDefinition1(_ json: FHIRJSON? = nil) throws -> SwiftFHIRGraphDefinition { let inst = (nil != json) ? try instantiateFrom(json: json!) : try instantiateFrom(filename: "graphdefinition-example.json") XCTAssertEqual(inst.contact?[0].telecom?[0].system, ContactPointSystem(rawValue: "url")!) XCTAssertEqual(inst.contact?[0].telecom?[0].value, "http://hl7.org/fhir") XCTAssertEqual(inst.date?.description, "2015-08-04") XCTAssertEqual(inst.description_fhir, "Specify to include list references when generating a document using the $document operation") XCTAssertEqual(inst.id, "example") XCTAssertEqual(inst.link?[0].description_fhir, "Link to List") XCTAssertEqual(inst.link?[0].path, "Composition.section.entry") XCTAssertEqual(inst.link?[0].target?[0].compartment?[0].code, CompartmentType(rawValue: "Patient")!) XCTAssertEqual(inst.link?[0].target?[0].compartment?[0].rule, GraphCompartmentRule(rawValue: "identical")!) XCTAssertEqual(inst.link?[0].target?[0].link?[0].description_fhir, "Include any list entries") XCTAssertEqual(inst.link?[0].target?[0].link?[0].path, "List.entry.item") XCTAssertEqual(inst.link?[0].target?[0].link?[0].target?[0].compartment?[0].code, CompartmentType(rawValue: "Patient")!) XCTAssertEqual(inst.link?[0].target?[0].link?[0].target?[0].compartment?[0].rule, GraphCompartmentRule(rawValue: "identical")!) XCTAssertEqual(inst.link?[0].target?[0].link?[0].target?[0].type, "Resource") XCTAssertEqual(inst.link?[0].target?[0].type, "List") XCTAssertEqual(inst.name, "Document Generation Template") XCTAssertEqual(inst.publisher, "FHIR Project") XCTAssertEqual(inst.start, "Composition") XCTAssertEqual(inst.status, PublicationStatus(rawValue: "draft")!) XCTAssertEqual(inst.text?.status, NarrativeStatus(rawValue: "generated")!) XCTAssertEqual(inst.url?.absoluteString, "http://h7.org/fhir/GraphDefinition/example") return inst } }
42.323529
134
0.748784
eb9ee0d7c1bd7ead357e5d5579a57082b9cbbe88
10,534
import UIKit import os.log extension Base { /// Turn on/off logging of init/deinit of all FCs /// ⚠️ Has no effect when Base.memoryLoggingEnabled is true public static var flowCoordinatorMemoryLoggingEnabled: Bool = true /** Handles view controllers connections and flow Starts with one of `start()` methods and ends with `stop()`. All start methods are supposed to be overridden and property `rootViewController` must be set in the end of the overridden implementation to avoid memory leaks. Don't forget to call super.start(). */ open class FlowCoordinator<DeepLinkType>: NSObject, UINavigationControllerDelegate, UIAdaptivePresentationControllerDelegate { /// Reference to the navigation controller used within the flow public weak var navigationController: UINavigationController? /// First VC of the flow. Must be set when FC starts. public weak var rootViewController: UIViewController! { didSet { rootVCSetter(rootViewController) } } /// When flow coordinator handles modally presented flow, we are interested `rootVC` changes private var rootVCSetter: (UIViewController?) -> () = { _ in } /// Parent coordinator public weak var parentCoordinator: FlowCoordinator? /// Array of child coordinators public var childCoordinators = [FlowCoordinator]() /// Currently active coordinator public weak var activeChild: FlowCoordinator? // MARK: - Lifecycle /// Just start and return rootViewController. Object calling this method will connect returned view controller to the flow. @discardableResult open func start() -> UIViewController { checkRootViewController() return UIViewController() } /// Start in window. Window's root VC is supposed to be set. open func start(in window: UIWindow) { checkRootViewController() } /// Start within existing navigation controller. open func start(with navigationController: UINavigationController) { self.navigationController = navigationController navigationController.delegate = self checkRootViewController() } /// Start by presenting from given VC. This method must be overridden by subclass. open func start(from viewController: UIViewController) { rootVCSetter = { [weak self] rootVC in rootVC?.presentationController?.delegate = self } rootVCSetter(rootViewController) } /// Clean up. Must be called when FC finished the flow to avoid memory leaks and unexpected behavior. open func stop(animated: Bool = false, completion: (() -> Void)? = nil) { let animationGroup = DispatchGroup() // stop all children DispatchQueue.main.async { self.childCoordinators.forEach { animationGroup.enter() $0.stop(animated: animated, completion: animationGroup.leave) } } if rootViewController == nil { ErrorHandlers.rootViewControllerDeallocatedBeforeStop?() } dismissPresentedViewControllerIfPossible(animated: animated, group: animationGroup) /// Determines whether dismiss should be called on `presentingViewController` of root, /// based on whether there are remaining VCs in the navigation stack. let shouldCallDismissOnPresentingVC = popAllViewControllersIfPossible(animated: animated, group: animationGroup) // ensure that dismiss will be called on presentingVC of root only when appropriate, // as presentingVC of root when modally presenting can be UITabBarController, // but the whole navigation shouldn't be dismissed, as there are still VCs // remaining in the navigation stack if shouldCallDismissOnPresentingVC, let presentingViewController = rootViewController?.presentingViewController { // dismiss when root was presented animationGroup.enter() presentingViewController.dismiss(animated: animated, completion: animationGroup.leave) } // stopping FC doesn't need to be nav delegate anymore -> pass it to parent navigationController?.delegate = parentCoordinator parentCoordinator?.removeChild(self) animationGroup.notify(queue: DispatchQueue(label: "animationGroup")) { completion?() } } // MARK: - Stop helpers /// Dismiss all VCs presented from root or nav if possible private func dismissPresentedViewControllerIfPossible(animated: Bool, group: DispatchGroup) { if let rootViewController = rootViewController, rootViewController.presentedViewController != nil { group.enter() rootViewController.dismiss(animated: animated, completion: group.leave) } } /// Pop all view controllers when started within navigation controller /// - Returns: Flag whether dismiss should be called on `presentingViewController` of root, /// based on whether there are remaining VCs in the navigation stack. private func popAllViewControllersIfPossible(animated: Bool, group: DispatchGroup) -> Bool { if let navigationController = navigationController, let rootViewController = rootViewController, let index = navigationController.viewControllers.firstIndex(of: rootViewController) { // VCs to be removed from navigation stack let toRemoveViewControllers = navigationController.viewControllers[index..<navigationController.viewControllers.count] // dismiss all presented VCs on VCs to be removed toRemoveViewControllers.forEach { vc in if vc.presentedViewController != nil { group.enter() vc.dismiss(animated: animated, completion: group.leave) } } // VCs to remain in the navigation stack let remainingViewControllers = Array(navigationController.viewControllers[0..<index]) if remainingViewControllers.isNotEmpty { navigationController.setViewControllers(remainingViewControllers, animated: animated) } // set the appropriate value based on whether there are VCs remaining in the navigation stack return remainingViewControllers.isEmpty } // Return the default value for the flag return true } // MARK: - Child coordinators open func addChild(_ flowController: FlowCoordinator) { if !childCoordinators.contains(where: { $0 === flowController }) { childCoordinators.append(flowController) flowController.parentCoordinator = self } } open func removeChild(_ flowController: FlowCoordinator) { if let index = childCoordinators.firstIndex(where: { $0 === flowController }) { childCoordinators.remove(at: index) } } // MARK: - UINavigationControllerDelegate open func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { // Check if the root is not dead guard let rootViewController = rootViewController else { return } // If the navigation controller is the current root view controller // then this method shouldn't get called. // But that's not possible with our current implementation. guard self.navigationController != rootViewController else { return } // If `rootViewController` is not present in the navigation stack // we have to stop the current flow if !navigationController.viewControllers.contains(rootViewController) { navigationController.delegate = parentCoordinator stop() } } // MARK: - UIAdaptivePresentationControllerDelegate open func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { if presentationController.presentedViewController == rootViewController { stop() } } // MARK: - DeepLink /// Handle deep link with currently active coordinator. If not handled, function returns false @discardableResult open func handleDeeplink(_ deeplink: DeepLinkType) -> Bool { activeChild?.handleDeeplink(deeplink) ?? false } // MARK: - Debug override public init() { super.init() if Base.memoryLoggingEnabled && Base.flowCoordinatorMemoryLoggingEnabled { if #available(iOS 10.0, *) { os_log("🔀 👶 %@", log: Logger.lifecycleLog(), type: .info, "\(self)") } else { NSLog("🔀 👶 \(self)") } } } deinit { if Base.memoryLoggingEnabled && Base.flowCoordinatorMemoryLoggingEnabled { if #available(iOS 10.0, *) { os_log("🔀 ⚰️ %@", log: Logger.lifecycleLog(), type: .info, "\(self)") } else { NSLog("🔀 ⚰️ \(self)") } } } /// Wait for a second and check whether rootViewController was set private func checkRootViewController() { let currentQueue = OperationQueue.current?.underlyingQueue assert(currentQueue != nil) currentQueue?.asyncAfter(deadline: .now() + 1) { [weak self] in /// If `self` is nil, then I think we should not care guard let self = self else { return } if self.rootViewController == nil { assertionFailure("rootViewController is nil") } } } } /// Empty class for Base.FlowCoordinator with no deep link handling public enum NoDeepLink {} /// Base VC with no VM open class FlowCoordinatorNoDeepLink: Base.FlowCoordinator<NoDeepLink> { } }
41.968127
165
0.623695
39d5497ceddbd98238d92055515c413c9e30d734
2,350
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol ___VARIABLE_sceneName___DisplayLogic: class { func displaySomething(viewModel: ___VARIABLE_sceneName___.Something.ViewModel) } class ___VARIABLE_sceneName___ViewController: UITableViewController, ___VARIABLE_sceneName___DisplayLogic { var interactor: ___VARIABLE_sceneName___BusinessLogic? var router: (NSObjectProtocol & ___VARIABLE_sceneName___RoutingLogic & ___VARIABLE_sceneName___DataPassing)? // MARK: Object lifecycle override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK: Setup private func setup() { let viewController = self let interactor = ___VARIABLE_sceneName___Interactor() let presenter = ___VARIABLE_sceneName___Presenter() let router = ___VARIABLE_sceneName___Router() viewController.interactor = interactor viewController.router = router interactor.presenter = presenter presenter.viewController = viewController router.viewController = viewController router.dataStore = interactor } // MARK: Routing override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let scene = segue.identifier { let selector = NSSelectorFromString("routeTo\(scene)WithSegue:") if let router = router, router.responds(to: selector) { router.perform(selector, with: segue) } } } // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() doSomething() } // MARK: Do something //@IBOutlet weak var nameTextField: UITextField! func doSomething() { let request = ___VARIABLE_sceneName___.Something.Request() interactor?.doSomething(request: request) } func displaySomething(viewModel: ___VARIABLE_sceneName___.Something.ViewModel) { //nameTextField.text = viewModel.name } }
26.704545
110
0.730638
6952b5fbab76768447a0ad70f6bd2b326c923ed9
718
// // LoginViewModelTests.swift // stock-portfolio-trackerTests // // Created by nb-058-41b on 1/9/21. // import XCTest import SwiftUI import DICE @testable import stock_portfolio_tracker class LoginViewModelTests: XCTestCase { func testViewStateShouldBeEqualToStartOnInit() { let state = AppState() let store = Store<AppState>(state) let container = DIContainer() container.register(AuthServiceType.self) { _ in return AuthServiceStub() } let session = Session(container: container, appState: store) let sut: LoginViewModel = session.resolve() XCTAssertEqual(sut.output.state, LoginViewState.start) } }
23.16129
68
0.662953
d55d67f1dd5cc41c61cb710966ad8b52b9e149ac
394
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "DTFoundation", platforms: [ .iOS(.v11), ], products: [ .library( name: "DTFoundation", targets: ["DTFoundation"]), ], dependencies: [ ], targets: [ .target( name: "DTFoundation", dependencies: []), ] )
17.909091
39
0.492386
64155cbf171dd3adf898aae4b1528d71e6888d0f
5,344
// // ViewControllerPresenter.swift // Reversi // // Created by 加賀江 優幸 on 2020/04/27. // Copyright © 2020 Yuta Koshizawa. All rights reserved. // import Combine // どちらの色のプレイヤーのターンかを表します。 enum Turn { case current(Disk) case finished } enum Player: Int { case manual = 0 case computer = 1 var change: Player { switch self { case .manual: return .computer case .computer: return .manual } } } class ViewControllerPresenter { let darkCountSubject = CurrentValueSubject<Int, Never>(0) let lightCountSubject = CurrentValueSubject<Int, Never>(0) let turnSubject = CurrentValueSubject<Turn, Never>(.current(.dark)) let playerControlValueChangedEvent = PassthroughSubject<Disk, Never>() let playerControlChangeRequest = PassthroughSubject<(Disk, Player), Never>() let darkPlayerControlSubject = CurrentValueSubject<Player, Never>(.manual) let lightPlayerControlSubject = CurrentValueSubject<Player, Never>(.manual) let darkActivityIndicatorSubject = CurrentValueSubject<Bool, Never>(false) let lightActivityIndicatorSubject = CurrentValueSubject<Bool, Never>(false) let boardViewPresenter: BoardViewPresenter // For UI let messageTextSubject = CurrentValueSubject<String, Never>("") let messageDiskSubject = CurrentValueSubject<Disk?, Never>(nil) private var cancellables: Set<AnyCancellable> = [] init(boardViewPresenter: BoardViewPresenter) { self.boardViewPresenter = boardViewPresenter playerControlValueChangedEvent .filter({ disk in disk == .dark }) .map({ _ in self.darkPlayerControlSubject.value.change }) .subscribe(darkPlayerControlSubject) .store(in: &cancellables) playerControlChangeRequest .filter({ (disk, player) in disk == .dark }) .map({ (disk, player) in player }) .subscribe(darkPlayerControlSubject) .store(in: &cancellables) playerControlValueChangedEvent .filter({ disk in disk == .light }) .map({ _ in self.lightPlayerControlSubject.value.change }) .subscribe(lightPlayerControlSubject) .store(in: &cancellables) playerControlChangeRequest .filter({ (disk, player) in disk == .light }) .map({ (disk, player) in player }) .subscribe(lightPlayerControlSubject) .store(in: &cancellables) // turnSubject -> messageTextSubject turnSubject.map { turn -> String in switch turn { case .current: return "'s turn" case .finished: // TODO: 勝者判定。一箇所にまとめたい。 let darkCount = self.countDisks(of: .dark) let lightCount = self.countDisks(of: .light) if darkCount == lightCount { return "Tied" } else { return " won" } } }.subscribe(messageTextSubject).store(in: &cancellables) // turnSubject -> messageDiskSubject turnSubject.map { turn -> Disk? in switch turn { case .current(let disk): return disk case .finished: // TODO: 勝者判定。一箇所にまとめたい。 let darkCount = self.countDisks(of: .dark) let lightCount = self.countDisks(of: .light) if darkCount == lightCount { return nil } else { return darkCount > lightCount ? .dark : .light } } }.subscribe(messageDiskSubject).store(in: &cancellables) // For Debug darkPlayerControlSubject.sink { player in print("[Debug] disk: dark, player: " + String(player.rawValue)) }.store(in: &cancellables) lightPlayerControlSubject.sink { player in print("[Debug] disk: light, player: " + String(player.rawValue)) }.store(in: &cancellables) } func playerControlSubject(forDisk disk: Disk) -> CurrentValueSubject<Player, Never> { switch disk { case .dark: return darkPlayerControlSubject case .light: return lightPlayerControlSubject } } func activityIndicatorSubject(forDisk disk: Disk) -> CurrentValueSubject<Bool, Never> { switch disk { case .dark: return darkActivityIndicatorSubject case .light: return lightActivityIndicatorSubject } } func countDisks(of side: Disk) -> Int { var count = 0 for y in BoardViewPresenter.yRange { for x in BoardViewPresenter.xRange { if boardViewPresenter.diskAt(x: x, y: y) == side { count += 1 } } } return count } // 互換性担保 var unsafeTurn: Disk? { switch turnSubject.value { case .current(let disk): return disk case .finished: return nil } } func unsafeSetTurn(disk: Disk?) { switch disk { case .some(let disk): turnSubject.send(.current(disk)) case .none: turnSubject.send(.finished) } } }
31.435294
91
0.580277
201d091091778f9bf8d58cdd38b8bd314b3aea01
861
// // JWBasicViewController.swift // SwiftDemo // // Created by apple on 17/5/4. // Copyright © 2017年 UgoMedia. All rights reserved. // import UIKit class JWBasicViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } 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. } */ }
23.916667
106
0.671312
e9b85628746b5711ef6226096ca5bd42aeed3173
1,488
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency -parse-as-library) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime // XFAIL: OS=windows-msvc struct Boom: Error {} struct IgnoredBoom: Error {} @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) func echo(_ i: Int) async -> Int { i } @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) func boom() async throws -> Int { throw Boom() } @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) func test_taskGroup_throws_rethrows() async { do { let got = try await withThrowingTaskGroup(of: Int.self, returning: Int.self) { group in group.spawn { await echo(1) } group.spawn { await echo(2) } group.spawn { try await boom() } do { while let r = try await group.next() { print("next: \(r)") } } catch { // CHECK: error caught and rethrown in group: Boom() print("error caught and rethrown in group: \(error)") throw error } print("should have thrown") return 0 } print("Expected error to be thrown, but got: \(got)") } catch { // CHECK: rethrown: Boom() print("rethrown: \(error)") } } @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) @main struct Main { static func main() async { await test_taskGroup_throws_rethrows() } }
26.571429
111
0.641129
db3745eafd4f37166bdea99c7adfb3089c91772f
2,028
import Combine import Foundation import ReduxKit import UIKit final class SUIDReducer: Reducer<SUIDState, SUIDActions> { override func reduce(action: SUIDActions, state: inout SUIDState) { switch action { case .increment(let uuid): var count = state.counts[uuid] ?? 0 count += 1 state.counts[uuid] = count case .decrement(let uuid): var count = state.counts[uuid] ?? 0 if count > 0 { count -= 1 } state.counts[uuid] = count case .addThing: state.things.append(SUIDState.Thing(uuid: UUID(), title: "added thing \(state.things.count + 1)")) case .setRandomBackgroundColor: handleRandomBackgroundColorAction(state: &state) case .changeUnusedState: state.unusedStuff = UUID() } } func handleRandomBackgroundColorAction(state: inout SUIDState) { state.backgroundColor = generateRandomPastelColor() state.backgroundColorChangeTimes.append(Date()) if state.raveMode { state.raveMode = false print("ok fine. psh.") return } if state.backgroundColorChangeTimes.count > 2 { let times = state.backgroundColorChangeTimes.suffix(3) if let first = times.first, let last = times.last, first.distance(to: last) < 1 { print("it looks like you want rave mode") state.raveMode = true doRaveMode() } } } func doRaveMode() { RunLoop.main.add( Timer(timeInterval: 0.2, repeats: false) { [self] _ in deferredReduction { state in if state.raveMode { state.backgroundColor = generateRandomPastelColor() doRaveMode() } } }, forMode: .common) } }
31.6875
110
0.531558
d9c20306c4448643b9f3d50035fc420650cf5ccd
1,555
// // StoreKitPurchaseTracker.swift // FlintCore-iOS // // Created by Marc Palmer on 16/02/2018. // Copyright © 2018 Montana Floss Co. Ltd. All rights reserved. // import Foundation #if canImport(StoreKit) import StoreKit #endif /// Example of validation of features by StoreKit In-App Purchase or subscription ID. /// /// Note that this code could be easily hacked on jailbroken devices. You may need to add your /// own app-specific logic to verify this so there isn't a single point of verification, /// and to check receipts. @available(iOS 3, tvOS 9, macOS 10.7, *) public class StoreKitPurchaseTracker: PurchaseTracker { private var observers = ObserverSet<PurchaseTrackerObserver>() public func addObserver(_ observer: PurchaseTrackerObserver) { let queue = SmartDispatchQueue(queue: .main) observers.add(observer, using: queue) } public func removeObserver(_ observer: PurchaseTrackerObserver) { observers.remove(observer) } /// Called to see if a specific product has been purchased public func isPurchased(_ productID: String) -> Bool? { // 1. Get list of purchases, or bail out if not ready yet // let verifiedPurchases: [String] = [] // 2. Map to products // let products = Flint.products.filter { return verifiedPurchases.contains($0) } // 3. Check requirement // return requirement.isFulfilled(verifiedPurchasedProducts: products as Set) flintNotImplemented("IAP checking is not implemented yet") } }
33.085106
94
0.696463
ac6a4172a654463f776ff3f0a6f74e8cae13c947
261
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { { extension NSData { deinit { { { { case = b( var { class B { func a { { { { class case ,
11.863636
87
0.689655
38a33a4386fbfb4fe97484144b842ecc5fa3179f
284
// // ColorConvertible.swift // Pixel-iOS // // Created by José Donor on 20/03/2019. // public protocol ColorConvertible { /// Color var color: Color { get } } extension Color: ColorConvertible { /// Color public var color: Color { return self } }
11.36
40
0.605634
640ff1f84c66d132e923913d7bd5c9dbeaaed79f
5,235
// // Secp256k1.swift // token // // Created by James Chen on 2016/10/26. // Copyright © 2016 imToken PTE. LTD. All rights reserved. // import Foundation import libsecp256k1 extension Encryptor { struct SignResult { let signature: String // Hex format let recid: Int32 } class Secp256k1 { static let failureSignResult = SignResult(signature: "", recid: 0) private let signatureLength = 64 private let keyLength = 64 /// Sign a message with a key and return the result. /// - Parameter key: Key in hex format. /// - Parameter message: Message in hex format. /// - Returns: Signature as a `SignResult`. func sign(key: String, message: String) -> SignResult { guard let keyBytes = key.tk_dataFromHexString()?.bytes, let messageBytes = message.tk_dataFromHexString()?.bytes else { return Secp256k1.failureSignResult } let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY))! defer { secp256k1_context_destroy(context) } if secp256k1_ec_seckey_verify(context, keyBytes) != 1 { return Secp256k1.failureSignResult } var sig = secp256k1_ecdsa_recoverable_signature() if secp256k1_ecdsa_sign_recoverable(context, &sig, messageBytes, keyBytes, secp256k1_nonce_function_rfc6979, nil) == 0 { return Secp256k1.failureSignResult } var data = Data(count: signatureLength) var recid: Int32 = 0 data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) in _ = secp256k1_ecdsa_recoverable_signature_serialize_compact(context, bytes, &recid, &sig) } return SignResult(signature: data.tk_toHexString(), recid: recid) } /// Recover public key from signature and message. /// - Parameter signature: Signature. /// - Parameter message: Raw message before signing. /// - Parameter recid: recid. /// - Returns: Recoverd public key. func recover(signature: String, message: String, recid: Int32) -> String? { guard let signBytes = signature.tk_dataFromHexString()?.bytes, let messageBytes = message.tk_dataFromHexString()?.bytes else { return nil } let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY))! defer { secp256k1_context_destroy(context) } var sig = secp256k1_ecdsa_recoverable_signature() secp256k1_ecdsa_recoverable_signature_parse_compact(context, &sig, signBytes, recid) var publicKey = secp256k1_pubkey() var result: Int32 = 0 result = secp256k1_ecdsa_recover(context, &publicKey, &sig, messageBytes) if result == 0 { return nil } var length = 65 var data = Data(count: length) data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) in result = secp256k1_ec_pubkey_serialize(context, bytes, &length, &publicKey, UInt32(SECP256K1_EC_UNCOMPRESSED)) } if result == 0 { return nil } return data.toHexString() } /// Recover public key from signature and message. /// - Parameter signature: Signature. /// - Parameter message: Raw message before signing. /// - Parameter recid: recid. /// - Returns: Recoverd public key. func eosRecover(signature: Data, message: Data, recid: Int32) -> String? { // guard let signBytes = signature.tk_dataFromHexString()?.bytes, // let messageBytes = message.tk_dataFromHexString()?.bytes else { // return nil // } let signBytes = signature.bytes let messageBytes = message.bytes let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY))! defer { secp256k1_context_destroy(context) } var sig = secp256k1_ecdsa_recoverable_signature() secp256k1_ecdsa_recoverable_signature_parse_compact(context, &sig, signBytes, recid) var publicKey = secp256k1_pubkey() var result: Int32 = 0 result = secp256k1_ecdsa_recover(context, &publicKey, &sig, messageBytes) if result == 0 { return nil } var length = 65 var data = Data(count: length) data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) in result = secp256k1_ec_pubkey_serialize(context, bytes, &length, &publicKey, UInt32(SECP256K1_EC_UNCOMPRESSED)) } if result == 0 { return nil } return data.toHexString() } /// Verify a key. /// - Parameter key: Key in hex format. /// - Returns: true if verified, otherwise return false. func verify(key: String) -> Bool { if key.count != keyLength || !Hex.isHex(key) { return false } let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_VERIFY))! defer { secp256k1_context_destroy(context) } if let data = key.tk_dataFromHexString() { let bytes = data.bytes return bytes.count == 32 && secp256k1_ec_seckey_verify(context, bytes) == 1 } else { return false } } } }
32.116564
126
0.654059
ac98407c342df5047c09e963435686799d2a988e
628
import Foundation /** Enum denoting the types of the destination waypoint highlighting on arrival. */ public enum WaypointStyle: Int { /** Do not highlight destination waypoint on arrival. Destination annotation is always shown by default. */ case annotation /** Highlight destination building on arrival in 2D. In case if destination building wasn't found only annotation will be shown. */ case building /** Highlight destination building on arrival in 3D. In case if destination building wasn't found only annotation will be shown. */ case extrudedBuilding }
28.545455
129
0.707006
21f40185c89ed16a23147e419e0dd172b4884970
4,364
// // SkinConfig.swift // Example // // Created by woko on 25/09/2019. // import Foundation import UIKit public protocol SettingsConfig { // MARK: Colors var backgroundColor: String { get } var paddingColor: String { get } var contentColor: String { get } var separatorColor: String { get } var darkGrayColor: String { get } var lightGrayColor: String { get } var tintColor: String { get } var primaryColor: String { get } var navBarColor: String { get } var tabBarColor: String { get } var textColor: String { get } var selectedColor: String { get } var accessoryColor: String { get } // MARK: Offsets var marginBase: Float { get } var marginLeft: Float { get } var marginRight: Float { get } var marginTop: Float { get } var marginBot: Float { get } var paddingLeft: Float { get } var paddingRight: Float { get } var paddingTop: Float { get } var paddingBot: Float { get } var separatorHeight: Float { get } var separatorPaddingLeft: Float { get } var separatorPaddingRight: Float { get } var accessoryPadding: Float { get } // MARK: Fonts var lightFont: UIFont? { get } var regularFont: UIFont? { get } var semiboldFont: UIFont? { get } var boldFont: UIFont? { get } var defaultFont: ConfigFont { get } var headerFont: ConfigFont { get } var titleFont: ConfigFont { get } var headlineFont: ConfigFont { get } // MARK: Misc var hasSeparator: Bool { get } var accessorySize: CGSize { get } } public extension SettingsConfig { // MARK: Colors var backgroundColor: String {"ffffff00" } var paddingColor: String {"ffffff00" } var contentColor: String { "ffffff00" } var separatorColor: String { if #available(iOS 13.0, *) { // dark mode compatible color return UIColor.opaqueSeparator.hexString } else { return UIColor.lightGray.hexString } } var darkGrayColor: String { if #available(iOS 13.0, *) { // dark mode compatible color return UIColor.systemGray2.hexString } else { return UIColor.gray.hexString } } var lightGrayColor: String { if #available(iOS 13.0, *) { // dark mode compatible color return UIColor.systemGray5.hexString } else { return UIColor.lightGray.hexString } } var tintColor: String { "770000" } var primaryColor: String { "ff0000" } var navBarColor: String { "007aff" } var tabBarColor: String { "007aff" } var textColor: String { if #available(iOS 13.0, *) { // dark mode compatible color return UIColor.label.hexString } else { return UIColor.darkText.hexString } } var selectedColor: String { "ffffff00" } var accessoryColor: String { if #available(iOS 13.0, *) { // dark mode compatible color return UIColor.systemGray2.hexString } else { return UIColor.gray.hexString } } // MARK: Offsets var marginBase: Float { 4 } var marginLeft: Float { 0 } var marginRight: Float { 0 } var marginTop: Float { 0 } var marginBot: Float { 0 } var paddingLeft: Float { marginBase } var paddingRight: Float { marginBase } var paddingTop: Float { marginBase } var paddingBot: Float { marginBase } var separatorHeight: Float { 1 } var separatorPaddingLeft: Float { marginBase } var separatorPaddingRight: Float { marginBase } var accessoryPadding: Float { 12 } var accessorySize: CGSize { CGSize(width: 16, height: 16) } // MARK: Fonts var lightFont: UIFont? { nil } var regularFont: UIFont? { nil } var semiboldFont: UIFont? { nil } var boldFont: UIFont? { nil } var defaultFont: ConfigFont { ConfigFont(size: 16, weight: .regular) } var headerFont: ConfigFont { ConfigFont(size: 26, weight: .regular) } var titleFont: ConfigFont { ConfigFont(size: 22, weight: .regular) } var headlineFont: ConfigFont { ConfigFont(size: 18, weight: .bold) } // MARK: Misc var hasSeparator: Bool { true } } public struct ConfigFont { var size: Float var weight: UIFont.Weight }
30.305556
74
0.613886
d7bd84c7966479d5506ae283ae35794b92c722ec
693
// // ContentView.swift // UsingTabViews // // Created by Edgar Nzokwe on 4/25/20. // Copyright © 2020 Edgar Nzokwe. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { TabView { HomeView() .tabItem{ Image(systemName: "house.fill") Text("Home") } CurrenciesView() .tabItem{ Image(systemName: "coloncurrencysign.circle.fill") Text("Currencies") } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
21
70
0.510823
e6c09f9275c55d6bdda20d9f8483de01a98219ca
77
// // Created by Mike on 9/18/21. // /// TODO public struct ScaledShape {}
11
31
0.61039
ed9601c5b461c5d58873bd025595dceedf5dc64a
608
// // Trip+CoreDataProperties.swift // TripPlanner // // Created by Benjamin Encz on 9/11/15. // Copyright © 2015 Make School. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension Trip { @NSManaged var lastUpdate: NSNumber? @NSManaged var location: NSObject? @NSManaged var locationDescription: String? @NSManaged var serverID: String? @NSManaged var parsing: NSNumber? @NSManaged var waypoints: NSSet? }
24.32
76
0.728618
110f59c469c89f82601de3dfb11981482126dd7b
209
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T{class g:func g<T{func g<d>:T.c
41.8
87
0.755981
6a0c0d7b168465b14bda19bb1e3a3290353d6d88
1,456
// // StatsRootRouterTests.swift // xDrip // // Created by Artem Kalmykov on 11.03.2020. // Copyright (c) 2020 Faifly. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // @testable import xDrip import XCTest final class StatsRootRouterTests: XCTestCase { // MARK: Subject under test var sut: StatsRootRouter! // MARK: Test lifecycle override func setUp() { super.setUp() sut = StatsRootRouter() } private func createSpy() -> ViewControllerSpy { let archiver = NSKeyedArchiver(requiringSecureCoding: false) archiver.finishEncoding() let data = archiver.encodedData let unarchiver = try! NSKeyedUnarchiver(forReadingFrom: data) return ViewControllerSpy(coder: unarchiver)! } // MARK: Test doubles final class ViewControllerSpy: StatsRootViewController { var dismissCalled = false override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { dismissCalled = true } } // MARK: Tests func testDismissSelf() { // Given let spy = createSpy() sut.viewController = spy // When sut.dismissSelf() // Given XCTAssertTrue(spy.dismissCalled) } }
24.677966
85
0.615385
01a4c27d80441a8e115afc41fa21f9a8f7264746
9,248
import Foundation import Shared public final class SourceGraph { private(set) public var allDeclarations: Set<Declaration> = [] private(set) public var reachableDeclarations: Set<Declaration> = [] private(set) public var redundantProtocols: [Declaration: Set<Reference>] = [:] private(set) public var rootDeclarations: Set<Declaration> = [] private(set) public var redundantPublicAccessibility: [Declaration: Set<String>] = [:] private(set) var rootReferences: Set<Reference> = [] private(set) var allReferences: Set<Reference> = [] private(set) var retainedDeclarations: Set<Declaration> = [] private(set) var potentialAssignOnlyProperties: Set<Declaration> = [] private(set) var ignoredDeclarations: Set<Declaration> = [] private(set) var assetReferences: Set<AssetReference> = [] private(set) var mainAttributedDeclarations: Set<Declaration> = [] private var allReferencesByUsr: [String: Set<Reference>] = [:] private var allDeclarationsByKind: [Declaration.Kind: Set<Declaration>] = [:] private var allExplicitDeclarationsByUsr: [String: Declaration] = [:] private let mutationQueue: DispatchQueue private var _allDeclarationsUnmodified: Set<Declaration> = [] public var allDeclarationsUnmodified: Set<Declaration> { _allDeclarationsUnmodified } public var unreachableDeclarations: Set<Declaration> { allDeclarations.subtracting(reachableDeclarations) } public init() { mutationQueue = DispatchQueue(label: "SourceGraph.mutationQueue") } public func indexingComplete() { rootDeclarations = allDeclarations.filter { $0.parent == nil } rootReferences = allReferences.filter { $0.parent == nil } _allDeclarationsUnmodified = allDeclarations } func declarations(ofKind kind: Declaration.Kind) -> Set<Declaration> { allDeclarationsByKind[kind] ?? [] } func declarations(ofKinds kinds: Set<Declaration.Kind>) -> Set<Declaration> { declarations(ofKinds: Array(kinds)) } func declarations(ofKinds kinds: [Declaration.Kind]) -> Set<Declaration> { Set(kinds.compactMap { allDeclarationsByKind[$0] }.joined()) } func explicitDeclaration(withUsr usr: String) -> Declaration? { allExplicitDeclarationsByUsr[usr] } func references(to decl: Declaration) -> Set<Reference> { Set(decl.usrs.flatMap { allReferencesByUsr[$0, default: []] }) } func hasReferences(to decl: Declaration) -> Bool { decl.usrs.contains { !allReferencesByUsr[$0, default: []].isEmpty } } func markRedundantProtocol(_ declaration: Declaration, references: Set<Reference>) { mutationQueue.sync { redundantProtocols[declaration] = references } } func markRedundantPublicAccessibility(_ declaration: Declaration, modules: Set<String>) { mutationQueue.sync { redundantPublicAccessibility[declaration] = modules } } func unmarkRedundantPublicAccessibility(_ declaration: Declaration) { mutationQueue.sync { _ = redundantPublicAccessibility.removeValue(forKey: declaration) } } func markIgnored(_ declaration: Declaration) { mutationQueue.sync { _ = ignoredDeclarations.insert(declaration) } } func markRetained(_ declaration: Declaration) { mutationQueue.sync { _ = retainedDeclarations.insert(declaration) } } func markPotentialAssignOnlyProperty(_ declaration: Declaration) { mutationQueue.sync { _ = potentialAssignOnlyProperties.insert(declaration) } } func markMainAttributed(_ declaration: Declaration) { mutationQueue.sync { _ = mainAttributedDeclarations.insert(declaration) } } func isRetained(_ declaration: Declaration) -> Bool { mutationQueue.sync { retainedDeclarations.contains(declaration) } } func add(_ declaration: Declaration) { mutationQueue.sync { allDeclarations.insert(declaration) allDeclarationsByKind[declaration.kind, default: []].insert(declaration) if !declaration.isImplicit { declaration.usrs.forEach { allExplicitDeclarationsByUsr[$0] = declaration } } } } func remove(_ declaration: Declaration) { mutationQueue.sync { removeUnsafe(declaration) } } func removeUnsafe(_ declaration: Declaration) { declaration.parent?.declarations.remove(declaration) allDeclarations.remove(declaration) allDeclarationsByKind[declaration.kind]?.remove(declaration) rootDeclarations.remove(declaration) reachableDeclarations.remove(declaration) potentialAssignOnlyProperties.remove(declaration) declaration.usrs.forEach { allExplicitDeclarationsByUsr.removeValue(forKey: $0) } } func add(_ reference: Reference) { mutationQueue.sync { addUnsafe(reference) } } func addUnsafe(_ reference: Reference) { _ = allReferences.insert(reference) if allReferencesByUsr[reference.usr] == nil { allReferencesByUsr[reference.usr] = [] } allReferencesByUsr[reference.usr]?.insert(reference) } func add(_ reference: Reference, from declaration: Declaration) { mutationQueue.sync { if reference.isRelated { _ = declaration.related.insert(reference) } else { _ = declaration.references.insert(reference) } } add(reference) } func remove(_ reference: Reference) { mutationQueue.sync { _ = allReferences.remove(reference) allReferences.subtract(reference.descendentReferences) allReferencesByUsr[reference.usr]?.remove(reference) } if let parent = reference.parent { mutationQueue.sync { parent.references.remove(reference) parent.related.remove(reference) } } } func add(_ assetReference: AssetReference) { mutationQueue.sync { _ = assetReferences.insert(assetReference) } } func markReachable(_ declaration: Declaration) { mutationQueue.sync { _ = reachableDeclarations.insert(declaration) } } func isReachable(_ declaration: Declaration) -> Bool { mutationQueue.sync { reachableDeclarations.contains(declaration) } } func isExternal(_ reference: Reference) -> Bool { explicitDeclaration(withUsr: reference.usr) == nil } func accept(visitor: SourceGraphVisitor.Type) throws { try visitor.make(graph: self).visit() } func inheritedTypeReferences(of decl: Declaration, seenDeclarations: Set<Declaration> = []) -> [Reference] { var references: [Reference] = [] for reference in decl.immediateInheritedTypeReferences { references.append(reference) if let inheritedDecl = explicitDeclaration(withUsr: reference.usr) { // Detect circular references. The following is valid Swift. // class SomeClass {} // extension SomeClass: SomeProtocol {} // protocol SomeProtocol: SomeClass {} guard !seenDeclarations.contains(inheritedDecl) else { continue } references = inheritedTypeReferences(of: inheritedDecl, seenDeclarations: seenDeclarations.union([decl])) + references } } return references } func inheritedDeclarations(of decl: Declaration) -> [Declaration] { inheritedTypeReferences(of: decl).compactMap { explicitDeclaration(withUsr: $0.usr) } } func immediateSubclasses(of decl: Declaration) -> [Declaration] { let allClasses = allDeclarationsByKind[.class] ?? [] return allClasses .filter { $0.related.contains(where: { ref in ref.kind == .class && decl.usrs.contains(ref.usr) }) }.filter { $0 != decl } } func subclasses(of decl: Declaration) -> [Declaration] { let immediate = immediateSubclasses(of: decl) return immediate + immediate.flatMap { subclasses(of: $0) } } func mutating(_ block: () -> Void) { mutationQueue.sync(execute: block) } func extendedDeclaration(forExtension extensionDeclaration: Declaration) throws -> Declaration? { guard let extendedKind = extensionDeclaration.kind.extendedKind?.referenceEquivalent else { throw PeripheryError.sourceGraphIntegrityError(message: "Unknown extended reference kind for extension '\(extensionDeclaration.kind.rawValue)'") } guard let extendedReference = extensionDeclaration.references.first(where: { $0.kind == extendedKind && $0.name == extensionDeclaration.name }) else { return nil } if let extendedDeclaration = allExplicitDeclarationsByUsr[extendedReference.usr] { return extendedDeclaration } return nil } }
34.766917
171
0.650627
097022973820ca03d72c82a9a643face30c91a7f
3,316
// // AsynchronousOperation.swift // EthosUtil // // Created by Etienne Goulet-Lang on 4/16/19. // Copyright © 2019 egouletlang. All rights reserved. // import Foundation /** The AsynchronousOperation class supports doing asynchronous work. This lets you chain operations and seperate code to improve reusability. The class wraps the main(..) function and waits for an explicit call to deactivate(..) before the operation 'completes'. Having said that, the operation is not allowed to run indefinitly. It uses two parameters SLEEP_TIME, COUNT_MAX to determine how long the thread will sleep and how many times it will sleep before abandoning respectively */ open class AsynchronousOperation: Operation { // MARK: - Constants & Types /** This constant determines the number of cycles to wait before stopping the operation. - note: The 'COUNT_MAX' and 'SLEEP_TIME' constants are part of a fail-safe mechanism to prevent any child Operation from blocking a queue, if the thread is left active for any reason. */ fileprivate static let COUNT_MAX = 500 /** This constant determines the amount of time (in seconds) to sleep between cycles= - note: The 'COUNT_MAX' and 'SLEEP_TIME' constants are part of a fail-safe mechanism to prevent any child Operation from blocking a queue, if the thread is left active for any reason. */ fileprivate static let SLEEP_TIME: TimeInterval = 0.1 // MARK: - Singleton & Delegate /** A delegate to handle the operation result once it is ready */ open weak var asynchronousOperationDelegate: AsynchronousOperationDelegate? // MARK: - State Variables /** This member tracks whether the operation is still active */ private var operationActive = false //MARK: - Lifecycle /** This method sets the operation state to active */ private func activate() { self.operationActive = true } /** This method sets the operation state to inactive, and uses the delegate to "complete" the action - parameters: - result: the operation result */ open func deactivate(result: Any?) { self.operationActive = false self.asynchronousOperationDelegate?.complete(result: result) } /** This method sleeps for `SLEEP_TIME` until either deactivate(..) is called or the number of sleep cycles reaches COUNT_MAX - Note: If TTL is exceeded, the operation is NOT cancelled. */ private func waitForDeactivate() { var count = 0 while (operationActive && count < AsynchronousOperation.COUNT_MAX) { Thread.sleep(forTimeInterval: AsynchronousOperation.SLEEP_TIME) count += 1 } } /** This class overrides the main method to - activate() - run() - waitForDeactivate() */ override open func main() { self.activate() self.run() self.waitForDeactivate() } // MARK: - “Abstract” Methods (Override these) /** Treat as main(..) - important: be sure to ALWAYS call deactivate(..), even when there is an error */ open func run() { assert(false, "You must overriding run(...)") } }
31.283019
120
0.658323
e8c98faf22879b6f175842644fde61ebd95cbcf1
600
// // File.swift // // // Created by Alexander Martirosov on 4/14/20. // import Foundation public extension Behavior { class AppearanceAnimation: Behavior { public let type: Type public init(id: String? = nil, type: Type, onlyOnce: Bool = false, onAppearing: Bool = false) { self.type = type super.init(id: id, trigger: !onAppearing ? .onAppeared(onlyOnce: onlyOnce) : .onAppearing(onlyOnce: onlyOnce)) } public enum `Type` { case slideFromBottom case opacity } } }
22.222222
122
0.563333
f4014163ce4f24875d337374d4b15fcb4880b9bc
7,400
// // Copyright © 2021 Rosberry. All rights reserved. // import Foundation import Stencil import StencilSwiftKit import Yams import PathKit public final class Renderer { public enum Error: Swift.Error & CustomStringConvertible { case noOutput(template: String) public var description: String { switch self { case let .noOutput(template): return "There is no output path for \(template) template. Please use --output option or add output to general.yml." } } } private class VariablesTemplate: Template { var variables: [String] required init(templateString: String, environment: Environment? = nil, name: String? = nil) { let pattern = "\\{\\{\\s*([a-zA-Z][a-zA-Z0-9]*)\\s*\\}\\}" self.variables = parseAllRegexMatches(pattern: pattern, rangeIndex: 1, string: templateString) super.init(templateString: templateString, environment: environment, name: name) } } public typealias Dependencies = HasFileHelper & HasSpecFactory let name: String let template: String let path: String let variables: [Variable] var output: String? private lazy var context: [String: Any] = { let year = Calendar.current.component(.year, from: .init()) var context: [String: Any] = ["name": name, "year": year] for variable in variables { context[variable.key] = variable.value } return context }() private let dependencies: Dependencies public init(name: String, template: String, path: String, variables: [Variable], output: String?, dependencies: Dependencies) { self.name = name self.template = template self.path = path self.variables = variables self.output = output self.dependencies = dependencies } public func render(completion: ((URL) throws -> Void)? = nil) throws { let templatesURL = defineTemplatesURL() let templateURL = templatesURL + template let specURL = templateURL + Constants.specFilename let templateSpec: TemplateSpec = try dependencies.specFactory.makeSpec(url: specURL) let environment = try makeEnvironment(templatesURL: templatesURL, templateURL: templateURL) try add(templateSpec, environment: environment, completion: completion) print("🎉 \(template) template with \(name) name was successfully generated.") } public func add(_ templateSpec: TemplateSpec, environment: Environment, completion: ((URL) throws -> Void)? = nil) throws { for file in templateSpec.files { if let fileURL = try render(file, templateSpec: templateSpec, environment: environment) { try completion?(fileURL) } } } public func render(_ file: File, templateSpec: TemplateSpec, environment: Environment) throws -> URL? { askRequiredVariables(file, environment: environment) let rendered = try environment.renderTemplate(name: file.template, context: context).trimmingCharacters(in: .whitespacesAndNewlines) let module = name let fileName = file.fileName(in: module) // make output url for the file var outputURL = URL(fileURLWithPath: path) if let output = file.output { outputURL.appendPathComponent(output) } else if let folder = outputFolder() { outputURL.appendPathComponent(folder) if let suffix = templateSpec.suffix { outputURL.appendPathComponent(name + suffix) } else { outputURL.appendPathComponent(name) } if let subfolder = file.folder { outputURL.appendPathComponent(subfolder) } outputURL.appendPathComponent(fileName) } else { throw Error.noOutput(template: template) } // write rendered template to file let fileURL = outputURL outputURL.deleteLastPathComponent() let fileManager = dependencies.fileHelper.fileManager guard !fileManager.fileExists(atPath: fileURL.path) else { print(yellow("File already exists: \(fileURL.path)")) return nil } try fileManager.createDirectory(at: outputURL, withIntermediateDirectories: true, attributes: nil) try rendered.write(to: fileURL, atomically: true, encoding: .utf8) return fileURL } // MARK: - Private private func outputFolder() -> String? { if let output = self.output { return output } let pathURL = URL(fileURLWithPath: path, isDirectory: true) let specURL = URL(fileURLWithPath: Constants.generalSpecName, relativeTo: pathURL) let generalSpec: GeneralSpec? = try? dependencies.specFactory.makeSpec(url: specURL) guard let output = generalSpec?.output(forTemplateName: template) else { return nil } return output.path } private func defineTemplatesURL() -> URL { let fileManager = dependencies.fileHelper.fileManager let folderName = Constants.templatesFolderName let localPath = "./\(folderName)/" if fileManager.fileExists(atPath: localPath + template) { return URL(fileURLWithPath: localPath) } return fileManager.homeDirectoryForCurrentUser + folderName } private func makeEnvironment(templatesURL: URL, templateURL: URL) throws -> Environment { let fileManager = dependencies.fileHelper.fileManager let commonTemplatesURL = templatesURL + Constants.commonTemplatesFolderName let contents = try fileManager.contentsOfDirectory(at: templateURL, includingPropertiesForKeys: [.isDirectoryKey], options: []) let directoryPaths: [Path] = contents.compactMap { url in guard url.hasDirectoryPath else { return nil } return Path(url.path) } var paths = [Path(commonTemplatesURL.path), Path(templateURL.path)] paths.append(contentsOf: directoryPaths) let environment = Environment(loader: FileSystemLoader(paths: paths)) environment.extensions.forEach { ext in ext.registerStencilSwiftExtensions() } return environment } private func askRequiredVariables(_ file: File, environment: Environment) { let templateEnvironment = Environment(loader: environment.loader, extensions: environment.extensions, templateClass: VariablesTemplate.self) guard let template = try? templateEnvironment.loadTemplate(name: file.template) as? VariablesTemplate, !template.variables.isEmpty else { return } print(yellow("Please enter following template variables")) template.variables.forEach { variable in if !context.keys.contains(variable) { context[variable] = ask("\(variable)") } } } }
38.947368
140
0.615946
dee1dac154d328a1af519764db340d7643d09665
879
// // MovieService.swift // MovieProject // // Created by Abdullah Coban on 14.07.2021. // import Foundation protocol MovieService { func getMovies() -> () func getMovieById(id: Int) -> () func searchMovie(query: String) -> () } enum MovieError: Error, CustomNSError { case apiError case invalidEndpoint case invalidResponse case noData case serializationError var localizedDescription: String { switch self { case .apiError: return "Failed to fetch data" case .invalidEndpoint: return "Invalid endpoint" case .invalidResponse: return "Invalid response" case .noData: return "No data" case .serializationError: return "Failed to decode data" } } var errorUserInfo: [String : Any] { [NSLocalizedDescriptionKey: localizedDescription] } }
21.975
64
0.640501
64ba8f5274d6872d884c15bbe923cb0b6a078858
2,336
@testable import Tasker import XCTest final class ArrayOfTasksTests: XCTestCase { override func setUp() { self.addTeardownBlock { ensure(AsyncOperation.referenceCounter.value).becomes(0) AsyncOperation.referenceCounter.value = 0 } } func testCanBeAwaited() { var tasks: [AnyTask<Int>] = [] for i in 0 ..< 10 { tasks.append(AnyTask { i }) } for (i, result) in (try! tasks.await()).sorted().enumerated() { XCTAssertEqual(i, result.successValue) } } func testEmptyArrayCanBeAwaited() { let tasks: [AnyTask<Int>] = [] let results = try? tasks.await() XCTAssertEqual(results?.count, 0) } func testCanBeAsynced() { var tasks: [AnyTask<Int>] = [] for i in 0 ..< 10 { tasks.append(AnyTask { if i.isMultiple(of: 2) { $0(.success(i)) } else { $0(.failure(NSError(domain: "", code: i, userInfo: nil))) } }) } let result = SynchronizedArray<Result<Int, Error>>() tasks.async { if let data = $0.successValue { result.data = data } } ensure(result.count).becomes(10) for (i, result) in result.data.sorted().enumerated() { if i.isMultiple(of: 2) { XCTAssertEqual(i, result.successValue) } else { XCTAssertEqual(i, (result.failureValue as NSError?)?.code) } } } func testAwaitSuccess() { var tasks: [AnyTask<Int>] = [] for i in 0 ..< 10 { tasks.append(AnyTask { if i.isMultiple(of: 2) { $0(.success(i)) } else { $0(.failure(NSError(domain: "", code: i, userInfo: nil))) } }) } XCTAssertEqual(tasks.awaitSuccess(), [0, 2, 4, 6, 8]) } func testAwaitSuccessInsideAsync() { let task = AnyTask<Int> { done in AnyTask<Int> { 5 }.async { _ in self.testAwaitSuccess() done(.success(5)) } } XCTAssertEqual(try! task.await(), 5) } }
27.809524
77
0.474315
ccb650ee757e906d2ff9b82c4fc201f9556981fb
6,011
// // EVReflectionWorkaroundsTests.swift // // Created by Edwin Vermeer on 7/23/15. // Copyright (c) 2015. All rights reserved. // import XCTest @testable import EVReflection /** Testing The 3 propery types that need a workaround. */ class EVReflectionWorkaroundsTests: XCTestCase { /** For now nothing to setUp */ override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. EVReflection.setBundleIdentifier(TestObject) } /** For now nothing to tearDown */ override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testWorkaroundsSmoketest() { let json:String = "{\"nullableType\": 1,\"enumType\": 0, \"list\": [ {\"nullableType\": 2}, {\"nullableType\": 3}] }" let status = WorkaroundObject(json: json) XCTAssertTrue(status.nullableType == 1, "the nullableType should be 1") XCTAssertTrue(status.enumType == .NotOK, "the status should be NotOK") XCTAssertTrue(status.list.count == 2, "the list should have 2 items") if status.list.count == 2 { XCTAssertTrue(status.list[0]?.nullableType == 2, "the first item in the list should have nullableType 2") XCTAssertTrue(status.list[1]?.nullableType == 3, "the second item in the list should have nullableType 3") } } func testWorkaroundsToJson() { let initialJson:String = "{\"nullableType\": 1,\"enumType\": 0, \"list\": [ {\"nullableType\": 2}, {\"nullableType\": 3}], \"unknownKey\": \"some\" }" let initialStatus = WorkaroundObject(json: initialJson) let json = initialStatus.toJsonString() let status = WorkaroundObject(json: json) print("To JSON = \(json)") XCTAssertTrue(status.nullableType == 1, "the nullableType should be 1") XCTAssertTrue(status.enumType == .NotOK, "the status should be NotOK") XCTAssertTrue(status.list.count == 2, "the list should have 2 items") if status.list.count == 2 { XCTAssertTrue(status.list[0]?.nullableType == 2, "the first item in the list should have nullableType 2") XCTAssertTrue(status.list[1]?.nullableType == 3, "the second item in the list should have nullableType 3") } } func testWorkaroundsCustomDictionary() { let json: String = "{\"dict\" : {\"firstkey\": {\"field\":5}, \"secondkey\": {\"field\":35}}}" let doc = WorkaroundObject(json: json) XCTAssertEqual(doc.dict.count, 2, "Should have 2 items in the dictionary") XCTAssertEqual(doc.dict["firstkey"]?.field, "5", "First sentence should have id 5") XCTAssertEqual(doc.dict["secondkey"]?.field, "35", "Second sentence should have id 35") } func testStruct() { let event = WorkaroundObject() event.structType = CGPointMake(2,3) let json = event.toJsonString() print("json = \(json)") let newEvent = WorkaroundObject(json:json) XCTAssertEqual(newEvent.structType.x, 2, "The location x should have been 2") XCTAssertEqual(newEvent.structType.y, 3, "The location y should have been 3") } } // class WorkaroundObject: EVObject, EVArrayConvertable, EVDictionaryConvertable { enum StatusType: Int, EVRawInt { case NotOK = 0 case OK = 1 } var nullableType: Int? var enumType: StatusType = .OK var list: [WorkaroundObject?] = [WorkaroundObject?]() var dict: [String: SubObject] = [:] var structType: CGPoint = CGPointMake(0,0) // Handling the setting of non key-value coding compliant properties override func setValue(value: AnyObject!, forUndefinedKey key: String) { switch key { case "nullableType": nullableType = value as? Int case "enumType": if let rawValue = value as? Int { if let status = StatusType(rawValue: rawValue) { self.enumType = status } } case "list": if let list = value as? NSArray { self.list = [] for item in list { self.list.append(item as? WorkaroundObject) } } case "dict": if let dict = value as? NSDictionary { self.dict = [:] for (key,value) in dict { self.dict[key as! String] = (value as! SubObject) } } case "structType": if let dict = value as? NSDictionary { if let x = dict["x"] as? NSNumber, let y = dict["y"] as? NSNumber { structType = CGPointMake(CGFloat(x), CGFloat(y)) } } default: print("---> setValue for key '\(key)' should be handled.") } } // Implementation of the EVArrayConvertable protocol for handling an array of nullble objects. func convertArray(key: String, array: Any) -> NSArray { assert(key == "list", "convertArray for key \(key) should be handled.") let returnArray = NSMutableArray() for item in array as! [WorkaroundObject?] { if item != nil { returnArray.addObject(item!) } } return returnArray } // Implementation of the EVDictionaryConvertable protocol for handling a Swift dictionary. func convertDictionary(field: String, dict: Any) -> NSDictionary { assert(field == "dict", "convertArray for key \(field) should be handled.") let returnDict = NSMutableDictionary() for (key, value) in dict as! NSDictionary { returnDict[key as! String] = SubObject(dictionary: value as! NSDictionary) } return returnDict } }
36.652439
158
0.593412
de8908a6ea2d75b4dee9e56ece050a42b5378f42
4,717
//===--- SwiftPrivatePthreadExtras.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 // //===----------------------------------------------------------------------===// // // This file contains wrappers for pthread APIs that are less painful to use // than the C APIs. // //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) import Glibc #endif /// An abstract base class to encapsulate the context necessary to invoke /// a block from pthread_create. internal class PthreadBlockContext { /// Execute the block, and return an `UnsafeMutablePointer` to memory /// allocated with `UnsafeMutablePointer.alloc` containing the result of the /// block. func run() -> UnsafeMutableRawPointer { fatalError("abstract") } } internal class PthreadBlockContextImpl<Argument, Result>: PthreadBlockContext { let block: (Argument) -> Result let arg: Argument init(block: @escaping (Argument) -> Result, arg: Argument) { self.block = block self.arg = arg super.init() } override func run() -> UnsafeMutableRawPointer { let result = UnsafeMutablePointer<Result>.allocate(capacity: 1) result.initialize(to: block(arg)) return UnsafeMutableRawPointer(result) } } /// Entry point for `pthread_create` that invokes a block context. internal func invokeBlockContext( _ contextAsVoidPointer: UnsafeMutableRawPointer? ) -> UnsafeMutableRawPointer! { // The context is passed in +1; we're responsible for releasing it. let context = Unmanaged<PthreadBlockContext> .fromOpaque(contextAsVoidPointer!) .takeRetainedValue() return context.run() } #if os(Cygwin) || os(FreeBSD) || os(Haiku) public typealias _stdlib_pthread_attr_t = UnsafePointer<pthread_attr_t?> #else public typealias _stdlib_pthread_attr_t = UnsafePointer<pthread_attr_t> #endif /// Block-based wrapper for `pthread_create`. public func _stdlib_pthread_create_block<Argument, Result>( _ attr: _stdlib_pthread_attr_t?, _ start_routine: @escaping (Argument) -> Result, _ arg: Argument ) -> (CInt, pthread_t?) { let context = PthreadBlockContextImpl(block: start_routine, arg: arg) // We hand ownership off to `invokeBlockContext` through its void context // argument. let contextAsVoidPointer = Unmanaged.passRetained(context).toOpaque() var threadID = _make_pthread_t() let result = pthread_create(&threadID, attr, { invokeBlockContext($0) }, contextAsVoidPointer) if result == 0 { return (result, threadID) } else { return (result, nil) } } #if os(Linux) || os(Android) internal func _make_pthread_t() -> pthread_t { return pthread_t() } #else internal func _make_pthread_t() -> pthread_t? { return nil } #endif /// Block-based wrapper for `pthread_join`. public func _stdlib_pthread_join<Result>( _ thread: pthread_t, _ resultType: Result.Type ) -> (CInt, Result?) { var threadResultRawPtr: UnsafeMutableRawPointer? let result = pthread_join(thread, &threadResultRawPtr) if result == 0 { let threadResultPtr = threadResultRawPtr!.assumingMemoryBound( to: Result.self) let threadResult = threadResultPtr.pointee threadResultPtr.deinitialize(count: 1) threadResultPtr.deallocate() return (result, threadResult) } else { return (result, nil) } } public class _stdlib_Barrier { var _pthreadBarrier: _stdlib_pthread_barrier_t var _pthreadBarrierPtr: UnsafeMutablePointer<_stdlib_pthread_barrier_t> { return _getUnsafePointerToStoredProperties(self) .assumingMemoryBound(to: _stdlib_pthread_barrier_t.self) } public init(threadCount: Int) { self._pthreadBarrier = _stdlib_pthread_barrier_t() let ret = _stdlib_pthread_barrier_init( _pthreadBarrierPtr, nil, CUnsignedInt(threadCount)) if ret != 0 { fatalError("_stdlib_pthread_barrier_init() failed") } } deinit { let ret = _stdlib_pthread_barrier_destroy(_pthreadBarrierPtr) if ret != 0 { fatalError("_stdlib_pthread_barrier_destroy() failed") } } public func wait() { let ret = _stdlib_pthread_barrier_wait(_pthreadBarrierPtr) if !(ret == 0 || ret == _stdlib_PTHREAD_BARRIER_SERIAL_THREAD) { fatalError("_stdlib_pthread_barrier_wait() failed") } } }
31.657718
85
0.698325
21703a4b598e23bde44db96c0c80b305702bc717
2,651
import ArgumentParser import Foundation import RxBlocking import RxSwift import TSCBasic import TuistCache import TuistCore import TuistGenerator import TuistLoader import TuistSupport enum FocusCommandError: FatalError { case noSources var description: String { switch self { case .noSources: return "A list of targets is required: tuist focus MyTarget." } } var type: ErrorType { switch self { case .noSources: return .abort } } } /// The focus command generates the Xcode workspace and launches it on Xcode. struct FocusCommand: ParsableCommand, HasTrackableParameters { static var configuration: CommandConfiguration { CommandConfiguration(commandName: "focus", abstract: "Opens Xcode ready to focus on the project in the current directory") } static var analyticsDelegate: TrackableParametersDelegate? @Option( name: .shortAndLong, help: "The path to the directory containing the project you plan to focus on.", completion: .directory ) var path: String? @Argument(help: "A list of targets in which you'd like to focus. Those and their dependant targets will be generated as sources.") var sources: [String] = [] @Flag( name: .shortAndLong, help: "Don't open the project after generating it." ) var noOpen: Bool = false @Flag( name: [.customShort("x"), .long], help: "When passed it uses xcframeworks (simulator and device) from the cache instead of frameworks (only simulator)." ) var xcframeworks: Bool = false @Option( name: [.customShort("P"), .long], help: "The name of the cache profile to be used when focusing on the target." ) var profile: String? @Flag( name: [.customLong("no-cache")], help: "Ignore cached targets, and use their sources instead." ) var ignoreCache: Bool = false func run() throws { if sources.isEmpty { throw FocusCommandError.noSources } FocusCommand.analyticsDelegate?.willRun(withParameters: [ "xcframeworks": String(xcframeworks), "no-cache": String(ignoreCache), "n_targets": String(sources.count), ]) try FocusService().run(path: path, sources: Set(sources), noOpen: noOpen, xcframeworks: xcframeworks, profile: profile, ignoreCache: ignoreCache) } }
29.455556
134
0.608827
90fba577ac16022463db58c8760a1a1bead93089
1,629
import Foundation extension String { // From https://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language var length: Int { return count } subscript (i: Int) -> String { return self[i ..< i + 1] } func substring(fromIndex: Int) -> String { return self[min(fromIndex, length) ..< length] } func substring(toIndex: Int) -> String { return self[0 ..< max(0, toIndex)] } subscript (r: Range<Int>) -> String { let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)), upper: min(length, max(0, r.upperBound)))) let start = index(startIndex, offsetBy: range.lowerBound) let end = index(start, offsetBy: range.upperBound - range.lowerBound) return String(self[start ..< end]) } } precedencegroup SingleFowardPipe { associativity: left higherThan: BitwiseShiftPrecedence } infix operator |> : SingleFowardPipe func |> <T, U>(result: T, next: ((T) -> U)) -> U { return next(result) } func printPipe <T>(result: T) { print(result) } struct Input { var Text: String; var Position: Int; } func substringFromInput (start: Int, len: Int, input: Input) -> Input { return (Input( Text: input.Text[start..<len], Position: input.Position + start)); } func main () { // {(output: Input) in print(output)} Input(Text: "This is a test string", Position: 0) |> {(elem: Input) -> Input in return substringFromInput(start: 0, len: 21, input: elem)} |> printPipe } main();
27.15
116
0.608963
c112d7e2efdee4fa6036e34b20980b31c940055f
4,799
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2019 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Crypto import NIO /// An SSH private key. /// /// This object identifies a single SSH entity, usually a server. It is used as part of the SSH handshake and key exchange process, /// and is also presented to clients that want to validate that they are communicating with the appropriate server. Clients use /// this key to sign data in order to validate their identity as part of user auth. /// /// Users cannot do much with this key other than construct it, but NIO uses it internally. public struct NIOSSHPrivateKey { /// The actual key structure used to perform the key operations. internal var backingKey: BackingKey private init(backingKey: BackingKey) { self.backingKey = backingKey } public init(ed25519Key key: Curve25519.Signing.PrivateKey) { self.backingKey = .ed25519(key) } public init(p256Key key: P256.Signing.PrivateKey) { self.backingKey = .ecdsaP256(key) } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) public init(secureEnclaveP256Key key: SecureEnclave.P256.Signing.PrivateKey) { self.backingKey = .secureEnclaveP256(key) } #endif // The algorithms that apply to this host key. internal var hostKeyAlgorithms: [Substring] { switch self.backingKey { case .ed25519: return ["ssh-ed25519"] case .ecdsaP256: return ["ecdsa-sha2-nistp256"] #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) case .secureEnclaveP256: return ["ecdsa-sha2-nistp256"] #endif } } } extension NIOSSHPrivateKey { /// The various key types that can be used with NIOSSH. internal enum BackingKey { case ed25519(Curve25519.Signing.PrivateKey) case ecdsaP256(P256.Signing.PrivateKey) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) case secureEnclaveP256(SecureEnclave.P256.Signing.PrivateKey) #endif } } extension NIOSSHPrivateKey { func sign<DigestBytes: Digest>(digest: DigestBytes) throws -> SSHSignature { switch self.backingKey { case .ed25519(let key): let signature = try digest.withUnsafeBytes { ptr in try key.signature(for: ptr) } return SSHSignature(backingSignature: .ed25519(.data(signature))) case .ecdsaP256(let key): let signature = try digest.withUnsafeBytes { ptr in try key.signature(for: ptr) } return SSHSignature(backingSignature: .ecdsaP256(signature)) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) case .secureEnclaveP256(let key): let signature = try digest.withUnsafeBytes { ptr in try key.signature(for: ptr) } return SSHSignature(backingSignature: .ecdsaP256(signature)) #endif } } func sign(_ payload: UserAuthSignablePayload) throws -> SSHSignature { switch self.backingKey { case .ed25519(let key): let signature = try key.signature(for: payload.bytes.readableBytesView) return SSHSignature(backingSignature: .ed25519(.data(signature))) case .ecdsaP256(let key): let signature = try key.signature(for: payload.bytes.readableBytesView) return SSHSignature(backingSignature: .ecdsaP256(signature)) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) case .secureEnclaveP256(let key): let signature = try key.signature(for: payload.bytes.readableBytesView) return SSHSignature(backingSignature: .ecdsaP256(signature)) #endif } } } extension NIOSSHPrivateKey { /// Obtains the public key for a corresponding private key. public var publicKey: NIOSSHPublicKey { switch self.backingKey { case .ed25519(let privateKey): return NIOSSHPublicKey(backingKey: .ed25519(privateKey.publicKey)) case .ecdsaP256(let privateKey): return NIOSSHPublicKey(backingKey: .ecdsaP256(privateKey.publicKey)) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) case .secureEnclaveP256(let privateKey): return NIOSSHPublicKey(backingKey: .ecdsaP256(privateKey.publicKey)) #endif } } }
36.915385
131
0.627631
dbfb312993a7df05ce77222edda5fa75930f210f
2,863
// // LoadingLabel.swift // GradientAnimation // // Created by mr.scorpion on 4/23/16. // Copyright © 2016 mr.scorpion. All rights reserved. // import UIKit @IBDesignable class LoadingLabel: UIView { // MARK: - Types struct Constants { struct Fonts { static let loadingLabel = "HelveticaNeue-UltraLight" } } // MARK: - Properties let gradientLayer: CAGradientLayer = { let gradientLayer = CAGradientLayer() // Configure gradient. gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5) let colors = [UIColor.grayColor().CGColor, UIColor.whiteColor().CGColor, UIColor.grayColor().CGColor] gradientLayer.colors = colors let locations = [0.25, 0.5, 0.75] gradientLayer.locations = locations return gradientLayer }() let textAttributes: [String: AnyObject] = { let style = NSMutableParagraphStyle() style.alignment = .Center return [NSFontAttributeName: UIFont(name: Constants.Fonts.loadingLabel, size: 70.0)!, NSParagraphStyleAttributeName: style] }() @IBInspectable var text: String! { didSet { setNeedsDisplay() // Create a temporary graphic context in order to render the text as an image. UIGraphicsBeginImageContextWithOptions(frame.size, false, 0) text.drawInRect(bounds, withAttributes: textAttributes) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // Use image to create a mask on the gradient layer. let maskLayer = CALayer() maskLayer.backgroundColor = UIColor.clearColor().CGColor maskLayer.frame = CGRectOffset(bounds, bounds.size.width, 0) maskLayer.contents = image.CGImage gradientLayer.mask = maskLayer } } // MARK: - View Life Cycle override func layoutSubviews() { gradientLayer.frame = CGRect(x: -bounds.size.width, y: bounds.origin.y, width: 2 * bounds.size.width, height: bounds.size.height) } override func didMoveToWindow() { super.didMoveToWindow() layer.addSublayer(gradientLayer) let gradientAnimation = CABasicAnimation(keyPath: "locations") gradientAnimation.fromValue = [0.0, 0.0, 0.25] gradientAnimation.toValue = [0.75, 1.0, 1.0] gradientAnimation.duration = 1.7 gradientAnimation.repeatCount = Float.infinity gradientAnimation.removedOnCompletion = false gradientAnimation.fillMode = kCAFillModeForwards gradientLayer.addAnimation(gradientAnimation, forKey: nil) } }
32.534091
137
0.619979
8fdb391d34e9e9ac6ce125255827afe509e5d41f
454
// // MediaPropertyFavoritesView.swift // Clematis (iOS) // // Created by Kyle Erhabor on 2/21/21. // import SwiftUI struct MediaPropertyFavoritesView: View { @EnvironmentObject private var viewModel: MediaViewModel var body: some View { if let favorites = viewModel.media?.favourites, favorites > 0 { GroupBox(label: Text("Favorites")) { Text("\(favorites.abbreviated)") } } } }
21.619048
71
0.618943
1da235fbb1ba3dbaffb2873218a214891a686de2
2,420
// // Be happy and free :) // // Nik Kov // nik-kov.com // #if os(iOS) import Foundation import UIKit open class NKVFlagView: UIView { // MARK: - Interface /// Shows what country is presenting now. The NKVPhoneTextField gets its value for `country` property from here. public var currentPresentingCountry: Country? /// A designated method for setting a flag image public func setFlag(with source: NKVSource) { if let flagImage = NKVSourcesHelper.flag(for: source), let newSettedCountry = Country.country(for: source) { self.flagButton.setImage(flagImage, for: .normal) currentPresentingCountry = newSettedCountry textField.presenter.enablePhoneFormat(for: newSettedCountry) } } /// Size of the flag icon public var iconSize: CGSize { didSet { configureInstance() } } /// Shifting for the icon from top, left, bottom and right. public var insets: UIEdgeInsets { didSet { configureInstance() } } // MARK: - Initialization public required init(with textField: NKVPhonePickerTextField) { self.textField = textField self.insets = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7) self.iconSize = CGSize(width: 18.0, height: textField.frame.height) super.init(frame: CGRect.zero) configureInstance() } override open func layoutSubviews() { updateFrame() } // MARK: - Implementation public var flagButton: UIButton = UIButton() private weak var textField: NKVPhonePickerTextField! private func configureInstance() { // Adding flag button to flag's view flagButton.imageEdgeInsets = insets; flagButton.imageView?.contentMode = .scaleAspectFit flagButton.contentMode = .scaleToFill if flagButton.superview == nil { self.addSubview(flagButton) } updateFrame() } /// Set and update flag view's frame. private func updateFrame() { self.frame = CGRect(x: 0, y: 0, width: insets.left + insets.right + iconSize.width, height: max(textField.frame.height, iconSize.height)) flagButton.frame = self.frame } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) not supported"); } } #endif
31.842105
116
0.627273
9113389783aea789d32304b652c72d94e4e2105f
2,507
// // ExtensionDelegate.swift // lAzR4t watchOS App Extension // // Created by Jakob Hain on 9/29/17. // Copyright © 2017 Jakob Hain. All rights reserved. // import WatchKit class ExtensionDelegate: NSObject, WKExtensionDelegate { func applicationDidFinishLaunching() { // Perform any final initialization of your application. } func applicationDidBecomeActive() { // 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 applicationWillResignActive() { // 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, etc. } func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) { // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one. for task in backgroundTasks { // Use a switch statement to check the task type switch task { case let backgroundTask as WKApplicationRefreshBackgroundTask: // Be sure to complete the background task once you’re done. backgroundTask.setTaskCompletedWithSnapshot(false) case let snapshotTask as WKSnapshotRefreshBackgroundTask: // Snapshot tasks have a unique completion call, make sure to set your expiration date snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil) case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask: // Be sure to complete the connectivity task once you’re done. connectivityTask.setTaskCompletedWithSnapshot(false) case let urlSessionTask as WKURLSessionRefreshBackgroundTask: // Be sure to complete the URL session task once you’re done. urlSessionTask.setTaskCompletedWithSnapshot(false) default: // make sure to complete unhandled task types task.setTaskCompletedWithSnapshot(false) } } } }
49.156863
285
0.697647
1d10d50aa2f2a50425d21b57aea03a08dd6885d3
6,275
// https://docs.swift.org/swift-book/LanguageGuide/Initialization.html // Swift 5.2 struct Size { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } let twoByTwo = Size(width: 2.0, height: 2.0) let zeroByTwo = Size(height: 2.0) print(zeroByTwo.width, zeroByTwo.height) // Prints "0.0 2.0" let zeroByZero = Size() print(zeroByZero.width, zeroByZero.height) // Prints "0.0 0.0" struct Rect { var origin = Point() var size = Size() init() {} init(origin: Point, size: Size) { self.origin = origin self.size = size } init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } /// Classes class Vehicle { var numberOfWheels = 0 var description: String { return "\(numberOfWheels) wheel(s)" } } let vehicle = Vehicle() print("Vehicle: \(vehicle.description)") // Vehicle: 0 wheel(s) class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } } let bicycle = Bicycle() print("Bicycle: \(bicycle.description)") // Bicycle: 2 wheel(s) class Hoverboard: Vehicle { var color: String init(color: String) { self.color = color // super.init() implicitly called here } override var description: String { return "\(super.description) in a beautiful \(color)" } } let hoverboard = Hoverboard(color: "silver") print("Hoverboard: \(hoverboard.description)") // Hoverboard: 0 wheel(s) in a beautiful silver /// Designated and Convenience Initializers in Action class Food { var name: String init(name: String) { self.name = name } convenience init() { self.init(name: "[Unnamed]") } } let namedMeat = Food(name: "Bacon") // namedMeat's name is "Bacon" let mysteryMeat = Food() // mysteryMeat's name is "[Unnamed]" class RecipeIngredient: Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } override convenience init(name: String) { self.init(name: name, quantity: 1) } } let oneMysteryItem = RecipeIngredient() let oneBacon = RecipeIngredient(name: "Bacon") let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6) class ShoppingListItem: RecipeIngredient { var purchased = false var description: String { var output = "\(quantity) x \(name)" output += purchased ? " ✔" : " ✘" return output } } var breakfastList = [ ShoppingListItem(), ShoppingListItem(name: "Bacon"), ShoppingListItem(name: "Eggs", quantity: 6), ] breakfastList[0].name = "Orange juice" breakfastList[0].purchased = true for item in breakfastList { print(item.description) } // 1 x Orange juice ✔ // 1 x Bacon ✘ // 6 x Eggs ✘ /// Failable Initializer for classes, structures and enums struct Animal { let species: String init?(species: String) { if species.isEmpty { return nil } self.species = species } } let someCreature = Animal(species: "Giraffe") // someCreature is of type Animal?, not Animal if let giraffe = someCreature { print("An animal was initialized with a species of \(giraffe.species)") } // Prints "An animal was initialized with a species of Giraffe" let anonymousCreature = Animal(species: "") // anonymousCreature is of type Animal?, not Animal if anonymousCreature == nil { print("The anonymous creature could not be initialized") } // Prints "The anonymous creature could not be initialized" /// Propagation of Initialization Failure class Product { let name: String init?(name: String) { if name.isEmpty { return nil } self.name = name } } class CartItem: Product { let quantity: Int init?(name: String, quantity: Int) { if quantity < 1 { return nil } self.quantity = quantity super.init(name: name) } } if let twoSocks = CartItem(name: "sock", quantity: 2) { print("Item: \(twoSocks.name), quantity: \(twoSocks.quantity)") } // Prints "Item: sock, quantity: 2" if let zeroShirts = CartItem(name: "shirt", quantity: 0) { print("Item: \(zeroShirts.name), quantity: \(zeroShirts.quantity)") } else { print("Unable to initialize zero shirts") } // Prints "Unable to initialize zero shirts" if let oneUnnamed = CartItem(name: "", quantity: 1) { print("Item: \(oneUnnamed.name), quantity: \(oneUnnamed.quantity)") } else { print("Unable to initialize one unnamed product") } // Prints "Unable to initialize one unnamed product" /// Overriding a Failable Initializer (override a failable initializer with a nonfailable initializer but not the other way around.) class Document { var name: String? // this initializer creates a document with a nil name value init() {} // this initializer creates a document with a nonempty name value init?(name: String) { if name.isEmpty { return nil } self.name = name } } class AutomaticallyNamedDocument: Document { override init() { super.init() self.name = "[Untitled]" } override init(name: String) { super.init() if name.isEmpty { self.name = "[Untitled]" } else { self.name = name } } } class UntitledDocument: Document { override init() { super.init(name: "[Untitled]")! // use forced unwrapping in an initializer to call a failable initializer from the superclass as part of the implementation of a subclass’s nonfailable initializer. } } /// Class specific: Required Initializers class SomeClass { required init() { // initializer implementation goes here } } class SomeSubclass: SomeClass { required init() { // subclass implementation of the required initializer goes here } } /// Class specific: Setting a Default Property Value with a Closure or Function class SomeOtherClass { let someProperty: SomeType = { // create a default value for someProperty inside this closure // someValue must be of the same type as SomeType return SomeType() }() } class SomeType { }
24.042146
204
0.646375
568efbed443c922f8346b3fc9c90b6a5ead77adb
2,221
// // File.swift // // // Created by Yu Ao on 2019/12/26. // import Foundation import AVFoundation @available(macOS 10.15, *) @available(tvOS, unavailable) extension Camera { @available(iOS 11.0, *) private class PhotoCaptureDelegateHandler: NSObject, AVCapturePhotoCaptureDelegate { var willBeginCaptureHandler: ((AVCaptureResolvedPhotoSettings) -> Void)? var didFinishProcessingHandler: ((Result<AVCapturePhoto, Swift.Error>) -> Void)? func photoOutput(_ output: AVCapturePhotoOutput, willBeginCaptureFor resolvedSettings: AVCaptureResolvedPhotoSettings) { self.willBeginCaptureHandler?(resolvedSettings) } func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Swift.Error?) { if let error = error { self.didFinishProcessingHandler?(.failure(error)) } else { self.didFinishProcessingHandler?(.success(photo)) } } } @available(iOS 11.0, *) public func capturePhoto(with settings: AVCapturePhotoSettings, willBeginCaptureHandler: ((AVCaptureResolvedPhotoSettings) -> Void)? = nil, didFinishProcessingHandler: @escaping (Result<AVCapturePhoto, Swift.Error>) -> Void) { assert(self.photoOutput != nil) guard let photoOutput = self.photoOutput else { return } let handler = PhotoCaptureDelegateHandler() handler.willBeginCaptureHandler = willBeginCaptureHandler handler.didFinishProcessingHandler = { [weak self, unowned handler] result in didFinishProcessingHandler(result) guard let strongSelf = self else { return } strongSelf.photoCaptureDelegateHandlers.removeAll(where: { $0 === handler}) } photoOutput.capturePhoto(with: settings, delegate: handler) self.photoCaptureDelegateHandlers.append(handler) } public func capturePhoto(with settings: AVCapturePhotoSettings, delegate: AVCapturePhotoCaptureDelegate) { assert(self.photoOutput != nil) self.photoOutput?.capturePhoto(with: settings, delegate: delegate) } }
41.90566
128
0.675822
09f09a34f28ea8564a106ac92658b070d7a1d47a
1,352
// // ViewController.swift // EPSignature // // Created by Prabaharan on 01/13/2016. // Modified By C0mrade on 27/09/2016. // Copyright (c) 2016 Prabaharan. All rights reserved. // import UIKit import EPSignatureUpdated class ViewController: UIViewController, EPSignatureDelegate { @IBOutlet weak var imgWidthConstraint: NSLayoutConstraint! @IBOutlet weak var imgHeightConstraint: NSLayoutConstraint! @IBOutlet weak var imgViewSignature: UIImageView! @IBAction func onTouchSignatureButton(sender: AnyObject) { let signatureVC = EPSignatureViewController(signatureDelegate: self, showsDate: true, showsSaveSignatureOption: true) signatureVC.subtitleText = "I agree to the terms and conditions" signatureVC.title = "John Doe" let nav = UINavigationController(rootViewController: signatureVC) present(nav, animated: true, completion: nil) } func epSignature(_: EPSignatureViewController, didCancel error : NSError) { print("User canceled") } func epSignature(_: EPSignatureViewController, didSign signatureImage : UIImage, boundingRect: CGRect) { print(signatureImage) imgViewSignature.image = signatureImage imgWidthConstraint.constant = boundingRect.size.width imgHeightConstraint.constant = boundingRect.size.height } }
34.666667
125
0.735207
f8e71a857aec459255c9ba4b7de98290fc788f3f
1,023
// // AppDelegate.swift // MINIMAL // // Created by Ric Telford on 7/17/17. // Copyright © 2017 ece564. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // this is the MINIMAL amount of code required to make an app run self.window = UIWindow(frame: UIScreen.main.bounds) // let navController = UINavigationController(rootViewController: MainViewController()) if let appWindow = self.window { appWindow.backgroundColor = UIColor.gray // point to VC file, even though it won't do anything (NOTE: navController is meant to be subclassed, not used) appWindow.rootViewController = MainViewController() appWindow.makeKeyAndVisible() } return true } } // End of Code
31
145
0.678397
2226317b3a7badc79a11c53603b3252420d70ac7
1,761
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import RealmSwift class SchemaTests: TestCase { var schema: Schema! override func setUp() { super.setUp() autoreleasepool { self.schema = try! Realm().schema } } func testObjectSchema() { let objectSchema = schema.objectSchema XCTAssertTrue(objectSchema.count > 0) } func testDescription() { XCTAssert(schema.description as Any is String) } func testSubscript() { XCTAssertEqual(schema["SwiftObject"]!.className, "SwiftObject") XCTAssertNil(schema["NoSuchClass"]) } func testEquals() { XCTAssertTrue(try! schema == Realm().schema) } func testNoSchemaForUnpersistedObjectClasses() { XCTAssertNil(schema["RLMObject"]) XCTAssertNil(schema["RLMObjectBase"]) XCTAssertNil(schema["RLMDynamicObject"]) XCTAssertNil(schema["Object"]) XCTAssertNil(schema["DynamicObject"]) XCTAssertNil(schema["MigrationObject"]) } }
29.847458
76
0.61272
dbdf28beda920992747095232ac708c0745d04c4
1,333
// // Number.swift // SwiftTools // // Created by Vladas Zakrevskis on 11/1/17. // Copyright © 2017 VladasZ. All rights reserved. // import Foundation extension String : Error { } public class Number { public var value: String public func getValue<T>() -> T { switch T.self { case is Bool.Type: return (value != "0") as! T case is String.Type: return value as! T case is Int.Type: return Int(value.withoutFractionPart) as! T case is Float.Type: return Float(value) as! T case is Double.Type: return Double(value) as! T default: return "Error" as! T } } public init?(_ value: Any?) { guard let value = value else { return nil } switch value { case is String: let string = value as! String if string == "true" || string == "false" { self.value = string == "true" ? "1" : "0" } else { guard Double(string) != nil else { return nil } self.value = string } case is Int: self.value = String(value as! Int) case is Float: self.value = String(value as! Float) case is Double: self.value = String(value as! Double) case is Bool: self.value = (value as! Bool) ? "1" : "0" default: return nil } } }
28.361702
77
0.55814
0817b44d5f8525fc5664d8bd39b9def95086bcc3
5,615
// // BaseWebView.swift // Action // // Created by pham.minh.tien on 5/8/20. // import Foundation import WebKit import RxSwift import RxCocoa open class BaseWebView: BasePage { private(set) public var wkWebView = WKWebView() open override func viewDidLoad() { super.viewDidLoad() wkWebView.clipsToBounds = true self.viewModel?.viewDidLoad = true } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let originY = UIApplication.shared.statusBarFrame.maxY wkWebView.frame = CGRect( x: 0, y: originY, width: self.view.bounds.width, height: self.view.bounds.height ) } open override func initialize() { setupWebView(wkWebView) } open override func bindViewAndViewModel() { super.bindViewAndViewModel() guard let viewModel = self.viewModel as? BaseWebViewModel else { return } // Subscribe Java script alert panel. wkWebView.rx.javaScriptAlertPanel.subscribe(onNext: { webView, message, frame, handler in viewModel.webView(webView, runJavaScriptAlertPanelWithMessage: message, initiatedByFrame: frame, completionHandler: handler) }) => disposeBag // Subcribe java script confirm panel. wkWebView.rx.javaScriptConfirmPanel.subscribe(onNext: { webView, message, frame, handler in viewModel.webView(webView, runJavaScriptConfirmPanelWithMessage: message, initiatedByFrame: frame, completionHandler: handler) }) => disposeBag // Subcribe java did receive challenge wkWebView.rx.didReceiveChallenge.subscribe(onNext: { webView, challenge, handler in guard challenge.previousFailureCount == 0 else { handler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil) return } viewModel.webView(webView, didReceive: challenge, completionHandler: handler) }) => disposeBag // Subcribe java did fail provisional navigation wkWebView.rx.didFailProvisionalNavigation.observe(on: MainScheduler.instance).subscribe(onNext: { webView, navigation, error in viewModel.webView(webView, didFailProvisionalNavigation: navigation, withError: error) }) => disposeBag // Subcribe java did receive policy navigation action wkWebView.rx.decidePolicyNavigationAction.observe(on: MainScheduler.instance).subscribe(onNext: { webview, navigation, handler in viewModel.webView(webview, decidePolicyFor: navigation, decisionHandler: handler) }) => disposeBag // Subcribe java did receive policy navigation response wkWebView.rx.decidePolicyNavigationResponse.observe(on: MainScheduler.instance).subscribe(onNext: { webview, response, handler in viewModel.webView(webview, decidePolicyFor: response, decisionHandler: handler) }) => disposeBag // Subcribe did finish navigation wkWebView.rx.didFinishNavigation.observe(on: MainScheduler.instance).subscribe(onNext: { webView, navigation in viewModel.webView(webView, didFinish: navigation) }) => disposeBag wkWebView.rx.estimatedProgress.share(replay: 1).subscribe(onNext: { [weak self] value in guard let self = self else { return } viewModel.webView(self.wkWebView, estimatedProgress: value) }) => disposeBag wkWebView.rx.loading.share(replay: 1).subscribe(onNext: { isLoading in viewModel.rxIsLoading.accept(isLoading) }) => disposeBag wkWebView.rx.canGoBack.share(replay: 1).subscribe(onNext: { canGoBack in viewModel.rxCanGoBack.accept(canGoBack) }) => disposeBag wkWebView.rx.canGoForward.share(replay: 1).subscribe(onNext: { canForward in viewModel.rxCanGoForward.accept(canForward) }) => disposeBag } // Call function in java script. /* E.g: In the page have a script function <script> function presentAlert() { do something } </script> Use: evaluateJavaScript("presentAlert()") */ public func evaluateJavaScript(_ function: String) { guard let viewModel = self.viewModel as? BaseWebViewModel else { return } wkWebView.rx.evaluateJavaScript(function).observeOn(MainScheduler.asyncInstance).subscribe {[weak self] event in guard let self = self else { return } if case .next(let ev) = event { viewModel.webView(self.wkWebView, evaluateJavaScript: (ev, nil)) } else if case .error(let error) = event { viewModel.webView(self.wkWebView, evaluateJavaScript: (nil, error)) } } => disposeBag } func setupWebView(_ webView: WKWebView) { self.view.addSubview(webView) } open override func destroy() { super.destroy() } }
37.939189
137
0.590383
2f6f7615753ac56bac90c8b7d5e12df2f47a9de7
161
// // PRNG.swift // Roguelike_iOS // // Created by Maarten Engels on 01/01/2021. // Copyright © 2021 thedreamweb. All rights reserved. // import Foundation
16.1
54
0.689441
72747326cfc0f024458dc4c7a153260620e5d6cf
1,190
// // ARChatModel.swift // AR-Voice-Tutorial-iOS // // Created by 余生丶 on 2020/9/7. // Copyright © 2020 AR. All rights reserved. // import UIKit class ARChatModel: NSObject { //频道id var channelId: String? //房主id var channelUid: String? //密码房 var isLock: String? //上麦模式 var isMicLock: Bool? //房间公告 var announcement: String? //主持人、游客 var isHoster: Bool? //房间名称 var roomName: String? //欢迎语 var welcome: String? //麦位 var seatDic: NSMutableDictionary! = NSMutableDictionary() var seat0: String? var seat1: String? var seat2: String? var seat3: String? var seat4: String? var seat5: String? var seat6: String? var seat7: String? var seat8: String? //禁麦 var muteMicList: NSArray! //禁言 var muteInputList: NSArray! //音效开关 var sound: Bool = false //0 ~ 8 var currentMic: NSInteger = 9 //录音开关 var record: Bool = false //音乐播放开关 var musicDic: NSMutableDictionary! = NSMutableDictionary() //非自由模式麦序 var waitList: NSMutableArray = NSMutableArray() //非自由模式麦序model var waitModelList: NSMutableArray = NSMutableArray() }
20.517241
62
0.620168
c131e534dcf644214aaf8b1af362da220036704d
1,791
// // PaymentezConstants.swift // PaymentezSDK // // Created by Gustavo Sotelo on 07/09/18. // Copyright © 2018 Paymentez. All rights reserved. // import Foundation import UIKit class PaymentezStyle { static let baseBaseColor = UIColor(red:0.30, green:0.69, blue:0.31, alpha:1.0) static let baseFontColor: UIColor = .white static let font = UIFont.systemFont(ofSize: 16) static let fontSmall = UIFont.systemFont(ofSize: 14) static let fontExtraSmall = UIFont.systemFont(ofSize: 12) } // Based on http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29 let BRANDS = [ PaymentezBrand(type: .visa, regex: "^4[0-9]{6,}$", prefixes: ["4"], maxLength: 16, imagePath: "stp_card_visa"), PaymentezBrand(type: .amex, regex: "^3[47][0-9]{5,}$", prefixes: ["34", "37"], maxLength: 15, imagePath: "stp_card_amex"), PaymentezBrand(type: .masterCard, regex: "^5[1-5][0-9]{5,}$", prefixes: ["2221", "2222", "2223", "2224", "2225", "2226", "2227", "2228", "2229", "223", "224", "225", "226", "227", "228", "229", "23", "24", "25", "26", "270", "271", "2720", "50", "51", "52", "53", "54", "55"], maxLength: 16, imagePath: "stp_card_mastercard"), PaymentezBrand(type: .diners, regex: "^3(?:0[0-5]|[68][0-9])[0-9]{11}$", prefixes: ["300", "301", "302", "303", "304", "305", "309", "36", "38", "39"], maxLength: 14, imagePath: "stp_card_diners"), PaymentezBrand(type: .discover, regex: "^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$", prefixes: ["60", "62", "64", "65"], maxLength: 16, imagePath: "stp_card_discover"), PaymentezBrand(type: .jcb, regex: "^(?:2131|1800|35[0-9]{3})[0-9]{11}$", prefixes: ["35"], maxLength: 16, imagePath: "stp_card_jcb") ]
61.758621
330
0.623116
db357dfa7b886635a20c0f119b7710749728d818
2,739
// // UIBezierPath+DisplayKit.swift // YHAsynDisplayKit // // Created by 吴云海 on 2020/4/13. // Copyright © 2020 YH. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Foundation extension UIBezierPath { /** * 该方法用来根据指定的矩形区域获取一个带圆角边框的路径 * 一般情况下仅限于框架内部使用 * * @param rect 矩形区域 * @param radius 定义圆角的结构体,可以指定任意一个角的弧度 * @param lineWidth 路径线条宽度 * * @return 贝塞尔路径 */ class func bezierPathCreateWithRect(_ rect:CGRect, cornerRadius radius:YHAsyncCornerRadius, lineWidth width:CGFloat) -> UIBezierPath { if YHAsyncCornerRadiusIsPerfect(radius) { return UIBezierPath.init(roundedRect: rect, byRoundingCorners: UIRectCorner.allCorners, cornerRadii: CGSize.init(width: radius.topLeft, height: radius.topLeft)) } let lineCenter:CGFloat = 0 //width / 2.0 var path:UIBezierPath = UIBezierPath.init() path.move(to: CGPoint(x: radius.topLeft, y: lineCenter)) path.addArc(withCenter: CGPoint(x: radius.topLeft, y: radius.topLeft), radius: radius.topLeft - lineCenter, startAngle: CGFloat.pi * 1.5, endAngle: CGFloat.pi, clockwise: false) path.addLine(to: CGPoint.init(x: lineCenter, y: rect.height - radius.bottomLeft)) path.addArc(withCenter: CGPoint.init(x: radius.bottomLeft, y: rect.height - radius.bottomLeft), radius: radius.bottomLeft - lineCenter, startAngle: CGFloat.pi, endAngle: CGFloat.pi * 0.5, clockwise: false) path.addLine(to: CGPoint.init(x: rect.width - radius.bottomRight, y: rect.height - lineCenter)) path.addArc(withCenter: CGPoint(x: rect.width - radius.bottomRight, y: rect.height - radius.bottomRight), radius: radius.bottomRight - lineCenter, startAngle: CGFloat.pi * 0.5, endAngle: 0.0, clockwise: false) path.addLine(to: CGPoint.init(x: rect.width - lineCenter, y: radius.topRight)) path.addArc(withCenter: CGPoint.init(x: rect.width - radius.topRight, y: radius.topRight), radius: radius.topRight - lineCenter, startAngle: 0.0, endAngle: CGFloat.pi * 1.5, clockwise: false) path.close() return path } }
43.47619
217
0.684922
118d61fe72c1ee7ab5d69448e937c51ab11f2929
1,052
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // LoadBalancerLoadBalancingRules is the network Client import Foundation import azureSwiftRuntime extension Commands { public struct LoadBalancerLoadBalancingRules { public static func Get(resourceGroupName: String, loadBalancerName: String, loadBalancingRuleName: String, subscriptionId: String) -> LoadBalancerLoadBalancingRulesGet { return GetCommand(resourceGroupName: resourceGroupName, loadBalancerName: loadBalancerName, loadBalancingRuleName: loadBalancingRuleName, subscriptionId: subscriptionId) } public static func List(resourceGroupName: String, loadBalancerName: String, subscriptionId: String) -> LoadBalancerLoadBalancingRulesList { return ListCommand(resourceGroupName: resourceGroupName, loadBalancerName: loadBalancerName, subscriptionId: subscriptionId) } } }
55.368421
178
0.79943
096f4cf57c1b76216ddc44d2e8cc3354b4f557b9
995
// // CYButtonExtension.swift // tdd // // Created by 春雨 on 2017/11/20. // Copyright © 2017年 ttlc. All rights reserved. // import UIKit extension UIButton { /// 为UIButton添加block事件,默认事件为:UIControlEventTouchUpInside /// /// - Parameters: /// - block: 闭包 /// - controlEvents: 事件类型 func addAction(_ block: @escaping ()->Void, for controlEvents: UIControlEvents = UIControlEvents.touchUpInside) -> Void { let key: UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "uibutton_cybutton_block".hashValue) objc_setAssociatedObject(self, key, block, .OBJC_ASSOCIATION_COPY_NONATOMIC) self.addTarget(self, action: #selector(cy_action), for: controlEvents) } @objc func cy_action() -> Void { let key: UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "uibutton_cybutton_block".hashValue) guard let block = objc_getAssociatedObject(self, key) as? ()->Void else { return } block() } }
31.09375
125
0.667337
2215d01c411814aecc9897b14d6e3d6eb0eaff79
2,049
// // FeedViewControllerTests+LoaderSpy.swift // EssentialFeediOSTests // // Created by Will Saults on 3/7/22. // import Foundation import EssentialFeed import EssentialFeediOS extension FeedUIIntegrationTests { class LoaderSpy: FeedLoader, FeedImageDataLoader { // MARK: - FeedLoader private var feedRequests = [(FeedLoader.Result) -> Void]() var loadFeedCallCount: Int { feedRequests.count } func load(completion: @escaping (FeedLoader.Result) -> Void) { feedRequests.append(completion) } func completeFeedLoading(with feed: [FeedImage] = [], at index: Int = 0) { feedRequests[index](.success(feed)) } func completeFeedLoadingWithError(at index: Int = 0) { let error = NSError(domain: "an error", code: 0) feedRequests[index](.failure(error)) } // MARK: - FeedImageDataLoader private struct TaskSpy: FeedImageDataLoaderTask { let cancelCallback: () -> Void func cancel() { cancelCallback() } } private var imageRequests = [(url: URL, completion: (FeedImageDataLoader.Result) -> Void)]() var loadedImageURLs: [URL] { imageRequests.map { $0.url } } private(set) var cancelledImageURLs = [URL]() func loadImageData(from url: URL, completion: @escaping (FeedImageDataLoader.Result) -> Void) -> FeedImageDataLoaderTask { imageRequests.append((url, completion)) return TaskSpy { [weak self] in self?.cancelledImageURLs.append(url) } } func completeImageLoading(with imageData: Data = Data(), at index: Int = 0) { imageRequests[index].completion(.success(imageData)) } func completeImageLoadingWithError(at index: Int = 0) { let error = NSError(domain: "an error", code: 0) imageRequests[index].completion(.failure(error)) } } }
28.458333
130
0.596388
0ea15016d531b2ababe34652536510aa09822c4f
5,989
// // settings.swift // Net // // Created by Serhiy Mytrovtsiy on 06/07/2020. // Using Swift 5.0. // Running on macOS 10.15. // // Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved. // import Cocoa import StatsKit import ModuleKit import SystemConfiguration internal class Settings: NSView, Settings_v { private var numberOfProcesses: Int = 8 private var readerType: String = "interface" public var callback: (() -> Void) = {} public var callbackWhenUpdateNumberOfProcesses: (() -> Void) = {} private let title: String private var button: NSPopUpButton? private var list: [Network_interface] = [] public init(_ title: String) { self.title = title self.numberOfProcesses = Store.shared.int(key: "\(self.title)_processes", defaultValue: self.numberOfProcesses) self.readerType = Store.shared.string(key: "\(self.title)_reader", defaultValue: self.readerType) super.init(frame: CGRect( x: 0, y: 0, width: Constants.Settings.width - (Constants.Settings.margin*2), height: 0 )) for interface in SCNetworkInterfaceCopyAll() as NSArray { if let bsdName = SCNetworkInterfaceGetBSDName(interface as! SCNetworkInterface), let displayName = SCNetworkInterfaceGetLocalizedDisplayName(interface as! SCNetworkInterface) { self.list.append(Network_interface(displayName: displayName as String, BSDName: bsdName as String)) } } self.canDrawConcurrently = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func load(widgets: [widget_t]) { self.subviews.forEach{ $0.removeFromSuperview() } let rowHeight: CGFloat = 30 let num: CGFloat = 2 self.addSubview(SelectTitleRow( frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 2, width: self.frame.width - (Constants.Settings.margin*2), height: 30), title: LocalizedString("Number of top processes"), action: #selector(changeNumberOfProcesses), items: NumbersOfProcesses.map{ "\($0)" }, selected: "\(self.numberOfProcesses)" )) self.addSubview(SelectRow( frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 1, width: self.frame.width - (Constants.Settings.margin*2), height: 30), title: LocalizedString("Reader type"), action: #selector(changeReaderType), items: NetworkReaders, selected: self.readerType )) self.addInterfaceSelector() self.setFrameSize(NSSize(width: self.frame.width, height: (rowHeight*(num+1)) + (Constants.Settings.margin*(2+num)))) } private func addInterfaceSelector() { let view: NSView = NSView(frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin, width: self.frame.width, height: 30)) let rowTitle: NSTextField = LabelField(frame: NSRect(x: 0, y: (view.frame.height - 16)/2, width: view.frame.width - 52, height: 17), LocalizedString("Network interface")) rowTitle.font = NSFont.systemFont(ofSize: 13, weight: .light) rowTitle.textColor = .textColor self.button = NSPopUpButton(frame: NSRect(x: view.frame.width - 200 - Constants.Settings.margin*2, y: 0, width: 200, height: 30)) self.button?.target = self self.button?.action = #selector(self.handleSelection) self.button?.isEnabled = self.readerType == "interface" let selectedInterface = Store.shared.string(key: "\(self.title)_interface", defaultValue: "") let menu = NSMenu() let autodetection = NSMenuItem(title: "Autodetection", action: nil, keyEquivalent: "") menu.addItem(autodetection) menu.addItem(NSMenuItem.separator()) self.list.forEach { (interface: Network_interface) in let interfaceMenu = NSMenuItem(title: "\(interface.displayName) (\(interface.BSDName))", action: nil, keyEquivalent: "") interfaceMenu.identifier = NSUserInterfaceItemIdentifier(rawValue: interface.BSDName) menu.addItem(interfaceMenu) if selectedInterface != "" && selectedInterface == interface.BSDName { interfaceMenu.state = .on } } self.button?.menu = menu if selectedInterface == "" { self.button?.selectItem(withTitle: "Autodetection") } view.addSubview(rowTitle) view.addSubview(self.button!) self.addSubview(view) } @objc func handleSelection(_ sender: NSPopUpButton) { guard let item = sender.selectedItem else { return } if item.title == "Autodetection" { Store.shared.remove("\(self.title)_interface") } else { if let bsdName = item.identifier?.rawValue { Store.shared.set(key: "\(self.title)_interface", value: bsdName) } } self.callback() } @objc private func changeNumberOfProcesses(_ sender: NSMenuItem) { if let value = Int(sender.title) { self.numberOfProcesses = value Store.shared.set(key: "\(self.title)_processes", value: value) self.callbackWhenUpdateNumberOfProcesses() } } @objc private func changeReaderType(_ sender: NSMenuItem) { guard let key = sender.representedObject as? String else { return } self.readerType = key Store.shared.set(key: "\(self.title)_reader", value: key) self.button?.isEnabled = self.readerType == "interface" } }
39.401316
201
0.6183
011b4601bf9b0c94d24294271bdb92e1059e48ec
1,657
import XCTest @testable import SwiftyHolidays final class CountryTests: XCTestCase { func testAllCountries() { for country in Country.allCases { _ = country.allHolidays(in: 2020) } } func testAllCountriesWithStates() { for countryWithState in CountryWithState.allCases { _ = countryWithState.allHolidays(in: 2020) } } func testInitWithIsoCode() { XCTAssertNil(Country(isoCode: "xxx")) XCTAssertNotNil(Country(isoCode: "de")) XCTAssertNotNil(Country(isoCode: "DE")) XCTAssertNotNil(Country(isoCode: "DEU")) } func testIso2Code() { for country in Country.allCases { XCTAssert(country.iso2Code.count == 2) } } func testIso3Code() { for country in Country.allCases { XCTAssert(country.iso3Code.count == 3) } } func testDisplayString() { let english = Locale(identifier: "en_US") XCTAssertEqual(Country.germany.displayString(locale: english), "Germany") let german = Locale(identifier: "de_DE") XCTAssertEqual(Country.unitedStates.displayString(locale: german), "Vereinigte Staaten") for country in Country.allCases { for locale in Locale.availableIdentifiers.map({ Locale(identifier: $0) }) { XCTAssert(!country.displayString(locale: locale).isEmpty) } } } static var allTests = [ ("testAllCountries", testAllCountries), ("testAllCountriesWithStates", testAllCountriesWithStates), ("testInitWithIsoCode", testInitWithIsoCode) ] }
30.685185
96
0.624019
d93f925b497bcd05b4ddbe90d75961acd1e7ce49
295
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import a} let v {enum k{ struct Q<T : T{ } let a { let i {let c{< class B<T : A {let c{< enum k{ protocol b:a{ func a<H : a {
19.666667
87
0.684746
1e7393d3f1e82164d74d938c720331bdc6629b6f
3,435
// // ViewController.swift // UizaSDKGoogleAdsExample // // Created by phan.huynh.thien.an on 6/12/19. // Copyright © 2019 uiza. All rights reserved. // import UIKit import UizaSDK import FrameLayoutKit class ViewController: UIViewController { let loadButton = UIButton() var frameLayout : StackFrameLayout! override func viewDidLoad() { super.viewDidLoad() loadButton.addTarget(self, action: #selector(loadVideo), for: .touchUpInside) loadButton.setTitle("Load Video", for: .normal) loadButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium) loadButton.setTitleColor(.white, for: .normal) loadButton.showsTouchWhenHighlighted = true loadButton.backgroundColor = .black self.view.addSubview(loadButton) frameLayout = StackFrameLayout(direction: .vertical, alignment: .center, views: []) frameLayout.append(view: loadButton).configurationBlock = { layout in layout.contentAlignment = (.center, .center) layout.minSize = CGSize(width: 0, height: 40) } self.view.addSubview(frameLayout) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() frameLayout.frame = self.view.bounds } override public var shouldAutorotate: Bool { return true } @objc func loadVideo() { loadButton.isEnabled = false UZContentServices().loadEntity(metadataId: nil, publishStatus: .success, page: 0, limit: 20) { [weak self] (results, error) in self?.loadButton.isEnabled = true if let videos = results, let video = videos.randomElement() { DispatchQueue.main.async { let viewController = FloatingPlayerViewController() viewController.delegate = self viewController.present(with: video).player.controlView.theme = UZTheme1() viewController.floatingHandler?.allowsCornerDocking = true } } } } } extension ViewController: UZPlayerDelegate { func UZPlayer(player: UZPlayer, playerStateDidChange state: UZPlayerState) { // called when player state was changed (buffering, buffered, readyToPlay ...) } func UZPlayer(player: UZPlayer, loadedTimeDidChange loadedDuration: TimeInterval, totalDuration: TimeInterval) { // called when loaded duration was changed } func UZPlayer(player: UZPlayer, playTimeDidChange currentTime: TimeInterval, totalTime: TimeInterval) { // called when player time was changed } func UZPlayer(player: UZPlayer, playerIsPlaying playing: Bool) { // called when playing state was changed } } extension ViewController: UZFloatingPlayerViewProtocol { func floatingPlayer(_ player: UZFloatingPlayerViewController, didBecomeFloating: Bool) { // called when floating player became floating mode or backed to normal mode } func floatingPlayer(_ player: UZFloatingPlayerViewController, onFloatingProgress: CGFloat) { // called when user drag the player from normal mode to floating mode } func floatingPlayerDidDismiss(_ player: UZFloatingPlayerViewController) { // called when player was dismissed } }
33.676471
134
0.653275
033a31b2c3d00fa48e1b9a4eb7e81a8d9ea5b3f7
1,894
// // NewsTableViewController.swift // NewsAppMVVM // // Created by Kas Song on 1/16/21. // import UIKit import RxSwift class NewsTableViewController: UITableViewController { // MARK: - Properties private let disposeBag = DisposeBag() private var articleListVM: ArticleListViewModel! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.prefersLargeTitles = true populateNews() } private func populateNews() { let url = URL(string: "")! let resource = Resource<ArticleResponse>(url: url) URLRequest.load(resource: resource) .subscribe(onNext: { articleResponse in let articles = articleResponse.articles self.articleListVM = ArticleListViewModel(articles) DispatchQueue.main.async { self.tableView.reloadData() } }).disposed(by: disposeBag) } } extension NewsTableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.articleListVM == nil ? 0 : self.articleListVM.articlesVM.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleTableViewCell", for: indexPath) as? ArticleTableViewCell else { fatalError() } let articleVM = self.articleListVM.articleAt(indexPath.row) articleVM.title.asDriver(onErrorJustReturn: "") .drive(cell.titleLabel.rx.text) .disposed(by: disposeBag) articleVM.description.asDriver(onErrorJustReturn: "") .drive(cell.descriptionLabel.rx.text) .disposed(by: disposeBag) return cell } }
34.436364
157
0.657339
9cd48061e5c3dcdf1fc97db53d5dd794b4fa1212
6,032
// // Message.swift // Server // // Created by BluDesign, LLC on 8/25/17. // import Foundation import MongoKitten struct Message { // MARK: - Parameters static let collectionName = "message" static var collection: MongoKitten.Collection { return MongoProvider.shared.database[collectionName] } } struct TwilioMessage: Codable { // MARK: - Parameters let sid: String let accountSid: String let messagingServiceId: String? let status: String? let from: String? let to: String? let price: String? let priceUnit: String? let mediaCount: String? let segmentCount: String? let apiVersion: String? private enum CodingKeys : String, CodingKey { case sid case accountSid = "account_sid" case messagingServiceId = "messaging_service_sid" case status case from case to case price case priceUnit = "price_unit" case mediaCount = "num_media" case segmentCount = "num_segments" case apiVersion = "api_version" } } struct MediaCodingKey: CodingKey { var stringValue: String init?(stringValue: String) { self.stringValue = stringValue } var intValue: Int? init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } } struct TwilioIncommingMessage: Decodable { // MARK: - Parameters let sid: String let accountSid: String let from: String? let to: String? let body: String? let messagingServiceId: String? let mediaCount: Int? let segmentCount: Int? let status: String? let apiVersion: String? let fromCity: String? let fromState: String? let fromZip: String? let fromCountry: String? let toCity: String? let toState: String? let toZip: String? let toCountry: String? let errorCode: String? let errorMessage: String? let mediaItems: [Media]? struct Media { let url: String let contentType: String } private enum CodingKeys : String, CodingKey { case sid = "MessageSid" case accountSid = "AccountSid" case from = "From" case to = "To" case body = "Body" case messagingServiceId = "MessagingServiceSid" case mediaCount = "NumMedia" case segmentCount = "NumSegments" case status = "MessageStatus" case apiVersion = "ApiVersion" case fromCity = "FromCity" case fromState = "FromState" case fromZip = "FromZip" case fromCountry = "FromCountry" case toCity = "ToCity" case toState = "ToState" case toZip = "ToZip" case toCountry = "ToCountry" case errorCode = "ErrorCode" case errorMessage = "ErrorMessage" case mediaUrl } private struct CustomCodingKeys: CodingKey { var intValue: Int? var stringValue: String init?(stringValue: String) { self.stringValue = stringValue } init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } static func makeKey(name: String) -> CustomCodingKeys? { return CustomCodingKeys(stringValue: name) } } // MARK: - Life Cycle init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) sid = try container.decode(String.self, forKey: .sid) accountSid = try container.decode(String.self, forKey: .accountSid) from = try? container.decode(String.self, forKey: .from) to = try? container.decode(String.self, forKey: .to) body = try? container.decode(String.self, forKey: .body) messagingServiceId = try? container.decode(String.self, forKey: .messagingServiceId) mediaCount = (try? container.decode(String.self, forKey: .mediaCount))?.intValue segmentCount = (try? container.decode(String.self, forKey: .segmentCount))?.intValue status = try? container.decode(String.self, forKey: .status) apiVersion = try? container.decode(String.self, forKey: .apiVersion) fromCity = try? container.decode(String.self, forKey: .fromCity) fromState = try? container.decode(String.self, forKey: .fromState) fromZip = try? container.decode(String.self, forKey: .fromZip) fromCountry = try? container.decode(String.self, forKey: .fromCountry) toCity = try? container.decode(String.self, forKey: .toCity) toState = try? container.decode(String.self, forKey: .toState) toZip = try? container.decode(String.self, forKey: .toZip) toCountry = try? container.decode(String.self, forKey: .toCountry) errorCode = try? container.decode(String.self, forKey: .errorCode) errorMessage = try? container.decode(String.self, forKey: .errorMessage) if let mediaCount = mediaCount, mediaCount > 0 { Logger.info("MEida; \(mediaCount)") var mediaItems: [Media] = [] let container = try decoder.container(keyedBy: CustomCodingKeys.self) for x in 0 ..< mediaCount { guard let urlKey = CustomCodingKeys.makeKey(name: "MediaUrl\(x)"), let contentTypeKey = CustomCodingKeys.makeKey(name: "MediaContentType\(x)") else { continue } guard let url = try? container.decode(String.self, forKey: urlKey), let contentType = try? container.decode(String.self, forKey: contentTypeKey) else { Logger.info("MMS Missing Media") continue } Logger.info("URL; \(url) Type: \(contentType)") mediaItems.append(Media(url: url, contentType: contentType)) } self.mediaItems = mediaItems } else { mediaItems = nil } } }
31.915344
177
0.612069
ab5b7b46115f2178e08c00e34b4d41ba74a638d9
248
// 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 S { { } func e { { } func a< > ( = [ { } ( ) { { } var d { class case ,
12.4
87
0.649194