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
|
---|---|---|---|---|---|
46662cbe075fa6a4494f718836ac20d0d7787bb4 | 1,128 | //
// MediatorPattern.swift
// Design-Patterns
//
// Created by liupengkun on 2020/5/11.
// Copyright © 2020 刘朋坤. All rights reserved.
//
/*
中介者模式(Mediator Pattern):用一个中介对象来封装一系列的对象交互,中介者使各对象之间不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
*/
import UIKit
class MediatorPattern: NSObject {
var userArray:Array<MediatorUser> = []
func addUser(user: MediatorUser) {
userArray.append(user)
}
func sendMessage(user: MediatorUser, message:String) {
userArray.forEach { (item_user) in
if (item_user != user) {
item_user.receivedMessage(message: message)
}
}
}
}
class MediatorUser: NSObject {
var name:String = ""
var mediator: MediatorPattern
init(name: String, mediator: MediatorPattern) {
self.name = name
self.mediator = mediator
}
func sendMessage(message: String) {
print("\n")
print(self.name, "说:")
self.mediator.sendMessage(user: self, message: message)
}
func receivedMessage(message: String) {
print("\(message), \(self.name)")
}
}
| 22.117647 | 90 | 0.613475 |
e052e5a80700bb77c573692a0a44b8b66be51398 | 2,108 | /* magic */
// Do not edit the line above.
// RUN: %empty-directory(%t)
// RUN: %target-run-simple-swift %s %t | %FileCheck %s
// REQUIRES: executable_test
// TODO: rdar://problem/33388782
// REQUIRES: CPU=x86_64
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#elseif os(Windows)
import MSVCRT
#endif
let sourcePath = CommandLine.arguments[1]
let tempPath = CommandLine.arguments[2] + "/libc.txt"
// CHECK: Hello world
fputs("Hello world", stdout)
// CHECK: 4294967295
print("\(UINT32_MAX)")
// CHECK: the magic word is ///* magic *///
let sourceFile = open(sourcePath, O_RDONLY)
assert(sourceFile >= 0)
var bytes = UnsafeMutablePointer<CChar>.allocate(capacity: 12)
var readed = read(sourceFile, bytes, 11)
close(sourceFile)
assert(readed == 11)
bytes[11] = CChar(0)
print("the magic word is //\(String(cString: bytes))//")
// CHECK: O_CREAT|O_EXCL returned errno *17*
let errFile =
open(sourcePath, O_RDONLY | O_CREAT | O_EXCL)
if errFile != -1 {
print("O_CREAT|O_EXCL failed to return an error")
} else {
let e = errno
print("O_CREAT|O_EXCL returned errno *\(e)*")
}
// CHECK-NOT: error
// CHECK: created mode *33216* *33216*
let tempFile =
open(tempPath, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR)
if tempFile == -1 {
let e = errno
print("error: open(tempPath \(tempPath)) returned -1, errno \(e)")
abort()
}
let written = write(tempFile, bytes, 11)
if (written != 11) {
print("error: write(tempFile) returned \(written), errno \(errno)")
abort()
}
var err: Int32
var statbuf1 = stat()
err = fstat(tempFile, &statbuf1)
if err != 0 {
let e = errno
print("error: fstat returned \(err), errno \(e)")
abort()
}
close(tempFile)
var statbuf2 = stat()
err = stat(tempPath, &statbuf2)
if err != 0 {
let e = errno
print("error: stat returned \(err), errno \(e)")
abort()
}
print("created mode *\(statbuf1.st_mode)* *\(statbuf2.st_mode)*")
assert(statbuf1.st_mode == S_IFREG | S_IRUSR | S_IWUSR | S_IXUSR)
assert(statbuf1.st_mode == statbuf2.st_mode)
| 23.954545 | 72 | 0.66888 |
1a310b9cab97cb87b525b4a34ad2fda0bfbd9505 | 8,114 | //
// ImageSelectionView.swift
// Philter
//
// Created by Philip Price on 9/19/16.
// Copyright © 2016 Nateemma. All rights reserved.
//
import UIKit
import Neon
import Photos
// Interface required of controlling View
protocol ImageSelectionViewDelegate: class {
func changeImagePressed()
func changeBlendPressed()
func savePressed()
}
// Class responsible for laying out the Image Selection View (edit/blend image, save)
class ImageSelectionView: UIView {
var theme = ThemeManager.currentTheme()
// delegate for handling events
weak var delegate: ImageSelectionViewDelegate?
//MARK: - Class variables:
let smallIconFactor : CGFloat = 0.75
var imageButton: SquareButton!
var blendButton: SquareButton!
var saveButton: SquareButton!
var imageLabel:UILabel! = UILabel()
var blendLabel:UILabel! = UILabel()
var saveLabel:UILabel! = UILabel()
var initDone: Bool = false
var showBlend:Bool = true
var showSave:Bool = true
//MARK: Accessors
public func enableBlend(_ enable:Bool){
showBlend = enable
}
public func enableSave(_ enable:Bool){
showSave = enable
}
//MARK: - Initialisation:
convenience init(){
self.init(frame: CGRect.zero)
}
func initViews(){
if (!initDone){
initDone = true
// set the colors etc.
self.backgroundColor = theme.backgroundColor
// set up buttons and labels
imageButton = SquareButton(bsize: UISettings.buttonSide)
blendButton = SquareButton(bsize: UISettings.buttonSide)
saveButton = SquareButton(bsize: UISettings.buttonSide)
saveButton.setImageAsset("ic_save")
saveButton.setTintable(true)
imageLabel.text = "photo"
blendLabel.text = "blend"
saveLabel.text = "save"
for l in [imageLabel, blendLabel, saveLabel] {
l!.font = UIFont.systemFont(ofSize: 10.0, weight: UIFont.Weight.thin)
l!.textColor = theme.textColor
l!.textAlignment = .center
}
// add the subviews to the main View
self.addSubview(imageButton)
self.addSubview(imageLabel)
if showBlend {
self.addSubview(blendButton)
self.addSubview(blendLabel)
}
if showSave {
self.addSubview(saveButton)
self.addSubview(saveLabel)
}
// populate values
update()
initDone = true
}
}
//MARK: - View functions
override func layoutSubviews() {
super.layoutSubviews()
theme = ThemeManager.currentTheme()
initViews()
let pad:CGFloat = 4
// set up layout based on orientation
if (UISettings.isLandscape){
// Landscape: top-to-bottom layout scheme
//self.anchorAndFillEdge(.right, xPad: 0, yPad: 0, otherSize: UISettings.panelHeight)
// add items to the view
imageButton.anchorToEdge(.top, padding: pad, width: UISettings.buttonSide, height: UISettings.buttonSide)
blendButton.anchorInCenter(width: UISettings.buttonSide, height: UISettings.buttonSide)
saveButton.anchorToEdge(.bottom, padding: pad, width: UISettings.buttonSide, height: UISettings.buttonSide)
imageLabel.align(.underCentered, relativeTo: imageButton, padding: pad, width: UISettings.buttonSide, height: UISettings.buttonSide/2)
blendLabel.align(.underCentered, relativeTo: blendButton, padding: pad, width: UISettings.buttonSide, height: UISettings.buttonSide/2)
saveLabel.align(.underCentered, relativeTo: saveButton, padding: pad, width: UISettings.buttonSide, height: UISettings.buttonSide/2)
} else {
// left-to-right layout scheme
//self.anchorAndFillEdge(.bottom, xPad: 0, yPad: 0, otherSize: UISettings.panelHeight)
// add items to the view
imageButton.anchorToEdge(.left, padding: pad, width: UISettings.buttonSide, height: UISettings.buttonSide)
blendButton.anchorInCenter(width: UISettings.buttonSide, height: UISettings.buttonSide)
saveButton.anchorToEdge(.right, padding: pad, width: UISettings.buttonSide, height: UISettings.buttonSide)
/***
imageButton.anchorInCorner(.topLeft, xPad: 4*pad, yPad: pad, width: UISettings.buttonSide, height: UISettings.buttonSide)
blendButton.anchorToEdge(.top, padding: pad, width: UISettings.buttonSide, height: UISettings.buttonSide)
saveButton.anchorInCorner(.topRight, xPad: 4*pad, yPad: pad, width: UISettings.buttonSide, height: UISettings.buttonSide)
***/
imageLabel.align(.underCentered, relativeTo: imageButton, padding: 0, width: UISettings.buttonSide, height: UISettings.buttonSide/2)
blendLabel.align(.underCentered, relativeTo: blendButton, padding: 0, width: UISettings.buttonSide, height: UISettings.buttonSide/2)
saveLabel.align(.underCentered, relativeTo: saveButton, padding: 0, width: UISettings.buttonSide, height: UISettings.buttonSide/2)
}
// register handlers for the various buttons
imageButton.addTarget(self, action: #selector(self.imageDidPress), for: .touchUpInside)
blendButton.addTarget(self, action: #selector(self.blendDidPress), for: .touchUpInside)
saveButton.addTarget(self, action: #selector(self.saveDidPress), for: .touchUpInside)
}
// set photo image to the last photo in the camera roll
func loadPhotoThumbnail(){
let tgtSize = imageButton.bounds.size
// set the photo thumbnail to the current input image
if let currImage = InputSource.getCurrentImage() {
self.imageButton.setImage(UIImage(ciImage: currImage.resize(size: tgtSize)!))
} else {
// no image, set to most recent photo
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
let last = fetchResult.lastObject
if let lastAsset = last {
let options = PHImageRequestOptions()
options.version = .current
PHImageManager.default().requestImage(
for: lastAsset,
targetSize: tgtSize,
contentMode: .aspectFit,
options: options,
resultHandler: { image, _ in
DispatchQueue.main.async {
self.imageButton.setImage(image!)
}
}
)
}
}
}
private func loadBlendThumbnail(){
DispatchQueue.main.async {
let image = UIImage(ciImage: ImageManager.getCurrentBlendImage(size:self.blendButton.frame.size)!)
self.blendButton.setImage(image)
}
}
// called to request an update of the view
open func update(){
log.debug("update requested")
loadPhotoThumbnail()
loadBlendThumbnail()
}
/////////////////////////////////
//MARK: - touch handlers
/////////////////////////////////
@objc func imageDidPress() {
delegate?.changeImagePressed()
}
@objc func saveDidPress() {
delegate?.savePressed()
}
@objc func blendDidPress() {
delegate?.changeBlendPressed()
}
}
| 32.850202 | 146 | 0.590338 |
fefeda30ab6d41f0fba12776e7aa46c6fd3c421e | 2,173 | //
// AppDelegate.swift
// SweenDemo
//
// Created by Shun Kuroda on 2017/05/30.
// Copyright © 2017年 kuroyam. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.234043 | 285 | 0.755177 |
0ef0f6c4c66ce0dd0875afc5e99ea5f186f285d2 | 523 | //
// PitchSpelling+CustomStringConvertible.swift
// PitchSpellingTools
//
// Created by James Bean on 5/3/16.
//
//
import Foundation
extension PitchSpelling: CustomStringConvertible {
// MARK: - CustomStringConvertible
/// Printed description.
public var description: String {
var result = ""
result += "\(letterName)"
if quarterStep != .natural { result += " \(quarterStep)" }
if eighthStep != .none { result += " \(eighthStep)" }
return result
}
}
| 21.791667 | 66 | 0.613767 |
18262105d5cf70564fbf0936adc6544cbf940a3d | 2,465 | //
// OccupancyStatusView.swift
// OBAKit
//
// Created by Aaron Brethorst on 12/13/18.
// Copyright © 2018 OneBusAway. All rights reserved.
//
import UIKit
@objc(OBAOccupancyStatusView)
public class OccupancyStatusView: UIView {
private let image: UIImage
private let imageSize: CGFloat = 12.0
private lazy var scaledImage: UIImage = image.oba_imageScaled(toFit: CGSize(width: imageSize, height: imageSize))
@objc public var highlightedBackgroundColor = UIColor.clear
@objc public var defaultBackgroundColor = UIColor(white: 0.98, alpha: 1.0)
@objc public init(image: UIImage) {
self.image = image
super.init(frame: .zero)
isAccessibilityElement = true
accessibilityLabel = Bundle(for: OccupancyStatusView.self).localizedString(forKey: "occupancy_status.accessibility_label", value: nil, table: nil)
accessibilityTraits = [.staticText]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public var intrinsicContentSize: CGSize {
return CGSize(width: imageSize * CGFloat(maxSilhouetteCount), height: imageSize)
}
override public func draw(_ rect: CGRect) {
super.draw(rect)
let background = isHighlighted ? highlightedBackgroundColor : defaultBackgroundColor
background.set()
UIRectFill(rect)
let imageWidth = Int(rect.width / CGFloat(maxSilhouetteCount))
for i in 0..<silhouetteCount {
let imageRect = CGRect(x: i * imageWidth, y: 0, width: imageWidth, height: Int(scaledImage.size.height))
scaledImage.draw(in: imageRect)
}
}
private let maxSilhouetteCount = 3
private var silhouetteCount: Int {
switch occupancyStatus {
case .empty: return 1
case .manySeatsAvailable: return 1
case .fewSeatsAvailable: return 1
case .standingRoomOnly: return 2
case .crushedStandingRoomOnly: return 3
case .full: return 3
default: return 0
}
}
@objc public var occupancyStatus: OBAOccupancyStatus = .unknown {
didSet {
isHidden = (occupancyStatus == .unknown)
accessibilityValue = OBALocalizedStringFromOccupancyStatus(occupancyStatus)
setNeedsDisplay()
}
}
@objc public var isHighlighted = false {
didSet {
setNeedsDisplay()
}
}
}
| 29.345238 | 154 | 0.661258 |
2f184a946f7f9466b266388fd4150a98aa214df0 | 3,698 | //
// AppDelegate.swift
// DinDinnPOC
//
// Created by Pankaj Talreja on 30/03/21.
//
import UIKit
import CoreData
@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.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "DinDinn")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 43.505882 | 199 | 0.656571 |
036350a0a0562da42d192c0722029b178ab89f90 | 323 | import Foundation
import enum TSCBasic.ProcessEnv
import TuistAnalytics
import TuistSupport
if CommandLine.arguments.contains("--verbose") { try? ProcessEnv.setVar(Constants.EnvironmentVariables.verbose, value: "true") }
TuistSupport.LogOutput.bootstrap()
TuistAnalytics.bootstrap()
import TuistKit
TuistCommand.main()
| 23.071429 | 128 | 0.823529 |
672feb414f39712b099189a202582edd4680eaf4 | 6,014 | //
// RecommendViewController.swift
// DYZB
//
// Created by yoke on 2016/12/8.
// Copyright © 2016年 yoke. All rights reserved.
// 推荐控制器
import UIKit
private let kItemMargin : CGFloat = 10
private let kHeaderViewH : CGFloat = 50
private let kNormalCellID = "kNormalCellID"
private let kHeaderViewID = "kHeaderViewID"
let kCycleH = kScreenW * 3 / 8
let kGameH : CGFloat = 90
class RecommendViewController: UIViewController {
//MARK:- 懒加载属性
fileprivate lazy var recommendVM : RecommendViewModel = RecommendViewModel()
fileprivate lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleH + kGameH), width: kScreenW, height: kCycleH)
return cycleView
}()
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.backgroundColor = UIColor.red
gameView.frame = CGRect(x: 0, y: -kGameH, width: kScreenW, height: kGameH)
return gameView
}()
lazy var collectionView : UICollectionView = { [unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
//创建 UIcollection
let collectionView : UICollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
///注册单元格的nib文件
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
//注册头部视图的nib文件
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.lightGray
//MARK: - 懒加载属性
//设置UI界面
setupUI()
//加载数据
loadData()
}
}
//MARK: - UI界面设置的方法
extension RecommendViewController {
fileprivate func setupUI() {
view.addSubview(collectionView)
//1.将cycleView添加到collectionView上
collectionView.addSubview(cycleView)
//2.将gameVie添加到collectionView上
collectionView.addSubview(gameView)
//3.设置collectionView的内边距
collectionView.contentInset = UIEdgeInsets(top: kCycleH + kGameH , left: 0, bottom: 0, right: 0)
}
}
extension RecommendViewController{
func loadData(){
//1.请求数据
recommendVM.requestData {
self.collectionView.reloadData()
//将数据传递给gameView
var groups = self.recommendVM.anchorGroups
groups.removeFirst()
groups.removeFirst()
let moreGroup = AnchorGroup()
moreGroup.tag_name = "更多"
groups.append(moreGroup)
self.gameView.groups = groups
}
//2.请求无线轮播的数据
recommendVM.requestCycleData {
self.cycleView.cycleModels = self.recommendVM.cycleModels
}
}
}
//MARK: - 遵循UICollectionViewDataSource的方法
extension RecommendViewController : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.recommendVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.recommendVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : CollectionBaseCell!
if indexPath.section == 1{
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionBaseCell
}else{
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionBaseCell
}
//2.设置数据
cell.anchor = self.recommendVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//1.取出headerView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// headerView.titleLabel.text = "全部"
// headerView.iconImageView.image = UIImage(named: "Img_orange")
// headerView.isHidden = true
return headerView
}
}
extension RecommendViewController : UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kNormalItemW, height: kPrettyItemH)
}
return CGSize(width: kNormalItemW, height: kNormalItemH)
}
}
| 32.684783 | 195 | 0.670436 |
28090e9c6bb023ada6e4a581fd9e615f17aa25eb | 2,968 | //
// ViewMapping+CaseIterable.swift
// MirrorControlsExample
//
// Created by Steve Barnegren on 12/01/2021.
//
import Foundation
import SwiftUI
protocol CaseIterableRefProvider {
var caseIterableRef: CaseIterableRef { get }
}
class CaseIterableRef {
struct Case {
let value: Any
let name: String
}
var allCases: [Case]
private var get: () -> Any
private var set: (Any) -> Void
var value: Any {
get { get() }
set { set(newValue) }
}
private var getByIndex: () -> Int
private var setByIndex: (Int) -> Void
var valueIndex: Int {
get { getByIndex() }
set { setByIndex(newValue) }
}
var selectedCase: Case {
return allCases[valueIndex]
}
init<T: CaseIterable & Equatable>(_ object: PropertyRef<T>) {
var cases = [Case]()
for c in type(of: object.value).allCases {
let caseName = "\(c)"
cases.append(
Case(value: c, name: PropertyNameFormatter.displayName(forPropertyName: caseName))
)
}
allCases = cases
get = {
return object.value
}
set = {
object.value = $0 as! T
}
getByIndex = {
for (index, c) in type(of: object.value).allCases.enumerated() {
if c == object.value {
return index
}
}
return 0
}
setByIndex = {
let allCases = type(of: object.value).allCases
let index = allCases.index(allCases.startIndex, offsetBy: $0)
object.value = type(of: object.value).allCases[index]
}
}
}
extension ViewMapping {
static func makeCaseIterableView(ref: CaseIterableRef, context: ViewMappingContext) -> AnyView {
let cases = ref.allCases
let selectionBinding = Binding(get: { ref.valueIndex },
set: { ref.valueIndex = $0 })
#if os(macOS)
let picker = Picker(selection: selectionBinding, label: Text(context.propertyName)) {
ForEach(0..<cases.count) { index in
let aCase = cases[index]
Text("\(aCase.name)")
}
}.pickerStyle(MenuPickerStyle())
return AnyView(picker)
#else
let picker = Picker(selection: selectionBinding, label: Text(ref.selectedCase.name)) {
ForEach(0..<cases.count) { index in
let aCase = cases[index]
Text("\(aCase.name)")
}
}.pickerStyle(MenuPickerStyle())
let pickerAndTitle = HStack {
Text(context.propertyName)
picker
}.animation(.none)
return AnyView(pickerAndTitle)
#endif
}
}
| 24.941176 | 100 | 0.511456 |
11d78440bad12230f592c74c1ef99c3fbce03b71 | 1,552 | //
// PreferenceTabViewController.swift
// mStat
//
// Created by venj on 2017/11/23.
// Copyright © 2017年 venj. All rights reserved.
//
import Cocoa
class PreferenceTabViewController: NSTabViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
override func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
super.tabView(tabView, didSelect: tabViewItem)
if let identifier = tabViewItem?.identifier as? String, identifier == "GeneralPreferences" {
let title = NSLocalizedString("General", comment: "General")
tabViewItem?.label = title
view.window?.title = title
}
}
override func transition(from fromViewController: NSViewController, to toViewController: NSViewController, options: NSViewController.TransitionOptions = [], completionHandler completion: (() -> Void)? = nil) {
super.transition(from: fromViewController, to: toViewController, options: options, completionHandler: completion)
if let window = view.window {
let contentSize = toViewController.view.fittingSize
let newWindowSize = window.frameRect(forContentRect: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: contentSize)).size
var frame = window.frame
frame.origin.y += (frame.size.height - newWindowSize.height)
frame.size = newWindowSize
window.animator().setFrame(frame, display: false, animate: true)
}
}
}
| 38.8 | 213 | 0.666237 |
d7b8554c23b1ad0a27d8f37d62aec4c0f0b3afbd | 3,431 | //
// ProductModel.swift
// XDExerciseExample
//
// Created by xiudou on 2018/4/29.
// Copyright © 2018年 CoderST. All rights reserved.
//
import UIKit
import HandyJSON
class ProductModel: HandyJSON {
var product_header_image: String = ""
var product_detail_list: [String] = [String]()
var video_image_list: [Video_Image_List] = [Video_Image_List]()
var buyer_show_total: Int = 0
var faved_count: Int = 0
var is_faved: Int = 0
var product_name: String = ""
var spike_delivery_price: Int = 0
var location_latitude: String = ""
var spike_type_id: Int = 0
var iwant_id: String = ""
var forward_count: Int = 0
var not_available_topic: [String] = [String]()
var product_header_image_32: String = ""
var classification: Classification = Classification()
var is_locking: Int = 0
var forward_price: Int = 0
var user: User = User()
var is_iwant: Int = 0
var product_delivery_price: String = ""
var code: Int = 0
var is_on_market: Int = 0
var comment_count: Int = 0
var product_views_count: Int = 0
var status: String = ""
var product_description: String = ""
var product_id: String = ""
var product_type: [Product_Type] = [Product_Type]()
var publish_date: String = ""
var location_title: String = ""
var spike_price: Int = 0
var forward_charge: String = ""
var location_longitude: String = ""
var topics: [String] = [String]()
var system_type_id: String = ""
var spike_status: Int = 0
var spike_stock: Int = 0
var show_iwant: Int = 0
var product_video_header_image: String = ""
var min_price: String = ""
var video_play_count: Int = 0
var forward_user_list: [Forward_User_List] = [Forward_User_List]()
var max_forward_price: Int = 0
var shop_coupon: Int = 0
var max_price: String = ""
required init() {}
}
class Classification : HandyJSON{
var classification_id: String = ""
var classification_name: String = ""
required init() {}
}
class Forward_User_List : HandyJSON{
var user_id: String = ""
var avatar: String = ""
required init() {}
}
class Product_Type : HandyJSON{
var type_id: String = ""
var type_name: String = ""
var type_price: String = ""
var stock: String = ""
required init() {}
}
class Video_Image_List : HandyJSON{
var height: String = ""
var video_stream_url: String = ""
var video_url: String = ""
var image_url: String = ""
var width: String = ""
var video_https_url: String = ""
var type: Int = 0
required init() {}
}
//class User : HandyJSON{
//
//var nick_name: String?
//
//var gender: String?
//
//var avatar: String?
//
//var friend_shop_count: Int = 0
//
//var fans_count: Int = 0
//
//var certification: Certification?
//
//var is_faved: Int = 0
//
//var user_id: String?
//
//var seller_level: String?
//
// required init() {}
//
//}
//class Certification : HandyJSON{
//
//var if_vip: String?
//
//var if_official_vip: Int = 0
//
//var if_celebrity_vip: Int = 0
//
// required init() {}
//
//}
| 17.777202 | 70 | 0.57884 |
1c3097550f79d39d2eb512d53f746d2a20ddaa47 | 2,544 | //
// Calculator.swift
// FelipeFranciscoGeovaniMarcello
//
// Created by Marcello Chuahy on 17/01/21.
// Copyright © 2021 Applause Codes. All rights reserved.
//
import Foundation
enum CustomLocale: String {
case enUS
case ptBR
var locale: Locale {
switch self {
case .enUS: return Locale(identifier: "en_US")
case .ptBR: return Locale(identifier: "pt_BR")
}
}
var currencySymbol: String {
switch self {
case .enUS: return "US$"
case .ptBR: return "R$"
}
}
}
class Calculator {
static let shared = Calculator()
let numberFormatter = NumberFormatter()
let userDefaults = UserDefaults.standard
private init() {
numberFormatter.usesGroupingSeparator = true
}
lazy var exchangeRateDolarAndReal: Double = { userDefaults.double(forKey: "AmericanDollarExchangeRate") }()
lazy var iofAsPercentage: Double = { userDefaults.double(forKey: "IOF") }()
var stateTaxAsPercentage: Double = 0.0
var priceInDolar: Double = 0.0
var priceInReal: Double { priceInDolar * exchangeRateDolarAndReal }
var productTaxInDolar: Double { priceInDolar * stateTaxAsPercentage / 100 }
var productIofInDolar: Double { (priceInDolar + productTaxInDolar) * iofAsPercentage / 100 }
func convertStringToDouble(numberAsString: String) -> Double {
let numberAsStringWithCommaDecimalSeparator = String(format:"%.2f", numberAsString.doubleValue)
return Double(numberAsStringWithCommaDecimalSeparator) ?? 0.00
}
func convertDoubleToString(double: Double, withLocale customLocale: CustomLocale?) -> String {
numberFormatter.locale = customLocale?.locale
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2
numberFormatter.numberStyle = .decimal
return numberFormatter.string(from: NSNumber(value:double)) ?? "0,00"
}
func convertDoubleToCurrency(double: Double,
withLocale customLocale: CustomLocale?,
returningStringWithCurrencySymbol: Bool) -> String {
if returningStringWithCurrencySymbol {
numberFormatter.currencySymbol = customLocale?.currencySymbol ?? ""
} else {
numberFormatter.currencySymbol = ""
}
numberFormatter.locale = customLocale?.locale
numberFormatter.numberStyle = .currency
numberFormatter.alwaysShowsDecimalSeparator = true
return numberFormatter.string(for: double) ?? "ERROR"
}
func calculateTotal(isPaymentMethodCreditCard: Bool) -> Double {
var total = priceInDolar + productTaxInDolar
if isPaymentMethodCreditCard {
total += productIofInDolar
}
return total
}
}
| 27.354839 | 108 | 0.742138 |
ab4b2c7efe9db9eecb3dd90f3b3807a0a92b5ba1 | 684 | //: Playground - noun: a place where people can play
import UIKit
var str: String?
str = "Hola"
str
print(str)
var ab:String?
var ac:String?
var ad:Int?
var ae:String?
ab = "Hola"
ac = "Mundo"
ad = 3
ae = "veces"
if let ab = ab, let ac = ac, let ad = ad where ad != 2, let ae = ae{
print(ab,ac,ad,ae)
}
guard let vab = ab where vab.characters.count > 0 else{
print("variable is empty")
throw NSError(domain: "Optional is Empty", code: 0, userInfo: nil)
}
print(vab)
var suma3 = {(numero:Int)-> Int in return numero + 3}
suma3(5)
var numero1 = 20
var numero2 = 40
var suma1n2 = {() -> Int in return numero1 + numero2 }
suma1n2()
numero1 += 10
suma1n2()
| 13.411765 | 70 | 0.635965 |
640fcf03dad2412e2cebce9d9721d9d4f811fe6b | 3,195 | //
// DateUtils.swift
// HorizontalCalendar
//
// Created by macbook pro on 24/9/2021.
//
import Foundation
public struct DateUtils {
public static func getDaysOfWeek(index: Int, firstWeekday : Int = 1)-> [Date] {
var cal = Calendar.autoupdatingCurrent
cal.firstWeekday = firstWeekday
cal.locale = Locale(identifier: "Fr")
cal.timeZone = TimeZone(identifier: "UTC")!
let currentDate = getTodayDateWithTZ().addDays(days: index*7)
let days = cal.daysWithSameWeekOfYear(as: currentDate)
return days
}
public static func getStartOfWeek(index: Int, firstWeekday : Int = 1)-> Date {
var cal = Calendar.autoupdatingCurrent
cal.firstWeekday = firstWeekday
cal.timeZone = TimeZone(identifier: "UTC")!
let currentDate = getTodayDateWithTZ().addDays(days: index*7)
let days = cal.daysWithSameWeekOfYear(as: currentDate)
return days.first ?? getTodayDateWithTZ()
}
public static func getNowDateWithTZ() -> Date {
let currentDate = Date()
let timezoneOffset = TimeZone.current.secondsFromGMT()
let epochDate = currentDate.timeIntervalSince1970
let timezoneEpochOffset = (epochDate + Double(timezoneOffset))
return Date(timeIntervalSince1970: timezoneEpochOffset)
}
public static func getTodayDateWithTZ() -> Date {
let currentDate = Date()
let timezoneOffset = TimeZone.current.secondsFromGMT()
let epochDate = currentDate.timeIntervalSince1970
let timezoneEpochOffset = (epochDate + Double(timezoneOffset))
//print(Date(timeIntervalSince1970: timezoneEpochOffset).today)
return Date(timeIntervalSince1970: timezoneEpochOffset).today
}
public static func getTodayDateWithTZ(h: Int, m : Int) -> Date {
var cal = Calendar.autoupdatingCurrent
cal.firstWeekday = 2
let date = cal.date(bySettingHour: h, minute: m, second: 0, of: Date())!
let timezoneOffset = TimeZone.current.secondsFromGMT()
let epochDate = date.timeIntervalSince1970
let timezoneEpochOffset = (epochDate + Double(timezoneOffset))
return Date(timeIntervalSince1970: timezoneEpochOffset)
}
public static func doEventsOverlap(_ eventOne: EventModel, _ eventTwo: EventModel) -> Bool {
let leftRange = eventOne.eStartTime! ... eventOne.eEndTime!
let rightRange = eventTwo.eStartTime! ... eventTwo.eEndTime!
return leftRange.overlaps(rightRange)
}
public static func weekDaySymbols(weekDayFormat: WeekdaySymbolsEnum = .short, firstWeekday : Int = 1, local : Locale = Locale.current)-> [String]{
let fmt = DateFormatter()
fmt.locale = local
var symbols : [String] = fmt.weekdaySymbols
switch weekDayFormat {
case .short:
symbols = fmt.shortWeekdaySymbols
case .veryShort:
symbols = fmt.veryShortWeekdaySymbols
default:
symbols = fmt.weekdaySymbols
}
symbols = Array(symbols[firstWeekday-1..<symbols.count]) + symbols[0..<firstWeekday-1]
return symbols
}
}
| 39.444444 | 150 | 0.66385 |
144fe12365164cce3b048cc07b41aaa10287fc35 | 982 | //
// BoardPosition.swift
// ShiftUI
//
// Created by Ryan Lintott on 2021-02-19.
//
import Foundation
enum BoardPosition: Comparable, UniqueById {
case occupied(square: ShiftSquare)
case empty(position: Position)
var position: Position {
switch self {
case let .occupied(square):
return square.position
case let .empty(position):
return position
}
}
var isEmpty: Bool {
switch self {
case .empty:
return true
case .occupied:
return false
}
}
var square: ShiftSquare? {
switch self {
case let .occupied(square):
return square
case .empty:
return nil
}
}
var id: Position {
switch self {
case let .occupied(square):
return square.id
case let .empty(position):
return Position(row: -position.row, column: -position.column)
}
}
static func < (lhs: BoardPosition, rhs: BoardPosition) -> Bool {
lhs.position < rhs.position
}
}
| 18.185185 | 67 | 0.618126 |
abac945162cbae3b99a4d57349d28306504447b3 | 3,531 | //
// ViewController.swift
// CKPhotoLibraryManager
//
// Created by kaich on 11/02/2016.
// Copyright (c) 2016 kaich. All rights reserved.
//
import UIKit
import CKPhotoLibraryManager
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
CKPhotoLibraryManager.shared.didFindPermissionTrouble = { status in
let alert = UIAlertController(title: "", message: "请在iPhone的“设置-爱思助手-隐私-照片”选项中,允许爱思助手访问您照片。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "暂不设置", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "现在设置", style: .default, handler: { _ in
UIApplication.shared.openURL(URL(string: UIApplication.openSettingsURLString)!)
}))
self.present(alert, animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func importAlbum(_ sender: AnyObject) {
if let filePath = Bundle.main.path(forResource: "map", ofType: "png") {
CKPhotoLibraryManager.shared.addAsset(filePath: filePath, type: .image, albumName: "CKPhoto") { (isOK, path, error) in
if error == nil {
let alert = UIAlertController(title: "导入成功", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
@IBAction func importPhotoAlbum(_ sender: Any) {
if let filePath = Bundle.main.path(forResource: "map", ofType: "png") {
CKPhotoLibraryManager.shared.addAsset(filePath: filePath, type: .image) { (isOK, path, error) in
if error == nil {
let alert = UIAlertController(title: "导入成功", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
@IBAction func deletePhotoAlbum(_ sender: Any) {
CKPhotoLibraryManager.shared.deleteAlbum(title: "CKPhoto", isDeleteAssets: true) { (error) in
if error == nil {
let alert = UIAlertController(title: "删除成功", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
@IBAction func importLivePhoto(_ sender: Any) {
if let filePath = Bundle.main.path(forResource: "IMG_0350", ofType: "JPG"), let filePath2 = Bundle.main.path(forResource: "IMG_0350", ofType: "MOV") {
CKPhotoLibraryManager.shared.addAsset(filePath: filePath, filePath2: filePath2, type: .livePhoto) { (isOK, path, error) in
if error == nil {
let alert = UIAlertController(title: "导入成功", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
}
| 42.542169 | 158 | 0.59983 |
c1424ac3b6384c74dfcd25047544679fb7f82ef2 | 2,175 | //----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.7.0.0
//
// Created by Quasar Development
//
//---------------------------------------------------
import Foundation
public class EPA_FdV_AUTHZ_SXCM_PQ : EPA_FdV_AUTHZ_PQ
{
/**
* A code specifying whether the set component is included
* (union) or excluded (set-difference) from the set, or
* other set operations with the current set component and
* the set as constructed from the representation stream
* up to the current point.
*/
var _operator:EPA_FdV_AUTHZ_SetOperator?
public required init()
{
super.init()
}
public override func loadWithXml(__node: DDXMLElement, __request:EPA_FdV_AUTHZ_RequestResultHandler)
{
super.loadWithXml(__node:__node, __request: __request)
if EPA_FdV_AUTHZ_Helper.hasAttribute(node: __node, name:"operator", url:"")
{
self._operator = EPA_FdV_AUTHZ_SetOperator.createWithXml(node: EPA_FdV_AUTHZ_Helper.getAttribute(node: __node, name:"operator", url:"")!)!
}
}
public override func serialize(__parent:DDXMLElement, __request:EPA_FdV_AUTHZ_RequestResultHandler)
{
super.serialize(__parent:__parent, __request:__request)
if self._operator != nil
{
let ___operatorItemElement=__request.addAttribute(name: "operator", URI:"", stringValue:"", element:__parent)
self._operator!.serialize(__parent: ___operatorItemElement);
}
}
public override func loadProperty(__node: DDXMLElement, __request: EPA_FdV_AUTHZ_RequestResultHandler ) -> Bool
{
if __node.localName=="operator"
{
if EPA_FdV_AUTHZ_Helper.isValue(node:__node, name: "operator")
{
self._operator = EPA_FdV_AUTHZ_SetOperator.createWithXml(node: __node)!
}
return true;
}
return super.loadProperty(__node:__node, __request:__request)
}
} | 33.984375 | 151 | 0.591264 |
8a1c73fe214e31949e4f5e2a64a0995763288463 | 1,435 | //
// ViewController.swift
// urna-distribuida-app
//
// Created by Laura Abitante on 07/12/17.
// Copyright © 2017 Laura Abitante. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var lblStatus: UILabel!
@IBOutlet weak var txtIpAddress: UITextField!
var urna: Urna!
override func viewDidLoad() {
super.viewDidLoad()
lblStatus.text = "Urna desconectada"
}
@IBAction func conectar() {
urna = Urna((txtIpAddress.text ?? "localhost") as CFString)
urna.delegate = self
txtIpAddress.resignFirstResponder()
}
@IBAction func sendMessageButtonPressed() {
urna.enviarMensagem("CONECTAR")
lblStatus.text = ""
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let votacaoVC = segue.destination as? TituloViewController {
votacaoVC.urna = urna
}
}
}
extension ViewController: UrnaDelegate {
func urnaConectada() {
lblStatus.text = ""
}
func mensagemRecebida(mensagem: String) {
if mensagem.contains("|") {
urna.zona = String(mensagem.split(separator: "|").first!)
urna.sessao = String(mensagem.split(separator: "|").last!)
performSegue(withIdentifier: "titulo", sender: self)
} else {
lblStatus.text = mensagem
}
}
}
| 25.175439 | 71 | 0.612544 |
6a1055528e2ee803afd4d0a289744eb9c4d04b7c | 415 | //
// AppDelegate.swift
// Demo
//
// Created by John on 2019/3/20.
// Copyright © 2019 Ganguo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
}
| 21.842105 | 145 | 0.720482 |
299241b4dd3adce54a97180102ce996d47da9d19 | 1,707 | //
// NibRow.swift
// EasyList
//
// Created by mathieu lecoupeur on 19/03/2019.
// Copyright © 2019 mathieu lecoupeur. All rights reserved.
//
import UIKit
open class NibRow<SourceType, CellType: TableCell<SourceType>>: Row<SourceType, CellType> {
var nibName: String?
public init(id: String, data: SourceType?, cellIdentifier: String?, nibName: String, cellPresenter: BaseCellPresenter<CellType, SourceType>?) {
super.init(id: id, data: data, cellIdentifier: cellIdentifier, cellPresenter: cellPresenter)
self.nibName = nibName
}
public init(id: String, data: SourceType?, cellIdentifier: String?, nibName: String, configureCell: @escaping (CellType, SourceType) -> Void) {
super.init(id: id, data: data, cellIdentifier: cellIdentifier, configureCell: configureCell)
self.nibName = nibName
}
override public func getCell(tableView: UITableView) -> UITableViewCell {
guard let nibName = nibName else {
fatalError("Nib Name is not set for row : " + String(describing:type(of: self)))
}
let cellNib = UINib(nibName: nibName, bundle: nil)
if let cellIdentifier = cellIdentifier {
tableView.register(cellNib, forCellReuseIdentifier: cellIdentifier)
cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? CellType
} else {
cell = cellNib.instantiate(withOwner: nil, options: nil).first as? CellType
}
if let data = data, cell != nil {
cellPresenter?.configureCell(cell: cell!, source: data)
}
return cell ?? UITableViewCell()
}
}
| 36.319149 | 147 | 0.646163 |
f8d0afd01af35b3d242c4d5db4b99d1e00d177fe | 1,183 | //
// ImageContainer.swift
//
//
// Created by Navi on 31/05/21.
//
import UIKit
class ImageContainer: UIView {
lazy private var imageView: UIImageView = {
let imageView = UIImageView(frame: bounds)
imageView.layer.minificationFilter = .trilinear
imageView.accessibilityIgnoresInvertColors = true
imageView.contentMode = .scaleAspectFit
addSubview(imageView)
return imageView
} ()
var image: UIImage? {
didSet {
imageView.frame = bounds
imageView.image = image
imageView.isUserInteractionEnabled = true
}
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = bounds
}
func contains(rect: CGRect, fromView view: UIView, tolerance: CGFloat = 1e-6) -> Bool {
let newRect = view.convert(rect, to: self)
let p1 = newRect.origin
let p2 = CGPoint(x: newRect.maxX, y: newRect.maxY)
let refBounds = bounds.insetBy(dx: -tolerance, dy: -tolerance)
return refBounds.contains(p1) && refBounds.contains(p2)
}
}
| 24.645833 | 91 | 0.590871 |
e52e483b4ff1653e7287d5504c4e07b25ae761a6 | 2,205 | //
// ProfileViewController.swift
// TwitterDemo
//
// Created by Chinedum Robert-Maduekwe on 2/29/16.
// Copyright © 2016 nedu. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tweets: [Tweet]!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
TwitterClient.sharedInstance.userTimeLine({ (tweets: [Tweet]) -> () in
self.tweets = tweets
self.tableView.reloadData()
for tweet in tweets {
print(tweet.text)
}
}, failure: { (error:NSError) -> () in
print(error.localizedDescription)
})
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLogOutButton(sender: AnyObject) {
TwitterClient.sharedInstance.logout()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TweetCell", forIndexPath: indexPath) as! TweetCell
cell.tweet = tweets![indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tweets != nil{
return tweets!.count
}
else
{
return 0
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 29.4 | 114 | 0.626757 |
2856022cf4711d1a497da01be97f92abb0495cf1 | 3,474 | // Copyright © 2017 Schibsted. All rights reserved.
import XCTest
@testable import Layout
class OptionalExpressionTests: XCTestCase {
func testEquateOptionalNumbers() {
let foo: Double? = 5
let node = LayoutNode(constants: ["foo": foo as Any])
let expression = LayoutExpression(boolExpression: "foo == 5", for: node)
XCTAssertTrue(try expression?.evaluate() as? Bool == true)
}
func testAddOptionalNumbers() {
let foo: Double? = 5
let node = LayoutNode(constants: ["foo": foo as Any])
let expression = LayoutExpression(doubleExpression: "foo + 5", for: node)
XCTAssertEqual(try expression?.evaluate() as? Double, 10)
}
func testMultiplyOptionalNumbers() {
let foo: Double? = 5
let node = LayoutNode(constants: ["foo": foo as Any])
let expression = LayoutExpression(doubleExpression: "foo * 5", for: node)
XCTAssertEqual(try expression?.evaluate() as? Double, 25)
}
func testEquateOptionalStrings() {
let foo: String? = "foo"
let node = LayoutNode(constants: ["foo": foo as Any])
let expression = LayoutExpression(boolExpression: "foo == 'foo'", for: node)
XCTAssertTrue(try expression?.evaluate() as? Bool == true)
}
func testAddOptionalStrings() {
let foo: String? = "foo"
let node = LayoutNode(constants: ["foo": foo as Any])
let expression = LayoutExpression(stringExpression: "{foo + 'bar'}", for: node)
XCTAssertEqual(try expression?.evaluate() as? String, "foobar")
}
func testNullCoalescingInNumberExpression() {
let null: Double? = nil
let node = LayoutNode(constants: ["foo": null as Any])
let expression = LayoutExpression(doubleExpression: "foo ?? 5", for: node)
XCTAssertEqual(try expression?.evaluate() as? Double, 5)
}
func testNullCoalescingErrorWithNonOptional() {
let node = LayoutNode(constants: ["foo": 7])
let expression = LayoutExpression(doubleExpression: "foo ?? 5", for: node)
XCTAssertThrowsError(try expression?.evaluate()) { error in
XCTAssert("\(error)".lowercased().contains("optional"))
}
}
func testNullStringExpression() {
let null: String? = nil
let node = LayoutNode(constants: ["foo": null as Any])
let expression = LayoutExpression(stringExpression: "{foo}", for: node)
XCTAssertEqual(try expression?.evaluate() as? String, "")
}
func testOptionalStringExpression() {
let foo: String? = "foo"
let node = LayoutNode(constants: ["foo": foo as Any])
let expression = LayoutExpression(stringExpression: "{foo}", for: node)
XCTAssertEqual(try expression?.evaluate() as? String, "foo")
}
func testNullImageExpression() {
let null: UIImage? = nil
let node = LayoutNode(constants: ["foo": null as Any])
let expression = LayoutExpression(imageExpression: "{foo}", for: node)
XCTAssertEqual((try expression?.evaluate() as? UIImage).map { $0.size }, .zero)
}
func testNullAnyExpression() {
let null: Any? = nil
let node = LayoutNode(constants: ["foo": null as Any])
let expression = LayoutExpression(expression: "foo", type: RuntimeType(Any.self), for: node)
XCTAssertThrowsError(try expression?.evaluate()) { error in
XCTAssert("\(error)".contains("nil"))
}
}
}
| 39.477273 | 100 | 0.6327 |
fc59285ca1a61f7a86ed8c03ec8eeba367e9dff2 | 2,486 | //
// ViewController.swift
// MFSnackBar
//
// Created by Jakub Darowski on 01/13/2017.
// Copyright (c) 2017 Jakub Darowski. All rights reserved.
//
import UIKit
import MFSnackBar
class ViewController: UIViewController {
var snackBar : MFSnackBarViewController?
var shouldUseSnackBarWindow = true
var animationDuration : TimeInterval = 0.0 {
didSet {
UIView.animate(withDuration: 0.1) {
self.animationDurationLabel.text = String(format: "%.1lf", self.animationDuration)
}
}
}
@IBOutlet weak var animationDurationSlider: UISlider!
@IBOutlet weak var animationDurationLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
snackBar = MFSnackBarViewController()
snackBar?.configureSnackbar(withMessage: "Supeeer uaoeiaeoiaoe duidy,.uikj dhfydihdihfyg hfygphdi ihd deuod pyeou", buttonText: "Okeej", dismissAction: { view in print("dismiss")}, buttonAction: { view in print("button"); view?.appendMessage(message: " more")} )
let snackBarViewConfigurator = MFSnackBarViewConfigurator()
if !shouldUseSnackBarWindow {
snackBarViewConfigurator.topMargin = (self.navigationController?.navigationBar.frame.size.height ?? 0) + snackBarViewConfigurator.topMargin
snackBarViewConfigurator.sideMargin = 0.0
snackBarViewConfigurator.cornerRadius = 0.0
}
snackBar?.snackBarConfigurator = snackBarViewConfigurator
animationDuration = 0.2
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showSnackBarButtonPressed(_ sender: Any) {
if shouldUseSnackBarWindow {
snackBar?.showView(animated: true, animationDuration)
} else {
snackBar?.showView(animated: true, animationDuration, inView: self.view)
}
}
@IBAction func hideSnackBarButtonPressed(_ sender: Any) {
snackBar?.hideView(animated: true, animationDuration)
}
@IBAction func sliderValueChanged(_ sender: UISlider) {
animationDuration = round(TimeInterval(sender.value) * 10.0) * 0.1
}
@IBAction func closeViewButtonPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
| 34.527778 | 271 | 0.671762 |
bba21486a2b3a07dfd02dd0a1f253cf01b9d40b2 | 5,752 | //
// ReferenceTypesFromJSON.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-11-29.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2018 Tristan Himmelman
//
// 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 XCTest
import DVTObjectMapper
class ToObjectTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testMappingPersonFromJSON(){
let name = "ASDF"
let spouseName = "HJKL"
let JSONString = "{\"name\" : \"\(name)\", \"spouse\" : {\"name\" : \"\(spouseName)\"}}"
let mappedObject = Mapper<Person>().map(JSONString: JSONString)
XCTAssertNotNil(mappedObject)
XCTAssertEqual(mappedObject?.name, name)
XCTAssertEqual(mappedObject?.spouse?.name, spouseName)
}
func testUpdatingChildObject(){
let name = "ASDF"
let initialSpouseName = "HJKL"
let updatedSpouseName = "QWERTY"
let initialJSONString = "{\"name\" : \"\(name)\", \"spouse\" : {\"name\" : \"\(initialSpouseName)\"}}"
let updatedJSONString = "{\"name\" : \"\(name)\", \"spouse\" : {\"name\" : \"\(updatedSpouseName)\"}}"
let mappedObject = Mapper<Person>().map(JSONString: initialJSONString)
let initialSpouse = mappedObject?.spouse
XCTAssertNotNil(mappedObject)
let updatedObject = Mapper<Person>().map(JSONString: updatedJSONString, toObject: mappedObject!)
XCTAssert(initialSpouse === updatedObject.spouse, "Expected mapping to update the existing object not create a new one")
XCTAssertEqual(updatedObject.spouse?.name, updatedSpouseName)
XCTAssertEqual(initialSpouse?.name, updatedSpouseName)
}
func testUpdatingChildDictionary(){
let childKey = "child_1"
let initialChildName = "HJKL"
let updatedChildName = "QWERTY"
let initialJSONString = "{\"children\" : {\"\(childKey)\" : {\"name\" : \"\(initialChildName)\"}}}"
let updatedJSONString = "{\"children\" : {\"\(childKey)\" : {\"name\" : \"\(updatedChildName)\"}}}"
let mappedObject = Mapper<Person>().map(JSONString: initialJSONString)
let initialChild = mappedObject?.children?[childKey]
XCTAssertNotNil(mappedObject)
XCTAssertNotNil(initialChild)
XCTAssertEqual(initialChild?.name, initialChildName)
_ = Mapper<Person>().map(JSONString: updatedJSONString, toObject: mappedObject!)
let updatedChild = mappedObject?.children?[childKey]
XCTAssert(initialChild === updatedChild, "Expected mapping to update the existing object not create a new one")
XCTAssertEqual(updatedChild?.name, updatedChildName)
XCTAssertEqual(initialChild?.name, updatedChildName)
}
func testToObjectFromString() {
let username = "bob"
let JSONString = "{\"username\":\"\(username)\"}"
let user = User()
user.username = "Tristan"
_ = Mapper().map(JSONString: JSONString, toObject: user)
XCTAssertEqual(user.username, username)
}
func testToObjectFromJSON() {
let username = "bob"
let JSON = ["username": username]
let user = User()
user.username = "Tristan"
_ = Mapper().map(JSON: JSON, toObject: user)
XCTAssertEqual(username, user.username)
}
func testToObjectFromAny() {
let username = "bob"
let userJSON = ["username": username]
let user = User()
user.username = "Tristan"
_ = Mapper().map(JSONObject: userJSON as Any, toObject: user)
XCTAssertEqual(user.username, username)
}
class Person: Mappable {
var name: String?
var spouse: Person?
var children: [String: Person]?
required init?(map: Map) {
}
func mapping(map: Map) {
name <- map["name"]
spouse <- map["spouse"]
children <- map["children"]
}
}
class User: Mappable {
var username: String = ""
init(){
}
required init?(map: Map){
}
func mapping(map: Map) {
username <- map["username"]
}
}
struct HumanInfo: Mappable {
var name: String?
init(name: String) {
self.name = name
}
init?(map: Map) {
}
mutating func mapping(map: Map) {
name <- map["name"]
}
}
struct Human: Mappable {
var info: HumanInfo?
init(name: String) {
info = HumanInfo(name: name)
}
init?(map: Map) {
}
mutating func mapping(map: Map) {
info <- map["info"]
}
}
func testConsume() {
var human1 = Human(name: "QW") //has a with name "QW"
let human2 = Human(name: "ER") //has a with name "ER"
human1 = Mapper().map(JSON: human2.toJSON(), toObject: human1)
XCTAssertEqual(human1.info?.name, human2.info?.name)
}
}
| 27.653846 | 122 | 0.683241 |
1d2aa8ad15294971ed3d6413db1ad049fb547531 | 3,490 | //
// TrackBall.swift
// LayersAnimation
//
// Created by Mazy on 2017/6/14.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
postfix operator **
postfix func ** (value: CGFloat) -> CGFloat {
return value * value
}
class TrackBall: NSObject {
let tolerance = 0.001
var baseTransform = CATransform3DIdentity
let trackBallRadius: CGFloat
let trackBallCenter: CGPoint
var trackBallStartPoint = (x: CGFloat(0.0), y: CGFloat(0.0), z: CGFloat(0.0))
init(with location: CGPoint, inRect bounds: CGRect) {
if bounds.width > bounds.height {
trackBallRadius = bounds.height * 0.5
} else {
trackBallRadius = bounds.width * 0.5
}
trackBallCenter = CGPoint(x: bounds.midX, y: bounds.midY)
super.init()
setStartPointFromLocation(location)
}
func setStartPointFromLocation(_ location: CGPoint) {
trackBallStartPoint.x = location.x - trackBallCenter.x
trackBallStartPoint.y = location.y - trackBallCenter.y
let distance = trackBallStartPoint.x** + trackBallStartPoint.y**
trackBallStartPoint.z = distance > trackBallRadius** ? CGFloat(0.0) : sqrt(trackBallRadius** - distance)
}
func finalizeTrackBallForLocation(_ location: CGPoint) {
baseTransform = rotationTransformForLocation(location)
}
func rotationTransformForLocation(_ location: CGPoint) -> CATransform3D {
var trackPointCurrentPoint = (x: location.x - trackBallCenter.x, y: location.y - trackBallCenter.y, z: CGFloat(0.0))
let withInTolerance = fabs(Double(trackPointCurrentPoint.x - trackBallStartPoint.x)) < tolerance && fabs(Double(trackPointCurrentPoint.y - trackBallStartPoint.y)) < tolerance
if withInTolerance {
return CATransform3DIdentity
}
let distance = trackPointCurrentPoint.x** + trackPointCurrentPoint.y**
if distance > trackBallRadius** {
trackPointCurrentPoint.z = 0.0
} else {
trackPointCurrentPoint.z = sqrt(trackBallRadius** - distance)
}
let startPoint = trackBallStartPoint
let currentPoint = trackPointCurrentPoint
let x = startPoint.y * currentPoint.z - startPoint.z * currentPoint.y
let y = -startPoint.x * currentPoint.z + trackBallStartPoint.z * currentPoint.x
let z = startPoint.x * currentPoint.y - startPoint.y * currentPoint.x
var rotationVector = (x: x, y: y, z: z)
let startLength = sqrt(Double(startPoint.x** + startPoint.y** + startPoint.z**))
let currentLength = sqrt(Double(currentPoint.x** + currentPoint.y** + currentPoint.z**))
let startDotCurrent = Double(startPoint.x * currentPoint.x + startPoint.y + currentPoint.y + startPoint.z + currentPoint.z)
let rotationLength = sqrt(Double(rotationVector.x** + rotationVector.y** + rotationVector.z**))
let angle = CGFloat(atan2(rotationLength / (startLength * currentLength), startDotCurrent / (startLength * currentLength)))
let normalizer = CGFloat(rotationLength)
rotationVector.x /= normalizer
rotationVector.y /= normalizer
rotationVector.z /= normalizer
let rotationTransform = CATransform3DMakeRotation(angle, rotationVector.x, rotationVector.y, rotationVector.z)
return CATransform3DConcat(baseTransform, rotationTransform)
}
}
| 40.581395 | 182 | 0.661318 |
abbd17af3e4d627dc1b574ea40b266cc61bb233d | 939 | // Copyright © 2017 SkeletonView. All rights reserved.
import UIKit
public protocol Appearance {
var tintColor: UIColor { get set }
var gradient: SkeletonGradient { get set }
var multilineHeight: CGFloat { get set }
var multilineSpacing: CGFloat { get set }
var multilineLastLineFillPercent: Int { get set }
var multilineCornerRadius: Int { get set }
}
public enum SkeletonAppearance {
public static var `default`: Appearance = SkeletonViewAppearance.shared
}
// codebeat:disable[TOO_MANY_IVARS]
class SkeletonViewAppearance: Appearance {
static var shared = SkeletonViewAppearance()
var tintColor: UIColor = .clouds
var gradient: SkeletonGradient = SkeletonGradient(baseColor: .clouds)
var multilineHeight: CGFloat = 15
var multilineSpacing: CGFloat = 10
var multilineLastLineFillPercent: Int = 70
var multilineCornerRadius: Int = 0
}
// codebeat:enable[TOO_MANY_IVARS]
| 26.083333 | 75 | 0.736954 |
2976bad311658dcd46be5f307da211c391f9623d | 2,179 | //
// AppDelegate.swift
// DymRangeSlider
//
// Created by Yiming Dong on 29/11/18.
// Copyright © 2018 Yiming Dong. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.361702 | 285 | 0.755392 |
22f679b1865577ada6efd62f6d7dbfc1020ab50e | 5,909 | //
import Defaults
// EventStore.swift
// MeetingBar
//
// Created by Andrii Leitsius on 12.06.2020.
// Copyright © 2020 Andrii Leitsius. All rights reserved.
//
import EventKit
extension EKEventStore {
func getMatchedCalendars(titles: [String] = [], ids: [String] = []) -> [EKCalendar] {
var matchedCalendars: [EKCalendar] = []
let allCalendars = calendars(for: .event)
for calendar in allCalendars {
if titles.contains(calendar.title) || ids.contains(calendar.calendarIdentifier) {
matchedCalendars.append(calendar)
}
}
return matchedCalendars
}
func getAllCalendars() -> [String: [EKCalendar]] {
let calendars = self.calendars(for: .event)
return Dictionary(grouping: calendars) { $0.source.title }
}
func loadEventsForDate(calendars: [EKCalendar], date: Date) -> [EKEvent] {
let dayMidnight = Calendar.current.startOfDay(for: date)
let nextDayMidnight = Calendar.current.date(byAdding: .day, value: 1, to: dayMidnight)!
let showAlldayEvents: Bool = Defaults[.allDayEvents] == AlldayEventsAppereance.show
let predicate = predicateForEvents(withStart: dayMidnight, end: nextDayMidnight, calendars: calendars)
let calendarEvents = events(matching: predicate).filter { ($0.isAllDay && showAlldayEvents) || Calendar.current.isDate($0.startDate, inSameDayAs: dayMidnight) }
var filteredCalendarEvents = [EKEvent]()
for calendarEvent in calendarEvents {
if !shouldIncludeMeeting(calendarEvent) {
continue
}
var addEvent = false
if calendarEvent.isAllDay {
if Defaults[.allDayEvents] == AlldayEventsAppereance.show {
addEvent = true
} else if Defaults[.allDayEvents] == AlldayEventsAppereance.show_with_meeting_link_only {
let result = getMeetingLink(calendarEvent)
if result?.url != nil {
addEvent = true
}
}
} else {
if Defaults[.nonAllDayEvents] == NonAlldayEventsAppereance.hide_without_meeting_link {
let result = getMeetingLink(calendarEvent)
if result?.url != nil {
addEvent = true
}
} else {
addEvent = true
}
}
let status = getEventParticipantStatus(calendarEvent)
if status == .pending, Defaults[.showPendingEvents] == .hide {
addEvent = false
}
if addEvent {
filteredCalendarEvents.append(calendarEvent)
}
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = I18N.instance.locale
let dateString = formatter.string(from: date)
NSLog("Loaded events for date \(dateString) from calendars \(calendars.map { $0.title })")
return filteredCalendarEvents
}
func getNextEvent(calendars: [EKCalendar]) -> EKEvent? {
var nextEvent: EKEvent?
let now = Date()
let startPeriod = Calendar.current.date(byAdding: .minute, value: 1, to: now)!
var endPeriod: Date
let todayMidnight = Calendar.current.startOfDay(for: now)
switch Defaults[.showEventsForPeriod] {
case .today:
endPeriod = Calendar.current.date(byAdding: .day, value: 1, to: todayMidnight)!
case .today_n_tomorrow:
endPeriod = Calendar.current.date(byAdding: .day, value: 2, to: todayMidnight)!
}
let predicate = predicateForEvents(withStart: startPeriod, end: endPeriod, calendars: calendars)
var nextEvents = events(matching: predicate)
// Filter out personal events, if not marked as 'active'
if Defaults[.personalEventsAppereance] != .show_active {
nextEvents = nextEvents.filter { $0.hasAttendees }
}
// If the current event is still going on,
// but the next event is closer than 13 minutes later
// then show the next event
for event in nextEvents {
if event.isAllDay || !shouldIncludeMeeting(event) {
continue
} else {
if Defaults[.nonAllDayEvents] == NonAlldayEventsAppereance.show_inactive_without_meeting_link {
let meetingLink = getMeetingLink(event)
if meetingLink == nil {
continue
}
} else if Defaults[.nonAllDayEvents] == NonAlldayEventsAppereance.hide_without_meeting_link {
let result = getMeetingLink(event)
if result?.url == nil {
continue
}
}
}
if let status = getEventParticipantStatus(event) {
if status == .declined { // Skip event if declined
continue
}
if status == .pending, Defaults[.showPendingEvents] == PendingEventsAppereance.hide || Defaults[.showPendingEvents] == PendingEventsAppereance.show_inactive {
continue
}
}
if event.status == .canceled {
continue
} else {
if nextEvent == nil {
nextEvent = event
continue
} else {
let soon = now.addingTimeInterval(780) // 13 min from now
if event.startDate < soon {
nextEvent = event
} else {
break
}
}
}
}
return nextEvent
}
}
| 36.701863 | 174 | 0.555424 |
e0eb218b4d2e73ca264a6b37859587ff35bf0401 | 897 | //
// ResizableTests.swift
// ResizableTests
//
// Created by Caroline on 6/09/2014.
// Copyright (c) 2014 Caroline. All rights reserved.
//
import UIKit
import XCTest
class ResizableTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 24.243243 | 111 | 0.61427 |
acd5a05b30da3eab2a3c5ee863a84f7789f22420 | 4,548 | //
// RecommeViewController.swift
// DYZB
//
// Created by 李孔文 on 2018/2/11.
// Copyright © 2018年 iOS _Liu. All rights reserved.
//
import UIKit
private let ItemMargin : CGFloat = 10
private let ItemW = (screenW - ItemMargin*3) / 2
private let ItemH = ItemW * 3 / 4
private let normalCell = "normalCell"
private let headerViewID = "headerViewID"
private let ItemheaderH : CGFloat = 50
private let cycleHeight = screenH * 3 / 8
private let recommeGameHeight : CGFloat = 90
class RecommeViewController: UIViewController {
//懒加载UICollectionView
fileprivate lazy var recommeMV : RecommeModel = RecommeModel()
//懒加载无线滚动View
fileprivate lazy var recommeCycle : RecommendCycle = {
let cycleView = RecommendCycle.createCycleView()
cycleView.frame = CGRect(x: 0, y: -(cycleHeight + recommeGameHeight), width: screenW, height: cycleHeight)
return cycleView
}()
//懒加载游戏推荐
fileprivate lazy var recommeGame : recomeGameView = {
let recommeGame = recomeGameView.createCycleView()
recommeGame.frame = CGRect(x: 0, y: -recommeGameHeight, width: screenW, height: recommeGameHeight)
return recommeGame
}()
fileprivate lazy var collection : UICollectionView = {[unowned self] in
//1、创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: ItemW, height: ItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = ItemMargin
layout.sectionInset = UIEdgeInsets(top: 0, left: ItemMargin, bottom: 0, right: ItemMargin)
layout.headerReferenceSize = CGSize(width: screenW, height: ItemheaderH)
//2、创建UICollectionView
let collection = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collection.backgroundColor = UIColor.yellow
//3、注册cell
//(1、普通cell注册 collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: normalCell)
collection.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: normalCell)
//4、注册headView
//(1、普通注册 collection.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewID)
//(2、取xib注册
collection.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewID)
//5、设置属性让collectionview随父控件的拉伸而拉伸
collection.autoresizingMask = [.flexibleHeight,.flexibleWidth]
collection.dataSource = self
return collection
}()
//回调函数
override func viewDidLoad() {
super.viewDidLoad()
setUI()
loadData()
}
}
//设置UI
extension RecommeViewController{
fileprivate func setUI(){
//1、将collection添加到控制器的View当中
view.addSubview(collection)
//2、将无线轮播图添加到collection中
collection.addSubview(recommeCycle)
//3、游戏推荐页面
collection.addSubview(recommeGame)
//4、给collection设置内边距--用来放置广告窗
collection.contentInset = UIEdgeInsets(top: cycleHeight + recommeGameHeight, left: 0, bottom: 0, right: 0)
}
}
//发送网络请求
extension RecommeViewController{
func loadData(){
recommeMV.requestData()
recommeMV.requestCycle()
//4、给轮播传送数据
recommeCycle.data = recommeMV.cycleGroup
}
}
extension RecommeViewController : UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 12
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 8
}
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1、获取cell
let cell = collection.dequeueReusableCell(withReuseIdentifier: normalCell, for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerViewID, for: indexPath)
return headview
}
}
| 33.688889 | 181 | 0.680299 |
e53da2b9a88c296d931b9455cd86b832aad9a3c0 | 2,833 | //
// JWTECTests.swift
//
// Copyright (c) 2016-present, LINE Corporation. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by LINE Corporation.
//
// As with any software that integrates with the LINE Corporation platform, your use of this software
// is subject to the LINE Developers Agreement [http://terms2.line.me/LINE_Developers_Agreement].
// This copyright 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 XCTest
@testable import LineSDK
// Private Key for test cases in this file:
/*
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgevZzL1gdAFr88hb2
OF/2NxApJCzGCEDdfSp6VQO30hyhRANCAAQRWz+jn65BtOMvdyHKcvjBeBSDZH2r
1RTwjmYSi9R/zpBnuQ4EiMnCqfMPWiZqB4QdbAd0E7oH50VpuZ1P087G
-----END PRIVATE KEY-----
*/
private let pubKey = """
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9
q9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==
-----END PUBLIC KEY-----
"""
/*
{
"alg": "RS256",
"typ": "JWT"
}.
{
"sub": "1234567890",
"name": "John Doe",
"admin": true,
"iat": 1516239022
}
*/
private let sample = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.0w6hDu9x9xd-FJqrJRboTslqAStdldw4jySapjF0tzxwhodlUS3zu81Z0bb1SoZckuprac2vxiuOH2I5i2uFUg"
private let LINEIDToken = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMzQ1In0.eyJpc3MiOiJodHRwczovL2FjY2Vzcy5saW5lLm1lIiwic3ViIjoiVTEyMzQ1Njc4OTBhYmNkZWYxMjM0NTY3ODkwYWJjZGVmIiwiYXVkIjoiMTIzNDUiLCJleHAiOjE1MzU5NTk4NzAsImlhdCI6MTUzNTk1OTc3MCwibm9uY2UiOiJBQkNBQkMiLCJuYW1lIjoib25ldmNhdCIsInBpY3R1cmUiOiJodHRwczovL29icy1iZXRhLmxpbmUtYXBwcy5jb20veHh4eCIsImVtYWlsIjoiYWJjQGRlZi5jb20ifQ.Chf78LoctctsENqBB5MecAYKlo--ITHL-C2Ah0zYqQM4C9i9yvwOMH7hYInIsVVVmleHxtOT7yPWuiMUbvpDMA"
class JWTECTests: XCTestCase {
func testJWTSignatureVerify() {
let data = Data(sample.utf8)
let token = try! JWT(data: data)
let key = try! Crypto.ECDSAPublicKey(pem: pubKey)
let result = try! token.verify(with: key)
XCTAssertTrue(result)
}
}
| 39.901408 | 474 | 0.786798 |
616ef21426697602bdbdc951f9f1dbfb4f27546e | 124 | import XCTest
import ShimmerViewTests
var tests = [XCTestCaseEntry]()
tests += ShimmerViewTests.allTests()
XCTMain(tests)
| 15.5 | 36 | 0.790323 |
2899111641182e0841101578cc232ca07ee2745e | 465 | import RIBs
import UIKit
extension UINavigationController: ViewControllable {
// MARK: Lifecycle
public convenience init(image: UIImage? = nil, unselectedImage: UIImage? = nil, root: ViewControllable) {
self.init(rootViewController: root.uiviewController)
tabBarItem.image = unselectedImage
tabBarItem.selectedImage = image
navigationBar.tintColor = .black
}
// MARK: Public
public var uiviewController: UIViewController { self }
}
| 22.142857 | 107 | 0.748387 |
69652489a09d020651b8aca69a16ef072803c2ba | 63 | //
// File.swift
// FingerprintExample
//
import Foundation
| 9 | 22 | 0.68254 |
1e6f57d05957ff30dd1f3d26cd2cd2b5ecc58733 | 2,400 | //
// NestedInteger.swift
// CodingChallenges
//
// Created by William Boles on 17/12/2021.
// Copyright © 2021 Boles. All rights reserved.
//
import Foundation
class NestedInteger {
private var value: Int?
private var list: [NestedInteger]?
// MARK: - Integer
func isInteger() -> Bool {
return value != nil
}
func getInteger() -> Int {
return value!
}
func setInteger(_ value: Int) {
self.value = value
}
// MARK: - List
func add(_ elem: NestedInteger) {
if list != nil {
self.list?.append(elem)
} else {
list = [elem]
}
}
func getList() -> [NestedInteger] {
return list!
}
}
extension NestedInteger {
static func deserialize(_ s: String) -> NestedInteger {
guard s[s.startIndex] == "[" else {
let ni = NestedInteger()
ni.setInteger(Int(s)!)
return ni
}
var stack = [NestedInteger]()
var num = ""
var head: NestedInteger!
for c in s {
if c == "[" {
let ni = NestedInteger()
stack.last?.add(ni)
stack.append(ni)
} else if c == "]" {
if let val = Int(num) {
let ni = NestedInteger()
ni.setInteger(val)
stack.last?.add(ni)
num = ""
}
head = stack.removeLast()
} else if c == "," {
if let val = Int(num) {
let ni = NestedInteger()
ni.setInteger(val)
stack.last?.add(ni)
num = ""
}
} else {
num += String(c)
}
}
return head
}
static func serialize(_ ni: NestedInteger) -> String {
guard !ni.isInteger() else {
return "\(ni.getInteger())"
}
var childStrings = [String]()
for child in ni.getList() {
childStrings.append(serialize(child))
}
return "[\(childStrings.joined(separator: ","))]"
}
}
| 22.857143 | 59 | 0.4125 |
46f7872d3dee84e929a64ba3cda949bfdb91a99e | 1,407 | //
// AppDelegate.swift
// TheMovieDB
//
// Created by ibrahim on 24/07/20.
// Copyright © 2020 ibrahim. All rights reserved.
//
import UIKit
@UIApplicationMain
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.
}
}
| 39.083333 | 179 | 0.748401 |
f5c3ffc3df8e7e467ed636f9ce26222d6ca241c0 | 18,991 | //
// Kumulos+Push.swift
// Copyright © 2016 Kumulos. All rights reserved.
//
import Foundation
import UserNotifications
import ObjectiveC.runtime
public class KSPushNotification: NSObject {
internal static let DeepLinkTypeInApp : Int = 1;
internal(set) open var id: Int
internal(set) open var aps: [AnyHashable:Any]
internal(set) open var data : [AnyHashable:Any]
internal(set) open var url: URL?
internal(set) open var actionIdentifier: String?
init(userInfo: [AnyHashable:Any]?) {
self.id = 0
self.aps = [:]
self.data = [:]
guard let userInfo = userInfo else {
return
}
guard let aps = userInfo["aps"] as? [AnyHashable:Any] else {
return
}
self.aps = aps
guard let custom = userInfo["custom"] as? [AnyHashable:Any] else {
return
}
guard let data = custom["a"] as? [AnyHashable:Any] else {
return
}
self.data = data
guard let msg = data["k.message"] as? [AnyHashable:Any] else {
return
}
let msgData = msg["data"] as! [AnyHashable:Any]
id = msgData["id"] as! Int
if let urlStr = custom["u"] as? String {
url = URL(string: urlStr)
} else {
url = nil
}
}
@available(iOS 10.0, *)
convenience init(userInfo: [AnyHashable:Any]?, response: UNNotificationResponse?) {
self.init(userInfo: userInfo)
if let notificationResponse = response {
if (notificationResponse.actionIdentifier != UNNotificationDefaultActionIdentifier) {
actionIdentifier = notificationResponse.actionIdentifier
}
}
}
public func inAppDeepLink() -> [AnyHashable:Any]? {
guard let deepLink = data["k.deepLink"] as? [AnyHashable:Any] else {
return nil
}
if deepLink["type"] as? Int != KSPushNotification.DeepLinkTypeInApp {
return nil
}
return deepLink
}
}
@available(iOS 10.0, *)
public typealias KSUNAuthorizationCheckedHandler = (UNAuthorizationStatus, Error?) -> Void
public extension Kumulos {
/**
Helper method for requesting the device token with alert, badge and sound permissions.
On success will raise the didRegisterForRemoteNotificationsWithDeviceToken UIApplication event
*/
@available(iOS 10.0, *)
static func pushRequestDeviceToken(_ onAuthorizationStatus: KSUNAuthorizationCheckedHandler? = nil) {
requestToken(onAuthorizationStatus)
}
/**
Helper method for requesting the device token with alert, badge and sound permissions.
On success will raise the didRegisterForRemoteNotificationsWithDeviceToken UIApplication event
*/
static func pushRequestDeviceToken() {
if #available(iOS 10.0, *) {
requestToken()
} else {
DispatchQueue.main.async {
requestTokenLegacy()
}
}
}
@available(iOS 10.0, *)
fileprivate static func requestToken(_ onAuthorizationStatus: KSUNAuthorizationCheckedHandler? = nil) {
let center = UNUserNotificationCenter.current()
let requestToken : () -> Void = {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
let askPermission : () -> Void = {
DispatchQueue.main.async {
if UIApplication.shared.applicationState == .background {
onAuthorizationStatus?(.notDetermined,
NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Application not active, aborting push permission request"]) as Error)
return
}
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if let err = error {
onAuthorizationStatus?(.notDetermined, err)
return
}
if (!granted) {
onAuthorizationStatus?(.denied, nil)
return
}
onAuthorizationStatus?(.authorized, nil)
requestToken()
}
}
}
center.getNotificationSettings { (settings) in
switch settings.authorizationStatus {
case .denied:
onAuthorizationStatus?(settings.authorizationStatus, nil)
return
case .authorized:
onAuthorizationStatus?(settings.authorizationStatus, nil)
requestToken()
break
default:
askPermission()
break
}
}
}
@available(iOS, deprecated: 10.0)
fileprivate static func requestTokenLegacy() {
// Determine the type of notifications we want to ask permission for, for example we may want to alert the user, update the badge number and play a sound
let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound]
// Create settings based on those notification types we want the user to accept
let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
// Get the main application
let application = UIApplication.shared
// Register the settings created above - will show alert first if the user hasn't previously done this
// See delegate methods in AppDelegate - the AppDelegate conforms to the UIApplicationDelegate protocol
application.registerUserNotificationSettings(pushNotificationSettings)
application.registerForRemoteNotifications()
}
/**
Register a device token with the Kumulos Push service
Parameters:
- deviceToken: The push token returned by the device
*/
static func pushRegister(_ deviceToken: Data) {
let token = serializeDeviceToken(deviceToken)
let iosTokenType = getTokenType()
let bundleId = Bundle.main.infoDictionary!["CFBundleIdentifier"] as Any
let parameters = ["token" : token,
"type" : sharedInstance.pushNotificationDeviceType,
"iosTokenType" : iosTokenType,
"bundleId": bundleId] as [String : Any]
Kumulos.trackEvent(eventType: KumulosEvent.PUSH_DEVICE_REGISTER, properties: parameters as [String : AnyObject], immediateFlush: true)
}
/**
Unsubscribe your device from the Kumulos Push service
*/
static func pushUnregister() {
Kumulos.trackEvent(eventType: KumulosEvent.DEVICE_UNSUBSCRIBED, properties: [:], immediateFlush: true)
}
// MARK: Open handling
/**
Track a user action triggered by a push notification
Parameters:
- notification: The notification which triggered the action
*/
static func pushTrackOpen(notification: KSPushNotification?) {
guard let notification = notification else {
return
}
let params = ["type": KS_MESSAGE_TYPE_PUSH, "id": notification.id]
Kumulos.trackEvent(eventType: KumulosEvent.MESSAGE_OPENED, properties:params)
}
@available(iOS 9.0, *)
internal func pushHandleOpen(withUserInfo: [AnyHashable: Any]?) {
guard let userInfo = withUserInfo else {
return
}
let notification = KSPushNotification(userInfo: userInfo)
if notification.id == 0 {
return
}
self.pushHandleOpen(notification: notification)
}
@available(iOS 10.0, *)
internal func pushHandleOpen(withUserInfo: [AnyHashable: Any]?, response: UNNotificationResponse?) -> Bool {
let notification = KSPushNotification(userInfo: withUserInfo, response: response)
if notification.id == 0 {
return false
}
self.pushHandleOpen(notification: notification)
PendingNotificationHelper.remove(id: notification.id)
return true
}
private func pushHandleOpen(notification: KSPushNotification) {
Kumulos.pushTrackOpen(notification: notification)
// Handle URL pushes
if let url = notification.url {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:]) { (success) in
// noop
}
} else {
DispatchQueue.main.async {
UIApplication.shared.openURL(url)
}
}
}
self.inAppHelper.handlePushOpen(notification: notification)
if let userOpenedHandler = self.config.pushOpenedHandlerBlock {
DispatchQueue.main.async {
userOpenedHandler(notification)
}
}
}
// MARK: Dismissed handling
@available(iOS 10.0, *)
internal func pushHandleDismissed(withUserInfo: [AnyHashable: Any]?, response: UNNotificationResponse?) -> Bool {
let notification = KSPushNotification(userInfo: withUserInfo, response: response)
if notification.id == 0 {
return false
}
self.pushHandleDismissed(notificationId: notification.id)
return true
}
@available(iOS 10.0, *)
private func pushHandleDismissed(notificationId: Int, dismissedAt: Date? = nil) {
PendingNotificationHelper.remove(id: notificationId)
self.pushTrackDismissed(notificationId: notificationId, dismissedAt: dismissedAt)
}
@available(iOS 10.0, *)
private func pushTrackDismissed(notificationId: Int, dismissedAt: Date? = nil) {
let params = ["type": KS_MESSAGE_TYPE_PUSH, "id": notificationId]
if let unwrappedDismissedAt = dismissedAt {
Kumulos.trackEvent(eventType: KumulosEvent.MESSAGE_DISMISSED.rawValue, atTime: unwrappedDismissedAt, properties:params)
}
else{
Kumulos.trackEvent(eventType: KumulosEvent.MESSAGE_DISMISSED, properties:params)
}
}
@available(iOS 10.0, *)
internal func maybeTrackPushDismissedEvents() {
if (!AppGroupsHelper.isKumulosAppGroupDefined()){
return;
}
UNUserNotificationCenter.current().getDeliveredNotifications { (notifications: [UNNotification]) in
var actualPendingNotificationIds: [Int] = []
for notification in notifications {
let notification = KSPushNotification(userInfo: notification.request.content.userInfo)
if (notification.id == 0){
continue
}
actualPendingNotificationIds.append(notification.id)
}
let recordedPendingNotifications = PendingNotificationHelper.readAll()
let deletions = recordedPendingNotifications.filter({ !actualPendingNotificationIds.contains( $0.id ) })
for deletion in deletions {
self.pushHandleDismissed(notificationId: deletion.id, dismissedAt: deletion.deliveredAt)
}
}
}
// MARK: Token handling
fileprivate static func serializeDeviceToken(_ deviceToken: Data) -> String {
var token: String = ""
for i in 0..<deviceToken.count {
token += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
}
return token
}
fileprivate static func getTokenType() -> Int {
let releaseMode = MobileProvision.releaseMode()
if let index = [
UIApplicationReleaseMode.adHoc,
UIApplicationReleaseMode.dev,
UIApplicationReleaseMode.wildcard
].firstIndex(of: releaseMode), index > -1 {
return releaseMode.rawValue + 1;
}
return Kumulos.sharedInstance.pushNotificationProductionTokenType
}
}
// MARK: Swizzling
fileprivate var existingDidReg : IMP?
fileprivate var existingDidFailToReg : IMP?
fileprivate var existingDidReceive : IMP?
class PushHelper {
typealias kumulos_applicationDidRegisterForRemoteNotifications = @convention(c) (_ obj:UIApplicationDelegate, _ _cmd:Selector, _ application:UIApplication, _ deviceToken:Data) -> Void
typealias didRegBlock = @convention(block) (_ obj:UIApplicationDelegate, _ application:UIApplication, _ deviceToken:Data) -> Void
typealias kumulos_applicationDidFailToRegisterForRemoteNotificaitons = @convention(c) (_ obj:Any, _ _cmd:Selector, _ application:UIApplication, _ error:Error) -> Void
typealias didFailToRegBlock = @convention(block) (_ obj:Any, _ application:UIApplication, _ error:Error) -> Void
typealias kumulos_applicationDidReceiveRemoteNotificationFetchCompletionHandler = @convention(c) (_ obj:Any, _ _cmd:Selector, _ application:UIApplication, _ userInfo: [AnyHashable : Any], _ completionHandler: @escaping (UIBackgroundFetchResult) -> Void) -> Void
typealias didReceiveBlock = @convention(block) (_ obj:Any, _ application:UIApplication, _ userInfo: [AnyHashable : Any], _ completionHandler: @escaping (UIBackgroundFetchResult) -> Void) -> Void
lazy var pushInit:Void = {
let klass : AnyClass = type(of: UIApplication.shared.delegate!)
// Did register push delegate
let didRegisterSelector = #selector(UIApplicationDelegate.application(_:didRegisterForRemoteNotificationsWithDeviceToken:))
let meth = class_getInstanceMethod(klass, didRegisterSelector)
let regType = NSString(string: "v@:@@").utf8String
let regBlock : didRegBlock = { (obj:UIApplicationDelegate, application:UIApplication, deviceToken:Data) -> Void in
if let _ = existingDidReg {
unsafeBitCast(existingDidReg, to: kumulos_applicationDidRegisterForRemoteNotifications.self)(obj, didRegisterSelector, application, deviceToken)
}
Kumulos.pushRegister(deviceToken)
}
let kumulosDidRegister = imp_implementationWithBlock(regBlock as Any)
existingDidReg = class_replaceMethod(klass, didRegisterSelector, kumulosDidRegister, regType)
// Failed to register handler
let didFailToRegisterSelector = #selector(UIApplicationDelegate.application(_:didFailToRegisterForRemoteNotificationsWithError:))
let didFailToRegType = NSString(string: "v@:@@").utf8String
let didFailToRegBlock : didFailToRegBlock = { (obj:Any, application:UIApplication, error:Error) -> Void in
if let _ = existingDidFailToReg {
unsafeBitCast(existingDidFailToReg, to: kumulos_applicationDidFailToRegisterForRemoteNotificaitons.self)(obj, didFailToRegisterSelector, application, error)
}
print("Failed to register for remote notifications: \(error)")
}
let kumulosDidFailToRegister = imp_implementationWithBlock(didFailToRegBlock as Any)
existingDidFailToReg = class_replaceMethod(klass, didFailToRegisterSelector, kumulosDidFailToRegister, didFailToRegType)
// iOS9 did receive remote delegate
// iOS9+ content-available handler
let didReceiveSelector = #selector(UIApplicationDelegate.application(_:didReceiveRemoteNotification:fetchCompletionHandler:))
let receiveType = NSString(string: "v@:@@@?").utf8String
let didReceive : didReceiveBlock = { (obj:Any, _ application: UIApplication, userInfo: [AnyHashable : Any], completionHandler: @escaping (UIBackgroundFetchResult) -> Void) in
var fetchResult : UIBackgroundFetchResult = .noData
let fetchBarrier = DispatchSemaphore(value: 0)
if let _ = existingDidReceive {
unsafeBitCast(existingDidReceive, to: kumulos_applicationDidReceiveRemoteNotificationFetchCompletionHandler.self)(obj, didReceiveSelector, application, userInfo, { (result : UIBackgroundFetchResult) in
fetchResult = result
fetchBarrier.signal()
})
} else {
fetchBarrier.signal()
}
if UIApplication.shared.applicationState == .inactive {
if #available(iOS 10, *) {
// Noop (tap handler in delegate will deal with opening the URL)
} else {
Kumulos.sharedInstance.pushHandleOpen(withUserInfo:userInfo)
}
}
let aps = userInfo["aps"] as! [AnyHashable:Any]
guard let contentAvailable = aps["content-available"] as? Int, contentAvailable == 1 else {
if #available(iOS 10, *) {} else {
self.setBadge(userInfo: userInfo)
self.trackPushDelivery(userInfo: userInfo)
}
completionHandler(fetchResult)
return
}
self.setBadge(userInfo: userInfo)
self.trackPushDelivery(userInfo: userInfo)
Kumulos.sharedInstance.inAppHelper.sync { (result:Int) in
_ = fetchBarrier.wait(timeout: DispatchTime.now() + DispatchTimeInterval.seconds(20))
if result < 0 {
fetchResult = .failed
} else if result > 0 {
fetchResult = .newData
}
// No data case is default, allow override from other handler
completionHandler(fetchResult)
}
}
let kumulosDidReceive = imp_implementationWithBlock(unsafeBitCast(didReceive, to: AnyObject.self))
existingDidReceive = class_replaceMethod(klass, didReceiveSelector, kumulosDidReceive, receiveType)
if #available(iOS 10, *) {
let delegate = KSUserNotificationCenterDelegate()
Kumulos.sharedInstance.notificationCenter = delegate
UNUserNotificationCenter.current().delegate = delegate
}
}()
fileprivate func setBadge(userInfo: [AnyHashable:Any]){
let badge: NSNumber? = KumulosHelper.getBadgeFromUserInfo(userInfo: userInfo)
if let newBadge = badge {
UIApplication.shared.applicationIconBadgeNumber = newBadge.intValue
}
}
fileprivate func trackPushDelivery(userInfo: [AnyHashable : Any]){
let notification = KSPushNotification(userInfo: userInfo)
if (notification.id == 0) {
return
}
let props: [String:Any] = ["type" : KS_MESSAGE_TYPE_PUSH, "id": notification.id]
Kumulos.trackEvent(eventType: KumulosSharedEvent.MESSAGE_DELIVERED, properties:props, immediateFlush: true)
}
}
| 38.915984 | 265 | 0.629035 |
083a2e4dd84f39a760f0a6fac41fdd1e2574eaa4 | 14,470 | /*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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.
*/
//
// Sender.swift
// Tracker
//
import Foundation
import CoreData
import UIKit
/// Hit sender
class Sender: Operation {
/// Tracker instance
let tracker: Tracker
/// Hit to send
var hit: Hit
/// Number of retry
let retryCount: Int = 3
/// Olt fixed value to use if multihits
var mhOlt: String?
/// force offline hits to be sent
var forceSendOfflineHits: Bool
/// Static var to check whether offline hits are being sent or not
struct OfflineHit {
static var processing: Bool = false
static var sentWithSuccess: Bool = false
}
/**
Initialize a sender
:params: tracker instance
:params: hit to send
:params: isOfflineHit indicates whether hit comes from database or not
*/
init(tracker: Tracker, hit: Hit, forceSendOfflineHits: Bool, mhOlt: String?) {
self.tracker = tracker
self.hit = hit
self.forceSendOfflineHits = forceSendOfflineHits
self.mhOlt = mhOlt
}
/**
Main function of NSOperation
*/
override func main () {
autoreleasepool{
self.send(false)
}
}
/**
Sends hit
*/
func send(_ includeOfflineHit: Bool = true) {
if(includeOfflineHit) {
Sender.sendOfflineHits(self.tracker, forceSendOfflineHits: false, async: false)
}
self.sendWithCompletionHandler(nil)
}
/**
Sends hit and call a callback to indicate if the hit was sent successfully or not
- parameter a: callback to indicate whether hit was sent successfully or not
*/
func sendWithCompletionHandler(_ completionHandler: ((success: Bool) -> Void)!) {
let db = Storage.sharedInstance
// Si pas de connexion ou que le mode offline est à "always"
if((self.tracker.configuration.parameters["storage"] == "always" && !self.forceSendOfflineHits)
|| TechnicalContext.connectionType == TechnicalContext.ConnexionType.offline
|| (!hit.isOffline && db.count() > 0)) {
// Si le mode offline n'est pas sur never (pas d'enregistrement)
if(self.tracker.configuration.parameters["storage"] != "never") {
// Si le hit ne provient pas du stockage offline, on le sauvegarde
if(!hit.isOffline) {
if(db.insert(&hit.url, mhOlt: self.mhOlt)) {
self.tracker.delegate?.saveDidEnd(hit.url)
if(Debugger.sharedInstance.viewController != nil) {
Debugger.sharedInstance.addEvent(self.hit.url, icon: "save48")
}
} else {
self.tracker.delegate?.warningDidOccur("Hit could not be saved : " + hit.url)
if(Debugger.sharedInstance.viewController != nil) {
Debugger.sharedInstance.addEvent("Hit could not be saved : " + hit.url, icon: "warning48")
}
}
}
}
} else {
let URL = Foundation.URL(string: hit.url)
if let optURL = URL {
// Si l'opération n'a pas été annulée on envoi sinon on sauvegarde le hit
if(!isCancelled) {
let semaphore = DispatchSemaphore(value: 0)
let sessionConfig = URLSessionConfiguration.default
sessionConfig.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
let session = URLSession(configuration: sessionConfig)
var request = URLRequest(url: optURL, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 30)
request.networkServiceType = NSURLRequest.NetworkServiceType.background
let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
var statusCode: Int?
if (response is HTTPURLResponse) {
let res = response as! HTTPURLResponse
statusCode = res.statusCode;
}
// Le hit n'a pas pu être envoyé
if(data == nil || error != nil || statusCode != 200) {
// Si le hit ne provient pas du stockage offline, on le sauvegarde si le mode offline est différent de "never"
if(self.tracker.configuration.parameters["storage"] != "never") {
if(!self.hit.isOffline) {
if(db.insert(&self.hit.url, mhOlt: self.mhOlt)) {
self.tracker.delegate?.saveDidEnd(self.hit.url)
if(Debugger.sharedInstance.viewController != nil) {
Debugger.sharedInstance.addEvent(self.hit.url, icon: "save48")
}
} else {
self.tracker.delegate?.warningDidOccur("Hit could not be saved : " + self.hit.url)
if(Debugger.sharedInstance.viewController != nil) {
Debugger.sharedInstance.addEvent("Hit could not be saved : " + self.hit.url, icon: "warning48")
}
}
} else {
let retryCount = db.getRetryCountForHit(self.hit.url)
if(retryCount < self.retryCount) {
db.setRetryCount(retryCount+1, hit: self.hit.url)
} else {
_ = db.delete(self.hit.url)
}
}
var errorMessage = ""
if let optError = error {
errorMessage = optError.localizedDescription
}
// On lève une erreur indiquant qu'une réponse autre que 200 a été reçue
self.tracker.delegate?.sendDidEnd(HitStatus.failed, message: errorMessage)
if(Debugger.sharedInstance.viewController != nil) {
Debugger.sharedInstance.addEvent(errorMessage, icon: "error48")
}
if((completionHandler) != nil) {
completionHandler(success: false)
}
}
} else {
// Si le hit provient du stockage et que l'envoi a réussi, on le supprime de la base
if(self.hit.isOffline) {
OfflineHit.sentWithSuccess = true
_ = db.delete(self.hit.url)
}
self.tracker.delegate?.sendDidEnd(HitStatus.success, message: self.hit.url)
if(Debugger.sharedInstance.viewController != nil) {
Debugger.sharedInstance.addEvent(self.hit.url, icon: "sent48")
}
if((completionHandler) != nil) {
completionHandler(success: true)
}
}
session.finishTasksAndInvalidate()
semaphore.signal()
})
task.resume()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
} else {
if(!hit.isOffline) {
if(db.insert(&hit.url, mhOlt: self.mhOlt)) {
self.tracker.delegate?.saveDidEnd(hit.url)
if(Debugger.sharedInstance.viewController != nil) {
Debugger.sharedInstance.addEvent(self.hit.url, icon: "save48")
}
} else {
self.tracker.delegate?.warningDidOccur("Hit could not be saved : " + hit.url)
if(Debugger.sharedInstance.viewController != nil) {
Debugger.sharedInstance.addEvent("Hit could not be saved : " + hit.url, icon: "warning48")
}
}
}
}
} else {
//On lève une erreur indiquant que le hit n'a pas été correctement construit et n'a pas pu être envoyé
self.tracker.delegate?.sendDidEnd(HitStatus.failed, message: "Hit could not be parsed and sent")
if(Debugger.sharedInstance.viewController != nil) {
Debugger.sharedInstance.addEvent("Hit could not be parsed and sent : " + hit.url, icon: "error48")
}
if((completionHandler) != nil) {
completionHandler(success: false)
}
}
}
}
class func sendOfflineHits(_ tracker: Tracker, forceSendOfflineHits: Bool, async: Bool = true) {
if((tracker.configuration.parameters["storage"] != "always" || forceSendOfflineHits)
&& TechnicalContext.connectionType != TechnicalContext.ConnexionType.offline) {
if(OfflineHit.processing == false)
{
// Check whether offline hits are already being sent
let offlineOperations = TrackerQueue.sharedInstance.queue.operations.filter() {
if let sender = $0 as? Sender {
if(sender.hit.isOffline == true) {
return true
} else {
return false
}
}
return false
}
// If there's no offline hit being sent
if(offlineOperations.count == 0) {
let storage = Storage.sharedInstance
// Check if offline hits exists in database
if(storage.count() > 0) {
#if !AT_EXTENSION
// Creates background task for offline hits
if(UIDevice.current.isMultitaskingSupported && tracker.configuration.parameters["enableBackgroundTask"]?.lowercased() == "true") {
_ = BackgroundTask.sharedInstance.begin()
}
#endif
if(async) {
for offlineHit in storage.get() {
let sender = Sender(tracker: tracker, hit: offlineHit, forceSendOfflineHits: forceSendOfflineHits, mhOlt: nil)
TrackerQueue.sharedInstance.queue.addOperation(sender)
}
} else {
OfflineHit.processing = true
for offlineHit in storage.get() {
OfflineHit.sentWithSuccess = false
let sender = Sender(tracker: tracker, hit: offlineHit, forceSendOfflineHits: forceSendOfflineHits, mhOlt: nil)
sender.send(false)
if(!OfflineHit.sentWithSuccess) {
break
}
}
OfflineHit.processing = false
}
}
}
}
}
}
}
| 47.13355 | 158 | 0.464133 |
acbaa11ab73430016f6bf0e3aa41576434516609 | 3,277 | //
// ViewController.swift
// Poke3D
//
// Created by Milovan Tomašević on 28/11/2020.
// Copyright © 2020 Milovan Tomašević. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
sceneView.showsStatistics = true
sceneView.autoenablesDefaultLighting = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARImageTrackingConfiguration()
if let imageToTrack = ARReferenceImage.referenceImages(inGroupNamed: "Pokemon Cards", bundle: Bundle.main) {
configuration.trackingImages = imageToTrack
configuration.maximumNumberOfTrackedImages = 2
print("Images Successfully Added")
}
// 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()
}
// MARK: - ARSCNViewDelegate
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
let node = SCNNode()
if let imageAnchor = anchor as? ARImageAnchor {
let plane = SCNPlane(width: imageAnchor.referenceImage.physicalSize.width, height: imageAnchor.referenceImage.physicalSize.height)
plane.firstMaterial?.diffuse.contents = UIColor(white: 1.0, alpha: 0.5)
let planeNode = SCNNode(geometry: plane)
planeNode.eulerAngles.x = -.pi / 2
node.addChildNode(planeNode)
// if imageAnchor.referenceImage.name == "eevee-card" {
// if let pokeScene = SCNScene(named: "art.scnassets/eevee.scn") {
//
// if let pokeNode = pokeScene.rootNode.childNodes.first {
//
// pokeNode.eulerAngles.x = .pi / 2
//
// planeNode.addChildNode(pokeNode)
// }
// }
// }
//
// if imageAnchor.referenceImage.name == "oddish-card" {
// if let pokeScene = SCNScene(named: "art.scnassets/oddish.scn") {
//
// if let pokeNode = pokeScene.rootNode.childNodes.first {
//
// pokeNode.eulerAngles.x = .pi / 2
//
// planeNode.addChildNode(pokeNode)
// }
// }
// }
}
return node
}
}
| 28.25 | 142 | 0.510528 |
72266cdcfb783d16acb5c4a2664088d3e79936bb | 4,476 | /*
* Copyright (c) 2011-2019, Zingaya, Inc. All rights reserved.
*/
import UIKit
extension UIViewController { // used to call segues with same id as a view controller type
func performSegue(withIdentifier typeIdentifier: UIViewController.Type, sender: Any?) {
performSegue(withIdentifier: String(describing: typeIdentifier), sender: sender)
}
func performSegue(withIdentifier typeIdentifier: UIViewController.Type, sender: Any?, _ completion: @escaping ()->Void) {
self.performSegue(withIdentifier: typeIdentifier, sender: sender)
DispatchQueue.main.async {
completion()
}
}
func canPerformSegue(withIdentifier id: String) -> Bool {
guard let segues = self.value(forKey: "storyboardSegueTemplates") as? [NSObject] else { return false }
return segues.first { $0.value(forKey: "identifier") as? String == id } != nil
}
func canPerformSegue(withIdentifier typeIdentifier: UIViewController.Type) -> Bool {
return canPerformSegue(withIdentifier: String(describing: typeIdentifier))
}
func performSegueIfPossible(withIdentifier id: String?, sender: Any?) {
guard let id = id, canPerformSegue(withIdentifier: id) else { return }
performSegue(withIdentifier: id, sender: sender)
}
func performSegueIfPossible(withIdentifier typeIdentifier: UIViewController.Type, sender: Any?) {
performSegueIfPossible(withIdentifier: String(describing: typeIdentifier), sender: sender)
}
}
extension UIStoryboard {
func instantiateViewController(withIdentifier typeIdentifier: UIViewController.Type) -> UIViewController {
return instantiateViewController(withIdentifier: String(describing: typeIdentifier))
}
}
extension UIViewController { // use this method to hide keyboard on tap on specific VC
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
extension UIViewController { // use this method to create UIImage from any color
func getImageWithColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1000, height: 1000)
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1000, height: 1000), true, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
extension UIViewController {
var topPresentedController: UIViewController {
if let presentedViewController = self.presentedViewController {
return presentedViewController.topPresentedController
} else {
return self
}
}
var toppestViewController: UIViewController {
if let navigationvc = self as? UINavigationController {
if let navigationsTopViewController = navigationvc.topViewController {
return navigationsTopViewController.topPresentedController
} else {
return navigationvc // no children
}
} else if let tabbarvc = self as? UITabBarController {
if let selectedViewController = tabbarvc.selectedViewController {
return selectedViewController.topPresentedController
} else {
return self // no children
}
} else if let firstChild = self.children.first {
// other container's view controller
return firstChild.topPresentedController
} else {
return self.topPresentedController
}
}
}
extension UIImage { // used to create logo image with insets
func imageWithInsets(insets: UIEdgeInsets) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: self.size.width + insets.left + insets.right,
height: self.size.height + insets.top + insets.bottom), false, self.scale)
let _ = UIGraphicsGetCurrentContext()
let origin = CGPoint(x: insets.left, y: insets.top)
self.draw(at: origin)
let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithInsets
}
}
| 39.964286 | 131 | 0.679848 |
11e52812c7b3d22342d4595b9adc76355736c709 | 1,531 | //
// MonthlyStatementsReportModuleContract.swift
// AptoSDK
//
// Created by Takeichi Kanzaki on 25/09/2019.
//
import AptoSDK
import Bond
protocol MonthlyStatementsReportModuleProtocol: UIModuleProtocol {
}
protocol FileDownloader {
func download(callback: @escaping Result<URL, NSError>.Callback)
}
protocol MonthlyStatementsReportInteractorProtocol {
func reportDate() -> (month: Int, year: Int)
func downloadReport(callback: @escaping Result<URL, NSError>.Callback)
}
class MonthlyStatementsReportViewModel {
let url: Observable<URL?> = Observable(nil)
let month: Observable<String> = Observable("")
let year: Observable<String> = Observable("")
let error: Observable<NSError?> = Observable(nil)
}
protocol MonthlyStatementsReportPresenterProtocol: class {
var router: MonthlyStatementsReportModuleProtocol? { get set }
var interactor: MonthlyStatementsReportInteractorProtocol? { get set }
var viewModel: MonthlyStatementsReportViewModel { get }
var analyticsManager: AnalyticsServiceProtocol? { get set }
func viewLoaded()
func closeTapped()
}
class DownloadUrlExpiredError: NSError {
private let errorDomain = "com.aptopayments.statements.download.timeout"
private let errorCode = 4444
init() {
let userInfo = [NSLocalizedDescriptionKey: "monthly_statements.report.error_url_expired.message".podLocalized()]
super.init(domain: errorDomain, code: errorCode, userInfo: userInfo)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| 28.886792 | 116 | 0.767472 |
f779e49e528ab18caa5bcfd55a265423dcb007a7 | 1,314 | //
// AppDelegate.swift
// QuerySuggestions
//
// Created by Vladislav Fitc on 04/11/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.
}
}
| 35.513514 | 177 | 0.773973 |
0e964a9c5ca8b8dd97c63b1fed98249c3fe2b197 | 2,230 | import AudioKit
import AudioKitUI
import AVFoundation
import SwiftUI
struct FlatFrequencyResponseReverbData {
var reverbDuration: AUValue = 0.5
var rampDuration: AUValue = 0.02
var balance: AUValue = 0.5
}
class FlatFrequencyResponseReverbConductor: ObservableObject, ProcessesPlayerInput {
let engine = AudioEngine()
let player = AudioPlayer()
let reverb: FlatFrequencyResponseReverb
let dryWetMixer: DryWetMixer
let buffer: AVAudioPCMBuffer
init() {
buffer = Cookbook.sourceBuffer
player.buffer = buffer
player.isLooping = true
reverb = FlatFrequencyResponseReverb(player)
dryWetMixer = DryWetMixer(player, reverb)
engine.output = dryWetMixer
}
@Published var data = FlatFrequencyResponseReverbData() {
didSet {
reverb.$reverbDuration.ramp(to: data.reverbDuration, duration: data.rampDuration)
dryWetMixer.balance = data.balance
}
}
func start() {
do { try engine.start() } catch let err { Log(err) }
}
func stop() {
engine.stop()
}
}
struct FlatFrequencyResponseReverbView: View {
@ObservedObject var conductor = FlatFrequencyResponseReverbConductor()
var body: some View {
ScrollView {
PlayerControls(conductor: conductor)
ParameterSlider(text: "Reverb Duration",
parameter: self.$conductor.data.reverbDuration,
range: 0...10,
units: "Seconds")
ParameterSlider(text: "Mix",
parameter: self.$conductor.data.balance,
range: 0...1,
units: "%")
DryWetMixView(dry: conductor.player, wet: conductor.reverb, mix: conductor.dryWetMixer)
}
.padding()
.navigationBarTitle(Text("Flat Frequency Response Reverb"))
.onAppear {
self.conductor.start()
}
.onDisappear {
self.conductor.stop()
}
}
}
struct FlatFrequencyResponseReverb_Previews: PreviewProvider {
static var previews: some View {
FlatFrequencyResponseReverbView()
}
}
| 28.961039 | 99 | 0.609417 |
5b4dce1bd9b4cd33f1240ea5de53f8af9d7d5549 | 2,363 | //
// TabButtons.swift
// Travel
//
// Created by Saswata Mukherjee on 30/06/20.
// Copyright © 2020 Saswata Mukherjee. All rights reserved.
//
import SwiftUI
struct TabButtons: View {
var body: some View {
HStack {
VStack {
Button(action: {}) {
Image(systemName: "airplane")
.foregroundColor(.white)
.padding(.all, 18)
.background(Color.blue.opacity(0.8))
.cornerRadius(12)
.shadow(radius: 2)
}
Text("Flights")
.font(.footnote)
.bold()
}
Spacer()
VStack {
Button(action: {}) {
Image(systemName: "bed.double.fill")
.foregroundColor(.white)
.padding(.all, 18)
.background(Color.orange.opacity(0.8))
.cornerRadius(12)
.shadow(radius: 2)
}
Text("Hotels")
.font(.footnote)
.bold()
}
Spacer()
VStack {
Button(action: {}) {
Image(systemName: "location.fill")
.foregroundColor(.white)
.padding(.all, 18)
.background(Color.purple.opacity(0.8))
.cornerRadius(12)
.shadow(radius: 2)
}
Text("Places")
.font(.footnote)
.bold()
}
Spacer()
VStack {
Button(action: {}) {
Image(systemName: "rectangle.grid.2x2.fill")
.foregroundColor(.white)
.padding(.all, 18)
.background(Color.red.opacity(0.8))
.cornerRadius(12)
.shadow(radius: 2)
}
Text("More")
.font(.footnote)
.bold()
}
}.padding()
}
}
struct TabButtons_Previews: PreviewProvider {
static var previews: some View {
TabButtons()
}
}
| 30.294872 | 64 | 0.377909 |
0ecea7a6dc9f64ca0fab402fc534a5852e97e99d | 1,761 | //
// ArticleTableViewDataSourceTests.swift
// ArticlesDemoAppTests
//
// Created by Waqas Sultan on 9/13/19.
// Copyright © 2019 Waqas Sultan. All rights reserved.
//
import XCTest
@testable import ArticlesDemoApp
class ArticlesTableViewDataSourceTests: XCTestCase {
var sut:ArticlesTableViewDataSource?
var articleViewController:ArticlesViewController?
var stubTableView:StubTableView?
var stubWorker:StubArticlesRemoteWorker?
override func setUp() {
super.setUp()
stubWorker = StubArticlesRemoteWorker()
stubWorker?.dataToReturnOnSuccess = StubArticles.dummyArticle()
articleViewController = (UIStoryboard.viewController(screenName: "ArticlesViewController", storyboardName: "Main") as! ArticlesViewController)
stubTableView = StubTableView(frame: CGRect(x: (articleViewController?.view.frame.origin.x)!, y: (articleViewController?.view.frame.origin.y)!, width: (articleViewController?.view.frame.size.width)!, height: (articleViewController?.view.frame.size.height)!), style: .plain)
articleViewController?.tableView = stubTableView
articleViewController?.viewDidLoad()
sut = articleViewController?.tableViewDataSource
articleViewController?.configurator.interactor.worker = stubWorker
articleViewController?.fetchArticles()
}
func testCellForIndexPath() {
_ = sut?.tableView(stubTableView!, cellForRowAt:IndexPath(row: 0, section: 0))
XCTAssertTrue(stubTableView!.isdequeueCalled)
}
func testCellForNumberOfItems() {
let row = sut?.tableView(stubTableView!, numberOfRowsInSection: 0)
XCTAssertTrue(row ?? 0 > 0)
}
}
| 32.611111 | 281 | 0.704713 |
39a2015ecf7fed9973bbd7663a35c56acc59b711 | 3,434 | //
// PhotoToolbar.swift
//
// Created by Richard on 2017/4/21.
// Copyright © 2017年 Richard. All rights reserved.
//
import UIKit
public protocol PhotoToolbarDelegate: NSObjectProtocol {
func touchPreviewAction()
func touchFinishAction()
}
open class PhotoToolbar: UIView {
fileprivate(set) var topLineView: UIView!
fileprivate(set) var previewButton: UIButton!
fileprivate(set) var finishButton: UIButton!
fileprivate(set) var contentLabel: UILabel!
fileprivate let barHeight: CGFloat = PickerConfig.pickerToolbarHeight
weak var delegate: PhotoToolbarDelegate!
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setCurrentNumber(number: Int, maxNumber: Int) {
let title = "已选择:\(number)/\(maxNumber)"
contentLabel.text = title
updateContentLabelFrame()
}
override open func layoutSubviews() {
super.layoutSubviews()
updateFrame()
}
}
private extension PhotoToolbar {
func setup() {
self.backgroundColor = PickerConfig.pickerToolbarColor
topLineView = UIView()
topLineView.backgroundColor = UIColor.lightGray
self.addSubview(topLineView)
previewButton = UIButton()
previewButton.backgroundColor = PickerConfig.pickerThemeColor
previewButton.setTitleColor(UIColor.white, for: .normal)
previewButton.setTitle("预览", for: .normal)
previewButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
previewButton.addTarget(self, action: #selector(onPreviewAction), for: .touchUpInside)
previewButton.layer.cornerRadius = 4
self.addSubview(previewButton)
finishButton = UIButton()
finishButton.backgroundColor = PickerConfig.pickerThemeColor
finishButton.setTitleColor(UIColor.white, for: .normal)
finishButton.setTitle("完成", for: .normal)
finishButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
finishButton.addTarget(self, action: #selector(onFinishAction), for: .touchUpInside)
finishButton.layer.cornerRadius = 4
self.addSubview(finishButton)
contentLabel = UILabel()
contentLabel.textAlignment = .center
contentLabel.font = UIFont.boldSystemFont(ofSize: 14)
contentLabel.textColor = PickerConfig.pickerToolbarLabelColor
self.addSubview(contentLabel)
}
func updateFrame() {
topLineView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 0.5)
previewButton.frame.origin = CGPoint(x: 20, y: (bounds.height - 30)/2)
previewButton.frame.size = CGSize(width: 80, height: 30)
finishButton.frame.origin = CGPoint(x: bounds.width - 20 - 80, y: (bounds.height - 30)/2)
finishButton.frame.size = CGSize(width: 80, height: 30)
updateContentLabelFrame()
}
func updateContentLabelFrame() {
contentLabel.center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
contentLabel.frame.size = CGSize(width: 150, height: 30)
}
@objc func onPreviewAction() {
self.delegate?.touchPreviewAction()
}
@objc func onFinishAction() {
self.delegate?.touchFinishAction()
}
}
| 32.093458 | 97 | 0.656669 |
bb15fa2cf82c4ce7bcacd07446b2149220c51372 | 2,002 | import UIKit
import RIBs; import Foundation
protocol MyDependency: Dependency {
var candy: Candy { get }
var cheese: Cheese { get }
}
protocol RandomProtocol {
var blah: Int { get }
}
let randomValue = 1234
class MyComponent: NeedleFoundation.Component<
MyDependency
> {
let stream: Stream = Stream()
var donut: Donut {
return Donut()
}
var sweetsBasket: Basket {
return shared {
Basket(dependency.candy, self.donut)
}
}
var myChildComponent: MyChildComponent {
return MyChildComponent(parent: self)
}
func childComponent(with dynamicDependency: String) -> MyChildComponent {
return MyChildComponent(parent: self, dynamicDependency: dynamicDependency)
}
}
protocol SomeNonCoreDependency: Dependency {
var aNonCoreDep: Dep { get }
var maybeNonCoreDep: MaybeDep? { get }
}
class SomeNonCoreComponent: NeedleFoundation.NonCoreComponent< SomeNonCoreDependency > {
var newNonCoreObject: NonCoreObject? {
return NonCoreObject()
}
var sharedNonCoreObject: SharedObject {
return shared {
return SharedObject()
}
}
}
class My2Component: Component<My2Dependency> {
var book: Book {
return shared {
Book()
}
}
var maybeWallet: Wallet? {
return Wallet()
}
private var banana: Banana {
return Banana()
}
fileprivate var apple: Apple {
return Apple()
}
}
protocol ADependency: Dependency {
var maybe: Maybe? { get }
}
protocol BExtension: PluginExtension {
var myPluginPoint: MyPluginPoint { get }
}
class SomePluginizedComp: PluginizedComponent<
ADependency,
BExtension, SomeNonCoreComponent
>, Stuff {
var tv: Tv {
return LGOLEDTv()
}
}
protocol My2Dependency: NeedleFoundation.Dependency {
var backPack: Pack { get }
var maybeMoney: Dollar? { get }
}
class RandomClass {
}
extension Dependency {
}
| 19.066667 | 92 | 0.648352 |
f99770ca905ca515abfb4312bfeb05006891179e | 945 | //
// SongSearchTableViewCell.swift
// Tempo
//
// Created by Austin Chan on 3/22/15.
// Copyright (c) 2015 CUAppDev. All rights reserved.
//
import UIKit
class SongSearchTableViewCell: UITableViewCell {
@IBOutlet var postView: SearchPostView!
@IBOutlet weak var separator: UIView!
@IBOutlet weak var separatorHeight: NSLayoutConstraint!
@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var shareButtonWidthConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
contentView.backgroundColor = .unreadCellColor
separator.backgroundColor = .readCellColor
separatorHeight.constant = 1
shareButton.layer.borderWidth = 1.5
shareButton.layer.borderColor = UIColor.tempoRed.cgColor
shareButton.titleLabel?.textColor = UIColor.white.withAlphaComponent(0.87)
shareButtonWidthConstraint.constant = 0
}
override func prepareForReuse() {
postView.setNeedsDisplay()
}
}
| 27 | 76 | 0.767196 |
7a34a157c3d9a8ca368a1fc41210159c389e8fb7 | 386 | import Foundation
public enum License : String {
case allRightsReserved = "all-rights-reserved"
case cc40by = "cc-40-by"
case cc40bysa = "cc-40-by-sa"
case cc40bynd = "cc-40-by-nd"
case cc40bync = "cc-40-by-nc"
case cc40byncnd = "cc-40-by-nc-nd"
case cc40byncsa = "cc-40-by-nc-sa"
case cc40zero = "cc-40-zero"
case publicDomain = "public-domain"
}
| 25.733333 | 50 | 0.645078 |
875857bf9483a9164d831bdbebd85a2ca3d250b8 | 505 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
let i {
={
}
class a :{class A{
class b<T where g:a{
class n{
=
{
}
let a = {
}
class A{
{ "
struct A {
let i: N
| 21.041667 | 78 | 0.69901 |
db8b7cb174c3273c3ab80acbc02d6f4131bd715c | 1,128 | //
// AlbumSelectCountPanView.swift
// FileMail
//
// Created by leo on 2017/5/17.
// Copyright © 2017年 leo. All rights reserved.
//
import UIKit
import QuartzCore
class AlbumSelectCountPanView: UIView {
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var doneButton: UIButton!
var doneCallBack:(() -> Void)?
class func createFromXib() -> AlbumSelectCountPanView? {
return Bundle.main.loadNibNamed("AlbumSelectCountPanView", owner: nil, options: nil)?.first as? AlbumSelectCountPanView
}
override func awakeFromNib() {
super.awakeFromNib()
self.doneButton.layer.cornerRadius = 4.0
self.doneButton.layer.masksToBounds = true
self.doneButton.setBackgroundImage(UIImage.imageWith(color: UIColor.mainScheme, size: self.doneButton.frame.size), for: .normal)
self.doneButton.setBackgroundImage(UIImage.imageWith(color: UIColor.placeholderText, size: self.doneButton.frame.size), for: .disabled)
}
@IBAction func doneAction(_ sender: UIButton) {
if let done = doneCallBack {
done()
}
}
}
| 29.684211 | 143 | 0.683511 |
e6eca15e211e6a499443eab10c569312041ef93f | 929 | //
// FrameExerciseTests.swift
// FrameExerciseTests
//
// Created by HongWeonpyo on 25/03/2019.
// Copyright © 2019 ShoppingBook. All rights reserved.
//
import XCTest
@testable import FrameExercise
class FrameExerciseTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.542857 | 111 | 0.665231 |
ff839ebe53d4397e8db5caf914e75e3fdf84190e | 9,918 | //******************************************************************************
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//==============================================================================
// ComputeService
public protocol ComputeService : ObjectTracking, Logging {
init(log: Log?) throws
var devices: [ComputeDevice] { get }
var id: Int { get set }
var name: String { get }
}
//==============================================================================
// ComputeDevice
// This specifies the compute device interface
public protocol ComputeDevice : ObjectTracking, Logging {
var attributes: [String:String] { get }
var availableMemory: Int { get }
var maxThreadsPerBlock: Int { get }
var name: String { get }
var id: Int { get }
var service: ComputeService! { get }
var usesUnifiedAddressing: Bool { get }
//----------------------------------------------------------------------------
// device resource functions
func createArray(count: Int) throws -> DeviceArray
func createStream(label: String) throws -> DeviceStream
func select() throws
func supports(dataType: DataType) -> Bool
}
public enum ComputeError : Error {
case serviceIsUnavailable
case functionFailure(location: String, message: String)
}
//==============================================================================
// AnyValue
// This is used to provide the necessary pointers to scale factors
// needed by cuda. Kind of ugly...
public final class AnyValue {
public init(dataType suggestedDataType: DataType, value: Double) {
self.dataType = suggestedDataType == .real64F ? .real64F : .real32F
switch dataType {
case .real32F:
floatValue = Float(value)
valuePointer = UnsafeRawPointer(withUnsafePointer(to: &floatValue) { $0 })
case .real64F:
doubleValue = value
valuePointer = UnsafeRawPointer(withUnsafePointer(to: &doubleValue) { $0 })
default: fatalError()
}
}
public var pointer : UnsafeRawPointer { return valuePointer }
public var real32FPointer : UnsafePointer<Float> {
assert(dataType == .real32F)
return withUnsafePointer(to: &floatValue) { $0 }
}
public var real64FPointer : UnsafePointer<Double> {
assert(dataType == .real64F)
return withUnsafePointer(to: &doubleValue) { $0 }
}
private let valuePointer: UnsafeRawPointer
public let dataType: DataType
private var floatValue: Float = 0
private var doubleValue: Double = 0
}
//==============================================================================
// Computable
public protocol Computable : ObjectTracking, Logging {
var stream: DeviceStream { get }
func setupForward(mode: EvaluationMode, inData: DataView, labels: DataView?,
outData: inout DataView, backData: inout DataView?) throws
func forward(mode: EvaluationMode, inData: DataView, labels: DataView?,
outData: inout DataView, backData: inout DataView?) throws
func setupBackward(outData: DataView, outGrad: DataView?, inData: DataView) throws
func backward(outData: DataView, outGrad: DataView?,
inData: DataView, inGrad: inout DataView?,
solver: ModelSolver, labels: DataView?) throws
}
extension Computable {
public func setupBackward(outData: DataView, outGrad: DataView?, inData: DataView) throws {}
}
//==============================================================================
// DeviceArray
// This represents a device data array
public protocol DeviceArray : ObjectTracking, Logging {
var device: ComputeDevice { get }
var data: UnsafeMutableRawPointer { get }
var count: Int { get }
var version: Int { get set }
func zero(using stream: DeviceStream?) throws
func copyAsync(from other: DeviceArray, using stream: DeviceStream) throws
func copyAsync(from buffer: BufferUInt8, using stream: DeviceStream) throws
func copy(to buffer: MutableBufferUInt8, using stream: DeviceStream) throws
func copyAsync(to buffer: MutableBufferUInt8, using stream: DeviceStream) throws
}
//==============================================================================
// StreamEvent
public protocol StreamEvent : ObjectTracking {
init(options: StreamEventOptions) throws
var occurred: Bool { get }
}
public struct StreamEventOptions: OptionSet {
public init(rawValue: Int) { self.rawValue = rawValue }
public let rawValue: Int
public static let hostSync = StreamEventOptions(rawValue: 1 << 0)
public static let timing = StreamEventOptions(rawValue: 1 << 1)
public static let interprocess = StreamEventOptions(rawValue: 1 << 2)
}
//==============================================================================
// RandomGeneratorState
public protocol RandomGeneratorState : ObjectTracking {
var count: Int { get }
}
//==============================================================================
// ComputableFilterProperties
public protocol ComputableFilterProperties : Filter { }
//==============================================================================
// DeviceStream
// A device stream is an asynchronous queue of commands executed on
// the associated device
//
public protocol DeviceStream : ObjectTracking, Logging {
// properties
var device: ComputeDevice { get }
var label: String { get }
var id: Int { get }
//-------------------------------------
// synchronization
func blockCallerUntilComplete() throws
func createEvent(options: StreamEventOptions) throws -> StreamEvent
func delay(seconds: Double) throws
func record(event: StreamEvent) throws -> StreamEvent
func sync(with other: DeviceStream, event: StreamEvent) throws
func wait(for event: StreamEvent) throws
//-------------------------------------
// device optimized computabes
func createComputable(type: String, props: ComputableFilterProperties) throws -> Computable
//-------------------------------------
// reduction state
func createReductionContext(op: ReductionOp, dataType: DataType,
inShape: Shape, outShape: Shape) throws -> ReductionContext
//-------------------------------------
// validate
// TODO: right now this tests for all values being finite or not
// eventually add range parameter
func validate(data: DataView, hasRangeError: inout DataView) throws
//-------------------------------------
// functions
func asum(x: DataView, result: inout DataView) throws
func compareEqual(data aData: DataView, with bData: DataView, result: inout DataView) throws
func copy(from inData: DataView, to outData: inout DataView, normalizeInts: Bool) throws
func reduce(context: ReductionContext, inData: DataView,
outData: inout DataView) throws
func reduce(context: ReductionContext, inData: DataView,
outData: inout DataView, indices: inout DataView) throws
func dot(x: DataView, y: DataView, result: inout DataView) throws
func expand(labels: DataView, to expanded: inout DataView) throws
// update
func update(weights: inout DataView, gradient: DataView,
learningRate: Double) throws
// with momentum
func update(weights: inout DataView, gradient: DataView, learningRate: Double,
history: inout DataView, momentum: Double) throws
// alpha * x + y
func axpy(alpha: Double, x: DataView, y: inout DataView) throws
// random number generator state
func createRandomGeneratorState(for dataView: DataView, seed: UInt?) throws -> RandomGeneratorState
// fill
func fill(data: inout DataView, with constant: Double) throws
func fillWithIndex(data: inout DataView, startingAt: Int) throws
func fillGaussian(data: inout DataView, mean: Double, std: Double, generatorState: RandomGeneratorState) throws
func fillMSRA(data: inout DataView, varianceNorm: FillVarianceNorm, generatorState: RandomGeneratorState) throws
func fillUniform(data: inout DataView, range: ClosedRange<Double>, generatorState: RandomGeneratorState) throws
func fillXavier(data: inout DataView, varianceNorm: FillVarianceNorm, generatorState: RandomGeneratorState) throws
// A x B -> C
func gemm(alpha: Double, transA: TransposeOp, matrixA: DataView,
transB: TransposeOp, matrixB: DataView,
beta: Double, matrixC: inout DataView) throws
}
public enum FillVarianceNorm : String, EnumerableType { case fanIn, fanOut, average }
public enum TransposeOp { case transpose, noTranspose, conjugateTranspose }
public enum ReductionOp { case add, mul, min, max, amax, avg, norm1, norm2 }
public protocol ReductionContext {}
extension DeviceStream {
func fillGaussian(data: inout DataView, mean: Double, std: Double, seed: UInt? = nil) throws {
try fillGaussian(data: &data, mean: mean, std: std,
generatorState: createRandomGeneratorState(for: data, seed: seed))
}
func fillMSRA(data: inout DataView, varianceNorm: FillVarianceNorm, seed: UInt? = nil) throws {
try fillMSRA(data: &data, varianceNorm: varianceNorm,
generatorState: createRandomGeneratorState(for: data, seed: seed))
}
func fillUniform(data: inout DataView, range: ClosedRange<Double>, seed: UInt? = nil) throws {
try fillUniform(data: &data, range: range,
generatorState: createRandomGeneratorState(for: data, seed: seed))
}
func fillXavier(data: inout DataView, varianceNorm: FillVarianceNorm, seed: UInt? = nil) throws {
try fillXavier(data: &data, varianceNorm: varianceNorm,
generatorState: createRandomGeneratorState(for: data, seed: seed))
}
}
| 38.146154 | 115 | 0.66223 |
cc5157af3ad2b8226e99238ccc239b347a5c3a37 | 1,188 | //
// Number+Format.swift
// SiFUtilities
//
// Created by NGUYEN CHI CONG on 8/17/21.
//
import Foundation
extension Numeric {
public func formatted(separator: String? = nil,
numberStyle: NumberFormatter.Style = .decimal,
localeIdentifier: String? = "vn_VN") -> String {
var locale = Locale.current
if let localeID = localeIdentifier {
locale = Locale(identifier: localeID)
}
let separator = separator ?? locale.decimalSeparator ?? ","
let formatter = NumberFormatter(separator: separator, numberStyle: numberStyle)
formatter.locale = locale
return formatter.string(for: self) ?? "\(self)"
}
}
extension NumberFormatter {
public convenience init(separator: String, numberStyle: NumberFormatter.Style) {
self.init()
self.usesGroupingSeparator = true
self.groupingSize = 3
self.currencyGroupingSeparator = separator
self.groupingSeparator = separator
self.numberStyle = numberStyle
}
}
extension Locale {
public static var vietnam: Locale {
return Locale(identifier: "vn_VN")
}
}
| 27.627907 | 87 | 0.632155 |
cc26835cf7f389f6d8e2df6db10f5408302c8cad | 2,171 | //
// AppDelegate.swift
// HelloUIPickerView
//
// Created by jason on 2018/12/3.
// Copyright © 2018 jason. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.191489 | 285 | 0.755412 |
1e131b73887e7fe73334c5ec0b4c93696651872c | 4,004 | //
// file+extension.swift
// WoLawyer
//
// Created by TLL on 2019/12/30.
// Copyright © 2019 wo_lawyer. All rights reserved.
//
import UIKit
// 显示缓存大小
func cacheSize() -> Double {
let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
return folderSize(filePath: cachePath)
}
//计算单个文件的大小
func fileSize(filePath: String) -> UInt64 {
let manager = FileManager.default
if manager.fileExists(atPath: filePath) {
do {
let attr = try manager.attributesOfItem(atPath: filePath)
let size = attr[FileAttributeKey.size] as! UInt64
return size
} catch {
LYPrint("error :\(error)")
return 0
}
}
return 0
}
//遍历文件夹,返回多少k
func folderSize(filePath: String) -> Double {
let folderPath = filePath
let manager = FileManager.default
if manager.fileExists(atPath: filePath) {
// 取出文件夹下所有文件数组
let fileArr = FileManager.default.subpaths(atPath: folderPath)
/* 文件总的大小 */
var totleSize = 0.0
for file in fileArr! {
// 把文件名拼接到路径中
let path = folderPath.appending("/\(file)")
// 取出文件属性
let floder = try! FileManager.default.attributesOfItem(atPath: path)
/* 用元组来取得 文件的的大小 */
for (key,value) in floder {
if key == FileAttributeKey.size {
/* 每个文件的大小 */
let size = (value as! Double)
totleSize += size //总的大小
}
}
}
return totleSize
}
return 0
}
// 清除缓存
func clearCache() {
// 取出cache文件夹目录 缓存文件都在这个目录下
let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
// 取出文件夹下所有文件数组
let fileArr = FileManager.default.subpaths(atPath: cachePath!)
// 遍历删除
for file in fileArr! {
let path = cachePath?.appending("/\(file)")
if FileManager.default.fileExists(atPath: path!) {
do {
try FileManager.default.removeItem(atPath: path!)
} catch {
}
}
}
}
// 清除doc文件
func clearDocPathCache() {
// 取出cache文件夹目录 缓存文件都在这个目录下
let cachePath = Constant.docPath
// 取出文件夹下所有文件数组
let fileArr = FileManager.default.subpaths(atPath: cachePath)
// 遍历删除
for file in fileArr! {
let path = cachePath.appending("/\(file)")
if FileManager.default.fileExists(atPath: path) {
do {
try FileManager.default.removeItem(atPath: path)
} catch {
}
}
}
}
//删除沙盒里的文件
func deleteFile(filePath: String) {
let manager = FileManager.default
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
let uniquePath = path.appendingPathComponent(filePath)
if manager.fileExists(atPath: uniquePath) {
do {
try FileManager.default.removeItem(atPath: uniquePath)
} catch {
LYPrint("error:\(error)")
}
}
/// 检查目录是否存在,如果不存在则创建
func directoryExisted(path: String) -> Bool {
var directoryExists = ObjCBool.init(false)
let existed = FileManager.default.fileExists(atPath: path, isDirectory: &directoryExists)
// 目录不存在
if !(existed == true && directoryExists.boolValue == true) {
do{
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
}
catch{
return false
}
}
return true
}
}
| 27.805556 | 169 | 0.583916 |
6926f33e833ef5636aaed65f111f3cddb9f3d850 | 585 | // 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
class d<T where d: I.B
class C<T>(c> {
class C(f)!("\()
static let c: d = c<c(""foobar""
func d<T {
return x in c == { _, Any) {
struct A {
}
protocol P {
}
}
var d : () -> {
}
}
for c {
| 24.375 | 79 | 0.673504 |
fff755a359c12ccc694ba07f1d6f6a6d34aff1ff | 6,828 | //
// AppDelegate.swift
// AmILying
//
// Created by Fredrik Carlsson on 2018-04-24.
// Copyright © 2018 Fredrik Carlsson. All rights reserved.
//
import UIKit
import CoreData
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
static var GameID: String?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
return true
}
// FOR RECIEVING DYNAMIC LINKS
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
guard let dynamicLinks = DynamicLinks.dynamicLinks() else {
return false
}
let handled = dynamicLinks.handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
self.handleIncomingDynamicLink(dynamicLink: dynamiclink!)
}
return handled
}
func handleIncomingDynamicLink(dynamicLink: DynamicLink) {
if let url = dynamicLink.url?.absoluteString {
AppDelegate.GameID = getQueryStringParameter(url: url, param: "param")
print("Push-VC opened!\(AppDelegate.GameID ?? "0")")
}
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "JoinDirectly")
window?.rootViewController = vc
}
func getQueryStringParameter(url: String, param: String) -> String? {
guard let url = URLComponents(string: url) else { return nil }
return url.queryItems?.first(where: { $0.name == param })?.value
}
@available(iOS 9.0, *)
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
return application(app, open: url,
sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,
annotation: "")
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
// if let dynamicLink = DynamicLinks.dynamicLinks()?.dynamicLink(fromCustomSchemeURL: url) {
// print("IM handling a link through the openURL method")
// //self.handleIncomingDynamicLink(dynamicLink: dynamicLink)
// // Handle the deep link. For example, show the deep-linked content or
// // apply a promotional offer to the user's account.
// // ...
// return true
// }
return false
}
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "AmILying")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 45.52 | 285 | 0.66403 |
ff25efeaf7804b837dd74a0b1944ce7641e7787c | 436 |
//
// MyPageController.swift
// myNews
//
// Created by kennyS on 12/17/19.
// Copyright © 2019 kennyS. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Reusable
import SVProgressHUD
class MyPageController: BaseController, StoryboardBased, ViewModelBased {
var viewModel: MyPageViewModel!
private let bag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
}
}
| 17.44 | 73 | 0.708716 |
11f9579fad123ed426c6e0c181b12b1914f80f2d | 4,139 | //
// MusicController.swift
// AppStoreJSONApis
//
// Created by Diego Oruna on 3/15/19.
// Copyright © 2019 Diego Oruna. All rights reserved.
//
import UIKit
// 1. Implement Cell
// 2. Implement a footer for the loader view
class MusicController: BaseListController, UICollectionViewDelegateFlowLayout {
fileprivate let cellId = "cellId"
fileprivate let footerId = "footerId"
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = .white
collectionView.register(TrackCell.self, forCellWithReuseIdentifier: cellId)
collectionView.register(MusicLoadingFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: footerId)
fetchData()
}
var results = [Result]() // blank empty array
fileprivate let searchTerm = "taylor"
fileprivate func fetchData() {
let urlString = "https://itunes.apple.com/search?term=\(searchTerm)&offset=0&limit=20"
Service.shared.fetchGenericJSONData(urlString: urlString) { (searchResult: SearchResult?, err) in
if let err = err {
print("Failed to paginate data:", err)
return
}
self.results = searchResult?.results ?? []
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: footerId, for: indexPath)
return footer
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
let height: CGFloat = isDonePaginating ? 0 : 100
return .init(width: view.frame.width, height: height)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return results.count
}
var isPaginating = false
var isDonePaginating = false
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TrackCell
let track = results[indexPath.item]
cell.nameLabel.text = track.trackName
cell.imageView.sd_setImage(with: URL(string: track.artworkUrl100))
cell.subtitleLabel.text = "\(track.artistName ?? "") • \(track.collectionName ?? "")"
// initiate pagination
if indexPath.item == results.count - 1 && !isPaginating {
print("fetch more data")
isPaginating = true
let urlString = "https://itunes.apple.com/search?term=\(searchTerm)&offset=\(results.count)&limit=20"
Service.shared.fetchGenericJSONData(urlString: urlString) { (searchResult: SearchResult?, err) in
if let err = err {
print("Failed to paginate data:", err)
return
}
if searchResult?.results.count == 0 {
self.isDonePaginating = true
}
sleep(2)
self.results += searchResult?.results ?? []
DispatchQueue.main.async {
self.collectionView.reloadData()
}
self.isPaginating = false
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return .init(width: view.frame.width, height: 100)
}
}
| 37.288288 | 171 | 0.61899 |
dda3a43f661d2f2274f645a0b782d8f85abc3fbe | 2,903 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
// This file was auto-autogenerated by scripts and templates at http://github.com/AudioKit/AudioKitDevTools/
import AVFoundation
import CAudioKit
/// This filter reiterates the input with an echo density determined by loop time. The attenuation rate is
/// independent and is determined by the reverberation time (defined as the time in seconds for a signal to
/// decay to 1/1000, or 60dB down from its original amplitude). Output will begin to appear immediately.
///
public class AKFlatFrequencyResponseReverb: AKNode, AKComponent, AKToggleable {
public static let ComponentDescription = AudioComponentDescription(effect: "alps")
public typealias AKAudioUnitType = InternalAU
public private(set) var internalAU: AKAudioUnitType?
// MARK: - Parameters
public static let reverbDurationDef = AKNodeParameterDef(
identifier: "reverbDuration",
name: "Reverb Duration (Seconds)",
address: akGetParameterAddress("AKFlatFrequencyResponseReverbParameterReverbDuration"),
range: 0 ... 10,
unit: .seconds,
flags: .default)
/// Seconds for a signal to decay to 1/1000, or 60dB down from its original amplitude.
@Parameter public var reverbDuration: AUValue
// MARK: - Audio Unit
public class InternalAU: AKAudioUnitBase {
public override func getParameterDefs() -> [AKNodeParameterDef] {
[AKFlatFrequencyResponseReverb.reverbDurationDef]
}
public override func createDSP() -> AKDSPRef {
akCreateDSP("AKFlatFrequencyResponseReverbDSP")
}
public func setLoopDuration(_ duration: AUValue) {
akFlatFrequencyResponseSetLoopDuration(dsp, duration)
}
}
// MARK: - Initialization
/// Initialize this reverb node
///
/// - Parameters:
/// - input: Input node to process
/// - reverbDuration: Seconds for a signal to decay to 1/1000, or 60dB down from its original amplitude.
/// - loopDuration: The loop duration of the filter, in seconds. This can also be thought of as the delay time or “echo density” of the reverberation.
///
public init(
_ input: AKNode,
reverbDuration: AUValue = 0.5,
loopDuration: AUValue = 0.1
) {
super.init(avAudioNode: AVAudioNode())
instantiateAudioUnit { avAudioUnit in
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
guard let audioUnit = avAudioUnit.auAudioUnit as? AKAudioUnitType else {
fatalError("Couldn't create audio unit")
}
self.internalAU = audioUnit
audioUnit.setLoopDuration(loopDuration)
self.reverbDuration = reverbDuration
}
connections.append(input)
}
}
| 35.839506 | 158 | 0.679297 |
089d2e27e5b98e5f909fc9b0000e68f6f69280a5 | 558 | //
// AlertMessage.swift
// Food Diary App!
//
// Created by Ben Shih on 19/12/2017.
// Copyright © 2017 BenShih. All rights reserved.
//
import Foundation
import UIKit
struct AlertMessage
{
func displayAlert(title: String, message: String, VC: UIViewController)
{
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Confirm", style: .default, handler: nil))
VC.present(alertController, animated: true, completion: nil)
}
}
| 26.571429 | 103 | 0.704301 |
6211cbc1ae3228271744c87211aa801ccccbacfb | 5,265 | //
// NVActivityIndicatorAnimationBallTrianglePath.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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 NVActivityIndicatorAnimationBallTrianglePath: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize = size.width / 5
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let duration: CFTimeInterval = 2
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.keyTimes = [0, 0.33, 0.66, 1]
animation.timingFunctions = [timingFunction, timingFunction, timingFunction]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Top-center circle
let topCenterCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values: ["{0,0}", "{hx,fy}", "{-hx,fy}", "{0,0}"], deltaX: deltaX, deltaY: deltaY)
topCenterCircle.frame = CGRect(x: x + size.width / 2 - circleSize / 2, y: y, width: circleSize, height: circleSize)
topCenterCircle.add(animation, forKey: "animation")
layer.addSublayer(topCenterCircle)
// Bottom-left circle
let bottomLeftCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values: ["{0,0}", "{hx,-fy}", "{fx,0}", "{0,0}"], deltaX: deltaX, deltaY: deltaY)
bottomLeftCircle.frame = CGRect(x: x, y: y + size.height - circleSize, width: circleSize, height: circleSize)
bottomLeftCircle.add(animation, forKey: "animation")
layer.addSublayer(bottomLeftCircle)
// Bottom-right circle
let bottomRightCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values: ["{0,0}", "{-fx,0}", "{-hx,-fy}", "{0,0}"], deltaX: deltaX, deltaY: deltaY)
bottomRightCircle.frame = CGRect(x: x + size.width - circleSize, y: y + size.height - circleSize, width: circleSize, height: circleSize)
bottomRightCircle.add(animation, forKey: "animation")
layer.addSublayer(bottomRightCircle)
}
func changeAnimation(_ animation: CAKeyframeAnimation, values rawValues: [String], deltaX: CGFloat, deltaY: CGFloat) {
let values = NSMutableArray(capacity: 5)
for rawValue in rawValues {
let point = CGPointFromString(translateString(rawValue, deltaX: deltaX, deltaY: deltaY))
values.add(NSValue(caTransform3D: CATransform3DMakeTranslation(point.x, point.y, 0)))
}
animation.values = values as [AnyObject]
}
func translateString(_ valueString: String, deltaX: CGFloat, deltaY: CGFloat) -> String {
let valueMutableString = NSMutableString(string: valueString)
let fullDeltaX = 2 * deltaX
let fullDeltaY = 2 * deltaY
var range = NSMakeRange(0, valueMutableString.length)
valueMutableString.replaceOccurrences(of: "hx", with: "\(deltaX)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "fx", with: "\(fullDeltaX)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "hy", with: "\(deltaY)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "fy", with: "\(fullDeltaY)", options: NSString.CompareOptions.caseInsensitive, range: range)
return valueMutableString as String
}
}
| 51.116505 | 144 | 0.707692 |
3a2f0ad7d3a3e19659a6af91da936c7da0dc7378 | 2,152 | // RUN: %empty-directory(%t)
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-emit-ir(mock-sdk: -sdk %S/Inputs -I %t) -parse-as-library %s | %FileCheck %s -check-prefix=IR
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -parse-as-library %s -D REFERENCE | %FileCheck %s
// RUN: %target-swift-emit-ir(mock-sdk: -sdk %S/Inputs -I %t) -parse-as-library %s -D REFERENCE | %FileCheck %s -check-prefix=IR
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -parse-as-library -primary-file %s %S/Inputs/UIApplicationMain-helper.swift -module-name test | %FileCheck %s
// RUN: %target-swift-emit-ir(mock-sdk: -sdk %S/Inputs -I %t) -parse-as-library -primary-file %s %S/Inputs/UIApplicationMain-helper.swift -module-name test | %FileCheck %s -check-prefix=IR
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -parse-as-library %s %S/Inputs/UIApplicationMain-helper.swift -module-name test | %FileCheck %s
// RUN: %target-swift-emit-ir(mock-sdk: -sdk %S/Inputs -I %t) -parse-as-library %s %S/Inputs/UIApplicationMain-helper.swift -module-name test | %FileCheck %s -check-prefix=IR
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -parse-as-library %S/Inputs/UIApplicationMain-helper.swift %s -module-name test | %FileCheck %s
// RUN: %target-swift-emit-ir(mock-sdk: -sdk %S/Inputs -I %t) -parse-as-library %S/Inputs/UIApplicationMain-helper.swift %s -module-name test | %FileCheck %s -check-prefix=IR
// REQUIRES: OS=ios
// REQUIRES: objc_interop
import Foundation
import UIKit
@UIApplicationMain
class MyDelegate : UIApplicationDelegate {}
// CHECK-LABEL: sil @main
// CHECK: function_ref @UIApplicationMain
// IR-LABEL: define{{( protected)?}} i32 @main
// IR: call i32 @UIApplicationMain
// Ensure that we coexist with normal references to the functions we
// implicitly reference in the synthesized main.
#if REFERENCE
func foo(x: AnyObject.Type) -> String {
return NSStringFromClass(x)
}
func bar() {
UIApplicationMain(0, nil, nil, nil)
}
#endif
| 48.909091 | 188 | 0.705855 |
e864d5da0b6fce5b00ab57159423c7f586f69220 | 4,853 | //
// FGVideoEditor.swift
// SkateMoments
//
// Created by xia on 2018/3/26.
// Copyright © 2018年 xgf. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
import FGHUD
import CoreMedia
public class FGVideoEditor: NSObject {
open static let shared = FGVideoEditor.init()
private var videoFolder = ""
override init() {
super.init()
setup()
}
private func setup() {
let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
videoFolder = docPath + "/FGVideo"
let exist = FileManager.default.fileExists(atPath: videoFolder)
if !exist {
do {
try FileManager.default.createDirectory(atPath: videoFolder, withIntermediateDirectories: true, attributes: nil)
} catch {
videoFolder = docPath
}
}
}
}
//MARK: - Crop
public extension FGVideoEditor {
public func cropVideo(url: URL, cropRange:CMTimeRange, completion:((_ newUrl: URL, _ newDuration:CGFloat,_ result:Bool) -> ())?) {
let asset = AVURLAsset.init(url: url, options: nil)
let duration = CGFloat(CMTimeGetSeconds(asset.duration))
let newPath = videoFolder + "/FGVideo" + UUID.init().uuidString + ".mov"
let outputUrl = URL.init(fileURLWithPath: newPath)
//let presets = AVAssetExportSession.exportPresets(compatibleWith: asset)
guard let exportSession = AVAssetExportSession.init(asset: asset, presetName: AVAssetExportPresetPassthrough) else {
if completion != nil {
completion?(outputUrl,duration,false)
}
return
}
exportSession.outputURL = outputUrl
exportSession.outputFileType = .mov
exportSession.shouldOptimizeForNetworkUse = true
exportSession.timeRange = cropRange
exportSession.exportAsynchronously {
let status = exportSession.status
switch status {
case .failed:
if completion != nil {
completion?(outputUrl,duration,false)
}
break
case .cancelled:
if completion != nil {
completion?(outputUrl,duration,false)
}
break
case .completed:
if completion != nil {
completion?(outputUrl,duration,true)
}
break
default:
break
}
}
}
}
//MARK: - Save
public extension FGVideoEditor {
public func save(vedio fileUrl:URL, hud:Bool) {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: fileUrl)
}, completionHandler: { (result, error) in
if !hud {
return
}
if result {
UIApplication.shared.keyWindow?.showHUD(.success("保存成功"))
} else {
UIApplication.shared.keyWindow?.showHUD(.error("保存失败"))
}
})
}
}
//MARK: - Remove
public extension FGVideoEditor {
public func removeVideo(at path:String) throws {
guard path.contains("FGVideo") else {
return
}
do {
try FileManager.default.removeItem(atPath: path)
} catch let e{
throw e
}
}
public func removeAll(completion:(() -> ())?) {
DispatchQueue.global().async {
guard let paths = FileManager.default.subpaths(atPath: self.videoFolder) else {
return
}
for p in paths {
guard p.contains("FGVideo") else {
continue
}
let fullPath = self.videoFolder + "/" + p
do {
try FileManager.default.removeItem(atPath: fullPath)
} catch {
}
}
let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
guard let array = FileManager.default.subpaths(atPath: docPath) else {
return
}
for p in array {
guard p.contains("FGVideo") else {
continue
}
let fullPath = docPath + "/" + p
guard p.contains("FGVideo") else {
continue
}
do {
try FileManager.default.removeItem(atPath: fullPath)
} catch {
}
}
}
if completion != nil {
completion?()
}
}
public func removeAll() {
removeAll(completion: nil)
}
}
| 32.57047 | 134 | 0.534103 |
4a9f805a47b35ab6a1733bc68cb490994850acb5 | 267 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for {
protocol C {
class B {
struct d {
deinit {
for in {
let a {
if true {
func g {
class
case ,
| 16.6875 | 87 | 0.715356 |
8a27bea68633d1cf6000fe2c9f3f96496b385b74 | 6,365 | //
// TopViewControllerDemoTests.swift
// TopViewControllerDemoTests
//
// Created by Siarhei Ladzeika on 4/10/19.
// Copyright © 2019 Siarhei Ladzeika. All rights reserved.
//
import Foundation
import XCTest
import TopViewControllerDetection
fileprivate func cleanup() {
let storyboard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
let viewController = storyboard.instantiateInitialViewController()
UIApplication.shared.keyWindow?.rootViewController = viewController
}
typealias Completion = () -> Void
class TopViewControllerDemoTests: XCTestCase {
func run(_ block: (_ complete: @escaping Completion) -> Void ) {
let expectation = XCTestExpectation(description: "")
block({ expectation.fulfill() })
self.wait(for: [expectation], timeout: 100)
}
func test_SimpleViewController() {
self.addTeardownBlock {
cleanup()
}
XCTAssert(UIApplication.shared.keyWindow != nil)
XCTAssert(UIApplication.shared.findTopViewController() == UIApplication.shared.keyWindow?.rootViewController);
}
func test_PresentedViewController() {
self.addTeardownBlock {
cleanup()
}
let root = UIViewController()
let nav = UINavigationController(rootViewController: root)
run { (complete) in
UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: false, completion: {
complete()
})
}
XCTAssert(UIApplication.shared.findTopViewController() == root);
}
func test_UINavigationViewController() {
self.addTeardownBlock {
cleanup()
}
let root = UIViewController()
let nav = UINavigationController(rootViewController: root)
UIApplication.shared.keyWindow?.rootViewController = nav
XCTAssert(UIApplication.shared.findTopViewController() == root);
}
func test_UITabBarController() {
self.addTeardownBlock {
cleanup()
}
let tab1 = UIViewController()
let tab2 = UIViewController()
let tab = UITabBarController()
tab.viewControllers = [tab1, tab2]
tab.selectedIndex = 1
UIApplication.shared.keyWindow?.rootViewController = tab
XCTAssert(UIApplication.shared.findTopViewController() == tab2);
}
func test_Child_UIViewController_Latest() {
self.addTeardownBlock {
cleanup()
}
let parent = UIViewController()
let child1 = UIViewController()
let child2 = UIViewController()
let child3 = UIViewController()
let add: (_ child: UIViewController, _ frame: CGRect) -> Void = { child, frame in
child.willMove(toParent: parent)
parent.addChild(child)
child.view.frame = frame
parent.view.addSubview(child.view)
child.didMove(toParent: parent)
}
add(child1, parent.view.bounds)
add(child2, parent.view.bounds)
add(child3, parent.view.bounds)
UIApplication.shared.keyWindow?.rootViewController = parent
XCTAssert(UIApplication.shared.findTopViewController() == child3);
}
func test_Child_UIViewController_Hidden() {
self.addTeardownBlock {
cleanup()
}
let parent = UIViewController()
let child1 = UIViewController()
let child2 = UIViewController()
let child3 = UIViewController()
let add: (_ child: UIViewController, _ frame: CGRect) -> Void = { child, frame in
child.willMove(toParent: parent)
parent.addChild(child)
child.view.frame = frame
parent.view.addSubview(child.view)
child.didMove(toParent: parent)
}
add(child1, parent.view.bounds)
add(child2, parent.view.bounds)
add(child3, parent.view.bounds)
child3.view.isHidden = true
UIApplication.shared.keyWindow?.rootViewController = parent
XCTAssert(UIApplication.shared.findTopViewController() == child2);
}
func test_Child_UIViewController_Alpha() {
self.addTeardownBlock {
cleanup()
}
let parent = UIViewController()
let child1 = UIViewController()
let child2 = UIViewController()
let child3 = UIViewController()
let add: (_ child: UIViewController, _ frame: CGRect) -> Void = { child, frame in
child.willMove(toParent: parent)
parent.addChild(child)
child.view.frame = frame
parent.view.addSubview(child.view)
child.didMove(toParent: parent)
}
add(child1, parent.view.bounds)
add(child2, parent.view.bounds)
add(child3, parent.view.bounds)
child3.view.alpha = 0.049;
UIApplication.shared.keyWindow?.rootViewController = parent
XCTAssert(UIApplication.shared.findTopViewController() == child2);
}
func test_Child_UIViewController_Frame() {
self.addTeardownBlock {
cleanup()
}
let parent = UIViewController()
let child1 = UIViewController()
let child2 = UIViewController()
let child3 = UIViewController()
let add: (_ child: UIViewController, _ frame: CGRect) -> Void = { child, frame in
child.willMove(toParent: parent)
parent.addChild(child)
child.view.frame = frame
parent.view.addSubview(child.view)
child.didMove(toParent: parent)
}
add(child1, parent.view.bounds)
add(child2, parent.view.bounds)
add(child3, parent.view.bounds)
child3.view.alpha = 0.049;
UIApplication.shared.keyWindow?.rootViewController = parent
XCTAssert(UIApplication.shared.findTopViewController() == child2);
}
}
| 29.467593 | 118 | 0.585075 |
26128cadd92c90e8d096ace94e06417712e393e9 | 2,026 | /// Copyright (c) 2020 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Foundation
public class WaitingForPickupViewModel {
// MARK: - Properties
let goToNewRideNavigator: GoToNewRideNavigator
// MARK: - Methods
public init(goToNewRideNavigator: GoToNewRideNavigator) {
self.goToNewRideNavigator = goToNewRideNavigator
}
@objc
public func startNewRide() {
goToNewRideNavigator.navigateToNewRide()
}
}
| 44.043478 | 83 | 0.758638 |
099a780f2c01b89987f1e69e778d7dfea68b9f03 | 974 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
/// Auth SignIn flow steps
///
///
public enum AuthSignInStep {
/// Auth step is SMS multi factor authentication.
///
/// Confirmation code for the MFA will be send to the provided SMS.
case confirmSignInWithSMSMFACode(AuthCodeDeliveryDetails, AdditionalInfo?)
/// Auth step is in a custom challenge depending on the plugin.
///
case confirmSignInWithCustomChallenge(AdditionalInfo?)
/// Auth step required the user to give a new password.
///
case confirmSignInWithNewPassword(AdditionalInfo?)
/// Auth step required the user to change their password.
///
case resetPassword(AdditionalInfo?)
/// Auth step that required the user to be confirmed
///
case confirmSignUp(AdditionalInfo?)
/// There is no next step and the signIn flow is complete
///
case done
}
| 25.631579 | 78 | 0.689938 |
163349f662ba266a7494f39beeb14943b042d2dd | 1,733 | class Solution {
// Solution @ Sergey Leschev, Belarusian State University
// 52. N-Queens II
// The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
// Given an integer n, return the number of distinct solutions to the n-queens puzzle.
// Example 1:
// Input: n = 4
// Output: 2
// Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
// Example 2:
// Input: n = 1
// Output: 1
// Constraints:
// 1 <= n <= 9
func totalNQueens(_ n: Int) -> Int {
var res: [[Int]] = []
func backtarck(_ path: [Int]) {
if path.count == n { res.append(path) }
var path = path
var available: [Int] = []
for i in 0..<n { available.append(i) }
for (i, val) in path.enumerated() {
if let index = available.firstIndex(of: val - path.count + i) {
available.remove(at: index)
}
if let index = available.firstIndex(of: val) {
available.remove(at: index)
}
if let index = available.firstIndex(of: val + path.count - i) {
available.remove(at: index)
}
}
for i in 0..<n {
if available.contains(i) == false { continue }
path.append(i)
backtarck(path)
path.remove(at: path.count - 1)
}
}
backtarck([])
return res.count
}
} | 29.372881 | 127 | 0.463935 |
299eb543be81dd2c6fea6f4c81aa1b46953a1563 | 2,978 | /*
-----------------------------------------------------------------------------
This source file is part of MedKitMIP.
Copyright 2016-2018 Jon Griffeth
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 MedKitCore
import SecurityKit
/**
RPCV1 Sequencer
*/
class RPCV1Sequencer {
/**
Completion handler type.
The type of the completion handler used to receive replies to synchronous
messages.
Completion handlers may throw exceptions to indicate an error when
decoding a reply.
*/
typealias CompletionHandler = (AnyCodable?, Error?) throws -> Void //: Completion handler signature for synchronous messages.
typealias IDType = UInt32
// MARK: - Private
private var completionHandlers = [IDType : CompletionHandler]()
private var sequence = SecurityManagerShared.main.random(IDType.self)
// MARK: - Initializers
init()
{
}
// MARK: -
/**
*/
func complete(id: IDType, reply: AnyCodable?, error: Error?) throws
{
let completion = try pop(id)
try completion(reply, error)
}
/**
*/
func push(completionHandler completion: @escaping CompletionHandler) -> IDType
{
let id = generateID()
completionHandlers[id] = completion
return id
}
/**
*/
func shutdown(for reason: Error?)
{
for (_, completion) in completionHandlers {
try? completion(nil, reason)
}
completionHandlers.removeAll()
}
// MARK: - Private
/**
Generate message ID.
- Returns:
Returns the generated message ID.
*/
private func generateID() -> IDType
{
let id = sequence
sequence += 1
return id
}
/**
Pop completion handler.
- Parameters:
- id: A message identifier.
- Returns:
Returns the completion handler assigned to the message ID, or nil if
no such completion handler exists.
*/
private func pop(_ id: IDType) throws -> CompletionHandler
{
if let completion = completionHandlers[id] {
completionHandlers.removeValue(forKey: id)
return completion
}
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "Unexpected message idenitfier."))
}
}
// End of File
| 24.016129 | 132 | 0.609805 |
1a1378e81e364103a7a3ecdbaa275775535ee2be | 1,333 | //
// MediaPlayerView.swift
// XZKit
//
// Created by mlibai on 2018/4/14.
// Copyright © 2018年 mlibai. All rights reserved.
//
import UIKit
import AVFoundation
/// MediaPlayerView 播放器视图。
@objc(XZMediaPlayerView) public final class MediaPlayerView: UIView {
open override class var layerClass: Swift.AnyClass {
return AVPlayerLayer.self
}
var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
// public override func draw(_ rect: CGRect) {
//
// let bounds = self.bounds
//
// let shadow = NSShadow()
// shadow.shadowColor = UIColor(rgba: 0x444444EE)
// shadow.shadowOffset = CGSize.zero//(width: 0, height: 3.0)
// shadow.shadowBlurRadius = 3.0
//
// let attribute: [String: Any] = [
// NSFontAttributeName: UIFont.systemFont(ofSize: 24),
// NSForegroundColorAttributeName: UIColor.darkGray,
// NSShadowAttributeName: shadow
// ]
//
// let string: NSAttributedString = NSAttributedString(string: "XZKit®", attributes: attribute)
// let size = string.size()
// string.draw(at: CGPoint(x: (bounds.width - size.width) * 0.5, y: (bounds.height - size.height) * 0.5))
//
// }
}
| 29.622222 | 116 | 0.585146 |
08dd9f40fa141b81306ca5c57f5225ccf5cd4c2f | 1,516 | // Ztopwatch.swift
// Ztopwatch
//
// Created by Slava Zubrin on 12/11/19.
// Copyright © 2019 Slava Zubrin. All rights reserved.
//
import Foundation
public protocol ZtopwatchI {
mutating func start()
mutating func stop()
mutating func reset()
var isRunning: Bool { get }
var duration: TimeInterval { get }
}
public struct Ztopwatch: ZtopwatchI {
private var startTik: DispatchTime? = nil
private var stopTik: DispatchTime? = nil
// MARK: - Lifecycle
public init() {}
// MARK: - Public
mutating public func start() {
guard !isRunning, !isDone else { return }
startTik = DispatchTime.now()
}
mutating public func stop() {
guard isRunning, !isDone else { return }
stopTik = DispatchTime.now()
}
mutating public func reset() {
startTik = nil
stopTik = nil
}
public var isRunning: Bool {
return startTik != nil && stopTik == nil
}
/// Measured duration in seconds
public var duration: TimeInterval {
guard let stop = stopTik, let start = startTik else { return .nan }
let nanoTime = stop.uptimeNanoseconds - start.uptimeNanoseconds // Difference in nanoseconds (UInt64)
return TimeInterval(nanoTime) / 1_000_000_000 // Technically could overflow for long running tests
}
// MARK: - Private
private var isDone: Bool {
return startTik != nil && stopTik != nil
}
}
| 23.6875 | 109 | 0.609499 |
237b4c7a7e78c768b964a4070eafe72ea5019d6d | 1,849 | import UserNotifications
class NotificationScheduler {
let center: NotificationCenterProtocol
init(center: NotificationCenterProtocol = UNUserNotificationCenter.current()) {
self.center = center
}
func getAllNotifications() {
let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests(completionHandler: { requests in
for request in requests {
print(request)
}
})
}
func createNotificationOnDate(id: String, name: String, date: Date, frequency: Frequency?) {
let notification = UNMutableNotificationContent()
notification.title = name
notification.body = "This is the notification create at \(date)"
let dateComponents = dateComponentsBuilder(frequency: frequency)
let triggerDate = Calendar.current.dateComponents(dateComponents, from: date)
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: triggerDate,
repeats: true)
let request = UNNotificationRequest(identifier: id,
content: notification,
trigger: notificationTrigger)
center.add(request, withCompletionHandler: nil)
}
func dateComponentsBuilder(frequency: Frequency?) -> Set<Calendar.Component> {
switch frequency {
case .day?:
return [.hour, .minute, .second]
case .week?:
return [.weekday, .hour, .minute, .second]
case .month?:
return [.day, .hour, .minute, .second]
case .year?:
return [.month, .day, .hour, .minute, .second]
default:
return [.year, .month, .day, .hour, .minute, .second]
}
}
}
| 38.520833 | 96 | 0.595457 |
dd6075b70b3d8665217369dfa54739fe98e775d3 | 5,838 | //
// ==----------------------------------------------------------------------== //
//
// SearchStoreTests_FunctionalStyle2.swift
//
// Created by Trevor Beasty on 10/3/19.
//
//
// This source file is part of the Lasso open source project
//
// https://github.com/ww-tech/lasso
//
// Copyright © 2019-2020 WW International, Inc.
//
// ==----------------------------------------------------------------------== //
//
import XCTest
@testable import Lasso_Example
import LassoTestUtilities
/// These test represent the more general functional style.
/// This style should be used when State and Output are not NOT Equatable.
/// You must conform to LassoStoreTesting
class SearchStoreTestsFunctionalStyle2: XCTestCase, LassoStoreTesting {
/// Be sure to explicitly declare the Store type to avoid compiler issues.
typealias Store = SearchStore<Item>
struct Item: SearchListRepresentable, Equatable {
let searchListTitle: String
}
var searchRequests = [(query: String?, completion: (Result<[Item], Error>) -> Void)]()
/// This is the factory for all your test cases. Because is accesses 'self', it must be lazy.
lazy var test = TestFactory<SearchStore<Item>>(
/// Provide some default initial state.
initialState: State(searchText: nil,
items: [],
phase: .idle,
viewDidAppear: false),
/// Set up the store. This is your chance to mock store dependencies, like network requests.
setUpStore: { (store: SearchStore<Item>) -> Void in
store.getSearchResults = { self.searchRequests.append(($0, $1)) }
},
/// Perform your typical teardown, resetting mocked values.
tearDown: {
self.searchRequests = []
})
func test_InitialFetch() {
let items = [Item(searchListTitle: "a")]
// loading state with pending request
let loading = test
.given({
$0.viewDidAppear = false
$0.searchText = nil
})
/// This is the most general form of 'when' statement you can make. You can dispatch Action's via the single argument.
.when({ dispatchAction in
dispatchAction(.viewWillAppear)
})
/// This is the most general form of 'then' assertion you can make.
/// The single argument contains the emitted values. It has the members:
/// previousState: State
/// states: [State]
/// outputs: [Output]
.then(assert { emitted in
XCTAssertEqual(emitted.states.last, State(searchText: nil, items: [], phase: .searching, viewDidAppear: true))
XCTAssertEqual(self.searchRequests.count, 1)
XCTAssertEqual(self.searchRequests[0].query, nil)
})
/// You may branch your test logic to reuse shared setup. Here, we want to test
/// both the success and failure of the network request.
// successful request
loading
/// You can ignore 'dispatchAction' when performing just side effects.
.when({ _ in
self.searchRequests[0].completion(.success(items))
})
.then(assert { emitted in
XCTAssertEqual(emitted.states.last, State(searchText: nil, items: items, phase: .idle, viewDidAppear: true))
})
.execute()
// request failure
loading
.when({ _ in
self.searchRequests[0].completion(.failure(NSError()))
})
.then(assert {
XCTAssertEqual($0.states, [State(searchText: nil, items: [], phase: .error(message: "Something went wrong"), viewDidAppear: true)])
})
.when({ dispatchAction in dispatchAction(.didAcknowledgeError) })
.then(assert { emitted in
XCTAssertEqual(emitted.states, [State(searchText: nil, items: [], phase: .idle, viewDidAppear: true)])
})
.execute()
}
/// This is a repeat of the above test's success case shown in a different way.
func test_InitialFetchSuccess_Condensed() {
let items = [Item(searchListTitle: "a")]
test
.given({
$0.viewDidAppear = false
$0.searchText = nil
})
/// If you need to both dispatch Action's and invoke side effects, you need to open up a closure.
.when({ dispatchAction in
dispatchAction(.viewWillAppear)
self.searchRequests[0].completion(.success(items))
})
/// You can make a large variety of assertions inside the 'assert' closure.
.then(assert { (emitted) in
let expectedStates = [
State(searchText: nil, items: [], phase: .searching, viewDidAppear: true),
State(searchText: nil, items: items, phase: .idle, viewDidAppear: true)
]
XCTAssertEqual(emitted.states, expectedStates)
XCTAssertTrue(emitted.outputs.isEmpty)
XCTAssertEqual(self.searchRequests.count, 1)
XCTAssertEqual(self.searchRequests[0].query, nil)
})
.execute()
}
func test_Selection() {
let items = [Item(searchListTitle: "a")]
test
.given({
$0.items = items
})
.when(actions(.didSelectItem(idx: 0)))
.then(assert { emitted in
XCTAssertEqual(emitted.outputs, [.didSelectItem(items[0])])
})
.execute()
}
}
| 38.92 | 147 | 0.548133 |
ccf74a2f7d450d991617e96af2fae93b0e627673 | 7,667 | //
// MeasureDirectionViewModelTestCase.swift
// GoMapTests
//
// Created by Wolfgang Timme on 4/2/19.
// Copyright © 2019 Bryce Cogswell. All rights reserved.
//
import XCTest
import CoreLocation
@testable import Go_Map__
class MeasureDirectionViewModelTestCase: XCTestCase {
private var viewModel: MeasureDirectionViewModel!
private var headingProviderMock: HeadingProviderMock!
private let key = "lorem-ipsum-key"
private var delegateMock: MeasureDirectionViewModelDelegateMock!
override func setUp() {
super.setUp()
headingProviderMock = HeadingProviderMock()
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock, key: key)
delegateMock = MeasureDirectionViewModelDelegateMock()
viewModel.delegate = delegateMock
}
override func tearDown() {
viewModel = nil
headingProviderMock = nil
delegateMock = nil
super.tearDown()
}
// MARK: Heading is not available
func testValueLabelTextShouldIndicateThatHeadingIsNotAvailableWhenHeadingIsNotAvailable() {
headingProviderMock.isHeadingAvailable = false
// Re-create the view model, since it only asks for the `headingAvailble` during initialization.
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock, key: key)
XCTAssertEqual(viewModel.valueLabelText.value, "🤷♂️")
}
func testOldValueLabelTextShouldIndicateThatHeadingIsNotAvailableWhenHeadingIsNotAvailable() {
headingProviderMock.isHeadingAvailable = false
// Re-create the view model, since it only asks for the `headingAvailble` during initialization.
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock, key: key)
XCTAssertEqual(viewModel.oldValueLabelText.value,
"This device is not able to provide heading data.")
}
func testIsPrimaryActionButtonHiddenShouldBeTrueWhenHeadingIsNotAvailable() {
headingProviderMock.isHeadingAvailable = false
// Re-create the view model, since it only asks for the `headingAvailble` during initialization.
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock, key: key)
XCTAssertTrue(viewModel.isPrimaryActionButtonHidden.value)
}
func testDismissButtonTitleShouldBeBackWhenHeadingIsNotAvailable() {
headingProviderMock.isHeadingAvailable = false
// Re-create the view model, since it only asks for the `headingAvailble` during initialization.
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock, key: key)
XCTAssertEqual(viewModel.dismissButtonTitle.value, "Back")
}
// MARK: Heading is available
func testValueLabelTextShouldInitiallyBeThreeDotsWhenHeadingIsAvailable() {
headingProviderMock.isHeadingAvailable = true
// Re-create the view model, since it only asks for the `headingAvailble` during initialization.
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock, key: key)
XCTAssertEqual(viewModel.valueLabelText.value, "...")
}
func testOldValueLabelTextShouldContainTheOldValueWhenItWasProvidedDuringInitialization() {
let oldValue = "Lorem Ipsum"
// Re-create the view model and pass the mocked old value.
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock,
key: key,
value: oldValue)
XCTAssertEqual(viewModel.oldValueLabelText.value, "Old value: \(oldValue)")
}
func testOldValueLabelTextShouldBeNilIfTheOriginalValueWasNil() {
let oldValue: String? = nil
// Re-create the view model and pass the mocked old value.
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock,
key: key,
value: oldValue)
XCTAssertNil(viewModel.oldValueLabelText.value)
}
func testOldValueLabelTextShouldBeNilIfTheOriginalValueWasAnEmptyString() {
let oldValue = ""
// Re-create the view model and pass the mocked old value.
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock,
key: key,
value: oldValue)
XCTAssertNil(viewModel.oldValueLabelText.value)
}
// MARK: primaryActionButtonTitle
func testPrimaryActionButtonTitleShouldIndicateThatTheGivenKeyWillBeUpdated() {
let key = "some-key"
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock, key: key)
XCTAssertEqual(viewModel.primaryActionButtonTitle, "Update 'some-key' tag")
}
// MARK: isPrimaryActionButtonHidden
func testPrimaryActionButtonShouldBeHiddenWhenNoHeadingUpdateHasBeenProvidedYet() {
XCTAssertTrue(viewModel.isPrimaryActionButtonHidden.value)
}
func testPrimaryActionButtonShouldBeVisibleWhenHeadingProviderDidUpdateHeading() {
let trueHeading: CLLocationDirection = 123.456789
let heading = CLHeadingMock(trueHeading: trueHeading)
headingProviderMock.delegate?.headingProviderDidUpdateHeading(heading)
XCTAssertFalse(viewModel.isPrimaryActionButtonHidden.value)
}
// MARK: Receiving heading updates
func testValueLabelTextShouldBeTrueHeadingWhenHeadingProviderDidUpdateHeading() {
let trueHeading: CLLocationDirection = 123.456789
let heading = CLHeadingMock(trueHeading: trueHeading)
headingProviderMock.delegate?.headingProviderDidUpdateHeading(heading)
XCTAssertEqual(viewModel.valueLabelText.value, "123")
}
// MARK: viewDidAppear
func testViewDidAppearShouldAskHeadingProviderToStartUpdatingHeading() {
viewModel.viewDidAppear()
XCTAssertTrue(headingProviderMock.startUpdatingHeadingCalled)
}
// MARK: viewDidDisappear
func testViewDidDisappearShouldAskHeadingProviderToStartUpdatingHeading() {
viewModel.viewDidDisappear()
XCTAssertTrue(headingProviderMock.stopUpdatingHeadingCalled)
}
// MARK: didTapPrimaryActionButton
func testDidTapPrimaryActionButtonWhenOldValueIsNilShouldNotInformDelegate() {
/// Given
let viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock,
key: "",
value: nil)
/// When
viewModel.didTapPrimaryActionButton()
/// Then
XCTAssertFalse(delegateMock.didFinishUpdatingTagCalled)
}
func testDidTapPrimaryActionButtonShouldInformDelegateWithTheKeyFromTheInitialization() {
let key = "foo"
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock, key: key)
viewModel.delegate = delegateMock
let heading = CLHeadingMock(trueHeading: 123.456)
headingProviderMock.delegate?.headingProviderDidUpdateHeading(heading)
viewModel.didTapPrimaryActionButton()
XCTAssertEqual(delegateMock.key, key)
}
func testDidTapPrimaryActionButtonShouldInformDelegateWithOldValueWhenNoHeadingUpdateWasReceivedYet() {
let oldValue = "Lorem Ipsum"
// Re-create the view model and pass the mocked old value.
viewModel = MeasureDirectionViewModel(headingProvider: headingProviderMock,
key: key,
value: oldValue)
viewModel.delegate = delegateMock
viewModel.didTapPrimaryActionButton()
XCTAssertEqual(delegateMock.value, oldValue)
}
func testDidTapPrimaryActionButtonShouldAskDelegateToDismissWithDirectionWithoutDecimalsOfTheLastHeadingUpdate() {
let firstHeading = CLHeadingMock(trueHeading: 123.456)
headingProviderMock.delegate?.headingProviderDidUpdateHeading(firstHeading)
let secondHeading = CLHeadingMock(trueHeading: 987.654)
headingProviderMock.delegate?.headingProviderDidUpdateHeading(secondHeading)
viewModel.didTapPrimaryActionButton()
XCTAssertEqual(delegateMock.value, "987")
}
}
| 33.77533 | 115 | 0.770445 |
e5d3d13538d489f80cdeffe93075a40b69fbc907 | 3,186 | //
// GasSpeedView.swift
// AlphaWallet
//
// Created by Vladyslav Shepitko on 20.08.2020.
//
import UIKit
class GasSpeedTableViewCell: UITableViewCell {
static let height: CGFloat = CGFloat(100)
private let estimatedTimeLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
private let speedLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
private let detailsLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
private let gasPriceLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let col0 = [
speedLabel,
detailsLabel,
gasPriceLabel,
].asStackView(axis: .vertical, alignment: .leading)
let col1 = [estimatedTimeLabel].asStackView(axis: .vertical)
let row = [.spacerWidth(ScreenChecker().isNarrowScreen ? 8 : 16), col0, col1, .spacerWidth(ScreenChecker().isNarrowScreen ? 8 : 16)].asStackView(axis: .horizontal)
let stackView = [
.spacer(height: ScreenChecker().isNarrowScreen ? 10 : 20),
row,
.spacer(height: ScreenChecker().isNarrowScreen ? 10 : 20)
].asStackView(axis: .vertical)
stackView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(stackView)
NSLayoutConstraint.activate([
col1.widthAnchor.constraint(equalToConstant: 100),
stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 0),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -30),
stackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0),
stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 1)
])
}
required init?(coder: NSCoder) {
return nil
}
func configure(viewModel: GasSpeedTableViewCellViewModel) {
backgroundColor = viewModel.backgroundColor
speedLabel.attributedText = viewModel.titleAttributedString
estimatedTimeLabel.textAlignment = .right
estimatedTimeLabel.attributedText = viewModel.estimatedTimeAttributedString
estimatedTimeLabel.isHidden = estimatedTimeLabel.attributedText == nil
detailsLabel.attributedText = viewModel.detailsAttributedString
detailsLabel.isHidden = detailsLabel.attributedText == nil
gasPriceLabel.attributedText = viewModel.gasPriceAttributedString
gasPriceLabel.isHidden = gasPriceLabel.attributedText == nil
accessoryType = viewModel.accessoryType
}
}
| 31.86 | 171 | 0.677966 |
9b66f6da7c42fe934c52f8db71e63d6be85cdb74 | 394 | //
// KisiKayitPresenter.swift
// KisilerUygulamasi
//
// Created by Kasım Adalan on 27.12.2021.
//
import Foundation
class KisiKayitPresenter : ViewToPresenterKisiKayitProtocol {
var kisiKayitInteractor: PresenterToInteractorKisiKayitProtocol?
func ekle(kisi_ad: String, kisi_tel: String) {
kisiKayitInteractor?.kisiEkle(kisi_ad: kisi_ad, kisi_tel: kisi_tel)
}
}
| 23.176471 | 75 | 0.743655 |
768efa648c606ca8a8a769dc8bda50782f08be2e | 2,155 | //
// DefaultTransitionAnimator.swift
//
// Copyright © 2018 Oak, LLC (https://oak.is)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
public class DefaultTransitionAnimator: NSObject, UICollectionViewCellAnimatedTransitioning {
public func transitionDuration(transitionContext: UICollectionViewCellContextTransitioning) -> TimeInterval {
return 0.15
}
public func animateTransition(transitionContext: UICollectionViewCellContextTransitioning) {
let toState = transitionContext.stateFor(key: .to)
let cell = transitionContext.cell()
let animationDuration = transitionContext.animationDuration()
UIView.animate(withDuration: animationDuration) {
switch toState {
case .drag:
cell.alpha = 0.7
cell.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
default:
cell.alpha = 1.0
cell.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}
}
}
}
| 39.181818 | 113 | 0.680742 |
9c777242874021ebee3e5cceba8f5370e1660a86 | 823 | //
// CustomImageView.swift
// ChatApp
//
// Created by Sergey Shalnov on 23/11/2018.
// Copyright © 2018 Sergey Shalnov. All rights reserved.
//
import UIKit
class ImageViewDownloader: UIImageView {
// MARK: - Private services
private lazy var loaderService: IRequestLoader = RequestLoader()
// MARK: - Private variables
private var url: String?
}
// MARK: - Pixabay extension
extension ImageViewDownloader {
func pixabayLoader(url: String) {
self.url = url
image = UIImage(named: "ImagePlaceholder")
loaderService.load(url: url) { (data) in
guard let data = data else {
return
}
DispatchQueue.main.async { [weak self] in
if self?.url == url {
self?.image = UIImage(data: data)
}
}
}
}
}
| 17.145833 | 66 | 0.607533 |
7679facda3942a1f10ab92873f32a45472bc9fbf | 599 | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "OneTimePassword",
platforms: [
.iOS(.v9),
.watchOS(.v2)
],
products: [
.library(
name: "OneTimePassword",
targets: ["OneTimePassword"])
],
dependencies: [
.package(url: "https://github.com/pace/Base32", .exact("1.2.0"))
],
targets: [
.target(name: "OneTimePassword", dependencies: ["Base32"], path: "Sources"),
.testTarget(name: "OneTimePasswordTests", dependencies: ["OneTimePassword"], path: "Tests")
]
)
| 26.043478 | 99 | 0.572621 |
e480de582726dc4b787d6b2028b423779981b88b | 3,058 | //
// AppDelegate.swift
// Twitter
//
// Created by YouGotToFindWhatYouLove on 2/16/16.
// Copyright © 2016 Candy. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
import AFNetworking
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var storyboard = UIStoryboard(name: "Main", bundle: nil)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "userDidLogout", name: userDidLogoutNotification, object: nil)
if User.currentUser != nil {
// Go to the logged in screen
let vc = storyboard.instantiateViewControllerWithIdentifier("TweetsViewController")
window?.rootViewController = vc
}
return true
}
func userDidLogout() {
let vc = storyboard.instantiateInitialViewController()! as UIViewController
window?.rootViewController = vc
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool
{
TwitterClient.sharedInstance.openURL(url)
return true
}
}
| 38.708861 | 285 | 0.71223 |
48489453d0948ee98fa89a65e7ce87cc8e7f28ad | 666 | import Foundation
import SwiftDux
import SwiftUI
@propertyWrapper
public struct WaypointParameter<T>: DynamicProperty where T: LosslessStringConvertible & Hashable & Equatable {
@Environment(\.waypoint) private var waypoint
private var parameter: Binding<T?>?
public var wrappedValue: T? {
parameter?.wrappedValue
}
public var projectedValue: Binding<T?> {
Binding(
get: { parameter?.wrappedValue },
set: { value in
if let value = value {
parameter?.wrappedValue = value
}
}
)
}
public init() {}
public mutating func update() {
self.parameter = waypoint.destination(as: T.self)
}
}
| 20.8125 | 111 | 0.666667 |
e90e53048c40e8cfe63132a13de3384478170e7b | 3,592 | //
// SpotifyAuthService.swift
// SpotifyAuthService
//
// Created by Deborah Newberry on 8/14/21.
//
import Combine
final class SpotifyAuthService: NSObject, SPTAppRemoteDelegate, SPTAppRemotePlayerStateDelegate {
private var cancellableBag = Set<AnyCancellable>()
static let main: SpotifyAuthService = SpotifyAuthService()
private override init() {
super.init()
currentPlayerStatePublisher
.removeDuplicates(by: { firstState, secondState in
return firstState.hash == secondState.hash
})
.map { $0.track }
.sink { [weak self] track in
self?.appRemote.imageAPI?.fetchImage(forItem: track, with: .init(width: 50, height: 50), callback: { (response, error) in
if let error = error {
print(error)
}
self?.currentImagePublisher.send(response as? UIImage)
})
}
.store(in: &cancellableBag)
isConnectedPublisher.send(false)
}
private let spotifyClientID = Bundle.stringValue(forKey: .spotifyClientId)
private let spotifyRedirectURL = URL(string: "dnewberr-lyric-search://spotify-login-callback")!
private var accessToken: String?
private lazy var configuration = SPTConfiguration(clientID: spotifyClientID, redirectURL: spotifyRedirectURL)
private lazy var appRemote: SPTAppRemote = {
let appRemote = SPTAppRemote(configuration: self.configuration, logLevel: .debug)
appRemote.connectionParameters.accessToken = self.accessToken
appRemote.delegate = self
return appRemote
}()
let currentPlayerStatePublisher = PassthroughSubject<SPTAppRemotePlayerState, Never>()
let currentImagePublisher = PassthroughSubject<UIImage?, Never>()
let isConnectedPublisher = PassthroughSubject<Bool, Never>()
func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
isConnectedPublisher.send(true)
appRemote.playerAPI?.delegate = self
appRemote.playerAPI?.subscribe(toPlayerState: { (result, error) in
if let error = error {
debugPrint(error.localizedDescription)
}
})
}
func appRemote(_ appRemote: SPTAppRemote, didDisconnectWithError error: Error?) {
isConnectedPublisher.send(false)
print("disconnected")
}
func appRemote(_ appRemote: SPTAppRemote, didFailConnectionAttemptWithError error: Error?) {
isConnectedPublisher.send(false)
print("failed")
}
func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
currentPlayerStatePublisher.send(playerState)
}
func authorize() {
appRemote.authorizeAndPlayURI("")
}
func attemptToEstablishConnection(fromUrl url: URL) {
let parameters = appRemote.authorizationParameters(from: url);
if let accessToken = parameters?[SPTAppRemoteAccessTokenKey] {
appRemote.connectionParameters.accessToken = accessToken
self.accessToken = accessToken
} else if let errorDescription = parameters?[SPTAppRemoteErrorDescriptionKey] {
// Show the error
debugPrint(errorDescription)
}
}
func disconnect() {
if appRemote.isConnected {
appRemote.disconnect()
}
}
func reconnect() {
if let _ = appRemote.connectionParameters.accessToken {
appRemote.connect()
}
}
}
| 35.564356 | 137 | 0.644766 |
de699cadcefaee20e6b1a04ed2aca250ebe20bfc | 3,264 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/**
State information for the conversation. To maintain state, include the context from the previous response.
*/
public struct Context: Codable, Equatable {
/**
The unique identifier of the conversation.
*/
public var conversationID: String?
/**
For internal use only.
*/
public var system: SystemResponse?
/**
Metadata related to the message.
*/
public var metadata: MessageContextMetadata?
/// Additional properties associated with this model.
public var additionalProperties: [String: JSON]
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case conversationID = "conversation_id"
case system = "system"
case metadata = "metadata"
static let allValues = [conversationID, system, metadata]
}
/**
Initialize a `Context` with member variables.
- parameter conversationID: The unique identifier of the conversation.
- parameter system: For internal use only.
- parameter metadata: Metadata related to the message.
- returns: An initialized `Context`.
*/
public init(
conversationID: String? = nil,
system: SystemResponse? = nil,
metadata: MessageContextMetadata? = nil,
additionalProperties: [String: JSON] = [:]
)
{
self.conversationID = conversationID
self.system = system
self.metadata = metadata
self.additionalProperties = additionalProperties
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
conversationID = try container.decodeIfPresent(String.self, forKey: .conversationID)
system = try container.decodeIfPresent(SystemResponse.self, forKey: .system)
metadata = try container.decodeIfPresent(MessageContextMetadata.self, forKey: .metadata)
let dynamicContainer = try decoder.container(keyedBy: DynamicKeys.self)
additionalProperties = try dynamicContainer.decode([String: JSON].self, excluding: CodingKeys.allValues)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(conversationID, forKey: .conversationID)
try container.encodeIfPresent(system, forKey: .system)
try container.encodeIfPresent(metadata, forKey: .metadata)
var dynamicContainer = encoder.container(keyedBy: DynamicKeys.self)
try dynamicContainer.encodeIfPresent(additionalProperties)
}
}
| 35.478261 | 112 | 0.702819 |
de60a5c518aafdc55df0a5396c33030d73fee885 | 11,018 | //
// POIDetailViewController.swift
// travelMapMvvm
//
// Created by green on 15/9/13.
// Copyright (c) 2015年 travelMapMvvm. All rights reserved.
//
import UIKit
import ReactiveCocoa
import GONMarkupParser
class POIDetailViewController: UITableViewController {
// MARK: - UI
@IBOutlet weak var poiPicV : UIImageView! // POI 图片
@IBOutlet weak var poiNameL : UILabel! // POI 名称
@IBOutlet weak var levelV : RatingBar! // POI 评分
@IBOutlet weak var moreMomentBtn: UIButton!
@IBOutlet weak var showGuideLineBtn: UIButton!
@IBOutlet weak var poiDescTextView : UITextView! // POI 简介
@IBOutlet weak var poiAddressTextView : UITextView! // POI 地址
@IBOutlet weak var poiOpenTimeTextView : UITextView! // POI 开放时间
@IBOutlet weak var poiTiketTextView : UITextView! // POI 票价
@IBOutlet weak var topViewContainer : UIView!
@IBOutlet weak var headerViewContainer : UIView!
@IBOutlet weak var poiDescTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var poiAddressTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var poiOpenTimeTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var poiTiketTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var scenicBtn : UIButton!
@IBOutlet weak var foodBtn : UIButton!
@IBOutlet weak var shoppingBtn : UIButton!
@IBOutlet weak var hotelBtn : UIButton!
@IBOutlet weak var activityBtn : UIButton!
// MARK: - TABLE Cell
let kCellIdentifier = "cell"
// MARK: - View Model
var poiDetailViewModel:POIDetailViewModel!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
// MARK: - Navigation
@IBAction func unwindSegueToPOIDetailViewController(segue: UIStoryboardSegue) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == kSegueFromPOIDetailViewControllerToMoreCommentsController {
let moreCommentsController = (segue.destinationViewController as! UINavigationController).topViewController as! MoreCommentsController
moreCommentsController.moreCommentViewModel = MoreCommentsViewModel(poiDetailViewModel: self.poiDetailViewModel)
}
if segue.identifier == kSegueFromPOIDetailViewControllerToPOIContainerController {
let poiContainerController = segue.destinationViewController as! POIContainerController
poiContainerController.poiContainerViewModel = POIContainerViewModel(paramTuple: (QueryTypeEnum.POIListByCenterPOIId,self.poiDetailViewModel.poiModel.poiId!))
}
if segue.identifier == kSegueFromPOIDetailViewControllerToGuideLineViewController {
let guideLineViewController = segue.destinationViewController as! GuideLineViewController
let latitude = Double((self.poiDetailViewModel.poiModel.latitude! as NSString).floatValue)
let longitude = Double((self.poiDetailViewModel.poiModel.longitude! as NSString).floatValue)
guideLineViewController.destinationCoordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
// MARK: - SetUp
private func setup() {
moreMomentBtn.loginBorderStyle()
setUpButtonEvent()
setupCommand()
bindViewModel()
setupMessage()
}
// MARK: - Set Up Button Event
private func setUpButtonEvent() {
scenicBtn.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { (any:AnyObject!) -> Void in
self.performSegueWithIdentifier(kSegueFromPOIDetailViewControllerToPOIContainerController, sender: nil)
}
foodBtn.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { (any:AnyObject!) -> Void in
self.performSegueWithIdentifier(kSegueFromPOIDetailViewControllerToPOIContainerController, sender: nil)
}
shoppingBtn.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { (any:AnyObject!) -> Void in
self.performSegueWithIdentifier(kSegueFromPOIDetailViewControllerToPOIContainerController, sender: nil)
}
hotelBtn.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { (any:AnyObject!) -> Void in
self.performSegueWithIdentifier(kSegueFromPOIDetailViewControllerToPOIContainerController, sender: nil)
}
activityBtn.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { (any:AnyObject!) -> Void in
self.performSegueWithIdentifier(kSegueFromPOIDetailViewControllerToPOIContainerController, sender: nil)
}
// 显示路线
showGuideLineBtn.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { (any:AnyObject!) -> Void in
self.performSegueWithIdentifier(kSegueFromPOIDetailViewControllerToGuideLineViewController, sender: nil)
}
}
// MARK: - Bind ViewModel
private func bindViewModel() {
// POI 图片
RACObserve(self, "poiDetailViewModel.poiImageViewModel.image") ~> RAC(poiPicV,"image")
// POI 名称
RACObserve(self, "poiDetailViewModel.poiModel.poiName") ~> RAC(poiNameL,"text")
// POI 评分
RACObserve(self, "poiDetailViewModel.poiModel").ignore(nil).map{ (poiModel:AnyObject!) -> AnyObject! in
let poiModel = poiModel as! POIModel
if let level = poiModel.level {
return CGFloat(level.index+1)
}
return nil
}.ignore(nil) ~> RAC(levelV,"rating")
// POI 详细
RACObserve(self, "poiDetailViewModel.poiModel").ignore(nil).subscribeNext { (any:AnyObject!) -> Void in
// textView width
let textViewWidth = UIScreen.mainScreen().bounds.width - 20
let attributeStringTuple = self.poiDetailViewModel.getPOITextViewData(any as! POIModel)
self.poiDescTextView.attributedText = attributeStringTuple.poiDesc
self.poiAddressTextView.attributedText = attributeStringTuple.poiAddress
self.poiOpenTimeTextView.attributedText = attributeStringTuple.openTime
self.poiTiketTextView.attributedText = attributeStringTuple.poiTiket
self.poiDescTextViewHeightConstraint.constant = self.poiDescTextView.height(textViewWidth)
self.poiAddressTextViewHeightConstraint.constant = self.poiAddressTextView.height(textViewWidth - 40 - 6)
self.poiOpenTimeTextViewHeightConstraint.constant = self.poiOpenTimeTextView.height(textViewWidth)
self.poiTiketTextViewHeightConstraint.constant = self.poiTiketTextView.height(textViewWidth)
// textViewContainer Height
let textViewContainerHeight = self.poiDescTextViewHeightConstraint.constant + self.poiAddressTextViewHeightConstraint.constant + self.poiOpenTimeTextViewHeightConstraint.constant + self.poiTiketTextViewHeightConstraint.constant + 32 + 33
self.headerViewContainer.setHeight(self.topViewContainer.height() + textViewContainerHeight)
self.view.layoutIfNeeded()
// 查询评论列表
self.poiDetailViewModel.searchCommentsCommand.execute(nil)
}
}
// MARK: - SETUP Command
private func setupCommand() {
poiDetailViewModel.searchCommentsCommand.executionSignals.subscribeNextAs { (signal:RACSignal) -> () in
signal.dematerialize().deliverOn(RACScheduler.mainThreadScheduler()).subscribeNext({ (any:AnyObject!) -> Void in
// 处理POI评论列表
self.poiDetailViewModel.comments = CommentCell.caculateCellHeight(any as! [CommentModel])
self.tableView.reloadData()
}, error: { (error:NSError!) -> Void in
self.poiDetailViewModel.failureMsg = error.localizedDescription
}, completed: { () -> Void in
// println("completed")
})
}
}
// MARKO: - Setup Message
/**
* 成功失败提示
*/
private func setupMessage() {
RACSignal.combineLatest([
RACObserve(poiDetailViewModel, "failureMsg"),
RACObserve(poiDetailViewModel, "successMsg"),
poiDetailViewModel.searchCommentsCommand.executing
]).subscribeNextAs { (tuple: RACTuple) -> () in
let failureMsg = tuple.first as! String
let successMsg = tuple.second as! String
let isLoading = tuple.third as! Bool
if isLoading {
self.showHUDIndicator()
} else {
if failureMsg.isEmpty && successMsg.isEmpty {
self.hideHUD()
}
}
if !failureMsg.isEmpty {
self.showHUDErrorMessage(failureMsg)
}
if !successMsg.isEmpty {
self.showHUDMessage(successMsg)
}
}
}
// MARK: - UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.poiDetailViewModel.comments.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as! UITableViewCell
// 解决模拟器越界 避免设置数据与reloadData时间差引起的错误
if indexPath.row < self.poiDetailViewModel.comments.count {
let item: AnyObject = self.poiDetailViewModel.comments.keys[indexPath.row]
if let reactiveView = cell as? ReactiveView {
reactiveView.bindViewModel(item)
}
// println(indexPath)
} else {
// print(indexPath)
// print("-越界\n")
}
return cell
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return CGFloat(self.poiDetailViewModel.comments[self.poiDetailViewModel.comments.keys[indexPath.row]]!.integerValue)
}
}
| 39.209964 | 249 | 0.635052 |
e5283199e6f6da66f87f90683c9687213b6aa114 | 3,045 | import Foundation
import azureSwiftRuntime
public protocol NamespacesListKeys {
var headerParameters: [String: String] { get set }
var resourceGroupName : String { get set }
var namespaceName : String { get set }
var authorizationRuleName : String { get set }
var subscriptionId : String { get set }
var apiVersion : String { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (ResourceListKeysProtocol?, Error?) -> Void) -> Void ;
}
extension Commands.Namespaces {
// ListKeys gets the Primary and Secondary ConnectionStrings to the namespace
internal class ListKeysCommand : BaseCommand, NamespacesListKeys {
public var resourceGroupName : String
public var namespaceName : String
public var authorizationRuleName : String
public var subscriptionId : String
public var apiVersion = "2017-04-01"
public init(resourceGroupName: String, namespaceName: String, authorizationRuleName: String, subscriptionId: String) {
self.resourceGroupName = resourceGroupName
self.namespaceName = namespaceName
self.authorizationRuleName = authorizationRuleName
self.subscriptionId = subscriptionId
super.init()
self.method = "Post"
self.isLongRunningOperation = false
self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/listKeys"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName)
self.pathParameters["{namespaceName}"] = String(describing: self.namespaceName)
self.pathParameters["{authorizationRuleName}"] = String(describing: self.authorizationRuleName)
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
self.queryParameters["api-version"] = String(describing: self.apiVersion)
}
public override func returnFunc(data: Data) throws -> Decodable? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let decoder = try CoderFactory.decoder(for: mimeType)
let result = try decoder.decode(ResourceListKeysData?.self, from: data)
return result;
}
throw DecodeError.unknownMimeType
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (ResourceListKeysProtocol?, Error?) -> Void) -> Void {
client.executeAsync(command: self) {
(result: ResourceListKeysData?, error: Error?) in
completionHandler(result, error)
}
}
}
}
| 49.112903 | 209 | 0.658128 |
ac4d41f85f203faa2f1e5089173bb34e99d78558 | 3,524 | /*
* Copyright 2018, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import SwiftProtobufPluginLibrary
class Generator {
internal var options: GeneratorOptions
private var printer: CodePrinter
internal var file: FileDescriptor
internal var service: ServiceDescriptor! // context during generation
internal var method: MethodDescriptor! // context during generation
internal let protobufNamer: SwiftProtobufNamer
init(_ file: FileDescriptor, options: GeneratorOptions) {
self.file = file
self.options = options
self.printer = CodePrinter()
self.protobufNamer = SwiftProtobufNamer(
currentFile: file,
protoFileToModuleMappings: options.protoToModuleMappings
)
self.printMain()
}
public var code: String {
return self.printer.content
}
internal func println(_ text: String = "", newline: Bool = true) {
self.printer.print(text)
if newline {
self.printer.print("\n")
}
}
internal func indent() {
self.printer.indent()
}
internal func outdent() {
self.printer.outdent()
}
internal func withIndentation(body: () -> Void) {
self.indent()
body()
self.outdent()
}
private func printMain() {
self.printer.print("""
//
// DO NOT EDIT.
//
// Generated by the protocol buffer compiler.
// Source: \(self.file.name)
//
//
// Copyright 2018, gRPC Authors All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//\n
""")
let moduleNames = [
"Foundation",
"NIO",
"NIOHTTP1",
"GRPC",
"SwiftProtobuf",
]
for moduleName in (moduleNames + self.options.extraModuleImports).sorted() {
self.println("import \(moduleName)")
}
// Add imports for required modules
let moduleMappings = self.options.protoToModuleMappings
for importedProtoModuleName in moduleMappings.neededModules(forFile: self.file) ?? [] {
self.println("import \(importedProtoModuleName)")
}
self.println()
// We defer the check for printing clients to `printClient()` since this could be the 'real'
// client or the test client.
for service in self.file.services {
self.service = service
self.printClient()
}
self.println()
if self.options.generateServer {
for service in self.file.services {
self.service = service
printServer()
}
}
}
}
| 28.419355 | 96 | 0.672815 |
e8823279da238dcfcd683ffd5e9af5daf3e87796 | 1,981 | //
// 1065 Index Pairs of a String.swift
// LeetCode-Solutions
//
// Created by Aleksandar Dinic on 19/03/2021.
// Copyright © 2021 Aleksandar Dinic. All rights reserved.
//
import Foundation
/// Source: https://leetcode.com/problems/index-pairs-of-a-string/
class Solution {
/// Finds all index pairs `[i, j]` so that the substring `text[i]...text[j]`
/// is in the list of `words`.
///
/// - Parameters:
/// - text: A string.
/// - words: A list of strings.
/// - Returns: All index pairs.
///
/// - Complexity:
/// - time: O(n * m), where n is the length of `text`, and m is the length
/// of `words`.
/// - space: O(n), where n is the length of `text`.
func indexPairs(_ text: String, _ words: [String]) -> [[Int]] {
var root = Trie()
for word in words {
var node = root
root.insert(word, &node)
}
let text = Array(text)
let count = text.count
var ans = [[Int]]()
for i in 0..<count {
var node = root
var j = i
while let child = node.children[text[j]] {
node = child
if child.isLast {
ans.append([i, j])
}
j += 1
guard j == count else { continue }
break
}
}
return ans.sorted { $0[0] != $1[0] ? $0[0] < $1[0] : $0[1] < $1[1] }
}
}
final class Trie {
private(set) var children = [Character: Trie]()
private(set) var isLast = false
func insert(_ word: String, _ node: inout Trie) {
for ch in word {
if let child = node.children[ch] {
node = child
} else {
let curr = Trie()
node.children[ch] = curr
node = curr
}
}
node.isLast = true
}
}
| 25.727273 | 80 | 0.459364 |
201b5e09a71ca101e1813eafc943e8879f31db96 | 1,829 | /*
Licensed under the MIT license:
Copyright (c) 2019 Michal Duda
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
/// Creates a valid CK550 keyboard data.
struct CK550Command {
/// Creates a CK550 data which could be sent to a keyboard.
///
/// - Parameter request: <#request description#>
/// - Returns: Data which could be sent to a keyboard by a single write HID request.
/// - Note: CK550 keyboard is an USB Full Speed device, therefore requires data of 64 bytes,
/// padded with 0. Padding is also a part of this function.
static func newCommand(request: [uint8]) -> [uint8] {
var command = Array.init(repeating: UInt8(0x00), count: 64)
command.replaceSubrange(Range<Int>(uncheckedBounds: (lower: 0, upper: request.count)), with: request)
return command
}
}
| 42.534884 | 109 | 0.746309 |
6ae772abb40be4cfd4e46ae5413ba953862dfd04 | 1,460 | //
// BetaLicenseAgreementUpdateRequest.swift
// AppStoreConnect-Swift-SDK
//
// Created by Pascal Edmond on 12/11/2018.
//
import Foundation
#if os(Linux)
import FoundationNetworking
#endif
/// A request containing a single resource.
public struct BetaLicenseAgreementUpdateRequest: Codable {
public struct Data: Codable {
/// The resource's attributes.
public let attributes: BetaLicenseAgreementUpdateRequest.Data.Attributes?
/// The opaque resource ID that uniquely identifies the resource.
public let `id`: String
/// The resource type.Value: betaLicenseAgreements
public let type: String = "betaLicenseAgreements"
}
/// The resource data.
public let data: BetaLicenseAgreementUpdateRequest.Data
/// - Parameters:
/// - id: The opaque resource ID that uniquely identifies the resource.
/// - agreementText: The license agreement text for your beta app that displays to users.
init(id: String, agreementText: String? = nil) {
data = .init(attributes: .init(agreementText: agreementText), id: id)
}
}
// MARK: BetaLicenseAgreementUpdateRequest.Data
extension BetaLicenseAgreementUpdateRequest.Data {
/// Attributes that describe a resource.
public struct Attributes: Codable {
/// The license agreement text for your beta app that displays to users.
public let agreementText: String?
}
}
| 30.416667 | 95 | 0.691096 |
e63e26826b4c9dda1320c9e0d4a75dc152c39cf6 | 4,941 | // Copyright 2020 Itty Bitty Apps Pty Ltd
import Foundation
import Model
struct TestFlightProgramDifference {
enum Change {
case addBetaGroup(BetaGroup)
case removeBetaGroup(BetaGroup)
case addBetaTesterToApps(BetaTester, [App])
case removeBetaTesterFromApps(BetaTester, [App])
case addBetaTesterToGroups(BetaTester, [BetaGroup])
case removeBetaTesterFromGroups(BetaTester, [BetaGroup])
var description: String {
let operation: String = {
switch self {
case .addBetaGroup, .addBetaTesterToGroups, .addBetaTesterToApps:
return "added to"
case .removeBetaGroup, .removeBetaTesterFromGroups, .removeBetaTesterFromApps:
return "removed from"
}
}()
switch self {
case .addBetaGroup(let betaGroup), .removeBetaGroup(let betaGroup):
let name = betaGroup.groupName ?? ""
let bundleId = betaGroup.app?.bundleId ?? ""
return "Beta Group named: \(name) will be \(operation) app: \(bundleId)"
case .addBetaTesterToApps(let betaTester, let apps),
.removeBetaTesterFromApps(let betaTester, let apps):
let email = betaTester.email ?? ""
let bundleIds = apps.compactMap(\.bundleId).joined(separator: ", ")
return "Beta Tester with email: \(email) " +
"will be \(operation) apps: \(bundleIds)"
case .addBetaTesterToGroups(let betaTester, let betaGroups),
.removeBetaTesterFromGroups(let betaTester, let betaGroups):
let email = betaTester.email ?? ""
let groupNames = betaGroups.compactMap(\.groupName).joined(separator: ", ")
let bundleIds = betaGroups.compactMap(\.app?.bundleId).joined(separator: ", ")
return "Beta Tester with email: \(email) " +
"will be \(operation) groups: \(groupNames) " +
"in apps: \(bundleIds)"
}
}
}
let changes: [Change]
init(local: TestFlightProgram, remote: TestFlightProgram) {
var changes: [Change] = []
// Groups
let localGroups = local.groups
let groupsToAdd: [BetaGroup] = localGroups.filter { $0.id == nil }
changes += groupsToAdd.map(Change.addBetaGroup)
let localGroupIds = localGroups.map(\.id)
let groupsToRemove: [BetaGroup] = remote.groups
.filter { group in localGroupIds.contains(group.id) == false }
changes += groupsToRemove.map(Change.removeBetaGroup)
// Testers
let newTesters = local.testers.filter { !remote.testers.map(\.email).contains($0.email) }
changes += newTesters.map { betaTester -> Change in
betaTester.betaGroups.isEmpty
? .addBetaTesterToApps(betaTester, betaTester.apps)
: .addBetaTesterToGroups(betaTester, betaTester.betaGroups)
}
for remoteTester in remote.testers {
let remoteApps = remoteTester.apps
let remoteBetaGroups = remoteTester.betaGroups
if let localTester = local.testers.first(where: { $0.email == remoteTester.email }) {
let appsToAdd = localTester.apps.filter { app in
let appIds = remoteApps.map(\.id) + remoteBetaGroups.compactMap(\.app?.id)
return appIds.contains(app.id) == false
}
let addToApps = Change.addBetaTesterToApps(remoteTester, appsToAdd)
changes += appsToAdd.isNotEmpty ? [addToApps] : []
let groupsToAdd = localTester.betaGroups
.filter { !remoteBetaGroups.map(\.id).contains($0.id) }
let addToGroups = Change.addBetaTesterToGroups(remoteTester, groupsToAdd)
changes += groupsToAdd.isNotEmpty ? [addToGroups] : []
let appsToRemove = remoteApps.filter { app in
let appIds = localTester.apps.map(\.id) + localTester.betaGroups.compactMap(\.app?.id)
return appIds.contains(app.id) == false
}
let removeFromApps = Change.removeBetaTesterFromApps(remoteTester, appsToRemove)
changes += appsToRemove.isNotEmpty ? [removeFromApps] : []
let groupsToRemove = remoteBetaGroups
.filter { !localTester.betaGroups.map(\.id).contains($0.id) }
let removeFromGroups = Change.removeBetaTesterFromGroups(remoteTester, groupsToRemove)
changes += groupsToRemove.isNotEmpty ? [removeFromGroups] : []
} else if remoteApps.isNotEmpty {
changes.append(.removeBetaTesterFromApps(remoteTester, remoteApps))
}
}
self.changes = changes
}
}
| 42.594828 | 106 | 0.591783 |
29d0b3abd8866b0fdd061255361d49fe705b0c3a | 474 | //
// RSEnhancedInstructionStep.swift
// Pods
//
// Created by James Kizer on 7/30/17.
//
//
import UIKit
import ResearchKit
open class RSEnhancedInstructionStep: RSStep {
override open func stepViewControllerClass() -> AnyClass {
return RSEnhancedInstructionStepViewController.self
}
open var gif: UIImage?
open var gifURL: URL?
open var image: UIImage?
open var audioTitle: String?
open var moveForwardOnTap: Bool = false
}
| 18.96 | 62 | 0.698312 |
4b71d9c8bee51acd0015a9425134e27bfe57a2f1 | 1,107 | import Carbon.HIToolbox
import Foundation
class EditorModeInsert: EditorMode {
let mode: Mode = .insert
weak var modeSwitcher: EditorModeSwitcher?
let operationMemory: OperationMemory
let currentFreeTextCommand: FreeTextOperation
/// Text is recorded to create a repeatable command
var recordedText: String = ""
init(modeSwitcher: EditorModeSwitcher, freeTextCommand: FreeTextOperation, operationMemory: OperationMemory) {
self.modeSwitcher = modeSwitcher
self.currentFreeTextCommand = freeTextCommand
self.operationMemory = operationMemory
}
func handleKeyEvent(_ keyEvent: KeyEvent, simulateKeyPress: SimulateKeyPress) -> Bool {
guard keyEvent.event == .down else {
return false
}
if keyEvent.key.keycode == kVK_Escape {
operationMemory.mostRecentCommand = currentFreeTextCommand.createOperation(string: recordedText)
modeSwitcher?.switchToCommandMode()
return true
}
recordedText.append(String(keyEvent.key.char))
return false
}
}
| 29.918919 | 114 | 0.698284 |
ebd61b5c7a4cea23a0212d82b74903094e8508b3 | 1,199 | //
// TSEnemy.swift
// TestSTG4
//
// Created by Wenqing Ge on 2021/4/17.
//
import Foundation
import SpriteKit
/**
A TSObject with health
*/
class TSEnemy: TSObject{
var hp: Double
var hitboxP: Double
var hitboxB: Double
var display: SKSpriteNode = SKSpriteNode()
var autoFree = true
init(hp: Double, playerHitbox: Double, bulletHitbox: Double){
self.hp=hp
self.hitboxP=playerHitbox
self.hitboxB=bulletHitbox
super.init()
position=CGPoint(x: -1000, y: -1000)
self.display.position=CGPoint(x: 0, y: 0)
display.texture=SKTexture(imageNamed: "testEnemy")
display.size=CGSize(width: 32, height: 32)
addChild(display)
}
/**
Delete this enemy ELEGANTLY
*/
func delete(){
alive=false
run(SKAction.sequence([
SKAction.group([
SKAction.scale(to: 5, duration: 0.1),
SKAction.fadeOut(withDuration: 0.1)
]),
SKAction.removeFromParent()
]))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 22.622642 | 65 | 0.576314 |
1c123d03481c105242e3e422b9a961ac81bc943a | 6,598 | import Foundation
enum Nodes {
static func transfer<Instance: AnyObject>(from lhs: Node<Instance>, to rhs: inout Node<Instance>) {
rhs.reusableInstance = rhs.reusableInstance ?? lhs.reusableInstance
guard !lhs.children.isEmpty else {
return
}
rhs.updateChildren {
recursiveTransferChildren(from: lhs.children, to: &$0)
}
}
static func recursiveTransferChildren<Instance: AnyObject>(from lhs: [Node<Instance>], to rhs: inout [Node<Instance>]) {
precondition(lhs.count == rhs.count)
(0..<lhs.count).forEach { index in
transfer(from: lhs[index], to: &rhs[index])
}
}
static func hasSameHierarchy<Instance: AnyObject>(_ lhs: Node<Instance>, _ rhs: Node<Instance>) -> Bool {
(lhs.name == rhs.name) &&
lhs.children.count == rhs.children.count &&
zip(lhs.children, rhs.children).allSatisfy({ hasSameHierarchy($0.0, $0.1) })
}
}
struct Node<Instance: AnyObject> {
private(set) var children: [Node<Instance>] = []
fileprivate var reusableInstance: Instance?
private(set) var name: String = ""
private(set) var values: AnyEquatable?
private var createInstanceCallback: () -> Instance
private var updateInstanceCallbacks: [(Instance, Any?) -> Void]
private(set) var transformInstanceCallback: ((Instance) -> Instance)?
private(set) var isDirty: Bool = false
init<Value: Equatable>(
name: String,
valueType: Value.Type,
values: Value?,
create: @escaping (() -> Instance),
transform: ((Instance) -> Instance)? = nil,
update: ((Instance, Value) -> Void)?
) {
self.name = name
self.createInstanceCallback = create
self.transformInstanceCallback = transform
if Value.self != Never.self {
self.updateInstanceCallbacks = [{ update?($0, $1 as! Value) }]
self.values = values.map(AnyEquatable.init(value:))
} else {
self.updateInstanceCallbacks = []
self.values = nil
}
}
init<Value: Equatable>(
name: String,
values: Value,
create: @escaping (() -> Instance),
transform: ((Instance) -> Instance)? = nil,
update: @escaping (Instance, Value) -> Void
) {
self.init(
name: name,
valueType: Value.self,
values: values,
create: create,
transform: transform,
update: update
)
}
init<Value: Equatable>(
name: String,
valueType: Value.Type,
create: @escaping (() -> Instance),
transform: ((Instance) -> Instance)? = nil
) {
self.init(
name: name,
valueType: valueType,
values: nil,
create: create,
transform: transform,
update: nil
)
}
mutating func modify(_ body: @escaping (Instance, Any?) -> Void) {
updateInstanceCallbacks.append(body)
}
mutating func updateInstanceIfNeeded() {
guard let instance = reusableInstance else {
return
}
let value = values?.base
updateInstanceCallbacks.forEach { body in
body(instance, value)
}
}
mutating func markDirty() {
isDirty = true
}
mutating private func _mapChildren<T>(_ block: (inout [Node<Instance>]) -> T, callBack: (T) -> Void) {
let oldValue = self
var newValue = self
var result: Any?
if T.self == Void.self {
_ = block(&newValue.children)
} else {
result = block(&newValue.children)
}
if Nodes.hasSameHierarchy(oldValue, newValue) {
if oldValue != newValue {
Nodes.transfer(from: oldValue, to: &newValue)
}
}
self = newValue
if T.self == Void.self {
callBack(() as! T)
} else {
callBack(result! as! T)
}
}
mutating func updateChildren(_ block: (inout [Node<Instance>]) -> Void) {
_mapChildren(block, callBack: { _ in })
}
mutating func mapChildren<T>(_ block: (inout [Node<Instance>]) -> T) -> T {
var result: T?
_mapChildren(block, callBack: { result = $0 })
return result!
}
mutating func makeInstance() -> Instance {
let view = reusableInstance ?? createInstanceCallback()
if reusableInstance !== view {
reusableInstance = view
}
return view
}
}
extension Node: Equatable {
static func == (lhs: Node, rhs: Node) -> Bool {
lhs.reusableInstance === rhs.reusableInstance && (lhs.name, lhs.values, lhs.children) == (rhs.name, rhs.values, rhs.children)
}
}
/// DEBUG
extension Node {
private func makeNodeDescription() -> NodeDescription {
var node = NodeDescription(name: self.name)
node.children = children.map({ $0.makeNodeDescription() })
return node
}
func tree() -> String {
makeNodeDescription().description
}
}
struct NodeDescription: CustomStringConvertible {
struct Feature: OptionSet {
let rawValue: Int
static let isRoot = Feature(rawValue: 1 << 0)
static let isLeaf = Feature(rawValue: 1 << 1)
static let isFirst = Feature(rawValue: 1 << 3)
static let isLast = Feature(rawValue: 1 << 4)
}
var name: String
var children: [NodeDescription] = []
private func _tree(indent: Int, features: Feature, environment: [Int]) -> String {
var environment0 = environment
let children = self.children
let prefix: String
if features.contains(.isRoot) {
prefix = ""
} else if features.contains(.isLeaf) {
if features.contains(.isLast) {
prefix = "└─"
} else {
prefix = "├─"
}
} else {
if features.contains(.isLast) {
prefix = "└┬"
if !environment0.isEmpty {
environment0.removeLast()
}
} else {
prefix = "├┬"
}
environment0.append(indent + 1)
}
var currentValue = "\(String(repeating: " ", count: indent))\(prefix)\(name)"
environment.forEach { offset in
guard offset != indent else {
return
}
currentValue.replaceSubrange(
currentValue.index(currentValue.startIndex, offsetBy: offset)..<currentValue.index(currentValue.startIndex, offsetBy: offset + 1),
with: "│"
)
}
if children.isEmpty {
return currentValue
}
let count = children.count
var strings: [String] = children.enumerated().map({
let (offset, node) = $0
let features0: Feature = [offset == 0 ? .isFirst : [], offset == count - 1 ? .isLast : [], node.children.isEmpty ? .isLeaf : []]
return node._tree(indent: indent + 1, features: features0, environment: environment0)
})
strings.insert(currentValue, at: 0)
return strings.joined(separator: "\n")
}
var description: String {
_tree(indent: 0, features: [.isRoot, children.isEmpty ? .isLeaf : []], environment: [])
}
}
| 30.688372 | 138 | 0.62428 |
21015f17dbc455b26ab1ac2581f0134ea53aa81e | 2,758 | //
// MerchantsClose.swift
// Units
//
// Created by on 17.10.2019.
// Copyright © 2019 Multinet. All rights reserved.
//
import UIKit
public protocol MerchantsCloseToMeProtocol {
func tappedRequestLocationPermission()
func tappedRestaurant(restaurant: Merchant)
}
public class MerchantsCloseToMe: UIView {
public var delegate: MerchantsCloseToMeProtocol?
public var showUnitTitle: Bool = true
var authorizedStateView: MerchantsCloseToMeAuthorizedState?
var notAuthorizedStateView: MerchantsCloseToMeUnauthorizedState?
var locationGestureRecognizer: UITapGestureRecognizer?
public var merchants: [Merchant]? {
didSet {
if authorizedStateView == nil || authorizedStateView != nil && !authorizedStateView!.isDescendant(of: self) {
initAuthorizedState()
}
authorizedStateView?.merchants = self.merchants
}
}
public override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
initViews()
}
func initViews() {
if ((Service.getLocationManager()?.isAuthorized()) != nil) {
initAuthorizedState()
} else {
initNotAuthorizedState()
}
}
public func initAuthorizedState() {
if notAuthorizedStateView != nil {
notAuthorizedStateView!.removeFromSuperview()
if let locationGestureRecognizer = locationGestureRecognizer {
self.removeGestureRecognizer(locationGestureRecognizer)
}
notAuthorizedStateView = nil
}
authorizedStateView = MerchantsCloseToMeAuthorizedState().then {[weak self] in
guard let self = self else { return }
$0.delegate = self.delegate
}
authorizedStateView!.translatesAutoresizingMaskIntoConstraints = false
addSubview(authorizedStateView!)
authorizedStateView!.bindFrameToSuperviewBounds()
}
public func initNotAuthorizedState() {
if authorizedStateView != nil {
authorizedStateView!.removeFromSuperview()
authorizedStateView = nil
}
notAuthorizedStateView = MerchantsCloseToMeUnauthorizedState(showTitle: showUnitTitle)
notAuthorizedStateView!.translatesAutoresizingMaskIntoConstraints = false
addSubview(notAuthorizedStateView!)
notAuthorizedStateView!.bindFrameToSuperviewBounds()
self.locationGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tappedRequestLocation))
self.addGestureRecognizer(self.locationGestureRecognizer!)
}
@objc func tappedRequestLocation() {
delegate?.tappedRequestLocationPermission()
}
}
| 32.447059 | 121 | 0.68673 |
2f23cdcf7a0ff38523ed82919b75f7b90e0b46a1 | 1,085 | import Foundation
//func maxArea(_ height: [Int]) -> Int {
// var maxCapacity = 0
// for (index1, h1) in height.enumerated() {
// var lastSideLength = 0
// for (index2, h2) in height.enumerated().reversed() {
// if index2 > index1 {
// if h2 > lastSideLength {
// let currentCapacity = min(h1, h2) * (index2 - index1)
// if currentCapacity > maxCapacity {
// maxCapacity = currentCapacity
// }
// lastSideLength = h2
// }
// }
// }
// }
// return maxCapacity
//}
func maxArea(_ height: [Int]) -> Int {
var maxCapacity = 0, left = 0, right = height.count - 1
while left < right {
let minHeight = min(height[left], height[right])
maxCapacity = max(maxCapacity, minHeight * (right - left))
if height[left] < height[right] {
left += 1
} else {
right -= 1
}
}
return maxCapacity
}
var height = [4,3,2,1,4]
maxArea(height)
| 28.552632 | 76 | 0.489401 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.