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
|
---|---|---|---|---|---|
5db520483a1e247ce802bbe152cd2fa0d93b7287
| 1,225 |
import Foundation
/**
Count and Say
Tags: String
https://leetcode.com/problems/count-and-say/
*/
/// 这道题主要把题意读对. 题意为按顺序计算重复的数并且"读"出该数的数值来. 即先计算重复的数的个数, 然后再拼接上该数本身.
class Solution {
func countAndSay(_ n: Int) -> String {
if n >= 1 {
var times = 1
var result = [Character("1")]
while times < n {
var i = 0
var temp: [Character] = []
while i < result.count {
let value = result[i]
var count = 1
while i + count < result.count && result[i] == result[i + count] {
count += 1
}
// 先count, 即出现该value的个数. 然后say, 即该value
temp.append(Character("\(count)"))
temp.append(Character("\(value)"))
i += count
}
result = temp
times += 1
}
return String(result)
}
return ""
}
}
Solution().countAndSay(1)
Solution().countAndSay(2)
Solution().countAndSay(3)
Solution().countAndSay(4)
Solution().countAndSay(5)
Solution().countAndSay(6)
Solution().countAndSay(7)
| 26.06383 | 86 | 0.473469 |
26dd7faee7aaf22f2c0a7240f70a49046765e31c
| 1,200 |
//
// TabBarController.swift
// BeiDou
//
// Created by Jyer on 2017/2/11.
// Copyright © 2017年 zjyzbfxgxzh. All rights reserved.
//
import UIKit
class TabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
for item:UITabBarItem in self.tabBar.items! {
let image = item.image
let selectImage = item.selectedImage
item.image = image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
item.selectedImage = selectImage?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 27.906977 | 106 | 0.666667 |
dea1ca2ca35566787818b86b9ccaf3d5e38c9ccd
| 6,592 |
import Flutter
import UIKit
import AuthenticationServices
import SafariServices
public class SwiftKakaoFlutterSdkPlugin: NSObject, FlutterPlugin, ASWebAuthenticationPresentationContextProviding {
var result: FlutterResult? = nil
var redirectUri: String? = nil
var authorizeTalkCompletionHandler : ((URL?, FlutterError?) -> Void)?
public static func register(with registrar: FlutterPluginRegistrar) {
NSLog("nslog register")
let channel = FlutterMethodChannel(name: "kakao_flutter_sdk", binaryMessenger: registrar.messenger())
let instance = SwiftKakaoFlutterSdkPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
registrar.addApplicationDelegate(instance) // This is necessary to receive open iurl delegate method.
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getOrigin":
result(Utility.origin())
case "getKaHeader":
result(Utility.kaHeader())
case "launchBrowserTab":
let args = call.arguments as! Dictionary<String, String>
let url = args["url"]
let redirectUri = args["redirect_uri"]
launchBrowserTab(url: url!, redirectUri: redirectUri, result: result)
case "authorizeWithTalk":
let args = call.arguments as! Dictionary<String, String>
let clientId = args["client_id"]
let redirectUri = args["redirect_uri"]
authorizeWithTalk(clientId: clientId!, redirectUri: redirectUri!, result: result)
case "isKakaoTalkInstalled":
guard let talkUrl = URL(string: "kakaokompassauth://authorize") else {
result(false)
return
}
result(UIApplication.shared.canOpenURL(talkUrl))
case "launchKakaoTalk":
let args = call.arguments as! Dictionary<String, String>
let uri = args["uri"]
launchKakaoTalk(uri: uri!, result: result)
default:
result(FlutterMethodNotImplemented)
}
}
private func launchKakaoTalk(uri: String, result: @escaping FlutterResult) {
let urlObject = URL(string: uri)!
if (UIApplication.shared.canOpenURL(urlObject)) {
UIApplication.shared.open(urlObject, options: [:]) { (openResult) in
result(openResult)
}
}
}
private func authorizeWithTalk(clientId: String, redirectUri: String, result: @escaping FlutterResult) {
self.result = result
self.redirectUri = redirectUri
self.authorizeTalkCompletionHandler = {
(callbackUrl:URL?, error: FlutterError?) in
guard error == nil else {
//TODO:error wrapping check
result(error)
return
}
guard let callbackUrl = callbackUrl else {
//TODO:error type check
result(FlutterError(code: "REDIRECT_URL_MISMATCH", message: "No callback url. This is probably a bug in Kakao Flutter SDK.", details: nil))
return
}
result(callbackUrl.absoluteString)
return
}
var parameters = [String:String]()
parameters["client_id"] = clientId
parameters["redirect_uri"] = redirectUri
parameters["response_type"] = "code"
guard let url = Utility.makeUrlWithParameters("kakaokompassauth://authorize", parameters: parameters) else {
result(FlutterError(code: "makeURL", message: "This is probably a bug in Kakao Flutter SDK.", details: nil))
return
}
UIApplication.shared.open(url, options: [:]) { (openResult) in
if (!openResult) {
result(FlutterError(code: "OPEN_URL_ERROR", message: "Failed to open KakaoTalk.", details: nil))
}
}
}
private func launchBrowserTab(url: String, redirectUri: String?, result: @escaping FlutterResult) {
var keepMe: Any? = nil
let completionHandler = { (url: URL?, err: Error?) in
keepMe = nil
if let err = err {
if #available(iOS 12, *) {
if case ASWebAuthenticationSessionError.Code.canceledLogin = err {
result(FlutterError(code: "CANCELED", message: "User canceled login.", details: nil))
return
}
} else {
if case SFAuthenticationError.Code.canceledLogin = err {
result(FlutterError(code: "CANCELED", message: "User canceled login.", details: nil))
return
}
}
result(FlutterError(code: "EUNKNOWN", message: err.localizedDescription, details: nil))
return
}
result(url?.absoluteString)
}
let urlObject = URL(string: url)!
let redirectUriObject: URL? = redirectUri == nil ? nil : URL(string: redirectUri!)
if #available(iOS 12, *) {
let session = ASWebAuthenticationSession(url: urlObject, callbackURLScheme: redirectUriObject?.scheme, completionHandler: completionHandler)
if #available(iOS 13.0, *) {
session.presentationContextProvider = self
}
session.start()
keepMe = session
} else {
let session = SFAuthenticationSession(url: urlObject, callbackURLScheme: redirectUriObject?.scheme, completionHandler: completionHandler)
session.start()
keepMe = session
}
}
public func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
guard let finalRedirectUri = self.redirectUri else {
self.authorizeTalkCompletionHandler?(nil, FlutterError(code: "EUNKNOWN", message: "No redirect uri to compare. This is probably a bug in Kakao Flutter SDK.", details: nil))
return true
}
if (url.absoluteString.hasPrefix(finalRedirectUri)) {
self.authorizeTalkCompletionHandler?(url, nil)
return true
}
self.authorizeTalkCompletionHandler?(nil, FlutterError(code: "REDIRECT_URL_MISMATCH", message: "Expected: \(finalRedirectUri), Actual: \(url.absoluteString)", details: nil))
return true
}
@available(iOS 12.0, *)
public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
return UIApplication.shared.keyWindow ?? ASPresentationAnchor()
}
}
| 43.084967 | 184 | 0.623028 |
ef80daea158cb8d48e99b3008d32252c25b338fd
| 5,110 |
//
// MenuViewController.swift
// Twitter
//
// Created by Marcel Weekes on 2/25/16.
// Copyright © 2016 Marcel Weekes. All rights reserved.
//
import UIKit
let NUM_SECTIONS = 2
let TIMELINE_SECTION = 0
let ACCOUNT_SECTION = 1
class MenuViewController: UIViewController {
@IBOutlet weak private var tableView: UITableView!
private var profileNavigationController: UINavigationController!
private var homeNavigationController: UINavigationController!
private var mentionsNavigationController: UINavigationController!
private var viewControllerTitles = ["Profile", "Home", "Mentions"]
private var viewControllers: [UIViewController] = []
var hamburgerViewController: HamburgerViewController!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
setUpMenuItemViewControllers()
// initial view controller
hamburgerViewController.contentViewController = homeNavigationController
}
private func setUpMenuItemViewControllers() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
profileNavigationController = storyboard.instantiateViewControllerWithIdentifier("TimelineNavigationController") as! UINavigationController
let profileVC = profileNavigationController.topViewController as! TweetsViewController
profileVC.timelineType = TweetsViewController.TimelineType.User
homeNavigationController = storyboard.instantiateViewControllerWithIdentifier("TimelineNavigationController") as! UINavigationController
let homeVC = homeNavigationController.topViewController as! TweetsViewController
homeVC.timelineType = TweetsViewController.TimelineType.Home
mentionsNavigationController = storyboard.instantiateViewControllerWithIdentifier("TimelineNavigationController") as! UINavigationController
let mentionsVC = mentionsNavigationController.topViewController as! TweetsViewController
mentionsVC.timelineType = TweetsViewController.TimelineType.Mentions
viewControllers.append(profileNavigationController)
viewControllers.append(homeNavigationController)
viewControllers.append(mentionsNavigationController)
}
private func logoutUser() {
if let user = User.currentUser {
let alertVC = UIAlertController(title: user.screenname, message: "Are you sure you want to sign out of Twitter?", preferredStyle: .Alert)
let logoutAction = UIAlertAction(title: "Sign out", style: .Default) { (action) in
user.logout()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// dismiss
}
alertVC.addAction(logoutAction)
alertVC.addAction(cancelAction)
hamburgerViewController.presentViewController(alertVC, animated: true, completion: nil)
}
}
/*
// 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.
}
*/
}
// MARK: - UITableViewDataSource
extension MenuViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// account section
if section == ACCOUNT_SECTION {
return 1
}
return viewControllers.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MenuItemCell")! as UITableViewCell
// account section
if indexPath.section == ACCOUNT_SECTION {
cell.textLabel?.text = "Sign out"
} else {
cell.textLabel?.text = viewControllerTitles[indexPath.row]
}
return cell
}
// MARK: - static table view
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return NUM_SECTIONS
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == TIMELINE_SECTION {
return "Timelines"
} else {
return "Account"
}
}
}
// MARK: - UITableViewDelegate
extension MenuViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.section == TIMELINE_SECTION {
hamburgerViewController.contentViewController = viewControllers[indexPath.row]
} else if indexPath.section == ACCOUNT_SECTION {
logoutUser()
}
}
}
| 35 | 149 | 0.691194 |
1ee4b57ab7a174f849c4d96644385d63e9e0248c
| 18,186 |
//
// YPLibraryVC.swift
// YPImagePicker
//
// Created by Sacha Durand Saint Omer on 27/10/16.
// Copyright © 2016 Yummypets. All rights reserved.
//
import UIKit
import Photos
public class YPLibraryVC: UIViewController, YPPermissionCheckable {
internal weak var delegate: YPLibraryViewDelegate?
internal var v: YPLibraryView!
internal var isProcessing = false // true if video or image is in processing state
internal var multipleSelectionEnabled = false
internal var initialized = false
internal var selection = [YPLibrarySelection]()
internal var currentlySelectedIndex: Int = 0
internal let mediaManager = LibraryMediaManager()
internal var latestImageTapped = ""
internal let panGestureHelper = PanGestureHelper()
// MARK: - Init
public required init() {
super.init(nibName: nil, bundle: nil)
title = YPConfig.wordings.libraryTitle
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setAlbum(_ album: YPAlbum) {
mediaManager.collection = album.collection
resetMultipleSelection()
}
private func resetMultipleSelection() {
selection.removeAll()
currentlySelectedIndex = 0
multipleSelectionEnabled = false
v.assetViewContainer.setMultipleSelectionMode(on: false)
delegate?.libraryViewDidToggleMultipleSelection(enabled: false)
checkLimit()
}
func initialize() {
mediaManager.initialize()
mediaManager.v = v
if mediaManager.fetchResult != nil {
return
}
setupCollectionView()
registerForLibraryChanges()
panGestureHelper.registerForPanGesture(on: v)
registerForTapOnPreview()
refreshMediaRequest()
v.assetViewContainer.multipleSelectionButton.isHidden = !(YPConfig.library.maxNumberOfItems > 1)
v.maxNumberWarningLabel.text = String(format: YPConfig.wordings.warningMaxItemsLimit, YPConfig.library.maxNumberOfItems)
}
// MARK: - View Lifecycle
public override func loadView() {
v = YPLibraryView.xibView()
view = v
}
public override func viewDidLoad() {
super.viewDidLoad()
// When crop area changes in multiple selection mode,
// we need to update the scrollView values in order to restore
// them when user selects a previously selected item.
v.assetZoomableView.cropAreaDidChange = { [weak self] in
guard let strongSelf = self else {
return
}
if strongSelf.multipleSelectionEnabled {
strongSelf.updateCropInfo()
}
}
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
v.assetViewContainer.squareCropButton
.addTarget(self,
action: #selector(squareCropButtonTapped),
for: .touchUpInside)
v.assetViewContainer.multipleSelectionButton
.addTarget(self,
action: #selector(multipleSelectionButtonTapped),
for: .touchUpInside)
// Forces assetZoomableView to have a contentSize.
// otherwise 0 in first selection triggering the bug : "invalid image size 0x0"
// Also fits the first element to the square if the onlySquareFromLibrary = true
if !YPConfig.library.onlySquare && v.assetZoomableView.contentSize == CGSize(width: 0, height: 0) {
v.assetZoomableView.setZoomScale(1, animated: false)
}
// Activate multiple selection when using `minNumberOfItems`
if YPConfig.library.minNumberOfItems > 1 {
multipleSelectionButtonTapped()
}
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
pausePlayer()
NotificationCenter.default.removeObserver(self)
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}
// MARK: - Crop control
@objc
func squareCropButtonTapped() {
doAfterPermissionCheck { [weak self] in
self?.v.assetViewContainer.squareCropButtonTapped()
}
}
// MARK: - Multiple Selection
@objc
func multipleSelectionButtonTapped() {
// Prevent desactivating multiple selection when using `minNumberOfItems`
if YPConfig.library.minNumberOfItems > 1 && multipleSelectionEnabled {
return
}
multipleSelectionEnabled = !multipleSelectionEnabled
if multipleSelectionEnabled {
if selection.isEmpty {
selection = [
YPLibrarySelection(index: currentlySelectedIndex,
cropRect: v.currentCropRect(),
scrollViewContentOffset: v.assetZoomableView!.contentOffset,
scrollViewZoomScale: v.assetZoomableView!.zoomScale)
]
}
} else {
selection.removeAll()
}
v.assetViewContainer.setMultipleSelectionMode(on: multipleSelectionEnabled)
v.collectionView.reloadData()
checkLimit()
delegate?.libraryViewDidToggleMultipleSelection(enabled: multipleSelectionEnabled)
}
// MARK: - Tap Preview
func registerForTapOnPreview() {
let tapImageGesture = UITapGestureRecognizer(target: self, action: #selector(tappedImage))
v.assetViewContainer.addGestureRecognizer(tapImageGesture)
}
@objc
func tappedImage() {
if !panGestureHelper.isImageShown {
panGestureHelper.resetToOriginalState()
// no dragup? needed? dragDirection = .up
v.refreshImageCurtainAlpha()
}
}
// MARK: - Permissions
func doAfterPermissionCheck(block:@escaping () -> Void) {
checkPermissionToAccessPhotoLibrary { hasPermission in
if hasPermission {
block()
}
}
}
func checkPermission() {
checkPermissionToAccessPhotoLibrary { [weak self] hasPermission in
guard let strongSelf = self else {
return
}
if hasPermission && !strongSelf.initialized {
strongSelf.initialize()
strongSelf.initialized = true
}
}
}
// Async beacause will prompt permission if .notDetermined
// and ask custom popup if denied.
func checkPermissionToAccessPhotoLibrary(block: @escaping (Bool) -> Void) {
// Only intilialize picker if photo permission is Allowed by user.
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .authorized:
block(true)
case .restricted, .denied:
let popup = YPPermissionDeniedPopup()
let alert = popup.popup(cancelBlock: {
block(false)
})
present(alert, animated: true, completion: nil)
case .notDetermined:
// Show permission popup and get new status
PHPhotoLibrary.requestAuthorization { s in
DispatchQueue.main.async {
block(s == .authorized)
}
}
}
}
func refreshMediaRequest() {
let options = buildPHFetchOptions()
if let collection = mediaManager.collection {
mediaManager.fetchResult = PHAsset.fetchAssets(in: collection, options: options)
} else {
mediaManager.fetchResult = PHAsset.fetchAssets(with: options)
}
if mediaManager.fetchResult.count > 0 {
changeAsset(mediaManager.fetchResult[0])
v.collectionView.reloadData()
v.collectionView.selectItem(at: IndexPath(row: 0, section: 0),
animated: false,
scrollPosition: UICollectionViewScrollPosition())
}
scrollToTop()
}
func buildPHFetchOptions() -> PHFetchOptions {
// Sorting condition
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
options.predicate = YPConfig.library.mediaType.predicate()
return options
}
func scrollToTop() {
tappedImage()
v.collectionView.contentOffset = CGPoint.zero
}
// MARK: - ScrollViewDelegate
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == v.collectionView {
mediaManager.updateCachedAssets(in: self.v.collectionView)
}
}
func changeAsset(_ asset: PHAsset) {
mediaManager.selectedAsset = asset
latestImageTapped = asset.localIdentifier
delegate?.libraryViewStartedLoading()
let completion = {
self.v.hideLoader()
self.v.hideGrid()
self.delegate?.libraryViewFinishedLoading()
self.v.assetViewContainer.refreshSquareCropButton()
}
DispatchQueue.global(qos: .userInitiated).async {
switch asset.mediaType {
case .image:
self.v.assetZoomableView.setImage(asset,
mediaManager: self.mediaManager,
storedCropPosition: self.fetchStoredCrop(),
completion: completion)
case .video:
self.v.assetZoomableView.setVideo(asset,
mediaManager: self.mediaManager,
storedCropPosition: self.fetchStoredCrop(),
completion: completion)
case .audio, .unknown:
()
}
}
}
// MARK: - Verification
private func fitsVideoLengthLimits(asset: PHAsset) -> Bool {
guard asset.mediaType == .video else {
return true
}
let tooLong = asset.duration > YPConfig.video.libraryTimeLimit
let tooShort = asset.duration < YPConfig.video.minimumTimeLimit
if tooLong || tooShort {
DispatchQueue.main.async {
let alert = tooLong ? YPAlert.videoTooLongAlert() : YPAlert.videoTooShortAlert()
self.present(alert, animated: true, completion: nil)
}
return false
}
return true
}
// MARK: - Stored Crop Position
internal func updateCropInfo(shouldUpdateOnlyIfNil: Bool = false) {
guard let selectedAssetIndex = selection.index(where: { $0.index == currentlySelectedIndex }) else {
return
}
if shouldUpdateOnlyIfNil && selection[selectedAssetIndex].scrollViewContentOffset != nil {
return
}
// Fill new values
var selectedAsset = selection[selectedAssetIndex]
selectedAsset.scrollViewContentOffset = v.assetZoomableView.contentOffset
selectedAsset.scrollViewZoomScale = v.assetZoomableView.zoomScale
selectedAsset.cropRect = v.currentCropRect()
// Replace
selection.remove(at: selectedAssetIndex)
selection.insert(selectedAsset, at: selectedAssetIndex)
}
internal func fetchStoredCrop() -> YPLibrarySelection? {
if self.multipleSelectionEnabled,
self.selection.contains(where: { $0.index == self.currentlySelectedIndex }) {
guard let selectedAssetIndex = self.selection
.index(where: { $0.index == self.currentlySelectedIndex }) else {
return nil
}
return self.selection[selectedAssetIndex]
}
return nil
}
internal func hasStoredCrop(index: Int) -> Bool {
return self.selection.contains(where: { $0.index == index })
}
// MARK: - Fetching Media
private func fetchImageAndCrop(for asset: PHAsset,
withCropRect: CGRect? = nil,
callback: @escaping (_ photo: UIImage, _ exif: [String : Any]) -> Void) {
delegate?.libraryViewStartedLoading()
let cropRect = withCropRect ?? DispatchQueue.main.sync { v.currentCropRect() }
let ts = targetSize(for: asset, cropRect: cropRect)
mediaManager.imageManager?.fetchImage(for: asset, cropRect: cropRect, targetSize: ts, callback: callback)
}
private func checkVideoLengthAndCrop(for asset: PHAsset,
withCropRect: CGRect? = nil,
callback: @escaping (_ videoURL: URL) -> Void) {
if fitsVideoLengthLimits(asset: asset) == true {
delegate?.libraryViewStartedLoading()
let normalizedCropRect = withCropRect ?? DispatchQueue.main.sync { v.currentCropRect() }
let ts = targetSize(for: asset, cropRect: normalizedCropRect)
let xCrop: CGFloat = normalizedCropRect.origin.x * CGFloat(asset.pixelWidth)
let yCrop: CGFloat = normalizedCropRect.origin.y * CGFloat(asset.pixelHeight)
let resultCropRect = CGRect(x: xCrop,
y: yCrop,
width: ts.width,
height: ts.height)
mediaManager.fetchVideoUrlAndCrop(for: asset, cropRect: resultCropRect, callback: callback)
}
}
public func selectedMedia(photoCallback: @escaping (_ photo: UIImage, _ exifMeta : [String : Any]?) -> Void,
videoCallback: @escaping (_ videoURL: URL) -> Void,
multipleItemsCallback: @escaping (_ items: [YPMediaItem]) -> Void) {
DispatchQueue.global(qos: .userInitiated).async {
// Multiple selection
if self.multipleSelectionEnabled && self.selection.count > 1 {
let selectedAssets: [(asset: PHAsset, cropRect: CGRect?)] = self.selection.map {
return (self.mediaManager.fetchResult[$0.index], $0.cropRect)
}
// Check video length
for asset in selectedAssets {
if self.fitsVideoLengthLimits(asset: asset.asset) == false {
return
}
}
// Fill result media items array
var resultMediaItems: [YPMediaItem] = []
let asyncGroup = DispatchGroup()
for asset in selectedAssets {
asyncGroup.enter()
switch asset.asset.mediaType {
case .image:
self.fetchImageAndCrop(for: asset.asset, withCropRect: asset.cropRect) { image, exifMeta in
let photo = YPMediaPhoto(image: image.resizedImageIfNeeded(), exifMeta: exifMeta)
resultMediaItems.append(YPMediaItem.photo(p: photo))
asyncGroup.leave()
}
case .video:
self.checkVideoLengthAndCrop(for: asset.asset, withCropRect: asset.cropRect) { videoURL in
let videoItem = YPMediaVideo(thumbnail: thumbnailFromVideoPath(videoURL),
videoURL: videoURL)
resultMediaItems.append(YPMediaItem.video(v: videoItem))
asyncGroup.leave()
}
default:
break
}
}
asyncGroup.notify(queue: .main) {
multipleItemsCallback(resultMediaItems)
self.delegate?.libraryViewFinishedLoading()
}
} else {
let asset = self.mediaManager.selectedAsset!
switch asset.mediaType {
case .video:
self.checkVideoLengthAndCrop(for: asset, callback: { videoURL in
DispatchQueue.main.async {
self.delegate?.libraryViewFinishedLoading()
videoCallback(videoURL)
}
})
case .image:
self.fetchImageAndCrop(for: asset) { image, exifMeta in
DispatchQueue.main.async {
self.delegate?.libraryViewFinishedLoading()
photoCallback(image.resizedImageIfNeeded(), exifMeta)
}
}
case .audio, .unknown:
return
}
}
}
}
// MARK: - TargetSize
private func targetSize(for asset: PHAsset, cropRect: CGRect) -> CGSize {
var width = (CGFloat(asset.pixelWidth) * cropRect.width).rounded(.toNearestOrEven)
var height = (CGFloat(asset.pixelHeight) * cropRect.height).rounded(.toNearestOrEven)
// round to lowest even number
width = (width.truncatingRemainder(dividingBy: 2) == 0) ? width : width - 1
height = (height.truncatingRemainder(dividingBy: 2) == 0) ? height : height - 1
return CGSize(width: width, height: height)
}
// MARK: - Player
func pausePlayer() {
v.assetZoomableView.videoView.pause()
}
// MARK: - Deinit
deinit {
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}
}
| 37.8875 | 128 | 0.563785 |
90530c9b6c2704363b1533f3fc3f3f1bb99705b6
| 1,631 |
// The MIT License (MIT)
//
// Copyright (c) 2015 Chris Davis
//
// 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.
//
// IAPHydrateable.swift
// InAppPurchase
//
// Created by Chris Davis on 16/12/2015.
// Copyright © 2015 nthState. All rights reserved.
//
import Foundation
// MARK: Protocol
internal protocol IAPHydrateable
{
// MARK: Methods
/**
Ensure that the class has an initalizer that takes a dictionary
*/
init(dic:NSDictionary)
/**
Ensure the class has a method which hydrates the object
*/
func hydrate(dic:NSDictionary)
}
| 33.979167 | 82 | 0.722256 |
09aff810f83e8a2c2adad265493cfc362f5a96a6
| 2,180 |
//
// AppDelegate.swift
// GetNameLogoExample
//
// Created by nipaashra on 09/22/2021.
// Copyright (c) 2021 nipaashra. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.382979 | 285 | 0.755505 |
e80d11a675da4e8725b3df420360ccc6ad4f9f19
| 3,570 |
import GRDB
enum CoinType {
static let bitcoinKey = "bitcoin_key"
static let bitcoinCashKey = "bitcoin_cash_key"
static let ethereumKey = "ethereum_key"
static let erc20Key = "erc_20_key"
case bitcoin
case bitcoinCash
case ethereum
case erc20(address: String, decimal: Int)
}
extension CoinType: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
switch self {
case .bitcoin: return CoinType.bitcoinKey.databaseValue
case .bitcoinCash: return CoinType.bitcoinCashKey.databaseValue
case .ethereum: return CoinType.ethereumKey.databaseValue
case .erc20(let address, let decimal): return "\(CoinType.erc20Key);\(address);\(decimal)".databaseValue
}
}
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CoinType? {
guard case .string(let rawValue) = dbValue.storage else {
return nil
}
switch rawValue {
case CoinType.bitcoinKey: return .bitcoin
case CoinType.bitcoinCashKey: return .bitcoinCash
case CoinType.ethereumKey: return .ethereum
case let value where rawValue.contains(CoinType.erc20Key):
let values = value.split(separator:";")
guard values.count == 3, let decimal = Int(values[2]) else {
return nil
}
return .erc20(address: String(values[1]), decimal: decimal)
default: return nil
}
}
}
struct Coin {
let title: String
let code: CoinCode
let type: CoinType
}
class StorableCoin: Record {
var coin: Coin
var enabled: Bool
var order: Int?
init(coin: Coin, enabled: Bool, order: Int?) {
self.coin = coin
self.enabled = enabled
self.order = order
super.init()
}
enum Columns: String, ColumnExpression {
case title, code, enabled, type, coinOrder
}
required init(row: Row) {
let title: String = row[Columns.title]
let code: String = row[Columns.code]
let type: CoinType = row[Columns.type]
enabled = row[Columns.enabled]
order = row[Columns.coinOrder]
coin = Coin(title: title, code: code, type: type)
super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
container[Columns.title] = coin.title
container[Columns.code] = coin.code
container[Columns.type] = coin.type
container[Columns.enabled] = enabled
container[Columns.coinOrder] = order
}
override class var databaseTableName: String {
return "coins"
}
}
extension Coin: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(code)
}
}
extension Coin: Equatable {
public static func ==(lhs: Coin, rhs: Coin) -> Bool {
return lhs.code == rhs.code && lhs.title == rhs.title && lhs.type == rhs.type
}
}
extension Coin: Comparable {
public static func <(lhs: Coin, rhs: Coin) -> Bool {
return lhs.title < rhs.title
}
}
extension CoinType: Equatable {
public static func ==(lhs: CoinType, rhs: CoinType) -> Bool {
switch (lhs, rhs) {
case (.bitcoin, .bitcoin): return true
case (.bitcoinCash, .bitcoinCash): return true
case (.ethereum, .ethereum): return true
case (.erc20(let lhsAddress, let lhsDecimal), .erc20(let rhsAddress, let rhsDecimal)):
return lhsAddress == rhsAddress && lhsDecimal == rhsDecimal
default: return false
}
}
}
| 28.110236 | 112 | 0.628852 |
147ef186207a2484a8901bcfee78feffdbb6f663
| 2,028 |
//
// SettingsTabViewController.swift
// Bunch
//
// Created by David Woodruff on 2015-08-31.
// Copyright (c) 2015 Jukeboy. All rights reserved.
//
import UIKit
import Parse
class FinishTabViewController: UIViewController, Refreshable {
@IBOutlet weak var visibilityLabel: UILabel!
@IBOutlet weak var disbandButton: UIButton!
@IBAction func disbandAction(sender: AnyObject) {
//delete bunch, remove it from map if user approves
var alertView = UIAlertController()
alertView = UIAlertController(title: "All done?", message: "This will delete the bunch", preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: nil))
alertView.addAction(UIAlertAction(title: "Finish", style: .Destructive, handler: { (alertAction) -> Void in
self.bunch.finish()
}))
presentViewController(alertView, animated: true, completion: nil)
}
var bunch: BNCBunch!
var parent: BunchTabBarController!
override func viewDidAppear(animated: Bool) {
bunch = parent.bunch
if bunch != nil {
if self.isViewLoaded() {
refresh()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func refresh() {
let bunchTime = bunch.time!
let dateformmatter:NSDateFormatter = NSDateFormatter()
dateformmatter.dateFormat = "h:mm a"
if bunch.type == "present" {
let hideTime = NSCalendar.currentCalendar().dateByAddingUnit(
.Minute,
value: 90,
toDate: bunchTime,
options: NSCalendarOptions(rawValue: 0))
visibilityLabel.text = "This bunch will automatically finish at \(dateformmatter.stringFromDate(hideTime!)) unless renewed."
} else {
visibilityLabel.text = "This bunch will automatically finish half an hour after it starts"
}
}
}
| 30.727273 | 136 | 0.619822 |
465e7b5f17226f5e7d8867af46257265570b3153
| 746 |
//
// StringPuzzles.swift
// Swift_dataStaructure
//
// Created by Albin Joseph on 11/12/21.
//
import Foundation
func isAPalindrome(_ str:String) -> Bool{
let maxIndex = str.count
let charArray = Array(str)
var isPalidrome = false
for i in 0...(maxIndex/2){
if(charArray[i] == charArray[(maxIndex-1)-i]){
isPalidrome = true
}else{
return false
}
}
return isPalidrome
}
func getFirstRepeatedChar(_ str:String) -> String {
var hashMap:[Character:Bool] = [:]
for element in str{
if let exist = hashMap[element], exist{
return String(element)
}else{
hashMap[element] = true
}
}
return "No item repeating"
}
| 21.314286 | 54 | 0.581769 |
e669dd652fe8bd069d4ffb406ba2e293b2d05836
| 2,974 |
//
// ExtensionDelegate.swift
// WatchOS Extension
//
// Created by Markus Moltke on 01/07/2020.
// Copyright © 2020 Markus Moltke. All rights reserved.
//
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillResignActive() {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, etc.
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
for task in backgroundTasks {
// Use a switch statement to check the task type
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// Be sure to complete the background task once you’re done.
backgroundTask.setTaskCompletedWithSnapshot(false)
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
// Snapshot tasks have a unique completion call, make sure to set your expiration date
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
// Be sure to complete the connectivity task once you’re done.
connectivityTask.setTaskCompletedWithSnapshot(false)
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
urlSessionTask.setTaskCompletedWithSnapshot(false)
case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask:
// Be sure to complete the relevant-shortcut task once you're done.
relevantShortcutTask.setTaskCompletedWithSnapshot(false)
case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask:
// Be sure to complete the intent-did-run task once you're done.
intentDidRunTask.setTaskCompletedWithSnapshot(false)
default:
// make sure to complete unhandled task types
task.setTaskCompletedWithSnapshot(false)
}
}
}
}
| 54.072727 | 285 | 0.699059 |
76e28d14fef79cefbb6a247707e73696d344dae1
| 241 |
//
// ___FILENAME___
// ___PROJECTNAME___
//
// Created ___FULLUSERNAME___ on ___DATE___.
// Copyright © ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
// This file was generated by Zin Lin Htet Naing.
//
import Foundation
| 20.083333 | 71 | 0.742739 |
480df709ba0b52bcfd10da08a896079bfc54857d
| 751 |
import Foundation
public struct VPNAccount {
public var type: VPNProtocolType = .IPSec
public var title: String = ""
public var server: String = ""
public var account: String?
public var groupName: String?
public var remoteID: String?
public var alwaysOn = true
public var passwordRef: Data?
public var secretRef: Data?
public init() { }
public init(type: VPNProtocolType, title: String,server : String, account: String, groupName: String, remoteId: String, alwaysOn: Bool){
self.type = type
self.title = title
self.server = server
self.account = account
self.groupName = groupName
self.remoteID = remoteId
self.alwaysOn = alwaysOn
}
}
| 28.884615 | 140 | 0.647137 |
1a1c669ad6265b7362f24d3efba1b4c3cb722399
| 514 |
//
// PhotoCellModel.swift
// PicSumAssignment
//
// Created by Satyam Sehgal on 24/05/19.
// Copyright © 2019 Satyam Sehgal. All rights reserved.
//
import Foundation
class PhotoCellModel {
let imageURL, author, id: String
let width, height: Int
required init (with viewModel: ViewModel) {
self.imageURL = viewModel.downloadURL
self.author = viewModel.author
self.id = viewModel.id
self.width = viewModel.width
self.height = viewModel.height
}
}
| 22.347826 | 56 | 0.659533 |
56eddab5ad65d4311dc2e678017eed6d878cfbed
| 4,456 |
import UIKit
protocol PageIndicatorDelegate: class {
func pageIndicator(_ pageIndicator: PageIndicator, didSelect index: Int)
func didSelectDropDown()
}
class PageIndicator: UIView {
let items: [String]
var buttons: [UIButton]!
lazy var indicator: UIImageView = self.makeIndicator()
lazy var dropDownButton: UIButton = self.makeDropDownButton()
weak var delegate: PageIndicatorDelegate?
let padding: CGFloat = 120.0
// MARK: - Initialization
required init(items: [String]) {
self.items = items
super.init(frame: .zero)
self.backgroundColor = .clear
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
let width = (bounds.size.width - 2 * padding) / CGFloat(buttons.count)
for (i, button) in buttons.enumerated() {
button.frame = CGRect(x: padding + width * CGFloat(i),
y: 0,
width: width,
height: bounds.size.height)
}
indicator.frame.size = CGSize(width: width / 1.5, height: 4)
indicator.frame.origin.y = bounds.size.height - indicator.frame.size.height
if indicator.frame.origin.x == 0 {
select(index: 0)
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
}
// MARK: - Setup
func setup() {
buttons = items.map {
let button = self.makeButton($0)
addSubview(button)
return button
}
addSubview(indicator)
if Config.DropDown.isOnBar {
addSubview(dropDownButton)
dropDownButton.g_pin(on: .right, constant: 0)
dropDownButton.g_pin(on: .bottom, constant: 0)
dropDownButton.g_pin(height: 30)
dropDownButton.g_pin(width: padding)
}
}
// MARK: - Controls
func makeDropDownButton() -> UIButton {
let button = UIButton(type: .custom)
button.backgroundColor = UIColor.clear
button.addTarget(self, action: #selector(dropDownButtonTouched(_:)), for: .touchUpInside)
return button
}
func makeButton(_ title: String) -> UIButton {
let button = UIButton(type: .custom)
button.setTitle(title, for: UIControl.State())
button.setTitleColor(Config.PageIndicator.textColor, for: UIControl.State())
button.setTitleColor(UIColor.gray, for: .highlighted)
button.backgroundColor = UIColor.clear //Config.PageIndicator.backgroundColor
button.addTarget(self, action: #selector(buttonTouched(_:)), for: .touchUpInside)
button.titleLabel?.font = buttonFont(false)
return button
}
func makeIndicator() -> UIImageView {
let imageView = UIImageView(image: GalleryBundle.image("gallery_page_indicator"))
return imageView
}
// MARK: - Action
@objc func dropDownButtonTouched(_ button: UIButton) {
delegate?.didSelectDropDown()
}
@objc func buttonTouched(_ button: UIButton) {
let index = buttons.index(of: button) ?? 0
delegate?.pageIndicator(self, didSelect: index)
select(index: index)
}
// MARK: - Logic
func select(index: Int, animated: Bool = true) {
for (i, b) in buttons.enumerated() {
let selected = i == index
b.titleLabel?.font = buttonFont(selected)
b.alpha = selected ? 1.0 : 0.4
}
UIView.animate(withDuration: animated ? 0.25 : 0.0,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.5,
options: .beginFromCurrentState,
animations: {
self.indicator.center.x = self.buttons[index].center.x
},
completion: nil)
}
// MARK: - Helper
func buttonFont(_ selected: Bool) -> UIFont {
return selected ? Config.PageIndicator.selectedFont : Config.PageIndicator.unselectedFont
}
}
| 30.312925 | 97 | 0.562388 |
eb6ddaf996131cf7a092d065d8be1b8a7f76566c
| 1,984 |
//
// UIButton+Label.swift
// Freetime
//
// Created by Ryan Nystrom on 6/8/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
extension UIButton {
enum State {
case merged
case closed
case open
case locked
case unlocked
}
func setupAsLabel(icon: Bool = true) {
accessibilityTraits = UIAccessibilityTraitNone
tintColor = .white
titleLabel?.font = Styles.Fonts.smallTitle
layer.cornerRadius = Styles.Sizes.labelCornerRadius
clipsToBounds = true
let magnitude = Styles.Sizes.buttonTopPadding
if icon {
imageEdgeInsets = UIEdgeInsets(top: 0, left: -Styles.Sizes.columnSpacing, bottom: 0, right: 0)
contentEdgeInsets = UIEdgeInsets(top: magnitude, left: Styles.Sizes.columnSpacing + magnitude, bottom: magnitude, right: magnitude * 2)
} else {
imageEdgeInsets = .zero
contentEdgeInsets = UIEdgeInsets(top: magnitude, left: magnitude, bottom: magnitude, right: magnitude)
}
}
func config(pullRequest: Bool, state: State) {
let prName = "git-pull-request-small"
let icon: String
let color: UIColor
switch state {
case .closed:
icon = pullRequest ? prName : "issue-closed-small"
color = Styles.Colors.Red.medium.color
case .open:
icon = pullRequest ? prName : "issue-opened-small"
color = Styles.Colors.Green.medium.color
case .merged:
icon = "git-merge-small"
color = Styles.Colors.purple.color
case .locked:
icon = "lock-small"
color = Styles.Colors.Gray.dark.color
case .unlocked:
icon = "key-small"
color = Styles.Colors.Gray.dark.color
}
setImage(UIImage(named: icon)?.withRenderingMode(.alwaysTemplate), for: .normal)
backgroundColor = color
}
}
| 29.176471 | 147 | 0.603327 |
e4eef67479bc674a2563842f291e280ab174a04a
| 894 |
//
// MusicLoadingFooter.swift
// AppStore
//
// Created by SUNG HAO LIN on 2020/2/27.
// Copyright © 2020 SUNG HAO LIN. All rights reserved.
//
import UIKit
class MusicLoadingFooter: UICollectionReusableView {
static let reuseId = "MusicLoadingFooter"
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
let aiv = UIActivityIndicatorView(style: .large)
aiv.color = .darkGray
aiv.startAnimating()
let label = UILabel(text: "Loading more...",
font: .systemFont(ofSize: 16))
label.textAlignment = .center
let stackView = VerticalStackView(arrangedSubviews: [
aiv,
label
], spacing: 8)
addSubview(stackView)
stackView.centerInSuperview(size: .init(width: 200, height: 0))
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 22.923077 | 67 | 0.662192 |
11be48da0d2fc088cedfc3f2cd415a9b64e6b693
| 251 |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func < {
extension Array {
let a {
protocol P {
let end = [ {
( == {
class
case ,
| 19.307692 | 87 | 0.705179 |
22c4371cc629348698facc73646e5213ff857804
| 1,814 |
//
// IncidentRecord.swift
// IncidentApp
//
// Created by Shubham Kumar on 21/03/20.
// Copyright © 2020 Shubham Kumar. All rights reserved.
//
import CoreData
import Foundation
class IncidentRecord {
var incidentManageObj: [NSManagedObject] = []
class func saveIncidentToDb( dataModel:IncidentModel,_ completionBlock : @escaping ()->()) {
if dataModel.machinename != nil {
let context = CoreDataStack.persistentContainer.viewContext
let currentIncident = Incident(context:context)
currentIncident.descriptions = dataModel.descriptions;
currentIncident.location = dataModel.location;
currentIncident.machineid = dataModel.machineid;
currentIncident.machinename = dataModel.machinename;
currentIncident.submissiontime = dataModel.submissiontime;
CoreDataStack.saveContext()
completionBlock()
}else{
// Do nothing - no error, response is empty
}
}
class func loadIncidentFromDb() -> [IncidentModel] {
let context = CoreDataStack.persistentContainer.viewContext
var viewModelArray = [IncidentModel]()
do {
let incidents : [Incident] = try context.fetch(Incident.fetchRequest())
if incidents.count > 0{
for incident in incidents{
let viewModel = IncidentModel(data: incident)
viewModelArray.append(viewModel!)
}
}
}catch {
print("Error fetching data from CoreData")
}
return viewModelArray
}
}
| 34.884615 | 96 | 0.562293 |
9b72ee3165ecad2da906314d82eede3466a9c0f0
| 410 |
//
// CyConversationMessagesResponseModel.swift
// Customerly
//
// Created by Paolo Musolino on 10/12/16.
// Copyright © 2016 Customerly. All rights reserved.
//
import ObjectMapper
class CyConversationMessagesResponseModel: Mappable {
var messages : [CyMessageModel]?
required init?(map: Map) {
}
func mapping(map: Map)
{
messages <- map["messages"]
}
}
| 17.083333 | 53 | 0.646341 |
d716d6a18da794e107edabfd1cee2ab017648cd0
| 1,368 |
//
// BaseSeparatorView.swift
// Cashew
//
// Created by Hicham Bouabdallah on 7/8/16.
// Copyright © 2016 SimpleRocket LLC. All rights reserved.
//
import Cocoa
@objc(SRBaseSeparatorView)
class BaseSeparatorView: BaseView {
static let separatorLineSelectedColor = NSColor(calibratedWhite: 255/255.0, alpha: 0.05)
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.setupSeparator()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.setupSeparator()
}
override func awakeFromNib() {
super.awakeFromNib()
setupSeparator()
}
var selected: Bool = false {
didSet {
if selected {
self.backgroundColor = BaseSeparatorView.separatorLineSelectedColor
} else {
self.backgroundColor = CashewColor.separatorColor()
}
}
}
fileprivate func setupSeparator() {
self.wantsLayer = true
self.selected = false
ThemeObserverController.sharedInstance.addThemeObserver(self) { [weak self] (mode) in
guard let strongSelf = self else {
return
}
let selected = strongSelf.selected
strongSelf.selected = selected
}
}
}
| 24 | 93 | 0.583333 |
ded3e9a77ceaeff5d213e660be30b27496ebb245
| 338 |
// RUN: %target-swift-frontend -emit-sil -verify %s | %FileCheck %s
func foo<T>(_ a: T) -> Int {
return 0
}
func foo(_ a: (Int) -> (Int)) -> Int {
return 42
}
// CHECK: function_ref @_T012rdar351421213fooS3icF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int) -> Int) -> Int
let _ = foo({ (a: Int) -> Int in a + 1 })
| 26 | 129 | 0.612426 |
46f7cbec38710bb8ddf6bc707572563515c6dcbd
| 3,777 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.5, *)
extension AsyncSequence {
/// Returns an asynchronous sequence, up to the specified maximum length,
/// containing the initial elements of the base asynchronous sequence.
///
/// Use `prefix(_:)` to reduce the number of elements produced by the
/// asynchronous sequence.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `10`. The `prefix(_:)` method causes the modified
/// sequence to pass through the first six values, then end.
///
/// for await number in Counter(howHigh: 10).prefix(6) {
/// print("\(number) ")
/// }
/// // prints "1 2 3 4 5 6"
///
/// If the count passed to `prefix(_:)` exceeds the number of elements in the
/// base sequence, the result contains all of the elements in the sequence.
///
/// - Parameter count: The maximum number of elements to return. The value of
/// `count` must be greater than or equal to zero.
/// - Returns: An asynchronous sequence starting at the beginning of the
/// base sequence with at most `count` elements.
@inlinable
public __consuming func prefix(
_ count: Int
) -> AsyncPrefixSequence<Self> {
precondition(count >= 0,
"Can't prefix a negative number of elements from an async sequence")
return AsyncPrefixSequence(self, count: count)
}
}
/// An asynchronous sequence, up to a specified maximum length,
/// containing the initial elements of a base asynchronous sequence.
@available(SwiftStdlib 5.5, *)
public struct AsyncPrefixSequence<Base: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let count: Int
@usableFromInline
init(_ base: Base, count: Int) {
self.base = base
self.count = count
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncPrefixSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The prefix sequence produces whatever type of element its base iterator
/// produces.
public typealias Element = Base.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the prefix sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
var remaining: Int
@usableFromInline
init(_ baseIterator: Base.AsyncIterator, count: Int) {
self.baseIterator = baseIterator
self.remaining = count
}
/// Produces the next element in the prefix sequence.
///
/// Until reaching the number of elements to include, this iterator calls
/// `next()` on its base iterator and passes through the result. After
/// reaching the maximum number of elements, subsequent calls to `next()`
/// return `nil`.
@inlinable
public mutating func next() async rethrows -> Base.Element? {
if remaining != 0 {
remaining &-= 1
return try await baseIterator.next()
} else {
return nil
}
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), count: count)
}
}
| 33.723214 | 80 | 0.660048 |
acbf7e42d1070432bc5c6879ec290f9b07a8a950
| 934 |
//
// ViewController.swift
// CollectionView
//
// Created by 郑尧元 on 2018/2/27.
// Copyright © 2018年 郑尧元. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, NSCollectionViewDataSource {
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "LabelCollectionViewItem"), for: indexPath)
return item
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| 23.948718 | 142 | 0.67666 |
d55d25cd17ea4bca4e3f9fad9def88a989a62b0e
| 12,093 |
//
// Automat
//
// Copyright (c) 2019 Automat Berlin GmbH - https://automat.berlin/
//
// 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 CocoaLumberjack
import TwilioVoice
class TwilioVoiceAdapter: NSObject {
/// The current call.
private var call: Call?
// Call invite required for several Twilio API functions.
private var twilioCallInvite: TVOCallInvite?
// Call required for several Twilio API functions.
private var twilioCall: TVOCall?
private var audioDevice: TVODefaultAudioDevice = TVODefaultAudioDevice()
/// The server credentials.
private var credentials: Credentials?
/// The application’s `VoIPManager` used to interact with a concrete adapter implementation.
private let voipManager: VoIPManager
/// Twilio specific temporary properties
private var accessToken = ""
private var deviceToken = ""
/**
Initializes the adapter.
- Parameter voipManager: The application’s `VoIPManager` that can be used for call-related functionality, and which delegates to an adapter implementation.
*/
init(voipManager: VoIPManager) {
self.voipManager = voipManager
super.init()
TwilioVoice.audioDevice = audioDevice
}
/**
Get accessToken
- Parameter credentials: The credentials that should be used for a login.
- Parameter completion: The block to execute after a login.
*/
private func login(credentials: Credentials, completion: @escaping (NSError?) -> Void) {
self.credentials = credentials
if let accessToken = fetchAccessToken() {
self.accessToken = accessToken
completion(nil)
} else {
let error = NSError(domain: "TwilioVoiceAdapter", code: 501, userInfo: ["description": "Couldn't retrieve accessToken"])
completion(error)
}
}
private func fetchAccessToken() -> String? {
guard let login = credentials?.login,
let endpoint = credentials?.sipServer else {
return nil
}
let endpointWithIdentity = String(format: "?identity=%@", login)
guard let accessTokenURL = URL(string: endpoint + endpointWithIdentity) else {
return nil
}
return try? String.init(contentsOf: accessTokenURL, encoding: .utf8)
}
}
// MARK: - VoIPManagerDelegate
extension TwilioVoiceAdapter: VoIPManagerDelegate {
func cancelLogin() {
}
var supportsVideo: Bool {
return false
}
var needsCodecs: Bool {
return false
}
var remoteVideoView: UIView? {
return nil
}
var localVideoView: UIView? {
return nil
}
func reload(with settings: Settings) {
}
var srtpOptions: [SRTP] {
return []
}
var audioCodecs: [Codec] {
return []
}
var videoCodecs: [Codec] {
return []
}
func logout(completion: (() -> Void)?) {
accessToken = ""
completion?()
}
func didEnterBackground() {
}
func willEnterForeground() {
}
func initAdapter(credentials: Credentials, completion: @escaping (NSError?) -> Void) {
login(credentials: credentials, completion: completion)
}
func answerCall(_ sessionId: Int, videoCall: Bool, completion: (NSError?) -> Void) {
var error: NSError?
audioDevice.isEnabled = false
audioDevice.block()
guard sessionId != -1,
let twilioCallInvite = twilioCallInvite else {
error = NSError(domain: Constants.Call.domain, code: Constants.Call.ErrorCode.sessionIdMissing.rawValue, userInfo: nil)
completion(error)
return
}
let acceptOptions: TVOAcceptOptions = TVOAcceptOptions(callInvite: twilioCallInvite) { (builder) in
builder.uuid = twilioCallInvite.uuid
}
twilioCall = twilioCallInvite.accept(with: acceptOptions, delegate: self)
if twilioCall?.state != .connecting {
DDLogError("☎️ - accepting incoming call failed")
error = NSError(domain: Constants.Call.domain, code: 0, userInfo: nil)
} else {
DDLogInfo("☎️ - accepting incoming call succeeded")
}
completion(error)
}
func hangUp(_ sessionId: Int, completion: (NSError?) -> Void) {
DDLogInfo("☎️ - hanging up call")
twilioCall?.disconnect()
call?.callState = .terminated
audioDevice.isEnabled = true
audioDevice.block()
completion(nil)
}
func rejectCall(_ sessionId: Int, code: Int, completion: (NSError?) -> Void) {
DDLogInfo("☎️ - rejecting call")
twilioCallInvite?.reject()
completion(nil)
}
func mute(_ sessionId: Int, mute: Bool, completion: (NSError?) -> Void) {
var error: NSError?
twilioCall?.isMuted = mute
if twilioCall?.isMuted != mute {
DDLogError("☎️ - Mute/unMute failed")
error = NSError(domain: Constants.Call.domain, code: 0, userInfo: ["description": "Mute/unMute failed"])
} else {
DDLogInfo("☎️ - Mute/unMute succeeded")
}
completion(error)
}
func hold(_ sessionId: Int, completion: (NSError?) -> Void) {
var error: NSError?
twilioCall?.isOnHold = true
if twilioCall?.isOnHold == false {
DDLogError("☎️ - Holding call failed")
error = NSError(domain: Constants.Call.domain, code: 0, userInfo: ["description": "Unholding call failed"])
} else {
DDLogInfo("☎️ - Holding call succeeded")
}
completion(error)
}
func unhold(_ sessionId: Int, completion: (NSError?) -> Void) {
var error: NSError?
twilioCall?.isOnHold = false
if twilioCall?.isOnHold == true {
DDLogError("☎️ - Unholding call failed")
error = NSError(domain: Constants.Call.domain, code: 0, userInfo: ["description": "Unholding call failed"])
} else {
DDLogInfo("☎️ - Unholding call succeeded")
}
completion(error)
}
func createCall(to: String, hasVideo: Bool, completion: (Call?, NSError?) -> Void) {
var error: NSError?
audioDevice.isEnabled = false
audioDevice.block()
guard let accessToken = fetchAccessToken(),
let from = credentials?.login else {
DDLogError("☎️ - creating outgoing call failed")
error = NSError(domain: Constants.Call.domain, code: 0, userInfo: ["description": "Call failed"])
completion(call, error)
return
}
call = Call(voipManager: voipManager)
let connectOptions: TVOConnectOptions = TVOConnectOptions(accessToken: accessToken) { (builder) in
builder.params = ["to": to]
}
twilioCall = TwilioVoice.connect(with: connectOptions, delegate: self)
call?.caller = from
call?.callee = to
call?.sessionId = Int.random(in: 0...100)
call?.callState = .initialized
completion(call, error)
}
func sendDTMF(_ sessionId: Int, character: Character) {
let characterString = String(character)
twilioCall?.sendDigits(characterString)
}
func startAudio() {
audioDevice.isEnabled = true
}
func stopAudio() {
}
func enableLocalVideo(_ enable: Bool, completion: ((Bool) -> Void)?) {
}
func enableRemoteVideo(_ enable: Bool, completion: ((Bool) -> Void)?) {
}
func toggleCameraPosition(completion: (NSError?) -> Void) {
}
}
// MARK: - TVOCallDelegate
extension TwilioVoiceAdapter: TVOCallDelegate {
func callDidStartRinging(_ call: TVOCall) {
DDLogInfo("☎️ - callDidStartRinging()")
guard let afoneCall = self.call else {
return
}
afoneCall.callState = .ringing
}
func callDidConnect(_ call: TVOCall) {
DDLogInfo("☎️ - callDidConnect()")
guard let afoneCall = self.call else {
return
}
if afoneCall.isIncomingCall {
voipManager.didAnswerCall(afoneCall)
}
afoneCall.callState = .talking
}
func call(_ call: TVOCall, didDisconnectWithError error: Error?) {
DDLogInfo("☎️ - didDisconnectWithError(): \(error.debugDescription)")
guard let afoneCall = self.call else {
return
}
if afoneCall.callState != .talking {
afoneCall.isMissed = true
voipManager.gotMissedCall(afoneCall)
}
afoneCall.isHungUpRemotely = true
afoneCall.callState = .terminated
self.call = nil
twilioCall = nil
twilioCallInvite = nil
}
func call(_ call: TVOCall, didFailToConnectWithError error: Error) {
DDLogInfo("☎️ - didFailToConnectWithError(): \(error.localizedDescription)")
self.call = nil
twilioCall = nil
twilioCallInvite = nil
}
}
// MARK: - TVONotificationDelegate
extension TwilioVoiceAdapter: TVONotificationDelegate {
func cancelledCallInviteReceived(_ cancelledCallInvite: TVOCancelledCallInvite) {
DDLogInfo("☎️ - cancelledCallInviteReceived()")
call?.callState = .terminated
twilioCallInvite?.reject()
}
func callInviteReceived(_ callInvite: TVOCallInvite) {
DDLogInfo("☎️ - callInviteReceived()")
call = Call(voipManager: voipManager)
call?.sessionId = Int.random(in: 0...100)
call?.caller = callInvite.from ?? ""
call?.callee = callInvite.to
call?.callerDisplayName = callInvite.from
call?.callState = .ringing
call?.isIncomingCall = true
twilioCallInvite = callInvite
if let call = call {
voipManager.gotIncomingCall(call)
}
}
}
// MARK: Push Registry
extension TwilioVoiceAdapter: PushPayloadObserver {
func didUpdatePushToken(_ token: Data) {
deviceToken = (token as NSData).description
guard let accessToken = fetchAccessToken() else {
DDLogError("☎️ - Failed to retrieve accessToken")
return
}
TwilioVoice.register(withAccessToken: accessToken, deviceToken: deviceToken) { (error) in
if let error = error {
DDLogError("☎️ - An error occurred while registering: \(error.localizedDescription)")
} else {
DDLogInfo("☎️ - Successfully registered for VoIP push notifications.")
}
}
}
func didReceivePayload(_ payload: [AnyHashable: Any]) {
TwilioVoice.handleNotification(payload, delegate: self)
}
func didInvalidatePushToken() {
guard let accessToken = fetchAccessToken() else {
DDLogError("☎️ - Failed to retrieve accessToken")
return
}
TwilioVoice.unregister(withAccessToken: accessToken, deviceToken: deviceToken) { [weak self] (_) in
self?.deviceToken = ""
}
}
}
| 29.639706 | 159 | 0.626974 |
569204f842baa2df42b3aae4a2e0e52dd261205f
| 6,754 |
//
// Stats.swift
// ably
//
// Created by Yavor Georgiev on 12.08.15.
// Copyright (c) 2015 г. Ably. All rights reserved.
//
import Ably
import Nimble
import Quick
import SwiftyJSON
import Foundation
class Stats: QuickSpec {
override func spec() {
describe("Stats") {
let encoder = ARTJsonLikeEncoder()
// TS6
for attribute in ["all", "persisted"] {
context(attribute) {
let data: JSON = [
[ attribute: [ "messages": [ "count": 5], "all": [ "data": 10 ] ] ]
]
let rawData = try! data.rawData()
let stats = try! encoder.decodeStats(rawData)[0] as? ARTStats
let subject = stats?.value(forKey: attribute) as? ARTStatsMessageTypes
it("should return a MessagesTypes object") {
expect(subject).to(beAnInstanceOf(ARTStatsMessageTypes.self))
}
// TS5
it("should return value for message counts") {
expect(subject?.messages.count).to(equal(5))
}
// TS5
it("should return value for all data transferred") {
expect(subject?.all.data).to(equal(10))
}
// TS2
it("should return zero for empty values") {
expect(subject?.presence.count).to(equal(0))
}
}
}
// TS7
for direction in ["inbound", "outbound"] {
context(direction) {
let data: JSON = [
[ direction: [
"realtime": [ "messages": [ "count": 5] ],
"all": [ "messages": [ "count": 25 ], "presence": [ "data": 210 ] ]
] ]
]
let rawData = try! data.rawData()
let stats = try! encoder.decodeStats(rawData)[0] as? ARTStats
let subject = stats?.value(forKey: direction) as? ARTStatsMessageTraffic
it("should return a MessageTraffic object") {
expect(subject).to(beAnInstanceOf(ARTStatsMessageTraffic.self))
}
// TS5
it("should return value for realtime message counts") {
expect(subject?.realtime.messages.count).to(equal(5))
}
// TS5
it("should return value for all presence data") {
expect(subject?.all.presence.data).to(equal(210))
}
}
}
// TS4
context("connections") {
let data: JSON = [
[ "connections": [ "tls": [ "opened": 5], "all": [ "peak": 10 ] ] ]
]
let rawData = try! data.rawData()
let stats = try! encoder.decodeStats(rawData)[0] as? ARTStats
let subject = stats?.connections
it("should return a ConnectionTypes object") {
expect(subject).to(beAnInstanceOf(ARTStatsConnectionTypes.self))
}
it("should return value for tls opened counts") {
expect(subject?.tls.opened).to(equal(5))
}
it("should return value for all peak connections") {
expect(subject?.all.peak).to(equal(10))
}
// TS2
it("should return zero for empty values") {
expect(subject?.all.refused).to(equal(0))
}
}
// TS9
context("channels") {
let data: JSON = [
[ "channels": [ "opened": 5, "peak": 10 ] ]
]
let rawData = try! data.rawData()
let stats = try! encoder.decodeStats(rawData)[0] as? ARTStats
let subject = stats?.channels
it("should return a ResourceCount object") {
expect(subject).to(beAnInstanceOf(ARTStatsResourceCount.self))
}
it("should return value for opened counts") {
expect(subject?.opened).to(equal(5))
}
it("should return value for peak channels") {
expect(subject?.peak).to(equal(10))
}
// TS2
it("should return zero for empty values") {
expect(subject?.refused).to(equal(0))
}
}
// TS8
for requestType in ["apiRequests", "tokenRequests"] {
let data: JSON = [
[ requestType: [ "succeeded": 5, "failed": 10 ] ]
]
let rawData = try! data.rawData()
let stats = try! encoder.decodeStats(rawData)[0] as? ARTStats
let subject = stats?.value(forKey: requestType) as? ARTStatsRequestCount
context(requestType) {
it("should return a RequestCount object") {
expect(subject).to(beAnInstanceOf(ARTStatsRequestCount.self))
}
it("should return value for succeeded") {
expect(subject?.succeeded).to(equal(5))
}
it("should return value for failed") {
expect(subject?.failed).to(equal(10))
}
}
}
context("interval") {
let data: JSON = [
[ "intervalId": "2004-02-01:05:06" ]
]
let rawData = try! data.rawData()
let stats = try! encoder.decodeStats(rawData)[0] as? ARTStats
it("should return a Date object representing the start of the interval") {
let dateComponents = NSDateComponents()
dateComponents.year = 2004
dateComponents.month = 2
dateComponents.day = 1
dateComponents.hour = 5
dateComponents.minute = 6
dateComponents.timeZone = NSTimeZone(name: "UTC") as TimeZone?
let expected = NSCalendar(identifier: NSCalendar.Identifier.gregorian)?.date(from: dateComponents as DateComponents)
expect(stats?.intervalTime()).to(equal(expected))
}
}
}
}
}
| 37.10989 | 136 | 0.450696 |
5643e58835a8fe4b3a1d04810f3427dc9cc021e9
| 387 |
//
// StoryboardIdentifier.swift
// TraktTV
//
// Created by dede.exe on 20/08/17.
// Copyright © 2017 dede.exe. All rights reserved.
//
import UIKit
public enum StoryboardIdentifier : String {
case movies = "Movies"
public var storyboard : UIStoryboard? {
let sb = UIStoryboard(name: self.rawValue, bundle: nil)
return sb
}
}
| 18.428571 | 63 | 0.612403 |
891ee82ef87d008332a43946a799a0a74b98bf97
| 673 |
//
// Config.swift
// UpcomingMovies
//
// Created by Mahavir Jain on 13/10/16.
// Copyright © 2016 CodeToArt. All rights reserved.
//
import Foundation
struct Config {
var imageBaseURLString: String?
var thumbSizeString: String?
var largeSizestring: String?
init(_ configDict: Dictionary<String, AnyObject?>) {
if let baseString = configDict["secure_base_url"] as? String {
self.imageBaseURLString = baseString
}
if let posterSizes = configDict["poster_sizes"] as? Array<String> {
self.thumbSizeString = posterSizes.first
self.largeSizestring = posterSizes.last
}
}
}
| 24.925926 | 75 | 0.64636 |
fbd8a73b23d13005f9d01b46bbb2d4bcd5542f84
| 1,339 |
//
// AppDelegate.swift
// Books2
//
// Created by 外園玲央 on 2020/11/30.
//
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.
}
}
| 37.194444 | 179 | 0.745332 |
262bf9feeddcacae7fd399d1f0e12fc91de0a0d9
| 3,706 |
public func flow<A, B, C>(
_ fnA: @escaping (A) -> B?,
_ fnB: @escaping (B) -> C?
)
-> (A) -> C?
{
return { (a: A) -> C? in
fnA(a).flatMap(fnB)
}
}
public func flow<A, B, C>(
_ fnA: @escaping (A) throws -> B?,
_ fnB: @escaping (B) throws -> C?
)
-> (A) throws -> C?
{
return { (a: A) -> C? in
try fnA(a).flatMap(fnB)
}
}
public func flow<A, B, C, D>(
_ fnA: @escaping (A) -> B?,
_ fnB: @escaping (B) -> C?,
_ fnC: @escaping (C) -> D?
)
-> (A) -> D?
{
return { (a: A) -> D? in
fnA(a).flatMap(fnB).flatMap(fnC)
}
}
public func flow<A, B, C, D>(
_ fnA: @escaping (A) throws -> B?,
_ fnB: @escaping (B) throws -> C?,
_ fnC: @escaping (C) throws -> D?
)
-> (A) throws -> D?
{
return { (a: A) -> D? in
try fnA(a).flatMap(fnB).flatMap(fnC)
}
}
public func flow<A, B, C, D, E>(
_ fnA: @escaping (A) -> B?,
_ fnB: @escaping (B) -> C?,
_ fnC: @escaping (C) -> D?,
_ fnD: @escaping (D) -> E?
)
-> (A) -> E?
{
return { (a: A) -> E? in
fnA(a).flatMap(fnB).flatMap(fnC).flatMap(fnD)
}
}
public func flow<A, B, C, D, E>(
_ fnA: @escaping (A) throws -> B?,
_ fnB: @escaping (B) throws -> C?,
_ fnC: @escaping (C) throws -> D?,
_ fnD: @escaping (D) throws -> E?
)
-> (A) throws -> E?
{
return { (a: A) -> E? in
try fnA(a).flatMap(fnB).flatMap(fnC).flatMap(fnD)
}
}
public func flow<A, B, C, D, E, F>(
_ fnA: @escaping (A) -> B?,
_ fnB: @escaping (B) -> C?,
_ fnC: @escaping (C) -> D?,
_ fnD: @escaping (D) -> E?,
_ fnE: @escaping (E) -> F?
)
-> (A) -> F?
{
return { (a: A) -> F? in
fnA(a).flatMap(fnB).flatMap(fnC).flatMap(fnD).flatMap(fnE)
}
}
public func flow<A, B, C, D, E, F>(
_ fnA: @escaping (A) throws -> B?,
_ fnB: @escaping (B) throws -> C?,
_ fnC: @escaping (C) throws -> D?,
_ fnD: @escaping (D) throws -> E?,
_ fnE: @escaping (E) throws -> F?
)
-> (A) throws -> F?
{
return { (a: A) -> F? in
try fnA(a).flatMap(fnB).flatMap(fnC).flatMap(fnD).flatMap(fnE)
}
}
public func flow<A, B, C, D, E, F, G>(
_ fnA: @escaping (A) -> B?,
_ fnB: @escaping (B) -> C?,
_ fnC: @escaping (C) -> D?,
_ fnD: @escaping (D) -> E?,
_ fnE: @escaping (E) -> F?,
_ fnF: @escaping (F) -> G?
)
-> (A) -> G?
{
return { (a: A) -> G? in
fnA(a).flatMap(fnB).flatMap(fnC).flatMap(fnD).flatMap(fnE).flatMap(fnF)
}
}
public func flow<A, B, C, D, E, F, G>(
_ fnA: @escaping (A) throws -> B?,
_ fnB: @escaping (B) throws -> C?,
_ fnC: @escaping (C) throws -> D?,
_ fnD: @escaping (D) throws -> E?,
_ fnE: @escaping (E) throws -> F?,
_ fnF: @escaping (F) throws -> G?
)
-> (A) throws -> G?
{
return { (a: A) -> G? in
try fnA(a).flatMap(fnB).flatMap(fnC).flatMap(fnD).flatMap(fnE).flatMap(fnF)
}
}
public func flow<A, B, C, D, E, F, G, H>(
_ fnA: @escaping (A) -> B?,
_ fnB: @escaping (B) -> C?,
_ fnC: @escaping (C) -> D?,
_ fnD: @escaping (D) -> E?,
_ fnE: @escaping (E) -> F?,
_ fnF: @escaping (F) -> G?,
_ fnG: @escaping (G) -> H?
)
-> (A) -> H?
{
return { (a: A) -> H? in
fnA(a).flatMap(fnB).flatMap(fnC).flatMap(fnD).flatMap(fnE).flatMap(fnF).flatMap(fnG)
}
}
public func flow<A, B, C, D, E, F, G, H>(
_ fnA: @escaping (A) throws -> B?,
_ fnB: @escaping (B) throws -> C?,
_ fnC: @escaping (C) throws -> D?,
_ fnD: @escaping (D) throws -> E?,
_ fnE: @escaping (E) throws -> F?,
_ fnF: @escaping (F) throws -> G?,
_ fnG: @escaping (G) throws -> H?
)
-> (A) throws -> H?
{
return { (a: A) -> H? in
try fnA(a).flatMap(fnB).flatMap(fnC).flatMap(fnD).flatMap(fnE).flatMap(fnF).flatMap(fnG)
}
}
| 23.455696 | 96 | 0.493794 |
ac89877573026756513c5520de44f7b2cf2ebf40
| 28,542 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import _SwiftConcurrencyShims
// ==== TaskGroup --------------------------------------------------------------
/// Starts a new task group which provides a scope in which a dynamic number of
/// tasks may be spawned.
///
/// Tasks added to the group by `group.spawn()` will automatically be awaited on
/// when the scope exits. If the group exits by throwing, all added tasks will
/// be cancelled and their results discarded.
///
/// ### Implicit awaiting
/// When the group returns it will implicitly await for all spawned tasks to
/// complete. The tasks are only cancelled if `cancelAll()` was invoked before
/// returning, the groups' task was cancelled, or the group body has thrown.
///
/// When results of tasks added to the group need to be collected, one can
/// gather their results using the following pattern:
///
/// while let result = await group.next() {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// It is also possible to collect results from the group by using its
/// `AsyncSequence` conformance, which enables its use in an asynchronous for-loop,
/// like this:
///
/// for await result in group {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// ### Cancellation
/// If the task that the group is running in is cancelled, the group becomes
/// cancelled and all child tasks spawned in the group are cancelled as well.
///
/// Since the `withTaskGroup` provided group is specifically non-throwing,
/// child tasks (or the group) cannot react to cancellation by throwing a
/// `CancellationError`, however they may interrupt their work and e.g. return
/// some best-effort approximation of their work.
///
/// If throwing is a good option for the kinds of tasks spawned by the group,
/// consider using the `withThrowingTaskGroup` function instead.
///
/// Postcondition:
/// Once `withTaskGroup` returns it is guaranteed that the `group` is *empty*.
///
/// This is achieved in the following way:
/// - if the body returns normally:
/// - the group will await any not yet complete tasks,
/// - once the `withTaskGroup` returns the group is guaranteed to be empty.
@available(SwiftStdlib 5.5, *)
@inlinable
public func withTaskGroup<ChildTaskResult, GroupResult>(
of childTaskResultType: ChildTaskResult.Type,
returning returnType: GroupResult.Type = GroupResult.self,
body: (inout TaskGroup<ChildTaskResult>) async -> GroupResult
) async -> GroupResult {
#if compiler(>=5.5) && $BuiltinTaskGroup
let _group = Builtin.createTaskGroup()
var group = TaskGroup<ChildTaskResult>(group: _group)
// Run the withTaskGroup body.
let result = await body(&group)
await group.awaitAllRemainingTasks()
Builtin.destroyTaskGroup(_group)
return result
#else
fatalError("Swift compiler is incompatible with this SDK version")
#endif
}
/// Starts a new throwing task group which provides a scope in which a dynamic
/// number of tasks may be spawned.
///
/// Tasks added to the group by `group.spawn()` will automatically be awaited on
/// when the scope exits. If the group exits by throwing, all added tasks will
/// be cancelled and their results discarded.
///
/// ### Implicit awaiting
/// When the group returns it will implicitly await for all spawned tasks to
/// complete. The tasks are only cancelled if `cancelAll()` was invoked before
/// returning, the groups' task was cancelled, or the group body has thrown.
///
/// When results of tasks added to the group need to be collected, one can
/// gather their results using the following pattern:
///
/// while let result = await try group.next() {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// It is also possible to collect results from the group by using its
/// `AsyncSequence` conformance, which enables its use in an asynchronous for-loop,
/// like this:
///
/// for try await result in group {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// ### Thrown errors
/// When tasks are added to the group using the `group.spawn` function, they may
/// immediately begin executing. Even if their results are not collected explicitly
/// and such task throws, and was not yet cancelled, it may result in the `withTaskGroup`
/// throwing.
///
/// ### Cancellation
/// If the task that the group is running in is cancelled, the group becomes
/// cancelled and all child tasks spawned in the group are cancelled as well.
///
/// If an error is thrown out of the task group, all of its remaining tasks
/// will be cancelled and the `withTaskGroup` call will rethrow that error.
///
/// Individual tasks throwing results in their corresponding `try group.next()`
/// call throwing, giving a chance to handle individual errors or letting the
/// error be rethrown by the group.
///
/// Postcondition:
/// Once `withThrowingTaskGroup` returns it is guaranteed that the `group` is *empty*.
///
/// This is achieved in the following way:
/// - if the body returns normally:
/// - the group will await any not yet complete tasks,
/// - if any of those tasks throws, the remaining tasks will be cancelled,
/// - once the `withTaskGroup` returns the group is guaranteed to be empty.
/// - if the body throws:
/// - all tasks remaining in the group will be automatically cancelled.
@available(SwiftStdlib 5.5, *)
@inlinable
public func withThrowingTaskGroup<ChildTaskResult, GroupResult>(
of childTaskResultType: ChildTaskResult.Type,
returning returnType: GroupResult.Type = GroupResult.self,
body: (inout ThrowingTaskGroup<ChildTaskResult, Error>) async throws -> GroupResult
) async rethrows -> GroupResult {
#if compiler(>=5.5) && $BuiltinTaskGroup
let _group = Builtin.createTaskGroup()
var group = ThrowingTaskGroup<ChildTaskResult, Error>(group: _group)
do {
// Run the withTaskGroup body.
let result = try await body(&group)
await group.awaitAllRemainingTasks()
Builtin.destroyTaskGroup(_group)
return result
} catch {
group.cancelAll()
await group.awaitAllRemainingTasks()
Builtin.destroyTaskGroup(_group)
throw error
}
#else
fatalError("Swift compiler is incompatible with this SDK version")
#endif
}
/// A task group serves as storage for dynamically spawned tasks.
///
/// It is created by the `withTaskGroup` function.
@available(SwiftStdlib 5.5, *)
@frozen
public struct TaskGroup<ChildTaskResult> {
/// Group task into which child tasks offer their results,
/// and the `next()` function polls those results from.
@usableFromInline
internal let _group: Builtin.RawPointer
/// No public initializers
@inlinable
init(group: Builtin.RawPointer) {
self._group = group
}
/// Add a child task to the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
public mutating func async(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) {
_ = _taskGroupAddPendingTask(group: _group, unconditionally: true)
// Set up the job flags for a new task.
var flags = JobFlags()
flags.kind = .task
flags.priority = priority
flags.isFuture = true
flags.isChildTask = true
flags.isGroupChildTask = true
// Create the asynchronous task future.
let (childTask, _) = Builtin.createAsyncTaskGroupFuture(
Int(flags.bits), _group, operation)
// Attach it to the group's task record in the current task.
_taskGroupAttachChild(group: _group, child: childTask)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(childTask))
}
/// Add a child task to the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
public mutating func asyncUnlessCancelled(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) -> Bool {
let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false)
guard canAdd else {
// the group is cancelled and is not accepting any new work
return false
}
// Set up the job flags for a new task.
var flags = JobFlags()
flags.kind = .task
flags.priority = priority
flags.isFuture = true
flags.isChildTask = true
flags.isGroupChildTask = true
// Create the asynchronous task future.
let (childTask, _) = Builtin.createAsyncTaskGroupFuture(
Int(flags.bits), _group, operation)
// Attach it to the group's task record in the current task.
_taskGroupAttachChild(group: _group, child: childTask)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(childTask))
return true
}
/// Wait for the a child task that was added to the group to complete,
/// and return (or rethrow) the value it completed with. If no tasks are
/// pending in the task group this function returns `nil`, allowing the
/// following convenient expressions to be written for awaiting for one
/// or all tasks to complete:
///
/// Await on a single completion:
///
/// if let first = try await group.next() {
/// return first
/// }
///
/// Wait and collect all group child task completions:
///
/// while let first = try await group.next() {
/// collected += value
/// }
/// return collected
///
/// Awaiting on an empty group results in the immediate return of a `nil`
/// value, without the group task having to suspend.
///
/// It is also possible to use `for await` to collect results of a task groups:
///
/// for await try value in group {
/// collected += value
/// }
///
/// ### Thread-safety
/// Please note that the `group` object MUST NOT escape into another task.
/// The `group.next()` MUST be awaited from the task that had originally
/// created the group. It is not allowed to escape the group reference.
///
/// Note also that this is generally prevented by Swift's type-system,
/// as the `add` operation is `mutating`, and those may not be performed
/// from concurrent execution contexts, such as child tasks.
///
/// ### Ordering
/// Order of values returned by next() is *completion order*, and not
/// submission order. I.e. if tasks are added to the group one after another:
///
/// group.spawn { 1 }
/// group.spawn { 2 }
///
/// print(await group.next())
/// /// Prints "1" OR "2"
///
/// ### Errors
/// If an operation added to the group throws, that error will be rethrown
/// by the next() call corresponding to that operation's completion.
///
/// It is possible to directly rethrow such error out of a `withTaskGroup` body
/// function's body, causing all remaining tasks to be implicitly cancelled.
public mutating func next() async -> ChildTaskResult? {
// try!-safe because this function only exists for Failure == Never,
// and as such, it is impossible to spawn a throwing child task.
return try! await _taskGroupWaitNext(group: _group)
}
/// Await all the remaining tasks on this group.
@usableFromInline
internal mutating func awaitAllRemainingTasks() async {
while let _ = await next() {}
}
/// Query whether the group has any remaining tasks.
///
/// Task groups are always empty upon entry to the `withTaskGroup` body, and
/// become empty again when `withTaskGroup` returns (either by awaiting on all
/// pending tasks or cancelling them).
///
/// - Returns: `true` if the group has no pending tasks, `false` otherwise.
public var isEmpty: Bool {
_taskGroupIsEmpty(_group)
}
/// Cancel all the remaining tasks in the group.
///
/// A cancelled group will not will NOT accept new tasks being added into it.
///
/// Any results, including errors thrown by tasks affected by this
/// cancellation, are silently discarded.
///
/// This function may be called even from within child (or any other) tasks,
/// and will reliably cause the group to become cancelled.
///
/// - SeeAlso: `Task.isCancelled`
/// - SeeAlso: `TaskGroup.isCancelled`
public func cancelAll() {
_taskGroupCancelAll(group: _group)
}
/// Returns `true` if the group was cancelled, e.g. by `cancelAll`.
///
/// If the task currently running this group was cancelled, the group will
/// also be implicitly cancelled, which will be reflected in the return
/// value of this function as well.
///
/// - Returns: `true` if the group (or its parent task) was cancelled,
/// `false` otherwise.
public var isCancelled: Bool {
return _taskGroupIsCancelled(group: _group)
}
}
// Implementation note:
// We are unable to just™ abstract over Failure == Error / Never because of the
// complicated relationship between `group.spawn` which dictates if `group.next`
// AND the AsyncSequence conformances would be throwing or not.
//
// We would be able to abstract over TaskGroup<..., Failure> equal to Never
// or Error, and specifically only add the `spawn` and `next` functions for
// those two cases. However, we are not able to conform to AsyncSequence "twice"
// depending on if the Failure is Error or Never, as we'll hit:
// conflicting conformance of 'TaskGroup<ChildTaskResult, Failure>' to protocol
// 'AsyncSequence'; there cannot be more than one conformance, even with
// different conditional bounds
// So, sadly we're forced to duplicate the entire implementation of TaskGroup
// to TaskGroup and ThrowingTaskGroup.
//
// The throwing task group is parameterized with failure only because of future
// proofing, in case we'd ever have typed errors, however unlikely this may be.
// Today the throwing task group failure is simply automatically bound to `Error`.
/// A task group serves as storage for dynamically spawned, potentially throwing,
/// child tasks.
///
/// It is created by the `withTaskGroup` function.
@available(SwiftStdlib 5.5, *)
@frozen
public struct ThrowingTaskGroup<ChildTaskResult, Failure: Error> {
/// Group task into which child tasks offer their results,
/// and the `next()` function polls those results from.
@usableFromInline
internal let _group: Builtin.RawPointer
/// No public initializers
@inlinable
init(group: Builtin.RawPointer) {
self._group = group
}
/// Await all the remaining tasks on this group.
@usableFromInline
internal mutating func awaitAllRemainingTasks() async {
while true {
do {
guard let _ = try await next() else {
return
}
} catch {}
}
}
/// Spawn, unconditionally, a child task in the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
public mutating func async(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) {
// we always add, so no need to check if group was cancelled
_ = _taskGroupAddPendingTask(group: _group, unconditionally: true)
// Set up the job flags for a new task.
var flags = JobFlags()
flags.kind = .task
flags.priority = priority
flags.isFuture = true
flags.isChildTask = true
flags.isGroupChildTask = true
// Create the asynchronous task future.
let (childTask, _) = Builtin.createAsyncTaskGroupFuture(
Int(flags.bits), _group, operation)
// Attach it to the group's task record in the current task.
_taskGroupAttachChild(group: _group, child: childTask)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(childTask))
}
/// Add a child task to the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
public mutating func asyncUnlessCancelled(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) -> Bool {
let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false)
guard canAdd else {
// the group is cancelled and is not accepting any new work
return false
}
// Set up the job flags for a new task.
var flags = JobFlags()
flags.kind = .task
flags.priority = priority
flags.isFuture = true
flags.isChildTask = true
flags.isGroupChildTask = true
// Create the asynchronous task future.
let (childTask, _) = Builtin.createAsyncTaskGroupFuture(
Int(flags.bits), _group, operation)
// Attach it to the group's task record in the current task.
_taskGroupAttachChild(group: _group, child: childTask)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(childTask))
return true
}
/// Wait for the a child task that was added to the group to complete,
/// and return (or rethrow) the value it completed with. If no tasks are
/// pending in the task group this function returns `nil`, allowing the
/// following convenient expressions to be written for awaiting for one
/// or all tasks to complete:
///
/// Await on a single completion:
///
/// if let first = try await group.next() {
/// return first
/// }
///
/// Wait and collect all group child task completions:
///
/// while let first = try await group.next() {
/// collected += value
/// }
/// return collected
///
/// Awaiting on an empty group results in the immediate return of a `nil`
/// value, without the group task having to suspend.
///
/// It is also possible to use `for await` to collect results of a task groups:
///
/// for await try value in group {
/// collected += value
/// }
///
/// ### Thread-safety
/// Please note that the `group` object MUST NOT escape into another task.
/// The `group.next()` MUST be awaited from the task that had originally
/// created the group. It is not allowed to escape the group reference.
///
/// Note also that this is generally prevented by Swift's type-system,
/// as the `add` operation is `mutating`, and those may not be performed
/// from concurrent execution contexts, such as child tasks.
///
/// ### Ordering
/// Order of values returned by next() is *completion order*, and not
/// submission order. I.e. if tasks are added to the group one after another:
///
/// group.spawn { 1 }
/// group.spawn { 2 }
///
/// print(await group.next())
/// /// Prints "1" OR "2"
///
/// ### Errors
/// If an operation added to the group throws, that error will be rethrown
/// by the next() call corresponding to that operation's completion.
///
/// It is possible to directly rethrow such error out of a `withTaskGroup` body
/// function's body, causing all remaining tasks to be implicitly cancelled.
public mutating func next() async throws -> ChildTaskResult? {
return try await _taskGroupWaitNext(group: _group)
}
/// - SeeAlso: `next()`
public mutating func nextResult() async throws -> Result<ChildTaskResult, Failure>? {
do {
guard let success: ChildTaskResult = try await _taskGroupWaitNext(group: _group) else {
return nil
}
return .success(success)
} catch {
return .failure(error as! Failure) // as!-safe, because we are only allowed to throw Failure (Error)
}
}
/// Query whether the group has any remaining tasks.
///
/// Task groups are always empty upon entry to the `withTaskGroup` body, and
/// become empty again when `withTaskGroup` returns (either by awaiting on all
/// pending tasks or cancelling them).
///
/// - Returns: `true` if the group has no pending tasks, `false` otherwise.
public var isEmpty: Bool {
_taskGroupIsEmpty(_group)
}
/// Cancel all the remaining tasks in the group.
///
/// A cancelled group will not will NOT accept new tasks being added into it.
///
/// Any results, including errors thrown by tasks affected by this
/// cancellation, are silently discarded.
///
/// This function may be called even from within child (or any other) tasks,
/// and will reliably cause the group to become cancelled.
///
/// - SeeAlso: `Task.isCancelled`
/// - SeeAlso: `TaskGroup.isCancelled`
public func cancelAll() {
_taskGroupCancelAll(group: _group)
}
/// Returns `true` if the group was cancelled, e.g. by `cancelAll`.
///
/// If the task currently running this group was cancelled, the group will
/// also be implicitly cancelled, which will be reflected in the return
/// value of this function as well.
///
/// - Returns: `true` if the group (or its parent task) was cancelled,
/// `false` otherwise.
public var isCancelled: Bool {
return _taskGroupIsCancelled(group: _group)
}
}
/// ==== TaskGroup: AsyncSequence ----------------------------------------------
@available(SwiftStdlib 5.5, *)
extension TaskGroup: AsyncSequence {
public typealias AsyncIterator = Iterator
public typealias Element = ChildTaskResult
public func makeAsyncIterator() -> Iterator {
return Iterator(group: self)
}
/// Allows iterating over results of tasks added to the group.
///
/// The order of elements returned by this iterator is the same as manually
/// invoking the `group.next()` function in a loop, meaning that results
/// are returned in *completion order*.
///
/// This iterator terminates after all tasks have completed successfully, or
/// after any task completes by throwing an error.
///
/// - SeeAlso: `TaskGroup.next()`
@available(SwiftStdlib 5.5, *)
public struct Iterator: AsyncIteratorProtocol {
public typealias Element = ChildTaskResult
@usableFromInline
var group: TaskGroup<ChildTaskResult>
@usableFromInline
var finished: Bool = false
// no public constructors
init(group: TaskGroup<ChildTaskResult>) {
self.group = group
}
/// Once this function returns `nil` this specific iterator is guaranteed to
/// never produce more values.
/// - SeeAlso: `TaskGroup.next()` for a detailed discussion its semantics.
public mutating func next() async -> Element? {
guard !finished else { return nil }
guard let element = await group.next() else {
finished = true
return nil
}
return element
}
public mutating func cancel() {
finished = true
group.cancelAll()
}
}
}
@available(SwiftStdlib 5.5, *)
extension ThrowingTaskGroup: AsyncSequence {
public typealias AsyncIterator = Iterator
public typealias Element = ChildTaskResult
public func makeAsyncIterator() -> Iterator {
return Iterator(group: self)
}
/// Allows iterating over results of tasks added to the group.
///
/// The order of elements returned by this iterator is the same as manually
/// invoking the `group.next()` function in a loop, meaning that results
/// are returned in *completion order*.
///
/// This iterator terminates after all tasks have completed successfully, or
/// after any task completes by throwing an error. If a task completes by
/// throwing an error, no further task results are returned.
///
/// - SeeAlso: `ThrowingTaskGroup.next()`
@available(SwiftStdlib 5.5, *)
public struct Iterator: AsyncIteratorProtocol {
public typealias Element = ChildTaskResult
@usableFromInline
var group: ThrowingTaskGroup<ChildTaskResult, Failure>
@usableFromInline
var finished: Bool = false
// no public constructors
init(group: ThrowingTaskGroup<ChildTaskResult, Failure>) {
self.group = group
}
/// - SeeAlso: `ThrowingTaskGroup.next()` for a detailed discussion its semantics.
public mutating func next() async throws -> Element? {
guard !finished else { return nil }
do {
guard let element = try await group.next() else {
finished = true
return nil
}
return element
} catch {
finished = true
throw error
}
}
public mutating func cancel() {
finished = true
group.cancelAll()
}
}
}
/// ==== -----------------------------------------------------------------------
/// Attach task group child to the group group to the task.
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_attachChild")
func _taskGroupAttachChild(
group: Builtin.RawPointer,
child: Builtin.NativeObject
)
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_destroy")
func _taskGroupDestroy(group: __owned Builtin.RawPointer)
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_addPending")
func _taskGroupAddPendingTask(
group: Builtin.RawPointer,
unconditionally: Bool
) -> Bool
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_cancelAll")
func _taskGroupCancelAll(group: Builtin.RawPointer)
/// Checks ONLY if the group was specifically cancelled.
/// The task itself being cancelled must be checked separately.
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_isCancelled")
func _taskGroupIsCancelled(group: Builtin.RawPointer) -> Bool
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_wait_next_throwing")
func _taskGroupWaitNext<T>(group: Builtin.RawPointer) async throws -> T?
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_hasTaskGroupStatusRecord")
func _taskHasTaskGroupStatusRecord() -> Bool
@available(SwiftStdlib 5.5, *)
enum PollStatus: Int {
case empty = 0
case waiting = 1
case success = 2
case error = 3
}
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_isEmpty")
func _taskGroupIsEmpty(
_ group: Builtin.RawPointer
) -> Bool
| 35.722153 | 106 | 0.679385 |
90792e31d71e8dfa17c2a78cc369cbecbf7b748d
| 4,074 |
//
// QuickBlurView.swift
// QuickBlurView
//
// Created by Krox on 2020/10/25.
//
import Foundation
/// Gaussian blur
@objcMembers public class QuickBlurView: UIView {
private enum Constants {
static let blurRadiusKey = "blurRadius"
static let colorTintKey = "colorTint"
static let colorTintAlphaKey = "colorTintAlpha"
}
// MARK: - Public
public var blurRadius: CGFloat = 10.0 {
didSet {
QuickBlurSetValue(blurRadius, forKey: Constants.blurRadiusKey)
}
}
public var colorTint: UIColor = .clear {
didSet { QuickBlurSetValue(colorTint, forKey: Constants.colorTintKey) }
}
public var colorTintAlpha: CGFloat = 0.8 {
didSet { QuickBlurSetValue(colorTintAlpha, forKey: Constants.colorTintAlphaKey) }
}
// MARK: - Private
private lazy var visualEffectView: UIVisualEffectView = {
if #available(iOS 14.0, *) {
return UIVisualEffectView(effect: customBlurEffect_ios14)
} else {
return UIVisualEffectView(effect: customBlurEffect)
}
}()
private lazy var customBlurEffect_ios14: CustomBlurEffect = {
let effect = CustomBlurEffect.effect(with: .light)
effect.blurRadius = blurRadius
return effect
}()
private lazy var customBlurEffect: UIBlurEffect = {
(NSClassFromString(getBlurClass()) as! UIBlurEffect.Type).init()
}()
// MARK: - Initialization
public init(
radius: CGFloat = 10.0,
color: UIColor = .clear,
colorAlpha: CGFloat = 0.8
) {
super.init(frame: .zero)
self.blurRadius = radius
backgroundColor = .clear
setupViews()
defer {
blurRadius = radius
colorTint = color
colorTintAlpha = colorAlpha
}
}
public convenience init() {
self.init(radius: 10.0, color: .clear, colorAlpha: 0.9)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
// MARK: private func
private extension QuickBlurView {
private func QuickBlurSetValue(_ value: Any?, forKey key: String) {
if #available(iOS 14.0, *) {
if key == Constants.blurRadiusKey {
updateViews()
}
let subviewClass = NSClassFromString(getColorSubview()) as? UIView.Type
let visualEffectSubview: UIView? = visualEffectView.subviews.filter {type(of: $0) == subviewClass}.first
visualEffectSubview?.backgroundColor = colorTint
visualEffectSubview?.alpha = colorTintAlpha
} else {
customBlurEffect.setValue(value, forKeyPath: key)
visualEffectView.effect = customBlurEffect
}
}
private func getColorSubview() -> String {
["_", "U", "I", "V", "i", "s", "u", "a", "l", "E", "f", "f", "e", "c", "t", "S", "u", "b", "v", "i", "e", "w"].joined(separator: "")
}
private func getBlurClass() -> String {
["_", "U", "I", "C", "u", "s", "t", "o", "m", "B", "l", "u", "r", "E", "f", "f", "e", "c", "t"].joined(separator: "")
}
private func setupViews() {
addSubview(visualEffectView)
visualEffectView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
visualEffectView.topAnchor.constraint(equalTo: topAnchor),
visualEffectView.trailingAnchor.constraint(equalTo: trailingAnchor),
visualEffectView.bottomAnchor.constraint(equalTo: bottomAnchor),
visualEffectView.leadingAnchor.constraint(equalTo: leadingAnchor)
])
}
/// Update in iOS 14
private func updateViews() {
if #available(iOS 14.0, *) {
visualEffectView.removeFromSuperview()
let newEffect = CustomBlurEffect.effect(with: .light)
newEffect.blurRadius = blurRadius
customBlurEffect_ios14 = newEffect
visualEffectView = UIVisualEffectView(effect: customBlurEffect_ios14)
setupViews()
}
}
}
| 31.338462 | 140 | 0.603829 |
e2fb8b74cb3bb6ca35706f60c771c4ab1055c31b
| 549 |
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "TILApp",
dependencies: [
// 💧 A server-side Swift web framework.
.package(url: "https://github.com/vapor/vapor.git", from: "3.0.0-rc.2"),
.package(url: "https://github.com/vapor/fluent-mysql.git", from: "3.0.0-rc.2")
],
targets: [
.target(name: "App", dependencies: ["FluentMySQL", "Vapor"]),
.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App"])
]
)
| 28.894737 | 86 | 0.588342 |
4b1d987393e617f30a78e4dfc7db897ebfd74bc6
| 366 |
//
// ViewController.swift
// Calculator1
//
// Created by Mitchell Phillips on 2/10/16.
// Copyright © 2016 Mitchell Phillips. All rights reserved.
//
import UIKit
class Calculator {
var value1 = 0
var hasTappedNumber = false
var hasCalculated = false
@IBAction func numberTapped(sender: UIBorderButton) {
}
}
| 13.555556 | 60 | 0.63388 |
629afeb5823d668a867cc219b1ddd821e7eb54ad
| 9,520 |
//
// Copyright 2021-2022, Optimizely, Inc. and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
extension OptimizelyClient {
/// Create a context of the user for which decision APIs will be called.
///
/// A user context will be created successfully even when the SDK is not fully configured yet.
///
/// - Parameters:
/// - userId: The user ID to be used for bucketing.
/// - attributes: A map of attribute names to current user attribute values.
/// - Returns: An OptimizelyUserContext associated with this OptimizelyClient
public func createUserContext(userId: String,
attributes: [String: Any]? = nil) -> OptimizelyUserContext {
return OptimizelyUserContext(optimizely: self, userId: userId, attributes: attributes)
}
func createUserContext(userId: String,
attributes: OptimizelyAttributes? = nil) -> OptimizelyUserContext {
return createUserContext(userId: userId,
attributes: (attributes ?? [:]) as [String: Any])
}
func decide(user: OptimizelyUserContext,
key: String,
options: [OptimizelyDecideOption]? = nil) -> OptimizelyDecision {
guard let config = self.config else {
return OptimizelyDecision.errorDecision(key: key, user: user, error: .sdkNotReady)
}
guard let feature = config.getFeatureFlag(key: key) else {
return OptimizelyDecision.errorDecision(key: key, user: user, error: .featureKeyInvalid(key))
}
let userId = user.userId
let attributes = user.attributes
let allOptions = defaultDecideOptions + (options ?? [])
let reasons = DecisionReasons(options: allOptions)
var decisionEventDispatched = false
var enabled = false
var decision: FeatureDecision?
// check forced-decisions first
let forcedDecisionResponse = decisionService.findValidatedForcedDecision(config: config,
user: user,
context: OptimizelyDecisionContext(flagKey: key))
reasons.merge(forcedDecisionResponse.reasons)
if let variation = forcedDecisionResponse.result {
decision = FeatureDecision(experiment: nil, variation: variation, source: Constants.DecisionSource.featureTest.rawValue)
} else {
// regular decision
let decisionResponse = decisionService.getVariationForFeature(config: config,
featureFlag: feature,
user: user,
options: allOptions)
reasons.merge(decisionResponse.reasons)
decision = decisionResponse.result
}
if let featureEnabled = decision?.variation.featureEnabled {
enabled = featureEnabled
}
if !allOptions.contains(.disableDecisionEvent) {
let ruleType = decision?.source ?? Constants.DecisionSource.rollout.rawValue
if shouldSendDecisionEvent(source: ruleType, decision: decision) {
sendImpressionEvent(experiment: decision?.experiment,
variation: decision?.variation,
userId: userId,
attributes: attributes,
flagKey: feature.key,
ruleType: ruleType,
enabled: enabled)
decisionEventDispatched = true
}
}
var variableMap = [String: Any]()
if !allOptions.contains(.excludeVariables) {
let decisionResponse = getDecisionVariableMap(feature: feature,
variation: decision?.variation,
enabled: enabled)
reasons.merge(decisionResponse.reasons)
variableMap = decisionResponse.result ?? [:]
}
var optimizelyJSON: OptimizelyJSON
if let opt = OptimizelyJSON(map: variableMap) {
optimizelyJSON = opt
} else {
reasons.addError(OptimizelyError.invalidJSONVariable)
optimizelyJSON = OptimizelyJSON.createEmpty()
}
let ruleKey = decision?.experiment?.key
let reasonsToReport = reasons.toReport()
sendDecisionNotification(userId: userId,
attributes: attributes,
decisionInfo: DecisionInfo(decisionType: .flag,
experiment: decision?.experiment,
variation: decision?.variation,
feature: feature,
featureEnabled: enabled,
variableValues: variableMap,
ruleKey: ruleKey,
reasons: reasonsToReport,
decisionEventDispatched: decisionEventDispatched))
return OptimizelyDecision(variationKey: decision?.variation.key,
enabled: enabled,
variables: optimizelyJSON,
ruleKey: ruleKey,
flagKey: feature.key,
userContext: user,
reasons: reasonsToReport)
}
func decide(user: OptimizelyUserContext,
keys: [String],
options: [OptimizelyDecideOption]? = nil) -> [String: OptimizelyDecision] {
guard config != nil else {
logger.e(OptimizelyError.sdkNotReady)
return [:]
}
guard keys.count > 0 else { return [:] }
let allOptions = defaultDecideOptions + (options ?? [])
var decisions = [String: OptimizelyDecision]()
let enabledFlagsOnly = allOptions.contains(.enabledFlagsOnly)
keys.forEach { key in
let decision = decide(user: user, key: key, options: options)
if !enabledFlagsOnly || decision.enabled {
decisions[key] = decision
}
}
return decisions
}
func decideAll(user: OptimizelyUserContext,
options: [OptimizelyDecideOption]? = nil) -> [String: OptimizelyDecision] {
guard let config = self.config else {
logger.e(OptimizelyError.sdkNotReady)
return [:]
}
return decide(user: user, keys: config.featureFlagKeys, options: options)
}
}
// MARK: - Utils
extension OptimizelyClient {
func getDecisionVariableMap(feature: FeatureFlag,
variation: Variation?,
enabled: Bool) -> DecisionResponse<[String: Any]> {
let reasons = DecisionReasons()
var variableMap = [String: Any]()
for v in feature.variables {
var featureValue = v.defaultValue ?? ""
if enabled, let variable = variation?.getVariable(id: v.id) {
featureValue = variable.value
}
if let value = parseFeatureVaraible(value: featureValue, type: v.type) {
variableMap[v.key] = value
} else {
let info = OptimizelyError.variableValueInvalid(v.key)
logger.e(info)
reasons.addError(info)
}
}
return DecisionResponse(result: variableMap, reasons: reasons)
}
func parseFeatureVaraible(value: String, type: String) -> Any? {
var valueParsed: Any? = value
if let valueType = Constants.VariableValueType(rawValue: type) {
switch valueType {
case .string:
break
case .integer:
valueParsed = Int(value)
case .double:
valueParsed = Double(value)
case .boolean:
valueParsed = Bool(value)
case .json:
valueParsed = OptimizelyJSON(payload: value)?.toMap()
}
}
return valueParsed
}
}
| 41.754386 | 132 | 0.520483 |
26e3c1cb9446cf8615a47bf9ad290f746e4edaf3
| 228 |
//
// DrawADayApp.swift
// DrawADay
//
// Created by Manuel Baez on 20/06/2021.
//
import SwiftUI
@main
struct DrawADayApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 12.666667 | 41 | 0.561404 |
114fae76dc024932b4efd43f808d4d7b63d4d39e
| 309 |
---
title: "Documents Directory Path"
summary: "Returns the URL for the documents directory wrapped in a guard."
completion-scope: Function or Method
---
guard let documentsDirectoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first else { <#code#> }
| 38.625 | 153 | 0.783172 |
e5232b6d31898fe5ccb05c23de83c60f177adb3b
| 3,905 |
//
// ViewController.swift
// PhotoBrowser
//
// Created by nick on 16/4/28.
// Copyright © 2016年 nick. All rights reserved.
//
import UIKit
private let ID = "cell"
//collectionView
class ViewController: UICollectionViewController {
private lazy var shops : [Shop] = [Shop]()
private lazy var customAnimation = CustomAnimation()
override func viewDidLoad() {
super.viewDidLoad()
//请求数据
loadData(0)
}
}
//请求数据
extension ViewController {
private func loadData(offSet : Int) {
AFNTool.shareAFN.loadHomeData(offSet) { (resoult, error) in
if error != nil {
print(error)
return
}
guard let resoultArray = resoult else {
print("数据不正确")
return
}
for resoultDict in resoultArray {
let shop = Shop(dict: resoultDict)
self.shops.append(shop)
}
self.collectionView?.reloadData()
}
}
}
// MARK:- 数据源方法
extension ViewController {
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.shops.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ID, forIndexPath: indexPath) as! CHViewCell
cell.shop = shops[indexPath.item]
if indexPath.item == self.shops.count - 1 {
//点击图片modal
loadData(self.shops.count)
}
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
showPhotoBrowser(indexPath)
}
}
extension ViewController {
func showPhotoBrowser(indexPath : NSIndexPath) {
let vc = CHShowPhotoViewController()
vc.indexPath = indexPath
vc.shops = shops
//3d翻转modal
// vc.modalTransitionStyle = .FlipHorizontal
//不让背景为黑色
vc.modalPresentationStyle = .Custom
//设置代理(自定义动画)
vc.transitioningDelegate = customAnimation
customAnimation.indexPath = indexPath
customAnimation.presentDelegate = self
customAnimation.disMissDelegate = vc
presentViewController(vc, animated: true, completion: nil)
}
}
// MARK:- 实现协议
extension ViewController : PresentDelegate {
func homeRect(indexPath: NSIndexPath) -> CGRect {
//取出cell
let cell = (collectionView?.cellForItemAtIndexPath(indexPath))!
//将cell的frame转成window的
let homeFrame = collectionView!.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
return homeFrame
}
func photoBrowserRect(indexPath: NSIndexPath) -> CGRect {
//取出cell
let cell = (collectionView?.cellForItemAtIndexPath(indexPath))! as! CHViewCell
//取出cell中显示的图片
let image = cell.imageView.image
//返回计算好的image的尺寸
return currentImageFrame(image!)
}
func imageView(indexPath: NSIndexPath) -> UIImageView {
// 1.创建imageView对象
let imageView = UIImageView()
// 2.设置显示的图片
// 2.1.取出cell
let cell = (collectionView?.cellForItemAtIndexPath(indexPath))! as! CHViewCell
// 2.2.取出cell中显示的图片
let image = cell.imageView.image
// 2.3.设置图片
imageView.image = image
// 3.设置imageView的属性
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
return imageView
}
}
| 26.564626 | 139 | 0.599488 |
ebe327a59490be4fa81e224a5c83d6f382482c6e
| 3,049 |
//
// FontViewController.swift
// FSNotes iOS
//
// Created by Oleksandr Glushchenko on 3/16/18.
// Copyright © 2018 Oleksandr Glushchenko. All rights reserved.
//
import UIKit
import NightNight
class FontViewController: UITableViewController {
private var fontFamilyNames: [String]? = [".SF UI Text"]
override func viewDidLoad() {
view.mixedBackgroundColor = MixedColor(normal: 0xffffff, night: 0x2e2c32)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(FontViewController.cancel))
self.title = "Font Family"
let names = UIFont.familyNames
for familyName in names {
fontFamilyNames?.append(familyName)
fontFamilyNames = fontFamilyNames?.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
}
navigationController?.navigationBar.mixedTitleTextAttributes = [NNForegroundColorAttributeName: MixedColor(normal: 0x000000, night: 0xfafafa)]
navigationController?.navigationBar.mixedTintColor = MixedColor(normal: 0x4d8be6, night: 0x7eeba1)
navigationController?.navigationBar.mixedBarTintColor = Colors.Header
super.viewDidLoad()
}
@objc func cancel() {
self.dismiss(animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.mixedBackgroundColor = MixedColor(normal: 0xffffff, night: 0x2e2c32)
cell.textLabel?.mixedTextColor = MixedColor(normal: 0x000000, night: 0xffffff)
let fontFamily = UserDefaultsManagement.noteFont.familyName
if let f = fontFamilyNames {
if f[indexPath.row] == fontFamily {
cell.accessoryType = .checkmark
}
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath), let label = cell.textLabel, let fontFamily = label.text {
UserDefaultsManagement.noteFont = UIFont(name: fontFamily, size: CGFloat(UserDefaultsManagement.fontSize))
self.dismiss(animated: true, completion: nil)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
if let f = fontFamilyNames {
cell.textLabel?.text = f[indexPath.row]
}
let view = UIView()
view.mixedBackgroundColor = MixedColor(normal: 0xe2e5e4, night: 0x686372)
cell.selectedBackgroundView = view
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let f = fontFamilyNames {
return f.count
}
return 0
}
}
| 36.73494 | 173 | 0.656937 |
fb5764dc904e15800ac8ecde37b26ce6075c64ae
| 1,018 |
//
// SparkPlayerFullscreenController.swift
// SparkPlayer
//
// Created by spark on 12/02/2018.
//
import Foundation
class SparkPlayerFullscreenController: SparkPlayerController {
override var modalPresentationStyle: UIModalPresentationStyle {
get {
return .fullScreen
}
set {}
}
override var modalTransitionStyle: UIModalTransitionStyle {
get {
return .crossDissolve
}
set {}
}
var isFullscreen = false
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
get {
return isFullscreen ? .landscape : .all
}
set {}
}
override func viewDidLoad() {
super.viewDidLoad()
if let resourceBundle = SparkPlayer.getResourceBundle() {
let fullscreenImage = UIImage(named: "FullscreenExit", in: resourceBundle, compatibleWith: nil)
sparkView.fullscreenButton.setImage(fullscreenImage, for: .normal)
}
}
}
| 22.130435 | 107 | 0.632613 |
16c1e6b3db9ae17bd23cf418568d87c489624a3c
| 2,757 |
// MIT license. Copyright (c) 2019 TriangleDraw. All rights reserved.
import CoreGraphics
struct E2CanvasClockwiseRotater {
let canvas: E2Canvas
let w: Int
let h: Int
let h2: Int
let half_w: Float
let half_h: Float
init(canvas: E2Canvas) {
let w = Int(canvas.cellsPerRow)
let h = Int(canvas.cellsPerColumn)
let h2 = Int(canvas.size.height)
let half_w: Float = Float(w) * 0.5
let half_h: Float = Float(h2) * 0.5
self.canvas = canvas
self.w = w
self.h = h
self.h2 = h2
self.half_w = half_w
self.half_h = half_h
}
func convert(pointInput: E2CanvasPoint) -> E2CanvasPoint? {
let i: Int = pointInput.x >> 1
let ii: Bool = pointInput.x & 1 == 1
let j: Int = pointInput.y >> 1
let jj: Bool = pointInput.y & 1 == 1
let cx: Float = Float(i) + 0.25
let cy: Float = Float(j * 2 + 1)
let i2: Float
let j2: Float
switch (ii, jj) {
case (false, false):
i2 = cx + 0.0
j2 = cy - 0.75
case (false, true):
i2 = cx + 0.0
j2 = cy + 0.75
case (true, false):
i2 = cx + 1.0
j2 = cy - 0.25
case (true, true):
i2 = cx + 1.0
j2 = cy + 0.25
}
let x: Float = (i2 - half_w) / half_w
let y: Float = (j2 - half_h) / half_h
let cgPoint = CGPoint(x: CGFloat(x), y: CGFloat(y))
return canvas.pointRotatedClockwise(cgPoint)
}
}
extension E2Canvas {
public func rotateClockwise() {
let sourceCanvas: E2Canvas = self.createCopy()
let rotator = E2CanvasClockwiseRotater(canvas: sourceCanvas)
for y in 0..<Int(self.cellsPerColumn * 2) {
for x in 0..<Int(self.cellsPerRow * 2) {
let destinationPoint = E2CanvasPoint(x: x, y: y)
if let sourcePoint: E2CanvasPoint = rotator.convert(pointInput: destinationPoint) {
let value: UInt8 = sourceCanvas.getPixel(sourcePoint)
self.setPixel(destinationPoint, value: value)
}
}
}
}
public func rotateCounterClockwise() {
// Rotating counter clockwise by 60 degrees, is the same as rotating clockwise 5 times 60 degrees.
rotateClockwise()
rotateClockwise()
rotateClockwise()
rotateClockwise()
rotateClockwise()
}
fileprivate func pointRotatedClockwise(_ point: CGPoint) -> E2CanvasPoint? {
let point_x = Float(point.x)
let point_y = Float(point.y)
let rads: Float = .pi / 3.0
let rot_x = Float(point_x * cosf(rads) - point_y * sinf(rads))
let rot_y = Float(point_y * cosf(rads) + point_x * sinf(rads))
let lookup_x: Float = (rot_x + 1.0) * 0.5
let lookup_y: Float = (rot_y + 1.0) * 0.5
if lookup_x < 0.0 || lookup_x > 1.0 || lookup_y < 0.0 || lookup_y > 1.0 {
return nil
}
let canvasPoint: E2CanvasPoint = self.canvasPoint(from: CGPoint(x: CGFloat(lookup_x), y: CGFloat(lookup_y)))
return canvasPoint
}
}
| 28.132653 | 110 | 0.6391 |
f9110a4d34ce24c9a1ff800fd68b97a4b61f9885
| 696 |
//
// Formatters.swift
// TicTacToe (iOS)
//
// Created by Cédric Bahirwe on 27/05/2021.
//
import Foundation
extension NumberFormatter {
static var currency: NumberFormatter = {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
return numberFormatter
}()
}
extension DateFormatter {
static var dueDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
return formatter
}()
static var timestampFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
return formatter
}()
}
| 21.090909 | 50 | 0.704023 |
db47895f1e7e544c145294bcc521f4f37f3dbec0
| 2,360 |
//
// AppDelegate.swift
// DGDialogAnimatorSample-tvOS
//
// Created by Benoit BRIATTE on 23/12/2016.
// Copyright © 2016 Digipolitan. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UINavigationController(rootViewController: ViewController())
self.window = window
window.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions
// (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers,
// and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the 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:.
}
}
| 49.166667 | 194 | 0.747458 |
08877633899f9091dc64e3b04bc561b4ce831363
| 2,582 |
//
// Scout
// Copyright (c) 2020-present Alexis Bridoux
// MIT license, see LICENSE file for details
import ScoutCLTCore
import Scout
import ArgumentParser
struct DeleteKeyCommand: SADCommand {
// MARK: - Constants
static let configuration = CommandConfiguration(
commandName: "delete-key",
abstract: "Delete all the (key, value) pairs where the key matches the regular expression pattern",
discussion: "To find examples and advanced explanations, please type `scout doc -c delete`")
// MARK: - Properties
var pathsCollection: [Path] { [Path("empty")] }
@Option(name: [.customShort("f", allowingJoined: true), .customLong("format")], help: "The data format to read the input")
var dataFormat: Scout.DataFormat
@Argument(help: "The regular expression pattern the keys to delete have to match")
var pattern: String
@Option(name: [.short, .customLong("input")], help: "A file path from which to read the data", completion: .file())
var inputFilePath: String?
@Option(name: [.short, .customLong("output")], help: "Write the modified data into the file at the given path", completion: .file())
var outputFilePath: String?
@Option(name: [.short, .customLong("modify")], help: "Read and write the data into the same file at the given path", completion: .file())
var modifyFilePath: String?
@Flag(help: "Highlight the ouput. --no-color or --nc to prevent it")
var color = ColorFlag.color
@Option(name: [.short, .long], help: "Fold the data at the given depth level")
var level: Int?
@Flag(name: [.short, .long], help: "When the deleted value leaves the array or dictionary holding it empty, delete it too")
var recursive = false
@Flag(name: [.customLong("csv")], help: "Convert the array data into CSV with the standard separator ';'")
var csv = false
@Option(name: [.customLong("csv-sep")], help: "Convert the array data into CSV with the given separator")
var csvSeparator: String?
@Option(name: [.short, .customLong("export")], help: "Convert the data to the specified format")
var exportFormat: ExportFormat?
// MARK: - Functions
func perform<P: SerializablePathExplorer>(pathExplorer: inout P, pathAndValue: Path) throws {
// postponed to 3.1.0
// will be called only once
// guard let regex = try? NSRegularExpression(pattern: pattern) else {
// throw RuntimeError.invalidRegex(pattern)
// }
// try pathExplorer.delete(regularExpression: regex, deleteIfEmpty: recursive)
}
}
| 37.970588 | 141 | 0.68048 |
3a3eba11c0e65e24f1550a32272924811c06f1d6
| 6,903 |
import Foundation
import AppKit
class IpViewController : NSViewController {
var button : NSButton?
var addr : NSTextField?
var iByte : NSTextField?
var oByte : NSTextField?
var ioByte : NSTextField?
override func loadView() {
view = NSStackView(frame: NSRect(x: 0, y: 0, width: 500, height: 0))
(view as! NSStackView).orientation = NSUserInterfaceLayoutOrientation.vertical
(view as! NSStackView).spacing = CGFloat(PADDING)
let titleBarSize = NSWindow.frameRect(forContentRect: self.view.frame, styleMask: NSWindowStyleMask.titled).height
(view as! NSStackView).edgeInsets = EdgeInsets(top: titleBarSize, left: PADDING, bottom: PADDING, right: PADDING)
//(view as! NSStackView).translatesAutoresizingMaskIntoConstraints = false
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
if(keyPath == "isActive") {
statusChange()
print("\(keyPath) did change here!", IpFilter.shared.isActive)
}
}
override func viewDidLoad() {
button = NSButton(title: "Go!", target: self, action: #selector(buttonPress))
let iByteName = NSTextField(string: "iByte:")
iByteName.isBordered = false
iByteName.isEditable = false
iByteName.isSelectable = false
iByteName.backgroundColor = NSColor.clear
let iByteLabel = NSTextField(string: "bytes")
iByteLabel.isBordered = false
iByteLabel.isEditable = false
iByteLabel.isSelectable = false
iByteLabel.alphaValue = 0.7
iByteLabel.backgroundColor = NSColor.clear
iByte = NSTextField(string: String(IpFilter.shared.iByte))
iByte?.placeholderString = "0"
iByte?.alignment = NSTextAlignment.right
let iByteStack = NSStackView(views: [iByteName, iByte!, iByteLabel])
iByteStack.orientation = NSUserInterfaceLayoutOrientation.horizontal
let oByteName = NSTextField(string: "oByte:")
oByteName.isBordered = false
oByteName.isEditable = false
oByteName.isSelectable = false
oByteName.backgroundColor = NSColor.clear
let oByteLabel = NSTextField(string: "bytes")
oByteLabel.isBordered = false
oByteLabel.isEditable = false
oByteLabel.isSelectable = false
oByteLabel.alphaValue = 0.7
oByteLabel.backgroundColor = NSColor.clear
oByte = NSTextField(string: String(IpFilter.shared.oByte))
oByte?.placeholderString = "0"
oByte?.alignment = NSTextAlignment.right
let oByteStack = NSStackView(views: [oByteName, oByte!, oByteLabel])
oByteStack.orientation = NSUserInterfaceLayoutOrientation.horizontal
let ioByteName = NSTextField(string: "ioByte:")
ioByteName.isBordered = false
ioByteName.isEditable = false
ioByteName.isSelectable = false
ioByteName.backgroundColor = NSColor.clear
let ioByteLabel = NSTextField(string: "bytes")
ioByteLabel.isBordered = false
ioByteLabel.isEditable = false
ioByteLabel.isSelectable = false
ioByteLabel.wantsLayer = true // to enable transparency
ioByteLabel.alphaValue = 0.7
ioByteLabel.backgroundColor = NSColor.clear
ioByte = TSTextField(string: String(IpFilter.shared.ioByte))
ioByte?.placeholderString = "0"
ioByte?.alignment = NSTextAlignment.right
let ioByteStack = NSStackView(views: [ioByteName, ioByte!, ioByteLabel])
ioByteStack.orientation = NSUserInterfaceLayoutOrientation.horizontal
//ioByteStack.alignment = NSLayoutAttribute.right
let addrName = NSTextField(string: "Address:")
addrName.isBordered = false
addrName.isEditable = false
addrName.isSelectable = false
addrName.backgroundColor = NSColor.clear
addr = TSTextField()
addr?.alignment = NSTextAlignment.right
let addrStack = NSStackView(views: [addrName, addr!])
addrStack.orientation = NSUserInterfaceLayoutOrientation.horizontal
//let parentStackView = NSStackView(views: [titleStackView, iByteStack, oByteStack, ioByteStack, mainStackView!, button!])
//parentStackView.orientation = NSUserInterfaceLayoutOrientation.vertical
//parentStackView.frame.size.height = 20
//parentStackView.frame.size.width = 200;
//self.view = parentStackView
(view as! NSStackView).addArrangedSubview(iByteStack)
(view as! NSStackView).addArrangedSubview(oByteStack)
(view as! NSStackView).addArrangedSubview(ioByteStack)
(view as! NSStackView).addArrangedSubview(addrStack)
(view as! NSStackView).addArrangedSubview(button!)
IpFilter.shared.addObserver(self, forKeyPath: "isActive", options: [NSKeyValueObservingOptions.initial, NSKeyValueObservingOptions.new], context: nil)
Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(checkStatus), userInfo: nil, repeats: true)
}
func buttonPress() {
switch(IpFilter.shared.isActive) {
case .active:
IpFilter.shared.isActive = IpFilter.activity.inactive
break
case .inactive:
IpFilter.shared.addr = (addr?.stringValue)!
IpFilter.shared.iByte = CInt(Int((iByte?.stringValue)!)!)
IpFilter.shared.oByte = CInt(Int((oByte?.stringValue)!)!)
IpFilter.shared.ioByte = CInt(Int((ioByte?.stringValue)!)!)
IpFilter.shared.isActive = IpFilter.activity.active
break
default:
break
}
statusChange()
}
func statusChange() {
let s = IpFilter.shared.isActive
lastStatus = s
switch(IpFilter.shared.isActive) {
case .active:
button?.title = "Stop"
button?.isEnabled = true
break
case .inactive:
button?.title = "Filter"
button?.isEnabled = true
break
default:
button?.title = "Filter"
button?.isEnabled = false
}
}
var lastStatus : IpFilter.activity = IpFilter.activity.unknown
func checkStatus() {
// This is necessary cause our KVO only detects changes
// that we make, not that the kernel makes, or other
// external programs
if IpFilter.shared.isActive != lastStatus {
statusChange()
}
}
}
| 38.780899 | 158 | 0.637114 |
7a04c1e435d900f60d76dc5e021dbe005e6d2102
| 3,068 |
//
// GitCredential.swift
// pass
//
// Created by Mingshen Sun on 30/4/2017.
// Copyright © 2017 Bob Sun. All rights reserved.
//
import Foundation
import ObjectiveGit
public struct GitCredential {
private var credential: Credential
private let passwordStore = PasswordStore.shared
public enum Credential {
case http(userName: String)
case ssh(userName: String, privateKey: String)
}
public init(credential: Credential) {
self.credential = credential
}
public func credentialProvider(requestCredentialPassword: @escaping (Credential, String?) -> String?) throws -> GTCredentialProvider {
var attempts = 0
return GTCredentialProvider { (_, _, _) -> (GTCredential?) in
var credential: GTCredential? = nil
switch self.credential {
case let .http(userName):
if attempts > 3 {
// After too many failures (say six), the error message "failed to authenticate ssh session" might be confusing.
return nil
}
var lastPassword = self.passwordStore.gitPassword
if lastPassword == nil || attempts != 0 {
if let requestedPassword = requestCredentialPassword(self.credential, lastPassword) {
if Defaults.isRememberGitCredentialPassphraseOn {
self.passwordStore.gitPassword = requestedPassword
}
lastPassword = requestedPassword
} else {
return nil
}
}
attempts += 1
credential = try? GTCredential(userName: userName, password: lastPassword!)
case let .ssh(userName, privateKey):
if attempts > 0 {
// The passphrase seems correct, but the previous authentification failed.
return nil
}
var lastPassword = self.passwordStore.gitSSHPrivateKeyPassphrase
if lastPassword == nil || attempts != 0 {
if let requestedPassword = requestCredentialPassword(self.credential, lastPassword) {
if Defaults.isRememberGitCredentialPassphraseOn {
self.passwordStore.gitSSHPrivateKeyPassphrase = requestedPassword
}
lastPassword = requestedPassword
} else {
return nil
}
}
attempts += 1
credential = try? GTCredential(userName: userName, publicKeyString: nil, privateKeyString: privateKey, passphrase: lastPassword!)
}
return credential
}
}
public func delete() {
switch credential {
case .http:
self.passwordStore.gitPassword = nil
case .ssh:
self.passwordStore.gitSSHPrivateKeyPassphrase = nil
}
}
}
| 37.414634 | 145 | 0.554759 |
e919bbb346f70cf49bbf978f4a9456b81e66299e
| 5,364 |
//
// AssemblerParserTests.swift
// Turtle16SimulatorCoreTests
//
// Created by Andrew Fox on 5/16/21.
// Copyright © 2021 Andrew Fox. All rights reserved.
//
import XCTest
import TurtleCore
import Turtle16SimulatorCore
class AssemblerParserTests: XCTestCase {
func parse(_ text: String) -> AssemblerParser {
let tokenizer = AssemblerLexer(text)
tokenizer.scanTokens()
let parser = AssemblerParser(tokens: tokenizer.tokens, lineMapper: tokenizer.lineMapper)
parser.parse()
return parser
}
func testEmptyProgramYieldsEmptyAST1() {
let parser = parse("")
XCTAssertFalse(parser.hasError)
guard let ast = parser.syntaxTree else {
XCTFail()
return
}
XCTAssertEqual(ast.children.count, 0)
}
func testEmptyProgramYieldsEmptyAST2() {
let parser = parse("\n")
XCTAssertFalse(parser.hasError)
guard let ast = parser.syntaxTree else {
XCTFail()
return
}
XCTAssertEqual(ast.children.count, 0)
}
func testParseExtraneousColon() {
let parser = parse(":")
XCTAssertTrue(parser.hasError)
XCTAssertNil(parser.syntaxTree)
XCTAssertEqual(parser.errors.first?.sourceAnchor, parser.lineMapper.anchor(0, 1))
XCTAssertEqual(parser.errors.first?.message, "unexpected end of input")
}
func testExtraneousComma() {
let parser = parse(",")
XCTAssertTrue(parser.hasError)
XCTAssertNil(parser.syntaxTree)
XCTAssertEqual(parser.errors.first?.sourceAnchor, parser.lineMapper.anchor(0, 1))
XCTAssertEqual(parser.errors.first?.message, "unexpected end of input")
}
func testParseOpcodeWithNoParameters() {
let parser = parse("NOP\nHLT\n")
XCTAssertFalse(parser.hasError)
guard let ast = parser.syntaxTree else {
XCTFail()
return
}
XCTAssertEqual(ast.children.count, 2)
XCTAssertEqual(ast.children[0], InstructionNode(instruction: "NOP", parameters: []))
XCTAssertEqual(ast.children[1], InstructionNode(instruction: "HLT", parameters: []))
}
func testParseOpcodeWithOneParameter1() {
let parser = parse("NOP $ffff")
XCTAssertFalse(parser.hasError)
guard let ast = parser.syntaxTree else {
XCTFail()
return
}
XCTAssertEqual(ast.children.count, 1)
XCTAssertEqual(ast.children.first, InstructionNode(instruction: "NOP", parameters: [
ParameterNumber(0xffff)
]))
}
func testParseOpcodeWithOneParameter2() {
let parser = parse("NOP $ffff\n")
XCTAssertFalse(parser.hasError)
guard let ast = parser.syntaxTree else {
XCTFail()
return
}
XCTAssertEqual(ast.children.count, 1)
XCTAssertEqual(ast.children.first, InstructionNode(instruction: "NOP", parameters: [
ParameterNumber(0xffff)
]))
}
func testParseOpcodeWithThreeParameters() {
let parser = parse("NOP 1, 2, foo")
XCTAssertFalse(parser.hasError)
guard let ast = parser.syntaxTree else {
XCTFail()
return
}
XCTAssertEqual(ast.children.count, 1)
XCTAssertEqual(ast.children.first, InstructionNode(instruction: "NOP", parameters: [
ParameterNumber(1),
ParameterNumber(2),
ParameterIdentifier("foo")
]))
}
func testParseOpcodeWithExtraneousComma1() {
let parser = parse("NOP 1,")
XCTAssertTrue(parser.hasError)
XCTAssertNil(parser.syntaxTree)
XCTAssertEqual(parser.errors.first?.message, "extraneous comma")
}
func testParseOpcodeWithExtraneousComma2() {
let parser = parse("NOP 1,\n")
XCTAssertTrue(parser.hasError)
XCTAssertNil(parser.syntaxTree)
XCTAssertEqual(parser.errors.first?.message, "extraneous comma")
}
func testParseAddressParameter() {
let parser = parse("JR 1(r1)")
XCTAssertFalse(parser.hasError)
guard let ast = parser.syntaxTree else {
XCTFail()
return
}
XCTAssertEqual(ast.children.count, 1)
XCTAssertEqual(ast.children.first, InstructionNode(instruction: "JR", parameters: [
ParameterAddress(offset: ParameterNumber(1), identifier: ParameterIdentifier("r1"))
]))
}
func testParseAddressParameterNegative() {
let parser = parse("JR -1(r1)")
XCTAssertFalse(parser.hasError)
guard let ast = parser.syntaxTree else {
XCTFail()
return
}
XCTAssertEqual(ast.children.count, 1)
XCTAssertEqual(ast.children.first, InstructionNode(instruction: "JR", parameters: [
ParameterAddress(offset: ParameterNumber(-1), identifier: ParameterIdentifier("r1"))
]))
}
func testParseLabel() {
let parser = parse("foo:")
XCTAssertFalse(parser.hasError)
guard let ast = parser.syntaxTree else {
XCTFail()
return
}
XCTAssertEqual(ast.children.count, 1)
XCTAssertEqual(ast.children.first, LabelDeclaration(identifier: "foo"))
}
}
| 33.111111 | 96 | 0.618755 |
abbffa7d4661d85a302a02516b364f98e1106498
| 602 |
import Foundation
struct AccountAttribute: Codable {
/// The name associated with the account in the Up application.
var displayName: String
/// The bank account type of this account.
var accountType: AccountTypeEnum
/// The available balance of the account, taking into account any amounts that are currently on hold.
var balance: MoneyObject
/// The date-time at which this account was first opened.
var createdAt: String
}
extension AccountAttribute {
var creationDate: String {
return App.formatDate(for: createdAt, dateStyle: UserDefaults.provenance.appDateStyle)
}
}
| 27.363636 | 103 | 0.757475 |
fc03a48bdce29c5b7dc3de59259bfc59ac5bd71d
| 14,570 |
/* file: interpolated_configuration_sequence.swift generated: Mon Jan 3 16:32:52 2022 */
/* This file was generated by the EXPRESS to Swift translator "exp2swift",
derived from STEPcode (formerly NIST's SCL).
exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23
WARNING: You probably don't want to edit it since your modifications
will be lost if exp2swift is used to regenerate it.
*/
import SwiftSDAIcore
extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF {
//MARK: -ENTITY DEFINITION in EXPRESS
/*
ENTITY interpolated_configuration_sequence
SUBTYPE OF ( geometric_representation_item );
segments : LIST [2 : ?] OF interpolated_configuration_segment;
DERIVE
n_segments : INTEGER := SIZEOF( segments );
closed_interpolation : LOGICAL := segments[n_segments].interpolation <>
discontinuous_interpolation_type;
configured_mechanism : mechanism_representation := segments[1].state.represented_mechanism;
WHERE
wr1: ( SIZEOF( QUERY ( ics <* segments | ( ics.state.represented_mechanism :<>: configured_mechanism ) ) )
= 0 );
END_ENTITY; -- interpolated_configuration_sequence (line:18348 file:ap242ed2_mim_lf_v1.101.TY.exp)
*/
//MARK: - ALL DEFINED ATTRIBUTES
/*
SUPER- ENTITY(1) representation_item
ATTR: name, TYPE: label -- EXPLICIT
SUPER- ENTITY(2) geometric_representation_item
ATTR: dim, TYPE: dimension_count -- DERIVED
:= dimension_of( SELF )
ENTITY(SELF) interpolated_configuration_sequence
ATTR: segments, TYPE: LIST [2 : ?] OF interpolated_configuration_segment -- EXPLICIT
ATTR: n_segments, TYPE: INTEGER -- DERIVED
:= SIZEOF( segments )
ATTR: closed_interpolation, TYPE: LOGICAL -- DERIVED
:= segments[n_segments].interpolation <> discontinuous_interpolation_type
ATTR: configured_mechanism, TYPE: mechanism_representation -- DERIVED
:= segments[1].state.represented_mechanism
*/
//MARK: - Partial Entity
public final class _interpolated_configuration_sequence : SDAI.PartialEntity {
public override class var entityReferenceType: SDAI.EntityReference.Type {
eINTERPOLATED_CONFIGURATION_SEQUENCE.self
}
//ATTRIBUTES
/// EXPLICIT ATTRIBUTE
public internal(set) var _segments: SDAI.LIST<eINTERPOLATED_CONFIGURATION_SEGMENT>/*[2:nil]*/ // PLAIN EXPLICIT ATTRIBUTE
/// DERIVE ATTRIBUTE
internal func _n_segments__getter(SELF: eINTERPOLATED_CONFIGURATION_SEQUENCE) -> SDAI.INTEGER? {
let _TEMP1 = SDAI.SIZEOF(SELF.SEGMENTS)
return _TEMP1
}
/// DERIVE ATTRIBUTE
internal func _closed_interpolation__getter(SELF: eINTERPOLATED_CONFIGURATION_SEQUENCE) -> SDAI.LOGICAL {
let _TEMP1 = SELF.SEGMENTS[SELF.N_SEGMENTS]
let _TEMP2 = _TEMP1?.INTERPOLATION
let _TEMP3 = _TEMP2 .!=. SDAI.FORCE_OPTIONAL(DISCONTINUOUS_INTERPOLATION_TYPE)
return _TEMP3
}
/// DERIVE ATTRIBUTE
internal func _configured_mechanism__getter(SELF: eINTERPOLATED_CONFIGURATION_SEQUENCE) ->
eMECHANISM_REPRESENTATION? {
let _TEMP1 = SELF.SEGMENTS[1]
let _TEMP2 = _TEMP1?.STATE
let _TEMP3 = _TEMP2?.REPRESENTED_MECHANISM
return _TEMP3
}
public override var typeMembers: Set<SDAI.STRING> {
var members = Set<SDAI.STRING>()
members.insert(SDAI.STRING(Self.typeName))
//SELECT data types (indirectly) referencing the current type as a member of the select list
members.insert(SDAI.STRING(sKINEMATIC_RESULT.typeName)) // -> Self
members.insert(SDAI.STRING(sKINEMATIC_ANALYSIS_DEFINITION.typeName)) // -> Self
return members
}
//VALUE COMPARISON SUPPORT
public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) {
super.hashAsValue(into: &hasher, visited: &complexEntities)
self._segments.value.hashAsValue(into: &hasher, visited: &complexEntities)
}
public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool {
guard let rhs = rhs as? Self else { return false }
if !super.isValueEqual(to: rhs, visited: &comppairs) { return false }
if let comp = self._segments.value.isValueEqualOptionally(to: rhs._segments.value, visited: &comppairs) {
if !comp { return false }
}
else { return false }
return true
}
public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? {
guard let rhs = rhs as? Self else { return false }
var result: Bool? = true
if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) {
if !comp { return false }
}
else { result = nil }
if let comp = self._segments.value.isValueEqualOptionally(to: rhs._segments.value, visited: &comppairs) {
if !comp { return false }
}
else { result = nil }
return result
}
//MARK: WHERE RULES (ENTITY)
public static func WHERE_wr1(SELF: eINTERPOLATED_CONFIGURATION_SEQUENCE?) -> SDAI.LOGICAL {
guard let SELF = SELF else { return SDAI.UNKNOWN }
let _TEMP1 = SELF.SEGMENTS.QUERY{ ICS in
let _TEMP1 = ICS.STATE
let _TEMP2 = _TEMP1.REPRESENTED_MECHANISM
let _TEMP3 = SDAI.FORCE_OPTIONAL(_TEMP2) .!==. SELF.CONFIGURED_MECHANISM
return _TEMP3 }
let _TEMP2 = SDAI.SIZEOF(_TEMP1)
let _TEMP3 = _TEMP2 .==. SDAI.FORCE_OPTIONAL(SDAI.INTEGER(0))
return _TEMP3
}
//EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR
public init(SEGMENTS: SDAI.LIST<eINTERPOLATED_CONFIGURATION_SEGMENT>/*[2:nil]*/ ) {
self._segments = SEGMENTS
super.init(asAbstructSuperclass:())
}
//p21 PARTIAL ENTITY CONSTRUCTOR
public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) {
let numParams = 1
guard parameters.count == numParams
else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil }
guard case .success(let p0) = exchangeStructure.recoverRequiredParameter(as: SDAI.LIST<
eINTERPOLATED_CONFIGURATION_SEGMENT>.self, from: parameters[0])
else { exchangeStructure.add(errorContext: "while recovering parameter #0 for entity(\(Self.entityName)) constructor"); return nil }
self.init( SEGMENTS: p0 )
}
}
//MARK: - Entity Reference
/** ENTITY reference
- EXPRESS:
```express
ENTITY interpolated_configuration_sequence
SUBTYPE OF ( geometric_representation_item );
segments : LIST [2 : ?] OF interpolated_configuration_segment;
DERIVE
n_segments : INTEGER := SIZEOF( segments );
closed_interpolation : LOGICAL := segments[n_segments].interpolation <>
discontinuous_interpolation_type;
configured_mechanism : mechanism_representation := segments[1].state.represented_mechanism;
WHERE
wr1: ( SIZEOF( QUERY ( ics <* segments | ( ics.state.represented_mechanism :<>: configured_mechanism ) ) )
= 0 );
END_ENTITY; -- interpolated_configuration_sequence (line:18348 file:ap242ed2_mim_lf_v1.101.TY.exp)
```
*/
public final class eINTERPOLATED_CONFIGURATION_SEQUENCE : SDAI.EntityReference {
//MARK: PARTIAL ENTITY
public override class var partialEntityType: SDAI.PartialEntity.Type {
_interpolated_configuration_sequence.self
}
public let partialEntity: _interpolated_configuration_sequence
//MARK: SUPERTYPES
public let super_eREPRESENTATION_ITEM: eREPRESENTATION_ITEM // [1]
public let super_eGEOMETRIC_REPRESENTATION_ITEM: eGEOMETRIC_REPRESENTATION_ITEM // [2]
public var super_eINTERPOLATED_CONFIGURATION_SEQUENCE: eINTERPOLATED_CONFIGURATION_SEQUENCE { return self } // [3]
//MARK: SUBTYPES
//MARK: ATTRIBUTES
/// __DERIVE__ attribute
/// - origin: SELF( ``eINTERPOLATED_CONFIGURATION_SEQUENCE`` )
public var CLOSED_INTERPOLATION: SDAI.LOGICAL {
get {
if let cached = cachedValue(derivedAttributeName:"CLOSED_INTERPOLATION") {
return cached.value as! SDAI.LOGICAL
}
let origin = self
let value = SDAI.LOGICAL( origin.partialEntity._closed_interpolation__getter(SELF: origin) )
updateCache(derivedAttributeName:"CLOSED_INTERPOLATION", value:value)
return value
}
}
/// __DERIVE__ attribute
/// - origin: SELF( ``eINTERPOLATED_CONFIGURATION_SEQUENCE`` )
public var CONFIGURED_MECHANISM: eMECHANISM_REPRESENTATION? {
get {
if let cached = cachedValue(derivedAttributeName:"CONFIGURED_MECHANISM") {
return cached.value as! eMECHANISM_REPRESENTATION?
}
let origin = self
let value = origin.partialEntity._configured_mechanism__getter(SELF: origin)
updateCache(derivedAttributeName:"CONFIGURED_MECHANISM", value:value)
return value
}
}
/// __DERIVE__ attribute
/// - origin: SELF( ``eINTERPOLATED_CONFIGURATION_SEQUENCE`` )
public var N_SEGMENTS: SDAI.INTEGER? {
get {
if let cached = cachedValue(derivedAttributeName:"N_SEGMENTS") {
return cached.value as! SDAI.INTEGER?
}
let origin = self
let value = origin.partialEntity._n_segments__getter(SELF: origin)
updateCache(derivedAttributeName:"N_SEGMENTS", value:value)
return value
}
}
/// __EXPLICIT__ attribute
/// - origin: SELF( ``eINTERPOLATED_CONFIGURATION_SEQUENCE`` )
public var SEGMENTS: SDAI.LIST<eINTERPOLATED_CONFIGURATION_SEGMENT>/*[2:nil]*/ {
get {
return SDAI.UNWRAP( self.partialEntity._segments )
}
set(newValue) {
let partial = self.partialEntity
partial._segments = SDAI.UNWRAP(newValue)
}
}
/// __EXPLICIT__ attribute
/// - origin: SUPER( ``eREPRESENTATION_ITEM`` )
public var NAME: tLABEL {
get {
return SDAI.UNWRAP( super_eREPRESENTATION_ITEM.partialEntity._name )
}
set(newValue) {
let partial = super_eREPRESENTATION_ITEM.partialEntity
partial._name = SDAI.UNWRAP(newValue)
}
}
/// __DERIVE__ attribute
/// - origin: SUPER( ``eGEOMETRIC_REPRESENTATION_ITEM`` )
public var DIM: tDIMENSION_COUNT? {
get {
if let cached = cachedValue(derivedAttributeName:"DIM") {
return cached.value as! tDIMENSION_COUNT?
}
let origin = super_eGEOMETRIC_REPRESENTATION_ITEM
let value = tDIMENSION_COUNT(origin.partialEntity._dim__getter(SELF: origin))
updateCache(derivedAttributeName:"DIM", value:value)
return value
}
}
//MARK: INITIALIZERS
public convenience init?(_ entityRef: SDAI.EntityReference?) {
let complex = entityRef?.complexEntity
self.init(complex: complex)
}
public required init?(complex complexEntity: SDAI.ComplexEntity?) {
guard let partial = complexEntity?.partialEntityInstance(_interpolated_configuration_sequence.self) else { return nil }
self.partialEntity = partial
guard let super1 = complexEntity?.entityReference(eREPRESENTATION_ITEM.self) else { return nil }
self.super_eREPRESENTATION_ITEM = super1
guard let super2 = complexEntity?.entityReference(eGEOMETRIC_REPRESENTATION_ITEM.self) else { return nil }
self.super_eGEOMETRIC_REPRESENTATION_ITEM = super2
super.init(complex: complexEntity)
}
public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) {
guard let entityRef = generic?.entityReference else { return nil }
self.init(complex: entityRef.complexEntity)
}
public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) }
public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) }
//MARK: WHERE RULE VALIDATION (ENTITY)
public override class func validateWhereRules(instance:SDAI.EntityReference?, prefix:SDAI.WhereLabel) -> [SDAI.WhereLabel:SDAI.LOGICAL] {
guard let instance = instance as? Self else { return [:] }
let prefix2 = prefix + " \(instance)"
var result = super.validateWhereRules(instance:instance, prefix:prefix2)
result[prefix2 + " .WHERE_wr1"] = _interpolated_configuration_sequence.WHERE_wr1(SELF: instance)
return result
}
//MARK: DICTIONARY DEFINITION
public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition }
private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition()
private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition {
let entityDef = SDAIDictionarySchema.EntityDefinition(name: "INTERPOLATED_CONFIGURATION_SEQUENCE", type: self, explicitAttributeCount: 1)
//MARK: SUPERTYPE REGISTRATIONS
entityDef.add(supertype: eREPRESENTATION_ITEM.self)
entityDef.add(supertype: eGEOMETRIC_REPRESENTATION_ITEM.self)
entityDef.add(supertype: eINTERPOLATED_CONFIGURATION_SEQUENCE.self)
//MARK: ATTRIBUTE REGISTRATIONS
entityDef.addAttribute(name: "CLOSED_INTERPOLATION", keyPath: \eINTERPOLATED_CONFIGURATION_SEQUENCE.CLOSED_INTERPOLATION,
kind: .derived, source: .thisEntity, mayYieldEntityReference: false)
entityDef.addAttribute(name: "CONFIGURED_MECHANISM", keyPath: \eINTERPOLATED_CONFIGURATION_SEQUENCE.CONFIGURED_MECHANISM,
kind: .derived, source: .thisEntity, mayYieldEntityReference: true)
entityDef.addAttribute(name: "N_SEGMENTS", keyPath: \eINTERPOLATED_CONFIGURATION_SEQUENCE.N_SEGMENTS,
kind: .derived, source: .thisEntity, mayYieldEntityReference: false)
entityDef.addAttribute(name: "SEGMENTS", keyPath: \eINTERPOLATED_CONFIGURATION_SEQUENCE.SEGMENTS,
kind: .explicit, source: .thisEntity, mayYieldEntityReference: true)
entityDef.addAttribute(name: "NAME", keyPath: \eINTERPOLATED_CONFIGURATION_SEQUENCE.NAME,
kind: .explicit, source: .superEntity, mayYieldEntityReference: false)
entityDef.addAttribute(name: "DIM", keyPath: \eINTERPOLATED_CONFIGURATION_SEQUENCE.DIM,
kind: .derived, source: .superEntity, mayYieldEntityReference: false)
return entityDef
}
}
}
| 40.248619 | 185 | 0.707207 |
69a3731cbedefda9a6273065b457dcaa09df6519
| 395 |
//
// Utils.swift
// CapriceDemoTests
//
// Created by Jean Raphael Bordet on 04/08/2020.
//
import XCTest
import Difference
public func XCTAssertEqual<T: Equatable>(_ expected: T, _ received: T, file: StaticString = #file, line: UInt = #line) {
XCTAssertTrue(expected == received, "Found difference for \n" + diff(expected, received).joined(separator: ", "), file: file, line: line)
}
| 28.214286 | 141 | 0.696203 |
fc7d41f44fb8fa6dc65bb082804722ae7e053931
| 179 |
//
// UserIdentifier.swift
// AdzerkSDK
//
// Created by Ben Scheirman on 10/16/20.
//
import Foundation
public struct UserIdentifier: Codable {
public let key: String
}
| 13.769231 | 41 | 0.692737 |
acd7912a5531725d596a4d71d0af5960c47d0708
| 361 |
//
// ball.swift
// SoccerPong
//
// Created by james luo on 2/14/18.
// Copyright © 2018 james luo. All rights reserved.
//
import Foundation
import SpriteKit
import GameplayKit
class ball{
var nodeID : SKNode
var isPowerUp : Bool
init(nodeID: SKNode, isPowerUp: Bool) {
self.nodeID = nodeID
self.isPowerUp = isPowerUp
}
}
| 18.05 | 52 | 0.65374 |
acf7bc2215afffaae9ab4eb02dde58dd92e4b351
| 10,305 |
//
// ViewController.swift
// BAKit
//
// Created by HVNT on 08/23/2018.
// Copyright (c) 2018 HVNT. All rights reserved.
//
import UIKit
import BAKit
import UserNotifications
import Firebase
import MaterialComponents
import CoreData
class LoginViewController: UIViewController {
@IBOutlet weak var devEnvSwitch: UISwitch!
@IBOutlet weak var devEnvLabel: UILabel!
@IBOutlet weak var emailTextField: MDCTextField!
@IBOutlet weak var passwordTextField: MDCTextField!
@IBOutlet weak var isolatedView: ShadowView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet var tapRecognizer: UITapGestureRecognizer!
@IBOutlet weak var devSwitchStack: UIStackView!
let activitiController = UIActivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: UIFont(name: "Montserrat-Regular", size: 20)!]
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard))
self.view.addGestureRecognizer(tap)
activitiController.frame = CGRect(x: (self.view.frame.width/2) - 40, y: (self.view.frame.height/2) - 40, width: 80, height: 80)
activitiController.backgroundColor = UIColor.lightGray
activitiController.activityIndicatorViewStyle = .whiteLarge
activitiController.layer.cornerRadius = 10
view.addSubview(activitiController)
if BoardActive.client.userDefaults!.bool(forKey: String.ConfigKeys.DeviceRegistered), let anEmail = BoardActive.client.userDefaults!.string(forKey: String.ConfigKeys.Email), let aPassword = BoardActive.client.userDefaults!.string(forKey: String.ConfigKeys.Password) {
self.emailTextField.text = anEmail
self.passwordTextField.text = aPassword
if (BoardActive.client.userDefaults?.string(forKey: String.ConfigKeys.AppKey) == String.AppKeys.Dev) {
devEnvSwitch.setOn(true, animated: false)
BoardActive.client.isDevEnv = true
} else {
devEnvSwitch.setOn(false, animated: false)
BoardActive.client.isDevEnv = false
}
self.signInAction(self)
}
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController!.navigationBar.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue, let keyboardBeginHeight = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? CGRect)?.height {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= (keyboardSize.height - 60)
} else if abs(Int(self.view.frame.origin.y)) == Int(keyboardBeginHeight - 60) {
self.view.frame.origin.y += (keyboardBeginHeight - keyboardSize.height)
}
}
}
@objc
func keyboardWillHide(notification: NSNotification) {
if view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
@objc func dismissKeyboard() {
self.view.endEditing(true)
}
@IBAction func signInAction(_ sender: Any) {
guard let email = emailTextField.text, let password = passwordTextField.text else {
DispatchQueue.main.async {
self.showCredentialsErrorAlert(error: "Both fields must contain entries.")
}
return
}
if (!email.isEmpty && !password.isEmpty) {
DispatchQueue.main.async {
self.activitiController.startAnimating()
}
BoardActive.client.userDefaults?.set(email, forKey: "email")
BoardActive.client.userDefaults?.set(password, forKey: "password")
if self.devEnvSwitch.isOn {
BoardActive.client.userDefaults?.set(true, forKey: "isDevEnv")
} else {
BoardActive.client.userDefaults?.set(false, forKey: "isDevEnv")
}
BoardActive.client.userDefaults?.synchronize()
let operationQueue = OperationQueue()
let registerDeviceOperation = BlockOperation {
BoardActive.client.postLogin(email: email, password: password) { (parsedJSON, err) in
guard (err == nil) else {
DispatchQueue.main.async {
self.showCredentialsErrorAlert(error: err!.localizedDescription)
self.activitiController.stopAnimating()
}
return
}
if let parsedJSON = parsedJSON {
let payload: LoginPayload = LoginPayload.init(fromDictionary: parsedJSON)
CoreDataStack.sharedInstance.deleteStoredData(entity: "BAKitApp")
for app in payload.apps {
// let apps = CoreDataStack.sharedInstance.fetchAppsFromDatabase()
let newApp = CoreDataStack.sharedInstance.createBAKitApp(fromApp: app)
// let appid = Int(truncatingIfNeeded: app.id)
// let newAppId = Int(truncatingIfNeeded: newApp.id)
StorageObject.container.apps.append(newApp)
// if apps!.count > 0 {
// if appid != newAppId {
// StorageObject.container.apps.append(newApp)
// } else {
// CoreDataStack.sharedInstance.mainContext.delete(newApp)
// }
// }
// else
// {
// StorageObject.container.apps.append(newApp)
// }
}
if payload.apps.count < 1 {
DispatchQueue.main.async {
self.activitiController.stopAnimating()
self.showCredentialsErrorAlert(error: parsedJSON["message"] as! String)
return
}
} else {
print("PAYLOAD :: APPS : \(payload.apps.description)")
DispatchQueue.main.async {
self.activitiController.stopAnimating()
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let appPickingViewController = storyBoard.instantiateViewController(withIdentifier: "AppPickingViewController")
self.navigationController?.pushViewController(appPickingViewController, animated: true)
}
}
} else {
DispatchQueue.main.async {
self.activitiController.stopAnimating()
}
}
}
if BoardActive.client.isDevEnv {
BoardActive.client.userDefaults?.set(String.AppKeys.Dev, forKey: String.ConfigKeys.AppKey)
} else {
BoardActive.client.userDefaults?.set(String.AppKeys.Prod, forKey: String.ConfigKeys.AppKey)
}
BoardActive.client.userDefaults?.synchronize()
}
operationQueue.addOperation(registerDeviceOperation)
} else {
DispatchQueue.main.async {
self.showCredentialsErrorAlert(error:"Both fields must contain entries.")
}
}
}
@objc
func showCredentialsErrorAlert(error: String) {
let alert = UIAlertController(title: "Login Error", message: error, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
@IBAction func switchValueDidChange(_ sender: Any) {
if ((sender as! UISwitch).isOn) {
BoardActive.client.isDevEnv = true
} else {
BoardActive.client.isDevEnv = false
}
}
@objc func textChanged(_ sender: Any) {
let textfield = sender as! UITextField
var resp : UIResponder! = textfield
while !(resp is UIAlertController) { resp = resp.next }
let alert = resp as! UIAlertController
alert.actions[0].isEnabled = (!(alert.textFields![0].text!.isEmpty) && !(alert.textFields![0].text!.isEmpty))
}
var count = 0
@IBAction func tapHandler(_ sender: UITapGestureRecognizer) {
if count < 6 {
count += 1
} else {
count = 0
if (devSwitchStack.isHidden) {
devSwitchStack.isHidden = false
} else {
devSwitchStack.isHidden = true
}
}
}
}
extension LoginViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| 43.481013 | 276 | 0.566521 |
bb738cde6b7e091aea7199d09a16079e28f315d6
| 356 |
//
// CJProfileVC.swift
// CJWB
//
// Created by 星驿ios on 2017/7/26.
// Copyright © 2017年 CJ. All rights reserved.
//
import UIKit
class CJProfileVC: CJBaseVC {
override func viewDidLoad() {
super.viewDidLoad()
visitorView.setupVisitorViewInfo("visitordiscover_image_profile", title: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人")
}
}
| 17.8 | 112 | 0.671348 |
f78409ce2b58156b7b20d1104f0bd6a3f3d90471
| 2,825 |
//
// YXSwiftKitUtil+file.swift
// YXSwiftKitUtil_Example
//
// Created by Mr_Jesson on 2022/3/7.
// Copyright © 2022 CocoaPods. All rights reserved.
//
import Foundation
import CommonCrypto
public enum YXSwiftKitUtilFileDirectoryType {
case home //程序主目录
case documents //应用中用户数据可以放在这里,iTunes备份和恢复的时候会包括此目录
case tmp //存放临时文件,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除
case caches //存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除,硬盘资源紧张时会被删除
}
public extension YXSwiftKitUtil {
///获取文件夹路径
func getFileDirectory(type: YXSwiftKitUtilFileDirectoryType) -> URL {
let homePath = NSHomeDirectory()
switch type {
case .home:
return URL(fileURLWithPath: homePath)
case .documents:
return URL(fileURLWithPath: homePath.appending("/Documents"))
case .tmp:
return URL(fileURLWithPath: homePath.appending("/tmp"))
case .caches:
return URL(fileURLWithPath: homePath.appending("/Library/Caches"))
}
}
/// 在指定文件夹中创建文件夹
/// - Parameters:
/// - type: 浮层文件夹类型
/// - directoryName: 文件夹名称
/// - Returns: 创建的文件夹路径
func createFileDirectory(in type: YXSwiftKitUtilFileDirectoryType, directoryName: String) -> URL {
let manager = FileManager.default
let superDirectory = self.getFileDirectory(type: type)
let newFolder = superDirectory.appendingPathComponent(directoryName, isDirectory: true)
var isDirectory: ObjCBool = false
let isDirExist = manager.fileExists(atPath: newFolder.path, isDirectory: &isDirectory)
if !isDirectory.boolValue || !isDirExist {
do {
try manager.createDirectory(at: newFolder, withIntermediateDirectories: true, attributes: nil)
} catch {
print("创建目录失败\(error)")
return newFolder
}
}
return newFolder
}
///获取指定文件的大小
func getFileSize(filePath: URL) -> Double {
let manager = FileManager.default
if manager.fileExists(atPath: filePath.path) {
let fileSize = try? manager.attributesOfItem(atPath: filePath.path)
return fileSize?[FileAttributeKey.size] as? Double ?? 0
}
return 0
}
///获取文件夹大小
func getFileDirectorySize(fileDirectoryPth: URL) -> Double {
let manager = FileManager.default
var size: Double = 0
if manager.fileExists(atPath: fileDirectoryPth.path), let subPath = manager.subpaths(atPath: fileDirectoryPth.path) {
for fileName in subPath {
let filePath = fileDirectoryPth.path.appending("/\(fileName)")
size = size + self.getFileSize(filePath: URL(fileURLWithPath: filePath))
}
}
return size
}
}
| 34.036145 | 125 | 0.63469 |
d5913de927c703b4a16f820c4487605d4ab61847
| 586 |
//
// ZanViewConfigProtocol.swift
// SamuraiTransition
//
// Created by Nishinobu.Takahiro on 2016/12/07.
// Copyright © 2016年 hachinobu. All rights reserved.
//
import Foundation
public protocol ZanViewConfigProtocol {
var inSideFrame: CGRect { get }
var outSideFrame: CGRect { get }
var isAlphaAnimation: Bool { get }
var mask: CAShapeLayer? { get }
var isScaleAnimation: Bool { get }
}
extension ZanViewConfigProtocol {
func viewFrame(isPresenting: Bool) -> CGRect {
return isPresenting ? inSideFrame : outSideFrame
}
}
| 20.928571 | 56 | 0.677474 |
018ab0de165a8ba8299142cd13cce04c8e92e263
| 2,652 |
//
// NVActivityIndicatorAnimationBallZigZagDeflect.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/23/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationBallZigZagDeflect: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize: CGFloat = size.width / 5
let duration: CFTimeInterval = 0.75
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize)
// Circle 1 animation
let animation = CAKeyframeAnimation(keyPath:"transform")
animation.keyTimes = [0.0, 0.33, 0.66, 1.0]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))]
animation.duration = duration
animation.repeatCount = HUGE
animation.autoreverses = true
animation.isRemovedOnCompletion = false
// Draw circle 1
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
// Circle 2 animation
animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))]
// Draw circle 2
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
}
func circleAt(frame: CGRect, layer: CALayer, size: CGSize, color: UIColor, animation: CAAnimation) {
let circle = NVActivityIndicatorShape.circle.layerWith(size: size, color: color)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| 47.357143 | 160 | 0.649698 |
ffdbeac8267d5198d96cbb93499d63def30a455d
| 1,543 |
//
// Grade.swift
// Crush
//
// Created by Alex Albert on 12/30/17.
// Copyright © 2017 Alex Albert. All rights reserved.
//
import UIKit
import UserNotifications
import Firebase
class Grade: UIViewController {
let application: UIApplication = UIApplication.shared
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Grade Picker Button
@IBAction func gradePicker(gradeButton : UIButton) {
var grade: String!
switch gradeButton.tag {
case 1:
grade = "9th"
case 2:
grade = "10th"
case 3:
grade = "11th"
default:
grade = "12th"
}
ref.child("users").child(uid!).child("grade").setValue(grade)
performSegue(withIdentifier: "gradeLogged", sender: Any?.self)
var loggedIn = "true"
UserDefaults.standard.set(loggedIn, forKey: "loggedIn")
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {(_,_) in })
}else{
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
}
}
| 26.603448 | 122 | 0.723914 |
ab37320aa97e4bd39c5949db94fde2b9137869a4
| 7,649 |
//
// AppDelegate.swift
// AroundU
//
// Created by Richer Archambault on 2017-03-04.
// Copyright © 2017 LassondeHacks. All rights reserved.
//
import CoreLocation
import UIKit
import Material
struct defaultsKeys {
static let email = "email"
static let password = "password"
static let cookie = "Cookie"
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
open class var darkPrimary : UIColor {
return UIColor(red: 22,green: 137,blue: 206)
}
open class var primary : UIColor {
return UIColor(red: 30,green: 170,blue: 241)
}
open class var lightPrimary : UIColor {
return UIColor(red: 181,green: 229,blue: 251)
}
open class var accent : UIColor {
return UIColor(red: 252,green: 88,blue: 48)
}
open class var primaryText : UIColor {
return UIColor(red: 33,green: 33,blue: 33)
}
open class var secondaryText : UIColor {
return UIColor(red: 117,green: 117,blue: 117)
}
open class var divider : UIColor {
return UIColor(red: 189,green: 189,blue: 189)
}
}
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
var loggedIn : Bool {
let user = UserDefaults.standard.string(forKey: defaultsKeys.email)
let psswd = UserDefaults.standard.string(forKey: defaultsKeys.password)
if ( user != nil && psswd != nil) {
Connection.connect(user!, psswd!)
return true
}
return false
}
var created: Bool = false
var loginViewController: LoginViewController!
var mainViewController: MainViewController!
var loginToolbarController: LoginToolbarController!
var mainToolbarController: AppToolbarController!
var publishFABMenu: PublishFABMenuController!
var locationManager:CLLocationManager!
var userLocation: CLLocation!
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
}
func startUserLocation(){
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func getUserLocation() -> CLLocation {
return userLocation
}
func stopUserLocation(){
locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations[0] as CLLocation
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: Screen.bounds)
loginViewController = LoginViewController()
loginToolbarController = LoginToolbarController(rootViewController: loginViewController)
if(!loggedIn) {
window?.rootViewController = loginToolbarController
} else {
renderMainViewController()
}
window?.makeKeyAndVisible()
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "loggedIn"), object: nil, queue: nil, using: switchToMainViewController)
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "CameraShoulClose"), object: nil, queue: nil, using: closeCamera)
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "CameraShoulOpen"), object: nil, queue: nil, using: openCamera)
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "willPublishText"), object: nil, queue: nil, using: switchToPublishTextView)
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "willPublishImage"), object: nil, queue: nil, using: switchToPublishImageView)
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "PublishShouldTerminate"), object: nil, queue: nil, using: switchToMainViewController)
determineMyCurrentLocation()
return true
}
func applicationWillResignActive(_ application: UIApplication) {}
func applicationDidEnterBackground(_ application: UIApplication) {}
func applicationWillEnterForeground(_ application: UIApplication) {}
func applicationDidBecomeActive(_ application: UIApplication) {}
func applicationWillTerminate(_ application: UIApplication) {}
func closeCamera(notification: Notification) {
UIView.transition(with: window!, duration: 0.5, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { Void in
self.window?.rootViewController = self.publishFABMenu
}, completion: nil)
}
func openCamera(notification: Notification) {
UIView.transition(with: window!, duration: 0.5, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { Void in
self.window?.rootViewController = AppCaptureController(rootViewController: CameraViewController())
}, completion: nil)
}
func switchToPublishTextView(notification: Notification) {
UIView.transition(with: window!, duration: 0.5, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { Void in
self.window?.rootViewController = PublishTextViewController()
}, completion: nil)
}
func switchToPublishImageView(notification: Notification) {
UIView.transition(with: window!, duration: 0.5, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { Void in
self.window?.rootViewController = PublishMediaViewController(image: notification.userInfo?["image"] as! UIImage)
}, completion: nil)
}
func switchToMainViewController(notification: Notification) {
renderMainViewController()
}
func renderMainViewController() {
if(!created) {
mainViewController = MainViewController()
mainToolbarController = AppToolbarController(rootViewController: mainViewController)
publishFABMenu = PublishFABMenuController(rootViewController: mainToolbarController)
self.window?.rootViewController = self.publishFABMenu
created = true
} else {
UIView.transition(with: window!, duration: 0.5, options: UIViewAnimationOptions.transitionFlipFromRight, animations: { Void in
self.window?.rootViewController = self.publishFABMenu
}, completion: nil)
}
}
}
| 37.312195 | 172 | 0.684011 |
fbf9908f4dc93d724c76e357f92e2c1a6e77137a
| 571 |
// RUN: %target-swift-frontend -emit-ir %s | FileCheck %s
func markUsed<T>(t: T) {}
protocol A {
typealias B
func b(_: B)
}
struct X<Y> : A {
// CHECK-LABEL: define hidden void @_TTWurGV23dependent_reabstraction1Xx_S_1AS_FS1_1bfwx1BT_(%swift.type** noalias nocapture dereferenceable({{.*}}), %V23dependent_reabstraction1X* noalias nocapture, %swift.type* %Self)
func b(b: X.Type) {
let x: Any = b
markUsed(b as X.Type)
}
}
func foo<T: A>(x: T, _ y: T.B) {
x.b(y)
}
let a = X<Int>()
let b = X<String>()
foo(a, X<Int>.self)
foo(b, X<String>.self)
| 21.148148 | 221 | 0.642732 |
e59b9fa59687e542bca4f126056de8cb1dd7d328
| 893 |
//
// PreworkTests.swift
// PreworkTests
//
// Created by Katrina Tsun on 9/10/21.
//
import XCTest
@testable import Prework
class PreworkTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.264706 | 111 | 0.661814 |
20a6d5cf6de261b66eb9702605de5f02074fb904
| 1,533 |
//
// ViewStyle.swift
// DesignElements
//
// Created by Михаил on 27/09/2019.
// Copyright © 2019 Handsapp. All rights reserved.
//
import UIKit
public extension StyleWrapper where Element == UIView {
/// Round corners for view with radius XS
static let roundCornersXs: StyleWrapper = .wrap { view, _ in
view.layer.cornerRadius = Grid.xs.offset
}
/// Round corners for view with radius S
static let roundCornersS: StyleWrapper = .wrap { view, _ in
view.layer.cornerRadius = Grid.s.offset
}
/// Round corners for view with radius SM
static let roundCornersSm: StyleWrapper = .wrap { view, _ in
view.layer.cornerRadius = Grid.sm.offset
}
/// Round corners for view with radius M
static let roundCornersM: StyleWrapper = .wrap { view, _ in
view.layer.cornerRadius = Grid.m.offset
}
/// Round corners for view with radius ML
static let roundCornersMl: StyleWrapper = .wrap { view, _ in
view.layer.cornerRadius = Grid.ml.offset
}
/// Round corners for view with radius L
static let roundCornersL: StyleWrapper = .wrap { view, _ in
view.layer.cornerRadius = Grid.l.offset
}
/// Round corners for view with radius XL
static let roundCornersXl: StyleWrapper = .wrap { view, _ in
view.layer.cornerRadius = Grid.xl.offset
}
/// Round corners for view with radius XXL
static let roundCornersXxl: StyleWrapper = .wrap { view, _ in
view.layer.cornerRadius = Grid.xxl.offset
}
}
| 33.326087 | 65 | 0.666014 |
089e5e3c384ee7ca30944280213b0342d927ee09
| 4,793 |
//
// BangTests.swift
// CardGameEngine_Tests
//
// Created by Hugues Stephano Telolahy on 04/10/2020.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import XCTest
import WildWestEngine
import Resolver
class BangTests: XCTestCase {
private let sut: GameRulesProtocol = Resolver.resolve()
func test_CanPlayBang_IfOtherIsReachable() throws {
// Given
let mockCard1 = MockCardProtocol()
.withDefault()
.identified(by: "c1")
.type(is: .brown)
.abilities(are: "bang")
let mockPlayer1 = MockPlayerProtocol()
.withDefault()
.identified(by: "p1")
.holding(mockCard1)
let mockPlayer2 = MockPlayerProtocol()
.withDefault()
.identified(by: "p2")
let mockPlayer3 = MockPlayerProtocol()
.withDefault()
.identified(by: "p3")
.attributes(are: [.mustang: 2])
let mockState = MockStateProtocol()
.withDefault()
.turn(is: "p1")
.phase(is: 2)
.players(are: mockPlayer1, mockPlayer2, mockPlayer3)
.playOrder(is: "p1", "p2", "p3")
// When
let moves = sut.active(in: mockState)
let events = sut.effects(on: try XCTUnwrap(moves?.first), in: mockState)
// Assert
XCTAssertEqual(moves, [GMove("bang", actor: "p1", card: .hand("c1"), args: [.target: ["p2"]])])
XCTAssertEqual(events, [.play(player: "p1", card: "c1"),
.addHit(hit: GHit(name: "bang", players: ["p2"], abilities: ["looseHealth"], cancelable: 1))])
}
func test_CannotPlayBang_IfReachedLimitPerTurn() throws {
// Given
let mockCard1 = MockCardProtocol()
.withDefault()
.identified(by: "c1")
.abilities(are: "bang")
let mockPlayer1 = MockPlayerProtocol()
.withDefault()
.identified(by: "p1")
.holding(mockCard1)
let mockPlayer2 = MockPlayerProtocol()
.withDefault()
.identified(by: "p2")
let mockState = MockStateProtocol()
.withDefault()
.turn(is: "p1")
.phase(is: 2)
.players(are: mockPlayer1, mockPlayer2)
.playOrder(is: "p1", "p2")
.played(are: "bang")
// When
let moves = sut.active(in: mockState)
// Assert
XCTAssertNil(moves)
}
func test_CannotPlayBang_IfOtherIsUnreachable() throws {
// Given
let mockCard1 = MockCardProtocol()
.withDefault()
.identified(by: "c1")
.abilities(are: "bang")
let mockPlayer1 = MockPlayerProtocol()
.withDefault()
.identified(by: "p1")
.holding(mockCard1)
let mockPlayer2 = MockPlayerProtocol()
.withDefault()
.identified(by: "p2")
.attributes(are: [.mustang: 1])
let mockState = MockStateProtocol()
.withDefault()
.turn(is: "p1")
.phase(is: 2)
.players(are: mockPlayer1, mockPlayer2)
.playOrder(is: "p1", "p2")
// When
let moves = sut.active(in: mockState)
// Assert
XCTAssertNil(moves)
}
func test_Need2MissesToCancelHisBang_IfPlayingBangAndHAvingAbility() throws {
// Given
let mockCard1 = MockCardProtocol()
.withDefault()
.identified(by: "c1")
.type(is: .brown)
.abilities(are: "bang")
let mockPlayer1 = MockPlayerProtocol()
.withDefault()
.identified(by: "p1")
.holding(mockCard1)
.playing(MockCardProtocol().withDefault().attributes(are: [.weapon: 2]))
.attributes(are: [.bangsCancelable: 2])
let mockPlayer2 = MockPlayerProtocol()
.withDefault()
.identified(by: "p2")
.attributes(are: [.mustang: 1])
let mockState = MockStateProtocol()
.withDefault()
.turn(is: "p1")
.phase(is: 2)
.players(are: mockPlayer1, mockPlayer2)
.playOrder(is: "p1", "p2")
// When
let moves = sut.active(in: mockState)
let events = sut.effects(on: try XCTUnwrap(moves?.first), in: mockState)
// Assert
XCTAssertEqual(moves, [GMove("bang", actor: "p1", card: .hand("c1"), args: [.target: ["p2"]])])
XCTAssertEqual(events, [.play(player: "p1", card: "c1"),
.addHit(hit: GHit(name: "bang", players: ["p2"], abilities: ["looseHealth"], cancelable: 2))])
}
}
| 33.753521 | 126 | 0.528062 |
bff26903b077765648b122524996dc7498d32008
| 4,109 |
//
// QCarouselCardCell.swift
// Qiscus
//
// Created by Ahmad Athaullah on 08/01/18.
// Copyright © 2018 Ahmad Athaullah. All rights reserved.
//
import UIKit
public protocol QCarouselCardDelegate {
func carouselCard(cardCell:QCarouselCardCell, didTapAction card:QCardAction)
}
public class QCarouselCardCell: UICollectionViewCell {
@IBOutlet weak var containerArea: UIView!
@IBOutlet weak var displayImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UITextView!
@IBOutlet weak var buttonContainer: UIStackView!
@IBOutlet weak var buttonAreaHeight: NSLayoutConstraint!
@IBOutlet weak var cardHeight: NSLayoutConstraint!
@IBOutlet weak var descriptionHeight: NSLayoutConstraint!
@IBOutlet weak var cardWidth: NSLayoutConstraint!
var buttons = [UIButton]()
var height = CGFloat(0)
public var cardDelegate: QCarouselCardDelegate?
var card:QCard?{
didSet{
if self.card != nil{
self.cardChanged()
}
}
}
override public func awakeFromNib() {
super.awakeFromNib()
self.containerArea.layer.cornerRadius = 10.0
self.containerArea.layer.borderWidth = 0.5
self.containerArea.layer.borderColor = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1).cgColor
self.containerArea.clipsToBounds = true
self.containerArea.layer.zPosition = 999
self.displayImageView.contentMode = .scaleAspectFill
self.displayImageView.clipsToBounds = true
self.cardWidth.constant = QiscusHelper.screenWidth() * 0.70
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(QCarouselCardCell.cardTapped))
self.containerArea.addGestureRecognizer(tapRecognizer)
}
func setupWithCard(card:QCard, height: CGFloat){
self.height = height
self.card = card
}
func cardChanged(){
if self.card!.displayURL != "" {
self.displayImageView.loadAsync(self.card!.displayURL)
}else{
self.displayImageView.image = nil
}
self.titleLabel.text = self.card!.title
self.descriptionLabel.text = self.card!.desc
for currentButton in self.buttons {
self.buttonContainer.removeArrangedSubview(currentButton)
currentButton.removeFromSuperview()
}
self.buttons = [UIButton]()
var yPos = CGFloat(0)
let titleColor = UIColor(red: 101/255, green: 119/255, blue: 183/255, alpha: 1)
var i = 0
let buttonWidth = QiscusHelper.screenWidth() * 0.70
for action in self.card!.actions{
let buttonFrame = CGRect(x: 0, y: yPos, width: buttonWidth, height: 45)
let button = UIButton(frame: buttonFrame)
button.setTitle(action.title, for: .normal)
button.tag = i
let borderFrame = CGRect(x: 0, y: 0, width: buttonWidth, height: 0.5)
let buttonBorder = UIView(frame: borderFrame)
buttonBorder.backgroundColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
button.setTitleColor(titleColor, for: .normal)
button.addSubview(buttonBorder)
self.buttons.append(button)
self.buttonContainer.addArrangedSubview(button)
button.addTarget(self, action: #selector(cardButtonTapped(_:)), for: .touchUpInside)
yPos += 45
i += 1
}
self.buttonAreaHeight.constant = yPos
self.cardHeight.constant = height - 185
self.containerArea.layoutIfNeeded()
}
@objc func cardButtonTapped(_ sender: UIButton) {
if let c = self.card {
self.cardDelegate?.carouselCard(cardCell: self, didTapAction: c.actions[sender.tag])
}
}
@objc func cardTapped(){
if let c = self.card {
if let action = c.defaultAction {
self.cardDelegate?.carouselCard(cardCell: self, didTapAction: action)
}
}
}
}
| 37.697248 | 113 | 0.637625 |
8f2c9ec06225358ec31665a13e9e727aabdaabdf
| 1,328 |
//
// UINavigationHelper.swift
// WeChatMoments
//
// Created by rainedAllNight on 2019/11/28.
// Copyright © 2019 luowei. All rights reserved.
//
import Foundation
import UIKit
public protocol WCNavigationControllerDelegate: class {
func alphaOfNavigationBar(in navigationController: UINavigationController) -> CGFloat
}
extension UINavigationController {
fileprivate func updateNavBar(_ alpha: CGFloat, originalColor: UIColor) {
var wcAlpha = alpha > 0.99 ? 0.99 : alpha
wcAlpha = wcAlpha < 0.0 ? 0.0 : wcAlpha
let navBgImage = UIImage.imageWithColor(originalColor)
let navBgImageWithAlpha = navBgImage.imageWithAlpha((wcAlpha))
self.navigationBar.setBackgroundImage(navBgImageWithAlpha, for: .default)
}
public func updateNavBar(with originalColor: UIColor) {
guard let topViewController = self.topViewController else {
return
}
if let delegate = topViewController as? WCNavigationControllerDelegate {
let alpha = delegate.alphaOfNavigationBar(in: self)
updateNavBar(alpha, originalColor: originalColor)
} else {
let navBgImage = UIImage.imageWithColor(originalColor)
self.navigationBar.setBackgroundImage(navBgImage, for: .default)
}
}
}
| 33.2 | 89 | 0.690512 |
721783b4471dcd679b279e6fb830863bbbe171e8
| 5,427 |
//
// TrendingViewModel.swift
// Giraffe-iOS
//
// Created by Evgen Dubinin on 7/16/16.
// Copyright © 2016 Yevhen Dubinin. All rights reserved.
//
import Foundation
import ReactiveCocoa
import GiraffeKit
// MARK: ViewModel Protocol -
struct TrendingViewModel: ViewModelType {
private struct Constants {
static let RetryAttempts: Int = Int.max
}
private let model: Pageable
private let response = MutableProperty<Response?>(nil)
private let items = MutableProperty<[Item]>([])
// messages
private let fetchErrorMsg = "Something went wrong while getting trending"
private let blankMsg = ""
private let emptyResponseMsg = "No items were found"
// images
private let loadingImage = UIImage(named: "GiraffeIsThinking")
private let notFoundImage = UIImage(named: "GiraffeIsDisappointed")
// MARK: ViewModelType -
let isActive = MutableProperty<Bool>(false)
let message = MutableProperty<String>("")
let shouldHideItemsView = MutableProperty<Bool>(true)
let itemViewModels = MutableProperty<[AnimatedImageViewModel]>([])
let shouldDenoteTrending = ConstantProperty<Bool>(false)
let isLoading = MutableProperty<Bool>(false)
let statusImage = MutableProperty<UIImage?>(nil)
// MARK: ViewModel Public Properties -
let headline = ConstantProperty<String?>("Trending")
let searchText = MutableProperty<String>("")
let searchResultViewModel = MutableProperty<SearchResultViewModel?>(nil)
let shouldEnableSearchButton = MutableProperty<Bool>(false)
let didScrollToBottom = MutableProperty<Void>()
// MARK: Initialization -
init(model: Pageable) {
self.model = model
// Setup RAC bindings.
self.setupBindings()
}
func setupBindings() {
self.isActive.producer
.filter { $0 }
.mapError { _ in
return GiraffeError.UnknownError
}.on(next: { _ in
self.isLoading.value = true
self.statusImage.value = self.loadingImage
})
.flatMap(.Latest) { _ in
return self.model.nextPage()
}
.on(failed: { _ in
self.isLoading.value = false
self.message.value = self.fetchErrorMsg
self.statusImage.value = nil
},
next: { _ in
self.isLoading.value = false
self.statusImage.value = nil
}
)
// HACK: We'd like to receive an error and update the UI, but it well known
// that SignalProducer stops upon failure, thus we have to retry it.
// For now, retry as much as we can (Int.max times). There has to be more correct way to do this
.retry(Constants.RetryAttempts)
.startWithResult { result in
self.response.value = result.value!
self.message.value = self.response.value!.zeroItems ? self.emptyResponseMsg : self.blankMsg
}
self.items <~ self.response.producer
.ignoreNil()
.map { response in
var result = self.items.value
result.appendContentsOf(response.data)
return result
}
self.itemViewModels <~ self.items.producer.map { items in
items.map { AnimatedImageViewModel(model: $0, denoteTrending: self.shouldDenoteTrending.value) }
}
let noItemsSignal = self.items.producer.map { items in
items.count == 0
}
self.shouldHideItemsView <~ noItemsSignal
self.statusImage <~ noItemsSignal.map { $0 ? self.notFoundImage : nil }
self.searchText.producer
.startWithResult { result in
if let query: String = result.value {
let searchModel = SearchResult(query: query)
let searchResultViewModel = SearchResultViewModel(model: searchModel)
searchResultViewModel.headline.value = query
self.searchResultViewModel.value = searchResultViewModel
}
}
self.shouldEnableSearchButton <~ self.isLoading.producer.map { !$0 }
let loadNextPage = self.didScrollToBottom.producer
loadNextPage
// prevent from calling this at first place, before the first set is loaded
// this is weird, but it works
.filter {_ in self.items.value.count > 0 }
.flatMap(.Latest) { _ in
return self.model.nextPage()
}
// HACK: We'd like to receive an error and update the UI, but it well known
// that SignalProducer stops upon failure, thus we have to retry it.
// For now, retry as much as we can (Int.max times). There has to be more correct way to do this
.retry(Constants.RetryAttempts)
.startWithResult { result in
self.response.value = result.value!
}
}
}
| 38.489362 | 108 | 0.565874 |
4bd0d20194cca3c1376a4e63ae89d554f2ad5f14
| 2,136 |
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
SceneKit node wrapper shows debug info for AR detected planes.
*/
import Foundation
import ARKit
class PlaneDebugVisualization: SCNNode {
var planeAnchor: ARPlaneAnchor
var planeGeometry: SCNPlane
var planeNode: SCNNode
init(anchor: ARPlaneAnchor) {
self.planeAnchor = anchor
let grid = UIImage(named: "Models.scnassets/plane_grid.png")
self.planeGeometry = createPlane(size: CGSize(width: CGFloat(anchor.extent.x), height: CGFloat(anchor.extent.z)),
contents: grid)
self.planeNode = SCNNode(geometry: planeGeometry)
self.planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2.0, 1, 0, 0)
super.init()
let originVisualizationNode = createAxesNode(quiverLength: 0.1, quiverThickness: 1.0)
self.addChildNode(originVisualizationNode)
self.addChildNode(planeNode)
self.position = SCNVector3(anchor.center.x, -0.002, anchor.center.z) // 2 mm below the origin of plane.
adjustScale()
}
func update(_ anchor: ARPlaneAnchor) {
self.planeAnchor = anchor
self.planeGeometry.width = CGFloat(anchor.extent.x)
self.planeGeometry.height = CGFloat(anchor.extent.z)
self.position = SCNVector3Make(anchor.center.x, -0.002, anchor.center.z)
adjustScale()
}
func update(extent: vector_float3) {
self.planeGeometry.width = CGFloat(extent.x)
self.planeGeometry.height = CGFloat(extent.z)
adjustScale()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func adjustScale() {
let scaledWidth: Float = Float(planeGeometry.width / 2.4)
let scaledHeight: Float = Float(planeGeometry.height / 2.4)
let offsetWidth: Float = -0.5 * (scaledWidth - 1)
let offsetHeight: Float = -0.5 * (scaledHeight - 1)
let material = self.planeGeometry.materials.first
var transform = SCNMatrix4MakeScale(scaledWidth, scaledHeight, 1)
transform = SCNMatrix4Translate(transform, offsetWidth, offsetHeight, 0)
material?.diffuse.contentsTransform = transform
}
}
| 28.864865 | 115 | 0.715824 |
75b9bbd43f0abf9a482dfe5cdddaf9f89fd2f320
| 5,389 |
//
// Networking.swift
// Grocery
//
// Created by Melody on 11/10/17.
// Copyright © 2017 Melody Yang. All rights reserved.
//
import Foundation
import KeychainSwift
let keychain = KeychainSwift()
enum Route {
case createUser
case getUser
case saveRecipe
case deleteRecipe
case getRecipe(query: String)
case analyzeImage
case shareNote
case retrieveRecipe // retrieve user's own notes
case saveNote
case getGlobalRecipe // get recipe variations
//10.206.106.47
//127.0.0.1
func path() -> String {
switch self {
case .createUser, .getUser:
return "https://sharecipe-app.herokuapp.com/users" // replace 127.0.0.1 with IP address
case .saveRecipe, .deleteRecipe, .retrieveRecipe, .saveNote:
return "https://sharecipe-app.herokuapp.com/recipes"
case let .getRecipe(query):
return "https://api.edamam.com/search?app_id=b50e6417&app_key=c845cafa9a669a2a5db0148d11af4e93&q=\(query)"
case .shareNote, .getGlobalRecipe:
return "https://sharecipe-app.herokuapp.com/global_recipes"
case .analyzeImage:
return "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify"
}
}
func headers() -> [String: String] {
switch self {
case .getUser, .retrieveRecipe, .saveNote:
let headers = ["Content-Type": "application/json",
"Accept": "application/json",
"Authorization": String(describing: keychain.get("BasicAuth")!)]
return headers
case .getRecipe:
let headers = [
"Content-Type": "application/json",
"Accept": "application/json"]
return headers
case .analyzeImage:
return ["Content-Type": ""]
default:
let headers = ["Content-Type": "application/json",
"Accept": "application/json"]
return headers
}
}
func urlParams() -> [String: String] {
switch self {
case .createUser, .getGlobalRecipe:
return [:]
case .getUser, .retrieveRecipe, .saveNote:
return ["email": "\(keychain.get("email")!)"]
case .getRecipe:
return ["q": "vallina"]
case .analyzeImage:
let urlParams = ["api_key": "a33be142c28212ecf61c5fd19f05a76a08e845d7",
"version": "2016-05-20",
"image_files": ".jpg",
"Accept-Language": "en",
//TODO: pass in dynamic ImageURL
"url": "https://www.edamam.com/web-img/58a/58a93a8d0c48110ac1c59e3b6e82a9ef.jpg"]
return urlParams
default:
let urlParams = ["email": String(describing: keychain.get("email")!)]
return urlParams
}
}
func body(data: Encodable?) -> Data? {
let encoder = JSONEncoder()
switch self {
case .createUser:
guard let model = data as? User else {return nil}
let result = try? encoder.encode(model)
return result
case .saveRecipe:
guard let model = data as? UserRecipe else {return nil}
let result = try? encoder.encode(model)
return result
case .saveNote:
guard let model = data as? Notes else {return nil}
let result = try? encoder.encode(model)
return result
case .shareNote:
guard let model = data as? GlobalRecipe else {return nil}
let result = try? encoder.encode(model)
return result
default:
return nil
}
}
func method() -> String {
switch self {
case .createUser, .analyzeImage, .shareNote, .saveRecipe, .saveNote:
return "POST"
case .deleteRecipe:
return "DELETE"
default:
return "GET"
}
}
}
var status = 0
class Networking {
static var shared = Networking()
let session = URLSession.shared
var statusCode = 0
func fetch(route: Route, data: Encodable?, params: [String:String]?, completion: @escaping (Data) -> Void) {
let base = route.path()
var url = URL(string: base)!
// var q = params?.values
if (params?.isEmpty)! {
url = url.appendingQueryParameters(route.urlParams())
}
url = url.appendingQueryParameters(params!)
var request = URLRequest(url: url)
request.allHTTPHeaderFields = route.headers()
request.httpBody = route.body(data: data)
request.httpMethod = route.method()
session.dataTask(with: request) { (data, res, err) in
let httpResponse = res as? HTTPURLResponse
if let data = data {
self.statusCode = (httpResponse?.statusCode)!
print(self.statusCode)
completion(data)
print("Networking succeeded")
}
else {
print(err?.localizedDescription ?? "Error")
}
}.resume()
}
}
| 31.7 | 118 | 0.539618 |
5beab8c99790595d0b4513ec4d8036618a482ec5
| 1,177 |
//
// Copyright (C) 2005-2022 Alfresco Software Limited.
//
// This file is part of the Alfresco Content Mobile iOS App.
//
// 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
protocol FileManagerAssetDelegate: AnyObject {
/// Notifies the delegate the review session is over and delivers captured asset information.
/// - Note: It is expected that the receiver copies over any desired disk data as the default capture location should be
/// cleared out after this call.
/// - Parameter selectedAssets: selected asset information containing metadata and path information
func didEndFileManager(for selectedAssets: [FileAsset])
}
| 42.035714 | 124 | 0.750212 |
d65c2f6975a398cd51867d8fa456afd0ae5685fc
| 3,578 |
//
// ViewController.swift
// PassGenerator
//
// Created by Sebastian San Blas on 20/06/2021.
//
import UIKit
class PassGeneratorViewController: UIViewController {
// Switchs
@IBOutlet var lowercaseSwitch: UISwitch!
@IBOutlet var uppercaseSwitch: UISwitch!
@IBOutlet var numberSwitch: UISwitch!
@IBOutlet var punctuationSwitch: UISwitch!
@IBOutlet var symbolsSwitch: UISwitch!
// Slider
@IBOutlet var lengthSlider: UISlider!
@IBOutlet var lengthValueSlider: UILabel!
// Buttons
@IBAction func regenerateButton(_ sender: Any) {
passwordLabel.text = generatePassword()
}
@IBAction func copyButton(_ sender: Any) {
UIPasteboard.general.string = passwordLabel.text
showCopyButton()
}
// Label
@IBOutlet var passwordLabel: UILabel!
@IBOutlet var statusCopyButton: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
lowercaseSwitch.isOn = true
uppercaseSwitch.isOn = true
numberSwitch.isOn = false
punctuationSwitch.isOn = false
symbolsSwitch.isOn = false
lengthSlider.value = 16
lengthValueSlider.text = String(Int(lengthSlider.value))
passwordLabel.text = generatePassword()
statusCopyButton.isHidden = true
}
@IBAction func lowercaseChanged(_ sender: Any) {
passwordLabel.text = generatePassword()
}
@IBAction func uppercaseChanged(_ sender: Any) {
passwordLabel.text = generatePassword()
}
@IBAction func numberChanged(_ sender: Any) {
passwordLabel.text = generatePassword()
}
@IBAction func punctuationChanged(_ sender: Any) {
passwordLabel.text = generatePassword()
}
@IBAction func symbolsChanged(_ sender: Any) {
passwordLabel.text = generatePassword()
}
@IBAction func sliderChanged(_ sender: Any) {
lengthValueSlider.text = String(Int(lengthSlider.value))
passwordLabel.text = generatePassword()
}
func generatePassword() -> String {
var password: String
password = PasswordGenerator.sharedInstance.generatePassword(includeLower: lowercaseSwitch.isOn,
includeUpper: uppercaseSwitch.isOn,
includeNumbers: numberSwitch.isOn,
includePunctuation: punctuationSwitch.isOn,
includeSymbols: symbolsSwitch.isOn,
length: Int(lengthSlider.value))
if password.isEmpty == true {
let alert = UIAlertController(title: "I can't allow it!", message: "You must select at least one option!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK, I got it", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
return password
}
func showCopyButton() {
statusCopyButton.isHidden = false
UIView.animate(withDuration: 1, delay: 0.25, options: UIView.AnimationOptions.transitionFlipFromTop, animations: {
self.statusCopyButton.alpha = 0
}, completion: { finished in
self.statusCopyButton.isHidden = true
self.statusCopyButton.alpha = 1
})
}
}
| 36.141414 | 142 | 0.594187 |
6475245f01427d92c98f7fe743a765d170dfee60
| 2,535 |
//
// Copyright (c) 2019 Adyen N.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
import UIKit
/// Displays a form for the user to enter details.
/// :nodoc:
internal final class FormView: UIView {
/// Initializes the form view.
internal init() {
super.init(frame: .zero)
backgroundColor = .componentBackground
addSubview(scrollView)
configureConstraints()
}
/// :nodoc:
internal required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Item Views
/// Appends an item view to the stack of item views.
///
/// - Parameter itemView: The item view to append.
internal func appendItemView(_ itemView: UIView) {
stackView.addArrangedSubview(itemView)
}
// MARK: - Scroll View
/// The form view's scroll view.
internal private(set) lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.preservesSuperviewLayoutMargins = true
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
return scrollView
}()
// MARK: - Stack View
private lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .fill
stackView.preservesSuperviewLayoutMargins = true
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
// MARK: - Layout
private func configureConstraints() {
let constraints = [
scrollView.topAnchor.constraint(equalTo: topAnchor),
scrollView.leadingAnchor.constraint(equalTo: leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: bottomAnchor),
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
]
NSLayoutConstraint.activate(constraints)
}
}
| 30.914634 | 100 | 0.644181 |
db31d639aed3119cf38afbab8034b711f29a3bfd
| 4,666 |
//
// TestMnemonic.swift
// Bitcoin_Tests
//
// Created by Wolf McNally on 10/29/18.
//
// Copyright © 2018 Blockchain Commons.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
import Bitcoin
import WolfCore
class TestMnemonic: XCTestCase {
func testNewMnemonic() {
func test(_ seed: String, _ language: Language, _ mnemonic: String) -> Bool {
let a = seed
return try! a |> dataLiteral |> newMnemonic(language: language) |> rawValue == mnemonic
}
XCTAssert(test("baadf00dbaadf00d", .en, "rival hurdle address inspire tenant alone"))
XCTAssert(test("baadf00dbaadf00dbaadf00dbaadf00d", .en, "rival hurdle address inspire tenant almost turkey safe asset step lab boy"))
XCTAssertThrowsError(try "baadf00dbaadf00dbaadf00dbaadf00dff" |> dataLiteral |> newMnemonic(language: .en) == "won't happen") // Invalid seed size
XCTAssert(test("7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", .en, "legal winner thank year wave sausage worth useful legal winner thank yellow"))
XCTAssert(test("baadf00dbaadf00dbaadf00dbaadf00d", .es, "previo humilde actuar jarabe tabique ahorro tope pulpo anís señal lavar bahía"))
XCTAssert(test("baadf00dbaadf00dbaadf00dbaadf00d", .fr, "placard garantir acerbe gratuit soluble affaire théorie ponctuel anguleux salon horrible bateau"))
XCTAssert(test("baadf00dbaadf00dbaadf00dbaadf00d", .it, "rizoma lastra affabile lucidato sultano algebra tramonto rupe annuncio sonda mega bavosa"))
XCTAssert(test("baadf00dbaadf00dbaadf00dbaadf00d", .ja, "ねんかん すずしい あひる せたけ ほとんど あんまり めいあん のべる いなか ふとる ぜんりゃく えいせい"))
XCTAssert(test("baadf00dbaadf00dbaadf00dbaadf00d", .cs, "semeno mudrc babka nasekat uvolnit bazuka vydra skanzen broskev trefit nuget datel"))
XCTAssert(test("baadf00dbaadf00dbaadf00dbaadf00d", .ru, "ремарка кривой айсберг лауреат тротуар амнезия фонтан рояль бакалея сухой магазин бунт"))
XCTAssert(test("baadf00dbaadf00dbaadf00dbaadf00d", .uk, "сержант ледачий актив люкс фах арена цемент слон бесіда тротуар мандри верба"))
XCTAssert(test("baadf00dbaadf00dbaadf00dbaadf00d", .zh_Hans, "博 肉 地 危 惜 多 陪 荒 因 患 伊 基"))
XCTAssert(test("baadf00dbaadf00dbaadf00dbaadf00d", .zh_Hant, "博 肉 地 危 惜 多 陪 荒 因 患 伊 基"))
}
func testMnemonicToSeed() {
func test(_ m: String, seed: String) -> Bool {
return try! m |> tagMnemonic |> toSeed |> toBase16 |> rawValue == seed
}
XCTAssert(test("rival hurdle address inspire tenant alone", seed: "33498afc5ef71e87afd7cad1e50a9d9adb9e30d3ca4b1da5dc370d266aa7796cbc1854eebce5ab3fd3b02b6625e2a82868dbb693e988e47d74106f04c76a6263"))
}
func testMnemonicToSeedWithPassphrase() {
func test(_ m: String, passphrase: String, seed: String) -> Bool {
return try! m |> tagMnemonic |> toSeed(passphrase: passphrase) |> toBase16 |> rawValue == seed
}
XCTAssert(test("legal winner thank year wave sausage worth useful legal winner thank yellow", passphrase: "TREZOR", seed: "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607"))
XCTAssert(test("legal winner thank year wave sausage worth useful legal winner thank yellow", passphrase: "博 肉 地 危 惜 多 陪 荒 因 患 伊 基", seed: "3e52585ea1275472a82fa0dcd84121e742140f64a302eca7c390832ba428c707a7ebf449267ae592c51f1740259226e31520de39fd8f33e08788fd21221c6f4e"))
XCTAssert(test("previo humilde actuar jarabe tabique ahorro tope pulpo anís señal lavar bahía", passphrase: "博 肉 地 危 惜 多 陪 荒 因 患 伊 基", seed: "e72505021b97e15171fe09e996898888579c4196c445d7629762c5b09586e3fb3d68380120b8d8a6ed6f9a73306dab7bf54127f3a610ede2a2d5b4e59916ac73"))
}
func testWordList() throws {
let words = wordList(for: .en)
XCTAssertEqual(words.count, 2048)
func wordsWithPrefix(_ prefix: String) -> [String] {
return words.filter { $0.hasPrefix(prefix) }
}
XCTAssertEqual(wordsWithPrefix("af"), ["affair", "afford", "afraid"])
XCTAssertEqual(wordsWithPrefix("zo"), ["zone", "zoo"])
}
}
| 59.820513 | 281 | 0.729318 |
612542c8794d616ce9e668ad693a1878c8f2da86
| 285 |
import Foundation
struct ProtocolMetadataLayout: MetadataLayoutType {
var valueWitnessTable: UnsafePointer<ValueWitnessTable>
var kind: Int
var layoutFlags: Int
var numberOfProtocols: Int
var protocolDescriptorVector: UnsafeMutablePointer<ProtocolDescriptor>
}
| 21.923077 | 74 | 0.796491 |
de80bb74fb091a33743d0ba48efbc07e11c25443
| 281 |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A {
func d
typealias B : B {
}
}
func < {
{
}
func b> {
{
}
return {
var b {
{
}
{
}
class a {
let a {
| 11.708333 | 87 | 0.658363 |
bff094a0ddf9409d8dd1cab878f10b5ed78e1f37
| 1,002 |
//
// SettinngsViewController.swift
// Tippy
//
// Created by aria javanmard on 4/5/20.
// Copyright © 2020 aria javanmard. All rights reserved.
//
import UIKit
class SettinngsViewController: UIViewController {
@IBOutlet weak var customField: UITextField!
@IBAction func customFieldAction(_ sender: Any) {
Custom = Double(customField.text!) ?? 0
UserDefaults.standard.set(Custom, forKey: "DoubleCustom")
}
override func viewDidLoad() {
super.viewDidLoad()
customField.becomeFirstResponder()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 25.05 | 106 | 0.654691 |
46925ac09d23fefe3b02c0939c8dcbc2444881f2
| 4,417 |
//
// SugoEventsSerializer.swift
// Sugo
//
// Created by Zack on 18/1/17.
// Copyright © 2017年 sugo. All rights reserved.
//
import Foundation
class SugoEventsSerializer {
class func encode(batch: [[String: Any]]) -> String? {
let userDefaults = UserDefaults.standard
let dimensions = userDefaults.object(forKey: "SugoDimensions") as! [[String: Any]]
var types = [String: String]()
var localKeys = [String]()
var keys = [String]()
var values = [[String: Any]]()
var dataString = String()
let TypeSeperator = "|"
let KeysSeperator = ","
let ValuesSeperator = "\(Character(UnicodeScalar(1)))"
let LinesSeperator = "\(Character(UnicodeScalar(2)))"
// Mark: - For keys
for object in batch {
for key in object.keys.reversed() {
if !localKeys.contains(key) {
localKeys.append(key)
}
}
}
for dimension in dimensions {
let dimensionKey = "\(dimension["name"]!)"
for key in localKeys {
if dimensionKey == key {
keys.append(key)
}
}
}
// Mark: - For types
for dimension in dimensions {
let dimensionKey = "\(dimension["name"]!)"
let dimensionType = "\(dimension["type"]!)"
var type: String?
for key in keys {
if dimensionKey == key {
switch dimensionType {
case "0":
type = "l"
break
case "7":
fallthrough
case "8":
fallthrough
case "1":
type = "f"
break
case "2":
type = "s"
break
case "4":
type = "d"
break
case "5":
type = "i"
break
default:
break
}
if type != nil {
types[key] = type!
}
break
}
}
}
for key in keys {
dataString = dataString + types[key]! + TypeSeperator + key + KeysSeperator
}
dataString = String(dataString[dataString.startIndex..<dataString.index(before: dataString.endIndex)])
dataString = dataString + LinesSeperator
// Mark: - For values
for object in batch {
var value: [String: Any] = [String: Any]()
for key in keys {
if object[key] != nil {
if types[key] == "i" {
value[key] = object[key]
} else if types[key] == "l" {
value[key] = object[key]
} else if types[key] == "f" {
value[key] = object[key]
} else if types[key] == "d" {
value[key] = object[key]
} else if types[key] == "s" {
value[key] = object[key]
} else {
value[key] = ""
}
} else {
value[key] = ""
}
}
values.append(value)
}
for value in values {
for key in keys {
dataString = dataString + "\(value[key]!)" + ValuesSeperator
}
dataString.removeLast()
dataString = dataString + LinesSeperator
}
return base64Encode(dataString: dataString)
}
private class func base64Encode(dataString: String) -> String? {
let data: Data? = dataString.data(using: String.Encoding.utf8)
guard let d = data else {
print("couldn't serialize object")
return nil
}
let base64Encoded = d.base64EncodedString(options: .endLineWithCarriageReturn)
return base64Encoded
}
}
| 29.059211 | 110 | 0.411139 |
f92d5048b841d600440f58dd4be10af1f2d2d535
| 5,706 |
//
// AuthWebViewController.swift
// MissCat
//
// Created by Yuiga Wada on 2020/03/08.
// Copyright © 2020 Yuiga Wada. All rights reserved.
//
import MisskeyKit
import RxCocoa
import RxSwift
import UIKit
import WebKit
class AuthWebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
@IBOutlet weak var returnButton: UIButton!
@IBOutlet weak var webView: WKWebView!
var completion: PublishRelay<String> = .init()
private var currentUrl: URL?
private var currentType: AuthType = .Signup
private var appSecret: String?
private var misskeyInstance: String?
private let disposeBag = DisposeBag()
// MARK: LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
setupWebView()
setupReturnButton()
removeWebKitCache()
if let url = currentUrl {
loadPage(url: url)
}
}
private func setupWebView() {
webView.uiDelegate = self
webView.navigationDelegate = self
webView.configuration.websiteDataStore = WKWebsiteDataStore.default() // LocalStorageを許可
}
private func setupReturnButton() {
returnButton.rx.tap.subscribe(onNext: {
self.dismiss(animated: true, completion: nil)
}).disposed(by: disposeBag)
}
private func removeWebKitCache() {
URLSession.shared.reset {} // cookieやキャッシュのリセット
let dataStore = WKWebsiteDataStore.default() // WKWebsiteに保存されている全ての情報の削除
dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), for: records, completionHandler: {})
}
WKProcessPool.shared.reset()
}
// MARK: Publics
func setupSignup(misskeyInstance: String, appSecret: String) {
self.appSecret = appSecret
self.misskeyInstance = misskeyInstance
currentType = .Signup
let httpsUrl = URL(string: "https://" + misskeyInstance)
let httpUrl = URL(string: "http://" + misskeyInstance)
let validHttpsUrl = (httpsUrl != nil ? UIApplication.shared.canOpenURL(httpsUrl!) : false)
let validHttpUrl = (httpUrl != nil ? UIApplication.shared.canOpenURL(httpUrl!) : false)
guard validHttpsUrl || validHttpUrl else { return }
currentUrl = validHttpsUrl ? httpsUrl! : httpUrl!
if webView != nil, let url = currentUrl {
loadPage(url: url)
}
}
func setupLogin(misskeyInstance: String, appSecret: String) {
self.appSecret = appSecret
self.misskeyInstance = misskeyInstance
currentType = .Login
MisskeyKit.shared.changeInstance(instance: misskeyInstance) // インスタンスを変更
MisskeyKit.shared.auth.startSession(appSecret: appSecret) { auth, error in
guard let auth = auth,
let token = auth.token,
error == nil,
let url = URL(string: token.url) else { /* Error */ return }
self.currentUrl = url
if self.webView != nil {
self.loadPage(url: url)
}
}
}
// MARK: Privates
private func loadPage(url: URL) {
DispatchQueue.main.async {
self.webView.load(URLRequest(url: url))
self.currentUrl = nil
}
}
/// LocalStorageからログイン処理が完了したかどうかを確認する
/// - Parameter handler: success→true
private func checkLogined(handler: @escaping (Bool) -> Void) {
// 新規登録やログインが完了したらLocalStorageに["i":(key)]が格納されるので、ここからログイン処理が完了したかどうかを確認する
webView.evaluateJavaScript("localStorage.getItem(\"i\")") { result, _ in
guard let result = result as? String, result != "" else { handler(false); return }
handler(true)
}
}
/// ApiKeyを取得し、StartViewControllerへと流す(comletion→StartViewController)
private func getApiKey() {
MisskeyKit.shared.auth.getAccessToken { auth, _ in
guard auth != nil, let apiKey = MisskeyKit.shared.auth.getAPIKey() else { return }
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
self.completion.accept(apiKey)
}
}
}
/// コールバックurlかどうか判定
/// - Parameter url: url
private func checkCallback(of url: URL?) -> Bool {
guard let url = url else { return false }
return url.absoluteString.contains("https://misscat.dev")
}
// MARK: Delegate
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
guard checkCallback(of: webView.url) else { return }
getApiKey()
}
// WebViewの読み込みが完了したらログイン処理が完了したかどうかをチェックする
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { // 読み込み完了
guard let appSecret = self.appSecret, let misskeyInstance = self.misskeyInstance else { return }
if checkCallback(of: webView.url) {
getApiKey()
}
checkLogined { success in
guard success, self.currentType == .Signup else { return }
self.setupLogin(misskeyInstance: misskeyInstance, appSecret: appSecret) // WebKit内でログインページへと遷移させる
}
}
}
extension AuthWebViewController {
enum AuthType {
case Signup
case Login
}
}
extension WKProcessPool {
static var shared = WKProcessPool()
func reset() {
WKProcessPool.shared = WKProcessPool()
}
}
| 31.7 | 120 | 0.614441 |
bf6c54eb83a1b86b0212adf27ad619ad00db2c66
| 1,814 |
//
// PhotoBrowserNumberPageControlDelegate.swift
// PhotoBrowser
//
// Created by JiongXing on 2017/4/25.
// Copyright © 2017年 JiongXing. All rights reserved.
//
import UIKit
/// 给图片浏览器提供一个数字样式的PageControl
public class PhotoBrowserNumberPageControlDelegate: PhotoBrowserPageControlDelegate {
/// 总页数
public var numberOfPages: Int
/// 字体
public var font = UIFont.systemFont(ofSize: 17)
/// 字颜色
public var textColor = UIColor.white
/// 中心点Y坐标
public var centerY: CGFloat = 30
public init(numberOfPages: Int) {
self.numberOfPages = numberOfPages
}
// MARK: - PhotoBrowserPageControlDelegate
public func pageControlOfPhotoBrowser(_ photoBrowser: PhotoBrowser) -> UIView {
let pageControl = UILabel()
pageControl.font = font
pageControl.textColor = textColor
pageControl.text = "1 / \(numberOfPages)"
return pageControl
}
public func photoBrowserPageControl(_ pageControl: UIView, didMoveTo superView: UIView) {
// 这里可以不作任何操作
}
public func photoBrowserPageControl(_ pageControl: UIView, needLayoutIn superView: UIView) {
layoutPageControl(pageControl)
}
public func photoBrowserPageControl(_ pageControl: UIView, didChangedCurrentPage currentPage: Int) {
guard let pageControl = pageControl as? UILabel else {
return
}
pageControl.text = "\(currentPage + 1) / \(numberOfPages)"
layoutPageControl(pageControl)
}
private func layoutPageControl(_ pageControl: UIView) {
pageControl.sizeToFit()
guard let superView = pageControl.superview else { return }
pageControl.center = CGPoint(x: superView.bounds.midX, y: superView.bounds.minY + centerY)
}
}
| 29.737705 | 104 | 0.671444 |
26cfa22f5b45a981f252de5c0214b57a17acd6dd
| 401 |
//: [Previous](@previous)
import Foundation
let queue = OperationQueue()
queue.name = "MySerialOperationQueue"
queue.maxConcurrentOperationCount = 1
let op1 = BlockOperation {
print("Do this first")
}
let op2 = BlockOperation {
print("Do this second")
}
let op3 = BlockOperation {
print("Do this third")
}
queue.waitUntilAllOperationsAreFinished()
print("Done!")
//: [Next](@next)
| 15.423077 | 41 | 0.703242 |
ded82d363b2be761afeaaf07a7b462db48f7c157
| 4,417 |
//
// ExampleTableViewController.swift
// TextFieldEffects
//
// Created by Raúl Riera on 28/08/2015.
// Copyright © 2015 Raul Riera. All rights reserved.
//
import UIKit
import TextFieldEffects
class ExampleTableViewController : UITableViewController, UITextFieldDelegate {
var travelbankNight: UIColor = UIColor(hex: "#1B2432")
var travelbankSilver: UIColor = UIColor(hex: "#E0E2E6")
var travelbankRadical: UIColor = UIColor(hex: "#FC3B60")
@IBOutlet private var textFields: [TextFieldEffects]!
@IBOutlet private var hoshiTextField: HoshiTextField?
/**
Set this value to true if you want to see all the "firstName"
textFields prepopulated with the name "Raul" (for testing purposes)
*/
let prefillTextFields = false
var cells: [(String, CGFloat)] = [(String, CGFloat)]()
override func viewDidLoad() {
super.viewDidLoad()
cells = [(NSLocalizedString("Firstname", comment: "Firstname example label"), 24),
(NSLocalizedString("Lastname", comment: "Lastname example label"), 15)]
hoshiTextField?.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyAwesomeCell")
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .delete
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.default,
title: "Delete" ,
handler: { (action: UITableViewRowAction, indexPath: IndexPath) -> Void in
self.cells.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
})
delete.backgroundColor = UIColor.red
return [delete]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cells.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MyAwesomeCell") else {
return UITableViewCell()
}
let configuredCell = configure(cell: cell, with: cells[indexPath.row].0, height: cells[indexPath.row].1)
return configuredCell
}
private func configure(cell: UITableViewCell, with placeholder: String, height: CGFloat) -> UITableViewCell {
let textField = HoshiTextField(frame: cell.frame)
textField.borderActiveColor = travelbankRadical
textField.borderInactiveColor = travelbankNight
textField.font = UIFont(name: "Roboto-Regular", size: height)
textField.placeholder = placeholder
textField.translatesAutoresizingMaskIntoConstraints = false
textField.delegate = self
cell.contentView.addSubview(textField)
let views: [String: Any] = [
"cell": cell,
"view": textField]
var allConstraints: [NSLayoutConstraint] = []
allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-60-[view]-|",
metrics: nil,
views: views)
allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-[view]",
options: [.alignAllCenterY],
metrics: nil,
views: views)
NSLayoutConstraint.activate(allConstraints)
cell.addConstraints(allConstraints)
return cell
}
// MARK: - TextFieldDelegate
func textFieldDidBeginEditing(_ textField: UITextField) {
guard let textField = textField as? HoshiTextField else { return }
textField.hideError()
}
@available(iOS 10.0, *)
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
if let text = textField.text, !text.isEmpty, let textField = textField as? HoshiTextField {
let message = NSLocalizedString("Error", comment: "Error Message for TextField")
textField.showError(message: message)
}
}
}
| 40.898148 | 127 | 0.666516 |
79dfbb4bd0fcba62c8b2d49d553e8294f79a7789
| 433 |
//
// Problem_186Tests.swift
// Problem 186Tests
//
// Created by sebastien FOCK CHOW THO on 2019-11-27.
// Copyright © 2019 sebastien FOCK CHOW THO. All rights reserved.
//
import XCTest
@testable import Problem_186
class Problem_186Tests: XCTestCase {
func test_example() {
let result = [5, 10, 15, 20, 25].pairWithSmallestDifference()
print(result)
XCTAssert(result.diff == 5)
}
}
| 19.681818 | 69 | 0.655889 |
1e7f094c9567bce72296eee07324f3ccb9c72d7b
| 864 |
//
// AuhtenticatedView.swift
// MVVMSwifUI
//
// Created by Artem Usachov on 18.05.2021.
//
import SwiftUI
import Stinsen
struct AuhtenticatedView<ViewModel>: View where ViewModel: AuthenticatedViewModel {
@StateObject var vm: ViewModel
@EnvironmentObject var main: ViewRouter<MainCoordinator.Route>
var body: some View {
VStack {
Text("Hello, \(vm.userName)!")
Button("Logout", action: {
vm.action.logout(completion: showLoginScreen)
})
}
}
}
struct AuhtenticatedView_Previews: PreviewProvider {
static var previews: some View {
let user = User(name: "test name")
AuthenticatedModule.build(input: .init(user: user))
}
}
extension AuhtenticatedView {
func showLoginScreen() {
main.route(to: .unauthenticated)
}
}
| 22.153846 | 83 | 0.62963 |
f5531b22be00c268ff36ba03dae5f4c97477e793
| 3,557 |
// Copyright (c) 2020 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
import BitByteData
final class LZMA2Decoder {
private let byteReader: LittleEndianByteReader
private let decoder: LZMADecoder
var out: [UInt8] {
return self.decoder.out
}
init(_ byteReader: LittleEndianByteReader, _ dictSizeByte: UInt8) throws {
self.byteReader = byteReader
self.decoder = LZMADecoder(byteReader)
guard dictSizeByte & 0xC0 == 0
else { throw LZMA2Error.wrongDictionarySize }
let bits = (dictSizeByte & 0x3F).toInt()
guard bits < 40
else { throw LZMA2Error.wrongDictionarySize }
let dictSize = bits == 40 ? UInt32.max :
(UInt32(truncatingIfNeeded: 2 | (bits & 1)) << UInt32(truncatingIfNeeded: bits / 2 + 11))
self.decoder.properties.dictionarySize = dictSize.toInt()
}
/// Main LZMA2 decoder function.
func decode() throws {
mainLoop: while true {
let controlByte = byteReader.byte()
switch controlByte {
case 0:
break mainLoop
case 1:
self.decoder.resetDictionary()
self.decodeUncompressed()
case 2:
self.decodeUncompressed()
case 3...0x7F:
throw LZMA2Error.wrongControlByte
case 0x80...0xFF:
try self.dispatch(controlByte)
default:
fatalError("Incorrect control byte.") // This statement is never executed.
}
}
}
/// Function which dispatches LZMA2 decoding process based on `controlByte`.
private func dispatch(_ controlByte: UInt8) throws {
let uncompressedSizeBits = controlByte & 0x1F
let reset = (controlByte & 0x60) >> 5
let unpackSize = (uncompressedSizeBits.toInt() << 16) +
self.byteReader.byte().toInt() << 8 + self.byteReader.byte().toInt() + 1
let compressedSize = self.byteReader.byte().toInt() << 8 + self.byteReader.byte().toInt() + 1
switch reset {
case 0:
break
case 1:
self.decoder.resetStateAndDecoders()
case 2:
try self.updateProperties()
case 3:
try self.updateProperties()
self.decoder.resetDictionary()
default:
throw LZMA2Error.wrongReset
}
self.decoder.uncompressedSize = unpackSize
let outStartIndex = self.decoder.out.count
let inStartIndex = self.byteReader.offset
try self.decoder.decode()
guard unpackSize == self.decoder.out.count - outStartIndex &&
self.byteReader.offset - inStartIndex == compressedSize
else { throw LZMA2Error.wrongSizes }
}
private func decodeUncompressed() {
let dataSize = self.byteReader.byte().toInt() << 8 + self.byteReader.byte().toInt() + 1
for _ in 0..<dataSize {
self.decoder.put(self.byteReader.byte())
}
}
/**
Sets `lc`, `pb` and `lp` properties of LZMA decoder with a single `byte` using standard LZMA properties encoding
scheme and resets decoder's state and sub-decoders.
*/
private func updateProperties() throws {
self.decoder.properties = try LZMAProperties(lzmaByte: byteReader.byte(),
self.decoder.properties.dictionarySize)
self.decoder.resetStateAndDecoders()
}
}
| 34.533981 | 117 | 0.599382 |
edac2a7a6c476ae4343425f95c0df9fc623818a5
| 805 |
// REQUIRES: rdar66283479
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out
// RUN: %{python} %S/../Inputs/not.py "%target-run %t/a.out" 2>&1 | %{lldb-python} %utils/symbolicate-linux-fatal %t/a.out - | %{python} %utils/backtrace-check -u
// REQUIRES: executable_test
// REQUIRES: OS=linux-gnu
// REQUIRES: lldb
// XFAIL: CPU=s390x
// NOTE: not.py is used above instead of "not --crash" because %target-run
// doesn't pass through the crash, and `not` may not be available when running
// on a remote host.
// Backtraces are not emitted when optimizations are enabled. This test can not
// run when optimizations are enabled.
// REQUIRES: swift_test_mode_optimize_none
func funcB() {
fatalError("linux-fatal-backtrace");
}
func funcA() {
funcB();
}
print("bla")
funcA()
| 28.75 | 162 | 0.689441 |
039f830919c0903d4ab44556584986cdc5f3f6aa
| 12,859 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
import azureSwiftRuntime
internal struct VMwareDetailsData : VMwareDetailsProtocol, FabricSpecificDetailsProtocol {
public var processServers: [ProcessServerProtocol?]?
public var masterTargetServers: [MasterTargetServerProtocol?]?
public var runAsAccounts: [RunAsAccountProtocol?]?
public var replicationPairCount: String?
public var processServerCount: String?
public var agentCount: String?
public var protectedServers: String?
public var systemLoad: String?
public var systemLoadStatus: String?
public var cpuLoad: String?
public var cpuLoadStatus: String?
public var totalMemoryInBytes: Int64?
public var availableMemoryInBytes: Int64?
public var memoryUsageStatus: String?
public var totalSpaceInBytes: Int64?
public var availableSpaceInBytes: Int64?
public var spaceUsageStatus: String?
public var webLoad: String?
public var webLoadStatus: String?
public var databaseServerLoad: String?
public var databaseServerLoadStatus: String?
public var csServiceStatus: String?
public var ipAddress: String?
public var agentVersion: String?
public var hostName: String?
public var lastHeartbeat: Date?
public var versionStatus: String?
public var sslCertExpiryDate: Date?
public var sslCertExpiryRemainingDays: Int32?
public var psTemplateVersion: String?
public var agentExpiryDate: Date?
public var agentVersionDetails: VersionDetailsProtocol?
enum CodingKeys: String, CodingKey {case processServers = "processServers"
case masterTargetServers = "masterTargetServers"
case runAsAccounts = "runAsAccounts"
case replicationPairCount = "replicationPairCount"
case processServerCount = "processServerCount"
case agentCount = "agentCount"
case protectedServers = "protectedServers"
case systemLoad = "systemLoad"
case systemLoadStatus = "systemLoadStatus"
case cpuLoad = "cpuLoad"
case cpuLoadStatus = "cpuLoadStatus"
case totalMemoryInBytes = "totalMemoryInBytes"
case availableMemoryInBytes = "availableMemoryInBytes"
case memoryUsageStatus = "memoryUsageStatus"
case totalSpaceInBytes = "totalSpaceInBytes"
case availableSpaceInBytes = "availableSpaceInBytes"
case spaceUsageStatus = "spaceUsageStatus"
case webLoad = "webLoad"
case webLoadStatus = "webLoadStatus"
case databaseServerLoad = "databaseServerLoad"
case databaseServerLoadStatus = "databaseServerLoadStatus"
case csServiceStatus = "csServiceStatus"
case ipAddress = "ipAddress"
case agentVersion = "agentVersion"
case hostName = "hostName"
case lastHeartbeat = "lastHeartbeat"
case versionStatus = "versionStatus"
case sslCertExpiryDate = "sslCertExpiryDate"
case sslCertExpiryRemainingDays = "sslCertExpiryRemainingDays"
case psTemplateVersion = "psTemplateVersion"
case agentExpiryDate = "agentExpiryDate"
case agentVersionDetails = "agentVersionDetails"
}
public init() {
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if container.contains(.processServers) {
self.processServers = try container.decode([ProcessServerData?]?.self, forKey: .processServers)
}
if container.contains(.masterTargetServers) {
self.masterTargetServers = try container.decode([MasterTargetServerData?]?.self, forKey: .masterTargetServers)
}
if container.contains(.runAsAccounts) {
self.runAsAccounts = try container.decode([RunAsAccountData?]?.self, forKey: .runAsAccounts)
}
if container.contains(.replicationPairCount) {
self.replicationPairCount = try container.decode(String?.self, forKey: .replicationPairCount)
}
if container.contains(.processServerCount) {
self.processServerCount = try container.decode(String?.self, forKey: .processServerCount)
}
if container.contains(.agentCount) {
self.agentCount = try container.decode(String?.self, forKey: .agentCount)
}
if container.contains(.protectedServers) {
self.protectedServers = try container.decode(String?.self, forKey: .protectedServers)
}
if container.contains(.systemLoad) {
self.systemLoad = try container.decode(String?.self, forKey: .systemLoad)
}
if container.contains(.systemLoadStatus) {
self.systemLoadStatus = try container.decode(String?.self, forKey: .systemLoadStatus)
}
if container.contains(.cpuLoad) {
self.cpuLoad = try container.decode(String?.self, forKey: .cpuLoad)
}
if container.contains(.cpuLoadStatus) {
self.cpuLoadStatus = try container.decode(String?.self, forKey: .cpuLoadStatus)
}
if container.contains(.totalMemoryInBytes) {
self.totalMemoryInBytes = try container.decode(Int64?.self, forKey: .totalMemoryInBytes)
}
if container.contains(.availableMemoryInBytes) {
self.availableMemoryInBytes = try container.decode(Int64?.self, forKey: .availableMemoryInBytes)
}
if container.contains(.memoryUsageStatus) {
self.memoryUsageStatus = try container.decode(String?.self, forKey: .memoryUsageStatus)
}
if container.contains(.totalSpaceInBytes) {
self.totalSpaceInBytes = try container.decode(Int64?.self, forKey: .totalSpaceInBytes)
}
if container.contains(.availableSpaceInBytes) {
self.availableSpaceInBytes = try container.decode(Int64?.self, forKey: .availableSpaceInBytes)
}
if container.contains(.spaceUsageStatus) {
self.spaceUsageStatus = try container.decode(String?.self, forKey: .spaceUsageStatus)
}
if container.contains(.webLoad) {
self.webLoad = try container.decode(String?.self, forKey: .webLoad)
}
if container.contains(.webLoadStatus) {
self.webLoadStatus = try container.decode(String?.self, forKey: .webLoadStatus)
}
if container.contains(.databaseServerLoad) {
self.databaseServerLoad = try container.decode(String?.self, forKey: .databaseServerLoad)
}
if container.contains(.databaseServerLoadStatus) {
self.databaseServerLoadStatus = try container.decode(String?.self, forKey: .databaseServerLoadStatus)
}
if container.contains(.csServiceStatus) {
self.csServiceStatus = try container.decode(String?.self, forKey: .csServiceStatus)
}
if container.contains(.ipAddress) {
self.ipAddress = try container.decode(String?.self, forKey: .ipAddress)
}
if container.contains(.agentVersion) {
self.agentVersion = try container.decode(String?.self, forKey: .agentVersion)
}
if container.contains(.hostName) {
self.hostName = try container.decode(String?.self, forKey: .hostName)
}
if container.contains(.lastHeartbeat) {
self.lastHeartbeat = DateConverter.fromString(dateStr: (try container.decode(String?.self, forKey: .lastHeartbeat)), format: .dateTime)
}
if container.contains(.versionStatus) {
self.versionStatus = try container.decode(String?.self, forKey: .versionStatus)
}
if container.contains(.sslCertExpiryDate) {
self.sslCertExpiryDate = DateConverter.fromString(dateStr: (try container.decode(String?.self, forKey: .sslCertExpiryDate)), format: .dateTime)
}
if container.contains(.sslCertExpiryRemainingDays) {
self.sslCertExpiryRemainingDays = try container.decode(Int32?.self, forKey: .sslCertExpiryRemainingDays)
}
if container.contains(.psTemplateVersion) {
self.psTemplateVersion = try container.decode(String?.self, forKey: .psTemplateVersion)
}
if container.contains(.agentExpiryDate) {
self.agentExpiryDate = DateConverter.fromString(dateStr: (try container.decode(String?.self, forKey: .agentExpiryDate)), format: .dateTime)
}
if container.contains(.agentVersionDetails) {
self.agentVersionDetails = try container.decode(VersionDetailsData?.self, forKey: .agentVersionDetails)
}
if var pageDecoder = decoder as? PageDecoder {
if pageDecoder.isPagedData,
let nextLinkName = pageDecoder.nextLinkName {
pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName)
}
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if self.processServers != nil {try container.encode(self.processServers as! [ProcessServerData?]?, forKey: .processServers)}
if self.masterTargetServers != nil {try container.encode(self.masterTargetServers as! [MasterTargetServerData?]?, forKey: .masterTargetServers)}
if self.runAsAccounts != nil {try container.encode(self.runAsAccounts as! [RunAsAccountData?]?, forKey: .runAsAccounts)}
if self.replicationPairCount != nil {try container.encode(self.replicationPairCount, forKey: .replicationPairCount)}
if self.processServerCount != nil {try container.encode(self.processServerCount, forKey: .processServerCount)}
if self.agentCount != nil {try container.encode(self.agentCount, forKey: .agentCount)}
if self.protectedServers != nil {try container.encode(self.protectedServers, forKey: .protectedServers)}
if self.systemLoad != nil {try container.encode(self.systemLoad, forKey: .systemLoad)}
if self.systemLoadStatus != nil {try container.encode(self.systemLoadStatus, forKey: .systemLoadStatus)}
if self.cpuLoad != nil {try container.encode(self.cpuLoad, forKey: .cpuLoad)}
if self.cpuLoadStatus != nil {try container.encode(self.cpuLoadStatus, forKey: .cpuLoadStatus)}
if self.totalMemoryInBytes != nil {try container.encode(self.totalMemoryInBytes, forKey: .totalMemoryInBytes)}
if self.availableMemoryInBytes != nil {try container.encode(self.availableMemoryInBytes, forKey: .availableMemoryInBytes)}
if self.memoryUsageStatus != nil {try container.encode(self.memoryUsageStatus, forKey: .memoryUsageStatus)}
if self.totalSpaceInBytes != nil {try container.encode(self.totalSpaceInBytes, forKey: .totalSpaceInBytes)}
if self.availableSpaceInBytes != nil {try container.encode(self.availableSpaceInBytes, forKey: .availableSpaceInBytes)}
if self.spaceUsageStatus != nil {try container.encode(self.spaceUsageStatus, forKey: .spaceUsageStatus)}
if self.webLoad != nil {try container.encode(self.webLoad, forKey: .webLoad)}
if self.webLoadStatus != nil {try container.encode(self.webLoadStatus, forKey: .webLoadStatus)}
if self.databaseServerLoad != nil {try container.encode(self.databaseServerLoad, forKey: .databaseServerLoad)}
if self.databaseServerLoadStatus != nil {try container.encode(self.databaseServerLoadStatus, forKey: .databaseServerLoadStatus)}
if self.csServiceStatus != nil {try container.encode(self.csServiceStatus, forKey: .csServiceStatus)}
if self.ipAddress != nil {try container.encode(self.ipAddress, forKey: .ipAddress)}
if self.agentVersion != nil {try container.encode(self.agentVersion, forKey: .agentVersion)}
if self.hostName != nil {try container.encode(self.hostName, forKey: .hostName)}
if self.lastHeartbeat != nil {
try container.encode(DateConverter.toString(date: self.lastHeartbeat!, format: .dateTime), forKey: .lastHeartbeat)
}
if self.versionStatus != nil {try container.encode(self.versionStatus, forKey: .versionStatus)}
if self.sslCertExpiryDate != nil {
try container.encode(DateConverter.toString(date: self.sslCertExpiryDate!, format: .dateTime), forKey: .sslCertExpiryDate)
}
if self.sslCertExpiryRemainingDays != nil {try container.encode(self.sslCertExpiryRemainingDays, forKey: .sslCertExpiryRemainingDays)}
if self.psTemplateVersion != nil {try container.encode(self.psTemplateVersion, forKey: .psTemplateVersion)}
if self.agentExpiryDate != nil {
try container.encode(DateConverter.toString(date: self.agentExpiryDate!, format: .dateTime), forKey: .agentExpiryDate)
}
if self.agentVersionDetails != nil {try container.encode(self.agentVersionDetails as! VersionDetailsData?, forKey: .agentVersionDetails)}
}
}
extension DataFactory {
public static func createVMwareDetailsProtocol() -> VMwareDetailsProtocol {
return VMwareDetailsData()
}
}
| 55.426724 | 152 | 0.721751 |
0aa0ca4de030afe10128ef85520277269c4a2f7c
| 165 |
import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(SwiftMindstormsTests.allTests),
]
}
#endif
| 16.5 | 48 | 0.684848 |
79b81b2012b854c11a762dc55c6f807c15e9cbb9
| 719 |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
re S.h == A
}
1
func f: e, g: B<T where H.e : b
func g: e
class d<T where H.e : C {
class a<T where g: Int = e, g.h == 1
va d<I : P {
class B<Int>
let a {
func b<T : a {
class a<T: P {
func f: b() {
class a<f : b()
class A {
class B
protocol A {
class a<T where H.e where g: e
let a {
struct Q<T
let a {
class B<T
protocol A : b() {
struct d<T
func f
class a<f {
class B<T where g.h == 1
class c
}
func f
func b() -> <T where g: e, g: b() -> <T where g: a {
1
class c<T where g.h == f : P {
struct Q<T : ()
func f: P {
let v: Int = b<T>) -> <T where
| 17.536585 | 87 | 0.600834 |
72d94ae4204572d14c54c385d59ae22276a6db83
| 2,529 |
//
// NetworkRequestor.swift
// Say Their Names
//
// Copyright (c) 2020 Say Their Names Team (https://github.com/Say-Their-Name)
//
// 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 Alamofire
// MARK: - NetworkRequestor
final class NetworkRequestor {
let concurrentQueue = DispatchQueue(label: "NetworkRequestor", attributes: .concurrent)
let session: Session
init(session: Session = .default) {
self.session = session
}
// MARK: - Public methods
public func fetchDecodable<T: Decodable>(_ url: String, completion: @escaping (Result<T, AFError>) -> Swift.Void) {
let request = self.session.request(url)
request.responseDecodable(of: T.self, queue: self.concurrentQueue) { (response) in
DispatchQueue.mainAsync { completion(response.result) }
}
}
public func fetchData(_ url: String, completion: @escaping (Result<Data, AFError>) -> Swift.Void) {
let request = self.session.request(url)
request.responseData(queue: self.concurrentQueue) { (response) in
DispatchQueue.mainAsync { completion(response.result) }
}
}
public func fetchJSON(_ url: String, completion: @escaping (Result<Any, AFError>) -> Swift.Void) {
let request = self.session.request(url)
request.responseJSON(queue: self.concurrentQueue) { (response) in
DispatchQueue.mainAsync { completion(response.result) }
}
}
}
| 41.459016 | 119 | 0.701858 |
1e85f399893432327b074242715a03c551dc5071
| 2,423 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Distributed Actors open source project
//
// Copyright (c) 2018-2022 Apple Inc. and the Swift Distributed Actors project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of Swift Distributed Actors project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Logging
/// System-wide receptionist, used to register and look up actors by keys they register with.
///
/// Receptionists are designed to work seamlessly offer the same capability local and distributed.
///
/// - SeeAlso: `_ActorContext<Message>.Receptionist`, accessible in the `_Behavior` style API via `context.receptionist`.
internal struct SystemReceptionist: _BaseReceptionistOperations {
let ref: _ActorRef<Receptionist.Message>
init(ref receptionistRef: _ActorRef<Receptionist.Message>) {
self.ref = receptionistRef
}
@discardableResult
public func register<Guest>(
_ guest: Guest,
as id: String,
replyTo: _ActorRef<_Reception.Registered<Guest>>? = nil
) -> _Reception.Key<Guest> where Guest: _ReceptionistGuest {
let key: _Reception.Key<Guest> = _Reception.Key(Guest.self, id: id)
self.register(guest, with: key, replyTo: replyTo)
return key
}
@discardableResult
public func register<Guest>(
_ guest: Guest,
with key: _Reception.Key<Guest>,
replyTo: _ActorRef<_Reception.Registered<Guest>>? = nil
) -> _Reception.Key<Guest> where Guest: _ReceptionistGuest {
self.ref.tell(Receptionist.Register<Guest>(guest, key: key, replyTo: replyTo))
return key
}
public func lookup<Guest>(
_ key: _Reception.Key<Guest>,
replyTo: _ActorRef<_Reception.Listing<Guest>>,
timeout: Duration = .effectivelyInfinite
) where Guest: _ReceptionistGuest {
self.ref.tell(Receptionist.Lookup<Guest>(key: key, replyTo: replyTo))
}
public func subscribe<Guest>(
_ subscriber: _ActorRef<_Reception.Listing<Guest>>,
to key: _Reception.Key<Guest>
) where Guest: _ReceptionistGuest {
self.ref.tell(Receptionist.Subscribe<Guest>(key: key, subscriber: subscriber))
}
}
| 37.276923 | 121 | 0.650021 |
89fcba1601cfa3545b4e6c02a105f186ec8dec91
| 3,009 |
//
// AppetitAPIManager.swift
// Appetit
//
// Created by Sense Infoway on 28/12/16.
// Copyright © 2016 Douglas Taquary. All rights reserved.
//
import Foundation
import Moya
import RxSwift
import ObjectMapper
import Moya_ObjectMapper
extension Response {
func removeAPIWrappers() -> Response {
guard let json = try? self.mapJSON() as? Dictionary<String, AnyObject>,
let results = json?["data"]?["foods"] ?? [],
let newData = try? JSONSerialization.data(withJSONObject: results, options: .prettyPrinted) else {
return self
}
let newResponse = Response(statusCode: self.statusCode,
data: newData,
response: self.response)
return newResponse
}
}
struct AppetitAPIManager {
let provider: RxMoyaProvider<AppetitAPI>
let disposeBag = DisposeBag()
init() {
provider = RxMoyaProvider<AppetitAPI>()
}
}
extension AppetitAPIManager {
typealias AdditionalStepsAction = (() -> ())
fileprivate func requestObject<T: Mappable>(_ token: AppetitAPI, type: T.Type,
completion: @escaping (T?) -> Void,
additionalSteps: AdditionalStepsAction? = nil) {
provider.request(token)
.debug()
.mapObject(T.self)
.subscribe { event -> Void in
switch event {
case .next(let parsedObject):
completion(parsedObject)
additionalSteps?()
case .error(let error):
print(error)
completion(nil)
default:
break
}
}.addDisposableTo(disposeBag)
}
fileprivate func requestArray<T: Mappable>(_ token: AppetitAPI, type: T.Type,
completion: @escaping ([T]?) -> Void,
additionalSteps: AdditionalStepsAction? = nil) {
provider.request(token)
.debug()
.map { response -> Response in
return response.removeAPIWrappers()
}
.mapArray(T.self)
.subscribe { event -> Void in
switch event {
case .next(let parsedArray):
completion(parsedArray)
additionalSteps?()
case .error(let error):
print(error)
completion(nil)
default:
break
}
}.addDisposableTo(disposeBag)
}
}
protocol AppetitAPICalls {
func items(completion: @escaping ([Item]?) -> Void)
}
extension AppetitAPIManager: AppetitAPICalls {
func items(completion: @escaping ([Item]?) -> Void) {
requestArray(.items,
type: Item.self,
completion: completion)
}
}
| 30.393939 | 110 | 0.516118 |
561588ca221cbcf43eaf79b6950de97f73f7e991
| 2,060 |
//
// User.swift
// Potluck
//
// Created by Jennifer Hamilton on 3/13/18.
// Copyright © 2018 Many Hands Apps. All rights reserved.
//
import UIKit
enum UserAuthorizationState: String, Codable {
/// not registered or logged in
case anonymous
/// initial sign up complete, email not verified
case unverified
/// email or phone verified, but basic profile details incomplete, not in database
case verified
/// verified and confirmed, basic profile complete, added to database
case registered
/// default value
// case unset
}
struct MHPUser: Codable {
var userID: String?
var firstName: String?
var lastName: String?
var email: String?
var phone: String?
var profileImageURL: String?
var facebookID: String?
var events: [String]?
var notificationPermissions: Bool?
var notificationPreferences: Bool?
var locationPermissions: Bool?
var facebookPermissions: Bool?
var userState: UserAuthorizationState!
init(userState: UserAuthorizationState = .anonymous) {
self.userState = userState
}
init(userID: String,
firstName: String,
lastName: String,
email: String,
phone: String,
profileImageURL: String,
facebookID: String,
events: [String],
notificationPermissions: Bool,
notificationPreferences: Bool,
locationPermissions: Bool,
facebookPermissions: Bool,
userState: UserAuthorizationState) {
self.userID = userID
self.firstName = firstName
self.lastName = lastName
self.email = email
self.phone = phone
self.profileImageURL = profileImageURL
self.facebookID = facebookID
self.events = events
self.notificationPermissions = notificationPermissions
self.notificationPreferences = notificationPreferences
self.locationPermissions = locationPermissions
self.facebookPermissions = facebookPermissions
self.userState = userState
}
}
| 28.611111 | 86 | 0.667961 |
2fa70360d5f68002da9fec5478694fbf6722eb92
| 223 |
//: Playground - noun: a place where people can play
import UIKit
import Look
let font = UIFont(name: "Courier New", size: 15)
font.debugDescription
Look(UIFont: font)
Look(UIFont: UIFont(name: "Helvetica", size: 15))
| 17.153846 | 52 | 0.721973 |
22f392cef38704dafd307961899167a96d0874a6
| 5,899 |
//
// PatternSortViewController.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2018-01-05.
//
// ---------------------------------------------------------------------------
//
// © 2018-2019 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
final class PatternSortViewController: NSViewController, SortPatternViewControllerDelegate {
// MARK: Private Properties
@objc dynamic private var sortOptions = SortOptions()
@objc dynamic var sampleLine: String?
@objc dynamic var sampleFontName: String?
@IBOutlet private weak var sampleLineField: NSTextField?
private weak var tabViewController: NSTabViewController?
// MARK: -
// MARK: View Controller Methods
/// keep tabViewController
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard
self.tabViewController == nil,
let tabViewController = segue.destinationController as? NSTabViewController
else { return }
self.tabViewController = tabViewController
tabViewController.tabViewItems
.compactMap { $0.viewController as? SortPatternViewController }
.forEach { $0.delegate = self }
}
// MARK: Actions
/// switch sort key setting (tab) view
@IBAction func changeSortPattern(_ sender: NSButton) {
self.tabViewController?.selectedTabViewItemIndex = sender.tag
}
/// perform sort
@IBAction func ok(_ sender: Any?) {
guard
let textView = self.representedObject as? NSTextView,
let pattern = self.sortPattern
else { return assertionFailure() }
do {
try pattern.validate()
} catch {
NSAlert(error: error).beginSheetModal(for: self.view.window!)
NSSound.beep()
return
}
guard self.endEditing() else {
NSSound.beep()
return
}
textView.sortLines(pattern: pattern, options: self.sortOptions)
self.dismiss(sender)
}
// MARK: Sort Pattern View Controller Delegate
/// sort pattern setting did update
func didUpdate(sortPattern: SortPattern) {
guard
let sampleLine = self.sampleLine,
let field = self.sampleLineField
else { return }
let attributedLine = NSMutableAttributedString(string: sampleLine)
try? sortPattern.validate() // invalidate regex
if let range = sortPattern.range(for: sampleLine) {
let nsRange = NSRange(range, in: sampleLine)
attributedLine.addAttribute(.backgroundColor, value: NSColor.selectedTextBackgroundColor, range: nsRange)
}
field.attributedStringValue = attributedLine
}
// MARK: Private Methods
/// SortPattern currently edited
private var sortPattern: SortPattern? {
return self.tabViewController?.tabView.selectedTabViewItem?.viewController?.representedObject as? SortPattern
}
}
// MARK: -
final class SortPatternTabViewController: NSTabViewController {
override func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) {
super.tabView(tabView, willSelect: tabViewItem)
// initialize viewController in representedObject
guard
let item = tabViewItem,
let viewController = item.viewController,
viewController.representedObject == nil
else { return }
switch tabView.indexOfTabViewItem(item) {
case 0:
viewController.representedObject = EntireLineSortPattern()
case 1:
viewController.representedObject = CSVSortPattern()
case 2:
viewController.representedObject = RegularExpressionSortPattern()
default:
preconditionFailure()
}
}
}
// MARK: -
protocol SortPatternViewControllerDelegate: AnyObject {
func didUpdate(sortPattern: SortPattern)
}
final class SortPatternViewController: NSViewController, NSTextFieldDelegate {
weak var delegate: SortPatternViewControllerDelegate?
override func viewWillAppear() {
super.viewWillAppear()
self.valueDidUpdate(self)
}
/// text field value did change
func controlTextDidChange(_ obj: Notification) {
self.valueDidUpdate(self)
}
/// notify value change to delegate
@IBAction func valueDidUpdate(_ sender: Any?) {
guard let pattern = self.representedObject as? SortPattern else { return assertionFailure() }
self.delegate?.didUpdate(sortPattern: pattern)
}
}
// MARK: -
extension CSVSortPattern {
override func setNilValueForKey(_ key: String) {
// avoid rising an exception when number field becomes empty
switch key {
case #keyPath(column):
self.column = 1
default:
super.setNilValueForKey(key)
}
}
}
| 26.217778 | 117 | 0.609256 |
fe5463fe431529a4cddb06d23055b7b70e3aecb3
| 3,104 |
import Kitura
import KituraStencil
import VertxEventBus
import Darwin
print("Starting example app on http://localhost:8080...")
// create an eventBus, set a top-level error hander, and connect to the bridge server
let eventBus = EventBus(host: "localhost", port: 7001)
eventBus.register(errorHandler: { print($0) })
do {
try eventBus.connect()
} catch let error {
print("Failed to connect to the event bus bridge; is it running? \(error)")
exit(1)
}
var words = [String: Word]()
func reverse(_ str: String) -> String {
return String(str.characters.reversed())
}
// register a listener to reverse words, sending the result back on a different address
let _ = try eventBus.register(address: "word.reverse") {
if let word = $0.body["word"].string {
do {
try eventBus.send(to: "word.reversed", body: ["word": word, "reversed": reverse(word)])
} catch let error {
print("Failed to send to the eventBus: \(error)")
}
}
}
// register a listener to store the reversed words
let _ = try eventBus.register(address: "word.reversed") {
if let word = $0.body["word"].string,
let reversed = $0.body["reversed"].string,
let wordRecord = words[word] {
wordRecord.reversed = reversed
}
}
func respond(_ response: RouterResponse) throws {
try response.render("index.stencil", context: ["words": Array(words.values)])
.end()
}
let router = Router()
router.add(templateEngine: StencilTemplateEngine())
router
.get("/") { _, response, _ in
try respond(response)
}
.post("/") { request, response, _ in
if let body = try request.readString() {
let parts = body.components(separatedBy: "=")
if parts.count > 1 {
let wordStr = parts[1]
if strlen(wordStr) > 0 {
var word = words[wordStr] ?? Word(wordStr)
words[wordStr] = word
let msg = ["word": wordStr]
// send the word off to the reverser
try eventBus.send(to: "word.reverse", body: msg)
// send the word off to the scrambler (implemented in the Java bridge), and register
// a callback to handle the response, storing it
try eventBus.send(to: "word.scramble", body: msg) {
if let msg = $0.message,
let scrambled = msg.body["scrambled"].string {
word.scrambled = scrambled
} else {
print("reply timed out!")
}
}
}
}
}
try respond(response)
}
.error { request, response, next in
response.headers["Content-Type"] = "text/plain"
let errorDescription: String
if let error = response.error {
errorDescription = "\(error)"
} else {
errorDescription = "Unknown error"
}
try response.send("An error occurred: \(errorDescription)").end()
}
Kitura.addHTTPServer(onPort: 8080, with: router)
Kitura.run()
| 31.673469 | 102 | 0.581508 |
e5f3bbb39990a0339841a58e1afb7eaf6fe1add2
| 319 |
public extension Set {
static func insert(_ newMember: Element) -> (Self) -> Self {
{ set in
var set = set
set.insert(newMember)
return set
}
}
func updated(with new: Set<Element>) -> Set<Element> {
var updated = new
self.forEach { updated.insert($0) }
return updated
}
}
| 19.9375 | 62 | 0.592476 |
4665a48d19493a0a1c5bca8332109c80c7e83fac
| 11,360 |
//
// NSXMLSVGParser.swift
// SwiftSVG
//
//
// Copyright (c) 2017 Michael Choe
// http://www.github.com/mchoe
// http://www.straussmade.com/
// http://www.twitter.com/_mchoe
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
/**
`NSXMLSVGParser` conforms to `SVGParser`
*/
extension NSXMLSVGParser: SVGParser { }
/**
Concrete implementation of `SVGParser` that uses Foundation's `XMLParser` to parse a given SVG file.
*/
open class NSXMLSVGParser: XMLParser, XMLParserDelegate {
/**
Error type used when a fatal error has occured
*/
enum SVGParserError {
case invalidSVG
case invalidURL
}
/// :nodoc:
fileprivate var asyncParseCount: Int = 0
/// :nodoc:
fileprivate var didDispatchAllElements = true
/// :nodoc:
fileprivate var elementStack = Stack<SVGElement>()
/// :nodoc:
public var completionBlock: ((SVGLayer) -> ())?
/// :nodoc:
public var supportedElements: SVGParserSupportedElements? = nil
/// The `SVGLayer` that will contain all of the SVG's sublayers
open var containerLayer = SVGLayer()
/// :nodoc:
let asyncCountQueue = DispatchQueue(label: "com.straussmade.swiftsvg.asyncCountQueue.serial", qos: .userInteractive)
/// :nodoc:
private init() {
super.init(data: Data())
}
/**
Convenience initializer that can initalize an `NSXMLSVGParser` using a local or remote `URL`
- parameter svgURL: The URL of the SVG.
- parameter supportedElements: Optional `SVGParserSupportedElements` struct that restrict the elements and attributes that this parser can parse.If no value is provided, all supported attributes will be used.
- parameter completion: Optional completion block that will be executed after all elements and attribites have been parsed.
*/
public convenience init(svgURL: URL, supportedElements: SVGParserSupportedElements? = nil, completion: ((SVGLayer) -> ())? = nil) {
do {
let urlData = try Data(contentsOf: svgURL)
self.init(svgData: urlData, supportedElements: supportedElements, completion: completion)
} catch {
self.init()
print("Couldn't get data from URL")
}
}
/// :nodoc:
@available(*, deprecated, renamed: "init(svgURL:supportedElements:completion:)")
public convenience init(SVGURL: URL, supportedElements: SVGParserSupportedElements? = nil, completion: ((SVGLayer) -> ())? = nil) {
self.init(svgURL: SVGURL, supportedElements: supportedElements, completion: completion)
}
/**
Initializer that can initalize an `NSXMLSVGParser` using SVG `Data`
- parameter svgURL: The URL of the SVG.
- parameter supportedElements: Optional `SVGParserSupportedElements` struct that restricts the elements and attributes that this parser can parse. If no value is provided, all supported attributes will be used.
- parameter completion: Optional completion block that will be executed after all elements and attribites have been parsed.
*/
public required init(svgData: Data, supportedElements: SVGParserSupportedElements? = SVGParserSupportedElements.allSupportedElements, completion: ((SVGLayer) -> ())? = nil) {
super.init(data: svgData)
self.delegate = self
self.supportedElements = supportedElements
self.completionBlock = completion
}
/// :nodoc:
@available(*, deprecated, renamed: "init(svgData:supportedElements:completion:)")
public convenience init(SVGData: Data, supportedElements: SVGParserSupportedElements? = SVGParserSupportedElements.allSupportedElements, completion: ((SVGLayer) -> ())? = nil) {
self.init(svgData: SVGData, supportedElements: supportedElements, completion: completion)
}
/**
Starts parsing the SVG document
*/
public func startParsing() {
self.asyncCountQueue.sync {
self.didDispatchAllElements = false
}
self.parse()
}
/**
The `XMLParserDelegate` method called when the parser has started parsing an SVG element. This implementation will loop through all supported attributes and dispatch the attribiute value to the given curried function.
*/
open func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
guard let elementType = self.supportedElements?.tags[elementName] else {
print("\(elementName) is unsupported. For a complete list of supported elements, see the `allSupportedElements` variable in the `SVGParserSupportedElements` struct. Click through on the `elementName` variable name to see the SVG tag name.")
return
}
let svgElement = elementType()
if var asyncElement = svgElement as? ParsesAsynchronously {
self.asyncCountQueue.sync {
self.asyncParseCount += 1
asyncElement.asyncParseManager = self
}
}
for (attributeName, attributeClosure) in svgElement.supportedAttributes {
if let attributeValue = attributeDict[attributeName] {
attributeClosure(attributeValue)
}
}
self.elementStack.push(svgElement)
}
/**
The `XMLParserDelegate` method called when the parser has ended parsing an SVG element. This methods pops the last element parsed off the stack and checks if there is an enclosing container layer. Every valid SVG file is guaranteed to have at least one container layer (at a minimum, a `SVGRootElement` instance).
If the parser has finished parsing a `SVGShapeElement`, it will resize the parser's `containerLayer` bounding box to fit all subpaths
If the parser has finished parsing a `<svg>` element, that `SVGRootElement`'s container layer is added to this parser's `containerLayer`.
*/
open func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
guard let last = self.elementStack.last else {
return
}
guard elementName == type(of: last).elementName else {
return
}
guard let lastElement = self.elementStack.pop() else {
return
}
if let rootItem = lastElement as? SVGRootElement {
DispatchQueue.main.safeAsync {
self.containerLayer.addSublayer(rootItem.containerLayer)
}
return
}
guard let containerElement = self.elementStack.last as? SVGContainerElement else {
return
}
lastElement.didProcessElement(in: containerElement)
if let lastShapeElement = lastElement as? SVGShapeElement {
self.resizeContainerBoundingBox(lastShapeElement.boundingBox)
}
}
/**
The `XMLParserDelegate` method called when the parser has finished parsing the SVG document. All supported elements and attributes are guaranteed to be dispatched at this point, but there's no guarantee that all elements have finished parsing.
- SeeAlso: `CanManageAsychronousParsing` `finishedProcessing(shapeLayer:)`
- SeeAlso: `XMLParserDelegate` (`parserDidEndDocument(_:)`)[https://developer.apple.com/documentation/foundation/xmlparserdelegate/1418172-parserdidenddocument]
*/
public func parserDidEndDocument(_ parser: XMLParser) {
self.asyncCountQueue.sync {
self.didDispatchAllElements = true
}
if self.asyncParseCount <= 0 {
DispatchQueue.main.safeAsync {
self.completionBlock?(self.containerLayer)
self.completionBlock = nil
}
}
}
/**
The `XMLParserDelegate` method called when the parser has reached a fatal error in parsing. Parsing is stopped if an error is reached and you may want to check that your SVG file passes validation.
- SeeAlso: `XMLParserDelegate` (`parser(_:parseErrorOccurred:)`)[https://developer.apple.com/documentation/foundation/xmlparserdelegate/1412379-parser]
- SeeAlso: (SVG Validator)[https://validator.w3.org/]
*/
public func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
print("Parse Error: \(parseError)")
let code = (parseError as NSError).code
switch code {
case 76:
print("Invalid XML: \(SVGParserError.invalidSVG)")
default:
break
}
}
}
extension NSXMLSVGParser {
/**
Method that resizes the container bounding box that fits all the subpaths.
*/
func resizeContainerBoundingBox(_ boundingBox: CGRect?) {
guard let thisBoundingBox = boundingBox else {
return
}
self.containerLayer.boundingBox = self.containerLayer.boundingBox.union(thisBoundingBox)
}
}
/**
`NSXMLSVGParser` conforms to the protocol `CanManageAsychronousParsing` that uses a simple reference count to see if there are any pending asynchronous tasks that have been dispatched and are still being processed. Once the element has finished processing, the asynchronous elements calls the delegate callback `func finishedProcessing(shapeLayer:)` and the delegate will decrement the count.
*/
extension NSXMLSVGParser: CanManageAsychronousParsing {
/**
The `CanManageAsychronousParsing` callback called when an `ParsesAsynchronously` element has finished parsing
*/
func finishedProcessing(_ shapeLayer: CAShapeLayer) {
self.asyncCountQueue.sync {
self.asyncParseCount -= 1
}
self.resizeContainerBoundingBox(shapeLayer.path?.boundingBox)
guard self.asyncParseCount <= 0 && self.didDispatchAllElements else {
return
}
DispatchQueue.main.safeAsync {
self.completionBlock?(self.containerLayer)
self.completionBlock = nil
}
}
}
| 40.571429 | 393 | 0.675088 |
561099958e9fafdeeffcb9c395c7aac7d541163b
| 3,767 |
//
// BusinessesViewController.swift
// Yelp
//
// Created by Timothy Lee on 4/23/15.
// Copyright (c) 2015 Timothy Lee. All rights reserved.
//
import UIKit
class BusinessesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
var businesses: [Business]!
var filtered: [Business]!
var searchActivated: Bool = false
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let searchBar = UISearchBar()
searchBar.sizeToFit()
navigationItem.titleView = searchBar
searchBar.delegate = self
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
Business.searchWithTerm(term: "Thai", completion: { (businesses: [Business]?, error: Error?) -> Void in
self.businesses = businesses
self.tableView.reloadData()
if let businesses = businesses {
for business in businesses {
print(business.name!)
print(business.address!)
}
}
}
)
/* Example of Yelp search with more search options specified
Business.searchWithTerm("Restaurants", sort: .Distance, categories: ["asianfusion", "burgers"], deals: true) { (businesses: [Business]!, error: NSError!) -> Void in
self.businesses = businesses
for business in businesses {
print(business.name!)
print(business.address!)
}
}
*/
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if searchActivated{
return filtered.count
}else{
if businesses != nil {
return businesses!.count
}else{
return 0
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "BusinessCell", for: indexPath) as! BusinessCell
if searchActivated{
cell.business = filtered[indexPath.row]
}else{
cell.business = businesses[indexPath.row]
}
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filtered = searchText.isEmpty ? businesses : businesses.filter { (item: Business) -> Bool in
// If dataItem matches the searchText, return true to include it
return item.name?.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
}
tableView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar){
searchActivated = true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar){
searchActivated = false
}
}
| 30.626016 | 173 | 0.591452 |
22cee842dd23a9b1dd9ba0eff29e821fafbb67cb
| 2,268 |
//
// SettingsView.swift
// SwiftUIOAuth
//
// Created by Chee Ket Yung on 28/03/2021.
//
import SwiftUI
struct SettingRowView : View {
var title : String
var systemImageName : String
var body : some View {
HStack (spacing : 15) {
Image(systemName: systemImageName)
Text (title)
}
}
}
struct SettingsView : View {
@State private var showSignOutPrompt : Bool = false
@EnvironmentObject private var userViewModel : UserViewModel
var body : some View {
NavigationView {
List {
// first section
Section(header: Text("Account")) {
NavigationLink(destination: EmptyView(), label: {
SettingRowView(title: "My Account",
systemImageName: "person")
})
}
// second section
Section(header: Text("More Features")) {
NavigationLink(destination: EmptyView(), label: {
SettingRowView(title: "Profit & Loss",
systemImageName:"dollarsign.circle")
})
NavigationLink(destination: EmptyView(), label: {
SettingRowView(title: "Announcement",
systemImageName: "newspaper")
})
}
Section(header: Text("")) {
Button(action: {
self.showSignOutPrompt.toggle()
}){
SettingRowView(title: "Sign Out", systemImageName: "arrow.backward.circle")
.foregroundColor(.gray)
}
}
}
.navigationTitle(Text("Settings"))
}
.alert(isPresented : $showSignOutPrompt){
Alert(title: Text("Are you sure you want to sign out now?"),
primaryButton: .default(Text("Yes")) {
userViewModel.signOut()
},
secondaryButton: .cancel(Text("No")))
}
}
}
| 27.325301 | 98 | 0.451058 |
f4f8e0cff652dfdf74e761213234b81f9c115e64
| 340 |
/* DO NOT EDIT | Generated by gyro */
import ObjectMapper
extension Address: Mappable {
// MARK: Initializers
convenience init?(map: Map) {
self.init()
}
// MARK: Mappable
func mapping(map: Map) {
// MARK: Attributes
self.city <- map["city"]
self.formatted <- map["formatted"]
self.zip <- map["zip"]
}
}
| 17 | 38 | 0.608824 |
5dddb6a043ca745006ff50ceac657c83d9509e27
| 3,854 |
import Foundation
public struct Statistic {
public enum Resolution {
case daily, monthly, monthlyAdjusted, yearly, all, weekly
}
public enum Kind {
case balancesByAccount
case balancesByAccountTypeGroup
case expensesByCategory
case expensesByPrimaryCategory
case expensesByCategoryByCount
case expensesByPrimaryCategoryByCount
case incomeByCategory
case incomeAndExpenses
case leftToSpend
case leftToSpendAverage
}
public let description: String
public let payload: String?
public let period: StatisticPeriod
public let resoultion: Resolution
public let kind: Kind
public let value: Double
let userID: String
}
public enum StatisticPeriod: Hashable {
case year(Int)
case week(year: Int, week: Int)
case month(year: Int, month: Int)
case day(year: Int, month: Int, day: Int)
/// Will map to the proper backend string representation of the reaspective periods.
public var stringRepresentation: String {
switch self {
case .year(let year): return "\(year)"
case .month(year: let year, month: let month): return String(format: "%d-%02d", year, month)
case .week(year: let year, week: let week): return String(format: "%d:%02d", year, week)
case .day(year: let year, month: let month, day: let day): return String(format: "%d-%02d-%02d", year, month, day)
}
}
init?(string: String) {
if let year = Int(string) {
self = .year(year)
return
}
do {
let monthExpression = try NSRegularExpression(pattern: #"^(\d+)-(\d{2})$"#, options: [])
let weekExpression = try NSRegularExpression(pattern: #"^(\d+):(\d{2})$"#, options: [])
let dayExpression = try NSRegularExpression(pattern: #"^(\d+)-(\d{2})-(\d{2})$"#, options: [])
let range = NSRange(string.startIndex..<string.endIndex,
in: string)
for match in monthExpression.matches(in: string, options: [], range: range) {
if match.numberOfRanges == 3,
let firstCaptureRange = Range(match.range(at: 1), in: string),
let secondCaptureRange = Range(match.range(at: 2), in: string),
let year = Int(string[firstCaptureRange]),
let month = Int(string[secondCaptureRange]) {
self = .month(year: year, month: month)
return
}
}
for match in weekExpression.matches(in: string, options: [], range: range) {
if match.numberOfRanges == 3,
let firstCaptureRange = Range(match.range(at: 1), in: string),
let secondCaptureRange = Range(match.range(at: 2), in: string),
let year = Int(string[firstCaptureRange]),
let week = Int(string[secondCaptureRange]) {
self = .week(year: year, week: week)
return
}
}
for match in dayExpression.matches(in: string, options: [], range: range) {
if match.numberOfRanges == 4,
let firstRange = Range(match.range(at: 1), in: string),
let secondRange = Range(match.range(at: 2), in: string),
let thirdRange = Range(match.range(at: 3), in: string),
let year = Int(string[firstRange]),
let month = Int(string[secondRange]),
let day = Int(string[thirdRange]) {
self = .day(year: year, month: month, day: day)
return
}
}
return nil
} catch {
return nil
}
}
}
| 37.417476 | 122 | 0.552673 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.