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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b6bbbd466390c31aae56203e390840bf66bdf984
|
Swift
|
Mbusihlatshwayo/Flight-Tracker-Network
|
/Flight Tracker Network/App/Controllers/Search/SearchCriteriaViewController.swift
|
UTF-8
| 1,121
| 2.671875
| 3
|
[] |
no_license
|
//
// SearchCriteriaViewController.swift
// Flight Tracker Network
//
// Created by Mbusi Hlatshwayo on 9/7/20.
// Copyright © 2020 Mbusi Hlatshwayo. All rights reserved.
//
import UIKit
class SearchCriteriaViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.navigationItem.title = "Search"
self.tabBarController?.navigationItem.rightBarButtonItem = nil
}
func presentSearchViewController(title: String) {
let vc = SearchViewController()
vc.title = title
self.tabBarController?.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func searchByAirline(_ sender: Any) {
presentSearchViewController(title: "Airlines")
}
@IBAction func searchByDepartureAirport(_ sender: Any) {
presentSearchViewController(title: "Airports")
}
@IBAction func searchByArrivalAirport(_ sender: Any) {
presentSearchViewController(title: "Airports")
}
}
| true
|
8c6c6c47aec592988c96c4c85c61a81e7ee3f88b
|
Swift
|
Yagnik13/ImageSlider
|
/ImageSlider/DataModel.swift
|
UTF-8
| 1,204
| 3.140625
| 3
|
[] |
no_license
|
//
// DataModel.swift
// ImageSlider
//
// Created by Yagnik Suthar on 25/01/17.
// Copyright © 2017 Yagnik Suthar. All rights reserved.
//
import UIKit
class DataModel: NSObject {
let images: [String] = ["img01","img02","img03","img04"]
func index(for currentImage: String) -> Int {
let index = images.index(of: currentImage)
return index!
}
func next(for currentImage: String) -> String {
var index = self.index(for: currentImage)
if index >= images.count - 1 {
index = images.count - 1
}else {
index = index + 1
}
let currentImage = images[index]
return currentImage
}
func previous(for currentImage: String) -> String {
var index = self.index(for: currentImage)
if index <= 0 {
index = 0
}else {
index = index - 1
}
let currentImage = images[index]
return currentImage
}
func setSliderValue(for currentImage: String) -> Int{
let total = images.count
var index = images.index(of: currentImage)
if currSlider == index
{
}
return 1
}
}
| true
|
c11163e79d63624ed18225b9774164e86d19e9f0
|
Swift
|
moonbuck/MoonKit
|
/CommonSource/Sequences/Zip.swift
|
UTF-8
| 2,971
| 3.375
| 3
|
[] |
no_license
|
//
// Zip.swift
// Essentia
//
// Created by Jason Cardwell on 11/18/17.
// Copyright © 2017 Moondeer Studios. All rights reserved.
//
// The content in this file is a modification of the file 'Zip.swift' from the standard
// library modified to zip three elements instead of two.
//
import Foundation
@inlinable
public func zip<S1, S2, S3>(_ seq1: S1, _ seq2: S2, _ seq3: S3) -> Zip3Sequence<S1, S2, S3>
where S1:Sequence, S2:Sequence, S3:Sequence
{
return Zip3Sequence(seq1, seq2, seq3)
}
/// An iterator for `Zip3Sequence`.
@frozen
public struct Zip3Iterator<Iterator1, Iterator2, Iterator3> : IteratorProtocol
where Iterator1:IteratorProtocol, Iterator2:IteratorProtocol, Iterator3:IteratorProtocol
{
/// The type of element returned by `next()`.
public typealias Element = (Iterator1.Element, Iterator2.Element, Iterator3.Element)
/// Creates an instance around a trio of underlying iterators.
@inlinable
internal init(_ iterator1: Iterator1, _ iterator2: Iterator2, _ iterator3: Iterator3) {
(_baseStream1, _baseStream2, _baseStream3) = (iterator1, iterator2, iterator3)
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable
public mutating func next() -> Element? {
if _reachedEnd {
return nil
}
guard let element1 = _baseStream1.next(),
let element2 = _baseStream2.next(),
let element3 = _baseStream3.next()
else
{
_reachedEnd = true
return nil
}
return (element1, element2, element3)
}
@usableFromInline
internal var _baseStream1: Iterator1
@usableFromInline
internal var _baseStream2: Iterator2
@usableFromInline
internal var _baseStream3: Iterator3
@usableFromInline
internal var _reachedEnd: Bool = false
}
@frozen
public struct Zip3Sequence<Sequence1:Sequence, Sequence2:Sequence, Sequence3:Sequence> : Sequence {
/// A type whose instances can produce the elements of this
/// sequence, in order.
public typealias Iterator = Zip3Iterator<Sequence1.Iterator,
Sequence2.Iterator,
Sequence3.Iterator>
/// Creates an instance that makes tuples of elements from `sequence1`, `sequence2` and
/// `sequence3`.
@inlinable
public
init(_ sequence1: Sequence1, _ sequence2: Sequence2, _ sequence3: Sequence3) {
(_sequence1, _sequence2, _sequence3) = (sequence1, sequence2, sequence3)
}
/// Returns an iterator over the elements of this sequence.
@inlinable
public func makeIterator() -> Iterator {
return Iterator(
_sequence1.makeIterator(),
_sequence2.makeIterator(),
_sequence3.makeIterator())
}
@usableFromInline
internal let _sequence1: Sequence1
@usableFromInline
internal let _sequence2: Sequence2
@usableFromInline
internal let _sequence3: Sequence3
}
| true
|
5e16d35e20f66898d163b9f927859b00346d1209
|
Swift
|
pereirinhaped/SwiftCalculator
|
/RetroCalculator/CalcVC.swift
|
UTF-8
| 2,988
| 2.65625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// RetroCalculator
//
// Created by Pedro Pereirinha on 17/08/16.
// Copyright © 2016 EpicDory. All rights reserved.
//
import UIKit
import AVFoundation
class CalcVC: UIViewController {
// MARK: IBOutlets
//Counter
@IBOutlet weak var counterLbl: UILabel!
// Numpad:
@IBOutlet weak var nineBtn: UIButton!
@IBOutlet weak var eightBtn: UIButton!
@IBOutlet weak var sevenBtn: UIButton!
@IBOutlet weak var sixBtn: UIButton!
@IBOutlet weak var fiveBtn: UIButton!
@IBOutlet weak var fourBtn: UIButton!
@IBOutlet weak var threeBtn: UIButton!
@IBOutlet weak var twoBtn: UIButton!
@IBOutlet weak var oneBtn: UIButton!
@IBOutlet weak var zeroBtn: UIButton!
// Operators:
@IBOutlet weak var divideBtn: UIButton!
@IBOutlet weak var multiplyBtn: UIButton!
@IBOutlet weak var subBtn: UIButton!
@IBOutlet weak var addBtn: UIButton!
@IBOutlet weak var equalBtn: UIButton!
// Initialize calculator instance
var calc = Calculator()
var btnSound: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
let beepSound = Bundle.main.path(forResource: "btn", ofType: "wav")
let beepSoundUrl = URL(fileURLWithPath: beepSound!)
do {
try btnSound = AVAudioPlayer(contentsOf: beepSoundUrl)
btnSound.prepareToPlay()
} catch let err as NSError {
print(err.description)
}
}
// MARK: @IBActions
@IBAction func onNumberPress(_ sender: UIButton) {
playSound()
updateCounterValue(sender: sender)
}
@IBAction func onOperationPress(_ sender: UIButton) {
playSound()
updateCalcValues(sender: sender)
}
@IBAction func onClearPressed(_ sender: AnyObject) {
playSound()
resetCalc()
}
// MARK: Functions
func playSound() {
if !btnSound.isPlaying {
btnSound.play()
}
}
func updateCounterValue(sender: UIButton) {
calc.counterText = String(sender.tag)
counterLbl.text = calc.counterText
}
func updateCurrentOperation(sender: UIButton) -> CalcOperations? {
switch sender.tag {
case 91:
return .divide
case 92:
return .multiply
case 93:
return .subtract
case 94:
return .add
case 99:
return .equal
default:
return nil
}
}
func updateCalcValues(sender: UIButton) {
let nextOp = updateCurrentOperation(sender: sender)
func performOp() {
calc.inputValue = Double(calc.counterText)
calc.currentValue = calc.returnOperation()
counterLbl.text = String(calc.currentValue!)
calc.resetCounterText()
}
if nextOp != .equal {
if calc.currentValue == nil {
calc.currentOp = nextOp
calc.currentValue = Double(calc.counterText)
counterLbl.text = "0"
calc.resetCounterText()
} else {
if calc.counterText.characters.count != 0 {
performOp()
calc.currentOp = nextOp
} else {
calc.currentOp = nextOp
calc.resetCounterText()
}
}
} else {
if calc.counterText.characters.count != 0 {
performOp()
}
}
}
func resetCalc() {
calc.resetCalc()
counterLbl.text = "0"
}
}
| true
|
85c901659c39b2acdfd861769772e388dc9696f6
|
Swift
|
damouse/AnyFunction
|
/AnyFunctionTests/AcceptanceTests.swift
|
UTF-8
| 1,786
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// ClosureTests.swift
// Deferred
//
// Created by damouse on 5/18/16.
// Copyright © 2016 I. All rights reserved.
//
import XCTest
@testable import AnyFunction
class ClosureSuccessTests: XCTestCase {
func testVoidVoid() {
let c = Closure.wrapOne { }
let ret = try! c.call([])
XCTAssert(ret.count == 0)
}
func testStringVoid() {
let t: (String) -> () = { (a: String) -> () in }
let c = Closure.wrapOne(t)
let ret = try! c.call(["A"])
XCTAssert(ret.count == 0)
}
func testReturn() {
let c = Closure.wrapOne { (a: String) in a }
let ret = try! c.call(["Test"])
XCTAssert(ret.count == 1)
XCTAssert(ret[0] as! String == "Test")
}
// More than one param
func testMultipleParams() {
let c = Closure.wrapTwo { (a: String, b: Int) in b }
let ret = try! c.call(["Test", 1])
XCTAssert(ret.count == 1)
XCTAssert(ret[0] as! Int == 1)
}
}
class ClosureFailureTests: XCTestCase {
// Too many arguments
func testBadNumParamsVoid() {
let c = Closure.wrapOne({ })
do {
try c.call([1])
XCTFail()
} catch {}
}
// too few arguments
func testBadNumParamsOne() {
let c = Closure.wrapOne{ (a: Int) in a }
do {
try c.call([])
XCTFail()
} catch {}
}
// This is already tested in Conversion tests, so more of a sanity check that the throws work correctly
func testBadType() {
let c = Closure.wrapOne({ (a: Int) in })
do {
try c.call(["Not an Int"])
XCTFail()
} catch {}
}
}
| true
|
0dbdc6244c46c25c8c3ddccd232ee3fd77529b13
|
Swift
|
IHsuanLu/RainyShinyWeatherApp
|
/rainyshiny/CurrentWeather.swift
|
UTF-8
| 4,354
| 3.53125
| 4
|
[] |
no_license
|
//
// CurrentWeather.swift
// rainyshiny
//
// Created by 呂易軒 on 2017/9/19.
// Copyright © 2017年 呂易軒. All rights reserved.
//
// stores all of the variables that will keep track of our weather data
import UIKit
import Alamofire // this is how you use the pods grabbed from cocoapods
// if there is an error, then press shift+command+K and then S+C+b
class CurrentWeather {
private var _cityName: String!
private var _date: String!
private var _weatherType: String!
private var _currentTemperature: Double!
// private var _highestTemp: Double!
// private var _lowestTemp: Double! 晚點再用
var cityName:String {
if _cityName == nil{
_cityName = ""
// if there is no value, at least it won't crash(有些經緯度沒有對應國家)
// 不是每次都用NewValue, 要看狀況
}
return _cityName
}
var date:String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long //option + clip可以看這是什麼
dateFormatter.timeStyle = .none
// by default it returns a time stamp as well
let currentDate = dateFormatter.string(from: Date())
//可以看成把剛剛設定的用String呈現
self._date = "Today, \(currentDate)"
return _date
}
var weatherType:String{
if _weatherType == nil {
_weatherType = ""
}
return _weatherType
}
var currentTemperature:Double{
if _currentTemperature == nil {
_currentTemperature = 0.0
}
return _currentTemperature
}
func downloadWeatherDetails(completed: @escaping DownloadComplete) {
// Alamofire download
// unwrapped, 我們要確保他一定有值
let currentWeatherURL = URL(string: CURRENT_WEATHER_URL)!
// get request .responseJSON 是設定server回傳的資料型態
// 不用completionhandler, 因為已經有設定(completed: DownloadComplete)
// 'response in' 是回傳指令
// conclusion: every request has response; every response has result
Alamofire.request(currentWeatherURL).responseJSON{ response in
let result = response.result //result是boolean
// 到此以前,確定JSON是可以被成功下載下來的
// 接下來就是要抓出JSON裡面我們所需要的部分
// 把 result.value 轉型成 Dictionary<String, AnyObject> 的型態
if let dictionary = result.value as? Dictionary<String, AnyObject>{
// look for the key in the dictionary that we want
if let name = dictionary["name"] as? String{
self._cityName = name.capitalized //確定大寫
print(self._cityName)
}
if let weather = dictionary["weather"] as? [Dictionary<String, AnyObject>]{
// 0 stands for the first value in the array(1st dictionary)
if let weathertype = weather[0]["main"] as? String{
self._weatherType = weathertype.capitalized
print(self._weatherType)
}
}
if let main = dictionary["main"] as? Dictionary<String, AnyObject> {
if let currenttemperature = main["temp"] as? Double {
let kelvinToCelsiusPre = currenttemperature - 273.15
let kelvinToCelsius = Double(round(10 * kelvinToCelsiusPre/10))
self._currentTemperature = kelvinToCelsius
print(self._currentTemperature)
}
}
}
completed() // URL裡面的東西下載完之後,func complete 即停止
}
}
}
| true
|
2f71d791e3d550e89d3317b9ca3ebb172ea6163a
|
Swift
|
taesan220/BestTestCollection_iOS
|
/BestTestCollection/ViewControllers/CategoryViewController.swift
|
UTF-8
| 3,350
| 2.640625
| 3
|
[] |
no_license
|
//
// CategoryViewController.swift
// BestTestCollection
//
// Created by Taesan Kim on 2021/03/17.
//
import UIKit
class CategoryViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//MARK: - init
func initializationPageInfo(navigationTitle title: String, subCategoryKey subKey: String) {
self.navigationTitle = title
self.subCategoryKey = subKey
}
//MARK: - Global Veriable
@IBOutlet weak var subCategoryTableView: UITableView!
var navigationTitle: String!
var subCategoryKey: String!
let cellReuseIdentifier = "subCell"
var navigationBarTitle: String!
var listModel: ListModel!
//var arrSubCategory: [ListModel]!
//MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = navigationBarTitle
self.subCategoryTableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
print("Sub category key = \(subCategoryKey ?? "nil")")
print("Identifier title = \(subCategoryKey ?? "nil")")
self.navigationItem.title = self.navigationTitle //상단 타이틀 변경
}
func setSubCategoryData(title: String, listModel: ListModel) {
self.navigationBarTitle = title
self.listModel = listModel
}
//MARK: - TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// guard let identifierKey: [Dictionary<String, String>] = arrSubCategory[VIEWCONTROLLERS] as? [Dictionary<String, String>] else {
// return 0
// }
return listModel.viewControllers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.subCategoryTableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier)! as UITableViewCell
// guard let identifierKey: [Dictionary<String, String>] = arrSubCategory[VIEWCONTROLLERS] as? [Dictionary<String, String>] else {
// return cell
// }
let index = indexPath.row
// let viewControllerInfo: Dictionary<String, String> = identifierKey[index]
let name = self.listModel.viewControllers[index].subViewControllerName
//subViewControllerName: "Custom Button", subViewControllerIdentifier: "custombuttonVC")
let text = String(index + 1) +
". " + name
cell.textLabel?.text = text
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboarName:String = listModel.storyboardName
let identifier:String = listModel.viewControllers[indexPath.row].subViewControllerIdentifier
print("storyboard name = \(storyboarName)")
// let viewControllerInfo:[Dictionary<String, String>] = arrSubCategory[VIEWCONTROLLERS] as! [Dictionary<String, String>]
// let identifier: String = viewControllerInfo[indexPath.row][SUB_VIEWCONTROLLER_ITENTIFIER]!
//
//
let vc = UIStoryboard(name: storyboarName, bundle: nil).instantiateViewController(withIdentifier: identifier)
self.navigationController?.show(vc, sender: self)
}
}
| true
|
3dedb364a512b02a2e9ce4ac087b3e321413c718
|
Swift
|
mmpub/StarLanes
|
/Sources/ConsoleFrontEnd/ConsoleFrontEnd+Persist.swift
|
UTF-8
| 1,013
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
//
// ConsoleFrontEnd+Persist.swift
//
// Copyright © 2018 Michael McMahon. All rights reserved worldwide.
// http://github.com/mmpub/starlanes
//
import Foundation
/// File is stored in users home directory.
private let fileURL = URL(fileURLWithPath: NSString(string: "~/.starlanes").expandingTildeInPath)
/// Front end delegate to store and retrieve a persisted game series.
/// The blob of data is never interpreted by the delegate.
extension ConsoleFrontEnd: FrontEndPersist {
/// Delegation to retrieve a previously persisted game/series.
/// - parameter completionHandler: The delegate calls this with the blob of data used to persist the game/series.
func retrievePersistedSession(completionHandler: (Data?) -> Void) {
completionHandler(try? Data(contentsOf: fileURL))
}
/// Delegation to store a game/series.
/// - parameter data: Blob of data containing the game/series.
func persistSession(data: Data) {
try? data.write(to: fileURL, options: .atomic)
}
}
| true
|
150556363d374fbe31a0b3d5e00aaf7676a3ed50
|
Swift
|
WalaaMarmash/Macbook-all
|
/ToGo/Transporter/Transporter/Controller/Transporter/Home Page Screen/TabBarControllerViewController.swift
|
UTF-8
| 1,623
| 2.65625
| 3
|
[] |
no_license
|
//
// TabBarControllerViewController.swift
// ToGo
//
// Created by Fratello Software Group on 5/16/18.
// Copyright © 2018 yara. All rights reserved.
//
import UIKit
import ReachabilitySwift
class TabBarControllerViewController: UITabBarController {
// Internet Connection
let reachability = Reachability()!
override func viewDidLoad() {
super.viewDidLoad()
// Check internet connection
//when Reachable
reachability.whenReachable = { reachability in
DispatchQueue.main.async {
// self.dismiss(animated: true, completion: nil)
}
}
// When UnReachable
self.reachability.whenUnreachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
DispatchQueue.main.async {
self.performSegue(withIdentifier: "NetworkUnavailable", sender: self)
//
}
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
override func viewWillAppear(_ animated: Bool) {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "NetworkUnavailable"{
_ = segue.destination as?
OfflineViewController
}
}
}
| true
|
2a18551799f07270b9ee18cfa638a3312e9519f1
|
Swift
|
Nekitosss/DITranquillityLinter
|
/Source/DITranquillityLinterFramework/Parsing/Sources/Subscript.swift
|
UTF-8
| 5,821
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import SourceKittenFramework
/// Describes subscript
final class Subscript: NSObject, Annotated, Definition, Codable, ProtobufBridgable {
typealias ProtoStructure = Protobuf_Subscript
var toProtoMessage: Subscript.ProtoStructure {
var res = ProtoStructure()
res.parameters = self.parameters.map({ $0.toProtoMessage })
res.returnTypeName = self.returnTypeName.toProtoMessage
res.returnType = .init(value: self.returnType?.toProtoMessage)
res.readAccess = self.readAccess
res.writeAccess = self.writeAccess
res.annotations = self.annotations.mapValues({ $0.toProtoMessage })
res.definedInType = .init(value: self.definedInType?.toProtoMessage)
res.definedInTypeName = .init(value: self.definedInTypeName?.toProtoMessage)
res.attributes = self.attributes.mapValues({ $0.toProtoMessage })
res.parserData = .init(value: self.parserData?.toProtoMessage)
return res
}
static func fromProtoMessage(_ message: Subscript.ProtoStructure) -> Subscript {
let res = Subscript(parameters: message.parameters.map({ .fromProtoMessage($0) }),
returnTypeName: .fromProtoMessage(message.returnTypeName),
accessLevel: (AccessLevel.init(value: message.readAccess), AccessLevel.init(value: message.writeAccess)),
attributes: message.attributes.mapValues({ .fromProtoMessage($0) }),
annotations: message.annotations.mapValues({ .fromProtoMessage($0) }),
definedInTypeName: message.definedInTypeName.toValue.flatMap({ .fromProtoMessage($0) }))
res.returnType = message.returnType.toValue.flatMap({ .fromProtoMessage($0) })
res.definedInType = message.definedInType.toValue.flatMap({ .fromProtoMessage($0) })
res.parserData = message.parserData.toValue.flatMap({ .fromProtoMessage($0) })
return res
}
override func isEqual(_ object: Any?) -> Bool {
guard let rhs = object as? Subscript else { return false }
if self.parameters != rhs.parameters { return false }
if self.returnTypeName != rhs.returnTypeName { return false }
if self.readAccess != rhs.readAccess { return false }
if self.writeAccess != rhs.writeAccess { return false }
if self.annotations != rhs.annotations { return false }
if self.definedInTypeName != rhs.definedInTypeName { return false }
if self.attributes != rhs.attributes { return false }
return true
}
/// Method parameters
var parameters: [MethodParameter]
/// Return value type name used in declaration, including generic constraints, i.e. `where T: Equatable`
var returnTypeName: TypeName
/// Actual return value type name if declaration uses typealias, otherwise just a `returnTypeName`
var actualReturnTypeName: TypeName {
return returnTypeName.actualTypeName ?? returnTypeName
}
// sourcery: skipEquality, skipDescription
/// Actual return value type, if known
var returnType: Type?
// sourcery: skipEquality, skipDescription
/// Whether return value type is optional
var isOptionalReturnType: Bool {
return returnTypeName.isOptional
}
// sourcery: skipEquality, skipDescription
/// Whether return value type is implicitly unwrapped optional
var isImplicitlyUnwrappedOptionalReturnType: Bool {
return returnTypeName.isImplicitlyUnwrappedOptional
}
// sourcery: skipEquality, skipDescription
/// Return value type name without attributes and optional type information
var unwrappedReturnTypeName: String {
return returnTypeName.unwrappedTypeName
}
/// Whether method is final
var isFinal: Bool {
return attributes[Attribute.Identifier.final.name] != nil
}
/// Variable read access level, i.e. `internal`, `private`, `fileprivate`, `public`, `open`
let readAccess: String
/// Variable write access, i.e. `internal`, `private`, `fileprivate`, `public`, `open`.
/// For immutable variables this value is empty string
var writeAccess: String
/// Whether variable is mutable or not
var isMutable: Bool {
return writeAccess != AccessLevel.none.rawValue
}
/// Annotations, that were created with // sourcery: annotation1, other = "annotation value", alterantive = 2
let annotations: Annotations
/// Reference to type name where the method is defined,
/// nil if defined outside of any `enum`, `struct`, `class` etc
let definedInTypeName: TypeName?
/// Reference to actual type name where the method is defined if declaration uses typealias, otherwise just a `definedInTypeName`
var actualDefinedInTypeName: TypeName? {
return definedInTypeName?.actualTypeName ?? definedInTypeName
}
// sourcery: skipEquality, skipDescription
/// Reference to actual type where the object is defined,
/// nil if defined outside of any `enum`, `struct`, `class` etc or type is unknown
var definedInType: Type?
/// Method attributes, i.e. `@discardableResult`
let attributes: [String: Attribute]
// Underlying parser data, never to be used by anything else
// sourcery: skipEquality, skipDescription, skipCoding, skipJSExport
/// :nodoc:
var parserData: Structure?
/// :nodoc:
init(parameters: [MethodParameter] = [],
returnTypeName: TypeName,
accessLevel: (read: AccessLevel, write: AccessLevel) = (.internal, .internal),
attributes: [String: Attribute] = [:],
annotations: Annotations = [:],
definedInTypeName: TypeName? = nil) {
self.parameters = parameters
self.returnTypeName = returnTypeName
self.readAccess = accessLevel.read.rawValue
self.writeAccess = accessLevel.write.rawValue
self.attributes = attributes
self.annotations = annotations
self.definedInTypeName = definedInTypeName
}
}
| true
|
889e3e1f813b5e01bd5b1f81b35b917006883381
|
Swift
|
Jsj84/Sho-Remind
|
/Sho Remind/TimeViewController.swift
|
UTF-8
| 4,632
| 2.578125
| 3
|
[] |
no_license
|
//
// TimeViewController.swift
// Sho Remind
//
// Created by Jesse St. John on 12/25/16.
// Copyright © 2016 JNJ Apps. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class TimeViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var reminderName: UILabel!
@IBOutlet weak var reminderDiscription: UITextField!
@IBOutlet weak var timePicker: UIDatePicker!
@IBOutlet weak var tableView: UITableView!
var textEntered:[String] = []
var timeAsString:[String] = []
var textData = [String]()
var timeData = [String]()
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
timePicker.backgroundColor = UIColor.black
timePicker.layer.cornerRadius = 10
timePicker.setValue(UIColor.white, forKeyPath: "textColor")
view.backgroundColor = UIColor.clear
reminderDiscription.delegate = self
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = UIColor.clear
tableView.isOpaque = true
tableView.allowsSelection = false
reminderDiscription.returnKeyType = UIReturnKeyType.done
self.hideKeyboardWhenTappedAround()
self.dismissKeyboard()
if textData.isEmpty == true && timeData.isEmpty == true {
textEntered = defaults.object(forKey: "textData") as? [String] ?? [String]()
timeAsString = defaults.object(forKey: "timeData") as? [String] ?? [String]()
}
else {}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if reminderDiscription.text?.isEmpty == true {
let alert = UIAlertController(title: "Alert", message: "You cannot save this reminder without a discription", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK, Got it!", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
else {
self.view.endEditing(true)
textEntered.append(reminderDiscription.text!)
textData.append(reminderDiscription.text!)
reminderDiscription.text?.removeAll()
let dateOnPicker = timePicker.date //capture the date shown on the picker
let dateFormatter = DateFormatter() //create a date formatter
dateFormatter.dateStyle = DateFormatter.Style.short
dateFormatter.timeStyle = DateFormatter.Style.short
let timeString = dateFormatter.string(from: dateOnPicker)
timeAsString.append(timeString) //ex. prints 3:04 AM as "3:04 AM" and 11:37 PM as "11:37 PM"
timeData.append(timeString)
defaults.set(textData, forKey: "textData")
defaults.set(timeData, forKey: "timeData")
tableView.reloadData()
}
return false
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Saved Reminders"
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return textEntered.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TimeTableViewCell
let row = indexPath.row
cell.myLabel_1.text = textEntered[row]
cell.myLabel_2.text = timeAsString[row]
cell.backgroundColor = UIColor.white
cell.layer.borderWidth = 5
cell.layer.cornerRadius = 15
cell.layer.borderColor = UIColor.black.cgColor
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
textEntered.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
}
}
}
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
| true
|
d2873f367dc61f119d4a4b6e0d86f49be60e03e6
|
Swift
|
wangyongyue/CatWeChat
|
/CatWeChat/AppDelegate.swift
|
UTF-8
| 3,394
| 2.578125
| 3
|
[] |
no_license
|
//
// AppDelegate.swift
// CatWeChat
//
// Created by wangyongyue on 2019/5/1.
// Copyright © 2019 wangyongyue. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let MainVC = Message().getViewController()
let MainNav = UINavigationController(rootViewController:MainVC)
MainNav.tabBarItem.title = "微信"
let ClassVC = Book().getViewController()
let ClassNav = UINavigationController(rootViewController:ClassVC)
ClassNav.tabBarItem.title = "通讯录"
let CartVC = Found().getViewController()
let CartNav = UINavigationController(rootViewController:CartVC)
CartNav.tabBarItem.title = "发现"
let MyVC = Mine().getViewController()
let MyNav = UINavigationController(rootViewController:MyVC)
MyNav.tabBarItem.title = "我的"
let tabBar = UITabBarController()
// 添加工具栏
let items = [MainNav,ClassNav,CartNav,MyNav]
tabBar.viewControllers = items
//tabBar 底部工具栏背景颜色 (以下两个都行)
tabBar.tabBar.barTintColor = UIColor.white
tabBar.tabBar.backgroundColor = UIColor.white
self.window?.rootViewController = tabBar;
self.window?.makeKeyAndVisible();
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| true
|
28cb9d3c258c92f0e98f63e87c539bed7f1fe707
|
Swift
|
vijaydairyf/HanuInnoTechSwift
|
/HITDairyAnalytics/ViewController.swift
|
UTF-8
| 1,683
| 2.71875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// HITDairyAnalytics
//
// Created by Aswini Ramesh on 8/22/17.
// Copyright © 2017 Aswini Ramesh. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var sensorIDTextField: UITextField!
@IBOutlet weak var sensorData: UITextField!
@IBOutlet weak var submitSensorDataButton: UIButton!
@IBAction func submitSensorDataPressed(_ sender: Any) {
if (sensorIDTextField.text == BLANK_STRING) || (sensorData.text == BLANK_STRING) {
let alertController = UIAlertController(title: ALERT_TITLE, message: SUBMIT_BUTTON_PROMPT, preferredStyle: .alert)
let ok = UIAlertAction(title: OK, style: .default, handler: nil)
alertController.addAction(ok)
present(alertController, animated: true) { _ in }
}
else {
let sensorDataObtained = sensorDataModel()
sensorDataObtained.sensorID = sensorIDTextField.text!
sensorDataObtained.sensorData = sensorData.text!.components(separatedBy: ",")
print("\(sensorDataObtained.sensorData)")
PostSensorDataToServer(sensorDataObt: sensorDataObtained)
}
}
func PostSensorDataToServer(sensorDataObt:sensorDataModel)
{
SensorWebServices.sharedSensor.postSensorData();
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
cd540b232e67fe7dd295db637f7e6c97b245823d
|
Swift
|
amrfarouqa/Rajany-iOS
|
/Rajany/SignupVC.swift
|
UTF-8
| 3,814
| 2.703125
| 3
|
[] |
no_license
|
//
// SignupVC.swift
// Rajany
//
// Created by Amr Farouq on 10/29/16.
// Copyright © 2016 Amr Farouq. All rights reserved.
//
import UIKit
import Firebase
class SignupVC: UIViewController, UITextFieldDelegate {
@IBOutlet weak var RePassword: UITextField!
@IBOutlet weak var Password: UITextField!
@IBOutlet weak var Email: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
RePassword.delegate = self
Password.delegate = self
Email.delegate = self
// Do any additional setup after loading the view.
}
@IBAction func btnSignUp(_ sender: AnyObject) {
if Reachability.isConnectedToNetwork() == true
{
let password:String = Password.text!
let confirm_password:String = RePassword.text!
let email:String = Email.text!
if (password.isEqual("") || confirm_password.isEqual("") || email.isEqual("")){
let alert = UIAlertController(title: "Oops!", message:"Please Enter FullName, Email And Password!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
self.present(alert, animated: true){};
} else if ( !password.isEqual(confirm_password) ) {
let alert = UIAlertController(title: "Oops!", message:"Password Doesn't Match!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
self.present(alert, animated: true){};
}else{
FIRAuth.auth()?.createUser(withEmail: email, password: password) { (user, error) in
let alert = UIAlertController(title: "Success!", message:"Login Now!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
let LoginVC = self.storyboard!.instantiateViewController(withIdentifier: "LoginVC")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window!.rootViewController = LoginVC
appDelegate.window!.makeKeyAndVisible()
})
self.present(alert, animated: true){};
}
}
}
else
{
let alert = UIAlertController(title: "Ooops!", message:"Please Connect To The Internet!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
self.present(alert, animated: true){};
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func showMessagePrompt(message :String){
let alert = UIAlertController(title: "Rajany", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
present(alert, animated: true){};
}
/*
// 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: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
14bc24809801d8f579c9a1a35fbfdd592162f7d1
|
Swift
|
Malexaad/ITEA_App
|
/ITEA_Diploma/Controllers/CourseCategoryViewController.swift
|
UTF-8
| 1,972
| 2.53125
| 3
|
[] |
no_license
|
//
// CourseCategoryViewController.swift
// ITEA_Diploma
//
// Created by Alex Marfutin on 5/28/19.
// Copyright © 2019 ITEA. All rights reserved.
//
import UIKit
class CourseCategoryViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var subNavigationBar: UINavigationItem!
@IBOutlet var subCategoryTableView: UITableView!
var subCategories = [Category]()
var courseName : String?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
subCategoryTableView.delegate = self
subCategoryTableView.dataSource = self
subNavigationBar.title = courseName
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return subCategories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SubCategoryCell") as! SubCategoryTableViewCell
cell.courseNameLabel.text = subCategories[indexPath.row].categoryName
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 147
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(withIdentifier: "AboutCourseViewController") as! AboutCourseViewController
vc.about = subCategories[indexPath.row].about
vc.after = subCategories[indexPath.row].afterCourse
vc.more = subCategories[indexPath.row].more
vc.courseName = subCategories[indexPath.row].categoryName
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func backBarButtonTapped(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
}
| true
|
7af715a8e4d28c78b6ea6394ce46f10e578dc4f8
|
Swift
|
deltafhict/SAM
|
/_iOS/SAMKit/Extensions.swift
|
UTF-8
| 1,076
| 2.90625
| 3
|
[] |
no_license
|
//
// Extensions.swift
// SAM
//
// Created by Bas on 01/04/2015.
// Copyright (c) 2015 Bas. All rights reserved.
//
import UIKit
extension UIColor
{
/**
Returns a color object whose RGB values are 0.396, 0.204, and 0.396 and whose alpha value is 1.0.
:returns: The UIColor object.
*/
public class func fontysColor() -> UIColor
{
return UIColor(red: 0.396, green: 0.204, blue: 0.396, alpha: 1)
}
/**
Returns a color object whose RGB values are 0.788, 0.788, and 0.808 and whose alpha value is 1.0.
:returns: The UIColor object.
*/
public class func searchBarColor() -> UIColor
{
return UIColor(red: 0.788, green: 0.788, blue: 0.808, alpha: 1)
}
}
extension NSDate: Equatable, Comparable
{
}
public func ==(lhs: NSDate, rhs: NSDate) -> Bool
{
return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool
{
return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
}
public func >(lhs: NSDate, rhs: NSDate) -> Bool
{
return lhs.timeIntervalSince1970 > rhs.timeIntervalSince1970
}
| true
|
0e26cb70561d4a0600e1dd66887492a8ee693e91
|
Swift
|
Ricks/Strux
|
/Tests/StruxTests/BSTree/BSTreeEquatableTests.swift
|
UTF-8
| 1,871
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// BSTreeEquatableTests.swift
// StruxTests
//
// Created by Richard Clark on 5/3/20.
// Copyright © 2020 Richard Clark. All rights reserved.
// MIT License (see LICENSE file).
//
import Foundation
import XCTest
import Foundation
@testable import Strux
let numTestTrees = 100
class BSTreeEquatableTests: XCTestCase {
func testRandom() {
setSeed(44)
for _ in 0 ..< 10 {
print(seededRandom(in: 1 ..< 5))
}
}
func testEquatable() {
for treeIndex in 0 ..< numTestTrees {
print(treeIndex)
var toInsert1 = [Int]()
for _ in 0 ..< 1000 {
toInsert1.append(seededRandom(in: -10..<10))
}
let toInsert2 = toInsert1.shuffled()
var toRemove1 = [Int]()
for _ in 0 ..< 100 {
toRemove1.append(seededRandom(in: -10..<10))
}
let toRemove2 = toRemove1.shuffled()
let tree1 = BSTree<Int>()
let tree2 = BSTree<Int>()
for i in 0..<toInsert1.count {
tree1.insert(toInsert1[i])
tree2.insert(toInsert2[i])
}
for i in 0..<toRemove1.count {
tree1.remove(toRemove1[i])
tree2.remove(toRemove2[i])
}
validateTree(tree1, "tree1 \(treeIndex)")
validateTree(tree2, "tree1 \(treeIndex)")
if tree1 != tree2 {
XCTFail("tree1 != tree2 for index \(treeIndex)")
print("tree1\n\(tree1)")
print("tree2\n\(tree2)")
}
}
}
func testEquatable2() {
let tree1 = BSTree(0, 9, 6, -3, 2)
let tree2 = BSTree(0, 9, 6, -3, 2, 42)
let tree3 = BSTree(0, 9, 6, -3, 11)
XCTAssertNotEqual(tree1, tree2)
XCTAssertNotEqual(tree1, tree3)
}
}
| true
|
ad7c01c6360ff323063044608179a1ebd6d74fa5
|
Swift
|
tankzeu29/swift-project-dama
|
/GameManager/Sources/GameManager/GameMover.swift
|
UTF-8
| 7,354
| 3.3125
| 3
|
[] |
no_license
|
/* responsible for the second phase in the game
which is each player moving his pieces until the game ends
*/
import CoreGame
import GameExceptions
import GameMessages
public class GameMover : GamePhase
{
private let NEEDED_PIECES_TO_FLY = 3
public init( gameBoard : Board , player1 : Player , player2 : Player)
{
super.init(board : gameBoard, player1 : player1 , player2 : player2)
}
/*
starts the game
*/
public func start()
{
print("Moving phase started!")
let board = getBoard()
var currentPlayer = getFirstPlayer()
var oponent = getSecondPlayer()
board.printBoard()
while(true)
{
let currentState = shouldGameEnd(firstPlayer:currentPlayer, secondPlayer : oponent, board : board)
if( currentState != EndGameState.IN_PROGRESS)
{
printWinner(winner : currentState)
break;
}
board.printBoard()
print(GameInputMessages.ENTER_INPUT_MOVE)
print("\(currentPlayer.getColour()) turn")
if let position = readLine() {
do {
try movePiece(position : position , currentPlayer : currentPlayer ,oponent : oponent , board : board)
let tempPlayer = currentPlayer
currentPlayer = oponent
oponent = tempPlayer
}
catch NineMortisError.runtimeError(let errorMessage) {
print(errorMessage)
}
catch
{
board.printBoard()
print(GameExceptionMessages.UNEXEPECTED_EXCEPTION)
}
}
else
{ board.printBoard()
print(WrongInputMessages.ENTER_INPUT_AGAIN)
}
}
}
/* Moves a piece for a player on the board
@param position - piece to be moved
@param currentPlayer - the player moving the piece
@param oponent - the oponent of the current player
@param board - game board
*/
public func movePiece(position : String , currentPlayer : Player , oponent : Player , board : Board) throws
{
let canCurrentPlayerFily = canPlayerFly(player : currentPlayer)
try MovementValidator.validateMovement(position : position , board : board , currentPlayer : currentPlayer , oponent : oponent , canFly : canCurrentPlayerFily)
let startPosition = try PositionParser.getPositionFromString(position : position.substring(to:2) , board : board)
board.removeAtPosition(point : startPosition)
try board.setSinglePosition(positionCordinates : position.substring(from:2) , currentPlayer :currentPlayer , oponent : oponent )
currentPlayer.removePiece(position : startPosition)
}
/* Checks if player can Fly
@param - player to check if he can move
@return true if he can fly , else false
*/
private func canPlayerFly(player : Player) -> Bool
{
return player.getTotalPieces() == NEEDED_PIECES_TO_FLY
}
/*
* Check if the game should end by verifying if a player is blocked or has 2 pieces
@param firstPlayer - first player of the game
@param secondPlayer - second player of the game
@param board - game board
@return game state
*/
private func shouldGameEnd(firstPlayer : Player , secondPlayer : Player , board : Board) -> EndGameState
{
let firstEnd = canMovePieces(currentPlayer : firstPlayer , board : board)
let secondEnd = canMovePieces(currentPlayer : secondPlayer , board : board)
if(!firstEnd)
{
return EndGameState.PLAYER2_WINNER
}
else if(!secondEnd)
{
return EndGameState.PLAYER1_WINNER
}
else
{
return EndGameState.IN_PROGRESS
}
}
/* Checks if player can move his pieces
@param currentPlayer - player to check if he can move
@board - game board
@return true if an move any of his pieces to adjacent location, else false
*/
private func canMovePieces(currentPlayer : Player , board : Board) -> Bool
{
if(currentPlayer.getTotalPieces() <= 2)
{
return false
}
var canCurrentPlayerMove = false
let currentPlayerPieces = currentPlayer.getPieces()
for piece in currentPlayerPieces
{
let offset = BoardOffsetFinder.getOffset(position : piece, board : board)
let xOffset = offset.xAnswer
let yOffset = offset.yAnswer
let isMovable = canPieceMove( position : piece , xOffset : xOffset , yOffset : yOffset , board : board)
if(isMovable)
{
canCurrentPlayerMove = true
break;
}
}
return canCurrentPlayerMove
}
/* Checks if piece can move to any of the directions - top, bottom ,left, right
by given offset for the cordinates
@position - position to check if it can move
@xOffset - axis offset to move
@yOffset - ordinate offset to move
@board - game board
@return true if the piece is not blocked , else false
*/
private func canPieceMove(position : BoardPosition ,xOffset : Int ,yOffset : Int ,board : Board) -> Bool
{
let startX = position.getX()
let startY = position.getY()
let topPosition = BoardPosition(xCordinate : startX + xOffset ,yCordinate : startY)
let bottomPosition = BoardPosition(xCordinate : startX + xOffset ,yCordinate : startY)
let leftPosition = BoardPosition(xCordinate : startX ,yCordinate : startY - yOffset)
let rightPosition = BoardPosition(xCordinate : startX ,yCordinate : startY + yOffset)
let canMove = board.isPositionEmpty(position : topPosition) ||
board.isPositionEmpty(position : bottomPosition) ||
board.isPositionEmpty(position : leftPosition) ||
board.isPositionEmpty(position : rightPosition)
return canMove
}
/* Prints the winner of the game
@param winner - the state of the game moving phase
*/
public func printWinner(winner : EndGameState)
{
if (winner == EndGameState.PLAYER1_WINNER)
{
print(GameResultMessages.PLAYER1_WON)
}
else if (winner == EndGameState.PLAYER2_WINNER)
{
print(GameResultMessages.PLAYER2_WON)
}
else
{
print(GameResultMessages.UNDETERMINED_WINNER)
}
}
}
| true
|
4cd95e6433eb7f9ec512d5c03eae4e0cfa965281
|
Swift
|
Vaporcasts/ProgrammaticUICustomCollectionView
|
/ProgrammaticUICustomCollectionView/CustomCollectionView/Models/CatList.swift
|
UTF-8
| 332
| 2.734375
| 3
|
[] |
no_license
|
//
// CatList.swift
// ProgrammaticUICustomCollectionView
//
// Created by Stephen Bodnar on 7/5/18.
// Copyright © 2018 Stephen Bodnar. All rights reserved.
//
import Foundation
class CatList {
var breed: String
var cats: [Cat]
init(breed: String, cats: [Cat]) {
self.breed = breed
self.cats = cats
}
}
| true
|
82b1a148ed0517c89e964e9c5d6ee36125a044ae
|
Swift
|
tim-nnd/Diatur-MC1
|
/Diatur-MC1/TaskDetailViewController.swift
|
UTF-8
| 9,803
| 2.515625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Diatur-MC1
//
// Created by Daffa Satria on 08/04/21.
//
import UIKit
class TaskDetailViewController: UIViewController {
@IBOutlet weak var nameTask: UILabel!
@IBOutlet weak var priorityLabel: UILabel!
@IBOutlet weak var pirorityImage: UIImageView!
@IBOutlet weak var dateTask: UILabel!
@IBOutlet weak var notesTask: UILabel!
@IBOutlet weak var startBtn: UIButton!
@IBOutlet weak var stopwatch_Counter: UILabel!
@IBOutlet weak var breakBtn: UIButton!
@IBOutlet weak var finishBtn: UIButton!
@IBOutlet weak var workBtn: UIButton!
@IBOutlet weak var frameTimer: UIImageView!
@IBOutlet weak var timerTitle: UILabel!
@IBOutlet weak var breakLabel: UILabel!
var activeTask: Task?
@IBOutlet weak var timer_Counter: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
nameTask.text = activeTask?.name
switch activeTask?.priority {
case 0:
pirorityImage.tintColor = #colorLiteral(red: 0.9255061746, green: 0.3098220527, blue: 0.2627460957, alpha: 1)
priorityLabel.text = "High Priority"
case 1:
pirorityImage.tintColor = #colorLiteral(red: 0.976410687, green: 0.8706294894, blue: 0.3489934802, alpha: 1)
priorityLabel.text = "Medium Priority"
case 2:
pirorityImage.tintColor = #colorLiteral(red: 0.6469622254, green: 0.7765128613, blue: 0.694031775, alpha: 1)
priorityLabel.text = "Low Priority"
default:
return
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.long
dateFormatter.dateFormat = "dd-MM-yyyy"
dateTask.text = dateFormatter.string(from: activeTask?.date ?? Date())
notesTask.text = activeTask?.notes
// Do any additional setup after loading the view.
}
@IBAction func startBtnOnTapped(_ sender: UIButton) {
// Hiding a StartBtn, Showing stopwatch_Counter on startBtn Click
ShowStopwatch()
HideStartBtn()
timerUpOn()
ShowBreakBtn()
ShowFinishBtn()
self.navigationItem.setHidesBackButton(true, animated:true)
}
@IBAction func breakBtnOnTapped(_ sender: UIButton) {
ShowWorkBtn()
ShowTimer()
timerUpOn()
HideBreakBtn()
breakLabel.isHidden = false
isBreakTimerActive = true
}
@IBAction func finishBtnOnTapped(_ sender: UIButton) {
//confirmation finish
let alert = UIAlertController (title: "Finish Task Confirmation", message: "are you sure you want to finish current task?", preferredStyle: .alert)
//finish Timer
alert.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: {(_)in
//result: show time used
}))
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: {(_)in
self.timerUpFinish()
self.HideFinishBtn()
self.HideTimer()
if let nav = self.navigationController{
nav.popViewController(animated: true)
}
self.activeTask?.isCompleted = true
}))
self.present(alert, animated: true, completion: nil)
}
@IBAction func workBtnOnTapped(_ sender: UIButton) {
ShowBreakBtn()
timerDownReset()
HideWorkBtn()
breakLabel.isHidden = true
timer_Counter.isHidden = true
}
func ShowStopwatch (){
// Showing stopwatch Label, Frame, & Title
if (stopwatch_Counter.isHidden == true && frameTimer.isHidden == true && timerTitle.isHidden == true){
stopwatch_Counter.isHidden = false
frameTimer.isHidden = false
timerTitle.isHidden = false
self.timerUpOn()
}
}
func ShowTimer()
{
//timer_Counter.isHidden.toggle()
// showing countdown timer counter
if timer_Counter.isHidden == true {
timer_Counter.isHidden = false
}
}
func HideTimer() {
// hide countdown timer counter
if timer_Counter.isHidden == false {
timer_Counter.isHidden = true
breakLabel.isHidden = true
}
}
func HideStartBtn(){
// hiding StartBtn
if (startBtn.isHidden == false){
startBtn.isHidden = true
}
}
func ShowBreakBtn(){
// showing breakBtn
if (breakBtn.isHidden == true){
breakBtn.isHidden = false
}
}
func HideBreakBtn(){
// hide breakBtn
if (breakBtn.isHidden == false){
breakBtn.isHidden = true
}
}
func ShowWorkBtn(){
// showing workBtn
if (workBtn.isHidden == true){
workBtn.isHidden = false
}
}
func HideWorkBtn(){
// hideWorkBtn
if (workBtn.isHidden == false) {
workBtn.isHidden = true
}
}
func ShowFinishBtn(){
// show finishBtn
if (finishBtn.isHidden == true){
finishBtn.isHidden = false
}
}
func HideFinishBtn() {
// hide finishBtn
if (finishBtn.isHidden == false){
finishBtn.isHidden = true
}
}
// STOPWATCH & TIMER
// [counting up timer]
var mainTimer: Timer = Timer()
var timeCounter: Int = 0
var isStopwatchActive:Bool = false
// var breakTimeRemaining = 301
var breakTimeRemaining = (Setting.breakMinute*60)+1
var isBreakTimerActive = false
// var breakTimer: Timer = Timer()
func timerUpFinish() {
if (isStopwatchActive)
{
isStopwatchActive = false
mainTimer.invalidate()
HideBreakBtn()
HideWorkBtn()
}
}
func timerUpOn(){
if (isStopwatchActive == false)
{
isStopwatchActive = true
mainTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerCounter), userInfo: nil, repeats: true)
}
}
@objc func timerCounter() -> Void
{
timeCounter = timeCounter + 1
let time = secondsToHoursMinutesSeconds(seconds: timeCounter)
let counterTimeString = makeTimeString(hours: time.0, minutes: time.1, seconds: time.2)
stopwatch_Counter.text = counterTimeString
if isBreakTimerActive {
if breakTimeRemaining > 0{
breakTimeRemaining -= 1
}
let timer = secondToMinutesSeconds(seconds: breakTimeRemaining)
let timerString = maketimerString(minutes: timer.0, seconds: timer.1)
timer_Counter.text = timerString
}
}
func secondsToHoursMinutesSeconds(seconds: Int) -> (Int, Int, Int)
{
return ((seconds / 3600), ((seconds % 3600)/60),((seconds % 3600) % 60))
}
func makeTimeString (hours: Int, minutes: Int, seconds: Int) -> String{
var counterTimeString = ""
counterTimeString += String(format: "%02d", hours)
counterTimeString += " : "
counterTimeString += String(format: "%02d", minutes)
counterTimeString += " : "
counterTimeString += String(format: "%02d", seconds)
return counterTimeString
}
// Timer Break
// Countdown timer
//
func timerDownReset()
{
if isBreakTimerActive == true{
// breakTimeRemaining = 301
breakTimeRemaining = (Setting.breakMinute*60)+1
HideTimer()
}
}
func secondToMinutesSeconds (seconds : Int) -> (Int, Int) {
(((seconds % 3600)/60),((seconds % 3600) % 60))
}
func maketimerString (minutes: Int, seconds: Int) -> String {
var timerString = ""
timerString += String (format: "%02d", minutes)
timerString += String (" : ")
timerString += String (format: "%02d", seconds)
return timerString
}
func timerDownFinish()
{
if isBreakTimerActive == true{
isBreakTimerActive = false
mainTimer.invalidate()
}
}
/*func timerDownOn()
{
if(timerStatus == false)
{
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector (downCounter), userInfo: nil, repeats: true)
timerStatus = true
}
}
*/
/* @objc func downCounter() -> Void
{
if timeRemaining > 0{
timeRemaining -= 1
}
let timer = secondToMinutesSeconds(seconds: timeRemaining)
let timerString = maketimerString(minutes: timer.0, seconds: timer.1)
timer_Counter.text = timerString
}*/
/*
func LabelChange(){
dateTask.text = "8 April 2021"
notesTask.text = "Ini contoh cobain data dummy, belom pake data asli yang dari new task, INI TEST GANTI DOANG"
}
*/
/*
// 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
|
e9a7fa59628536e9e9e0453c070e1f3d68df6d29
|
Swift
|
taijased/base-playground-swift
|
/15 Кортежи.playground/Contents.swift
|
UTF-8
| 564
| 4
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
let one = 1
let two = 2
let three = 3
(one, two, three)
let boy = (5, "Sergey")
boy.0
boy.1
let (first, second, third) = (1, 2, 3)
first
second
let greenPencil = (color: "green", length: 20, weight: 4)
greenPencil.length
let (greenColor, greenLength, greenWeight) = greenPencil
let agesAndNames = ["Misha": 29, "Kostya": 90, "Mira": 30]
var age = 0
var name = ""
for (nameInD, ageInD) in agesAndNames {
if age < ageInD {
age = ageInD
name = nameInD
}
}
age
name
| true
|
b4ec2c1aed93969ab0eb531330e394a7567dbbf9
|
Swift
|
jacky0207/SwiftSportApp
|
/SportApp/LoginViewController.swift
|
UTF-8
| 4,585
| 2.65625
| 3
|
[] |
no_license
|
//
// LoginViewController.swift
// SportApp
//
// Created by 17200113 on 16/11/2018.
// Copyright © 2018 17200113. All rights reserved.
//
import UIKit
//import FirebaseAuth
import Firebase
class LoginViewController: UIViewController {
@IBOutlet weak var email: UITextField!
@IBOutlet weak var password: UITextField!
var db: Firestore!
@IBAction func loginButtonClicked(_ sender: Any) {
// Firebase login
Auth.auth().signIn(withEmail: email.text!, password: password.text!) { (user, error) in
if let error = error {
let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
return
}
if let user = user?.user {
print("userId: \(user.uid)")
print("userDisplayName: \(user.displayName)")
print("userImage: \(user.photoURL)")
// Retrieve user information
let docRef = self.db.collection("account").document(user.uid)
var name : String = ""
// var gender : String = ""
// var age : Int = 0
docRef.getDocument { (document, error) in
if let document = document, document.exists {
// let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
// print("Document data: \(dataDescription)")
let data = document.data();
// Store data in variable
// userDetail = dataDescription.json
name = data!["name"]! as! String
// gender = data!["gender"]! as! String
// age = data!["age"]! as! Int
// Further detail
UserDefaults.standard.set(name, forKey: "name")
// UserDefaults.standard.set(gender, forKey: "gender")
// UserDefaults.standard.set(age, forKey: "age")
// Debug
print("name: \(name)")
// print("gender: \(gender)")
// print("age: \(age)")
} else {
print("Document does not exist")
}
}
// Login detail
UserDefaults.standard.set(user.uid, forKey: "userId")
UserDefaults.standard.set(user.displayName, forKey: "userDisplayName")
UserDefaults.standard.set(user.photoURL, forKey: "userImage")
self.navigationController?.popViewController(animated: true)
}
// let alertController = UIAlertController(title: "Login", message: "Successfully", preferredStyle: .alert)
// alertController.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
// self.present(alertController, animated: true, completion: nil)
//print("asd")
let homeView = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! UITabBarController
//print("asd2")
self.present(homeView, animated: true, completion: nil)
//print("as3")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// [START setup]
let settings = FirestoreSettings()
Firestore.firestore().settings = settings
// [END setup]
db = Firestore.firestore()
}
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.
}
*/
}
| true
|
2b0ea76e25caac0b5c354be1fabd1db608aeb094
|
Swift
|
laurentiurogean/FlickrClient
|
/FlickrClientTests/MockedRepository.swift
|
UTF-8
| 1,107
| 2.609375
| 3
|
[] |
no_license
|
//
// MockedRepository.swift
// FlickrClientTests
//
// Created by Laurentiu Rogean on 09/02/2021.
//
@testable import FlickrClient
class MockedRepository: PhotosRepository {
func searchPhotos(tags: String, page: Int, completion: @escaping (Result<PhotosAPIResponse?, AppError>) -> Void) {
let photo = Photo(id: "12345",
owner: "John",
secret: "xx",
server: "xx",
farm: 12,
title: "Test",
isPublic: 1,
isFriend: 1,
isFamily: 1,
imageUrl: "url",
searchString: "string")
let photos = Photos(page: 1, pages: 3, total: "3", photo: [photo])
let response = PhotosAPIResponse(photos: photos)
completion(.success(response))
}
func getSizes(photoId: String, completion: @escaping (Result<SizesAPIResponse?, AppError>) -> Void) {
completion(.failure(AppError(code: 0, message: "Test")))
}
}
| true
|
b69235b218c032c1f0f41708df77f6c5fe440474
|
Swift
|
iabudiab/gdg-devfestka-2015-swift
|
/Swift Intro.playground/Pages/Functions & Closures.xcplaygroundpage/Contents.swift
|
UTF-8
| 2,915
| 3.953125
| 4
|
[
"MIT"
] |
permissive
|
//: [Previous](@previous)
func hello() {
print("Hello Swift!")
}
func foo(x: Int) {
print("int parameter")
}
func foo(x: Float) {
print("float parameter")
}
func foo(x: String) -> Bool {
return x.characters.count > 3
}
func multiplyNumber(number: Int, with: Int) -> Int {
return number * with
}
multiplyNumber(4, with: 10)
func multiplyNumber(num x: Int, by y: Int) -> Int {
return x * y
}
multiplyNumber(num: 4, by: 10)
func read(fileAtPath path: String,
offset: Int,
length: Int) {}
read(fileAtPath: "path", offset: 10, length: 1024)
func createFileAtPath(path: String,
overwriteIfExists: Bool) {}
createFileAtPath("path", overwriteIfExists: false)
func getImageInfoAtPath(path: String) -> (String,Int,Int) {
return ("png", 1920, 1080)
}
var tuple = getImageInfoAtPath("path")
print("Image \(tuple.0, tuple.1, tuple.2)")
let (_, w, h) = getImageInfoAtPath("path")
print("Image \(w, h)")
func anotherGetImageInfoAtPath(path: String) -> (type: String, width: Int, height: Int) {
return ("png", 1920, 1080)
}
let imageInfo = anotherGetImageInfoAtPath("path")
print("Image \(imageInfo.type, imageInfo.width, imageInfo.height)")
func greetAndCount(var name: String, inout count: Int) {
name += ", Hello!"
count++
}
let name = "Swift"
var count = 0
greetAndCount(name, count: &count)
print("Count \(count)")
let sayHello = {
print("Hello")
}
let sayHi: () -> () = {
print("Hi")
}
sayHello()
sayHi()
let adder = { (x: Int, y: Int) in
x + y
}
adder(5, 7)
func multiplyBy2(x: Int) -> Int { return x * 2 }
let doubler = multiplyBy2
func transform(x: Int, function: (Int) -> Int) -> Int {
return function(x)
}
transform(3, function: doubler)
transform(3, function: { (x: Int) -> Int in
return x * 5
})
transform(3, function: { (x) -> Int in
return x * 5
})
transform(3, function: { x -> Int in
return x * 5
})
transform(3, function: { x in
return x * 5
})
transform(3, function: { x in
x * 5
})
transform(3, function: { $0 * 5 })
transform(3) { $0 * 5 }
let languages = ["Java": 4, "JavaScript": 3, "Swift": 1,
"C++": 4, "Objective-C": 2]
languages.map({ (key, value) -> String in
return key
}).filter({ (language) -> Bool in
return language.characters.count > 4
}).forEach({ (language) -> () in
print(language)
})
languages.map { key, value in
key
}.filter { language in
language.characters.count > 4
}.forEach { language in
print(language)
}
languages.map{ $0.0 }
.filter{ $0.characters.count > 4 }
.forEach { print($0) }
func add(x: Int, y: Int) -> Int {
return x + y
}
add(5, y: 7)
func addCurry(x: Int) -> (Int) -> Int {
func add(y: Int) -> Int {
return x + y
}
return add
}
addCurry(5)(7)
func addCurry(x: Int)(y: Int) -> Int {
return x + y
}
addCurry(5)(y: 7)
func partial(function:(Int,Int)->Int, x:Int) -> (Int)->Int {
func inner(y: Int) -> Int {
return function(x, y)
}
return inner
}
partial(add, x: 5)(7)
//: [Next](@next)
| true
|
7de96f13796c9b2c81cf8fb4e15a080f3dbcd135
|
Swift
|
pmanuelli/ios-extensions
|
/iOSExtensions/Classes/RxSwift/Observable+Extensions.swift
|
UTF-8
| 465
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
import RxSwift
public extension Observable where Element == Int {
static func countdownTimer(from: Int, to: Int,
period: RxTimeInterval = .seconds(1),
scheduler: SchedulerType = MainScheduler.instance) -> Observable<Int> {
Observable<Int>
.timer(.seconds(0), period: period, scheduler: scheduler)
.take(from - to + 1)
.map { from - $0 }
}
}
| true
|
1631bb2055e60fc1a784075a748b93f034b262dd
|
Swift
|
TransformDevTeam/Transform
|
/Sleep_Tracker/DatePicker copy/ViewController.swift
|
UTF-8
| 4,150
| 2.90625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// DatePicker
//
// Created by Pedro Rosete on 10/10/20.
//
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var Hour: UITextField!
@IBOutlet weak var Minutes: UITextField!
@IBOutlet weak var AM_PM: UITextField!
@IBOutlet weak var Hour2: UITextField!
@IBOutlet weak var Minutes2: UITextField!
@IBOutlet weak var AM_PM2: UITextField!
var pickerView1 = UIPickerView()
var pickerView2 = UIPickerView()
var pickerView3 = UIPickerView()
var picker1Options = ["01","02","03","04","05","06","07","08","09",
"10","11","12"]
var picker2Options = ["00","01","02","03","04","05","06","07","08","09",
"10","11","12","13","14","15","16","17","18","19",
"20","21","22","23","24","25","26","27","28","29",
"30","31","32","33","34","35","36","37","38","39",
"40","41","42","43","44","45","46","47","48","49",
"50","51","52","53","54","55","56","57","58","59"]
var picker3Options = ["AM","PM"]
override func viewDidLoad() {
super.viewDidLoad()
pickerView1.delegate = self
pickerView1.dataSource = self
pickerView2.delegate = self
pickerView2.delegate = self
pickerView3.delegate = self
pickerView3.delegate = self
Hour.inputView = pickerView1
Hour.textAlignment = .center
Hour.placeholder = "HH"
Minutes.inputView = pickerView2
Minutes.textAlignment = .center
Minutes.placeholder = "MM"
AM_PM.inputView = pickerView3
AM_PM.textAlignment = .center
AM_PM.placeholder = "AM/PM"
Hour2.inputView = pickerView1
Hour2.textAlignment = .center
Hour2.placeholder = "HH"
Minutes2.inputView = pickerView2
Minutes2.textAlignment = .center
Minutes2.placeholder = "MM"
AM_PM2.inputView = pickerView3
AM_PM2.textAlignment = .center
AM_PM2.placeholder = "AM/PM"
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == pickerView1{
return picker1Options.count
}else if pickerView == pickerView3{
return picker3Options.count
}
else{
return picker2Options.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == pickerView1 {
return picker1Options[row]
}else if pickerView == pickerView3{
return picker3Options[row]
}
else {
return picker2Options[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == pickerView1{
Hour.text = picker1Options[row]
Hour.resignFirstResponder()
Hour2.text = picker1Options[row]
Hour2.resignFirstResponder()
}else if pickerView == pickerView3{
AM_PM.text = picker3Options[row]
AM_PM.resignFirstResponder()
AM_PM2.text = picker3Options[row]
AM_PM2.resignFirstResponder()
}
else{
Minutes.text = picker2Options[row]
Minutes.resignFirstResponder()
Minutes2.text = picker2Options[row]
Minutes2.resignFirstResponder()
}
}
//@IBAction func SaveButton(_ sender: Any) {
//let alertController = UIAlertController(title: "Time Saved!", message: "Nice Job", preferredStyle: .alert)
//alertController.addAction(UIAlertAction(title: "Dismiss", style: .default))
//self.present(alertController, animated: true, completion: nil)
//}
}
| true
|
af3199ca76150708930412fadddbbc734a13df7a
|
Swift
|
melsomino/undeclared-swift
|
/UnDeclared/Declaration/DeclarationParser.swift
|
UTF-8
| 7,429
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
//
// DeclarationParser.swift
// Unified Declaration Library
//
// Created by Michael Vlasov on 28.04.2018.
// Copyright © 2018 Michael Vlasov. All rights reserved.
//
import Foundation
public class DeclarationParser {
public static func parse(string: String) throws -> [DeclarationElement] {
return try parse(chars: CharReader(string: string))
}
public static func parse(chars: CharReader) throws -> [DeclarationElement] {
let tokens = try TokenReader(chars: chars, tokenizer: tokenize)
var elements = [DeclarationElement]()
if try tokens.pass(token: indentation) && tokens.passed.valueInt == 0 {
try parse(elements: &elements, indentation: 0, tokens: tokens)
}
if tokens.hasCurrent {
throw ParsingError.unexpected(token: tokens.current, context: tokens.currentContext)
}
return elements
}
// Internals
private static func isNotCrOrLf(c: UnicodeScalar) -> Bool {
return c != "\r" && c != "\n"
}
private static func isTab(c: UnicodeScalar) -> Bool {
return c == "\t"
}
private static let reservedUnicode = " \t\r\n()='`~#".unicodeScalars
private static func isNotReserved(c: UnicodeScalar) -> Bool {
return !reservedUnicode.contains(c)
}
private static func isWhitespace(c: UnicodeScalar) -> Bool {
return c == " " || c == "\t"
}
private static func parseBackQuotedString(chars: CharReader) throws -> LexicalToken {
var string = ""
let startPos = chars.currentPos
while chars.hasCurrent {
chars.passWhile { $0 != "`" }
string += chars.passed
if !chars.passChar("`") {
throw ParsingError.error(message: "Unterminated backquoted string", context: chars.contextAt(pos: startPos))
}
if !chars.passChar("`") {
break
}
string += "`"
}
return nameOrValue.with(value: .string(string))
}
private static let escapedByChar: [UnicodeScalar: UnicodeScalar] = [
"0": "\0",
"\'": "\'",
"\\": "\\",
"n": "\n",
"r": "\r",
"t": "\t"]
private static let hexChars = CharacterSet(charactersIn: "0123456789ABCDEFabcdef")
private static func expectCharFromCodePoint(chars: CharReader, digits: Int) throws -> UnicodeScalar{
var hex = [UnicodeScalar]()
var digits = digits
while digits > 0 {
if !chars.hasCurrent || !hexChars.contains(chars.current) {
throw ParsingError.error(message: "Invalid hex code string", context: chars.contextAt(pos: chars.currentPos))
}
hex.append(chars.current)
chars.next()
digits -= 1
}
let hexString = String(String.UnicodeScalarView(hex))
return UnicodeScalar(Int(hexString, radix: 16) ?? 0) ?? "\0"
}
private static func parseSingleQuotedString(chars: CharReader) throws -> LexicalToken {
var unicode = [UnicodeScalar]()
let startPos = chars.currentPos
while chars.hasCurrent {
if chars.passChar("\'") {
return nameOrValue.with(value: .string(String(String.UnicodeScalarView(unicode))))
}
if chars.passChar("\\") {
if !chars.hasCurrent {
break
}
if let escaped = escapedByChar[chars.current] {
unicode.append(escaped)
chars.next()
} else if chars.passChar("x") {
unicode.append(try expectCharFromCodePoint(chars: chars, digits: 2))
} else if chars.passChar("u") {
unicode.append(try expectCharFromCodePoint(chars: chars, digits: 4))
} else {
throw ParsingError.error(message: "Invalid escape sequence", context: chars.currentContext)
}
} else {
unicode.append(chars.current)
chars.next()
}
}
throw ParsingError.error(message: "Unterminated backquoted string", context: chars.contextAt(pos: startPos))
}
private static func passLineEnd(chars: CharReader) -> Bool {
if chars.current == "#" {
chars.passWhile(isNotCrOrLf)
}
if chars.passChar("\r") {
chars.passChar("\n")
return true
}
if chars.passChar("\n") {
return true
}
return false
}
private static func parseIndentation(chars: CharReader) -> LexicalToken? {
while chars.tag == nil || passLineEnd(chars: chars) {
chars.tag = true
let start = chars.nextPos
chars.passWhile(isTab)
if !chars.hasCurrent {
return nil
}
chars.passWhile(isWhitespace)
if chars.current != "\r" && chars.current != "\n" && chars.current != "#" {
let level = chars.unicode.distance(from: start, to: chars.nextPos)
return indentation.with(value: .int(level))
}
}
return nil
}
private static func tokenize(chars: CharReader) throws -> LexicalToken? {
var token = parseIndentation(chars: chars)
if let token = token {
return token
}
guard chars.hasCurrent else {
return nil
}
if chars.passChar("=") {
token = nameValueSeparator
} else if chars.passChar("~") {
token = attributeContinuation
} else if chars.passChar("(") {
token = openList
} else if chars.passChar(")") {
token = closeList
} else if chars.passChar("\'") {
token = try parseSingleQuotedString(chars: chars)
} else if chars.passChar("`") {
token = try parseBackQuotedString(chars: chars)
} else if chars.passWhile(isNotReserved) {
token = nameOrValue.with(value: .string(String(chars.passed)))
} else {
return nil
}
chars.passWhile(isWhitespace)
return token
}
private static func parse(attributes: inout [DeclarationAttribute], tokens: TokenReader) throws {
while try tokens.pass(token: nameOrValue) {
let name = tokens.passed.valueString
var value = DeclarationAttribute.Value.missing
if try tokens.pass(token: nameValueSeparator) {
if try tokens.pass(token: openList) {
var items = [String]()
while try tokens.pass(token: nameOrValue) {
items.append(tokens.passed.valueString)
}
try tokens.pass(required: closeList)
value = .array(items)
} else {
try tokens.pass(required: nameOrValue)
value = .string(tokens.passed.valueString)
}
}
attributes.append(DeclarationAttribute(name: name, value: value))
}
}
private static func pass(expectedIndentation: Int, tokens: TokenReader) throws -> Bool {
if tokens.hasCurrent && tokens.current.name == indentation.name &&
tokens.current.valueInt == expectedIndentation {
try tokens.next()
return true
}
return false
}
private static func parseElement(to elements: inout [DeclarationElement], indentation: Int, tokens: TokenReader) throws {
var attributes = [DeclarationAttribute]()
var children = [DeclarationElement]()
try parse(attributes: &attributes, tokens: tokens)
while try pass(expectedIndentation: indentation + 1, tokens: tokens) {
if try tokens.pass(token: attributeContinuation) {
try parse(attributes: &attributes, tokens: tokens)
} else {
try parse(elements: &children, indentation: indentation + 1, tokens: tokens)
break
}
}
elements.append(DeclarationElement(attributes: attributes, children: children))
}
private static func parse(elements: inout [DeclarationElement], indentation: Int, tokens: TokenReader) throws {
repeat {
try parseElement(to: &elements, indentation: indentation, tokens: tokens)
} while try pass(expectedIndentation: indentation, tokens: tokens)
}
static let nameOrValue = LexicalToken.register("name or value")
static let nameValueSeparator = LexicalToken.register("=")
static let attributeContinuation = LexicalToken.register("~")
static let indentation = LexicalToken.register("⇥")
static let openList = LexicalToken.register("(")
static let closeList = LexicalToken.register(")")
}
| true
|
7aa8ec9e4e921eaaf6fe2000bae5c1c45d2cc772
|
Swift
|
MontanaFlossCo/Flint
|
/FlintCore/Constraints/Permissions/DefaultPermissionChecker.swift
|
UTF-8
| 5,750
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// DefaultPermissionChecker.swift
// FlintCore
//
// Created by Marc Palmer on 01/05/2018.
// Copyright © 2018 Montana Floss Co. Ltd. All rights reserved.
//
import Foundation
public enum ContactsEntity {
case contacts
}
/// The implementation of the system permission checker.
///
/// This registers and verifies the approprite adapters and uses them to check the status
/// of all the permissions required by a feature.
///
/// !!! TODO: Add sanity check for missing Info.plist usage descriptions?
public class DefaultPermissionChecker: SystemPermissionChecker, CustomDebugStringConvertible {
/// - note: Access only from the accessQueue
private var permissionAdapters: [SystemPermissionConstraint:SystemPermissionAdapter] = [:]
public weak var delegate: SystemPermissionCheckerDelegate?
private var accessQueue = DispatchQueue(label: "tools.flint.permission-checker")
public init() {
}
/// - note: Call only from the access queue
private func add(_ adapters: [SystemPermissionAdapter]) {
for adapter in adapters {
permissionAdapters[adapter.permission] = adapter
}
}
/// Get the correct adapter for a given permission, lazily creating it if it has not been requested
/// previously. This allows us to avoid bootstrapping a bunch of SDK APIs e.g. CoreLocation if the permission
/// is never used.
private func getAdapter(for permission: SystemPermissionConstraint) -> SystemPermissionAdapter? {
return accessQueue.sync {
// Fast-path with existing adapters
if let result = permissionAdapters[permission] {
return result
}
// Lazily create the required adapter, to avoid e.g. creating a location manager when it is not needed
let adapterType: SystemPermissionAdapter.Type?
switch permission {
case .camera:
adapterType = CameraPermissionAdapter.self
case .microphone:
adapterType = MicrophonePermissionAdapter.self
case .location:
adapterType = LocationPermissionAdapter.self
case .contacts:
adapterType = ContactsPermissionAdapter.self
case .photos:
adapterType = PhotosPermissionAdapter.self
case .calendarEvents:
adapterType = EventKitPermissionAdapter.self
case .reminders:
adapterType = EventKitPermissionAdapter.self
case .motion:
adapterType = MotionPermissionAdapter.self
case .speechRecognition:
adapterType = SpeechRecognitionPermissionAdapter.self
case .siriKit:
adapterType = SiriKitPermissionAdapter.self
case .bluetooth:
adapterType = BluetoothPeripheralPermissionAdapter.self
case .mediaLibrary:
adapterType = MediaLibraryPermissionAdapter.self
}
if let adapter = adapterType {
if adapter.isSupported {
// We probably need to also verify there is actual camera hardware, e.g. WatchOS
add(adapter.createAdapters(for: permission))
} else {
FlintInternal.logger?.warning("Permission \"\(permission)\" is not supported. Either the target platform does not implement it, or your target is not linking the framework required.")
}
}
// Return the one appropriate for the request, now we have it created (if possible)
return permissionAdapters[permission]
}
}
public func isAuthorised(for permissions: Set<SystemPermissionConstraint>) -> Bool {
var result = false
for permission in permissions {
if status(of: permission) != .authorized {
result = false
break
} else {
result = true
}
}
return result
}
public func status(of permission: SystemPermissionConstraint) -> SystemPermissionStatus {
guard let adapter = getAdapter(for: permission) else {
FlintInternal.logger?.warning("Cannot get status for permission \(permission), there is no adapter for it")
return .unsupported
}
return adapter.status
}
public func requestAuthorization(for permission: SystemPermissionConstraint,
completion: @escaping (_ permission: SystemPermissionConstraint, _ status: SystemPermissionStatus) -> Void) {
guard let adapter = getAdapter(for: permission) else {
flintBug("No permission adapter for \(permission)")
}
FlintInternal.logger?.debug("Permission checker requesting authorization for: \(permission)")
adapter.requestAuthorisation { adapter, status in
FlintInternal.logger?.debug("Permission checker authorization request for: \(permission) resulted in \(status)")
completion(adapter.permission, status)
// Tell our delegate that things were updated - caches will need to be invalidated etc.
self.delegate?.permissionStatusDidChange(adapter.permission)
}
}
public var debugDescription: String {
let adapters = accessQueue.sync { permissionAdapters }
let results = adapters.values.map { adapter in
return "\(adapter.permission): \(adapter.status)"
}
return "Current permission statuses:\n\(results.joined(separator: "\n"))"
}
}
| true
|
e240e8d034e3d8b72202973286286722751b6f61
|
Swift
|
AdrianoAntoniev/JanKenPoUI
|
/JanKenPoUI/ViewController.swift
|
UTF-8
| 3,554
| 2.796875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// JanKenPoUI
//
// Created by Adriano Rodrigues Vieira on 09/09/20.
// Copyright © 2020 Adriano Rodrigues Vieira. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var rock: UIButton!
@IBOutlet weak var paper: UIButton!
@IBOutlet weak var scissors: UIButton!
@IBOutlet weak var playerChooseLabel: UILabel!
@IBOutlet weak var resultLabel: UILabel!
var playerSkin: String?
var opponentSkin: String?
private var playerChoices: [String]?
private var opponentChoices: [String]?
@IBOutlet weak var opponentChooseLabel: UILabel! {
didSet {
opponentChooseLabel.transform = opponentChooseLabel.transform.rotated(by: CGFloat.pi)
}
}
override func viewDidLoad() {
super.viewDidLoad()
opponentSkin = Game.getRandomSkinColorSample()
playerChoices = Game.getHandChoices(basedOnSkin: playerSkin!)
opponentChoices = Game.getHandChoices(basedOnSkin: opponentSkin!)
// TODO: Eliminar esses numeros magicos!
rock.setTitle(playerChoices![0], for: .normal)
paper.setTitle(playerChoices![1], for: .normal)
scissors.setTitle(playerChoices![2], for: .normal)
playerChooseLabel.text = ""
opponentChooseLabel.text = ""
resultLabel.text = ""
}
@IBAction func handChosen(_ hand: UIButton) {
resultLabel.text = ""
playerChooseLabel.text = hand.currentTitle
opponentChooseLabel.text = opponentChoices!.randomElement()
performAnimation(in: playerChooseLabel, withAdditionalAnimation: {})
performAnimation(in: opponentChooseLabel, withAdditionalAnimation:
{self.opponentChooseLabel.transform = self.opponentChooseLabel.transform.rotated(by: CGFloat.pi)})
Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false) { (_) in
if let playerHand = self.playerChooseLabel.text, let opponentHand = self.opponentChooseLabel.text {
if let playerChoiceIndex = self.playerChoices?.firstIndex(of: playerHand),
let opponentChoiceIndex = self.opponentChoices?.firstIndex(of: opponentHand) {
self.resultLabel.text = Game.defineWinner(between: playerChoiceIndex, and: opponentChoiceIndex)
}
}
}
}
private func performAnimation(in label: UILabel, withAdditionalAnimation additionalAnimation: @escaping () -> Void) {
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: Measures.DURATION_OF_ANIMATION,
delay: Measures.DELAY_TIME,
options: [],
animations: {
label.transform = CGAffineTransform.identity.scaledBy(x: CGFloat(Measures.GROWN_SIZE_SCALE), y: CGFloat(Measures.GROWN_SIZE_SCALE))
additionalAnimation()
},
completion: { position in
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: Measures.DURATION_OF_ANIMATION,
delay: Measures.DELAY_TIME,
options: [],
animations: {
label.transform = CGAffineTransform.identity.scaledBy(x: CGFloat(Measures.NORMAL_SIZE_SCALE), y: CGFloat(Measures.NORMAL_SIZE_SCALE))
additionalAnimation()
}
)
}
)
}
}
| true
|
8589561c18906debca16832f04a0e54a6f53426a
|
Swift
|
davidellus/TwilioVideo
|
/Sources/App/Controllers/UserController.swift
|
UTF-8
| 4,409
| 2.78125
| 3
|
[] |
no_license
|
//
// UserController.swift
// App
//
// Created by Davide Fastoso on 01/06/2020.
//
import Foundation
import Vapor
import Fluent
struct UserController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
let userRoutes = routes.grouped("users")
let protectedUsers = userRoutes.grouped(User.authenticator(), AdminMiddleware())
protectedUsers.get(use: indexHandler)
userRoutes.post("signup",use: createHandler)
userRoutes.delete(use: delete)
let httpBasicAuthRoutes = userRoutes.grouped(User.authenticator())
httpBasicAuthRoutes.post("login", use: loginHandler)
// Token.authenticator.middleware() adds Bearer authentication with middleware,
// Guard middlware ensures a user is logged in
let tokenAuthRoutes = userRoutes.grouped(Token.authenticator(), User.guardMiddleware())
tokenAuthRoutes.get("me", use: getMyDetailsHandler)
let adminMiddleware = tokenAuthRoutes.grouped(AdminMiddleware())
adminMiddleware.delete(":userID", use: deleteHandler)
}
//Show all user
func indexHandler(_ req: Request) throws -> EventLoopFuture<[User]> {
let userSignup = try req.content.decode(UserSignup.self)
return User.query(on: req.db).all()
}
//Create a USER - OK
fileprivate func createHandler(req: Request) throws -> EventLoopFuture<NewSession> {
try UserSignup.validate(req)
try req.auth.require(User.self)
let userSignup = try req.content.decode(UserSignup.self)
let user = try User.create(from: userSignup)
var token: Token!
return checkIfUserExists(userSignup.username, req: req).flatMap { exists in
guard !exists else {
return req.eventLoop.future(error: UserError.usernameTaken)
}
return user.save(on: req.db)
}.flatMap {
guard let newToken = try? user.createToken(source: .signup) else {
return req.eventLoop.future(error: Abort(.internalServerError))
}
token = newToken
return token.save(on: req.db)
}.flatMapThrowing {
NewSession(token: token.value, user: try user.asPublic())
}
}
//Delete a USER - OK
func deleteHandler(_ req: Request) throws -> EventLoopFuture<HTTPStatus> {
return User.find(req.parameters.get("userID"), on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { $0.delete(on: req.db) }
.transform(to: .ok)
}
//Login a User - OCHECK
func loginHandler(_ req: Request) throws -> EventLoopFuture<NewSession> {
let user = try req.auth.require(User.self)
let token = try user.createToken(source: .login)
return token.save(on: req.db).flatMapThrowing {
NewSession(token: token.value, user: try user.asPublic())}
}
func getMyDetailsHandler(_ req: Request) throws -> User {
try req.auth.require(User.self)
}
func getMyOwnUser(req: Request) throws -> User.Public {
try req.auth.require(User.self).asPublic()
}
// - OK
private func checkIfUserExists(_ username: String, req: Request) -> EventLoopFuture<Bool> {
User.query(on: req.db)
.filter(\.$username == username)
.first()
.map { $0 != nil }
}
//GET - ALL USERS WITH EVENTS
func index(req: Request) throws -> EventLoopFuture<[User]>{
User.query(on: req.db).with(\.$events).all()
}
// DELETE A USER
func delete(req: Request) throws -> EventLoopFuture<HTTPStatus> {
return User.find(req.parameters.get("id"), on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap {$0.delete(on: req.db)}
.transform(to: .ok)
}
}
struct CreateUserData: Content {
let name: String
let email: String
let password: String
let userType: UserType
}
| true
|
f8493430fcf33d31d330dd4564001da11265cfc6
|
Swift
|
makemakeway/WorkTable
|
/Swift/FeelingDiary/RisingcampWeek2/Model/Tutorial.swift
|
UTF-8
| 944
| 2.859375
| 3
|
[] |
no_license
|
//
// TutorialModel.swift
// RisingcampWeek2
//
// Created by 박연배 on 2021/09/22.
//
import Foundation
class Tutorial {
static let shared = Tutorial()
func isFirstRun() -> Bool {
return !UserDefaults.standard.bool(forKey: "isFirstRun")
}
func setTutorialCompleted() {
UserDefaults.standard.set(true, forKey: "isFirstRun")
}
var contentTitle = ["Step 1", "Step 2", "Step 3", "Step 4", "Step 5"]
var contentImages = ["page0", "page1", "page2", "page3", "page4"]
var contentManual = ["일기를 작성하고 싶은 날짜를 선택해주세요!", "감정을 선택하고, 마음껏 일기를 작성해주세요!", "작성을 마친 뒤 완료를 누르면 감정과 일기가 저장됩니다.", "달력에서 작성한 날짜의 감정을 확인할 수 있습니다.", "선택한 감정에 따라 달력에 색이 채워집니다."]
static var isFirst = "123456"
}
| true
|
65c8516f96f746e91fbd8d66c52c5e53b79deb22
|
Swift
|
ChrisMyrants/Form
|
/Form/FieldConfig.swift
|
UTF-8
| 1,369
| 2.765625
| 3
|
[] |
no_license
|
import Functional
public struct FieldConfig<Options: FieldOptions> {
public typealias FieldValueType = Options.ValueType
public let title: String
public let deferredOptions: Deferred<Options>
public init(title: String, deferredOptions: Deferred<Options>) {
self.title = title
self.deferredOptions = deferredOptions
}
public init(title: String, options: Options) {
self.init(title: title, deferredOptions: Deferred<Options>(options))
}
public func getViewModel(for key: FieldKey, in storage: FormStorage, rules: [FieldRule<FieldValueType>]) -> FieldViewModel {
guard let availableOptions = [storage.getOptions(at: key) as? Options,
deferredOptions.peek]
.firstUnwrappedOrNil else {
deferredOptions.upon { storage.set(options: $0, at: key) }
return FieldViewModel.empty(
isHidden: storage.getHidden(at: key),
isLoading: true)
}
let value = storage.getValue(at: key)
let errorMessage = rules.joinAll()
.isValid(value: value.flatMap(Options.sanitizeValue), storage: storage)
.invalidMessages
.map { "\(title): \($0)" }
.joinAll(separator: "\n")
return FieldViewModel(
title: title,
value: value,
style: availableOptions.style,
errorMessage: Optional(errorMessage).filter { $0.isEmpty == false },
isHidden: storage.getHidden(at: key),
isLoading: false)
}
}
| true
|
060ce5d028f9c7ad5752d1d6a63a867fecd3569c
|
Swift
|
alhazme/MauKemanaWithCI
|
/Modules/Place/Place/Sources/Place/PlaceTransformer.swift
|
UTF-8
| 4,011
| 2.625
| 3
|
[] |
no_license
|
//
// PlaceTransformer.swift
//
//
// Created by Moch Fariz Al Hazmi on 29/11/20.
//
import Foundation
import Core
public struct PlaceTransformer: Mapper {
public typealias Response = PlaceResponse
public typealias Entity = PlaceModuleEntity
public typealias Domain = PlaceDomainModel
public init() {}
public func transformResponsesToDomains(responses: [PlaceResponse]) -> [PlaceDomainModel] {
return responses.map { response in
return PlaceDomainModel(
id: response.id,
name: response.name,
description: response.description,
address: response.address,
longitude: response.longitude,
latitude: response.latitude,
like: response.like,
image: response.image,
favorite: false
)
}
}
public func transformResponsesToEntities(responses: [PlaceResponse]) -> [PlaceModuleEntity] {
return responses.map { response in
let placeModuleEntity = PlaceModuleEntity()
placeModuleEntity.id = response.id
placeModuleEntity.name = response.name
placeModuleEntity.desc = response.description
placeModuleEntity.address = response.address
placeModuleEntity.longitude = response.longitude
placeModuleEntity.latitude = response.latitude
placeModuleEntity.like = response.like
placeModuleEntity.image = response.image
placeModuleEntity.favorite = false
return placeModuleEntity
}
}
public func transformEntitiesToDomains(entities: [PlaceModuleEntity]) -> [PlaceDomainModel] {
return entities.map { entity in
return PlaceDomainModel(
id: entity.id,
name: entity.name,
description: entity.desc,
address: entity.address,
longitude: entity.longitude,
latitude: entity.latitude,
like: entity.like,
image: entity.image,
favorite: entity.favorite
)
}
}
public func transformDomainsToEntities(domains: [PlaceDomainModel]) -> [PlaceModuleEntity] {
return domains.map { domain in
let placeModuleEntity = PlaceModuleEntity()
placeModuleEntity.id = domain.id
placeModuleEntity.name = domain.name
placeModuleEntity.desc = domain.description
placeModuleEntity.address = domain.address
placeModuleEntity.longitude = domain.longitude
placeModuleEntity.latitude = domain.latitude
placeModuleEntity.like = domain.like
placeModuleEntity.image = domain.image
placeModuleEntity.favorite = domain.favorite
return placeModuleEntity
}
}
public func transformEntityToDomain(entity: PlaceModuleEntity) -> PlaceDomainModel {
return PlaceDomainModel(
id: entity.id,
name: entity.name,
description: entity.desc,
address: entity.address,
longitude: entity.longitude,
latitude: entity.latitude,
like: entity.like,
image: entity.image,
favorite: entity.favorite
)
}
public func transformDomainToEntity(domain: PlaceDomainModel) -> PlaceModuleEntity {
let placeModuleEntity = PlaceModuleEntity()
placeModuleEntity.id = domain.id
placeModuleEntity.name = domain.name
placeModuleEntity.desc = domain.description
placeModuleEntity.address = domain.address
placeModuleEntity.longitude = domain.longitude
placeModuleEntity.latitude = domain.latitude
placeModuleEntity.like = domain.like
placeModuleEntity.image = domain.image
placeModuleEntity.favorite = domain.favorite
return placeModuleEntity
}
}
| true
|
b12a0e31c54499935c16a031a101f2c59ea27359
|
Swift
|
informramiz/design-patterns
|
/Singleton.playground/Contents.swift
|
UTF-8
| 845
| 3.796875
| 4
|
[
"Apache-2.0"
] |
permissive
|
import UIKit
//------------Singleton pattern----------------//
//a simple data placeholder
struct Meme {
let memeText: String
let memedImage: UIImage
}
class Memes {
//define an instance of this class with class scope
static let shared = Memes()
private var memes = [Meme]()
//make the constructor/initializer private so no one can create
//an instance of this class using syntax `Memes()`
private init() {
}
func append(_ meme: Meme) {
memes.append(meme)
}
func clear() {
memes.removeAll()
}
func getMemes() -> [Meme] {
return memes
}
}
//get instance of Memes, now you can't create instance with code `let memes1 = Memes()`
let memes1 = Memes.shared
//all calls to Memes use same shared instance
let memes2 = Memes.shared
| true
|
d3ff0ac0c3647e59f79acee266b4a2e7edb6f0e8
|
Swift
|
Shadowman405/HeroesWiki3
|
/HeroesWiki3/View/HeroDetailsViewController.swift
|
UTF-8
| 969
| 2.578125
| 3
|
[] |
no_license
|
//
// HeroDetailsViewController.swift
// HeroesWiki3
//
// Created by Maxim Mitin on 1.08.21.
//
import UIKit
class HeroDetailsViewController: UIViewController {
@IBOutlet weak var heroImage: UIImageView!
@IBOutlet weak var heroNameLbl: UILabel!
@IBOutlet weak var herClassLbl: UILabel!
@IBOutlet weak var heroSpecsLbl: UILabel!
@IBOutlet weak var heroFractionLbl: UILabel!
@IBOutlet weak var heroStoryLbl: UILabel!
var heroDetails : Hero?
override func viewDidLoad() {
super.viewDidLoad()
heroImage.image = UIImage(named: heroDetails?.imageName ?? "")
heroNameLbl.text = "Name: \(heroDetails?.name ?? "")"
herClassLbl.text = "Class: \(heroDetails?.heroClass ?? "")"
heroSpecsLbl.text = "Specialization: \(heroDetails?.specialization ?? "")"
heroFractionLbl.text = "Fraction: \(heroDetails?.fraction ?? "")"
heroStoryLbl.text = heroDetails?.story ?? ""
}
}
| true
|
8055ae585f509285daa09561fdef5a1514d59d11
|
Swift
|
whatdakell/KellyLinehanAdvancedMAD
|
/picCollection/CollectionCollectionViewController.swift
|
UTF-8
| 5,554
| 2.609375
| 3
|
[] |
no_license
|
//
// CollectionCollectionViewController.swift
// picCollection
//
// Created by Kelly Linehan on 2/16/16.
// Copyright © 2016 Kelly Linehan. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class CollectionCollectionViewController: UICollectionViewController , UICollectionViewDelegateFlowLayout{
var expoImage = [String]()
override func viewDidLoad() {
super.viewDidLoad()
for i in 0...19{
expoImage.append("atlas" + String(i+1))
}
let layout = UICollectionViewFlowLayout()
//layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
self.collectionView?.setCollectionViewLayout(layout, animated : true)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
//self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
/*
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return sectionInserts
}
*/
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
print("header")
return CGSize(width: 50,height: 50)
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return expoImage.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
// Configure the cell
let image = UIImage(named: expoImage[indexPath.row])
cell.imageView.image = image
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let image = UIImage(named: expoImage[indexPath.row])
let newSize:CGSize = CGSize(width: (image?.size.width)!/8, height: (image?.size.height)!/8)
let rect = CGRectMake(0, 0, newSize.width, newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image?.drawInRect(rect)
let image2 = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return (image2?.size)!
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
print("in method")
var header: CollectionSupplementaryView?
if kind == UICollectionElementKindSectionHeader{
header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "Header", forIndexPath: indexPath) as? CollectionSupplementaryView
header?.headerLabel.text = "Fall 2015"
}
return header!
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
}
| true
|
585aac62e3484e08bd7d3143448ce034a97c6e80
|
Swift
|
MasterFushi/WeatherReader
|
/WeatherReader/WeatherReader/WeatherDisplay.swift
|
UTF-8
| 817
| 3.0625
| 3
|
[] |
no_license
|
//
// WeatherDisplay.swift
// WeatherReader
//
// Created by Nevin Gregory on 5/26/20.
// Copyright © 2020 Nevin Gregory. All rights reserved.
//
import SwiftUI
struct WeatherDisplay: View {
var wArray = DataReader.wArray
var body: some View {
ScrollView(.horizontal) {
HStack(spacing: 20) {
ForEach(0..<wArray.count)
{ item in
Text("\( self.wArray[item].dateString)\n\(self.wArray[item].temp)°F\n\(self.wArray[item].summary)").foregroundColor(.white)
.frame(width: 200, height: 200)
.background(Color.blue)
}
}
}
}
}
struct WeatherDisplay_Previews: PreviewProvider {
static var previews: some View {
WeatherDisplay()
}
}
| true
|
124daf2883981d469bfd213851185b22421cf6cb
|
Swift
|
andrewcb/malimbe
|
/Examples/guestbook.swift
|
UTF-8
| 2,280
| 2.953125
| 3
|
[] |
no_license
|
/*
A simple web guestbook, arguably the “Hello World” of web apps.
This version stores the data in memory and does not persist it.
*/
import Foundation
import malimbe
struct GuestbookEntry {
let name: String
let text: String
}
extension GuestbookEntry : HTMLRenderable {
var asHTML: String {
return [
HTMLTag.DIV([
HTMLTag.SPAN(HTMLTag.B(self.name), "says:", class:"itemtop"),
HTMLTag.DIV(self.text, class:"itembody")
], class:"guestbookitem")
].asHTML
}
}
var guestbookItems:[GuestbookEntry] = [
//GuestbookEntry(name: "Bob", text:"Hello")
]
func rootPageHandler(request: HTTPRequest, args:[String:String]) -> Future<HTTPResponse> {
let items: [HTMLRenderable]
if guestbookItems.count > 0 {
items = [HTMLTag.H2("Guestbook items:")] + guestbookItems.map { $0 as HTMLRenderable }
} else {
items = [HTMLTag.P("The guestbook is currently empty.")]
}
let content = HTMLTag.HTML(
HTMLTag.HEAD(HTMLTag.TITLE("Guestbook"), HTMLTag.LINK(rel:"StyleSheet", href:"/static/style.css", type:"text/css", media:"screen")),
HTMLTag.BODY(
items,
HTMLTag.FORM(
HTMLTag.P("Your name:", HTMLTag.INPUT(type:"text", name:"name")),
HTMLTag.P("Your message:", HTMLTag.BR(), HTMLTag.TEXTAREA( name:"text", cols:60, rows:4)),
HTMLTag.INPUT(type:"submit"),
action:"post", method:"POST")
)
)
return Future(immediate: HTTPResponse.OK(["Content-Type": "text/html"],
content:content)
)
}
func postHandler(request: HTTPRequest, args:[String:String]) -> Future<HTTPResponse> {
if let name = request.queryArgs["name"], text = request.queryArgs["text"] {
guestbookItems.append(GuestbookEntry(name:name, text:text))
}
return Future(immediate: HTTPResponse.Redirect("/"))
}
let router = Router(routes:[
Router.Post("/post", handler:postHandler),
Router.Get("/post", handler:postHandler),
Router.Get("/", handler:rootPageHandler)
])
let staticFiles = StaticFileRequestHandler(pathPrefix: "/static/", staticDir:appRelativePath("GuestbookStatic/"), next:router )
let server = HTTPServer(handler: staticFiles)
print("starting...")
do {
try server.start(9999)
print("started on 9999")
while(true) {
NSRunLoop.mainRunLoop().runUntilDate(NSDate.distantFuture())
}
} catch {
print("error: \(error)")
}
| true
|
1aa4bd09ee9fbc1ed0f3c8ee303e8e11030a42e8
|
Swift
|
phuhuynh2411/PullToRefresh
|
/PullToRefresh/CustomTableViewController.swift
|
UTF-8
| 1,231
| 2.609375
| 3
|
[] |
no_license
|
//
// CustomTableViewController.swift
// PullToRefresh
//
// Created by Huynh Tan Phu on 11/12/19.
// Copyright © 2019 Filesoft. All rights reserved.
//
import UIKit
class CustomTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
refreshControl = UIRefreshControl()
refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl?.addTarget(self, action: #selector(refreshTableView(sender:)), for: .valueChanged)
}
@objc func refreshTableView(sender: AnyObject){
print("Refresh the table view")
refreshControl?.endRefreshing()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "Test data"
return cell
}
}
| true
|
d520eb6a774551a33bdb9c5713b36ed236f8b95c
|
Swift
|
Apolla/iGraffiti
|
/iGraffiti-Demo/WallTableViewCell.swift
|
UTF-8
| 1,643
| 2.53125
| 3
|
[] |
no_license
|
//
// WallTableViewCell.swift
// iGraffiti-Demo
//
// Created by 张 家豪 on 2017/5/9.
// Copyright © 2017年 张 家豪. All rights reserved.
//
import Foundation
import UIKit
class WallTableViewCell: UITableViewCell {
// MARK: Properties
var wall: Wall! {
didSet {
self.textLabel?.text = wall.name
}
}
let identifier = "WallTableViewCell"
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init() {
super.init(style: UITableViewCellStyle.default, reuseIdentifier: identifier)
self.accessoryType = UITableViewCellAccessoryType.detailDisclosureButton
self.selectionStyle = UITableViewCellSelectionStyle.default
}
// MARK: Storyboard Method
func pushDetailView(pusher: UIViewController) {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "WallInfoTableViewController") as! WallInfoTableViewController
viewController.hidesBottomBarWhenPushed = true
viewController.wall = wall.copy() as! Wall
pusher.navigationController?.pushViewController(viewController, animated: true)
}
func pushWallView() {
guard let viewControllers = SceneManager.sharedInstance.mainTabBarController.viewControllers else {
return
}
WallManager.sharedInstance.wall = wall
SceneManager.sharedInstance.mainTabBarController.selectedViewController = viewControllers[0] as! UINavigationController
}
}
| true
|
719387798e280bde72a3adafdbdc89aafb86eb4f
|
Swift
|
aortich/Schedule
|
/TakeHome/Extensions/UITableView+Reusable.swift
|
UTF-8
| 917
| 2.71875
| 3
|
[] |
no_license
|
//
// UITableView+Reusable.swift
// TakeHome
//
// Created by Alberto Enrique Ortiz Chavolla on 23/08/21.
// Copyright © 2021 Alberto Enrique Ortiz Chavolla. All rights reserved.
//
import UIKit
extension UITableView {
func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath, with identifier: String, as cellType: T.Type = T.self) -> T {
guard let cell = dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? T else {
preconditionFailure("Failed to dequeue cell with identifier \(identifier)")
}
return cell
}
func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(with identifier: String, as viewType: T.Type = T.self) -> T {
guard let view = dequeueReusableHeaderFooterView(withIdentifier: identifier) as? T else {
preconditionFailure("Failed to dequeue header with identifier \(identifier)")
}
return view
}
}
| true
|
e7e0f888442454abf131e5724054b69ceee482a3
|
Swift
|
Waincey/KWK-2019
|
/XCodes/Day 7/KWK Day 7.playground/Contents.swift
|
UTF-8
| 330
| 2.859375
| 3
|
[] |
no_license
|
//import UIKit
//
//var str = "Hello, playground"
// Code Challenge - Stop the Trolls
let string = "Sorry for being late!"
let k = String(string.flatMap(){
if(!["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"].contains($0))
{
return $0
}else{
return nil
}
})
| true
|
64902ad74901dfb680eb73c667d93cb85e239ec7
|
Swift
|
ccalvomartinez/MadridShops
|
/MadridShops/Models/Mappers/PlaceMapper.swift
|
UTF-8
| 1,526
| 2.703125
| 3
|
[] |
no_license
|
//
// PlaceMapper.swift
// MadridShops
//
// Created by Administrador on 18/9/17.
// Copyright © 2017 CCM. All rights reserved.
//
import CoreData
func mapPlaceCDIntoPlace(placeCD: PlaceCD) -> Place {
let place = Place(name: placeCD.name!)
place.address = placeCD.address ?? ""
place.description_en = placeCD.description_en ?? ""
place.description_es = placeCD.description_es ?? ""
place.image = placeCD.image
place.image_url = placeCD.image_url ?? ""
place.latitude = placeCD.latitude
place.longitude = placeCD.longitude
place.logo = placeCD.logo
place.logo_url = placeCD.logo_url ?? ""
place.openingHours_en = placeCD.openingHours_en ?? ""
place.openingHours_es = placeCD.openingHours_es ?? ""
place.map = placeCD.map
return place
}
func mapPlaceIntoPlaceCD(context: NSManagedObjectContext, place: Place, isShop: Bool) -> PlaceCD {
let placeCD = PlaceCD(context: context)
placeCD.name = place.name
placeCD.address = place.address
placeCD.description_en = place.description_en
placeCD.description_es = place.description_es
placeCD.image = place.image
placeCD.image_url = place.image_url
placeCD.latitude = place.latitude ?? 0
placeCD.longitude = place.longitude ?? 0
placeCD.logo = place.logo
placeCD.logo_url = place.logo_url
placeCD.openingHours_en = place.openingHours_en
placeCD.openingHours_es = place.description_es
placeCD.isShop = isShop
placeCD.map = place.map
return placeCD
}
| true
|
da46553a053e8a79556c8d9344330195a4e26bd3
|
Swift
|
jaeyoon-lee2/ICS4U-Unit2-04-Swift
|
/MrCoxallStack.swift
|
UTF-8
| 1,249
| 3.578125
| 4
|
[] |
no_license
|
/*
This class creates an integer stack.
author Jay Lee
version 1.3
since 2020-05-21
*/
class MrCoxallStack {
enum InvalidInputError : Error {
case invalidInput
}
private var stack:[Int] = []
// This method push an integer to the stack.
func Push(pushNumber: String) {
do {
guard let pushNumber = Int(pushNumber) else {
throw InvalidInputError.invalidInput
}
self.stack.append(pushNumber)
} catch {
print("\nInvalid input.")
}
}
// This method returns the last integer in the stack.
func Peek() -> Int? {
if (self.stack.count == 0) {
return nil
}
return self.stack[self.stack.count - 1]
}
// This method pops the top integer from the stack.
func Pop() -> Int? {
if (self.stack.count == 0) {
return nil
}
let element = self.Peek()
self.stack.remove(at: self.stack.count - 1)
return element
}
// This method clears the stack.
func Clear() {
for counter in stride(from: self.stack.count, to: 0, by: -1) {
self.stack.remove(at: counter - 1)
}
}
// This method prints out the list of items in the stack.
func ShowStack() {
for index in 0..<self.stack.count {
print(self.stack[index])
}
}
}
| true
|
fdc72b10dc8a95f62fb112dae3ce163f9b5c2d52
|
Swift
|
awmcclain/CEF.swift
|
/CEF.swift/Handlers/CEFWebPluginUnstableCallback.swift
|
UTF-8
| 732
| 2.765625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
//
// CEFWebPluginUnstableCallback.swift
// CEF.swift
//
// Created by Tamas Lustyik on 2015. 08. 07..
// Copyright © 2015. Tamas Lustyik. All rights reserved.
//
import Foundation
/// Interface to implement for receiving unstable plugin information. The methods
/// of this class will be called on the browser process IO thread.
public protocol CEFWebPluginUnstableCallback {
/// Method that will be called for the requested plugin. |unstable| will be
/// true if the plugin has reached the crash count threshold of 3 times in 120
/// seconds.
func isUnstable(path: String, unstable: Bool)
}
public extension CEFWebPluginUnstableCallback {
func isUnstable(path: String, unstable: Bool) {
}
}
| true
|
2557032b57074a03b447fc3b49fd1bab21d5dadf
|
Swift
|
VRomanov89/BloomChatApp-v4
|
/BusinessMessenger2/FacebookBlueButton.swift
|
UTF-8
| 1,530
| 2.65625
| 3
|
[] |
no_license
|
//
// FacebookBlueButton.swift
// BusinessMessenger2
//
// Created by Volodymyr Romanov on 3/26/16.
// Copyright © 2016 EEEnthusiast. All rights reserved.
//
import UIKit
class FacebookBlueButton: UIButton {
override func awakeFromNib() {
//Create the rounded sides of the button by dividing the height of the object by 2.
layer.cornerRadius = 10
//Create the background color (RGB: 19/82/205) - BLUE 3B5998 (59, 89, 152)
layer.backgroundColor = UIColor(red: 59/255, green: 89/255, blue: 152/255, alpha: 1).CGColor
//Create a shadow for the button.
layer.shadowColor = UIColor(red: SHADOW_COLOR, green: SHADOW_COLOR, blue: SHADOW_COLOR, alpha: 1).CGColor
layer.shadowOpacity = 0.8
layer.shadowRadius = 1.0
layer.shadowOffset = CGSizeMake(0.0, 1.0)
//Create a border for the button. (RGB: 19/82/205) - BLUE
layer.borderWidth = 1.0
layer.borderColor = UIColor(red: 19/255, green: 82/255, blue: 226/255, alpha: 1).CGColor
//layer.
//Set the color of the text to white in Normal state. (RGB: 10/70/205) - BLUE
self.setTitleColor(UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1), forState: UIControlState.Normal)
//self.imageEdgeInsets =
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| true
|
63b77849ee4da7b0fae59d0ed65ba04d8e3d8b7d
|
Swift
|
marcnava13/curso-ios-10-swift
|
/MyRecipies/MyRecipies/DetailViewController.swift
|
UTF-8
| 4,153
| 2.65625
| 3
|
[] |
no_license
|
//
// DetailViewController.swift
// MyRecipies
//
// Created by Marcos Navarro Pérez on 29/01/2018.
// Copyright © 2018 Marcos Navarro Pérez. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet var recipeImageView: UIImageView!
@IBOutlet var tableView: UITableView!
@IBOutlet var ratingButton: UIButton!
var recipe : Recipe!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = recipe.name
self.recipeImageView.image = recipe.image
self.tableView.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 0.25)
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
self.tableView.separatorColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 0.25)
self.tableView.estimatedRowHeight = 44.0
self.tableView.rowHeight = UITableViewAutomaticDimension
self.ratingButton.setImage(UIImage(named: self.recipe.rating), for: .normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func close(segue: UIStoryboardSegue) {
if let reviewVC = segue.source as? ReviewViewController {
if reviewVC.ratingSelected != nil {
self.recipe.rating = reviewVC.ratingSelected!
self.ratingButton.setImage(UIImage(named: self.recipe.rating), for: .normal)
}
}
}
}
extension DetailViewController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 2
case 1:
return self.recipe.ingredients.count
case 2:
return self.recipe.steps.count
default:
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DetailRecipeCell", for: indexPath) as! RecipeDetailViewCell
cell.backgroundColor = UIColor.clear
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
cell.keyLabel.text = "Name: "
cell.keyValue.text = self.recipe.name
case 1:
cell.keyLabel.text = "Time: "
cell.keyValue.text = ("\(self.recipe.time!) min")
/*case 2:
cell.keyLabel.text = "Favourite: "
if self.recipe.isFavourite {
cell.keyValue.text = "Yes"
} else {
cell.keyValue.text = "No"
}*/
default:
break;
}
case 1:
if indexPath.row == 0 {
cell.keyLabel.text = "Ingredients: "
} else {
cell.keyLabel.text = ""
}
cell.keyValue.text = self.recipe.ingredients[indexPath.row]
case 2:
if indexPath.row == 0 {
cell.keyLabel.text = "Steps: "
} else {
cell.keyLabel.text = ""
}
cell.keyValue.text = self.recipe.steps[indexPath.row]
default:
break
}
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = ""
switch section {
case 1:
title = "Ingredients"
case 2:
title = "Steps"
default:
break
}
return title
}
}
extension DetailViewController : UITableViewDelegate {
}
| true
|
225c1ab62d549ccc88da8c678e65b0adb4b98a75
|
Swift
|
mikkomanoza/fox_weather_app
|
/Fox Weather/Module/Login/API/LoginService.swift
|
UTF-8
| 738
| 2.65625
| 3
|
[] |
no_license
|
//
// LoginService.swift
// Fox Weather
//
// Created by Joseph Mikko Mañoza on 19/02/2020.
// Copyright © 2020 Joseph Mikko Mañoza. All rights reserved.
//
import Foundation
class LoginService {
public func callAPILogin(username: String, password: String,
onSuccess successCallback: ((_ user: User) -> Void)?,
onFailure failureCallback: ((_ errorMessage: String) -> Void)?) {
LoginAPICallManager.instance.callAPILogin (
username: username, password: password, onSuccess: { (session) in
successCallback?(session)
},
onFailure: { (errorMessage) in
failureCallback?(errorMessage)
}
)
}
}
| true
|
e717d0884129abdb6bcdfe68b4d9370902d7f941
|
Swift
|
mmehr2/StampCollection
|
/StampCollection/InventoryItem+Ex.swift
|
UTF-8
| 7,610
| 2.578125
| 3
|
[] |
no_license
|
//
// InventoryItem+Ex.swift
// StampCollection
//
// Created by Michael L Mehr on 5/6/15.
// Copyright (c) 2015 Michael L. Mehr. All rights reserved.
//
import Foundation
import CoreData
/*
This class provides useful extensions to the CoreData object model classes, to allow them to remain re-generateable by XCode 6.3.
Currently it seems that these generated classes are all @NSManaged properties, and any additions will be clobbered.
*/
// TOTAL DEBUGGING KLUDGE!
private var lastCreatedInventoryObject: InventoryItem?
extension InventoryItem: SortTypeSortableEx {
static func getLastCreatedInventoryObject() -> InventoryItem? {
return lastCreatedInventoryObject
}
var normalizedCode: String {
return dealerItem.normalizedCode
}
var normalizedDate: String {
return dealerItem.normalizedDate
}
var plateNumber: Int {
return dealerItem.plateNumber
}
var wanted: Bool {
return self.wantHave == "w"
}
var itemCondition: String {
let prices = self.category.prices!
let conds: [String:String]
switch prices {
case "PF": conds = ["price1":"Mint", "price2":"FDC"]
default: conds = ["price1":"Mint", "price2":"Used", "price3":"OnFDC", "price4":"M/NT"]
}
return conds[itemType]!
}
var itemPrice: String {
return self.dealerItem.getPrice(itemType)
}
func updateBaseItem( _ item: DealerItem ) {
let newID = item.id
self.baseItem = newID
self.dealerItem = item
}
func updateRefItem( _ item: DealerItem ) {
let newID = item.id
self.refItem = newID
self.referredItem = item
}
enum ValueType {
case tInt(NSNumber)
case tString(String)
}
fileprivate static func translateKeyName( _ nameIn: String, forExport: Bool = false ) -> String {
var name = nameIn
// translate key name if needed (not allowed to use 1st letter as capital, not allowed to use the word "description"
switch name {
//case "CatgDisplayNum": name = "catgDisplayNum"
default:
// need to lowercase the 1st character in the name
let index = name.index(after: name.startIndex)
let firstChar = forExport ? name[..<index].uppercased() : name[..<index].lowercased()
let rest = name[index...]
name = firstChar + rest
}
return name
}
fileprivate static func typeForKeyName( _ name: String, withValue value: String ) -> ValueType {
var output = ValueType.tString(value)
// translate key name if needed (not allowed to use 1st letter as capital, not allowed to use the word "description"
switch name {
case "catgDisplayNum": output = ValueType.tInt(NSNumber(value: Int(value)! as Int))
case "exOrder": output = ValueType.tInt(NSNumber(value: Int(value)! as Int)) // autosequencing property generated by import processor
default: break
}
return output
}
fileprivate static func setDataValuesForObject( _ newObject: InventoryItem, fromData data: [String : String]) {
for (key, value) in data {
// translate key name if needed (not allowed to use 1st letter as capital, not allowed to use the word "description"
let keyName = translateKeyName(key)
// set the attributes of the new object (allows Int16 type or String type, for now)
let valueType = typeForKeyName( keyName, withValue: value )
switch valueType {
case .tInt (let val): newObject.setValue(val, forKey: keyName)
case .tString: newObject.setValue(value, forKey: keyName)
}
}
// create fixups and extracted data properties here
}
static func makeObjectFromData( _ data: [String : String], withRelationships relations: [String:NSManagedObject], inContext moc: NSManagedObjectContext? = nil) -> Bool {
// add a new object of this type to the moc
if let moc = moc {
let entityName = "InventoryItem"
if let newObject = NSEntityDescription.insertNewObject(forEntityName: entityName, into: moc) as? InventoryItem {
// set the relationships back to the proper objects
if let robj = relations["referredItem"] as? DealerItem {
newObject.referredItem = robj
}
if let mobj = relations["dealerItem"] as? DealerItem {
newObject.dealerItem = mobj
}
if let cobj = relations["category"] as? Category {
newObject.category = cobj
}
if let pobj = relations["page"] as? AlbumPage {
newObject.page = pobj
}
// set all the other data values here, so it can use related object reference data
InventoryItem.setDataValuesForObject(newObject, fromData: data)
lastCreatedInventoryObject = newObject // optional reference usage by single-item creators
return true
} else {
// report error creating object in CoreData MOC
print("Unable to make CoreData InventoryItem from data \(data)")
}
}
return false
}
// return the names of the data properties, in import/export order (from the CSV file)
static func getDataHeaderNames() -> [String] {
var output : [String] = []
//In Defined Order for CSV file:
// WantHave, BaseItem,ItemType, AlbumType,AlbumRef,AlbumSection,AlbumPage, RefItem, Desc,Notes, CatgDisplayNum
output.append("wantHave")
output.append("baseItem")
output.append("itemType")
output.append("albumType")
output.append("albumRef")
output.append("albumSection")
output.append("albumPage")
output.append("refItem")
output.append("desc")
output.append("notes")
output.append("catgDisplayNum")
return output
}
static func getExportHeaderNames() -> [String] {
var output : [String] = []
//In Defined Order for CSV file:
// WantHave, BaseItem,ItemType, AlbumType,AlbumRef,AlbumSection,AlbumPage, RefItem, Desc,Notes, CatgDisplayNum
output = getDataHeaderNames().map { x in
self.translateKeyName(x, forExport: true)
}
return output
}
func makeDataFromObject() -> [String : String] {
var output: [String : String] = [:]
let headerNames = InventoryItem.getDataHeaderNames()
//println("InventoryItem header names are \(headerNames)")
for headerName in headerNames {
let keyname = InventoryItem.translateKeyName(headerName, forExport: true)
switch headerName {
case "wantHave", "baseItem", "itemType", "desc", "notes", "refItem"
, "albumPage", "albumRef", "albumSection", "albumType":
let value = self.value(forKey: headerName) as? String ?? ""
output[keyname] = value
break
case "catgDisplayNum":
let value = self.value(forKey: headerName) as? Int ?? 0
output[keyname] = "\(value)"
break
default: break // ignore any auto-generated properties; we just want the basics
}
}
//println("New InventoryItem data is \(output)")
return output
}
}
| true
|
67819888855c9c906a3ff0e9328fd22c0df840be
|
Swift
|
ufukcanli/Tander
|
/Tander/Screens/Home/HomeView.swift
|
UTF-8
| 1,538
| 2.765625
| 3
|
[] |
no_license
|
//
// HomeView.swift
// Tander
//
// Created by Ufuk Canlı on 17.03.2021.
//
import SwiftUI
struct HomeView: View {
@StateObject private var viewModel = HomeViewModel()
var body: some View {
VStack {
TopMenuView(viewModel: viewModel)
Spacer()
ZStack {
ForEach(viewModel.cards) { card in
CardView(card: card)
.shadow(color: Color.black.opacity(0.2), radius: 2)
.animation(.interpolatingSpring(stiffness: 180, damping: 100))
.transition(viewModel.removalTransition)
.gesture(
DragGesture()
.onChanged { value in
viewModel.updatePositionOf(card: card, using: value)
}
.onEnded { value in
viewModel.shouldRemove(card: card, using: value)
}
)
}
}
.zIndex(1)
Spacer()
BottomMenuView(viewModel: viewModel)
}
.sheet(isPresented: $viewModel.isShowingSettings) {
SettingsView(viewModel: SettingsViewModel(isShowing: $viewModel.isShowingSettings))
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
| true
|
b3c996e40fa971516ed34a93ef30f6735bc02d7b
|
Swift
|
badrinathvm/SwiftUI
|
/Basics/Basics/View/Combine/CombineAsync.swift
|
UTF-8
| 1,300
| 2.953125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// CombineAsync.swift
// Basics
//
// Created by Venkatnarayansetty, Badarinath on 11/13/19.
// Copyright © 2019 Badarinath Venkatnarayansetty. All rights reserved.
//
import Foundation
import Combine
import SwiftUI
struct CombineAsync: View {
var combineAsync = DataSource()
var body: some View {
return VStack {
Text("Hello Async Combine")
}
}
}
enum RequestError: Error {
case sessionError(error: Error)
}
class DataSource: ObservableObject {
let URLPublisher = PassthroughSubject<URL, RequestError>()
init() {
let subscription = URLPublisher.flatMap { requestUrl in
URLSession.shared
.dataTaskPublisher(for: requestUrl)
.mapError { (error) -> RequestError in
RequestError.sessionError(error: error)
}
}
.assertNoFailure()
.receive(on: RunLoop.main)
.sink { result in
print("Request Finished \(result.data)")
}
//URLPublisher.send(URL(string: "https://httpbin.org/image/jpeg")!)
URLPublisher.send(URL(string: "https://gist.githubusercontent.com/badrinathvm/8f5485b6cf3f7f939261d9eb280c2583/raw/7b12b52736865dbe27cc0ffa31f89b4834914c9d/sample.json")!)
}
}
| true
|
c32ada6abe85ec52dcec000feb36422113cf0e1b
|
Swift
|
nganesan91/Series-Tracker-master
|
/Series Tracker/TvSeasonsController.swift
|
UTF-8
| 5,721
| 2.515625
| 3
|
[] |
no_license
|
//
// let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("storyBoardIdFor your new ViewController") as SecondViewController self.navigationController.pushViewController(secondViewController, animated- true).swift
// Series Tracker
//
// Created by Nitish Krishna Ganesan on 9/21/15.
// Copyright © 2015 NKG. All rights reserved.
//
import UIKit
import Alamofire
var selectedseason:Int = 0
var selectedepisode:Int = 0
class TvSeasonsController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var episode_count = [Int:Int]()
var season_count = [Int]()
@IBOutlet weak var customtableview: UITableView!
@IBOutlet weak var theme: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.customtableview.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
customtableview.delegate = self
customtableview.dataSource = self
let headers = ["application/json": "Accept"]
let id = selectedid
//new
var paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let getImagePath1 = paths[0] as? String
let getImagePath = getImagePath1! + "/" + selectedseries + ".jpg"
if paths.count > 0 {
let savePath = getImagePath
//print(savePath)
self.theme.image = UIImage(named: savePath)
}
// retrieving the episode list
if(reachability?.isReachable() == false){
let msg = "Cellular Data is Turned Off"
let alertController = UIAlertController(title: "Alert", message:
msg, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
else
{ // getting list of seasons and episodes
Alamofire.request(.GET, "http://api.themoviedb.org/3/tv/"+id, parameters: ["api_key": "133c880eda26e631ff9b8810b963fffc" ], headers:headers)
.response { (request, response, data, error) in
let json: AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
//print(json)
let result = json["seasons"] as! [[String : AnyObject]]
for res in result {
let epi = res["episode_count"]! as! Int
let season = res["season_number"]! as! Int
print(epi)
print(season)
if(season != 0){
self.episode_count[season] = epi
self.season_count.append(season)
}
}
self.customtableview.reloadData()
}
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return season_count.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
return "Season "+String(section+1)
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView //recast your view as a UITableViewHeaderFooterView
header.contentView.backgroundColor = UIColor(red: 150/255, green: 150/255, blue: 100/255, alpha: 1.0) //make the background color light blue
header.textLabel!.textColor = UIColor.blackColor() //make the text white
header.alpha = 0.5 //make the header transparent
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(episode_count.count>0){
return episode_count[section+1]!
}
return season_count.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.customtableview.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath) as UITableViewCell
cell.opaque = false
//cell.backgroundColor = [UIColor colorWithRed:0 green:0.39 blue:0.106 alpha:0]
// Configure the cell
if(season_count.count>0){
cell.textLabel!.text = " Episode "+String(indexPath.row+1)
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow;
let currentCell = tableView.cellForRowAtIndexPath(indexPath!);
print(currentCell!.textLabel!.text!)
selectedseason = indexPath!.section
selectedepisode = indexPath!.row
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let destination = storyboard.instantiateViewControllerWithIdentifier("EpisodeViewController") as! EpisodeViewController
navigationController?.pushViewController(destination, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func shouldAutorotate() -> Bool {
return false
}
}
| true
|
a9d6d58a01aab311a5ce06aba775498664696b2f
|
Swift
|
krasnoukhov/Spine
|
/Spine/Serializing.swift
|
UTF-8
| 7,107
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
//
// Mapping.swift
// Spine
//
// Created by Ward van Teijlingen on 23-08-14.
// Copyright (c) 2014 Ward van Teijlingen. All rights reserved.
//
import Foundation
/**
A JSONAPIDocument represents a JSON API document containing
resources, errors, metadata, links and jsonapi data.
*/
struct JSONAPIDocument {
/// Primary resources extracted from the response.
var data: [Resource]?
/// Included resources extracted from the response.
var included: [Resource]?
/// Errors extracted from the response.
var errors: [NSError]?
/// Metadata extracted from the reponse.
var meta: [String: AnyObject]?
/// Links extracted from the response.
var links: [String: NSURL]?
/// JSONAPI information extracted from the response.
var jsonapi: [String: AnyObject]?
}
struct SerializationOptions: OptionSetType {
let rawValue: Int
init(rawValue: Int) { self.rawValue = rawValue }
/// Whether to include the resource ID in the serialized representation.
static let IncludeID = SerializationOptions(rawValue: 1 << 1)
/// Whether to only serialize fields that are dirty.
static let DirtyFieldsOnly = SerializationOptions(rawValue: 1 << 2)
/// Whether to include to-many linked resources in the serialized representation.
static let IncludeToMany = SerializationOptions(rawValue: 1 << 3)
/// Whether to include to-one linked resources in the serialized representation.
static let IncludeToOne = SerializationOptions(rawValue: 1 << 4)
}
/**
The built in serializer that (de)serializes according to the JSON:API specification.
*/
class Serializer {
/// The resource factory used for dispensing resources.
var resourceFactory: ResourceFactory
/// The transformers used for transforming to and from the serialized representation.
var valueFormatters: ValueFormatterRegistry
/// The key formatter used for formatting field names to keys.
var keyFormatter: KeyFormatter
/**
Initializes a new JSONSerializer.
- parameter resourceFactory: The resource factory to use for creating resource instances. Defaults to empty resource factory.
- parameter valueFormatters: ValueFormatterRegistry containing value formatters to use for (de)serializing.
- parameter keyFormatter: KeyFormatter to use for (un)formatting keys. Defaults to the AsIsKeyFormatter.
- returns: JSONSerializer.
*/
init(resourceFactory: ResourceFactory = ResourceFactory(), valueFormatters: ValueFormatterRegistry = ValueFormatterRegistry.defaultRegistry(), keyFormatter: KeyFormatter = AsIsKeyFormatter()) {
self.resourceFactory = resourceFactory
self.valueFormatters = valueFormatters
self.keyFormatter = keyFormatter
}
/**
Deserializes the given data into a JSONAPIDocument.
- parameter data: The data to deserialize.
- parameter mappingTargets: Optional resources onto which data will be deserialized.
- throws: NSError that can occur in the deserialization.
- returns: A JSONAPIDocument.
*/
func deserializeData(data: NSData, mappingTargets: [Resource]? = nil) throws -> JSONAPIDocument {
let deserializeOperation = DeserializeOperation(data: data, resourceFactory: resourceFactory, valueFormatters: valueFormatters, keyFormatter: keyFormatter)
if let mappingTargets = mappingTargets {
deserializeOperation.addMappingTargets(mappingTargets)
}
deserializeOperation.start()
switch deserializeOperation.result! {
case .Failure(let error):
throw error
case .Success(let document):
return document
}
}
/**
Serializes the given JSON:API document into NSData. Currently only the main data is serialized.
- parameter document: The JSONAPIDocument to serialize.
- parameter options: The serialization options to use.
- throws: NSError that can occur in the serialization.
- returns: Serialized data.
*/
func serializeDocument(document: JSONAPIDocument, options: SerializationOptions = [.IncludeID]) throws -> NSData {
let serializeOperation = SerializeOperation(document: document, valueFormatters: valueFormatters, keyFormatter: keyFormatter)
serializeOperation.options = options
serializeOperation.start()
switch serializeOperation.result! {
case .Failure(let error):
throw error
case .Success(let data):
return data
}
}
/**
Serializes the given Resources into NSData.
- parameter resources: The resources to serialize.
- parameter options: The serialization options to use.
- throws: NSError that can occur in the serialization.
- returns: Serialized data.
*/
func serializeResources(resources: [Resource], options: SerializationOptions = [.IncludeID]) throws -> NSData {
let document = JSONAPIDocument(data: resources, included: nil, errors: nil, meta: nil, links: nil, jsonapi: nil)
return try serializeDocument(document, options: options)
}
}
/**
A ResourceFactory creates resources from given factory funtions.
*/
struct ResourceFactory {
private var factoryFunctions: [ResourceType: () -> Resource] = [:]
/**
Registers a given factory function that creates resource with a given type.
Registering a function for an already registered resource type will override that factory function.
- parameter type: The resource type for which to register a factory function.
- parameter factory: The factory function that returns a resource.
*/
mutating func registerResource(type: ResourceType, factory: () -> Resource) {
factoryFunctions[type] = factory
}
/**
Instantiates a resource with the given type, by using a registered factory function.
- parameter type: The resource type to instantiate.
- returns: An instantiated resource.
*/
func instantiate(type: ResourceType) -> Resource {
assert(factoryFunctions[type] != nil, "Cannot instantiate resource of type \(type). You must register this type with Spine first.")
return factoryFunctions[type]!()
}
/**
Dispenses a resource with the given type and id, optionally by finding it in a pool of existing resource instances.
This methods tries to find a resource with the given type and id in the pool. If no matching resource is found,
it tries to find the nth resource, indicated by `index`, of the given type from the pool. If still no resource is found,
it instantiates a new resource with the given id and adds this to the pool.
- parameter type: The resource type to dispense.
- parameter id: The id of the resource to dispense.
- parameter pool: An array of resources in which to find exisiting matching resources.
- parameter index: Optional index of the resource in the pool.
- returns: A resource with the given type and id.
*/
func dispense(type: ResourceType, id: String, inout pool: [Resource], index: Int? = nil) -> Resource {
var resource: Resource! = pool.filter { $0.resourceType == type && $0.id == id }.first
if resource == nil && index != nil && !pool.isEmpty {
let applicableResources = pool.filter { $0.resourceType == type }
if index! < applicableResources.count {
resource = applicableResources[index!]
}
}
if resource == nil {
resource = instantiate(type)
resource.id = id
pool.append(resource)
}
return resource
}
}
| true
|
8d16d5882b25f48825a525f5bb3588437d812421
|
Swift
|
StepanMirsky/ping-pong-swiftUI
|
/PinpongSwiftUI/Game/GameView.swift
|
UTF-8
| 6,421
| 2.953125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// PinpongSwiftUI
//
// Created by Лесников Александр Максимович on 04/07/2019.
// Copyright © 2019 Лесников Александр Максимович. All rights reserved.
//
import SwiftUI
struct GameViewModel: Identifiable {
let id = UUID()
let gameId: Int
let homeUser: UserViewModel
let awayUser: UserViewModel
var homeScore: UInt
var awayScore: UInt
var isFinished: Bool
var homeIsWinner: Bool {
return homeScore > awayScore
}
var awayIsWinner: Bool {
return !homeIsWinner
}
init(gameId: Int,
homeUser: UserViewModel,
awayUser: UserViewModel,
homeScore: UInt,
awayScore: UInt,
isFinished: Bool) {
self.gameId = gameId
self.homeUser = homeUser
self.awayUser = awayUser
self.homeScore = homeScore
self.awayScore = awayScore
self.isFinished = isFinished
}
}
extension GameViewModel {
init(game: Game) {
self.gameId = game.id
self.homeUser = UserViewModel(from: game.homeUser)
self.homeScore = UInt(game.homeScore)
self.awayUser = UserViewModel(from: game.awayUser)
self.awayScore = UInt(game.awayScore)
self.isFinished = game.isFinished
}
}
struct PlayerView : View {
let user: UserViewModel
let textAlignment: HorizontalAlignment
var body: some View {
VStack(alignment: textAlignment) {
Image(uiImage: user.image)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100)
.clipShape(Circle())
Text(user.name)
.font(.system(.title, design: .rounded))
Text(String(Int(user.rating)))
.font(.system(.headline, design: .rounded))
.color(.ratingColor(user.rating))
}
}
}
struct ScoreView : View {
let homeScore: UInt
let awayScore: UInt
let isFinished: Bool
var body: some View {
ZStack {
HStack {
HStack {
Spacer()
Text(String(homeScore))
.font(.system(size: 72))
.color(isFinished ? (homeScore > awayScore ? .green : .red) : .black)
}
Spacer()
HStack {
Text(String(awayScore))
.font(.system(size: 72))
.color(isFinished ? (awayScore > homeScore ? .green : .red) : .black)
Spacer()
}
}
Text(":")
.font(.system(size: 72))
}
}
}
struct GameView : View {
let gameService: GameService = GameServiceImpl()
let userService: UserService = UserServiceImpl()
@State var game: GameViewModel!
var awayUser: UserViewModel?
var body: some View {
VStack {
if game != nil {
ScrollView(showsIndicators: false) {
HStack {
PlayerView(user: game.homeUser, textAlignment: .leading).padding(.leading, 24)
Spacer()
Divider()
Spacer()
PlayerView(user: game.awayUser, textAlignment: .trailing).padding(.trailing, 24)
}.navigationBarTitle("Матч")
Divider()
ScoreView(homeScore: game.homeScore, awayScore: game.awayScore, isFinished: game.isFinished)
Divider()
if game.isFinished {
VStack {
Text("Победитель")
.font(.system(.largeTitle, design: .rounded))
PlayerView(user: game.homeIsWinner ? game.homeUser : game.awayUser, textAlignment: .center)
}
} else {
HStack {
Button(action: {
self.addScore(to: true)
}) {
Rectangle()
.frame(width: 100, height: 100)
.cornerRadius(20)
.foregroundColor(.green)
}.padding(16)
Divider()
Button(action: {
self.addScore(to: false)
}) {
Rectangle()
.frame(width: 100, height: 100)
.cornerRadius(20)
.foregroundColor(.blue)
}.padding(16)
}
}
}
} else {
ActivityIndicator(isAnimating: .constant(true), style: .large)
}
}.onAppear {
self.viewAppeared()
}
}
func viewAppeared() {
guard let awayUser = awayUser else {
return
}
gameService.create(awayUser.name) { result in
switch result {
case .success(let game):
self.game = game
case .failure:
break
}
}
}
func addScore(to isHome: Bool) {
if isHome {
game.homeScore += 1
} else {
game.awayScore += 1
}
endGameIfNeeded()
}
func endGameIfNeeded() {
if game.homeScore >= 11 && game.homeScore > game.awayScore && game.homeScore - game.awayScore >= 2 {
game.isFinished = true
gameService.updateGame(game) { result in
switch result {
case .success(let game):
self.game = game
case .failure:
break
}
}
}
if game.awayScore >= 11 && game.awayScore > game.homeScore && game.awayScore - game.homeScore >= 2 {
game.isFinished = true
gameService.updateGame(game) { result in
switch result {
case .success(let game):
self.game = game
case .failure:
break
}
}
}
}
}
| true
|
c7f4ae40de95cf2b6d14299d3f33376cf1414141
|
Swift
|
firdousali86/iOSSwift
|
/testProj/Controllers/BaseController.swift
|
UTF-8
| 3,093
| 2.546875
| 3
|
[] |
no_license
|
//
// BaseController.swift
// testProj
//
// Created by Firdous on 30/12/2015.
// Copyright © 2015 TenPearls. All rights reserved.
//
import UIKit
class BaseController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func getViewName() -> String{
let file = self.description
do{
if(!file.hasSuffix("Controller")){
try self.throwException(ControllerExceptions.InvalidClassName)
}
}
catch{
print("Invalid class name. Name should end with string 'controller' (e.g. SampleController)")
}
return file.stringByReplacingOccurrencesOfString("Controller", withString: "View")
}
func throwException(message : ControllerExceptions) throws -> String {
throw message
}
/*
-(void)loadView:(NSString*)nib{
if ([Utils isiPad]) {
//nib = [nib stringByAppendingString:@"~ipad"];
}
if([[NSBundle mainBundle] pathForResource:nib ofType:@"nib"] == nil){
[self throwExceptioin:[NSString stringWithFormat:@"%@ nib/class not found in project.",nib]];
}
UINib *nibs = [UINib nibWithNibName:nib bundle:nil];
NSArray *array = [nibs instantiateWithOwner:nil options:nil];
if(array.count == 0){
[self throwExceptioin:[NSString stringWithFormat:@"%@ nib doesn't have any view (IB error)",nib]];
}
if(![[array objectAtIndex:0] isKindOfClass:[BaseView class]]){
[self throwExceptioin:[NSString stringWithFormat:@"%@ nib should be subclass of %@ -> BaseView (IB error).",nib,nib]];
}
BaseView *view = (BaseView*)[array objectAtIndex:0];
view.controller = self;
self.view = view;
}
*/
func loadView(var nib : String) throws {
if(Utils.isiPad()){
nib = nib.stringByAppendingString("~ipad");
}
guard NSBundle.mainBundle().pathForResource(nib, ofType: "nib") != nil else {
throw ControllerExceptions.NibNotFound
}
let nibs = UINib.init(nibName: nib, bundle: nil)
let array = nibs.instantiateWithOwner(nil, options: nil)
guard array.count != 0 else {
throw ControllerExceptions.NoViewInNib
}
guard let arr0 = array[0] as? BaseView else {
throw ControllerExceptions.NibNotSubClassOfBaseView
}
let view : BaseView = array[0] as! BaseView
}
}
| true
|
047c610cc85d43c714c8200aeb8676e31c89f47b
|
Swift
|
chaserCN/UTF8CSV
|
/UTF8CSV/CSVString.swift
|
UTF-8
| 976
| 2.75
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// CSVString.swift
// UTF8CSV
//
// Created by Nicolas on 9/5/16.
// Copyright © 2016 Mobile Labs. All rights reserved.
//
import Foundation
extension String {
var toDelocalizedDecimalNumber: NSDecimalNumber? {
let number = NSDecimalNumber(string: self.replacingOccurrences(of: ",", with: "."),
locale: nil)
return number == NSDecimalNumber.notANumber ? nil : number
}
}
// utf8ToString is from Apple's protobuffer parser.
// it's even slightly faster than String(bytesNoCopy:length:encoding:freeWhenDone:)
// see StringUtils.swift in https://github.com/apple/swift-protobuf
internal func utf8ToString(bytes: UnsafePointer<UInt8>, count: Int) -> String? {
if count == 0 {
return String()
}
let s = NSString(bytes: bytes, length: count, encoding: String.Encoding.utf8.rawValue)
if let s = s {
return String._unconditionallyBridgeFromObjectiveC(s)
}
return nil
}
| true
|
8590b50877717ad5d7d718d78738a2aaf693c3bf
|
Swift
|
Gunwoos/programmers_study
|
/210101_pickMiddleWord.playground/Contents.swift
|
UTF-8
| 454
| 3.046875
| 3
|
[] |
no_license
|
import UIKit
func solution(_ s:String) -> String {
var arr = [String]()
var result : String = ""
for i in s {
arr.append(String(i))
}
if arr.count%2 == 0 {
let countNum : Int = arr.count/2
result = arr[countNum-1] + arr[countNum]
return result
}
else{
let countNum : Int = arr.count/2
result = arr[countNum]
return result
}
}
| true
|
c3da01b1dae05a0cc24be3666dbdf8202b68af30
|
Swift
|
thestoneage/Circuvals
|
/Circuvals/Formatter/IntervalFormatter.swift
|
UTF-8
| 1,049
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
struct IntervalFormatter {
let formatter = DateComponentsFormatter()
var interval: Interval
init(interval: Interval) {
self.interval = interval
formatter.zeroFormattingBehavior = .dropLeading
formatter.unitsStyle = .short
}
var title: String {
if let title = interval.title, title != "" {
return title
}
else {
return "\(type) Interval"
}
}
var type: String {
return interval.intervalType.readable()
}
var duration: String {
return formatter.string(from: Double(interval.duration / 10))!
}
func titleWith(index: Int) -> String {
return "(\(index + 1)) \(title)"
}
func descriptionWith(index: Int) -> String {
return "(\(index + 1)) - \(description)"
}
var description: String {
return "\(type), \(duration)"
}
func accessibilityIDWith(index: Int) -> String {
return "Interval\(index)"
}
}
| true
|
c155478f20e1e57033d0807e7aa783c37fa4a5e3
|
Swift
|
Akshay00009/Global_iOS
|
/Global/New Group/NetworkHelper.swift
|
UTF-8
| 2,615
| 2.578125
| 3
|
[] |
no_license
|
import Foundation
import Alamofire
import UIKit
import SwiftyJSON
import NVActivityIndicatorView
public class NetworkHelper : UIViewController {
@available(*, deprecated, message: "use shareWithPars: instead")
public static func shareWithPars(parameter: Any? ,method: HTTPMethod, url: String, completion: @escaping (_ result: [String : Any]) -> Void, completionError: @escaping (_ error: [String : Any]) -> Void) {
let status = Reachability.isConnectedToNetwork()
switch status {
case .unknown,.offline:
let errorDist = ["errorType":1, "errorValue": kNoInterNetMessage] as [String : Any]
completionError(errorDist as [String : Any])
break
case .online(.wwan),.online(.wiFi):
let headers: NSMutableDictionary = self.headerDictionary()
Alamofire.request(url, method: method, parameters: parameter as? Parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in
if response.result.isSuccess {
print(response)
NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
if let json = response.result.value {
if let jsonObjects = json as? [String: Any] {
completion(jsonObjects )
}
} else if let error = response.result.error {
NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
let errorDist = ["errorType":2, "errorValue": kSomethingGetWrong] as [String : Any]
completionError(errorDist as [String : AnyObject])
}
} else {
NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
let errorDist = ["errorType":3, "errorValue": kSomethingGetWrong] as [String : Any]
completionError(errorDist as [String : Any])
}
}
break
}
}
func getPostString(params:[String:Any]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
public static func headerDictionary()-> NSMutableDictionary {
let headers: NSMutableDictionary = NSMutableDictionary()
headers.setValue("application/json", forKey: "Content-Type")
return headers
}
}
| true
|
417efa39389d961fc1c4cdf72a3f0789a6b1aab7
|
Swift
|
fmtonakai/MahjongCalculator
|
/MahJongCalculator/Calculator.swift
|
UTF-8
| 4,503
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// Calculator.swift
// MahJongCalculator
//
// Created by Fuke Masaki on 2020/02/13.
// Copyright © 2020 Fuke Masaki. All rights reserved.
//
import Foundation
struct PaymentCalculator {
enum Role: Int, CustomStringConvertible {
case parent = 3, child = 2
fileprivate var multipleScore: Int {
rawValue
}
var description: String {
switch self {
case .parent: return "親"
case .child: return "子"
}
}
}
enum Payment: CustomStringConvertible, Equatable {
case all(Int)
case normal(parent: Int, child: Int)
case direct(Int)
var description: String {
switch self {
case let .all(score): return "\(score)点 オール"
case let .normal(parent: parent, child: child): return "親: \(parent)点, 子: \(child)点"
case let .direct(score): return "\(score)の支払い"
}
}
}
var han: Int
var fu: Int
var role: Role
var counters: Int
private var basePoint: Int {
switch han {
case 13... : return 16000 * role.multipleScore
case 11..<13: return 12000 * role.multipleScore
case 8..<11: return 8000 * role.multipleScore
case 6..<8: return 6000 * role.multipleScore
case 5: return 4000 * role.multipleScore
default: return lowerPoint
}
}
private var lowerPoint: Int {
let score = fu * (2 << (han + 2)) * role.multipleScore
return min(4000 * role.multipleScore, integral(score: score))
}
private func integral(score: Int) -> Int {
Int(ceil(Double(score) / 100) * 100)
}
var paymentForRon: Payment {
return .direct(integral(score: basePoint) + 300 * counters)
}
var paymentForTsumo: Payment {
switch role {
case .parent: return .all(integral(score: basePoint / 3) + 100 * counters)
case .child: return .normal(parent: integral(score: basePoint / 2) + 100 * counters,
child: integral(score: basePoint / 4) + 100 * counters)
}
}
}
struct FuCalculator {
static let `default` = FuCalculator(exceptionType: .none,
winningType: .tsumo,
headType: .numbers,
waitingType: .ryanmenOrShabo,
sets: [.init(type: .shuntsu, isSecret: true, isEdgeOrCharactors: false),
.init(type: .shuntsu, isSecret: true, isEdgeOrCharactors: false),
.init(type: .shuntsu, isSecret: true, isEdgeOrCharactors: false),
.init(type: .shuntsu, isSecret: true, isEdgeOrCharactors: false)])
var exceptionType: ExceptionType
var winningType: WinningType
var headType: HeadType
var waitingType: WaitingType
var sets: [JongSet]
private var isPinfuTsumo: Bool {
winningType == .tsumo && headType == .numbers && waitingType.score == 0 && sets.reduce(0, {$0 + $1.score}) == 0
}
var score: Int {
guard sets.count == 4 else { return 0 }
switch exceptionType {
case .pinfuTsumo: return 20
case .chitoitsu: return 25
default:
let baseScore = winningType.score + headType.score + waitingType.score + sets.reduce(0, {$0 + $1.score}) + 20
return max(30, min(110, Int( ceil(Double(baseScore) / 10) * 10)))
}
}
enum ExceptionType: CaseIterable {
case none, pinfuTsumo, chitoitsu
}
enum WinningType: Int, CaseIterable {
case tsumo = 2, ron = 0, menzenRon = 10
var score: Int { rawValue }
}
enum HeadType: Int, CaseIterable {
case charactors = 2, numbers = 0
var score: Int { rawValue }
}
struct JongSet {
enum SetType: Int, CaseIterable {
case shuntsu = 0, kotsu = 2, kantsu = 8
var score: Int { rawValue }
}
var type: SetType
var isSecret: Bool
var isEdgeOrCharactors: Bool
var score: Int {
type.score * (isSecret ? 2 : 1) * (isEdgeOrCharactors ? 2 : 1)
}
}
enum WaitingType: Int, CaseIterable {
case ryanmenOrShabo = 0, others = 2
var score: Int { rawValue }
}
}
| true
|
b90e73e87c0a5080a62f8daec468d98f37bcf880
|
Swift
|
rhx/SwiftHelloClutter
|
/Sources/HelloClutter/main.swift
|
UTF-8
| 2,134
| 3.078125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
import CClutter
import Clutter
/// Create a rectangle of a given colour on the given stage.
func createRectOn(_ s: Stage, colour c: Color, x: Double = 256, y: Double = 256, width: Double = 256, height: Double = 128, anchorX: Double = 128, anchorY: Double = 64) -> Rectangle {
var r = Rectangle(color: c)
r.setAnchorPoint(anchorX: anchorX, anchorY: anchorY)
r.size = (width, height)
r.position = (x, y)
s.add(child: r)
r.show()
return r
}
// Main function
guard initialize() == .success else {
fatalError("Could not initialise clutter.")
}
let black = Color(red: 0, green: 0, blue: 0, alpha: 255)
let stage = Stage()
stage.setSize(width: 512, height: 512)
stage.setBackground(color: black)
let red = Color(red: 255, green: 0, blue: 0, alpha: 128 )
let green = Color(red: 0, green: 255, blue: 0, alpha: 128 )
let blue = Color(red: 0, green: 0, blue: 255, alpha: 128 )
let yellow = Color(red: 255, green: 255, blue: 0, alpha: 128 )
let cyan = Color(red: 0, green: 255, blue: 255, alpha: 128 )
let purple = Color(red: 255, green: 0, blue: 255, alpha: 128 )
let colours = [red, green, blue, yellow, cyan, purple]
let rectangles = colours.map { createRectOn(stage, colour: $0) }
//
// Hide clicked rectangles
//
stage.connect(event: .buttonPressEvent) { stage, event, _ in
var x: gfloat = 0
var y: gfloat = 0
clutter_event_get_coords(event, &x, &y)
guard let clicked = stage.getActorAtPos(pickMode: .all, x: Int(x), y: Int(y)),
clicked.ptr != stage.ptr else { return }
clicked.hide()
}
var scale = 0.0
var rotation = 0.0
let timeLine = Timeline(msecs: 60)
timeLine.setRepeat(count: -1)
timeLine.onNewFrame { _,_,_ in
rotation += 0.3;
scale += 0.01
if scale > 1 { scale = 0 }
let scaleAmount = scale.smoothStep2(0.5, 2.0)
let n = rectangles.count
for i in 0..<n {
let r = rectangles[i]
r.setRotationAngle(axis: .zAxis, angle: rotation * Double(n-i-1))
r.setScale(scaleX: scaleAmount, scaleY: scaleAmount)
if scale == 0 { r.show() }
}
}
timeLine.start()
stage.show()
main()
| true
|
438890a7f72dcd9db4e0799aa43aaf1d068d5689
|
Swift
|
SherifNasr/CurrencyConverter
|
/CurrencyConverter/CurrencyConverter/Base/Extensions/UIViewExtension.swift
|
UTF-8
| 577
| 2.734375
| 3
|
[] |
no_license
|
//
// UIViewExtension.swift
// CurrencyConverter
//
// Created by Sherif Nasr on 21/04/2021.
//
import UIKit
extension UIView {
func addShadow(){
layer.shadowColor = .init(red: 0, green: 0, blue: 0, alpha: 16)
layer.shadowOpacity = 1
layer.shadowOffset = CGSize(width: 0, height: 2)
layer.shadowRadius = 4
layer.masksToBounds = false
}
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
}
| true
|
c3eaeb8b35067f5515964220f4b1a955ab5d5aab
|
Swift
|
mustasaari/WeatherApp
|
/WeatherApp/WeatherStruct.swift
|
UTF-8
| 429
| 2.734375
| 3
|
[] |
no_license
|
//
// WeatherStruct.swift
// WeatherApp
//
// Created by Mikko Mustasaari on 09/10/2019.
// Copyright © 2019 Mikko Mustasaari. All rights reserved.
//
import Foundation
class WeatherStruct: Codable {
var name: String
var main: Temperature
var weather: [Descriptions]
}
class Temperature: Codable {
var temp: Double
}
class Descriptions: Codable {
var main: String
var description: String
var icon: String
}
| true
|
bb40237a9dccca788d1a621f704f8b05f1524043
|
Swift
|
phucgo240699/Udemy
|
/Udemy/Controllers/Featured/CategoryCollectionViewCell.swift
|
UTF-8
| 2,864
| 2.71875
| 3
|
[] |
no_license
|
//
// CategoryCollectionViewCell.swift
// Udemy
//
// Created by Phúc Lý on 10/22/20.
// Copyright © 2020 Phúc Lý. All rights reserved.
//
import UIKit
import Alamofire
import SDWebImage
class CategoryCollectionViewCell: UICollectionViewCell {
var container: UIView?
var thumbnailImgView: UIImageView?
var titleLbl: UILabel?
var margin: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 20.0 : 10.0
override init(frame: CGRect) {
super.init(frame: frame)
initializeComponents(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initializeComponents(frame: CGRect) {
// Container
container = UIView(frame: CGRect(x: margin, y: margin, width: frame.width - 2 * margin, height: frame.height - 2 * margin))
guard let container = container else {
return
}
self.addSubview(container)
// let containerWidth = container.bounds.width
// let containerHeight = container.bounds.height
// Thumbnail
thumbnailImgView = UIImageView(frame: container.bounds)
// Title
// titleLbl = UILabel(frame: CGRect(x: 0, y: 0, width: containerWidth, height: containerHeight * 0.2))
guard let thumbnailImgView = thumbnailImgView else { //, let titleLbl = titleLbl else {
return
}
// Font - Size - Color
container.layer.cornerRadius = container.bounds.height * 0.05
container.layer.masksToBounds = true
thumbnailImgView.contentMode = .scaleAspectFill
// thumbnailImgView.addBlur()
// titleLbl.font = UIFont(name: Common.fontName, size: containerHeight * 0.15)
// titleLbl.font = UIFont.boldSystemFont(ofSize: containerHeight * 0.15)
// titleLbl.textColor = Common.color.textColor
// titleLbl.textAlignment = .center
// titleLbl.numberOfLines = 0
container.addSubview(thumbnailImgView)
// container.addSubview(titleLbl)
// Constraints
// titleLbl.translatesAutoresizingMaskIntoConstraints = false
// titleLbl.centerYAnchor.constraint(equalTo: container.centerYAnchor).isActive = true
// titleLbl.centerXAnchor.constraint(equalTo: container.centerXAnchor).isActive = true
}
func fillData(_ category: Category) {
// Thumbnail
if let imageName = category.image {
if let url = URL(string: "\(Common.link.getCategoryThumbnail)/\(imageName)") {
self.thumbnailImgView?.sd_setImage(with: url, completed: nil)
}
}
// Title
if let title = category.name {
titleLbl?.text = title
}
}
}
| true
|
39f402d5bfbe215235c405b65ffab88ce300619e
|
Swift
|
magic-script/magic-script-components-react-native
|
/ios/RNMagicScript/components/Utils/Extensions/Maths+Extension.swift
|
UTF-8
| 2,238
| 2.9375
| 3
|
[
"Apache-2.0",
"CC0-1.0",
"GPL-3.0-only",
"LGPL-3.0-only",
"CC-BY-4.0",
"AGPL-3.0-only",
"MPL-1.1",
"BSD-3-Clause",
"MPL-2.0",
"CC-BY-3.0",
"WTFPL",
"MPL-2.0-no-copyleft-exception",
"CDDL-1.1",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"CDDL-1.0",
"ISC",
"LGPL-2.1-only",
"MIT",
"GPL-2.0-only",
"EPL-1.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"AGPL-3.0-or-later"
] |
permissive
|
//
// Copyright (c) 2019-2020 Magic Leap, Inc. All Rights Reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import CoreGraphics
class Math {
@inline(__always) static public func deg2rad<T: FloatingPoint>(_ angle: T) -> T {
return angle * (T.pi / T(180))
}
@inline(__always) static public func rad2deg<T: FloatingPoint>(_ angle: T) -> T {
return angle * (T(180) / T.pi)
}
@inline(__always) static public func lerp<T>(_ left: T, _ right: T, _ p: T) -> T where T: FloatingPoint{
return (1 - p) * left + p * right
}
@inline(__always) static public func clamp<T>(_ value: T, _ a: T, _ b: T) -> T where T: Comparable {
return max(a, min(value, b))
}
}
extension CGFloat {
public var toRadians: CGFloat { return Math.deg2rad(self) }
public var toDegrees: CGFloat { return Math.rad2deg(self) }
public func clamped(_ minimum: CGFloat, _ maximum: CGFloat) -> CGFloat {
return Math.clamp(self, minimum, maximum)
}
}
extension Float {
public var toRadians: Float { return Math.deg2rad(self) }
public var toDegrees: Float { return Math.rad2deg(self) }
public func clamped(_ minimum: Float, _ maximum: Float) -> Float {
return Math.clamp(self, minimum, maximum)
}
}
extension Double {
public var toRadians: Double { return Math.deg2rad(self) }
public var toDegrees: Double { return Math.rad2deg(self) }
public func clamped(_ minimum: Double, _ maximum: Double) -> Double {
return Math.clamp(self, minimum, maximum)
}
}
extension Int {
public func clamped(_ minimum: Int, _ maximum: Int) -> Int {
return Math.clamp(self, minimum, maximum)
}
}
| true
|
82b526a8c12a1423fa4d2337684a400e0c9bbe2e
|
Swift
|
noxt/Groshy-SwiftUI
|
/Sources/Features/Hashtags/HashtagsActions.swift
|
UTF-8
| 1,145
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// Created by Dmitry Ivanenko on 12.10.2019.
// Copyright © 2019 Dmitry Ivanenko. All rights reserved.
//
import Foundation
import SwiftUIFlux
extension HashtagsFeature {
enum Actions {
struct SaveHashtag: Action {
let hashtag: Hashtag
}
struct LoadHashtags: AsyncAction {
func execute(state: FluxState?, dispatch: @escaping DispatchFunction) {
let hashtags = [
Hashtag(id: UUID(), title: "BigZ"),
Hashtag(id: UUID(), title: "Корона"),
Hashtag(id: UUID(), title: "Green"),
Hashtag(id: UUID(), title: "Газпром"),
Hashtag(id: UUID(), title: "Доставка"),
Hashtag(id: UUID(), title: "Salateira"),
]
dispatch(Actions.SetHastags(hashtags: hashtags))
}
}
struct SetHastags: Action {
let hashtags: [Hashtag]
}
struct SelectHashtag: Action {
let id: Hashtag.ID
}
struct ClearSelectedHashtag: Action {
}
}
}
| true
|
51b7174fc09f2a8a2793eda1196175bc911298c5
|
Swift
|
absin1/talentifyIOS
|
/Talentify/TaskScreenController.swift
|
UTF-8
| 1,543
| 2.546875
| 3
|
[] |
no_license
|
//
// TaskScreenController.swift
// Talentify
//
// Created by Feroz on 12/19/17.
// Copyright © 2017 iSTAR Skill Development Pvt. Ltd. All rights reserved.
//
import UIKit
class TaskScreenController: UIViewController {
@IBOutlet weak var rootTopView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pinBackground(backgroundView, to: rootTopView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private lazy var backgroundView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.talentifyRed
return view
}()
private func pinBackground(_ view: UIView, to stackView: UIStackView) {
view.translatesAutoresizingMaskIntoConstraints = false
stackView.insertSubview(view, at: 0)
view.pin(to: stackView)
}
}
public extension UIView {
public func pin(to view: UIView) {
NSLayoutConstraint.activate([
leadingAnchor.constraint(equalTo: view.leadingAnchor),
trailingAnchor.constraint(equalTo: view.trailingAnchor),
topAnchor.constraint(equalTo: view.topAnchor),
bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
extension UIColor {
static let talentifyRed = UIColor(red: 235/255, green: 56/255, blue: 79/255, alpha: 1)
}
| true
|
3283a3f59bb571348095e20e8c450ce2db310092
|
Swift
|
aBloomingTree/CaiyunWeather
|
/Sources/CaiyunWeather/CYHourly.swift
|
UTF-8
| 3,021
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//
// CYHourly.swift
//
//
// Created by 袁林 on 2021/6/14.
//
import Foundation
public struct CYHourly: Codable, Equatable {
public let responseStatus: String
public let description: String
public let phenomenon: [Phenomenon]
public let temperature: [Temperature]
public let precipitation: [Precipitation]
public let cloudrate: [Cloudrate]
public let humidity: [Humidity]
public let pressure: [Pressure]
public let wind: [Wind]
public let visibility: [Visibility]
public let dswrf: [DSWRF]
public let airQuality: AirQuality
private enum CodingKeys: String, CodingKey {
case responseStatus = "status"
case description
case phenomenon = "skycon"
case temperature
case precipitation
case cloudrate
case humidity
case pressure
case wind
case visibility
case dswrf
case airQuality = "air_quality"
}
}
// MARK: - Redefined Types
extension CYHourly {
public struct AirQuality: Codable, Equatable {
let aqi: [AQI]
let pm25: [PM25]
}
}
// MARK: - Type Alias
extension CYHourly {
public typealias HourlyContentDouble = ValueWithDatetime<Double>
public typealias Phenomenon = ValueWithDatetime<CYContent.Phenomenon>
public typealias Temperature = HourlyContentDouble
public typealias Precipitation = HourlyContentDouble
public typealias Cloudrate = HourlyContentDouble
public typealias Humidity = HourlyContentDouble
public typealias Pressure = HourlyContentDouble
public typealias Wind = ValueWithDatetimeFlat<CYContent.Wind>
public typealias Visibility = HourlyContentDouble
public typealias DSWRF = HourlyContentDouble
public typealias AQI = ValueWithDatetime<CYContent.AirQuality.AQI>
public typealias PM25 = HourlyContentDouble
}
// MARK: - Abstract Types
extension CYHourly {
public struct ValueWithDatetime<T: Codable & Equatable>: Codable, Equatable {
/// 时间
public let datetime: CYContent.DatetimeServerType
/// 值
public let value: T
}
public struct ValueWithDatetimeFlat<T: Codable & Equatable>: Codable, Equatable {
/// 时间
public let datetime: CYContent.DatetimeServerType
/// 值
public let value: T
private enum CodingKeys: String, CodingKey {
case datetime
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
datetime = try container.decode(CYContent.DatetimeServerType.self, forKey: .datetime)
value = try T(from: decoder)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(datetime, forKey: .datetime)
try value.encode(to: encoder)
}
}
}
| true
|
3b83b8e6ee004c60c9e6c25244b7ce0ee056186f
|
Swift
|
mks1388/PhonePeTest
|
/PhonePeTest/PhonePeTest/Utility/JSONParser.swift
|
UTF-8
| 484
| 2.6875
| 3
|
[] |
no_license
|
//
// JSONParser.swift
// PhonePeTest
//
// Created by Mithilesh on 15/02/20.
// Copyright © 2020 Mithilesh. All rights reserved.
//
import UIKit
class JSONParser {
func parseData<T: Decodable>(data: Data, type: T.Type, callBack: @escaping((Result<T, Error>) -> Void)) {
do {
let model = try JSONDecoder().decode(type, from: data)
callBack(.success(model))
} catch let error {
callBack(.failure(error))
}
}
}
| true
|
5dc06a2c69eb9d62acfc55a4fb50205e0bb548d1
|
Swift
|
HenryLTran/Tip-Calculator
|
/TipCalculator/TipCalculatorViewController.swift
|
UTF-8
| 4,343
| 2.703125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// TipCalculatorViewController.swift
// TipCalculator
//
// Created by Henry on 1/15/17.
// Copyright © 2017 Henry. All rights reserved.
//
import UIKit
class TipCalculatorViewController: UIViewController, UITextFieldDelegate {
var currencyFormatter = NumberFormatter()
var tipArray: [Double] = [0.10,0.15,0.20]
//var bill: Double?
var alpha: Double = 1.0
@IBOutlet weak var billTextField: UITextField!
@IBOutlet weak var currencyLabel: UILabel!
@IBOutlet weak var tipsAmountLabel: UILabel!
@IBOutlet weak var totalAmountLabel: UILabel!
@IBOutlet weak var tipPercent: UISegmentedControl!
@IBOutlet weak var firstView: UIView!
@IBOutlet weak var secondView: UIView!
@IBAction func indexSegmentChanged (sender:UISegmentedControl) {
calculateTip()
}
@IBAction func calculateButton (sender: UIButton) {
calculateTip()
}
override func viewDidLoad() {
super.viewDidLoad()
//print("viewDidLoad")
self.billTextField.delegate = self
self.billTextField.becomeFirstResponder()
self.billTextField.keyboardType = UIKeyboardType.decimalPad
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = NumberFormatter.Style.currency
currencyFormatter.locale = NSLocale.current
if let currencyS = currencyFormatter.locale.currencySymbol {
currencyLabel.text = currencyS
}
self.navigationController?.navigationBar.tintColor = self.navigationItem.rightBarButtonItem?.tintColor
let defaults = UserDefaults.standard
if let tipTimestamp = defaults.object(forKey: "SavedTimestamp") as? Date {
let currentTimestamp = Date().addingTimeInterval(-600) //10m=600s
if (currentTimestamp <= tipTimestamp) {
if let bill = defaults.object(forKey: "SavedBillAmount") as? Double {
billTextField.text = "\(bill)"
}
} //if (currentDate <= tipTimestamp)
else {
billTextField.text = ""
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//print("viewWillAppear")
//billTextField.text = ""
//setting default tip
let defaults = UserDefaults.standard
if let tipSegment = defaults.object(forKey: "TipSegment") as? Int
{
tipPercent.selectedSegmentIndex = tipSegment
}
viewAnimatedTransition(alpha: 0.0)
} //viewWillAppear
func calculateTip() {
viewAnimatedTransition(alpha: 1.0)
if var bill = Double(billTextField.text!) {
bill = round(bill*100)/100
billTextField.text = "\(bill)"
let tip = tipArray[tipPercent.selectedSegmentIndex]
var tipAmount = (bill * tip)
tipAmount = round(tipAmount*100)/100
tipsAmountLabel.text = "\(tipAmount)"
let totalAmount = bill + tipAmount
totalAmountLabel.text = currencyFormatter.string(from: totalAmount as NSNumber)
let delegate = UIApplication.shared.delegate as! AppDelegate
delegate.savedBill = bill
}
}
func viewAnimatedTransition(alpha: CGFloat) {
UIView.animate(withDuration: 1.0, delay: 0.0, options: .transitionCrossDissolve, animations: {
self.secondView.alpha = alpha
}, completion: nil)
}
// Text Field Delegate Methods
// Tapping on the view should dismiss the keyboard.
/*
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
*/
func textFieldShouldClear(_ textField: UITextField) -> Bool {
viewAnimatedTransition(alpha: 0.0)
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
calculateTip()
return true
}
}
extension String {
subscript(idx: Int) -> Character {
guard let strIdx = index(startIndex, offsetBy: idx, limitedBy: endIndex)
else { fatalError("String index out of bounds") }
return self[strIdx]
}
}
| true
|
0392e5dc925dd4eccbf1e563a5c5d0ad4fafbfb6
|
Swift
|
syrotynin/CompetitionManager
|
/CoreDataMVVM/View/Competiotion/ParticipantsViewController.swift
|
UTF-8
| 2,317
| 2.546875
| 3
|
[] |
no_license
|
//
// ParticipantsViewController.swift
// CoreDataMVVM
//
// Created by Serhii Syrotynin on 7/14/17.
// Copyright © 2017 Serhii Syrotynin. All rights reserved.
//
import UIKit
class ParticipantsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchField: UITextField!
@IBOutlet weak var doneButton: UIBarButtonItem!
let viewModel = ParticipantsViewModel()
override func viewDidLoad() {
super.viewDidLoad()
bindViewModel()
}
func bindViewModel() {
viewModel.searchString.bidirectionalBind(to:searchField.reactive.text)
viewModel.searchResults.bind(to: tableView) { dataSource, indexPath, tableView in
let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserTableViewCell
let participant = dataSource[indexPath.row]
cell.name.text = participant.name
// load track image
// let backgroundQueue = DispatchQueue(label: "backgroundQueue",
// qos: .background,
// attributes: .concurrent,
// autoreleaseFrequency: .inherit,
// target: nil)
// cell.photo.image = nil
// backgroundQueue.async {
// if let imageData = try? Data(contentsOf: track.url) {
// DispatchQueue.main.async() {
// cell.photo.image = UIImage(data: imageData)
// }
// }
// }
return cell
}
_ = viewModel.errorMessages.observeNext {
[unowned self] error in
let alertController = UIAlertController(title: "Something went wrong :-(", message: error, preferredStyle: .alert)
self.present(alertController, animated: true, completion: nil)
let actionOk = UIAlertAction(title: "OK", style: .default,
handler: { action in alertController.dismiss(animated: true, completion: nil) })
alertController.addAction(actionOk)
}
}
}
| true
|
f2469d2689bdfa9f4ea74d582210d157f6a59832
|
Swift
|
kang77649119/DouYuDemo
|
/DouYuDemo/DouYuDemo/Classes/Tools/NetWorkTools.swift
|
UTF-8
| 1,522
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// NetWorkTools.swift
// DouYuDemo
//
// Created by 也许、 on 16/10/11.
// Copyright © 2016年 K. All rights reserved.
//
import UIKit
import AFNetworking
enum DYMethod {
case GET
case POST
}
class NetWorkTools: NSObject {
class func request(type:DYMethod, url: String, parameters:[String : AnyObject]?, finisher:@escaping ([String:AnyObject]?)->()) {
if type == .GET {
AFHTTPSessionManager().get(url, parameters: parameters, progress: { (_) in
}, success: { (_, response) in
if response == nil {
finisher(nil)
return
}
finisher(response! as? [String : AnyObject])
}, failure: { (_, error) in
finisher(nil)
})
} else {
AFHTTPSessionManager().post(url, parameters: parameters, progress: { (_) in
}, success: { (_, response) in
if response == nil {
finisher(nil)
return
}
finisher(response! as? [String : AnyObject])
}, failure: { (_, error) in
finisher(nil)
})
}
}
}
| true
|
1a4f047bdbd5354f542c152be1053c7a5edb152f
|
Swift
|
JCTGY/MasterMind
|
/MasterMind/Constants.swift
|
UTF-8
| 1,383
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// Constants.swift
// MasterMind
//
// Created by jeffrey chiang on 2/11/20.
// Copyright © 2020 jeffrey chiang. All rights reserved.
//
/**
## K (Constant)
storing the constant string for the game, to avoid typo
- pausePopUpSegue: segue for PausePopUpViewController
- endPopUpSegue: segue for EndPopUpViewController
- normalModeSegue: segue for NomalGameViewController
- hardModeSegue: segue for HardGameViewController
- ruleSegue: segue for RuleViewController
- SoundFileName: sound file's file Name
- backgroud: Sound file name for background
- select: Sound file name for selec/deselect buttons
- submit: Sound file name for submit button
## Example
let GameSound = GameSound()
GameSound.playBackgroundSong()
*/
struct K {
static let pausePopUpSegue = "goToPausePopUp"
static let endPopUpSegue = "goToEndPopUp"
static let normalModeSegue = "goToNormalMode"
static let hardModeSegue = "goToHardMode"
static let ruleSegue = "goToRule"
static let leaderboardSegue = "goToLeaderboard"
static let leaderboardNibName = "LeaderboardCell"
static let tableCellIdentifier = "reuseableCell"
struct FStore {
static let leaderboard = "leaderboard"
static let name = "name"
static let score = "score"
}
struct SoundFileName {
static let background = "Background"
static let select = "playerSelect"
static let submit = "submit"
}
}
| true
|
b0a78725b5ccec5e3e454f29aeb2ae957ce9f572
|
Swift
|
snik2003/Telegram-Client
|
/Helpers/ViewControllerUtils.swift
|
UTF-8
| 3,453
| 2.59375
| 3
|
[] |
no_license
|
//
// ViewControllerUtils.swift
// VK-total
//
// Created by Сергей Никитин on 17.03.2018.
// Copyright © 2018 Sergey Nikitin. All rights reserved.
//
import UIKit
class ViewControllerUtils {
private static var container: UIView = UIView()
private static var loadingView: UIView = UIView()
private static var mainLabel: UILabel = UILabel()
private static var detailLabel: UILabel = UILabel()
private static var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
func showActivityIndicator(uiView: UIView) {
ViewControllerUtils.container.frame = uiView.frame
ViewControllerUtils.container.center = uiView.center
ViewControllerUtils.container.backgroundColor = UIColor.clear
let frame = CGRect(x: 0, y: 0, width: 140, height: 105)
ViewControllerUtils.loadingView.frame = frame
ViewControllerUtils.loadingView.center = uiView.center
ViewControllerUtils.loadingView.backgroundColor = Constants.shared.mainColor
ViewControllerUtils.loadingView.clipsToBounds = true
ViewControllerUtils.loadingView.layer.cornerRadius = 6
ViewControllerUtils.activityIndicator.frame = CGRect(x: frame.width/2 - 20, y: 15, width: 40, height: 40);
ViewControllerUtils.activityIndicator.style = .large
ViewControllerUtils.activityIndicator.color = .white
ViewControllerUtils.activityIndicator.clipsToBounds = false
ViewControllerUtils.mainLabel.text = "Подождите..."
ViewControllerUtils.mainLabel.frame = CGRect(x: 0, y: 55, width: frame.width, height: 20)
ViewControllerUtils.mainLabel.textColor = .white
ViewControllerUtils.mainLabel.font = UIFont.boldSystemFont(ofSize: 16)
ViewControllerUtils.mainLabel.textAlignment = .center
ViewControllerUtils.detailLabel.text = "Получение данных"
ViewControllerUtils.detailLabel.frame = CGRect(x: 0, y: 75, width: frame.width, height: 20)
ViewControllerUtils.detailLabel.textColor = .white //UIColor(red: 217/255, green: 37/255, blue: 43/255, alpha: 1)
ViewControllerUtils.detailLabel.font = UIFont.boldSystemFont(ofSize: 12)
ViewControllerUtils.detailLabel.textAlignment = .center
ViewControllerUtils.loadingView.addSubview(ViewControllerUtils.activityIndicator)
ViewControllerUtils.loadingView.addSubview(ViewControllerUtils.mainLabel)
ViewControllerUtils.loadingView.addSubview(ViewControllerUtils.detailLabel)
ViewControllerUtils.container.addSubview(ViewControllerUtils.loadingView)
uiView.addSubview(ViewControllerUtils.container)
ViewControllerUtils.activityIndicator.startAnimating()
}
func hideActivityIndicator() {
ViewControllerUtils.activityIndicator.stopAnimating()
ViewControllerUtils.container.removeFromSuperview()
}
func UIColorFromHex(rgbValue: UInt32, alpha: Double=1.0) -> UIColor {
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red: red, green: green, blue: blue, alpha: CGFloat(alpha))
}
}
extension UIView {
var visibleRect: CGRect {
guard let superview = superview else { return frame }
return frame.intersection(superview.bounds)
}
}
| true
|
52048140f01e4352fc239b4d7be4c07f7e90ab48
|
Swift
|
naseefptpm/MovieList
|
/MovieList/ApiManager.swift
|
UTF-8
| 915
| 2.90625
| 3
|
[] |
no_license
|
//
// ApiManager.swift
// MovieList
//
// Created by codeteki private Ltd on 23/12/20.
//
import Foundation
class ApiManager{
static let shared = ApiManager()
func httpGet(urlString: String!, callback: @escaping (MovieResponse?, String?) -> Void) {
let request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared
let task = session.dataTask(with: request){
(data, response, error) -> Void in
if error != nil {
callback(nil, error?.localizedDescription)
} else {
// let result = String(data: data!, encoding: .ascii)
do {
let result = try MovieResponse.init(data: data!)
callback(result, nil)
} catch {
callback(nil,"error")
}
}
}
task.resume()
}
}
| true
|
4b3f26890d7f5380b32aadbc4c47a933111e7e3b
|
Swift
|
soumarsi-navsoft/TwoLevelCache
|
/Example/Tests/Tests.swift
|
UTF-8
| 10,404
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
import XCTest
import TwoLevelCache
fileprivate let TestsSampleImagePath = "1x1.png"
fileprivate let TestsSampleImageUrl = "https://nzigen.com/static/img/common/logo.png"
class Tests: XCTestCase {
func testFindingWithDownloaderOrCaches() {
let cache = generateImageCache()
let expectation0 =
self.expectation(description: "downloading an image")
let expectation1 =
self.expectation(description: "finding an image from memory cache")
let expectation2 =
self.expectation(description: "finding an image from file cache")
let url = TestsSampleImageUrl + "?v=\(Date().timeIntervalSince1970)"
cache.findObject(forKey: url) { (image, status) in
XCTAssertNotNil(image)
XCTAssertEqual(status, TwoLevelCacheHitStatus.downloader)
expectation0.fulfill()
cache.findObject(forKey: url) { (image, status) in
XCTAssertNotNil(image)
XCTAssertEqual(status, TwoLevelCacheHitStatus.memory)
expectation1.fulfill()
cache.removeObject(forMemoryCacheKey: url)
cache.findObject(forKey: url) { (image, status) in
XCTAssertNotNil(image)
XCTAssertEqual(status, TwoLevelCacheHitStatus.file)
expectation2.fulfill()
}
}
}
wait(for: [expectation0, expectation1, expectation2], timeout: 30)
}
func testInitialization() {
let cache = try? TwoLevelCache<UIImage>("cache")
XCTAssertNotNil(cache)
}
func testRemovingCaches() {
let cache = generateImageCache()
let expectation0 =
self.expectation(description: "downloading an image")
let url = TestsSampleImageUrl + "?v=\(Date().timeIntervalSince1970)"
cache.findObject(forKey: url) { (image, status) in
XCTAssertNotNil(image)
XCTAssertEqual(status, TwoLevelCacheHitStatus.downloader)
sleep(1)
cache.removeObject(forMemoryCacheKey: url)
XCTAssertNil(cache.object(forMemoryCacheKey: url))
XCTAssertNotNil(cache.object(forFileCacheKey: url))
cache.removeObject(forFileCacheKey: url)
XCTAssertNil(cache.object(forMemoryCacheKey: url))
XCTAssertNil(cache.object(forFileCacheKey: url))
expectation0.fulfill()
}
wait(for: [expectation0], timeout: 30)
}
func testRemovingAllObjects() {
let cache = generateImageCache()
let image = UIImage(named: TestsSampleImagePath)!
cache.setObject(image, forKey: TestsSampleImagePath)
let memoryCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNotNil(memoryCached)
let fileCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNotNil(fileCached)
cache.removeAllObjects()
let memoryNotCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNil(memoryNotCached)
let fileNotCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNil(fileNotCached)
}
func testRemovingAllObjectsWithCallback() {
let cache = generateImageCache()
let image = UIImage(named: TestsSampleImagePath)!
cache.setObject(image, forKey: TestsSampleImagePath)
let memoryCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNotNil(memoryCached)
let fileCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNotNil(fileCached)
cache.removeAllObjects {
let memoryNotCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNil(memoryNotCached)
let fileNotCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNil(fileNotCached)
}
}
func testRemovingObject() {
let cache = generateImageCache()
let image = UIImage(named: TestsSampleImagePath)!
cache.setObject(image, forKey: TestsSampleImagePath)
let memoryCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNotNil(memoryCached)
let fileCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNotNil(fileCached)
cache.removeObject(forKey: TestsSampleImagePath)
let memoryNotCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNil(memoryNotCached)
let fileNotCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNil(fileNotCached)
}
func testRemovingObjectForFileCache() {
let cache = generateImageCache()
let image = UIImage(named: TestsSampleImagePath)!
cache.setObject(image, forKey: TestsSampleImagePath)
let memoryCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNotNil(memoryCached)
let fileCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNotNil(fileCached)
cache.removeObject(forFileCacheKey: TestsSampleImagePath)
let memoryStillCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNotNil(memoryStillCached)
let fileNotCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNil(fileNotCached)
}
func testRemovingObjectForMemoryCache() {
let cache = generateImageCache()
let image = UIImage(named: TestsSampleImagePath)!
cache.setObject(image, forKey: TestsSampleImagePath)
let memoryCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNotNil(memoryCached)
let fileCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNotNil(fileCached)
cache.removeObject(forMemoryCacheKey: TestsSampleImagePath)
let memoryNotCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNil(memoryNotCached)
let fileStillCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNotNil(fileStillCached)
}
func testSettingData() {
let cache = generateImageCache()
let image = UIImage(named: TestsSampleImagePath)!
cache.setData(UIImagePNGRepresentation(image)!, forKey: TestsSampleImagePath)
let memoryCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNotNil(memoryCached)
XCTAssertEqual(memoryCached!.size, image.size)
let fileCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNotNil(fileCached)
XCTAssertEqual(fileCached!.size, image.size)
}
func testSettingDataForFileCache() {
let cache = generateImageCache()
let image = UIImage(named: TestsSampleImagePath)!
cache.setData(UIImagePNGRepresentation(image)!, forFileCacheKey: TestsSampleImagePath)
let memoryCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNil(memoryCached)
let fileCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNotNil(fileCached)
XCTAssertEqual(fileCached!.size, image.size)
}
func testSettingDataForMemoryCache() {
let cache = generateImageCache()
let image = UIImage(named: TestsSampleImagePath)!
cache.setData(UIImagePNGRepresentation(image)!, forMemoryCacheKey: TestsSampleImagePath)
let memoryCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNotNil(memoryCached)
XCTAssertEqual(memoryCached!.size, image.size)
let fileCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNil(fileCached)
}
func testSettingObject() {
let cache = generateImageCache()
let image = UIImage(named: TestsSampleImagePath)!
cache.setObject(image, forKey: TestsSampleImagePath)
let memoryCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNotNil(memoryCached)
XCTAssertEqual(memoryCached!.size, image.size)
let fileCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNotNil(fileCached)
XCTAssertEqual(fileCached!.size, image.size)
}
func testSettingObjectForFileCache() {
let cache = generateImageCache()
let image = UIImage(named: TestsSampleImagePath)!
cache.setObject(image, forFileCacheKey: TestsSampleImagePath)
let memoryCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNil(memoryCached)
let fileCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNotNil(fileCached)
XCTAssertEqual(fileCached!.size, image.size)
}
func testSettingObjectForMemoryCache() {
let cache = generateImageCache()
let image = UIImage(named: TestsSampleImagePath)!
cache.setObject(image, forMemoryCacheKey: TestsSampleImagePath)
let memoryCached = cache.object(forMemoryCacheKey: TestsSampleImagePath)
XCTAssertNotNil(memoryCached)
XCTAssertEqual(memoryCached!.size, image.size)
let fileCached = cache.object(forFileCacheKey: TestsSampleImagePath)
XCTAssertNil(fileCached)
}
private func generateImageCache() -> TwoLevelCache<UIImage> {
let cache = try! TwoLevelCache<UIImage>("test-cache")
cache.downloader = { (key, callback) in
let url = URL(string: key)!
URLSession.shared.dataTask(with: url) { data, response, error in
callback(data)
}.resume()
}
cache.deserializer = { (data) in
return UIImage(data: data)
}
cache.serializer = { (object) in
return UIImagePNGRepresentation(object)
}
cache.removeAllObjects()
return cache
}
}
extension Tests {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
}
| true
|
57fc80a468daba74254a631736afa87a6869ddef
|
Swift
|
democres/MLSearchApp-iOS
|
/MLSearchApp/Modules/Home/HomeView.swift
|
UTF-8
| 3,336
| 2.796875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// HomeView.swift
// MLSearchApp
//
// Created by David Figueroa on 11/04/21.
//
import SwiftUI
struct HomeView: View {
@ObservedObject var presenter: HomePresenter
@State private var isEditing = false
@Environment(\.viewController) private var viewControllerHolder: UIViewController?
private var viewController: UIViewController? {
self.viewControllerHolder
}
var body: some View {
VStack{
Image("MainLogo")
.resizable()
.scaledToFit()
.frame(width: 60, height: 60)
.padding(.top, 30)
.padding(.bottom, 10)
Text("Mercado Libre Search")
.font(.custom("Harabara Mais Bold", size: 25))
.foregroundColor(MLSearchAppColors.darkBlue)
.padding(.bottom, 15)
TextField("Buscar productos, marcas y más...", text: $presenter.searchText, onCommit: {
presenter.getSearchResults(searchQuery: presenter.searchText)
})
.padding(7)
.padding(.horizontal, 25)
.font(.custom("Harabara Mais", size: 18))
.background(Color(.systemGray6))
.cornerRadius(8)
.overlay(
HStack {
Image(systemName: "magnifyingglass")
.foregroundColor(.gray)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.padding(.leading, 8)
if isEditing {
Button(action: { [weak presenter] in
self.isEditing = false
presenter?.searchText.removeAll()
presenter?.articles.removeAll()
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}) {
Image(systemName: "multiply.circle.fill")
.foregroundColor(.gray)
.padding(.trailing, 8)
}
}
}
)
.padding(.horizontal, 20)
.padding(.bottom, 20)
.onTapGesture {
self.isEditing = true
}
if presenter.isLoading {
ProgressView("Buscando..")
}
if presenter.showMessage {
MessageView(showMessage: $presenter.showMessage, message: presenter.errorMessage, isError: true)
}
List(presenter.articles) { article in
Button (action: {
self.viewController?.present(style: .fullScreen, transitionStyle: .flipHorizontal) {
ProductDetailViewControllerUI(article: article)
}
}) {
ArticleCell(article: article)
}
}
Spacer()
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView(presenter: HomePresenter(interactor: HomeInteractor()))
}
}
| true
|
414439ec0d82bba54b24f6395acbfaf8e09b88a7
|
Swift
|
rurunuela/playground-uKm2j1vL
|
/codeSwift/src/pattern/singleton/testSingleton/Tests/testSingletonTests/testSingletonTests.swift
|
UTF-8
| 998
| 2.765625
| 3
|
[] |
no_license
|
import XCTest
import MySingleton
@testable import testSingleton
class testSingletonTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
XCTAssertEqual(testSingleton().text, "Hello, World!")
}
func testA (){
let ms = MySingleton.sharedInstance
let ms2 = MySingleton.sharedInstance
XCTAssertEqual(ms === ms2,true)
}
func testB (){
let ms = MySingleton.sharedInstance
XCTAssertEqual(ms.valeur,1)
let ms2 = MySingleton.sharedInstance
XCTAssertEqual(ms2.valeur,2)
let ms3 = MySingleton.sharedInstance
XCTAssertEqual(ms3.valeur,3)
XCTAssertEqual(ms3.valeur,ms.valeur)
}
static var allTests : [(String, (testSingletonTests) -> () throws -> Void)] {
return [
("testB", testA),
("testA", testA),
]
}
}
| true
|
fbab3a256aed5de7fe84b6ef7d5ad557ddfedcd1
|
Swift
|
AdamZuspan/HomePageFeeder
|
/CodeChallenge-main/CodeChallenge/Networking/DecodeJson.swift
|
UTF-8
| 557
| 2.8125
| 3
|
[] |
no_license
|
//
// DecodeJson.swift
// CodeChallenge
//
// Created by Adam Zuspan on 10/18/21.
//
import Foundation
protocol DecodeJson {
func decodeObject<T:Decodable>(input:Data, type:T.Type)-> T?
func decodeArray<T:Decodable>(input:Data, type:T.Type)-> [T]?
}
extension DecodeJson {
func decodeObject<T:Decodable>(input:Data, type:T.Type)-> T? {
return try? JSONDecoder().decode(T.self, from: input)
}
func decodeArray<T:Decodable>(input:Data, type:T.Type)-> [T]? {
return try? JSONDecoder().decode([T].self, from: input)
}
}
| true
|
04ce9136387f89aecf8f04bfb12f878d367546e9
|
Swift
|
shadeesaleh/swapi
|
/StarShadee/controllers/People/PeopleViewController.swift
|
UTF-8
| 2,648
| 2.515625
| 3
|
[] |
no_license
|
//
// PeopleViewController.swift
// StarShadee
//
// Created by Shadee Saleh on 16/02/2016.
// Copyright © 2016 SS. All rights reserved.
//
import UIKit
import MRProgress
import Falcon
class PeopleViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var people:[AnyObject] = []
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.startAnimating()
// Retrieve data
SWAPI.getPeopleWithCompletion({
(result:SWResultSet!, error: NSError!) -> () in
self.activityIndicator.stopAnimating()
self.activityIndicator.hidden = true
self.people = result.items
self.tableView.reloadData()
})
// Register Table Cells
tableView.registerNib(PeopleTableViewCell.nib(), forCellReuseIdentifier: PeopleTableViewCell.reuseIdentifier())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = indexPath.row
let cell = tableView.dequeueReusableCellWithIdentifier(PeopleTableViewCell.reuseIdentifier(), forIndexPath: indexPath) as! PeopleTableViewCell
let person = people[row] as! SWPerson
print("\(person.name)")
cell.nameLabel.text = person.name
return cell;
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let person = people[indexPath.row]
// deselect the row
tableView.deselectRowAtIndexPath(indexPath, animated: false)
// Present the People Details
let vc = PeopleDetailsViewController()
vc.person = person as! SWPerson
self.presentViewController(vc, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
37e4239d34f49dc30f0ccdbdf8db46b73d403084
|
Swift
|
rachel-13/shpock_coding_challenge
|
/Shpock Pirate Ships/ViewControllers/PirateShipDetailVC.swift
|
UTF-8
| 5,445
| 2.78125
| 3
|
[] |
no_license
|
//
// PirateShipDetailVC.swift
// Shpock Pirate Ships
//
// Created by pohyee on 24/01/2021.
// Copyright © 2021 pohyee. All rights reserved.
//
import UIKit
class PirateShipDetailVC: UIViewController {
lazy var imageView: UIImageView = {
let uiimageView = UIImageView(frame: .zero).withAutoLayout()
uiimageView.contentMode = .scaleAspectFit
uiimageView.image = UIImage(named: "no_image")
return uiimageView
}()
lazy var titleLabel: UILabel = {
let uiLabel = UILabel(frame: .zero).withAutoLayout()
uiLabel.font = uiLabel.font.withSize(24)
uiLabel.lineBreakMode = .byWordWrapping
uiLabel.numberOfLines = 0
return uiLabel
}()
lazy var descriptionLabel: UILabel = {
let uiLabel = UILabel(frame: .zero).withAutoLayout()
uiLabel.font = uiLabel.font.withSize(15)
uiLabel.lineBreakMode = .byWordWrapping
uiLabel.numberOfLines = 0
return uiLabel
}()
lazy var priceLabel: UILabel = {
let uiLabel = UILabel(frame: .zero).withAutoLayout()
uiLabel.text = "No Price Available"
uiLabel.font = uiLabel.font.withSize(18)
return uiLabel
}()
lazy var greetingButton: UIButton = {
let uiButton = UIButton(frame: .zero).withAutoLayout()
uiButton.layer.cornerRadius = 5
uiButton.backgroundColor = .systemBlue
uiButton.setTitle("Say Hi!", for: .normal)
return uiButton
}()
let viewModel: PirateShipDetailViewModel
init(viewModel: PirateShipDetailViewModel) {
self.viewModel = viewModel
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 = .white
self.view.addSubview(imageView)
self.view.addSubview(titleLabel)
self.view.addSubview(descriptionLabel)
self.view.addSubview(priceLabel)
self.view.addSubview(greetingButton)
setupImageView()
setupTitleLabel()
setupDescriptionLabel()
setupPriceLabel()
setupGreetingButton()
bindViewModel()
}
private func bindViewModel() {
viewModel.model.bind { pirateShip in
self.titleLabel.text = pirateShip.getTitle()
self.descriptionLabel.text = pirateShip.description
self.priceLabel.text = pirateShip.getPrice()
}
viewModel.imageData.bind { data in
if let imageData = data,
let uiimage = UIImage(data: imageData) {
self.imageView.image = uiimage
}
}
viewModel.greeting.bind { pirateGreeting in
if pirateGreeting.isEmpty { return }
self.showAlert(greeting: pirateGreeting)
}
}
}
extension PirateShipDetailVC {
private func setupImageView() {
let imageViewConstraints = [
imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 75),
imageView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.35),
imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10)
]
NSLayoutConstraint.activate(imageViewConstraints)
}
private func setupTitleLabel() {
let titleLabelConstraints = [
titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
titleLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 10)
]
NSLayoutConstraint.activate(titleLabelConstraints)
}
private func setupDescriptionLabel() {
let descriptionLabelConstraints = [
descriptionLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
descriptionLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
descriptionLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 25)
]
NSLayoutConstraint.activate(descriptionLabelConstraints)
}
private func setupPriceLabel() {
let priceLabelConstraints = [
priceLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
priceLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
priceLabel.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 30),
priceLabel.bottomAnchor.constraint(lessThanOrEqualTo: greetingButton.topAnchor, constant: 30)
]
NSLayoutConstraint.activate(priceLabelConstraints)
}
private func setupGreetingButton() {
let buttonConstraints = [
greetingButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
greetingButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
greetingButton.heightAnchor.constraint(equalToConstant: 50),
greetingButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -30)
]
NSLayoutConstraint.activate(buttonConstraints)
greetingButton.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
}
@IBAction func didTapButton() {
viewModel.didTapButton()
}
private func showAlert(greeting: String) {
let alert = UIAlertController(title: nil, message: greeting, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
| true
|
15c1ea6c7ab40dede9a9d93898ecc94ee9b89064
|
Swift
|
doug-salvati/Brick-Collector
|
/Brick Collector/Model/Rebrickable/RBMoldColor.swift
|
UTF-8
| 958
| 3.03125
| 3
|
[] |
no_license
|
//
// PartColor.swift
// Brick Collector
//
// Created by Doug Salvati on 12/21/21.
//
import Foundation
struct RBMoldColor: Decodable {
var colorId:Int
var colorName:String
var img:String?
var elements:[String]
enum CodingKeys: String, CodingKey {
case color_id, color_name, part_img_url, elements
}
init(from decoder:Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
colorId = try container.decode(Int.self, forKey: .color_id)
colorName = try container.decode(String.self, forKey: .color_name)
img = try? container.decode(String.self, forKey: .part_img_url)
elements = try container.decode([String].self, forKey: .elements)
}
init(colorId:Int, colorName:String, img:String?, elements:[String]) {
self.colorId = colorId
self.colorName = colorName
self.img = img
self.elements = elements
}
}
| true
|
345fbf6a990f8f5aed193539333f6b19d9b548af
|
Swift
|
xinzy/Swift-Wan
|
/Wan/Classes/Biz/Suare/Presenter/SquareViewPresenter.swift
|
UTF-8
| 1,354
| 2.53125
| 3
|
[] |
no_license
|
//
// SquareViewPresenter.swift
// Wan
//
// Created by Yang on 2020/4/26.
// Copyright © 2020 Xinzy. All rights reserved.
//
import Foundation
class SquareViewPresenter<View>: SquarePresenter where View: SquareView, View: UIViewController {
typealias V = View
var mView: View
var isKnowledgeLoaded: Bool { mKnowledgeLoaded }
var isNavigationLoaded: Bool { mNavigationLoaded }
private var mKnowledgeLoaded = false
private var mNavigationLoaded = false
required init(_ view: View) {
self.mView = view
}
func fetchKnowledge() {
HttpApis.loadKnowledgeChapter { [unowned self] in
self.mView.endRefreshKnowledge()
switch $0 {
case .success(let chapters):
self.mKnowledgeLoaded = true
self.mView.showKnowledges(chapters)
case.failure(let msg):
self.mView.showToast(msg)
}
}
}
func fetchNavigation() {
HttpApis.loadNavi { [unowned self] in
self.mView.hideProgress()
switch $0 {
case .success(let navs):
self.mNavigationLoaded = true
self.mView.showNav(navs)
case .failure(let msg):
self.mView.showToast(msg)
}
}
}
}
| true
|
827ba4620863452c24d4ec566ca703d31d4d703e
|
Swift
|
tomieq/SwiftPlannerBackend
|
/Sources/Planner/webApp/model/ScheduleDay.swift
|
UTF-8
| 1,199
| 3.328125
| 3
|
[] |
no_license
|
//
// ScheduleDay.swift
//
//
// Created by Tomasz Kucharski on 29/12/2020.
//
import Foundation
enum ScheduleError: Error {
case invalidAssigmentError(String)
}
class ScheduleDay: Codable {
let dayNumber: Int
var selectedUser: ScheduleUser?
var availableUsers: [ScheduleUser]
init(dayNumber: Int, availableUsers: [ScheduleUser]) {
self.dayNumber = dayNumber
self.availableUsers = availableUsers
self.selectedUser = nil
}
init(from snapshot: ScheduleDaySnapshot) {
self.dayNumber = snapshot.dayNumber
self.selectedUser = ScheduleUser(from: snapshot.selectedUser)
self.availableUsers = snapshot.availableUsers.compactMap{ ScheduleUser(from: $0) }
}
func assign(user: ScheduleUser) throws {
if let selectedUser = (self.availableUsers.filter{ $0.id == user.id }.first) {
self.selectedUser = selectedUser
self.availableUsers = []
return
}
throw ScheduleError.invalidAssigmentError("User \(user.name) is not allowed to work here on \(self.dayNumber.ordinal)!")
}
var isScheduled: Bool {
return self.selectedUser != nil
}
}
| true
|
fb240d184dda74537d7f7c3fdb264006b5e647d9
|
Swift
|
GittieLabs/photosviewer
|
/PhotoViewer/MenuDataSource.swift
|
UTF-8
| 2,864
| 2.828125
| 3
|
[] |
no_license
|
//
// MenuDataSource.swift
// PhotoViewer
//
// Created by Keith Elliott on 10/8/15.
// Copyright © 2015 GittieLabs. All rights reserved.
//
import UIKit
import Photos
protocol MenuSelectionDelegate{
func selectionChanged(menuIndex: Int)
}
class MenuDataSource: NSObject, UICollectionViewDelegate, UICollectionViewDataSource {
let menuReuseIdentifier = "menuCell"
var menus = ["Last Month","Last 3 Months", "Albums"]
var selectionDelegate: MenuSelectionDelegate? = nil
let collectionView: UICollectionView
var selectedIndexPath: NSIndexPath {
didSet{
selectionDelegate?.selectionChanged(selectedIndexPath.item)
}
}
init(collectionView: UICollectionView){
self.collectionView = collectionView
self.selectedIndexPath = NSIndexPath(forItem: 0, inSection: 0)
super.init()
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.registerNib(UINib(nibName: "MenuCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: menuReuseIdentifier)
let menuFlowLayout = UICollectionViewFlowLayout()
menuFlowLayout.itemSize = CGSize(width: 125, height: 50)
menuFlowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
menuFlowLayout.minimumInteritemSpacing = 0.0
menuFlowLayout.minimumLineSpacing = 0.0
self.collectionView.collectionViewLayout = menuFlowLayout
}
// MARK: - UICollectionView Delegate methods
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(menuReuseIdentifier,
forIndexPath: indexPath) as! MenuCollectionViewCell
cell.menuTitle.text = self.menus[indexPath.row]
cell.selectedBar.hidden = selectedIndexPath == indexPath ? false : true
cell.menuTitle.textColor = self.collectionView.tintColor
cell.selectedBar.backgroundColor = self.collectionView.tintColor
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return menus.count
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: Int)->UIEdgeInsets{
return UIEdgeInsets(top: 0.0, left: 5.0, bottom: 0.0, right: 5.0)
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let prevSelectedPath = selectedIndexPath
selectedIndexPath = indexPath
collectionView.reloadItemsAtIndexPaths([prevSelectedPath, indexPath])
}
}
| true
|
479f47665240cdc465ebc20562de6bbe0c34f280
|
Swift
|
wassupnari/tipmunk
|
/tipmunk/ViewController.swift
|
UTF-8
| 3,504
| 2.703125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ViewController.swift
// tipmunk
//
// Created by Nari Kim Shin on 7/23/16.
// Copyright © 2016 Nari Shin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let CONTROL_INDEX_KEY = "default_position"
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var totalView: UIView!
var value1: Int!
var value2: Int!
var value3: Int!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
initView()
calculate()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
@IBAction func onEditingStarted(sender: AnyObject) {
UIView.animateWithDuration(0.4, animations: {
self.totalView.alpha = 1
})
}
@IBAction func calculateTip(sender: AnyObject) {
let position = tipControl.selectedSegmentIndex
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(position, forKey: CONTROL_INDEX_KEY)
defaults.synchronize()
calculate()
}
func calculate() {
let tipPercentages = [Double(value1)/100.0, Double(value2)/100.0, Double(value3)/100.0]
// ?? : returns the right value if the left value is equal to nil
let bill = Double(billField.text!) ?? 0
let tip = bill * tipPercentages[tipControl.selectedSegmentIndex]
let total = bill + tip
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
}
func initView() {
// Set defaults
let defaults = NSUserDefaults.standardUserDefaults()
value1 = defaults.integerForKey("custom_1") == 0 ? 18 : defaults.integerForKey("custom_1")
value2 = defaults.integerForKey("custom_2") == 0 ? 20 : defaults.integerForKey("custom_2")
value3 = defaults.integerForKey("custom_3") == 0 ? 25 : defaults.integerForKey("custom_3")
tipControl.setTitle(String(value1) + "%", forSegmentAtIndex: 0)
tipControl.setTitle(String(value2) + "%", forSegmentAtIndex: 1)
tipControl.setTitle(String(value3) + "%", forSegmentAtIndex: 2)
tipControl.selectedSegmentIndex = defaults.integerForKey("default_position")
// Show or hide total view
if(Double(billField.text!) > 0) {
self.totalView.alpha = 1
} else {
self.totalView.alpha = 0
}
// Placeholder for billField
// if(Double(billField.text!) == 0) {
// let placeholder = NSAttributedString(string: "$", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
// let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 100, height: 30));
// billField.attributedPlaceholder = placeholder;
// self.billField.addSubview(textField)
// }
}
}
| true
|
515f8d9b6a9e048db9de79d90c73437293d68ab5
|
Swift
|
guilhermePaciulli/BeerMeUp
|
/BeerMeUp/Views/BeerPropertiesView.swift
|
UTF-8
| 2,932
| 2.921875
| 3
|
[] |
no_license
|
//
// BeerPropertiesView.swift
// BeerMeUp
//
// Created by Guilherme Paciulli on 07/02/21.
//
import ComposableArchitecture
import SwiftUI
struct BeerPropertiesView: View {
@Binding var isEditing: Bool
var store: Store<Beer, BeerActions>
var body: some View {
WithViewStore(store) { viewStore in
VStack {
if !isEditing {
Text(viewStore.name)
.padding(12)
.font(.system(size: 18,
weight: .light,
design: .rounded))
} else {
TextField(viewStore.name,
text: viewStore.binding(
get: \.name,
send: BeerActions.renameBeer))
.textFieldStyle(RoundedBorderTextFieldStyle())
.font(.system(size: 18,
weight: .light,
design: .rounded))
.padding(12)
.allowsHitTesting(isEditing)
}
HStack {
Text("Hops")
.font(.system(size: 18, weight: .light))
BeerSliderView(isEditing: $isEditing,
currentValue:
viewStore.binding(get: \.hops,
send: BeerActions.updateHops),
activeColor: Color.green, image: .hop)
}.padding([.leading, .trailing], 12)
.frame(height: 44)
HStack {
Text("Malt ")
.font(.system(size: 18, weight: .light))
BeerSliderView(isEditing: $isEditing,
currentValue:
viewStore.binding(
get: \.malt,
send: BeerActions.updateMalts),
activeColor: Color.yellow, image: .malt)
}.padding([.leading, .trailing], 12)
.frame(height: 44)
BeerEditingButtons(isEditing: $isEditing, store: store)
}
}
}
}
struct BeerPropertiesView_Previews: PreviewProvider {
@State static var isEditing = false
static var previews: some View {
BeerPropertiesView(isEditing: $isEditing,
store:
Store(
initialState: Beer.mocks.first!,
reducer: beerReducer,
environment: BeerListEnvironment()
)
).frame(height: 144.0)
}
}
| true
|
0ee2572def79807ba2595511407661f13ca586d2
|
Swift
|
fwtrailsapp/iOS
|
/Rivergreenway/Converter.swift
|
UTF-8
| 4,831
| 3
| 3
|
[] |
no_license
|
//
// Copyright (C) 2016 Jared Perry, Jaron Somers, Warren Barnes, Scott Weidenkopf, and Grant Grimm
// 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.
//
//
// Converter.swift
// Rivergreenway
//
// Created by Scott Weidenkopf on 1/23/16.
// Copyright © 2016 City of Fort Wayne Greenways and Trails Department. All rights reserved.
//
import Foundation
/**
Class for unit conversions ;)
*/
class Converter {
class func poundsToKilograms(pounds: Double) -> Double {
return pounds * 0.453592
}
class func inchesToCentimeters(inches: Double) -> Double {
return inches * 2.54
}
class func feetToMeters(feet: Double) -> Double {
return feet * 0.3048
}
class func metersToFeet(meters: Double) -> Double {
return meters * 3.28084
}
class func timeIntervalToString(duration: NSTimeInterval) -> String {
let ti = Int(duration)
let sec = ti % 60
let min = (ti / 60) % 60
let hour = ti / 3600
return String(format: "%0.2d:%0.2d:%0.2d",hour,min,sec)
}
class func stringToDate(dateStr: String) -> NSDate? {
let format = NSDateFormatter()
format.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
return format.dateFromString(dateStr)
}
class func doubleToString(number: Double) -> String {
return String(format: "%.2f", number)
}
/**
Converts array of GMSMutablePaths to a String
*/
class func pathsToString(paths: [GMSMutablePath]) -> String {
//send all of the paths hooked together... god help us
var coords = [String]()
for path in paths {
if path.count() > 0 {
for index in 0..<path.count() {
let thisCoord = path.coordinateAtIndex(index)
let lat = thisCoord.latitude
let long = thisCoord.longitude
let format = "%.7f"
coords.append("\(String(format: format, lat)) \(String(format: format, long))")
}
}
}
let joined = coords.joinWithSeparator(",")
return joined
}
/**
Converts an NSDate into a string using the provided format.
*/
class func dateToString(date: NSDate, format: String = "yyyy-MM-dd'T'HH:mm:ss") -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = format
return formatter.stringFromDate(date)
}
class func stringToTimeInterval(intervalStr: String) -> NSTimeInterval? {
//a time interval string can be
//[d.]hh:mm:ss[.fffffff]
//where d is days and f are fractional seconds
//we'll parse this by splitting by colon -> [d.hh, mm, ss.fffffff]
//then splitting by period in the first index of the above -> [d, hh] or maybe [hh]
let split = intervalStr.componentsSeparatedByString(":")
if split.count != 3 {
return nil
}
let dayHour = split[0] //d.hh or hh
let dayHourArray = dayHour.componentsSeparatedByString(".")
var oDay: Int? = 0
if dayHourArray.count == 2 { //we have a day
oDay = Int(dayHourArray.first!)
}
let oHour: Int? = Int(dayHourArray.last!)
let oMin = Int(split[1])
let oSec = Double(split[2])
guard let day = oDay else {
return nil
}
guard let hour = oHour else {
return nil
}
guard let min = oMin else {
return nil
}
guard let sec = oSec else {
return nil
}
let finalSec = Double(day*24*60*60) + Double(hour*60*60) + Double(min*60) + sec
return NSTimeInterval(finalSec)
}
}
| true
|
b850ef9def0afb23d8eba5f31f0a47cb51cbb952
|
Swift
|
evanxlh/BluetoothCentral
|
/Demo/Demo/BluetoothDeviceViewController.swift
|
UTF-8
| 3,865
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// BluetoothDeviceViewController.swift
// Demo
//
// Created by Evan Xie on 2020/5/28.
//
import UIKit
import BluetoothCentral
class BluetoothDeviceViewController: UIViewController {
fileprivate var logBuffer = String()
var manager: CentralManager!
var peripheral: Peripheral!
@IBOutlet weak var logView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
logView.text = logBuffer
logView.isEditable = false
peripheral.receiveDataDelegate = self
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "退出", style: .plain, target: self, action: #selector(disconnectAndExit))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "开启蓝牙服务", style: .plain, target: self, action: #selector(prepareServicesToRead))
}
func outputLog(_ message: Any) {
DispatchQueue.main.async {
self.logBuffer.append("\(message)\n")
self.logView.text = self.logBuffer
print("\(message)\n")
}
}
@objc private func disconnectAndExit() {
manager.disconnectPeripheral(peripheral)
}
@objc private func prepareServicesToRead() {
KRProgressHUD.showInfo(withMessage: "开启蓝牙服务中...")
// let service = ServiceInterested(serviceUUID: dataServiceUUID, characteristicUUIDs: [readCharacteristicUUID, writeCharacteristicUUID, writeAndNotifyCharacteristicUUID])
peripheral.prepareServicesToReady([], successHandler: { (serviceInfos) in
self.outputLog(serviceInfos.description)
}) { (error) in
}
}
@IBAction func readFromReadCharacteristic(_ sender: Any) {
peripheral.readData(from: readCharacteristicUUID) { (error) in
}
}
@IBAction func writeToReadCharacteristic(_ sender: Any) {
outputLog("send: Hello, I'm a just read characteristic")
do {
try peripheral.writeData("Hello, I'm a just read characteristic".data(using: .utf8)!, toCharacteristic: readCharacteristicUUID)
} catch {
outputLog(error)
}
}
@IBAction func readFromWriteCharacteristic(_ sender: Any) {
peripheral.readData(from: writeCharacteristicUUID) { (error) in
}
}
@IBAction func writeToWriteCharacteristic(_ sender: Any) {
do {
outputLog("send: Hello, I'm a write characteristic")
try peripheral.writeData("Hello, I'm a write characteristic".data(using: .utf8)!, toCharacteristic: writeCharacteristicUUID)
} catch {
outputLog(error)
}
}
@IBAction func readFromWriteAndNotifiyCharacteristic(_ sender: Any) {
peripheral.readData(from: writeAndNotifyCharacteristicUUID) { (error) in
}
}
@IBAction func writeToWriteAndNotifiyCharacteristic(_ sender: Any) {
do {
outputLog("send: Hello, I'm write and notify characteristic")
try peripheral.writeData("Hello, I'm write and notify characteristic".data(using: .utf8)!, toCharacteristic: writeAndNotifyCharacteristicUUID)
} catch {
outputLog(error)
}
}
func showAlertWithMessage(_ message: String) {
let alert = UIAlertController(title: "提 示", message: message, preferredStyle: .alert)
present(alert, animated: true, completion: nil)
}
}
extension BluetoothDeviceViewController: PeripheralReceiveDataDelegate {
func peripheralDidRecevieCharacteristicData(_ peripheral: Peripheral, data: Data, characteristicUUID: String) {
outputLog("Received data from \(characteristicUUID): \(String(describing: String(data: data, encoding: .utf8)))")
}
}
| true
|
ffc07ba99d853571ad1b37a0cc764e056dbff38f
|
Swift
|
5x7x23/Awesome
|
/Awesome/Awesome/ViewControllers/DatepickerViewController.swift
|
UTF-8
| 1,105
| 3.046875
| 3
|
[] |
no_license
|
//
// DatepickerViewController.swift
// Awesome
//
// Created by 박익범 on 2021/05/05.
//
import UIKit
protocol dateData {
func dataSend(data : String)
func finishDateSend(data : String)
}
class DatepickerViewController: UIViewController {
@IBOutlet weak var pickerView: UIDatePicker!
var chooseDate: String = ""
var delegate : dateData?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func datepickerSelected(_ sender: Any) {
changed()
}
func changed(){
let dateformatter = DateFormatter()
dateformatter.dateStyle = .none
dateformatter.timeStyle = .short
dateformatter.locale = Locale(identifier: "en_GB")
print(pickerView.date)
chooseDate = dateformatter.string(from: pickerView.date)
}
@IBAction func okButtonClicked(_ sender: Any) {
delegate?.dataSend(data: chooseDate)
self.dismiss(animated: true, completion: nil)
print(chooseDate)
}
}
| true
|
30ae9cb4e5d259db5b28b5c777cdc11a68b338e1
|
Swift
|
Constantine1995/Weather-App
|
/Weather-App/Weather-App/Extensions/APIManagerProtocol+Extension.swift
|
UTF-8
| 2,444
| 2.875
| 3
|
[] |
no_license
|
//
// APIManagerProtocol+Extension.swift
// Weather-App
//
// Created by mac on 5/27/19.
// Copyright © 2019 mac. All rights reserved.
//
import Foundation
extension APIManagerProtocol {
func JSONTaskWith(request: URLRequest, completionHandler: @escaping JSONCompletionHandler) -> JSONTask {
let dataTask = session.dataTask(with: request) { (data, response, error) in
guard let HTTPResponse = response as? HTTPURLResponse else {
let userInfo = [
NSLocalizedDescriptionKey: NSLocalizedString("Missing HTTP Response", comment: "")
]
let error = NSError(domain: WeatherNetworkingErrorDomain, code: 100, userInfo: userInfo)
completionHandler(nil, nil, error)
return
}
if data == nil {
if let error = error {
completionHandler(nil, HTTPResponse, error)
}
} else {
switch HTTPResponse.statusCode {
case 200:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject]
completionHandler(json, HTTPResponse, nil)
} catch let error as NSError {
completionHandler(nil, HTTPResponse, error)
}
default:
print("We have got response status \(HTTPResponse.statusCode)")
}
}
}
return dataTask
}
func fetch<T>(request: URLRequest, parse: @escaping ([String: AnyObject]?) -> T?, completionHandler: @escaping (APIResult<T>) -> Void) {
let dataTask = JSONTaskWith(request: request) { (json, response, error) in
DispatchQueue.main.async {
guard let json = json else {
if let error = error {
completionHandler(.Failure(error))
}
return
}
if let value = parse(json) {
completionHandler(.Succes(value))
} else {
let error = NSError(domain: WeatherNetworkingErrorDomain, code: 200, userInfo: nil)
completionHandler(.Failure(error))
}
}
}
dataTask.resume()
}
}
| true
|
07233a0e9dafaedb87eb92f164895952ef7c418f
|
Swift
|
kandavel/cineaste-ios
|
/Cineaste/ViewController/Movies/SeenMovieCell.swift
|
UTF-8
| 1,049
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// SeenMovieCell.swift
// Cineaste
//
// Created by Felizia Bernutz on 12.05.18.
// Copyright © 2018 notimeforthat.org. All rights reserved.
//
import UIKit
class SeenMovieCell: UITableViewCell {
static let identifier = "SeenMovieCell"
@IBOutlet weak var background: UIView!
@IBOutlet weak var poster: UIImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var watchedDateLabel: UILabel!
func configure(with movie: Movie) {
background.backgroundColor = .cineCellBackground
poster.accessibilityIgnoresInvertColors = true
poster.loadingImage(from: movie.posterPath, in: .small)
title.text = movie.title
watchedDateLabel.text = movie.formattedWatchedDate
applyAccessibility(for: movie)
}
private func applyAccessibility(for movie: Movie) {
isAccessibilityElement = true
accessibilityLabel = movie.title
if let watchedDate = movie.formattedWatchedDate {
accessibilityLabel?.append(", \(watchedDate)")
}
}
}
| true
|
2378a70aa0ada8fb066888b2367e230255fcaf17
|
Swift
|
math-eww/Pendulum-Wave-Swift
|
/Loading.swift
|
UTF-8
| 5,493
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// Loading.swift
// Matt Saunders
//
// Created by Matt Saunders on 2015-06-24.
// Copyright (c) 2015 Matt Saunders. All rights reserved.
//
import Foundation
import UIKit
import Darwin
import QuartzCore
class Loading {
var numBalls = 20 // Number of balls
var ballRadius = 5 // Size of balls
var ballSpace = 5 // Space between balls?
var ballYTravel = 100 // How far up and down the balls go
var animationPosX = 50 // X position of entire animation
var ballColor = UIColor.blackColor().CGColor // Color of balls
var timeStep = 0 // Affects starting position of balls
// UI stuff
let containerView = UIView()
var circlesArr = Array<CAShapeLayer>()
// Animation updater display link
var updater = CADisplayLink()
var isAnimating = false
// Builds one ball
func drawCircle() -> CAShapeLayer {
var circle = CAShapeLayer()
var path = UIBezierPath()
path.addArcWithCenter(CGPoint(x: 30, y: 30), radius: CGFloat(ballRadius), startAngle: 0, endAngle: 180, clockwise: true)
circle.frame = CGRect(x: 15, y: 15, width: ballRadius, height: ballRadius)
circle.path = path.CGPath
circle.strokeColor = ballColor
circle.fillColor = ballColor
circle.lineWidth = 1.0
return circle
}
// Initializes all balls
func setupCircles() {
for var i=0; i<numBalls; i++ {
circlesArr.append(drawCircle())
containerView.layer.addSublayer(circlesArr[i])
}
}
// Animates the balls
@objc func animateBalls(sender: CADisplayLink) {
for var i=0; i<numBalls; i++ {
//Move balls to location getY and appropriate x pos
circlesArr[i].frame = CGRect(x: animationPosX + ballSpace * i, y: getY(i, t: timeStep), width: ballRadius, height: ballRadius)
}
timeStep++
}
// Returns the Y position for a given ball at a given time
func getY(i:Int, t:Int) -> Int {
return Int(Float(ballYTravel)/2 * (1 + sin((Float(timeStep) * (Float(i)/500 + 0.02)))))
}
// Builds and returns the entire view
func setupLoading() -> UIView {
// Initialize all balls and add to view
setupCircles()
// Set containerView size to fit balls
let width = animationPosX + (numBalls * ballRadius) + (ballSpace * (numBalls - 1))
containerView.bounds = CGRectMake(0, 0, CGFloat(width), CGFloat(ballYTravel) * 1.5)
// Setup animation caller and pause it
self.updater = CADisplayLink(target: self, selector: "animateBalls:")
self.updater.frameInterval = 1
self.updater.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
self.updater.paused = true
// Return the containing view
return containerView
}
func startLoad() {
self.isAnimating = true
self.updater.paused = false
/*
let positionAnimation = CABasicAnimation
let animationGroup = CAAnimationGroup()
animationGroup.repeatCount = Float.infinity
animationGroup.duration = 2.0
animationGroup.beginTime = [borderShapeLayer convertTime:CACurrentMediaTime() fromLayer:nil] + ring
animationGroup.timingFunction = [CAMediaTimingFunction functionWithControlPoints:.3:0:1:1]
animationGroup.animations = [scaleAnimation, opacityAnimation]
*/
/*
UIView.animateWithDuration(0.1, delay: 0, options: .Repeat, animations: {
self.animateBalls()
}, completion: nil)
*/
}
func stopLoad() {
self.isAnimating = false
self.updater.paused = true
}
//Reference code from inspiration
/*
private const NUM_BALL:int = 24;
private var loadingBall:Vector.<Shape> = new Vector.<Shape>(NUM_BALL);
private var timeStep:int = 0;
private const BALL_HEIGHT:int = 40;
public function animateBalls(e:Event):void
{
for (var i:int = 0; i < NUM_BALL; i++ )
{
loadingBall[i].graphics.clear();
loadingBall[i].graphics.beginFill(0x0B5F95);
loadingBall[i].graphics.drawCircle(455+5*i,getY(i,timeStep),2);
}
timeStep++;
}
public function getY(i:int, t:int):int
{
return 260 + BALL_HEIGHT/2 * (1 + Math.sin((timeStep * (i/500 + 0.02)) % 2*Math.PI));
}
*/
/*
var numBalls = 24; // numb balls
var timeStep = 0;
var ballYTravel = 100;
var ballRadius = 5;
var ballSpace = 20;
var animationPosX = 100;
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function drawBall(x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.stroke();
}
function animateBalls() {
clearCanvas();
for (var i = 0; i < numBalls; i++) {
drawBall(animationPosX + ballSpace * i, getY(i, timeStep), ballRadius);
}
timeStep++;
requestAnimationFrame(animateBalls);
}
function getY(i, timeStep) {
return 200 + ballYTravel / 2 * (Math.sin(timeStep * (i / 200 + 0.08)));
}
animateBalls();
*/
// (deprecated) Hides all balls
/*
func clearContainerView() {
var containerViewSubviewsArr = containerView.subviews
for view in containerViewSubviewsArr {
view.layer.hidden = true
}
}
*/
}
| true
|
9c5c666f3fe1e31690cf9c5306d56e6f14d56568
|
Swift
|
Bharatk2/FindYourMeal
|
/FreeMeals/FreeMeals/Extensions+Utilities/Cache.swift
|
UTF-8
| 702
| 3.375
| 3
|
[] |
no_license
|
//
// Cache.swift
// FreeMeals
//
// Created by Bharat Kumar on 8/18/21.
//
import Foundation
// MARK: - Cache Instructions
/* Cache helps us to avoid unnecesery reloading of data or fetching. This helps us to fetch the image by observing the url
It will help us to avoid making duplicate data. */
class Cache<Key: Hashable, Value> {
private var cache: [Key: Value] = [ : ]
private var queue = DispatchQueue(label: "Cache serial queue")
func cache(value: Value, for key: Key) {
queue.async {
self.cache[key] = value
}
}
func value(for key: Key) -> Value? {
queue.sync {
return self.cache[key]
}
}
}
| true
|
72e4172e1a7ea611f7d2e61bbd00430e64d353e4
|
Swift
|
MohamedNasser17/Nutrition-Analysis
|
/Nutrition Analysis/Modules/NutritionFacts/View/ViewController/NutritionFactsViewController.swift
|
UTF-8
| 1,567
| 2.578125
| 3
|
[] |
no_license
|
//
// NutritionFactsViewController.swift
// Nutrition Analysis
//
// Created by Mohamed Nasser on 27/06/2021.
//
import UIKit
import RxSwift
import RxCocoa
class NutritionFactsViewController: UIViewController {
// MARK: - UIViews
@IBOutlet private weak var totalButton: UIButton!
@IBOutlet private weak var dailyNutritionFactsTableView: UITableView!
// MARK: - Proprities
let disposeBag = DisposeBag()
var viewModel: NutritionFactsViewModelProtocol?
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupBinding()
viewModel?.fetchTotalNutritionFactsData()
}
}
// MARK: - Private UI Methods
extension NutritionFactsViewController {
private func setupUI() {
registerTableViewCells()
title = "Nutrition Facts"
}
private func registerTableViewCells() {
dailyNutritionFactsTableView.register(UITableViewCell.self,
forCellReuseIdentifier: "DailyNutritionFactsTableViewCell")
}
}
// MARK: - Private Binding Methods
extension NutritionFactsViewController {
private func setupBinding() {
bindTableViewDataSource()
}
private func bindTableViewDataSource() {
viewModel?.uiModel?.totalDailyNutrients
.bind(to: dailyNutritionFactsTableView.rx.items(cellIdentifier: "DailyNutritionFactsTableViewCell")) { (_, nutrition, cell) in
cell.textLabel?.text = nutrition
}.disposed(by: disposeBag)
}
}
| true
|
94087a906db2c5695a58666f9e074b4691286caf
|
Swift
|
omise/omise-ios
|
/OmiseSDK/PaymentInformation.Atome.swift
|
UTF-8
| 3,020
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public extension PaymentInformation {
var isAtome: Bool {
switch self {
case .atome: return true
default: return false
}
}
var atomeData: Atome? {
switch self {
case .atome(let data): return data
default: return nil
}
}
struct Atome: PaymentMethod {
public static var paymentMethodTypePrefix: String = OMSSourceTypeValue.atome.rawValue
public var type: String = OMSSourceTypeValue.atome.rawValue
/// The customers phone number. Contains only digits and has 10 or 11 characters
public let phoneNumber: String
public let name: String?
public let email: String?
public let items: [Item]
public let shippingAddress: ShippingAddress
private enum CodingKeys: String, CodingKey {
case name
case email
case phoneNumber = "phone_number"
case items = "items"
case shippingAddress = "shipping"
}
/// Creates a new Atome source with the given customer information
///
/// - Parameters:
/// - phoneNumber: The customers phone number
public init(phoneNumber: String, name: String? = nil, email: String? = nil, shippingAddress: ShippingAddress, items: [Item]) {
self.name = name
self.email = email
self.phoneNumber = phoneNumber
self.shippingAddress = shippingAddress
self.items = items
}
}
}
public extension PaymentInformation.Atome {
struct Item: Codable, Equatable {
public let sku: String
public let category: String?
public let name: String
public let quantity: Int
public let amount: Int64
public let itemUri: String?
public let imageUri: String?
public let brand: String?
private enum CodingKeys: String, CodingKey {
case sku
case amount
case name
case quantity
case category
case brand
case imageUri = "image_uri"
case itemUri = "item_uri"
}
}
struct ShippingAddress: Codable, Equatable {
public let country: String
public let city: String
public let postalCode: String
public let state: String
public let street1: String
public let street2: String
private enum CodingKeys: String, CodingKey {
case country
case city
case postalCode = "postal_code"
case state
case street1
case street2
}
init(country: String, city: String, postalCode: String, state: String, street1: String, street2: String) {
self.country = country
self.city = city
self.postalCode = postalCode
self.state = state
self.street1 = street1
self.street2 = street2
}
}
}
| true
|
1fd3e47bcbc7f5d1870752a4a0b234d1acc9a016
|
Swift
|
melaabd/Dubizzle-Movies
|
/DubizzleMovies/Controllers/Network/DecodableResponse.swift
|
UTF-8
| 644
| 2.71875
| 3
|
[] |
no_license
|
//
// DecodableResponse.swift
// Dubizzle-Movies-List_iOSApp
//
// Created by El-Abd on 12/23/19.
// Copyright © 2019 El-Abd. All rights reserved.
//
import Foundation
class DecodableResponse<T: Decodable>: ResponseProtocol {
// MARK: - ResponseProtocol properties
let request: RequestProtocol
let data: Result<Data>
// MARK: - Properties
lazy private(set) var decodedData: Result<T> = data.flatMap { Result<T>(jsonEncoded: $0) }
// MARK: - Initializer
required init(request: RequestProtocol, data: Result<Data>) {
self.request = request
self.data = data
}
}
| true
|
aec38dc564ff540aebc0db712d98edd4c42529b0
|
Swift
|
mr-araujo/h4x0s-news
|
/Shared/Views/DetailView.swift
|
UTF-8
| 364
| 2.578125
| 3
|
[] |
no_license
|
//
// DetailView.swift
// H4X0R News (iOS)
//
// Created by Murillo R. Araujo on 08/09/21.
//
import SwiftUI
struct DetailView: View {
let url: String?
var body: some View {
WebView(urlString: url)
}
}
struct DetailView_Previews: PreviewProvider {
static var previews: some View {
DetailView(url: "https://google.com")
}
}
| true
|
17cc89244c8ba55b9f3c1bbc75f8b11db2bd8c65
|
Swift
|
lucabelezal/Skeleton
|
/Modules/Networking/Networking/Source/Service/NetworkResponse.swift
|
UTF-8
| 898
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public enum NetworkResponse: Error {
case success
case authenticationError
case badRequest
case outdated
case failed
case noData
case unableToDecode
case connection
public var description: String {
switch self {
case .success:
return String()
case .authenticationError:
return "You need to be authenticated first."
case .badRequest:
return "Bad request"
case .outdated:
return "The url you requested is outdated."
case .failed:
return "Network request failed."
case .noData:
return "Response returned with no data to decode."
case .unableToDecode:
return "We could not decode the response."
case .connection:
return "Please check your network connection."
}
}
}
| true
|
e4d16f9b53826d5eae1e558e92478ee080144bc0
|
Swift
|
David-Paez/No-One-Left-A-Loan
|
/No One Left A-Loan/No One Left A-Loan/TabViews/ProfileView.swift
|
UTF-8
| 3,368
| 3.03125
| 3
|
[] |
no_license
|
//
// ProfileView.swift
// No One Left A-Loan
//
// Created by Leila Adaza on 9/26/20.
//
import SwiftUI
import CoreData
struct ProfileView: View {
@ObservedObject var studentModel:StudentModel
var body: some View {
VStack {
Color("barGray")
.edgesIgnoringSafeArea(.all)
.frame(height:1)
.overlay(Text("Profile").bold().padding(.bottom,30))
VStack(alignment: .center, spacing: 25) {
Image("profileIcon")
.resizable()
.scaledToFit()
.frame(height:200)
Button("Change Profile Picture") {
}
VStack(alignment: .center, spacing: 10) {
ProgressView(value: 0.25)
.padding(.horizontal, 20)
.accentColor(.blue)
Text("$2,500 / $10,000")
.font(.title2)
.foregroundColor(.white)
.padding(.horizontal, 20)
.background(Color.blue)
.cornerRadius(10)
}
VStack(alignment: .leading, spacing: 20) {
HStack {
Text("Username")
Text(studentModel.userName)
.foregroundColor(.gray)
}
NameView(studentModel: studentModel)
BioView(studentModel: studentModel)
AddressView(studentModel: studentModel)
SchoolView(studentModel: studentModel)
GradView(studentModel: studentModel)
Spacer()
}
.padding(.horizontal, 10)
}
}
}
}
struct ProfileView_Previews: PreviewProvider {
static var previews: some View {
ProfileView(studentModel: StudentModel()).environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
struct NameView: View {
@ObservedObject var studentModel: StudentModel
var body: some View {
HStack {
Text("Name")
Text(studentModel.firstName + " " + studentModel.lastName)
.foregroundColor(.gray)
}
}
}
struct BioView: View {
@ObservedObject var studentModel: StudentModel
var body: some View {
HStack {
Text("Bio")
Text(studentModel.biography)
.font(.subheadline)
.foregroundColor(.gray)
}
}
}
struct AddressView: View {
@ObservedObject var studentModel: StudentModel
var body: some View {
HStack {
Text("City, State")
Text(studentModel.address)
.foregroundColor(.gray)
}
}
}
struct GradView: View {
@ObservedObject var studentModel: StudentModel
var body: some View {
HStack {
Text("Graduation Year")
Text(studentModel.gradYear)
.foregroundColor(.gray)
}
}
}
struct SchoolView: View {
@ObservedObject var studentModel: StudentModel
var body: some View {
HStack {
Text("School")
Text(studentModel.school)
.foregroundColor(.gray)
}
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.