blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
6
116
path
stringlengths
5
872
src_encoding
stringclasses
7 values
length_bytes
int64
10
4.68M
score
float64
2.52
5.63
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
7
4.81M
download_success
bool
1 class
d9efe4f3c70c7637a0b4898f8bd5361fbd59487c
Swift
dmaulikr/Mine-workout
/DermWritePractice/AnimateViewController.swift
UTF-8
3,106
2.609375
3
[]
no_license
// // AnimateViewController.swift // DermWritePractice // // Created by Padalingam A on 5/25/17. // Copyright © 2017 Padalingam A. All rights reserved. // import UIKit class AnimateViewController: UIViewController { @IBOutlet weak var customView: UIView! var flag: Bool! override func viewDidLoad() { super.viewDidLoad() flag = true customView.frame.size = .zero customView.layer.cornerRadius = 15 customView.layer.shadowOffset = CGSize(width: 5, height: 5) customView.layer.shadowRadius = 2.5 customView.layer.shadowColor = UIColor.black.cgColor // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func expand(_ sender: Any) { if flag { UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: { //self.customView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) // self.customView.frame.size = CGSize(width: self.customView.frame.size.width+100, height: self.customView.frame.size.height+100) self.customView.frame.size.width += 500 self.customView.frame.origin.x -= 500 self.customView.frame.size.height += 500 self.customView.layer.cornerRadius = 15 self.customView.layer.shadowOffset = CGSize(width: 20, height: 20) self.customView.layer.shadowRadius = 10 self.customView.layer.borderWidth = 5 self.customView.layer.borderColor = UIColor.black.cgColor self.customView.layer.shadowColor = UIColor.black.cgColor //self.customView.frame.origin.y += 100 }) // UIView.animate(withDuration: 0.5) { // //self.customView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) // self.customView.frame.size = CGSize(width: self.customView.frame.size.width+100, height: self.customView.frame.size.height+100) // } flag = !flag } else { UIView.animate(withDuration: 0.5) { self.customView.frame.size.width = 0 self.customView.frame.origin.x += 500 self.customView.frame.size.height = 0 //self.customView.transform = .identity // self.customView.frame.size = CGSize(width: self.customView.frame.size.width-100, height: self.customView.frame.size.height-100) } flag = !flag } } /* // 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. } */ }
true
ebe3d505563674565f9bffbdb69fb376f325b4ac
Swift
cs-gabriel-preto/cs-bootcamp
/CsBootcamp/Scenes/FavoritesList/Views/FavoriteTableViewCell.swift
UTF-8
3,973
2.71875
3
[]
no_license
// // FavoriteTableViewCell.swift // CsBootcamp // // Created by Gabriel Preto on 03/04/2018. // Copyright © 2018 Bootcampers. All rights reserved. // import UIKit final class FavoriteTableViewCell: UITableViewCell { private let imagerFetcher: ImageFetcher = KingfisherImageFetcher() static var cellHeight: CGFloat = CGFloat(120).proportionalToWidth lazy var posterImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true return imageView }() lazy var titleLabel: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFont(ofSize: CGFloat(18).proportionalToWidth) label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 2 return label }() lazy var releaseDateLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: CGFloat(17).proportionalToWidth, weight: .light) label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .right return label }() lazy var overviewLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: CGFloat(14).proportionalToWidth, weight: .ultraLight) label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 3 return label }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: reuseIdentifier) setupViewHierarchy() setupContraints() contentView.backgroundColor = .white selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup(viewModel: ViewModel) { imagerFetcher.fetchImage(from: viewModel.posterUrl, to: posterImageView) {} self.titleLabel.text = viewModel.title self.releaseDateLabel.text = viewModel.releaseDate self.overviewLabel.text = viewModel.overview } private func setupViewHierarchy() { contentView.addSubview(posterImageView) contentView.addSubview(titleLabel) contentView.addSubview(releaseDateLabel) contentView.addSubview(overviewLabel) } private func setupContraints() { posterImageView .topAnchor(equalTo: contentView.topAnchor) .bottomAnchor(equalTo: contentView.bottomAnchor) .leadingAnchor(equalTo: contentView.leadingAnchor) .widthAnchor(equalTo: posterImageView.heightAnchor, multiplier: 0.8) titleLabel .topAnchor(equalTo: contentView.topAnchor, constant: CGFloat(16).proportionalToWidth) .leadingAnchor(equalTo: posterImageView.trailingAnchor, constant: CGFloat(8).proportionalToWidth) titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) overviewLabel .topAnchor(equalTo: titleLabel.bottomAnchor, constant: CGFloat(8).proportionalToWidth) .leadingAnchor(equalTo: titleLabel.leadingAnchor) .trailingAnchor(equalTo: contentView.trailingAnchor, constant: -8) releaseDateLabel .topAnchor(equalTo: titleLabel.topAnchor) .trailingAnchor(equalTo: contentView.trailingAnchor, constant: CGFloat(-8).proportionalToWidth) .leadingAnchor(equalTo: titleLabel.trailingAnchor, constant: CGFloat(8).proportionalToWidth) } } extension FavoriteTableViewCell { struct ViewModel: Equatable { let posterUrl: URL let title: String let releaseDate: String let overview: String } }
true
7dc33ef997ec4d2362a6159a1820c7ed60eb7473
Swift
elpsk/Swift-Koan
/KoanUI/KoanUI/Configuration.swift
UTF-8
987
2.578125
3
[ "MIT" ]
permissive
// // Configuration.swift // KoanUI // // Created by Alberto Pasca on 30/05/16. // Copyright © 2016 albertopasca.it. All rights reserved. // import Cocoa class Configuration { func loadDataModel() -> NSDictionary { return File().dictionaryFromFile(Constants.kJsonFileName, Constants.kJsonFileExt) } func loadAllCategories() -> [String] { let categories = loadDataModel() return (categories.valueForKey("categories")?.allKeys)! } func loadDetailForCategory(category : String) -> NSMutableDictionary { let categories = loadDataModel() let array = (categories.valueForKeyPath(String(format: "categories.%@", category)) as? NSArray)! let retDict = NSMutableDictionary() for item in array { let key = (item as! NSDictionary).allKeys[0] as! String let val = (item as! NSDictionary).allValues[0] as! String retDict.setValue(val, forKey: key) } return retDict } }
true
2a41cfeeff0b23b768576d5f9db019d1932bfa69
Swift
ecaepsey/fff
/MVVMC-SplitViewController/Application/AppCoordinator.swift
UTF-8
2,100
2.578125
3
[]
no_license
// // AppCoordinator.swift // MVVMC-SplitViewController // // Created by Mathew Gacy on 12/28/17. // Copyright © 2017 Mathew Gacy. All rights reserved. // import UIKit import RxSwift class AppCoordinator: BaseCoordinator<Void> { private let window: UIWindow private let dependencies: AppDependency init(window: UIWindow) { self.window = window self.dependencies = AppDependency() } override func start() -> Observable<Void> { coordinateToRoot(basedOn: dependencies.userManager.authenticationState) return .never() } /// Recursive method that will restart a child coordinator after completion. /// Based on: /// https://github.com/uptechteam/Coordinator-MVVM-Rx-Example/issues/3 private func coordinateToRoot(basedOn authState: AuthenticationState) { switch authState { case .signedIn: return showSplitView() .subscribe(onNext: { [weak self] authState in self?.window.rootViewController = nil self?.coordinateToRoot(basedOn: authState) }) .disposed(by: disposeBag) case .signedOut: return showLogin() .subscribe(onNext: { [weak self] authState in self?.window.rootViewController = nil self?.coordinateToRoot(basedOn: authState) }) .disposed(by: disposeBag) } } private func showSplitView() -> Observable<AuthenticationState> { let splitViewCoordinator = SplitViewCoordinator(window: self.window, dependencies: dependencies) return coordinate(to: splitViewCoordinator) .map { [unowned self] _ in self.dependencies.userManager.authenticationState } } private func showLogin() -> Observable<AuthenticationState> { let loginCoordinator = LoginCoordinator(window: window, dependencies: dependencies) return coordinate(to: loginCoordinator) .map { [unowned self] _ in self.dependencies.userManager.authenticationState } } }
true
e919bfb3d8fcafc3228f305afe387c7b3069260f
Swift
derrickkim0109/100-days-swift-projects
/Day91Challenge/Learn-Core-Graphics.playground/Pages/Images.xcplaygroundpage/Contents.swift
UTF-8
1,830
3.71875
4
[]
no_license
//: [< Previous](@previous)           [Home](Introduction)           [Next >](@next) //: # Picture perfect //: If you have a `UIImage`, you can render it directly into a Core Graphics context at any size you want – it will automatically be scaled up or down as needed. To do this, just call `draw(in:)` on your image, passing in the `CGRect` where it should be drawn. //: //: - Experiment: Your designer wants you to create a picture frame effect for an image. He's placed the frame at the right size, but it's down to you to position it correctly then position and size the image inside it. import UIKit let rect = CGRect(x: 0, y: 0, width: 1000, height: 1000) let renderer = UIGraphicsImageRenderer(bounds: rect) let mascot = UIImage(named: "HackingWithSwiftMascot.jpg") extension CGSize { func centerOffset(in rect: CGRect) -> CGPoint { let x = (rect.width - self.width) / 2 + rect.origin.x let y = (rect.height - self.height) / 2 + rect.origin.y return CGPoint(x: x, y: y) } } let rendered = renderer.image { ctx in UIColor.darkGray.setFill() ctx.cgContext.fill(rect) let frameEdge = 640 let frameSize = CGSize(width: frameEdge, height: frameEdge) let frameOrigin = frameSize.centerOffset(in: rect) UIColor.black.setFill() let frameRect = CGRect(origin: frameOrigin, size: frameSize) ctx.cgContext.fill(frameRect) let frameWidth = 20 let imageEdge = frameEdge - 2 * frameWidth let imageSize = CGSize(width: imageEdge, height: imageEdge) let imageOrigin = imageSize.centerOffset(in: frameRect) let imageRect = CGRect(origin: imageOrigin, size: imageSize) mascot?.draw(in: imageRect) } showOutput(rendered) //: [< Previous](@previous)           [Home](Introduction)           [Next >](@next)
true
1f4efc6077afa393a1cbdcbbe673580793320cb6
Swift
rohitsainier/SwiftUI6
/SwiftUI6/ContentView.swift
UTF-8
1,121
2.734375
3
[]
no_license
// // ContentView.swift // SwiftUI6 // // Created by Rohit Saini on 01/07/20. // Copyright © 2020 AccessDenied. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { Image("profilepic").resizable().frame(height: 300).aspectRatio(contentMode: .fit).cornerRadius(20).padding() .contextMenu{ VStack{ Button(action: { print("Save") }) { HStack{ Image(systemName: "folder.fill") Text("Save to Gallery") } } Button(action: { print("Send") }) { HStack{ Image(systemName: "paperplane.fill") Text("Send") } } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
true
71ef60fc3f886530ed798e3e9e04035f97189ace
Swift
vsricci/ProjectTestCI
/Extensions/UIViewController+Extensions.swift
UTF-8
1,565
2.671875
3
[]
no_license
// // UIViewController+Extensions.swift // GoodWeather // // Created by Vinicius Ricci on 07/02/19. // Copyright © 2019 Vinicius Ricci. All rights reserved. // import UIKit extension UIViewController { private struct AssociatedKeys { static var ParentCoordinator = "ParentCoordinator" } weak var parentCoordinator: Coordinator? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ParentCoordinator) as? Coordinator } set { objc_setAssociatedObject(self, &AssociatedKeys.ParentCoordinator, newValue, .OBJC_ASSOCIATION_ASSIGN) } } } extension UIViewController : Presentable { func toPresent() -> UIViewController? { return self } } extension UIViewController { private class func instantiateControllerInStoryboard<T: UIViewController>(_ storyboard: UIStoryboard, identifier: String) -> T { return storyboard.instantiateViewController(withIdentifier: identifier) as! T } class func controllerInStoryboard(_ storyboard: UIStoryboard, identifier: String) -> Self { return instantiateControllerInStoryboard(storyboard, identifier: identifier) } class func controllerInStoryboard(_ storyboard: UIStoryboard) -> Self { return controllerInStoryboard(storyboard, identifier: nameOfClass) } class func controllerFromStoryboard(_ storyboard: Storyboards) -> Self { return controllerInStoryboard(UIStoryboard(name: storyboard.rawValue, bundle: nil), identifier: nameOfClass) } }
true
1e48d16a7c33d79d2bd37587844bbd0291a0429f
Swift
pamierdt/LeetCode
/LeetCode/MyPlayground.playground/Contents.swift
UTF-8
4,815
3.34375
3
[ "MIT" ]
permissive
import UIKit class Solution { func bubbleSort(_ list: inout [Int]) { guard list.count > 1 else { return } for i in 0 ..< list.count { for j in i + 1 ..< list.count { let a = list[i] let b = list[j] if b < a { list[i] = b list[j] = a } else {/* do nothing*/} } } } /// 选择排序 func selectionSort(_ list: inout [Int]) { for j in 0 ..< list.count - 1 { var minIndex = j for i in j ..< list.count { if list[minIndex] > list[i] { minIndex = i } } list.swapAt(j, minIndex) } } // 从排序数组中删除重复项 func removeDuplicates(_ nums: inout [Int]) -> Int { // 空数组 和 一个元素的数组 if nums.count < 2 { return nums.count } var numbers: Int = 0 for i in 0 ..< nums.count { if nums[i] != nums[numbers] { numbers += 1 nums[numbers] = nums[i] } } return numbers + 1 } // 双指针 // if nums.count < 2 { // return nums.count // } // var fast = 1 // var slow = 1 // while fast < nums.count { // if nums[fast] != nums[fast-1] { // nums[slow] = nums[fast] // slow += 1 // } // fast += 1 // } // return slow // 最大利润 func maxProfit(_ prices: [Int]) -> Int { /* 一次遍历 不可用 var minPrice: Int = Int.max var maxProfit: Int = Int.min for p in prices { if (p < minPrice) { minPrice = p } else if (p - minPrice > maxProfit) { maxProfit = p - minPrice } } return maxProfit */ // 1. 暴力搜索 // 2. 动态规划 // 3. 贪心算法 var result: [Int] = [] return 0 } // 旋转数组 func rotate(_ nums: inout [Int], _ k: Int) { } //爬楼梯 func climbStairs(_ n: Int) -> Int { return 1 } // 两个数组中重复的元素 func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] { let len1 = nums1.count let len2 = nums2.count var bl: [Bool] = nums2.map { (_) -> Bool in return false } var array: [Int] = [] for i in 0..<len1 { for j in 0..<len2 { if nums1[i] == nums2[j], bl[j] == false { array.append(nums1[i]) bl[j] = true break } } } var result: [Int] = Array(array) var e: Int = 0 for i in array { result[e] = i e += 1 } return result } func plusOne(_ digits: [Int]) -> [Int] { var results: [Int] = Array(digits) for i in (0...digits.count-1).reversed() { if results[i] == 9 { results[i] = 0 } else { results[i] += 1 return results } } var numbers: [Int] = [] for _ in 0...digits.count { numbers.append(0) } numbers[0] = 1 return numbers } func moveZeroes(_ nums: inout [Int]) { var zeroIndex = -1 var i = 0 while(i < nums.count) { if (nums[i] != 0) { if (zeroIndex >= 0) { nums[zeroIndex] = nums[i] nums[i] = 0 zeroIndex += 1 } } else if (zeroIndex < 0) { zeroIndex = i } i += 1 } } func twoSum(_ nums: [Int], _ target: Int) -> [Int] { var dict = [Int: Int]() for (i, num) in nums.enumerated() { if let lastIndex = dict[target - num] { return [lastIndex, i] } dict[num] = i } fatalError("No valid outputs") } func isValidSudoku(_ board: [[Character]]) -> Bool { for i in 0..<board.count { for j in 0..<board[i].count { print(j) } } return false } // } var arrays: [Int] = [2, 0, 12, 2, 0, 3] print(arrays) Solution().selectionSort(&arrays) print(arrays) print(Solution().removeDuplicates(&arrays)) print(arrays) Solution().moveZeroes(&arrays) print(arrays) print(Solution().twoSum([2,3,5,7], 5)) Solution().isValidSudoku([[]])
true
384fa5ab0e508b2f281a33f156e5c9678201502e
Swift
AviPogrow/ShadchanContactManagerV18
/NasiShadchanHelper/CustomViews/GradientColor/GradientView.swift
UTF-8
6,505
3.203125
3
[]
no_license
import UIKit @IBDesignable class GradientButton: UIButton { // Comma(,) seprated hex codes of gradient colors @IBInspectable var gradientColors: String! // Gradient style possible values only 0,1,2 @IBInspectable var gradientStyle:Int = 1 // Gradient color alpha possible values only 0 to 1 @IBInspectable var colorsAlpha:CGFloat = 1.0 override func layoutSubviews() { super.layoutSubviews() updateGradientColors() } func updateGradientColors() { if gradientColors != nil { let aryGradientColors = gradientColors.components(separatedBy: ",") let style = GradientStyle(rawValue: gradientStyle) self.backgroundColor = UIColor.gradient(style:style!, frame:bounds, hexColors: aryGradientColors,alpha:colorsAlpha) } } } @IBDesignable class GradientTransView: UIView { // Comma(,) seprated hex codes of gradient colors @IBInspectable var gradientColors: String! // Gradient style possible values only 0,1,2 @IBInspectable var gradientStyle:Int = 1 // Gradient color alpha possible values only 0 to 1 @IBInspectable var colorsAlpha:CGFloat = 1.0 override func layoutSubviews() { super.layoutSubviews() updateGradientColors() } func updateGradientColors() { if gradientColors != nil { let aryGradientColors = gradientColors.components(separatedBy: ",") let style = GradientStyle(rawValue: gradientStyle) self.backgroundColor = UIColor.gradient(style:style!, frame:bounds, hexColors: aryGradientColors,alpha:colorsAlpha) } } } //MARK: Gradient Type @objc enum GradientStyle : Int { case leftToRight case radial case topToBottom case diagonal } //MARK: -UIColor extension UIColor { // Gradient color with Hex codes and specific style Frame Dependant class func gradient(style:GradientStyle,frame:CGRect,hexColors:[String]) -> UIColor { if hexColors.count == 0 { return Constant.AppColor.colorAppTheme } else { var cgColors = [CGColor]() hexColors.forEach({ (hexCode) in cgColors.append(withHex(hex: hexCode, alpha: 1.0).cgColor) }) return gradient(style: style, frame: frame, colors: cgColors) } } // Gradient color with Hex codes & alpha and specific style Frame Dependant class func gradient(style:GradientStyle,frame:CGRect,hexColors:[String],alpha:CGFloat) -> UIColor { if hexColors.count == 0 { return Constant.AppColor.colorAppTheme } else { var cgColors = [CGColor]() hexColors.forEach({ (hexCode) in cgColors.append(withHex(hex: hexCode, alpha: alpha).cgColor) }) return gradient(style: style, frame: frame, colors: cgColors) } } // Gradient color with radial style Frame InDependant class func gradient(frame:CGRect,colors:[CGColor]) -> UIColor { return gradient(style:.radial, frame:frame, colors: colors) } // Gradient color with radial style and HexColors Frame InDependant class func gradient(frame:CGRect,hexColors:[String]) -> UIColor { if hexColors.count == 0 { return Constant.AppColor.colorAppTheme } else { var cgColors = [CGColor]() hexColors.forEach({ (hexCode) in cgColors.append(withHex(hex: hexCode, alpha: 1.0).cgColor) }) return gradient(style:.radial, frame: frame, colors: cgColors) } } // Gradient color with specific style and CGColors Frame Dependant class func gradient(style:GradientStyle,frame:CGRect,colors:[CGColor]) -> UIColor { let gradientLayer = CAGradientLayer() gradientLayer.frame = frame if style == .leftToRight || style == .topToBottom { gradientLayer.colors = colors if style == .leftToRight { gradientLayer.startPoint = CGPoint.init(x: 0.0, y: 0.5) gradientLayer.endPoint = CGPoint.init(x: 1.0, y: 0.5) } UIGraphicsBeginImageContextWithOptions(gradientLayer.bounds.size, false, UIScreen.main.scale) gradientLayer.render(in: UIGraphicsGetCurrentContext()!) let gradientImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return UIColor.init(patternImage: gradientImage!) } else if style == .diagonal { gradientLayer.colors = colors gradientLayer.startPoint = CGPoint.init(x: 1.0, y: 0.0) gradientLayer.endPoint = CGPoint.init(x: 0.0, y: 1.0) UIGraphicsBeginImageContextWithOptions(gradientLayer.bounds.size, false, UIScreen.main.scale) gradientLayer.render(in: UIGraphicsGetCurrentContext()!) let gradientImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return UIColor.init(patternImage: gradientImage!) } else { UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.main.scale) let locations:[CGFloat] = [0.0,1.0] //Default to the RGB Colorspace let myColorspace = CGColorSpaceCreateDeviceRGB() let arrayRef:CFArray = colors as CFArray //Create our Gradient let gradient = CGGradient.init(colorsSpace:myColorspace, colors: arrayRef, locations: locations); // Normalise the 0-1 ranged inputs to the width of the image let centerPoint = CGPoint.init(x: frame.size.width*0.5, y: frame.size.height*0.5) let radius = min(frame.size.width, frame.size.height)*1.0 // Draw our Gradient UIGraphicsGetCurrentContext()?.drawRadialGradient(gradient!, startCenter:centerPoint, startRadius:0, endCenter: centerPoint, endRadius: radius, options: .drawsAfterEndLocation) let gradientImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext() return UIColor.init(patternImage: gradientImage!) } } }
true
a821306aad8f2fcf099a2efa978afa03aff8cf4f
Swift
cotkjaer/Rounding
/RoundingTests/RoundingTests.swift
UTF-8
2,796
3.078125
3
[]
no_license
// // RoundingTests.swift // RoundingTests // // Created by Christian Otkjær on 05/11/2017. // Copyright © 2017 Silverback IT. All rights reserved. // import XCTest @testable import Rounding class RoundingTests: XCTestCase { func test_round() { var d: Double? = nil XCTAssertEqual(d?.round, nil) XCTAssertEqual(round(d), nil) d = .pi XCTAssertNotEqual(d?.round, nil) XCTAssertEqual(round(d), 3) XCTAssertEqual(Double.pi.round, 3) XCTAssertEqual(Double(3).round, 3) XCTAssertEqual(Double(-3).round, -3) XCTAssertEqual((-Double.pi).round, -3) XCTAssertEqual(Float.pi.round, 3) XCTAssertEqual(Float(3).round, 3) XCTAssertEqual(Float(-3).round, -3) XCTAssertEqual((-Float.pi).round, -3) } func test_ceil() { var d: Double? = nil XCTAssertEqual(d?.ceil, nil) XCTAssertEqual(ceil(d), nil) d = .pi XCTAssertNotEqual(d?.ceil, nil) XCTAssertEqual(ceil(d), 4) XCTAssertEqual(Double.pi.ceil, 4) XCTAssertEqual(Double(3).ceil, 3) XCTAssertEqual(Double(-3).ceil, -3) XCTAssertEqual((-Double.pi).ceil, -3) XCTAssertEqual(Float.pi.ceil, 4) XCTAssertEqual(Float(3).ceil, 3) XCTAssertEqual(Float(-3).ceil, -3) XCTAssertEqual((-Float.pi).ceil, -3) } func test_floor() { var d: Double? = nil XCTAssertEqual(d?.floor, nil) XCTAssertEqual(floor(d), nil) d = .pi XCTAssertNotEqual(d?.floor, nil) XCTAssertEqual(floor(d), 3) XCTAssertEqual(Double.pi.floor, 3) XCTAssertEqual(Double(3).floor, 3) XCTAssertEqual(Double(-3).floor, -3) XCTAssertEqual((-Double.pi).floor, -4) XCTAssertEqual(Float.pi.floor, 3) XCTAssertEqual(Float(3).floor, 3) XCTAssertEqual(Float(-3).floor, -3) XCTAssertEqual((-Float.pi).floor, -4) } func test_round_to_nearest() { let d = 5.081 XCTAssertEqual(d.rounded(toNearest: 100), 0.0) XCTAssertEqual(d.rounded(toNearest: 10), 10.0) XCTAssertEqual(d.rounded(toNearest: 1), 5.0) XCTAssertEqual(d.rounded(toNearest: 0.1), 5.1) XCTAssertEqual(d.rounded(toNearest: 0.01), 5.08) XCTAssertEqual(d.rounded(toNearest: 0.001), 5.081) XCTAssertEqual(d.rounded(toNearest: 0.0001), 5.081) XCTAssertEqual(d.rounded(toNearest: 0.0001), d.rounded(toNearest: 0.00000001)) XCTAssertEqual(d.rounded(toNearest: 2.54), 5.08) XCTAssertEqual(d.rounded(toNearest: -2.54), 5.08) } }
true
443d812d55b19ff83e58e4108f6a659d4fbf0668
Swift
danaennash/CodableAndJSONDecoding
/CodeableAndJSONDecoding/Model/Inventory.swift
UTF-8
482
3.015625
3
[]
no_license
// // Inventory.swift // CodeableAndJSONDecoding // // Created by Danae N Nash on 11/04/19. // Copyright © 2019 Danae N Nash. All rights reserved. // import Foundation struct ItemInventory: Codable{ var status: String var products: [Product] enum CodingKeys: String, CodingKey{ case status case products } } struct Product: Codable{ var id: Int var category: String var title: String var price: Double var stockedQuantity: Int }
true
17054ad8c3fb276ba75bebc1d258c028415d8fb9
Swift
fumiyasac/ReduxSampleSwift
/ReduxSampleSwift/Enum/SelectedResidentPeriodEnum.swift
UTF-8
962
3.109375
3
[]
no_license
// // SelectedResidentPeriodEnum.swift // ReduxSampleSwift // // Created by 酒井文也 on 2018/04/30. // Copyright © 2018年 酒井文也. All rights reserved. // import Foundation enum SelectedResidentPeriodEnum: String { case first = "1年未満" case second = "1年~5年未満" case third = "5年~10年未満" case fourth = "10年~15年未満" case fifth = "15年~20年未満" case sixth = "20年以上" // MARK: - Static Function static func getAll() -> [SelectedResidentPeriodEnum] { return [.first, .second, .third, .fourth, .fifth, .sixth] } // MARK: - Function func getStatusCode() -> Int { switch self { case .first: return 1 case .second: return 2 case .third: return 3 case .fourth: return 4 case .fifth: return 5 case .sixth: return 6 } } }
true
37d189e0229d7b36ab59a24192da90cb776775c0
Swift
Anilkr91/FB
/FunBook/Controllers/Address/EditAddressTableViewController.swift
UTF-8
2,560
2.5625
3
[]
no_license
// // EditAddressTableViewController.swift // FunBook // // Created by admin on 22/01/18. // Copyright © 2018 Techximum. All rights reserved. // import UIKit class EditAddressTableViewController: BaseTableViewController { @IBOutlet weak var selectCountryTextField: UITextField! @IBOutlet weak var firstNameTextField: UITextField! @IBOutlet weak var lastNameTextField: UITextField! @IBOutlet weak var addressFirstTextField: UITextField! @IBOutlet weak var addressSecondTextField: UITextField! @IBOutlet weak var cityTextField: UITextField! @IBOutlet weak var stateTextField: UITextField! @IBOutlet weak var zipCodeTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func submitButtonTapped(_ sender: Any) { let country = selectCountryTextField.text! let firstName = firstNameTextField.text! let lastName = lastNameTextField.text! let addressFirst = addressFirstTextField.text! let addressSecond = addressSecondTextField.text! let city = cityTextField.text! let state = stateTextField.text! let zipCode = zipCodeTextField.text! if country.removeAllSpaces().isEmpty { showAlert("Error", message: "country cannot be empty") } else if firstName.removeAllSpaces().isEmpty { showAlert("Error", message: "firstName cannot be empty") } else if lastName.removeAllSpaces().isEmpty { showAlert("Error", message: "lastName cannot be empty") } else if addressFirst.removeAllSpaces().isEmpty { showAlert("Error", message: "addressFirst cannot be empty") } else if addressSecond.removeAllSpaces().isEmpty { showAlert("Error", message: "addressSecond cannot be empty") } else if city.removeAllSpaces().isEmpty { showAlert("Error", message: "city cannot be empty") } else if state.removeAllSpaces().isEmpty { showAlert("Error", message: "state cannot be empty") } else if zipCode.removeAllSpaces().isEmpty { showAlert("Error", message: "zipCode cannot be empty") } else { print("hit api") } } }
true
bc1523f2b94c770f37e5c7e0876d901f77dcef32
Swift
exalted/Yeni1Tarif
/app/data_sources/EntriesDataSource.Index.swift
UTF-8
675
2.859375
3
[]
no_license
import UIKit extension EntriesDataSource : UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! EntryCell guard let entry = self.entryAtIndexPath(indexPath) else { return cell } cell.configureWithObject(entry, forIndexPath: indexPath) return cell } }
true
dffba96c172b0023df62f85e2bfca7f3dbb6b8ee
Swift
radianttap/Fields
/Fields/Cells/FormFieldCell.swift
UTF-8
1,398
2.5625
3
[ "MIT" ]
permissive
// // FormFieldCell.swift // Fields // // Copyright © 2019 Radiant Tap // MIT License · http://choosealicense.com/licenses/mit/ // import UIKit class FormFieldCell: UICollectionViewCell { override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { let attr = layoutAttributes.copy() as! UICollectionViewLayoutAttributes let labels: [UILabel] = deepGrepSubviews() labels.forEach { $0.preferredMaxLayoutWidth = min($0.preferredMaxLayoutWidth, bounds.width) } if #available(iOS 13, *) { // works fine } else { // without this, fittedSize (below) becomes {0,0} layoutIfNeeded() } let fittedSize = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel) attr.frame.size.height = ceil(fittedSize.height) return attr } } fileprivate extension UIView { func grepSubviews<T: UIView>() -> [T] { return subviews.compactMap { $0 as? T } } func deepGrepSubviews<T: UIView>() -> [T] { var arr: [T] = grepSubviews() let children: [T] = subviews.reduce([]) { current, v in var arr = current let x: [T] = v.deepGrepSubviews() arr.append(contentsOf: x) return arr } arr.append(contentsOf: children) return arr } }
true
c48f6f796a520a4ea4e3f95dd67b0be0a7cf41d6
Swift
odelfyette/OnTheMap
/On The Map/Controllers/StudentMapViewController.swift
UTF-8
3,469
2.59375
3
[]
no_license
// // StudentMapViewController.swift // On The Map // // Created by Octavius on 11/8/17. // Copyright © 2017 Delfyette Designs. All rights reserved. // import UIKit import MapKit class StudentMapViewController: UIViewController { //MARK: Variables @IBOutlet weak var mapView: MKMapView! let appDelegate = (UIApplication.shared.delegate as! AppDelegate) //MARK: LifeCycle override func viewDidLoad() { super.viewDidLoad() let controller = self.storyboard!.instantiateViewController(withIdentifier: "LoadingStudentsViewController") as! LoadingStudentsViewController self.present(controller, animated: true, completion: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setPins() } } //MARK: MAP Delegates extension StudentMapViewController: MKMapViewDelegate{ func setPins(){ var annotations = [MKPointAnnotation]() if(ParseStudentLocationSharedInstance.sharedInstance.studentLocations != nil){ for student in ParseStudentLocationSharedInstance.sharedInstance.studentLocations{ if let latitude = student.latitude, let longitude = student.longitude{ let lat = CLLocationDegrees(latitude) let long = CLLocationDegrees(longitude) let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long) let annotation = MKPointAnnotation() annotation.coordinate = coordinate annotation.title = StringFormat.formatNameText(firstName: student.firstName, lastName: student.lastName) if let mediaURL = student.mediaURL{ annotation.subtitle = mediaURL }else{ annotation.subtitle = "[No Media URL]" } annotations.append(annotation) } } self.mapView.removeAnnotations(mapView.annotations) self.mapView.addAnnotations(annotations) } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let reuseId = "pin" var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView!.canShowCallout = true pinView!.pinTintColor = .red pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } else { pinView!.annotation = annotation } return pinView } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if control == view.rightCalloutAccessoryView { let app = UIApplication.shared if let toOpen = view.annotation?.subtitle! { if(ValidateURL.isValidURL(urlString: toOpen)){ app.open(URL(string: toOpen)!, options: [:], completionHandler: nil) }else{ ValidateURL.showInvalidUrlMessage(viewCtrl: self) } } } } }
true
6af40445146e6ef8b28bfb4f359c31d6cf9e3729
Swift
javaBin/ems-ios
/EMS/Network/Model/EMSSpeaker.swift
UTF-8
414
2.59375
3
[]
no_license
import Foundation @objc class EMSSpeaker: NSObject { var name: String? var href: NSURL? var bio: String? var thumbnailUrl: NSURL? var lastUpdated: NSDate? override var description: String { return "<\(self.dynamicType): self.name=\(self.name), self.href=\(self.href), self.bio=\(self.bio), self.thumbnailUrl=\(self.thumbnailUrl), self.lastUpdated=\(self.lastUpdated)>" } }
true
21aa8abb8a1a2c9a3e76189c48d7471ecd413d34
Swift
ganeshpatro/TineyNetworkRequestClient
/TinyNetworkRequestClient/ViewController.swift
UTF-8
1,225
2.96875
3
[ "MIT" ]
permissive
// // ViewController.swift // TinyNetworkRequestClient // // Created by Ganesh on 02/02/19. // Copyright © 2019 Ganesh. All rights reserved. // import UIKit enum AppURL: String { case GROUPS = "http://api.myjson.com/bins/3b0u2" } enum GroupsResult<T> { case success(T) case error(Error) } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NetworkRequestManager.sharedManager.sendGETRequest(AppURL.GROUPS.rawValue) { (result) in switch (result) { case .success(let dataResponnse): //Handle the response and do the parsing do { let searchResultDict = try JSONSerialization.jsonObject(with: dataResponnse, options: JSONSerialization.ReadingOptions.allowFragments); print("API Result is - \(searchResultDict)") } catch(let error) { print("Error in serializing - \(error)") } case .failue(let error): print("There is an error in the response.") } } } }
true
6bf03cbdac456d3a1c1996645e888e7728afdcf1
Swift
wyd2004/LeetCode-Swift
/LeetCode-Swift/299. 猜数字游戏/getHint.swift
UTF-8
1,191
3.421875
3
[]
no_license
// // getHint.swift // LeetCode-Swift // // Created by 王一丁 on 2020/4/14. // Copyright © 2020 yidingw. All rights reserved. // import Foundation func getHint(_ secret: String, _ guess: String) -> String { func count(_ string: String) -> Dictionary<Character, Int> { var result = [Character : Int]() for char in string { if let _ = result[char] { result[char]! += 1 } else { result[char] = 1 } } return result } var secretCounter = count(secret) var guessCounter = count(guess) var result = (0, 0) for (x, y) in zip(secret, guess) { if x == y { secretCounter[x]! -= 1 guessCounter[y]! -= 1 result.0 += 1 } } let secretCountSet = Set<Character>.init(secretCounter.keys) let guessCountSet = Set<Character>.init(guessCounter.keys) for k in secretCountSet.union(guessCountSet) { if let _ = secretCounter[k], let _ = guessCounter[k] { result.1 += min(secretCounter[k]!, guessCounter[k]!) } } return "\(result.0)A\(result.1)B" }
true
e79d7e3cb81607da9193846aecdd83d74ffaeb5b
Swift
williamxiewz/Demo-Xcode-github
/Demo/Demo/Foundations/Toggles/TogglesDataStoreType.swift
UTF-8
177
2.9375
3
[]
permissive
import Foundation protocol ToggleType { } protocol TogglesDataStoreType { func isToggleOn(_ toggle: ToggleType) -> Bool func update(toggle: ToggleType, value: Bool) }
true
1c395081986b5d7b7be99631c497c8fe7663af3c
Swift
VovaLobanov/petProject
/PetProject/Presentation/Users/UsersProtocols.swift
UTF-8
510
2.71875
3
[]
no_license
// // UsersProtocols.swift // PetProject // // Created by Lobanov Vladimir on 3/12/21. // import UIKit protocol UsersViewInput { func updateUI() } protocol UsersViewOutput { func viewDidLoad() func userSelected(at index: Int) func didPullToRefresh() var users: [User] { get } } protocol UsersInteractorInput { func fetchUsers() } protocol UsersInteractorOutput { func usersFetched(users: [User]) func usersFetchingFailed() } protocol UsersRouterInput { func openRepositories(for user: User) }
true
c93344d4effd9bc85ce9d795b50db4a1e25cf63e
Swift
RaisaRamazanova/Homework
/Лекция07/Reduce.playground/Contents.swift
UTF-8
280
3.484375
3
[ "Apache-2.0" ]
permissive
import UIKit var array = [2, 3, 6, 5, 4] // filter var array2 = array.reduce([], { a, b in var c = a if b > 5 { c.append(b) } return c }) print(array2) // map var array3 = array.reduce([], { a, b in var c = a c.append(b*b) return c }) print(array3)
true
5f81963c06eab5eba6a7a5d38c83926b668b58f8
Swift
mejiagarcia/GamingNewsiOS
/gamingnews/Shared/Cells/CollectionViewCells/FilterCollectionViewCell/FilterCellViewModel.swift
UTF-8
891
2.6875
3
[]
no_license
// // FilterCellViewModel.swift // gamingnews // // Created by Carlos Mejia on 3/19/19. // Copyright © 2019 Carlos Mejia. All rights reserved. // import Foundation import UIKit struct FilterCellViewModel: FilterCollectionViewCellDataSource { let title: String let titleFont: UIFont? let titleColor: UIColor? let backgroundColor: UIColor? let iconImage: UIImage? let iconImageTintColor: UIColor? init(title: String, titleFont: UIFont? = nil, titleColor: UIColor? = nil, backgroundColor: UIColor? = nil, iconImage: UIImage? = nil, iconImageTintColor: UIColor? = nil) { self.title = title self.titleFont = titleFont self.titleColor = titleColor self.backgroundColor = backgroundColor self.iconImage = iconImage self.iconImageTintColor = iconImageTintColor } }
true
cc574d89133ec993379eee4325a0c01c58c9cd5e
Swift
hubpixie/sagxa-dormo-ios
/SagxaDormo/Views/View/UIActivityIndicatorView+ext.swift
UTF-8
2,985
2.59375
3
[]
no_license
// // UIActivityIndicatorView+ext.swift // SaĝaDormo // // Created by venus.janne on 2018/08/08. // Copyright © 2018年 venus.janne. All rights reserved. // import UIKit extension UIActivityIndicatorView { class func setupIndicator(parentView: UIView) -> UIActivityIndicatorView { let loadingView: UIView = UIView() loadingView.frame = CGRect(x: 0, y: 0, width: 100, height: 100) loadingView.center = parentView.center loadingView.backgroundColor = UIColor(displayP3Red: 0x00, green: 0x00, blue: 0x00, alpha: 0.4) loadingView.clipsToBounds = true loadingView.layer.cornerRadius = 10 loadingView.isHidden = true let indicator: UIActivityIndicatorView = UIActivityIndicatorView() indicator.frame = CGRect(x: 0, y: 0, width: 100, height: 100) indicator.center = CGPoint(x: loadingView.frame.size.width / 2, y: loadingView.frame.size.height / 2) indicator.color = UIColor.red.withAlphaComponent(0.5) indicator.style = .whiteLarge indicator.hidesWhenStopped = true loadingView.addSubview(indicator) parentView.addSubview(loadingView) parentView.bringSubviewToFront(loadingView) return indicator } func startAnimatingEx(sender: Any?) { if let sender = sender as? UIButton { sender.isEnabled = false } else if let sender = sender as? UISwitch { sender.isEnabled = false } if let subViews = self.superview?.subviews { for v in subViews { if v is UITextField && v.isUserInteractionEnabled { v.isUserInteractionEnabled = false } } } self.superview?.isHidden = false self.startAnimating() if !UIApplication.shared.isIgnoringInteractionEvents { UIApplication.shared.beginIgnoringInteractionEvents() } } func adjustToPosition(frame: CGRect) { self.superview?.backgroundColor = .clear self.style = .gray self.color = UIColor.red.withAlphaComponent(0.5) self.superview?.center = CGPoint(x: frame.origin.x + frame.width / 8 , y: frame.origin.y + frame.height / 2) } func stopAnimatingEx(sender: Any?) { if let sender = sender as? UIButton { sender.isEnabled = true } else if let sender = sender as? UISwitch { sender.isEnabled = true } if let subViews = self.superview?.subviews { for v in subViews { if v is UITextField && !v.isUserInteractionEnabled { v.isUserInteractionEnabled = true } } } self.superview?.isHidden = true self.stopAnimating() if UIApplication.shared.isIgnoringInteractionEvents { UIApplication.shared.endIgnoringInteractionEvents() } } }
true
a7aff04920f7555cb67fc780ac4aacfe22b4a45c
Swift
ellishg/Tip-Calculator
/tips/SettingsViewController.swift
UTF-8
3,908
2.625
3
[ "Apache-2.0" ]
permissive
// // SettingsViewController.swift // tips // // Created by Ellis Sparky Hoag on 12/5/15. // Copyright © 2015 Ellis Sparky Hoag. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var tipSlider: UISlider! @IBOutlet weak var redSlider: UISlider! @IBOutlet weak var greenSlider: UISlider! @IBOutlet weak var blueSlider: UISlider! @IBOutlet weak var colorView: UIView! @IBOutlet weak var roundingSwitch: UISwitch! @IBOutlet weak var signControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let defaults = NSUserDefaults.standardUserDefaults() tipSlider.value = Float(defaults.integerForKey("Default Tip")) tipLabel.text = ("Default Tip: \(defaults.integerForKey("Default Tip"))%") let red = defaults.floatForKey("Red Background") let green = defaults.floatForKey("Green Background") let blue = defaults.floatForKey("Blue Background") redSlider.value = red greenSlider.value = green blueSlider.value = blue colorView.backgroundColor = UIColor(colorLiteralRed: red, green: green, blue: blue, alpha: 1.0) colorView.layer.borderColor = UIColor(colorLiteralRed: 0.0, green: 0.0, blue: 0.0, alpha: 1.0).CGColor colorView.layer.borderWidth = 1.5 signControl.selectedSegmentIndex = defaults.integerForKey("Currency Sign") roundingSwitch.on = defaults.boolForKey("Rounding Switch") } 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. } */ @IBAction func tipValueChanged(sender: AnyObject) { tipLabel.text = "Default Tip: \(Int(tipSlider.value))%" let defaults = NSUserDefaults.standardUserDefaults() defaults.setInteger(Int(tipSlider.value), forKey: "Default Tip") defaults.synchronize() } @IBAction func colorSlider(sender: AnyObject) { let defaults = NSUserDefaults.standardUserDefaults() let red = redSlider.value let green = greenSlider.value let blue = blueSlider.value let color = UIColor(colorLiteralRed: red, green: green, blue: blue, alpha: 1.0) defaults.setFloat(red, forKey: "Red Background") defaults.setFloat(green, forKey: "Green Background") defaults.setFloat(blue, forKey: "Blue Background") defaults.synchronize() colorView.backgroundColor = color } @IBAction func signControlChanged(sender: AnyObject) { let defaults = NSUserDefaults.standardUserDefaults() signControl.titleForSegmentAtIndex(signControl.selectedSegmentIndex) defaults.setInteger(signControl.selectedSegmentIndex, forKey: "Currency Sign") defaults.synchronize() } @IBAction func roundingSwitchValueChanged(sender: AnyObject) { let defaults = NSUserDefaults.standardUserDefaults() defaults.setBool(roundingSwitch.on, forKey: "Rounding Switch") defaults.synchronize() } }
true
5e6c80a771d10bb3ecbef0f28bc35033907180ff
Swift
openffd/cc
/CartrackContacts/Views/Signup/CreatePassword/SignupCreatePasswordViewModel.swift
UTF-8
1,665
2.71875
3
[]
no_license
// // SignupCreatePasswordViewModel.swift // CartrackContacts // // Created by Feb De La Cruz on 9/12/20. // Copyright © 2020 Feb De La Cruz. All rights reserved. // import Foundation import RxSwift final class SignupCreatePasswordViewModel: ViewModel { struct Input { let usernameSubject: BehaviorSubject<String> let password: AnyObserver<String> } struct Output {} enum PasswordValidity { case valid, invalid } enum PasswordErrorVisibility { case shouldShow, shouldHide } let passwordMinimumCharacterCount = 3 let input: Input let output: Output fileprivate let passwordSubject = BehaviorSubject<String>(value: "") let proceedAction = PublishSubject<Void>() init(usernameSubject: BehaviorSubject<String>) { input = Input(usernameSubject: usernameSubject, password: passwordSubject.asObserver()) output = Output() } func shouldShowError(for password: String) -> PasswordErrorVisibility { if password.count > 0 && password.count < passwordMinimumCharacterCount { return .shouldShow } else { return .shouldHide } } func validatePassword(_ password: String) -> PasswordValidity { guard password.count >= passwordMinimumCharacterCount else { return .invalid } return .valid } } extension SignupCreatePasswordViewModel { func instantiateSelectCountryViewModel() -> SignupSelectCountryViewModel { SignupSelectCountryViewModel(usernameSubject: input.usernameSubject, passwordSubject: passwordSubject) } }
true
935c70c952e3f785f2d136b72df68e95f1601790
Swift
eoinlavery/ios-sprint-challenge-my-movies
/MyMovies/View Controllers/MyMoviesTableViewController.swift
UTF-8
4,666
2.765625
3
[]
no_license
// // MyMoviesTableViewController.swift // MyMovies // // Created by Spencer Curtis on 8/17/18. // Copyright © 2018 Lambda School. All rights reserved. // import UIKit import CoreData class MyMoviesTableViewController: UITableViewController, MovieTableViewCellDelegate { func watchedStatusChanged(for cell: MovieTableViewCell) { guard let movie = cell.movie else { return } } override func viewDidLoad() { super.viewDidLoad() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return fetchedResultsController.sections?.count ?? 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fetchedResultsController.sections?[section].numberOfObjects ?? 0 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let section = fetchedResultsController.sections?[section] if section?.name == "0" { return "Not Watched" } else { return "Seen" } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as? MovieTableViewCell else { return UITableViewCell() } cell.delegate = self cell.movie = fetchedResultsController.object(at: indexPath) return cell } // MARK: - 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. } //NSFetchedResultsController lazy var fetchedResultsController: NSFetchedResultsController<Movie> = { let fr: NSFetchRequest<Movie> = Movie.fetchRequest() fr.sortDescriptors = [NSSortDescriptor(key: "hasWatched", ascending: true), NSSortDescriptor(key: "title", ascending: true)] let moc = CoreDataStack.shared.mainContext let frc = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: moc, sectionNameKeyPath: "hasWatched", cacheName: nil) frc.delegate = self do { try frc.performFetch() } catch { NSLog("Unable to fetch Movies from mainContext.") } return frc }() } extension MyMoviesTableViewController: NSFetchedResultsControllerDelegate { // MARK: - NSFetchedResultsControllerDelegate func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.beginUpdates() } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.endUpdates() } // Sections func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: tableView.insertSections(IndexSet(integer: sectionIndex), with: .automatic) case .delete: tableView.deleteSections(IndexSet(integer: sectionIndex), with: .automatic) default: break } } // Rows func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: guard let newIndexPath = newIndexPath else { return } tableView.insertRows(at: [newIndexPath], with: .automatic) case .update: guard let indexPath = indexPath else { return } tableView.reloadRows(at: [indexPath], with: .automatic) case .move: guard let oldIndexPath = indexPath, let newIndexPath = newIndexPath else { return } tableView.deleteRows(at: [oldIndexPath], with: .automatic) tableView.insertRows(at: [newIndexPath], with: .automatic) case .delete: guard let indexPath = indexPath else { return } tableView.deleteRows(at: [indexPath], with: .automatic) default: break } } }
true
2439ca8e3cb410f7b5b3f8933a9cd3fcb9a03cfd
Swift
alexbtlv/pictures
/pic2/Extensions/StringExtensions.swift
UTF-8
895
2.8125
3
[]
no_license
// // StringExtensions.swift // pic2 // // Created by Alexander Batalov on 9/2/19. // Copyright © 2019 Alexander Batalov. All rights reserved. // extension String { func isValidEmail() -> Bool { if self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || self.count > Constants.maximumEmailLength { return false } do { // swiftlint:disable line_length let pattern = "^[a-zA-Z0-9]{1,}+((\\.|\\_|\\+|-{0,1})[a-zA-Z0-9]{1,})*+@[a-zA-Z0-9а-яА-Я]{1,}((\\.|\\_|-{0,1})[a-zA-Z0-9а-яА-Я]{1,})*\\.[a-zA-Zа-яА-Я]{2,64}$" let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive) let range = regex.rangeOfFirstMatch(in: self, options: .anchored, range: NSRange(location: 0, length: count)) return range.length == count } catch { return false } } }
true
222f5e0b9d3338c27e4c2fe81dbe8348c3f7d4ef
Swift
ichen014/ImaginaryAnimalsLister2
/ImaginaryAnimalsLister/URLImageView.swift
UTF-8
1,746
2.96875
3
[]
no_license
// // URLImageView.swift // ImaginaryAnimalsLister // // Created by Brian Freese on 9/17/15. // Copyright © 2015 MathNotRequired. All rights reserved. // import UIKit class LoadingImageOperation : NSOperation { var animal : ImaginaryAnimal? var animalImageView : URLImageView? var url : NSURL? init(imaginaryAnimal: ImaginaryAnimal, animalImageView: URLImageView) { self.animal = imaginaryAnimal self.animalImageView = animalImageView } init(url: NSURL) { self.url = url super.init() self.qualityOfService = .UserInitiated } override func main() { if let url = self.animal?.imageURL, let imageData = NSData(contentsOfURL: url) { NSOperationQueue.mainQueue().addOperationWithBlock() { self.animalImageView?.image = UIImage(data: imageData) } } if let url = self.url, let imageData = NSData(contentsOfURL: url) { NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in self.animalImageView?.image = UIImage(data: imageData) }) } } } class URLImageView: UIImageView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ var url:NSURL? { didSet { if let url = self.url { let loadOp = LoadingImageOperation(url: url) loadOp.animalImageView = self NSOperationQueue().addOperation(loadOp) } } } }
true
fd35cb4466f70e455f9c02e4ee6beec9663de659
Swift
godemodegame/RostelecomAuto
/RostelecomAuto/Modules/TabBarView.swift
UTF-8
570
2.5625
3
[]
no_license
import SwiftUI struct TabBar: View { var body: some View { TabView { MapView(request: .nearMe) .tabItem { Image(systemName: "map.fill") Text("Map") } SiriView() .tabItem { Image(systemName: "gear") Text("Preferences") } } } } struct TabBarView_Previews: PreviewProvider { static var previews: some View { TabBar() .preferredColorScheme(.dark) } }
true
6990b0ee0e40d73e6ae9c26766fc9a4eb20ab3f2
Swift
mohamed930/Map
/Map/Networking/checkCredentials/checkCredentialsAPI.swift
UTF-8
774
2.84375
3
[]
no_license
// // checkCredentialsAPI.swift // Map // // Created by Mohamed Ali on 11/26/20. // import Foundation protocol checkCredentialsProtocol { func login(name: String , password: String , deviceToken: String,completion: @escaping (Result<checkCredentialsResponse?,NSError>) -> Void) } class checkCredentialsAPI: BaseAPI<checkCredentialsNetworking> , checkCredentialsProtocol { func login(name: String , password: String , deviceToken: String,completion: @escaping (Result<checkCredentialsResponse?,NSError>) -> Void) { self.fetchData(Target: .Log_in_as_Supervisor(name: name, password: password, deviceToken: deviceToken), ClassName: checkCredentialsResponse.self) { (response) in completion(response) } } }
true
4878fce48ec049a7bfe5fce6dc569983ac577d3b
Swift
hao44le/MakeSchool2016Projects
/Swift-Language-Playgrounds-master/Swift-Intro.playground/Pages/P06-Dictionaries.xcplaygroundpage/Contents.swift
UTF-8
3,377
4.96875
5
[]
no_license
/*: # Dictionaries Dictionary is a collection type that can store multiple values, and each value has a unique key associated with it. (If you know Python, you may be familiar with Python dictionaries; in Java these are called HashMaps.) Unlike arrays, dictionaries are _unordered_, which means they do not keep the values in any particular order. Dictionaries are helpful in situations where you want to quickly look up a value based on its unique key. ## Instantiation Let's jump right in and define a dictionary variable. */ var cities: [String: String] = ["New York City": "USA", "Paris": "France", "London": "UK"] /*: As you can see, the type of a dictionary depends on both the type of its key and the type of its value. The syntax to declare a dictionary type is `[<key type>: <value type>]`. In the example above, the key and the value are both `String`. In this case, the key is the name of a city, and the value is the country that the city is in. Just like arrays, the type of the dictionary can be inferred, so the `[String : String]` part is not strictly necessary. Also like arrays, you can both instantiate and place items in a dictionary using a literal, in this case a _dictionary literal_, which you can see on the right-hand side of the expression. As you can see, place a colon `:` between each key and its corresponding value, and use a comma `,` to separate each key-value pair. */ /*: ## Examine the Dictionary To count the number of key-value pairs, you can use the `count` property just like arrays. `isEmpty` works as well. */ print("The dictionary contains \(cities.count) items.") /*: */ /*: ## Using the Dictionary You can add a new key-value pair like this: */ cities["San Francisco"] = "USA" /*: It's similar to putting a value in an array, except instead of putting the index number inside the brackets, you put the key. You can also the change the value that a key is associated with in the same manner: */ cities["San Francisco"] = "United States of America" /*: When trying to retrieve a value for a key, there is a possibility that key-value pair does not exist, so you have to make sure you check for this case. As a result, it is best to use optional binding to retrieve a value from the dictionary: */ if let country = cities["London"] { print("London is in \(country).") } else { print("The dictionary does not contain London as a key.") } /*: You can remove a key-value pair simply by setting the key's value to nil: */ cities["London"] = nil print(cities) //does not contain "London" anymore /*: To empty the dictionary: */ cities = [:] //: - note: `[:]` is the literal for empty dictionary, it can't be `[]` because that means empty array /*: To define a new empty dictionary: */ var dictionary = [String: Int]() // or var anotherDictionary: [String: Int] = [:] /*: Notice how the type of the values is Int. The value type can be any type you want. The key can also be any type you want. However, the key has to conform to the _hashable_ protocol. This has to do with how the dictionary actually works beneath the hood, but that's out of the scope of this tutorial. All the Swift basic types work as a key, and there are rarely any situations that you will need a custom type to be the key anyway. */ /*: [Previous](@previous) | [Table of Contents](P00-Table-of-Contents) | [Next](@next) */
true
7030542ea467a5714fe658237fa14692ad518de4
Swift
Jxrgxn/Birdbrain
/BirdbrainTests/BirdbrainMathTest.swift
UTF-8
2,729
2.828125
3
[ "MIT" ]
permissive
// // BirdbrainMathTest.swift // Birdbrain // // Created by Jorden Hill on 11/25/15. // Copyright © 2015 Jorden Hill. All rights reserved. // import XCTest import Foundation import Birdbrain //Test primary functions in Math.swift class BirdbrainMathTest: XCTestCase { let testVector1: [Float] = [1.0, 2.0] let testVector2: [Float] = [3.0, 4.0] let testMatrix1: [Float] = [1.0, 2.0, 3.0, 4.0] let testMatrix2: [Float] = [1.0, 2.0, 3.0, 4.0] func testVectorSum() { XCTAssertEqual(sum(testVector1), 3.0, "Wrong vector sum") } func testVectorAddition() { XCTAssertTrue(add(testVector1, y: testVector2) == [4.0, 6.0], "Wrong vector + vector result") } func testVectorSubtraction() { XCTAssertTrue(sub(testVector1, y: testVector2) == [-2.0, -2.0], "Wrong vector - vector result") } func testScalarAddition() { XCTAssertTrue(add(testVector1, c: 1.0) == [2.0, 3.0], "Wrong scalar vector addition result") } func testScalarMultiplication() { XCTAssertTrue(mul(testVector1, c: 2.0) == [2.0, 4.0], "Wrong scalar vector multiplication result") } func testVectorVectorMultiplication() { XCTAssertTrue(mul(testVector1, y: testVector2) == [3.0, 8.0], "Wrong vector-vector multiplication result") } func testVectorMatricMultiplication() { XCTAssertTrue(mvMul(testMatrix1, m: 2, n: 2, x: testVector1) == [5, 11], "Wrong vector matrix multiplication result") } func testVectorVectorDivision() { XCTAssertTrue(div(testVector2, y: testVector1) == [3.0, 2.0], "Wrong vector vector division result") } func testExponentiation() { XCTAssertTrue(exp(testVector1) == [exp(1.0), exp(2.0)], "Wrong elementwise exponentiation result") } func testHyperbolicTangent() { XCTAssertTrue(tanh(testVector1) == [tanhf(1.0), tanhf(2.0)], "Wrong elementwise hyperbolic tangent result") } func testSquare() { XCTAssertTrue(square(testVector1) == [powf(1.0, 2.0), powf(2.0, 2.0)], "Wrong elementwise square result") } func testNegation() { XCTAssertTrue(neg(testVector1) == [-1.0, -2.0], "Wrong elementwise negation result") } func testMatrixFormation() { XCTAssertTrue(outer(testMatrix1, y: testMatrix2) == [1.0, 2.0, 3.0, 4.0, 2.0, 4.0, 6.0, 8.0, 3.0, 6.0, 9.0, 12.0, 4.0, 8.0, 12.0, 16.0], "Wrong matrix formation result") } }
true
67de96655c5493124cabd61314711cad8bd70df5
Swift
alienintheheights/FoodTrackerWithCoreData
/FoodTracker/Meal.swift
UTF-8
413
2.578125
3
[]
no_license
// // Meal.swift // FoodTracker // // Created by .a. on 1/8/16. // Copyright © 2016 Thinking Dog. All rights reserved. // import Foundation import CoreData import UIKit @objc(Meal) class Meal: NSManagedObject { @NSManaged var name: String! @NSManaged var photo: UIImage? @NSManaged var rating: NSNumber override var description: String { return "name: \(name)" + "rating: \(rating)" } }
true
ed97ddc551f7340e9323067ef94fc0a8738dec88
Swift
ashwinp-r/RippleAnimation
/Demo/Demo/ViewController.swift
UTF-8
2,197
2.828125
3
[ "MIT" ]
permissive
// // ViewController.swift // Demo // // Created by Motoki on 2015/12/22. // Copyright (c) 2015 MotokiNarita. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: properties let colors = [ OriginalCell.CellInfo(color: UIColor.alizarin(), clipsToBouds: false), OriginalCell.CellInfo(color: UIColor.carrot(), clipsToBouds: true), OriginalCell.CellInfo(color: UIColor.sunflower(), clipsToBouds: false), OriginalCell.CellInfo(color: UIColor.turquoize(), clipsToBouds: true), OriginalCell.CellInfo(color: UIColor.river(), clipsToBouds: false), OriginalCell.CellInfo(color: UIColor.amethyst(), clipsToBouds: true) ] @IBOutlet weak var tableView: UITableView! // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Action @IBAction func tapped(_ sender: UIButton) { // !!!: example for ripple animation for UIView let config = UIView.RippleConfiguration(color: UIColor.alizarin()) sender.rippleAnimate(with: config, completionHandler: { print("ripple!!") }) } } extension ViewController: UITableViewDataSource, UITableViewDelegate { // MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return colors.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? OriginalCell else { fatalError() } cell.configure(colors[indexPath.row]) return cell } // MARK: UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } }
true
4847d9ca35c85ce35ee0cdbe9bf7dc66da36ae73
Swift
marksLiang/LKKJ
/ProjectFramework/Common/Extension/UIButton+Creation.swift
UTF-8
1,488
2.8125
3
[]
no_license
// // UIButton+Creation.swift // LKKJ // // Created by Jinjun liang on 2017/11/9. // Copyright © 2017年 HCY. All rights reserved. // import UIKit extension UIButton { /// 创建文本按钮 /// /// - Parameters: /// - title: 标题文字 /// - fontSize: 字体大小 /// - normalColor: 默认字体颜色 /// - heightlightedColor: 高亮字体颜色 /// - Returns: 实例 class func lk_textButton(title: String, fontSize: CGFloat, normalColor: UIColor, heightlightedColor: UIColor) -> UIButton { let button = UIButton() button.setTitle(title, for: .normal) button.setTitleColor(normalColor, for: .normal) button.setTitleColor(heightlightedColor, for: .highlighted) return button } /// 创建文本按钮 /// /// - Parameters: /// - title: 标题文字 /// - fontSize: 字体大小 /// - normalColor: 默认字体颜色 /// - heightlightedColor: 高亮字体颜色 /// - backgrounImageName: 背景图片 /// - Returns: 实例 class func lk_textButton(_ title: String, fontSize: CGFloat, normalColor: UIColor, heightlightedColor: UIColor, backgrounImageName: String) -> UIButton { let button = UIButton.lk_textButton(title: title, fontSize: fontSize, normalColor: normalColor, heightlightedColor: heightlightedColor) button.setBackgroundImage(UIImage(named: backgrounImageName), for: .normal) return button } }
true
113163b01bd715ad8d20a180f41d2ce9e24f3d85
Swift
stillotherguy/swiftinaction
/Foundation/Foundation/Array.playground/section-1.swift
UTF-8
623
3.515625
4
[]
no_license
// Playground - noun: a place where people can play import UIKit let array:[Int] = [1,2,3,4] let nsarray:NSArray = array; let swiftarray:[Int] = array as [Int] println(array.count) let array1:[AnyObject] = [1,2,3,4,"5"] //error //array1 as [Int] var array2 = [1,2,3,4] var mutableArray = NSMutableArray(array: array2) mutableArray.removeLastObject() println(mutableArray) array2[0...2] array2[0..<2] let range = NSRange(location: 1, length: 2) let indexSet = NSIndexSet(indexesInRange: range) println(nsarray.objectsAtIndexes(indexSet)) nsarray.containsObject("5") contains(array, {$0 == 1}) find(array, 1)
true
24df033924e84dd644c2592c991b2229c7f04e67
Swift
gubraun/lucaapp
/Luca/Services/Backend/V2/Requests/Misc/FetchScannerAsyncOperation.swift
UTF-8
717
2.578125
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import Foundation enum FetchScannerError: RequestError { case notFound } extension FetchScannerError { var errorDescription: String? { return "\(self)" } var localizedTitle: String { return L10n.Navigation.Basic.error } } class FetchScannerAsyncOperation: BackendAsyncDataOperation<KeyValueParameters, ScannerInfo, FetchScannerError> { init(backendAddress: BackendAddress, scannerId: String) { let fullUrl = backendAddress.apiUrl .appendingPathComponent("scanners") .appendingPathComponent(scannerId.lowercased()) super.init(url: fullUrl, method: .get, errorMappings: [404: .notFound]) } }
true
3749e3a7745d4c97a45dc3e80e375e7c88f2e12b
Swift
krugazor/TermPlot
/Tests/TermPlotTests/TermPlotTests.swift
UTF-8
6,741
2.71875
3
[ "MIT" ]
permissive
import XCTest import LoremSwiftum @testable import TermPlot #if os(macOS) import AppKit #elseif os(iOS) import UIKit #endif final class TermPlotTests: XCTestCase { func testColors() { for s in TermStyle.allCases { for c in TermColor.allCases { print("This is a test \(s.rawValue)-\(c.rawValue)".apply(c,style: s)) } } } func testCharacters() { for s in DisplayStyle.allCases { for c in DisplaySymbol.allCases { print(c.withStyle(s)) } } } func testUtils() { print("This test is highly unreliable...") #if os(macOS) let (c,r) = TermSize() print("\(c) cols x \(r) rows") #endif let (c2,r2) = TermSize2() print("\(c2) cols x \(r2) rows") print("10s of listening to size changes...") TermHandler.shared.windowResizedAction = { print("\($0.cols) cols x \($0.rows) rows") } for _ in 1...10 { RunLoop.current.run(until: Date(timeIntervalSinceNow: 1)) } } func testCursors() { print("testing left") TermHandler.shared.set(TermColor.light_red, styles: [.swap, .hide]) for _ in 0..<10 { TermHandler.shared.put(s: "@") } TermHandler.shared.moveCursorLeft(5) TermHandler.shared.set(TermColor.blue, styles: [.swap, .hide]) for _ in 0..<5 { TermHandler.shared.put(s: "@") } TermHandler.shared.set(TermColor.default, style: .default) TermHandler.shared.put(s: "\n") print("testing right") TermHandler.shared.moveCursorRight(5) TermHandler.shared.set(TermColor.blue, styles: [.swap, .hide]) for _ in 0..<5 { TermHandler.shared.put(s: "@") } TermHandler.shared.set(TermColor.default, style: .default) TermHandler.shared.put(s: "\n") print("testing up") TermHandler.shared.set(TermColor.red, styles: [.swap, .hide]) for _ in 0..<10 { TermHandler.shared.put(s: "@@@@@@@@@@\n") } TermHandler.shared.moveCursorUp(5) TermHandler.shared.set(TermColor.blue, styles: [.swap, .hide]) for _ in 0..<5 { TermHandler.shared.put(s: "@@@@@@@@@@\n") } TermHandler.shared.set(TermColor.default, style: .default) TermHandler.shared.put(s: "\n") print("testing down") TermHandler.shared.set(TermColor.red, styles: [.swap, .hide]) for _ in 0..<10 { TermHandler.shared.put(s: "@@@@@@@@@@\n") } TermHandler.shared.moveCursorUp(10) TermHandler.shared.moveCursorDown(5) TermHandler.shared.set(TermColor.blue, styles: [.swap, .hide]) for _ in 0..<5 { TermHandler.shared.put(s: "@@@@@@@@@@\n") } TermHandler.shared.set(TermColor.default, style: .default) TermHandler.shared.put(s: "\n") } func testMapping() { let measures : [(Double,Double)] = [(1.0,5.0), (2.66,8), (4.5,5), (6.33, 6), (8,10)] let ticks : [Double] = [1,2,3,4,5,6,7,8] let mapping = TimeSeriesWindow.mapDomains(measures, to: ticks) print(mapping) } func testMulti() { var v1 = 1 let series1 = TimeSeriesWindow(tick: 0.25, total: 8) { v1 += 1 v1 = v1 % 10 let random = Int.random(in: 0...v1) return Double(random) } series1.seriesColor = .monochrome(.light_cyan) var v2 = 1 let series2 = TimeSeriesWindow(tick: 0.25, total: 8) { v2 += 1 v2 = v1 % 10 let random = Int.random(in: 0...v2) return Double(random) } series2.seriesColor = .monochrome(.light_cyan) guard let multi = try? TermMultiWindow(stack: .vertical, ratios: [0.5,0.5], series1,series2) else { XCTFail() ; return } multi.start() RunLoop.current.run(until: Date(timeIntervalSinceNow: 60)) } #if os(macOS) func testWebText() { if let data = try? Data(contentsOf: URL(string: "https://blog.krugazor.eu/2018/08/31/we-suck-as-an-industry/")!), let html = NSAttributedString(html: data, baseURL: URL(string: "https://blog.krugazor.eu/2018/08/31/we-suck-as-an-industry/")!, documentAttributes: nil) { let lines = underestimatedLines(mapAttributes(html)) XCTAssert(lines > 0) let buffer = fit(mapAttributes(html), in: 80, lines: 47) XCTAssert(buffer.count > 0) debugTermPrint(buffer) let txtW = TextWindow() txtW.add(html) RunLoop.current.run(until: Date(timeIntervalSinceNow: 10)) } else { XCTFail() } } #elseif os(iOS) func testWebText() { do { let data = try Data(contentsOf: URL(string: "https://blog.krugazor.eu/2018/08/31/we-suck-as-an-industry/")!) let html = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .defaultAttributes: [ NSAttributedString.Key("NSColor") : UIColor.clear ] ], documentAttributes: nil) let lines = underestimatedLines(mapAttributes(html)) XCTAssert(lines > 0) let buffer = fit(mapAttributes(html), in: 80, lines: 47) XCTAssert(buffer.count > 0) debugTermPrint(buffer) } catch { XCTFail(error.localizedDescription) } } #endif func testText() { let str = generateAttributedString(minLength: 8000) let lines = underestimatedLines(mapAttributes(str)) XCTAssert(lines > 0) let splitted = toLines(mapAttributes(str), in: 80) XCTAssert(splitted.count > 0) let buffer = fit(mapAttributes(str), in: 80, lines: 47) XCTAssert(buffer.count > 0) debugTermPrint(buffer) let txtW = TextWindow() txtW.add(str) txtW.newline() txtW.add(Lorem.sentence) RunLoop.current.run(until: Date(timeIntervalSinceNow: 10)) } static var allTests = [ ("testColors", testColors), ("testCharacters", testCharacters), ("testUtils", testUtils), ("testMulti", testMulti), ] }
true
e0808bbb375531c754fa0408f906975682d7157a
Swift
prestonprice57/knotz
/knotz/Connector.swift
UTF-8
547
2.671875
3
[]
no_license
// // Connector.swift // BrickBreak // // Created by Preston Price on 1/3/16. // Copyright © 2016 prestonwprice. All rights reserved. // import Foundation import SpriteKit class Connector: NSObject { var circle: SKShapeNode var circleTouchArea: SKShapeNode var lineIn: Line var lineOut: Line init(circle: SKShapeNode, circleTouchArea: SKShapeNode, lineIn: Line, lineOut: Line) { self.circle = circle self.circleTouchArea = circleTouchArea self.lineIn = lineIn self.lineOut = lineOut } }
true
e845645b4c0f49f10d9eb4dba142a39c9df5f4e8
Swift
TRS-CODER/NXZZQ
/RX宁夏/Common/Extension/UIWidget+Extension.swift
UTF-8
5,955
2.75
3
[]
no_license
// // UIWidget+Extension.swift // ENJOY // // Created by yudai on 2018/1/10. // Copyright © 2018年 拓尔思. All rights reserved. // import UIKit // MARK: - UILabel Extensions extension UILabel { /// 遍历构造函数扩充1 /// /// - Parameters: /// - frame: label的frame /// - title: lable的文字 /// - color: label的字体颜色 /// - fontSize: label的字体 convenience init(_ frame: CGRect, _ title: String, _ color: UIColor, _ fontSize: CGFloat) { self.init() self.frame = frame text = title textColor = color font = UIFont.systemFont(ofSize: fontSize) } /// 根据字符串 获取lable的宽度 /// /// - Parameters: /// - labelStr: 需要计算宽度的NSString /// - font: label的字体大小 /// - height: label指定的最大高度 /// - Returns: label的宽度 class func getLabelWidth(_ labelStr: String,_ fontSize: CGFloat,_ height: CGFloat) -> CGFloat { let statusLabelText: NSString = labelStr as NSString let size = CGSize(width: 999, height: height) let font = UIFont.systemFont(ofSize: fontSize) let dict = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying) let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dict as? [NSAttributedStringKey : Any], context: nil).size return strSize.width } /// 根据字符串 获取lable的高度 /// /// - Parameters: /// - labelStr: 需要计算高度的NSString /// - font: label的字体大小 /// - width: label的指定最大宽度 /// - Returns: lable的高度 class func getLabelHeight(_ labelStr: String, _ fontSize: CGFloat, _ width: CGFloat) -> CGFloat { let statusLabelText: NSString = labelStr as NSString let size = CGSize(width: width, height: 999) let font = UIFont.systemFont(ofSize: fontSize) let dict = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying) let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dict as? [NSAttributedStringKey : Any], context: nil).size return strSize.height } /// 限定最多行数返回高度 /// /// - Parameters: /// - labelStr: 需要计算高度的NSString /// - font: label的字体大小 /// - width: label的宽度 /// - maxRows: 标签最大行数(默认Int.max) /// - Returns: lable的高度 class func getLabelHeight(_ labelStr: String, _ fontSize: CGFloat, _ width: CGFloat, _ maxRows: Int = Int.max) -> CGFloat { let statusLabelText: NSString = labelStr as NSString let size = CGSize(width: width, height: CGFloat(MAXFLOAT)) let font = UIFont.systemFont(ofSize: fontSize) let dict = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying) let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dict as? [NSAttributedStringKey : Any], context: nil).size let maxH = UILabel.getLabelHeight("1", fontSize, width) * CGFloat(maxRows) return min(strSize.height, maxH) } } // MARK: - UIButton Extensions extension UIButton { /// 便利构造函数扩充1 /// /// - Parameters: /// - title: 按钮的文字 /// - titleColor: 按钮的颜色 /// - fontSize: 按钮文字的字体 convenience init(title : String, titleColor : UIColor, fontSize : CGFloat) { self.init() setTitle(title, for: .normal) setTitleColor(titleColor, for: .normal) titleLabel?.font = UIFont.systemFont(ofSize: fontSize) } /// 便利构造函数扩充2 /// /// - Parameters: /// - title: 按钮的文字 /// - norColor: 普通状态的文字颜色 /// - selColr: 选中状态的文字颜色 /// - bgColor: 按钮的背景颜色 /// - fontSize: 按钮文字的字体 convenience init(title : String, norColor : UIColor, selColr: UIColor, bgColor : UIColor, fontSize : CGFloat) { self.init() setTitle(title, for: .normal) setTitleColor(norColor, for: .normal) setTitleColor(selColr, for: .selected) backgroundColor = bgColor titleLabel?.font = UIFont.systemFont(ofSize: fontSize) } /// 便利构造函数扩充3 /// /// - Parameters: /// - norImage: 按钮普通状态的图片 /// - selImage: 按钮选中状态的图片 convenience init(norImage: String, selImage:String) { self.init() setImage(UIImage(named:norImage), for: .normal) setImage(UIImage(named:selImage), for: .selected) } /// 遍历构造函数扩充4 /// /// - Parameters: /// - img: 普通状态图片 /// - title: 标题 /// - fontSize: 字体大小 convenience init(img : String, title : String , fontSize : CGFloat) { self.init() setImage(UIImage(named:img), for: .normal) setTitle(title, for: .normal) titleLabel?.font = UIFont.systemFont(ofSize: fontSize) } } // MARK: UIFont Extensions extension UIFont { /// 获得某个字体的高度 /// /// - Parameter CGFloat: 字体大小 /// - Returns: 对应高度 class func getFontH(fontSize CGFloat: CGFloat) -> CGFloat { let statusLabelText: NSString = "" as NSString let size = CGSize(width: 1, height: 999) let font = UIFont.systemFont(ofSize: CGFloat) let dict = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying) let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dict as? [NSAttributedStringKey : Any], context: nil).size return strSize.height } }
true
bf7da104b30081e9067fd19f2b29922ea7f02ccf
Swift
MrCcccC/HappyTime
/休闲一刻/ConsView.swift
UTF-8
1,318
2.671875
3
[]
no_license
// // ConsView.swift // 每日一乐 // // Created by 5201-mac on 2017/4/13. // Copyright © 2017年 5201-mac. All rights reserved. // import UIKit class ConsView: UIView { override init(frame:CGRect){ super.init(frame: frame) setupUI() } lazy var ConsLabel = UILabel(withText: "星座名", fontsize: 16, color: UIColor.darkGray) lazy var DateLabel = UILabel(withText: "日期", fontsize: 16, color: UIColor.darkGray) lazy var ConsButton = UIButton(title: "请选择", fontSize: 16, normalColor: UIColor.darkGray, highlightedColor: UIColor.darkGray, backgroundImageName: "button") lazy var DateButton = UIButton(title: "请选择", fontSize: 16, normalColor: UIColor.darkGray, highlightedColor: UIColor.darkGray, backgroundImageName: "button") required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ addSubview(ConsLabel) addSubview(DateLabel) addSubview(ConsButton) addSubview(DateButton) for v in subviews{ v.translatesAutoresizingMaskIntoConstraints = false //自动布局 //imageview } } }
true
0d3183132b51207d69de0d9e85a8627ff919aff5
Swift
d0ping/Points
/Source/Services/API/APIEndpoint.swift
UTF-8
1,397
3
3
[]
no_license
// // APIEndpoint.swift // Points // // Created by Denis Bogatyrev on 24/09/2019. // Copyright © 2019 Denis Bogatyrev. All rights reserved. // import Foundation struct APIEndpoint { private let config = APIConfiguration() let path: String let queryItems: [URLQueryItem] } extension APIEndpoint { var url: URL? { var components = URLComponents() components.scheme = config.scheme components.host = config.baseHost components.path = path components.queryItems = queryItems return components.url } } enum PartnersAccountType: String { case credit = "Credit" } extension APIEndpoint { static func depositionPoints(latitude: Double, longitude: Double, radius: Int) -> APIEndpoint { return APIEndpoint( path: "/v1/deposition_points", queryItems: [ URLQueryItem(name: "latitude", value: String(latitude)), URLQueryItem(name: "longitude", value: String(longitude)), URLQueryItem(name: "radius", value: String(radius)) ] ) } static func depositionPartners(accountType: PartnersAccountType) -> APIEndpoint { return APIEndpoint( path: "/v1/deposition_partners", queryItems: [ URLQueryItem(name: "accountType", value: String(accountType.rawValue)) ] ) } }
true
959f8aeb5b429924e89a30023cd3d6b2eff88066
Swift
IrenaChou/IRDouYuZB
/videoMusic/IRVideoCapture-视频采集/IRVideoCapture/ViewController.swift
UTF-8
6,681
2.578125
3
[ "MIT" ]
permissive
// // ViewController.swift // IRVideoCapture // // Created by zhongdai on 2017/1/23. // Copyright © 2017年 ir. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { // 视频输出队列 fileprivate lazy var videoQueue = DispatchQueue.global() //音频输出队列 fileprivate lazy var audioQueue = DispatchQueue.global() // 1.创建捕捉会话【一个session中可以添加多个Input】 fileprivate lazy var session : AVCaptureSession = AVCaptureSession() // 4.给用户看到一个预览图层【可选】 fileprivate lazy var previewLayer : AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session); fileprivate var videoOutput : AVCaptureVideoDataOutput? fileprivate var videoInput : AVCaptureDeviceInput? fileprivate var movieOutPut : AVCaptureMovieFileOutput? } // MARK: - 视频采集 extension ViewController{ /// 开始采集 @IBAction func starCapture(_ sender: Any) { //设置视频的输入&输出 setupVideo() //设置音频的输入&输出 setupAudio() // 3. 添加写入文件的output let movieOutput = AVCaptureMovieFileOutput() self.movieOutPut = movieOutput session.addOutput(movieOutput) // 3.1 设置写入的稳定性 let connection = movieOutput.connection(withMediaType: AVMediaTypeVideo) connection?.preferredVideoStabilizationMode = .auto // 4.给用户看到一个预览图层【可选】 previewLayer.frame = view.bounds view.layer.insertSublayer(previewLayer, at: 0) // 5.开始采集 session.startRunning() // 6.开始将采集到的文件写入到文件中 let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/abc.mp4" let url = URL(fileURLWithPath: path) movieOutput.startRecording(toOutputFileURL: url, recordingDelegate: self) } /// 停止采集 @IBAction func stopCapture(_ sender: Any) { //结束写入文件 self.movieOutPut?.stopRecording() session.stopRunning() previewLayer.removeFromSuperlayer() } /// 切的前后摄像头 @IBAction func switchScene(){ // 1. 获取之前的镜头 guard var position = videoInput?.device.position else { return } // 2. 获取当前应该显示的镜头 position = position == .front ? .back : .front // 3. 根据当前镜头创建新的Device let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as? [AVCaptureDevice] guard let device = devices?.filter({ $0.position == position }).first else { return } // 4. 根据新的Device创建Input guard let newVideoInput = try? AVCaptureDeviceInput(device: device) else { return } // 5. 在session中切的input session.beginConfiguration() session.removeInput(self.videoInput) session.addInput(newVideoInput) session.commitConfiguration() self.videoInput = newVideoInput } } extension ViewController{ fileprivate func setupVideo(){ // 2. 给捕捉会话设置输入源【摄像头】 // 2.1 获取摄像头设备【前后都包含】 guard let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as? [AVCaptureDevice] else { print("摄像头不可用") return } // let device = devices.filter { ( device : AVCaptureDevice) -> Bool in // return device.position == .front // }.first // 2.2 通过$0取出第一个属性【前置摄像头 】 guard let device = devices.filter({ $0.position == .front }).first else { return } // 2.3 通过device创建AVCaptureInput对象 guard let videoInput = try? AVCaptureDeviceInput(device: device) else { return } self.videoInput = videoInput // 2.4 将input添加到会话中 session.addInput(videoInput) // 3.给捕捉会话设置输出源 let videoOutput = AVCaptureVideoDataOutput() videoOutput.setSampleBufferDelegate(self, queue: videoQueue) session.addOutput(videoOutput) // self.videoOutput = videoOutput // 获取video对象的connection // let connection = videoOutput.connection(withMediaType: AVMediaTypeVideo) self.videoOutput = videoOutput } fileprivate func setupAudio(){ // 1.设置音频的输入【话筒】 // 1.1获取话筒设备 guard let device = AVCaptureDevice.devices(withMediaType: AVMediaTypeAudio).first as? AVCaptureDevice else { return } // 1.2 根据device创建AVCaptureInput guard let audioInpu = try? AVCaptureDeviceInput(device: device ) else { return } // 1.3 将Input添加到会话中 session.addInput(audioInpu) // 2.给会话设置音频的输出源 let audioOutput = AVCaptureAudioDataOutput() audioOutput.setSampleBufferDelegate(self, queue: audioQueue) session.addOutput(audioOutput) } } // MARK: - 【遵守视频代理协议】获取数据 extension ViewController : AVCaptureVideoDataOutputSampleBufferDelegate,AVCaptureAudioDataOutputSampleBufferDelegate { /// 采集到的每一帧数据 /// /// - Parameters: /// - sampleBuffer: 存储采集到的所有帧数据【需要美颜和编码处理就是对他进行处理】 func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) { if connection == self.videoOutput?.connection(withMediaType: AVMediaTypeVideo) { print("+++++采集到视频画面") }else{ print("~~~~~采集到音频画面") } } } // MARK: - 写入文件协议 extension ViewController : AVCaptureFileOutputRecordingDelegate{ func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) { print("开始写入文件") } func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) { print("结束写入文件") } }
true
fe8eb2d697e4995d9fb2ee89f68b519815f1ca1e
Swift
Jef-in/GoodWeather
/Good Weather/Good Weather/Controllers/WeatherDetailsViewController.swift
UTF-8
854
2.671875
3
[]
no_license
// // WeatherDetailsViewController.swift // Good Weather // // Created by Jefin on 17/10/20. // Copyright © 2020 Jefin. All rights reserved. // import Foundation import UIKit class WeatherDetailsViewController : UIViewController { @IBOutlet weak var cityNameLabel : UILabel! @IBOutlet weak var currentTempLabel : UILabel! @IBOutlet weak var maxTempLabel : UILabel! @IBOutlet weak var minTempLabel : UILabel! var weatherViewModel : WeatherViewModel? override func viewDidLoad() { setupVmBinding() } private func setupVmBinding() { if let weatherVM = self.weatherViewModel { weatherVM.name.bind { self.cityNameLabel.text = $0 } weatherVM.currentTemperature.temperature.bind { self.currentTempLabel.text = $0.formatAsDegree} } } }
true
18225c50c3ab05b29488b38ae8820586e58bd3ee
Swift
aminhp93/ios_fundamentals
/fundamental_3.playground/Contents.swift
UTF-8
1,179
4.25
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit // Write a program that adds the numbers 1-255 to an array var result:[Int] = [Int]() for i in 1...255{ result.append(i) } print(result) // Swap two random values in array var index1 = Int(arc4random_uniform(UInt32(result.count))) var index2 = Int(arc4random_uniform(UInt32(result.count))) for i in result{ let temp = result[index1] result[index1] = result[index2] result[index2] = temp } print(result) // Write the code that swaps random vlaues 100 times for i in 1...100{ index1 = Int(arc4random_uniform(UInt32(result.count))) index2 = Int(arc4random_uniform(UInt32(result.count))) let temp = result[index1] result[index1] = result[index2] result[index2] = temp } print(result) // Remove the value "42" from the array and Print "We found the answer to the Ultimate Question of Life, the Univers, adn Everything at index __" and print the index of where "42" was before you removed it. for i in 0...(result.count-1){ if (result[i] == 42){ print("We found the answer to the Ultimate Question of Life, the Univers, adn Everything at index \(i)") } }
true
ad6c0670a443e2a0c16e6fe00e7bd894178bf97e
Swift
ricardoAntolin/demo
/Network/Repositories/PhotosNetworkRepository.swift
UTF-8
573
2.75
3
[]
no_license
// // PhotoNetworkRepository.swift // network // // Created by Ricardo Antolin on 31/01/2019. // Copyright © 2019 Square1. All rights reserved. // import Alamofire public protocol PhotosNetworkRepository: class { var baseUrl: String { get set } } extension PhotosNetworkRepository { public func getPhotos(albumId: Int, completion: @escaping (Result<[NWPhotoEntity]>)->Void){ AF.request("\(baseUrl)/photos/\(albumId)") .responseDecodable { (response: DataResponse<[NWPhotoEntity]>) in completion(response.result) } } }
true
9a39fab32cfc2cb830202d3992ef757f95496c7f
Swift
vladg/weather
/simpleweather/WeatherProvider.swift
UTF-8
3,216
2.9375
3
[]
no_license
// // WeatherProvider.swift // simpleweather // // Created by Vladislav Glabai on 3/25/17. // Copyright © 2017 Vladislav Glabai. All rights reserved. // import Foundation class WeatherProvider { static let instance = WeatherProvider() static let API_KEY = "00d6a04371eea33bc61269fbd760ee1e" static let BASE_URL = "http://api.openweathermap.org/data/2.5/weather?" // HTTP or JSON deserialization error will not be meaningfull to the end user // therefore this method will discard all errors and simply call handler with nil // also, for this sample project we will not model out weather as a class nor // will we do any validation on the received weather info // simply return weather information as NSDictionary func fetchWeatherForLocation(_ location: String, handler: @escaping (NSDictionary?) -> Void) { let escapedLocation = location.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) guard escapedLocation != nil else { DispatchQueue.main.async { handler(nil) } return; } let urlString = WeatherProvider.BASE_URL + "APPID=\(WeatherProvider.API_KEY)" + "&" + "q=\(escapedLocation!)" let url = URL(string: urlString) let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in guard error == nil else { debugPrint(error!); DispatchQueue.main.async { handler(nil) } return; } if let jsonData = data { let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) debugPrint("===>" + jsonString!) do { let json = try JSONSerialization.jsonObject(with: jsonData) if(json is NSDictionary) { debugPrint(json) let code = (json as! NSDictionary)["cod"] as? Int if (code != nil && code == 200) { DispatchQueue.main.async { handler(json as? NSDictionary) } } else { DispatchQueue.main.async { handler(nil) } } } else { // in theory this we probably should also check for JSON array // but for this sample project we don't care about that DispatchQueue.main.async { handler(nil) } } } catch { DispatchQueue.main.async { handler(nil) } } } } task.resume() } class func extractIcon(_ json: NSDictionary) -> String? { let weatherList = json["weather"] as? NSArray let weather = weatherList?[0] as? NSDictionary let icon = weather?["icon"] as? String return icon } class func extractDescription(_ json: NSDictionary) -> String? { let weatherList = json["weather"] as? NSArray let weather = weatherList?[0] as? NSDictionary let description = weather?["description"] as? String return description } class func extractTemp(_ json: NSDictionary) -> String? { let main = json["main"] as? NSDictionary let temp = main?["temp"] as? Double guard temp != nil else { return nil } let tempC = temp! - 273 // Kelvin to Celsius let tempF = ((9 * tempC) / 5) + 32 // Celsius to Fahrenheit let roundedTemp = Double(round(tempF * 10) / 10) // round to one digit after decimal return "\(roundedTemp)°F" } class func extractHumidity(_ json: NSDictionary) -> String? { let main = json["main"] as? NSDictionary let humidity = main?["humidity"] as? Int guard humidity != nil else { return nil } return "\(humidity!)%" } }
true
55a684c7ca5271812bbc40b135aa4be4139f08de
Swift
AZbang/vingoapp
/Vingo/MuseumView/AchievementView.swift
UTF-8
1,990
2.671875
3
[]
no_license
// // AchievementView.swift // Vingo // // Created by Andrey Zhevlakov on 31.07.2020. // import SwiftUI var colors = [Color(#colorLiteral(red: 0.9953433871, green: 0, blue: 0.5229544044, alpha: 1)), Color(#colorLiteral(red: 0.3101347089, green: 0.2808781564, blue: 1, alpha: 1)), Color(#colorLiteral(red: 0.3101347089, green: 0.2808781564, blue: 1, alpha: 1)), Color(#colorLiteral(red: 0.3101347089, green: 0.2808781564, blue: 1, alpha: 1)), Color(#colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1))] struct Achiv: View { public var data: Achievement public var progress: Double var body: some View { ZStack { RoundedRectangle(cornerRadius: data.rx).foregroundColor(colors[Int.random(in: 0..<colors.count)]).opacity(min(0.8, max(0.2, self.progress))) Text(data.icon).font(.system(size: min(data.height-16, data.width-16))).grayscale(1-abs(self.progress-0.01)) } .offset(x: data.x, y: data.y) .frame(width: data.width, height: data.height) .overlay(RoundedRectangle(cornerRadius: data.rx) .strokeBorder(style: StrokeStyle(lineWidth: 4)) .foregroundColor(Color.clear) .offset(x: data.x, y: data.y)) } } struct AchievementView: View { public var achievements: [Achievement] @EnvironmentObject var app: AppStore var body: some View { ScrollView(Axis.Set.horizontal, showsIndicators: false) { ZStack(alignment: .topLeading) { ForEach(achievements) { item in Achiv(data: item, progress: self.app.getAchivProgress(id: item.id)).onTapGesture { self.app.activeStory = item self.app.storyMode = true } } Image("rama").offset(y: 160) } .padding(.horizontal, 20) .frame(width: 1050, height: 280) .offset(x: -10, y: -60) } } }
true
5c11e9f2c0f64d71ccb19135e42538451a873b97
Swift
abstertee/protocols_test
/protocols/StatusTab.swift
UTF-8
1,665
2.90625
3
[]
no_license
// // StatusTab.swift // protocols // // Created by Abraham Tarverdi on 6/5/18. // Copyright © 2018 // import Foundation class StatusTab { func firewallCheck() -> Array<String> { let status = ShellCommand().shell("defaults", "read", "/Library/Preferences/com.apple.alf.plist", "globalstate") //print(status) //sleep(5) if status.contains("1"){ return ["good", "Firewall is enabled"] } else { return ["bad", "Firewall is disabled"] } } } class OSUpdate { func short_osUpdateCheck() -> Array<String> { let updates = ShellCommand().shell("softwareupdate", "-l", "--no-scan") return osUpdateCheck(updates) } func long_osUpdateCheck() -> Array<String> { let updates = ShellCommand().shell("softwareupdate", "-l") return osUpdateCheck(updates) } func osUpdateCheck(_ updates: String) -> Array<String> { var pending = [String]() if updates.contains("Software Update found the following new or updated software:") { let updateArr = updates.components(separatedBy: "\n") for u in updateArr { if u.contains("*") { debugPrint(u) pending.append(u) } } if pending.isEmpty { return ["warning", "Could not collect pending updates list."] } let pendingString = pending.joined(separator: ", ") return ["warning", pendingString] } else { return ["good", "No pending updates"] } } }
true
3f7d35aafac2598e84b05cf11f635fd4b39e6b37
Swift
vincent-coetzee/Argonaut
/Argonaut/System Extensions/Date+Extensions.swift
UTF-8
707
3.125
3
[]
no_license
// // Date+Extensions.swift // Argonaut // // Created by Vincent Coetzee on 31/10/21. // import Foundation extension Date { /// /// /// Generate a ( psuedo ) random date that is in the past. /// /// public static var randomPast:Date { let day = Int.random(in: 1...27) let month = Int.random(in: 1...12) var components = Calendar.current.dateComponents([.year],from: Date()) var year = components.year! let yearDelta = Int.random(in: 0..<20) year -= yearDelta components = DateComponents(year: year,month: month,day: day) let date = Calendar.current.date(from: components)! return(date) } }
true
0d9fa8623a6a085fbc2e327f02e61583d79393fa
Swift
apruth/EarthQuake
/EarthQuake/EarthQuakeViewController.swift
UTF-8
17,625
2.796875
3
[]
no_license
// // EarthQuakeViewController.swift // Assignment2 // // Created by Aaron Ruth on 6/15/15. // Copyright (c) 2015 Aaron Ruth. All rights reserved. // import UIKit import UserNotifications import CoreLocation /** * EarthQuakeViewController - View containing UI components that will display and interact with earthquake data and user. */ class EarthQuakeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { private let earthQuakeDays = 30 private var earthQuakes: [EarthQuake]? private var refreshControl: UIRefreshControl! private let locationNotificationRecuestIdentifier = "LocationRequest" @IBOutlet weak var earthQuakeTable: UITableView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() //remove all previously set location notifications UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [locationNotificationRecuestIdentifier]) //establish tableview refresh control self.refreshControl = UIRefreshControl() self.refreshControl.addTarget(self, action: #selector(EarthQuakeViewController.refreshTable(_:)), for: UIControlEvents.valueChanged) self.earthQuakeTable.addSubview(self.refreshControl) //show activity indicator until data is loaded self.activityIndicator.startAnimating() self.activityIndicator.isHidden = false //load earth quake data self.loadEarthQuakeData() } /** * Action fired when table view is refreshed */ func refreshTable(_ sender: AnyObject) { //reload earthquake data loadEarthQuakeData() DispatchQueue.main.async(execute: {[weak self] in if let strongSelf = self { strongSelf.refreshControl.endRefreshing() } }) } /** * Loads earthquake data through EarthQuakes singleton and updates table view with data */ private func loadEarthQuakeData() { EarthQuakes.sharedInstance.getEarthQuakeData(earthQuakeDays) { [weak self] (inner) -> () in if let strongSelf = self { do { //try to get earthquake data let earthQuakes = try inner() //load table with earthquake data strongSelf.earthQuakes = earthQuakes DispatchQueue.main.async(execute: { _ in strongSelf.activityIndicator.stopAnimating() strongSelf.earthQuakeTable.reloadData() }) } catch let error { //catch exception and present error print("Error occurred - \(error)") DispatchQueue.main.async(execute: { _ in strongSelf.showAlertError() }) } } } } /** * Function used to show an alert view in case an error occurred while retrieving earth quake data */ private func showAlertError() { let alert = UIAlertController(title: "Error", message: "An error occurred while tyring to retreive earth quake data. Press button below to try again", preferredStyle: UIAlertControllerStyle.alert) let action = UIAlertAction(title: "Try Again", style: UIAlertActionStyle.default, handler: { [weak self](alert: UIAlertAction!) -> () in if let strongSelf = self { strongSelf.loadEarthQuakeData() } }) alert.addAction(action) self.present(alert, animated: true, completion: nil) } /**) * UITableView datasource method for returning the number of sections in a table */ func numberOfSections(in tableView: UITableView) -> Int { return EarthQuakeViewController.getSectionTotal(0, earthQuakes: self.earthQuakes, previousComponents: nil) } /** * UITableView datasource method for returning number of rows in a section */ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //construct index path let indexPath = IndexPath(row: 0, section: section) if let earthQuake = EarthQuakeViewController.getEarthQuakeForIndexPath(indexPath, currentRow: 0, currentSection: 0, earthQuakes: self.earthQuakes), let sectionDate = earthQuake.date { let dateComponentsForSection = EarthQuakeViewController.getDateComponentsForDate(sectionDate as Date) return EarthQuakeViewController.getNumberOfRowsForDate(dateComponentsForSection, earthQuakes: self.earthQuakes) } return 0 } /** * UITableView datasource method for building table */ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var tableCell = UITableViewCell() if let earthQuake = EarthQuakeViewController.getEarthQuakeForIndexPath(indexPath, currentRow: 0, currentSection: 0, earthQuakes: self.earthQuakes), let earthQuakeCell = tableView.dequeueReusableCell(withIdentifier: "EarthQuakeTableViewCell") as? EarthQuakeTableViewCell { //set title, longitude, lattitude, and date for cell earthQuakeCell.titleLabel.text = earthQuake.title earthQuakeCell.latlonLabel.text = "Lat: \(earthQuake.lattitude) Lon: \(earthQuake.longitude)" if let earthQuakeDate = earthQuake.date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss" earthQuakeCell.dateLabel.text = dateFormatter.string(from: earthQuakeDate as Date) } let magSevenColor = UIColor(red: CGFloat(255)/255, green: CGFloat(50)/255, blue: CGFloat(30)/255, alpha: 1.0) let magFiveColor = UIColor(red: CGFloat(255)/255, green: CGFloat(145)/255, blue: CGFloat(165)/255, alpha: 1.0) //set background color of cell where appropriate if let magnitude = Int(earthQuake.floorMagnitude) { if magnitude >= 7 { earthQuakeCell.backgroundColor = magSevenColor } else if magnitude >= 5 { earthQuakeCell.backgroundColor = magFiveColor } else { earthQuakeCell.backgroundColor = UIColor.white } } tableCell = earthQuakeCell //set location notification let content = UNMutableNotificationContent() content.title = "EarthQuake!" content.subtitle = "Nearby & Recent Earthquake" content.body = "An earthquake happened here recently." content.sound = UNNotificationSound.default() let lattitude = CLLocationDegrees(earthQuake.lattitude)! let longitude = CLLocationDegrees(earthQuake.longitude)! let center = CLLocationCoordinate2DMake(lattitude, longitude) let region = CLCircularRegion.init(center: center, radius: 2000.0, identifier: earthQuake.title) region.notifyOnEntry = true; region.notifyOnExit = false; let trigger = UNLocationNotificationTrigger.init(region: region, repeats: false) let request = UNNotificationRequest(identifier: locationNotificationRecuestIdentifier, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) } return tableCell } /** * UITableView datasource method for getting header titles */ func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { //construct index path let indexPath = IndexPath(row: 0, section: section) if let earthQuake = EarthQuakeViewController.getEarthQuakeForIndexPath(indexPath, currentRow: 0, currentSection: 0, earthQuakes: self.earthQuakes), let sectionDate = earthQuake.date { let dateComponentsForSection = EarthQuakeViewController.getDateComponentsForDate(sectionDate as Date) let monthName = DateFormatter().monthSymbols[dateComponentsForSection.month! - 1] return "\(monthName) \(dateComponentsForSection.day!)" } return "" } /** * UITableView datasource method indicating that a row can be deleted */ func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } /** * UITableView datasource method for deleting a table cell */ func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if let earthQuake = EarthQuakeViewController.getEarthQuakeForIndexPath(indexPath, currentRow: 0, currentSection: 0, earthQuakes: self.earthQuakes), let earthQuakes = self.earthQuakes { self.earthQuakes = earthQuakes.filter({$0 != earthQuake}) self.earthQuakeTable.reloadData() } } /** * UITableView delegate method indicating that a row has been selected. */ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let earthQuake = EarthQuakeViewController.getEarthQuakeForIndexPath(indexPath, currentRow: 0, currentSection: 0, earthQuakes: self.earthQuakes), let url = URL(string: earthQuake.link) { UIApplication.shared.open(url) } tableView.deselectRow(at: indexPath, animated: true) } /** * Returns the earthquake in earthquakes list for given index path * * @param indexPath - path used to retrieve earthquake from list * @param currentRow - row tally * @param currentSection - sectionTally * @param earthQuakes - list of earthquakes to query * * @return - retrieved earthquake */ private class func getEarthQuakeForIndexPath(_ indexPath: IndexPath, currentRow: Int, currentSection: Int, earthQuakes: [EarthQuake]?) -> EarthQuake? { if let earthQuakes = earthQuakes, let firstEarthQuake = earthQuakes.first, let rowDate = firstEarthQuake.date { //base case if sections and rows are equal if (indexPath as NSIndexPath).section == currentSection && (indexPath as NSIndexPath).row == currentRow { return firstEarthQuake } //get tail of earthquake list let tail = Array(earthQuakes.dropFirst()) //advance row if (indexPath as NSIndexPath).section == currentSection { return getEarthQuakeForIndexPath(indexPath, currentRow: currentRow + 1, currentSection: currentSection, earthQuakes: tail) } //advance section if let firstTail = tail.first, let tailDate = firstTail.date { //get date components of first and second element let rowComponents = EarthQuakeViewController.getDateComponentsForDate(rowDate as Date) let tailComponents = EarthQuakeViewController.getDateComponentsForDate(tailDate as Date) //recurse through list looking for date components of given section if tailComponents.month != rowComponents.month || tailComponents.day != rowComponents.day { return getEarthQuakeForIndexPath(indexPath, currentRow: currentRow, currentSection: currentSection + 1, earthQuakes: tail) } else { return getEarthQuakeForIndexPath(indexPath, currentRow: currentRow, currentSection: currentSection, earthQuakes: tail) } } } return nil } /** * Function returns the count of sections in table. Sections are determined by unique month/day combo * * @param currentSection - tally of section * @param earthQuakes - list of earthquakes to tally against * @param previousComponents - the date components of previous row for comparison for last element * * @return count of sections */ private class func getSectionTotal(_ currentSection: Int, earthQuakes: [EarthQuake]?, previousComponents: DateComponents?) -> Int { if let earthQuakes = earthQuakes, let firstEarthQuake = earthQuakes.first, let rowDate = firstEarthQuake.date { //get date components of first element let rowComponents = EarthQuakeViewController.getDateComponentsForDate(rowDate as Date) //get tail of earthquake list let tail = Array(earthQuakes.dropFirst()) if let firstTail = tail.first, let tailDate = firstTail.date { let tailComponents = EarthQuakeViewController.getDateComponentsForDate(tailDate as Date) //recurse through list looking for date components of given section if tailComponents.month != rowComponents.month || tailComponents.day != rowComponents.day { return getSectionTotal(currentSection + 1, earthQuakes: tail, previousComponents: rowComponents) } else { //acccount for last section of length two if tail.count == 1 && tailComponents.month == rowComponents.month && tailComponents.day == rowComponents.day { if let previousComponents = previousComponents , tailComponents.month != previousComponents.month || tailComponents.day != previousComponents.day { return getSectionTotal(currentSection + 1, earthQuakes: tail, previousComponents: rowComponents) } } return getSectionTotal(currentSection, earthQuakes: tail, previousComponents: rowComponents) } } else { //see if last (sole) earthquake comprises a new section in and of itself if let previousComponents = previousComponents { if (rowComponents.month != previousComponents.month || rowComponents.day != previousComponents.day) { //need to add one because the last element is a new section return currentSection + 1 } } //for earth quake lists consisting of only one day we still want a section if currentSection == 0 { return currentSection + 1 } } } return currentSection } /** * Processes a list of earthquakes and counts the number of dates at beginning of list are equal * to the given date. * * @param sectionComponents - the date to compare beginning of list to * @param earthQuakes - the list of earthquakes that is being examined * * @return the count of earthquakes at beginning of list that are equal to given date. */ private class func processRowsForSection(_ sectionComponents: DateComponents, earthQuakes: [EarthQuake]?) -> Int { if let earthQuakes = earthQuakes, let firstEarthquake = earthQuakes.first, let rowDate = firstEarthquake.date { let rowComponents = EarthQuakeViewController.getDateComponentsForDate(rowDate as Date) if rowComponents.month == sectionComponents.month && rowComponents.day == sectionComponents.day { let tail = Array(earthQuakes.dropFirst()) return 1 + processRowsForSection(sectionComponents, earthQuakes: tail) } else { return 0 } } return 0 } /** * Returns the number of earthquakes reported for the given day. This represents a section. * * @param dateForRows - the date to get earthquakes on * @param earthQuakes - the list earthquakes to pull from * * @return the number of earthquakes for a given day. */ private class func getNumberOfRowsForDate(_ sectionComponents: DateComponents, earthQuakes:[EarthQuake]?) -> Int { if let earthQuakes = earthQuakes, let firstEarthquake = earthQuakes.first, let rowDate = firstEarthquake.date { let rowComponents = EarthQuakeViewController.getDateComponentsForDate(rowDate as Date) let tail = Array(earthQuakes.dropFirst()) if rowComponents.month == sectionComponents.month && rowComponents.day == sectionComponents.day { return 1 + EarthQuakeViewController.processRowsForSection(sectionComponents, earthQuakes: tail) } else { return getNumberOfRowsForDate(sectionComponents, earthQuakes: tail) } } return 0 } /** * Gets date components for given nsdate * * @param date - date to retreive date components from * * @return date components for date */ private class func getDateComponentsForDate(_ date: Date) -> DateComponents { return NSCalendar.current.dateComponents([.day, .month], from: date) } }
true
7d59b22532993631bbd00926e258713aa783c2b7
Swift
SofiaSantosCev/ventaentradas
/VentaDeEntradas/Entrada.swift
UTF-8
1,472
3.03125
3
[]
no_license
import Foundation import UIKit class Entrada: NSObject, NSCoding { var name:String var date:String var city:String var image: UIImage var code:Int var cantidad: String init(name: String, date: String, city: String, image: UIImage, cantidad: String) { self.name = name self.date = date self.city = city self.image = image self.code = Int(arc4random_uniform(1000000000)) self.cantidad = cantidad } /* Este método sobreescribe el init */ required convenience init(coder aDecoder: NSCoder) { let name = aDecoder.decodeObject(forKey: "name") as! String let image = aDecoder.decodeObject(forKey: "image") as! UIImage let date = aDecoder.decodeObject(forKey: "date") as! String let city = aDecoder.decodeObject(forKey: "city") as! String let cantidad = aDecoder.decodeObject(forKey: "cantidad") as! String self.init(name: name, date: date, city: city, image: image, cantidad: cantidad) } /* Este metodo asigna una clave a cada dato para guardarlo */ func encode(with aCoder: NSCoder) { aCoder.encode(image, forKey: "image") aCoder.encode(city, forKey: "city") aCoder.encode(name, forKey: "name") aCoder.encode(code, forKey: "code") aCoder.encode(date, forKey: "date") aCoder.encode(cantidad, forKey: "cantidad") } }
true
9e625f3d02e4b31924c5607e96b9e77c534f0068
Swift
mateusvagner/OOP_Swift
/Chapter04/Chapter04/main.swift
UTF-8
480
2.671875
3
[]
no_license
// // main.swift // Chapter04 // // Created by Mateus Vagner Guedes de Almeida on 19/11/20. // import Foundation let authenticator = Authenticator() let authorizor = Authorizor(authenticator: authenticator) try authenticator.addUser(username: "joe", password: "joepassword") try authorizor.addPermission(permName: "test program") try authorizor.addPermission(permName: "change program") try authorizor.permitUser(permName: "test program", username: "joe") Editor(authenticator, authorizor).menu()
true
a17d04f2e9dd6712b55b8835b6f5b4ce30f8d2b7
Swift
TIMMYDOTO/zaimbot
/ZaimBot/LableVC.swift
UTF-8
2,510
2.78125
3
[]
no_license
// // LableVC.swift // ZaimBot // // Created by Artyom Schiopu on 27.12.2019. // Copyright © 2019 Artyom Schiopu. All rights reserved. // import UIKit import ActiveLabel class LableVC: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() hideKeyboardWhenTappedAround() // dismissKeyboard() } } extension LableVC: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TestCell cell.activeLabel.text = "Проанализировав ваш профиль предлагаем займ у нашего партнера Е - Капуста. Для моментального, автоматического получения до 30.000 ₽ под 0% (сколько взяли столько и отдаете) до 30 дней оставьте заявку здесь https://go.leadgid.ru/aff_c?offer_id=1658&aff_id=58757 (нажмите на ссылку)\n Так же Займер готов одобрить до 30 000 уже через 15 минут Вам на карту! https://go.leadgid.ru/aff_c?offer_id=1621&aff_id=58757 (нажмите на ссылку)\nДоЗарплаты - от 2 000 до 100 000 руб до 12 месяцев https://go.leadgid.ru/aff_c?offer_id=2555&aff_id=58757 (нажмите на ссылку)\n Быстроденьги - Для Вас до 15 000 руб под 0% - забирайте! https://go.leadgid.ru/aff_c?offer_id=4464&aff_id=58757 (нажмите на ссылку)\n Или напиши мне любое сообщение, чтобы начать подбор других займов." cell.activeLabel.handleURLTap { (url) in print(url) } cell.activeLabel.sizeToFit() return cell } } extension LableVC { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } }
true
bd8e08be70afa18b91df0d1c5108dced28504763
Swift
kellanburket/Passenger
/Example/Passenger/Twitter/TwitterOAuth1Helper.swift
UTF-8
2,260
2.515625
3
[ "MIT" ]
permissive
// // TwitterOAuth1Helper.swift // Passenger // // Created by Kellan Cummings on 7/8/15. // Copyright (c) 2015 CocoaPods. All rights reserved. // import Foundation import Passenger class TwitterOAuth1Helper: OAuth1Helper { override init() { super.init() if let service = Api.shared().getAuthorizationService(AuthorizationType.OAuth1) as? OAuth1 { service.token = "3270562178-EKvfMjCLUJinVd2CzSXRB1fASUTMHwR5jng4O8J" service.secret = "mt3K6B05FOebpcD6dE51CXcv4Y7AywYU1gQnvx5lO8W3M" } } override func getRequestToken() -> OAuth1Helper { if let service = Api.shared().getAuthorizationService(AuthorizationType.OAuth1) as? OAuth1 { if service.token == nil || service.secret == nil { service.getRequestTokenUrl { secret, url in if let url = url { UIApplication.sharedApplication().openURL(url) } else { println("Request Token Url not discovered.") } } } else { println("Access Token:\(service.token)") println("Access Token Secret:\(service.secret)") } } else { println("OAuth1 Service not implemented.") } return self } override func getAccessToken(url: NSURL) -> OAuth1Helper { if let service = Api.shared().getAuthorizationService(AuthorizationType.OAuth1) as? OAuth1 { service.delegate = self let query = HttpRequest.parseQueryString(url) if let token = query["oauth_token"] as? String, verifier = query["oauth_verifier"] as? String { service.fetchAccessToken(token: token, verifier: verifier) } else { println("Could not parse query: \(query)") } } else { println("OAuth1 Service not implemented.") } return self } override func accessTokenHasBeenFetched(accessToken: String, accessTokenSecret: String) { super.accessTokenHasBeenFetched(accessToken, accessTokenSecret: accessTokenSecret) println("Access Token:\(accessToken)") println("Access Token Secret:\(accessTokenSecret)") } }
true
cac5bb6de416491b6e97d48169d940bbbb1fbbc1
Swift
edenni/hunch
/miyagi_coupon/Views/ShopListItem.swift
UTF-8
2,199
3.015625
3
[]
no_license
// // CardView.swift // miyagi_coupon // // Created by EdenN0 on 2021/07/04. // import Foundation import SwiftUI import UIKit struct ShopListItem: View { let shop: Shop let cardwidth = UIScreen.screenWidth*0.872 var body: some View { VStack(spacing: 0) { Image(shop.imageUrl) .resizable() .frame(width: cardwidth, height: cardwidth*0.75, alignment: .center) HStack { VStack(spacing:0) { Text(shop.name) .font(Font.custom("Tamil MN Bold", size: 23)) .foregroundColor(Color(hex: 0x4a4a4a)) .padding(EdgeInsets(top: 10, leading: 0, bottom: 3, trailing: 0)) .lineLimit(1) Rectangle() .frame(width: 40, height: 3, alignment: .center) .foregroundColor(Color(hex: 0xe2e228)) .padding(EdgeInsets(top: 0, leading: 0, bottom: 10, trailing: 0)) HStack(spacing:0) { Image(systemName: "mappin.and.ellipse") Text(String(shop.distance)+"m") Spacer().frame(width:20) Image(systemName: "yensign.circle") Text(shop.values) } .font(Font.custom("Tamil MN Bold", size: 19)) .foregroundColor(Color(hex: 0x7b7b7b)) .lineLimit(1) } .frame(width: cardwidth, height: cardwidth*0.25, alignment: .center) .layoutPriority(100) } } .background(Color(hex: 0xffffff)) .cornerRadius(23) .frame(width: cardwidth, height: cardwidth, alignment: .center) } } //struct ShopListItem_Previews: PreviewProvider { // static var previews: some View { // ShopListItem(shop: Shop( // name: "お肉本舗", // imageUrl: "megumin", // distance: 300, // values: "1000 - 2000" // )) // .previewDevice("iPhone 12 Pro") // } //}
true
6bb8e65d7117fe1bc857890d4ea74eba35c475a5
Swift
kimar/OnelinerKit
/OnelinerKit/View/OnelinerView.swift
UTF-8
3,226
2.609375
3
[ "MIT" ]
permissive
// // OnelinerView.swift // OnelinerKit // // Created by Marcus Kida on 17.12.17. // Copyright © 2017 Marcus Kida. All rights reserved. // import ScreenSaver open class OnelinerView: ScreenSaverView { private let fetchQueue = DispatchQueue(label: .fetchQueue) private let mainQueue = DispatchQueue.main private var label: NSTextField! private var fetchingDue = true private var lastFetchDate: Date? public var backgroundColor = NSColor.black public var textColor = NSColor.white override public init?(frame: NSRect, isPreview: Bool) { super.init(frame: frame, isPreview: isPreview) label = .label(isPreview, bounds: frame) initialize() } required public init?(coder: NSCoder) { super.init(coder: coder) label = .label(isPreview, bounds: bounds) initialize() } override open var configureSheet: NSWindow? { return nil } override open var hasConfigureSheet: Bool { return false } override open func animateOneFrame() { fetchNext() } override open func draw(_ rect: NSRect) { super.draw(rect) var newFrame = label.frame newFrame.origin.x = 0 newFrame.origin.y = rect.size.height / 2 newFrame.size.width = rect.size.width newFrame.size.height = (label.stringValue as NSString).size(withAttributes: [NSAttributedStringKey.font: label.font!]).height label.frame = newFrame label.textColor = textColor backgroundColor.setFill() rect.fill() } open func fetchOneline(_ completion: @escaping (String) -> Void) { preconditionFailure("`fetchOneline` must be overridden") } private func initialize() { animationTimeInterval = 0.5 addSubview(label) restoreLast() scheduleNext() } private func restoreLast() { fetchingDue = true set(oneliner: UserDefaults.lastOneline) } private func set(oneliner: String?) { if let oneliner = oneliner { label.stringValue = oneliner UserDefaults.lastOneline = oneliner setNeedsDisplay(frame) } } private func scheduleNext() { mainQueue.asyncAfter(deadline: .now() + 1) { [weak self] in guard let 🕑 = self?.lastFetchDate else { self?.scheduleForFetch() return } guard Date().isFetchDue(since: 🕑) else { self?.scheduleNext() return } self?.scheduleForFetch() } } private func scheduleForFetch() { fetchingDue = true fetchNext() } private func fetchNext() { if !fetchingDue { return } fetchingDue = false fetchQueue.sync { [weak self] in self?.fetchOneline { oneline in self?.mainQueue.async { [weak self] in self?.lastFetchDate = Date() self?.scheduleNext() self?.set(oneliner: oneline) } } } } }
true
68282a9115cefb5c8a1c5f340fa6403a5fae48af
Swift
alexanderritik/ByteCoin
/ByteCoin/Model/CoinManager.swift
UTF-8
2,212
2.9375
3
[]
no_license
// // CoinManager.swift // ByteCoin // // Created by Angela Yu on 11/09/2019. // Copyright © 2019 The App Brewery. All rights reserved. // import Foundation protocol CoinManagerDelegate { func didCurrencyUpdate(_ data: CoinModel) func didCurrencyFail(_ error : Error) } struct CoinManager { var delegate : CoinManagerDelegate? let baseURL = "https://rest.coinapi.io/v1/exchangerate/BTC" let apiKey = "F76481C5-4064-4AFC-ABDF-19C24F80B422" let currencyArray = ["AUD", "BRL","CAD","CNY","EUR","GBP","HKD","IDR","ILS","INR","JPY","MXN","NOK","NZD","PLN","RON","RUB","SEK","SGD","USD","ZAR"] func performRequest(for urlString:String){ let url = "\(baseURL)/\(urlString)/?apikey=\(apiKey)" // print(url) if let url = URL(string: url) { // 2 . Create a URL session let session=URLSession(configuration: .default) // 3 . Give the session a task let task = session.dataTask(with: url) {(data , response,error) in if error != nil { self.delegate?.didCurrencyFail(error!) //print(error!) return } if let safeData = data { if let data = self.parseJson(currencyData: safeData) { self.delegate?.didCurrencyUpdate(data) // print(data) } } } task.resume() } } func parseJson(currencyData : Data) -> CoinModel? { let decode = JSONDecoder() do { let money = try decode.decode(CoinData.self , from: currencyData) let coinModel = CoinModel(coinString: money.rate , currency: money.asset_id_quote) return coinModel } catch { print(error) self.delegate?.didCurrencyFail(error) return nil } } }
true
ac8b4a0b0e947bc457804699cb3b52d303390504
Swift
mothule/uitableview-base-layout
/TableView/Presentations/Views/CarouselTableViewCell.swift
UTF-8
3,242
2.921875
3
[ "MIT" ]
permissive
// // CarouselTableViewCell.swift // TableView // // Created by mothule on 2019/10/09. // Copyright © 2019 mothule. All rights reserved. // import Foundation import UIKit class CarouselTableViewCell: UITableViewCell, Nibable { @IBOutlet private weak var collectionView: UICollectionView! @IBOutlet private weak var pageControl: UIPageControl! private var images: [String] = [] private var timer: Timer! override func awakeFromNib() { super.awakeFromNib() collectionView.dataSource = self collectionView.delegate = self pageControl.addTarget(self, action: #selector(onTouchedPageControl(_:)), for: .valueChanged) scheduleAutoSwipe() } deinit { timer?.invalidate() } func setup(imageURLs: [String]) { pageControl.numberOfPages = imageURLs.count pageControl.currentPage = 0 images = imageURLs setupCollectionViewLayout() } @objc private func onTouchedPageControl(_ sender: UIPageControl) { let path = IndexPath(item: sender.currentPage, section: 0) collectionView.scrollToItem(at: path, at: .left, animated: true) // 操作されたらタイマーリセット scheduleAutoSwipe() } private func setupCollectionViewLayout() { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.itemSize = collectionView.bounds.size layout.minimumLineSpacing = 0.0 layout.minimumInteritemSpacing = 0.0 collectionView.collectionViewLayout = layout } private func scheduleAutoSwipe() { timer?.invalidate() timer = Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true, block: { [weak self] _ in guard let self = self else { return } self.pageControl.movePage(dir: .next) self.onTouchedPageControl(self.pageControl) }) } } extension CarouselTableViewCell: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(CarouselCollectionViewCell.self, for: indexPath) let image = images[indexPath.item] cell.setup(imageURL: image) return cell } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.size.width) } } class CarouselCollectionViewCell: UICollectionViewCell, Nibable { @IBOutlet private weak var imageView: UIImageView! func setup(imageURL: String) { let url = URL(string: imageURL)! URLSession.shared.dataTask(with: url) { (data, res, error) in if let data = data { DispatchQueue.main.async { self.imageView.image = UIImage(data: data) self.imageView.setNeedsLayout() } } }.resume() } }
true
5c4dddb2988b070635e1ac477970049bd72d257a
Swift
swiftforarduino/community
/demo examples/light-dimmer.swift
UTF-8
2,181
3.421875
3
[ "MIT" ]
permissive
import AVR typealias IntegerLiteralType = UInt8 // configuration constants let triacPin = 4 let storedBrightnessLocation: UInt16 = 34 let storedOnOffLocation: UInt16 = 35 let brightnessi2cRegister = 6 let onOffi2cRegister = 7 // defaults until EEPROM is read var delayFactor = 90 var delayUs: UInt32 = 9000 var enabled = false // setup triac pin pinMode(pin: triacPin, mode: OUTPUT) func i2cUpdate(register: UInt8, value: UInt8) { if register == brightnessi2cRegister { updateDelay(value) } else if register == onOffi2cRegister { updateEnabled(boolForUInt8(value)) } } func i2cRead(register: UInt8) -> UInt8 { if register == brightnessi2cRegister { return delayFactor } else if register == onOffi2cRegister { return uint8ForBool(enabled) } return 0 } // the update function, calcs and storage func updateDelay(_ newDelayFactorIn: UInt8) { var newDelayFactor = newDelayFactorIn if newDelayFactor > 90 { newDelayFactor = 90 } if newDelayFactor < 5 { newDelayFactor = 5 } delayFactor = newDelayFactor delayUs = UInt32(newDelayFactor) &* 100 writeEEPROM(address: storedBrightnessLocation, value: newDelayFactor) } func updateEnabled(_ newEnabled: Bool) { enabled = newEnabled writeEEPROM(address: storedOnOffLocation, value: uint8ForBool(newEnabled)) } // initialise brightness from EEPROM updateDelay(readEEPROM(address: storedBrightnessLocation)) enabled = boolForUInt8(readEEPROM(address: storedOnOffLocation)) // the core of the program, a delayed triac fire a set time after zero cross setupPin2InterruptCallback(edgeType: RISING_EDGE) { setupTimerSingleShotInterruptCallback(microseconds: delayUs) { digitalWrite(pin: triacPin, value: HIGH) delay(microseconds: 200) digitalWrite(pin: triacPin, value: LOW) } } // Use I2C to communicate to the pi for remote control i2cSlaveSetupRegisterReceiveCallback { register, value in i2cUpdate(register: register, value: value) } i2cSlaveSetupRegisterSendCallback { register -> UInt8 in return i2cRead(register: register) } setupI2CSlave(address: 0x23) // main loop, for now do nothing, later add rotary encoder support while (true) { }
true
041a2c6853a1182ca3c743d93477f86f9f926eea
Swift
smehus/Highlands
/Common/Utility/RenderPass.swift
UTF-8
3,257
2.90625
3
[]
no_license
import MetalKit class RenderPass { var descriptor: MTLRenderPassDescriptor var texture: MTLTexture var depthTexture: MTLTexture let name: String init(name: String, size: CGSize) { self.name = name texture = RenderPass.buildTexture(size: size, label: name, pixelFormat: .bgra8Unorm) depthTexture = RenderPass.buildTexture(size: size, label: name, pixelFormat: .depth32Float_stencil8) descriptor = RenderPass.setupRenderPassDescriptor(texture: texture, depthTexture: depthTexture) } func updateTextures(size: CGSize) { texture = RenderPass.buildTexture(size: size, label: name, pixelFormat: .bgra8Unorm) depthTexture = RenderPass.buildTexture(size: size, label: name, pixelFormat: .depth32Float_stencil8) descriptor = RenderPass.setupRenderPassDescriptor(texture: texture, depthTexture: depthTexture) } static func setupRenderPassDescriptor(texture: MTLTexture, depthTexture: MTLTexture) -> MTLRenderPassDescriptor { let descriptor = MTLRenderPassDescriptor() descriptor.setUpColorAttachment(position: 0, texture: texture) descriptor.setUpRenderPassDepthAttachment(texture: depthTexture) return descriptor } static func buildTexture(size: CGSize, label: String, pixelFormat: MTLPixelFormat) -> MTLTexture { let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixelFormat, width: Int(size.width * 0.5), height: Int(size.height * 0.5), mipmapped: false) descriptor.sampleCount = 1 descriptor.storageMode = .private descriptor.textureType = .type2D descriptor.usage = [.renderTarget, .shaderRead] guard let texture = Renderer.device.makeTexture(descriptor: descriptor) else { fatalError("Texture not created") } texture.label = label return texture } } private extension MTLRenderPassDescriptor { func setUpRenderPassDepthAttachment(texture: MTLTexture) { depthAttachment.texture = texture depthAttachment.loadAction = .clear depthAttachment.storeAction = .store depthAttachment.clearDepth = 1 stencilAttachment.texture = texture stencilAttachment.loadAction = .clear stencilAttachment.storeAction = .dontCare } func setUpColorAttachment(position: Int, texture: MTLTexture) { let attachment: MTLRenderPassColorAttachmentDescriptor = colorAttachments[position] attachment.texture = texture attachment.loadAction = .clear attachment.storeAction = .store attachment.clearColor = MTLClearColorMake(1, 1, 1, 1) } }
true
a3f86fcc80d8086cb9004b4d35f0ee078795659a
Swift
exah/piny-ios
/piny/Views/LogIn.swift
UTF-8
2,829
3.03125
3
[]
no_license
// // Login.swift // piny // // Created by John Grishin on 16/07/2020. // Copyright © 2020 John Grishin. All rights reserved. // import SwiftUI struct LogIn: View { @EnvironmentObject var userState: UserState @State private var name: String = "" @State private var pass: String = "" @State private var email: String = "" @State private var shouldSignUp: Bool = false func handleLogin() { self.userState.login( name: name, pass: pass ).catch { error in if let error = error as? API.Error { switch error { case .notOK( _, let statusCode, _): do { if statusCode == 404 { self.shouldSignUp = true } } default: Piny.log(error, .error) } } } } func handleSignUp() { self.userState.signUp( name: name, pass: pass, email: email ).catch { error in Piny.log(error, .error) } } var body: some View { NavigationView { ZStack { Color.piny.background .edgesIgnoringSafeArea(.all) VStack { VStack(spacing: 24) { VStack(spacing: 12) { Image("Logo") .renderingMode(.template) .foregroundColor(.piny.foreground) Text("Welcome 👋") .variant(.secondary) .foregroundColor(.piny.grey50) } VStack(spacing: 12) { Group { Input("Username", value: $name) Input("Password", type: .password, value: $pass) } .autocapitalization(.none) .autocorrectionDisabled() } Button(action: handleLogin) { Group { if (userState.isLoading) { Image(systemName: "circle.dotted") } else { Text("Login") } }.frame(maxWidth: .infinity) } .variant(.primary) .disabled(userState.isLoading) .alert( "Enter your email to create an account", isPresented: $shouldSignUp ) { TextField("Email", text: $email) Button("Create account", action: handleSignUp) Button("Cancel", role: .cancel, action: { email = "" shouldSignUp.toggle() }) } } .padding(32) .background(Color.piny.level48) .cornerRadius(40) .shadow(color: .piny.black.opacity(0.08), radius: 48) } .padding(.horizontal, 12) } } } } struct Login_Previews: PreviewProvider { static var previews: some View { LogIn() .environmentObject(UserState()) } }
true
64f312b2351e4489a3bad77701d0cd09cc92fd3d
Swift
adeiji/TRAFOD
/TRAFOD/UtilityFunctions.swift
UTF-8
572
2.90625
3
[]
no_license
// // UtilityFunctions.swift // TRAFOD // // Created by Adebayo Ijidakinro on 7/24/19. // Copyright © 2019 Dephyned. All rights reserved. // import Foundation import GameKit class UtilityFunctions { /** Given two nodes it returns the distance between them - Parameter first: The first node - Parameter second: The second node */ class func SDistanceBetweenPoints(first: SKNode, second: SKNode) -> CGFloat { return CGFloat(hypotf(Float(second.position.x - first.position.x), Float(second.position.y - first.position.y))); } }
true
752eadd1be1ff81a36f3bd6b5ae1d8569a78b997
Swift
buuuuutek/MapboxFramework
/MapboxFramework/ViewController.swift
UTF-8
4,282
2.65625
3
[]
no_license
// // ViewController.swift // MapboxFramework // // Created by ApplePie on 15.03.18. // Copyright © 2018 VictorVolnukhin. All rights reserved. // import UIKit import Mapbox import SwiftyJSON class ViewController: UIViewController, MGLMapViewDelegate { var hexMarkerColor = String() override func viewDidLoad() { super.viewDidLoad() let map = createMap() let fileData = getFileData(fileName: "map", fileType: "geojson") if let json = try? JSON(data: fileData){ addAnnotations(from: json, to: map) } else { print("Application couldn't parse this data to JSON.") } } private func addAnnotations(from json: JSON, to mapView: MGLMapView) { let features = json["features"].arrayValue for item in features { let newAnnotation = MGLPointAnnotation() newAnnotation.title = item["properties"]["name"].stringValue let x = item["geometry"]["coordinates"][0].doubleValue let y = item["geometry"]["coordinates"][1].doubleValue newAnnotation.coordinate = CLLocationCoordinate2D(latitude: y, longitude: x) hexMarkerColor = item["properties"]["marker-color"].stringValue mapView.addAnnotation(newAnnotation) } } func createMap() -> MGLMapView { let mapView = MGLMapView(frame: view.bounds) mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] mapView.setCenter(CLLocationCoordinate2D(latitude: 55.75, longitude: 37.61), zoomLevel: 11, animated: false) view.addSubview(mapView) mapView.delegate = self return mapView } func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? { // This example is only concerned with point annotations. guard annotation is MGLPointAnnotation else { return nil } // Use the point annotation’s longitude value (as a string) as the reuse identifier for its view. let reuseIdentifier = "\(annotation.coordinate.longitude)" // For better performance, always try to reuse existing annotations. var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) // If there’s no reusable annotation view available, initialize a new one. if annotationView == nil { annotationView = CustomAnnotationView(reuseIdentifier: reuseIdentifier) annotationView!.frame = CGRect(x: 0, y: 0, width: 40, height: 40) annotationView!.backgroundColor = hexStringToUIColor(hex: hexMarkerColor) } return annotationView } func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool { return true } func getFileData(fileName: String, fileType: String) -> Data { var data = Data() if let path = Bundle.main.path(forResource: fileName, ofType: fileType) { do { data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped) } catch { print("Contents could not be loaded.") } } else { print("\(fileName).\(fileType) not found.") } return data } func hexStringToUIColor (hex:String) -> UIColor { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.characters.count) != 6) { return UIColor.gray } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } }
true
c8643ad61a6b945fb07ead89d7c1f07a10bdb707
Swift
onmyway133/Github.swift
/Carthage/Checkouts/Tailor/Sources/Shared/Extensions/Dictionary+Tailor.swift
UTF-8
7,632
3.53125
4
[ "MIT" ]
permissive
import Sugar // MARK: - Basic public extension Dictionary { /** - Parameter name: The name of the property that you want to map - Returns: A generic type if casting succeeds, otherwise it returns nil */ func property<T>(name: String) -> T? { guard let key = name as? Key, value = self[key] as? T else { return nil } return value } /** - Parameter name: The name of the property that you want to map - Returns: A generic type if casting succeeds, otherwise it throws */ func propertyOrThrow<T>(name: String) throws -> T { guard let result: T = property(name) else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") } return result } /** - Parameter name: The name of the property that you want to map - Parameter transformer: A transformation closure - Returns: A generic type if casting succeeds, otherwise it returns nil */ func transform<T, U>(name: String, transformer: ((value: U) -> T?)) -> T? { guard let key = name as? Key, value = self[key] as? U else { return nil } return transformer(value: value) } /** - Parameter name: The name of the property that you want to map - Returns: A mappable object directory, otherwise it returns nil */ func directory<T : Mappable>(name: String) -> [String : T]? { guard let key = name as? Key, dictionary = self[key] as? JSONDictionary else { return nil } var directory = [String : T]() for (key, value) in dictionary { guard let value = value as? JSONDictionary else { continue } directory[key] = T(value) } return directory } /** - Parameter name: The name of the key - Returns: A child dictionary for that key, otherwise it returns nil */ func dictionary(name: String) -> JSONDictionary? { guard let key = name as? Key, value = self[key] as? JSONDictionary else { return nil } return value } /** - Parameter name: The name of the key - Returns: A child dictionary for that key, otherwise it throws */ func dictionaryOrThrow(name: String) throws -> JSONDictionary { guard let result = dictionary(name) else { throw MappableError.TypeError(message: "Tried to get value for \(name) as JSONDictionary") } return result } /** - Parameter name: The name of the key - Returns: A child array for that key, otherwise it returns nil */ func array(name: String) -> JSONArray? { guard let key = name as? Key, value = self[key] as? JSONArray else { return nil } return value } /** - Parameter name: The name of the key - Returns: A child array for that key, otherwise it throws */ func arrayOrThrow(name: String) throws -> JSONArray { guard let result = array(name) else { throw MappableError.TypeError(message: "Tried to get value for \(name) as JSONArray") } return result } /** - Parameter name: The name of the key - Returns: An enum if casting succeeds, otherwise it returns nil */ func `enum`<T: RawRepresentable>(name: String) -> T? { guard let key = name as? Key, value = self[key] as? T.RawValue else { return nil } return T(rawValue: value) } /** - Parameter name: The name of the key - Returns: An enum if casting succeeds, otherwise it throws */ func enumOrThrow<T: RawRepresentable>(name: String) throws -> T { guard let result: T = `enum`(name) else { throw MappableError.TypeError(message: "Tried to get value for \(name) as enum") } return result } } // MARK: - Relation public extension Dictionary { /** - Parameter name: The name of the property that you want to map - Returns: A mappable object, otherwise it returns nil */ func relation<T : Mappable>(name: String) -> T? { guard let key = name as? Key, dictionary = self[key] as? JSONDictionary else { return nil } return T(dictionary) } /** - Parameter name: The name of the property that you want to map - Returns: A generic type if casting succeeds, otherwise it throws */ func relationOrThrow<T : Mappable>(name: String) throws -> T { guard let result: T = relation(name) else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") } return result } /** - Parameter name: The name of the property that you want to map - Returns: A mappable object, otherwise it returns nil */ func relation<T : SafeMappable>(name: String) -> T? { guard let key = name as? Key, dictionary = self[key] as? JSONDictionary else { return nil } let result: T? do { result = try T(dictionary) } catch { result = nil } return result } /** - Parameter name: The name of the property that you want to map - Returns: A generic type if casting succeeds, otherwise it throws */ func relationOrThrow<T : SafeMappable>(name: String) throws -> T { guard let result: T = relation(name) else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") } return result } } // MARK: - Relations public extension Dictionary { /** - Parameter name: The name of the property that you want to map - Returns: A mappable object array, otherwise it returns nil */ func relations<T : Mappable>(name: String) -> [T]? { guard let key = name as? Key, array = self[key] as? JSONArray else { return nil } return array.map { T($0) } } /** - Parameter name: The name of the property that you want to map - Returns: A mappable object array, otherwise it throws */ func relationsOrThrow<T : Mappable>(name: String) throws -> [T] { guard let result: [T] = relations(name) else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") } return result } /** - Parameter name: The name of the property that you want to map - Returns: A mappable object array, otherwise it returns nil */ func relations<T : SafeMappable>(name: String) -> [T]? { guard let key = name as? Key, array = self[key] as? JSONArray else { return nil } var result = [T]() do { result = try array.map { try T($0) } } catch {} return result } /** - Parameter name: The name of the property that you want to map - Returns: A mappable object array, otherwise it throws */ func relationsOrThrow<T : SafeMappable>(name: String) throws -> [T] { guard let result: [T] = relations(name) else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") } return result } } // MARK: - Relation Hierarchically public extension Dictionary { /** - Parameter name: The name of the property that you want to map - Returns: A mappable object, considering hierarchy, otherwise it returns nil */ func relationHierarchically<T where T: Mappable, T: HierarchyType>(name: String) -> T? { guard let key = name as? Key, dictionary = self[key] as? JSONDictionary else { return nil } return T.cluster(dictionary) as? T } /** - Parameter name: The name of the property that you want to map - Returns: A mappable object array, considering hierarchy, otherwise it returns nil */ func relationsHierarchically<T where T: Mappable, T: HierarchyType>(name: String) -> [T]? { guard let key = name as? Key, array = self[key] as? JSONArray else { return nil } return array.flatMap { T.cluster($0) as? T } } }
true
342b5a52ee191c2562dc4023609612d4a3ea6bcc
Swift
GaurishGB/CustomSegmentedControl
/CustomSegmentedControl/ViewController.swift
UTF-8
1,267
2.53125
3
[]
no_license
// // ViewController.swift // CustomSegmentedControl // // Created by Gaurish on 26/09/19. // Copyright © 2019 GB. All rights reserved. // var counter1:Int = 0 import UIKit class ViewController: UIViewController { @IBOutlet weak var uiSegmentedControl: UISegmentedControl! @IBOutlet weak var gbSegmentedControl: GBSegmentedControl! @IBOutlet weak var gbSegmentedSliderControl: GBSegmentedSliderControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func didChangeUISegmentedControlValue(_ sender: UISegmentedControl) { changeSelection(index: sender.selectedSegmentIndex) } @IBAction func didChangeGBSegmentedControlValue(_ sender: GBSegmentedControl) { changeSelection(index: sender.selectedSegmentIndex) } @IBAction func didChangeGBSegmentedSliderControlValue(_ sender: GBSegmentedSliderControl) { changeSelection(index: sender.selectedSegmentIndex) } func changeSelection(index:Int) { uiSegmentedControl.selectedSegmentIndex = index gbSegmentedControl.changeSelectedSegmentIndex = index gbSegmentedSliderControl.changeSelectedSegmentIndex = index } }
true
382d91b17443a08261299437e1b6733032f35bbd
Swift
foodtruck-tracker/iOS
/FoodTruckTracker/FoodTruckTracker/Controllers/RegisterViewController.swift
UTF-8
3,678
2.71875
3
[]
no_license
// // RegisterViewController.swift // FoodTruckTracker // // Created by Lambda_School_Loaner_218 on 1/8/20. // Copyright © 2020 Lambda_School_Loaner_218. All rights reserved. // import UIKit class RegisterViewController: UIViewController { enum loginType { case signUp case login } let registerController = RegisterController() var logintype: loginType = .signUp @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var roleTextField: UITextField! @IBOutlet weak var cityTextField: UITextField! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var logintypeSegmentedControl: UISegmentedControl! @IBAction func LoginSelector(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: logintype = .signUp signUpButton.setTitle("Sign Up", for: .normal) case 1: logintype = .login signUpButton.setTitle("Log In", for: .normal) default: break } } override func viewDidLoad() { super.viewDidLoad() } @IBAction func registerPressed(_ sender: Any) { guard let email = emailTextField.text, let password = passwordTextField.text, let role = roleTextField.text, let city = cityTextField.text else { return } let newUser = User(username: email, password: password, role: Int(role) ?? 2 , city: city) registerController.signUp(with: newUser) { (error) in if let error = error { print("Error for sign up:\(error.localizedDescription)") } DispatchQueue.main.async { self.performSegue(withIdentifier: "RegisterSegue", sender: self) } if self.logintype == .signUp { self.registerController.signUp(with: newUser) { (error) in if let error = error { print("Error occourred during sugn up: \(error)") } else { let alertControl = UIAlertController(title: "Sign up Succesful", message: "Now please login", preferredStyle: .alert) let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertControl.addAction(alertAction) self.present(alertControl,animated: true) { self.logintype = .signUp self.logintypeSegmentedControl.selectedSegmentIndex = 1 self.signUpButton.setTitle("Sign In", for: .normal) } } } } else { self.registerController.login(with: newUser) { (error) in if let error = error { print("Error signing up: \(error)") } else { self.dismiss(animated: true, completion: nil) } } } } } /* // 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. } */ }
true
c0d3e65209bd2138b5b5822ba7b8d6375ef26453
Swift
elegantchaos/CollectionExtensions
/Sources/CollectionExtensions/Sequence+Sorting.swift
UTF-8
532
2.734375
3
[ "MIT" ]
permissive
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Created by Sam Deane on 29/05/2020. // All code (c) 2020 - present day, Elegant Chaos Limited. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- import Foundation public extension Sequence { /// Returns the sequence, sorted by a keypath. func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>) -> [Element] { return sorted { a, b in return a[keyPath: keyPath] < b[keyPath: keyPath] } } }
true
be8a4725f8a0ed6436cd5f06ec634cef376e3544
Swift
jaredcassoutt/WallBounceGame
/Wall Runner/Templates/Obstacle.swift
UTF-8
323
2.8125
3
[]
no_license
// // Obstacle.swift // Wall Runner // // Created by Jared Cassoutt on 12/8/20. // import Foundation class Obstacle { var side: String var type: String var distance: Int init(side:String,type:String, distance: Int) { self.side = side self.type = type self.distance = distance } }
true
5b68dd7800a81175753f81636d8f771add43ec57
Swift
nahung89/WizelineMovie
/Challenge/ViewModels/MovieDetailViewModel.swift
UTF-8
3,602
2.8125
3
[]
no_license
// // MovieDetailViewModel.swift // Challenge // // Created by Nah on 2/19/19. // Copyright © 2019 Nah. All rights reserved. // import Foundation import RxSwift typealias MovieDetailViewModelDependency = MovieDetailViewModel.Dependency extension MovieDetailViewModel { struct Dependency { let detailRepository: MovieDetailRepository let creditRepository: MovieCreditsRepository } } class MovieDetailViewModel { let viewState: BehaviorSubject<ViewState> = BehaviorSubject(value: .blank) let onRefresh: PublishSubject<Void> = PublishSubject() private(set) var movieDetail: MovieDetail { didSet { parseData() } } private(set) var movieCredits: MovieCredits { didSet { parseData() } } private(set) var sections: [MovieDetailViewController.Section] = [] private(set) var rowsInSections: [MovieDetailViewController.Section: [MovieDetailViewController.Row]] = [:] private let detailRepository: MovieDetailRepository private let creditRepository: MovieCreditsRepository private let disposeBag = DisposeBag() init(_ dependency: Dependency) { detailRepository = dependency.detailRepository creditRepository = dependency.creditRepository movieDetail = detailRepository.movieDetail movieCredits = creditRepository.movieCredits onRefresh.subscribe(onNext: { [unowned self] _ in self.refresh() }).disposed(by: disposeBag) detailRepository.apiState.asObservable() .map({ ViewState($0) }) .do(onNext: { [unowned self] viewState in guard viewState == .working else { return } self.movieDetail = self.detailRepository.movieDetail }) .bind(to: viewState) .disposed(by: disposeBag) creditRepository.apiState.asObservable() .map({ ViewState($0) }) .do(onNext: { [unowned self] viewState in guard viewState == .working else { return } self.movieCredits = self.creditRepository.movieCredits }) .bind(to: viewState) .disposed(by: disposeBag) // 1st call since KVO doesn't work in initalize parseData() } func refresh() { detailRepository.fetch() creditRepository.fetch() } } private extension MovieDetailViewModel { func parseData() { var newSections: [MovieDetailViewController.Section] = [.detail] // Only append if has cast or at least 1 director if !movieCredits.casts.isEmpty || movieCredits.crews.contains(where: { $0.isDirector }) { newSections.append(.credits) } var newRowsInSections: [MovieDetailViewController.Section: [MovieDetailViewController.Row]] = [:] for section in newSections { var rows: [MovieDetailViewController.Row] = [] switch section { case .detail: rows.append(contentsOf: [.backdrop, .title]) if !movieDetail.overview.isEmpty { rows.append(.summary) } case .credits: if !movieCredits.casts.isEmpty { rows.append(.casts) } if movieCredits.crews.contains(where: { $0.isDirector }) { rows.append(.director) } } newRowsInSections[section] = rows } sections = newSections rowsInSections = newRowsInSections } }
true
737fddeca740f03d8dc0cae1a8c4baf488793c90
Swift
thanhtuan44/AquaIGateIOS
/Employee/Product/ProductDetail/ViewDetailInfo.swift
UTF-8
2,788
2.578125
3
[]
no_license
// // TbvProductDetailInfo.swift // Employee // // Created by Thanh Tuan on 4/9/18. // Copyright © 2018 Thanh Tuan. All rights reserved. // import UIKit class ViewDetailInfo : UIView { required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(frame: CGRect, superView: UIView) { super.init(frame: frame); self.translatesAutoresizingMaskIntoConstraints = false superView.addSubview(self) } func setupDetailInfo(_ arrTitle: NSMutableArray) { var viewBindingsDict = [String: AnyObject]() var verticalLayout : String = "" verticalLayout += "V:|" if(arrTitle.count > 0) { for i in 0..<(arrTitle.count) { let title = arrTitle[i] as? String let vwTitle = ViewTitleWithNoteCircle.init(frame: CGRect.zero, superView: self) vwTitle.tag = i vwTitle.lblInfo.text = title self.addSubview(vwTitle) AutoLayoutCommon.setLayoutFullWidthSuperView(vwTitle) viewBindingsDict[String(format: "imv%d", i)] = vwTitle verticalLayout += String(format: "[imv%d(>=44)]", i) } } verticalLayout += "|" self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: verticalLayout, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewBindingsDict)) } } class ViewTitleWithNoteCircle : UIView { let lblInfo = UILabel.initUILableAutoLayout() let vwCircle = UIView.initUIViewAutoLayout() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(frame: CGRect, superView: UIView) { super.init(frame: frame); self.translatesAutoresizingMaskIntoConstraints = false superView.addSubview(self) addControl(superView: self) setupLayout(superView: self) } func addControl(superView: UIView){ superView.addSubview(lblInfo) superView.addSubview(vwCircle) vwCircle.backgroundColor = Utilities.UIColorFromRGB(Constant.COLOR_AQUA) lblInfo.numberOfLines = 0 vwCircle.layer.cornerRadius = 5 vwCircle.clipsToBounds = true } func setupLayout(superView: UIView){ AutoLayoutCommon.setLayoutFullHeightSuperView(lblInfo) AutoLayoutCommon.setLayoutHeightEqualWidthItSelf(vwCircle) AutoLayoutCommon.setLayoutCenterVerticalSuperView(vwCircle) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[vwCircle(==10)]-15-[lblInfo]-(==10@999)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["vwCircle":vwCircle,"lblInfo":lblInfo])) } }
true
ad645133e84c81780a881840acf8536acd50930e
Swift
brien84/iKinas
/Cinema/Shared/Views/GetterViews.swift
UTF-8
2,014
3.328125
3
[]
no_license
// // GetterViews.swift // Cinema // // Created by Marius on 2023-01-01. // Copyright © 2023 Marius. All rights reserved. // import SwiftUI /// Reads and writes the `frame` of a `View` into a binding. /// /// To use `FrameGetter`, add it to a `View` as a background using the `background` modifier. /// The `frame` of the surrounding view will be read and stored in the provided property. /// /// Example: /// /// struct SomeView: View { /// @State var frame: CGRect = CGRect() /// /// var body: some View { /// VStack { /// Text("Hello, World!") /// } /// .background(FrameGetter(frame: $frame)) /// } /// } struct FrameGetter: View { @Binding var frame: CGRect var body: some View { GeometryReader { proxy in self.makeView(proxy: proxy) } } func makeView(proxy: GeometryProxy) -> some View { DispatchQueue.main.async { frame = proxy.frame(in: .global) } return Color.clear } } /// Reads and writes the `safeAreaInsets` of a `View` into a binding. /// /// To use `SafeAreaGetter`, add it to a `View` as a background using the `background` modifier. /// The `safeAreaInsets` of the surrounding view will be read and stored in the provided property. /// /// Example: /// /// struct SomeView: View { /// @State var safeAreaInsets: EdgeInsets = EdgeInsets() /// /// var body: some View { /// VStack { /// Text("Hello, World!") /// } /// .background(SafeAreaGetter(frame: $frame)) /// } /// } struct SafeAreaGetter: View { @Binding var insets: EdgeInsets var body: some View { GeometryReader { proxy in self.makeView(proxy: proxy) } } func makeView(proxy: GeometryProxy) -> some View { DispatchQueue.main.async { insets = proxy.safeAreaInsets } return Color.clear } }
true
e5e0db6e19f63969b345d898ee0c0f09fb568d40
Swift
exRyusei1026/iOSVIPERSample
/iOSVIPERSample/module/detail/contract/DetailContract.swift
UTF-8
1,072
2.625
3
[ "MIT" ]
permissive
// // DetailContract.swift // iOSVIPERSample // // Created by 小林健人 on 2018/11/23. // Copyright © 2018 小林健人. All rights reserved. // import UIKit // MARK: Implement on ViewController protocol DetailView: class { var presenter: DetailPresentation! { get set } func showItem(_ item: Item) func showErrorPopup(message: String) } // MARK: Implement on Presenter protocol DetailPresentation: class { var view: DetailView? { get set } var interactor: DetailInteractorInput! { get set } var router: DetailWireframe! { get set } func updateView(id: String) } protocol DetailInteractorOutput: class { func didItemFetched(_ item: Item) func didFetchFailed(error: Error) } // MARK: Implement on Interactor protocol DetailInteractorInput: class { var output: DetailInteractorOutput! { get set } var repository: ItemRepository! { get set } func fetchItem(by id: String) } // MARK: Implement on Router protocol DetailWireframe: Wireframe { static func assembleModule(by itemID: String) -> UIViewController }
true
921a25d2220da59926dfe90f1c3e41c45b91b0c5
Swift
LittleJohnD/SwiftColourNamer
/SwiftColourNamer/ColourNamer.swift
UTF-8
849
2.65625
3
[]
no_license
// // ColourNamer.swift // SwiftColourNamer // // Created by John Dyer on 10/02/2015. // Copyright (c) 2015 John Dyer. All rights reserved. // import UIKit class ColourNamerEntry: ViewController { @IBOutlet weak var nameEntry: UITextField! weak var colourSelector: ViewController? var bgColour = UIColor() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = bgColour } func textFieldShouldReturn(nameEntry: UITextField) -> Bool { colourSelector?.colourLabel.text = nameEntry.text nameEntry.resignFirstResponder() dismissViewControllerAnimated(true, completion: nil) return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
21c372907a8076678f1bc3502e9266342fa45c28
Swift
peddamat/PDFKitApp
/PDFKitApp/ViewController5.swift
UTF-8
2,773
2.609375
3
[]
no_license
// // ViewController5.swift // PDFWatermarkApp // // Created by Imanou on 08/03/2018. // Copyright © 2018 Imanou. All rights reserved. // import UIKit import PDFKit class ViewController5: UIViewController { let pdfView = PDFView() let pdfDocument = PDFDocument(url: Bundle.main.url(forResource: "Document2", withExtension: "pdf")!)! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white pdfView.backgroundColor = .red pdfView.documentView?.backgroundColor = .green pdfView.usePageViewController(true, withViewOptions: nil) pdfView.document = pdfDocument view.addSubview(pdfView) pdfView.translatesAutoresizingMaskIntoConstraints = false pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true pdfView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true let addAnnotationButton = UIBarButtonItem(title: "Annotate", style: .plain, target: self, action: #selector(addAnnotationTapped2(_:))) navigationItem.rightBarButtonItem = addAnnotationButton } override func viewWillLayoutSubviews() { pdfView.autoScales = true } @objc func addAnnotationTapped(_ sender: UIBarButtonItem) { let bounds = CGRect(x: 10, y: 10, width: 100, height: 100) let annotation = PDFAnnotation(bounds: bounds, forType: .square, withProperties: nil) annotation.color = .red let border = PDFBorder() border.lineWidth = 2 annotation.border = border pdfDocument.page(at: 0)!.addAnnotation(annotation) } @objc func addAnnotationTapped2(_ sender: UIBarButtonItem) { let bounds = CGRect(x: 10, y: 10, width: 250, height: 100) let textFieldWidget = PDFAnnotation(bounds: bounds, forType: .widget, withProperties: nil) textFieldWidget.widgetFieldType = .text textFieldWidget.backgroundColor = .blue textFieldWidget.font = UIFont.systemFont(ofSize: 14) textFieldWidget.widgetStringValue = "Hello, World!" pdfDocument.page(at: 0)!.addAnnotation(textFieldWidget) } @objc func addAnnotationTapped3(_ sender: UIBarButtonItem) { let bounds = CGRect(x: 10, y: 10, width: 250, height: 100) let widget = PDFAnnotation(bounds: bounds, forType: .widget, withProperties: nil) widget.widgetFieldType = .signature pdfDocument.page(at: 0)!.addAnnotation(widget) } }
true
6d28e5ea1fd63e741cdbd3d59183cfabf720842e
Swift
eharrison/iOSCourse-AwesomePictures2
/AwesomePictures2/Model/ImageObject.swift
UTF-8
1,951
3
3
[]
no_license
// // ImageObject.swift // AwesomePictures // // Created by Evandro Harrison Hoffmann on 2/15/17. // Copyright © 2017 Evandro Harrison Hoffmann. All rights reserved. // import Foundation import AwesomeData class ImageObject: NSObject { var thumbnail: String? var lowResolution: String? var standardResolution: String? // MARK: - Class functions func name(){ } static func fetchImages(completed: ((_ images: [ImageObject])->Void)?){ _ = AwesomeRequester.performRequest("https://www.instagram.com/evandroharrison/media/") { (data) in if let jsonObject = AwesomeParser.jsonObject(data) { var images = [ImageObject]() if let items = jsonObject["items"] as? [[String: Any]] { for item in items { if let image = item["images"] as? [String: Any] { let imageObject = ImageObject() if let image = image["thumbnail"] as? [String: Any] { imageObject.thumbnail = AwesomeParser.stringValue(image, key: "url") } if let image = image["low_resolution"] as? [String: Any] { imageObject.lowResolution = AwesomeParser.stringValue(image, key: "url") } if let image = image["standard_resolution"] as? [String: Any] { imageObject.standardResolution = AwesomeParser.stringValue(image, key: "url") } images.append(imageObject) } } completed?(images) } } } } }
true
6d9f7f862ffe488cd6076e1449362e9417fb6c58
Swift
EliasPaulinoAndrade/Fishes
/Fishes/Grid.swift
UTF-8
954
3.140625
3
[]
no_license
// // Grid.swift // Peixes // // Created by Elias Paulino on 03/11/19. // Copyright © 2019 Elias Paulino. All rights reserved. // import Foundation class Grid { var gridArray: [[GridElement]] var numberOfColumns: Int { return gridArray.first?.count ?? 0 } var numberOfLines: Int { return gridArray.count } init(gridArray: [[GridElement]]) { self.gridArray = gridArray } func move(fish: FishProtocol, toPositionX positionX: Int, positionY: Int) { if let fishPositionY = fish.positionY, let fishPositionX = fish.positionX { self.gridArray[fishPositionY][fishPositionX] = .empty } fish.positionX = positionX fish.positionY = positionY self.gridArray[positionY][positionX] = .fish(fish) } func removeElement(fromPositionX positionX: Int, positionY: Int) { self.gridArray[positionY][positionX] = .empty } }
true
d03a10ee3c7f7285ab049325ee2ad2c9dc31e3ec
Swift
newboadki/Expensit
/Expenses/src/CoreDataPersistence/Sources/CoreDataPersistence/Stack Helpers/CoreDataStack.swift
UTF-8
1,189
2.515625
3
[]
no_license
// // CoreDataStack.swift // Expensit // // Created by Borja Arias Drake on 12/07/2020. // Copyright © 2020 Borja Arias Drake. All rights reserved. // import Foundation import CoreData public struct CoreDataStack { public static func context(_ completion: @escaping (Result<NSManagedObjectContext, Error>) -> ()) { let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let docsURL = documentsDirectory.appendingPathComponent("expensesDataBase.sqlite") let persistentContainer = NSPersistentContainer(name: "Expenses") persistentContainer.persistentStoreDescriptions = [NSPersistentStoreDescription(url: docsURL)] persistentContainer.loadPersistentStores() { (description, error) in if let error = error { completion(.failure(error)) return } completion(.success(persistentContainer.newBackgroundContext())) } } public static func model() -> NSManagedObjectModel { let url = Bundle.main.url(forResource: "Expenses", withExtension: "momd") return NSManagedObjectModel(contentsOf: url!)! } }
true
8cfe3500e1fe854d81f4226d37a1db37f9f4817d
Swift
tvds/nativeAppsIOS
/EindProject/EindProject/MedicationModel.swift
UTF-8
2,132
2.8125
3
[]
no_license
// // MedicationModel.swift // EindProject // // Created by Thomas Vanderschaeve on 27/12/16. // Copyright © 2016 Thomas Vanderschaeve. All rights reserved. // import Foundation import UIKit class MedicationModel { var medications = [Medication]() func setDummyData(){ medications = [ Medication(description:"Behandeling parkinson", name:"Akineton", image: UIImage(named: "Akineton")!), Medication(description:"antibioticum", name:"Amoxiclav teva", image: UIImage(named: "Amoxiclav teva")!), Medication(description:"Hypertensie", name:"Bisoprolol", image: UIImage(named: "Bisoprolol")!), Medication(description:"Spasmolytica, heft verkramping (spasmen) op in maag-darmkanaal, galwegen, urinewegen.", name:"Buscopan (oraal, I.M)"), Medication(description:"Antitrombotica/anticoagulantia. Antistolling, behandeling diverse cardiovasculaire problemen", name:"Clexane (subcutaan)"), Medication(description:"Behandeling Parkinson", name:"Corbilta", image: UIImage(named: "Corbilta")!), Medication(description:"Antibioticum", name:"Clamoxyl I.M"), Medication(description:"Opheffen van luchtwegvernauwing bij COPD", name:"Combivent unit dose"), Medication(description:"Anti-Alzheimer middelen", name:"Donepezil", image: UIImage(named: "Donepezil")!), Medication(description:"Krachtige pijnstiller", name:"Durogesic (pleister)"), Medication(description:"Antitrombotica", name:"Eliquis"), Medication(description:"Diarree", name:"Enterol") ] } var count: Int { return medications.count } func getMedication(at index: Int) -> (Medication) { guard index >= 0 && index < medications.count else { fatalError("Invalid index into MedicationModel: \(index)") } return medications[index] } func removeMedication(at index: Int) { guard index >= 0 && index < medications.count else { fatalError("Invalid index into MedicationModel: \(index)") } medications.remove(at: index) } }
true
f7f7914b68a1ac4dd72ffc7f5834c66dafc4dfa1
Swift
varxogre/LMCTest
/LMCTest/Application/View/StringExtension.swift
UTF-8
336
2.546875
3
[]
no_license
// // StringExtension.swift // LMCTest // // Created by сергей on 05.02.2021. // import Foundation //extension String { // func prepareWhitespace() -> String { // return self.components(separatedBy: .whitespacesAndNewlines) // .filter { !$0.isEmpty } // .joined(separator: "%20") // } //}
true
5f21de8fb8d39244c6fec92cdf994db595bd99ff
Swift
hunterknepshield/SwiftJSON
/JSONTests/CustomStringConvertibleTest.swift
UTF-8
675
3.109375
3
[]
no_license
// // CustomStringConvertibleTest.swift // JSON // // Created by Hunter Knepshield on 11/28/16. // Copyright © 2016 Hunter Knepshield. All rights reserved. // import XCTest @testable import JSON class CustomStringConvertibleTest: XCTestCase { func testExample() { let array = JSON(rawJson: "[1, 2, 3]")! print(array) // The string should indeed look like this let object = JSON(rawJson: "{" + "\"one\": 1," + "\"two\": 2," + "\"three\": {" + "\"one\": 1," + "\"two\": [1, 2, 3]," + "\"three\": {" + "\"array\": [{" + "\"1\": 1" + "}, 2, {" + "\"3\": 3" + "}]" + "}" + "}" + "}")! print(object) } }
true
6496edaf930cb11009d9591db6928b0b4447f143
Swift
langyx/Maze-AStar-Pathfinding
/MazProject/Map/Map.swift
UTF-8
1,406
3.140625
3
[]
no_license
// // Map.swift // MazProject // // Created by Yannis Lang on 31/10/2021. // import Foundation struct Map { let boxs: [[Box]] let lineLenght: Int var lineHeight:Int { boxs.count } init(_ data: String) { (boxs, lineLenght) = Map.parse(from: data) } } extension Map { static func parse(from data: String) -> ([[Box]], Int) { let boxs = data.lines.map { line in line.map { Box(rawValue: Int(String($0)) ?? Box.empty.rawValue)! } } let max = boxs.max(by: { (a, b) -> Bool in return a.count < b.count }) .map { $0.count } ?? 0 return (boxs.map { boxLine -> [Box] in let lengthDiff = max - boxLine.count return boxLine + (lengthDiff > 0 ? [Box](repeating: Box(rawValue: Box.wall.rawValue)!, count: lengthDiff) : []) }, max) } } extension Map { enum Box: Int { case empty, wall } func box(for point: Point) -> Box? { boxs[safe: point.y]?[safe: point.x] } } extension Map { static var dataTestMap = """ 1111111111111111 1000000000000001 1001111111010001 1001000000000001 1001000000000001 1001000000000001 1001000000000001 1001000000000001 1000000000000001 1111111111111111 """ static var testMap = Map(Map.dataTestMap) }
true
3319ef4038cf75a1e198002ab8d15968c132e382
Swift
3adel/derSatz-iOS
/Texture/UI/Utility/LoaderShowable.swift
UTF-8
791
2.765625
3
[]
no_license
// // LoaderShowable.swift // Texture // // Created by Halil Gursoy on 07.01.18. // Copyright © 2018 Texture. All rights reserved. // import UIKit import WebKit protocol WebLoaderShowable: WKNavigationDelegate { var activityIndicator: UIActivityIndicatorView? { get set } var view: UIView! { get set } func showActivityIndicator() func hideActivityIndicator() } extension WebLoaderShowable where Self: UIViewController { func showActivityIndicator() { activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) view.addSubview(activityIndicator!) activityIndicator?.centerInSuperview() activityIndicator?.startAnimating() } func hideActivityIndicator() { activityIndicator?.stopAnimating() } }
true
1b5f42b5070e9e88044c7af5e8d35714f5376639
Swift
cuongtvwru/CalculatorApp
/LoginAcazia/StartController/LoginVC.swift
UTF-8
1,441
2.5625
3
[]
no_license
// // StartViewController.swift // LoginAcazia // // Created by Home on 4/2/19. // Copyright © 2019 Home. All rights reserved. // import UIKit class StartViewController: UIViewController { @IBOutlet var pgView: UIProgressView! var countTimer: Timer! let couterTotal: Float = 5 var counterCurrent: Float = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { timer in self.counterCurrent += 1 / (self.couterTotal * 100) self.pgView.setProgress(self.counterCurrent, animated: true) if self.counterCurrent >= 1 { let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginVC") as? LoginViewController self.navigationController?.pushViewController(vc!, animated: true) timer.invalidate() } }) } /* // 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. } */ }
true
903b2ecc962e673931712f91b452f320929bf975
Swift
leonljy/Mugic
/Mugic/Instruments/Drum.swift
UTF-8
2,342
2.65625
3
[]
no_license
// // Drum.swift // Mugic // // Created by Jeong-Uk Lee on 2018. 3. 21.. // Copyright © 2018년 Jeong-Uk Lee. All rights reserved. // import Foundation import AudioKit enum DrumKit: Int { case Crash = 0 case Ride case Kick case RimShot case TomHi case TomMid case TomLow case Snare case HihatOpened case HihatClosed } class Drum: BeatInstrument { let kick = AKAppleSampler() let snare = AKAppleSampler() let rimShot = AKAppleSampler() let ride = AKAppleSampler() let hihatOpened = AKAppleSampler() let hihatClosed = AKAppleSampler() let crash = AKAppleSampler() let tomHi = AKAppleSampler() let tomMid = AKAppleSampler() let tomLow = AKAppleSampler() let drumkit: [AKAppleSampler] override init() { try? self.kick.loadWav("Sounds/Drum/Kick") try? self.snare.loadWav("Sounds/Drum/Snare") try? self.rimShot.loadWav("Sounds/Drum/RimShot") try? self.ride.loadWav("Sounds/Drum/Ride") try? self.hihatOpened.loadWav("Sounds/Drum/HatsOpen") try? self.hihatClosed.loadWav("Sounds/Drum/HatsClosed") try? self.crash.loadWav("Sounds/Drum/Crash") try? self.tomHi.loadWav("Sounds/Drum/TomHi") try? self.tomMid.loadWav("Sounds/Drum/TomMid") try? self.tomLow.loadWav("Sounds/Drum/TomLow") self.drumkit = [self.kick, self.snare, self.rimShot, self.ride, self.hihatClosed, self.hihatOpened, self.crash, self.tomLow, self.tomMid, self.tomHi] super.init() // self.numberOfPolyphonic = 10 } func play(_ drumkit: DrumKit) { switch drumkit { case .Kick: try? self.kick.play() case .Snare: try? self.snare.play() case .RimShot: try? self.rimShot.play() case .Ride: try? self.ride.play() case .HihatClosed: try? self.hihatClosed.play() case .HihatOpened: try? self.hihatOpened.play() case .Crash: try? self.crash.play() case .TomHi: try? self.tomHi.play() case .TomMid: try? self.tomMid.play() case .TomLow: try? self.tomLow.play() } } }
true
dbc99e1c9e7ff2d61c75b9408ad014e919b5f858
Swift
Optimal-Joke/Dine-Out-of-Ten
/Dine Out of Ten/Views/UIAssets/Home.swift
UTF-8
3,584
3.0625
3
[]
no_license
// // Home.swift // Home // // Created by Hunter Holland on 8/2/21. // import SwiftUI struct ContentView: View { var body: some View { Home() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } struct Home: View { @State private var showSheet = false var body: some View { NavigationView { Button { self.showSheet = true } label: { Text("Present Sheet") } .navigationTitle("Half Modal Sheet") .halfSheet(showSheet: $showSheet) { // Put your sheet view here ZStack { Color.orange VStack { Text("This is inside a sheet!") .font(.title.bold()) Button { self.showSheet = false } label: { Text("Dismiss Sheet") } } } .ignoresSafeArea() } onEnd: { print("Sheet dismissed") } } } } // Custom Half Sheet Modifier.... extension View { // Binding Show Variable... func halfSheet<SheetView: View>(showSheet: Binding<Bool>, @ViewBuilder sheetView: @escaping () -> SheetView, onEnd: @escaping () -> Void = { } ) -> some View { return self .background( HalfSheetHelper(sheetView: sheetView(), showSheet: showSheet, onEnd: onEnd) ) } } struct HalfSheetHelper<SheetView: View>: UIViewControllerRepresentable { var sheetView: SheetView @Binding var showSheet: Bool var onEnd: () -> Void let controller = UIViewController() func makeCoordinator() -> Coordinator { return Coordinator(parent: self) } func makeUIViewController(context: Context) -> UIViewController { controller.view.backgroundColor = .clear return controller } func updateUIViewController(_ uiViewController: UIViewController, context: Context) { if showSheet { // present modal view let sheetController = CustomHostingController(rootView: sheetView) sheetController.presentationController?.delegate = context.coordinator uiViewController.present(sheetController, animated: true) } else { uiViewController.dismiss(animated: true) } } // On dismiss... class Coordinator: NSObject, UISheetPresentationControllerDelegate { var parent: HalfSheetHelper init(parent: HalfSheetHelper) { self.parent = parent } func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { parent.showSheet = false parent.onEnd() } } } class CustomHostingController<Content: View>: UIHostingController<Content>{ override func viewDidLoad() { // view.backgroundColor = .clear // setting presentation controller properties... if let presentationController = presentationController as? UISheetPresentationController { presentationController.detents = [.medium(), .large()] presentationController.prefersGrabberVisible = true presentationController.preferredCornerRadius = 35 } } }
true
3581a726a3a2089eb80560c86c8334de9a49b157
Swift
furqanmk/Silofit
/Silofit/Modules/Onboarding/OnboardingViewController.swift
UTF-8
2,428
2.65625
3
[]
no_license
import UIKit final class OnboardingViewController: UIViewController { // MARK: Properties let viewOutput: OnboardingViewOutput private let stackSpacing: CGFloat = 16 // MARK: Initalizers init(viewOutput: OnboardingViewOutput) { self.viewOutput = viewOutput super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() viewOutput.viewIsReady() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } // MARK: View private lazy var signInButton: UIButton = { Button(text: "Sign in", style: .solid, selector: #selector(onSignInClicked)) }() private lazy var joinNowButton: UIButton = { Button(text: "Join now", style: .border, selector: #selector(onJoinNowClicked)) }() private lazy var stackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [signInButton, joinNowButton]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.spacing = stackSpacing stackView.axis = .vertical return stackView }() private func setupView() { view.backgroundColor = Theme.light view.addSubview(stackView) let margins = view.readableContentGuide NSLayoutConstraint.activate([ stackView.bottomAnchor.constraint(equalTo: margins.bottomAnchor), stackView.leadingAnchor.constraint(equalTo: margins.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: margins.trailingAnchor) ]) } @objc private func onSignInClicked(_ button: UIButton) { viewOutput.didClickSignIn() } @objc private func onJoinNowClicked(_ button: UIButton) { viewOutput.didClickJoinNow() } } // MARK: Presenter To View Protocol extension OnboardingViewController: OnboardingViewInput { func setupInitialState() { setupView() } }
true
7deb3ece71cb8f28c4dbf1d9d2eb731ea866dd84
Swift
mussaiin/Swift
/SplitViewWebsiteApp/SplitViewWebsiteApp/SiteViewController.swift
UTF-8
2,442
2.6875
3
[]
no_license
// // LoadSiteViewController.swift // WebBrowser04GH // // Created by Darkhan on 30.01.18. // Copyright © 2018 SDU. All rights reserved. // import UIKit class SiteViewController: UIViewController, UIWebViewDelegate { var website : String?w var index: Int? var webTitle: String? var previousViewController : WebsitesTableViewController? var startingSite = "https://google.com" var added: Bool? = false @IBOutlet weak var webView: UIWebView! @IBOutlet weak var myIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() myIndicator.layer.opacity = 0 myIndicator.startAnimating() if let nonOptionalWebsite = website{ let site_url = URL(string: nonOptionalWebsite) webView.loadRequest(URLRequest(url: site_url!)) myIndicator.layer.opacity = 1 webView.delegate = self } let tapGesture = UITapGestureRecognizer(target: self, action: #selector(threeTaps)) tapGesture.numberOfTapsRequired = 3 webView.addGestureRecognizer(tapGesture) // Do any additional setup after loading the view. } @objc func threeTaps() { if added! { previousViewController?.favourites.remove(at:((previousViewController?.favourites.count)!-1)) previousViewController?.tableView.reloadData() added = false } else{ let currentURL = webView.request?.url?.absoluteString previousViewController?.favourites.append(Website.init(webTitle!, currentURL!)) previousViewController?.tableView.reloadData() added = true } } 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. } */ func webViewDidFinishLoad(_ webView: UIWebView) { myIndicator.stopAnimating() myIndicator.hidesWhenStopped = true navigationController?.popViewController(animated: true) } }
true
44a64e915e4ff1b1621cd7e73f2b14575a407036
Swift
Hitesh136/Swift-Ds
/Algorithms/Console/String/LeetCode_1221.swift
UTF-8
615
3.078125
3
[]
no_license
// // LeetCode_1221.swift // Console // // Created by Hitesh Agarwal on 17/05/22. // import Foundation // https://leetcode.com/problems/split-a-string-in-balanced-strings/ // 16 Aug 2022: Round 2 class LeetCode_1221 { func balancedStringSplit(_ s: String) -> Int { var stack = [Character]() var l = 0 var r = 0 var count = 0 for c in s { if c == "R" { r += 1 } else if c == "L" { l += 1 } if r == l { count += 1 } } return count } }
true
b57628f76c6eaa189c3fd0f50b829395d5abb4d7
Swift
victis23/Inventory-Tracker-Iphone-App
/IphoneInventoryTracker/PaperCalculatorModules/Controller/CostOfSpentGoodsTableViewController.swift
UTF-8
3,591
2.8125
3
[]
no_license
// // CostOfSpentGoodsTableViewController.swift // IphoneInventoryTracker // // Created by Scott Leonard on 11/9/19. // Copyright © 2019 Scott Leonard. All rights reserved. // import UIKit /// Updates and displays the total cost of goods for each item in inventory. class CostOfSpentGoodsTableViewController: UITableViewController, CostTrackerDelegate { //MARK: Local Data types //Sections used for DataSource. enum Section { case main } //KEYS struct Keys { static var uniqueCellIdentifer = "cell" static var segueKey = "addStock" } //MARK: Class Properties var dataSource : DataSource! var localStockArray : [Stock]? = [] { didSet { createSnapShot() } } var inventoryIsEmpty: Bool = false //MARK: State override func viewDidLoad() { super.viewDidLoad() setupDataSource() retrieveCostInformation() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) createSnapShot() } //MARK: Methods /// Decodes list of stocks from disk and assigns to local collection. /// - Note: Object method returns a generic <T: Hashable>. func retrieveCostInformation(){ // Method returns a generic that needs to be specified. localStockArray = Stock.decode() as [Stock]? // If the user has not added inventory to their list yet a default Stock value is assigned to tableview. if localStockArray == nil { let nilStock = Stock() localStockArray = [nilStock] inventoryIsEmpty = true } } //MARK: - TableView DataSource & Delegate Methods. func setupDataSource(){ dataSource = DataSource(tableView: tableView, cellProvider: { (tableView, indexPath, stock) -> UITableViewCell? in let cell = tableView.dequeueReusableCell(withIdentifier: Keys.uniqueCellIdentifer, for: indexPath) as! CostTableViewCell // This is executed if user has not added any inventory to their list. guard stock.name != nil else { cell.nameLabel.text = stock.errorMessage cell.costLabel.text = "ADD" cell.costLabel.textColor = .systemBlue return cell } cell.nameLabel.text = stock.name guard let spent = stock.spent else {fatalError()} // Adds two decimal points to value. $0.00 cell.costLabel.text = "$\(String(format: "%.2f", spent))" return cell }) } func createSnapShot(){ guard let stock = localStockArray else {return} var snapShot = NSDiffableDataSourceSnapshot<Section,Stock>() snapShot.appendSections([.main]) snapShot.appendItems(stock, toSection: .main) dataSource?.apply(snapShot, animatingDifferences: true, completion: nil) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 90 } class DataSource : UITableViewDiffableDataSource<Section,Stock> { override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { default: return "Total Cost Of Item" } } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch inventoryIsEmpty { case true: performSegue(withIdentifier: Keys.segueKey, sender: nil) default: break } } } extension CostOfSpentGoodsTableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Keys.segueKey { let navigationController = segue.destination as! UINavigationController let controller = navigationController.topViewController as! InventoryTracker_CollectionViewController controller.costDelegate = self controller.passthroughSegue() } } }
true
a2a5e1d1fd7dfdeae401832d9de1d66768196aca
Swift
AlexNorcross/Testing
/Testing/Meal.swift
UTF-8
282
2.875
3
[]
no_license
// // Meal.swift // Testing // // Created by Alexandra Norcross on 6/21/16. // Copyright © 2016 Alexandra Norcross. All rights reserved. // import Foundation struct Meal { var cost: Float! var tipPercent: Float! var tip: Float { get { return cost * tipPercent / 100 } } }
true
ab0ef662d8ec9da02f103b4a77463d14bfbc7c1f
Swift
JMatharu/Data-Structure-and-Algotithm
/Youtube/Tree/Binary Tree Implementation.swift
UTF-8
497
3.375
3
[]
no_license
public class TreeNode<T> { public var val: T public var left: TreeNode? public var right: TreeNode? public init(_ val: T) { self.val = val; self.left = nil; self.right = nil; } public init(_ val: T, _ left: TreeNode?, _ right: TreeNode?) { self.val = val self.left = left self.right = right } } let node1 = TreeNode(1) let node2 = TreeNode(2) let head = TreeNode(0, node1, node2) head.val // 0 head.left?.val // 1 head.right?.val // 2
true
0d0420c59dae17f45e87d8c92d4700269f25d0f6
Swift
maniharshaanne/chefxdoor
/ChefXDoor/ChefXDoor/TableViewCells/CXDMealDetailTableViewCell.swift
UTF-8
1,875
2.53125
3
[]
no_license
// // CXDMealDetailTableViewCell.swift // ChefXDoor // // Created by Anne, Mani on 9/22/18. // Copyright © 2018 ChefXDoor. All rights reserved. // import Foundation import UIKit import Kingfisher class CXDMealDetailTableViewCell: UITableViewCell { @IBOutlet public weak var profileImageView:UIImageView! @IBOutlet public weak var ratingImageView:UIImageView! @IBOutlet public weak var titleLabel:UILabel! @IBOutlet public weak var detailLabel:UILabel! public func updateCell(mealReview : CXDMealReview) { profileImageView.kf.cancelDownloadTask() if let imageUrl = mealReview.userPhotoUrl { let resource = ImageResource(downloadURL: URL.init(string: imageUrl)!) profileImageView.layer.cornerRadius = profileImageView.frame.size.width/2 profileImageView.clipsToBounds = true profileImageView.kf.setImage(with: resource) } if let modifiedDate = mealReview.timeModified { var dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" var modifiedDateSplitString = modifiedDate.split(separator: "T").first! var modifiedSplitDate = dateFormatter.date(from: String(modifiedDateSplitString)) dateFormatter.dateFormat = "MM/dd/yy" var modifiedDateString = dateFormatter.string(from: modifiedSplitDate!) titleLabel.text = mealReview.username! + " . " + modifiedDateString if let image = CXDUtility.sharedUtility.imageFor(rating: (mealReview.rating?.intValue)!) as? UIImage { ratingImageView.image = image.withRenderingMode(.alwaysTemplate) ratingImageView.tintColor = CXDAppearance.primaryColor() } } detailLabel.text = mealReview.message } }
true
e68b8943a459cc95a28b00e6b67d681d33a76f7a
Swift
intere/scroggle
/Scroggle/Common/Extensions/Font.swift
UTF-8
570
2.9375
3
[ "MIT" ]
permissive
// // Font.swift // Scroggle // // Created by Eric Internicola on 10/21/17. // Copyright © 2017 Eric Internicola. All rights reserved. // import UIKit extension UIFont { /// Scroggle font structure, used as a namespace struct Scroggle { static let defaultFontName = "Chalkduster" /// Gives you the default font of the provided size /// /// - Parameter size: The size of the font you would like static func defaultFont(ofSize size: CGFloat) -> UIFont? { return UIFont(name: defaultFontName, size: size) } } }
true
f85eb4eb480a4f25ff343a2421a8b0230b77a864
Swift
mikekozub/movies
/movieDatabase/Classes/ApiManager.swift
UTF-8
1,032
2.796875
3
[]
no_license
// // ApiManager.swift // movieDatabase // // Created by Michael Kozub on 9/10/19. // Copyright © 2019 Michael Kozub. All rights reserved. // import UIKit class APIManager { func loadJsonFromUrl() -> Data? { do { let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=a020691c4cf21a30210d62ca7b841e5a")! let data = try Data(contentsOf: url) print(data) return data } catch { print(error) } return nil } func deserializeData(loadedData: Data, onCompletion: @escaping (_ toilets: [MovieDataModel]) -> Void){ DispatchQueue.global().async { do { let decoder = JSONDecoder() let moviesDecoded = try decoder.decode(ApiResponse.self, from: loadedData) DispatchQueue.main.async { onCompletion(moviesDecoded.results) } } catch { print(error) } } } }
true
9f5ac90d5a19fff21bacf076e9ed55c4954966d4
Swift
quantumOrange/ChessEngine
/Sources/ChessEngine/ChessLogic/ValidChessMoves.swift
UTF-8
21,346
3.15625
3
[]
no_license
// // ValidChessMoves.swift // Chess // // Created by david crooks on 14/09/2019. // Copyright © 2019 david crooks. All rights reserved. // import Foundation public func validate(chessboard:Chessboard, move:Move) -> ChessMove? { guard let chessMove = ChessMove.createMove(from: move.from.int8Value, to: move.to.int8Value ,on:chessboard) else { return nil } return validate(chessboard: chessboard, move: chessMove) } func validate(chessboard:Chessboard, move:ChessMove) -> ChessMove? { guard let thePieceToMove = chessboard[move.from] else { //You can't move nothing return nil } if !isYourPiece(chessboard: chessboard, move: move) { return nil } if let thePieceToCapture = chessboard[move.to] { if thePieceToMove.player == thePieceToCapture.player { //you can't capture your own piece return nil } } func primaryMoveIsEqual(lhs:ChessMove,rhs:ChessMove) -> Bool { // Equal up to auxillary move (which is ignored) // User only indicates the primary move. return (lhs.from == rhs.from) && (lhs.to == rhs.to) } //return validMoves(chessboard: chessboard).contains(where: {primaryMoveIsEqual(lhs: $0, rhs: move)}) return validMoves(chessboard: chessboard).first(where: {primaryMoveIsEqual(lhs: $0, rhs: move)}) } func isValid(move:Move, on board:Chessboard) -> Bool { guard let chessMove = ChessMove.createMove(from: move.from.int8Value, to: move.to.int8Value, on: board,updateCasteleState: true) else { return false } return isValid(move: chessMove, on: board) } func isValid(move:ChessMove, on board:Chessboard) -> Bool { validMoves(chessboard:board).contains( where:{$0.from == move.from && $0.to == move.to}) } func validMoves(chessboard:Chessboard) -> [ChessMove] { var moves = uncheckedValidMoves(chessboard: chessboard) .filter { !isInCheck(chessboard:apply(move: $0, to:chessboard ), player: chessboard.whosTurnIsItAnyway) } moves.append(contentsOf: validCastles(board: chessboard)) return moves } /* Not checked for check! */ func uncheckedValidMoves(chessboard:Chessboard) -> [ChessMove] { var moves:[ChessMove] = [] /* for square in chessboard.squares { moves += validMoves(chessboard: chessboard, for: square) } */ let range:Range<Int8> = 0..<64 for square in range { // moves += validMoves(chessboard: chessboard, for: square) moves += validMoves(chessboard: chessboard, square: square) } return moves } func isInCheck(chessboard:Chessboard, player:PlayerColor) -> Bool { var board = chessboard guard let kingSquare:ChessboardSquare = board.squares(with: ChessPiece(player: player, kind:.king,id:-1)).first else { return false } // guard let kingSquare:ChessboardSquare = board.squares(with: ChessPiece(player: player, kind:.king,id:-1)).first else { fatalError() } if player == board.whosTurnIsItAnyway { //If we are looking to see if the current players king is in check, we need the other players moves //So we flip player with a null move //board = apply(move:ChessMove.nullMove, to: board) board.toggleTurn() } let enemyMoves = uncheckedValidMoves(chessboard:board) let movesThatAttackTheKing = enemyMoves.filter { $0.to.chessboardSquare == kingSquare } return !movesThatAttackTheKing.isEmpty } func isControlled(square:ChessboardSquare, by player:PlayerColor, on chessboard:Chessboard) -> Bool { var board = chessboard //guard let kingSquare:ChessboardSquare = board.squares(with: ChessPiece(player: player, kind:.king,id:-1)).first else { fatalError() } if player != board.whosTurnIsItAnyway { //If we are looking to see if the current players square is in check, we need the other players moves //So we flip player with a null move //board = apply(move:ChessMove.nullMove, to: board) board.toggleTurn() } let playerMoves = uncheckedValidMoves(chessboard:board) let movesThatAttackTheSquare = playerMoves.filter { $0.to.chessboardSquare == square } return !movesThatAttackTheSquare.isEmpty } //TODO: clean this up . Make valid move internal public func validMoves(chessboard:Chessboard, square origin:ChessboardSquare, includeCastles:Bool = false) -> [ChessMove] { validMoves(chessboard:chessboard, square:origin.int8Value, includeCastles:includeCastles) } func validMoves(chessboard:Chessboard, square origin:Int8, includeCastles:Bool = false) -> [ChessMove] { guard let piece = chessboard[origin], piece.player == chessboard.whosTurnIsItAnyway else { return [] } switch piece.kind { case .pawn: return validPawnMoves(board: chessboard, square:origin ) case .knight: return validKnightMoves(board: chessboard, square:origin) case .bishop: return validBishopMoves(board: chessboard, square: origin) case .rook: return validRookMoves(board: chessboard, square:origin) case .queen: return validQueenMoves(board: chessboard, square:origin) case .king: var kingMoves = validKingMoves(board: chessboard, square: origin) if( includeCastles ) { kingMoves += validCastles(board: chessboard ) } return kingMoves } } func getAllMoves(on board:Chessboard, from square:ChessboardSquare, in direction:Direction)->[ChessMove]{ return getAllMoves(on:board,from:square,currentSquare:square, in:direction) } func getAllMoves(on board:Chessboard, from origin:ChessboardSquare , currentSquare square:ChessboardSquare, in direction:Direction) -> [ChessMove] { if let toSquare = square.getNeighbour(direction) , let mv = makeMove(board: board, from:origin , to: toSquare) { if let piece = board[toSquare], piece.player != board.whosTurnIsItAnyway { //This is an enemy piece, which we can take, but we can't go any further in this direction, so we terminate here. return [mv] } return getAllMoves(on:board,from:origin,currentSquare:toSquare, in:direction) + [mv] } else { // We cannot go any further in this direction, either becuase we have reached the edge of the board, // or because one of our own pieces is in the way. return [] } } func makeMove(board:Chessboard, from:ChessboardSquare, to:ChessboardSquare) -> ChessMove? { guard board.whosTurnIsItAnyway != board[to]?.player else { return nil } return ChessMove.createMove(from: from.int8Value, to: to.int8Value, on:board) } /* func makePawnForwardMove(board:Chessboard, from:ChessboardSquare, to:ChessboardSquare) -> ChessMove? { //Pawns cannot take moving forward, so "to" square must be empty guard let player = board[from]?.player, board[to] == nil, let move = ChessMove.createMove(from: from.int8Value, to: to.int8Value,on:board) else { return nil } return promotePawnIfValid(move:move, player:player,board:board) } func promotePawnIfValid(move:ChessMove,player:PlayerColor, board:Chessboard) -> ChessMove { let farRank = (player == .white ) ? ChessRank._8 : ChessRank._1 if move.to.rank == Int8(farRank.rawValue) { if let prometedMove = ChessMove.createMove(from:move.from,to:move.to,on:board, promote:.queen) { return prometedMove } } return move } func makePawnTakingdMove(board:Chessboard, from:ChessboardSquare, to:ChessboardSquare?) -> ChessMove? { //Pawns can only take diagonaly, so "to" square must contain an enemy piece guard let to = to, let piece = board[to], let player = board[from]?.player, board.whosTurnIsItAnyway != piece.player, let move = ChessMove.createMove(from: from.int8Value, to: to.int8Value,on:board) else { return nil } return promotePawnIfValid(move:move, player:player, board: board) } */ func enPassant(board:Chessboard, square origin:Int8)->ChessMove? { return ChessMove(enPassant:origin, on: board) } func validPawnMoves(board:Chessboard, square origin:Int8) -> [ChessMove] { var destinationSqs:[Int8] = [] // let origin = square.int8Value let rank = origin.rank let file = origin.file // rank + 1 -> +1 // file + 1 -> +8 // sq = 8 * file + rank switch board.whosTurnIsItAnyway { case .white: let moveForwardOne = origin &+ 1 if board[moveForwardOne] == nil { destinationSqs.append(moveForwardOne) if rank == 1 { let moveForwardTwo = moveForwardOne &+ 1 if board[moveForwardTwo] == nil { destinationSqs.append(moveForwardTwo ) } } } if file > 0 { let takeLeft = origin &- 7 //( -8 file, +1 rank ) if board[takeLeft]?.player == .black { destinationSqs.append(takeLeft ) } } if file < 7 { let takeRight = origin &+ 9 //( +8 file, +1 rank ) if board[takeRight]?.player == .black { destinationSqs.append(takeRight) } } case .black: let moveForwardOne = origin &- 1 if board[moveForwardOne] == nil { destinationSqs.append(moveForwardOne) if rank == 6 { let moveForwardTwo = moveForwardOne &- 1 if board[moveForwardTwo] == nil { destinationSqs.append(moveForwardTwo ) } } } if file > 0 { let takeLeft = origin &- 9 //( -8 file, -1 rank ) if board[takeLeft]?.player == .white { destinationSqs.append(takeLeft ) } } if file < 7 { let takeRight = origin &+ 7 //( +8 file, -1 rank ) if board[takeRight]?.player == .white { destinationSqs.append(takeRight) } } } var moves = destinationSqs .compactMap{ ChessMove.createMove(from: origin, to: $0, on: board ) } if let enPassant = enPassant(board: board, square: origin){ moves.append( enPassant) } // TODO: pawn promotion return moves } func validKnightMoves(board:Chessboard, square origin:Int8) -> [ChessMove] { /* 8 . * . * . . . . 7 * . . . * . . . 6 . . ♘ . . . . . 5 * . . . * . . . 4 . * . * * . * . 3 . . . * . . . * 2 . . . . . ♞ . . 1 . . . * . . . ♜ a b c d e f g h //"b4" , "a5","d4","e5", "a7","b8","d8", "e7" */ var destinationSqs:[Int8] = [] // let origin = square.int8Value let rank = origin.rank let file = origin.file if rank < 7 { // rank + 1 -> +1 if file < 6 { // file + 2 -> +16 destinationSqs.append( origin &+ 17 ) } if file > 1 { // file -2 -> -16 destinationSqs.append( origin &- 15 ) } if rank < 6 { // rank + 2 -> +2 if file < 7 { // file + 1 -> +8 destinationSqs.append( origin &+ 10 ) } if file > 0 { // file - 1 -> -8 destinationSqs.append( origin &- 6 ) } } } if rank > 0 { // rank - 1 -> -1 if file < 6 { // file + 2 -> +16 destinationSqs.append( origin &+ 15 ) } if file > 1 { // file -2 -> -16 destinationSqs.append( origin &- 17 ) } if rank > 1 { // rank - 2 -> -2 if file < 7 { // file + 1 -> +8 destinationSqs.append( origin &+ 6 ) } if file > 0 { // file - 1 -> -8 destinationSqs.append( origin &- 10 ) } } } return destinationSqs .filter { board[$0]?.player != board.whosTurnIsItAnyway } .compactMap{ ChessMove.createMove(from: origin, to: $0, on: board ) } } func validKingMoves(board:Chessboard, square origin:Int8) -> [ChessMove] { var destinationSqs:[Int8] = [] // let origin = square.int8Value let rank = origin.rank let file = origin.file //topLeft // - 7 // increase rank (+1) , decrease file (-8) // n = min ( 7 - rank , file ) //topRight // + 9 // increase rank and file // n = min ( 7 - rank , 1-file ) //bottomLeft // - 9 // decrease rank and file // n = min ( rank , file ) //bottomRight // + 7 // decrease rank (-1) , increase file (+8) // n = min ( rank , 1 - file ) /* 8 . . . . . . . . 7 . * * * . . . . 6 . * ♔ * . . . . 5 . * * * . . . . 4 . . . . . . . . 3 . . . . . . . . 2 . . . . . ♟ * ♙ 1 . . . . . * ♚ * a b c d e f g h */ //above if rank < 7 { destinationSqs.append( origin &+ 1 ) // top +1 if file > 0 { //let sq = origin - 7 destinationSqs.append( origin &- 7 ) // top left } if file < 7 { // let sq = destinationSqs.append( origin &+ 9 ) // top right } } //below if rank > 0 { destinationSqs.append( origin &- 1 ) // bottom -1 if file > 0 { destinationSqs.append( origin &- 9 ) // bottom left } if file < 7 { destinationSqs.append( origin &+ 7 ) // bottom right } } //middle if file > 0 { destinationSqs.append( origin &- 8 ) // bottom left } if file < 7 { destinationSqs.append( origin &+ 8 ) // bottom right } return destinationSqs .filter { board[$0]?.player != board.whosTurnIsItAnyway } .compactMap{ ChessMove.createMove(from: origin, to: $0, on: board , updateCasteleState: true) } } func validBishopMoves(board:Chessboard, square origin:Int8) -> [ChessMove] { var destinationSqs:[Int8] = [] //topLeft // - 7 // increase rank (+1) , decrease file (-8) // n = min ( 7 - rank , file ) //topRight // + 9 // increase rank and file // n = min ( 7 - rank , 1-file ) //bottomLeft // - 9 // decrease rank and file // n = min ( rank , file ) //bottomRight // + 7 // decrease rank (-1) , increase file (+8) // n = min ( rank , 1 - file ) var i = origin let rank:Int8 = origin.rank let file:Int8 = origin.file let inv_rank = 7 &- rank let inv_file = 7 &- file var n_moves = min(rank, inv_file) var n = 0 while n < n_moves { i &+= 7 n &+= 1 // rank = i.rank // file = i.file // print(i) if let piece = board[i] { if piece.player != board.whosTurnIsItAnyway { // print(i) destinationSqs.append(i) } break } // print(i) destinationSqs.append(i) //assert( i >= 0 && i < 64 ) } // while n < n_moves //while rank != 0 && rank != 7 && file != 0 && file != 7 i = origin n_moves = min(inv_rank, file) n = 0 while n < n_moves { i &-= 7 n &+= 1 // rank = i.rank // file = i.file // print(i) if let piece = board[i] { if piece.player != board.whosTurnIsItAnyway { // print(i) destinationSqs.append(i) } break } // print(i) destinationSqs.append(i) //assert( i >= 0 && i < 64 ) } //while n < n_moves //while rank != 0 && rank != 7 && file != 0 && file != 7 i = origin n_moves = min(inv_rank, inv_file) n = 0 while n < n_moves { i &+= 9 n &+= 1 // rank = i.rank // file = i.file // print(i) if let piece = board[i] { if piece.player != board.whosTurnIsItAnyway { // print(i) destinationSqs.append(i) } break } // print(i) destinationSqs.append(i) //assert( i >= 0 && i < 64 ) } // while n < n_moves //while rank != 0 && rank != 7 && file != 0 && file != 7 i = origin n_moves = min(rank, file) n = 0 while n < n_moves { i &-= 9 n &+= 1 //rank = i.rank // file = i.file // print(i) if let piece = board[i] { if piece.player != board.whosTurnIsItAnyway { // print(i) destinationSqs.append(i) } break } // print(i) destinationSqs.append(i) //assert( i >= 0 && i < 64 ) } // while rank != 0 && rank != 7 && file != 0 && file != 7 return destinationSqs .compactMap{ ChessMove.createMove(from: origin, to: $0, on: board ) } // return [] // let directions:[ChessboardSquare.Direction] = [.topLeft,.topRight,.bottomLeft,.bottomRight] // return directions.flatMap{ getAllMoves(on: board, from: square, in: $0)} } func validRookMoves(board:Chessboard, square origin:Int8) -> [ChessMove] { var destinationSqs:[Int8] = [] let rightEdge = 56 &+ origin.rank var i = origin while i != rightEdge { i &+= 8 if let piece = board[i] { if piece.player != board.whosTurnIsItAnyway { destinationSqs.append(i) } break } destinationSqs.append(i) assert( i >= 0 && i < 64 ) } //left - 8 let leftEdge = origin.rank i = origin while i != leftEdge { i &-= 8 if let piece = board[i] { if piece.player != board.whosTurnIsItAnyway { destinationSqs.append(i) } break } destinationSqs.append(i) assert( i >= 0 && i < 64 ) } let topEdge = origin.file * 8 + 7 i = origin while i != topEdge { i &+= 1 if let piece = board[i] { if piece.player != board.whosTurnIsItAnyway { destinationSqs.append(i) } break } destinationSqs.append(i) assert( i >= 0 && i < 64 ) } //bottom -1 let bottomEdge = origin.file &* 8 i = origin while i != bottomEdge { i &-= 1 if let piece = board[i] { if piece.player != board.whosTurnIsItAnyway { // print(i) destinationSqs.append(i) } break } // print(i) destinationSqs.append(i) assert( i >= 0 && i < 64 ) } return destinationSqs .compactMap{ ChessMove.createMove(from: origin, to: $0, on: board, updateCasteleState: true ) } } func validQueenMoves(board:Chessboard, square origin:Int8) -> [ChessMove] { validRookMoves(board: board, square: origin) + validBishopMoves(board: board, square: origin) }
true
c6eb2d043ff0f0b3dc5a1ea8a417ee22a0a3bad4
Swift
evanmoran/DSFToolbar
/Demos/DSFToolbar Demo/DSFToolbar Demo/panes/popover-popup/PopoverContentController.swift
UTF-8
1,115
2.796875
3
[ "MIT" ]
permissive
// // PopoverContentController.swift // DSFToolbar Demo // // Created by Darren Ford on 27/9/20. // import Cocoa class PopoverContentController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } var color: NSColor? var colorChange: ((NSColor?) -> Void)? @IBAction func selectedColor(_ sender: ColorButton) { self.color = sender.backgroundColor self.colorChange?(self.color) } } @IBDesignable class ColorButton: NSButton { @IBInspectable var backgroundColor: NSColor? { didSet { self.layer?.backgroundColor = self.backgroundColor?.cgColor } } override init(frame frameRect: NSRect) { super.init(frame: frameRect) self.setup() } required init?(coder: NSCoder) { super.init(coder: coder) self.setup() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() self.setup() } override func viewDidMoveToSuperview() { super.viewDidMoveToSuperview() self.setup() } func setup() { self.wantsLayer = true self.layer?.backgroundColor = self.backgroundColor?.cgColor } }
true
fd615f23ed5127b9255005e3daf8fefc5dba5045
Swift
imajoriri/3memo
/3m/VIews/ContentView.swift
UTF-8
4,210
2.625
3
[]
no_license
// // ContentView.swift // 3m // // Created by imajo-takeyuki on 2020/03/09. // Copyright © 2020 imajo. All rights reserved. // import SwiftUI struct ContentView: View { @State var segmentSelection:Int = 0 @State var memos:Array<Memo> = [] init() { UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.systemIndigo] UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.systemIndigo] UINavigationBar.appearance().tintColor = UIColor.systemIndigo } func deleteMemo(offsets: IndexSet) { let memo = self.memos[offsets.first!] MemoModel.delete(memo: memo) } func isShowMemo(memo:Memo) -> Bool { switch self.segmentSelection { case 0: return true case 1: if !memo.fact.isEmpty { return true } return false case 2: if !memo.abstruct.isEmpty { return true } return false case 3: if !memo.product.isEmpty { return true } return false default: return true } } func displayMemos() -> Array<Memo> { return self.memos.filter { self.isShowMemo(memo: $0) } } var body: some View { NavigationView { GeometryReader { geometry in ZStack { VStack{ List { ForEach(self.displayMemos()) {memo in VStack { NavigationLink(destination: MemoDetailView(memo: memo)) { EmptyView() } Group { MemoListRowView(memo: memo) .navigationBarBackButtonHidden(true) } } } .onDelete(perform: self.deleteMemo) } .navigationBarTitle(Text("メモ")) Spacer() .frame(height: 0) Rectangle() .frame(height: 0.5) .foregroundColor(Color(UIColor.separator)) HStack{ Text(String(self.displayMemos().count)+"件のメモ") .multilineTextAlignment(.center) .font(.system(size: 14)) .padding(.leading,16) Spacer() Button(action: { UIImpactFeedbackGenerator().impactOccurred() }) { NavigationLink(destination: MemoDetailView(memo: Memo())) { ZStack { Image(systemName: "square.and.pencil") .foregroundColor(.appBlue) .font(.system(size: 20, weight: .regular, design: .default)) } } }.padding(.trailing,16) } .frame(height: 40) .background(Color(UIColor.systemBackground)) } VStack { Spacer() SegmentedControlView(selection: self.$segmentSelection) .frame(height: 44) .padding(.leading, 12) .padding(.trailing, 12) Spacer() .frame(height: 44 + 20) } } } .onAppear(perform: { MemoModel.getAllMemo() {memos in self.memos = memos } }) } } }
true
f36f70bdc301794412f0b3c812b2b955bbd644b2
Swift
cere-io/widget-ios
/RewardsModule/JSWrappers/SetNativeStorageItemWrapper.swift
UTF-8
838
2.546875
3
[]
no_license
// // SetNativeStorageItemWrapper.swift // RewardsModule // // Created by Konstantin on 2/1/19. // Copyright © 2019 Cerebellum Network, Inc. All rights reserved. // import Foundation class SetNativeStorageItemWrapper : JsProtocolWithResponse { override func handleEvent(widget: RewardsModule, data: AnyObject, responseCallback: ResponseCallback) { if let bodyObj = data as? [AnyObject] { guard let key = bodyObj[0] as? String, let value = bodyObj[1] as? String else { responseCallback?(false); return; } StorageService(widget.env.name).set(value, for: key); print("SetNativeStorageItemWrapper: key=\(key) value=\(value)"); } responseCallback?(true); } }
true