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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bda2a9c2363f959fa607d802e077e86bf8883689
|
Swift
|
ZackDT/WeiBo
|
/DinoWeiBo(微博)/DinoWeiBo/Classes/VIew/Main/Visitor/VisitorView.swift
|
UTF-8
| 5,236
| 2.578125
| 3
|
[] |
no_license
|
//
// VisitorView.swift
// DinoWeiBo
//
// Created by liu yao on 2017/2/5.
// Copyright © 2017年 深圳多诺信息科技有限公司. All rights reserved.
//
import UIKit
import SnapKit
/*
使用带来传递消息是为了在控制器和视图之间解耦,让视图在多个控制器复用。例如UITableView。
但是如果视图仅是为了封装代码,而从控制器中剥离出来,并且确认该视图不会被其他控制器复用,可以直接用addTarget方法
*/
//传递事件:代理、通知、block、kvo、addTag。不用代理也可以用self的属性直接添加添加监听方法
/// 访客视图协议
protocol VisitorViewDelegate:NSObjectProtocol {
/// 注册
func visitorViewDidRegister()
/// 登录
func visitorViewDidLogin()
}
/// 访客视图 - 处理未登录的界面显示
class VisitorView: UIView {
/// 弱引用
weak var delegate: VisitorViewDelegate?
// MARK: - 监听方法
@objc private func clickLogin() {
delegate?.visitorViewDidLogin()
}
@objc private func clickRegister() {
loginButton.shake()
delegate?.visitorViewDidRegister()
}
// MARK: - 设置视图信息
/// 设置视图信息
///
/// - Parameters:
/// - imageName: 图片, 首页设置为nil
/// - title: 消息文字
func setupInfo(imageName: String?, title: String) {
messageLabel.text = title
//为nil的话是首页
guard let imgName = imageName else {
startAnim()
return
}
iconView.image = UIImage(named: imgName)
homeView.isHidden = true
//将遮罩视图移动到底层
sendSubview(toBack: maskIconView)
}
private func startAnim() {
let anim = CABasicAnimation(keyPath: "transform.rotation")
anim.toValue = 2 * M_PI
anim.repeatCount = MAXFLOAT
anim.duration = 20
anim.isRemovedOnCompletion = false
iconView.layer.add(anim, forKey: nil)
}
/// 指定构造函数
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
// 使用sb或xib开发加载的函数
required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
setupUI()
}
/// 图标
private lazy var iconView: UIImageView = UIImageView(imageName: "visitordiscover_feed_image_smallicon")
/// 遮罩图像
private lazy var maskIconView: UIImageView = UIImageView(imageName: "visitordiscover_feed_mask_smallicon")
private lazy var homeView: UIImageView = UIImageView(imageName: "visitordiscover_feed_image_house")
/// 消息文字
private lazy var messageLabel: UILabel = UILabel(title: "关注一些人,会这看看有什么惊喜!")
//注册按钮
private lazy var registerButton: UIButton = UIButton(title: "注册", color: UIColor.orange, backimageName: "common_button_white_disable")
//登录按钮
private lazy var loginButton: UIButton = UIButton(title: "登录", color: UIColor.orange, backimageName: "common_button_white_disable")
/// 设置界面
private func setupUI() {
//这里使用苹果的自动布局来写
//建议子视图最好有一个统一的参照物
addSubview(iconView)
addSubview(maskIconView)
addSubview(homeView)
addSubview(messageLabel)
addSubview(registerButton)
addSubview(loginButton)
//背景灰度图
backgroundColor = UIColor(white: 237.0 / 255.0, alpha: 1.0)
//1> 图标
iconView.snp.makeConstraints { (make) in
make.centerX.equalTo(self.snp.centerX)
make.centerY.equalTo(self.snp.centerY).offset(-60)
}
//2> 小房子
homeView.snp.makeConstraints { (make) in
make.center.equalTo(iconView.snp.center)
}
//3> 消息文字
messageLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(iconView.snp.centerX)
make.top.equalTo(iconView.snp.bottom).offset(16)
make.width.equalTo(224)
make.height.equalTo(36)
}
//4> 注册按钮
registerButton.snp.makeConstraints { (make) in
make.left.equalTo(messageLabel.snp.left)
make.size.equalTo(CGSize(width: 100, height: 36))
make.top.equalTo(messageLabel.snp.bottom).offset(16)
}
//5> 登录按钮
loginButton.snp.makeConstraints { (make) in
make.right.equalTo(messageLabel.snp.right)
make.top.width.height.equalTo(registerButton)
}
//6> 遮罩图形
maskIconView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(self)
make.bottom.equalTo(registerButton.snp.bottom)
}
//添加监听方法
registerButton.addTarget(self, action: #selector(VisitorView.clickRegister), for: .touchUpInside)
loginButton.addTarget(self, action: #selector(VisitorView.clickLogin), for: .touchUpInside)
}
}
extension VisitorView {
}
| true
|
8800748f406aa648569631cccfd9bc549a7e06d4
|
Swift
|
airspeedswift/swift
|
/stdlib/private/OSLog/OSLogNSObjectType.swift
|
UTF-8
| 4,512
| 2.6875
| 3
|
[
"Apache-2.0",
"Swift-exception"
] |
permissive
|
//===----------------- OSLogNSObjectType.swift ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This file defines extensions for interpolating NSObject into an OSLogMesage.
// It defines `appendInterpolation` function for NSObject type. It also defines
// extensions for generating an os_log format string for NSObjects (using the
// format specifier %@) and for serializing NSObject into the argument buffer
// passed to os_log ABIs.
//
// The `appendInterpolation` function defined in this file accept privacy
// options along with the interpolated expression as shown below:
//
// "\(x, privacy: .public\)"
import ObjectiveC
extension OSLogInterpolation {
/// Define interpolation for expressions of type NSObject.
/// - Parameters:
/// - argumentObject: the interpolated expression of type NSObject, which is autoclosured.
/// - privacy: a privacy qualifier which is either private or public.
/// It is auto-inferred by default.
@_semantics("constant_evaluable")
@_semantics("oslog.requires_constant_arguments")
@inlinable
@_optimize(none)
public mutating func appendInterpolation(
_ argumentObject: @autoclosure @escaping () -> NSObject,
privacy: OSLogPrivacy = .auto
) {
guard argumentCount < maxOSLogArgumentCount else { return }
formatString += getNSObjectFormatSpecifier(privacy)
addNSObjectHeaders(privacy)
arguments.append(argumentObject)
argumentCount += 1
}
/// Update preamble and append argument headers based on the parameters of
/// the interpolation.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
internal mutating func addNSObjectHeaders(_ privacy: OSLogPrivacy) {
// Append argument header.
let header = getArgumentHeader(privacy: privacy, type: .object)
arguments.append(header)
// Append number of bytes needed to serialize the argument.
let byteCount = pointerSizeInBytes()
arguments.append(UInt8(byteCount))
// Increment total byte size by the number of bytes needed for this
// argument, which is the sum of the byte size of the argument and
// two bytes needed for the headers.
totalBytesForSerializingArguments += byteCount + 2
preamble = getUpdatedPreamble(privacy: privacy, isScalar: false)
}
/// Construct an os_log format specifier from the given parameters.
/// This function must be constant evaluable and all its arguments
/// must be known at compile time.
@inlinable
@_semantics("constant_evaluable")
@_effects(readonly)
@_optimize(none)
internal func getNSObjectFormatSpecifier(_ privacy: OSLogPrivacy) -> String {
switch privacy {
case .private:
return "%{private}@"
case .public:
return "%{public}@"
default:
return "%@"
}
}
}
extension OSLogArguments {
/// Append an (autoclosured) interpolated expression of type NSObject, passed to
/// `OSLogMessage.appendInterpolation`, to the array of closures tracked
/// by this instance.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
internal mutating func append(_ value: @escaping () -> NSObject) {
argumentClosures.append({ (position, _) in
serialize(value(), at: &position)
})
}
}
/// Serialize an NSObject pointer at the buffer location pointed by
/// `bufferPosition`.
@inlinable
@_alwaysEmitIntoClient
@inline(__always)
internal func serialize(
_ object: NSObject,
at bufferPosition: inout ByteBufferPointer
) {
let byteCount = pointerSizeInBytes();
let dest =
UnsafeMutableRawBufferPointer(start: bufferPosition, count: byteCount)
// Get the address of this NSObject as an UnsafeRawPointer.
let objectAddress = Unmanaged.passUnretained(object).toOpaque()
// Copy the address into the destination buffer. Note that the input NSObject
// is an interpolated expression and is guaranteed to be alive until the
// os_log ABI call is completed by the implementation. Therefore, passing
// this address to the os_log ABI is safe.
withUnsafeBytes(of: objectAddress) { dest.copyMemory(from: $0) }
bufferPosition += byteCount
}
| true
|
d79bdd3025eb84c0433fdd0ae904e59aab818e03
|
Swift
|
viniciusmesquitac/UmSimplesDiario
|
/UmSimplesDiario/Shared/ThemeManager/AvailableThemes/PurpleTheme.swift
|
UTF-8
| 1,150
| 2.59375
| 3
|
[] |
no_license
|
//
// PurpleTheme.swift
// UmSimplesDiario
//
// Created by Vinicius Mesquita on 14/05/21.
//
import Foundation
class PurpleTheme: ThemeProtocol {
var assets: Themeable {
return ThemeAssets(
labelAssets: LabelAssets(
textColor: StyleSheet.Color.primaryColor,
font: .systemFont(ofSize: 12, weight: .black)
),
buttonAssets: ButtonAssets(
normalBackgroundColor: #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1),
selectedBackgroundColor: #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1),
disabledBackgroundColor: #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1),
tintColor: #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)
),
switchAssets: SwitchAssets(
isOnColor: .purple,
isOnDefault: true
)
)
}
var `extension`: (() -> Void)? {
return {
/*Nothing*/
}
}
}
| true
|
e5b3d2d63cb85a83928d3f9364bfad33fcedc5c2
|
Swift
|
piggest777/TouchyApp
|
/TouchyApp/Controller/CreateNoteVC.swift
|
UTF-8
| 2,067
| 2.5625
| 3
|
[] |
no_license
|
//
// CreateNoteVC.swift
// TouchyApp
//
// Created by Denis Rakitin on 2019-10-01.
// Copyright © 2019 Denis Rakitin. All rights reserved.
//
import UIKit
class CreateNoteVC: UIViewController {
@IBOutlet weak var noteTxtView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// self.hideKeyboardWhenTappedAround()
// let tap = UITapGestureRecognizer(target: self, action: #selector(removeKeyboard))
// noteTxtView.addGestureRecognizer(tap)
self.noteTxtView.addDoneButton(title: "Done", target: self, selector: #selector(tapDone(sender:)))
}
// @objc func removeKeyboard(){
//
// noteTxtView.resignFirstResponder()
//
// }
@objc func tapDone(sender: Any) {
self.view.endEditing(true)
}
@IBAction func onlySaveBtn(_ sender: Any) {
showAction()
}
func showAction () {
let alertVC = UIAlertController(title: "Please choose", message: "Create and lock or just create", preferredStyle: .actionSheet)
let createAndSaveAlert = UIAlertAction(title: "Create and Locked!", style: .default) { (action) in
NoteCore.instance.createNote(noteTxt: self.noteTxtView.text, lockStatus: .locked) { (success) in
if success {
self.navigationController?.popViewController(animated: true)
}
}
}
let createAlert = UIAlertAction(title: "Create ", style: .default) { (action) in
NoteCore.instance.createNote(noteTxt: self.noteTxtView.text, lockStatus: .unlocked) { (success) in
if success {
self.navigationController?.popViewController(animated: true)
}
}
}
let closeAlert = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertVC.addAction(createAlert)
alertVC.addAction(createAndSaveAlert)
alertVC.addAction(closeAlert)
present(alertVC, animated: true, completion: nil)
}
}
| true
|
07f4c85ab603a36f29f456f2955d0ecc2984c843
|
Swift
|
TeamMeowBox/MeowBox-iOS
|
/MeowBox/MeowBox/Util/Service/SignService.swift
|
UTF-8
| 5,283
| 2.578125
| 3
|
[] |
no_license
|
//
// SignService.swift
// MeowBox
//
// Created by 장한솔 on 2018. 7. 8..
// Copyright © 2018년 yeen. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
struct SignService : APIService{
//MARK: 로그인 서비스
static func login(email: String, pwd: String, completion: @escaping (_ message: String)->Void){
let userdefault = UserDefaults.standard
let URL = url("/user/signin")
let body: [String: Any] = [
"email" : email,
"pwd" : pwd
]
Alamofire.request(URL, method: .post, parameters: body, encoding: JSONEncoding.default, headers: nil).responseData(){ res in
switch res.result{
case .success:
if let value = res.result.value{
if let message = JSON(value)["message"].string{
if message == "success"{ // 로그인 성공
/***************** USER DEFAULT *****************/
let myToken = gsno(JSON(value)["result"]["token"].string)
let myCat_idx = gsno(JSON(value)["result"]["cat_idx"].string)
print("token: "+myToken)
print("cat_idx: "+myCat_idx)
print("name: "+gsno(JSON(value)["result"]["name"].string))
userdefault.set(email, forKey: "email")
userdefault.set(gsno(JSON(value)["result"]["token"].string), forKey: "token")
userdefault.set(gsno(JSON(value)["result"]["cat_idx"].string), forKey: "cat_idx")
userdefault.set(gsno(JSON(value)["result"]["name"].string), forKey: "name")
userdefault.set(gsno(JSON(value)["result"]["phone_number"].string), forKey: "phone_number")
userdefault.set(gsno(JSON(value)["result"]["image_profile"].string), forKey: "image_profile")
userdefault.set(gsno(JSON(value)["result"]["flag"].string), forKey: "flag")
completion("success")
}else{ // 로그인 실패
print("로그인 실패 : "+message)
completion("failure")
}
}
}
break
case .failure(let err):
print(err.localizedDescription)
break
}
}
}
//MARK: 회원가입 서비스
static func signup(email: String, pwd: String, name: String, phone_number: String, completion: @escaping (_ message: String)->Void){
let URL = url("/user/signup")
let body: [String: Any] = [
"email" : email,
"pwd" : pwd,
"name" : name,
"phone_number" : phone_number,
]
Alamofire.request(URL, method: .post, parameters: body, encoding: JSONEncoding.default, headers: nil).responseData(){ res in
switch res.result{
case .success:
if let value = res.result.value{
if let message = JSON(value)["message"].string{
if message == "success"{ // 회원가입 성공
completion("success")
}else if message == "exist_id"{ // 중복 있음
completion("exist_id")
}
}
}
break
case .failure(let err):
print(err.localizedDescription)
break
}
}
}
//MARK : 회원탈퇴 서비스
static func leave(completion: @escaping (_ messgae: String)->Void){
let userDefault = UserDefaults.standard
let URL = url("/user/account")
guard let token = userDefault.string(forKey: "token") else { return }
let headers = ["authorization": token]
Alamofire.request(URL, method: .delete, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseData(){ res in
switch res.result{
case .success:
if let value = res.result.value{
if let message = JSON(value)["message"].string{
if message == "success"{ // 회원탈퇴 성공
print("회원 탈퇴 성공!")
completion("success")
}
}
}
break
case .failure(let err):
print(err.localizedDescription)
break
}
}
}
}
| true
|
c164debbdafb04c91f044c8d85da405d8a0fb872
|
Swift
|
MarioBiuuuu/WorkSummary201607-201804
|
/ReactorTableViewDemo/ReactorTableViewDemo/Utility/RxConvenient/UIAlertController+RxConvenient.swift
|
UTF-8
| 3,294
| 2.65625
| 3
|
[] |
no_license
|
//
// UIAlertController+RxConvenient.swift
// ifanr
//
// Created by luhe liu on 2018/7/13.
// Copyright © 2018年 com.ifanr. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
public protocol AlertActionType {
var title: String? { get }
var style: UIAlertActionStyle { get }
}
public extension AlertActionType {
public var style: UIAlertActionStyle {
return .default
}
}
public protocol AlertType {
associatedtype ActionType: AlertActionType
var title: String? { get }
var message: String? { get }
var style: UIAlertControllerStyle { get }
var actions: [ActionType] { get }
}
extension AlertType {
public var title: String? { return "" }
public var message: String? { return "" }
public var style: UIAlertControllerStyle { return .alert }
}
public enum AlertResponse<T: AlertActionType> {
case willPresent
case didPresent
case action(T)
}
extension Reactive where Base: UIViewController {
public func showAlert<T: AlertType>(type: T, animated: Bool = true, dimissCompletion: (() -> Void)? = nil) -> Observable<AlertResponse<T.ActionType>> {
return Observable.create { [weak base = self.base] observer in
guard let strongBase = base else {
return Disposables.create()
}
let alert = UIAlertController(title: type.title, message: type.message, preferredStyle: type.style)
for action in type.actions {
let alertAction = UIAlertAction(title: action.title, style: action.style) { _ in
observer.on(.next(.action(action)))
observer.on(.completed)
}
alert.addAction(alertAction)
}
observer.on(.next(.willPresent))
strongBase.present(alert, animated: animated, completion: {
observer.on(.next(.didPresent))
})
return Disposables.create {
alert.dismiss(animated: animated, completion: dimissCompletion)
}
}
}
}
extension Reactive where Base: UIView {
public func showAlert<T: AlertType>(type: T, animated: Bool = true, dimissCompletion: (() -> Void)? = nil) -> Observable<AlertResponse<T.ActionType>> {
return Observable.create { [weak base = self.base] observer in
guard let strongBase = base, let responderController = strongBase.responderController else {
return Disposables.create()
}
let alert = UIAlertController(title: type.title, message: type.message, preferredStyle: type.style)
for action in type.actions {
let alertAction = UIAlertAction(title: action.title, style: action.style) { _ in
observer.on(.next(.action(action)))
observer.on(.completed)
}
alert.addAction(alertAction)
}
observer.on(.next(.willPresent))
responderController.present(alert, animated: animated, completion: {
observer.on(.next(.didPresent))
})
return Disposables.create {
alert.dismiss(animated: animated, completion: dimissCompletion)
}
}
}
}
| true
|
af5bb06f835fbbfddb1ff41e051816b6c7bf3c43
|
Swift
|
ActionMads/Skyens-B-rn
|
/Skyens_Boern/A good Melody/Components/RunningWaterComponent.swift
|
UTF-8
| 816
| 2.84375
| 3
|
[] |
no_license
|
//
// RunningWaterComponent.swift
// Dromedary
//
// Created by Mads Munk on 25/02/2021.
// Copyright © 2021 Mads Munk. All rights reserved.
//
import Foundation
import GameplayKit
import SpriteKit
class RunningWaterComponent: GKComponent {
func run() {
guard let sprite = entity?.component(ofType: SpriteComponent.self) else {return}
print("sprite name", sprite.sprite.name)
let water = SKSpriteNode(imageNamed: "VandStråle")
water.position = CGPoint(x: 110, y: 0)
water.zPosition = -1
sprite.sprite.addChild(water)
let run = SKAction.move(to: CGPoint(x: 110, y: -400), duration: 0.5)
let remove = SKAction.removeFromParent()
let seq = SKAction.sequence([run, remove])
water.run(seq)
}
}
| true
|
f0c7b4b48aab083772983584fdb7f202fa9a7524
|
Swift
|
marksands/BetterCodable
|
/Tests/BetterCodableTests/LossyOptionalTests.swift
|
UTF-8
| 2,504
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
import BetterCodable
class DefaultNilTests: XCTestCase {
/// This test demonstrates the problem that `@LossyOptional` solves. When decoding
/// optional types, it often the case that we end up with an error instead of
/// defaulting back to `nil`.
func testDecodingBadUrlAsOptionalWithoutDefaultNil() {
struct Fixture: Codable {
var a: URL?
}
let jsonData = #"{"a":"https://example .com"}"#.data(using: .utf8)!
XCTAssertThrowsError(try JSONDecoder().decode(Fixture.self, from: jsonData))
}
func testDecodingWithUrlConversions() throws {
struct Fixture: Codable {
@LossyOptional var a: URL?
@LossyOptional var b: URL?
}
let badUrlString = "https://example .com"
let goodUrlString = "https://example.com"
let jsonData = #"{"a":"\#(badUrlString)", "b":"\#(goodUrlString)"}"#.data(using: .utf8)!
let fixture = try JSONDecoder().decode(Fixture.self, from: jsonData)
XCTAssertNil(fixture.a)
XCTAssertEqual(fixture.b, URL(string: goodUrlString))
}
func testDecodingWithIntegerConversions() throws {
struct Fixture: Codable {
@LossyOptional var a: Int?
@LossyOptional var b: Int?
}
let jsonData = #"{ "a": 3.14, "b": 3 }"#.data(using: .utf8)!
let _fixture = try JSONDecoder().decode(Fixture.self, from: jsonData)
let fixtureData = try JSONEncoder().encode(_fixture)
let fixture = try JSONDecoder().decode(Fixture.self, from: fixtureData)
XCTAssertNil(fixture.a)
XCTAssertEqual(fixture.b, 3)
}
func testDecodingWithNullValue() throws {
struct Fixture: Codable {
@LossyOptional var a: String?
}
let jsonData = #"{"a":null}"#.data(using: .utf8)!
let fixture = try JSONDecoder().decode(Fixture.self, from: jsonData)
XCTAssertNil(fixture.a)
}
func testDecodingWithMissingKey() throws {
struct Fixture: Codable {
@LossyOptional var a: String?
}
let jsonData = "{}".data(using: .utf8)!
let _fixture = try JSONDecoder().decode(Fixture.self, from: jsonData)
let fixtureData = try JSONEncoder().encode(_fixture)
let fixture = try JSONDecoder().decode(Fixture.self, from: fixtureData)
XCTAssertNil(fixture.a)
}
}
| true
|
624e57deab9b2123ae269e39fd133041d8df03d4
|
Swift
|
sundaysmeSwift/asradial
|
/ASRadial/ASLineBGView.swift
|
UTF-8
| 1,356
| 2.6875
| 3
|
[] |
no_license
|
//
// ASLineBGView.swift
// ASRadial
//
// Created by Biggerlens on 2021/7/14.
// Copyright © 2021 alperSenyurt. All rights reserved.
//
import UIKit
protocol ASLineBGDelegate:AnyObject{
func buttonDidFinishAnimation(lineButton : UIView?)
}
class ASLineBGView: UIView {
var centerPoint:CGPoint!
var originPoint:CGPoint!
weak var delegate:ASLineBGDelegate?
override init(frame:CGRect){
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
}
// func willAppear () {
// self.alpha = 1.0
//
// UIView.animate(withDuration: 0.5) {[weak self] in
// self!.center = self!.centerPoint
// } completion: { [weak self] (finished: Bool) -> Void in
// self!.center = self!.centerPoint
// }
//
// }
//
// func willDisappear () {
// UIView.animate(withDuration: 0.5) {[weak self] in
// self!.center = self!.originPoint
// } completion: { [weak self] (finished: Bool) -> Void in
// self!.center = self!.originPoint
// self?.alpha = 1
// self?.delegate?.buttonDidFinishAnimation(lineButton: self)
// }
// }
}
| true
|
2d7e39e64f362bf9ae2a6730e8cf67a0415a9e18
|
Swift
|
prizrak1609/TestMK
|
/TestMK/DriversScreen.swift
|
UTF-8
| 3,993
| 2.75
| 3
|
[] |
no_license
|
//
// DriversScreen.swift
// TestMK
//
// Created by Dima Gubatenko on 13.07.17.
// Copyright © 2017 Dima Gubatenko. All rights reserved.
//
import UIKit
final class DriversScreen: UIViewController {
@IBOutlet fileprivate weak var tableView: UITableView!
fileprivate var tableViewIsInEditMode = false
fileprivate var drivers = [DriverInfo]()
fileprivate let database = Database()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setNavigationBarHidden(false, animated: false)
title = NSLocalizedString("Drivers", comment: "DriversScreen title")
let addCarButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addDriverButtonClicked))
navigationItem.rightBarButtonItems = [addCarButton]
initTableView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if case .error(let text) = database.openOrCreate() {
log(text)
}
switch database.getAllDrivers() {
case .error(let text): log(text)
case .success(let drivers):
self.drivers = drivers
tableView.reloadData()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
database.close()
}
}
extension DriversScreen : UITableViewDelegate, UITableViewDataSource {
func initTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 100
tableView.register(UINib(nibName: Cell.driverInfo, bundle: nil), forCellReuseIdentifier: Cell.driverInfo)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return drivers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: Cell.driverInfo) as? DriverInfoCell else { return UITableViewCell() }
cell.model = drivers[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .normal, title: "Edit", handler: { [weak self] _, indexPath in
guard let welf = self else { return }
if let driverCreateScreen = Storyboards.driverCreate as? DriverCreateScreen {
driverCreateScreen.model = welf.drivers[indexPath.row]
welf.navigationController?.pushViewController(driverCreateScreen, animated: true)
} else {
showText("can't get \(Storyboards.Name.driverCreate) storyboard")
}
})
let deleteAction = UITableViewRowAction(style: .default, title: "Delete") { [weak self] _, indexPath in
guard let welf = self else { return }
let driver = welf.drivers.remove(at: indexPath.row)
if case .error(let text) = welf.database.remove(driver: driver) {
log(text)
}
welf.tableView.reloadData()
}
return [deleteAction, editAction]
}
}
private extension DriversScreen {
@objc
func addDriverButtonClicked() {
if let driverCreate = Storyboards.driverCreate {
navigationController?.pushViewController(driverCreate, animated: true)
} else {
showText("can't get \(Storyboards.Name.driverCreate) storyboard")
}
}
@objc
func editButtonClicked() {
tableViewIsInEditMode = !tableViewIsInEditMode
tableView.setEditing(tableViewIsInEditMode, animated: true)
}
}
| true
|
8bb5145af5220e797af6ca2e001c93614d5fa930
|
Swift
|
ty5491003/fuzzilli
|
/Sources/Fuzzilli/Execution/Execution.swift
|
UTF-8
| 2,368
| 2.890625
| 3
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
func WIFEXITED(_ status: Int32) -> Bool {
return status & 0x7f == 0
}
func WEXITSTATUS(_ status: Int32) -> Int32 {
return (status >> 8) & 0xff
}
func WTERMSIG(_ status: Int32) -> Int32 {
return status & 0x7f
}
/// The possible outcome of a program execution.
public enum ExecutionOutcome: CustomStringConvertible {
case crashed
case failed
case succeeded
case timedOut
public var description: String {
switch self {
case .crashed:
return "Crashed!"
case .failed:
return "Failed"
case .succeeded:
return "Succeeded"
case .timedOut:
return "TimedOut"
}
}
/// Converts an exit code into an ExecutionOutcome.
public static func fromExitCode(_ code: Int32) -> ExecutionOutcome {
if code == 0 {
return .succeeded
} else {
return .failed
}
}
/// Converts an exit status (from wait (2) etc.) into an execution outcome.
public static func fromExitStatus(_ status: Int32) -> ExecutionOutcome {
if WIFEXITED(status) {
return fromExitCode(WEXITSTATUS(status))
} else if WTERMSIG(status) == SIGKILL {
return .timedOut
} else {
return .crashed
}
}
}
/// The result of executing a program.
public struct Execution {
/// The PID of the process that executed the program
public let pid: Int
/// The execution outcome
public let outcome: ExecutionOutcome
/// The termination signal
public let termsig: Int
/// Program output (not stdout but FuzzIL output)
public let output: String
/// Execution time in ms
public let execTime: UInt
}
| true
|
53378afc5ef7fdf8371889a661d34a3f2c586f8e
|
Swift
|
asfcarvalho/IssueApp
|
/IssueApp/IssueApp/Modules/IssueList/View/Cell/IssueListCell.swift
|
UTF-8
| 1,276
| 2.671875
| 3
|
[] |
no_license
|
//
// IssueListCell.swift
// IssueApp
//
// Created by Anderson F Carvalho on 17/04/20.
// Copyright © 2020 asfcarvalho. All rights reserved.
//
import UIKit
class IssueListCell: UITableViewCell {
var title: UILabel = {
let label = UILabel()
label.numberOfLines = 0
return label
}()
var status = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setupCell()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
private func setupCell() {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fill
stackView.spacing = 8
stackView.addArrangedSubview(title)
stackView.addArrangedSubview(status)
browseAddSubviews([stackView])
stackView.browseEdgeToSuperView(UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16))
}
func setupFetch(_ issue: IssueListViewModel.Issue?) {
title.attributedText = issue?.title
status.attributedText = issue?.status
}
}
| true
|
65474e9cf82fbeb8b5a55c857c898975af4fdd9c
|
Swift
|
Macro-swift/Macro
|
/Sources/MacroCore/Streams/Concat.swift
|
UTF-8
| 3,974
| 2.890625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Concat.swift
// Macro
//
// Created by Helge Hess.
// Copyright © 2020 ZeeZide GmbH. All rights reserved.
//
/**
* Returns a stream in the spirit of the Node `concat-stream` module:
*
* https://github.com/maxogden/concat-stream
*
* Be careful w/ using that. You don't want to baloon payloads in memory!
*
*/
@inlinable
public func concat(maximumSize: Int = _defaultConcatMaximumSize,
yield: @escaping ( Buffer ) -> Void) -> ConcatByteStream
{
let stream = ConcatByteStream(maximumSize: maximumSize)
return stream.onceFinish {
let result = stream.writableBuffer
stream.writableBuffer = MacroCore.shared.emptyBuffer
yield(result)
}
}
/**
* Returns a stream in the spirit of the Node `concat-stream` module:
*
* https://github.com/maxogden/concat-stream
*
* Be careful w/ using that. You don't want to baloon payloads in memory!
*
*/
@inlinable
public func concat(maximumSize: Int = _defaultConcatMaximumSize,
yield: @escaping ( Buffer ) throws -> Void)
-> ConcatByteStream
{
let stream = ConcatByteStream(maximumSize: maximumSize)
return stream.onceFinish {
defer { stream.writableBuffer = MacroCore.shared.emptyBuffer }
do {
try yield(stream.writableBuffer)
}
catch {
stream.emit(error: error)
}
}
}
/**
* A stream in the spirit of the Node `concat-stream` module:
*
* https://github.com/maxogden/concat-stream
*
* Be careful w/ using that. You don't want to baloon payloads in memory!
*
* Create those objects using the `concat` function.
*/
public class ConcatByteStream: WritableByteStream,
WritableByteStreamType, WritableStreamType,
CustomStringConvertible
{
// TBD: This should be duplex? Or is the duplex a "compacting stream"?
enum StreamState: Equatable {
case ready
case finished
}
public var writableBuffer = MacroCore.shared.emptyBuffer
public let maximumSize : Int
private var state = StreamState.ready
override public var writableFinished : Bool { return state == .finished }
@inlinable
override public var writableEnded : Bool { return writableFinished }
@inlinable
override public var writable : Bool { return !writableFinished }
@inlinable
open var writableLength : Int { return writableBuffer.count }
@usableFromInline init(maximumSize: Int) {
self.maximumSize = maximumSize
}
@discardableResult
@inlinable
public func write(_ bytes: Buffer, whenDone: @escaping () -> Void = {})
-> Bool
{
guard !writableEnded else {
emit(error: WritableError.writableEnded)
whenDone()
return true
}
let newSize = writableBuffer.count + bytes.count
guard newSize <= maximumSize else {
emit(error: ConcatError
.maximumSizeExceeded(maximumSize: maximumSize,
availableSize: newSize))
whenDone()
return true
}
writableBuffer.append(bytes)
whenDone()
return true
}
public func end() {
state = .finished
finishListeners.emit()
finishListeners.removeAll()
errorListeners .removeAll()
}
// MARK: - CustomStringConvertible
open var description: String {
var ms = "<Concat[\(ObjectIdentifier(self))]:"
defer { ms += ">" }
let count = writableBuffer.count
if writableCorked {
if count > 0 {
ms += " corked=#\(count)"
}
else {
ms += " corked(empty)"
}
}
else {
ms += " buffered=#\(count)"
}
if writableEnded { ms += " ended" }
return ms
}
}
public enum ConcatError: Swift.Error {
case maximumSizeExceeded(maximumSize: Int, availableSize: Int)
}
public let _defaultConcatMaximumSize =
process.getenv("macro.concat.maxsize",
defaultValue : 1024 * 1024, // 1MB
lowerWarningBound : 128)
| true
|
cd0e268452239b6a5ff2dc2db6180e5c70fa93ae
|
Swift
|
manuelteixeira/100_days_swift
|
/100 Days of swift/Projects 7-9/Projects 7-9/ViewController.swift
|
UTF-8
| 7,494
| 3
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// Projects 7-9
//
// Created by Manuel Teixeira on 15/05/2020.
// Copyright © 2020 Manuel Teixeira. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var currentAnswer: UITextField!
var addGuessButton: UIButton!
var incorrectGuessesLabel: UILabel!
var emojiLabel: UILabel!
let maxGuesses = 7
var wordsToGuess = [String]()
var usedLetters = ""
var activeWordToGuess = ""
var level = 0
var incorrectGuesses = 0 {
didSet {
incorrectGuessesLabel.text = "You have \(maxGuesses - incorrectGuesses) guesses left"
}
}
override func loadView() {
view = UIView()
view.backgroundColor = .white
currentAnswer = UITextField()
currentAnswer.translatesAutoresizingMaskIntoConstraints = false
currentAnswer.font = UIFont.systemFont(ofSize: 44)
currentAnswer.textAlignment = .center
currentAnswer.isUserInteractionEnabled = false
view.addSubview(currentAnswer)
addGuessButton = UIButton()
addGuessButton.translatesAutoresizingMaskIntoConstraints = false
addGuessButton.setTitle("Add Guess", for: .normal)
addGuessButton.setTitleColor(.darkGray, for: .normal)
addGuessButton.addTarget(self, action: #selector(addGuessButtonTapped), for: .touchUpInside)
view.addSubview(addGuessButton)
incorrectGuessesLabel = UILabel()
incorrectGuessesLabel.translatesAutoresizingMaskIntoConstraints = false
incorrectGuessesLabel.textColor = .systemRed
incorrectGuessesLabel.font = UIFont.systemFont(ofSize: 17)
incorrectGuessesLabel.text = "You have \(maxGuesses - incorrectGuesses) guesses left"
view.addSubview(incorrectGuessesLabel)
emojiLabel = UILabel()
emojiLabel.translatesAutoresizingMaskIntoConstraints = false
emojiLabel.text = "🤔"
emojiLabel.font = UIFont.systemFont(ofSize: 84)
view.addSubview(emojiLabel)
NSLayoutConstraint.activate([
currentAnswer.centerXAnchor.constraint(equalTo: view.centerXAnchor),
currentAnswer.centerYAnchor.constraint(equalTo: view.centerYAnchor),
currentAnswer.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
currentAnswer.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
incorrectGuessesLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
incorrectGuessesLabel.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 8),
addGuessButton.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor),
addGuessButton.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
emojiLabel.bottomAnchor.constraint(equalTo: currentAnswer.topAnchor, constant: -40),
emojiLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
}
override func viewDidLoad() {
super.viewDidLoad()
performSelector(inBackground: #selector(importWords), with: nil)
}
@objc func importWords() {
guard
let levelFileURL = Bundle.main.url(forResource: "city_names", withExtension: "txt"),
let data = try? String(contentsOf: levelFileURL)
else {
let errorMessage = "Couldn't import words from file"
DispatchQueue.main.async { [weak self] in
self?.showError(message: errorMessage)
}
return
}
let words = data.components(separatedBy: "\n")
for word in words {
if !word.isEmpty {
wordsToGuess.append(word.lowercased())
}
}
DispatchQueue.main.async { [weak self] in
self?.loadLevel()
}
}
func loadLevel() {
activeWordToGuess = wordsToGuess[level]
var hiddenString = ""
for _ in activeWordToGuess {
hiddenString += "?"
}
currentAnswer.text = hiddenString
}
@objc func addGuessButtonTapped(_ sender: UIButton) {
let alertController = UIAlertController(title: "Make a guess", message: nil, preferredStyle: .alert)
alertController.addTextField()
let action = UIAlertAction(title: "Add guess", style: .default) { [weak self] action in
guard let self = self else { return }
guard
let guess = alertController.textFields?[0].text,
guess.count == 1
else {
self.showError(message: "Hey, it's must be only ONE letter guess")
return
}
DispatchQueue.global(qos: .userInitiated).async {
self.checkGuess(guess.lowercased())
}
}
alertController.addAction(action)
present(alertController, animated: true)
}
@objc func checkGuess(_ guess: String) {
if activeWordToGuess.contains(guess) {
usedLetters.append(guess)
var text = ""
for activeWordLetter in activeWordToGuess {
let stringActiveWordLetter = String(activeWordLetter)
if usedLetters.contains(stringActiveWordLetter) {
text.append(stringActiveWordLetter)
} else {
text.append("?")
}
}
DispatchQueue.main.async { [weak self] in
self?.currentAnswer.text = text
if !text.contains("?") {
self?.showMessage(message: "You WIN!")
self?.level += 1
self?.usedLetters.removeAll()
self?.incorrectGuesses = 0
self?.loadLevel()
}
}
} else {
DispatchQueue.main.async { [weak self] in
self?.incorrectGuesses += 1
if self?.incorrectGuesses == 7 {
self?.showMessage(message: "Game OVER!")
self?.level = 0
self?.usedLetters.removeAll()
self?.incorrectGuesses = 0
self?.loadLevel()
}
self?.showMessage(message: "Oops, try again!")
}
}
}
func showError(title: String = "Error", message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(action)
present(alertController, animated: true)
}
func showMessage(title: String = "Message", message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(action)
present(alertController, animated: true)
}
}
| true
|
8fdaf8afe42dfce2e628be71d12efe2b56ff3473
|
Swift
|
amrish036/Swift-Algorithm-Learning
|
/BinarySearch.playground/Contents.swift
|
UTF-8
| 649
| 3.453125
| 3
|
[
"MIT"
] |
permissive
|
func binarySearch<T: Comparable>(_ a:[T], key: T, range: Range<Int>) -> Int?{
if range.lowerBound >= range.upperBound{
return nil
}
else{
let midIndex = range.lowerBound + (range.upperBound - range.lowerBound)/2
if a[midIndex] > key {
return binarySearch(a, key: key, range: range.lowerBound ..< midIndex)
}
else if a[midIndex] < key{
return binarySearch(a, key: key, range: midIndex+1 ..< range.upperBound)
}
else{
return midIndex
}
}
}
let numbers = [1,2,6,5,3,2,7,9,10,124,554,78,34,01,56,345,11,3456].sorted()
binarySearch(numbers, key: 78, range: 0 ..< numbers.count)
| true
|
83c73d1967838de3b089061a20ba67fe7abc1a8a
|
Swift
|
jzxyouok/openblog
|
/openblog/openblog/Classes/Home/View/XDInputTextView.swift
|
UTF-8
| 1,336
| 2.6875
| 3
|
[] |
no_license
|
//
// XDInputTextView.swift
// openblog
//
// Created by inspiry on 16/1/4.
// Copyright © 2016年 inspiry. All rights reserved.
//
import UIKit
class XDInputTextView: UITextView {
var plaveLabel:UILabel?
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
plaveLabel = UILabel(frame: CGRect(x: 10, y: 10, width: self.width, height: 15))
plaveLabel?.font = XDFont(15)
plaveLabel?.textColor = UIColor.lightGrayColor()
self.addSubview(plaveLabel!)
self.returnKeyType = UIReturnKeyType.Send
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("textViewChange"), name: UITextViewTextDidChangeNotification, object: self)
}
var plaveStr:String? {
didSet {
plaveLabel?.text = plaveStr
textViewChange()
}
}
func textViewChange() {
if self.text.characters.count == 0 {
plaveLabel?.hidden = false
} else {
plaveLabel?.hidden = true
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| true
|
2f6b837d1a36a749c83f8042a314b57c9be88bee
|
Swift
|
marcadam/Tipsie
|
/Tipsie/Tipsie/Tips.swift
|
UTF-8
| 1,409
| 2.953125
| 3
|
[] |
no_license
|
//
// Constants.swift
// Tipsie
//
// Created by Marc Anderson on 1/7/16.
// Copyright © 2016 Marc Anderson. All rights reserved.
//
import Foundation
import UIKit
struct Tips {
static let double = [0.15, 0.18, 0.20, 0.23, 0.25]
static let string = ["15%", "18%", "20%", "23%", "25%"]
static let defaultTipIndexKey = "DefaultTipIndex"
static let defaultTipIndexChangedKey = "DefaultTipIndexChanged"
static func setTipControlText(_ control: UISegmentedControl) {
for (index, tipText) in Tips.string.enumerated() {
control.setTitle(tipText, forSegmentAt: index)
}
}
static func setDefaultTipIndex(_ defaultTipIndex: Int) {
let defaults = UserDefaults.standard
defaults.set(defaultTipIndex, forKey: defaultTipIndexKey)
Tips.setDefaultTipIndexChanged(true)
defaults.synchronize()
}
static func getDefaultTipIndex() -> Int {
let defaults = UserDefaults.standard
return defaults.integer(forKey: defaultTipIndexKey)
}
static func setDefaultTipIndexChanged(_ changed: Bool) {
let defaults = UserDefaults.standard
defaults.set(changed, forKey: defaultTipIndexChangedKey)
defaults.synchronize()
}
static func getDefaultTipIndexChanged() -> Bool {
let defaults = UserDefaults.standard
return defaults.bool(forKey: defaultTipIndexChangedKey)
}
}
| true
|
4f6d2730cdaff225c3fe6d98b486cdc79ae134b5
|
Swift
|
mressier/SwiftyProtein
|
/SwiftyProtein/SwiftyProtein/Shared/Packages/ViewControllerUtils/ConstraintType.swift
|
UTF-8
| 3,024
| 3.578125
| 4
|
[] |
no_license
|
import UIKit
/*******************************************************************************
* ConstraintType
*
* Generate common constraints.
*
******************************************************************************/
enum ConstraintType {
/// Pin a view to the edges.
case edge
/// Center a view and resize its width and height if one.
case center(size: CGSize? = nil)
}
//==============================================================================
// MARK: - Contraint computing
//==============================================================================
extension ConstraintType {
/// Compute and return the constraints of a subview related to a superview
/// related to the given case.
///
/// - Parameters:
/// - subview: The subview
/// - superview: The view
/// - Returns: Computed constraints.
func constraints(subview: UIView,
superview: UIView) -> [NSLayoutConstraint] {
switch self {
case .edge:
return edgeConstraints(subview: subview, superview: superview)
case .center(let size):
return
centerConstraints(subview: subview, superview: superview, size: size)
}
}
/// Set the relationship between a subiew and superview constraints to pin
/// the edges of the subview to the edges of the superview.
///
/// - Parameters:
/// - subview: The view to add constraints.
/// - superview: The view that contains the subview.
/// - Returns: The computed constraints.
private func edgeConstraints(subview: UIView,
superview: UIView) -> [NSLayoutConstraint] {
return [
subview.topAnchor.constraint(equalTo: superview.topAnchor),
subview.bottomAnchor.constraint(equalTo: superview.bottomAnchor),
subview.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
subview.trailingAnchor.constraint(equalTo: superview.trailingAnchor)
]
}
/// Set the relationship between a subiew and superview constraints to move
/// the subview at the center of the superview while optionally setting its
/// width and height.
/// - Parameter subview: The view to add constraints.
/// - Parameter superview: The view that contains the subview.
/// - Parameter size: The constraints size of the subview. If nil, the subview
/// size won't be changed.
private func centerConstraints(subview: UIView,
superview: UIView,
size: CGSize? = nil) -> [NSLayoutConstraint] {
var constraints = [
subview.centerXAnchor.constraint(equalTo: superview.centerXAnchor),
subview.centerYAnchor.constraint(equalTo: superview.centerYAnchor)
]
if let size = size {
let widthAnchor =
subview.widthAnchor.constraint(equalToConstant: size.width)
let heightAnchor =
subview.heightAnchor.constraint(equalToConstant: size.height)
constraints.append(contentsOf: [widthAnchor, heightAnchor])
}
return constraints
}
}
| true
|
cfd8328d259015d35426f6752e743f0b51c466ab
|
Swift
|
gti-gatech/waddle_ios
|
/MiltonWalking/Helpers/MediaPickerHelper/MediaPickerHelper.swift
|
UTF-8
| 11,424
| 2.59375
| 3
|
[] |
no_license
|
//
// ImagePickerHelper.swift
// CleanSwiftDemo
//
// Created by Bharat Kumar Pathak on 13/10/17.
// Copyright © 2017 Konstant. All rights reserved.
//
import Foundation
import UIKit
import Photos
import MobileCoreServices
enum PickingMediaType {
case video
case image
case imageAndVideo
}
typealias ImageCompletionHandler = (_ response:Any?) -> ()
fileprivate var imagePickingHandler: ImageCompletionHandler?
fileprivate var requestedMediaType: PickingMediaType?
fileprivate var shouldEditingEnabled: Bool?
extension UIViewController {
//-----------------------------------------------------------------------------------------------------------
func showImagePickingOptions(type mediaType: PickingMediaType, allowEditing allow: Bool, _ success:@escaping ImageCompletionHandler)
//-----------------------------------------------------------------------------------------------------------
{
requestedMediaType = mediaType
shouldEditingEnabled = allow
imagePickingHandler = success
showOptionSheet()
}
private func showOptionSheet() {
if requestedMediaType == .imageAndVideo {
self.showMediaPicker(withSource: .photoLibrary, andMedia: [kUTTypeImage, kUTTypeGIF, kUTTypeMovie])
} else {
self.showActionSheetWithTitle(title: nil, message: nil, onViewController: self, withButtonArray: ["Choose from Gallery", "Capture from Camera"]) { [unowned self] (index) in
let requestedMedia = (requestedMediaType == .image) ? [kUTTypeImage] : [kUTTypeMovie]
if index == 0 {
self.showGallery(forMedia: requestedMedia)
} else if index == 1 {
self.openCamera(forMedia: requestedMedia)
}
}
}
}
//-----------------------------------------------------------------------------------------------------------
private func showGallery(forMedia mediaType: [CFString])
//-----------------------------------------------------------------------------------------------------------
{
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let authStatus = PHPhotoLibrary.authorizationStatus()
if authStatus == .notDetermined {
PHPhotoLibrary.requestAuthorization({ (status) in
if status == PHAuthorizationStatus.authorized {
self.showImagePicker(withSource: .photoLibrary, andMedia: mediaType)
}
})
} else if authStatus == .restricted || authStatus == .denied {
self.showGalleryDisableAlert()
} else {
self.showImagePicker(withSource: .photoLibrary, andMedia: mediaType)
}
}
}
//-----------------------------------------------------------------------------------------------------------
private func openCamera(forMedia mediaType: [CFString])
//-----------------------------------------------------------------------------------------------------------
{
if UIImagePickerController.isSourceTypeAvailable(.camera) {
self.checkForCamera(forMedia: mediaType)
}
}
//-----------------------------------------------------------------------------------------------------------
private func showMediaPicker(withSource source: UIImagePickerController.SourceType, andMedia mediaType: [CFString])
//-----------------------------------------------------------------------------------------------------------
{
let mediaTypes = mediaType as [String]
DispatchQueue.main.async {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = source
imagePicker.mediaTypes = mediaTypes
imagePicker.allowsEditing = shouldEditingEnabled!
self.present(imagePicker, animated: true, completion: nil)
}
}
//-----------------------------------------------------------------------------------------------------------
private func showImagePicker(withSource source: UIImagePickerController.SourceType, andMedia mediaType: [CFString])
//-----------------------------------------------------------------------------------------------------------
{
let mediaTypes = mediaType as [String]
DispatchQueue.main.async {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = source
imagePicker.mediaTypes = mediaTypes
imagePicker.allowsEditing = shouldEditingEnabled!
self.present(imagePicker, animated: true, completion: nil)
}
}
//-----------------------------------------------------------------------------------------------------------
private func checkForCamera(forMedia mediaType: [CFString])
//-----------------------------------------------------------------------------------------------------------
{
let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if authStatus == .notDetermined {
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) -> Void in
if granted == true {
self.showImagePicker(withSource: .camera, andMedia: mediaType)
}
})
} else if authStatus == .restricted || authStatus == .denied {
self.showCameraDisableAlert()
} else {
self.showImagePicker(withSource: .camera, andMedia: mediaType)
}
}
//-----------------------------------------------------------------------------------------------------------
private func showGalleryDisableAlert()
//-----------------------------------------------------------------------------------------------------------
{
self.showAlertWithTitle(title: "Photo Access Denied", message: "Please enable photo library access in your privacy settings", onViewController: self, withButtonArray: nil, dismissHandler: nil)
}
//-----------------------------------------------------------------------------------------------------------
private func showCameraDisableAlert()
//-----------------------------------------------------------------------------------------------------------
{
self.showAlertWithTitle(title: "Camera Access Denied", message: "Please enable camera access in your privacy settings", onViewController: self, withButtonArray: nil, dismissHandler: nil)
}
}
extension UIViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
//-----------------------------------------------------------------------------------------------------------
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
//-----------------------------------------------------------------------------------------------------------
{
picker.dismiss(animated: true)
if let image: UIImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
imagePickingHandler!(image)
} else {
let videoUrl = info[UIImagePickerController.InfoKey.mediaURL]
picker.dismiss(animated: true) {
imagePickingHandler!(videoUrl)
}
}
// if let selectedImage: UIImage = info[.editedImage] as? UIImage {
// picker.dismiss(animated: true) {
// imagePickingHandler!(selectedImage)
// }
// } else {
// let videoUrl = info[UIImagePickerController.InfoKey.mediaURL]
// picker.dismiss(animated: true) {
// imagePickingHandler!(videoUrl)
// }
// }
}
//-----------------------------------------------------------------------------------------------------------
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
//-----------------------------------------------------------------------------------------------------------
{
DispatchQueue.main.async {
picker.dismiss(animated: true, completion: nil)
}
}
}
extension UIViewController {
fileprivate func showActionSheetWithTitle(title:String? = "", message:String? = "", onViewController:UIViewController?, withButtonArray buttonArray:[String]? = [], dismissHandler:((_ buttonIndex:Int)->())?) -> Void {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
var ignoreButtonArray = false
if buttonArray == nil
{
ignoreButtonArray = true
}
if !ignoreButtonArray
{
for item in buttonArray!
{
let action = UIAlertAction(title: item, style: .default, handler: { (action) in
alertController.dismiss(animated: true, completion: nil)
guard (dismissHandler != nil) else
{
return
}
dismissHandler!(buttonArray!.index(of: item)!)
})
alertController.addAction(action)
}
}
let action = UIAlertAction(title: "cancel", style: .cancel, handler: nil)
alertController.addAction(action)
DispatchQueue.main.async {
onViewController?.present(alertController, animated: true, completion: nil)
}
}
fileprivate func showAlertWithTitle(title:String? = "", message:String? = "", onViewController:UIViewController?, withButtonArray buttonArray:[String]? = [], dismissHandler:((_ buttonIndex:Int)->())?) -> Void {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
var ignoreButtonArray = false
if buttonArray == nil
{
ignoreButtonArray = true
}
if !ignoreButtonArray
{
for item in buttonArray!
{
let action = UIAlertAction(title: item, style: .default, handler: { (action) in
alertController.dismiss(animated: true, completion: nil)
guard (dismissHandler != nil) else
{
return
}
dismissHandler!(buttonArray!.index(of: item)!)
})
alertController.addAction(action)
}
}
let action = UIAlertAction(title: "Ok", style: .cancel, handler: { (action) in
guard (dismissHandler != nil) else
{
return
}
dismissHandler!(LONG_MAX)
})
alertController.addAction(action)
DispatchQueue.main.async {
onViewController?.present(alertController, animated: true, completion: nil)
}
}
}
| true
|
7f8652d4578df0bfbb0a3d340db0a6797f75cc21
|
Swift
|
anthonymobileapps/IOS
|
/ItuneSearch/ItuneSearch/DetailTableViewController.swift
|
UTF-8
| 3,339
| 2.5625
| 3
|
[] |
no_license
|
//
// DetailTableViewController.swift
// ItuneSearch
//
// Created by Anthony Fung on 2019-02-16.
// Copyright © 2019 mac2_ios. All rights reserved.
//
import UIKit
class DetailTableViewController: UITableViewController {
var storeItem: StoreItem?
var storeItems = [StoreItem]()
var isSaveButtonTapped = false
@IBOutlet weak var photoImage: UIImageView!
@IBOutlet weak var shareButton: UIBarButtonItem!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var productNameLabel: UILabel!
@IBOutlet weak var decriptionLable: UILabel!
var urlKey:String?
//var artworkUrl:URL?
override func viewDidLoad() {
super.viewDidLoad()
storeItems = readFromFile()
urlKey = storeItem?.artworkURL.description
setUI( urlKey:urlKey ?? "" )
shareButton.isEnabled = false
}
func setUI(urlKey:String ){
if let url = URL (string: urlKey){
do{
let data = try Data(contentsOf: url)
self.photoImage.image = UIImage (data: data)
}
catch let err{
print("Error : \(err.localizedDescription)")
}
}
productNameLabel.text = storeItem?.name
nameLabel.text = storeItem?.artist
decriptionLable.text =
storeItem?.description
}
@IBAction func shareButtonTapped(_ sender: UIBarButtonItem) {
guard let image = photoImage.image else {return}
let activityController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
activityController.popoverPresentationController?.sourceView = sender as? UIView
present (activityController, animated: true, completion: nil)
}
@IBAction func saveButtonTapped(_ sender: UIBarButtonItem) {
if storeItem?.name != "" {
storeItems.append(storeItem!)
saveToFile()
isSaveButtonTapped = true
shareButton.isEnabled = true
}
// showAlert(title: "Add to Favourite", message: "Successfully save!")
}
func showAlert (title: String, message: String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
showAlertAction(alertController)
}
func showAlertAction (_ alertController: UIAlertController){
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
self.present(alertController,animated:true, completion: nil)
}
func saveToFile(){
let propertyListEncoder = PropertyListEncoder()
let encodedNoteArray = try? propertyListEncoder.encode(storeItems)
try? encodedNoteArray?.write(to: archiveURL, options: .noFileProtection)
}
func readFromFile() -> [StoreItem]{
let propertyListDecoder = PropertyListDecoder()
if let retrievedNotesData = try? Data(contentsOf: archiveURL), let decodedNotes = try? propertyListDecoder.decode(Array<StoreItem>.self, from: retrievedNotesData){
return(decodedNotes)
}else{
return storeItems
}
}
override func viewWillDisappear(_ animated: Bool) {
saveToFile()
}
}
| true
|
b19f5361addf474b98bee23b08bdda9ba4be6921
|
Swift
|
ITzombietux/masters-cocoa
|
/week2-wed/TypingPracticeGameApp/TypingPracticeGameApp/TypingPracticeGame.swift
|
UTF-8
| 1,407
| 3.34375
| 3
|
[] |
no_license
|
//
// TypingPracticeGame.swift
// TypingPracticeGameApp
//
// Created by zombietux on 2020/11/11.
//
import Foundation
import UIKit
struct TypingPraticeGame {
private (set) var currentWord = ""
private (set) var nextWord = ""
private (set) var gamesStep = 0 //1
private (set) var isAnswer = false
private var words: [String] = []
private (set) var currentWordColor: UIColor = .black
let myWords = Words()
mutating func loadWord() {
words = myWords.getWords() // ["asdfasdf", "asdfsdaf", .... ]
currentWord = words[gamesStep] //0 gameStep
nextWord = words[gamesStep + 1]
}
mutating func setWord() {
if currentWord == words[8] {
currentWord = words[gamesStep] //1
nextWord = ""
} else if currentWord == words[9] {
currentWord = myWords.endGame
} else {
currentWord = words[gamesStep] //1
nextWord = words[gamesStep + 1] //2
}
}
mutating func moveWord() {
gamesStep += 1
}
mutating func answerCheck(wordInput: String) {
if currentWord == wordInput {
isAnswer = true
moveWord()
setWord()
currentWordColor = .black //추가미션
} else {
isAnswer = false
currentWordColor = .red //추가미션
}
}
}
| true
|
ab7496604383a5dc32076f9216b29c36fe4b1045
|
Swift
|
justinmilo/Modulus
|
/Interface/1.0 Canvas/Grow.swift
|
UTF-8
| 8,894
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// Grow.swift
// CanvasTester
//
// Created by Justin Smith on 12/17/19.
// Copyright © 2019 Justin Smith. All rights reserved.
//
import SwiftUI
import Geo
import ComposableArchitecture
import Combine
struct GrowUI : UIViewControllerRepresentable {
typealias UIViewControllerType = GrowVC
/// Creates a `UIViewController` instance to be presented.
func makeUIViewController(context: Context) -> GrowVC {
GrowVC()
}
/// Updates the presented `UIViewController` (and coordinator) to the latest
/// configuration.
func updateUIViewController(_ uiViewController: GrowVC, context: Context) {
}
}
public struct ReadScrollState : Equatable {
var contentSize: CGSize
var contentOffset: CGPoint
var rootContentFrame : CGRect
var areaOfInterest : CGRect
var zoomScale: CGFloat
}
struct GrowState : Equatable {
var read: ReadScrollState
var drag: Drag
var zoom: Zoom
}
enum Drag {
case dragging
case decelerating
case none
}
enum Zoom {
case zooming
case none
}
public enum GrowAction {
case onZoomBegin( scrollState : ReadScrollState, pinchLocations:(CGPoint,CGPoint) )
case onZoom(scrollState : ReadScrollState, pinchLocations: (CGPoint,CGPoint) )
case onZoomEnd( scrollState : ReadScrollState )
case onDragBegin( scrollState: ReadScrollState)
case onDrag(scrollState: ReadScrollState)
case onDragEnd(scrollState: ReadScrollState, willDecelerate: Bool)
case onDecelerate(scrollState: ReadScrollState)
case onDecelerateEnd(scrollState: ReadScrollState)
}
struct GrowEnvironment {
}
let growReducer = Reducer<GrowState, GrowAction, GrowEnvironment>.combine(
Reducer{(state: inout GrowState, action: GrowAction, env: GrowEnvironment) -> Effect<GrowAction, Never> in
switch action {
case .onZoomBegin(let scrollState, _),
.onZoom(let scrollState, _),
.onZoomEnd(let scrollState),
.onDragBegin(let scrollState),
.onDrag(let scrollState),
.onDragEnd(let scrollState, _),
.onDecelerate(let scrollState),
.onDecelerateEnd(let scrollState):
state.read = scrollState
}
return .none
},
Reducer{(state: inout GrowState, action: GrowAction, env: GrowEnvironment) -> Effect<GrowAction, Never> in
switch action {
case .onDragBegin:
state.drag = .dragging
case .onDrag: break
case .onDragEnd(_, let willDecelerate):
state.drag = willDecelerate ? Drag.decelerating : Drag.none
case .onDecelerate: break
case .onDecelerateEnd:
state.drag = .none
case .onZoomBegin:
state.zoom = .zooming
case .onZoom:
state.zoom = .zooming
case .onZoomEnd:
state.zoom = .none
}
return .none
}
)
final class ScrollViewCA : UIScrollView, UIScrollViewDelegate
{
var store : Store<GrowState, GrowAction>
var viewStore : ViewStore<GrowState, GrowAction>
var cancellables : Set<AnyCancellable> = []
var rootContent : UIView
var areaOfInterest = NoHitView()
// MARK: - Init
init(frame: CGRect, store: Store<GrowState, GrowAction>, rootContent:UIView) {
self.store = store
self.viewStore = ViewStore(store)
self.rootContent = rootContent
super.init(frame: frame)
self.delegate = self
self.contentSize = viewStore.read.contentSize
self.contentOffset = viewStore.read.contentOffset
self.contentInsetAdjustmentBehavior = .never
self.rootContent.frame = viewStore.read.rootContentFrame
self.addSubview(self.rootContent)
self.areaOfInterest.frame = viewStore.read.areaOfInterest
self.rootContent.addSubview(areaOfInterest)
self.maximumZoomScale = 3.0
self.minimumZoomScale = 0.5
self.showsVerticalScrollIndicator = false
self.showsHorizontalScrollIndicator = false
viewStore.publisher.sink { [weak self] in
guard let self = self else { return }
self.set(state: $0.read)
}.store(in: &self.cancellables)
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.viewStore.send((.onDragBegin(scrollState: self.scrollState)))
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if self.viewStore.drag == .dragging {
self.viewStore.send((.onDrag(scrollState: self.scrollState)))
}
if self.viewStore.drag == .decelerating {
self.viewStore.send(.onDecelerate(scrollState: self.scrollState))
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.viewStore.send(.onDragEnd(scrollState: self.scrollState, willDecelerate: decelerate))
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.viewStore.send(.onDecelerateEnd(scrollState: self.scrollState))
}
func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
guard let pinch = scrollView.pinchGestureRecognizer, pinch.numberOfTouches >= 2 else { return }
let pinches = (pinch.location(ofTouch: 0, in: scrollView), pinch.location(ofTouch: 1, in: scrollView))
self.viewStore.send(.onZoomBegin(scrollState: self.scrollState, pinchLocations: pinches))
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
guard let pinch = scrollView.pinchGestureRecognizer, pinch.numberOfTouches >= 2 else { return }
let pinches = (pinch.location(ofTouch: 0, in: scrollView), pinch.location(ofTouch: 1, in: scrollView))
self.viewStore.send(.onZoom(scrollState: self.scrollState, pinchLocations: pinches))
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
self.viewStore.send(.onZoomEnd(scrollState: self.scrollState))
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
self.rootContent
}
}
extension ScrollViewCA {
var scrollState: ReadScrollState {
ReadScrollState(contentSize: self.contentSize,
contentOffset: self.contentOffset,
rootContentFrame: self.rootContent.frame,
areaOfInterest: self.areaOfInterest.frame,
zoomScale: self.zoomScale)
}
func set(state: ReadScrollState ) {
rootContent.transform = .init(scale: CGScale(factor: state.zoomScale))
self.rootContent.frame = state.rootContentFrame
self.contentSize = state.contentSize
self.bounds.origin = state.contentOffset
self.areaOfInterest.frame = state.areaOfInterest
}
}
import Singalong
class GrowVC : UIViewController {
var store : Store<GrowState,GrowAction>! {
didSet {
self.viewStore = ViewStore(self.store)
}
}
var viewStore : ViewStore<GrowState,GrowAction>!
private var cancellables: Set<AnyCancellable> = []
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
let sizeBiggerThanView = self.view.bounds.size.insetBy(dx: -40, dy: -100)
let grow = GrowState(
read: ReadScrollState(
contentSize: sizeBiggerThanView,
contentOffset: CGPoint(0,0),
rootContentFrame: CGRect(sizeBiggerThanView),
areaOfInterest: CGRect(origin: CGPoint(50,50), size: CGSize(200,200)),
zoomScale: 1.0),
drag: .none,
zoom: .none)
self.store = Store(
initialState: grow,
reducer: growReducer,
environment: GrowEnvironment()
)
let frame = CGRect(self.view.frame.size)
let scrollView = ScrollViewCA(frame: frame, store: self.store!, rootContent: NoHitView())
self.view.addSubview(scrollView )
addBorder(view: scrollView.areaOfInterest, width: 2, color: #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1))
let (l1,l2,l3,l4,l5) = (UILabel(),UILabel(),UILabel(),UILabel(),UILabel())
let stackView = UIStackView(frame: CGRect(x:0,
y: self.view.frame.midX - 50,
width: self.view.frame.width,
height: 100)
)
stackView.addArrangedSubview(l1)
stackView.addArrangedSubview(l2)
stackView.addArrangedSubview(l3)
stackView.addArrangedSubview(l4)
stackView.addArrangedSubview(l5)
stackView.alignment = .center
stackView.distribution = .equalSpacing
stackView.axis = .vertical
self.view.addSubview(stackView)
self.viewStore.publisher.sink {
l1.text = "size: \($0.read.contentSize.rounded(places: 2))"
l2.text = "offset: \($0.read.contentOffset.rounded(places: 2))"
l3.text = "content: \($0.read.rootContentFrame.rounded(places: 2))"
l5.text = "scale: \($0.read.zoomScale.rounded(places: 2))"
}.store(in: &self.cancellables)
}
}
| true
|
60fb162c15f7d6154995fdabd6138d40798f26ef
|
Swift
|
developer-bas/Netflix-Clone
|
/NetflixClone/Helpers/Globalhelpers.swift
|
UTF-8
| 9,608
| 2.703125
| 3
|
[] |
no_license
|
//
// Globalhelpers.swift
// NetflixClone
//
// Created by PROGRAMAR on 21/09/20.
//
import Foundation
import SwiftUI
let exampleVideoURL = URL(string: "https://assets.mixkit.co/videos/preview/mixkit-rolling-on-roller-skates-on-the-ground-of-a-parking-34551-large.mp4")!
let exampleImageURL = URL(string: "https://picsum.photos/300/104")!
let exampleImageURL2 = URL(string: "https://picsum.photos/300/105")!
let exampleImageURL3 = URL(string: "https://picsum.photos/300/106")!
var randomExampleImageURL: URL {
return [exampleImageURL, exampleImageURL2, exampleImageURL3].randomElement() ?? exampleImageURL
}
let exampleTrailer1 = Trailer(name: "Season 3 Trailer", videoURL: exampleVideoURL, thumbnailImageURL: exampleImageURL)
let exampleTrailer2 = Trailer(name: "The Hero's Journey", videoURL: exampleVideoURL, thumbnailImageURL: exampleImageURL2)
let exampleTrailer3 = Trailer(name: "The Mysterious", videoURL: exampleVideoURL, thumbnailImageURL: exampleImageURL3)
let exampleTrailers = [exampleTrailer1, exampleTrailer2, exampleTrailer3]
let episode1 = Episode(name: "Beginnings and Endings",
season: 1,
episodeNumber: 1,
thumbnailImageURLString: "https://picsum.photos/300/112",
description: "Six months after the disappearances, the police form a task force. In 2052, Jonas learns that most of Winden perished in an apocalyptic event.",
length: 53,
videoURL: exampleVideoURL)
let episode2 = Episode(name: "Dark Matter",
season: 1,
episodeNumber: 2,
thumbnailImageURLString: "https://picsum.photos/300/111",
description: "Clausen and Charlotte interview Regina. The Stranger takes Hannah to 1987, where Claudia has an unnerving encounter and Egon visits an old nemesis.",
length: 54,
videoURL: exampleVideoURL)
let episode3 = Episode(name: "Ghosts",
season: 1,
episodeNumber: 3,
thumbnailImageURLString: "https://picsum.photos/300/110",
description: "In 1954, a missing Helge returns, but he'll only speak to Noah. In 1987, Claudia brings the time machine to Tannhaus, and Egon questions Ulrich again.",
length: 56,
videoURL: exampleVideoURL)
let episode4 = Episode(name: "Beginnings and Endings",
season: 2,
episodeNumber: 1,
thumbnailImageURLString: "https://picsum.photos/300/109",
description: "Six months after the disappearances, the police form a task force. In 2052, Jonas learns that most of Winden perished in an apocalyptic event.",
length: 53,
videoURL: exampleVideoURL)
let episode5 = Episode(name: "Dark Matter",
season: 2,
episodeNumber: 2,
thumbnailImageURLString: "https://picsum.photos/300/108",
description: "Clausen and Charlotte interview Regina. The Stranger takes Hannah to 1987, where Claudia has an unnerving encounter and Egon visits an old nemesis.",
length: 54,
videoURL: exampleVideoURL)
let episode6 = Episode(name: "Ghosts",
season: 2,
episodeNumber: 3,
thumbnailImageURLString: "https://picsum.photos/300/107",
description: "In 1954, a missing Helge returns, but he'll only speak to Noah. In 1987, Claudia brings the time machine to Tannhaus, and Egon questions Ulrich again.",
length: 56,
videoURL: exampleVideoURL)
var allExampleEpisodes = [episode1, episode2, episode3, episode4, episode5, episode6]
let exampleMovie1 = Movie(
id: UUID().uuidString,
name: "DARK",
thumbnailURL: URL(string: "https://i.pinimg.com/originals/7b/a3/c3/7ba3c31ae368511e0b3b2ae4e5eececb.jpg")!,
categories: ["Dystopian", "Exciting", "Suspenseful", "Sci-Fi TV"],
episodes: allExampleEpisodes, year: 2020,
rating: "TV-MA",
numberOfSeasons: 2,
accentColor : Color.blue, defaultEpisodeInfo: exampleEpisodeInfo1,
creators: "Baran bo Odan, Jantje Friese",
cast: "Louis Hofmann, Oliver Masucci, jordis Triebel",
moreLikeThisMovies: [exampleMovie2, exampleMovie3, exampleMovie4, exampleMovie5, exampleMovie6, exampleMovie7],
trailers: exampleTrailers, previewImageName: "darkPreview", previewVideoUrl: exampleVideoURL)
let exampleMovie2 = Movie(
id: UUID().uuidString,
name: "La casa de papel",
thumbnailURL: URL(string: "https://www.magazinespain.com/wp-content/uploads/2019/06/la-casa-de-papel-3-poster.jpg")!,
categories: ["Dystopian", "Exciting", "Suspenseful", "Sci-Fi TV"],
year: 2020,
rating: "TV-MA",
numberOfSeasons: 3,
defaultEpisodeInfo: exampleEpisodeInfo1,
creators: "Baran bo Odan, Jantje Friese",
cast: "Louis Hofmann, Oliver Masucci, jordis Triebel",
moreLikeThisMovies: [],
promotionHeadline: "Best Rated Show",
trailers: exampleTrailers, previewImageName: "ozarkPreview" , previewVideoUrl: exampleVideoURL)
let exampleMovie3 = Movie(
id: UUID().uuidString,
name: "Stranger Things",
thumbnailURL: URL(string: "https://images-na.ssl-images-amazon.com/images/I/81QDU13hAAL._AC_SY741_.jpg")!,
categories: ["Dystopian", "Exciting", "Suspenseful", "Sci-Fi TV"],
year: 2020,
rating: "TV-MA",
numberOfSeasons: 3,
defaultEpisodeInfo: exampleEpisodeInfo1,
creators: "Baran bo Odan, Jantje Friese",
cast: "Louis Hofmann, Oliver Masucci, jordis Triebel",
moreLikeThisMovies: [],
trailers: exampleTrailers, previewImageName: "arrestedDevPreview" , previewVideoUrl: exampleVideoURL )
let exampleMovie4 = Movie(
id: UUID().uuidString,
name: "You",
thumbnailURL: URL(string: "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRXduQ2BAANPfWWL-tmrzW7JEX16BzohDmhMg&usqp=CAU")!,
categories: ["Dystopian", "Exciting", "Suspenseful", "Sci-Fi TV"],
year: 2020,
rating: "TV-MA",
numberOfSeasons: 4,
defaultEpisodeInfo: exampleEpisodeInfo1,
creators: "Baran bo Odan, Jantje Friese",
cast: "Louis Hofmann, Oliver Masucci, jordis Triebel",
moreLikeThisMovies: [],
promotionHeadline: "New episodes coming soon",
trailers: exampleTrailers, previewImageName: "darkPreview" , previewVideoUrl: exampleVideoURL)
let exampleMovie5 = Movie(
id: UUID().uuidString,
name: "Black mirror",
thumbnailURL: URL(string: "https://venngage-wordpress.s3.amazonaws.com/uploads/2018/03/image32.jpg")!,
categories: ["Dystopian", "Exciting", "Suspenseful", "Sci-Fi TV"],
year: 2020,
rating: "TV-MA",
numberOfSeasons: 5,
defaultEpisodeInfo: exampleEpisodeInfo1,
creators: "Baran bo Odan, Jantje Friese",
cast: "Louis Hofmann, Oliver Masucci, jordis Triebel",
moreLikeThisMovies: [],
trailers: exampleTrailers, previewImageName: "travelersPreview" , previewVideoUrl: exampleVideoURL)
let exampleMovie6 = Movie(
id: UUID().uuidString,
name: "The witcher",
thumbnailURL: URL(string: "https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/the-witcher-imagenes-y-poster-1562002627.jpeg")!,
categories: ["Dystopian", "Exciting", "Suspenseful", "Sci-Fi TV"],
year: 2020,
rating: "TV-MA",
numberOfSeasons: 6,
defaultEpisodeInfo: exampleEpisodeInfo1,
creators: "Baran bo Odan, Jantje Friese",
cast: "Louis Hofmann, Oliver Masucci, jordis Triebel",
moreLikeThisMovies: [],
promotionHeadline: "Watch Season 6 Now",
trailers: exampleTrailers, previewImageName: "travelersPreview" , previewVideoUrl: exampleVideoURL)
let exampleMovie7 = Movie(
id: UUID().uuidString,
name: "After Life",
thumbnailURL: URL(string: "https://picsum.photos/200/305")!,
categories: ["Dystopian", "Exciting", "Suspenseful", "Sci-Fi TV"],
year: 2020,
rating: "TV-MA",
numberOfSeasons: 6,
defaultEpisodeInfo: exampleEpisodeInfo1,
creators: "Baran bo Odan, Jantje Friese",
cast: "Louis Hofmann, Oliver Masucci, jordis Triebel",
moreLikeThisMovies: [],
promotionHeadline: "Watch Season 6 Now",
trailers: exampleTrailers, previewImageName: "darkPreview")
var exampleMovies: [Movie] {
return [exampleMovie1, exampleMovie2, exampleMovie3, exampleMovie4, exampleMovie5, exampleMovie6].shuffled()
}
let exampleEpisodeInfo1 = CurrentEpisodeInfo(episodeName: "Beginnings and Endings", description: "Six months after the disappearances, the police form a task force. In 2052, Jonas learns that most of Winden perished in an apocalyptic event.", season: 2, episode: 1)
extension LinearGradient{
static let blackOpacityGradient = LinearGradient(
gradient: Gradient(colors: [Color.black.opacity(0.0), Color.black.opacity(0.95)]),
startPoint: .top,
endPoint: .bottom
)
}
extension String{
func widthOfString(usingFont font:UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.width
}
}
extension View {
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
extension View {
@ViewBuilder func isHidden(_ hidden: Bool, remove: Bool = false) -> some View {
if hidden {
if !remove {
self.hidden()
}
}else{
self
}
}
}
| true
|
3adfd70d4a64682cb9390cfdb554b7ae8f67ab16
|
Swift
|
bleege/FCFinderV2App
|
/Shared/Country.swift
|
UTF-8
| 344
| 2.890625
| 3
|
[] |
no_license
|
//
// Country.swift
// FCFinderV2App
//
// Created by Brad Leege on 8/2/20.
//
import Foundation
struct Country: Identifiable, Hashable {
let id: UUID
let countryId: Int
let name: String
init(countryId: Int, name: String) {
self.id = UUID()
self.countryId = countryId
self.name = name
}
}
| true
|
fa219d1cd6c9c7353f9bfc4cd40259a57eeb0954
|
Swift
|
suho/learn-swift
|
/Chapter1/Basic Swift From C/Chapter2Ex3.playground/Contents.swift
|
UTF-8
| 1,420
| 3.578125
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
//Bài 3: Giải bất phương trình bậc 2 > 0
var x1: Double = 0
var x2: Double = 0
func giaiBatPhuongTrinhBac2(heSoA a: Double, heSoB b: Double, heSoC c: Double) -> String {
if a == 0 {
if b == 0 {
if c > 0 {
return "Bat Phuong Trinh Co Vo So Nghiem"
} else {
return "Bat Phuong Trinh Vo Nghiem"
}
} else {
x1 = -c/b
if b > 0 {
return "Bat Phuong trinh co nghiem x > \(x1)"
} else {
return "Bat Phuong trinh co nghiem x < \(x1)"
}
}
} else {
let delta = sqrt(b) - 4*a*c
if a > 0 {
if delta <= 0 {
return "Bat Phuong trinh dung voi moi x"
} else {
x1 = (-b-sqrt(delta))/(2*a)
x2 = (-b-sqrt(delta))/(2*a)
return "Bat Phuong trinh co nghiem x < \(x1) hoac x > \(x2)"
}
} else {
if delta <= 0 {
return "Bat Phuong Trinh Vo Nghiem"
} else {
x1 = (-b-sqrt(delta))/(2*a)
x2 = (-b-sqrt(delta))/(2*a)
return "Bat Phuong trinh co nghiem \(x1) < x < \(x2)"
}
}
}
}
let str = giaiBatPhuongTrinhBac2(heSoA: -11, heSoB: 2, heSoC: 1)
print(str)
| true
|
0a317dd40b263a6fc38a77ca282fbb4c56bcd653
|
Swift
|
fnxpt/OpenWeatherTest
|
/OpenWeather/Protocols/Updatable.swift
|
UTF-8
| 52
| 2.640625
| 3
|
[] |
no_license
|
protocol Updatable {
func update(model: Any?)
}
| true
|
59ffa8cea37a64c2309a461ae8e333b28bd86f3b
|
Swift
|
Polarity4Ltd/Project-13-iOS
|
/Project Thirteen/cellDetailsViewController.swift
|
UTF-8
| 1,083
| 2.515625
| 3
|
[] |
no_license
|
//
// cellDetailsViewController.swift
// Project Thirteen
//
// Created by Alex Pilcher on 17/07/2019.
// Copyright © 2019 Alex Pilcher. All rights reserved.
//
import UIKit
class cellDetailsViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var dateTimeLabel: UILabel!
var cellTitle: String = ""
var cellText: String = ""
var cellDateCreated: String = ""
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = cellTitle
contentLabel.text = cellText
dateTimeLabel.text = cellDateCreated
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
9bb5b65ab182ca150392f912735b540b7fda41a8
|
Swift
|
iyinraphael/FetchRewards-ios-exercise
|
/FetchRewards-ios-exercise/FetchRewards-ios-exercise/View/GeekSeatEventTableViewCell.swift
|
UTF-8
| 6,534
| 2.578125
| 3
|
[] |
no_license
|
//
// GeekSeatTableViewCell.swift
// FetchRewards-ios-exercise
//
// Created by Iyin Raphael on 2/2/21.
//
import UIKit
class GeekSeatEventTableViewCell: UITableViewCell {
// MARK: - Properties
var eventImageView: UIImageView!
var favoriteImageView: UIImageView!
var eventTitleLabel: UILabel!
var eventCityAndStateLabel: UILabel!
var datetimeLabel: UILabel!
var cellView: UIView!
var cellContentView: UIView!
private let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM YYY \nHH:mm a"
return dateFormatter
}()
var seatGeekEvent: GeekSeatEvent?{
didSet{
configureCell()
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
cellContentView = UIView()
cellContentView.translatesAutoresizingMaskIntoConstraints = false
cellContentView.backgroundColor = .white
addSubview(cellContentView)
cellView = UIView()
cellView.translatesAutoresizingMaskIntoConstraints = false
cellView.layer.frame = contentView.bounds
cellView.backgroundColor = .white
cellView.layer.backgroundColor = UIColor.white.cgColor
cellView.layer.contentsGravity = .center
cellView.layer.magnificationFilter = .linear
cellView.layer.cornerRadius = 10.0
cellView.layer.borderWidth = 0.1
cellView.layer.borderColor = UIColor.white.cgColor
cellView.layer.shadowOpacity = 0.4
cellView.layer.shadowOffset = CGSize(width: 0, height: 3)
cellView.layer.shadowRadius = 3.0
cellView.layer.isGeometryFlipped = false
cellContentView.addSubview(cellView)
favoriteImageView = UIImageView()
favoriteImageView.translatesAutoresizingMaskIntoConstraints = false
eventImageView = UIImageView()
eventImageView.translatesAutoresizingMaskIntoConstraints = false
eventImageView.layer.cornerRadius = 10
eventImageView.clipsToBounds = true
eventTitleLabel = UILabel()
eventTitleLabel.translatesAutoresizingMaskIntoConstraints = false
eventTitleLabel.numberOfLines = 0
eventTitleLabel.font = .boldSystemFont(ofSize: 18)
eventCityAndStateLabel = UILabel()
eventCityAndStateLabel.translatesAutoresizingMaskIntoConstraints = false
eventCityAndStateLabel.font = .systemFont(ofSize: 15)
eventCityAndStateLabel.textColor = .gray
datetimeLabel = UILabel()
datetimeLabel.translatesAutoresizingMaskIntoConstraints = false
datetimeLabel.font = .systemFont(ofSize: 15)
datetimeLabel.textColor = .gray
datetimeLabel.numberOfLines = 0
cellView.addSubview(favoriteImageView)
cellView.addSubview(eventImageView)
cellView.insertSubview(eventImageView, belowSubview: favoriteImageView)
cellView.addSubview(eventTitleLabel)
cellView.addSubview(eventCityAndStateLabel)
cellView.addSubview(datetimeLabel)
NSLayoutConstraint.activate([
cellContentView.topAnchor.constraint(equalTo: topAnchor),
cellContentView.leadingAnchor.constraint(equalTo: leadingAnchor),
cellContentView.trailingAnchor.constraint(equalTo: trailingAnchor),
cellContentView.bottomAnchor.constraint(equalTo: bottomAnchor),
cellView.topAnchor.constraint(equalTo: cellContentView.topAnchor),
cellView.leadingAnchor.constraint(equalTo: cellContentView.leadingAnchor, constant: 10),
cellView.trailingAnchor.constraint(equalTo: cellContentView.trailingAnchor, constant: -10),
cellView.bottomAnchor.constraint(equalTo: cellContentView.bottomAnchor, constant: -10),
favoriteImageView.topAnchor.constraint(equalTo: cellView.topAnchor),
favoriteImageView.leadingAnchor.constraint(equalTo: cellView.leadingAnchor, constant: 5),
favoriteImageView.heightAnchor.constraint(equalToConstant: 30),
favoriteImageView.widthAnchor.constraint(equalToConstant: 30),
eventImageView.topAnchor.constraint(equalTo: cellView.topAnchor, constant: 10),
eventImageView.leadingAnchor.constraint(equalTo: cellView.leadingAnchor, constant: 10),
eventImageView.heightAnchor.constraint(equalToConstant: 75),
eventImageView.widthAnchor.constraint(equalToConstant: 75),
eventTitleLabel.topAnchor.constraint(equalTo: cellView.topAnchor, constant: 10),
eventTitleLabel.leadingAnchor.constraint(equalTo: eventImageView.trailingAnchor, constant: 10),
eventTitleLabel.trailingAnchor.constraint(equalTo: cellView.trailingAnchor, constant: -10),
eventCityAndStateLabel.topAnchor.constraint(equalTo: eventTitleLabel.bottomAnchor, constant: 10),
eventCityAndStateLabel.leadingAnchor.constraint(equalTo: eventImageView.trailingAnchor, constant: 10),
eventCityAndStateLabel.trailingAnchor.constraint(equalTo: cellView.trailingAnchor, constant: -10),
datetimeLabel.topAnchor.constraint(equalTo: eventCityAndStateLabel.bottomAnchor, constant: 10),
datetimeLabel.leadingAnchor.constraint(equalTo: eventImageView.trailingAnchor, constant: 10),
datetimeLabel.trailingAnchor.constraint(equalTo: cellView.trailingAnchor, constant: -10),
datetimeLabel.bottomAnchor.constraint(equalTo: cellView.bottomAnchor, constant: -10)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Methods
func configureCell() {
eventTitleLabel.text = seatGeekEvent?.title
let cityAndState = "\(seatGeekEvent?.venue.city ?? ""), \(seatGeekEvent?.venue.state ?? "")"
eventCityAndStateLabel.text = cityAndState
let date = dateFormatter.date(from: seatGeekEvent?.datetimeLocal ?? "")
datetimeLabel.text = dateFormatter.string(from: date ?? Date())
if seatGeekEvent?.isFavorite == true {
favoriteImageView.image = UIImage(named: "favorite.red")
} else {
favoriteImageView.image = nil
}
}
}
| true
|
cda0cec761adb35cf619cfa9ba4a8473e07e9477
|
Swift
|
SamuelCowin/PriorityDeclarationPrototype
|
/PriorityDeclarationPrototype/PriorityDeclarationPrototype/PriorityDeclarationPrototypeTests/PriorityDeclarationPrototypeTests.swift
|
UTF-8
| 1,193
| 3.15625
| 3
|
[] |
no_license
|
//
// PriorityDeclarationPrototypeTests.swift
// PriorityDeclarationPrototypeTests
//
// Created by Samuel Cowin on 1/6/17.
// Copyright © 2017 Shepard. All rights reserved.
//
import XCTest
@testable import PriorityDeclarationPrototype
class PriorityDeclarationPrototypeTests: XCTestCase {
//MARK: Priority Class Tests
// Confirm that the Meal initializer returns a Meal object when passed valid parameters.
func testPriorityInitializationSucceeds() {
// Zero rating
let zeroRatingPriority = RoadPriority.init(fromDate: "Zero", toDate: "hello", priorityValue: 0)
XCTAssertNotNil(zeroRatingPriority)
// Highest positive rating
let positiveRatingPriority = RoadPriority.init(fromDate: "Positive", toDate: "hskdfvnod", priorityValue: 100)
XCTAssertNotNil(positiveRatingPriority)
}
// Confirm that the Meal initialier returns nil when passed a negative rating or an empty name.
func testPriorityInitializationFails() {
// Empty String
let emptyStringPriority = RoadPriority.init(fromDate: "", toDate: "", priorityValue: 0)
XCTAssertNil(emptyStringPriority)
}
}
| true
|
2c9abdd8f61a19e14328f0f0efb4414d27464c63
|
Swift
|
qiang512833564/Logo
|
/LogoCompiler/Extension/Character+Extension.swift
|
UTF-8
| 2,518
| 3.515625
| 4
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// Character+Extension.swift
// LogoCompiler
//
// Created by developer on 8/19/19.
// Copyright © 2019 iOSDevLog. All rights reserved.
//
import Foundation
// MARK: - Properties
public extension Character {
/// Check if character is emoji
/// - example: Character("😊").isEmoji -> true
var isEmoji: Bool {
let scalarValue = String(self).unicodeScalars.first!.value
switch scalarValue {
case 0x3030, 0x00AE, 0x00A9, // Special Character > 特殊字符
0x1D000...0x1F77F, // Emoticons > 情感符
0x2100...0x27BF, // Misc symbols and Dingbats >
0xFE00...0xFE0F, // Variation Selectors > 变异选择符
0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs > 补充的符号和象形文字
return true
default:
return false
}
}
/// Check if character is number
/// - example: Character("1").isNummber
var isNumber: Bool {
return Int(String(self)) != nil
}
/// Check if character is a letter(字母)
/// - example: (1) Character("4").isLetter -> false, (2) Character("a").isLetter -> True
var isLetter: Bool {
return String(self).rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
}
/// Check if character is lowercased
/// - example: (1) Character("a").isLowercased -> true, (2) Character("A").isLowercased -> false
var isLowercased: Bool {
return String(self) == String(self).lowercased()
}
/// Check if character is uppercased
/// - example: (1) Character("a").isUppercased -> true, (2) Character("A").isUppercased -> true
var isUppercased: Bool {
return String(self) == String(self).uppercased()
}
/// Check if character is white space(空格)
/// - example: (1) Character(" ").isWhiteSpace -> true, (2) Character("A").isWhiteSpace -> false
var isWhiteSpace: Bool {
return String(self) == " ";
}
/// Integer value from character (if applicable)
/// - example: (1) Character("1").int -> 1, (2) Character("A").int -> nil
var int: Int? {
return Int(String(self))
}
// String value from character
var string: String {
return String(self)
}
/// Return the character lowercased
var lowercased: Character {
return String(self).lowercased().first!
}
/// Return the character uppercased
var uppercased: Character {
return String(self).uppercased().first!
}
}
| true
|
6eda8b09923369e63187963ebc896c9378f0c2ab
|
Swift
|
WolfAndrei/AppStoreDemo
|
/AppStoreDemo/Views/MusicFooterView.swift
|
UTF-8
| 1,190
| 2.75
| 3
|
[] |
no_license
|
//
// MusicFooterView.swift
// AppStoreDemo
//
// Created by Andrei Volkau on 26.08.2020.
// Copyright © 2020 Andrei Volkau. All rights reserved.
//
import UIKit
class MusicFooterView: UICollectionReusableView {
let activityIndicator: UIActivityIndicatorView = {
let aiv = UIActivityIndicatorView(style: .large)
aiv.tintColor = .darkGray
aiv.startAnimating()
return aiv
}()
let label: UILabel = {
let label = UILabel()
label.text = "Loading..."
label.textAlignment = .center
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupLayout() {
let stackView = VerticalStackView(arrangedSubviews: [activityIndicator, label], spacing: 8).withWidth(frame.width)
addSubview(stackView)
stackView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
}
| true
|
6ccbf6db15acfd0244cababff65b761cd02a4728
|
Swift
|
DevMountain/Bookshelf
|
/Bookshelf/Bookshelf/Model/Book.swift
|
UTF-8
| 498
| 3.046875
| 3
|
[] |
no_license
|
//
// Book.swift
// Bookshelf
//
// Created by Cameron Stuart on 12/14/20.
//
import UIKit
class Book {
let title: String
let author: String
let releaseYear: Int
let cover: UIImage
let description: String
init(title: String, author: String, releaseYear: Int, cover: UIImage, description: String) {
self.title = title
self.author = author
self.releaseYear = releaseYear
self.cover = cover
self.description = description
}
}
| true
|
2b1f77ad71ed6d79827ebc814017fc7ce386360d
|
Swift
|
MarwenRh/runloop-queue
|
/RunloopQueue/RunloopQueue+Streams.swift
|
UTF-8
| 1,252
| 2.78125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
//
// RunloopQueue+Streams.swift
// RunloopQueue
//
// Created by Daniel Kennett on 2017-02-14.
// For license information, see LICENSE.md.
//
import Foundation
public extension RunloopQueue {
/// Schedules the given stream into the queue.
///
/// - Parameter stream: The stream to schedule.
@objc(scheduleStream:)
func schedule(_ stream: Stream) {
if let input = stream as? InputStream {
sync { CFReadStreamScheduleWithRunLoop(input as CFReadStream, CFRunLoopGetCurrent(), .commonModes) }
} else if let output = stream as? OutputStream {
sync { CFWriteStreamScheduleWithRunLoop(output as CFWriteStream, CFRunLoopGetCurrent(), .commonModes) }
}
}
/// Removes the given stream from the queue.
///
/// - Parameter stream: The stream to remove.
@objc(unscheduleStream:)
func unschedule(_ stream: Stream) {
if let input = stream as? InputStream {
sync { CFReadStreamUnscheduleFromRunLoop(input as CFReadStream, CFRunLoopGetCurrent(), .commonModes) }
} else if let output = stream as? OutputStream {
sync { CFWriteStreamUnscheduleFromRunLoop(output as CFWriteStream, CFRunLoopGetCurrent(), .commonModes) }
}
}
}
| true
|
86f421bdcdccf56a7bc7dd97a2987c49cde6a9ee
|
Swift
|
eduardo22i/ankat
|
/Ankat/MyOffers/OfferCalendarViewController.swift
|
UTF-8
| 6,020
| 2.65625
| 3
|
[] |
no_license
|
//
// OfferCalendarViewController.swift
// Ankat
//
// Created by Eduardo Irías on 8/3/15.
// Copyright (c) 2015 Estamp. All rights reserved.
//
import UIKit
import Parse
func < (left: Date, right: Date) -> Bool {
return left.compare(right) == ComparisonResult.orderedAscending
}
func == (left: Date, right: Date) -> Bool {
return left.compare(right) == ComparisonResult.orderedSame
}
struct DateRange : Sequence {
var calendar: Calendar
var startDate: Date
var endDate: Date
var stepUnits: NSCalendar.Unit
var stepValue: Int
func makeIterator() -> Iterator {
return Iterator(range: self)
}
struct Iterator: IteratorProtocol {
var range: DateRange
mutating func next() -> Date? {
let nextDate = (range.calendar as NSCalendar).date(byAdding: range.stepUnits,
value: range.stepValue,
to: range.startDate,
options: NSCalendar.Options())
if range.endDate.compare(nextDate!) == .orderedAscending {
return nil
}
else {
range.startDate = nextDate!
return nextDate
}
}
}
}
class OfferCalendarViewController: UIViewController, GLCalendarViewDelegate {
var recommendation : Offer!
@IBOutlet var calendarView : GLCalendarView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = recommendation.name
self.calendarView.delegate = self
self.calendarView.showMaginfier = false
let today = Date()
self.calendarView.firstDate = GLDateUtils.date(byAddingDays: -120, to: today)
self.calendarView.lastDate = GLDateUtils.date(byAddingDays: 120, to: today)
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: { () -> Void in
DataManager.findOfferDates(self.recommendation, completionBlock: { (offerDates : [Any]?, error: Error?) in
let ranges : NSMutableArray = NSMutableArray()
if let offerDates = offerDates as? [PFObject] {
for offerDate in offerDates {
if let date = offerDate["startDate"] as? Date, let range = GLCalendarDateRange(begin: date, end: date) {
range.editable = false
range.backgroundColor = UIColor().appGreenLigthColor()
ranges.add(range)
}
}
self.calendarView.ranges = ranges
self.calendarView.reload()
DispatchQueue.main.async(execute: { () -> Void in
self.calendarView.scroll(to: today, animated: false)
})
}
})
})
}
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.
if let vc = segue.destination as? SelectOfferDayViewController {
let calendar = Calendar.current
var days : [Date] = []
for ranges in calendarView.ranges {
if let ranges = ranges as? GLCalendarDateRange {
let dateRange = DateRange(calendar: calendar,
startDate: ranges.beginDate,
endDate: ranges.endDate,
stepUnits: .day,
stepValue: 1)
days.append(ranges.beginDate)
for date in dateRange {
days.append(date)
}
}
}
vc.days = days
vc.recommendation = recommendation
}
}
//MARK: GLCalendarViewDelegate
func calenderView(_ calendarView: GLCalendarView!, rangeToAddWithBegin beginDate: Date!) -> GLCalendarDateRange! {
let endDate = GLDateUtils.date(byAddingDays: 0, to: beginDate)
let range = GLCalendarDateRange(begin: beginDate, end: endDate)
range?.editable = true
range?.backgroundColor = UIColor().appGreenColor()
calendarView.begin(toEdit: range)
return range
}
func calenderView(_ calendarView: GLCalendarView!, canAddRangeWithBegin beginDate: Date!) -> Bool {
if beginDate.compare(Date()) == .orderedSame {
return true
}
if beginDate.compare(Date()) == .orderedDescending {
return false
}
return true
}
func calenderView(_ calendarView: GLCalendarView!, canUpdate range: GLCalendarDateRange!, toBegin beginDate: Date!, end endDate: Date!) -> Bool {
return true
}
func calenderView(_ calendarView: GLCalendarView!, beginToEdit range: GLCalendarDateRange!) {
if self.calendarView.ranges.contains(range) {
self.calendarView.removeRange(range)
}
}
func calenderView(_ calendarView: GLCalendarView!, didUpdate range: GLCalendarDateRange!, toBegin beginDate: Date!, end endDate: Date!) {
}
func calenderView(_ calendarView: GLCalendarView!, finishEdit range: GLCalendarDateRange!, continueEditing: Bool) {
}
}
| true
|
bfe1830676d4c1e67f11194574f35aa73025a613
|
Swift
|
moryk87/Coin
|
/Coin/NotificationLabel.swift
|
UTF-8
| 730
| 2.84375
| 3
|
[] |
no_license
|
//
// NotificationLabel.swift
// Coin
//
// Created by Jan Moravek on 04/01/2018.
// Copyright © 2018 Jan Moravek. All rights reserved.
//
import Foundation
class NotificationLabel {
var coinNameCell : String
var tickerCell : String
var conditionCell : String
var valueCell : Float
var currencyCell : String
var keyCell : String
init (coinNameCell: String, tickerCell: String, conditionCell: String, valueCell: Float, currencyCell: String, keyCell: String) {
self.coinNameCell = coinNameCell
self.tickerCell = tickerCell
self.conditionCell = conditionCell
self.valueCell = valueCell
self.currencyCell = currencyCell
self.keyCell = keyCell
}
}
| true
|
35bb0d4068d19835a1b3bc830bd5d70a62be6b16
|
Swift
|
Pavel71/MyBSL
|
/InsulinProjectBSL/Workers/Animator/SlideMenuAnimated/SlideMenuAnimated.swift
|
UTF-8
| 1,125
| 2.578125
| 3
|
[] |
no_license
|
//
// SlideMenuAnimated.swift
// InsulinProjectBSL
//
// Created by PavelM on 19/09/2019.
// Copyright © 2019 PavelM. All rights reserved.
//
import UIKit
class SlideMenuAnimated {
static let animator: UIViewPropertyAnimator = {
return UIViewPropertyAnimator(duration: 0.5, curve: .easeOut)
}()
static func closeMenu(view: UIView) {
animator.addAnimations {
view.frame.origin.x = 0
}
// Это кгода Continue Animation
animator.addCompletion { position in
}
animator.startAnimation()
}
// static func closeMenu(gesture: UIPanGestureRecognizer, view: UIView) {
//
//
// switch gesture.state {
//
// case .began:
// print("Начало")
// animator.pauseAnimation()
// case .changed:
// print("изменяется")
// let translationX = -gesture.translation(in: view).x
// animator.fractionComplete = translationX
//
// case .ended:
// print("Конец")
// animator.continueAnimation(withTimingParameters: nil, durationFactor: 0)
// default: break
// }
// }
}
| true
|
3dfb5f749b7d63419f9ccec76faef5f1cb46c9e3
|
Swift
|
ThangaAyyanar/swift
|
/Advent of Code/Day 10/Sources/Day 10/Day_10.swift
|
UTF-8
| 2,660
| 3.515625
| 4
|
[] |
no_license
|
public struct Day_10 {
var inputs: [String]
public init(inputs: [String]) {
self.inputs = inputs
}
func getSyntaxScore(char: String) -> Int {
switch char {
case ")":
return 3
case "]":
return 57
case "}":
return 1197
case ">":
return 25137
default:
return 0
}
}
func part1() -> Int {
var count = 0
for input in inputs {
var stack = [String]()
for _char in input {
let char = String(_char)
if char == "(" || char == "[" || char == "{" || char == "<" {
stack.append(char)
}
else if let last = stack.popLast() {
if (last == "(" && char != ")") ||
(last == "[" && char != "]") ||
(last == "{" && char != "}") ||
(last == "<" && char != ">"){
count += getSyntaxScore(char: char)
break
}
}
}
}
return count
}
func getSyntaxScorePart2(char: String) -> Int {
switch char {
case "(":
return 1
case "[":
return 2
case "{":
return 3
case "<":
return 4
default:
return 0
}
}
func part2() -> Int {
var count = [Int]()
for input in inputs {
var stack = [String]()
var isCorrupted = false
for _char in input {
let char = String(_char)
if char == "(" || char == "[" || char == "{" || char == "<" {
stack.append(char)
}
else if let last = stack.popLast() {
if (last == "(" && char != ")") ||
(last == "[" && char != "]") ||
(last == "{" && char != "}") ||
(last == "<" && char != ">"){
isCorrupted = true
}
}
}
if isCorrupted == false && stack.isEmpty == false {
var localCount = 0
for char in stack.reversed() {
localCount = (localCount * 5) + getSyntaxScorePart2(char: char)
}
/*print("\(stack.joined()) and its count is \(localCount)")*/
count.append(localCount)
}
}
return count.sorted()[count.count/2]
}
}
| true
|
2dc0de6b4d8672c209ad796557967d4bb4163b17
|
Swift
|
Arthurli/TextureSwiftDemo
|
/TextureSwiftDemo/ASTableDemo/Demo1RootNode.swift
|
UTF-8
| 2,933
| 3.015625
| 3
|
[] |
no_license
|
//
// Demo1RootNode.swift
// TextureSwiftDemo
//
// Created by 李晨 on 2019/1/16.
// Copyright © 2019 李晨. All rights reserved.
//
import Foundation
import AsyncDisplayKit
class Demo1RootNode: ASDisplayNode, ASTableDelegate, ASTableDataSource {
var tableNode: ASTableNode = ASTableNode()
var imageCategory: String = ""
var nodes: [Demo1DetailNode] = []
override init() {
super.init()
self.automaticallyManagesSubnodes = true
self.backgroundColor = UIColor.yellow
self.tableNode.delegate = self
self.tableNode.dataSource = self
self.tableNode.backgroundColor = UIColor.white
DispatchQueue.global().async {
for i in 1...1000 {
let node = Demo1DetailNode()
node.row = i
let range = ASSizeRangeMake(CGSize(width: UIScreen.main.bounds.width, height: 0), CGSize(width: UIScreen.main.bounds.width, height: 10000))
node.layoutThatFits(range)
self.nodes.append(node)
}
DispatchQueue.main.async {
self.tableNode.reloadData()
}
}
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
self.tableNode.style.preferredSize = UIScreen.main.bounds.size
return ASAbsoluteLayoutSpec(children: [self.tableNode])
}
func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) {
tableNode.reloadData()
}
func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int {
return nodes.count
}
func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode {
return nodes[indexPath.row]
}
}
class Demo1DetailNode: ASCellNode {
var row: Int = 0
var cache: ASLayout?
var imageNode: ASNetworkImageNode = ASNetworkImageNode()
var imageURL: URL {
let imageSize = self.calculatedSize;
return URL(string: "http://lorempixel.com/\(Int(imageSize.width))/\(Int(imageSize.height))/cats/\(self.row%10)")!
}
override init() {
super.init()
self.automaticallyManagesSubnodes = true
}
override func layoutDidFinish() {
super.layoutDidFinish()
self.imageNode.url = self.imageURL
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
return ASRatioLayoutSpec(ratio: 1, child: self.imageNode)
}
override func calculateLayoutThatFits(_ constrainedSize: ASSizeRange, restrictedTo size: ASLayoutElementSize, relativeToParentSize parentSize: CGSize) -> ASLayout {
if let cache = self.cache {
return cache
}
let cache = super.calculateLayoutThatFits(constrainedSize, restrictedTo: size, relativeToParentSize: parentSize)
self.cache = cache
return cache
}
}
| true
|
875f4d19bb0f72760854f6d331e695d270e060f3
|
Swift
|
amichnia/BrainCloud
|
/SkillCloud/Classes/Utils/Extensions/UIKit/UIColor+Extensions.swift
|
UTF-8
| 2,473
| 2.921875
| 3
|
[] |
no_license
|
//
// UIColor+Extensions.swift
// SkillCloud
//
// Created by Andrzej Michnia on 02/07/16.
// Copyright © 2016 amichnia. All rights reserved.
//
import UIKit
// MARK: - Color
extension UIColor {
convenience init(rgba: (CGFloat,CGFloat,CGFloat,CGFloat)) {
self.init(red: rgba.0, green: rgba.1, blue: rgba.2, alpha: rgba.3)
}
convenience init?(rgbString: String, separator: Character = ",") {
self.init(rgbaString: rgbString, separator: separator)
}
convenience init?(rgbaString: String, separator: Character = ",") {
let components = rgbaString.characters.split(separator: separator).map(String.init)
guard components.count == 4 || components.count == 3 else {
return nil
}
guard
let red = Int(components[0]),
let green = Int(components[1]),
let blue = Int(components[2]),
let alpha = components.count == 4 ? Int(components[3]) : 255
else {
return nil
}
self.init(red: red, green: green, blue: blue, alphaValue: alpha)
}
func randomAbbreviation() -> UIColor {
var color : (CGFloat,CGFloat,CGFloat,CGFloat) = (0,0,0,0)
self.getRed(&color.0, green: &color.1, blue: &color.2, alpha: &color.3)
color.0 += CGFloat(arc4random()%40 - 20)
color.1 += CGFloat(arc4random()%40 - 20)
return UIColor(rgba: color)
}
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(red: Int, green: Int, blue: Int, alphaValue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alphaValue) / 255.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}
| true
|
584b73b4c882731fecfa6faa351d78e4506ce30d
|
Swift
|
lemonnv/RandomUser-iOS
|
/App/Scenes/UsersList/UsersListRouter.swift
|
UTF-8
| 801
| 2.8125
| 3
|
[] |
no_license
|
//
// UsersListRouter.swift
// RandomUser
//
// Created by Vincent Lemonnier on 11/02/2020.
// Copyright (c) 2020 Vincent Lemonnier. All rights reserved.
//
import UIKit
protocol UsersListRouting: class {
func routeToDetail(user: User)
}
class UsersListRouter: UsersListRouting {
public weak var viewController: UIViewController?
//MARK: Object lifecycle
public init(viewController: UIViewController?) {
self.viewController = viewController
}
//MARK: Routing
func routeToDetail(user: User) {
let userDetailsDisplay: UserDetailsDisplay = resolve(argument: user)
if let userDetailsViewController = userDetailsDisplay.viewController {
self.viewController?.present(userDetailsViewController, animated: true)
}
}
}
| true
|
91d8d42c3aba317822f2f5441bc31e3db60f4011
|
Swift
|
WooRaZil-Boy/Raywenderlich_iOS
|
/Core_Data/Dog Walk/Dog Walk/CoreDataStack.swift
|
UTF-8
| 5,167
| 3.21875
| 3
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
//
// CoreDataStack.swift
// Dog Walk
//
// Created by 근성가이 on 2018. 3. 10..
// Copyright © 2018년 Razeware. All rights reserved.
//
import Foundation
import CoreData
class CoreDataStack {
//MARK: - Properties
private let modelName: String //저장할 속성 이름
private lazy var storeContainer: NSPersistentContainer = { //NSPersistentContainer 초기화
let container = NSPersistentContainer(name: self.modelName) //CoreData Stack이 캡슐화된 객체
container.loadPersistentStores { storeDescription, error in //PersistentStore를 가져온다.
if let error = error as NSError? {
print("Unresolved error \(error), \(error.userInfo)")
}
}
return container
}()
lazy var managedContext: NSManagedObjectContext = {
return self.storeContainer.viewContext //NSManagedObjectContext를 가져온다
}()
//storeContainer가 private이므로, 외부에서 CoreDataStack에 접근할 수 있는 속성은 managedContext 뿐이다.
//managedContext는 나머지 CoreData Stack에 접근하는데 필요한 유일한 진입점이다.
//PersistentStoreCoordinator는 NSManagedObjectContext의 공용 속성이다.
//또한, ManagedObjectModel과 PersistentStore은 PersistentStoreCoordinator의 공용 속성이다.
//결국 managedContext로 다른 CoreData Stack에 접근할 수 있다. NSPersistentContainer안에 존재
//MARK: - LifeCycle
init(modelName: String) {
self.modelName = modelName
}
}
extension CoreDataStack {
func saveContext() {
guard managedContext.hasChanges else { return } //변경 있을 때만 저장한다.
do {
try managedContext.save() //저장
} catch let error as NSError {
print("Unresolved error \(error), \(error.userInfo)")
}
}
}
//CoreData Stack은 4개의 클래스로 구성되어 있다. //4개 모두 맞물려 돌아가며, 분리하여 각각 사용하는 경우의 거의 없다.
//• NSManagedObjectModel : 데이터 모델 객체의 유형, 속성 및 관계를 나타낸다. 데이터 베이스 스키마로 생각하면 된다.
// SQLite를 사용하는 경우, 스키마가 된다. 하지만, SQLite 외에 다른 유형으로 CoreData를 생성할 수도 있다.
// xcdatamodel 파일을 작성하고 편집하는 특별한 컴파일러 momc가 있다. CoreData는 컴파일된 momd 폴더 내용을 사용해
// 런타임 시 NSManagedObjectModel을 초기화한다.
//• NSPersistentStore : 사용하기로 한 저장 방법을 읽고, 데이터를 쓴다. 4가지의 타입이 있다.
// atomic은 읽기 쓰기 작업 수행 전 직렬화가 해제되고 메모리에 로드되어야 한다. non-atomic은 필요에 따라.
// 4가지 방법 외에도 JSON이나 CSV 등으로 자제적인 NSPersistentStore를 만들 수 있다.
// - NSQLiteStoreType : SQLite 방식. non-atomic. default이며 가볍고 효율적이다.
// - NSXMLStoreType : XML 방식. atomic. 사람이 이해하기 쉽다. OSX에서만 사용할 수 있으며 메모리 사용량이 크다.
// - NSBinaryStoreType : 2진 데이터 방식. atomic. 잘 안 쓴다.
// - NSInMemoryStoreType : 메모리 방식. 앱을 종료하면 데이터가 사라진다. 유닛 테스팅과 캐싱에 사용된다.
//• NSPersistentStoreCoordinator : managed object와 persistent store간의 브릿지. 캡슐화되어 있다.
// 따라서 NSManagedObjectContext는 NSPersistentStore의 종류에 상관없이 일정한 작업을 할 수 있으며,
// 여러개의 NSPersistentStore를 사용하더라도, NSPersistentStoreCoordinator로 통합해 관리할 수 있다.
//• NSManagedObjectContext : 가장 빈번하게 사용. 실제 개발 시 NSManagedObjectContext로 작업하는 경우가 대부분
// 컨텍스트는 managed object로 작업하기 위한 메모리 내의 스크래치 패드.
// managed object 내에서 CoreData로 모든 작업을 수행한다. 컨텍스트에서 save()를 호출하기 전에는 저장되지 않는다.
// - 컨텍스트는 생성하거나 가져오는 객체의 라이프 사이클을 관리한다. 여기에는 오류 처리, 역 관계 처리, 유효성 검사 등이 포함된다.
// - managed object는 연결된 컨텍스트 없이 존재할 수 없다. 모든 managed object는 컨텍스트에 대한 참조를 유지한다.
// 따라서 managed object에서 컨텍스트를 가져올 수도 있다.
// ex) let managedContext = employee.managedObjectContext
// - managed object가 특정 컨텍스트와 연결되면, 라이프 사이클 동안 동일한 컨텍스트와 연결이 유지된다.
// - 여러 개의 컨텍스트를 사용할 수 있다. 동일한 CoreData를 서로 다른 컨텍스트에 연결할 수도 있다.
// - 컨텍스트는 non thread-safe이다. managed object도 마찬가지로 non thread-safe이다.
// 생성된 동일한 스레드에서만 컨텍스트 관리 및 managed object와 상호작용 할 수 있다.
//iOS 10부터 4개의 CoreData Stack을 조율하는 NSPersistentContainer를 사용할 수 있다.
//4개의 CoreData Stack을 모두 연결하면서, 더 쉽게 CoreData를 사용할 수 있다.
| true
|
fcdb3bfbe8bb69e8a4c77b3c4b4efadfa6588452
|
Swift
|
behrank/Testfy
|
/Testfy/Network/NetworkProvider.swift
|
UTF-8
| 1,295
| 2.578125
| 3
|
[] |
no_license
|
//
// NetworkProvider.swift
// Testfy
//
// Created by Behran Kankul on 11.07.2018.
// Copyright © 2018 Be Moebil. All rights reserved.
//
import Foundation
import Moya
import Alamofire
class NetworkProvider {
static let shared = NetworkProvider()
let provider = MoyaProvider<NetworkAPI>()
fileprivate init() { }
func call<T: Decodable>(target:NetworkAPI, completion:@escaping (T) -> (), failureCompletion:@escaping (String)-> Void) {
provider.request(target) { [weak self] result in
if result.value == nil {
return failureCompletion("")
}
switch result.value!.statusCode {
case 200:
do {
let data = try JSONDecoder().decode(T.self, from: result.value!.data)
completion(data)
}
catch let jsonErr{
//debugPrint(String(data: result.value!.data, encoding: .utf8))
debugPrint(jsonErr)
return failureCompletion("")
}
return
case 500,400:
return failureCompletion("")
default:
return failureCompletion("")
}
}
}
}
| true
|
ee6629cdd5ca9e33fef1aca4c2a3dda014c7a033
|
Swift
|
olx-inc/ios-library
|
/AirshipDebugKit/AirshipDebugKit/Automation/TextInfoDetailViewController.swift
|
UTF-8
| 3,739
| 2.578125
| 3
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
/* Copyright Urban Airship and Contributors */
import UIKit
import AirshipKit
/**
* The TextInfoDetailViewController displays the details of an IAA
* text info block. It is used to display the details of headings,
* bodies and button labels.
*/
class TextInfoDetailViewController: UAStaticTableViewController {
public static let segueID = "ShowTextInfoDetail"
/* The UAInAppMessageTextInfo to be displayed. */
public var textInfo : UAInAppMessageTextInfo?
@IBOutlet var textCell: UITableViewCell!
@IBOutlet var textLabel: UILabel!
@IBOutlet var alignmentCell: UITableViewCell!
@IBOutlet var alignmentLabel: UILabel!
@IBOutlet var styleCell: UITableViewCell!
@IBOutlet var styleLabel: UILabel!
@IBOutlet var fontFamiliesCell: UITableViewCell!
@IBOutlet var fontFamiliesLabel: UILabel!
@IBOutlet var sizeCell: UITableViewCell!
@IBOutlet var sizeLabel: UILabel!
@IBOutlet var colorCell: UITableViewCell!
@IBOutlet var colorLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
refreshView()
}
@objc func refreshView() {
guard let textInfo = textInfo else { return }
var fontFamiliesDescription : String?
var colorDescription : String?
// text
updateOrHideCell(textCell, label: textLabel, newText: textInfo.text)
// alignment
switch (textInfo.alignment) {
case .none:
alignmentLabel.text = "ua_textinfo_alignment_none".localized()
case .left:
alignmentLabel.text = "ua_textinfo_alignment_left".localized()
case .center:
alignmentLabel.text = "ua_textinfo_alignment_center".localized()
case .right:
alignmentLabel.text = "ua_textinfo_alignment_right".localized()
}
// style
var styles:[String] = []
if (textInfo.style.contains(.bold)) {
styles.append("ua_textinfo_style_bold".localized())
}
if (textInfo.style.contains(.italic)) {
styles.append("ua_textinfo_style_italic".localized())
}
if (textInfo.style.contains(.underline)) {
styles.append("ua_textinfo_style_underline".localized())
}
if (styles.count == 0) {
styles.append("ua_textinfo_style_normal".localized())
}
styleLabel.text = styles.joined(separator: ", ")
// fontFamilies
if let fontFamilies = textInfo.fontFamilies {
if (fontFamilies.count > 0) {
fontFamiliesDescription = "\(fontFamilies.count)"
}
}
updateOrHideCell(fontFamiliesCell, label: fontFamiliesLabel, newText: fontFamiliesDescription)
// size
sizeLabel.text = "\(textInfo.sizePoints)"
// color
colorDescription = descriptionForColor(textInfo.color)
updateOrHideCell(colorCell, label: colorLabel, newText: colorDescription)
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
// let superview override
let heightFromSuperview = super.tableView(tableView, heightForRowAt: indexPath)
if heightFromSuperview != UITableView.automaticDimension {
return heightFromSuperview
}
// superview didn't override, so let's check our cells
if cell == textCell {
return heightForCell(cell, resizingLabel:textLabel)
} else {
return UITableView.automaticDimension
}
}
// TODO - implement Font Families View
}
| true
|
677daa401584c2a862f6c4077afb6e24bc72ebec
|
Swift
|
simoneacker/Shorecrest-Connect
|
/app/SC-Connect/Constants.swift
|
UTF-8
| 7,909
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// Constants.swift
// Testbed for Messages Type Interface
//
// Created by Simon Acker on 3/9/17.
// Copyright © 2017 Shorecrest Computer Science. All rights reserved.
//
import Foundation
import AWSCore //for aws region
import UIKit //for color and device
// All constants and functions are static so call doesn't need to initialize an object of the struct type before using it.
/// Constants used for network requests to the server.
struct NetworkConstants {
/// The foundation url of the server.
private static let baseURL = "https://api.shorecrestconnect.com"
/// The port for both sockets and REST.
private static let port = 443
/// The REST API url addition.
private static let restURLAddition = "/scconnect/"
/// The URL of the REST API.
public static let restURL = NetworkConstants.baseURL + ":" + "\(NetworkConstants.port)" + NetworkConstants.restURLAddition
/// The URL of the Socket API.
public static let socketURL = NetworkConstants.baseURL + ":" + "\(NetworkConstants.port)"
}
/// Constants used to upload or download media content from AWS S3
struct AWSConstants {
/// The region identifier for the bucket which stores the media.
static let region = AWSRegionType.USWest2
/// The AWS Cognito Pool Identifier for the bucket which stores the media.
static let poolID = "us-west-2:e63203a1-e27a-4630-b3ee-55eb30ab0e32"
/// The name of the bucket which stores all of the media content.
static let bucketName = "scconnect-production"
}
/// Key constants for posting and observing NotificationCenter notifications. Used to decrease chance of mistyping and make changes easier.
struct NotificationCenterConstants {
/// Called when a user has successfully signed into their google account.
static let googleUserSignedInKey = "GoogleUserSignedIn"
/// Called when a user has successfully signed out of their google account.
static let googleUserSignedOutKey = "GoogleUserSignedOut"
/// Called when the user changes their selected graduation year.
static let graduationYearChangedKey = "GraduationYearChanged"
/// Called when a tag's color is changed.
static let tagColorChangedKey = "TagColorChanged"
/// Called when a new message is posted by the user.
static let newMessagePostedKey = "NewMessagePosted"
/// Called when the user subscribes or unsubscribes from a tag.
static let subscriptionsChangedKey = "SubscriptionsChanged"
/// Called when the user reads at least one new message.
static let lastReadMessagesChangedKey = "LastReadMessagesChanged"
/// Called when the selected sport is changed.
static let selectedSportChangedKey = "SelectedSportChanged"
/// Called when the an image has been uploaded to fan cam.
static let fanCamImageCreatedKey = "FanCamImageCreated"
/// Called when the day of the week is changed on clubs page.
static let clubsSelectedDayOfWeekChangedKey = "ClubsSelecgtedDayOfWeekChanged"
/// Called when the selected graduation year is changed.
static let selectedGraduationYearChangedKey = "SelectedGraduationYearChanged"
}
/// Key constants for saving and accessing information saved to UserDefaults. Used to decrease chance of mistyping and make changes easier.
struct UserDefaultsConstants {
/// The key which references information about the signed in user, if there is one.
static let googleUserInfoKey = "GoogleUserInfo"
/// The key which references a dictionary that holds the identifier (value) of the last read message for each of the subscribed tags by name (key).
static let lastReadMessageIdentifiersKey = "LastReadMessageIdentifiers"
/// The key which references information about the current authentication session, if there is one.
static let jwtKey = "JSONWebToken"
/// The key which references information about the signed in user's selected graduation year. Empty if no Google Account signed in.
static let graduationYearKey = "GraduationYear"
/// The key which references a boolean about whether or not the user has completed the tutorial.
static let tutorialCompletedKey = "TutorialCompleted"
/// The key which references a boolean about whether or not the school property warning alert has been shown.
static let schoolPropertyWarningShownKey = "SchoolPropertyWarningShown"
}
/// Constant names for all icon images called in code. Used to make changing an icon easier.
struct IconNameConstants {
/// Used by the tag color picker to highlight which color is currently selected.
static let checkmark = "color_picker_checkmark_icon_inverted"
}
/// All URLs used within the app.
struct URLConstants {
/// The link of information about the app and components/media used in it.
static let aboutURL = "http://www.shorecrestconnect.com/scconnect-about.html"
/// The link of information about terms of use agreed upon by using the app.
static let termsOfUseURL = "http://www.shorecrestconnect.com/terms_of_use.pdf"
/// The link of information about the EULA agreed upon by using the app.
static let endUserLiscenseAgreementURL = "http://www.shorecrestconnect.com/EULA.pdf"
/// The link of information about the privacy policy agreed upon by using the app.
static let privacyPolicyURL = "http://www.shorecrestconnect.com/Privacy%20Policy.pdf"
/// The link of the daily bulletin.
static let dailyBulletinURL = "http://www.shorelineschools.org/site/Default.aspx?PageType=3&DomainID=19&PageID=31&ViewID=ed695a1c-ef13-4546-b4eb-4fefcdd4f389&FlexDataID=4221"
/// The link of the school calendar.
static let schoolCalendarURL = "http://www.shorelineschools.org/site/Default.aspx?PageID=32"
/// The link of the highlander home google calendar in agenda mode by default.
static let hhScheduleURL = "https://calendar.google.com/calendar/embed?src=johanna.phillips@k12.shorelineschools.org&ctz=America/Los_Angeles&pli=1&mode=AGENDA"
/// The link of Mr. Mitchell's video's page on YouTube.
static let videosURL = "https://www.youtube.com/channel/UCJkBDvKzeAwYKFCkG5--9Qw/videos?sort=dd&view=0&shelf_id=0"
}
/// All constants used for storing, parsing or displaying tag information.
struct TagConstants {
/**
Gives the color information for one of the color indexes.
- Note: Using a function because it is much simpler than having 15 named colors like colorOne, colorTwo, etc.
- Parameters:
- index: The integer index of the color (0-14).
- Returns: UIColor with the RGB values for that specific color index.
*/
static func colorFor(index: Int) -> UIColor {
switch index { //using a switch for readability and easy defaulting
case 0:
return UIColor(red: 0.35, green: 0.18, blue: 0.55, alpha: 1.0)
case 1:
return UIColor(red: 0.71, green: 0.12, blue: 0.45, alpha: 1.0)
case 2:
return UIColor(red: 0.91, green: 0.12, blue: 0.15, alpha: 1.0)
case 3:
return UIColor(red: 0.90, green: 0.36, blue: 0.15, alpha: 1.0)
case 4:
return UIColor(red: 0.90, green: 0.51, blue: 0.15, alpha: 1.0)
case 5:
return UIColor(red: 0.89, green: 0.71, blue: 0.13, alpha: 1.0)
case 6:
return UIColor(red: 0.90, green: 0.90, blue: 0.09, alpha: 1.0)
case 7:
return UIColor(red: 0.49, green: 0.04, blue: 0.26, alpha: 1.0)
case 8:
return UIColor(red: 0.09, green: 0.62, blue: 0.29, alpha: 1.0)
case 9:
return UIColor(red: 0.09, green: 0.57, blue: 0.70, alpha: 1.0)
case 10:
return UIColor(red: 0.04, green: 0.34, blue: 0.64, alpha: 1.0)
case 11:
return UIColor(red: 0.16, green: 0.20, blue: 0.54, alpha: 1.0)
case 12:
return UIColor(red: 0.37, green: 0.37, blue: 0.37, alpha: 1.0)
case 13:
return UIColor(red: 0.61, green: 0.61, blue: 0.61, alpha: 1.0)
case 14:
return UIColor(red: 0.77, green: 0.77, blue: 0.77, alpha: 1.0)
default:
return UIColor.clear
}
}
}
| true
|
8b393f71d71e10fd350e9f0392c5dcab87942d57
|
Swift
|
jujien/erf
|
/ERF/UIViewControllerExtension.swift
|
UTF-8
| 1,265
| 2.65625
| 3
|
[] |
no_license
|
//
// UIViewControllerExtension.swift
// ERP
//
// Created by Mr.Vu on 6/19/16.
// Copyright © 2016 Techkids. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = true
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
func showAlert(titleAlert: String, message: String, titleActions: [String], actions: [((UIAlertAction) -> Void)?]?, complete: (() -> Void)?) -> Void {
let alert = UIAlertController(title: titleAlert, message: message, preferredStyle: .Alert)
for i in 0..<titleActions.count {
let actionAlert = UIAlertAction(title: titleActions[i], style: .Default, handler: { (action) in
if let actions = actions {
if let a = actions[i] {
a(action)
}
}
})
alert.addAction(actionAlert)
}
presentViewController(alert, animated: true, completion: complete)
}
}
| true
|
9e621031e750ea99943c59c905f9cf5164bcd69c
|
Swift
|
3D4Medical/glTFSceneKit
|
/Sources/glTFSceneKit/TextureStorageManager.swift
|
UTF-8
| 6,931
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// TextureStorageManager.swift
// glTFSceneKit
//
// Created by Volodymyr Boichentsov on 29/04/2018.
//
import Foundation
import SceneKit
import os
// Texture load status
enum TextureStatus: Int {
case no = 0
case loading
case loaded
}
protocol TextureLoaderDelegate: class {
var renderer: SCNSceneRenderer? { get }
func texturesLoaded()
}
class TextureAssociator {
var status: TextureStatus = .no
private var content_: Any? = OSColor.white
var content: Any? {
set {
content_ = newValue
if newValue != nil {
self.status = .loaded
for property in associatedProperties {
property.contents = self.content_
}
}
}
get {
return content_
}
}
lazy var associatedProperties = Set<SCNMaterialProperty>()
func associate(property: SCNMaterialProperty) {
associatedProperties.insert(property)
property.contents = self.content
}
deinit {
associatedProperties.removeAll()
}
}
@available(OSX 10.12, iOS 10.0, *)
class TextureStorageManager {
static let manager = TextureStorageManager()
private var worker = DispatchQueue(label: "textures_loader")
private var groups: [Int: DispatchGroup] = [Int: DispatchGroup]()
lazy private var _associators: [Int: [Int: TextureAssociator]] = [Int: [Int: TextureAssociator]]()
func clear(gltf: GLTF) {
let hash = gltf.hashValue
self.groups[hash] = nil
self._associators[hash] = nil
}
func textureAssociator(gltf: GLTF, at index: Int) -> TextureAssociator {
let hash = gltf.hashValue
if self._associators[hash] == nil {
self._associators[hash] = [Int: TextureAssociator]()
}
var tStatus = (self._associators[hash])![index]
if tStatus == nil {
tStatus = TextureAssociator()
self._associators[hash]![index] = tStatus
}
return tStatus!
}
func group(gltf: GLTF, delegate: TextureLoaderDelegate, _ enter: Bool = false) -> DispatchGroup {
let index = gltf.hashValue
var group: DispatchGroup? = groups[index]
if group == nil {
groups[index] = DispatchGroup()
group = groups[index]
group?.enter()
let startLoadTextures = Date()
// notify when all textures are loaded
// this is last operation.
group?.notify(queue: DispatchQueue.global(qos: .userInteractive)) {
os_log("textures loaded %d ms", log: log_scenekit, type: .debug, Int(startLoadTextures.timeIntervalSinceNow * -1000))
delegate.texturesLoaded()
}
} else if enter {
group?.enter()
}
return group!
}
/// Load texture by index.
///
/// - Parameters:
/// - index: index of GLTFTexture in textures
/// - property: material's property
static func loadTexture(gltf: GLTF, delegate: TextureLoaderDelegate, index: Int, property: SCNMaterialProperty) {
self.manager._loadTexture(gltf: gltf, delegate: delegate, index: index, property: property)
}
fileprivate func _loadTexture(gltf: GLTF, delegate: TextureLoaderDelegate, index: Int, property: SCNMaterialProperty) {
guard let texture = gltf.textures?[index] else {
print("Failed to find texture")
return
}
let group = self.group(gltf: gltf, delegate: delegate, true)
worker.async {
let tStatus = self.textureAssociator(gltf: gltf, at: index)
if tStatus.status == .no {
tStatus.status = .loading
tStatus.associate(property: property)
gltf.loadSampler(sampler: texture.sampler, property: property)
let device = MetalDevice.device
let metalOn = (delegate.renderer?.renderingAPI == .metal || device != nil)
if let descriptor = texture.extensions?[compressedTextureExtensionKey] as? GLTF_3D4MCompressedTextureExtension, metalOn {
// load first level mipmap as texture
gltf.loadCompressedTexture(descriptor: descriptor, loadLevel: .first) { cTexture, error in
tStatus.content = cTexture
if gltf.isCancelled {
group.leave()
return
}
if error != nil {
print("Failed to load comressed texture \(error.debugDescription). Fallback on image source.")
self._loadImageTexture(gltf, delegate, texture, tStatus)
group.leave()
} else {
tStatus.content = cTexture
// load all levels
gltf.loadCompressedTexture(descriptor: descriptor, loadLevel: .last) { (cTexture2, error) in
if gltf.isCancelled {
group.leave()
return
}
if error != nil {
print("Failed to load comressed texture \(error.debugDescription). Fallback on image source.")
self._loadImageTexture(gltf, delegate, texture, tStatus)
} else {
tStatus.content = cTexture2
}
group.leave()
}
}
}
} else {
self._loadImageTexture(gltf, delegate, texture, tStatus)
group.leave()
}
} else {
tStatus.associate(property: property)
group.leave()
}
}
}
/// load original image source png or jpg
fileprivate func _loadImageTexture(_ gltf: GLTF, _ delegate: TextureLoaderDelegate, _ texture: GLTFTexture, _ tStatus: TextureAssociator) {
self.worker.async {
if gltf.isCancelled {
return
}
let group = self.group(gltf: gltf, delegate: delegate, true)
if let imageSourceIndex = texture.source {
if let gltf_image = gltf.images?[imageSourceIndex] {
gltf.loader.load(gltf: gltf, resource: gltf_image) { resource, _ in
if resource.image != nil {
tStatus.content = gltf._compress(image: resource.image!)
}
group.leave()
}
}
}
}
}
}
| true
|
9cb4abe63bdbaebc46d04cf5eba99027ff7047a4
|
Swift
|
mercedes-benz/MBSDK-NetworkKit-iOS
|
/MBNetworkKit/MBNetworkKit/Socket/Protocols/SocketProtocol.swift
|
UTF-8
| 3,332
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// Copyright © 2019 MBition GmbH. All rights reserved.
//
import Foundation
/// Protocol to implement the socket handling
public protocol SocketProtocol {
// MARK: Typealias
/// Completion for empty closue
typealias Completion = () -> Void
/// Completion for socket conection status
///
/// Returns a SocketConnectionState
typealias SocketConnectionStateObserver = (SocketConnectionState) -> Void
/// Completion for receiving data via
///
/// Returns data
typealias SocketReceiveDataObserver = (Data) -> Void
// MARK: Properties
/// Returns whether the socket is connected
var isConnected: Bool { get }
// MARK: Functions
/// Close the socket connection and remove all observable tokens
func close()
/// Connect your service with the socket
///
/// - Parameters:
/// - socketToken: SocketToken object
/// - connectionState: Closure with SocketConnectionStateObserver
/// - Returns: A valid SocketConnectionToken
func connect(socketToken: SocketToken, connectionState: @escaping SocketConnectionStateObserver) -> SocketConnectionToken
/// Disconnect the socket
/// - Parameters:
/// - forced: Force the disconnect wihtout any delay
func disconnect(forced: Bool)
/// Register service to receive socket data
///
/// - Parameters:
/// - observer: Closure with SocketReceiveDataObserver
func receiveData(observer: @escaping SocketReceiveDataObserver) -> SocketReceiveDataToken
/// Try to reconnect the socket
func reconnect()
/// Send some data to the socket
///
/// - Parameters:
/// - data: Data to be sent
/// - completion: Optional closure when finished
func send(data: Data, completion: Completion?)
/// Update the socket enviroment
///
/// - Parameters:
/// - socketToken: SocketToken object
/// - needsReconnect: Needs the socket a reconnect because the connection was lost after expired credentials
/// - reconnectManually: Takes the reconnect manually
func update(socketToken: SocketToken, needsReconnect: Bool, reconnectManually: Bool)
/// This method is used to unregister a token from the observation of the socket connection status
///
/// - Parameters: Optional SocketConnectionToken
func unregister(token: SocketConnectionToken?)
/// This method is used to unregister a token from the observation of the socket connection status
///
/// - Parameters: Optional SocketReceiveDataToken
func unregister(token: SocketReceiveDataToken?)
/// This method is used to unregister a token from the observation of the socket connection status and try to disconnect the socket
///
/// - Parameters: Optional SocketConnectionToken
/// - connectionToken: Optional SocketConnectionToken
/// - receiveDataToken: Optional SocketReceiveDataToken
func unregisterAndDisconnectIfPossible(connectionToken: SocketConnectionToken?, receiveDataToken: SocketReceiveDataToken?)
/// This method is used to unregister an array of tokens from the observation of the socket connection status and try to disconnect the socket
///
/// - Parameters: Optional SocketConnectionToken
/// - connectionTokens: Array of SocketConnectionToken
/// - receiveDataToken: Optional SocketReceiveDataToken
func unregisterAndDisconnectIfPossible(connectionTokens: [SocketConnectionToken], receiveDataToken: SocketReceiveDataToken?)
}
| true
|
4f2e8bb5a143bcdea37ef2d0344ec6cbed7134cd
|
Swift
|
neelamsharma12/PhoneBookDemo
|
/PhoneBook/PhoneBook/Views/CustomCell/ContactEditTableViewCell.swift
|
UTF-8
| 1,477
| 2.703125
| 3
|
[] |
no_license
|
//
// ContactEditTableViewCell.swift
// PhoneBook
//
// Created by Neelam on 13/05/18.
// Copyright © 2018 Neelam. All rights reserved.
//
import UIKit
protocol UpdateContactDetailsProtocol: class {
/**
Protocol method get called to update the contact details
- parameter contactData: ContactDetailModel
- returns:
*/
func didFinishEditingContactDetails(updatedData: String?, propertyTag: Int)
}
class ContactEditTableViewCell: UITableViewCell {
// MARK: - Properties
@IBOutlet weak var editContactPropertyNameLabel: UILabel!
@IBOutlet weak var editContactPropertyInfoLabel: UITextField!
//MARK :- Variable declaration
weak var delegate: UpdateContactDetailsProtocol? = nil
override func awakeFromNib() {
super.awakeFromNib()
editContactPropertyInfoLabel.delegate = self
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension ContactEditTableViewCell: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
editContactPropertyInfoLabel.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
delegate?.didFinishEditingContactDetails(updatedData: textField.text, propertyTag: textField.tag)
}
}
| true
|
6faa45ed733c805f2fd0365f8b5979e3d9126089
|
Swift
|
AmarvirSingh/hotelApp
|
/Hotel/Hotel/detailsViewController.swift
|
UTF-8
| 1,927
| 3.078125
| 3
|
[] |
no_license
|
//
// detailsViewController.swift
// Hotel
//
// Created by Amarvir Mac on 21/11/20.
// Copyright © 2020 Amarvir Mac. All rights reserved.
//
import UIKit
class detailsViewController: UIViewController {
//****************
@IBOutlet weak var name: UILabel!
@IBOutlet weak var address: UITextView!
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var rent: UILabel!
//***********************
var hotelName = ""
var hotelAdd = ""
var hotelRent = ""
var imageName = ""
var imageName2 = ""
var imageName3 = ""
var imageName4 = ""
var imageName5 = ""
// this will be filled when the array is passed from view controller
var arrayImage = [""]
override func viewDidLoad() {
super.viewDidLoad()
name.text = hotelName
address.text = hotelAdd
image.image = UIImage(named: imageName)
rent.text = "$ " + hotelRent + " per Night"
}
@IBAction func showMoreImages(_ sender: Any) {
let vc = self.storyboard?.instantiateViewController(identifier: "ImageViewController") as! ImageViewController
// the images are passed from this veiw controller to next view controller
vc.imageName = imageName
vc.imageName2 = imageName2
vc.imageName3 = imageName3
vc.imageName4 = imageName4
vc.imageName5 = imageName5
// or we can pass like this >>>>>>>>> here we are passing the names of images which are dtored in arrayImage ARRAY which got filled from previous viewController
/*
vc.imageName = arrayImage[0]
vc.imageName2 = arrayImage[1]
vc.imageName3 = arrayImage[2]
vc.imageName4 = arrayImage[3]
vc.imageName5 = arrayImage[4]
*/
self.navigationController?.pushViewController(vc, animated: true)
}
}
| true
|
bb3ffa5c45430e12c55faf387455e5af84491f26
|
Swift
|
Hwangho/iOS_FastCampus
|
/FastCampus/FastCampus/Login/ContactsVC.swift
|
UTF-8
| 3,482
| 2.9375
| 3
|
[] |
no_license
|
//
// ContactsVC.swift
// FastCampus
//
// Created by 송황호 on 2020/12/23.
//
import UIKit
import Contacts
class ContactsVC: UIViewController {
static let identifier = "ContactsVC"
@IBOutlet weak var contactTable: UITableView!
var contactList = [informations]()
override func viewDidLoad() {
super.viewDidLoad()
contactTable.delegate = self
contactTable.dataSource = self
readContacts()
}
// 주소록 읽어오기
private func readContacts() {
let store = CNContactStore()
store.requestAccess(for: .contacts) { (granted, err) in
if let err = err{
print("faild" , err)
return
}
if granted{
let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]
let request = CNContactFetchRequest(keysToFetch:keys as [CNKeyDescriptor])
do {
request.sortOrder = CNContactSortOrder.userDefault
try store.enumerateContacts(with: request, usingBlock: {(contacts, stopPointerIfYouWantToStopEnumerating) in
let phone_number = contacts.phoneNumbers.first?.value.stringValue ?? ""
if phone_number != "" {
let full_name = contacts.givenName + " " + contacts.familyName
let contact_model = informations(fullNmae: full_name, phoneNumber: phone_number)
self.contactList.append(contact_model)
}
})
self.contactTable.reloadData()
}catch let err{
print("err", err)
}
}
}
}
@IBAction func backPressButton(_ sender: Any) {
print("주소로오오오옥 --> \(self.contactList.count)")
self.navigationController?.popViewController(animated: true)
// dismiss(animated: true, completion: nil)
}
}
extension ContactsVC: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.contactList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = contactTable.dequeueReusableCell(withIdentifier: ContactsTVCell.identifier, for: indexPath) as? ContactsTVCell else { return UITableViewCell() }
let rowdata = self.contactList[indexPath.row]
cell.bind(name: rowdata.fullNmae, phone: rowdata.phoneNumber)
return cell
}
}
extension ContactsVC: UITableViewDelegate{
}
//MARK: TableViewCell 관련
class ContactsTVCell: UITableViewCell{
static let identifier = "ContactsTVCell"
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var phoneNumLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
func bind(name: String, phone: String){
self.nameLabel.text = name
self.phoneNumLabel.text = "\(phone)"
}
}
// MARK: Struct 만들기
struct informations{
var fullNmae: String
var phoneNumber: String
}
| true
|
2ca6e939745b1cf3e8d5982b2bdc26f1898cf3bd
|
Swift
|
kkiani/ComboPicker
|
/Sources/ComboPicker/ComboPicker.swift
|
UTF-8
| 3,589
| 2.515625
| 3
|
[] |
no_license
|
#if !os(macOS)
import UIKit
open class ComboPickerView: UITextField,UITextFieldDelegate {
// MARK: - Global Variables
public var dataSource = [String](){
didSet{
if dataSource.count > 0{
selectItem(0)
}
}
}
private var picker:UIPickerView = UIPickerView(frame: CGRect.zero)
private let accessoryView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 44))
var Done:UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
var titleLabel:UILabel = UILabel()
fileprivate func defualts() {
self.inputView = picker
self.tintColor = UIColor.clear
picker.delegate = self
picker.dataSource = self
accessoryView.addSubview(titleLabel)
accessoryView.addSubview(Done)
accessoryView.backgroundColor = UIColor.groupTableViewBackground
Done.setTitle("Done", for: UIControl.State.normal)
Done.sizeToFit()
Done.addTarget(self, action: #selector(Done_tapped(_:)), for: UIControl.Event.touchUpInside)
NSLayoutConstraint.activate([
Done.widthAnchor.constraint(equalToConstant: 44),
Done.trailingAnchor.constraint(equalTo: Done.superview!.trailingAnchor, constant: -16),
Done.topAnchor.constraint(equalTo: Done.superview!.topAnchor, constant: 0),
Done.bottomAnchor.constraint(equalTo: Done.superview!.bottomAnchor, constant: 0)
])
Done.translatesAutoresizingMaskIntoConstraints = false
titleLabel.textColor = UIColor.darkGray
NSLayoutConstraint.activate([
titleLabel.leadingAnchor.constraint(equalTo: titleLabel.superview!.leadingAnchor, constant: 16),
titleLabel.trailingAnchor.constraint(equalTo: Done.leadingAnchor, constant: -8),
titleLabel.topAnchor.constraint(equalTo: titleLabel.superview!.topAnchor, constant: 0),
titleLabel.bottomAnchor.constraint(equalTo: titleLabel.superview!.bottomAnchor, constant: 0)
])
titleLabel.translatesAutoresizingMaskIntoConstraints = false
self.inputAccessoryView = accessoryView
}
override init(frame: CGRect) {
super.init(frame: frame)
defualts()
}
required public init?(coder aDecoder: NSCoder){
super.init(coder: aDecoder)
defualts()
}
@objc func Done_tapped(_ sender:Any){
self.resignFirstResponder()
}
}
extension ComboPickerView{
public func selectItem(_ index: Int){
guard index < dataSource.count else{return}
text = dataSource[index]
sendActions(for: .editingDidEnd)
}
public func selectedItem() -> Int?{
guard let text = self.text else{return nil}
return dataSource.firstIndex(of: text)
}
}
// MARK: - UIPickerView Delegate & DataSource
extension ComboPickerView: UIPickerViewDelegate, UIPickerViewDataSource{
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataSource.count
}
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
return dataSource[row]
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.selectItem(row)
}
}
#endif
| true
|
eaa5bb7429812f61b3a078862971daf8f5c8a718
|
Swift
|
JoeyBodnar/AsokeiOS
|
/AsokeSourceFiles/AsokeViewControlelrs/AsokeCircularVC.swift
|
UTF-8
| 1,947
| 2.734375
| 3
|
[] |
no_license
|
//
// CircularCropVC.swift
// DownvoteN00bs
//
// Created by Stephen Bodnar on 05/04/2017.
// Copyright © 2017 Stephen Bodnar. All rights reserved.
//
import Foundation
import UIKit
class AsokeCircularVC: ParentViewController {
var radius = CGFloat()
convenience init(circleRadius: CGFloat, withImageToCrop image: UIImage) {
self.init(nibName: nil, bundle: nil)
radius = circleRadius
self.imageToCrop = image
}
override func viewDidLoad() {
super.viewDidLoad()
if AsokeHelpers.radiusIsValid(radius, inView: self.view) {
setup()
} else {
let error = NSError(domain: "NSRectRangeException", code: 10, userInfo: [NSLocalizedDescriptionKey: "Your radius is invalid. The radius may not be greater than the ((width of your view) - 2)"])
self.delegate?.didFailWithError(error)
self.dismiss(animated: true, completion: nil)
}
}
func setup() {
let circularOverlay = CircularOverlayView(frame: view.frame, withRadius: radius)
croppingRect = circularOverlay.croppingRectFromRadius()
setupScrollView()
setupPhoto()
view.addSubview(circularOverlay)
addSaveButton()
addCancelButton()
}
func addSaveButton() {
let button = UIButton(frame: CGRect(x: (self.view.frame.width - 70), y: 20, width: 75, height: 30))
button.titleLabel?.font = UIFont(name: "Avenir-Heavy", size: 21)
button.setTitle("Save", for: UIControlState())
button.addTarget(self, action: #selector(save), for: UIControlEvents.touchUpInside)
button.setTitleColor(UIColor.white, for: UIControlState())
button.sizeToFit()
self.view.addSubview(button)
}
func save() {
let roundedImage = imageToPass.circularImage(imageToPass.size.width / 2)
delegate?.didFinishCroppingImage(roundedImage)
}
}
| true
|
0941dd985b96942be5319bcf7fee13c6465220a4
|
Swift
|
nagabharank/Pokedex
|
/Pokedex/Pokemon.swift
|
UTF-8
| 2,036
| 2.78125
| 3
|
[] |
no_license
|
//
// Pokemon.swift
// Pokedex
//
// Created by NagaBharan Kothrui on 1/19/18.
// Copyright © 2018 Bharan Kothrui. All rights reserved.
//
import Foundation
import Alamofire
class Pokemon {
private var _name: String!
private var _pokedexId: Int!
private var _mainImg: String!
private var _descrition: String!
private var _type: String!
private var _defence: String!
private var _height: String!
private var _weight: String!
private var _baseAttack: String!
private var _nextEvoTxt: String!
private var _pokemonURL: String!
var name: String {
return _name
}
var pokedexId: Int {
return _pokedexId
}
init(name: String, PokedexId: Int) {
self._name = name
self._pokedexId = PokedexId
self._pokemonURL = "\(URL_BASE)\(URL_POKEMON)\(self.pokedexId)/"
}
func downloadPokemonDetails(completed: DownloadComplete) {
Alamofire.request(_pokemonURL).responseString { (response) in
if let dict = response.result.value as? Dictionary<String, AnyObject> {
if let weight = dict["weight"] as? String {
self._weight = weight
}
if let heigh = dict["height"] as? String {
self._height = heigh
}
if let baseattack = dict["base_experience"] as? String {
self._baseAttack = baseattack
}
if let stats = dict["stats"] as? [Dictionary<String, AnyObject>] {
if let defence = stats[0]["base_stat"] as? String {
self._defence = defence
}
}
print(self._weight)
print(self._height)
print(self._baseAttack)
print(self._defence)
}
}
}
}
| true
|
6c562e7663412620c2900c874a688ebbca624583
|
Swift
|
logicandform/TouchMapInterface
|
/Sources/Managers/RecordManager.swift
|
UTF-8
| 2,332
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
// Copyright © 2018 JABT. All rights reserved.
import Foundation
final class RecordManager {
static let instance = RecordManager()
/// Type: [ID: Record]
private var recordsForType: [RecordType: [Int: Record]] = [:]
// MARK: Init
/// Use singleton
private init() {
for type in RecordType.allCases {
recordsForType[type] = [:]
}
}
// MARK: API
/// Creates mock records and relates them to one another
func initialize() {
guard let jsonURL = Bundle.main.url(forResource: "cities", withExtension: "json"), let data = try? Data(contentsOf: jsonURL), let json = try? JSONSerialization .jsonObject(with: data, options: []) as? [JSON], let citiesJSON = json else {
fatalError("Failed to serialize City records from cities.json file.")
}
let cities = citiesJSON.compactMap { City(json: $0) }
store(cities, for: .city)
// Create events and individuals to relate to each city
var siblings = [Record]()
for id in (1 ... 10) {
siblings.append(Record(type: .event, id: id, title: "Event \(id)", description: "Description", dates: nil, coordinate: nil))
siblings.append(Record(type: .individual, id: id, title: "Person \(id)", description: "Description", dates: nil, coordinate: nil))
}
for city in cities {
for sibling in siblings {
city.relate(to: sibling)
}
}
}
func allRecords() -> [Record] {
return RecordType.allCases.reduce([]) { $0 + records(for: $1) }
}
func record(for type: RecordType, id: Int) -> Record? {
return recordsForType[type]?[id]
}
func records(for type: RecordType, ids: [Int]) -> [Record] {
return ids.compactMap { recordsForType[type]?[$0] }
}
func records(for type: RecordType) -> [Record] {
guard let recordsForID = recordsForType[type] else {
return []
}
return Array(recordsForID.values)
}
// MARK: Helpers
private func createRecords(of type: RecordType) -> [Record] {
return []
}
private func store(_ records: [Record], for type: RecordType) {
for record in records {
recordsForType[type]?[record.id] = record
}
}
}
| true
|
e3d84c0fc5bb3cf38740f15a9c4fc06906b49e8b
|
Swift
|
majd-asab/iOS
|
/MemeMe/Click Counter/Click Counter/ViewController.swift
|
UTF-8
| 2,198
| 3.140625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Click Counter
//
// Created by Majd on 2018-12-01.
// Copyright © 2018 HappyWorld. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var count = 0
// {
// didSet {
// view.backgroundColor = self.colors.randomElement()
// }
// }
@IBOutlet var label: UILabel!
// var label2: UILabel!
// color array
let colors: [UIColor] = [.red, .blue, .yellow, .green, .black, .white]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// label
// let label = UILabel()
// label.frame = CGRect(x: 150, y: 150, width: 60, height:60)
// label.text = "0"
// view.addSubview(label)
// self.label = label
//
// // label2
// let label2 = UILabel()
// label2.frame = CGRect(x: 210, y: 150, width: 60, height:60)
// label2.text = "\(self.count)"
// view.addSubview(label2)
// self.label2 = label2
//
// //button
// let button = UIButton()
// button.frame = CGRect(x: 100, y: 250, width: 100, height: 60)
// button.setTitle("Increment", for: .normal)
// button.setTitleColor( .blue, for: .normal)
// button.tag = 1
// view.addSubview(button)
//
// button.addTarget(self, action: #selector(changeCount), for: UIControl.Event.touchUpInside)
//
// //button
// let button2 = UIButton()
// button2.frame = CGRect(x: 210, y: 250, width: 100, height: 60)
// button2.setTitle("Decrement", for: .normal)
// button2.setTitleColor( .red, for: .normal)
// button2.tag = -1
// view.addSubview(button2)
//
// button2.addTarget(self, action: #selector(changeCount), for: UIControl.Event.touchUpInside)
}
// @objc func changeCount(sender: UIButton) {
// self.count += sender.tag
// self.label.text = "\(self.count)"
// self.label2.text = "\(self.count)"
// }
@IBAction func incremenetCount() {
self.count += 1
self.label.text = "\(self.count)"
}
}
| true
|
6ae2a096935a433cb25d5a3af049b944d8683dc4
|
Swift
|
Akemi/test_secondary_screen_window_position
|
/testWindowPosition.swift
|
UTF-8
| 3,530
| 3.25
| 3
|
[] |
no_license
|
import Cocoa
let debug: Bool = false
let screenNumberTest: Int = 2
let testCases: [String] = ["width", "height"]
var titleBarHeight: Int = Int(NSWindow.frameRect(forContentRect: CGRect.zero, styleMask: .titled).size.height+1)
print("You have \(NSScreen.screens.count) screen(s):")
for (num, screen) in NSScreen.screens.enumerated() {
print("Screen \(num+1): \(screen.frame)")
}
print("----------------------------------------------------")
if NSScreen.screens.count < screenNumberTest {
print("\u{001B}[0;31mYou need at least \(screenNumberTest) screens\u{001B}[0;0m")
exit(0)
}
let screenToTest = NSScreen.screens[screenNumberTest-1]
var mainFrame = NSScreen.screens[0].frame
var testFrame = screenToTest.frame
mainFrame.origin.x = 0
mainFrame.origin.y = 0
testFrame.origin.x = 0
testFrame.origin.y = 0
if NSContainsRect(mainFrame, testFrame) {
print("\u{001B}[0;31mScreen 1 and \(screenNumberTest) need two different virtual resolutions.")
print("Either width or height of screen \(screenNumberTest) needs to be greater than the one of screen 1.\u{001B}[0;0m")
exit(0)
}
print("Trying window positions on screen \(screenNumberTest) with a resolution of \(Int(testFrame.size.width))x\(Int(testFrame.size.height))")
for dim in testCases {
let positionText = dim == "width" ? "x" : "y"
let end = dim == "width" ? Int(testFrame.size.width) : Int(testFrame.size.height)
var fuckUpCount: Int = 0
var lastFuckUp: Int = 0
print("Testing screen's \(positionText) position from 0 to \(end-1)")
for index in 0...end-1 {
let rect = dim == "width" ? NSRect(x: index, y: 0, width: 1, height: 1)
: NSRect(x: 0, y: index, width: 1, height: 1)
let window = NSWindow(contentRect: rect,
styleMask: [.titled, .fullSizeContentView],
backing: .buffered,
defer: false,
screen: screenToTest)
var actual = window.frame.origin
actual.x -= screenToTest.frame.origin.x
actual.y -= screenToTest.frame.origin.y
let testPosition = dim == "width" ? Int(rect.origin.x) : Int(rect.origin.y)
let actualPosition = dim == "width" ? Int(actual.x) : Int(actual.y)
if debug {
let pass = testPosition == actualPosition ? "[0;32m" : "[0;31m"
print("\u{001B}\(pass)\(positionText) position expected: \(testPosition) actual: \(actualPosition)")
} else {
if testPosition != actualPosition {
if lastFuckUp != actualPosition-1 {
if fuckUpCount < 1 {
print("\u{001B}[0;32m\(positionText) position from 0 to \(testPosition-1) were okay")
if dim == "height" {
print("Keep in mind your title bar is \(titleBarHeight)pt high and the actual usable height of screen 1 " +
"is 0-\(Int(mainFrame.size.height)-titleBarHeight-1)pt of the \(Int(mainFrame.size.height)) points.")
}
}
print("\u{001B}[0;31m\(positionText) position jump: \(fuckUpCount+1)")
print("\u{001B}[0;31m\(positionText) position expected: \(testPosition) actual: \(actualPosition)")
fuckUpCount += 1
}
lastFuckUp = actualPosition
}
}
}
print("\u{001B}[0;0m")
}
| true
|
9a96363e2227f49ca09e77f3178dda9c7e869966
|
Swift
|
kimdaeman14/RxSwift-Collage
|
/JayCollage/Classes/UIImage+Collage.swift
|
UTF-8
| 3,809
| 3.046875
| 3
|
[] |
no_license
|
//
// UIImage+Collage.swift
// JayCollage
//
// Created by Jaycee on 2020/01/01.
// Copyright © 2020 Jaycee. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
static func collage(images: [UIImage], size: CGSize) -> UIImage {
let rows = images.count < 3 ? 1 : 2
let columns = Int(round(Double(images.count) / Double(rows)))
let tileSize = CGSize(width: round(size.width / CGFloat(columns)), //사진 사이즈조절해주는곳인듯?.
height: round(size.height / CGFloat(rows)))
UIGraphicsBeginImageContextWithOptions(size, true, 0)
UIColor.white.setFill()
UIRectFill(CGRect(origin: .zero, size: size))
for (index, image) in images.enumerated() {
image.scaled(tileSize).draw(at: CGPoint(
x: CGFloat(index % columns) * tileSize.width,
y: CGFloat(index / columns) * tileSize.height
))
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image ?? UIImage()
}
static func rotateCollage(images: [UIImage], size: CGSize) -> UIImage {
let rows = images.count < 3 ? 1 : 2
let columns = Int(round(Double(images.count) / Double(rows)))
let tileSize = CGSize(width: round(size.width / CGFloat(columns)), //사진 사이즈조절해주는곳인듯?.
height: round(size.height / CGFloat(rows)))
UIGraphicsBeginImageContextWithOptions(size, true, 0)
UIColor.white.setFill()
UIRectFill(CGRect(origin: .zero, size: size))
for (index, image) in images.enumerated() {
let random = CGFloat(Double.random(in: 0.1 ..< 1.0))
let random1 = Float(Double.random(in: -20.0 ..< 20.0))
image.rotate(radians: .pi/random1)?.scaled(tileSize).draw(at: CGPoint(
x: CGFloat(index % columns) * tileSize.width * random,
y: CGFloat(index / columns) * tileSize.height * random
))
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image ?? UIImage()
}
func scaled(_ newSize: CGSize) -> UIImage {
guard size != newSize else {
return self
}
let ratio = max(newSize.width / size.width, newSize.height / size.height)
let width = size.width * ratio
let height = size.height * ratio
let scaledRect = CGRect(
x: (newSize.width - width) / 2.0,
y: (newSize.height - height) / 2.0,
width: width, height: height)
UIGraphicsBeginImageContextWithOptions(scaledRect.size, false, 0.0);
defer { UIGraphicsEndImageContext() }
draw(in: scaledRect)
return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
}
}
extension UIImage {
func rotate(radians: Float) -> UIImage? {
var newSize = CGRect(origin: CGPoint.zero, size: self.size).applying(CGAffineTransform(rotationAngle: CGFloat(radians))).size
newSize.width = floor(newSize.width)
newSize.height = floor(newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale)
let context = UIGraphicsGetCurrentContext()!
context.translateBy(x: newSize.width/2, y: newSize.height/2)
context.rotate(by: CGFloat(radians))
self.draw(in: CGRect(x: -self.size.width/2, y: -self.size.height/2, width: self.size.width, height: self.size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
| true
|
934db6a53c399d536ff267b5bd169f1712997a6b
|
Swift
|
turlodales/FrameGrabber
|
/Frame Grabber/Scenes/Album Picker/List/AlbumCell.swift
|
UTF-8
| 1,217
| 2.640625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
import Combine
import UIKit
class AlbumCell: UICollectionViewCell {
var identifier: String?
var imageRequest: Cancellable?
@IBOutlet private(set) var imageView: UIImageView!
@IBOutlet private(set) var titleLabel: UILabel!
@IBOutlet private(set) var detailLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
configureViews()
}
override func prepareForReuse() {
super.prepareForReuse()
identifier = nil
imageRequest = nil
titleLabel.text = nil
detailLabel.text = nil
imageView.image = nil
}
private func configureViews() {
imageView.layer.cornerRadius = 12
imageView.layer.cornerCurve = .continuous
selectedBackgroundView = UIView()
selectedBackgroundView?.backgroundColor = .cellSelection
selectedBackgroundView?.layer.cornerRadius = 12
selectedBackgroundView?.layer.cornerCurve = .continuous
// Allow the selection to spill over.
clipsToBounds = false
let selectionFrame = bounds.inset(by: UIEdgeInsets(top: 0, left: -10, bottom: 0, right: -10))
selectedBackgroundView?.frame = selectionFrame
}
}
| true
|
394c97a3e48ef28d490c1ee67d6a631827647134
|
Swift
|
ach-ref/SOS-Zombies
|
/SOS Zombies/Repository/AppRepository.swift
|
UTF-8
| 3,624
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// AppRepository.swift
// SOS Zombies
//
// Created by Achref Marzouki on 21/4/21.
//
import CoreData
class AppRepository: NSObject {
// MARK: - Shared instance
static let shared = AppRepository()
// MARK: - Private
private var refreshSucceeded = false
// MARK: - Initialzers
override private init() {
super.init()
}
// MARK: - Public
func refreshRemoteData(in context: NSManagedObjectContext, completion: @escaping (Bool) -> Void) {
refreshSucceeded = true
let group = DispatchGroup()
refreshIllnesses(group: group, in: context)
refreshHospitals(group: group, in: context)
// completion
group.notify(queue: .global()) {
completion(self.refreshSucceeded)
}
}
// MARK: - Private
private func refreshIllnesses(limit: Int? = nil, page: Int? = nil, group: DispatchGroup, in context: NSManagedObjectContext) {
group.enter()
WSManager.shared.remoteDataForRoute(DataRouter.illnesses(limit: limit, page: page)) { response in
if let jsonResponse = response {
// illnesses
if let result = jsonResponse[C.Keys.EMBEDDED] as? Json, let jsonArray = result[C.Keys.ILLNESSES] as? [Json] {
Illness.insertOrUpdate(fromJson: jsonArray, in: context)
context.saveContext()
}
// pagination
let pagination = self.extractPagination(from: jsonResponse)
if pagination.nextPage != -1 {
self.refreshIllnesses(limit: pagination.limit, page: pagination.nextPage, group: group, in: context)
}
self.refreshSucceeded = self.refreshSucceeded && true
group.leave()
} else {
self.refreshSucceeded = false
group.leave()
}
}
}
private func refreshHospitals(limit: Int? = nil, page: Int? = nil, group: DispatchGroup, in context: NSManagedObjectContext) {
group.enter()
WSManager.shared.remoteDataForRoute(DataRouter.hospitals(limit: limit, page: page)) { [self] response in
if let jsonResponse = response {
// hospitals
if let result = jsonResponse[C.Keys.EMBEDDED] as? Json, let jsonArray = result[C.Keys.HOSPITALS] as? [Json] {
Hospital.insertOrUpdate(fromJson: jsonArray, in: context)
context.saveContext()
}
// pagination
let pagination = self.extractPagination(from: jsonResponse)
if pagination.nextPage != -1 {
self.refreshHospitals(limit: pagination.limit, page: pagination.nextPage, group: group, in: context)
}
self.refreshSucceeded = self.refreshSucceeded && true
group.leave()
} else {
self.refreshSucceeded = false
group.leave()
}
}
}
// MARK: - Helpers
private func extractPagination(from jsonResponse: Json) -> (limit: Int, nextPage: Int) {
let pagination = jsonResponse[C.Keys.PAGE] as? Json
let currentPage = pagination?[C.Keys.NUMBER] as? Int ?? 0
let totalPages = pagination?[C.Keys.TOTAL_PAGES] as? Int ?? 0
let limit = pagination?[C.Keys.SIZE] as? Int ?? 0
var nextPage = currentPage + 1
nextPage = nextPage > totalPages ? -1 : nextPage
return (limit, nextPage)
}
}
| true
|
70f45d41c61eaae3b7781657f6b0854efdd6f67a
|
Swift
|
yolan90/playground_things2
|
/Function.xcplaygroundpage/Contents.swift
|
UTF-8
| 867
| 4.59375
| 5
|
[] |
no_license
|
import Foundation
/* Function
Chunk of code that can be reused
1º - Function with no parameter and no return
2º - Function with parameter and no return
3º - Function with parameter and return
*/
// 1º
func greetingUser() {
print("Olá usuário")
}
// Declaring a function it's not going to execute it
// Calling a function
greetingUser()
// 2º
//func sayMessage(text: String) {
func sayMessage(_ text: String, _ when: String) {
print("Say \(text) when \(when)")
}
//sayMessage(text: "Halo")
sayMessage("Hola", "February")
func sum2Numbers (number1 num1: Int, number2 num2:Int) {
print("\(num1 + num2)")
}
sum2Numbers(number1: 1, number2: 2)
// 3º
func multiply(number1 num1:Int, number2 num2:Int) -> Int {
let result = num1 * num2
return result;
//return num1 * num2
}
var result = multiply(number1: 2, number2: 4)
print(result)
| true
|
0693cc71aa99c3f1ddaa5ca332b1d23fd9db08ce
|
Swift
|
iffytheperfect1983/NetworkingTemplate
|
/NetworkingTemplate/ViewController.swift
|
UTF-8
| 3,874
| 2.921875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// NetworkingTemplate
//
// Created by Phanit Pollavith on 5/5/21.
//
import UIKit
import Alamofire
import PromiseKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var myLabel: UILabel!
private lazy var session: Session = {
return ConnectionSettings.sessionManager()
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func buttonPressed(_ sender: Any) {
handleButtonPress1()
}
func handleButtonPressed() {
guard let numberString = textField.text,
let number = Int(numberString) else {
return
}
let apiRouterStructure = APIRouterStructer(apiRouter: .todos(number: number))
let todosPromise: Promise<Todo> = session.request(apiRouterStructure)
firstly {
todosPromise
}
.then { [weak self] todo -> Promise<Todo> in
guard let self = self else { throw InternalError.unexpected }
self.myLabel.text = "\(todo.id). " + todo.title
return Promise<Todo>.value(todo)
}
.then { [weak self] todo -> Promise<Todo> in
guard let self = self else { throw InternalError.unexpected }
let nextID = todo.id + 1
let apiRouterStructure = APIRouterStructer(apiRouter: .todos(number: nextID))
let todosPromiseNext: Promise<Todo> = self.session.request(apiRouterStructure)
return todosPromiseNext
}
.then{ [weak self] todoNext -> Promise<Todo> in
guard let self = self else { throw InternalError.unexpected }
self.myLabel.text = self.myLabel.text! + "\n" + "\(todoNext.id). " + todoNext.title
let nextID = todoNext.id + 5
let apiRouterStructure = APIRouterStructer(apiRouter: .todos(number: nextID))
let todosPromiseNext: Promise<Todo> = self.session.request(apiRouterStructure)
return todosPromiseNext
}
.then { [weak self] todoNext -> Promise<Void> in
guard let self = self else { throw InternalError.unexpected }
self.myLabel.text = self.myLabel.text! + "\n" + "\(todoNext.id). " + todoNext.title
return Promise()
}
.catch { [weak self] error in
guard let self = self else { return }
print("there was an error")
self.myLabel.text = "There was an error"
}
.finally {
print("finally done")
}
}
}
extension ViewController {
func handleButtonPress1() {
guard let numberString = textField.text,
let number = Int(numberString) else {
return
}
let postModel = PostModel(title: "Hello Title", body: "This is body!", userID: 20)
let apiRouterStructure = APIRouterStructer(apiRouter: .posts(postModel: postModel))
let postPromise: Promise<Post> = session.request(apiRouterStructure)
firstly {
postPromise
}
.then { [weak self] post -> Promise<Post> in
guard let self = self else { throw InternalError.unexpected }
self.myLabel.text = "ID: \(post.id) - " + "UserID: \(post.userID)--" + post.body
return Promise<Post>.value(post)
}
.then { [weak self] post -> Promise<Todo> in
guard let self = self else { throw InternalError.unexpected }
let apiRouterStructure = APIRouterStructer(apiRouter: .todos(number: number))
let todosPromise: Promise<Todo> = self.session.request(apiRouterStructure)
return todosPromise
}
.then { [weak self] todo -> Promise<Void> in
guard let self = self else { throw InternalError.unexpected }
self.myLabel.text = self.myLabel.text! + "\n" + "\(todo.id). " + todo.title
return Promise()
}
.catch { [weak self] error in
guard let self = self else { return }
print("there was an error")
self.myLabel.text = "There was an error"
}
.finally {
print("finally done")
}
}
}
| true
|
896721d74fac3827b7fe05fc9ee507d564769bb8
|
Swift
|
mhanlon/AppDevelopmentWithSwiftResources
|
/Student Resources/2 - Introduction to UIKit/4 - Classes and Inheritance/lab/Lab - Classes.playground/Pages/1. Exercise - Define a Base Class.xcplaygroundpage/Contents.swift
|
UTF-8
| 1,814
| 4.84375
| 5
|
[
"MIT"
] |
permissive
|
/*:
## Exercise - Define a Base Class
- Note: The exercises below are based on a game where a spaceship avoids obstacles in space. The ship is positioned at the bottom of a coordinate system and can only move left and right while obstacles "fall" from top to bottom. Throughout the exercises, you'll create classes to represent different types of spaceships that can be used in the game.
Create a `Spaceship` class with three variable properties: `name`, `health`, and `position`. The default value of `name` should be an empty string and `health` should be 0. `position` will be represented by an `Int` where negative numbers place the ship further to the left and positive numbers place the ship further to the right. The default value of `position` should be 0.
*/
/*:
Create a `let` constant called `falcon` and assign it to an instance of `Spaceship`. After initialization, set `name` to "Falcon".
*/
/*:
Go back and add a method called `moveLeft()` to the definition of `Spaceship`. This method should adjust the position of the spaceship to the left by one. Add a similar method called `moveRight()` that moves the spaceship to the right. Once these methods exist, use them to move `falcon` to the left twice and to the right once. Print the new position of `falcon` after each change in position.
*/
/*:
The last thing `Spaceship` needs for this example is a method to handle what happens if the ship gets hit. Go back and add a method `wasHit()` to `Spaceship` that will decrement the ship's health by 5, then if `health` is less than or equal to 0 will print "Sorry. Your ship was hit one too many times. Do you want to play again?" Once this method exists, call it on `falcon` and print out the value of `health`.
*/
//: page 1 of 4 | [Next: Exercise - Create a Subclass](@next)
| true
|
1dba33939787732573f73e5ffffc216288282e91
|
Swift
|
lahavamir27/MySecert
|
/ProjectX/Collection + Extention.swift
|
UTF-8
| 422
| 2.9375
| 3
|
[] |
no_license
|
//
// Collection + Extention.swift
// ProjectX
//
// Created by amir lahav on 25.9.2017.
// Copyright © 2017 LA Computers. All rights reserved.
//
import Foundation
extension Collection{
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
subscript (safe index: Index) -> Generator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
| true
|
e2d73bdb475308a75b0538cc54551480bb980a4c
|
Swift
|
devMfawzy/TheNewsApp
|
/TheNewsApp/View Models/NewsDetailsViewModel.swift
|
UTF-8
| 1,614
| 2.921875
| 3
|
[] |
no_license
|
//
// NewsDetailsViewModel.swift
// TheNewsApp
//
// Created by Mohamed Fawzy on 30/06/2021.
//
import UIKit
class NewsDetailsViewModel: NewsDetailsViewModeling {
private var article: Article
init(model: Article) {
self.article = model
}
var imageURL: URL? {
guard let urlString = article.urlToImage else {
return nil
}
return URL(string: urlString)
}
var title: String? {
article.title
}
var description: String? {
article.description
}
var author: String? {
article.author
}
var date: String? {
guard let dateString = article.publishedAt else {
return nil
}
let dateFormater = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let date = dateFormater.date(from: dateString)
dateFormater.dateFormat = "MMM d, yyyy"
return dateFormater.string(from: date!)
}
var content: NSAttributedString? {
guard let attributedString = article.content?.htmlToAttributedString else {
return nil
}
let mutableAttributedString = NSMutableAttributedString(attributedString: attributedString)
mutableAttributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 17), range: NSRange(location: 0, length: attributedString.length))
return mutableAttributedString
}
var url: URL? {
guard let urlString = article.url else {
return nil
}
return URL(string: urlString)
}
}
| true
|
6a6d9d97ff1f1adb3f3b2d4398b33ef6ab99088e
|
Swift
|
AlexKokhovets/PrPS-final-lab
|
/HospitalApp/HospitalApp/EmployeeInterface.swift
|
UTF-8
| 708
| 2.703125
| 3
|
[] |
no_license
|
//
// EmployeeInterface.swift
// HospitalApp
//
// Created by Alex on 19.05.2020.
// Copyright © 2020 Alex. All rights reserved.
//
import Foundation
class EmployeeInterface{
var emplID: Int = 0
var currentCallID: Int = 0
var db: DBHelper
init(db: DBHelper, id:Int){
self.db = db
self.emplID = id
}
func finishCall(diagnos: String, hosp: Bool){
db.finishCall(callId: currentCallID, diagnos: diagnos, hosp: hosp)
}
func getFreeCall() -> Call{
let call = db.getFreeCall(brigID: Int(db.getBrigadeId(id: emplID)))
currentCallID = call.id
return call
}
func getID()-> Int{
return emplID
}
}
| true
|
2ced5ae6253b2888712b1e1d333b9dbdf5006044
|
Swift
|
michelefranco/occurrences-counter
|
/OccurrencesCounter/Occurrences Management/Word Occurrence Manager/WordOccurrenceManager.swift
|
UTF-8
| 183
| 2.671875
| 3
|
[] |
no_license
|
import Foundation
protocol WordOccurrenceManager {
init(text: String)
func occurrences() -> Set<WordOccurrence>
func occurrences(with order: Order) -> [WordOccurrence]
}
| true
|
096c602876ffd7531f77e84c5372e1fc123d8a71
|
Swift
|
psvmc/PhotoSelect_Swift
|
/PhotoSelect_Swift/ViewController.swift
|
UTF-8
| 2,488
| 2.53125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// PhotoSelect_Swift
//
// Created by 张剑 on 16/1/23.
// Copyright © 2016年 张剑. All rights reserved.
//
import UIKit
class ViewController: UIViewController,DNImagePickerControllerDelegate{
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var rightImageView: UIImageView!
@IBOutlet weak var filePathLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
imageView.contentMode = UIViewContentMode.scaleAspectFit
rightImageView.contentMode = UIViewContentMode.scaleAspectFit
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func photoSelectClick(_ sender: AnyObject) {
self.filePathLabel.text = "";
let imagePicker = DNImagePickerController();
imagePicker.imagePickerDelegate = self;
imagePicker.navigationBarColor = UIColor.black;
self.present(imagePicker, animated: true, completion: nil);
}
//图片选择组件
private func dnImagePickerController(_ imagePicker: DNImagePickerController!, sendImages imageAssets: [AnyObject]!, isFullImage fullImage: Bool) {
var urls:[URL] = [];
for obj in imageAssets{
let dnasset = obj as! DNAsset;
urls.append(dnasset.url);
}
ZJALAssetUtils.aLAsset(with: urls[0]) { (asset) -> Void in
if(asset != nil){
let representation = asset?.defaultRepresentation()
let image = UIImage(cgImage:(representation?.fullScreenImage().takeUnretainedValue())!)
self.imageView.image = image;
}
}
ZJALAssetUtils.images(withURLs: urls) { (imageURLs) -> Void in
var myimageURLs:[URL] = [];
var filePathText = "";
self.filePathLabel.text = "";
for obj in imageURLs!{
let imageURL = obj as! URL;
myimageURLs.append(imageURL);
filePathText += "文件路径: \(imageURL.path)\n\n";
}
if(myimageURLs.count > 0){
self.rightImageView.image = UIImage(contentsOfFile: myimageURLs[0].path);
}
self.filePathLabel.text = filePathText;
}
}
func dnImagePickerControllerDidCancel(_ imagePicker: DNImagePickerController!) {
imagePicker.dismiss(animated: true, completion: nil);
}
}
| true
|
c12fbc338fa70fe9702e0f7f4bf47d9dbc3a2f3f
|
Swift
|
wojtowiczm/SwiftyCoreData
|
/SwiftyCoreDataExample/SwiftyCoreDataExample/Extension/ArrayExtension.swift
|
UTF-8
| 733
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
//
// ArrayExtension.swift
// SwiftyCoreDataExample
//
// Created by Michał Wójtowicz on 09/01/2019.
// Copyright © 2019 Michał Wójtowicz. All rights reserved.
//
import Foundation
extension Collection where Element: Numeric {
/// Returns the total sum of all elements in the array
var total: Element { return reduce(0, +) }
}
extension Collection where Element: BinaryInteger {
/// Returns the average of all elements in the array
var average: Double {
return isEmpty ? 0 : Double(Int(total)) / Double(count)
}
}
extension Collection where Element: BinaryFloatingPoint {
/// Returns the average of all elements in the array
var average: Element {
return isEmpty ? 0 : total / Element(count)
}
}
| true
|
730a1a5902eb5494a848ec9b7da16c30f077cd96
|
Swift
|
GiPyoK/ios-guided-project-mapkit-starter
|
/Quakes/Quakes/EarthquakesViewController.swift
|
UTF-8
| 2,948
| 2.765625
| 3
|
[] |
no_license
|
//
// EarthquakesViewController.swift
// Quakes
//
// Created by Paul Solt on 10/3/19.
// Copyright © 2019 Lambda, Inc. All rights reserved.
//
import UIKit
import MapKit
class EarthquakesViewController: UIViewController {
// NOTE: You need to import MapKit to link to MKMapView
@IBOutlet var mapView: MKMapView!
var quakeFetcher = QuakeFetcher()
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.register(MKMarkerAnnotationView.self, forAnnotationViewWithReuseIdentifier: "QuakeView")
fetchQuakes()
}
private func fetchQuakes() {
quakeFetcher.fetchQuakes { (quakes, error) in
if let error = error {
fatalError("Error: \(error)")
}
if let quakes = quakes {
// print("Quakes: \(quakes)")
print("Number of Quakes: \(quakes.count)")
// Show a region of interest -> Zoom map to location
// Show the biggest quake
// Customize the popup (register Cell)
// Custom pin color
DispatchQueue.main.async {
self.mapView.addAnnotations(quakes)
// Zoom to the earthquake
// guard let largestQuake = quakes.first else { return }
// Zoom to La Habra
let coordinateSpan = MKCoordinateSpan(latitudeDelta: 2, longitudeDelta: 2)
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 33.9319, longitude: -117.9461), span: coordinateSpan)
self.mapView.setRegion(region, animated: true)
}
}
}
}
}
extension EarthquakesViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let quake = annotation as? Quake else { fatalError("Only Quake objects are shown in demo") }
guard let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "QuakeView") as? MKMarkerAnnotationView else {
print("Missing a registered map annotation view")
return nil
}
annotationView.glyphImage = UIImage(named: "QuakeIcon")
if quake.magnitude >= 6 {
annotationView.markerTintColor = .red
} else if quake.magnitude >= 3 && quake.magnitude < 6 {
annotationView.markerTintColor = .orange
} else {
annotationView.markerTintColor = .yellow
}
annotationView.canShowCallout = true
let detailView = QuakeDetailView()
detailView.quake = quake
annotationView.detailCalloutAccessoryView = detailView
return annotationView
}
}
| true
|
cdbf9e7d3fa94a1bdc75cdd0e5cffe8069466e4d
|
Swift
|
kandelvijaya/DeclarativeTableView
|
/DeclarativePlayground.playground/Contents.swift
|
UTF-8
| 4,044
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
import DeclarativeTableView
import PlaygroundSupport
class ViewController: UIViewController {
private var currentChild: UIViewController?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let models = ["Apple", "Microsoft", "Google", "||Zalando is a company that i work currently at.||"]
let identifier = "MyCell"
let cellDescs = models.map { m -> CollectionCellDescriptor<String, SimpleCell> in
var cd = CollectionCellDescriptor(m, identifier: identifier, cellClass: SimpleCell.self, configure: { cell in
cell.textLabel?.text = m
})
cd.onSelect = { [weak self] in
self?.tapped(m)
}
return cd
}
let sections = CollectionSectionDescriptor(with: cellDescs)
let modelsForNextSection = [ModelItem(color: .red, int: 1), .init(color: .blue, int: 2), .init(color: .purple, int: 3)]
let identifier2 = "IntCell"
let cellDescs2 = modelsForNextSection.map { m in
return CollectionCellDescriptor(m, identifier: identifier2, cellClass: SimpleCell.self, configure: { cell in
cell.textLabel?.text = "\(m.int)"
cell.backgroundColor = m.color
})
}
let secondSection = CollectionSectionDescriptor(with: cellDescs2)
let mc1 = CollectionCellDescriptor(1, identifier: "mc1", cellClass: SimpleCell.self, configure: { cell in
cell.textLabel?.text = "\(1)"
})
let mc2 = CollectionCellDescriptor("hello", identifier: "mc2", cellClass: AnotherCell.self, configure: { cell in
cell.textLabel?.text = "hello"
cell.backgroundColor = .purple
})
let mixedSection = CollectionSectionDescriptor(with: [mc1.any(), mc2.any()])
let combinedSections = [sections.any(), secondSection.any(), mixedSection]
let list = CollectionViewController(with: combinedSections)
embed(list)
}
struct ModelItem: Hashable {
let color: UIColor
let int: Int
}
func tapped(_ item: String) {
let thisModels = [1,2,3]
let cellDescs = thisModels.map { item in
return CollectionCellDescriptor(item, identifier: "Inner", cellClass: SimpleCell.self, configure: { cell in
cell.textLabel?.text = "\(item)"
})
}
let sectionDesc = CollectionSectionDescriptor(with: cellDescs)
let list = CollectionViewController(with: [sectionDesc])
self.show(list, sender: self)
}
func embed(_ vc: UIViewController) {
self.currentChild = vc
self.addChild(vc)
vc.view.frame = view.bounds
self.view.addSubview(vc.view)
vc.didMove(toParent: self)
}
func removeChild() {
self.currentChild?.willMove(toParent: nil)
self.currentChild?.view.removeFromSuperview()
self.currentChild?.removeFromParent()
}
}
class SimpleCell: UICollectionViewCell {
var textLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
setupLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLabel()
}
func setupLabel() {
textLabel = UILabel()
self.contentView.addSubview(textLabel)
textLabel.translatesAutoresizingMaskIntoConstraints = false
[
textLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
textLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
textLabel.topAnchor.constraint(equalTo: contentView.topAnchor),
textLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
].forEach { $0.isActive = true }
}
}
class AnotherCell: SimpleCell {
}
| true
|
186006f4ca802e370e647587ef9598f885eb7fc2
|
Swift
|
aybekckaya/Plist
|
/Plist/Plist/Plist/PlistSwift.swift
|
UTF-8
| 9,817
| 3.25
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Plist.swift
// Plist
//
// Created by aybek can kaya on 05/09/2017.
// Copyright © 2017 aybek can kaya. All rights reserved.
//
import UIKit
/**
used to define the source path of plist.
**documentsDirectory** : plist will be created at device documents directory. Once it is created , it can be accessible from app's documents directory.
**bundle** : plist is at app's bundle. Once it is accessed , it will be directly copied to documents directory if it is not created before. After that it can be accessible from documents directory.
Note that : if plist source path is `bundle` and it has created before , then for reading and writing this class uses latest version which is at documents directory
*/
enum PlistSourcePath {
case documentsDirectory
case bundle
}
class Plist: NSObject {
/**
Plist Errors that conforms Swift's Error protocol.
*/
enum PlistError:Error {
// plist contents is null. So it can not be accessible.
case couldNotFetchPlistContents
// error occured while converting object to json string
case couldNotConvertToJsonString
// string is not a json , it cannot be decoded
case couldNotDecodeJson
func errorComponent()->Error {
switch self {
case .couldNotConvertToJsonString:
return NSError(domain: "could not convert json", code: 10000, userInfo: nil) as Error
case .couldNotFetchPlistContents:
return NSError(domain: "could not fetch plist contents", code: 10001, userInfo: nil) as Error
case .couldNotDecodeJson:
return NSError(domain: "could not decode json string", code: 10002, userInfo: nil) as Error
}
}
}
// name of the plist file without extension
fileprivate var name:String = ""
// source path
fileprivate var source:PlistSourcePath = .documentsDirectory
// folder path of plist . Plist is at : /documentsFolder/folderPath/name.plist
fileprivate var folderPath:String = "plists"
// plist path can be accessible , but it should not be settable
var plistPath:String {
get{ return plistFullPath() }
}
/**
# Initializer
## parameters :
**name** : name of the plist .
** source** : from which source plist can be accessible (default : documents directory)
** folder Path ** : plist folder at documents directory.
*/
init(_name:String , _source:PlistSourcePath = .documentsDirectory , _folderPath:String = "plists") {
super.init()
name = _name
source = _source
folderPath = _folderPath.replacingOccurrences(of: "/", with: "")
source == .documentsDirectory ? createPlist() : copyFromBundle()
}
/**
creates plist if it is not exists.
*/
private func createPlist() {
let fullPath:String = plistFullPath()
guard !fullPath.fileExistAtPath() else { return }
folderPath.createDir()
let emptyDct = NSDictionary(dictionary: [:])
emptyDct.write(toFile: fullPath, atomically: true)
}
private func plistFullPath()->String {
return String.documentsDirectoryPath()+"/"+folderPath+"/"+name+".plist"
}
/**
copy plist from bundle to /documentsDir/folderPath/
throws error if it cannot be created.
*/
private func copyFromBundle() {
let fullname = name+".plist"
guard !plistPath.fileExistAtPath() else { return }
folderPath.createDir()
guard let documentsURL = Bundle.main.resourceURL?.appendingPathComponent(fullname) else { return }
do {
try FileManager.default.copyItem(atPath: (documentsURL.path), toPath: plistPath)
} catch let error as NSError {
print("Error:\(error.description)")
}
}
/**
returns whole content of plist as a dictionary.
*/
func contents()->[String:Any]? {
let path = plistFullPath()
guard let dct = NSDictionary(contentsOfFile: path) as? [String: Any] else { return nil }
return dct
}
/**
saves json with key in async fashion.
*/
func save(key:String , data:Any , completion:@escaping (_ error:Error?)->Void) {
guard var contentsList = contents() else {
completion(PlistError.couldNotFetchPlistContents.errorComponent())
return
}
let dct:[String:Any] = [key:data]
guard let jsonStr = dct.toJsonString() else {
completion(PlistError.couldNotConvertToJsonString.errorComponent())
return
}
contentsList[key] = jsonStr
DispatchQueue.global(qos: .background).async {
(contentsList as NSDictionary).write(toFile: self.plistFullPath(), atomically: true)
DispatchQueue.main.async {
completion(nil)
}
}
}
/**
reads value with given key.
*/
func read(key:String , completion:@escaping(_ data:[String:Any]? , _ error:Error?)->Void) {
DispatchQueue.global(qos: .background).async {
let path = self.plistFullPath()
guard let dct = NSDictionary(contentsOfFile: path) as? [String: Any] else {
DispatchQueue.main.async { completion(nil, PlistError.couldNotFetchPlistContents.errorComponent()) }
return
}
guard let content = dct[key] as? String else {
DispatchQueue.main.async { completion(nil, nil) }
return
}
guard let json = content.decodeJSON() else {
completion(nil, PlistError.couldNotDecodeJson.errorComponent())
return
}
completion(json, nil)
}
}
/**
deletes the value with given key.
*/
func removeKey(key:String) {
guard var contents:[String:Any] = contents() else { return }
contents.removeValue(forKey: key)
(contents as NSDictionary).write(toFile: plistPath, atomically: true)
}
/**
removes the plist file.
*/
func removePlist() {
let fullPath:String = plistFullPath()
guard fullPath.fileExistAtPath() else { return }
fullPath.removeFile()
}
/**
lists all plist names that is at /documents/plistPath/
*/
static func allPlistFiles(directoryName:String)->[String] {
let allFiles:[String] = directoryName.allFilesInDirectory()
return allFiles.map{ $0.components(separatedBy: "/").last! }.filter{element in
let ext = element.components(separatedBy: ".").last!
return ext == "plist"
}.map{ $0.components(separatedBy: ".").first! }
}
}
protocol JsonConvertible {
func toJsonString()->String?
}
extension JsonConvertible {
func toJsonString()->String? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonString = String(data: jsonData, encoding: String.Encoding.utf8)
return jsonString
} catch {
return nil
}
}
}
extension Array:JsonConvertible {}
extension Dictionary:JsonConvertible {}
extension String {
func decodeJSON()->[String:Any]? {
guard let data = self.data(using: String.Encoding.utf8) else { return nil }
do{
let jsonParsed = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
return jsonParsed as? [String:Any]
}catch {
print("err: \(error.localizedDescription)")
return nil
}
}
static func documentsDirectoryPath()->String {
return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
}
func fileExistAtPath()->Bool {
return FileManager.default.fileExists(atPath: self)
}
func directoryExists()->Bool {
let fileManager = FileManager.default
var isDir : ObjCBool = false
if fileManager.fileExists(atPath: self, isDirectory:&isDir) {
if isDir.boolValue {
return true
} else {
fatalError("String:\(self) is not a directory path")
}
}
return false
}
func removeFile() {
do { try FileManager.default.removeItem(atPath: self)}
catch { print("error : \(error.localizedDescription)") }
}
func allFilesInDirectory()->[String] {
var documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
documentsUrl.appendPathComponent(self)
var contents:[String] = []
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
contents = directoryContents.map{ $0.absoluteString }
return contents
} catch { return contents }
}
func createDir() {
guard !self.directoryExists() else { return }
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let pt = self+"/"
let dataPath = documentsDirectory.appendingPathComponent(pt)
do { try FileManager.default.createDirectory(at: dataPath, withIntermediateDirectories: false, attributes: nil) }
catch let error as NSError { print("Error creating directory: \(error.localizedDescription)") }
}
}
| true
|
e832ca684325fe81b538e2c844ce3f459525391b
|
Swift
|
jellodomingo/Where2Meet
|
/Where2Meet/Controllers/ViewController.swift
|
UTF-8
| 812
| 2.859375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Where2Meet
//
// Created by Angelo Domingo on 2/1/20.
// Copyright © 2020 Angelo Domingo. All rights reserved.
//
import UIKit
import Foundation
enum APIError: Error {
case responseProblem
case decodingProblem
case encodingProblem
case otherProblem
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/*
let testLocation = Location(deviceId: "testDeviceID", code: "testCode", location: "testLocation")
save(testLocation, completion: {result in
switch result {
case .success(let message):
print("It worked?")
case .failure(let error):
print("Error: \(error)")
}
})
*/
}
}
| true
|
dedd8bea108f03add350ba9fc64da58242c364ea
|
Swift
|
MCTOK1903/LearningSwift
|
/F1Racers/F1Racers/Racer.swift
|
UTF-8
| 430
| 2.765625
| 3
|
[] |
no_license
|
//
// Racer.swift
// F1Racers
//
// Created by MCT on 9.03.2020.
// Copyright © 2020 MCT. All rights reserved.
//
import Foundation
import UIKit
class Racer {
var name : String
var racerOfTeam : String
var racerImage :UIImage
init(racerName: String, racerTeam: String, racerOfImage:UIImage) {
name = racerName
racerOfTeam = racerTeam
racerImage = racerOfImage
}
}
| true
|
edb8113f6f5da249d09df9943fd2d9b1fb0502da
|
Swift
|
difomiry/Coordinator
|
/Sources/Coordinator/Result+Void.swift
|
UTF-8
| 119
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
extension Result where Success == Void {
/// A success.
public static var success: Self {
.success(())
}
}
| true
|
20e97d4e84a92e2dbd8e0ff2a27bc3a25f107ca6
|
Swift
|
neoneye/SwiftSnakeEngine
|
/EngineShared/Bot/SnakeBot4.swift
|
UTF-8
| 23,099
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
// MIT license. Copyright (c) 2020 Simon Strandgaard. All rights reserved.
import Foundation
fileprivate struct Constant {
static let printStats = false
static let printVerbose = false
}
public class SnakeBot4: SnakeBot {
public static var info = SnakeBotInfo(
uuid: "5563adb7-44ee-4dbb-bf80-dd0dc7989a2c",
name: "Tree search"
)
public let plannedMovement: SnakeBodyMovement
private let iteration: UInt
private init(iteration: UInt, plannedMovement: SnakeBodyMovement) {
self.iteration = iteration
self.plannedMovement = plannedMovement
}
required public convenience init() {
self.init(iteration: 0, plannedMovement: .dontMove)
}
public var plannedPath: [IntVec2] {
[]
}
public func compute(level: SnakeLevel, player: SnakePlayer, oppositePlayer: SnakePlayer, foodPosition: IntVec2?) -> SnakeBot {
let t0 = CFAbsoluteTimeGetCurrent()
let result = compute_inner(level: level, player: player, oppositePlayer: oppositePlayer, foodPosition: foodPosition)
let t1 = CFAbsoluteTimeGetCurrent()
let elapsed: Double = t1 - t0
if Constant.printStats {
log.debug("#\(iteration) total elapsed: \(elapsed)")
}
return result
}
private func compute_inner(level: SnakeLevel, player: SnakePlayer, oppositePlayer: SnakePlayer, foodPosition: IntVec2?) -> SnakeBot {
let scope_t0 = CFAbsoluteTimeGetCurrent()
// if iteration > 0 {
// log.debug("---")
// }
guard player.isInstalledAndAlive else {
//log.debug("Do nothing. The bot must be installed and alive. It doesn't make sense to run the bot.")
return SnakeBot4()
}
// log.debug("#\(iteration) -")
let level_emptyPositionSet: Set<IntVec2> = level.emptyPositionSet
// IDEA: This is being computed over and over. This is overkill, since the food position rarely changes.
// A faster approach would be to re-compute this only when the food position changes.
let distanceToFoodMap: SnakeLevelDistanceMap = SnakeLevelDistanceMap.create(level: level, initialPosition: foodPosition)
// IDEA: Computing ChoiceNodes over and over takes time. Caching of the choice nodes to the next "compute",
// so that less time is spent on allocating the same memory over and over.
let rootChoice = ParentChoiceNode.create(depth: 9)
// log.debug("nodeCount: \(rootChoice.nodeCount)")
rootChoice.assignMovements()
var nodes: [LeafChoiceNode] = rootChoice.leafNodes()
// log.debug("nodes: \(nodes.count)")
let scope_t1 = CFAbsoluteTimeGetCurrent()
if Constant.printStats {
let elapsed: Double = scope_t1 - scope_t0
log.debug("#\(iteration) setup: \(elapsed)")
}
// Discard poor choices where the snake impacts a wall
var count_collisionWithWall: Int = 0
var elapsed_collisionWithWall: Double = 0
do {
let t0 = CFAbsoluteTimeGetCurrent()
rootChoice.checkCollisionWithWall(level_emptyPositionSet: level_emptyPositionSet, snakeHead: player.snakeBody.head)
let t1 = CFAbsoluteTimeGetCurrent()
let count0: Int = nodes.count
nodes.removeAll { $0.collisionWithWall }
let count1: Int = nodes.count
count_collisionWithWall = count0 - count1
elapsed_collisionWithWall = t1 - t0
}
if Constant.printStats {
log.debug("#\(iteration) collisions with wall: \(count_collisionWithWall) elapsed: \(elapsed_collisionWithWall)")
}
// Discard choices that causes the snake to eat itself
// Discard choices where the snake first eats food, and grows longer, and afterwards eats itself
var count_collisionWithSelf: Int = 0
var elapsed_collisionWithSelf: Double = 0
do {
let t0 = CFAbsoluteTimeGetCurrent()
rootChoice.checkCollisionWithSelf(snakeBody: player.snakeBody, foodPosition: foodPosition)
let t1 = CFAbsoluteTimeGetCurrent()
let count0: Int = nodes.count
nodes.removeAll { $0.collisionWithSelf }
let count1: Int = nodes.count
count_collisionWithSelf = count0 - count1
elapsed_collisionWithSelf = t1 - t0
}
if Constant.printStats {
log.debug("#\(iteration) collisions with self: \(count_collisionWithSelf) elapsed: \(elapsed_collisionWithSelf)")
}
// Estimate distances to the food
// Prefer the choices that gets the snake closer to the food
let count_estimateDistanceToFood: Int = nodes.count
var elapsed_estimateDistanceToFood: Double = 0
do {
let t0 = CFAbsoluteTimeGetCurrent()
let currentHead: SnakeHead = player.snakeBody.head
for node: ChoiceNode in nodes {
var head: SnakeHead = currentHead
var distanceToFood: UInt32 = UInt32.max
var distanceToFoodIgnoringAnyObstacles: UInt32 = UInt32.max
var hasFood = true
let currentFoodPosition: IntVec2 = foodPosition ?? IntVec2.zero
for (numberOfTicks, movement) in node.movements.enumerated() {
let snakeBodyMovement: SnakeBodyMovement = movement.snakeBodyMovement
head = head.simulateTick(movement: snakeBodyMovement)
if hasFood && head.position == currentFoodPosition {
distanceToFood = UInt32(numberOfTicks)
hasFood = false
// log.debug("choice leads directly to food \(distanceToFood)")
}
if hasFood {
let d: UInt32 = 10000 + currentFoodPosition.manhattanDistance(head.position) * 10000 + UInt32(numberOfTicks)
if distanceToFoodIgnoringAnyObstacles > d {
distanceToFoodIgnoringAnyObstacles = d
}
}
}
let lastPosition: IntVec2 = head.position
// // Experiments computing a SnakeLevelDistanceMap that also considers the snake body. However it's incredibly slow.
// var distanceToFoodIgnoringSelf: UInt32 = UInt32.max
// if hasFood {
// var body: SnakeBody = player.snakeBody
// var hasFood2: Bool = (foodPosition != nil)
// for (numberOfTicks, movement) in node.movements.enumerated() {
// let snakeBodyMovement: SnakeBodyMovement = movement.snakeBodyMovement
// let head: SnakeHead = body.head.simulateTick(movement: snakeBodyMovement)
// let act: SnakeBodyAct
// if hasFood2 && head.position == foodPosition {
// act = .eat
// hasFood2 = false
// } else {
// act = .doNothing
// }
// body = body.stateForTick(movement: snakeBodyMovement, act: act)
//
// }
// var emptyPositionsSet = level_emptyPositionSet
// emptyPositionsSet.subtract(body.positionSet())
// let distanceToFoodMap2 = SnakeLevelDistanceMap.create(levelSize: level.size, emptyPositionSet: emptyPositionsSet, optionalFoodPosition: foodPosition)
//
// let lastPosition2: IntVec2 = body.head.position
// if hasFood2 {
// if let cell: DistanceToFoodCell = distanceToFoodMap2.getValue(lastPosition) {
// switch cell {
// case .distance(let steps):
// distanceToFoodIgnoringSelf = steps
// case .obscured:
// ()
// }
// }
// }
//
// }
// Optimally the the distanceToFoodMap should be computed for every tick in the simulation.
// And the distanceToFoodMap should be used for estimating. However this is a expensive computation.
// When there is no distanceToFood, then I'm relying on distanceToFoodIgnoringSelf and this gives a terrible estimate.
// IDEA: A less expensive operaion could be to compute the distance to food considering original self.
var distanceToFoodIgnoringSelf: UInt32 = UInt32.max
if hasFood {
if let cell: SnakeLevelDistanceMapCell = distanceToFoodMap.getValue(lastPosition) {
switch cell {
case .distance(let steps):
distanceToFoodIgnoringSelf = steps
case .obscured:
()
}
}
}
var distance: UInt32 = UInt32.max
if distanceToFood < UInt32.max {
distance = distanceToFood
} else {
if distanceToFoodIgnoringSelf < UInt32.max {
distance = 100 + distanceToFoodIgnoringSelf * 100
} else {
if distanceToFoodIgnoringAnyObstacles < UInt32.max {
distance = distanceToFoodIgnoringAnyObstacles
}
}
}
node.setEstimatedDistanceToFood(distance: distance)
}
let t1 = CFAbsoluteTimeGetCurrent()
elapsed_estimateDistanceToFood = t1 - t0
nodes.sort {
$0.estimatedDistanceToFood < $1.estimatedDistanceToFood
}
}
if Constant.printStats {
log.debug("#\(iteration) estimate distance to food: \(count_estimateDistanceToFood) elapsed: \(elapsed_estimateDistanceToFood)")
printEstimatedDistancesToFood(nodes: nodes)
}
// Compute alive/death risk for each of the choices.
// Minimize risk of death.
//
// Compute the number of ticks to get to the food.
// Minimize the number of ticks.
//
// Minimize the number of turns.
//
// Maximize the number of available choices after following a full sequence of movements.
// If there are 3 candidate choices, then compare the number of open choices after following each of the candidate movements.
// Pick the path with the most number of open choices.
//
// Take a longer route, in order to make room near the food.
//
// Determine most likely areas where new food will be placed.
// After picking up the food, then simulate using the likely next food position.
//
// Simulate choices of the opponent, the same way as for the player itself.
//
// Do an intersection of the opponent nodes with the player nodes.
//
// Avoid eating the opponent snake, since it's poisonous.
// Discard the choices that leads to the food,
// that also causes the snake to get trapped a few ticks later.
// Do this by simulating the entire snake and check for collisions.
var numberOfDeaths: UInt = 0
var nodeWithMetadataArray = [LeafChoiceNodeWithMetaData]()
for (nodeIndex, node) in nodes.enumerated() {
if nodeIndex == 5 && numberOfDeaths < 5 {
break
}
if nodeIndex == 10 && numberOfDeaths < 10 {
break
}
if nodeIndex == 20 && numberOfDeaths < 20 {
break
}
if nodeIndex == 40 && numberOfDeaths < 40 {
break
}
if nodeIndex == 80 && numberOfDeaths < 80 {
break
}
guard nodeIndex < 160 else {
break
}
var body: SnakeBody = player.snakeBody
var hasFood: Bool = (foodPosition != nil)
for movement in node.movements {
let snakeBodyMovement: SnakeBodyMovement = movement.snakeBodyMovement
let head: SnakeHead = body.head.simulateTick(movement: snakeBodyMovement)
let act: SnakeBodyAct
if hasFood && head.position == foodPosition {
act = .eat
hasFood = false
} else {
act = .doNothing
}
body = body.stateForTick(movement: snakeBodyMovement, act: act)
}
var availablePositions: Set<IntVec2> = Set<IntVec2>(level_emptyPositionSet)
let snakePositions: Set<IntVec2> = body.positionSet()
availablePositions.subtract(snakePositions)
availablePositions.insert(body.head.position)
let snakeLength: UInt = body.length
let areaSize: UInt = MeasureAreaSize.compute(positionSet: availablePositions, startPosition: body.head.position)
let insufficientRoom: Bool = snakeLength > areaSize
let prettyMovements: String = node.movements.map { $0.shorthand }.joined(separator: "")
if insufficientRoom {
if Constant.printVerbose {
log.debug("#\(iteration) choice#\(nodeIndex) \(prettyMovements) areaSize: \(areaSize) snakeLength: \(snakeLength) DEATH. Insufficient room for snake!")
}
numberOfDeaths += 1
// IDEA: Keep track of all the certain death cases, so they can be prioritized.
// This is useful when there are no "alive case". In this case we still want to pick the most optimal case.
} else {
if Constant.printVerbose {
log.debug("#\(iteration) choice#\(nodeIndex) \(prettyMovements) areaSize: \(areaSize) snakeLength: \(snakeLength)")
}
let nodeWithMetadata = LeafChoiceNodeWithMetaData(
leafChoiceNode: node,
areaSize: areaSize,
snakeLength: snakeLength
)
nodeWithMetadataArray.append(nodeWithMetadata)
}
}
// IDEA: Prioritize based on areaSize, snakeLength, risk.
// nodeWithMetadataArray.sort { $0.areaSize < $1.areaSize }
let optimalNodes: [LeafChoiceNode] = nodeWithMetadataArray.map { $0.leafChoiceNode }
var pendingMovement: SnakeBodyMovement = .moveForward
// Pick the first
for node: ChoiceNode in optimalNodes {
guard let movement: ChoiceMovement = node.movements.first else {
continue
}
//log.debug("#\(iteration) pick the first: \(node.estimatedDistanceToFood)")
let snakeBodyMovement: SnakeBodyMovement = movement.snakeBodyMovement
pendingMovement = snakeBodyMovement
break
}
return SnakeBot4(
iteration: self.iteration + 1,
plannedMovement: pendingMovement
)
}
private func printEstimatedDistancesToFood(nodes: ChoiceNodeArray) {
var dict = [Int: ChoiceNodeArray]()
for node: ChoiceNode in nodes {
let key: Int = Int(node.estimatedDistanceToFood)
var value: ChoiceNodeArray = dict[key] ?? ChoiceNodeArray()
value.append(node)
dict[key] = value
}
typealias KeyValuePair = (Int, ChoiceNodeArray)
var keyValuePairs = [KeyValuePair]()
for (key, value) in dict {
let keyValuePair: KeyValuePair = (key, value)
keyValuePairs.append(keyValuePair)
}
keyValuePairs.sort { $0.0 < $1.0 }
var pairs = [String]()
for (index, tupple) in keyValuePairs.enumerated() {
guard index < 5 else {
break
}
let distance: Int = tupple.0
let numberOfChoices: Int = tupple.1.count
let pair = "\(distance)=\(numberOfChoices)"
pairs.append(pair)
}
let prettyPairsJoined: String = pairs.joined(separator: " ")
log.debug("#\(iteration) estimated distance to food: \(prettyPairsJoined)")
}
}
extension SnakeBot4: CustomDebugStringConvertible {
public var debugDescription: String {
return "SnakeBot4 \(iteration)"
}
}
fileprivate enum ChoiceMovement {
case moveForward
case moveCCW
case moveCW
var snakeBodyMovement: SnakeBodyMovement {
switch self {
case .moveForward:
return .moveForward
case .moveCCW:
return .moveCCW
case .moveCW:
return .moveCW
}
}
var shorthand: String {
switch self {
case .moveForward:
return "-"
case .moveCCW:
return "<"
case .moveCW:
return ">"
}
}
}
fileprivate protocol ChoiceNode {
var movements: [ChoiceMovement] { get }
var collisionWithWall: Bool { get }
var collisionWithSelf: Bool { get }
var estimatedDistanceToFood: UInt32 { get }
var nodeCount: UInt { get }
func assignMovements_inner(movements: [ChoiceMovement])
func allNodes() -> [ChoiceNode]
func leafNodes() -> [LeafChoiceNode]
func recursiveFlag_collisionWithWall()
func recursiveFlag_collisionWithSelf()
func getNode0() -> ChoiceNode?
func getNode1() -> ChoiceNode?
func getNode2() -> ChoiceNode?
func setEstimatedDistanceToFood(distance: UInt32)
}
extension ChoiceNode {
// IDEA: Move to a RootChoiceNode which hold all the root functions
fileprivate func assignMovements() {
self.assignMovements_inner(movements: [])
}
}
fileprivate class LeafChoiceNode: ChoiceNode {
var movements: [ChoiceMovement] = []
var collisionWithWall: Bool = false
var collisionWithSelf: Bool = false
var estimatedDistanceToFood: UInt32 = UInt32.max
var nodeCount: UInt {
return 1
}
func assignMovements_inner(movements: [ChoiceMovement]) {
self.movements = movements
}
func allNodes() -> [ChoiceNode] {
return [self]
}
func leafNodes() -> [LeafChoiceNode] {
return [self]
}
func recursiveFlag_collisionWithWall() {
collisionWithWall = true
}
func recursiveFlag_collisionWithSelf() {
collisionWithSelf = true
}
func getNode0() -> ChoiceNode? {
return nil
}
func getNode1() -> ChoiceNode? {
return nil
}
func getNode2() -> ChoiceNode? {
return nil
}
func setEstimatedDistanceToFood(distance: UInt32) {
estimatedDistanceToFood = distance
}
}
fileprivate class ParentChoiceNode: ChoiceNode {
let node0: ChoiceNode
let node1: ChoiceNode
let node2: ChoiceNode
var movements: [ChoiceMovement] = []
var collisionWithWall: Bool = false
var collisionWithSelf: Bool = false
var estimatedDistanceToFood: UInt32 = UInt32.max
init(node0: ChoiceNode, node1: ChoiceNode, node2: ChoiceNode) {
self.node0 = node0
self.node1 = node1
self.node2 = node2
}
var nodeCount: UInt {
let count0: UInt = node0.nodeCount
let count1: UInt = node1.nodeCount
let count2: UInt = node2.nodeCount
return 1 + count0 + count1 + count2
}
func assignMovements_inner(movements: [ChoiceMovement]) {
self.movements = movements
node0.assignMovements_inner(movements: movements + [.moveCW])
node1.assignMovements_inner(movements: movements + [.moveForward])
node2.assignMovements_inner(movements: movements + [.moveCCW])
}
func allNodes() -> [ChoiceNode] {
let nodes0: [ChoiceNode] = node0.allNodes()
let nodes1: [ChoiceNode] = node1.allNodes()
let nodes2: [ChoiceNode] = node2.allNodes()
let nodes: [ChoiceNode] = [self] + nodes0 + nodes1 + nodes2
return nodes
}
func leafNodes() -> [LeafChoiceNode] {
let leafNodes0: [LeafChoiceNode] = node0.leafNodes()
let leafNodes1: [LeafChoiceNode] = node1.leafNodes()
let leafNodes2: [LeafChoiceNode] = node2.leafNodes()
let leafNodes: [LeafChoiceNode] = leafNodes0 + leafNodes1 + leafNodes2
return leafNodes
}
func recursiveFlag_collisionWithWall() {
collisionWithWall = true
node0.recursiveFlag_collisionWithWall()
node1.recursiveFlag_collisionWithWall()
node2.recursiveFlag_collisionWithWall()
}
func recursiveFlag_collisionWithSelf() {
collisionWithSelf = true
node0.recursiveFlag_collisionWithSelf()
node1.recursiveFlag_collisionWithSelf()
node2.recursiveFlag_collisionWithSelf()
}
func getNode0() -> ChoiceNode? {
return node0
}
func getNode1() -> ChoiceNode? {
return node1
}
func getNode2() -> ChoiceNode? {
return node2
}
func setEstimatedDistanceToFood(distance: UInt32) {
estimatedDistanceToFood = distance
}
}
extension ParentChoiceNode {
// IDEA: Move to a RootChoiceNode which hold all the root functions
fileprivate static func create(depth: UInt) -> ChoiceNode {
guard depth >= 2 else {
let ci = LeafChoiceNode()
return ci
}
let node0: ChoiceNode = create(depth: depth - 1)
let node1: ChoiceNode = create(depth: depth - 1)
let node2: ChoiceNode = create(depth: depth - 1)
let ci = ParentChoiceNode(node0: node0, node1: node1, node2: node2)
return ci
}
}
/// Detect collision with wall
///
/// Originally this code looped over all the leaf-nodes and checked for collision with walls. This was slow.
///
/// Now paths that share the same beginning, are being ruled out. So much fewer paths needs to be checked.
/// This code starts with the top-level node, then moves on to the next nested level.
extension ChoiceNode {
fileprivate func checkCollisionWithWall(level_emptyPositionSet: Set<IntVec2>, snakeHead: SnakeHead) {
getNode0()?.checkCollisionWithWall_inner(level_emptyPositionSet: level_emptyPositionSet, movement: .moveCW, snakeHead: snakeHead)
getNode1()?.checkCollisionWithWall_inner(level_emptyPositionSet: level_emptyPositionSet, movement: .moveForward, snakeHead: snakeHead)
getNode2()?.checkCollisionWithWall_inner(level_emptyPositionSet: level_emptyPositionSet, movement: .moveCCW, snakeHead: snakeHead)
}
private func checkCollisionWithWall_inner(level_emptyPositionSet: Set<IntVec2>, movement: ChoiceMovement, snakeHead: SnakeHead) {
let newSnakeHead: SnakeHead = snakeHead.simulateTick(movement: movement.snakeBodyMovement)
guard level_emptyPositionSet.contains(newSnakeHead.position) else {
recursiveFlag_collisionWithWall()
return
}
getNode0()?.checkCollisionWithWall_inner(level_emptyPositionSet: level_emptyPositionSet, movement: .moveCW, snakeHead: newSnakeHead)
getNode1()?.checkCollisionWithWall_inner(level_emptyPositionSet: level_emptyPositionSet, movement: .moveForward, snakeHead: newSnakeHead)
getNode2()?.checkCollisionWithWall_inner(level_emptyPositionSet: level_emptyPositionSet, movement: .moveCCW, snakeHead: newSnakeHead)
}
}
/// Detect collision with self, is the snake eating itself
///
/// Originally this code looped over all the leaf-nodes and checked for collision with the snake itself. This was slow.
///
/// Now paths that share the same beginning, are being ruled out. So much fewer paths needs to be checked.
/// This code starts with the top-level node, then moves on to the next nested level.
///
/// IDEA: The `SnakeBody.isEatingItself` is slow. And it gets called many times.
/// Internally it does conversions from Array to Set.
/// Optimizing this may speed things up.
extension ChoiceNode {
fileprivate func checkCollisionWithSelf(snakeBody: SnakeBody, foodPosition: IntVec2?) {
getNode0()?.checkCollisionWithSelf_inner(movement: .moveCW, snakeBody: snakeBody, foodPosition: foodPosition)
getNode1()?.checkCollisionWithSelf_inner(movement: .moveForward, snakeBody: snakeBody, foodPosition: foodPosition)
getNode2()?.checkCollisionWithSelf_inner(movement: .moveCCW, snakeBody: snakeBody, foodPosition: foodPosition)
}
private func checkCollisionWithSelf_inner(movement: ChoiceMovement, snakeBody: SnakeBody, foodPosition: IntVec2?) {
guard !self.collisionWithWall else {
return
}
var body: SnakeBody = snakeBody
var hasFood: Bool = (foodPosition != nil)
let snakeBodyMovement: SnakeBodyMovement = movement.snakeBodyMovement
let head: SnakeHead = body.head.simulateTick(movement: snakeBodyMovement)
let act: SnakeBodyAct
if hasFood && head.position == foodPosition {
act = .eat
hasFood = false
// IDEA: The exact same computation is being done later for every leaf node, when determining the distance to the food.
// This is inefficient of time doing it on the leaf nodes. It's much fewer computations doing recursively.
// recursively set distance to food, to save computations.
} else {
act = .doNothing
}
body = body.stateForTick(movement: snakeBodyMovement, act: act)
if body.isEatingItself {
recursiveFlag_collisionWithSelf()
return
}
let newFoodPosition: IntVec2?
if hasFood {
newFoodPosition = foodPosition
} else {
newFoodPosition = nil
}
// IDEA: in case the food hasn't been eaten. Then the distance to food map have to be recomputed.
// This is painfully slow. The entire snake body simulation have to be done all over.
// Maybe a faster solution is to store the snake body in the leaf nodes,
// so the distance to the food can be computed.
// Maybe compute the distance to food map, here in this function. So that there is no allocations of variable sizes.
getNode0()?.checkCollisionWithSelf_inner(movement: .moveCW, snakeBody: body, foodPosition: newFoodPosition)
getNode1()?.checkCollisionWithSelf_inner(movement: .moveForward, snakeBody: body, foodPosition: newFoodPosition)
getNode2()?.checkCollisionWithSelf_inner(movement: .moveCCW, snakeBody: body, foodPosition: newFoodPosition)
}
}
fileprivate typealias ChoiceNodeArray = [ChoiceNode]
fileprivate class LeafChoiceNodeWithMetaData {
let leafChoiceNode: LeafChoiceNode
let areaSize: UInt
let snakeLength: UInt
init(leafChoiceNode: LeafChoiceNode, areaSize: UInt, snakeLength: UInt) {
self.leafChoiceNode = leafChoiceNode
self.areaSize = areaSize
self.snakeLength = snakeLength
}
}
| true
|
df7e3479c0de43e27f7faa711b6a8f2c5dc386c2
|
Swift
|
mcknight0219/reddity
|
/Services/NetworkActivityInicator.swift
|
UTF-8
| 942
| 2.640625
| 3
|
[] |
no_license
|
//
// NetworkActivityIndicator.swift
// Reddity
//
// Created by Qiang Guo on 2016-07-28.
// Copyright © 2016 Qiang Guo. All rights reserved.
import UIKit
class NetworkActivityIndicator {
private static var activityCount: Int = 0
class func incrementActivityCount () {
self.activityCount = self.activityCount + 1
if self.activityCount > 1 {
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
}
}
class func decreaseActivityCount () {
self.activityCount = self.activityCount - 1
if self.activityCount < 0 { self.activityCount = 0 }
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = ( self.activityCount > 0 )
}
}
}
| true
|
7821f3ba547b6a90be6828366914855dcf10d7a3
|
Swift
|
vgillestad/HuePlay
|
/HuePlay/Sources/ViewController.swift
|
UTF-8
| 5,587
| 2.546875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// HuePlay
//
// Created by Vegard Gillestad on 06/05/2020.
// Copyright © 2020 Tibber. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let minBrightness:Float = 1
let maxBrightness:Float = 254
let minKelvin:Float = 2000
let maxKelvin:Float = 6500
let model:String = "LCT001"
private let brightnessSlider = UISlider()
private let brightnessLabel = UILabel()
private let colorTemperatureBackground = UIView()
private let colorTemperatureSlider = UISlider()
private let colorTemperatureLabel = UILabel()
private var xyColorWheel:ColorWheel!
private let xyLabel = UILabel()
private let xySelectedColor = UIView()
private var currentMode:ColorMode?
private var debounceTimer:Timer?
override func viewDidLoad() {
super.viewDidLoad()
brightnessSlider.minimumValue = minBrightness
brightnessSlider.maximumValue = maxBrightness
brightnessSlider.setValue((minBrightness+maxBrightness/2), animated: false)
brightnessSlider.addTarget(self, action: #selector(didChangeBrightness), for: .valueChanged)
colorTemperatureSlider.minimumValue = minKelvin //* 0.9 //min Kelvin
colorTemperatureSlider.maximumValue = maxKelvin //* 1.1 //max Kelvin
colorTemperatureSlider.setValue(minKelvin, animated: false)
colorTemperatureSlider.addTarget(self, action: #selector(didChangeColorTemperature), for: .valueChanged)
brightnessLabel.frame = CGRect(x: 0, y: 50, width: view.bounds.width, height: 20)
brightnessSlider.frame = CGRect(x: 0, y: brightnessLabel.frame.maxY, width: view.bounds.width, height: 50)
colorTemperatureBackground.frame = CGRect(x: 0, y: brightnessSlider.frame.maxY, width: view.bounds.width, height: 100)
colorTemperatureSlider.frame = colorTemperatureBackground.frame
colorTemperatureLabel.frame = CGRect(x: 5, y: colorTemperatureBackground.frame.minY, width: view.bounds.width - 5, height: 50)
let initialColor = HueUtilities.colorFromXY(CGPoint(x: 0.4263, y: 0.1857), forModel: model)
xyColorWheel = ColorWheel(
frame: CGRect(x: 0, y: colorTemperatureBackground.frame.maxY + 40, width: view.bounds.width, height: view.bounds.width),
color: initialColor
)
xyColorWheel.delegate = self
xySelectedColor.frame = CGRect(x: 0, y: colorTemperatureBackground.frame.maxY + 20, width: 20, height: 20)
xyLabel.frame = CGRect(x: xySelectedColor.frame.maxX + 5, y: xySelectedColor.frame.minY, width: view.bounds.width, height: 20)
view.addSubview(brightnessLabel)
view.addSubview(brightnessSlider)
view.addSubview(colorTemperatureBackground)
view.addSubview(colorTemperatureLabel)
view.addSubview(colorTemperatureSlider)
view.addSubview(xyColorWheel)
view.addSubview(xyLabel)
view.addSubview(xySelectedColor)
hueAndSaturationSelected(initialColor.hsba.hue, saturation: initialColor.hsba.saturation)
didChangeColorTemperature()
didChangeBrightness()
}
@objc func didChangeColorTemperature() {
let kelvin = colorTemperatureSlider.value
colorTemperatureBackground.backgroundColor = UIColor(temperature: CGFloat(kelvin))
colorTemperatureLabel.text = "kelvin: \(Int(kelvin))"
currentMode = .ct(Int(kelvin))
sendToGw()
}
@objc func didChangeBrightness() {
brightnessLabel.text = "bri: \(Int(brightnessSlider.value))"
sendToGw()
}
private func sendToGw() {
guard let currentMode = currentMode else { return }
debounceTimer?.invalidate()
debounceTimer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false, block: { _ in
TibberGW.sendColor(colorMode:currentMode, brightness: Int(self.brightnessSlider.value))
})
}
}
extension ViewController : ColorWheelDelegate {
func hueAndSaturationSelected(_ hue: CGFloat, saturation: CGFloat) {
let color = UIColor(hue: hue, saturation: saturation, brightness: 1, alpha: 1)
// let point = HueUtilities.calculateXY(color, forModel: model)
// xyLabel.text = "xy: [\(point.x.fourDecimals),\(point.y.fourDecimals)]"
xySelectedColor.backgroundColor = color
currentMode = .xy(color)
sendToGw()
}
}
extension CGFloat {
var fourDecimals:CGFloat { return ((self*10000).rounded())/10000 }
}
extension UIColor {
public var hsba: (hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) {
var h: CGFloat = 0
var s: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return (h, s, b, a)
}
public var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
return (r, g, b, a)
}
func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return NSString(format:"#%06x", rgb) as String
}
}
| true
|
0d7633f5d9c9a512254a30aacb30d0155d37cd6c
|
Swift
|
enggrakeshcse/Data-Structure
|
/Single-Linked-List/Linked-List/SinglyLinkedList.swift
|
UTF-8
| 3,518
| 3.765625
| 4
|
[] |
no_license
|
//
// Question1.swift
// Single-Linked-List
//
// Created by Rakesh on 01/08/19.
//
import Foundation
//MARK: - Linked list Node
class SingleNode<T: Equatable> {
var val: T?
var next: SingleNode?
}
class SingleLinkedList<T: Equatable> {
var head = SingleNode<T>()
//MARK: - insertion from end
func insert(value: T) {
if head.val == nil {
self.head.val = value
} else {
var lastNode = self.head
while lastNode.next != nil {
lastNode = lastNode.next!
}
let newNode = SingleNode<T>()
newNode.next = nil
newNode.val = value
lastNode.next = newNode
}
}
//MARK: - print all element
func printAllElemetArray() {
var current: SingleNode! = head
if current.val == nil {
print("There is no element in Linked List ")
} else {
while current.next != nil {
print(current.val ?? "")
current = current.next
}
print(current.val ?? "")
}
}
//MARK: - remove from linkedList
func remove(value: T) {
var current: SingleNode! = head
var previous: SingleNode! = head
if current.val == value{
if head.next == nil {
head.val = nil
} else {
head = head.next!
}
current = head
} else {
while current.val != value && current.next != nil {
previous = current
current = current.next
}
if current.next == nil && current.val != value {
print("There is no Match Elements in LinkedList")
} else if current.next == nil {
previous.next = nil
} else {
previous.next = current.next
}
}
}
//MARK: - implements Question1
//How do you find the middle element of a singly linked list in one pass?
func Solution1() {
var middlenode: SingleNode! = head
var current: SingleNode! = head
var length = 0
while current.next != nil {
length += 1
if length%2 == 0 {
middlenode = middlenode.next
}
current = current.next
}
print("length on linkedlist is \(length + 1)")
if length%2 == 1 {
print("Data in middle \(middlenode.val!) \(middlenode.next!.val!)")
//middlenode = middlenode.next
} else {
print("Data in middle \(middlenode.val!)")
}
}
//MARK: - implements Quetion2
//How do you reverse a linked list?
func Solution2() {
var start = head
var previous: SingleNode<T>? = nil
var current = head
while start.next != nil {
current = start
start = start.next!
current.next = previous
previous = current
head = current
}
current = start
current.next = previous
head = current
}
//MARK: - Question3
// Third element from end
func findThirdNode() {
var start = head
var previous = head
var count = 0
while start.next?.next != nil {
count += 1
previous = start
start = start.next!
}
count == 0 ? print("not possible"):print(previous.val!)
}
}
| true
|
a69e1e73506a4222bfd8e9999717f02d6b57df5f
|
Swift
|
espressif/esp-idf-provisioning-ios
|
/ESPProvision/Security2/SRP/Group.swift
|
UTF-8
| 13,672
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright (C) 2016 Bouke Haarsma
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
/// SRP Group Parameters
///
/// The 1024-, 1536-, and 2048-bit groups are taken from software
/// developed by Tom Wu and Eugene Jhong for the Stanford SRP
/// distribution, and subsequently proven to be prime. The larger primes
/// are taken from [MODP], but generators have been calculated that are
/// primitive roots of N, unlike the generators in [MODP].
///
/// The values of N and g used in this protocol must be agreed upon by
/// the two parties in question. They can be set in advance, or the host
/// can supply them to the client. In the latter case, the host should
/// send the parameters in the first message along with the salt. For
/// maximum security, N should be a safe prime (i.e. a number of the form
/// N = 2q + 1, where q is also prime). Also, g should be a generator
/// modulo N (see [SRP] for details), which means that for any X where 0
/// < X < N, there exists a value x for which g^x % N == X.
///
/// [MODP] Kivinen, T. and M. Kojo, "More Modular Exponentiation
/// (MODP) Diffie-Hellman groups for Internet Key Exchange
/// (IKE)", RFC 3526, May 2003.
///
/// [SRP] T. Wu, "The Secure Remote Password Protocol", In
/// Proceedings of the 1998 Internet Society Symposium on
/// Network and Distributed Systems Security, San Diego, CA,
/// pp. 97-111.
public enum Group {
/// 1024-bits group
case N1024
/// 2048-bits group
case N2048
/// 1536-bits group
case N1536
/// 3072-bits group
case N3072
/// 4096-bits group
case N4096
/// 6144-bits group
case N6144
/// 8192-bits group
case N8192
/// Custom group parameters. See `init(prime:generator:)` for more information.
public struct CustomGroup {
let N: BigUInt
let g: BigUInt
}
/// Custom group parameters. See `init(prime:generator:)` for more information.
case custom(CustomGroup)
/// Create custom group parameters. See the enum's documentation for
/// considerations on good parameters.
/// - Parameters:
/// - prime: hex-encoded prime
/// - generator: hex-encoded generator
/// - Returns: nil if one of the parameters chould not be decoded
public init?(prime: String, generator: String) {
guard let N = BigUInt(prime, radix: 16), let g = BigUInt(generator, radix: 16) else {
return nil
}
self = .custom(CustomGroup(N: N, g: g))
}
var N: BigUInt {
switch self {
case .N1024:
return BigUInt(
"EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C" +
"9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4" +
"8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29" +
"7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" +
"FD5138FE8376435B9FC61D2FC0EB06E3",
radix: 16)!
case .N1536:
return BigUInt(
"9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA961" +
"4B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F843" +
"80B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0B" +
"E3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF5" +
"6EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734A" +
"F7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E" +
"8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB",
radix: 16)!
case .N2048:
return BigUInt(
"AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294" +
"3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D" +
"CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB" +
"D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74" +
"7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A" +
"436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D" +
"5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73" +
"03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" +
"94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" +
"9E4AFF73",
radix: 16)!
case .N3072:
return BigUInt(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" +
"8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" +
"302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" +
"A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" +
"49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" +
"FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" +
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" +
"180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" +
"3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" +
"04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" +
"B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" +
"1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" +
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" +
"E0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",
radix: 16)!
case .N4096:
return BigUInt(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" +
"8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" +
"302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" +
"A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" +
"49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" +
"FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" +
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" +
"180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" +
"3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" +
"04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" +
"B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" +
"1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" +
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" +
"E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" +
"99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" +
"04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" +
"233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" +
"D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" +
"FFFFFFFFFFFFFFFF",
radix: 16)!
case .N6144:
return BigUInt(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" +
"8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" +
"302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" +
"A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" +
"49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" +
"FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" +
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" +
"180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" +
"3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" +
"04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" +
"B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" +
"1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" +
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" +
"E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" +
"99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" +
"04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" +
"233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" +
"D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" +
"36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" +
"AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" +
"DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" +
"2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" +
"F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" +
"BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" +
"CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" +
"B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" +
"387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" +
"6DCC4024FFFFFFFFFFFFFFFF",
radix: 16)!
case .N8192:
return BigUInt(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" +
"8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" +
"302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" +
"A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" +
"49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" +
"FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" +
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" +
"180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" +
"3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" +
"04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" +
"B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" +
"1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" +
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" +
"E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" +
"99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" +
"04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" +
"233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" +
"D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" +
"36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" +
"AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" +
"DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" +
"2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" +
"F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" +
"BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" +
"CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" +
"B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" +
"387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" +
"6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA" +
"3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C" +
"5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" +
"22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886" +
"2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6" +
"6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5" +
"0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268" +
"359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6" +
"FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" +
"60C980DD98EDD3DFFFFFFFFFFFFFFFFF",
radix: 16)!
case .custom(let custom):
return custom.N
}
}
var g: BigUInt {
switch self {
case .N1024:
return BigUInt(2)
case .N1536:
return BigUInt(2)
case .N2048:
return BigUInt(2)
case .N3072:
return BigUInt(5)
case .N4096:
return BigUInt(5)
case .N6144:
return BigUInt(5)
case .N8192:
return BigUInt(19)
case .custom(let custom):
return custom.g
}
}
}
| true
|
646b4e5909dd4c8963307aeaf032aa148e0f2a16
|
Swift
|
davidldphan94/virtually_safe
|
/virtually_safe/Model/UserProfile.swift
|
UTF-8
| 1,768
| 2.703125
| 3
|
[] |
no_license
|
//
// UserProfile.swift
// MovieListApp
//
// Created by David Phan on 4/30/21.
//
import Foundation
import SwiftUI
import Combine
import Firebase
import FirebaseFirestore
struct UserProfile: Encodable, Identifiable {
var id: String = UUID().uuidString
let birthday: String
let email: String
let first_name: String
let last_name: String
let location: String
let profile_pic_url: String
let username: String
var dictionary: [String : Any] {
let data = (try? JSONEncoder().encode(self)) ?? Data()
return (try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)) as? [String: Any] ?? [:]
}
enum CodingKeys: String, CodingKey {
case id
case birthday
case email
case first_name
case last_name
case location
case profile_pic_url
case username
}
}
class UserProfileViewModel :ObservableObject {
var didChange = PassthroughSubject<UserProfileViewModel, Never>()
@Published var profile = [String: String]()
private var db = Firestore.firestore()
func fetchData(userID: String) {
let user = Auth.auth().currentUser!
db.collection("users").document(user.uid).collection("settings")
.document("user_info").getDocument {(document, error) in
if error != nil {
print("No documents")
return
}
if let document = document, document.exists {
let data = document.data()
for (key, value) in data! {
self.profile[key] = (value as AnyObject? as? String) ?? "N/A"
}
}
}
}
}
| true
|
1ba2c92febd01660911f1576686b1c166bc3eb82
|
Swift
|
fubaoyule/HongFu
|
/HongFu/HongFu/Utiltes/RotateScreen.swift
|
UTF-8
| 4,918
| 2.546875
| 3
|
[] |
no_license
|
//
// RotateScreen.swift
// FuTu
//
// Created by Administrator1 on 17/10/16.
// Copyright © 2016 Taylor Tan. All rights reserved.
//
import UIKit
import WebKit
class RotateScreen: NSObject {
class func left() {
tlPrint(message: "left")
currentScreenOritation = UIInterfaceOrientationMask.landscapeLeft
//获取判别变量
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.blockRotation = UIInterfaceOrientationMask.landscapeLeft
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
class func right() {
tlPrint(message: "right")
currentScreenOritation = UIInterfaceOrientationMask.landscapeRight
//获取判别变量
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.blockRotation = UIInterfaceOrientationMask.landscapeRight
let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
class func portrait() {
tlPrint(message: "portraint")
currentScreenOritation = UIInterfaceOrientationMask.portrait
//获取判别变量
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.blockRotation = UIInterfaceOrientationMask.portrait
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
class func all() {
tlPrint(message: "portraint")
currentScreenOritation = UIInterfaceOrientationMask.all
//获取判别变量
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.blockRotation = UIInterfaceOrientationMask.all
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
// class func anyRotation() {
//
// tlPrint(message: "anyRotation")
//
// currentScreenOritation = UIInterfaceOrientationMask.all
// //获取判别变量
// let appDelegate = UIApplication.shared.delegate as! AppDelegate
// appDelegate.blockRotation = UIInterfaceOrientationMask.all
//
// let value = UIInterfaceOrientation.landscapeLeft
//
// UIDevice.current.setValue(value, forKey: "orientation")
//
// }
// //========================
// //Mark:-旋转当前屏幕方向-逆时针(右)
// //========================
// class func right(view: UIView){
// tlPrint(message: "[rotateScreenRight]")
// UIApplication.shared.setStatusBarOrientation(.landscapeRight, animated: true)
// //UIApplication.shared.setStatusBarHidden(true, with: .fade)
//
// UIView.beginAnimations(nil, context: nil)
//
// UIApplication.shared.setStatusBarOrientation(UIInterfaceOrientation.landscapeRight, animated: true)
//// let screen = UIScreen.main.bounds
//// view.frame = CGRect(x: -20, y: -20, width: screen.width, height: screen.height)
// view.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI*0.5))
// UIView.commitAnimations()
// }
//
// //========================
// //Mark:-旋转当前屏幕方向-顺时针(左)
// //========================
// class func left(view: UIView){
// tlPrint(message: "[rotateScreenLeft]")
// UIApplication.shared.setStatusBarOrientation(.landscapeLeft, animated: true)
// //UIApplication.shared.setStatusBarHidden(true, with: .slide)
// UIView.beginAnimations(nil, context: nil)
//
// UIApplication.shared.setStatusBarOrientation(UIInterfaceOrientation.landscapeLeft, animated: true)
// let screen = UIScreen.main.bounds
// view.frame = CGRect(x: 0, y: 0, width: screen.width, height: screen.height)
// view.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI*0.5))
// UIView.commitAnimations()
// }
//
// //========================
// //Mark:-恢复当前屏幕方向-竖屏
// //========================
// class func portrait(view: UIView){
// tlPrint(message: "[rotateScreenPortrait]")
// UIApplication.shared.setStatusBarHidden(false , with: .slide)
// UIView.beginAnimations(nil, context: nil)
//
// UIApplication.shared.setStatusBarOrientation(.portrait, animated: true)
//
// view.frame = CGRect(x: 0, y: 0, width: view.frame.width , height: view.frame.height - 20)
// view.transform = CGAffineTransform(rotationAngle: CGFloat(0))
// UIView.commitAnimations()
// }
}
| true
|
3f2400d6cf00fc6476e111ad354b4365f44f730c
|
Swift
|
TemnosHD/datapersistence
|
/DataPersistence/Item.swift
|
UTF-8
| 640
| 2.765625
| 3
|
[] |
no_license
|
//
// Item.swift
// DataPersistence
//
// Created by Arthur Heimbrecht on 13.6.16.
// Copyright © 2016 iOS Dev Kurs Universität Heidelberg. All rights reserved.
//
import Foundation
import CoreData
class Item : NSManagedObject {
@NSManaged var list: List
@NSManaged var name: String
@NSManaged var created: NSDate
@NSManaged var importance: Int
@NSManaged var done: Bool
// Called when the object is created, i.e. inserted in a context
override func awakeFromInsert() {
super.awakeFromInsert()
// Set attribute value as initial value, bypassing undo mechanics and such
self.setPrimitiveValue(NSDate(), forKey: "created")
}
}
| true
|
a91dc39f4028d9cf0462d285faaa59052be1aa91
|
Swift
|
viggurt/BetSquad
|
/LoggedInViewController.swift
|
UTF-8
| 3,913
| 2.546875
| 3
|
[] |
no_license
|
//
// LoggedInViewController.swift
// BetSquad
//
// Created by Viktor on 15/04/16.
// Copyright © 2016 viggurt. All rights reserved.
//
import UIKit
import Firebase
class LoggedInViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//Referensen till Firebase URL
let ref = Firebase(url: "https://betsquad.firebaseio.com/Groups")
//MARK: Variabler
var createdGroups: [CreateGroup] = []
var chosenGroup = 0
var choosenGroup: CreateGroup?
@IBOutlet var groupTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
//Visar vägen i Firebase
ref.childByAppendingPath(ref.authData.uid).observeEventType(.Value, withBlock: {
snapshot in
var groups: [CreateGroup] = []
for item in snapshot.children {
let group = CreateGroup(snapshot: item as! FDataSnapshot)
groups.append(group)
}
self.createdGroups = groups
self.groupTableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: TableView egenskaper
//Funktion för hur många rader denna TableView ska ha
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return createdGroups.count
}
//Funktion för vilken cell du väljer
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
chosenGroup = indexPath.row
}
//Funktion för vad som ska stå i cellen
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("GroupCell", forIndexPath: indexPath) as! CustomCell
cell.groupName.text = "\(createdGroups[indexPath.row].name)"
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
//Funktion för att swipea en cell åt höger så kan man deleta den gruppen
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
if let tv = groupTableView
{
let ref = createdGroups.removeAtIndex(indexPath.row)
ref.ref?.removeValue()
tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
}
//Förbereder för att visa de placerade spelen i gruppen
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "GroupView" {
let VC = segue.destinationViewController as? ViewController
if let cell = sender as? UITableViewCell {
if let indexPath = groupTableView.indexPathForCell(cell){
VC?.choosenGroup = createdGroups[indexPath.row]
}
}
}
}
//MARK: Actions
//Funktion för att logga ut
@IBAction func logOutButtonWasPressed(sender: UIBarButtonItem) {
let VC = self.storyboard?.instantiateViewControllerWithIdentifier("logInScreen") as! LogInViewController!
self.presentViewController(VC,animated: true, completion: nil)
}
}
| true
|
8d4b456e4a3594021aca42d83fe857ec6dcfe19f
|
Swift
|
LukMorye/BestFitMe
|
/BestFitMe/Extension/Date.swift
|
UTF-8
| 1,023
| 3.03125
| 3
|
[] |
no_license
|
//
// Date.swift
// DemoKit
//
// Created by Титов Валентин on 24.05.17.
// Copyright © 2017 TrueNorth. All rights reserved.
//
import UIKit
private let kDateFormat = "dd.MM.yyyy, HH:mm"
extension Date {
static let kDay: TimeInterval = 1.0
static let kHoursInDay: TimeInterval = 24.0
static let kMinInHour: TimeInterval = 60.0
static let kSecInMin: TimeInterval = 60.0
static func dateStringFrom(date:Date) -> String {
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = kDateFormat
let dateString = dateFormatter.string(from: date) as String
return "\(dateString)"
}
static func dateStringFrom(timestamp:TimeInterval) -> String {
return dateStringFrom(date: Date.init(timeIntervalSince1970: timestamp))
}
static func wholeNumbersOfDaysSince(timeInterval: TimeInterval) -> Int {
let now: TimeInterval = Date().timeIntervalSince1970
let seconds: TimeInterval = now-timeInterval
return Int(seconds/kSecInMin/kMinInHour/kHoursInDay)
}
}
| true
|
00bf92166ffb0a039442445a7b721a5d1f5c9191
|
Swift
|
brunophilipe/MastodonKit
|
/Sources/MastodonKit/Result.swift
|
UTF-8
| 1,171
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
//
// Result.swift
// MastodonKit
//
// Created by Ornithologist Coder on 6/6/17.
// Copyright © 2017 MastodonKit. All rights reserved.
//
import Foundation
public enum Result<Model> {
/// Success wraps a model and an optional pagination
case success(Model, Pagination?)
/// Failure wraps an ErrorType
case failure(ClientError)
}
public extension Result {
/// Convenience getter for the value.
var value: Model? {
switch self {
case .success(let value, _): return value
case .failure: return nil
}
}
/// Convenience getter for the pagination.
var pagination: Pagination? {
switch self {
case .success(_, let pagination): return pagination
case .failure: return nil
}
}
/// Convenience getter for the error.
var error: ClientError? {
switch self {
case .success: return nil
case .failure(let error): return error
}
}
/// Convenience getter to test whether the result is an error or not.
var isError: Bool {
switch self {
case .success: return false
case .failure: return true
}
}
}
| true
|
681ca5a3ddeaee6d135ce2755d1c0cf8221affef
|
Swift
|
DanielHJA/FileDownloaderQueue
|
/CustomOperations/BaseTableViewCell.swift
|
UTF-8
| 439
| 2.75
| 3
|
[] |
no_license
|
//
// BaseTableViewCell.swift
// CustomOperations
//
// Created by Daniel Hjärtström on 2020-03-13.
// Copyright © 2020 Daniel Hjärtström. All rights reserved.
//
import UIKit
class BaseTableViewCell<T: Decodable>: UITableViewCell {
var object: T!
func configure(_ object: T) {
self.object = object
}
}
extension BaseTableViewCell {
static var identifier: String {
return String(describing: self)
}
}
| true
|
e14732c4b58aa1f81d7d97b6706e90e1915fcd18
|
Swift
|
chrisbudro/GrowlerHour
|
/growlers/UIView+BackgroundShadow.swift
|
UTF-8
| 627
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// UIView+BackgroundShadow.swift
// growlers
//
// Created by Chris Budro on 10/16/15.
// Copyright © 2015 chrisbudro. All rights reserved.
//
import Foundation
extension UIView {
func setBackgroundShadow() {
self.setNeedsLayout()
self.layoutIfNeeded()
let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: 2)
self.layer.shadowPath = shadowPath.CGPath
self.layer.shadowColor = UIColor.darkGrayColor().CGColor
self.layer.shadowOffset = CGSizeMake(0, 1)
self.layer.shadowOpacity = 0.4
self.layer.shadowRadius = 2
self.layer.cornerRadius = 2
}
}
| true
|
64a07b57b23d9e65336bc8dbb6ab31c3ac1ae45a
|
Swift
|
faizadli/SwiftUIBootCamp
|
/SwiftUIBootCamp/Gambar.swift
|
UTF-8
| 577
| 2.921875
| 3
|
[] |
no_license
|
//
// Gambar.swift
// SwiftUIBootCamp
//
// Created by faiz on 21/04/21.
//
import SwiftUI
struct Gambar: View {
var body: some View {
Image("Transparan")
.renderingMode(.template)
.resizable()
.scaledToFit()
.frame(width: 300, height: 300)
.foregroundColor(.red)
//.clipped()
//.cornerRadius(150)
.clipShape(
//Circle()
Ellipse()
)
}
}
struct Gambar_Previews: PreviewProvider {
static var previews: some View {
Gambar()
}
}
| true
|
3c6f572713a3e0694550fc51c376b5cd129d66a2
|
Swift
|
CudB/Set
|
/Set/ViewController.swift
|
UTF-8
| 4,927
| 2.609375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Set
//
// Created by Andy Au on 2018-12-11.
// Copyright © 2018 Stanford University. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// Overrides the default UI colors to match the selected theme when the app is loaded.
override func viewDidLoad() {
newGameButton.layer.cornerRadius = 3.0
addCardsButton.layer.cornerRadius = 3.0
showSetButton.layer.cornerRadius = 3.0
remainingCardsButton.layer.cornerRadius = 3.0
remainingCardsButton.layer.borderWidth = 1.0
remainingCardsButton.layer.borderColor = UIColor.black.cgColor
remainingCardsButton.isEnabled = false
updateViewFromModel()
}
private var game = Set() {
didSet {
updateViewFromModel()
}
}
@IBOutlet weak var newGameButton: UIButton!
@IBOutlet weak var addCardsButton: UIButton!
@IBOutlet weak var showSetButton: UIButton!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var remainingCardsButton: UIButton!
@IBOutlet weak var setCardGridView: SetCardGridView! {
didSet {
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(drawCards))
swipe.direction = .up
setCardGridView.addGestureRecognizer(swipe)
}
}
@IBAction func tapGrid(_ sender: UITapGestureRecognizer) {
setCardGridView.tappedLocation = sender.location(in: setCardGridView)
}
@IBAction func shuffleCards(_ sender: UIRotationGestureRecognizer) {
game.hand.shuffle()
updateViewFromModel()
}
@objc func drawCards() {
game.draw(amount: Set.CardLimits.cardsTakenPerDraw)
}
// Reveals a possible match to the player.
@IBAction func showSetButton(_ sender: UIButton) {
// if let setIndices = game.hand.cards.retrieveSetIndices {
// for index in setIndices {
//// cardButtons[index].layer.borderWidth = 3.0
//// cardButtons[index].layer.borderColor = UIColor.green.cgColor
// }
// //TODO: Penalize player if a set is found.
// } else {
// //TODO: Display a message in the game to let the player know that there are no sets.
// print("No sets present")
// }
}
@IBAction func addCardsButton(_ sender: UIButton) {
game.draw(amount: Set.CardLimits.cardsTakenPerDraw)
// updateViewFromModel()
}
@IBAction func newGameButton(_ sender: UIButton) {
game.startNewGame()
// updateViewFromModel()
}
// @IBAction func touchCard(_ sender: UIButton) {
// if let cardNumber = cardButtons.index(of: sender) {
// game.chooseCard(at: cardNumber)
// updateViewFromModel()
// } else {
// print("Chosen card was not in cardButtons.")
// }
// }
private func updateViewFromModel() {
setCardGridView.cards = game.hand.cards
// for index in cardButtons.indices {
// let button = cardButtons[index]
//
// // Only enable the button if it is needed to represent a drawn card
// if index >= game.hand.cards.count {
// disableCardButton(button: button)
// } else {
// enableCardButton(button: button)
// button.layer.borderColor = UIColor.black.cgColor
// let card = game.hand.cards[index]
// assignCardFace(to: button, from: card)
//
// // Gives selected cards a border.
// for chosenIndex in game.chosenCardIndices {
// if chosenIndex == index {
// if !game.matchMade {
// // Border for selected cards.
// button.layer.borderWidth = 3.0
// button.layer.borderColor = UIColor.blue.cgColor
// } else if !game.successfulMatchMade {
// // Border for unsuccessful match.
// button.layer.borderWidth = 3.0
// button.layer.borderColor = UIColor.red.cgColor
// }
// }
// }
// }
// }
// Update labels with score and card count.
scoreLabel.text = "SCORE: \(game.statistics.score)"
remainingCardsButton.setTitle("\(game.deck.cards.count)", for: UIControl.State.normal)
// Disables addCardsButton if there are not enough cards in the deck.
if game.deck.cards.count < 1 {
addCardsButton.isEnabled = false
addCardsButton.alpha = 0.15
} else {
addCardsButton.isEnabled = true
addCardsButton.alpha = 1
}
}
}
| true
|
4745c752fa76bf40fa5d95a6f2d5fa4c2f809641
|
Swift
|
advantis/HelloForm
|
/HelloForm/ErrorIndicator+ErrorReporting.swift
|
UTF-8
| 214
| 2.53125
| 3
|
[] |
no_license
|
//
// Copyright © 2014 Yuri Kotov
//
import UIKit
extension ErrorIndicator: ErrorReporting {
func setError(error: NSError?) {
backgroundColor = error ? UIColor.redColor() : UIColor.greenColor()
}
}
| true
|
e76cb6ade3c68b32e7ee0c8fe1dd5580858be0c4
|
Swift
|
DimitriSky/AutoExpandingTextView
|
/AutoExpandingTextView/Cell.swift
|
UTF-8
| 813
| 2.546875
| 3
|
[] |
no_license
|
//
// Cell.swift
// AutoExpandingTextView
//
// Created by Dmitry Labetsky on 03/11/16.
// Copyright © 2016 DmiLab. All rights reserved.
//
import UIKit
class Cell: UITableViewCell, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
var onHeightUpdate: (() -> ())?
func textViewDidChange(_ textView: UITextView) {
let size = textView.sizeThatFits(CGSize(width: self.frame.width,
height: CGFloat.greatestFiniteMagnitude))
if size.height < autoExpandingTextViewMinimumHeight {
heightConstraint.constant = autoExpandingTextViewMinimumHeight
} else {
heightConstraint.constant = size.height
}
onHeightUpdate?()
}
}
| true
|
a0ff0096b631b7266a59c4da7babad8ec30fa52e
|
Swift
|
AlynMing/FoodFacts
|
/FoodFacts/NutrientViewViewController.swift
|
UTF-8
| 3,471
| 2.734375
| 3
|
[] |
no_license
|
//
// NutrientViewViewController.swift
// FoodFacts
//
// Created by Sathya Sri Pasham on 11/15/20.
// Copyright © 2020 archit. All rights reserved.
//
import UIKit
import Parse
class NutrientViewViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var favButton: UIButton!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "IngredientTableViewCell", for: indexPath) as! IngredientTableViewCell
// let name = nutrients.ke ys[indexPath]
//let ingridient = nutrients[indexPath.row]["user"]
cell.ingredientName.text = (nutrients[indexPath.row]["nutrientName"] as! String)
let value = nutrients[indexPath.row]["value"] as! Float64
let str1 = "\(value)"
cell.ingredientValue.text = str1
return cell
}
// var nutrients = [String: Float64]()
//var nutrients1 = [NSDictionary]()
var nutrients = [NSDictionary]()
var itemName = String()
var image: UIImage!
var itemObj: PFObject!
@IBOutlet weak var foodName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
print("in the details view controller")
print(nutrients)
print(itemName)
// if (itemObj != nil) {
// foodName.text = itemObj["name"] as! String
// imageView.image = UIImage(itemObj["image"])
// } else {
foodName.text = itemName
imageView.image = image
//}
self.tableView.reloadData()
// Do any additional setup after loading the view.
}
// func getDetails(_ sender: Any) {
// let searchItem = SearchViewController()
// searchItem.itemFeild.text! = itemName
// searchItem.getDetails(sender)
// }
@available(iOS 13.0, *)
@IBAction func onFavoriteButton(_ sender: Any) {
setFavorite(_isFavorited: true)
let fav_item = PFObject(className:"Favorites")
fav_item["name"] = foodName.text!
fav_item["user"] = PFUser.current()!
let imageData = imageView.image!.pngData()!
let file = PFFileObject(data: imageData)
fav_item["image"] = file
fav_item.saveInBackground { (success, error) in
if (success) {
print("saved")
} else {
print("error")
}
}
}
@available(iOS 13.0, *)
func setFavorite(_isFavorited:Bool) {
if (_isFavorited){
favButton.setImage(UIImage(systemName:"heart.fill"), for: UIControl.State.normal)
} else {
favButton.setImage(UIImage(systemName:"heart"), for: UIControl.State.normal)
}
}
/*
// 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
|
8c2ca093e82a85a8e2b68673565fdb7ee3f66acd
|
Swift
|
fellipecaetano/Wolf
|
/Carthage/Checkouts/IBentifiers/Source/Storyboards/Identifiable.swift
|
UTF-8
| 277
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public protocol Identifiable {
associatedtype Identifier
static var identifier: Identifier { get }
}
public extension Identifiable where Self.Identifier == String {
static var identifier: String {
return String(describing: self)
}
}
| true
|
44b0d9452048f68593849cd92e22054dd4b22e91
|
Swift
|
brozelle/Checklists
|
/Checklists/DataModel.swift
|
UTF-8
| 3,444
| 3.203125
| 3
|
[] |
no_license
|
//
// DataModel.swift
// Checklists
//
// Created by Buck Rozelle on 5/15/20.
// Copyright © 2020 buckrozelledotcomLLC. All rights reserved.
//
import Foundation
class DataModel {
var lists = [Checklist]()
//computer property
var indexOfSelectedChecklist: Int {
get {
return UserDefaults.standard.integer(forKey: "ChecklistIndex")
}
set {
UserDefaults.standard.set(newValue,
forKey: "ChecklistIndex")
}
}
init() {
loadChecklists()
registerDefaults()
handleFirstTime()
}
//Sets default values for user defaults
func registerDefaults() {
let dictionary = [ "ChecklistIndex": -1, "FirstTime": true] as [String : Any]
UserDefaults.standard.register(defaults: dictionary)
}
//first time running the app
func handleFirstTime() {
let userDefaults = UserDefaults.standard
let firstTime = userDefaults.bool(forKey: "FirstTime")
if firstTime {
let checklist = Checklist(name: "List")
lists.append(checklist)
indexOfSelectedChecklist = 0
userDefaults.set(false, forKey: "FirstTime")
userDefaults.synchronize()
}
}
//MARK:- Data Saving
//gets the full path to the documents folder
func documentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)
return paths[0]
}
//Uses documentsDirectory to construct the full path to the Checklists.plist file.
func dataFilePath() -> URL {
return documentsDirectory().appendingPathComponent("Checklists.plist")
}
//sorting the checklists
func sortChecklists() {
lists.sort(by: { list1, list2 in
return list1.name.localizedStandardCompare(list2.name) == .orderedAscending
})
}
func saveChecklists() {
//Create an instance of PropertyListEncoder
let encoder = PropertyListEncoder()
//Sets up a block to catch errors.
do {
//try to encode the lists array.
let data = try encoder.encode(lists)
//if the constant was created then write the data to a file.
try data.write(to: dataFilePath(), options: Data.WritingOptions.atomic)
//execute if an error was thrown.
} catch {
//print the error.
print("Error encoding item array: \(error.localizedDescription)")
}
}
func loadChecklists() {
//put the results dataFilePath in a temp constant.
let path = dataFilePath()
//try to load the contents of Checklists.plist into a new data object
if let data = try? Data(contentsOf: path) {
//load the entire array its contents
let decoder = PropertyListDecoder()
do {
//load the saved data back into items
lists = try decoder.decode([Checklist].self, from: data)
//and sorts them
sortChecklists()
} catch {
//if there was an error, print it in the console.
print("Error decoding item array: \(error.localizedDescription)")
}
}
}
}
| true
|
b6f781a5faea891ce14bc83308593ed4e1c46926
|
Swift
|
sfldzh/SRAlbum
|
/Classes/Brightroom/BrightroomEngine/Engine/CoreGraphics+.swift
|
UTF-8
| 6,771
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// Copyright (c) 2021 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import CoreGraphics
import ImageIO
extension CGContext {
@discardableResult
func perform(_ drawing: (CGContext) -> Void) -> CGContext {
drawing(self)
return self
}
static func makeContext(for image: CGImage, size: CGSize? = nil) throws -> CGContext {
var bitmapInfo = image.bitmapInfo
/**
Modifies alpha info in order to solve following issues:
[For creating CGContext]
- A screenshot image taken on iPhone might be DisplayP3 16bpc. This is not supported in CoreGraphics.
https://stackoverflow.com/a/42684334/2753383
[For MTLTexture]
- An image loaded from ImageIO seems to contains something different bitmap-info compared with UIImage(named:)
That causes creating broken MTLTexture, technically texture contains alpha and wrong color format.
I don't know why it happens.
*/
bitmapInfo.remove(.alphaInfoMask)
bitmapInfo.formUnion(.init(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue))
/**
The image from PHImageManager uses `.byteOrder32Little`.
This is not compatible with MTLTexture.
*/
bitmapInfo.remove(.byteOrder32Little)
/**
Ref: https://github.com/guoyingtao/Mantis/issues/12
*/
let outputColorSpace: CGColorSpace
if let colorSpace = image.colorSpace, colorSpace.supportsOutput {
outputColorSpace = colorSpace
} else {
EngineLog.error(.default, "CGImage's color-space does not support output. \(image.colorSpace as Any)")
outputColorSpace = CGColorSpaceCreateDeviceRGB()
}
let width = size.map { Int($0.width) } ?? image.width
let height = size.map { Int($0.height) } ?? image.height
if let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: image.bitsPerComponent,
bytesPerRow: 0,
space: outputColorSpace,
bitmapInfo: bitmapInfo.rawValue
) {
return context
}
return
try CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: 8 * 4 * image.width,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue
).unwrap()
}
fileprivate func detached(_ perform: () -> Void) {
saveGState()
perform()
restoreGState()
}
}
extension CGImage {
var size: CGSize {
return .init(width: width, height: height)
}
func croppedWithColorspace(to cropRect: CGRect) throws -> CGImage {
let cgImage = try autoreleasepool { () -> CGImage? in
let context = try CGContext.makeContext(for: self, size: cropRect.size)
.perform { c in
c.draw(
self,
in: CGRect(
origin: .init(
x: -cropRect.origin.x,
y: -(size.height - cropRect.maxY)
),
size: size
)
)
}
return context.makeImage()
}
return try cgImage.unwrap()
}
func resized(maxPixelSize: CGFloat) throws -> CGImage {
let cgImage = try autoreleasepool { () -> CGImage? in
let targetSize = Geometry.sizeThatAspectFit(
size: size,
maxPixelSize: maxPixelSize
)
let context = try CGContext.makeContext(for: self, size: targetSize)
.perform { c in
c.interpolationQuality = .high
c.draw(self, in: c.boundingBoxOfClipPath)
}
return context.makeImage()
}
return try cgImage.unwrap()
}
enum Flipping {
case vertically
case horizontally
}
func rotated(angle: CGFloat, flipping: Flipping? = nil) throws -> CGImage {
guard angle != 0 else {
return self
}
var rotatedSize: CGSize =
size
.applying(.init(rotationAngle: angle))
rotatedSize.width = abs(rotatedSize.width)
rotatedSize.height = abs(rotatedSize.height)
let cgImage = try autoreleasepool { () -> CGImage? in
let rotatingContext = try CGContext.makeContext(for: self, size: rotatedSize)
.perform { c in
if let flipping = flipping {
switch flipping {
case .vertically:
c.translateBy(x: 0, y: rotatedSize.height)
c.scaleBy(x: 1, y: -1)
case .horizontally:
c.translateBy(x: rotatedSize.width, y: 0)
c.scaleBy(x: -1, y: 1)
}
}
c.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
c.rotate(by: angle)
c.translateBy(
x: -size.width / 2,
y: -size.height / 2
)
c.draw(self, in: .init(origin: .zero, size: self.size))
}
return rotatingContext.makeImage()
}
return try cgImage.unwrap()
}
func oriented(_ orientation: CGImagePropertyOrientation) throws -> CGImage {
let angle: CGFloat
switch orientation {
case .down, .downMirrored:
angle = CGFloat.pi
case .left, .leftMirrored:
angle = CGFloat.pi / 2.0
case .right, .rightMirrored:
angle = CGFloat.pi / -2.0
case .up, .upMirrored:
angle = 0
}
let flipping: Flipping?
switch orientation {
case .upMirrored, .downMirrored:
flipping = .horizontally
case .leftMirrored, .rightMirrored:
flipping = .vertically
case .up, .down, .left, .right:
flipping = nil
}
let result = try rotated(angle: angle, flipping: flipping)
return result
}
func rotated(rotation: EditingCrop.Rotation, flipping: Flipping? = nil)
throws -> CGImage
{
try rotated(angle: -rotation.angle, flipping: flipping)
}
}
| true
|
dfd587e50852700a768f501551cfd72b134a1b78
|
Swift
|
Rudrj2/wire
|
/wire-library/wire-runtime-swift/src/test/swift/JSONStringTests.swift
|
UTF-8
| 1,145
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Copyright © 2020 Square Inc. All rights reserved.
//
import Foundation
import XCTest
@testable import Wire
final class JsonStringTests: XCTestCase {
struct SupportedTypes : Codable, Equatable {
@JSONString
var a: Int64
@JSONString
var b: UInt64
@JSONString
var c: [Int64]
@JSONString
var d: [UInt64]
}
func testSupportedTypes() throws {
let expectedStruct = SupportedTypes(
a: -12,
b: 13,
c: [-14],
d: [15]
)
let expectedJson = """
{\
"a":"-12",\
"b":"13",\
"c":["-14"],\
"d":["15"]\
}
"""
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys // For deterministic output.
let jsonData = try! encoder.encode(expectedStruct)
let actualJson = String(data: jsonData, encoding: .utf8)!
XCTAssertEqual(expectedJson, actualJson)
let actualStruct = try! JSONDecoder().decode(SupportedTypes.self, from: jsonData)
XCTAssertEqual(expectedStruct, actualStruct)
}
}
| true
|
fb61ada884fd48f6c887e32a5446b7a12e7dda94
|
Swift
|
toldom/LightClicker-SwiftGame
|
/GameSelectScene.swift
|
UTF-8
| 4,033
| 2.765625
| 3
|
[] |
no_license
|
//
// GameSelectScene.swift
// LightClicker
//
// Created by Marcus Toldo on 2016-06-15.
// Copyright © 2016 Marcus Toldo. All rights reserved.
//
import Foundation
import SpriteKit
class GameSelectScene: SKScene {
let gameSelectBackground = SKSpriteNode(imageNamed: "gameSelectBackground")
let backButtonOn = SKSpriteNode(imageNamed: "backButton")
let backButtonOff = SKSpriteNode(imageNamed: "backButtonOff")
let classicButtonOn = SKSpriteNode(imageNamed: "classicButton")
let classicButtonOff = SKSpriteNode(imageNamed: "classicButtonOff")
let speedButtonOn = SKSpriteNode(imageNamed: "speedButton")
let speedButtonOff = SKSpriteNode(imageNamed: "speedButtonOff")
override func didMove(to view: SKView) {
gameSelectBackground.anchorPoint = CGPoint(x: 0, y: 0)
backButtonOn.anchorPoint = CGPoint(x: 0, y: 0); backButtonOff.anchorPoint = CGPoint(x: 0, y: 0)
classicButtonOff.anchorPoint = CGPoint(x: 0, y: 0); classicButtonOn.anchorPoint = CGPoint(x: 0, y: 0)
speedButtonOff.anchorPoint = CGPoint(x: 0, y: 0); speedButtonOn.anchorPoint = CGPoint(x: 0, y: 0)
gameSelectBackground.position = CGPoint(x: 0, y: 0); gameSelectBackground.zPosition = 0
backButtonOff.position = CGPoint(x: 0, y: 0); backButtonOn.position = CGPoint(x: 0, y: 0); backButtonOff.zPosition = 1; backButtonOn.zPosition = 1
classicButtonOff.position = CGPoint(x: 50, y: size.height/2-40); classicButtonOn.position = CGPoint(x: 50, y: size.height/2-40); classicButtonOff.zPosition = 1; classicButtonOn.zPosition = 1
speedButtonOff.position = CGPoint(x: size.width/2 + 75, y: size.height/2-40); speedButtonOn.position = CGPoint(x: size.width/2 + 75, y: size.height/2-40); speedButtonOff.zPosition = 1; speedButtonOn.zPosition = 1
addChild(gameSelectBackground)
addChild(backButtonOff)
addChild(classicButtonOff)
addChild(speedButtonOff)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.location(in: self)
if backButtonOff.contains(location) {
addChild(backButtonOn)
backButtonOff.removeFromParent()
}
if classicButtonOff.contains(location) {
addChild(classicButtonOn)
classicButtonOff.removeFromParent()
}
if speedButtonOff.contains(location) {
addChild(speedButtonOn)
speedButtonOff.removeFromParent()
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.location(in: self)
let backToMenu = SKAction.run() {
let menuScene = MainMenu(size: self.size)
self.view?.presentScene(menuScene)
}
let playGame = SKAction.run() {
let gameScene = GameSceneHalves(size: self.size)
self.view?.presentScene(gameScene)
}
let playSpeed = SKAction.run() {
let speedScene = GameSceneSpeed(size: self.size)
self.view?.presentScene(speedScene)
}
if backButtonOn.contains(location) {
addChild(backButtonOff)
backButtonOn.removeFromParent()
run(backToMenu)
}
if classicButtonOn.contains(location) {
addChild(classicButtonOff)
classicButtonOn.removeFromParent()
run(playGame)
}
if speedButtonOn.contains(location) {
addChild(speedButtonOff)
speedButtonOn.removeFromParent()
run(playSpeed)
}
}
}
}
| true
|
909171141f4a4cc5f80aa277715b490cddb348cf
|
Swift
|
parmarvhv/SwiftDelhiMeetup---Chapter24
|
/Demo Project/AppExtension/Code/Helpers/UITextField+Helper.swift
|
UTF-8
| 722
| 2.59375
| 3
|
[] |
no_license
|
//
// UITextField+Helper.swift
// AppExtension
//
// Created by Vaibhav Parmar on 11/12/18.
// Copyright © 2020 Nickelfox. All rights reserved.
//
import UIKit
extension UITextField {
@IBInspectable var placeholderColor: UIColor? {
get {
return self.placeholderColor
}
set {
guard let placeholder = self.placeholder,
let placeholderColor = newValue else { return }
let foregroundAttribute = [NSAttributedString.Key.foregroundColor: placeholderColor]
self.attributedPlaceholder = NSAttributedString(string: placeholder,
attributes: foregroundAttribute)
}
}
}
| true
|
cee0cfaf4238de279fcaaf5c43db6294b27bd53e
|
Swift
|
priyankagaikwad/FlickrImageSearch
|
/FlickrImageSearch/Scenes/FlickrImageSearch/FISWorker.swift
|
UTF-8
| 2,599
| 2.921875
| 3
|
[] |
no_license
|
//
// FISWorker.swift
// FlickrImageSearch
//
// Created by Priyanka Gaikwad on 12/09/21.
//
import Foundation
class FISWorker: NSObject {
// Generate search URL
func getSearchURL(searchText:String, pageCount:Int) -> URL? {
let urlString = "\(FISConstants.apiUrl)&api_key=\(FISConstants.apiKey)&%20format=json&nojsoncallback=1&safe_search=\(pageCount)&text=\(searchText)"
guard let searchURL = URL(string: urlString) else {
debugPrint("Invalid url string", urlString)
return nil
}
return searchURL
}
func request(_ searchText: String, pageNo: Int, completion: @escaping (Result<Photos?>) -> Void) {
guard let requestURL = createSearchRequest(searchText: searchText, pageNo: pageNo) else {
return
}
NetworkManager.shared.request(requestURL) { (result) in
switch result {
case .Success(let responseData):
if let response = self.processResponse(responseData) {
return response.stat.uppercased().contains("OK") ? completion(.Success(response.photos)) : completion(.Failure(FISConstants.errorMessage))
} else {
return completion(.Failure(FISConstants.errorMessage))
}
case .Failure(let message):
return completion(.Failure(message))
case .Error(let error):
return completion(.Failure(error))
}
}
}
func processResponse(_ data: Data) -> FlickrPhotos? {
do {
let responseModel = try JSONDecoder().decode(FlickrPhotos.self, from: data)
return responseModel
} catch(let error) {
print(error)
return nil
}
}
func createSearchRequest(searchText:String, pageNo:Int, bodyParams: [String: Any]? = nil) -> NSMutableURLRequest? {
guard let urlString = getSearchURL(searchText: searchText, pageCount: pageNo) else { return nil }
let request = NSMutableURLRequest(url: urlString)
do {
if let bodyParams = bodyParams {
let data = try JSONSerialization.data(withJSONObject: bodyParams, options: .prettyPrinted)
request.httpBody = data
}
} catch(let error) {
print("Invalid Request", error)
return nil
}
request.httpMethod = HttpMethod.get.value
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
return request
}
}
| true
|
96eede54329b25fda84bfe250a0ef0cc0a210990
|
Swift
|
chronicqazxc/FeedbackNoRx
|
/FeedbackTests/FeedbackTests.swift
|
UTF-8
| 2,134
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
//
// FeedbackTests.swift
// FeedbackTests
//
// Created by YuHan Hsiao on 2021/09/20.
//
import XCTest
@testable import Feedback
enum State {
case idle
case loading
case loaded(Int)
case error(Error)
}
enum Event {
case onAppear
case increase
case loaded(Int)
}
class FeedbackTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testDynamic() throws {
let dynamic = Dynamic<String>("")
dynamic.bind { newValue in
XCTAssertNotEqual(newValue, "124")
XCTAssertEqual(newValue, "123")
}
dynamic.value = "123"
}
var loadedValue: Int = 0
func testSystem() {
let exp = XCTestExpectation()
let system = System(initial: (State.idle, Event.onAppear),
reduce: reduce,
feedbacks: feedbackWith)
system.state.bindAndFire { newState in
if case let .loaded(newValue) = newState {
exp.fulfill()
XCTAssertEqual(1, newValue)
}
}
system.event.value = .increase
wait(for: [exp], timeout: 3.0)
}
func feedbackWith(input: Event) -> Feedback<State, Event> {
Feedback<State, Event> { state, callback in
if case .increase = input {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.loadedValue += 1
return callback(Event.loaded(self.loadedValue))
}
}
return callback(input)
}
}
func reduce(state: State, event: Event) -> State {
switch event {
case .loaded(let value):
return .loaded(value)
default:
break
}
return state
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.