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
|
---|---|---|---|---|---|
62211ed1fea30a47f22b246da8f2cce9ff56b3d5
| 1,284 |
//
// Book.swift
// BookRoom
//
// Created by romance on 2017/5/4.
// Copyright © 2017年 romance. All rights reserved.
//
import Foundation
struct Book {
var bid: Int!
var bookName: String!
var isRead: Bool!
var orientation: Int!
var pic: String!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: [String: Any]){
bid = dictionary["bid"] as? Int
bookName = dictionary["book_name"] as? String
isRead = dictionary["is_read"] as? Bool
orientation = dictionary["orientation"] as? Int
pic = dictionary["pic"] as? String
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
var dictionary = [String: Any]()
if bid != nil{
dictionary["bid"] = bid
}
if bookName != nil{
dictionary["book_name"] = bookName
}
if isRead != nil{
dictionary["is_read"] = isRead
}
if orientation != nil{
dictionary["orientation"] = orientation
}
if pic != nil{
dictionary["pic"] = pic
}
return dictionary
}
}
| 22.928571 | 181 | 0.630062 |
e8023499dac5072594531004ae36464d34199c4e
| 3,152 |
/* Copyright Airship and Contributors */
import Foundation
@testable
import AirshipChat
import AirshipCore
/* Copyright Airship and Contributors */
import Foundation
struct MockChatMessageData : ChatMessageDataProtocol {
var messageID: Int
var requestID: String?
var text: String?
var createdOn: Date
var direction: UInt
var attachment: URL?
}
struct MockPendingChatMessageData : PendingChatMessageDataProtocol {
var requestID: String
var text: String?
var attachment: URL?
var createdOn: Date
var direction: UInt
}
class MockChatDAO: ChatDAOProtocol {
private let dispatcher: UADispatcher
private var messages = Dictionary<String, ChatMessageDataProtocol>()
private var pendingMessages = Dictionary<String, PendingChatMessageDataProtocol>()
init(dispatcher: UADispatcher = MockDispatcher()) {
self.dispatcher = dispatcher
}
func upsertMessage(messageID: Int, requestID: String?, text: String?, createdOn: Date, direction: UInt, attachment: URL?) {
dispatcher.dispatchAsync {
self.messages["\(messageID)"] = MockChatMessageData(messageID: messageID,
requestID: requestID,
text: text,
createdOn: createdOn,
direction: direction,
attachment: attachment)
}
}
func upsertPending(requestID: String, text: String?, attachment: URL?, createdOn: Date, direction: UInt) {
dispatcher.dispatchAsync {
self.pendingMessages[requestID] = MockPendingChatMessageData(requestID: requestID, text: text, attachment: attachment, createdOn: createdOn, direction: direction)
}
}
func removePending(_ requestID: String) {
dispatcher.dispatchAsync {
self.pendingMessages.removeValue(forKey: requestID)
}
}
func fetchMessages(completionHandler: @escaping (Array<ChatMessageDataProtocol>, Array<PendingChatMessageDataProtocol>)->()) {
dispatcher.dispatchAsync {
let sortedMessages = self.messages.values.sorted { $0.createdOn <= $1.createdOn }
let sortedPending = self.pendingMessages.values.sorted { $0.createdOn <= $1.createdOn }
completionHandler(sortedMessages, sortedPending)
}
}
func fetchPending(completionHandler: @escaping (Array<PendingChatMessageDataProtocol>)->()) {
dispatcher.dispatchAsync {
let sortedPending = self.pendingMessages.values.sorted { $0.createdOn <= $1.createdOn }
completionHandler(sortedPending)
}
}
func hasPendingMessages(completionHandler: @escaping (Bool)->()) {
dispatcher.dispatchAsync {
completionHandler(!self.pendingMessages.isEmpty)
}
}
func deleteAll() {
dispatcher.dispatchAsync {
self.pendingMessages.removeAll()
self.messages.removeAll()
}
}
}
| 34.26087 | 174 | 0.624683 |
e5d8f8c0b0f5c0ecbb2d7fe2070c2ff523e3dbc9
| 4,611 |
//
// TodayView.swift
// AC Helper UI Playground
//
// Created by Matt Bonney on 5/6/20.
// Copyright © 2020 Matt Bonney. All rights reserved.
//
import SwiftUI
import SwiftUIKit
import Combine
import Backend
import UI
struct TodayView: View {
// MARK: - Vars
@EnvironmentObject private var uiState: UIState
@EnvironmentObject private var collection: UserCollection
@EnvironmentObject private var subManager: SubscriptionManager
@EnvironmentObject private var items: Items
@EnvironmentObject private var userDefaults: AppUserDefaults
@ObservedObject private var viewModel = DashboardViewModel()
@State private var selectedSheet: Sheet.SheetType?
@State private var showWhatsNew: Bool = false
// MARK: - Critters Calculations
private var fishAvailable: [Item] {
items.categories[.fish]?.filterActive() ?? []
}
private var bugsAvailable: [Item] {
items.categories[.bugs]?.filterActive() ?? []
}
// MARK: - Body
var body: some View {
NavigationView {
List {
if showWhatsNew {
TodayWhatsNewSection(showWhatsNew: $showWhatsNew)
}
if uiState.routeEnabled {
uiState.route.map { route in
NavigationLink(destination: route.makeDetailView(),
isActive: $uiState.routeEnabled) {
EmptyView()
}.hidden()
}
}
Group {
ForEach(viewModel.sectionOrder, id: \.self) { section in
// The required data could be refactored into the model.
TodaySectionView(section: section,
viewModel: self.viewModel,
selectedSheet: self.$selectedSheet)
}
self.arrangeSectionsButton
}
}
.listStyle(GroupedListStyle())
.environment(\.horizontalSizeClass, .regular)
.navigationBarTitle(Text("\(dateString.capitalized)"))
.navigationBarItems(leading: aboutButton, trailing: settingsButton)
.sheet(item: $selectedSheet, content: { Sheet(sheetType: $0) })
ActiveCrittersView(activeFishes: fishAvailable,
activeBugs: bugsAvailable)
}
}
var arrangeSectionsButton: some View {
Section {
Button(action: { self.selectedSheet = .rearrange(viewModel: self.viewModel) }) {
HStack {
Image(systemName: "arrow.up.arrow.down")
.font(.system(.body, design: .rounded))
Text("Change Section Order")
.font(.system(.body, design: .rounded))
.fontWeight(.semibold)
}
}
.frame(maxWidth: .infinity)
.accentColor(.acHeaderBackground)
}
}
// MARK: - Navigation Bar Button(s)
private var settingsButton: some View {
Button(action: { self.selectedSheet = .settings(subManager: self.subManager,
collection: self.collection) } ) {
Image(systemName: "slider.horizontal.3")
.style(appStyle: .barButton)
.foregroundColor(.acText)
}
.buttonStyle(BorderedBarButtonStyle())
.accentColor(Color.acText.opacity(0.2))
.safeHoverEffect()
}
private var aboutButton: some View {
Button(action: { self.selectedSheet = .about } ) {
Image(systemName: "info.circle")
.style(appStyle: .barButton)
.foregroundColor(.acText)
}
.buttonStyle(BorderedBarButtonStyle())
.accentColor(Color.acText.opacity(0.2))
.safeHoverEffect()
}
// MARK: - Others
private var dateString: String {
let f = DateFormatter()
f.setLocalizedDateFormatFromTemplate("EEEE, MMM d")
return f.string(from: Date())
}
}
struct TodayView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
TodayView()
}
.environmentObject(Items.shared)
.environmentObject(UIState())
.environmentObject(UserCollection.shared)
.environmentObject(SubscriptionManager.shared)
}
}
| 33.904412 | 92 | 0.545869 |
75b3fe8c8555171edd5e839717a1510b1ef30a7d
| 1,654 |
//
// FunnyViewController.swift
// DouYuZhiBo_new
//
// Created by LEPU on 2020/7/24.
// Copyright © 2020 LEPU. All rights reserved.
/*
趣玩
*/
import UIKit
private let topMarginH :CGFloat = 15
class FunnyViewController: BaseAnchorViewController {
//MARK: - 懒加载
private lazy var recommentVM:FunnyViewModel = FunnyViewModel()
//对返回数据的加工
lazy var anchorGroupsNew : [AnchorGroup] = [AnchorGroup]()
//MARK: - 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
//MARK: - 设置UI界面
extension FunnyViewController {
override func setupUI(){
super.setupUI()
let layer = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layer.headerReferenceSize = CGSize.zero
collectionView.contentInset = UIEdgeInsets(top: topMarginH, left: 0, bottom: 0, right: 0)
}
}
//MARK: - 请求数据
extension FunnyViewController {
func loadData() {
//请求推荐数据
baseVM = recommentVM
recommentVM.funnyReloadData {[unowned self] in
//这里的数据源不对,需要整合成一组;
let model : AnchorGroup = AnchorGroup()
for AnchorModel in self.recommentVM.anchorGroups {
let dataArray:[RoomAnchorModel]? = AnchorModel.anchors
guard dataArray != nil else{
return
}
for diction in dataArray! {
model.anchors.append(diction)
}
}
self.anchorGroupsNew.append(model)
self.collectionView.reloadData()
self.removeImgV()
}
}
}
| 25.060606 | 97 | 0.59734 |
4be57133701e93f190574920fd77c6ee05726c1c
| 785 |
//
// SwitchCell.swift
// EvaluateDay
//
// Created by Konstantin Tsistjakov on 12/01/2019.
// Copyright © 2019 Konstantin Tsistjakov. All rights reserved.
//
import UIKit
class SwitchCell: UITableViewCell {
// MARK: - UI
@IBOutlet weak var iconImage: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var switchControl: UISwitch!
// MARK: - Override
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// MARK: - Actions
@IBAction func switchAction(_ sender: UISwitch) {
}
}
| 21.805556 | 65 | 0.648408 |
792d3d77bbd2294eeaecafd5685a7b3ec9975cbc
| 4,381 |
//
// twoController.swift
// CNanNavigationBar_Example
//
// Created by cn on 2020/6/4.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import UIKit
class twoCell: UITableViewCell {
@objc func btnClick(sender: UIButton) {
print(sender)
}
lazy var btn: UIButton = {
let btn = UIButton.init(type: UIButton.ButtonType.custom)
btn.setTitle("可测试导航穿透", for: UIControl.State.normal)
btn.setTitleColor(UIColor.black, for: UIControl.State.normal)
btn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
btn.sizeToFit()
return btn
}()
override func layoutSubviews() {
btn.centerY = contentView.centerY
btn.centerX = contentView.centerX
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = UITableViewCell.SelectionStyle.none
backgroundColor = UIColor.lightGray
contentView.addSubview(btn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class twoController: UIViewController, UITableViewDelegate, UITableViewDataSource {
override var shouldPopOnBackButtonPress: Bool {
return true
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// navigationController?.navigationBar.cn_scrollViewWillBeginDragging(scrollView: scrollView)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// navigationController?.navigationBar.cn_scrollViewDidScroll(scrollView: scrollView)
let offestY = scrollView.contentOffset.y/300;
cn_navBarAlpha = offestY;
if offestY>0.5 {
cn_titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white, NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 24)]
cn_tintColor = UIColor.white
cn_statusBarStyle = .lightContent;
} else {
cn_titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black, NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 18)]
cn_tintColor = UIColor.black
cn_statusBarStyle = .default;
}
// navigationItem.rightBarButtonItem?.setTitleTextAttributes(cn_titleTextAttributes, for: UIControl.State.normal)
}
/// MARK: ----- UITableViewDelegate,UITableViewDataSource -----
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: twoCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(twoCell.self), for: indexPath) as! twoCell
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
lazy var tableView: UITableView = {
let tableView = UITableView.init(frame: view.bounds, style: UITableView.Style.plain)
tableView.register(twoCell.self, forCellReuseIdentifier: NSStringFromClass(twoCell.self))
tableView.backgroundColor = UIColor.lightGray
tableView.separatorStyle = .none
tableView.separatorColor = UIColor.red
tableView.separatorInset = UIEdgeInsets.zero
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "一"
cn_navBarAlpha = 0.0
cn_shadowHidden = true
cn_navBarStyle = .black
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "测试", style: UIBarButtonItem.Style.plain, target: nil, action: nil)
self.view.addSubview(tableView)
automaticallyAdjustsScrollViewInset(scrollView: tableView)
// automaticallyAdjustsScrollViewInset(scrollView: tableView)
print(NSLocalizedString("Bundle name", comment: ""))
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return cn_statusBarStyle
}
deinit {
print("\(self)-->deinit")
}
}
| 39.827273 | 154 | 0.688656 |
2055091616426449aa690231a6c4309ce5e02536
| 1,425 |
//
// PreWorkUITests.swift
// PreWorkUITests
//
// Created by Ronte' Parker on 1/27/22.
//
import XCTest
class PreWorkUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.139535 | 182 | 0.654737 |
c1dbe132585c8fc49c97835eb3aef0eb26ebc4ef
| 2,601 |
//
// Session.swift
// Ebates
//
// Created by Macbook on 10/9/18.
// Copyright © 2018 personal. All rights reserved.
//
import Foundation
public class TKLocalizeSession: NSObject {
public static let shared = TKLocalizeSession()
override init() {
super.init()
self.loadDefault()
}
public var isFirstTime: Bool = false {
didSet {
let userDef = UserDefaults.standard
userDef.setValue(isFirstTime, forKey: CONSTANT.keyIsFirstTime)
}
}
// for checking first select language
public var isSelectedLanguage: Bool = false {
didSet {
let userDef = UserDefaults.standard
userDef.setValue(isSelectedLanguage, forKey: CONSTANT.keyIsSelectedLanguage)
}
}
// current language code
private var languageCode: String = CONSTANT.keySystemLanguage {
didSet {
let userDef = UserDefaults.standard
userDef.setValue(languageCode, forKey: CONSTANT.keyLanguageCode)
}
}
// current language Name
private var languageName: String = "" {
didSet {
let userDef = UserDefaults.standard
userDef.setValue(languageName, forKey: CONSTANT.keyLanguageName)
}
}
// system language
public var systemLanguage: String = "en"
// language pack version
public var languagePackVersion: Double = 0 {
didSet {
let userDef = UserDefaults.standard
userDef.set(languagePackVersion, forKey: CONSTANT.keyLanguagePackVersion)
}
}
public func getLanguageCode() -> String {
return self.languageCode
}
public func getLanguageName() -> String {
return self.languageName
}
public func setLanguage(languageCode: String) {
self.languageCode = languageCode
}
public func setLanguageName(languageName: String) {
self.languageName = languageName
}
public func loadDefault() {
let userDef = UserDefaults.standard
self.languageCode = (userDef.object(forKey: CONSTANT.keyLanguageCode) ?? "vi") as! String
self.isFirstTime = (userDef.object(forKey: CONSTANT.keyIsFirstTime) ?? false) as! Bool
self.isSelectedLanguage = (userDef.object(forKey: CONSTANT.keyIsSelectedLanguage) ?? false) as! Bool
self.languageName = (userDef.object(forKey: CONSTANT.keyLanguageName) ?? "") as! String
self.languagePackVersion = (userDef.object(forKey: CONSTANT.keyLanguagePackVersion) ?? Double(0)) as! Double
}
}
| 30.244186 | 116 | 0.638601 |
fe522d8850ccfb9fba05be25c6c902176a8b732c
| 1,770 |
//
// AppDelegate.swift
// Shroud
//
// Created by Lynk on 9/1/20.
// Copyright © 2020 Lynk. All rights reserved.
//
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
let apperance = UINavigationBar.appearance()
apperance.tintColor = .white
apperance.barTintColor = ShroudColors.darkGray
apperance.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
apperance.isTranslucent = false
apperance.barStyle = .black
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.
}
}
| 37.659574 | 179 | 0.735028 |
d55095468002188c12a4f3caadbd299b259feb57
| 9,463 |
// OverlayView.swift
//
// Copyright (c) 2015 Frédéric Maquin <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
// Overlay a blocking view on top of the screen and handle the cutout path
// around the point of interest.
internal class OverlayView: UIView {
//MARK: - Internal properties
/// The background color of the overlay
var overlayColor: UIColor = kOverlayColor
/// The blur effect style to apply to the overlay.
/// Setting this property to anything but `nil` will
/// enable the effect. `overlayColor` will be ignored if this
/// property is set.
var blurEffectStyle: UIBlurEffectStyle? {
didSet {
if self.blurEffectStyle != oldValue {
self.destroyBlurView()
self.createBlurView()
}
}
}
/// `true` to let the overlay catch tap event and forward them to the
/// CoachMarkController, `false` otherwise.
/// After receiving a tap event, the controller will show the next coach mark.
var allowOverlayTap: Bool {
get {
return self.singleTapGestureRecognizer.view != nil
}
set {
if newValue == true {
self.addGestureRecognizer(self.singleTapGestureRecognizer)
} else {
self.removeGestureRecognizer(self.singleTapGestureRecognizer)
}
}
}
/// Used to temporarily disable the tap, for a given coachmark.
var disableOverlayTap: Bool = false
/// Delegate to which tell that the overlay view received a tap event.
weak var delegate: OverlayViewDelegate?
//MARK: - Private properties
/// The original cutout path
fileprivate var cutoutPath : UIBezierPath?
/// The cutout mask
fileprivate var cutoutMaskLayer = CAShapeLayer()
/// The full mask (together with `cutoutMaskLayer` they will form the cutout shape)
fileprivate var fullMaskLayer = CAShapeLayer()
/// The overlay layer, which will handle the background color
fileprivate var overlayLayer = CALayer()
/// The view holding the blur effect
fileprivate var blurEffectView: UIVisualEffectView?
/// TapGestureRecognizer that will catch tap event performed on the overlay
fileprivate lazy var singleTapGestureRecognizer: UITapGestureRecognizer = {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(OverlayView.handleSingleTap(_:)))
return gestureRecognizer
}()
//MARK: - Initialization
init() {
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
//MARK: - Internal methods
/// Prepare for the fade, by removing the cutout shape.
func prepareForFade() {
self.updateCutoutPath(nil)
}
/// Show a cutout path with fade in animation
///
/// - Parameter duration: duration of the animation
func showCutoutPathViewWithAnimationDuration(_ duration: TimeInterval) {
CATransaction.begin()
self.fullMaskLayer.opacity = 0.0
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = 1.0
animation.toValue = 0.0
animation.duration = duration
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.isRemovedOnCompletion = true
self.fullMaskLayer.add(animation, forKey: "opacityAnimationFadeIn")
CATransaction.commit()
}
/// Hide a cutout path with fade in animation
///
/// - Parameter duration: duration of the animation
func hideCutoutPathViewWithAnimationDuration(_ duration: TimeInterval) {
CATransaction.begin()
self.fullMaskLayer.opacity = 1.0
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = 0.0
animation.toValue = 1.0
animation.duration = duration
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.isRemovedOnCompletion = true
self.fullMaskLayer.add(animation, forKey: "opacityAnimationFadeOut")
CATransaction.commit()
}
/// Update the cutout path. Please note that the update won't perform any
/// interpolation. The previous cutout path better be hidden or else,
/// some jaggy effects are to be expected.
///
/// - Parameter cutoutPath: the cutout path
func updateCutoutPath(_ cutoutPath: UIBezierPath?) {
self.cutoutMaskLayer.removeFromSuperlayer()
self.fullMaskLayer.removeFromSuperlayer()
self.overlayLayer.removeFromSuperlayer()
self.cutoutPath = cutoutPath
if cutoutPath == nil {
if self.blurEffectView == nil {
self.backgroundColor = self.overlayColor
}
return
}
self.backgroundColor = UIColor.clear
self.cutoutMaskLayer = CAShapeLayer()
self.cutoutMaskLayer.name = "cutoutMaskLayer"
self.cutoutMaskLayer.fillRule = kCAFillRuleEvenOdd
self.cutoutMaskLayer.frame = self.frame
self.fullMaskLayer = CAShapeLayer()
self.fullMaskLayer.name = "fullMaskLayer"
self.fullMaskLayer.fillRule = kCAFillRuleEvenOdd
self.fullMaskLayer.frame = self.frame
self.fullMaskLayer.opacity = 1.0
let cutoutMaskLayerPath = UIBezierPath()
cutoutMaskLayerPath.append(UIBezierPath(rect: self.bounds))
cutoutMaskLayerPath.append(cutoutPath!)
let fullMaskLayerPath = UIBezierPath()
fullMaskLayerPath.append(UIBezierPath(rect: self.bounds))
self.cutoutMaskLayer.path = cutoutMaskLayerPath.cgPath
self.fullMaskLayer.path = fullMaskLayerPath.cgPath
let maskLayer = CALayer()
maskLayer.frame = self.layer.bounds
maskLayer.addSublayer(self.cutoutMaskLayer)
maskLayer.addSublayer(self.fullMaskLayer)
self.overlayLayer = CALayer()
self.overlayLayer.frame = self.layer.bounds
if self.blurEffectView == nil {
self.overlayLayer.backgroundColor = self.overlayColor.cgColor
}
self.overlayLayer.mask = maskLayer
if let blurEffectView = self.blurEffectView {
blurEffectView.layer.mask = maskLayer
} else {
self.layer.addSublayer(self.overlayLayer)
}
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hitView = super.hitTest(point, with: event)
if hitView == self {
guard let cutoutPath = self.cutoutPath else {
return hitView
}
if cutoutPath.contains(point) {
return nil
} else {
return hitView
}
}
return hitView
}
//MARK: - Private Methods
/// Creates the visual effect view holding
/// the blur effect and adds it to the overlay.
fileprivate func createBlurView() {
if self.blurEffectStyle == nil { return }
let blurEffect = UIBlurEffect(style: self.blurEffectStyle!)
self.blurEffectView = UIVisualEffectView(effect:blurEffect)
self.blurEffectView!.translatesAutoresizingMaskIntoConstraints = false
self.blurEffectView!.isUserInteractionEnabled = false
self.addSubview(self.blurEffectView!)
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[visualEffectView]|", options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil, views: ["visualEffectView": self.blurEffectView!]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[visualEffectView]|", options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil, views: ["visualEffectView": self.blurEffectView!]))
}
/// Removes the view holding the blur effect.
fileprivate func destroyBlurView() {
self.blurEffectView?.removeFromSuperview()
self.blurEffectView = nil
}
/// This method will be called each time the overlay receive
/// a tap event.
///
/// - Parameter sender: the object which sent the event
@objc fileprivate func handleSingleTap(_ sender: AnyObject?) {
if (!disableOverlayTap) {
self.delegate?.didReceivedSingleTap()
}
}
}
| 35.178439 | 147 | 0.673782 |
ed9ac4d4693c5112681f9883025ad23bad1c09a3
| 6,653 |
//
// ViewController.swift
// ConnectWrapper
//
// Copyright © 2020 finicity. All rights reserved.
//
import UIKit
import Connect
class ViewController: UIViewController {
@IBOutlet weak var infoView: UIView!
@IBOutlet weak var urlInput: UITextField!
@IBOutlet var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var connectButton: UIButton!
var connectViewController: ConnectViewController!
var connectNavController: UINavigationController!
let gradientLayer = CAGradientLayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Query Connect.xcframework for SDK version.
print("Connect.xcframework SDK version: \(sdkVersion())")
self.navigationController?.navigationBar.isHidden = true
setupViews()
// Add tap gesture recognizer to dismiss keyboard when tapped outside of textfield.
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(screenTapped))
view.addGestureRecognizer(tapGesture)
urlInput.becomeFirstResponder()
}
// For iPad rotation need to adjust gradient frame size
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
gradientLayer.frame = view.frame
}
// If screen tapped then end editing in textField
@objc func screenTapped(gesture: UITapGestureRecognizer) {
view.endEditing(true)
}
// On startup initialize sub-views that cannot be initialized in storyboard.
private func setupViews() {
setGradientBackgroundLayer()
activityIndicator.style = .large
activityIndicator.color = .white
infoView.layer.cornerRadius = 8
connectButton.layer.cornerRadius = 24
connectButton.isEnabled = false
connectButton.setTitleColor(UIColor(red: 254.0/255.0, green: 254.0/255.0, blue: 254.0/255.0, alpha: 0.32), for: .disabled)
connectButton.setTitleColor(UIColor(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
}
// Added gradient background layer to view hierarchy
private func setGradientBackgroundLayer() {
gradientLayer.colors = [
UIColor(red: 0.518, green: 0.714, blue: 0.427, alpha: 1).cgColor,
UIColor(red: 0.004, green: 0.537, blue: 0.616, alpha: 1).cgColor,
UIColor(red: 0.008, green: 0.22, blue: 0.447, alpha: 1).cgColor
]
gradientLayer.locations = [0, 0.4, 1]
// Diagonal Gradient
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 1, y: 1)
gradientLayer.frame = view.frame
view.layer.insertSublayer(gradientLayer, at: 0)
}
@IBAction func startButtonClicked(_ sender: UIButton) {
view.endEditing(true)
activityIndicator.startAnimating()
self.openWebKitConnectView()
}
func openWebKitConnectView() {
if let connectUrl = urlInput.text {
let config = ConnectViewConfig(connectUrl: connectUrl, loaded: self.connectViewLoaded, done: self.connectViewDone, cancel: self.connectViewCancelled, error: self.connectViewError, route: self.connectViewRoute, userEvent: self.connectViewUserEvent)
print("creating & loading connectViewController")
self.connectViewController = ConnectViewController()
self.connectViewController.load(config: config)
} else {
print("no connect url provided.")
activityIndicator.stopAnimating()
}
}
func connectViewLoaded() {
print("connectViewController loaded")
self.connectNavController = UINavigationController(rootViewController: self.connectViewController)
self.connectNavController.modalPresentationStyle = .automatic
self.connectNavController.isModalInPresentation = true
self.connectNavController.presentationController?.delegate = self
self.present(self.connectNavController, animated: true)
}
func connectViewDone(_ data: NSDictionary?) {
print("connectViewController done")
print(data?.debugDescription ?? "no data in callback")
self.activityIndicator.stopAnimating()
// Needed to trigger deallocation of ConnectViewController
self.connectViewController = nil
self.connectNavController = nil
}
func connectViewCancelled() {
print("connectViewController cancel")
self.activityIndicator.stopAnimating()
// Needed to trigger deallocation of ConnectViewController
self.connectViewController = nil
self.connectNavController = nil
}
func connectViewError(_ data: NSDictionary?) {
print("connectViewController error")
print(data?.debugDescription ?? "no data in callback")
self.activityIndicator.stopAnimating()
// Needed to trigger deallocation of ConnectViewController
self.connectViewController = nil
self.connectNavController = nil
}
func connectViewRoute(_ data: NSDictionary?) {
print("connectViewController route")
print(data?.debugDescription ?? "no data in callback")
}
func connectViewUserEvent(_ data: NSDictionary?) {
print("connectViewController user")
print(data?.debugDescription ?? "no data in callback")
}
}
extension ViewController: UIAdaptivePresentationControllerDelegate {
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
print("connectViewController dismissed by gesture")
self.activityIndicator.stopAnimating()
}
}
// If textfield is not empty enable connect button, otherwise disable connect button
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return false }
let newLength = text.count + string.count - range.length
let isEnabled = newLength > 0
connectButton.isEnabled = isEnabled
// Adjust opacity based on button enabled state
if isEnabled {
connectButton.backgroundColor = UIColor(red: 254.0 / 255.0, green: 254.0 / 255.0, blue: 254.0 / 255.0, alpha: 0.24)
} else {
connectButton.backgroundColor = UIColor(red: 254.0 / 255.0, green: 254.0 / 255.0, blue: 254.0 / 255.0, alpha: 0.16)
}
return true
}
}
| 38.906433 | 259 | 0.67338 |
e0401c4b1fc6b1d21ddddd9ca378944071a229e5
| 2,840 |
//
// CDAKGlobalData.swift
// CDAKit
//
// Created by Eric Whitley on 12/3/15.
// Copyright © 2015 Eric Whitley. All rights reserved.
//
import Foundation
/**
Stores and manages all cross-record data and settings for CDA import and export
*/
public class CDAKGlobals {
///allows access to all global properties
public static let sharedInstance = CDAKGlobals()
private init() {
//CDAKDefaultMetadata = CDAKQRDAHeader()
//CDAKDefaultMetadata.confidentiality = .Normal
}
/**
If you'd like to globally apply organizational metadata to your CDA headers for all CDA documents you can inject that metadata here.
If Record-specific metadata is found, that will be used instead.
*/
public var CDAKDefaultMetadata: CDAKQRDAHeader?
/**
Allows importing of "non-standard" CDA documents. If we find an XML file with the general CDA header we're going to attempt to import it
Any document with a template ID of "2.16.840.1.113883.10.20.22.1.1", but does not conform to another known OID for a CCDA / C32 type (or whatever else we support) will be caught and send through the CCDA importer.
The default value is "false." You will need to explicitly enable this if you want to attempt to import unknown document types.
*/
public var attemptNonStandardCDAImport = false
/**
Returns all providers discovered during import of all records.
*This will be removed*
It is possible that, during import, a provider is "dropped" and not imported. This can occur if the provider already "exists" in this collection based on matching rules. The system will only import ONE copy of a given provider where a "match" is found. Match rules include things like "same NPI" or (failing NPI match) "same name(s)."
- Version 1.0: Originally public access
- Version 1.0.1: Removed public and set to internal
*/
internal var allProviders: [CDAKProvider] {
get {
return CDAKProviders
}
}
var CDAKProviders = [CDAKProvider]()
/**
Returns all records imported during all sessions
*This will be removed*
NOTE: this should really be removed, but right now legacy Ruby logic relies on it
*/
internal var allRecords: [CDAKRecord] {
get {
return CDAKRecords
}
}
var CDAKRecords = [CDAKRecord]()
/**
Allows extension of known code systems as we find new ones - or you can add them explicitly.
Requires entry in the format - "OID": "VocabualaryName"
EX: "2.16.840.1.113883.6.1" : "LOINC",
During import this will be automatically extended to incorporate new types that are not in the original Ruby version of HDS.
You can inject any custom code systems and OIDs here
*/
public var CDAK_EXTENDED_CODE_SYSTEMS: [String:String] = CDAKCodeSystemHelper.CODE_SYSTEMS
}
| 30.869565 | 340 | 0.708803 |
754345596ece5f117d16e3b834f7f7324b36f122
| 2,201 |
/*
* The MIT License (MIT)
*
* Copyright (C) 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Original Inspiration & Author
* Copyright (c) 2016 Luke Zhao <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
extension MotionTransition {
/**
A helper transition function.
- Parameter from: A UIViewController.
- Parameter to: A UIViewController.
- Parameter in view: A UIView.
- Parameter completion: An optional completion handler.
*/
public func transition(from: UIViewController, to: UIViewController, in view: UIView, completion: ((Bool) -> Void)? = nil) {
guard !isTransitioning else {
return
}
state = .notified
isPresenting = true
transitionContainer = view
fromViewController = from
toViewController = to
completionCallback = { [weak self] in
guard let `self` = self else {
return
}
completion?($0)
self.state = .possible
}
start()
}
}
| 34.936508 | 128 | 0.664244 |
cca270ddad17c99726054cdb3fb75049be51b125
| 734 |
// SubtaskState enumerates the values for subtask state.
// 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.
public enum SubtaskStateEnum: String, Codable
{
// SubtaskStateCompleted specifies the subtask state completed state for subtask state.
case SubtaskStateCompleted = "completed"
// SubtaskStatePreparing specifies the subtask state preparing state for subtask state.
case SubtaskStatePreparing = "preparing"
// SubtaskStateRunning specifies the subtask state running state for subtask state.
case SubtaskStateRunning = "running"
}
| 45.875 | 96 | 0.776567 |
e930ca79dcfc3d5d7d05af21f7a174d54484a202
| 6,118 |
import Foundation
import TSCBasic
import TuistCore
import TuistSupport
import XCTest
@testable import TuistAutomation
@testable import TuistSupportTesting
final class XcodeBuildControllerTests: TuistUnitTestCase {
var subject: XcodeBuildController!
override func setUp() {
super.setUp()
subject = XcodeBuildController()
}
override func tearDown() {
subject = nil
super.tearDown()
}
func test_build() async throws {
// Given
let path = try temporaryPath()
let xcworkspacePath = path.appending(component: "Project.xcworkspace")
let target = XcodeBuildTarget.workspace(xcworkspacePath)
let scheme = "Scheme"
let shouldOutputBeColoured = true
environment.shouldOutputBeColoured = shouldOutputBeColoured
var command = ["/usr/bin/xcrun", "xcodebuild", "clean", "build", "-scheme", scheme]
command.append(contentsOf: target.xcodebuildArguments)
system.succeedCommand(command, output: "output")
// When
let events = subject.build(target, scheme: scheme, clean: true, arguments: [])
let result = try await events.toArray()
XCTAssertEqual(result, [.standardOutput(XcodeBuildOutput(raw: "output"))])
}
func test_test_when_device() async throws {
// Given
let path = try temporaryPath()
let xcworkspacePath = path.appending(component: "Project.xcworkspace")
let target = XcodeBuildTarget.workspace(xcworkspacePath)
let scheme = "Scheme"
let shouldOutputBeColoured = true
environment.shouldOutputBeColoured = shouldOutputBeColoured
var command = [
"/usr/bin/xcrun",
"xcodebuild",
"clean",
"test",
"-scheme",
scheme,
]
command.append(contentsOf: target.xcodebuildArguments)
command.append(contentsOf: ["-destination", "id=device-id"])
system.succeedCommand(command, output: "output")
// When
let events = subject.test(
target,
scheme: scheme,
clean: true,
destination: .device("device-id"),
derivedDataPath: nil,
resultBundlePath: nil,
arguments: [],
retryCount: 0
)
let result = try await events.toArray()
XCTAssertEqual(result, [.standardOutput(XcodeBuildOutput(raw: "output"))])
}
func test_test_when_mac() async throws {
// Given
let path = try temporaryPath()
let xcworkspacePath = path.appending(component: "Project.xcworkspace")
let target = XcodeBuildTarget.workspace(xcworkspacePath)
let scheme = "Scheme"
let shouldOutputBeColoured = true
environment.shouldOutputBeColoured = shouldOutputBeColoured
var command = [
"/usr/bin/xcrun",
"xcodebuild",
"clean",
"test",
"-scheme",
scheme,
]
command.append(contentsOf: target.xcodebuildArguments)
system.succeedCommand(command, output: "output")
// When
let events = subject.test(
target,
scheme: scheme,
clean: true,
destination: .mac,
derivedDataPath: nil,
resultBundlePath: nil,
arguments: [],
retryCount: 0
)
let result = try await events.toArray()
XCTAssertEqual(result, [.standardOutput(XcodeBuildOutput(raw: "output"))])
}
func test_test_with_derived_data() async throws {
// Given
let path = try temporaryPath()
let xcworkspacePath = path.appending(component: "Project.xcworkspace")
let target = XcodeBuildTarget.workspace(xcworkspacePath)
let scheme = "Scheme"
let derivedDataPath = try temporaryPath()
var command = [
"/usr/bin/xcrun",
"xcodebuild",
"clean",
"test",
"-scheme",
scheme,
]
command.append(contentsOf: target.xcodebuildArguments)
command.append(contentsOf: ["-derivedDataPath", derivedDataPath.pathString])
system.succeedCommand(command, output: "output")
// When
let events = subject.test(
target,
scheme: scheme,
clean: true,
destination: .mac,
derivedDataPath: derivedDataPath,
resultBundlePath: nil,
arguments: [],
retryCount: 0
)
let result = try await events.toArray()
XCTAssertEqual(result, [.standardOutput(XcodeBuildOutput(raw: "output"))])
}
func test_test_with_result_bundle_path() async throws {
// Given
let path = try temporaryPath()
let xcworkspacePath = path.appending(component: "Project.xcworkspace")
let target = XcodeBuildTarget.workspace(xcworkspacePath)
let scheme = "Scheme"
let resultBundlePath = try temporaryPath()
var command = [
"/usr/bin/xcrun",
"xcodebuild",
"clean",
"test",
"-scheme",
scheme,
]
command.append(contentsOf: target.xcodebuildArguments)
command.append(contentsOf: ["-resultBundlePath", resultBundlePath.pathString])
system.succeedCommand(command, output: "output")
// When
let events = subject.test(
target,
scheme: scheme,
clean: true,
destination: .mac,
derivedDataPath: nil,
resultBundlePath: resultBundlePath,
arguments: [],
retryCount: 0
)
let result = try await events.toArray()
XCTAssertEqual(result, [.standardOutput(XcodeBuildOutput(raw: "output"))])
}
}
extension AsyncSequence {
func toArray() async throws -> [Element] {
var result = [Element]()
for try await element in self {
result.append(element)
}
return result
}
}
| 30.137931 | 91 | 0.586957 |
01f0f8d7cc5fb2f8d3e7ca4ade7668731014260c
| 193 |
//
// ReactionVendor.swift
// EngagementSDK
//
// Created by Jelzon Monzon on 9/19/19.
//
import Foundation
protocol ReactionVendor {
func getReactions() -> Promise<[ReactionAsset]>
}
| 14.846154 | 51 | 0.694301 |
eb7d5e55e483e4c251ce4dd42f7aca54a41ac73c
| 4,004 |
//===---- EmitSupportedFeatures.swift - Swift Compiler Features Info Job ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===////
import TSCBasic
import SwiftOptions
/// Describes information about the compiler's supported arguments and features
@_spi(Testing) public struct SupportedCompilerFeatures: Codable {
var SupportedArguments: [String]
var SupportedFeatures: [String]
}
extension Toolchain {
func emitSupportedCompilerFeaturesJob(requiresInPlaceExecution: Bool = false,
swiftCompilerPrefixArgs: [String]) throws -> Job {
var commandLine: [Job.ArgTemplate] = swiftCompilerPrefixArgs.map { Job.ArgTemplate.flag($0) }
var inputs: [TypedVirtualPath] = []
commandLine.append(contentsOf: [.flag("-frontend"),
.flag("-emit-supported-features")])
// This action does not require any input files, but all frontend actions require
// at least one so we fake it.
// FIXME: Teach -emit-supported-features to not expect any inputs, like -print-target-info does.
let dummyInputPath = VirtualPath.temporaryWithKnownContents(.init("dummyInput.swift"),
"".data(using: .utf8)!)
commandLine.appendPath(dummyInputPath)
inputs.append(TypedVirtualPath(file: dummyInputPath, type: .swift))
return Job(
moduleName: "",
kind: .emitSupportedFeatures,
tool: .absolute(try getToolPath(.swiftCompiler)),
commandLine: commandLine,
displayInputs: [],
inputs: inputs,
primaryInputs: [],
outputs: [.init(file: .standardOutput, type: .jsonCompilerFeatures)],
requiresInPlaceExecution: requiresInPlaceExecution,
supportsResponseFiles: false
)
}
}
extension Driver {
static func computeSupportedCompilerFeatures(of toolchain: Toolchain, hostTriple: Triple,
parsedOptions: inout ParsedOptions,
diagnosticsEngine: DiagnosticsEngine,
fileSystem: FileSystem,
executor: DriverExecutor, env: [String: String])
throws -> Set<String> {
// TODO: Once we are sure libSwiftScan is deployed across supported platforms and architectures
// we should deploy it here.
// let swiftScanLibPath = try Self.getScanLibPath(of: toolchain,
// hostTriple: hostTriple,
// env: env)
//
// if fileSystem.exists(swiftScanLibPath) {
// let libSwiftScanInstance = try SwiftScan(dylib: swiftScanLibPath)
// if libSwiftScanInstance.canQuerySupportedArguments() {
// return try libSwiftScanInstance.querySupportedArguments()
// }
// }
// Invoke `swift-frontend -emit-supported-features`
let frontendOverride = try FrontendOverride(&parsedOptions, diagnosticsEngine)
frontendOverride.setUpForTargetInfo(toolchain)
defer { frontendOverride.setUpForCompilation(toolchain) }
let frontendFeaturesJob =
try toolchain.emitSupportedCompilerFeaturesJob(swiftCompilerPrefixArgs:
frontendOverride.prefixArgsForTargetInfo)
let decodedSupportedFlagList = try executor.execute(
job: frontendFeaturesJob,
capturingJSONOutputAs: SupportedCompilerFeatures.self,
forceResponseFiles: false,
recordedInputModificationDates: [:]).SupportedArguments
return Set(decodedSupportedFlagList)
}
}
| 45.5 | 100 | 0.639111 |
2640782db8658571d201262e7998bb204f867590
| 1,877 |
//
// Reference.swift
// SwiftFHIR
//
// Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/Reference) on 2019-11-19.
// 2019, SMART Health IT.
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
/**
A reference from one resource to another.
*/
open class Reference: Element {
override open class var resourceType: String {
get { return "Reference" }
}
/// Text alternative for the resource.
public var display: FHIRString?
/// Logical reference, when literal reference is not known.
public var identifier: Identifier?
/// Literal reference, Relative, internal or absolute URL.
public var reference: FHIRString?
/// Type the reference refers to (e.g. "Patient").
public var type: FHIRURL?
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
display = createInstance(type: FHIRString.self, for: "display", in: json, context: &instCtx, owner: self) ?? display
identifier = createInstance(type: Identifier.self, for: "identifier", in: json, context: &instCtx, owner: self) ?? identifier
reference = createInstance(type: FHIRString.self, for: "reference", in: json, context: &instCtx, owner: self) ?? reference
type = createInstance(type: FHIRURL.self, for: "type", in: json, context: &instCtx, owner: self) ?? type
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.display?.decorate(json: &json, withKey: "display", errors: &errors)
self.identifier?.decorate(json: &json, withKey: "identifier", errors: &errors)
self.reference?.decorate(json: &json, withKey: "reference", errors: &errors)
self.type?.decorate(json: &json, withKey: "type", errors: &errors)
}
}
| 34.127273 | 127 | 0.720298 |
874ec98ac755c310c37b4d25fbae5fd98a91da4f
| 503 |
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
let g = c> S<T
let t: NSObject {
class B<H : d where A: AnyObject) {
let c>: String {
}
var f: Int = ""\
| 33.533333 | 79 | 0.715706 |
8a28df47f2d3e43d40ca8a6a7db10ae79932f7ec
| 1,843 |
//
// EmacsKeyHelper.swift
//
// Copyright (c) 2011 The McBopomofo Project.
//
// Contributors:
// Mengjuei Hsieh (@mjhsieh)
// Weizhong Yang (@zonble)
//
// Based on the Syrup Project and the Formosana Library
// by Lukhnos Liu (@lukhnos).
//
// 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 Cocoa
@objc enum McBopomofoEmacsKey: UInt16 {
case none = 0
case forward = 6 // F
case backward = 2 // B
case home = 1 // A
case end = 5 // E
case delete = 4 // D
case nextPage = 22 // V
}
class EmacsKeyHelper: NSObject {
@objc static func detect(charCode: UniChar, flags: NSEvent.ModifierFlags) -> McBopomofoEmacsKey {
if flags.contains(.control) {
return McBopomofoEmacsKey(rawValue: charCode) ?? .none
}
return .none;
}
}
| 33.509091 | 101 | 0.704286 |
23aadb7181885bdd92b76486598c211ea11a1568
| 1,113 |
/*
* license-start
*
* Copyright (C) 2021 Ministero della Salute and all other contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// HCert+PersonalData.swift
// VerificaC19
//
// Created by Andrea Prosseda on 27/06/21.
//
import Foundation
import SwiftDGC
extension HCert {
var name: String { lastName + " " + firstName }
var firstName: String { body["nam"]["gn"].string ?? "" }
var lastName: String { body["nam"]["fn"].string ?? "" }
var birthDate: String { body["dob"].string?.toDate?.toDateReadableString ?? "" }
}
| 27.825 | 84 | 0.669362 |
9c3d71c6de6851290991f67640de8dcb3f2ec02b
| 2,551 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Distributed Tracing open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Tracing
extension SpanAttributeName {
/// - See: EndUserAttributes
public enum EndUser {
/// - See: EndUserAttributes
public static let id = "enduser.id"
/// - See: EndUserAttributes
public static let role = "enduser.role"
/// - See: EndUserAttributes
public static let scope = "enduser.scope"
}
}
#if swift(>=5.2)
extension SpanAttributes {
/// Semantic end-user attributes.
public var endUser: EndUserAttributes {
get {
.init(attributes: self)
}
set {
self = newValue.attributes
}
}
}
/// End-user-related semantic conventions as defined in the OpenTelemetry spec.
///
/// - SeeAlso: [OpenTelemetry: General identity attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/b70565d5a8a13d26c91fb692879dc874d22c3ac8/specification/trace/semantic_conventions/span-general.md#general-identity-attributes) (as of August 2020)
@dynamicMemberLookup
public struct EndUserAttributes: SpanAttributeNamespace {
public var attributes: SpanAttributes
public init(attributes: SpanAttributes) {
self.attributes = attributes
}
public struct NestedSpanAttributes: NestedSpanAttributesProtocol {
public init() {}
/// Username or client_id extracted from the access token or Authorization header in the inbound request from outside the system.
public var id: Key<String> { .init(name: SpanAttributeName.EndUser.id) }
/// Actual/assumed role the client is making the request under extracted from token or application security context.
public var role: Key<String> { .init(name: SpanAttributeName.EndUser.role) }
/// Scopes or granted authorities the client currently possesses extracted from token or application security context.
/// The value would come from the scope associated with an OAuth 2.0 Access Token or an attribute value in a SAML 2.0 Assertion.
public var scope: Key<String> { .init(name: SpanAttributeName.EndUser.scope) }
}
}
#endif
| 38.074627 | 273 | 0.660525 |
0e1b9f8bf334ba236db39f38999b9716f5233e84
| 7,703 |
//
// TrailingCommaRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 21/11/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
private enum TrailingCommaReason: String {
case missingTrailingCommaReason = "Multi-line collection literals should have trailing commas."
case extraTrailingCommaReason = "Collection literals should not have trailing commas."
}
private typealias CommaRuleViolation = (index: Int, reason: TrailingCommaReason)
public struct TrailingCommaRule: ASTRule, CorrectableRule, ConfigurationProviderRule {
public var configuration = TrailingCommaConfiguration()
public init() {}
private static let triggeringExamples = [
"let foo = [1, 2, 3↓,]\n",
"let foo = [1, 2, 3↓, ]\n",
"let foo = [1, 2, 3 ↓,]\n",
"let foo = [1: 2, 2: 3↓, ]\n",
"struct Bar {\n let foo = [1: 2, 2: 3↓, ]\n}\n",
"let foo = [1, 2, 3↓,] + [4, 5, 6↓,]\n",
"let example = [ 1,\n2↓,\n // 3,\n]",
"let foo = [\"אבג\", \"αβγ\", \"🇺🇸\"↓,]\n"
// "foo([1: \"\\(error)\"↓,])\n"
]
private static let corrections: [String: String] = {
let fixed = triggeringExamples.map { $0.replacingOccurrences(of: "↓,", with: "") }
var result: [String: String] = [:]
for (triggering, correction) in zip(triggeringExamples, fixed) {
result[triggering] = correction
}
return result
}()
public static let description = RuleDescription(
identifier: "trailing_comma",
name: "Trailing Comma",
description: "Trailing commas in arrays and dictionaries should be avoided/enforced.",
kind: .style,
nonTriggeringExamples: [
"let foo = [1, 2, 3]\n",
"let foo = []\n",
"let foo = [:]\n",
"let foo = [1: 2, 2: 3]\n",
"let foo = [Void]()\n",
"let example = [ 1,\n 2\n // 3,\n]",
"foo([1: \"\\(error)\"])\n"
],
triggeringExamples: TrailingCommaRule.triggeringExamples,
corrections: TrailingCommaRule.corrections
)
private static let commaRegex = regex(",", options: [.ignoreMetacharacters])
public func validate(file: File, kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
if let (index, reason) = violationIndexAndReason(in: file, kind: kind, dictionary: dictionary) {
return violations(file: file, byteOffset: index, reason: reason.rawValue)
} else {
return []
}
}
private func violationIndexAndReason(in file: File, kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> CommaRuleViolation? {
let allowedKinds: [SwiftExpressionKind] = [.array, .dictionary]
guard let bodyOffset = dictionary.bodyOffset,
let bodyLength = dictionary.bodyLength,
allowedKinds.contains(kind) else {
return nil
}
let endPositions = dictionary.elements.flatMap { dictionary -> Int? in
guard let offset = dictionary.offset,
let length = dictionary.length else {
return nil
}
return offset + length
}
guard let lastPosition = endPositions.max(), bodyLength + bodyOffset >= lastPosition else {
return nil
}
let contents = file.contents.bridge()
if let (startLine, _) = contents.lineAndCharacter(forByteOffset: bodyOffset),
let (endLine, _) = contents.lineAndCharacter(forByteOffset: lastPosition),
configuration.mandatoryComma && startLine == endLine {
// shouldn't trigger if mandatory comma style and is a single-line declaration
return nil
}
let length = bodyLength + bodyOffset - lastPosition
let contentsAfterLastElement = contents.substringWithByteRange(start: lastPosition, length: length) ?? ""
// if a trailing comma is not present
guard let commaIndex = trailingCommaIndex(contents: contentsAfterLastElement, file: file,
offset: lastPosition) else {
guard configuration.mandatoryComma else {
return nil
}
return (lastPosition, .missingTrailingCommaReason)
}
// trailing comma is present, which is a violation if mandatoryComma is false
guard !configuration.mandatoryComma else {
return nil
}
let violationOffset = lastPosition + commaIndex
return (violationOffset, .extraTrailingCommaReason)
}
private func violations(file: File, byteOffset: Int, reason: String) -> [StyleViolation] {
return [
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severityConfiguration.severity,
location: Location(file: file, byteOffset: byteOffset),
reason: reason
)
]
}
private func trailingCommaIndex(contents: String, file: File, offset: Int) -> Int? {
let nsstring = contents.bridge()
let range = NSRange(location: 0, length: nsstring.length)
let ranges = TrailingCommaRule.commaRegex.matches(in: contents, options: [], range: range).map { $0.range }
// skip commas in comments
return ranges.filter {
let range = NSRange(location: $0.location + offset, length: $0.length)
let kinds = file.syntaxMap.kinds(inByteRange: range)
return !kinds.contains(where: SyntaxKind.commentKinds().contains)
}.last.flatMap {
nsstring.NSRangeToByteRange(start: $0.location, length: $0.length)
}?.location
}
private func violationRanges(in file: File,
dictionary: [String: SourceKitRepresentable]) -> [NSRange] {
return dictionary.substructure.flatMap { subDict -> [NSRange] in
var violations = violationRanges(in: file, dictionary: subDict)
if let kindString = subDict.kind,
let kind = KindType(rawValue: kindString),
let index = violationIndexAndReason(in: file, kind: kind, dictionary: subDict)?.index {
violations += [NSRange(location: index, length: 1)]
}
return violations
}
}
public func correct(file: File) -> [Correction] {
let violations = violationRanges(in: file, dictionary: file.structure.dictionary)
let correctedViolations = violations.map {
file.contents.bridge().byteRangeToNSRange(start: $0.location, length: $0.length)!
}
let matches = file.ruleEnabled(violatingRanges: correctedViolations, for: self)
if matches.isEmpty { return [] }
let correctedContents = NSMutableString(string: file.contents)
matches.reversed().forEach { range in
if configuration.mandatoryComma {
correctedContents.insert(",", at: range.location)
} else {
correctedContents.deleteCharacters(in: range)
}
}
let description = type(of: self).description
let corrections = matches.map { range -> Correction in
let location = Location(file: file, characterOffset: range.location)
return Correction(ruleDescription: description, location: location)
}
file.write(correctedContents.bridge())
return corrections
}
}
| 38.90404 | 115 | 0.598598 |
147f48df9374fcf1625d032ae78d6072c419bec8
| 9,895 |
//
// ViewController.swift
// AlzheimeR
//
// Created by Gary Dhillon on 2018-01-13.
//
import UIKit
import SceneKit
import ARKit
import CoreGraphics
import ARCL
import CoreLocation
struct Person : Codable {
let name: String
let lat: String
let lon: String
}
class ViewController: UIViewController, ARSCNViewDelegate, CLLocationManagerDelegate {
@objc
var locNodes = [LocationNode]()
@objc func wtvr() {
print("hello")
let url = URL(string: "http://52.233.39.60:5000/gps")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"
var persons = [Person]()
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
//let responseString = String(data: data, encoding: .utf8)
//print("responseString = \(responseString)")
do {
persons = try JSONDecoder().decode([Person].self, from: data!)
for loc in self.locNodes {
self.sceneLocationView.removeLocationNode(locationNode: loc)
}
self.locNodes = [LocationNode]()
for person in persons {
print(person.name)
let lat = Double(person.lat)
let lon = Double(person.lon)
print(lat)
print(lon)
let coordinate = CLLocationCoordinate2D(latitude: lat!, longitude: lon!)
let location = CLLocation(coordinate: coordinate, altitude: 90)
let image = UIImage(named: "art.scnassets/pin.png")!
let image3 = self.textToImage(drawText:person.name, inImage:image, atPoint:CGPoint(x:0,y:0))
let annotationNode = LocationAnnotationNode(location: location, image: image3)
annotationNode.scaleRelativeToDistance = true
self.locNodes.append(annotationNode)
self.sceneLocationView.addLocationNodeWithConfirmedLocation(locationNode: annotationNode)
}
} catch {
print("error")
}
}
task.resume()
let coordinate = CLLocationCoordinate2D(latitude: 49.26225, longitude: -123.2452)
let location = CLLocation(coordinate: coordinate, altitude: 90)
let image = UIImage(named: "art.scnassets/pin.png")!
let image3 = textToImage(drawText:"Son's Home", inImage:image, atPoint:CGPoint(x:0,y:0))
let annotationNode = LocationAnnotationNode(location: location, image: image3)
annotationNode.scaleRelativeToDistance = true
let coordinate1 = CLLocationCoordinate2D(latitude: 49.2651, longitude: -123.2506)
let location1 = CLLocation(coordinate: coordinate1, altitude: 85)
let image1 = UIImage(named: "art.scnassets/pin.png")!
let image2 = textToImage(drawText:"STUFF", inImage:image1, atPoint:CGPoint(x:0,y:0))
let annotationNode1 = LocationAnnotationNode(location: location1, image: image2)
annotationNode1.scaleRelativeToDistance = true
// let text = SCNText(string: "Hello,World", extrusionDepth: 1)
// let material = SCNMaterial()
// material.diffuse.contents = UIColor.green
// text.materials = [material]
//
// let textNode = SCNNode()
// textNode.position = SCNVector3(x:0,y:0,z:0)
// textNode.scale = SCNVector3(x:0.01,y:0.01,z:0.01)
// textNode.geometry = text
//let annotationNode2 = LocationAnnotationNode(location: location, textNode: textNode)
//annotationNode2.scaleRelativeToDistance = false
//sceneLocationView.autoenablesDefaultLighting = true
sceneLocationView.addLocationNodeWithConfirmedLocation(locationNode: annotationNode)
sceneLocationView.addLocationNodeWithConfirmedLocation(locationNode: annotationNode1)
//sceneLocationView.scene.rootNode.addChildNode(textNode)
print("DOOM")
sceneLocationView.run()
}
var sceneLocationView = SceneLocationView()
@IBOutlet var sceneView: ARSCNView!
var locationManager: CLLocationManager = CLLocationManager()
var alt = 0.0
var yourName = "";
var timer:Timer?
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.wtvr), userInfo: nil, repeats: true)
yourName = "Parash Rahman (Brother In Law)"
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
sceneView.showsStatistics = true
// Create a new scene
//let scene = SCNScene(named: "art.scnassets/ship.scn")!
// Set the scene to the view
//sceneView.scene = scene
view.addSubview(sceneLocationView)
}
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.green
let textFont = UIFont(name: "Helvetica Bold", size: 20)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSAttributedStringKey.font: textFont,
NSAttributedStringKey.foregroundColor: textColor,
] as [NSAttributedStringKey : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let lastLocation: CLLocation = locations[locations.count - 1]
alt = lastLocation.altitude
let url = URL(string: "http://52.233.39.60:5000/gps")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "{\"name\":\"\(yourName)\", \"lon\":\"\(lastLocation.coordinate.longitude)\", \"lat\":\"\(lastLocation.coordinate.latitude)\"}"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
print("\(alt)")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
// Run the view's session
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
// MARK: - ARSCNViewDelegate
/*
// Override to create and configure nodes for anchors added to the view's session.
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
let node = SCNNode()
return node
}
*/
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
sceneLocationView.frame = view.bounds
}
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
}
| 36.378676 | 152 | 0.591309 |
676eddde9ffd60e69c8462875452633b784d1547
| 1,315 |
//
// ActionTableViewCell.swift
// AcnGatewayiOS
//
// Created by Michael Kalinin on 21/07/16.
// Copyright © 2016 Arrow Electronics. All rights reserved.
//
import Foundation
import AcnSDK
class ActionTableViewCell: UITableViewCell {
var actionModel: ActionModel?
var deviceHid: String?
@IBOutlet weak var actionTypeLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var enableSwitch: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
enableSwitch.onTintColor = .mainColor
backgroundColor = .gray0
contentView.backgroundColor = .gray0
}
func setupCellWithActionModel(model: ActionModel, deviceHid: String) {
self.actionModel = model
self.deviceHid = deviceHid
actionTypeLabel.text = model.actionType.nameForDisplay
descriptionLabel.text = model.description
enableSwitch.setOn(model.enabled, animated: false)
}
@IBAction func enabledStateChanged(_ sender: UISwitch) {
if actionModel != nil {
actionModel!.enabled = sender.isOn
ArrowConnectIot.sharedInstance.deviceApi.updateDeviceAction(hid: deviceHid!, action: actionModel!)
}
}
}
| 26.836735 | 110 | 0.653992 |
8ff994b0f4fb9dc78d51907b43edfae22aa92324
| 1,539 |
// Copyright 2020 Carton contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
public enum SanitizeVariant: String, CaseIterable {
case stackOverflow
}
/// The target environment to build for.
/// `Environment` doesn't specify the concrete environment, but the type of environments enough for build planning.
public enum Environment: String, CaseIterable {
public static var allCasesNames: [String] { Environment.allCases.map { $0.rawValue } }
// TODO: Rename to `commandLine` to avoid confusion
case wasmer
case node
case defaultBrowser
}
public struct BuildFlavor {
public var isRelease: Bool
public var environment: Environment
public var sanitize: SanitizeVariant?
public var swiftCompilerFlags: [String]
public init(
isRelease: Bool,
environment: Environment,
sanitize: SanitizeVariant?,
swiftCompilerFlags: [String]
) {
self.isRelease = isRelease
self.environment = environment
self.sanitize = sanitize
self.swiftCompilerFlags = swiftCompilerFlags
}
}
| 31.408163 | 115 | 0.746589 |
fce38854318b251e24c7cf74b76975384f9ab1a0
| 366 |
//
// OneSelection.swift
// Beiwe
//
// Created by Keary Griffin on 4/8/16.
// Copyright © 2016 Rocketfarm Studios. All rights reserved.
//
import Foundation
import ObjectMapper
struct OneSelection : Mappable {
var text: String = "";
init?(map: Map) {
}
// Mappable
mutating func mapping(map: Map) {
text <- map["text"];
}
}
| 15.25 | 61 | 0.60929 |
08a60c160e161953f43580425b00dd1d76baaafe
| 380 |
// SWIFT_ENABLE_TENSORFLOW
struct Base : PointwiseMultiplicative {}
// expected-note @+1 3 {{type declared here}}
struct OtherFileNonconforming : Equatable, AdditiveArithmetic {
var base: Base
}
// expected-note @+1 3 {{type declared here}}
struct GenericOtherFileNonconforming<
T : PointwiseMultiplicative
> : Equatable, AdditiveArithmetic {
var x: T
var base: Base
}
| 22.352941 | 63 | 0.747368 |
87e891d8511ccb75203203dd5667b54573c698cb
| 779 |
//
// JellyValue.swift
// AxisSegmentedViewExample
//
// Created by jasu on 2022/03/23.
// Copyright (c) 2022 jasu All rights reserved.
//
import SwiftUI
import AxisSegmentedView
class JellyValue: ObservableObject {
@Published var constant = ASConstant(divideLine: .init(color: Color(hex: 0x444444), scale: 0))
@Published var backgroundColor: Color = .gray.opacity(0.1)
@Published var foregroundColor: Color = .purple
@Published var jellyRadius: CGFloat = 110
@Published var jellyDepth: CGFloat = 0.9
@Published var jellyEdge: ASEdgeMode = .bottomTrailing
@Published var selectArea0: CGFloat = 0
@Published var selectArea1: CGFloat = 0
@Published var selectArea2: CGFloat = 0
@Published var selectArea3: CGFloat = 0
}
| 28.851852 | 98 | 0.707317 |
20004262033c0f8c9d68bb3858eb777abccbab0f
| 3,520 |
//
// AppDelegate.swift
// MovieViewer
//
// Created by Christine Hong on 2/4/16.
// Copyright © 2016 christinehong. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nowPlayingNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MoviesViewController
nowPlayingViewController.endpoint = "now_playing"
nowPlayingNavigationController.tabBarItem.title = "Now Playing"
nowPlayingNavigationController.tabBarItem.image = UIImage(named: "now-playing")
let topRatedNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let topRatedViewController = topRatedNavigationController.topViewController as! MoviesViewController
topRatedViewController.endpoint = "top_rated"
topRatedNavigationController.tabBarItem.title = "Top Rated"
topRatedNavigationController.tabBarItem.image = UIImage(named: "top-rated")
let tabBarController = UITabBarController()
tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController]
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 51.764706 | 285 | 0.756818 |
d998d5b61582d73f3d9e0f4b2815cc5b02fdb6b3
| 854 |
import UIKit
import WQNetworkActivityIndicator
class ViewController: UIViewController {
private var aStarted = false
private var bStarted = false
override func viewDidLoad() {
super.viewDidLoad()
WQNetworkActivityIndicator.shared.timeout = 0
}
@IBAction func startA(_ sender: Any) {
if !aStarted {
aStarted = true
WQNetworkActivityIndicator.shared.show()
}
}
@IBAction func stopA(_ sender: Any) {
aStarted = false
WQNetworkActivityIndicator.shared.hide()
}
@IBAction func startB(_ sender: Any) {
if !bStarted {
bStarted = true
WQNetworkActivityIndicator.shared.show()
}
}
@IBAction func stopB(_ sender: Any) {
bStarted = false
WQNetworkActivityIndicator.shared.hide()
}
}
| 23.081081 | 53 | 0.617096 |
e40cddf397282eb300be3c849d6d3ee3274a36ec
| 643 |
// RUN: %empty-directory(%t)
// RUN: %target-clang -c %S/Inputs/static-member-var.cpp -I %S/Inputs -o %t/static-member-var.o -std=c++17
// RUN: %target-build-swift %s -I %S/Inputs -o %t/statics %t/static-member-var.o -Xfrontend -enable-cxx-interop -Xcc -std=c++17
// RUN: %target-codesign %t/statics
// RUN: %target-run %t/statics
//
// REQUIRES: executable_test
import StaticMemberVar
import StdlibUnittest
var ConstexprStaticMemberVarTestSuite = TestSuite("ConstexprStaticMemberVarTestSuite")
ConstexprStaticMemberVarTestSuite.test("constexpr-static-member") {
expectEqual(139, WithConstexprStaticMember.definedInline)
}
runAllTests()
| 33.842105 | 127 | 0.755832 |
22e53277865a68207ee256a228c27e2373b5222c
| 1,270 |
import XCTest
import Foundation
class TestData {
class func stringFromFile(name: String) -> String {
let path = URL(fileURLWithPath: #file)
.deletingLastPathComponent()
.appendingPathComponent("TestData")
.appendingPathComponent(name)
do {
if !(try path.checkResourceIsReachable()) {
XCTAssert(false, "Fixture \(name) not found.")
return ""
}
return try String(contentsOf: path, encoding: .utf8)
}
catch {
XCTAssert(false, "Unable to decode fixture at \(path): \(error).")
return ""
}
}
class func dataFromFile(name: String) -> Data {
let path = URL(fileURLWithPath: #file)
.deletingLastPathComponent()
.appendingPathComponent("TestData")
.appendingPathComponent(name)
do {
if !(try path.checkResourceIsReachable()) {
XCTAssert(false, "Fixture \(name) not found.")
return Data()
}
return try Data(contentsOf: path)
}
catch {
XCTAssert(false, "Unable to decode fixture at \(path): \(error).")
return Data()
}
}
}
| 28.222222 | 78 | 0.529921 |
33ef930edb6c58e3a610a26b91e12cbf6e8df531
| 2,920 |
//
// ViewController.swift
// DoubleSliderDemo
//
// Created by josh on 2018/03/30.
// Copyright © 2018年 yhkaplan. All rights reserved.
//
import UIKit
import DoubleSlider
class ViewController: UIViewController {
@IBOutlet weak var backgroundView: UIView!
@IBOutlet weak var normalSlider: UISlider!
@IBOutlet weak var redDoubleSlider: DoubleSlider!
var labels: [String] = []
var doubleSlider: DoubleSlider!
override func viewDidLoad() {
super.viewDidLoad()
makeLabels()
setupDoubleSlider()
redDoubleSlider.labelDelegate = self
redDoubleSlider.numberOfSteps = labels.count
redDoubleSlider.labelsAreHidden = false
redDoubleSlider.smoothStepping = true
}
private func makeLabels() {
for num in stride(from: 0, to: 200, by: 10) {
labels.append("$\(num)")
}
labels.append("No limit")
}
private func setupDoubleSlider() {
let height: CGFloat = 38.0 //TODO: make this the default height
let width = view.bounds.width - 38.0
let frame = CGRect(
x: backgroundView.bounds.minX - 2.0,
y: backgroundView.bounds.midY - (height / 2.0),
width: width,
height: height
)
doubleSlider = DoubleSlider(frame: frame)
doubleSlider.translatesAutoresizingMaskIntoConstraints = false
doubleSlider.labelDelegate = self
doubleSlider.numberOfSteps = labels.count
doubleSlider.smoothStepping = true
let labelOffset: CGFloat = 8.0
doubleSlider.lowerLabelMarginOffset = labelOffset
doubleSlider.upperLabelMarginOffset = labelOffset
doubleSlider.lowerValueStepIndex = 0
doubleSlider.upperValueStepIndex = labels.count - 1
// You can use traditional notifications
doubleSlider.addTarget(self, action: #selector(printVal(_:)), for: .valueChanged)
// Or Swifty delegates
doubleSlider.editingDidEndDelegate = self
backgroundView.addSubview(doubleSlider)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
doubleSlider.removeTarget(self, action: #selector(printVal(_:)), for: .valueChanged)
}
@objc func printVal(_ doubleSlider: DoubleSlider) {
print("Lower: \(doubleSlider.lowerValue) Upper: \(doubleSlider.upperValue)")
}
}
extension ViewController: DoubleSliderEditingDidEndDelegate {
func editingDidEnd(for doubleSlider: DoubleSlider) {
print("Lower Step Index: \(doubleSlider.lowerValueStepIndex) Upper Step Index: \(doubleSlider.upperValueStepIndex)")
}
}
extension ViewController: DoubleSliderLabelDelegate {
func labelForStep(at index: Int) -> String? {
return labels.item(at: index)
}
}
| 31.06383 | 124 | 0.649658 |
de291097310be9382ea66d370129db7a1064ab34
| 2,678 |
//
// OAuthViewController.swift
// FSWeiBo
//
// Created by LKLFS on 16/9/20.
// Copyright © 2016年 LKLFS. All rights reserved.
//
import UIKit
import WebKit
class OAuthViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 1.创建webView
view.addSubview(webView)
// 2.加载登陆界面
let oauthUrlStr = "https://api.weibo.com/oauth2/authorize?client_id=1052156984&redirect_uri=http://www.baidu.com"
guard let url = NSURL(string: oauthUrlStr) else {
return
}
let request = NSURLRequest(url: url as URL)
webView.load(request as URLRequest)
}
// webView
private lazy var webView: WKWebView = {
var webview = WKWebView()
// webview.delegate = self
webview.frame = CGRect.init(x:0, y:0, width:self.view.frame.width, height:self.view.frame.height)
return webview
}()
}
//MARK: - 代理方法
extension OAuthViewController: UIWebViewDelegate
{
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool
{
guard let urlStr = request.url?.absoluteString else {
return true
}
if !(urlStr.hasPrefix("http://www.baidu.com/")) {
FSLog(message: "不是授权回调页!")
return true
}
let keyCode = "code="
guard let query = request.url?.query else {
return true
}
if (urlStr.contains(keyCode)) {
// 拿到code
let codeStr = query.substring(from: keyCode.endIndex)
loadAccessToken(codeStr: codeStr)
return false
}
return false
}
private func loadAccessToken(codeStr: String){
// 请求路径
let urlStr = "oauth2/access_token"
// 请求参数
let appKey = "1052156984"
let appSecret = "d4fca7800335e384edb24ff6cffba88a"
let paramter = ["client_id" : appKey,
"client_secret": appSecret,
"grant_type" : "authorization_code",
"code" : codeStr,
"redirect_uri" : "http://www.baidu.com"]
// 发送请求
NetWorkTools.shareInstance.post(urlStr, parameters: paramter, progress: nil,
success: { (task:URLSessionDataTask, respone) in
print(respone!)
},
failure: { (task:URLSessionDataTask?, Error) in
print(Error)
})
}
}
| 26.78 | 129 | 0.542196 |
46320213f103df64ad99858af83a4fc7fef668db
| 1,733 |
//----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.7.0.0
//
// Created by Quasar Development
//
//---------------------------------------------------
import Foundation
/**
* abstDomain: A14687 (C-0-T14581-A16931-A14687-cpt)
*/
public enum EPA_FdV_AUTHZ_Insertion:Int,CustomStringConvertible
{
case CERVINS
case IOSURGINS
case IU
case LPINS
case PR
case SQSURGINS
case URETHINS
case VAGINSI
static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_Insertion?
{
return createWithString(value: node.stringValue!)
}
static func createWithString(value:String) -> EPA_FdV_AUTHZ_Insertion?
{
var i = 0
while let item = EPA_FdV_AUTHZ_Insertion(rawValue: i)
{
if String(describing: item) == value
{
return item
}
i += 1
}
return nil
}
public var stringValue : String
{
return description
}
public var description : String
{
switch self
{
case .CERVINS: return "CERVINS"
case .IOSURGINS: return "IOSURGINS"
case .IU: return "IU"
case .LPINS: return "LPINS"
case .PR: return "PR"
case .SQSURGINS: return "SQSURGINS"
case .URETHINS: return "URETHINS"
case .VAGINSI: return "VAGINSI"
}
}
public func getValue() -> Int
{
return rawValue
}
func serialize(__parent:DDXMLNode)
{
__parent.stringValue = stringValue
}
}
| 21.6625 | 75 | 0.500289 |
1ccb00478505a0e8eb541e6af7af2995bab9435a
| 794 |
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AudioKit
import XCTest
class ClipTests: XCTestCase {
func testClip() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = OperationEffect(input) { $0.clip(0.5) }
input.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testDefault() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = OperationEffect(input) { $0.clip() }
input.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
}
| 27.37931 | 100 | 0.623426 |
1d7991d0e13d3b025dd4ba501f18948141f394ba
| 556 |
//
// UserDefaultsMockTests.swift
// swaapTests
//
// Created by Chad Rutherford on 4/20/20.
// Copyright © 2020 swaap. All rights reserved.
//
import XCTest
@testable import swaap
class UserDefaultsTests: XCTestCase {
func testUserDefaultsMock() {
let objectKey = "InitialLaunch"
let userDefaults = UserDefaultsMock() as UserDefaultsProtocol
userDefaults.setObject(true, forKey: objectKey)
XCTAssertNotNil(userDefaults.objectForKey(objectKey))
if let key = userDefaults.objectForKey(objectKey) as? Bool {
XCTAssertTrue(key)
}
}
}
| 23.166667 | 63 | 0.75 |
bba8dd6efd2c59828372a867399e3b22775a9b6c
| 1,558 |
//
// TabBarCoordinator.swift
// WhatToWatch
//
// Created by Denis Novitsky on 03.03.2021.
//
import Foundation
import Swinject
final class TabBarCoordinator: BaseFlowCoordinator {
// MARK: - Private Properties
private weak var route: TabBarRoute?
private let coordinatorProvider: FlowCoordinatorProvider
init(route: TabBarRoute, diContainer: Container) {
self.route = route
self.coordinatorProvider = diContainer.resolve(FlowCoordinatorProvider.self)!
super.init()
}
// MARK: - Methods
override func start() {
route?.onStart = runDiscoverCoordinator()
route?.onDiscoverSelect = runDiscoverCoordinator()
route?.onSearchSelect = runSearchCoordinator()
}
// MARK: - Private Methods
private func runCoordinator(_ coordinator: FlowCoordinator) {
addDependency(coordinator)
coordinator.start()
}
private func runDiscoverCoordinator() -> ((NavigationRouter) -> Void) {
return { [weak self] router in
guard let self = self else { return }
let coordinator = self.coordinatorProvider.makeDiscoverCoordinator(router: router)
self.runCoordinator(coordinator)
}
}
private func runSearchCoordinator() -> ((NavigationRouter) -> Void) {
return { [weak self] router in
guard let self = self else { return }
let coordinator = self.coordinatorProvider.makeSearchCoordinator(router: router)
self.runCoordinator(coordinator)
}
}
}
| 26.40678 | 94 | 0.660462 |
1dd580d76d912f09b6e567d5f5d03c692b7f5ff0
| 626 |
//
// BioContainer.swift
// Tuned
//
// Created by Ravikiran Pathade on 3/29/18.
// Copyright © 2018 Ravikiran Pathade. All rights reserved.
//
import Foundation
import UIKit
class BioContainer:UIViewController{
@IBOutlet weak var bioLabel: UILabel!
var bioLabelText:String!
@IBOutlet weak var bioLabelTextView: UITextView!
var lastFmUrl:NSMutableAttributedString!
override func viewDidLoad() {
bioLabelTextView.isEditable = false
bioLabelTextView.dataDetectorTypes = .link
bioLabelTextView.isSelectable = true
bioLabelTextView.text = bioLabelText
}
}
| 24.076923 | 60 | 0.709265 |
91b46147ccb234d96ff8ee871337c690c1884507
| 3,534 |
import XCTest
@testable import Geometry
let point: [String: Any] = [
"type": "Feature",
"geometry": [
"type": "Point",
"coordinates": [102, 0.5]
]
]
let lineString: [String: Any] = [
"type": "Feature",
"geometry": [
"type": "LineString",
"coordinates": [
[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
]
]
]
let simplePolygon: [String: Any] = [
"type": "Feature",
"geometry": [
"type": "Polygon",
"coordinates": [
[[30, 10], [40, 40], [20, 40], [10, 20], [30, 10]]
]
]
]
let complexPolygon: [String: Any] = [
"type": "Feature",
"geometry": [
"type": "Polygon",
"coordinates": [
[[35, 10], [45, 45], [15, 40], [10, 20], [35, 10]],
[[20, 30], [35, 35], [30, 20], [20, 30]]
]
]
]
class CawGeoJSONTests: XCTestCase {
func testPoint () {
do {
let feature = try Feature (json: point)
XCTAssert (feature.geometry as? Geometry.Point != nil, "Geometry was supposed to be a point")
} catch let error {
XCTFail("\(error)")
}
}
func testLineString () {
do {
let feature = try Feature (json: lineString)
XCTAssert (feature.geometry as? Geometry.LineString != nil, "Geometry was supposed to be a linestring")
} catch let error {
XCTFail("\(error)")
}
}
func testSimplePolygon () {
do {
let feature = try Feature (json: simplePolygon)
guard let polygon = feature.geometry as? Geometry.Polygon else {
XCTFail("Geometry was supposed to be a polygon")
return
}
XCTAssert(polygon.outerCoordinates.count == 5, "Polygon should have 5 outer points")
XCTAssert(polygon.innerCoordinates.count == 0, "Polygon should have 0 inner points")
} catch let error {
XCTFail("\(error)")
}
}
func testComplexPolygon () {
do {
let feature = try Feature (json: complexPolygon)
guard let polygon = feature.geometry as? Geometry.Polygon else {
XCTFail("Geometry was supposed to be a polygon")
return
}
XCTAssert(polygon.outerCoordinates.count == 5, "Polygon should have 5 outer points")
XCTAssert(polygon.innerCoordinates.count == 4, "Polygon should have 4 inner points")
} catch let error {
XCTFail("\(error)")
}
}
func testFeatureCollection () {
let features = [
point,
lineString,
simplePolygon,
complexPolygon
]
let collection: [String: Any] = [
"type": "FeatureCollection",
"features": features
]
do {
let featureCollection = try FeatureCollection (json: collection)
print (featureCollection.features)
XCTAssert (featureCollection.features.count == features.count,
"Feature Collection should have \(features.count) features")
} catch let error {
XCTFail("\(error)")
}
}
static var allTests = [
("testPoint", testPoint),
("testLineString", testLineString),
("testSimplePolygon", testSimplePolygon),
("testComplexPolygon", testComplexPolygon),
("testFeatureCollection", testFeatureCollection),
]
}
| 28.967213 | 115 | 0.525467 |
d95ba98259b6adcedb7c66f8283ce904fde97798
| 1,472 |
//
// Theme.swift
// App Love
//
// Created by Woodie Dovich on 2016-02-27.
// Copyright © 2016 Snowpunch. All rights reserved.
//
// Theme colors for the app.
//
// cleaned
import UIKit
internal struct Theme {
// dark pastel blue
static let defaultColor = UIColor(red: 43/255, green: 85/255, blue: 127/255, alpha: 1.0)
static let lighterDefaultColor = UIColor(red: 73/255, green: 115/255, blue: 157/255, alpha: 1.0)
static let lightestDefaultColor = UIColor(red: 103/255, green: 145/255, blue: 197/255, alpha: 1.0)
static func navigationBar() {
let bar = UINavigationBar.appearance()
bar.tintColor = .whiteColor()
bar.barTintColor = Theme.defaultColor
bar.translucent = false
bar.barStyle = .Black
}
static func mailBar(bar:UINavigationBar) {
bar.tintColor = .whiteColor()
bar.barTintColor = Theme.defaultColor
bar.translucent = false
bar.barStyle = .Black
}
static func toolBar(item:UIToolbar) {
item.tintColor = .whiteColor()
item.barTintColor = Theme.defaultColor
item.translucent = false
}
static func alertController(item:UIAlertController) {
item.view.tintColor = Theme.lighterDefaultColor
}
static func searchBar(item:UISearchBar) {
item.barTintColor = Theme.defaultColor
item.backgroundImage = UIImage()
item.backgroundColor = Theme.defaultColor
}
}
| 28.862745 | 102 | 0.648098 |
798b1df139d374f99c595c72a77b79956b1d1451
| 2,620 |
//
// BaseTestCaseWithLogin.swift
// Figo
//
// Created by Christian König on 24.11.15.
// Copyright © 2015 figo GmbH. All rights reserved.
//
import Foundation
import XCTest
@testable import Figo
let figo = FigoClient(clientID: "C3XGp3LGISZFwJSsDfxwhHvXT1MjCoF92lOJ3VZrKeBI", clientSecret: "SJtBMNCn6KrIkjQSCkV-xU3_ob0sUTHAFLy-K1V86SpY", logger: ConsoleLogger(levels: [.verbose, .debug, .error]))
class BaseTestCaseWithLogin: XCTestCase {
let username = "[email protected]"
let password = "eVPVdiL7"
let clientID = "C3XGp3LGISZFwJSsDfxwhHvXT1MjCoF92lOJ3VZrKeBI"
let clientSecret = "SJtBMNCn6KrIkjQSCkV-xU3_ob0sUTHAFLy-K1V86SpY"
let demoBankCode = "90090042"
let demoCredentials = ["demo", "demo"]
let demoGiroAccountId = "A2132899.4"
let demoGiroAccountTANSchemeId = "M2132899.9"
let demoSavingsAccountId = "A2132899.5"
let demoDepotId = "A2132899.6"
let demoUserId = "B2132899.2"
let demoSecurityId = "S2132899.4"
var refreshToken: String?
override class func setUp() {
super.setUp()
}
func login(_ completionHandler: @escaping () -> Void) {
guard refreshToken == nil else {
debugPrint("Active session, skipping Login")
completionHandler()
return
}
debugPrint("Begin Login")
figo.loginWithUsername(username, password: password) { refreshToken in
self.refreshToken = refreshToken.value
XCTAssertNotNil(refreshToken.value)
XCTAssertNil(refreshToken.error)
debugPrint("End Login")
completionHandler()
}
}
func logout(_ completionHandler: @escaping () -> Void) {
guard refreshToken != nil else {
debugPrint("No active session, skipping Logout")
completionHandler()
return
}
debugPrint("Begin Logout")
figo.revokeRefreshToken(self.refreshToken!) { result in
XCTAssertNil(result.error)
debugPrint("End Logout")
completionHandler()
}
}
/// Allows you to get rid of the boilerplate code for async callbacks in test cases
func waitForCompletionOfTests(_ tests: (_ doneWaiting: @escaping () -> ()) -> ()) {
let completionExpectation = self.expectation(description: "Completion should be called")
tests {
completionExpectation.fulfill()
}
self.waitForExpectations(timeout: 30, handler: nil)
}
func testThatCertificateIsPresent() {
XCTAssertNotNil(figo.publicKeys)
}
}
| 31.566265 | 200 | 0.646183 |
4b3f96122c486c30361cf0972dd24861ee32d12a
| 255 |
//
// NetworkClient.swift
//
// Created by Nixon Shih on 2020/8/22.
//
import Foundation
import RxSwift
public protocol NetworkClient {
func fetchDataModel<Request>(request: Request) -> Observable<Request.Response> where Request: NetworkRequest
}
| 19.615385 | 112 | 0.74902 |
48f4471ddd043e58d93877c5a8b7dc37b9a23d29
| 4,303 |
// Copyright 2020 Penguin Authors
//
// 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
@testable import PenguinTables
final class IndexSetTests: XCTestCase {
func testInitializer() {
let s = PIndexSet(indices: [1, 4, 8], count: 10)
XCTAssertEqual(
s,
PIndexSet(
[
false,
true,
false,
false,
true,
false,
false,
false,
true,
false,
],
setCount: 3))
}
func testUnion() {
let lhs = PIndexSet([true, false, false, true], setCount: 2)
let rhs = PIndexSet([true, true, false, false], setCount: 2)
let expected = PIndexSet([true, true, false, true], setCount: 3)
XCTAssertEqual(try! lhs.unioned(rhs), expected)
}
func testUnionExtension() {
let lhs = PIndexSet([true, false, true, false], setCount: 2)
let rhs = PIndexSet([true, true], setCount: 2)
let expected = PIndexSet([true, true, true, false], setCount: 3)
XCTAssertEqual(try! lhs.unioned(rhs, extending: true), expected)
XCTAssertEqual(try! rhs.unioned(lhs, extending: true), expected)
}
func testIntersect() {
let lhs = PIndexSet([true, false, false, true], setCount: 2)
let rhs = PIndexSet([true, true, false, false], setCount: 2)
let expected = PIndexSet([true, false, false, false], setCount: 1)
XCTAssertEqual(try! lhs.intersected(rhs), expected)
}
func testIntersectExtension() {
let lhs = PIndexSet([true, false, true, false], setCount: 2)
let rhs = PIndexSet([true, true], setCount: 2)
let expected = PIndexSet([true, false, false, false], setCount: 1)
XCTAssertEqual(try! lhs.intersected(rhs, extending: true), expected)
XCTAssertEqual(try! rhs.intersected(lhs, extending: true), expected)
}
func testNegate() {
let s = PIndexSet([true, false, true, false, false], setCount: 2)
let expected = PIndexSet([false, true, false, true, true], setCount: 3)
XCTAssertEqual(!s, expected)
}
func testIsEmpty() {
XCTAssertTrue(PIndexSet([false, false, false], setCount: 0).isEmpty)
XCTAssertFalse(PIndexSet([true, false], setCount: 1).isEmpty)
}
func testAllInitializer() {
XCTAssertEqual(PIndexSet(all: true, count: 2), PIndexSet([true, true], setCount: 2))
XCTAssertEqual(PIndexSet(all: false, count: 3), PIndexSet([false, false, false], setCount: 0))
}
func testSorting() {
let indices = [2, 3, 1, 0]
XCTAssertEqual(
PIndexSet([true, false, true, false], setCount: 2).gathering(indices),
PIndexSet([true, false, false, true], setCount: 2))
}
func testEmptyInit() {
let s = PIndexSet(empty: false)
XCTAssertEqual(0, s.setCount)
XCTAssertEqual([], s.impl)
}
func testAppend() {
var s = PIndexSet(empty: false)
s.append(false)
s.append(true)
s.append(false)
s.append(true)
let expected = PIndexSet([false, true, false, true], setCount: 2)
XCTAssertEqual(expected, s)
}
func testIndexIterator() {
let s = PIndexSet([true, false, false, true, false, true, false], setCount: 3)
var itr = s.makeIndexIterator()
XCTAssertEqual(0, itr.next())
XCTAssertEqual(3, itr.next())
XCTAssertEqual(5, itr.next())
XCTAssertEqual(nil, itr.next())
}
static var allTests = [
("testInitializer", testInitializer),
("testUnion", testUnion),
("testUnionExtension", testUnionExtension),
("testIntersect", testIntersect),
("testIntersectExtension", testIntersectExtension),
("testNegate", testNegate),
("testIsEmpty", testIsEmpty),
("testAllInitializer", testAllInitializer),
("testSorting", testSorting),
("testEmptyInit", testEmptyInit),
("testAppend", testAppend),
("testIndexIterator", testIndexIterator),
]
}
| 31.874074 | 98 | 0.657216 |
56dae96f38209f88781a693ed50120cf1ebcd821
| 1,291 |
//
// Quickly
//
public class QFieldForm : IQFieldForm {
public private(set) var fields: [IQField]
public private(set) var isValid: Bool
private var _observer: QObserver< IQFieldFormObserver >
public init() {
self.fields = []
self.isValid = false
self._observer = QObserver< IQFieldFormObserver >()
}
public func add(observer: IQFieldFormObserver) {
self._observer.add(observer, priority: 0)
}
public func remove(observer: IQFieldFormObserver) {
self._observer.remove(observer)
}
public func add(field: IQField) {
if self.fields.contains(where: { return $0 === field }) == false {
self.fields.append(field)
}
}
public func remove(field: IQField) {
if let index = self.fields.firstIndex(where: { return $0 === field }) {
self.fields.remove(at: index)
}
}
public func validation() {
let invalids = self.fields.filter({ return $0.isValid == false })
let isValid = (self.fields.count > 0) && (invalids.count == 0)
if self.isValid != isValid {
self.isValid = isValid
self._observer.notify({ $0.fieldForm(self, isValid: isValid) })
}
}
}
| 26.895833 | 79 | 0.577072 |
f4bfc188639279522448f0e98dd34d867152a720
| 228 |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
protocol C {
class A {
let a {
func a( = {
class
case c,
| 19 | 87 | 0.723684 |
629d5b7e8998d2990a8f327ff0be08e5838e1a64
| 5,836 |
/*
This source file is part of the Swift.org open source project
Copyright (c) 2018 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/// A version according to the semantic versioning specification.
///
/// A package version is a three period-separated integer, for example `1.0.0`. It must conform to the semantic versioning standard in order to ensure
/// that your package behaves in a predictable manner once developers update their
/// package dependency to a newer version. To achieve predictability, the semantic versioning specification proposes a set of rules and
/// requirements that dictate how version numbers are assigned and incremented. To learn more about the semantic versioning specification, visit
/// [semver.org](www.semver.org).
///
/// **The Major Version**
///
/// The first digit of a version, or *major version*, signifies breaking changes to the API that require
/// updates to existing clients. For example, the semantic versioning specification
/// considers renaming an existing type, removing a method, or changing a method's signature
/// breaking changes. This also includes any backward-incompatible bug fixes or
/// behavioral changes of the existing API.
///
/// **The Minor Version**
//
/// Update the second digit of a version, or *minor version*, if you add functionality in a backward-compatible manner.
/// For example, the semantic versioning specification considers adding a new method
/// or type without changing any other API to be backward-compatible.
///
/// **The Patch Version**
///
/// Increase the third digit of a version, or *patch version*, if you are making a backward-compatible bug fix.
/// This allows clients to benefit from bugfixes to your package without incurring
/// any maintenance burden.
///
public struct Version {
/// The major version according to the semantic versioning standard.
public let major: Int
/// The minor version according to the semantic versioning standard.
public let minor: Int
/// The patch version according to the semantic versioning standard.
public let patch: Int
/// The pre-release identifier according to the semantic versioning standard, such as `-beta.1`.
public let prereleaseIdentifiers: [String]
/// The build metadata of this version according to the semantic versioning standard, such as a commit hash.
public let buildMetadataIdentifiers: [String]
/// Initializes and returns a newly allocated version struct
/// for the provided components of a semantic version.
///
/// - Parameters:
/// - major: The major version numner.
/// - minor: The minor version number.
/// - patch: The patch version number.
/// - prereleaseIdentifiers: The pre-release identifier.
/// - buildMetaDataIdentifiers: Build metadata that identifies a build.
public init(
_ major: Int,
_ minor: Int,
_ patch: Int,
prereleaseIdentifiers: [String] = [],
buildMetadataIdentifiers: [String] = []
) {
precondition(major >= 0 && minor >= 0 && patch >= 0, "Negative versioning is invalid.")
self.major = major
self.minor = minor
self.patch = patch
self.prereleaseIdentifiers = prereleaseIdentifiers
self.buildMetadataIdentifiers = buildMetadataIdentifiers
}
}
extension Version: Comparable {
public static func < (lhs: Version, rhs: Version) -> Bool {
let lhsComparators = [lhs.major, lhs.minor, lhs.patch]
let rhsComparators = [rhs.major, rhs.minor, rhs.patch]
if lhsComparators != rhsComparators {
return lhsComparators.lexicographicallyPrecedes(rhsComparators)
}
guard lhs.prereleaseIdentifiers.count > 0 else {
return false // Non-prerelease lhs >= potentially prerelease rhs
}
guard rhs.prereleaseIdentifiers.count > 0 else {
return true // Prerelease lhs < non-prerelease rhs
}
let zippedIdentifiers = zip(lhs.prereleaseIdentifiers, rhs.prereleaseIdentifiers)
for (lhsPrereleaseIdentifier, rhsPrereleaseIdentifier) in zippedIdentifiers {
if lhsPrereleaseIdentifier == rhsPrereleaseIdentifier {
continue
}
let typedLhsIdentifier: Any = Int(lhsPrereleaseIdentifier) ?? lhsPrereleaseIdentifier
let typedRhsIdentifier: Any = Int(rhsPrereleaseIdentifier) ?? rhsPrereleaseIdentifier
switch (typedLhsIdentifier, typedRhsIdentifier) {
case let (int1 as Int, int2 as Int): return int1 < int2
case let (string1 as String, string2 as String): return string1 < string2
case (is Int, is String): return true // Int prereleases < String prereleases
case (is String, is Int): return false
default:
return false
}
}
return lhs.prereleaseIdentifiers.count < rhs.prereleaseIdentifiers.count
}
}
extension Version: CustomStringConvertible {
/// A textual description of the version object.
public var description: String {
var base = "\(major).\(minor).\(patch)"
if !prereleaseIdentifiers.isEmpty {
base += "-" + prereleaseIdentifiers.joined(separator: ".")
}
if !buildMetadataIdentifiers.isEmpty {
base += "+" + buildMetadataIdentifiers.joined(separator: ".")
}
return base
}
}
extension Version: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(description)
}
}
| 41.098592 | 150 | 0.684202 |
90d32d856584b0a130e6bb72a6c6cecd817b918b
| 2,297 |
//
// TableViewController.swift
// FlagPhoneNumber_Example
//
// Created by Aurelien on 24/12/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
import FlagPhoneNumber
class TableViewController: UITableViewController {
@IBOutlet weak var firstPhoneNumberTextField: FPNTextField!
@IBOutlet weak var secondPhoneNumberTextField: FPNTextField!
var listController: FPNCountryListViewController = FPNCountryListViewController(style: .grouped)
var repository: FPNCountryRepository = FPNCountryRepository()
override func viewDidLoad() {
super.viewDidLoad()
title = "In Table View"
tableView.delaysContentTouches = false
firstPhoneNumberTextField.displayMode = .picker
firstPhoneNumberTextField.delegate = self
secondPhoneNumberTextField.displayMode = .list
secondPhoneNumberTextField.delegate = self
listController.setup(repository: secondPhoneNumberTextField.countryRepository)
listController.didSelect = { [weak self] country in
self?.secondPhoneNumberTextField.setFlag(countryCode: country.code)
}
}
@objc func dismissCountries() {
listController.dismiss(animated: true, completion: nil)
}
}
extension TableViewController: FPNTextFieldDelegate {
func fpnDisplayCountryList() {
let navigationViewController = UINavigationController(rootViewController: listController)
listController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(dismissCountries))
self.present(navigationViewController, animated: true, completion: nil)
}
func fpnDidValidatePhoneNumber(textField: FPNTextField, isValid: Bool) {
textField.rightViewMode = .always
textField.rightView = UIImageView(image: isValid ? #imageLiteral(resourceName: "success") : #imageLiteral(resourceName: "error"))
print(
isValid,
textField.getFormattedPhoneNumber(format: .E164) ?? "E164: nil",
textField.getFormattedPhoneNumber(format: .International) ?? "International: nil",
textField.getFormattedPhoneNumber(format: .National) ?? "National: nil",
textField.getFormattedPhoneNumber(format: .RFC3966) ?? "RFC3966: nil",
textField.getRawPhoneNumber() ?? "Raw: nil"
)
}
func fpnDidSelectCountry(name: String, dialCode: String, code: String) {
print(name, dialCode, code)
}
}
| 31.902778 | 146 | 0.78276 |
75dd7fa5cd4c4533e38e1ea3a73687258156b8dd
| 1,755 |
// The MIT License (MIT)
//
// Copyright (c) 2015 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 UIKit
private var b_refreshing_key = 0
public extension UIRefreshControl {
var b_refreshing: BindableProperty<UIRefreshControl, Bool> {
associatedObjectProperty(self, &b_refreshing_key) { _ in
BindableProperty(self, setter: { control, value in
switch (control.isRefreshing, value) {
case (false, true):
control.beginRefreshing()
case (true, false):
control.endRefreshing()
default:
break
}
})
}
}
}
| 39 | 81 | 0.674644 |
de7cd14e00793f9b7207d681883e9af3337843e6
| 17,894 |
//
// Response.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/// Used to store all data associated with a serialized response of a data or upload request.
public struct DataResponse<Value> {
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The data returned by the server.
public let data: Data?
/// The final metrics of the response.
public let metrics: URLSessionTaskMetrics?
/// The time taken to serialize the response.
public let serializationDuration: TimeInterval
/// The result of response serialization.
public let result: Result<Value>
/// Returns the associated value of the result if it is a success, `nil` otherwise.
public var value: Value? { return result.value }
/// Returns the associated error value if the result if it is a failure, `nil` otherwise.
public var error: Error? { return result.error }
/// Creates a `DataResponse` instance with the specified parameters derviced from the response serialization.
///
/// - Parameters:
/// - request: The `URLRequest` sent to the server.
/// - response: The `HTTPURLResponse` from the server.
/// - data: The `Data` returned by the server.
/// - metrics: The `URLSessionTaskMetrics` of the serialized response.
/// - serializationDuration: The duration taken by serialization.
/// - result: The `Result` of response serialization.
public init(request: URLRequest?,
response: HTTPURLResponse?,
data: Data?,
metrics: URLSessionTaskMetrics?,
serializationDuration: TimeInterval,
result: Result<Value>) {
self.request = request
self.response = response
self.data = data
self.metrics = metrics
self.serializationDuration = serializationDuration
self.result = result
}
}
// MARK: -
extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
public var description: String {
return result.debugDescription
}
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
/// response, the server data, the duration of the network and serializatino actions, and the response serialization
/// result.
public var debugDescription: String {
let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil"
let responseDescription = response.map { (response) in
let headers = response.allHeaderFields as! HTTPHeaders
let keys = headers.keys.sorted(by: >)
let sortedHeaders = keys.map { "\($0): \(headers[$0]!)" }.joined(separator: "\n")
return """
Status Code: \(response.statusCode)
Headers: \(sortedHeaders)
"""
} ?? "nil"
let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
return """
[Request]: \(requestDescription)
[Response]: \(responseDescription)
[Data]: \(data?.description ?? "None")
[Network Duration]: \(metricsDescription)
[Serialization Duration]: \(serializationDuration)s
[Result]: \(result.debugDescription)
"""
}
}
// MARK: -
extension DataResponse {
/// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped
/// result value as a parameter.
///
/// Use the `map` method with a closure that does not throw. For example:
///
/// let possibleData: DataResponse<Data> = ...
/// let possibleInt = possibleData.map { $0.count }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's
/// result is a failure, returns a response wrapping the same failure.
public func map<T>(_ transform: (Value) -> T) -> DataResponse<T> {
return DataResponse<T>(request: request,
response: self.response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.map(transform))
}
/// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result
/// value as a parameter.
///
/// Use the `flatMap` method with a closure that may throw an error. For example:
///
/// let possibleData: DataResponse<Data> = ...
/// let possibleObject = possibleData.flatMap {
/// try JSONSerialization.jsonObject(with: $0)
/// }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's
/// result is a failure, returns the same failure.
public func flatMap<T>(_ transform: (Value) throws -> T) -> DataResponse<T> {
return DataResponse<T>(request: request,
response: self.response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.flatMap(transform))
}
/// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `mapError` function with a closure that does not throw. For example:
///
/// let possibleData: DataResponse<Data> = ...
/// let withMyError = possibleData.mapError { MyError.error($0) }
///
/// - Parameter transform: A closure that takes the error of the instance.
/// - Returns: A `DataResponse` instance containing the result of the transform.
public func mapError<E: Error>(_ transform: (Error) -> E) -> DataResponse {
return DataResponse(request: request,
response: self.response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.mapError(transform))
}
/// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `flatMapError` function with a closure that may throw an error. For example:
///
/// let possibleData: DataResponse<Data> = ...
/// let possibleObject = possibleData.flatMapError {
/// try someFailableFunction(taking: $0)
/// }
///
/// - Parameter transform: A throwing closure that takes the error of the instance.
///
/// - Returns: A `DataResponse` instance containing the result of the transform.
public func flatMapError<E: Error>(_ transform: (Error) throws -> E) -> DataResponse {
return DataResponse(request: request,
response: self.response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.flatMapError(transform))
}
}
// MARK: -
/// Used to store all data associated with a serialized response of a download request.
public struct DownloadResponse<Value> {
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The temporary destination URL of the data returned from the server.
public let temporaryURL: URL?
/// The final destination URL of the data returned from the server if it was moved.
public let destinationURL: URL?
/// The resume data generated if the request was cancelled.
public let resumeData: Data?
/// The final metrics of the response.
public let metrics: URLSessionTaskMetrics?
/// The time taken to serialize the response.
public let serializationDuration: TimeInterval
/// The result of response serialization.
public let result: Result<Value>
/// Returns the associated value of the result if it is a success, `nil` otherwise.
public var value: Value? { return result.value }
/// Returns the associated error value if the result if it is a failure, `nil` otherwise.
public var error: Error? { return result.error }
/// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
///
/// - Parameters:
/// - request: The `URLRequest` sent to the server.
/// - response: The `HTTPURLResponse` from the server.
/// - temporaryURL: The temporary destinatio `URL` of the data returned from the server.
/// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved.
/// - resumeData: The resume `Data` generated if the request was cancelled.
/// - metrics: The `URLSessionTaskMetrics` of the serialized response.
/// - serializationDuration: The duration taken by serialization.
/// - result: The `Result` of response serialization.
public init(
request: URLRequest?,
response: HTTPURLResponse?,
temporaryURL: URL?,
destinationURL: URL?,
resumeData: Data?,
metrics: URLSessionTaskMetrics?,
serializationDuration: TimeInterval,
result: Result<Value>)
{
self.request = request
self.response = response
self.temporaryURL = temporaryURL
self.destinationURL = destinationURL
self.resumeData = resumeData
self.metrics = metrics
self.serializationDuration = serializationDuration
self.result = result
}
}
// MARK: -
extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
public var description: String {
return result.debugDescription
}
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
/// response, the temporary and destination URLs, the resume data, the durations of the network and serialization
/// actions, and the response serialization result.
public var debugDescription: String {
let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil"
let responseDescription = response.map { (response) in
let headers = response.allHeaderFields as! HTTPHeaders
let keys = headers.keys.sorted(by: >)
let sortedHeaders = keys.map { "\($0): \(headers[$0]!)" }.joined(separator: "\n")
return """
Status Code: \(response.statusCode)
Headers: \(sortedHeaders)
"""
} ?? "nil"
let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
let resumeDataDescription = resumeData.map { "\($0)" } ?? "None"
return """
[Request]: \(requestDescription)
[Response]: \(responseDescription)
[TemporaryURL]: \(temporaryURL?.path ?? "nil")
[DestinationURL]: \(destinationURL?.path ?? "nil")
[ResumeData]: \(resumeDataDescription)
[Network Duration]: \(metricsDescription)
[Serialization Duration]: \(serializationDuration)s
[Result]: \(result.debugDescription)
"""
}
}
// MARK: -
extension DownloadResponse {
/// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
/// result value as a parameter.
///
/// Use the `map` method with a closure that does not throw. For example:
///
/// let possibleData: DownloadResponse<Data> = ...
/// let possibleInt = possibleData.map { $0.count }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's
/// result is a failure, returns a response wrapping the same failure.
public func map<T>(_ transform: (Value) -> T) -> DownloadResponse<T> {
return DownloadResponse<T>(
request: request,
response: self.response,
temporaryURL: temporaryURL,
destinationURL: destinationURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.map(transform)
)
}
/// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
/// result value as a parameter.
///
/// Use the `flatMap` method with a closure that may throw an error. For example:
///
/// let possibleData: DownloadResponse<Data> = ...
/// let possibleObject = possibleData.flatMap {
/// try JSONSerialization.jsonObject(with: $0)
/// }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this
/// instance's result is a failure, returns the same failure.
public func flatMap<T>(_ transform: (Value) throws -> T) -> DownloadResponse<T> {
return DownloadResponse<T>(
request: request,
response: self.response,
temporaryURL: temporaryURL,
destinationURL: destinationURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.flatMap(transform)
)
}
/// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `mapError` function with a closure that does not throw. For example:
///
/// let possibleData: DownloadResponse<Data> = ...
/// let withMyError = possibleData.mapError { MyError.error($0) }
///
/// - Parameter transform: A closure that takes the error of the instance.
/// - Returns: A `DownloadResponse` instance containing the result of the transform.
public func mapError<E: Error>(_ transform: (Error) -> E) -> DownloadResponse {
return DownloadResponse(
request: request,
response: self.response,
temporaryURL: temporaryURL,
destinationURL: destinationURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.mapError(transform)
)
}
/// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `flatMapError` function with a closure that may throw an error. For example:
///
/// let possibleData: DownloadResponse<Data> = ...
/// let possibleObject = possibleData.flatMapError {
/// try someFailableFunction(taking: $0)
/// }
///
/// - Parameter transform: A throwing closure that takes the error of the instance.
///
/// - Returns: A `DownloadResponse` instance containing the result of the transform.
public func flatMapError<E: Error>(_ transform: (Error) throws -> E) -> DownloadResponse {
return DownloadResponse(
request: request,
response: self.response,
temporaryURL: temporaryURL,
destinationURL: destinationURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.flatMapError(transform)
)
}
}
| 43.750611 | 125 | 0.630044 |
181ef0cd11107d9119e4aeddb8035226eb701ff2
| 2,050 |
//
// json-functions-swift
//
// Parts of this file are copied from file
// https://github.com/eu-digital-green-certificates/json-logic-swift/blob/master/Sources/jsonlogic/Parser.swift
// in forked Repository
// https://github.com/eu-digital-green-certificates/json-logic-swift
//
// Parser.swift
// jsonlogic
//
// Created by Christos Koninis on 16/06/2018.
// Licensed under MIT
//
// Modifications Copyright (c) 2022 SAP SE or an SAP affiliate company
//
import Foundation
public let optionalPrefix = "URN:UVCI:"
struct ExtractFromUVCI: Expression {
let expression: Expression
func eval(with data: inout JSON) throws -> JSON {
let result = try expression.eval(with: &data)
if let arr = result.array,
let uvci = arr[0]["data"].string,
let index = arr[1].int
{
guard let extractedUVCI = fromUVCI(uvci: uvci, index: Int(index)) else {
return .Null
}
return JSON(extractedUVCI)
}
if let arr = result.array,
let uvci = arr[0].string,
let index = arr[1].int
{
guard let extractedUVCI = fromUVCI(uvci: uvci, index: Int(index)) else {
return .Null
}
return JSON(extractedUVCI)
}
return .Null
}
}
/**
* @returns The fragment with given index from the UVCI string
* (see Annex 2 in the [UVCI specification](https://ec.europa.eu/health/sites/default/files/ehealth/docs/vaccination-proof_interoperability-guidelines_en.pdf)),
* or `null` when that fragment doesn't exist.
*/
func fromUVCI(uvci: String?, index: Int) -> String? {
guard let uvci = uvci, index >= 0 else {
return nil
}
let prefixlessUvci = uvci.starts(with: optionalPrefix) ? uvci.substring(from: optionalPrefix.count) : uvci
let separators = CharacterSet(charactersIn: "/#:")
let fragments = prefixlessUvci.components(separatedBy: separators)
return index < fragments.count ? fragments[index] : nil
}
| 28.472222 | 161 | 0.634146 |
c1b27e3c6a4893282cfa756161e3a54d6a23295e
| 2,264 |
import Foundation
import UIKit
final class ToMiniAnimator: NSObject, UIViewControllerAnimatedTransitioning {
private let destinationFrame: CGRect
init(destinationFrame: CGRect) {
self.destinationFrame = destinationFrame
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 1.0
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fullScreenVC = transitionContext.viewController(forKey: .from) as? FullScreenViewController,
let parentVC = transitionContext.viewController(forKey: .to) as? ParentViewController else {
return
}
guard let miniPlayerView = parentVC.miniViewController.view else { return }
guard let parentSnapshot = parentVC.view.snapshotView(afterScreenUpdates: true) else { return }
let containerView = transitionContext.containerView
parentSnapshot.frame = destinationFrame
parentSnapshot.alpha = 0.75
containerView.addSubview(parentSnapshot)
parentVC.view.isHidden = true
let duration = transitionDuration(using: transitionContext)
UIView.animateKeyframes(
withDuration: duration,
delay: 0,
options: .calculationModeCubic,
animations: {
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 1/3) {
parentSnapshot.alpha = 0.75
}
UIView.addKeyframe(withRelativeStartTime: 1/3, relativeDuration: 1/3) {
parentSnapshot.alpha = 0.5
}
UIView.addKeyframe(withRelativeStartTime: 2/3, relativeDuration: 1/3) {
parentSnapshot.alpha = 0
}
},
completion: { _ in
parentSnapshot.removeFromSuperview()
miniPlayerView.alpha = 1
parentVC.view.isHidden = false
if transitionContext.transitionWasCancelled {
parentVC.view.removeFromSuperview()
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
| 35.375 | 110 | 0.641343 |
3382e0d4b7453d329f8409b8f2ca7bf102778eac
| 1,366 |
//
// AppDelegate.swift
// SwiftUIBankCardAnimation2
//
// Created by Luan Nguyen on 03/01/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.918919 | 179 | 0.748902 |
0a7066a00089af136ff0332050387d5d3d1cc70e
| 5,874 |
import Foundation
/// Witness for the `Tree<A>` data type. To be used in simulated Higher Kinded Types.
public final class ForTree {}
/// Partial application of the Tree type constructor, omitting the last type parameter.
public typealias TreePartial = ForTree
/// Higher Kinded Type alias to improve readability over `Kind<ForTree, A>`.
public typealias TreeOf<A> = Kind<ForTree, A>
/// `Tree` represents a non-empty tree that allows node to have an arbitrary number of children.
///
/// The `Foldable` instance walks through the tree in depth-first order.
public final class Tree<A>: TreeOf<A> {
public let root: A
public let subForest: [Tree<A>]
/// Safe downcast.
///
/// - Parameter fa: Value in higher-kind form.
/// - Returns: Value cast to Tree.
public static func fix(_ fa: TreeOf<A>) -> Tree<A> {
fa as! Tree<A>
}
/// Initializes a tree.
///
/// - Parameters:
/// - head: First element for the array.
/// - tail: An array with the rest of elements.
public init(root: A, subForest: [Tree<A>]) {
self.root = root
self.subForest = subForest
}
/// Adds a tree as a subtree of `self`.
///
/// The root of `tree` will be place directly under the root of `self`.
///
/// - Parameter tree: The tree to add under `self.root`.
/// - Returns: A tree with the same elements as self with `tree` added as subtree.
public func appendSubTree(_ tree: Tree<A>) -> Tree<A> {
appendSubForest([tree])
}
/// Adds a collection of trees as subtrees of `self`.
///
/// The root of each subtree will be place directly under the root of `self`.
///
/// - Parameter subForest: A collection of trees to add under `self.root`
/// - Returns: A tree with the same elements as self with the trees of `subForest` added as subtrees.
public func appendSubForest(_ subForest: [Tree<A>]) -> Tree<A> {
Tree(root: root, subForest: self.subForest + subForest)
}
}
/// Safe downcast.
///
/// - Parameter fa: Value in higher-kind form.
/// - Returns: Value cast to Tree.
public postfix func ^<A>(_ fa: TreeOf<A>) -> Tree<A> {
Tree.fix(fa)
}
// MARK: Instance of EquatableK for Tree
extension TreePartial: EquatableK {
public static func eq<A>(_ lhs: TreeOf<A>, _ rhs: TreeOf<A>) -> Bool where A : Equatable {
lhs^.root == rhs^.root && lhs^.subForest == rhs^.subForest
}
}
// MARK: Instance of HashableK for Tree
extension TreePartial: HashableK {
public static func hash<A>(_ fa: TreeOf<A>, into hasher: inout Hasher) where A : Hashable {
hasher.combine(fa^.root)
hasher.combine(fa^.subForest)
}
}
// MARK: Instance of Functor for Tree
extension TreePartial: Functor {
public static func map<A, B>(
_ fa: TreeOf<A>,
_ f: @escaping (A) -> B) -> TreeOf<B> {
Tree(root: f(fa^.root),
subForest: fa^.subForest.map { TreePartial.map($0, f)^ })
}
}
// MARK: Instance of Applicative for Tree
extension TreePartial: Applicative {
public static func pure<A>(_ a: A) -> TreeOf<A> {
Tree(root: a, subForest: [])
}
public static func ap<A, B>(_ functionTree: TreeOf<(A) -> B>, _ elementsTree: TreeOf<A>) -> TreeOf<B> {
let functionTree = functionTree^
let elementsTree = elementsTree^
return Tree(root: functionTree.root(elementsTree.root),
subForest: elementsTree.subForest.map { TreePartial.map($0, functionTree.root)^ }
+ functionTree.subForest.map { TreePartial.ap($0, elementsTree)^ })
}
}
// MARK: Instance of Selective for Tree
extension TreePartial: Selective {}
// MARK: Instance of Monad for Tree
extension TreePartial: Monad {
public static func flatMap<A, B>(_ fa: TreeOf<A>, _ f: @escaping (A) -> TreeOf<B>) -> TreeOf<B> {
f(fa^.root)^.appendSubForest(
fa^.subForest.map { TreePartial.flatMap($0, f)^ }
)
}
public static func tailRecM<A, B>(_ a: A, _ f: @escaping (A) -> TreeOf<Either<A, B>>) -> TreeOf<B> {
let f = { f($0)^ }
return loop(f(a), f).run()
}
private static func loop<A, B>(_ a: TreeOf<Either<A, B>>, _ f: @escaping (A) -> TreeOf<Either<A, B>>) -> Trampoline<TreeOf<B>> {
.defer {
let fLiftedToEither: (Either<A, B>) -> Trampoline<TreeOf<B>> = { e in
e.fold({ a in
loop(f(a), f)
}) { b in
.done(.pure(b))
}
}
let rootImageTrampoline = fLiftedToEither(a^.root)
let subForestImageTrampoline = a^.subForest.traverse { loop($0, f) }^
return .map(rootImageTrampoline, subForestImageTrampoline) { (rootImage, subForestImage) in
rootImage^.appendSubForest(subForestImage.map { $0^ })
}^
}
}
}
// MARK: Instance of Foldable for Tree
extension TreePartial: Foldable {
public static func foldLeft<A, B>(_ fa: Kind<ForTree, A>, _ b: B, _ f: @escaping (B, A) -> B) -> B {
fa^.subForest.foldLeft(f(b, fa^.root)) { (bPartial, tree) in
foldLeft(tree, bPartial, f)
}
}
public static func foldRight<A, B>(_ fa: Kind<ForTree, A>, _ b: Eval<B>, _ f: @escaping (A, Eval<B>) -> Eval<B>) -> Eval<B> {
fa^.subForest.foldRight(f(fa^.root, b)) { (tree, bPartial) -> Eval<B> in
foldRight(tree, bPartial, f)
}
}
}
// MARK: Instance of Traverse for Tree
extension TreePartial: Traverse {
public static func traverse<G, A, B>(_ fa: TreeOf<A>, _ f: @escaping (A) -> Kind<G, B>) -> Kind<G, TreeOf<B>> where G : Applicative {
let liftedRoot = f(fa^.root)
let liftedSubForest = fa^.subForest.traverse { t in t.traverse(f).map { $0^ } }
return G.map(liftedRoot, liftedSubForest, Tree.init)
}
}
| 35.817073 | 137 | 0.601464 |
141f8b996d3633a5ec69a078d4af746b3c30b1fc
| 4,623 |
//
// USBInstrument.swift
// SwiftVISA
//
// Created by Connor Barnes on 5/30/19.
// Copyright © 2019 SwiftVISA. All rights reserved.
//
import CVISA
public final class USBInstrument: MessageBasedInstrument, InstrumentProtocol {
static var _events: [UInt] = [VI_EVENT_SERVICE_REQ, VI_EVENT_USB_INTR]
var _lockState: LockState
public var bufferSize: Int
public var buffer: UnsafeMutableRawBufferPointer
public var session: Session
public var identifier: String
public var timeout: TimeInterval
// public var delegate: InstrumentDelegate?
public var dispatchQueue: DispatchQueue
public init(session: Session, identifier: String) {
bufferSize = 20480
buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: bufferSize, alignment: 4096)
self.session = session
self.identifier = identifier
_lockState = .unlocked
timeout = 5.0
dispatchQueue = DispatchQueue(label: identifier, qos: .userInitiated)
}
/// Performs a USB control pipe transfer from the device
/// This operation is intended for people familiar with the USB Protocol
/// and assumes that you will do buffer management yourself
/// - Parameters:
/// - requestType: bmRequestType; Bitmap specifying the request type in the USB standard
/// - requestId: bRequest of setup stage in the USB standard
/// - requestValue: wValue param of setup stage in the USB standard
/// - index: wIndex parameter of setup stage in the USB standard (typically index of interface or endpoint)
/// - length: wLength parameter of setup stage in the USB standard; also specifies the amount of data elements to receive data from optional data stage of the control transfer
/// - Return: The data buffer received from the optional data stage of the control transfer
public func usb_control_in(requestType: Int16, requestId: Int16, requestValue: UInt16, index: UInt16, length: UInt16) throws -> Data {
#warning("not tested")
let returnCountBuffer = UnsafeMutablePointer<ViUInt16>.allocate(capacity: 1)
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(length))
// nil return count should really be converted to VI_NULL, but the types don't match
let status = viUsbControlIn(session.viSession, requestType, requestId, requestValue, index, length, buffer, returnCountBuffer)
if status < VI_SUCCESS {
throw VISAError(status)
}
let result = Data(bytes: buffer, count: Int(returnCountBuffer.pointee))
// todo I don't know enough about the USB standard to know if we should unpack the data from the buffer ourselves
return result
}
/// Performs a USB control pipe transfer from the device
/// This operation is intended for people familiar with the USB Protocol
/// and assumes that you will do buffer management yourself
/// - Parameters:
/// - requestType: bmRequestType; Bitmap specifying the request type in the USB standard
/// - requestId: bRequest of setup stage in the USB standard
/// - requestValue: wValue param of setup stage in the USB standard
/// - index: wIndex parameter of setup stage in the USB standard (typically index of interface or endpoint)
/// - length: wLength parameter of setup stage in the USB standard; also specifies the size of the data buffer to send from optional data stage of the control transfer
/// - buffer: data buffer that sends data from the optional data stage of the control transfer. Ignored if length is 0.
/// - Returns: The data buffer that sends the data from the optional data stage of the control transfer.
public func usb_control_out(requestType: Int16, requestId: Int16, requestValue: UInt16, index: UInt16, length: UInt16) throws -> Data {
#warning("not tested")
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(length))
let result = Data(bytes: buffer, count: Int(length))
let status = viUsbControlOut(session.viSession, requestType, requestId, requestValue, index, length, buffer)
if status < VI_SUCCESS {
throw VISAError(status)
}
// todo same note as usb_control in on if we should unpack data
return result
}
public func getProductID() throws -> UInt16 {
return try getAttribute(VI_ATTR_MODEL_CODE, as: UInt16.self)
}
public func getModelName() throws -> String {
return try getAttribute(VI_ATTR_MODEL_NAME, as: String.self)
}
public func getIs4882Compliant() throws -> Bool {
return try getAttribute(VI_ATTR_4882_COMPLIANT, as: Bool.self)
}
}
| 46.23 | 181 | 0.720311 |
dd8ed0af28994f81a4690ca64343d863b8b53329
| 1,913 |
//
// View2.swift
// TopBarMenu
//
// Created by ibrahim on 11/22/16.
// Copyright © 2016 Indosytem. All rights reserved.
//
import UIKit
class View2 : UIView {
@IBOutlet weak var tableView: UITableView!
var contentView : UIView?
var cellIdentifier:String = "view2Cell"
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
// additional option
// use defined table nib, doesnt work in swift 3
//let nibName = UINib(nibName: "InvitationTableViewCell", bundle: nil)
//tableView.register(nibName, forCellReuseIdentifier: cellIdentifier)
// setting up table row
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100.0
tableView.autoresizingMask = UIViewAutoresizing.flexibleBottomMargin
// don't show table separator
//tableView.separatorStyle = UITableViewCellSeparatorStyle.None
}
func xibSetup() {
contentView = loadViewFromNib()
// use bounds not frame or it'll be offset
contentView!.frame = bounds
// Make the view stretch with containing view
contentView!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(contentView!)
}
func loadViewFromNib() -> UIView! {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
}
| 28.984848 | 109 | 0.619969 |
56b76ac5b0714628f00ecc9230e7be3959c5eabf
| 2,663 |
/*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
class ProductTableViewController: UITableViewController, DataStoreOwner, IAPContainer {
var dataStore : DataStore? {
didSet {
tableView.reloadData()
}
}
var iapHelper : IAPHelper?
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataStore?.products.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell", forIndexPath: indexPath)
if let cell = cell as? ProductTableViewCell {
cell.product = dataStore?.products[indexPath.row]
}
return cell
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let destVC = segue.destinationViewController as? ProductViewController {
let selectedRow = tableView.indexPathForSelectedRow?.row ?? 0
destVC.product = dataStore?.products[selectedRow]
}
}
}
extension ProductTableViewController {
@IBAction func handleRestorePurchasesPressed(sender: AnyObject) {
// TODO: Provide an implemention to make payment restoration work
}
}
| 32.876543 | 116 | 0.735637 |
0ea64be7557f58478dcb8200a5aaeed54a9ec002
| 1,965 |
//
// DividerView.swift
// KVKCalendar
//
// Created by Sergei Kviatkovskii on 18.07.2021.
//
#if os(iOS)
import UIKit
final class DividerView: UIView {
private var style: Style
private lazy var timeLabel: UILabel = {
let label = UILabel()
label.textColor = style.timeline.timeDividerColor
label.font = style.timeline.timeDividerFont
label.textAlignment = .right
return label
}()
private lazy var lineView: UIView = {
let view = UIView()
view.backgroundColor = style.timeline.timeDividerColor
return view
}()
var txt: String? {
didSet {
timeLabel.text = txt
}
}
init(style: Style, frame: CGRect) {
self.style = style
super.init(frame: frame)
setUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension DividerView: CalendarSettingProtocol {
var currentStyle: Style {
style
}
func reloadFrame(_ frame: CGRect) {
subviews.forEach({ $0.removeFromSuperview() })
self.frame = frame
setUI()
}
func updateStyle(_ style: Style) {
self.style = style
}
func setUI() {
timeLabel.frame = CGRect(x: style.timeline.offsetTimeX,
y: 0,
width: style.timeline.widthTime,
height: style.timeline.heightTime)
let xLine = timeLabel.bounds.width + style.timeline.offsetTimeX + style.timeline.offsetLineLeft
lineView.frame = CGRect(x: xLine,
y: timeLabel.center.y,
width: bounds.width - xLine,
height: style.timeline.heightLine)
[timeLabel, lineView].forEach({ addSubview($0) })
}
}
#endif
| 23.674699 | 103 | 0.53944 |
f4280a01149255f5b2e10b7c4480c6cb3460f7ef
| 1,577 |
import Foundation
public protocol EasyAutoLayoutDataSource: class {
var info: EasyAutoLayout.Info { get }
var subViews: [EasyAutoLayout.View] { get }
func addConstraint(_ constraint: NSLayoutConstraint, to target: EasyAutoLayout.View)
func beginLayout()
func commitLayout()
}
protocol EasyAutoLayoutDelegate: class {
func addSubView(_ view: EasyAutoLayout.View)
}
extension EasyAutoLayoutDataSource where Self: UIViewController {
var subViews: [EasyAutoLayout.View] {
return view.subviews
}
}
extension EasyAutoLayoutDelegate where Self: UIViewController {
func addSubView(_ view: EasyAutoLayout.View) {
self.view.addSubview(view)
}
}
open class EasyAutoLayoutViewController: UIViewController, EasyAutoLayoutDataSource, EasyAutoLayoutDelegate {
public var info: EasyAutoLayout.Info
public var subViews: [EasyAutoLayout.View] = []
public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, info: EasyAutoLayout.Info) {
self.info = info
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required public init?(coder: NSCoder) {
self.info = EasyAutoLayout.Info()
super.init(coder: coder)
}
public func addConstraint(_ constraint: NSLayoutConstraint, to target: EasyAutoLayout.View) {
}
public func beginLayout() {
}
public func commitLayout() {
}
func addSubView(_ view: EasyAutoLayout.View) {
}
}
| 23.537313 | 109 | 0.668992 |
b980ddd6a9831aeebb4f8ed71f36b92328bac65b
| 3,610 |
//
// SurveyViewModelFromSurvey.swift
// SurveyTakerTests
//
// Created by Arun Jose on 04/04/19.
// Copyright © 2019 __ORGANIZATION NAME__. All rights reserved.
//
import XCTest
import Alamofire
@testable import SurveyTaker_Debug
class SurveyViewModelFromSurvey: XCTestCase {
var viewModel: SurveyTaker_Debug.SurveyViewModelFromSurvey?
var params = [String: Any]()
override func setUp() {
super.setUp()
StubHandler.installJSONStub()
StubHandler.installAccessTokenStub()
params = [
"page": 1,
"per_page": 6
]
viewModel = SurveyTaker_Debug.SurveyViewModelFromSurvey()
}
override func tearDown() {
params = [:]
viewModel = nil
StubHandler.uninstallJSONStub()
StubHandler.uninstallAccessTokenStub()
super.tearDown()
}
// func testGetSurveyListCount() {
//
// let promise = expectation(description: "Succefully fetch survey through API")
// let surveysListFetchCompletionHanlder: ([Survey]) -> Void = { prefetchedSurveyList in
// XCTAssertTrue(prefetchedSurveyList.count == 6)
// promise.fulfill()
// }
//
// self.getAccessToken { [unowned self] token in
// self.viewModel?.getSurveyList(witAccessToken: token,
// withParams: self.params,
// forUrl: Constants.SurveyAPIURL,
// completionHandler: surveysListFetchCompletionHanlder )
// }
//
// waitForExpectations(timeout: 5, handler: nil)
// }
func testfetchSurveysFirstValue() {
let testSurvey = Survey(title: "Scarlett Bangkok",
description: "We'd love ot hear from you!",
bgImage: "https://dhdbhh0jsld0o.cloudfront.net/m/1ea51560991bcb7d00d0_")
let promise = expectation(description: "Succefully completed fetchSurveys")
viewModel?.noOfSurveys.bind { [unowned self] _ in
let firstSurvey = self.viewModel?.prefetchedSurveyList[0]
XCTAssertTrue(firstSurvey == testSurvey)
promise.fulfill()
}
viewModel?.fetchSurveys()
waitForExpectations(timeout: 5, handler: nil)
}
func testfetchSurveys() {
let promise = expectation(description: "Succefully completed fetchSurveys")
viewModel?.noOfSurveys.bind { count in
XCTAssertTrue(count == 6)
promise.fulfill()
}
viewModel?.fetchSurveys()
waitForExpectations(timeout: 5, handler: nil)
}
private func getAccessToken(completionHandler: @escaping (Token?) -> Void) {
let headers: HTTPHeaders = [
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
]
let params = [
"grant_type": "password",
"username": "[email protected]",
"password": "antikera"
]
Alamofire.request(Constants.AccessTokenAPIURL, method: .post, parameters: params, headers: headers)
.validate(contentType: ["application/json"])
.responseJSON { response in
guard let responseObj = response.result.value as? [String: Any] else {
completionHandler(nil)
return
}
let token = Token.getTokenFrom(jsonObj: responseObj)
completionHandler(token)
}
}
}
| 35.048544 | 107 | 0.580609 |
794e1377137db0eecd60d25a1b0d64c721bdafc3
| 2,980 |
//
// LikeButton.swift
// SwiftUI-Animations
//
// Created by Shubham Singh on 26/09/20.
// Copyright © 2020 Shubham Singh. All rights reserved.
//
import SwiftUI
struct LikeView: View {
// MARK:- variables
let animationDuration: Double = 0.25
@State var isAnimating: Bool = false
@State var shrinkIcon: Bool = false
@State var floatLike: Bool = false
@State var showFlare: Bool = false
// MARK:- views
var body: some View {
ZStack {
Color.likeBackground
.edgesIgnoringSafeArea(.all)
ZStack {
if (floatLike) {
CapusuleGroupView(isAnimating: $floatLike)
.offset(y: -130)
.scaleEffect(self.showFlare ? 1.25 : 0.8)
.opacity(self.floatLike ? 1 : 0)
.animation(Animation.spring().delay(animationDuration / 2))
}
Circle()
.foregroundColor(self.isAnimating ? Color.likeColor : Color.likeOverlay)
.animation(Animation.easeOut(duration: animationDuration * 2).delay(animationDuration))
HeartImageView()
.foregroundColor(.white)
.offset(y: 12)
.scaleEffect(self.isAnimating ? 1.25 : 1)
.overlay(
Color.likeColor
.mask(
HeartImageView()
)
.offset(y: 12)
.scaleEffect(self.isAnimating ? 1.35 : 0)
.animation(Animation.easeIn(duration: animationDuration))
.opacity(self.isAnimating ? 0 : 1)
.animation(Animation.easeIn(duration: animationDuration).delay(animationDuration))
)
}.frame(width: 250, height: 250)
.scaleEffect(self.shrinkIcon ? 0.35 : 1)
.animation(Animation.spring(response: animationDuration, dampingFraction: 1, blendDuration: 1))
if (floatLike) {
FloatingLike(isAnimating: $floatLike)
.offset(y: -40)
}
}.onTapGesture {
if (!floatLike) {
self.floatLike.toggle()
self.isAnimating.toggle()
self.shrinkIcon.toggle()
Timer.scheduledTimer(withTimeInterval: animationDuration, repeats: false) { _ in
self.shrinkIcon.toggle()
self.showFlare.toggle()
}
} else {
self.isAnimating = false
self.shrinkIcon = false
self.showFlare = false
self.floatLike = false
}
}
}
}
struct LikeButton_Previews: PreviewProvider {
static var previews: some View {
LikeView()
}
}
| 35.903614 | 110 | 0.494966 |
8f254b0226d87cfe1070561b9640aa323620a2bb
| 2,063 |
//
// NuguClient+NattyLog.swift
// NuguClientKit
//
// Created by yonghoonKwon on 2019/12/11.
// Copyright (c) 2019 SK Telecom Co., Ltd. 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 Foundation
import NattyLog
// MARK: - NattyLog
let log: Natty = NattyLog.Natty(by: nattyConfiguration)
private var nattyConfiguration: NattyConfiguration {
#if DEBUG
return NattyConfiguration(
minLogLevel: .debug,
maxDescriptionLevel: .error,
showPersona: true,
prefix: "NuguClientKit")
#else
return NattyConfiguration(
minLogLevel: .warning,
maxDescriptionLevel: .warning,
showPersona: true,
prefix: "NuguClientKit")
#endif
}
/// Turn the log enable and disable in `NuguClientKit`.
@available(*, deprecated, message: "Replace to `logLevel`")
public var logEnabled: Bool {
set {
guard newValue == true else {
log.configuration.minLogLevel = .nothing
return
}
#if DEBUG
log.configuration.minLogLevel = .debug
#else
log.configuration.minLogLevel = .warning
#endif
} get {
switch log.configuration.minLogLevel {
case .nothing:
return false
default:
return true
}
}
}
/// The minimum log level in `NuguClientKit`.
public var logLevel: NattyLog.LogLevel {
set {
log.configuration.minLogLevel = newValue
} get {
return log.configuration.minLogLevel
}
}
| 26.792208 | 76 | 0.651478 |
61d9e815b4f47fc034e4063213e14f1771788f38
| 1,213 |
//
// String+Ex.swift
// MaxwinBus
//
// Created by Yume on 2019/3/26.
// Copyright © 2019 Yume. All rights reserved.
//
import UIKit
extension String {
public func size(width: CGFloat? = nil, font: UIFont? = nil) -> CGSize? {
let max: CGSize = CGSize(
width: width ?? UIScreen.main.bounds.size.width,
height: 1000
)
let option: [NSAttributedString.Key: UIFont] = [
NSAttributedString.Key.font: font ?? UIFont.systemFont(ofSize: 17.0)
]
return (self as NSString).boundingRect(with: max, options: .usesLineFragmentOrigin, attributes: option, context: nil).size
}
}
extension UILabel {
public func size() -> CGSize? {
let max: CGSize = CGSize(
width: self.frame.width,
height: 1000
)
let option: [NSAttributedString.Key: UIFont] = [
NSAttributedString.Key.font: self.font ?? UIFont.systemFont(ofSize: 17.0)
]
return ((self.text ?? "") as NSString).boundingRect(
with: max,
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: option,
context: nil
).size
}
}
| 28.880952 | 130 | 0.576257 |
9b371c3338325644c5ffa47fe97af2b44a062bc9
| 2,521 |
import Vapor
struct ErrorResponse: Codable {
var error: Bool
var reason: String
var errorCode: String?
}
extension ErrorMiddleware {
static func `custom`(environment: Environment) -> ErrorMiddleware {
return .init { req, error in
let status: HTTPResponseStatus
let reason: String
let headers: HTTPHeaders
let errorCode: String?
switch error {
case let appError as AppError:
reason = appError.reason
status = appError.status
headers = appError.headers
errorCode = appError.identifier
case let abort as AbortError:
// this is an abort error, we should use its status, reason, and headers
reason = abort.reason
status = abort.status
headers = abort.headers
errorCode = nil
case let error as LocalizedError where !environment.isRelease:
// if not release mode, and error is debuggable, provide debug
// info directly to the developer
reason = error.localizedDescription
status = .internalServerError
headers = [:]
errorCode = nil
default:
// not an abort error, and not debuggable or in dev mode
// just deliver a generic 500 to avoid exposing any sensitive error info
reason = "Something went wrong."
status = .internalServerError
headers = [:]
errorCode = nil
}
// Report the error to logger.
req.logger.report(error: error)
// create a Response with appropriate status
let response = Response(status: status, headers: headers)
// attempt to serialize the error to json
do {
let errorResponse = ErrorResponse(error: true, reason: reason, errorCode: errorCode)
response.body = try .init(data: JSONEncoder().encode(errorResponse))
response.headers.replaceOrAdd(name: .contentType, value: "application/json; charset=utf-8")
} catch {
response.body = .init(string: "Oops: \(error)")
response.headers.replaceOrAdd(name: .contentType, value: "text/plain; charset=utf-8")
}
return response
}
}
}
| 39.390625 | 107 | 0.546608 |
181bd9c9435d1c78fd78e3466732aa3c173c0176
| 797 |
//
// ViewController.swift
// FlashChat
//
// Created by Tarokh on 10/7/20.
// Copyright © 2020 Tarokh. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
//MARK: - @IBOutlets
@IBOutlet var registerButton: RoundButton!
@IBOutlet var loginButton: RoundButton!
//MARK: - Variables
//MARK: - Views
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//MARK: - Functions
@IBAction func registerButtonTapped(_ sender: Any) {
self.performSegue(withIdentifier: "signUp", sender: self)
}
@IBAction func loginButtonTapped(_ sender: Any) {
self.performSegue(withIdentifier: "login", sender: self)
}
}
| 20.435897 | 65 | 0.631117 |
1d527164a7f379b4201e95b3fd6c20ac64132583
| 18,072 |
//
// ViewController.swift
// ARGearSample
//
// Created by Jaecheol Kim on 2019/10/28.
// Copyright © 2019 Seerslab. All rights reserved.
//
import UIKit
import CoreMedia
import SceneKit
import AVFoundation
import ARGear
public final class MainViewController: UIViewController {
var toast_main_position = CGPoint(x: 0, y: 0)
// MARK: - ARGearSDK properties
private var argConfig: ARGConfig?
private var argSession: ARGSession?
private var currentFaceFrame: ARGFrame?
private var nextFaceFrame: ARGFrame?
private var preferences: ARGPreferences = ARGPreferences()
// MARK: - Camera & Scene properties
private let serialQueue = DispatchQueue(label: "serialQueue")
private var currentCamera: CameraDeviceWithPosition = .front
private var arCamera: ARGCamera!
private var arScene: ARGScene!
private var arMedia: ARGMedia = ARGMedia()
private lazy var cameraPreviewCALayer = CALayer()
// MARK: - Functions UI
@IBOutlet weak var filterCancelLabel: UILabel!
@IBOutlet weak var contentCancelLabel: UILabel!
// MARK: - UI
@IBOutlet weak var splashView: SplashView!
@IBOutlet weak var touchLockView: UIView!
@IBOutlet weak var permissionView: PermissionView!
@IBOutlet weak var settingView: SettingView!
@IBOutlet weak var ratioView: RatioView!
@IBOutlet weak var mainTopFunctionView: MainTopFunctionView!
@IBOutlet weak var mainBottomFunctionView: MainBottomFunctionView!
private var argObservers = [NSKeyValueObservation]()
// MARK: - Lifecycles
override public func viewDidLoad() {
super.viewDidLoad()
setupARGearConfig()
setupScene()
setupCamera()
setupUI()
addObservers()
initHelpers()
connectAPI()
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
runARGSession()
}
override public func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
stopARGSession()
}
deinit {
removeObservers()
}
private func initHelpers() {
NetworkManager.shared.argSession = self.argSession
BeautyManager.shared.argSession = self.argSession
FilterManager.shared.argSession = self.argSession
ContentManager.shared.argSession = self.argSession
BulgeManager.shared.argSession = self.argSession
BeautyManager.shared.start()
}
// MARK: - connect argear API
private func connectAPI() {
NetworkManager.shared.connectAPI { (result: Result<[String: Any], APIError>) in
switch result {
case .success(let data):
RealmManager.shared.setARGearData(data) { [weak self] success in
guard let self = self else { return }
self.loadAPIData()
}
case .failure(.network):
self.loadAPIData()
break
case .failure(.data):
self.loadAPIData()
break
case .failure(.serializeJSON):
self.loadAPIData()
break
}
}
}
private func loadAPIData() {
DispatchQueue.main.async {
let categories = RealmManager.shared.getCategories()
self.mainBottomFunctionView.contentView.contentsCollectionView.contents = categories
self.mainBottomFunctionView.contentView.contentTitleListScrollView.contents = categories
self.mainBottomFunctionView.filterView.filterCollectionView.filters = RealmManager.shared.getFilters()
}
}
// MARK: - ARGearSDK setupConfig
private func setupARGearConfig() {
do {
let config = ARGConfig(
apiURL: API_HOST,
apiKey: API_KEY,
secretKey: API_SECRET_KEY,
authKey: API_AUTH_KEY
)
argSession = try ARGSession(argConfig: config, feature: [.faceMeshTracking])
argSession?.delegate = self
let debugOption: ARGInferenceDebugOption = self.preferences.showLandmark ? .optionDebugFaceLandmark2D : .optionDebugNON
argSession?.inferenceDebugOption = debugOption
} catch let error as NSError {
print("Failed to initialize ARGear Session with error: %@", error.description)
} catch let exception as NSException {
print("Exception to initialize ARGear Session with error: %@", exception.description)
}
}
// MARK: - setupScene
private func setupScene() {
arScene = ARGScene(viewContainer: view)
arScene.sceneRenderUpdateAtTimeHandler = { [weak self] renderer, time in
guard let self = self else { return }
self.refreshARFrame()
}
arScene.sceneRenderDidRenderSceneHandler = { [weak self] renderer, scene, time in
guard let _ = self else { return }
}
cameraPreviewCALayer.contentsGravity = .resizeAspect//.resizeAspectFill
cameraPreviewCALayer.frame = CGRect(x: 0, y: 0, width: arScene.sceneView.frame.size.height, height: arScene.sceneView.frame.size.width)
cameraPreviewCALayer.contentsScale = UIScreen.main.scale
view.layer.insertSublayer(cameraPreviewCALayer, at: 0)
}
// MARK: - setupCamera
private func setupCamera() {
arCamera = ARGCamera()
arCamera.sampleBufferHandler = { [weak self] output, sampleBuffer, connection in
guard let self = self else { return }
self.serialQueue.async {
self.argSession?.update(sampleBuffer, from: connection)
}
}
self.permissionCheck {
self.arCamera.startCamera()
self.setCameraInfo()
}
}
func setCameraInfo() {
if let device = arCamera.cameraDevice, let connection = arCamera.cameraConnection {
self.arMedia.setVideoDevice(device)
self.arMedia.setVideoDeviceOrientation(connection.videoOrientation)
self.arMedia.setVideoConnection(connection)
}
arMedia.setMediaRatio(arCamera.ratio)
arMedia.setVideoBitrate(ARGMediaVideoBitrate(rawValue: self.preferences.videoBitrate) ?? ._4M)
}
// MARK: - UI
private func setupUI() {
self.mainTopFunctionView.delegate = self
self.mainBottomFunctionView.delegate = self
self.settingView.delegate = self
self.ratioView.setRatio(arCamera.ratio)
self.settingView.setPreferences(autoSave: self.arMedia.autoSave, showLandmark: self.preferences.showLandmark, videoBitrate: self.preferences.videoBitrate)
toast_main_position = CGPoint(x: self.view.center.x, y: mainBottomFunctionView.frame.origin.y - 24.0)
ARGLoading.prepare()
}
private func startUI() {
self.setCameraInfo()
self.touchLock(false)
}
private func pauseUI() {
self.ratioView.blur(true)
self.touchLock(true)
}
func refreshRatio() {
let ratio = arCamera.ratio
self.ratioView.setRatio(ratio)
self.mainTopFunctionView.setRatio(ratio)
self.setCameraPreview(ratio)
self.arMedia.setMediaRatio(ratio)
}
func setCameraPreview(_ ratio: ARGMediaRatio) {
self.cameraPreviewCALayer.contentsGravity = (ratio == ._16x9) ? .resizeAspectFill : .resizeAspect
}
// MARK: - ARGearSDK Handling
private func refreshARFrame() {
guard self.nextFaceFrame != nil && self.nextFaceFrame != self.currentFaceFrame else { return }
self.currentFaceFrame = self.nextFaceFrame
}
private func drawARCameraPreview() {
guard
let frame = self.currentFaceFrame,
let pixelBuffer = frame.renderedPixelBuffer
else {
return
}
var flipTransform = CGAffineTransform(scaleX: -1, y: 1)
if self.arCamera.currentCamera == .back {
flipTransform = CGAffineTransform(scaleX: 1, y: 1)
}
DispatchQueue.main.async {
CATransaction.flush()
CATransaction.begin()
CATransaction.setAnimationDuration(0)
if #available(iOS 11.0, *) {
self.cameraPreviewCALayer.contents = pixelBuffer
} else {
self.cameraPreviewCALayer.contents = self.pixelbufferToCGImage(pixelBuffer)
}
let angleTransform = CGAffineTransform(rotationAngle: .pi/2)
let transform = angleTransform.concatenating(flipTransform)
self.cameraPreviewCALayer.setAffineTransform(transform)
self.cameraPreviewCALayer.frame = CGRect(x: 0, y: -self.getPreviewY(), width: self.cameraPreviewCALayer.frame.size.width, height: self.cameraPreviewCALayer.frame.size.height)
self.view.backgroundColor = .white
CATransaction.commit()
}
}
private func getPreviewY() -> CGFloat {
let height43: CGFloat = (self.view.frame.width * 4) / 3
let height11: CGFloat = self.view.frame.width
var previewY: CGFloat = 0
if self.arCamera.ratio == ._1x1 {
previewY = (height43 - height11)/2 + CGFloat(kRatioViewTopBottomAlign11/2)
}
if #available(iOS 11.0, *), self.arCamera.ratio != ._16x9 {
if let topInset = UIApplication.shared.keyWindow?.rootViewController?.view.safeAreaInsets.top {
if self.arCamera.ratio == ._1x1 {
previewY += topInset/2
} else {
previewY += topInset
}
}
}
return previewY
}
private func pixelbufferToCGImage(_ pixelbuffer: CVPixelBuffer) -> CGImage? {
let ciimage = CIImage(cvPixelBuffer: pixelbuffer)
let context = CIContext()
let cgimage = context.createCGImage(ciimage, from: CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(pixelbuffer), height: CVPixelBufferGetHeight(pixelbuffer)))
return cgimage
}
private func runARGSession() {
argSession?.run()
}
private func stopARGSession() {
argSession?.pause()
}
func removeSplashAfter(_ sec: TimeInterval) {
DispatchQueue.main.asyncAfter(deadline: .now() + sec) {
self.splashView.removeFromSuperview()
}
}
}
// MARK: - ARGearSDK ARGSession delegate
extension MainViewController : ARGSessionDelegate {
public func didUpdate(_ arFrame: ARGFrame) {
if let splash = self.splashView {
splash.removeFromSuperview()
}
self.drawARCameraPreview()
for face in arFrame.faces.faceList {
if face.isValid {
// NSLog("landmarkcount = %d", face.landmark.landmarkCount)
// get face information (landmarkCoordinates , rotation_matrix, translation_vector)
// let landmarkcount = face.landmark.landmarkCount
// let landmarkCoordinates = face.landmark.landmarkCoordinates
// let rotation_matrix = face.rotation_matrix
// let translation_vector = face.translation_vector
}
}
nextFaceFrame = arFrame
if #available(iOS 11.0, *) {
} else {
self.arScene.sceneView.sceneTime += 1
}
}
}
// MARK: - User Interaction
extension MainViewController {
// Touch Lock Control
func touchLock(_ lock: Bool) {
self.touchLockView.isHidden = !lock
if lock {
mainTopFunctionView.disableButtons()
} else {
mainTopFunctionView.enableButtons()
}
}
}
// MARK: - Permission
extension MainViewController {
func permissionCheck(_ permissionCheckComplete: @escaping PermissionCheckComplete) {
let permissionLevel = self.permissionView.permission.getPermissionLevel()
self.permissionView.permission.grantedHandler = permissionCheckComplete
self.permissionView.setPermissionLevel(permissionLevel)
switch permissionLevel {
case .Granted:
break
case .Restricted:
self.removeSplashAfter(1.0)
case .None:
self.removeSplashAfter(1.0)
}
}
}
// MARK: - Observers
extension MainViewController {
// MainTopFunctionView
func addMainTopFunctionViewObservers() {
self.argObservers.append(
self.arCamera.observe(\.ratio, options: [.new]) { [weak self] obj, _ in
guard let self = self else { return }
self.mainTopFunctionView.setRatio(obj.ratio)
}
)
}
// MainBottomFunctionView
func addMainBottomFunctionViewObservers() {
self.argObservers.append(
self.arCamera.observe(\.ratio, options: [.new]) { [weak self] obj, _ in
guard let self = self else { return }
self.mainBottomFunctionView.setRatio(obj.ratio)
}
)
}
// Add
func addObservers() {
self.addMainTopFunctionViewObservers()
self.addMainBottomFunctionViewObservers()
}
// Remove
func removeObservers() {
self.argObservers.removeAll()
}
}
// MARK: - Setting Delegate
extension MainViewController: SettingDelegate {
func autoSaveSwitchAction(_ sender: UISwitch) {
self.arMedia.autoSave = sender.isOn
}
func faceLandmarkSwitchAction(_ sender: UISwitch) {
self.preferences.setShowLandmark(sender.isOn)
if let session = self.argSession {
let debugOption: ARGInferenceDebugOption = sender.isOn ? .optionDebugFaceLandmark2D : .optionDebugNON
session.inferenceDebugOption = debugOption
}
}
func bitrateSegmentedControlAction(_ sender: UISegmentedControl) {
self.preferences.setVideoBitrate(sender.selectedSegmentIndex)
self.arMedia.setVideoBitrate(ARGMediaVideoBitrate(rawValue: sender.selectedSegmentIndex) ?? ._4M)
}
}
// MARK: - MainTopFunction Delegate
extension MainViewController: MainTopFunctionDelegate {
func settingButtonAction() {
self.settingView.open()
}
func ratioButtonAction() {
guard
let session = argSession
else { return }
self.pauseUI()
session.pause()
self.arCamera.changeCameraRatio {
self.startUI()
self.refreshRatio()
session.run()
}
}
func toggleButtonAction() {
guard
let session = argSession
else { return }
self.pauseUI()
session.pause()
arCamera.toggleCamera {
self.startUI()
self.refreshRatio()
session.run()
}
}
}
// MARK: - MainBottomFunction Delegate
extension MainViewController: MainBottomFunctionDelegate {
func photoButtonAction(_ button: UIButton) {
self.arMedia.takePic { image in
self.photoButtonActionFinished(image: image)
}
}
func videoButtonAction(_ button: UIButton) {
if button.tag == 0 {
// start record
button.tag = 1
self.mainTopFunctionView.disableButtons()
self.arMedia.recordVideoStart { [weak self] recTime in
guard let self = self else { return }
DispatchQueue.main.async {
self.mainBottomFunctionView.setRecordTime(Float(recTime))
}
}
} else {
// stop record
ARGLoading.show()
button.tag = 0
self.mainTopFunctionView.enableButtons()
self.arMedia.recordVideoStop({ tempFileInfo in
}) { resultFileInfo in
ARGLoading.hide()
if let info = resultFileInfo as? Dictionary<String, Any> {
self.videoButtonActionFinished(videoInfo: info)
}
}
}
}
func photoButtonActionFinished(image: UIImage?) {
guard let saveImage = image else { return }
self.arMedia.save(saveImage, saved: {
self.view.showToast(message: "photo_video_saved_message".localized(), position: self.toast_main_position)
}) {
self.goPreview(content: saveImage)
}
}
func videoButtonActionFinished(videoInfo: Dictionary<String, Any>?) {
guard let info = videoInfo else { return }
self.arMedia.saveVideo(info, saved: {
self.view.showToast(message: "photo_video_saved_message".localized(), position: self.toast_main_position)
}) {
self.goPreview(content: info)
}
}
func goPreview(content: Any) {
self.performSegue(withIdentifier: "toPreviewSegue", sender: content)
}
override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toPreviewSegue" {
if let previewController = segue.destination as? PreviewViewController {
previewController.ratio = self.arCamera.ratio
previewController.media = self.arMedia
if let image = sender as? UIImage {
previewController.mode = .photo
previewController.previewImage = image
} else if let videoInfo = sender as? [String: Any] {
previewController.mode = .video
previewController.videoInfo = videoInfo
}
}
}
}
}
| 32.099467 | 186 | 0.605356 |
d673a3e08f828e032cf1f7dfc41b13f15643dec5
| 13,617 |
//
// BinUtils.swift
// BinUtils
//
// Created by Nicolas Seriot on 12/03/16.
// Copyright © 2016 Nicolas Seriot. All rights reserved.
//
import Foundation
import CoreFoundation
// MARK: protocol UnpackedType
public protocol Unpackable {}
extension NSString: Unpackable {}
extension Bool: Unpackable {}
extension Int: Unpackable {}
extension Double: Unpackable {}
// MARK: protocol DataConvertible
protocol DataConvertible {}
extension DataConvertible {
init?(data: Data) {
guard data.count == MemoryLayout<Self>.size else { return nil }
self = data.withUnsafeBytes { $0.load(as: Self.self) }
}
init?(bytes: [UInt8]) {
let data = Data(bytes)
self.init(data:data)
}
var data: Data {
var value = self
return Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
}
}
extension Bool : DataConvertible { }
extension Int8 : DataConvertible { }
extension Int16 : DataConvertible { }
extension Int32 : DataConvertible { }
extension Int64 : DataConvertible { }
extension UInt8 : DataConvertible { }
extension UInt16 : DataConvertible { }
extension UInt32 : DataConvertible { }
extension UInt64 : DataConvertible { }
extension Float32 : DataConvertible { }
extension Float64 : DataConvertible { }
// MARK: String extension
extension String {
subscript (from:Int, to:Int) -> String {
return NSString(string: self).substring(with: NSMakeRange(from, to-from))
}
}
// MARK: Data extension
extension Data {
var bytes : [UInt8] {
return [UInt8](self)
}
}
// MARK: functions
public func hexlify(_ data:Data) -> String {
// similar to hexlify() in Python's binascii module
// https://docs.python.org/2/library/binascii.html
var s = String()
var byte: UInt8 = 0
for i in 0 ..< data.count {
NSData(data: data).getBytes(&byte, range: NSMakeRange(i, 1))
s = s.appendingFormat("%02x", byte)
}
return s as String
}
public func unhexlify(_ string:String) -> Data? {
// similar to unhexlify() in Python's binascii module
// https://docs.python.org/2/library/binascii.html
let s = string.uppercased().replacingOccurrences(of: " ", with: "")
let nonHexCharacterSet = CharacterSet(charactersIn: "0123456789ABCDEF").inverted
if let range = s.rangeOfCharacter(from: nonHexCharacterSet) {
print("-- found non hex character at range \(range)")
return nil
}
var data = Data(capacity: s.count / 2)
for i in stride(from: 0, to:s.count, by:2) {
let byteString = s[i, i+2]
let byte = UInt8(byteString.withCString { strtoul($0, nil, 16) })
data.append([byte] as [UInt8], count: 1)
}
return data
}
func readIntegerType<T:DataConvertible>(_ type:T.Type, bytes:[UInt8], loc:inout Int) -> T {
let size = MemoryLayout<T>.size
let sub = Array(bytes[loc..<(loc+size)])
loc += size
return T(bytes: sub)!
}
func readFloatingPointType<T:DataConvertible>(_ type:T.Type, bytes:[UInt8], loc:inout Int, isBigEndian:Bool) -> T {
let size = MemoryLayout<T>.size
let sub = Array(bytes[loc..<(loc+size)])
loc += size
let sub_ = isBigEndian ? sub.reversed() : sub
return T(bytes: sub_)!
}
func isBigEndianFromMandatoryByteOrderFirstCharacter(_ format:String) -> Bool {
guard let firstChar = format.first else { assertionFailure("empty format"); return false }
let s = NSString(string: String(firstChar))
let c = s.substring(to: 1)
if c == "@" { assertionFailure("native size and alignment is unsupported") }
if c == "=" || c == "<" { return false }
if c == ">" || c == "!" { return true }
assertionFailure("format '\(format)' first character must be among '=<>!'")
return false
}
// akin to struct.calcsize(fmt)
public func numberOfBytesInFormat(_ format:String) -> Int {
var numberOfBytes = 0
var n = 0 // repeat counter
var mutableFormat = format
while !mutableFormat.isEmpty {
let c = mutableFormat.remove(at: mutableFormat.startIndex)
if let i = Int(String(c)) , 0...9 ~= i {
if n > 0 { n *= 10 }
n += i
continue
}
if c == "s" {
numberOfBytes += max(n,1)
n = 0
continue
}
let repeatCount = max(n,1)
switch(c) {
case "@", "<", "=", ">", "!", " ":
()
case "c", "b", "B", "x", "?":
numberOfBytes += 1 * repeatCount
case "h", "H":
numberOfBytes += 2 * repeatCount
case "i", "l", "I", "L", "f":
numberOfBytes += 4 * repeatCount
case "q", "Q", "d":
numberOfBytes += 8 * repeatCount
case "P":
numberOfBytes += MemoryLayout<Int>.size * repeatCount
default:
assertionFailure("-- unsupported format \(c)")
}
n = 0
}
return numberOfBytes
}
func formatDoesMatchDataLength(_ format:String, data:Data) -> Bool {
let sizeAccordingToFormat = numberOfBytesInFormat(format)
let dataLength = data.count
if sizeAccordingToFormat != dataLength {
print("format \"\(format)\" expects \(sizeAccordingToFormat) bytes but data is \(dataLength) bytes")
return false
}
return true
}
/*
pack() and unpack() should behave as Python's struct module https://docs.python.org/2/library/struct.html BUT:
- native size and alignment '@' is not supported
- as a consequence, the byte order specifier character is mandatory and must be among "=<>!"
- native byte order '=' assumes a little-endian system (eg. Intel x86)
- Pascal strings 'p' and native pointers 'P' are not supported
*/
public enum BinUtilsError: Error {
case formatDoesMatchDataLength(format:String, dataSize:Int)
case unsupportedFormat(character:Character)
}
public func pack(_ format:String, _ objects:[Any], _ stringEncoding:String.Encoding=String.Encoding.windowsCP1252) -> Data {
var objectsQueue = objects
var mutableFormat = format
var mutableData = Data()
var isBigEndian = false
let firstCharacter = mutableFormat.remove(at: mutableFormat.startIndex)
switch(firstCharacter) {
case "<", "=":
isBigEndian = false
case ">", "!":
isBigEndian = true
case "@":
assertionFailure("native size and alignment '@' is unsupported'")
default:
assertionFailure("unsupported format chacracter'")
}
var n = 0 // repeat counter
while !mutableFormat.isEmpty {
let c = mutableFormat.remove(at: mutableFormat.startIndex)
if let i = Int(String(c)) , 0...9 ~= i {
if n > 0 { n *= 10 }
n += i
continue
}
var o : Any = 0
if c == "s" {
o = objectsQueue.remove(at: 0)
guard let stringData = (o as! String).data(using: .utf8) else { assertionFailure(); return Data() }
var bytes = stringData.bytes
let expectedSize = max(1, n)
// pad ...
while bytes.count < expectedSize { bytes.append(0x00) }
// ... or trunk
if bytes.count > expectedSize { bytes = Array(bytes[0..<expectedSize]) }
assert(bytes.count == expectedSize)
if isBigEndian { bytes = bytes.reversed() }
mutableData.append(bytes, count: bytes.count)
n = 0
continue
}
for _ in 0..<max(n,1) {
var bytes : [UInt8] = []
if c != "x" {
o = objectsQueue.removeFirst()
}
switch(c) {
case "?":
bytes = (o as! Bool) ? [0x01] : [0x00]
case "c":
let charAsString = (o as! NSString).substring(to: 1)
guard let data = charAsString.data(using: stringEncoding) else {
assertionFailure("cannot decode character \(charAsString) using encoding \(stringEncoding)")
return Data()
}
bytes = data.bytes
case "b":
bytes = Int8(truncatingIfNeeded:o as! Int).data.bytes
case "h":
bytes = Int16(truncatingIfNeeded:o as! Int).data.bytes
case "i", "l":
bytes = Int32(truncatingIfNeeded:o as! Int).data.bytes
case "q", "Q":
bytes = Int64(o as! Int).data.bytes
case "B":
bytes = UInt8(truncatingIfNeeded:o as! Int).data.bytes
case "H":
bytes = UInt16(truncatingIfNeeded:o as! Int).data.bytes
case "I", "L":
bytes = UInt32(truncatingIfNeeded:o as! Int).data.bytes
case "f":
bytes = Float32(o as! Double).data.bytes
case "d":
bytes = Float64(o as! Double).data.bytes
case "x":
bytes = [0x00]
default:
assertionFailure("Unsupported packing format: \(c)")
}
if isBigEndian { bytes = bytes.reversed() }
let data = Data(bytes)
mutableData.append(data)
}
n = 0
}
return mutableData
}
public func unpack(_ format:String, _ data:Data, _ stringEncoding:String.Encoding=String.Encoding.windowsCP1252) throws -> [Unpackable] {
assert(CFByteOrderGetCurrent() == 1 /* CFByteOrderLittleEndian */, "\(#file) assumes little endian, but host is big endian")
let isBigEndian = isBigEndianFromMandatoryByteOrderFirstCharacter(format)
if formatDoesMatchDataLength(format, data: data) == false {
throw BinUtilsError.formatDoesMatchDataLength(format:format, dataSize:data.count)
}
var a : [Unpackable] = []
var loc = 0
let bytes = data.bytes
var n = 0 // repeat counter
var mutableFormat = format
mutableFormat.remove(at: mutableFormat.startIndex) // consume byte-order specifier
while !mutableFormat.isEmpty {
let c = mutableFormat.remove(at: mutableFormat.startIndex)
if let i = Int(String(c)) , 0...9 ~= i {
if n > 0 { n *= 10 }
n += i
continue
}
if c == "s" {
let length = max(n,1)
let sub = Array(bytes[loc..<loc+length])
guard let s = NSString(bytes: sub, length: length, encoding: stringEncoding.rawValue) else {
assertionFailure("-- not a string: \(sub)")
return []
}
a.append(s)
loc += length
n = 0
continue
}
for _ in 0..<max(n,1) {
var o : Unpackable?
switch(c) {
case "c":
let optionalString = NSString(bytes: [bytes[loc]], length: 1, encoding: String.Encoding.utf8.rawValue)
loc += 1
guard let s = optionalString else { assertionFailure(); return [] }
o = s
case "b":
let r = readIntegerType(Int8.self, bytes:bytes, loc:&loc)
o = Int(r)
case "B":
let r = readIntegerType(UInt8.self, bytes:bytes, loc:&loc)
o = Int(r)
case "?":
let r = readIntegerType(Bool.self, bytes:bytes, loc:&loc)
o = r ? true : false
case "h":
let r = readIntegerType(Int16.self, bytes:bytes, loc:&loc)
o = Int(isBigEndian ? Int16(bigEndian: r) : r)
case "H":
let r = readIntegerType(UInt16.self, bytes:bytes, loc:&loc)
o = Int(isBigEndian ? UInt16(bigEndian: r) : r)
case "i":
fallthrough
case "l":
let r = readIntegerType(Int32.self, bytes:bytes, loc:&loc)
o = Int(isBigEndian ? Int32(bigEndian: r) : r)
case "I":
fallthrough
case "L":
let r = readIntegerType(UInt32.self, bytes:bytes, loc:&loc)
o = Int(isBigEndian ? UInt32(bigEndian: r) : r)
case "q":
let r = readIntegerType(Int64.self, bytes:bytes, loc:&loc)
o = Int(isBigEndian ? Int64(bigEndian: r) : r)
case "Q":
let r = readIntegerType(UInt64.self, bytes:bytes, loc:&loc)
o = Int(isBigEndian ? UInt64(bigEndian: r) : r)
case "f":
let r = readFloatingPointType(Float32.self, bytes:bytes, loc:&loc, isBigEndian:isBigEndian)
o = Double(r)
case "d":
let r = readFloatingPointType(Float64.self, bytes:bytes, loc:&loc, isBigEndian:isBigEndian)
o = Double(r)
case "x":
loc += 1
case " ":
()
default:
throw BinUtilsError.unsupportedFormat(character:c)
}
if let o = o { a.append(o) }
}
n = 0
}
return a
}
| 30.192905 | 137 | 0.536388 |
269ea0dfc0444229e20147cf2ecf56ddf864e21e
| 2,014 |
import Foundation
import UIKit
import M13ProgressSuite
import vividFaces
class BrainsViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
progressView.progressImage = UIImage(named: "Striped_apple_logo")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setProgress(progress: 0.0)
if VividFaces.modelIsReady() {
nextPage()
return
}
initCheck()
}
@IBOutlet weak var progressView: M13ProgressViewImage!
func initCheck(){
let initSuc : ()->() = { () -> () in
print("vividfaces init suc")
self.nextPage()
return
}
let initProgress: (CGFloat)->() = { (progress: CGFloat) -> () in
self.setProgress(progress: progress)
}
let initFail = {(error: VFError, onRetry: @escaping ()->(), onCancel: @escaping ()->()) -> () in
print("vividfaces init Error \(error)")
UIInterfaceQMUI().createNonCancellableErrorRetryDialog(error: error, onRetry: {
print("onRetry clicked")
self.setProgress(progress: 0.0)
onRetry()
})()
}
VividFaces.mayDownloadModel(onInitSuc: initSuc, onInitFail: initFail, onProgress: initProgress, ignoreDownloadMessage: false)
}
func nextPage (){
//DispatchQueue.main.async {
let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateInitialViewController()
self.present(vc!, animated: true, completion: {
print("nextPage")
})
//}
}
func setProgress(progress: CGFloat){
progressView.setProgress(progress, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
| 34.724138 | 133 | 0.593843 |
261f461bfc412e243c94e25a7f3fba4e6b851e7c
| 3,816 |
//
// FormView.swift
// seco
//
// Created by Javier Calatrava on 04/04/2020.
// Copyright © 2020 Javier Calatrava. All rights reserved.
//
import SwiftUI
import Combine
protocol IssueVProtocol {
func presentActivityIndicator()
func removeActivityIndicator()
func dismiss()
}
struct FormView: View {
var onDismissPublisher: AnyPublisher<Void, Never> {
return onDismissInternalPublisher.eraseToAnyPublisher()
}
public var onDismissInternalPublisher = PassthroughSubject<Void, Never>()
@ObservedObject var issueUI: IssueUI = IssueUI()
var presenter: IssueFormPresenterProtocol = IssuePresenterNew()
@ObservedObject var keyboardHandler: KeyboardFollower = KeyboardFollower()
@State var isWrongFilled: Bool = false
init(issueUI: IssueUI,
presenter: IssueFormPresenterProtocol = IssuePresenterNew(),
keyboardHandler: KeyboardFollower = KeyboardFollower()) {
self.issueUI = issueUI
self.presenter = presenter
self.keyboardHandler = keyboardHandler
presenter.set(issueVC: self)
}
var body: some View {
ScrollView {
VStack {
TextInputCell(text: "issue_name".localized, value: $issueUI.name.self)
TextInputCell(text: "issue_surename".localized, value: $issueUI.surename.self)
TextInputCell(text: "issue_email".localized, value: $issueUI.email.self)
TextInputCell(text: "issue_phone".localized, value: $issueUI.phone.self)
DateSelectorCell(text: "issue_timestamp".localized, value: $issueUI.timestamp.self)
MultilineInputTextView(text: "issue_report".localized, value: $issueUI.report.self)
// MultilineInputCell(value: $issueUI.report.self).frame(height: 200).bordered().padding()
ActionCell {
guard self.isFormProperlyFilled() else {
self.isWrongFilled = true
return
}
self.isWrongFilled = false
let issue = Issue(issueUI: self.issueUI)
self.presenter.save(issue: issue)
}
}.padding(.bottom, keyboardHandler.keyboardHeight)
.alert(isPresented: $isWrongFilled) {
Alert(title: Text("issue_alert_title".localized),
message: Text("issue_alert_message".localized),
dismissButton: .default(Text("OK"),
action: {
}))
}
}
}
private func isFormProperlyFilled() -> Bool {
guard issueUI.report.isEmpty || issueUI.report.count <= 200 else { return false}
guard isValidEmail(issueUI.email) else { return false}
return !issueUI.name.isEmpty &&
!issueUI.surename.isEmpty &&
!issueUI.email.isEmpty
}
func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format: "SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
}
extension FormView: IssueVProtocol {
func presentActivityIndicator() {
print("")
}
func removeActivityIndicator() {
print("")
}
func dismiss() {
self.onDismissInternalPublisher.send()
}
}
struct FormView_Previews: PreviewProvider {
static var previews: some View {
let issue = Issue(route: "asdf", name: "Pepito", surename: "Grillo", email: "[email protected]", timestamp: 123, report: "blah, blah", phone: "123456789")
let issueUI = IssueUI(issue: issue)
return FormView(issueUI: issueUI)
}
}
| 34.378378 | 165 | 0.605346 |
1d113fa3753692b52bb1397b2dd4179f07fdfd21
| 2,910 |
let magic: [UInt8] = [0x00, 0x61, 0x73, 0x6D]
let version: [UInt8] = [0x01, 0x00, 0x00, 0x00]
typealias Index = Int
typealias Offset = Int
typealias Size = Int
enum SectionCode: UInt8, CaseIterable {
case custom = 0
case type = 1
case `import` = 2
case function = 3
case table = 4
case memory = 5
case global = 6
case export = 7
case start = 8
case elem = 9
case code = 10
case data = 11
case dataCount = 12
}
enum NameSectionSubsection: UInt8 {
case function = 1
}
enum ExternalKind: UInt8, Equatable {
case `func` = 0
case table = 1
case memory = 2
case global = 3
case except = 4
}
enum ValueType: UInt8, Equatable {
case i32 = 0x7F
case i64 = 0x7E
case f32 = 0x7D
case f64 = 0x7C
}
enum ElementType: UInt8, Equatable {
case funcRef = 0x70
}
enum ConstOpcode: UInt8 {
case i32Const = 0x41
case i64Const = 0x42
case f32Const = 0x43
case f64Const = 0x44
}
enum Opcode: UInt8 {
case end = 0x0B
case call = 0x10
}
enum RelocType: UInt8, Equatable {
case FUNCTION_INDEX_LEB = 0
case TABLE_INDEX_SLEB = 1
case TABLE_INDEX_I32 = 2
case MEMORY_ADDR_LEB = 3
case MEMORY_ADDR_SLEB = 4
case MEMORY_ADDR_I32 = 5
case TYPE_INDEX_LEB = 6
case GLOBAL_INDEX_LEB = 7
case FUNCTION_OFFSET_I32 = 8
case SECTION_OFFSET_I32 = 9
// case EVENT_INDEX_LEB = 10
case MEMORY_ADDR_REL_SLEB = 11
case TABLE_INDEX_REL_SLEB = 12
case GLOBAL_INDEX_I32 = 13
case MEMORY_ADDR_LEB64 = 14
case MEMORY_ADDR_SLEB64 = 15
case MEMORY_ADDR_I64 = 16
case MEMORY_ADDR_REL_SLEB64 = 17
case TABLE_INDEX_SLEB64 = 18
case TABLE_INDEX_I64 = 19
// case TABLE_NUMBER_LEB = 20
// case MEMORY_ADDR_TLS_SLEB = 21
// case FUNCTION_OFFSET_I64 = 22
case MEMORY_ADDR_SELFREL_I32 = 23
}
let LIMITS_HAS_MAX_FLAG: UInt8 = 0x1
let LIMITS_IS_SHARED_FLAG: UInt8 = 0x2
struct Limits {
var initial: Size
var max: Size?
var isShared: Bool
}
enum LinkingEntryType: UInt8 {
case segmentInfo = 5
case initFunctions = 6
case comdatInfo = 7
case symbolTable = 8
}
enum SymbolType: UInt8 {
case function = 0
case data = 1
case global = 2
case section = 3
case event = 4
case table = 5
}
let SYMBOL_FLAG_UNDEFINED: UInt32 = 0x10
let SYMBOL_VISIBILITY_MASK: UInt32 = 0x4
let SYMBOL_BINDING_MASK: UInt32 = 0x3
let SYMBOL_BINDING_GLOBAL: UInt32 = 0x0
let SYMBOL_BINDING_WEAK: UInt32 = 0x1
let SYMBOL_BINDING_LOCAL: UInt32 = 0x2
let SYMBOL_VISIBILITY_DEFAULT: UInt32 = 0x0
let SYMBOL_VISIBILITY_HIDDEN: UInt32 = 0x4
let SYMBOL_EXPORTED: UInt32 = 0x20
let SYMBOL_EXPLICIT_NAME: UInt32 = 0x40
let SYMBOL_NO_STRIP: UInt32 = 0x80
let PAGE_SIZE: Int = 65536
let FUNC_TYPE_CODE: UInt8 = 0x60
| 22.55814 | 47 | 0.657388 |
76fcae4ebf5320cd1fad1af5c9e65d80895437b6
| 383 |
//
// CheckoutResponse.swift
// TamaraSDK
//
// Created by Chuong Dang on 4/23/20.
// Copyright © 2020 Tamara. All rights reserved.
//
import Foundation
struct TamaraCheckoutResponse: Codable {
var orderId: String?
var checkoutUrl: String
enum CodingKeys: String, CodingKey {
case orderId = "order_id"
case checkoutUrl = "checkout_url"
}
}
| 19.15 | 49 | 0.663185 |
bb45417b333b404a4f49dbf25067a7b0c5fdc3fa
| 5,868 |
//
// Copyright: Ambrosus Technologies GmbH
// Email: [email protected]
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import UIKit
/// Constants for colors used in the Application Interface
struct Colors {
/// The darkest background, used for Navigation and dark sections
static let darkElement1 = #colorLiteral(red: 0, green: 0, blue: 0.2509803922, alpha: 1)
/// A lighter shade of the darkest background for section headers and interactive text
static let darkElement2 = #colorLiteral(red: 0.0862745098, green: 0.1647058824, blue: 0.4980392157, alpha: 1)
/// The color for the shadows on floating elements
static let shadowColor = #colorLiteral(red: 0.04705882353, green: 0.03921568627, blue: 0.2980392157, alpha: 1)
/// The background for screens
static let background = #colorLiteral(red: 0.937254902, green: 0.937254902, blue: 0.9568627451, alpha: 1)
/// The color for all floating modules
static let module = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
/// A light color for titles on dark elements
static let navigationSectionContent = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
/// Used in cells for descriptive text
static let descriptionText = #colorLiteral(red: 0.4756369591, green: 0.4756369591, blue: 0.4756369591, alpha: 1)
/// A lighter description for timeline dates e.g. '2 days ago'
static let lightDescriptionText = #colorLiteral(red: 0.6642268896, green: 0.6642268896, blue: 0.6642268896, alpha: 1)
/// Unselected tab bar item tint color
static let unselectedTabTint = #colorLiteral(red: 0.7087258697, green: 0.7087258697, blue: 0.7087258697, alpha: 1)
/// The titles for modules, darker than information
static let detailTitleText = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
/// Used for detail modules information, lighter than detail titles
static let detailInfoText = #colorLiteral(red: 0.2666666667, green: 0.2666666667, blue: 0.2666666667, alpha: 1)
}
/// Constants for fonts used in the Application Interface
struct Fonts {
/// The title text for Navigation Bars
static let navigationBarTitle = UIFont.systemFont(ofSize: 20, weight: .medium)
/// The title text for table sections
static let sectionHeaderTitle = UIFont.systemFont(ofSize: 17, weight: .bold)
/// The title text for cells
static let cellTitle = UIFont.systemFont(ofSize: 14, weight: .medium)
/// The description text for cells e.g. Sep 17, 2017
static let cellDescription = UIFont.systemFont(ofSize: 13, weight: .light)
/// A lighter version of descriptions for additional information
static let cellLightDescription = UIFont.systemFont(ofSize: 11, weight: .light)
/// The title for detail module items
static let detailTitle = UIFont.systemFont(ofSize: 13, weight: .semibold)
/// The info for detail module items
static let detailInfo = UIFont.systemFont(ofSize: 12, weight: .regular)
}
/// Contains constants that are used app wide and theme settings for app wide elements
struct Interface {
private static let rootNavigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController
private static let screenSize = UIScreen.main.bounds
static let screenWidth = screenSize.width
static let screenHeight = screenSize.height
static let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
static var isNavigationBarHidden: Bool {
return rootNavigationController?.isNavigationBarHidden ?? false
}
static func applyNavigationBarTheme() {
let navigationBarAppearance = UINavigationBar.appearance()
navigationBarAppearance.barTintColor = Colors.darkElement1
navigationBarAppearance.tintColor = Colors.navigationSectionContent
navigationBarAppearance.titleTextAttributes = [NSAttributedStringKey.foregroundColor: Colors.navigationSectionContent,
NSAttributedStringKey.font: Fonts.navigationBarTitle]
navigationBarAppearance.isTranslucent = false
}
static func applyTabBarTheme() {
let tabBarAppearance = UITabBar.appearance()
tabBarAppearance.barTintColor = Colors.darkElement1
tabBarAppearance.tintColor = Colors.navigationSectionContent
tabBarAppearance.unselectedItemTintColor = Colors.unselectedTabTint
tabBarAppearance.isTranslucent = false
}
}
extension UITabBar {
func centerItems() {
guard let items = items else {
return
}
let centeredImageEdgeInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
for item in items {
item.imageInsets = centeredImageEdgeInsets
}
}
}
| 47.707317 | 261 | 0.719325 |
9cad875ee38938667fdf14e5c8ff5662096d0727
| 416 |
// RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{
{
{
{
}
{} }struct c{
{
{}}let h=a<1
{{
A{{ {class{{{{ {
}
{ {{{}}}} }}}}}}}}}}class S{func ah{a {
}
class A{var d{
{
{
}
{
{
}}}class S{ {
}{}
struct Q< = {f
struct d {
class AA{var:{
a=f
func
| 12.606061 | 87 | 0.588942 |
624b9b961524583a9387d70d0ea923275a41ed0d
| 2,142 |
//
// AppDelegate.swift
// Todo-List
//
// Created by Kevin Liao on 7/5/15.
// Copyright (c) 2015 Kevin Liao. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.574468 | 285 | 0.752568 |
b99aa351197534a55d4ac90f3a06a6f0e219f529
| 2,235 |
//
// ListViewController.swift
// StoriesLayout_Example
//
// Created by Andrea Altea on 02/06/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import PowerTools
import StoriesLayout
import SafariLayout
class ListViewController: UIViewController {
weak var collectionView: UICollectionView!
var dataSource: GridCollectionDataSource!
var layouts: [ItemViewModel] = [
LayoutItemViewModel(descriptor:MyStoriesCollectionViewCell.Descriptor()) { StoriesCollectionViewLayout() },
LayoutItemViewModel(descriptor:MySafariCollectionViewCell.Descriptor()) { SafariCollectionViewLayout() }
]
override func viewDidLoad() {
super.viewDidLoad()
setupCollection()
setupCells()
setupDataSource()
}
func setupCollection() {
let collection = UICollectionView(frame: .zero,
collectionViewLayout: UICollectionViewFlowLayout())
collection.translatesAutoresizingMaskIntoConstraints = false
collection.backgroundColor = .white
view.addSubview(collection)
view.topAnchor.constraint(equalTo: collection.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: collection.bottomAnchor).isActive = true
view.leftAnchor.constraint(equalTo: collection.leftAnchor).isActive = true
view.rightAnchor.constraint(equalTo: collection.rightAnchor).isActive = true
self.collectionView = collection
}
func setupCells() {
layouts.forEach { item in
self.collectionView.register(UINib(nibName: item.descriptor.reuseIdentifier,
bundle: Bundle.main),
forCellWithReuseIdentifier: item.descriptor.reuseIdentifier)
}
}
func setupDataSource() {
self.dataSource = GridCollectionDataSource(view: collectionView,
model: [ConcreteGridSection(items: layouts)])
self.dataSource.interactionDelegate = self
}
}
extension ListViewController: InteractionFactory {
var context: UIViewController {
return self
}
}
| 34.384615 | 115 | 0.654586 |
9ce53771bce2d9a9945f331f6febb8a3a818d5ed
| 596 |
//
// TextField.swift
// TABTestKit
//
// Created by Kane Cheshire on 09/09/2019.
//
import XCTest
/// Represents a standard UITextField.
public struct TextField: Element, Editable, Tappable, ValueRepresentable {
public let id: String?
public let parent: Element
public let type: XCUIElement.ElementType = .textField
public var value: String { return underlyingXCUIElement.value as? String ?? "" }
public var placeholder: String? { return underlyingXCUIElement.placeholderValue }
public init(id: String, parent: Element = App.shared) {
self.id = id
self.parent = parent
}
}
| 23.84 | 82 | 0.729866 |
265fae480e39c5e71eceb9e3a77241e901fd8ad2
| 2,355 |
//
// SceneDelegate.swift
// Example
//
// Created by Вячеслав Яшунин on 03.07.2020.
// Copyright © 2020 Вячеслав Яшунин. All rights reserved.
//
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 neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.611111 | 147 | 0.714225 |
5d733911c5ef2d20593f2310bbe04eb120d65a77
| 3,989 |
//
// AST.swift
// Dumpling
//
// Created by Wojciech Chojnacki on 30/11/2019.
// Copyright © 2019 Wojciech Chojnacki. All rights reserved.
//
import Foundation
public protocol ASTNode {
var children: [ASTNode] { get }
}
extension ASTNode {
static var typeName: String { "\(type(of: self))" }
var typeName: String {
Self.typeName
}
}
public struct AST {
public struct TextNode: ASTNode {
public let children: [ASTNode] = []
public let text: String
public init(_ text: String) {
self.text = text
}
public init(_ character: Character) {
text = String(character)
}
public init(_ text: Substring) {
self.text = String(text)
}
}
public struct StyleNode: ASTNode {
public let children: [ASTNode]
public let id: StyleID
public init(id: StyleID, children: [ASTNode]) {
self.children = children
self.id = id
}
}
public struct ParagraphNode: ASTNode {
public let children: [ASTNode]
public init(children: [ASTNode]) {
self.children = children
}
}
public struct HeaderNode: ASTNode {
public let children: [ASTNode]
public let size: Int
public init(size: Int, children: [ASTNode]) {
self.size = size
self.children = children
}
}
public struct NewLineNode: ASTNode {
public let children = [ASTNode]()
public let soft: Bool
public init(soft: Bool) {
self.soft = soft
}
}
public struct EOFNode: ASTNode {
public var children = [ASTNode]()
public init() {}
}
public struct SpaceNode: ASTNode {
public var children = [ASTNode]()
public let count: Int
public init(count: Int) {
self.count = count
}
}
public struct LinkNode: ASTNode {
public enum LinkValue: Equatable {
case inline(String)
case reference(String)
}
public let children: [ASTNode]
public let link: LinkValue
public let title: String?
public init(text: String, link: LinkValue, title: String?) {
children = [AST.TextNode(text)]
self.link = link
self.title = title
}
}
public struct CodeNode: ASTNode {
public let children: [ASTNode]
public let params: String?
public let isBlock: Bool
public init(params: String?, body: String, isBlock: Bool) {
children = [AST.TextNode(body)]
self.params = params
self.isBlock = isBlock
}
}
public struct ListNode: ASTNode {
public enum Kind {
public enum Delimeter: Equatable {
case period
case paren
}
case bullet
case ordered(start: Int, delimeter: Delimeter)
}
public let children: [ASTNode]
public let kind: Kind
public let level: Int
public init(kind: Kind, level: Int, children: [ListElementNode]) {
self.children = children
self.kind = kind
self.level = level
}
}
public struct ListElementNode: ASTNode {
public let children: [ASTNode]
public init(children: [ASTNode]) {
self.children = children
}
}
public struct HorizontalLineNode: ASTNode {
public let children: [ASTNode] = []
public init() {}
}
public struct BlockquoteNode: ASTNode {
public let children: [ASTNode]
public init(children: [ASTNode]) {
self.children = children
}
}
public struct RootNode: ASTNode {
public let children: [ASTNode]
public init(children: [ASTNode]) {
self.children = children
}
}
}
| 23.60355 | 74 | 0.544497 |
eb25552e42e17246ac9643b56dd7edf29d801d45
| 7,205 |
//
// ViewController.swift
// Meme_1
//
// Created by admin on 11/11/18.
// Copyright © 2018 admin. All rights reserved.
//
import UIKit
class MemeCreationController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
//MARK:- UI Var
var currentIndex = 0
var currentMeme: Meme? {
didSet{
backgroundImageView.image = currentMeme?.originalImage
topTextField.text = currentMeme?.top
bottomTextField.text = currentMeme?.bottom
}
}
var backgroundImageView: UIImageView = {
var imageView = UIImageView()
imageView.backgroundColor = UIColor.black
imageView.isUserInteractionEnabled = true
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
var topTextField: UITextField = {
var textField = UITextField()
textField.backgroundColor = UIColor.clear
textField.borderStyle = .none
textField.clearsOnBeginEditing = true
let memeTextAttributes:[NSAttributedString.Key: Any] = [
NSAttributedString.Key.strokeColor: UIColor.black,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSAttributedString.Key.strokeWidth: -4.6
]
textField.defaultTextAttributes = memeTextAttributes
let memeText = NSMutableAttributedString(string: "TOP", attributes: memeTextAttributes)
textField.attributedText = memeText
textField.textAlignment = .center
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
var bottomTextField: UITextField = {
var textField = UITextField()
textField.backgroundColor = UIColor.clear
textField.borderStyle = .none
textField.clearsOnBeginEditing = true
let memeTextAttributes:[NSAttributedString.Key: Any] = [
NSAttributedString.Key.strokeColor: UIColor.black,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSAttributedString.Key.strokeWidth: -4.6
]
textField.defaultTextAttributes = memeTextAttributes
let memeText = NSMutableAttributedString(string: "BOTTOM", attributes: memeTextAttributes)
textField.attributedText = memeText
textField.textAlignment = .center
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
func setupTextFieldAndBackgroundImage(){
[backgroundImageView].forEach{view.addSubview($0)}
[topTextField, bottomTextField].forEach{backgroundImageView.addSubview($0)}
NSLayoutConstraint.activate([
topTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
topTextField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 90),
bottomTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
bottomTextField.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -90),
backgroundImageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
backgroundImageView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
backgroundImageView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
backgroundImageView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
]
)
}
//MARK: Toolbars
var topToolbar: UIToolbar = {
var toolbar = UIToolbar()
toolbar.barTintColor = UIColor.lightGray
toolbar.isTranslucent = false
toolbar.translatesAutoresizingMaskIntoConstraints = false
return toolbar
}()
var bottomToolbar: UIToolbar = {
var toolbar = UIToolbar()
toolbar.barTintColor = UIColor.lightGray
toolbar.isTranslucent = false
toolbar.translatesAutoresizingMaskIntoConstraints = false
return toolbar
}()
//MARK:- Constraints
func setupUI_and_Contraints(){
setupTopToolBar()
setupBottomToolBar()
[topToolbar, bottomToolbar].forEach{backgroundImageView.addSubview($0)}
NSLayoutConstraint.activate([
topToolbar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
topToolbar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
topToolbar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
bottomToolbar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
bottomToolbar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
bottomToolbar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
}
//MARK:- Override Swift Functions
override var prefersStatusBarHidden: Bool {
return true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
subscribeToKeyboardNotification()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
unsubscribeToKeyboardNotification()
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.black
setupTextFieldAndBackgroundImage()
setupUI_and_Contraints()
[topTextField, bottomTextField].forEach{
$0.addTarget(self, action: #selector(myTextFieldTextChanged), for: UIControl.Event.editingChanged)
$0.delegate = self
}
if currentMeme != nil {
loadAllGestures()
showTopAndBottomToolbars(makeVisible: false)
}
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(handleActivityBarButton))
}
//MARK:- Handler Functions <---> currentMeme? != nil
@objc func handleActivityBarButton() {
let currentMeme2 = saveMeme2()
let myAppDelegate = UIApplication.shared.delegate as! AppDelegate
myAppDelegate.memes.append(currentMeme2)
let items = [currentMeme2.finalImage]
let activityVC = UIActivityViewController(activityItems: items, applicationActivities: nil)
activityVC.completionWithItemsHandler = {[unowned self](activityType: UIActivity.ActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) in
if !completed {
return
}
self.navigationController?.popViewController(animated: true)
}
present(activityVC, animated: true)
}
func saveMeme2()-> Meme {
let currentMeme = Meme(topTxtField: topTextField, bottomTxtField: bottomTextField, originalImageView: backgroundImageView, memeImage: generateMemedImage())
return currentMeme
}
}
| 41.889535 | 163 | 0.687717 |
e27658a75d4cef2c9c9522eecfc97515a831cbad
| 668 |
//
// CastViewModel.swift
// RxFlowDemo
//
// Created by Thibault Wittemberg on 17-12-06.
// Copyright (c) RxSwiftCommunity. All rights reserved.
//
class CastDetailViewModel: ServicesViewModel {
typealias Services = HasMoviesService
var services: Services! {
didSet {
let cast = self.services.moviesService.cast(forId: castId)
self.name = cast.name
self.image = cast.image
self.bio = cast.bio
}
}
private(set) var name = ""
private(set) var image = ""
private(set) var bio = ""
public let castId: Int
init(withCastId id: Int) {
self.castId = id
}
}
| 20.875 | 70 | 0.598802 |
26b5554804776bdbe2fc3bec5d5fb3cb31633b92
| 4,285 |
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONTEXT | %FileCheck %s -check-prefix=CONTEXT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONTEXT_VARNAME | %FileCheck %s -check-prefix=CONTEXT_VARNAME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONTEXT_STORAGE_VARNAME | %FileCheck %s -check-prefix=CONTEXT_STORAGE_VARNAME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SELF | %FileCheck %s -check-prefix=CONTEXT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SELF_VARNAME | %FileCheck %s -check-prefix=CONTEXT_VARNAME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SELF_STORAGE_VARNAME | %FileCheck %s -check-prefix=CONTEXT_STORAGE_VARNAME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PARAM | %FileCheck %s -check-prefix=PARAM
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PARAM_CLOSURE | %FileCheck %s -check-prefix=PARAM
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=LOCAL | %FileCheck %s -check-prefix=LOCAL
@propertyWrapper
struct Lazzzy<T> {
var wrappedValue: T
var projectedValue: String { "" }
init(wrappedValue: T) { fatalError() }
func delegateOperation() -> Int {}
}
struct MyMember {
var x: Int
var y: Int
static var zero = MyMember(x: 0, y: 0)
}
class MyClass {
@Lazzzy<MyMember>
var foo = .zero
func test() {
let _ = #^CONTEXT^#
// CONTEXT: Begin completions
// CONTEXT-DAG: Decl[InstanceVar]/CurrNominal: foo[#MyMember#];
// CONTEXT-DAG: Decl[InstanceVar]/CurrNominal: $foo[#String#];
// CONTEXT-DAG: Decl[InstanceVar]/CurrNominal: _foo[#Lazzzy<MyMember>#];
// CONTEXT: End completions
let _ = foo.#^CONTEXT_VARNAME^#
// CONTEXT_VARNAME: Begin completions, 3 items
// CONTEXT_VARNAME-DAG: Keyword[self]/CurrNominal: self[#MyMember#]; name=self
// CONTEXT_VARNAME-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#]; name=x
// CONTEXT_VARNAME-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#]; name=y
// CONTEXT_VARNAME-NOT: _
// CONTEXT_VARNAME-DAG: End completions
let _ = _foo.#^CONTEXT_STORAGE_VARNAME^#
// CONTEXT_STORAGE_VARNAME: Begin completions, 4 items
// CONTEXT_STORAGE_VARNAME-DAG: Keyword[self]/CurrNominal: self[#Lazzzy<MyMember>#]; name=self
// CONTEXT_STORAGE_VARNAME-DAG: Decl[InstanceVar]/CurrNominal: wrappedValue[#MyMember#]; name=wrappedValue
// CONTEXT_STORAGE_VARNAME-DAG: Decl[InstanceVar]/CurrNominal: projectedValue[#String#]; name=projectedValue
// CONTEXT_STORAGE_VARNAME-DAG: Decl[InstanceMethod]/CurrNominal: delegateOperation()[#Int#]; name=delegateOperation()
// CONTEXT_STORAGE_VARNAME-NOT: _
// CONTEXT_STORAGE_VARNAME: End completions
let _ = self.#^SELF^#
// Same as CONTEXT.
let _ = self.foo.#^SELF_VARNAME^#
// Same as CONTEXT_VARNAME.
let _ = self._foo.#^SELF_STORAGE_VARNAME^#
// Same as CONTEXT_STORAGE_VARNAME.
}
}
func paramTest(@Lazzzy arg: MyMember) {
#^PARAM^#
// PARAM: Begin completions
// PARAM-DAG: Decl[LocalVar]/Local: arg[#MyMember#]; name=arg
// PARAM-DAG: Decl[LocalVar]/Local: $arg[#String#]; name=$arg
// PARAM-DAG: Decl[LocalVar]/Local: _arg[#Lazzzy<MyMember>#]; name=_arg
// PARAM-DAG: Decl[FreeFunction]/CurrModule: paramTest({#arg: MyMember#})[#Void#]; name=paramTest(arg:)
// PARAM: End completions
}
func closureTest() {
func receive(fn: (MyMember) -> Void) {}
receive { (@Lazzzy arg: MyMember) in
#^PARAM_CLOSURE^#
// Same as PARAM
}
}
func localTest() {
@Lazzzy var local: MyMember = .zero
#^LOCAL^#
// LOCAL: Begin completions
// LOCAL-DAG: Decl[LocalVar]/Local: local[#MyMember#]; name=local
// LOCAL-DAG: Decl[LocalVar]/Local: $local[#String#]; name=$local
// LOCAL-DAG: Decl[LocalVar]/Local: _local[#Lazzzy<MyMember>#]; name=_local
// LOCAL-DAG: Decl[FreeFunction]/CurrModule: paramTest({#arg: MyMember#})[#Void#]; name=paramTest(arg:)
// LOCAL: End completions
}
| 43.282828 | 168 | 0.701984 |
e56b3ce04a8c55e7b69dba85673171071623d52c
| 8,060 |
// The MIT License (MIT)
// Copyright © 2017 Ivan Varabei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class SPMengTransformCollectionViewCell: SPCollectionViewCell {
let backgroundImageView = SPDownloadingImageView()
let titleLabel = UILabel()
let subtitleLabel = UILabel()
let gradientView = SPGradientView.init()
let gradeView = UIView()
let shadowContainerView = UIView()
var withShadow: Bool = true {
didSet {
if self.withShadow {
shadowContainerView.layer.shadowOpacity = 0.25
shadowContainerView.layer.shadowOffset = CGSize.init(width: 0, height: 10)
shadowContainerView.layer.shadowRadius = 20
} else {
shadowContainerView.layer.shadowOpacity = 0
shadowContainerView.layer.shadowOffset = CGSize.init(width: 0, height: 0)
shadowContainerView.layer.shadowRadius = 0
}
}
}
override func commonInit() {
shadowContainerView.backgroundColor = UIColor.white
shadowContainerView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(shadowContainerView)
shadowContainerView.leadingAnchor.constraint(equalTo:
self.leadingAnchor).isActive = true
shadowContainerView.trailingAnchor.constraint(equalTo:
self.trailingAnchor).isActive = true
shadowContainerView.topAnchor.constraint(equalTo:
self.topAnchor, constant: 0).isActive = true
shadowContainerView.bottomAnchor.constraint(equalTo:
self.bottomAnchor, constant: 0).isActive = true
let contentView = UIView()
contentView.backgroundColor = UIColor.clear
contentView.translatesAutoresizingMaskIntoConstraints = false
shadowContainerView.addSubview(contentView)
contentView.leadingAnchor.constraint(equalTo:
shadowContainerView.leadingAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo:
shadowContainerView.trailingAnchor).isActive = true
contentView.topAnchor.constraint(equalTo:
shadowContainerView.topAnchor, constant: 0).isActive = true
contentView.bottomAnchor.constraint(equalTo:
shadowContainerView.bottomAnchor, constant: 0).isActive = true
self.backgroundImageView.contentMode = .scaleAspectFill
self.backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
self.backgroundImageView.layer.masksToBounds = false
contentView.addSubview(self.backgroundImageView)
self.backgroundImageView.leadingAnchor.constraint(equalTo:
contentView.leadingAnchor, constant: 0).isActive = true
self.backgroundImageView.trailingAnchor.constraint(equalTo:
contentView.trailingAnchor, constant: 0).isActive = true
self.backgroundImageView.topAnchor.constraint(equalTo:
contentView.topAnchor, constant: 0).isActive = true
self.backgroundImageView.bottomAnchor.constraint(equalTo:
contentView.bottomAnchor, constant: 0).isActive = true
self.gradientView.startColorPosition = .topLeft
self.gradientView.endColorPosition = .bottomRight
self.gradientView.isHidden = true
self.gradientView.translatesAutoresizingMaskIntoConstraints = false
self.gradientView.layer.masksToBounds = false
contentView.addSubview(self.gradientView)
self.gradientView.leadingAnchor.constraint(equalTo:
contentView.leadingAnchor).isActive = true
self.gradientView.trailingAnchor.constraint(equalTo:
contentView.trailingAnchor).isActive = true
self.gradientView.topAnchor.constraint(equalTo:
contentView.topAnchor, constant: 0).isActive = true
self.gradientView.bottomAnchor.constraint(equalTo:
contentView.bottomAnchor, constant: 0).isActive = true
self.gradeView.isHidden = true
self.gradeView.backgroundColor = UIColor.black
self.gradeView.alpha = 0
self.gradeView.translatesAutoresizingMaskIntoConstraints = false
self.gradeView.layer.masksToBounds = false
contentView.addSubview(self.gradeView)
self.gradeView.leadingAnchor.constraint(equalTo:
contentView.leadingAnchor).isActive = true
self.gradeView.trailingAnchor.constraint(equalTo:
contentView.trailingAnchor).isActive = true
self.gradeView.topAnchor.constraint(equalTo:
contentView.topAnchor, constant: 0).isActive = true
self.gradeView.bottomAnchor.constraint(equalTo:
contentView.bottomAnchor, constant: 0).isActive = true
contentView.layer.masksToBounds = true
shadowContainerView.layer.cornerRadius = 14
contentView.layer.cornerRadius = 14
self.titleLabel.text = ""
self.titleLabel.setDeepShadowForLetters()
self.titleLabel.translatesAutoresizingMaskIntoConstraints = false
self.titleLabel.font = UIFont.system(weight: .demiBold, size: 32)
self.titleLabel.textColor = UIColor.white
self.titleLabel.numberOfLines = 0
contentView.addSubview(self.titleLabel)
self.titleLabel.leadingAnchor.constraint(equalTo:
contentView.leadingAnchor, constant: 20).isActive = true
self.titleLabel.trailingAnchor.constraint(equalTo:
contentView.trailingAnchor, constant: -20).isActive = true
self.titleLabel.topAnchor.constraint(equalTo:
contentView.topAnchor, constant: 20).isActive = true
self.subtitleLabel.text = ""
self.subtitleLabel.setDeepShadowForLetters()
self.subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
self.subtitleLabel.font = UIFont.system(weight: .regular, size: 17)
self.subtitleLabel.textColor = UIColor.white
self.subtitleLabel.numberOfLines = 0
contentView.addSubview(self.subtitleLabel)
self.subtitleLabel.leadingAnchor.constraint(equalTo:
contentView.leadingAnchor, constant: 20).isActive = true
self.subtitleLabel.trailingAnchor.constraint(equalTo:
contentView.trailingAnchor, constant: -20).isActive = true
self.subtitleLabel.bottomAnchor.constraint(equalTo:
contentView.bottomAnchor, constant: -20).isActive = true
}
override func prepareForReuse() {
super.prepareForReuse()
self.backgroundImageView.image = nil
self.titleLabel.text = ""
self.subtitleLabel.text = ""
self.gradientView.isHidden = true
self.gradeView.alpha = 0
self.gradeView.isHidden = true
self.titleLabel.isHidden = false
self.subtitleLabel.isHidden = false
self.titleLabel.alpha = 1
self.subtitleLabel.alpha = 1
}
}
| 47.411765 | 90 | 0.698263 |
1dc55b93e1416df787ce2671d3c067fa037f3b46
| 2,460 |
import Foundation
import azureSwiftRuntime
public protocol ApplicationSecurityGroupsDelete {
var headerParameters: [String: String] { get set }
var resourceGroupName : String { get set }
var applicationSecurityGroupName : String { get set }
var subscriptionId : String { get set }
var apiVersion : String { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (Error?) -> Void) -> Void;
}
extension Commands.ApplicationSecurityGroups {
// Delete deletes the specified application security group. This method may poll for completion. Polling can be
// canceled by passing the cancel channel argument. The channel will be used to cancel polling and any outstanding HTTP
// requests.
internal class DeleteCommand : BaseCommand, ApplicationSecurityGroupsDelete {
public var resourceGroupName : String
public var applicationSecurityGroupName : String
public var subscriptionId : String
public var apiVersion = "2018-01-01"
public init(resourceGroupName: String, applicationSecurityGroupName: String, subscriptionId: String) {
self.resourceGroupName = resourceGroupName
self.applicationSecurityGroupName = applicationSecurityGroupName
self.subscriptionId = subscriptionId
super.init()
self.method = "Delete"
self.isLongRunningOperation = true
self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName)
self.pathParameters["{applicationSecurityGroupName}"] = String(describing: self.applicationSecurityGroupName)
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
self.queryParameters["api-version"] = String(describing: self.apiVersion)
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (Error?) -> Void) -> Void {
client.executeAsyncLRO(command: self) {
(error) in
completionHandler(error)
}
}
}
}
| 48.235294 | 178 | 0.68252 |
26ded10250f611d2419a6a844e7fd5def38121dc
| 213 |
//
// Item.swift
// NSNumberFormatter
//
// Created by 伯驹 黄 on 2016/11/2.
// Copyright © 2016年 伯驹 黄. All rights reserved.
//
import Foundation
struct Item {
let methodName: String
let desc: String
}
| 14.2 | 48 | 0.652582 |
d9ab6773aea5eb6374d00df647112ebec48abcd6
| 4,256 |
//
// TestMerchantBackend.swift
// StashCore
//
// Created by Robert on 16.07.19.
// Copyright © 2019 MobiLab Solutions GmbH. All rights reserved.
//
import Foundation
class TestMerchantBackend {
private let endpoint: String
private let encoder = JSONEncoder()
private let decoder = JSONDecoder()
private let userId: String
init(endpoint: String = "https://payment-dev.mblb.net/merchant/v1", userId: String = "9os4fezF3QuS8EoV") {
self.endpoint = endpoint
self.userId = userId
}
private enum HTTPMethod: String {
case GET
case POST
case DELETE
case PUT
}
private struct CustomError: Error, CustomStringConvertible {
let description: String
}
func createPaymentMethod(alias: String, paymentMethodType: String, completion: @escaping (Result<TestMerchantPaymentMethod, Error>) -> Void) {
guard let url = URL(string: self.endpoint)?.appendingPathComponent("payment-method")
else { completion(.failure(CustomError(description: "Could not create the endpoint URL"))); return }
let request = CreatePaymentMethodRequest(aliasId: alias, type: paymentMethodType, userId: userId)
guard let encoded = try? self.encoder.encode(request)
else { completion(.failure(CustomError(description: "Could not serialize the request"))); return }
self.makeRequest(url: url, body: encoded, httpMethod: .POST, completion: completion)
}
func authorizePayment(payment: PaymentRequest, completion: @escaping (Result<TestMerchantAuthorization, Error>) -> Void) {
guard let url = URL(string: self.endpoint)?.appendingPathComponent("authorization")
else { completion(.failure(CustomError(description: "Could not create the endpoint URL"))); return }
guard let encoded = try? self.encoder.encode(payment)
else { completion(.failure(CustomError(description: "Could not serialize the request"))); return }
self.makeRequest(url: url, body: encoded, httpMethod: .PUT, completion: completion)
}
private func makeRequest<T: Codable>(url: URL, body: Data? = nil, httpMethod: HTTPMethod, completion: @escaping (Result<T, Error>) -> Void) {
var request = URLRequest(url: url)
request.httpMethod = httpMethod.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = body
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 10
print("Making Request to \(request.url?.absoluteString ?? "nil")")
print("Data: \(body.flatMap { String(data: $0, encoding: .utf8) } ?? "nil")")
let session = URLSession(configuration: sessionConfig)
session.dataTask(with: request) { data, response, err in
if let err = err {
completion(.failure(err))
return
}
print("Response: \(data.flatMap { String(data: $0, encoding: .utf8) } ?? "nil")")
guard let httpResponse = response as? HTTPURLResponse,
let data = data,
let deserialized = try? self.decoder.decode(T.self, from: data) else {
completion(.failure(CustomError(description: "Invalid response")))
return
}
if 200..<300 ~= httpResponse.statusCode {
completion(.success(deserialized))
} else {
completion(.failure(CustomError(description: "Unknown Error with status code \(httpResponse.statusCode)")))
}
}.resume()
}
}
private struct CreatePaymentMethodRequest: Codable {
let aliasId: String
let type: String
let userId: String
}
private struct CreateUserReqeust: Codable {}
private struct User: Codable {
let userId: String
}
struct TestMerchantPaymentMethod: Codable {
let paymentMethodId: String
}
struct TestMerchantAuthorization: Codable {
let additionalInfo: String?
let amount: Int?
let currency: String?
let status: String
let transactionId: String?
}
struct PaymentRequest: Codable {
let amount: Int
let currency: String
let paymentMethodId: String
let reason: String
}
| 34.885246 | 146 | 0.660714 |
1cea8c90cf072d7d4fa8260573e93efdb12032b5
| 767 |
//
// NNWTableViewCell.swift
// NetNewsWire-iOS
//
// Created by Jim Correia on 9/2/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import UIKit
class NNWTableViewCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
applyThemeProperties()
}
/// Subclass overrides should call super
func applyThemeProperties() {
let selectedBackgroundView = UIView(frame: .zero)
selectedBackgroundView.backgroundColor = AppAssets.primaryAccentColor
self.selectedBackgroundView = selectedBackgroundView
}
}
| 23.242424 | 76 | 0.750978 |
20bc06400de3b1b33a1fa20666bfe8a1068329da
| 14,128 |
//
// DUXBetaTakeOffWidgetModel.swift
// UXSDKFlight
//
// MIT License
//
// Copyright © 2018-2020 DJI
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import UXSDKCore
let kTakeOffHeight: Double = 1.2
let kPrecisionTakeOffHeight: Double = 6.0
let kLandHeight: Double = 0.3
/**
* Enum defining the state of the aircraft.
*/
@objc public enum DUXBetaTakeOffLandingState: Int {
public typealias RawValue = Int
/**
* The aircraft is ready to take off.
*/
case ReadyToTakeOff
/**
* The aircraft is currently flying and is ready to land.
*/
case ReadyToLand
/**
* The aircraft has started auto landing.
*/
case AutoLanding
/**
* The aircraft has started auto landing and it cannot be canceled.
*/
case ForcedAutoLanding
/**
* The aircraft has paused auto landing and is waiting for confirmation before continuing.
*/
case WaitingForLandingConfirmation
/**
* The aircraft has determined it is unsafe to land while auto landing is in progress
*/
case UnsafeToLand
/**
* The aircraft is returning to its home location.
*/
case ReturningHome
/**
* The aircraft cannot take off.
*/
case TakeOffDisabled
/**
* The aircraft cannot land.
*/
case LandDisabled
/**
* The aircraft is disconnected.
*/
case Disconnected
}
/**
* Data model for the DUXBetaTakeOffWidget used to define
* the underlying logic and communication.
*/
@objcMembers public class DUXBetaTakeOffWidgetModel: DUXBetaBaseWidgetModel {
/// The state of the model.
dynamic public var state: DUXBetaTakeOffLandingState = .Disconnected
/// The boolean value indicating if aircraft is flying.
dynamic public var isFlying = false
/// The boolean value indicating if aircraft is landing.
dynamic public var isLanding = false
/// The boolean value indicating if aircraft is going home.
dynamic public var isGoingHome = false
/// The boolean value indicating if aircraft has motors on.
dynamic public var areMotorsOn = false
/// The boolean value indicating if flight mode is ATTI.
dynamic public var isInAttiMode = false
/// The boolean value indicating if aircraft requires landing confirmation.
dynamic public var isLandingConfirmationNeeded = false
/// The boolean value indicating if aircraft supports precision take off.
dynamic public var isPrecisionTakeoffSupported = false
/// The boolean value indicating if auto landing is disabled.
dynamic public var isCancelAutoLandingDisabled = false
/// The boolean value indicating if the aircraft is an Inspire2 or any of Matrice200 series.
dynamic public var isInspire2OrMatrice200Series = false
/// The confirmation height limit when auto landing.
dynamic public var forcedLandingHeight: Int = Int.min
/// The model name of the aircraft.
dynamic public var modelName: String = ""
/// The flight mode of the aircraft.
dynamic public var flightMode: DJIFlightMode = .unknown
/// The remote control mode of the aircraft.
dynamic public var remoteControlMode: DJIRCMode = .unknown
/// The landing protection state of the aircraft.
dynamic public var landingProtectionState: DJIVisionLandingProtectionState = .none
/// The module handling the unit type related logic
dynamic public var unitModule = DUXBetaUnitTypeModule()
/// Get the height the aircraft will reach after takeoff.
public var takeOffHeight: Double {
return kTakeOffHeight
}
/// Get the height the aircraft will reach after a precision takeoff
public var precisionTakeOffHeight: Double {
return kPrecisionTakeOffHeight
}
/// Get the current height of the aircraft while waiting for landing confirmation.
public var landHeight: Double {
if forcedLandingHeight != Int.min {
return Double(forcedLandingHeight) * 0.1
}
return kLandHeight
}
public override init() {
super.init()
add(unitModule)
}
/**
* Override of parent inSetup method that binds properties to keys
* and attaches method callbacks on properties updates.
*/
override public func inSetup() {
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamIsFlying) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.isFlying).toString)
}
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamIsLanding) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.isLanding).toString)
}
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamIsGoingHome) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.isGoingHome).toString)
}
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamFlightMode) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.flightMode).toString)
}
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamForceLandingHeight) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.forcedLandingHeight).toString)
}
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamIsLandingConfirmationNeeded) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.isLandingConfirmationNeeded).toString)
}
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamAreMotorsOn) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.areMotorsOn).toString)
}
if let key = DJIRemoteControllerKey(param: DJIRemoteControllerParamMode) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.remoteControlMode).toString)
}
if let key = DJIProductKey(param: DJIProductParamModelName) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.modelName).toString)
}
if let key = DJIFlightControllerKey(param: DJIFlightAssistantParamPrecisionLandingEnabled) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.isPrecisionTakeoffSupported).toString)
}
if let key = DJIFlightControllerKey(index: 0,
subComponent: DJIFlightControllerFlightAssistantSubComponent,
subComponentIndex: 0,
andParam: DJIFlightControllerParamLandingProtectionState) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.landingProtectionState).toString)
}
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamIsCancelAutoLandingDisabled) {
bindSDKKey(key, (\DUXBetaTakeOffWidgetModel.isCancelAutoLandingDisabled).toString)
}
bindRKVOModel(self, #selector(updateIsInAttiMode), (\DUXBetaTakeOffWidgetModel.flightMode).toString)
bindRKVOModel(self, #selector(updateIsInspire2OrMatrice200Series), (\DUXBetaTakeOffWidgetModel.modelName).toString)
bindRKVOModel(self, #selector(updateState),
(\DUXBetaTakeOffWidgetModel.isFlying).toString,
(\DUXBetaTakeOffWidgetModel.isLanding).toString,
(\DUXBetaTakeOffWidgetModel.isGoingHome).toString,
(\DUXBetaTakeOffWidgetModel.isInAttiMode).toString,
(\DUXBetaTakeOffWidgetModel.forcedLandingHeight).toString,
(\DUXBetaTakeOffWidgetModel.isLandingConfirmationNeeded).toString,
(\DUXBetaTakeOffWidgetModel.areMotorsOn).toString,
(\DUXBetaTakeOffWidgetModel.remoteControlMode).toString,
(\DUXBetaTakeOffWidgetModel.isInspire2OrMatrice200Series).toString,
(\DUXBetaTakeOffWidgetModel.isPrecisionTakeoffSupported).toString,
(\DUXBetaTakeOffWidgetModel.landingProtectionState).toString,
(\DUXBetaTakeOffWidgetModel.isCancelAutoLandingDisabled).toString,
(\DUXBetaTakeOffWidgetModel.isProductConnected).toString)
}
/**
* Override of parent inCleanup method that unbinds properties from keys
* and detaches methods callbacks.
*/
override public func inCleanup() {
unbindSDK(self)
unbindRKVOModel(self)
}
/**
* Performs take off action.
*/
public func performTakeOffAction(_ completion: @escaping DUXBetaWidgetModelActionCompletionBlock) {
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamStartTakeoff) {
DJISDKManager.keyManager()?.performAction(for: key, withArguments: nil, andCompletion: { (finished, response, error) in
completion(error)
})
} else {
completion(nil)
}
}
/**
* Performs precision take off action.
*/
public func performPrecisionTakeOffAction(_ completion: @escaping DUXBetaWidgetModelActionCompletionBlock) {
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamStartPrecisionTakeoff) {
DJISDKManager.keyManager()?.performAction(for: key, withArguments: nil, andCompletion: { (finished, response, error) in
completion(error)
})
} else {
completion(nil)
}
}
/**
* Performs landing action.
*/
public func performLandingAction(_ completion: @escaping DUXBetaWidgetModelActionCompletionBlock) {
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamAutoLanding) {
DJISDKManager.keyManager()?.performAction(for: key, withArguments: nil, andCompletion: { (finished, response, error) in
completion(error)
})
} else {
completion(nil)
}
}
/**
* Performs the landing confirmation action. This allows aircraft to land when
* landing confirmation is received.
*/
public func performLandingConfirmationAction(_ completion: @escaping DUXBetaWidgetModelActionCompletionBlock) {
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamConfirmLanding) {
DJISDKManager.keyManager()?.performAction(for: key, withArguments: nil, andCompletion: { (finished, response, error) in
completion(error)
})
} else {
completion(nil)
}
}
/**
* Performs cancel landing action.
*/
public func performCancelLandingAction(_ completion: @escaping DUXBetaWidgetModelActionCompletionBlock) {
if let key = DJIFlightControllerKey(param: DJIFlightControllerParamCancelAutoLanding) {
DJISDKManager.keyManager()?.performAction(for: key, withArguments: nil, andCompletion: { (finished, response, error) in
completion(error)
})
} else {
completion(nil)
}
}
/**
* Updates the isInAttiMode property based of the flightMode value.
*/
public func updateIsInAttiMode() {
isInAttiMode = flightMode == .atti || flightMode == .attiCourseLock || flightMode == .gpsAtti || flightMode == .gpsAttiWristband
}
/**
* Updates the isInspire2OrMatrice200Series property based of the aircraft model name.
*/
public func updateIsInspire2OrMatrice200Series() {
isInspire2OrMatrice200Series = modelName == DJIAircraftModelNameInspire2 || ProductUtil.isMatrice200Series()
}
/**
* Updates the state property based on several flight status properties.
* It gets called anytime a change is detected in the underlying variables.
*/
public func updateState() {
var nextState: DUXBetaTakeOffLandingState = .Disconnected
if isProductConnected {
if isLanding {
if cancelAutoLandingDisabled {
nextState = .ForcedAutoLanding
} else if landingProtectionState == .notSafeToLand {
nextState = .UnsafeToLand
} else if isLandingConfirmationNeeded {
nextState = .WaitingForLandingConfirmation
} else {
nextState = .AutoLanding
}
} else if isGoingHome {
nextState = .ReturningHome
} else if !areMotorsOn {
if remoteControlMode == .slave {
nextState = .TakeOffDisabled
} else {
nextState = .ReadyToTakeOff
}
} else {
if remoteControlMode == .slave {
nextState = .LandDisabled
} else {
nextState = .ReadyToLand
}
}
}
if nextState != state {
state = nextState
}
}
fileprivate var cancelAutoLandingDisabled: Bool {
return isCancelAutoLandingDisabled || remoteControlMode == .slave
}
}
| 40.83237 | 136 | 0.660108 |
ebc5ab9bdbd8d3dffa7a85353dc60daa7a932230
| 2,145 |
//
// AppDelegate.swift
// 06-TextKit
//
// Created by Clay Tinnell on 1/2/16.
// Copyright © 2016 Clay Tinnell. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.638298 | 285 | 0.75338 |
bffac996dc690f1c7267f1cfa9ea6e33a70dadb2
| 3,814 |
//
// AppDelegate.swift
// MovieScoop
//
// Created by Sabareesh Kappagantu on 3/29/17.
// Copyright © 2017 Sabareesh Kappagantu. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nowPlayingNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController
let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MoviesViewController
nowPlayingViewController.endpoint = "now_playing"
nowPlayingNavigationController.tabBarItem.title = "Now Playing"
nowPlayingNavigationController.tabBarItem.image = UIImage(named: "now_playing")
let topRatedNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController
let topRatedViewController = topRatedNavigationController.topViewController as! MoviesViewController
topRatedViewController.endpoint = "top_rated"
topRatedNavigationController.tabBarItem.title = "Top Rated"
topRatedNavigationController.tabBarItem.image = UIImage(named: "top_rated")
let tabBarController = UITabBarController()
tabBarController.tabBar.backgroundColor = UIColor.magenta
tabBarController.tabBar.barTintColor = UIColor.black
tabBarController.tabBar.tintColor = UIColor.black
tabBarController.tabBar.alpha = 0.8
tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController]
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 50.853333 | 285 | 0.751442 |
acede4747af1134c4817c2522b0c6103931eb8ef
| 6,850 |
//
// UserFeedback.swift
// RelistenShared
//
// Created by Jacob Farkas on 8/23/18.
// Copyright © 2018 Alec Gorge. All rights reserved.
//
import Foundation
import PinpointKit
import CWStatusBarNotification
import Realm
import RealmConverter
public class UserFeedback {
static public let shared = UserFeedback()
let pinpointKit : PinpointKit
var screenshotDetector : ScreenshotDetector?
var currentNotification : CWStatusBarNotification?
public init() {
let versionString = "Relisten \(RelistenApp.appVersion) (\(RelistenApp.appBuildVersion))"
var feedbackConfig = FeedbackConfiguration(recipients: ["[email protected]"])
feedbackConfig.title = "[Bug Report: \(versionString)]"
feedbackConfig.body = "\n\n\n[Please write a brief description of the problem you're seeing above this line]\n\n\nConfiguration Information (Please don't delete):\n\t\(versionString)\n\tCrash log identifier \(RelistenApp.sharedApp.crashlyticsUserIdentifier)"
let config = Configuration(logCollector: RelistenLogCollector(), feedbackConfiguration: feedbackConfig)
pinpointKit = PinpointKit(configuration: config)
}
public func setup() {
screenshotDetector = ScreenshotDetector(delegate: self)
}
public func presentFeedbackView(from vc: UIViewController? = nil, screenshot : UIImage? = nil) {
guard let viewController = vc ?? RelistenApp.sharedApp.delegate.rootNavigationController else { return }
if let screenshot = screenshot {
currentNotification?.dismiss()
pinpointKit.show(from: viewController, screenshot: screenshot)
} else {
currentNotification?.dismiss() {
// If I grab the screenshot immediately there's still a tiny line from the notification animating away. If I let the runloop run for just a bit longer then the screenshot doesn't pick up that turd.
DispatchQueue.main.async {
self.pinpointKit.show(from: viewController, screenshot: Screenshotter.takeScreenshot())
}
}
}
}
public func requestUserFeedback(from vc : UIViewController? = nil, screenshot : UIImage? = nil) {
currentNotification?.dismiss()
let notification = CWStatusBarNotification()
notification.notificationTappedBlock = {
self.presentFeedbackView(screenshot: screenshot)
}
notification.notificationStyle = .navigationBarNotification
notification.notificationLabelBackgroundColor = AppColors.highlight
notification.notificationLabelFont = UIFont.preferredFont(forTextStyle: .headline)
currentNotification = notification
currentNotification?.display(withMessage: "🐞 Tap here to report a bug 🐞", forDuration: 3.0)
}
}
extension UserFeedback : ScreenshotDetectorDelegate {
public func screenshotDetector(_ screenshotDetector: ScreenshotDetector, didDetect screenshot: UIImage) {
requestUserFeedback(screenshot: screenshot)
}
public func screenshotDetector(_ screenshotDetector: ScreenshotDetector, didFailWith error: ScreenshotDetector.Error) {
}
}
class RelistenLogCollector : LogCollector {
public func retrieveLogs() -> [String] {
var retval : [String] = []
let fm = FileManager.default
let logDir = RelistenApp.logDirectory
// List offline tracks
do {
var isDir : ObjCBool = false
if fm.fileExists(atPath: DownloadManager.shared.downloadFolder, isDirectory: &isDir), isDir.boolValue {
retval.append("======= Offline Files =======")
for file in try fm.contentsOfDirectory(atPath: DownloadManager.shared.downloadFolder) {
retval.append("\t\(file)")
}
retval.append("======= End Offline Files =======\n\n")
}
} catch {
LogWarn("Error enumerating downloaded tracks: \(error)")
}
let group = DispatchGroup()
group.enter()
// Force a new thread so that Realm doesn't try to reuse an instance which errors out
// becuase no other instances use `dynamic = true`
let realmThread = Thread {
do {
let config = RLMRealmConfiguration()
config.dynamic = true
let realm = try RLMRealm.init(configuration: config)
let exporter = CSVDataExporter(realm: realm)
let tempDir = try self.createTemporaryDirectoy().path
defer {
do {
try fm.removeItem(atPath: tempDir)
} catch {
LogError("Caught error: \(error)")
LogError("Could not clean up \(tempDir)")
}
}
try exporter.export(toFolderAtPath: tempDir)
let csvs = try fm.contentsOfDirectory(atPath: tempDir)
for csvFile in csvs {
let data = try String(contentsOfFile: tempDir + "/" + csvFile, encoding: .utf8)
retval.append("======= Realm Table Dump (\(csvFile)) =======")
retval.append(contentsOf: data.components(separatedBy: .newlines))
retval.append("======= End Realm Table Dump (\(csvFile)) =======\n\n")
}
} catch {
LogWarn("Unable to dump Realm tables: \(error)")
}
group.leave()
}
realmThread.start()
group.wait()
// Grab the latest log file
autoreleasepool {
do {
if let logFile = try fm.contentsOfDirectory(atPath: logDir).sorted(by: { return $0 > $1 }).first {
let data = try String(contentsOfFile: logDir + "/" + logFile, encoding: .utf8)
retval.append("======= Latest Log File (\(logFile)) =======")
retval.append(contentsOf: data.components(separatedBy: .newlines))
retval.append("======= End Latest Log File (\(logFile)) =======\n\n")
}
} catch {
LogWarn("Couldn't read log file at \(logDir): \(error)")
}
}
return retval
}
func createTemporaryDirectoy() throws -> URL{
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
return url
}
}
| 41.26506 | 266 | 0.590949 |
ff710899647722bf08f37ec6237d31be756a3542
| 465 |
//: [Previous](@previous)
/*
고차함수란?
- 하나 이상의 함수를 인자로 취하는 함수
- 함수를 결과로 반환하는 함수
※ 고차 함수가 되기 위한 조건은 함수가 1급 객체여야 한다.
*/
/*
1급 객체 (First-class citizen)
- 변수나 데이터에 할당할 수 있어야 한다.
- 객체의 인자로 넘길 수 있어야 한다.
- 객체의 리턴값으로 리턴할 수 있어야 한다.
*/
func firstClassCitizen() {
print("function call")
}
func function(_ parameter: @escaping ()->()) -> (()->()) {
return parameter
}
let returnValue = function(firstClassCitizen)
returnValue
returnValue()
//: [Next](@next)
| 15.5 | 58 | 0.627957 |
483a547aa89de85e1f4391728e89238f3c90ccdc
| 1,481 |
//
// FeedSourcesView.swift
// Cheapiez
//
// Created by Tianran Ding on 19/09/21.
//
import SwiftUI
import Combine
struct FeedSourcesView: View {
@StateObject var viewModel = FeedSourceViewModel()
@State var selectedFeed: FeedSource?
var body: some View {
List {
Section(header: Text("Feed / Sources")) {
ForEach(viewModel.feeds) { feed in
FeedCell(feed: feed, selectedFeed: $selectedFeed)
}
}
}.onAppear {
selectedFeed = viewModel.feeds.first
}
.listStyle(GroupedListStyle())
.ignoresSafeArea()
}
}
struct FeedCell: View {
let feed: FeedSource
@Binding var selectedFeed: FeedSource?
var body: some View {
HStack {
Text(feed.feedFlag)
Text(feed.feedName)
Spacer()
Text(feed.unread > 0 ? "\(feed.unread)": "").foregroundColor(.secondary)
}
.frame(height: 40)
.padding(.horizontal, 10)
.background(
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(feed.id == selectedFeed?.id ? Color.orange : Color.clear))
.onTapGesture {
self.selectedFeed = feed
NetworkingPipeline.shared.markSourceReadForIndex(feed.id)
}
}
}
struct FeedSourcesView_Previews: PreviewProvider {
static var previews: some View {
return FeedSourcesView()
}
}
| 25.534483 | 84 | 0.576637 |
f53972206ee8e070f8d5604c4fc4112811dd786b
| 2,701 |
//
// AES.swift
// NeoSwift
//
// Created by Luís Silva on 21/09/17.
// Copyright © 2017 drei. All rights reserved.
//
import Foundation
import CSwiftyCommonCrypto
struct AES {
public enum KeySize: Int {
case keySize128 = 128
case keySize192 = 192
case keySize256 = 256
var kCCKeySize: Int {
switch self {
case .keySize128: return kCCKeySizeAES128
case .keySize192: return kCCKeySizeAES192
case .keySize256: return kCCKeySizeAES256
}
}
}
static public func encrypt(bytes: [UInt8], key: [UInt8], keySize: KeySize, pkcs7Padding: Bool) -> [UInt8] {
assert(keySize.rawValue / 8 <= key.count)
let options = kCCOptionECBMode | (pkcs7Padding ? kCCOptionPKCS7Padding : 0)
let resultSize = bytes.count + 16
var result: [UInt8] = Array(repeatElement(0, count: resultSize))
var numBytesEncrypted = 0
let status = CCCrypt(CCOperation(kCCEncrypt),
CCAlgorithm(kCCAlgorithmAES),
CCOptions(options),
key,
keySize.kCCKeySize,
nil,
bytes,
bytes.count,
&result,
resultSize,
&numBytesEncrypted)
guard status == 0 else { return [] }
result.removeLast(resultSize - numBytesEncrypted)
return result
}
static public func decrypt(bytes: [UInt8], key: [UInt8], keySize: KeySize, pkcs7Padding: Bool) -> [UInt8] {
assert(keySize.rawValue / 8 <= key.count)
let options = kCCOptionECBMode | (pkcs7Padding ? kCCOptionPKCS7Padding : 0)
let resultSize = bytes.count
var result: [UInt8] = Array(repeatElement(0, count: resultSize))
var numBytesEncrypted = 0
let status = CCCrypt(CCOperation(kCCDecrypt),
CCAlgorithm(kCCAlgorithmAES),
CCOptions(options),
key,
keySize.kCCKeySize,
nil,
bytes,
bytes.count,
&result,
resultSize,
&numBytesEncrypted)
guard status == 0 else { return [] }
result.removeLast(resultSize - numBytesEncrypted)
return result
}
}
| 31.406977 | 111 | 0.482414 |
791e6ddac252072b844459f37ae01a1433c7b0c3
| 10,048 |
//
// SortingManager.swift
// iTorrent
//
// Created by Daniil Vinogradov on 17.05.2018.
// Copyright © 2018 XITRIX. All rights reserved.
//
import Foundation
import UIKit
class SortingManager {
public enum SortingTypes: Int {
case name = 0
case dateAdded = 1
case dateCreated = 2
case size = 3
}
public static func createSortingController(buttonItem: UIBarButtonItem? = nil, applyChanges: @escaping () -> Void = {}) -> ThemedUIAlertController {
let alphabetAction = createAlertButton(NSLocalizedString("Name", comment: ""), SortingTypes.name, applyChanges)
let dateAddedAction = createAlertButton(NSLocalizedString("Date Added", comment: ""), SortingTypes.dateAdded, applyChanges)
let dateCreatedAction = createAlertButton(NSLocalizedString("Date Created", comment: ""), SortingTypes.dateCreated, applyChanges)
let sizeAction = createAlertButton(NSLocalizedString("Size", comment: ""), SortingTypes.size, applyChanges)
let sectionsAction = createSectionsAlertButton(applyChanges)
let cancel = UIAlertAction(title: NSLocalizedString("Close", comment: ""), style: UIAlertAction.Style.cancel, handler: nil)
var sortAlertController = ThemedUIAlertController(title: NSLocalizedString("Sort Torrents By:", comment: ""), message: nil, preferredStyle: .actionSheet)
var message = NSLocalizedString("Currently sorted by ", comment: "")
checkConditionToAddButtonToList(&sortAlertController, &message, alphabetAction, SortingTypes.name)
checkConditionToAddButtonToList(&sortAlertController, &message, dateAddedAction, SortingTypes.dateAdded)
checkConditionToAddButtonToList(&sortAlertController, &message, dateCreatedAction, SortingTypes.dateCreated)
checkConditionToAddButtonToList(&sortAlertController, &message, sizeAction, SortingTypes.size)
sortAlertController.addAction(sectionsAction)
sortAlertController.addAction(cancel)
sortAlertController.message = message
if sortAlertController.popoverPresentationController != nil, buttonItem != nil {
sortAlertController.popoverPresentationController?.barButtonItem = buttonItem
}
return sortAlertController
}
private static func createAlertButton(_ buttonName: String, _ sortingType: SortingTypes, _ applyChanges: @escaping () -> Void = {}) -> UIAlertAction {
UIAlertAction(title: buttonName, style: .default) { _ in
UserPreferences.sortingType.value = sortingType.rawValue
applyChanges()
}
}
private static func createSectionsAlertButton(_ applyChanges: @escaping () -> Void = {}) -> UIAlertAction {
let sections = UserPreferences.sortingSections.value
let name = sections ? NSLocalizedString("Disable state sections", comment: "") : NSLocalizedString("Enable state sections", comment: "")
return UIAlertAction(title: name, style: sections ? .destructive : .default) { _ in
UserPreferences.sortingSections.value = !sections
applyChanges()
}
}
private static func checkConditionToAddButtonToList(_ sortAlertController: inout ThemedUIAlertController, _ message: inout String, _ alertAction: UIAlertAction, _ sortingType: SortingTypes) {
if SortingTypes(rawValue: UserPreferences.sortingType.value) != sortingType {
sortAlertController.addAction(alertAction)
} else {
message.append(alertAction.title!)
}
}
public static func sortTorrentManagers(managers: [TorrentStatus], headers: inout [String]) -> [[TorrentStatus]] {
var res = [[TorrentStatus]]()
var localManagers = [TorrentStatus](managers)
headers = [String]()
if UserPreferences.sortingSections.value {
var collection = [String: [TorrentStatus]]()
collection[Utils.TorrentStates.allocating.rawValue] = [TorrentStatus]()
collection[Utils.TorrentStates.checkingFastresume.rawValue] = [TorrentStatus]()
collection[Utils.TorrentStates.downloading.rawValue] = [TorrentStatus]()
collection[Utils.TorrentStates.finished.rawValue] = [TorrentStatus]()
collection[Utils.TorrentStates.hashing.rawValue] = [TorrentStatus]()
collection[Utils.TorrentStates.metadata.rawValue] = [TorrentStatus]()
collection[Utils.TorrentStates.paused.rawValue] = [TorrentStatus]()
collection[Utils.TorrentStates.queued.rawValue] = [TorrentStatus]()
collection[Utils.TorrentStates.seeding.rawValue] = [TorrentStatus]()
for manager in localManagers {
collection[manager.displayState]?.append(manager)
}
let sortingOrder = UserPreferences.sectionsSortingOrder.value
for id in sortingOrder {
let state = Utils.TorrentStates(id: id)!
if var list = collection[state.rawValue] {
addManager(&res, &list, &headers, state.rawValue)
}
}
} else {
headers.append("")
simpleSort(&localManagers)
res.append(localManagers)
}
return res
}
// public static func sortTorrentManagers2(managers: [TorrentStatus], headers: inout [String]) -> [[TorrentStatus]] {
// var res = [[TorrentStatus]]()
// var localManagers = [TorrentStatus](managers)
// headers = [String]()
//
// if (UserPreferences.sortingSections.value) {
//
// var allocatingManagers = [TorrentStatus]()
// var checkingFastresumeManagers = [TorrentStatus]()
// var downloadingManagers = [TorrentStatus]()
// var finishedManagers = [TorrentStatus]()
// var hashingManagers = [TorrentStatus]()
// var metadataManagers = [TorrentStatus]()
// var pausedManagers = [TorrentStatus]()
// var queuedManagers = [TorrentStatus]()
// var seedingManagers = [TorrentStatus]()
//
// for manager in localManagers {
// switch (manager.displayState) {
// case Utils.torrentStates.Allocating.rawValue:
// allocatingManagers.append(manager)
// case Utils.torrentStates.CheckingFastresume.rawValue:
// checkingFastresumeManagers.append(manager)
// case Utils.torrentStates.Downloading.rawValue:
// downloadingManagers.append(manager)
// case Utils.torrentStates.Finished.rawValue:
// finishedManagers.append(manager)
// case Utils.torrentStates.Hashing.rawValue:
// hashingManagers.append(manager)
// case Utils.torrentStates.Metadata.rawValue:
// metadataManagers.append(manager)
// case Utils.torrentStates.Paused.rawValue:
// pausedManagers.append(manager)
// case Utils.torrentStates.Queued.rawValue:
// queuedManagers.append(manager)
// case Utils.torrentStates.Seeding.rawValue:
// seedingManagers.append(manager)
// default:
// break
// }
// }
//
// let sortingOrder = UserPreferences.sectionsSortingOrder.value
// for id in sortingOrder {
// let state = Utils.torrentStates.init(id: id)!
// switch (state) {
// case .Allocating:
// addManager(&res, &allocatingManagers, &headers, Utils.torrentStates.Allocating.rawValue)
// case .CheckingFastresume:
// addManager(&res, &checkingFastresumeManagers, &headers, Utils.torrentStates.CheckingFastresume.rawValue)
// case .Downloading:
// addManager(&res, &downloadingManagers, &headers, Utils.torrentStates.Downloading.rawValue)
// case .Finished:
// addManager(&res, &finishedManagers, &headers, Utils.torrentStates.Finished.rawValue)
// case .Hashing:
// addManager(&res, &hashingManagers, &headers, Utils.torrentStates.Hashing.rawValue)
// case .Metadata:
// addManager(&res, &metadataManagers, &headers, Utils.torrentStates.Metadata.rawValue)
// case .Paused:
// addManager(&res, &pausedManagers, &headers, Utils.torrentStates.Paused.rawValue)
// case .Queued:
// addManager(&res, &queuedManagers, &headers, Utils.torrentStates.Queued.rawValue)
// case .Seeding:
// addManager(&res, &seedingManagers, &headers, Utils.torrentStates.Seeding.rawValue)
// }
// }
// } else {
// headers.append("")
// simpleSort(&localManagers)
// res.append(localManagers)
// }
//
// return res
// }
private static func addManager(_ res: inout [[TorrentStatus]], _ list: inout [TorrentStatus], _ headers: inout [String], _ header: String) {
if list.count > 0 {
simpleSort(&list)
headers.append(header)
res.append(list)
}
}
private static func simpleSort(_ list: inout [TorrentStatus]) {
switch SortingTypes(rawValue: UserPreferences.sortingType.value)! {
case SortingTypes.name:
list.sort { (t1, t2) -> Bool in
t1.title < t2.title
}
case SortingTypes.dateAdded:
list.sort { (t1, t2) -> Bool in
t1.addedDate! > t2.addedDate!
}
case SortingTypes.dateCreated:
list.sort { (t1, t2) -> Bool in
t1.creationDate! > t2.creationDate!
}
case SortingTypes.size:
list.sort { (t1, t2) -> Bool in
t1.totalWanted > t2.totalWanted
}
}
}
}
| 46.518519 | 195 | 0.621218 |
03980bf846ea1d653f2ac12532cd675fcc0faa3b
| 93 |
import Foundation
public protocol AppStateProviding {
var isAppActive: Bool { get }
}
| 11.625 | 35 | 0.731183 |
f948bec529de3ca7be6e013836b6a3356642c6c6
| 1,038 |
//
// AddItemAddItemInteractor.swift
// TOTP
//
// Created by Tarik on 10/10/2020.
// Copyright © 2020 Taras Markevych. All rights reserved.
//
import OneTimePassword
final class AddItemInteractor: AddItemInteractorInput {
weak var output: AddItemInteractorOutput!
func setToken(string: String) {
if let url = URL(string: string), let tokenData = Token(url: url) {
guard let secretKey = url.absoluteString.components(separatedBy: "secret=").last?.components(separatedBy: "&issuer=").first else {
self.output.addTokenFails()
return
}
print(secretKey)
RealmManager.shared.saveNewUser(name: tokenData.name, issuer: tokenData.issuer, token: secretKey, completionHandler: { isSuccess in
if isSuccess {
self.output.tokenAdded()
} else {
self.output.addTokenFails()
}
})
} else {
output.addTokenFails()
}
}
}
| 31.454545 | 143 | 0.588632 |
283580e6bec61e9ac08291c470a6fc3d7da731ee
| 1,373 |
//----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.7.0.0
//
// Created by Quasar Development
//
//---------------------------------------------------
import Foundation
/**
* abstDomain: A17893 (C-0-T11527-S13856-S11529-A17893-cpt)
*/
public enum EPA_FdV_AUTHZ_ActClassROI:Int,CustomStringConvertible
{
case ROIBND
case ROIOVL
static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_ActClassROI?
{
return createWithString(value: node.stringValue!)
}
static func createWithString(value:String) -> EPA_FdV_AUTHZ_ActClassROI?
{
var i = 0
while let item = EPA_FdV_AUTHZ_ActClassROI(rawValue: i)
{
if String(describing: item) == value
{
return item
}
i += 1
}
return nil
}
public var stringValue : String
{
return description
}
public var description : String
{
switch self
{
case .ROIBND: return "ROIBND"
case .ROIOVL: return "ROIOVL"
}
}
public func getValue() -> Int
{
return rawValue
}
func serialize(__parent:DDXMLNode)
{
__parent.stringValue = stringValue
}
}
| 20.191176 | 77 | 0.499636 |
612edf470790f49326fe80160a1ba3a30094012f
| 1,744 |
//
// UIImageViewWebExt.swift
// Joke
//
// Created by xiao on 2018/1/27.
// Copyright © 2018年 jeikerxiao. All rights reserved.
//
import UIKit
import Foundation
extension UIImageView {
func setImage(_ urlString:String, placeHolder:UIImage!) {
let url = URL(string: urlString)
let cacheFilename = url!.lastPathComponent
let cachePath = FileUtil.cachePath(cacheFilename)
let image : AnyObject = FileUtil.imageDataFromPath(cachePath)
if image as! NSObject != NSNull() {
self.image = image as? UIImage
} else {
let req = URLRequest(url: url!)
let queue = OperationQueue();
NSURLConnection.sendAsynchronousRequest(req, queue: queue, completionHandler: { response, data, error in
if (error != nil) {
DispatchQueue.main.async(execute: {
print(error!)
self.image = placeHolder
})
} else {
DispatchQueue.main.async(execute: {
let image = UIImage(data: data!)
if (image == nil) {
print("image is nil and url fail=\(urlString)")
self.image = placeHolder
} else {
self.image = image
let bIsSuccess = FileUtil.imageCacheToPath(cachePath,image:data!)
if !bIsSuccess {
print("*******cache fail,path=\(cachePath)")
}
}
})
}
})
}
}
}
| 33.538462 | 116 | 0.468463 |
79e7824125470549f21e2f844ba4a2316ee375b6
| 1,654 |
/**
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import CoreGraphics
let DegreesPerRadians = Float(Double.pi/180)
let RadiansPerDegrees = Float(180/Double.pi)
func convertToRadians(angle:Float) -> Float {
return angle * DegreesPerRadians
}
func convertToRadians(angle:CGFloat) -> CGFloat {
return CGFloat(CGFloat(angle) * CGFloat(DegreesPerRadians))
}
func convertToDegrees(angle:Float) -> Float {
return angle * RadiansPerDegrees
}
func convertToDegrees(angle:CGFloat) -> CGFloat {
return CGFloat(CGFloat(angle) * CGFloat(RadiansPerDegrees))
}
| 37.590909 | 80 | 0.761185 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.