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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23e8cdce46ab9e4070e01df30b4a376b53adaf94
|
Swift
|
tuist/tuist
|
/Sources/TuistGraph/Models/LaunchArgument.swift
|
UTF-8
| 468
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
/// It represents an argument that is passed when running a scheme's action
public struct LaunchArgument: Equatable, Codable, Hashable {
// MARK: - Attributes
/// The name of the launch argument
public let name: String
/// Whether the argument is enabled or not
public let isEnabled: Bool
// MARK: - Init
public init(name: String, isEnabled: Bool) {
self.name = name
self.isEnabled = isEnabled
}
}
| true
|
11ab410745791bb510a1b1394d588d83eb253874
|
Swift
|
azureplus/FFProbe
|
/Sources/FFProbe/Types/MediaDuration.swift
|
UTF-8
| 2,214
| 3.515625
| 4
|
[
"MIT"
] |
permissive
|
public struct MediaDuration: RawRepresentable, ExpressibleByStringLiteral {
public let rawValue: Int
public let hours: Int
public let minutes: Int
public let seconds: Int
public static let unknown = MediaDuration(rawValue: -1)
public init(stringLiteral value: String) {
let parts = value.components(separatedBy: ":")
guard !parts.isEmpty else {
self = .unknown
return
}
if parts.count == 3 {
hours = Int(parts[0])!
minutes = Int(parts[1])!
seconds = Int(parts[2])!
} else if parts.count == 2 {
hours = 0
minutes = Int(parts[0])!
seconds = Int(parts[1])!
} else {
let secs = Int(Double(value)!)
let mins = secs / 60
hours = mins / 60
seconds = secs % 60
minutes = mins % 60
}
rawValue = seconds + (minutes * 60) + (hours * 60 * 60)
}
public init(rawValue: Int) {
self.rawValue = rawValue
seconds = rawValue % 60
let mins = rawValue / 60
hours = mins / 60
minutes = mins % 60
}
}
extension MediaDuration: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self.init(stringLiteral: try container.decode(String.self))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(description)
}
}
extension MediaDuration: Comparable, Equatable {
public static func < (lhs: MediaDuration, rhs: MediaDuration) -> Bool {
return lhs.rawValue < rhs.rawValue
}
public static func == (lhs: MediaDuration, rhs: MediaDuration) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension MediaDuration: CustomStringConvertible {
public var description: String {
var str = ""
if hours > 0 {
str += "\(hours):"
}
if hours > 0 || minutes > 0 {
str += String(format: "%02d:", minutes)
}
str += String(format: "%02d", seconds)
return str
}
}
| true
|
11242b9800e35248f62cdda993d5cbc1101bd3cb
|
Swift
|
Sage-Bionetworks/JsonModel-Swift
|
/Tests/JsonModelTests/AnyCodableTests.swift
|
UTF-8
| 10,993
| 3.046875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
//
// AnyCodableTests.swift
//
//
import XCTest
@testable import JsonModel
final class AnyCodableTests: XCTestCase {
func testAnyCodableDictionary() {
let input: [String : JsonSerializable] = [
"array" : ["cat", "dog", "duck"],
"dictionary" : ["a" : 1, "b" : "bat", "c" : true],
"bool" : true,
"double" : Double(1.234),
"integer" : Int(34),
"number" : NSNumber(value: 23),
"string" : "String",
]
let orderedKeys = ["string",
"number",
"integer",
"double",
"bool",
"array",
"dictionary"]
let anyDictionary = AnyCodableDictionary(input, orderedKeys: orderedKeys)
let factory = SerializationFactory.defaultFactory
let encoder = factory.createJSONEncoder()
(encoder as? OrderedJSONEncoder)?.shouldOrderKeys = true
let decoder = factory.createJSONDecoder()
do {
let jsonData = try encoder.encode(anyDictionary)
let jsonString = String(data: jsonData, encoding: .utf8)!
// The order of the keys should be the same as the `orderedKeys` and *not*
// in the order defined either using alphabetical sort or the `input` declaration.
let mappedOrder: [(index: String.Index, value: String) ] = orderedKeys.map {
guard let range = jsonString.range(of: $0) else {
XCTFail("Could not find \($0) in the json string")
return (jsonString.endIndex, "")
}
return (range.lowerBound, $0)
}.sorted(by: { $0.index < $1.index })
let actualOrder = mappedOrder.map { $0.value }
XCTAssertEqual(orderedKeys, actualOrder)
// Decode from the data and the dictionaries should match.
let object = try decoder.decode(AnyCodableDictionary.self, from: jsonData)
XCTAssertEqual(anyDictionary, object)
} catch {
XCTFail("Failed to decode/encode dictionary: \(error)")
}
}
func testDictionary_Encodable() {
let factory = SerializationFactory.defaultFactory
let encoder = factory.createJSONEncoder()
let decoder = factory.createJSONDecoder()
let now = Date()
var dateComponents = DateComponents()
dateComponents.day = 1
dateComponents.month = 6
let data = Data(base64Encoded: "ABCD")!
let uuid = UUID()
let url = URL(string: "http://test.example.org")!
let input: [String : Any] = [
"string" : "String",
"number" : NSNumber(value: 23),
"infinity" : Double.infinity,
"integer" : Int(34),
"double" : Double(1.234),
"bool" : true,
"null" : NSNull(),
"date" : now,
"dateComponents" : dateComponents,
"data" : data,
"uuid" : uuid,
"url" : url,
"array" : ["cat", "dog", "duck"],
"dictionary" : ["a" : 1, "b" : "bat", "c" : true] as [String : Any]
]
do {
encoder.dataEncodingStrategy = .base64
encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "+inf", negativeInfinity: "-inf", nan: "NaN")
let jsonData = try encoder.encodeDictionary(input)
guard let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String : Any]
else {
XCTFail("Encoded object is not a dictionary")
return
}
XCTAssertEqual("String", dictionary["string"] as? String)
XCTAssertEqual(23, dictionary["number"] as? Int)
XCTAssertEqual("+inf", dictionary["infinity"] as? String)
XCTAssertEqual(34, dictionary["integer"] as? Int)
XCTAssertEqual(1.234, dictionary["double"] as? Double)
XCTAssertEqual(true, dictionary["bool"] as? Bool)
XCTAssertNotNil(dictionary["null"] as? NSNull)
XCTAssertEqual(now.jsonObject() as? String, dictionary["date"] as? String)
XCTAssertEqual("06-01", dictionary["dateComponents"] as? String)
XCTAssertEqual(data.base64EncodedString(), dictionary["data"] as? String)
XCTAssertEqual(uuid.uuidString, dictionary["uuid"] as? String)
if let array = dictionary["array"] as? [String] {
XCTAssertEqual(["cat", "dog", "duck"], array)
} else {
XCTFail("Failed to encode array. \(String(describing: dictionary["array"]))")
}
if let subd = dictionary["dictionary"] as? [String : Any] {
XCTAssertEqual( 1, subd["a"] as? Int)
XCTAssertEqual("bat", subd["b"] as? String)
XCTAssertEqual(true, subd["c"] as? Bool)
} else {
XCTFail("Failed to encode dictionary. \(String(describing: dictionary["dictionary"]))")
}
// Test convert to object
let object = try decoder.decode(TestDecodable.self, from: dictionary)
XCTAssertEqual("String", object.string)
XCTAssertEqual(34, object.integer)
XCTAssertEqual(true, object.bool)
XCTAssertEqual(now.timeIntervalSinceReferenceDate, object.date.timeIntervalSinceReferenceDate, accuracy: 0.01)
XCTAssertEqual(uuid, object.uuid)
XCTAssertEqual(["cat", "dog", "duck"], object.array)
XCTAssertNil(object.null)
} catch let err {
XCTFail("Failed to decode/encode object: \(err)")
return
}
}
func testArray_Codable() {
let factory = SerializationFactory.defaultFactory
let encoder = factory.createJSONEncoder()
let decoder = factory.createJSONDecoder()
let now = Date()
var dateComponents = DateComponents()
dateComponents.day = 1
dateComponents.month = 6
let uuid = UUID()
let input: [Any] = [["string" : "String",
"integer" : NSNumber(value: 34),
"bool" : NSNumber(value:true),
"date" : now.jsonObject(),
"uuid" : uuid.uuidString,
"array" : ["cat", "dog", "duck"]]]
do {
guard let object = try decoder.decode([TestDecodable].self, from: input).first
else {
XCTFail("Failed to decode object")
return
}
XCTAssertEqual("String", object.string)
XCTAssertEqual(34, object.integer)
XCTAssertEqual(true, object.bool)
XCTAssertEqual(now.timeIntervalSinceReferenceDate, object.date.timeIntervalSinceReferenceDate, accuracy: 0.01)
XCTAssertEqual(uuid, object.uuid)
XCTAssertEqual(["cat", "dog", "duck"], object.array)
XCTAssertNil(object.null)
encoder.dataEncodingStrategy = .base64
encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "+inf", negativeInfinity: "-inf", nan: "NaN")
let jsonData = try encoder.encodeArray(input)
guard let array = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String: Any]],
let dictionary = array.first
else {
XCTFail("Encoded object is not a dictionary")
return
}
XCTAssertEqual("String", dictionary["string"] as? String)
XCTAssertEqual(34, dictionary["integer"] as? Int)
XCTAssertEqual(true, dictionary["bool"] as? Bool)
XCTAssertNotNil(dictionary["date"] as? String)
XCTAssertEqual(uuid.uuidString, dictionary["uuid"] as? String)
XCTAssertEqual(["cat", "dog", "duck"], dictionary["array"] as? [String])
} catch let err {
XCTFail("Failed to decode/encode object: \(err)")
return
}
}
func testEncodableToJsonElement_Object() {
let uuid = UUID()
let now = Date()
let expected: [String : JsonSerializable] = ["string" : "String",
"integer" : NSNumber(value: 34),
"bool" : NSNumber(value:true),
"date" : now.jsonObject(),
"uuid" : uuid.uuidString,
"array" : ["cat", "dog", "duck"]]
let test = TestDecodable(string: "String",
integer: 34,
uuid: uuid,
date: now,
bool: true,
array: ["cat", "dog", "duck"],
null: nil)
do {
let jsonElement = try test.jsonElement()
XCTAssertEqual(JsonElement.object(expected), jsonElement)
let dictionary = try test.jsonEncodedDictionary()
XCTAssertEqual(expected as NSDictionary, dictionary as NSDictionary)
let data = try test.jsonEncodedData()
let obj = try SerializationFactory.defaultFactory.createJSONDecoder().decode(TestDecodable.self, from: data)
XCTAssertEqual(test.string, obj.string)
XCTAssertEqual(test.integer, obj.integer)
XCTAssertEqual(test.uuid, obj.uuid)
XCTAssertEqual(test.date.timeIntervalSinceReferenceDate, obj.date.timeIntervalSinceReferenceDate, accuracy: 1)
XCTAssertEqual(test.bool, obj.bool)
XCTAssertEqual(test.array, obj.array)
XCTAssertEqual(test.null, obj.null)
} catch let err {
XCTFail("Failed to decode/encode object: \(err)")
return
}
}
func testEncodableToJsonElement_Int() {
do {
let test = 3
let jsonElement = try test.jsonElement()
XCTAssertEqual(JsonElement.integer(3), jsonElement)
} catch let err {
XCTFail("Failed to decode/encode object: \(err)")
return
}
}
}
struct TestDecodable : Codable {
let string: String
let integer: Int
let uuid: UUID
let date: Date
let bool: Bool
let array: [String]
let null: String?
}
| true
|
1a2b9bb25fab38fe378cd0af260f738ed3977cea
|
Swift
|
ypark12/QuaRoutine_iOSApp
|
/ViewControllers/Dashboard/RoutineViewController.swift
|
UTF-8
| 3,044
| 2.890625
| 3
|
[] |
no_license
|
//
// RoutineViewController.swift
// FoodTracker
//
// Created by Jane Appleseed on 10/17/16.
// Copyright © 2016 Apple Inc. All rights reserved.
//
import UIKit
import os.log
class RoutineViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate {
//MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var selectionControl: SelectionControl!
@IBOutlet weak var saveButton: UIBarButtonItem!
/*
This value is either passed by `RoutineTableViewController` in `prepare(for:sender:)`
or constructed as part of adding a new routine.
*/
var routine: Routine?
//Maintain streak if there was one already. Placeholder variable
var streak = 0
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field’s user input through delegate callbacks.
nameTextField.delegate = self
// Set up views if editing an existing Routine.
if let routine = routine {
navigationItem.title = routine.name
nameTextField.text = routine.name
selectionControl.selection = routine.weekdays
streak = routine.streak
}
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
navigationItem.title = nameTextField.text
}
//MARK: Navigation
@IBAction func cancel(_ sender: UIBarButtonItem) {
// Depending on style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways.
let isPresentingInAddRoutineMode = presentingViewController is UINavigationController
if isPresentingInAddRoutineMode {
dismiss(animated: true, completion: nil)
}
else if let owningNavigationController = navigationController{
owningNavigationController.popViewController(animated: true)
}
else {
fatalError("The RoutineViewController is not inside a navigation controller.")
}
}
// This method lets you configure a view controller before it's presented.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
// Configure the destination view controller only when the save button is pressed.
guard let button = sender as? UIBarButtonItem, button === saveButton else {
os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug)
return
}
let name = nameTextField.text ?? ""
let selection = selectionControl.selection
// Set the routine to be passed to RoutineTableViewController after the unwind segue.
routine = Routine(name: name, weekdays: selection, streak: streak)
}
}
| true
|
006237cba3aaee6c1a8dd686db46c6e69310d29a
|
Swift
|
BeaVDeveloper/Privat-Bank-Currency
|
/DB2/Common/Globals.swift
|
UTF-8
| 1,903
| 2.515625
| 3
|
[] |
no_license
|
//
// Globals.swift
// DB2
//
// Created by Yura Velko on 7/12/19.
// Copyright © 2019 Yura Velko. All rights reserved.
//
import Foundation
extension Date {
private static let dateFormatter = DateFormatter()
func formattedString() -> String {
Date.dateFormatter.dateFormat = "dd.MM.YYYY"
return Date.dateFormatter.string(from: self)
}
}
struct Globals {
static let rusNameDict = [
"AUD": "Австралийский Доллар",
"USD": "Доллар США",
"RUB": "Росийский Рубль",
"EUR": "Евро",
"JPY": "Японская Иена",
"CHF": "Швейцарский Франк",
"GBP": "Британский Фунт",
"PLZ": "Польский Злотый",
"SEK": "Шведская Крона",
"CAD": "Канадский Доллар",
"CZK": "Чешская Крона",
"DKK": "Датская Крона",
"ILS": "Новый Израильский Шекель",
"KZT": "Казахстанский Тенге",
"NOK": "Норвежская Крона",
"TMT": "Туркменский Манат",
"TRY": "Турецкая Лира",
"CNY": "Китайский Юань",
"HUF": "Венгерский Форинт",
"MLD": "Молдавский Лей",
"SGD": "Сингапурский Доллар",
"BYN": "Белорусский Рубль",
"AZN": "Азербайджанский Манат",
"GEL": "Грузинский Лари",
]
struct NotificationNames {
static let UpdateTableData = Notification.Name("UpdatePrivatData")
static let StartLoadingData = Notification.Name("StartLoadingData")
}
struct CellIdentifier {
static let privatBankCell = "privatBankCell"
static let nbuCell = "nbuCell"
}
}
| true
|
4d1e9b317de7f76cc0e5a4fd7741009ced4c77e6
|
Swift
|
mupacif/IOS
|
/03_Swift_fondamentaux/01_fondamentauxSwift/01_fondamentauxSwift/test.playground/Contents.swift
|
UTF-8
| 2,755
| 4.15625
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
let i=1
assert(i>0,"hoho")
//tuples
var (a,b) = (1,2)
//condition multiple
(2,4,6)<(2,4,8)
// Ternaire
let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
//range opérator
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
//Half-Open Range Operator
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
print("Person \(i + 1) is called \(names[i])")
}
//String
for character in "Dog!🐶".characters {
print(character)
}
// concaténation string
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)
// + += let exclamationMark: Character = "!"
//welcome.append(exclamationMark)
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a
//-*******************
for index in greeting.characters.indices {
print("\(greeting[index]) ")
}
//
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"
welcome.insert(contentsOf: " there".characters, at: welcome.index(before: welcome.endIndex))
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
//-***** méthode de classe String
let romeoAndJuliet = [
"Act 1 Scene 1: Verona, A public place",
"Act 1 Scene 2: Capulet's mansion",
"Act 1 Scene 3: A room in Capulet's mansion",
"Act 1 Scene 4: A street outside Capulet's mansion",
"Act 1 Scene 5: The Great Hall in Capulet's mansion",
"Act 2 Scene 1: Outside Capulet's mansion",
"Act 2 Scene 2: Capulet's orchard",
"Act 2 Scene 3: Outside Friar Lawrence's cell",
"Act 2 Scene 4: A street in Verona",
"Act 2 Scene 5: Capulet's mansion",
"Act 2 Scene 6: Friar Lawrence's cell"
]
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
act1SceneCount += 1
}
}
print("There are \(act1SceneCount) scenes in Act 1")
func insertion(tab:[Int],op:(Int,Int)->Bool={$0>$1})
{
var tmpTab = tab
var i = 0
for j in 1..<tmpTab.count
{
var key = tmpTab[j]
i=j-1
while i > -1 && op(tmpTab[i],key)
{
tmpTab[i+1]=tmpTab[i]
i=i-1
}
tmpTab[i+1]=key
}
print(tmpTab)
}
insertion(tab: [50,5,3,4]){$0<$1}
| true
|
fa366402374951ef9c7ba4ad3faf5a2217bd9a04
|
Swift
|
kk-laoguo/KKSwiftPractice
|
/SwiftStudy/U17Demo/U17Demo/Classes/Home/View/ReadTopBarView.swift
|
UTF-8
| 2,888
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// ReadTopBarView.swift
// U17Demo
//
// Created by zainguo on 2020/7/25.
// Copyright © 2020 zainguo. All rights reserved.
//
import UIKit
class ReadTopBarView: UIView {
lazy var backButton: UIButton = {
let backBtn = UIButton(type: .custom)
backBtn.setImage(UIImage(named: "nav_back_white"), for: .normal)
return backBtn
}()
lazy var titleLabel: UILabel = {
let lab = UILabel()
// lab.backgroundColor = .red
lab.textAlignment = .left
lab.textColor = .white
lab.font = .systemFont(ofSize: 18)
return lab
}()
lazy var downButton: UIButton = {
let downButton = UIButton(type: .system)
downButton.setImage(UIImage(named: "readerMenu_download")?.withRenderingMode(.alwaysOriginal), for: .normal)
return downButton
}()
lazy var screenshotButton: UIButton = {
let screenshotButton = UIButton(type: .system)
screenshotButton.setImage(UIImage(named: "readerMenu_clip")?.withRenderingMode(.alwaysOriginal), for: .normal)
return screenshotButton
}()
lazy var shareButton: UIButton = {
let shareButton = UIButton(type: .system)
shareButton.setImage(UIImage(named: "readerMenu_more")?.withRenderingMode(.alwaysOriginal), for: .normal)
return shareButton
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ReadTopBarView {
func setupUI() {
let blurEffect = UIBlurEffect(style: .dark)
// 创建一个承载模糊效果的视图
let blurView = UIVisualEffectView(effect: blurEffect)
addSubview(blurView)
blurView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
blurView.contentView.addSubview(backButton)
backButton.snp.makeConstraints { (make) in
make.width.height.equalTo(40)
make.left.centerY.equalToSuperview()
}
blurView.contentView.addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 50))
}
let stackV = UIStackView()
stackV.spacing = 0
stackV.alignment = .fill
stackV.distribution = .fillEqually
blurView.contentView.addSubview(stackV)
stackV.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: screenWidth - 140, bottom: 0, right: 0))
}
stackV.addArrangedSubview(downButton)
stackV.addArrangedSubview(screenshotButton)
stackV.addArrangedSubview(shareButton)
}
}
| true
|
e492a579820255319da49087e6e700fa17cd1dba
|
Swift
|
amoham37/Soup-Music-Player
|
/SoupMusicPlayer/MasterLyricTableViewController.swift
|
UTF-8
| 2,244
| 2.625
| 3
|
[] |
no_license
|
//
// MasterLyricTableViewController.swift
// SoupMusicPlayer
//
// Created by Ahmet Mohammed on 3/11/19.
// Copyright © 2019 Ahmet. All rights reserved.
//
import UIKit
class MasterLyricTableViewController: UITableViewController{
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let lyric = data[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = lyric.name
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier:"goRight", sender: indexPath)
}
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let lyric = data[indexPath.row]
let title = lyric.name
let message = "Album: " + lyric.albumname + "\n" + "Relesead: " + String(lyric.albumyear) + "\n" + "Artist: " + lyric.artist
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Okay", style: .default, handler: nil)
alertController.addAction(okayAction)
present(alertController, animated: true, completion: nil)
self.tableView.deselectRow(at: indexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let detailViewController = segue.destination as? DetailViewController {
if let indexPath = self.tableView.indexPathForSelectedRow {
detailViewController.lyric = data[indexPath.row]
}
}
}
}
| true
|
5d85207be7424ca095a0ac0cd47815d0b20e7a38
|
Swift
|
tunisij/Sports-Game-Finder
|
/Pluto/Invite.swift
|
UTF-8
| 1,159
| 2.828125
| 3
|
[] |
no_license
|
//
// Invite.swift
// Pluto
//
// Created by John Tunisi on 3/20/16.
// Copyright © 2016 John Tunisi. All rights reserved.
//
import Firebase
class Invite {
let key: String!
let ref: Firebase?
var teamKey: String!
var teamName: String!
var sender: String!
var recipient: String!
init(teamKey: String, teamName: String!, sender: String, recipient: String, key: String = "") {
self.key = key
self.teamKey = teamKey
self.teamName = teamName
self.sender = sender
self.recipient = recipient
self.ref = nil
}
init(snapshot: FDataSnapshot) {
key = snapshot.key
teamKey = snapshot.value["teamKey"] as! String
teamName = snapshot.value["teamName"] as! String
sender = snapshot.value["sender"] as! String
recipient = snapshot.value["recipient"] as! String
ref = snapshot.ref
}
func toAnyObject() -> AnyObject {
return [
"teamKey": teamKey,
"teamName": teamName,
"sender": sender,
"recipient": recipient
]
}
}
typealias Invites = [Invite]
| true
|
0afbb1a16e4256d341e3762c8a60c77ae2051df7
|
Swift
|
lighthola/MySwiftPractice
|
/PlayVideo/PlayVideo/PlayVideoCollectionViewFlowLayout.swift
|
UTF-8
| 847
| 2.546875
| 3
|
[] |
no_license
|
//
// PlayVideoCollectionViewFlowLayout.swift
// PlayVideo
//
// Created by Bevis Chen on 2016/10/14.
// Copyright © 2016年 Bevis Chen. All rights reserved.
//
import UIKit
class PlayVideoCollectionViewFlowLayout: UICollectionViewFlowLayout {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print("--\n PlayVideoCollectionViewFlowLayout Init Coder\n--")
baseInit()
}
private func baseInit() {
let margin = 0.0
minimumLineSpacing = 1
minimumInteritemSpacing = 0.0
let screenWidth = Double(UIScreen.main.bounds.size.width)
let maxCol = Double(1)
let width = (screenWidth - margin * (maxCol + 1)) / maxCol
let height = 220.0
itemSize = CGSize(width: width, height: height)
}
}
| true
|
9c3d7d300d7dc67f579de58f0b76f64fd39ed03e
|
Swift
|
celil/SwiftBox
|
/NSDate+Extension.swift
|
UTF-8
| 522
| 3.09375
| 3
|
[] |
no_license
|
//
// NSDate+Extension.swift
//
//
// Created by Celil Bozkurt on 9.12.2017.
//
import Foundation
extension Date {
// days function return days number from any NSDate.
func days(from date: Date) -> Int {
return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
}
// daysBetween function return days number between any two dates.
func daysBetween(start: Date, end: Date) -> Int {
return Calendar.current.dateComponents([.day], from: start, to: end).day!
}
}
| true
|
861ac4275a6bde1185ae124852d94137a391a323
|
Swift
|
kwdx/LeetCode-Practise
|
/Swift/784.字母大小写全排列.swift
|
UTF-8
| 1,410
| 3.703125
| 4
|
[] |
no_license
|
/*
* @lc app=leetcode.cn id=784 lang=swift
*
* [784] 字母大小写全排列
*/
// @lc code=start
class Solution {
func letterCasePermutation(_ s: String) -> [String] {
let n = s.count
var m = 0
let chars = Array(s)
for c in chars {
if !c.isNumber {
m += 1
}
}
var ans = [String]()
for mask in 0..<(1<<m) {
var str = ""
var k = 0
for j in 0..<n {
if chars[j].isNumber {
str.append(chars[j])
} else {
if mask & (1 << k) != 0 {
str.append(chars[j].uppercased())
} else {
str.append(chars[j].lowercased())
}
k += 1
}
}
ans.append(str)
}
return ans
}
}
// @lc code=end
func main() {
var s: String
var res: [String]
/**
输入:s = "a1b2"
输出:["a1b2", "a1B2", "A1b2", "A1B2"]
*/
s = "a1b2"
res = ["a1b2", "a1B2", "A1b2", "A1B2"].sorted()
assert(res == Solution().letterCasePermutation(s).sorted())
/**
输入: s = "3z4"
输出: ["3z4","3Z4"]
*/
s = "3z4"
res = ["3z4","3Z4"].sorted()
assert(res == Solution().letterCasePermutation(s).sorted())
}
| true
|
8b2401d90c056c37b09292a9263e3a664f84d43f
|
Swift
|
RusChr/RW_iOS12andSwift42ForBeginners
|
/DecodingJSON.playground/Contents.swift
|
UTF-8
| 750
| 3.140625
| 3
|
[] |
no_license
|
import UIKit
struct Image: Decodable {
enum Kind: String, Decodable {
case scene
case sticker
}
enum DecodingError: Error {
case missingFile
}
let name: String
let kind: Kind
let pngData: Data
}
extension Array where Element == Image {
init(fileName: String) throws {
guard let url = Bundle.main.url(forResource: fileName, withExtension: "json") else {
throw Image.DecodingError.missingFile
}
let decoder = JSONDecoder()
let data = try Data(contentsOf: url)
self = try decoder.decode([Image].self, from: data)
}
}
let images = try [Image](fileName: "images")
images.map { UIImage(data: $0.pngData) }
| true
|
9295c4a9804c351c39821ed618990796c55dd5eb
|
Swift
|
archergs/WatchKitImageZoom
|
/scrolltest WatchKit Extension/InterfaceController.swift
|
UTF-8
| 4,931
| 2.71875
| 3
|
[] |
no_license
|
//
// InterfaceController.swift
// scrolltest WatchKit Extension
//
// Created by Will Bishop on 9/2/18.
// Copyright © 2018 Will Bishop. All rights reserved.
//
import WatchKit
import Foundation
import SpriteKit
class InterfaceController: WKInterfaceController, WKCrownDelegate {
var zoomLevel: CGFloat = 1
var previous = CGPoint()
let scene = SKScene(fileNamed: "MyScene")
@IBOutlet var skInterface: WKInterfaceSKScene!
var imageNode = SKSpriteNode()
let cameraNode = SKCameraNode()
override func awake(withContext context: Any?) {
super.awake(withContext: context)
cameraNode.position = CGPoint(x: WKInterfaceDevice.current().screenBounds.width / 2, y: WKInterfaceDevice.current().screenBounds.height / 2)
scene?.addChild(cameraNode)
scene?.camera = cameraNode
// Present the scene
scene?.children.forEach {node in
if node.name == "image"{
cameraNode.position = node.position
if let shape = node as? SKSpriteNode{
imageNode = shape
let image = UIImage(named: "comic")!
let tex = SKTexture(image: image)
imageNode.run(SKAction.setTexture(tex))
let newSize = CGSize(width: WKInterfaceDevice.current().screenBounds.width, height: image.size.height)
imageNode.run(SKAction.resize(toWidth: newSize.width, height: newSize.height * (WKInterfaceDevice.current().screenBounds.width / image.size.width), duration: 0))
}
}
}
self.skInterface.presentScene(scene)
// Use a preferredFramesPerSecond that will maintain consistent frame rate
self.skInterface.preferredFramesPerSecond = 30
crownSequencer.delegate = self
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
crownSequencer.focus()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
@IBAction func didPan(_ sender: WKPanGestureRecognizer) {
if(sender.state == .ended)
{
previous = CGPoint()
} else{
var translation = sender.translationInObject()
translation.y *= -1 //Panning to the right would make it go left, need to * -1
translation.x = translation.x * cameraNode.xScale
translation.y = translation.y * cameraNode.yScale
print((cameraNode.frame.maxX - imageNode.frame.maxX) + (imageNode.frame.width / 2) * zoomLevel)
if ((cameraNode.frame.minX - imageNode.frame.minX) - (imageNode.frame.width / 2) * zoomLevel) > 0{
if (cameraNode.frame.maxX - imageNode.frame.maxX) + (imageNode.frame.width / 2) * zoomLevel < 0{
cameraNode.position.x -= translation.x - self.previous.x
} else{
cameraNode.position.x = imageNode.frame.maxX - (imageNode.frame.width / 2) * zoomLevel
}
} else{
cameraNode.position.x = imageNode.frame.minX + (imageNode.frame.width / 2) * zoomLevel //Stick to left
}
if (cameraNode.frame.minY - imageNode.frame.minY) - (imageNode.frame.width / 2) * zoomLevel > 0{
if ((cameraNode.frame.maxY - imageNode.frame.maxY) + (imageNode.frame.width / 2) * zoomLevel) < 0{
cameraNode.position.y -= translation.y - self.previous.y
} else{
cameraNode.position.y = imageNode.frame.maxY - (imageNode.frame.width / 2) * zoomLevel - 0.1
}
} else{
cameraNode.position.y = imageNode.frame.minY + (imageNode.frame.width / 2) * zoomLevel
}
if (cameraNode.frame.minY - imageNode.frame.minY) - (imageNode.frame.width / 2) * zoomLevel < 1{
print("Equal")
cameraNode.position.y = imageNode.frame.minY + (imageNode.frame.width / 2) * zoomLevel + 0.1
}
self.previous = translation
}
}
func crownDidRotate(_ crownSequencer: WKCrownSequencer?, rotationalDelta: Double) {
if zoomLevel > 1{
zoomLevel = 1
}
print(zoomLevel)
if rotationalDelta < 0 && zoomLevel <= 1{ //Zoom out
zoomLevel += 0.01 * zoomLevel
let zoomInAction = SKAction.scale(to: zoomLevel, duration: 0)
cameraNode.run(zoomInAction)
}
if rotationalDelta > 0{ //Zoom in
zoomLevel -= 0.01 * zoomLevel
let zoomInAction = SKAction.scale(to: zoomLevel, duration: 0)
cameraNode.run(zoomInAction)
}
}
}
extension CGPoint{
static func +=(left: CGPoint, right: CGPoint) -> CGPoint{
var copy = left
copy.x += right.x
copy.y += right.y
return copy
}
static func -=(left: CGPoint, right: CGPoint) -> CGPoint{
var copy = left
copy.x -= right.x
copy.y -= right.y
return copy
}
static func -(left: CGPoint, right: CGPoint) -> CGPoint{
var copy = left
copy.x -= right.x
copy.y -= right.y
return copy
}
static func -(left: CGPoint, right: CGFloat) -> CGPoint{
var copy = left
copy.x -= right
copy.y -= right
return copy
}
static func +(left: CGPoint, right: CGPoint) -> CGPoint{
var copy = left
copy.x += right.x
copy.y += right.y
return copy
}
}
| true
|
147591971593e9542ac7e8e6e1e576b4ce4e8d07
|
Swift
|
freemiumdev/FBAnnotationClusteringSwift
|
/Pod/Classes/FBAnnotationClusterTemplate.swift
|
UTF-8
| 1,108
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
//
// FBAnnotationClusterTemplate.swift
// FBAnnotationClusteringSwift
//
// Created by Antoine Lamy on 23/9/2016.
// Copyright (c) 2016 Antoine Lamy. All rights reserved.
//
import Foundation
public enum FBAnnotationClusterDisplayMode {
case SolidColor(sideLength: CGFloat, color: UIColor)
case Image(imageName: String)
}
public struct FBAnnotationClusterTemplate {
let range: Range<Int>?
let displayMode: FBAnnotationClusterDisplayMode
public var borderWidth: CGFloat = 0
public var fontSize: CGFloat = 15
public var fontName: String?
public var font: UIFont? {
if let fontName = fontName {
return UIFont(name: fontName, size: fontSize)
} else {
return UIFont.boldSystemFont(ofSize: fontSize)
}
}
public init(range: Range<Int>?, displayMode: FBAnnotationClusterDisplayMode) {
self.range = range
self.displayMode = displayMode
}
public init (range: Range<Int>?, sideLength: CGFloat) {
self.init(range: range, displayMode: .SolidColor(sideLength: sideLength,
color: UIColor(red:0.11, green:0.70, blue:0.42, alpha:1.00)))
}
}
| true
|
0d4255a12d1a98d515a137b203d6bbdb85ad667c
|
Swift
|
WowbaggersLiquidLunch/vapor-take-home
|
/Sources/App/Controllers/ArtistController.swift
|
UTF-8
| 1,134
| 3.28125
| 3
|
[] |
no_license
|
import Vapor
/// A controller for artist-related endpoints.
final class ArtistController {
/// Searches for an artist as requested.
/// - Parameter request: The request to search the artist.
/// - Returns: A future instance of `Artists`.
func searchArtist(_ request: Request) throws -> Future<Artists> {
let artistString = try request.query.get(String.self, at: "q")
let service = try request.make(ArtistService.self)
return try service.searchArtist(artist: artistString, on: request)
}
/// Searches for songs by title and artist ID as specified in the given request.
/// - Parameter request: The given request that specifies the song title and the artist's ID.
/// - Returns: A future instance of `Songs`.
func searchSongs(_ request: Request) throws -> Future<Songs> {
let artistID = try request.parameters.next(Int.self)
let songTitle = try request.query.get(String.self, at: "q")
let service = try request.make(ArtistService.self)
return try service.searchSongs(title: songTitle, byArtistID: artistID, on: request)
}
}
| true
|
ac652321261c4611d7804b4613174216411d8d7e
|
Swift
|
apple/FHIRModels
|
/Sources/ModelsR5/ChargeItemDefinition.swift
|
UTF-8
| 21,656
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ChargeItemDefinition.swift
// HealthSoftware
//
// Generated from FHIR 5.0.0 (http://hl7.org/fhir/StructureDefinition/ChargeItemDefinition)
// Copyright 2023 Apple Inc.
//
// 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 FMCore
/**
Definition of properties and rules about how the price and the applicability of a ChargeItem can be determined.
The ChargeItemDefinition resource provides the properties that apply to the (billing) codes necessary to calculate
costs and prices. The properties may differ largely depending on type and realm, therefore this resource gives only a
rough structure and requires profiling for each type of billing code system.
*/
open class ChargeItemDefinition: DomainResource {
override open class var resourceType: ResourceType { return .chargeItemDefinition }
/// All possible types for "versionAlgorithm[x]"
public enum VersionAlgorithmX: Hashable {
case coding(Coding)
case string(FHIRPrimitive<FHIRString>)
}
/// Canonical identifier for this charge item definition, represented as a URI (globally unique)
public var url: FHIRPrimitive<FHIRURI>?
/// Additional identifier for the charge item definition
public var identifier: [Identifier]?
/// Business version of the charge item definition
public var version: FHIRPrimitive<FHIRString>?
/// How to compare versions
/// One of `versionAlgorithm[x]`
public var versionAlgorithm: VersionAlgorithmX?
/// Name for this charge item definition (computer friendly)
public var name: FHIRPrimitive<FHIRString>?
/// Name for this charge item definition (human friendly)
public var title: FHIRPrimitive<FHIRString>?
/// Underlying externally-defined charge item definition
public var derivedFromUri: [FHIRPrimitive<FHIRURI>]?
/// A larger definition of which this particular definition is a component or step
public var partOf: [FHIRPrimitive<Canonical>]?
/// Completed or terminated request(s) whose function is taken by this new request
public var replaces: [FHIRPrimitive<Canonical>]?
/// The current state of the ChargeItemDefinition.
public var status: FHIRPrimitive<PublicationStatus>
/// For testing purposes, not real usage
public var experimental: FHIRPrimitive<FHIRBool>?
/// Date last changed
public var date: FHIRPrimitive<DateTime>?
/// Name of the publisher/steward (organization or individual)
public var publisher: FHIRPrimitive<FHIRString>?
/// Contact details for the publisher
public var contact: [ContactDetail]?
/// Natural language description of the charge item definition
public var description_fhir: FHIRPrimitive<FHIRString>?
/// The context that the content is intended to support
public var useContext: [UsageContext]?
/// Intended jurisdiction for charge item definition (if applicable)
public var jurisdiction: [CodeableConcept]?
/// Why this charge item definition is defined
public var purpose: FHIRPrimitive<FHIRString>?
/// Use and/or publishing restrictions
public var copyright: FHIRPrimitive<FHIRString>?
/// Copyright holder and year(s)
public var copyrightLabel: FHIRPrimitive<FHIRString>?
/// When the charge item definition was approved by publisher
public var approvalDate: FHIRPrimitive<FHIRDate>?
/// When the charge item definition was last reviewed by the publisher
public var lastReviewDate: FHIRPrimitive<FHIRDate>?
/// Billing code or product type this definition applies to
public var code: CodeableConcept?
/// Instances this definition applies to
public var instance: [Reference]?
/// Whether or not the billing code is applicable
public var applicability: [ChargeItemDefinitionApplicability]?
/// Group of properties which are applicable under the same conditions
public var propertyGroup: [ChargeItemDefinitionPropertyGroup]?
/// Designated initializer taking all required properties
public init(status: FHIRPrimitive<PublicationStatus>) {
self.status = status
super.init()
}
/// Convenience initializer
public convenience init(
applicability: [ChargeItemDefinitionApplicability]? = nil,
approvalDate: FHIRPrimitive<FHIRDate>? = nil,
code: CodeableConcept? = nil,
contact: [ContactDetail]? = nil,
contained: [ResourceProxy]? = nil,
copyright: FHIRPrimitive<FHIRString>? = nil,
copyrightLabel: FHIRPrimitive<FHIRString>? = nil,
date: FHIRPrimitive<DateTime>? = nil,
derivedFromUri: [FHIRPrimitive<FHIRURI>]? = nil,
description_fhir: FHIRPrimitive<FHIRString>? = nil,
experimental: FHIRPrimitive<FHIRBool>? = nil,
`extension`: [Extension]? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
identifier: [Identifier]? = nil,
implicitRules: FHIRPrimitive<FHIRURI>? = nil,
instance: [Reference]? = nil,
jurisdiction: [CodeableConcept]? = nil,
language: FHIRPrimitive<FHIRString>? = nil,
lastReviewDate: FHIRPrimitive<FHIRDate>? = nil,
meta: Meta? = nil,
modifierExtension: [Extension]? = nil,
name: FHIRPrimitive<FHIRString>? = nil,
partOf: [FHIRPrimitive<Canonical>]? = nil,
propertyGroup: [ChargeItemDefinitionPropertyGroup]? = nil,
publisher: FHIRPrimitive<FHIRString>? = nil,
purpose: FHIRPrimitive<FHIRString>? = nil,
replaces: [FHIRPrimitive<Canonical>]? = nil,
status: FHIRPrimitive<PublicationStatus>,
text: Narrative? = nil,
title: FHIRPrimitive<FHIRString>? = nil,
url: FHIRPrimitive<FHIRURI>? = nil,
useContext: [UsageContext]? = nil,
version: FHIRPrimitive<FHIRString>? = nil,
versionAlgorithm: VersionAlgorithmX? = nil
) {
self.init(status: status)
self.applicability = applicability
self.approvalDate = approvalDate
self.code = code
self.contact = contact
self.contained = contained
self.copyright = copyright
self.copyrightLabel = copyrightLabel
self.date = date
self.derivedFromUri = derivedFromUri
self.description_fhir = description_fhir
self.experimental = experimental
self.`extension` = `extension`
self.id = id
self.identifier = identifier
self.implicitRules = implicitRules
self.instance = instance
self.jurisdiction = jurisdiction
self.language = language
self.lastReviewDate = lastReviewDate
self.meta = meta
self.modifierExtension = modifierExtension
self.name = name
self.partOf = partOf
self.propertyGroup = propertyGroup
self.publisher = publisher
self.purpose = purpose
self.replaces = replaces
self.text = text
self.title = title
self.url = url
self.useContext = useContext
self.version = version
self.versionAlgorithm = versionAlgorithm
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case applicability
case approvalDate; case _approvalDate
case code
case contact
case copyright; case _copyright
case copyrightLabel; case _copyrightLabel
case date; case _date
case derivedFromUri; case _derivedFromUri
case description_fhir = "description"; case _description_fhir = "_description"
case experimental; case _experimental
case identifier
case instance
case jurisdiction
case lastReviewDate; case _lastReviewDate
case name; case _name
case partOf; case _partOf
case propertyGroup
case publisher; case _publisher
case purpose; case _purpose
case replaces; case _replaces
case status; case _status
case title; case _title
case url; case _url
case useContext
case version; case _version
case versionAlgorithmCoding
case versionAlgorithmString; case _versionAlgorithmString
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Decode all our properties
self.applicability = try [ChargeItemDefinitionApplicability](from: _container, forKeyIfPresent: .applicability)
self.approvalDate = try FHIRPrimitive<FHIRDate>(from: _container, forKeyIfPresent: .approvalDate, auxiliaryKey: ._approvalDate)
self.code = try CodeableConcept(from: _container, forKeyIfPresent: .code)
self.contact = try [ContactDetail](from: _container, forKeyIfPresent: .contact)
self.copyright = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .copyright, auxiliaryKey: ._copyright)
self.copyrightLabel = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .copyrightLabel, auxiliaryKey: ._copyrightLabel)
self.date = try FHIRPrimitive<DateTime>(from: _container, forKeyIfPresent: .date, auxiliaryKey: ._date)
self.derivedFromUri = try [FHIRPrimitive<FHIRURI>](from: _container, forKeyIfPresent: .derivedFromUri, auxiliaryKey: ._derivedFromUri)
self.description_fhir = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .description_fhir, auxiliaryKey: ._description_fhir)
self.experimental = try FHIRPrimitive<FHIRBool>(from: _container, forKeyIfPresent: .experimental, auxiliaryKey: ._experimental)
self.identifier = try [Identifier](from: _container, forKeyIfPresent: .identifier)
self.instance = try [Reference](from: _container, forKeyIfPresent: .instance)
self.jurisdiction = try [CodeableConcept](from: _container, forKeyIfPresent: .jurisdiction)
self.lastReviewDate = try FHIRPrimitive<FHIRDate>(from: _container, forKeyIfPresent: .lastReviewDate, auxiliaryKey: ._lastReviewDate)
self.name = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .name, auxiliaryKey: ._name)
self.partOf = try [FHIRPrimitive<Canonical>](from: _container, forKeyIfPresent: .partOf, auxiliaryKey: ._partOf)
self.propertyGroup = try [ChargeItemDefinitionPropertyGroup](from: _container, forKeyIfPresent: .propertyGroup)
self.publisher = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .publisher, auxiliaryKey: ._publisher)
self.purpose = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .purpose, auxiliaryKey: ._purpose)
self.replaces = try [FHIRPrimitive<Canonical>](from: _container, forKeyIfPresent: .replaces, auxiliaryKey: ._replaces)
self.status = try FHIRPrimitive<PublicationStatus>(from: _container, forKey: .status, auxiliaryKey: ._status)
self.title = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .title, auxiliaryKey: ._title)
self.url = try FHIRPrimitive<FHIRURI>(from: _container, forKeyIfPresent: .url, auxiliaryKey: ._url)
self.useContext = try [UsageContext](from: _container, forKeyIfPresent: .useContext)
self.version = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .version, auxiliaryKey: ._version)
var _t_versionAlgorithm: VersionAlgorithmX? = nil
if let versionAlgorithmString = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .versionAlgorithmString, auxiliaryKey: ._versionAlgorithmString) {
if _t_versionAlgorithm != nil {
throw DecodingError.dataCorruptedError(forKey: .versionAlgorithmString, in: _container, debugDescription: "More than one value provided for \"versionAlgorithm\"")
}
_t_versionAlgorithm = .string(versionAlgorithmString)
}
if let versionAlgorithmCoding = try Coding(from: _container, forKeyIfPresent: .versionAlgorithmCoding) {
if _t_versionAlgorithm != nil {
throw DecodingError.dataCorruptedError(forKey: .versionAlgorithmCoding, in: _container, debugDescription: "More than one value provided for \"versionAlgorithm\"")
}
_t_versionAlgorithm = .coding(versionAlgorithmCoding)
}
self.versionAlgorithm = _t_versionAlgorithm
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try applicability?.encode(on: &_container, forKey: .applicability)
try approvalDate?.encode(on: &_container, forKey: .approvalDate, auxiliaryKey: ._approvalDate)
try code?.encode(on: &_container, forKey: .code)
try contact?.encode(on: &_container, forKey: .contact)
try copyright?.encode(on: &_container, forKey: .copyright, auxiliaryKey: ._copyright)
try copyrightLabel?.encode(on: &_container, forKey: .copyrightLabel, auxiliaryKey: ._copyrightLabel)
try date?.encode(on: &_container, forKey: .date, auxiliaryKey: ._date)
try derivedFromUri?.encode(on: &_container, forKey: .derivedFromUri, auxiliaryKey: ._derivedFromUri)
try description_fhir?.encode(on: &_container, forKey: .description_fhir, auxiliaryKey: ._description_fhir)
try experimental?.encode(on: &_container, forKey: .experimental, auxiliaryKey: ._experimental)
try identifier?.encode(on: &_container, forKey: .identifier)
try instance?.encode(on: &_container, forKey: .instance)
try jurisdiction?.encode(on: &_container, forKey: .jurisdiction)
try lastReviewDate?.encode(on: &_container, forKey: .lastReviewDate, auxiliaryKey: ._lastReviewDate)
try name?.encode(on: &_container, forKey: .name, auxiliaryKey: ._name)
try partOf?.encode(on: &_container, forKey: .partOf, auxiliaryKey: ._partOf)
try propertyGroup?.encode(on: &_container, forKey: .propertyGroup)
try publisher?.encode(on: &_container, forKey: .publisher, auxiliaryKey: ._publisher)
try purpose?.encode(on: &_container, forKey: .purpose, auxiliaryKey: ._purpose)
try replaces?.encode(on: &_container, forKey: .replaces, auxiliaryKey: ._replaces)
try status.encode(on: &_container, forKey: .status, auxiliaryKey: ._status)
try title?.encode(on: &_container, forKey: .title, auxiliaryKey: ._title)
try url?.encode(on: &_container, forKey: .url, auxiliaryKey: ._url)
try useContext?.encode(on: &_container, forKey: .useContext)
try version?.encode(on: &_container, forKey: .version, auxiliaryKey: ._version)
if let _enum = versionAlgorithm {
switch _enum {
case .string(let _value):
try _value.encode(on: &_container, forKey: .versionAlgorithmString, auxiliaryKey: ._versionAlgorithmString)
case .coding(let _value):
try _value.encode(on: &_container, forKey: .versionAlgorithmCoding)
}
}
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? ChargeItemDefinition else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return applicability == _other.applicability
&& approvalDate == _other.approvalDate
&& code == _other.code
&& contact == _other.contact
&& copyright == _other.copyright
&& copyrightLabel == _other.copyrightLabel
&& date == _other.date
&& derivedFromUri == _other.derivedFromUri
&& description_fhir == _other.description_fhir
&& experimental == _other.experimental
&& identifier == _other.identifier
&& instance == _other.instance
&& jurisdiction == _other.jurisdiction
&& lastReviewDate == _other.lastReviewDate
&& name == _other.name
&& partOf == _other.partOf
&& propertyGroup == _other.propertyGroup
&& publisher == _other.publisher
&& purpose == _other.purpose
&& replaces == _other.replaces
&& status == _other.status
&& title == _other.title
&& url == _other.url
&& useContext == _other.useContext
&& version == _other.version
&& versionAlgorithm == _other.versionAlgorithm
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(applicability)
hasher.combine(approvalDate)
hasher.combine(code)
hasher.combine(contact)
hasher.combine(copyright)
hasher.combine(copyrightLabel)
hasher.combine(date)
hasher.combine(derivedFromUri)
hasher.combine(description_fhir)
hasher.combine(experimental)
hasher.combine(identifier)
hasher.combine(instance)
hasher.combine(jurisdiction)
hasher.combine(lastReviewDate)
hasher.combine(name)
hasher.combine(partOf)
hasher.combine(propertyGroup)
hasher.combine(publisher)
hasher.combine(purpose)
hasher.combine(replaces)
hasher.combine(status)
hasher.combine(title)
hasher.combine(url)
hasher.combine(useContext)
hasher.combine(version)
hasher.combine(versionAlgorithm)
}
}
/**
Whether or not the billing code is applicable.
Expressions that describe applicability criteria for the billing code.
*/
open class ChargeItemDefinitionApplicability: BackboneElement {
/// Boolean-valued expression
public var condition: Expression?
/// When the charge item definition is expected to be used
public var effectivePeriod: Period?
/// Reference to / quotation of the external source of the group of properties
public var relatedArtifact: RelatedArtifact?
/// Designated initializer taking all required properties
override public init() {
super.init()
}
/// Convenience initializer
public convenience init(
condition: Expression? = nil,
effectivePeriod: Period? = nil,
`extension`: [Extension]? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
modifierExtension: [Extension]? = nil,
relatedArtifact: RelatedArtifact? = nil
) {
self.init()
self.condition = condition
self.effectivePeriod = effectivePeriod
self.`extension` = `extension`
self.id = id
self.modifierExtension = modifierExtension
self.relatedArtifact = relatedArtifact
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case condition
case effectivePeriod
case relatedArtifact
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Decode all our properties
self.condition = try Expression(from: _container, forKeyIfPresent: .condition)
self.effectivePeriod = try Period(from: _container, forKeyIfPresent: .effectivePeriod)
self.relatedArtifact = try RelatedArtifact(from: _container, forKeyIfPresent: .relatedArtifact)
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try condition?.encode(on: &_container, forKey: .condition)
try effectivePeriod?.encode(on: &_container, forKey: .effectivePeriod)
try relatedArtifact?.encode(on: &_container, forKey: .relatedArtifact)
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? ChargeItemDefinitionApplicability else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return condition == _other.condition
&& effectivePeriod == _other.effectivePeriod
&& relatedArtifact == _other.relatedArtifact
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(condition)
hasher.combine(effectivePeriod)
hasher.combine(relatedArtifact)
}
}
/**
Group of properties which are applicable under the same conditions.
Group of properties which are applicable under the same conditions. If no applicability rules are established for the
group, then all properties always apply.
*/
open class ChargeItemDefinitionPropertyGroup: BackboneElement {
/// Conditions under which the priceComponent is applicable
public var applicability: [ChargeItemDefinitionApplicability]?
/// Components of total line item price
public var priceComponent: [MonetaryComponent]?
/// Designated initializer taking all required properties
override public init() {
super.init()
}
/// Convenience initializer
public convenience init(
applicability: [ChargeItemDefinitionApplicability]? = nil,
`extension`: [Extension]? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
modifierExtension: [Extension]? = nil,
priceComponent: [MonetaryComponent]? = nil
) {
self.init()
self.applicability = applicability
self.`extension` = `extension`
self.id = id
self.modifierExtension = modifierExtension
self.priceComponent = priceComponent
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case applicability
case priceComponent
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Decode all our properties
self.applicability = try [ChargeItemDefinitionApplicability](from: _container, forKeyIfPresent: .applicability)
self.priceComponent = try [MonetaryComponent](from: _container, forKeyIfPresent: .priceComponent)
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try applicability?.encode(on: &_container, forKey: .applicability)
try priceComponent?.encode(on: &_container, forKey: .priceComponent)
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? ChargeItemDefinitionPropertyGroup else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return applicability == _other.applicability
&& priceComponent == _other.priceComponent
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(applicability)
hasher.combine(priceComponent)
}
}
| true
|
3057d7c416ef0456c646e744fbdbedf06f00cf14
|
Swift
|
tgaul/Kotoba
|
/code/Kotoba/WordListStore.swift
|
UTF-8
| 1,470
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//
// WordList.swift
// Words
//
// Created by Will Hains on 2016-06-05.
// Copyright © 2016 Will Hains. All rights reserved.
//
import UIKit
/// Choices for where to store the word list.
enum WordListStore
{
case local
case iCloud
var data: WordListDataSource
{
switch self
{
case .local: return UserDefaults(suiteName: APP_GROUP_ID)!
case .iCloud: return NSUbiquitousKeyValueStore.default;
}
}
func synchroniseStores()
{
// Merge local history with iCloud history
debugLog("Synchronise/merge local and iCloud word stores")
// TODO: Code duplicated above.
var local: WordListStrings = UserDefaults(suiteName: APP_GROUP_ID)!
var cloud: WordListStrings = NSUbiquitousKeyValueStore.default
debugLog("add: BEFORE local=\(local.wordStrings.first ?? "")..\(local.wordStrings.last ?? "")")
debugLog("add: BEFORE cloud=\(cloud.wordStrings.first ?? "")..\(cloud.wordStrings.last ?? "")")
for word in local.wordStrings where !cloud.wordStrings.contains(word)
{
cloud.wordStrings.insert(word, at: 0)
}
local.wordStrings = cloud.wordStrings
debugLog("add: AFTER local=\(local.wordStrings.first ?? "")..\(local.wordStrings.last ?? "")")
debugLog("add: AFTER cloud=\(cloud.wordStrings.first ?? "")..\(cloud.wordStrings.last ?? "")")
}
}
/// Current selection of word list store.
var wordListStore: WordListStore
{
get { NSUbiquitousKeyValueStore.iCloudEnabledInSettings ? .iCloud : .local }
set { newValue.synchroniseStores() }
}
| true
|
531b60055ddef6f6648663fdc6876d0a72069c4b
|
Swift
|
TeaDoan/Notever
|
/Note/Data/UIImage+Local.swift
|
UTF-8
| 1,177
| 2.890625
| 3
|
[] |
no_license
|
//
// UIImage+Local.swift
// Camma
//
// Created by Steve Uffelman on 8/21/17.
// Copyright © 2017 Steve Uffelman. All rights reserved.
//
import UIKit
extension UIImage {
class func imageFor(_ path: URL) -> UIImage? {
do {
let data = try Data(contentsOf: path)
return UIImage(data: data)
} catch let err {
print(err)
return nil
}
}
class func originalImagePath(for guid: String) -> URL {
let documentsDir = FileManager.default.documentsDirectory()
return documentsDir.appendingPathComponent("\(guid).jpg")
}
class func thumbnailPath(for guid: String) -> URL {
let documentsDir = FileManager.default.documentsDirectory()
return documentsDir.appendingPathComponent("\(guid)-thumbnail.jpg")
}
// func scaled(to size: CGSize) -> UIImage? {
// UIGraphicsBeginImageContext( size )
// draw(in: CGRect(x: 0,y: 0,width: size.width,height: size.height))
// let newImage = UIGraphicsGetImageFromCurrentImageContext()
// UIGraphicsEndImageContext()
// return newImage?.withRenderingMode(.alwaysOriginal)
// }
}
| true
|
0822eada5e2ab2c858f4cc0e34a2558d8ae4fab2
|
Swift
|
Dkornil/IOS_CodingChallenge
|
/PageFeed/PageFeed/Extra/Utilities.swift
|
UTF-8
| 1,059
| 2.84375
| 3
|
[] |
no_license
|
//
// Utilities.swift
// PageFeed
//
// Created by Daniil Kornilov on 10/4/21.
//
import UIKit
class Utilities {
func getTextAndImageForComment(comments:String?) -> NSAttributedString {
let fullString = NSMutableAttributedString(string: "Comments: \(comments ?? "") ")
let commentsImage = NSTextAttachment()
commentsImage.image = UIImage(systemName: "bubble.right.fill", withConfiguration:.none)
let commentsAndString = NSAttributedString(attachment: commentsImage)
fullString.append(commentsAndString)
return fullString
}
func getTextAndImageForScore(score:String?) -> NSAttributedString {
let fullString = NSMutableAttributedString(string: "\(score ?? "") ")
let scoreImage = NSTextAttachment()
scoreImage.image = UIImage(systemName: "arrow.up.arrow.down", withConfiguration:.none)
let scoreAndImage = NSAttributedString(attachment: scoreImage)
fullString.append(scoreAndImage)
return fullString
}
}
| true
|
b18ce813157a83b06ba6e2c995929a6e13f2c9fd
|
Swift
|
benSmith1981/igenFamilyTree
|
/iGenFamilyTree/iGenFamilyTree/Family Tree.swift
|
UTF-8
| 7,939
| 3.171875
| 3
|
[] |
no_license
|
//
// Family Tree.swift
// iGenFamilyTree
//
// Created by Ton on 2017-06-30.
// Copyright © 2017. All rights reserved.
//
import Foundation
typealias ID = String
// Human is a very generic structure of all relationships a human can have in this family
// the processed boolean variable is used in function traverseTreeFor to prevent endless looping
struct Human {
var name: String
var gender: String
var processed: Bool = false
var spouses: [ID] = []
var parents: [ID] = []
var children: [ID] = []
var siblings: [ID] = []
init(name: String, gender: String) {
self.name = name
self.gender = gender
}
}
var humans: [ID: Human] = [:]
// Patient for whom we have to maintain a family tree
// row and col are starting points for the modelling of the family tree
// we build this structure from the humans array, which contains all humans in this family
struct Patient {
static var id: ID = ""
static var row = 7
static var col = 7
static var mySpousesIDs: [ID] = []
static var myParentsIDs: [ID] = []
static var myChildrenIDs: [ID] = []
static var mySiblingsIDs: [ID] = []
static var fatherSiblingsIDs: [ID] = []
static var motherSiblingsIDs: [ID] = []
}
// Model is a 2D matrix for building the family tree and connecting the nodes
// we build this from the Patient structure
struct Model {
static var minLevel = 1
static var maxLevel = 1
static var cell: [[String]] = Array(repeating: Array(repeating: "", count: 15), count: 15)
}
// functions for populating the Patient structure by calling function traverseTreeFor,
// which is then again called recursively for every human
// it also calculates the minimum and maximum levels traversed
// for processing siblings we need to test for siblings of the Patient or siblings of the father or mother of the Patient
func makeTreeFor(_ id: ID) {
let level = 1
Patient.id = id
print("Family tree for", humans[id]!.name, "is on level", level)
traverseTreeFor(id, level)
print("minLevel=", Model.minLevel)
print("maxLevel=", Model.maxLevel)
print("")
}
private func traverseTreeFor(_ id: ID, _ level: Int) {
if humans[id]!.processed == false {
humans[id]!.processed = true
Model.maxLevel = max(Model.maxLevel, level)
Model.minLevel = min(Model.minLevel, level)
for spouseID in humans[id]!.spouses {
print("spouse of", humans[id]!.name, "is", humans[spouseID]!.name, "on level", level)
if id == Patient.id {
Patient.mySpousesIDs.append(spouseID)
}
traverseTreeFor(spouseID, level)
}
for parentID in humans[id]!.parents {
print("parent of", humans[id]!.name, "is", humans[parentID]!.name, "on level", level - 1)
if id == Patient.id {
Patient.myParentsIDs.append(parentID)
}
traverseTreeFor(parentID, level - 1)
}
for childID in humans[id]!.children {
print("child of", humans[id]!.name, "is", humans[childID]!.name, "on level", level + 1)
if id == Patient.id {
Patient.myChildrenIDs.append(childID)
}
traverseTreeFor(childID, level + 1)
}
for siblingID in humans[id]!.siblings {
print("sibling of", humans[id]!.name, "is", humans[siblingID]!.name, "on level", level)
if id == Patient.id {
Patient.mySiblingsIDs.append(siblingID)
} else if humans[Patient.id]!.parents.contains(id) {
if humans[id]!.gender == "M" {
Patient.fatherSiblingsIDs.append(siblingID)
} else {
Patient.motherSiblingsIDs.append(siblingID)
}
}
traverseTreeFor(siblingID, level)
}
}
}
// functions for populating the Model structure
// Model is a 2D matrix for building the family tree and connecting the nodes
// we build this from the Patient structure
func makeModelFromTree() {
var row = Patient.row
var col = Patient.col
Model.cell[row][col] = Patient.id
col = Patient.col - 1
for id in Patient.mySpousesIDs {
Model.cell[row][col] = "---,---"
col -= 1
Model.cell[row][col] = id
}
row = Patient.row
col = Patient.col
for id in Patient.mySiblingsIDs {
col += 1
Model.cell[row][col] = id
Model.cell[row - 1][Patient.col] = "|--"
if id == Patient.mySiblingsIDs.last {
Model.cell[row - 1][col] = "--,"
} else {
Model.cell[row - 1][col] = "-------"
}
}
row = Patient.row - 2
col = Patient.col
for id in Patient.myParentsIDs {
if humans[id]!.gender == "M" {
Model.cell[row][col + 1] = id
} else {
Model.cell[row][col - 1] = id
}
}
if Patient.myParentsIDs.count == 2 {
Model.cell[row][col] = "---,---"
}
row = Patient.row - 2
col = Patient.col + 1
for id in Patient.fatherSiblingsIDs {
col += 1
Model.cell[row][col] = id
Model.cell[row - 1][Patient.col + 1] = ",--"
if id == Patient.fatherSiblingsIDs.last {
Model.cell[row - 1][col] = "--,"
} else {
Model.cell[row - 1][col] = "-------"
}
}
row = Patient.row - 2
col = Patient.col - 1
for id in Patient.motherSiblingsIDs {
col -= 1
Model.cell[row][col] = id
Model.cell[row - 1][Patient.col - 1] = "--,"
if id == Patient.motherSiblingsIDs.last {
Model.cell[row - 1][col] = ",--"
} else {
Model.cell[row - 1][col] = "-------"
}
}
row = Patient.row + 2
col = Patient.col - 2
for id in Patient.myChildrenIDs {
col += 1
Model.cell[row][col] = id
if id == Patient.myChildrenIDs.last {
Model.cell[row - 1][col] = "--,"
} else {
Model.cell[row - 1][col] = "-------"
}
}
if Patient.myChildrenIDs.count > 0 {
Model.cell[row - 1][Patient.col - 1] = "|--"
}
}
// supporting functions for populating the humans array
func addSpouseFor(_ id: ID, spouse: ID) {
humans[id]!.spouses.append(spouse)
}
func addParentFor(_ id: ID, parent: ID) {
humans[id]!.parents.append(parent)
}
func addChildFor(_ id: ID, child: ID) {
humans[id]!.children.append(child)
}
func addSiblingFor(_ id: ID, sibling: ID) {
humans[id]!.siblings.append(sibling)
}
// supporting function, just for debugging
func printHuman(_ id: ID) {
print("name:", humans[id]!.name)
for spouseID in humans[id]!.spouses {
print("spouse:", humans[spouseID]!.name)
}
for parentID in humans[id]!.parents {
print("parent:", humans[parentID]!.name)
}
for childID in humans[id]!.children {
print("child:", humans[childID]!.name)
}
for siblingID in humans[id]!.siblings {
print("sibling:", humans[siblingID]!.name)
}
print("")
}
// supporting function, just for debugging
func printPatient() {
for id in Patient.myParentsIDs {
print("myParentsIDs", id)
}
for id in Patient.fatherSiblingsIDs {
print("fatherSiblingsIDs", id)
}
for id in Patient.motherSiblingsIDs {
print("motherSiblingsIDs", id)
}
for id in Patient.mySpousesIDs {
print("mySpousesIDs", id)
}
for id in Patient.mySiblingsIDs {
print("mySiblingsIDs", id)
}
for id in Patient.myChildrenIDs {
print("myChildrenIDs", id)
}
print("")
}
// supporting function, just for debugging
func printModel() {
for i in Patient.row - 2 ... Patient.row + 2 {
for j in 0 ... 14 {
print(Model.cell[i][j], " ", terminator: "")
}
print("")
}
print("")
}
| true
|
1d5b01fbc845102861e8c0507532bd2b7378e4c4
|
Swift
|
Avinash-Gatsy/Liquid_Intake_Tracker
|
/GraphView.swift
|
UTF-8
| 8,624
| 3.09375
| 3
|
[] |
no_license
|
//
// GraphView.swift
// Liquid_Intake_Tracker
//
// Created by Avinash on 02/02/17.
// Copyright © 2017 avinash. All rights reserved.
//
import UIKit
@IBDesignable class GraphView: UIView {
//Weekly sample data
var graphPoints:[Int] = [4, 2, 6, 4, 5, 8, 3]
//the properties for the gradient
//You set up the start and end colors for the gradient as @IBInspectable properties, so that you’ll be able to change them in the storyboard.
@IBInspectable var startColor: UIColor = UIColor.red
@IBInspectable var endColor: UIColor = UIColor.green
override func draw(_ rect: CGRect) {
let width = rect.width
let height = rect.height
//set up background clipping area
let path = UIBezierPath(roundedRect: rect,
byRoundingCorners: UIRectCorner.allCorners,
cornerRadii: CGSize(width: 8.0, height: 8.0))
path.addClip()
//get the current context
//CG drawing functions need to know the context in which they will draw, so you use the UIKit method UIGraphicsGetCurrentContext() to obtain the current context. That’s the one that drawRect(_:) draws into.
let context = UIGraphicsGetCurrentContext()
let colors = [startColor.cgColor, endColor.cgColor]
//set up the color space
//All contexts have a color space. This could be CMYK or grayscale, but here you’re using the RGB color space.
let colorSpace = CGColorSpaceCreateDeviceRGB()
//set up the color stops
//The color stops describe where the colors in the gradient change over. In this example, you only have two colors, red going to green, but you could have an array of three stops, and have red going to blue going to green. The stops are between 0 and 1, where 0.33 is a third of the way through the gradient.
let colorLocations:[CGFloat] = [0.0, 1.0]
//create the gradient
//Create the actual gradient, defining the color space, colors and color stops.
let gradient = CGGradient(colorsSpace: colorSpace,
colors: colors as CFArray,
locations: colorLocations)
//draw the gradient
//Finally, you draw the gradient. CGContextDrawLinearGradient()
var startPoint = CGPoint.zero
var endPoint = CGPoint(x:0, y:self.bounds.height)
context!.drawLinearGradient(gradient!,
start: startPoint,
end: endPoint,
options: CGGradientDrawingOptions(rawValue: 0))
//calculate the x point
//columnXPoint takes a column as a parameter, and returns a value where the point should be on the x-axis.
let margin:CGFloat = 20.0
let columnXPoint = { (column:Int) -> CGFloat in
//Calculate gap between points
let spacer = (width - margin*2 - 4) /
CGFloat((self.graphPoints.count - 1))
var x:CGFloat = CGFloat(column) * spacer
x += margin + 2
return x
}
// calculate the y point
//Because the origin is in the top-left corner and you draw a graph from an origin point in the bottom-left corner, columnYPoint adjusts its return value so that the graph is oriented as you would expect.
let topBorder:CGFloat = 60
let bottomBorder:CGFloat = 50
let graphHeight = height - topBorder - bottomBorder
let maxValue = graphPoints.max()
let columnYPoint = { (graphPoint:Int) -> CGFloat in
var y:CGFloat = CGFloat(graphPoint) /
CGFloat(maxValue!) * graphHeight
y = graphHeight + topBorder - y // Flip the graph
return y
}
// draw the line graph
UIColor.white.setFill()
UIColor.white.setStroke()
//set up the points line
let graphPath = UIBezierPath()
//go to start of line
graphPath.move(to: CGPoint(x:columnXPoint(0),
y:columnYPoint(graphPoints[0])))
//add points for each item in the graphPoints array
//at the correct (x, y) for the point
for i in 1..<graphPoints.count {
let nextPoint = CGPoint(x:columnXPoint(i),
y:columnYPoint(graphPoints[i]))
graphPath.addLine(to: nextPoint)
}
//graphPath.stroke()
//create a gradient underneath this path by using the path as a clipping path.
//Create the clipping path for the graph gradient
//save the state of the context
context!.saveGState() //refer note1
//make a copy of the path, Copy the plotted path to a new path that defines the area to fill with a gradient.
let clippingPath = graphPath.copy() as! UIBezierPath
//add lines to the copied path to complete the clip area
//Complete the area with the corner points and close the path. This adds the bottom-right and bottom-left points of the graph.
clippingPath.addLine(to: CGPoint(
x: columnXPoint(graphPoints.count - 1),
y:height))
clippingPath.addLine(to: CGPoint(
x:columnXPoint(0),
y:height))
clippingPath.close()
//Add the clipping path to the context. When the context is filled, only the clipped path is actually filled.
clippingPath.addClip()
//find the highest number of glasses drunk and use that as the starting point of the gradient.
let highestYPoint = columnYPoint(maxValue!)
startPoint = CGPoint(x:margin, y: highestYPoint)
endPoint = CGPoint(x:margin, y:self.bounds.height)
context!.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0))
context!.restoreGState() //refer note1
//draw the line on top of the clipped gradient
graphPath.lineWidth = 2.0
graphPath.stroke()
//Draw the circles on top of graph stroke
for i in 0..<graphPoints.count {
var point = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
point.x -= 5.0/2
point.y -= 5.0/2
let circle = UIBezierPath(ovalIn:
CGRect(origin: point,
size: CGSize(width: 5.0, height: 5.0)))
circle.fill()
}
//Draw horizontal graph lines on the top of everything
let linePath = UIBezierPath()
//top line
linePath.move(to: CGPoint(x:margin, y: topBorder))
linePath.addLine(to: CGPoint(x: width - margin,
y:topBorder))
//center line
linePath.move(to: CGPoint(x:margin,
y: graphHeight/2 + topBorder))
linePath.addLine(to: CGPoint(x:width - margin,
y:graphHeight/2 + topBorder))
//bottom line
linePath.move(to: CGPoint(x:margin,
y:height - bottomBorder))
linePath.addLine(to: CGPoint(x:width - margin,
y:height - bottomBorder))
let color = UIColor(white: 1.0, alpha: 0.3)
color.setStroke()
linePath.lineWidth = 1.0
linePath.stroke()
}
}
//Note1 : Graphics contexts can save states. When you set many context properties, such as fill color, transformation matrix, color space or clip region, you’re actually setting them for the current graphics state. You can save a state by using CGContextSaveGState(), which pushes a copy of the current graphics state onto the state stack. You can also make changes to context properties, but when you call CGContextRestoreGState(), the original state is taken off the stack and the context properties revert.
//By doing this, you:
//Push the original graphics state onto the stack with CGContextSaveGState().
//Add the clipping path to a new graphics state.
//Draw the gradient within the clipping path.
//Restore the original graphics state with CGContextRestoreGState() — this was the state before you added the clipping path.
| true
|
3934ddffdbf59f4513fae2f7c925be078f19f476
|
Swift
|
Lea-Dukaez/swiftUI-City-Sights-App
|
/City Sights/Views/Home/List/BusinessCell.swift
|
UTF-8
| 1,145
| 3.390625
| 3
|
[] |
no_license
|
//
// BusinessCell.swift
// City Sights
//
// Created by Léa Dukaez on 10/09/2021.
//
import SwiftUI
struct BusinessCell: View {
@ObservedObject var business: Business
var body: some View {
HStack {
let uiImage = UIImage(data: business.imageData ?? Data())
Image(uiImage: uiImage ?? UIImage())
.resizable()
.frame(width: 58, height: 58, alignment: .center)
.cornerRadius(5)
.scaledToFit()
VStack (alignment: .leading, spacing: 10) {
Text(business.name ?? "").bold()
Text(String(format: "%.1f km away", (business.distance ?? 0)/1000)).font(.caption)
}
Spacer()
VStack {
Image("regular_\(business.rating ?? 0)")
Text("\(business.reviewCount ?? 0) Reviews").font(.caption)
}
}
}
}
struct BusinessCell_Previews: PreviewProvider {
static var previews: some View {
BusinessCell(business: Business.getTestData())
}
}
| true
|
852e090745c1785855511e1b89d410b0a03c584e
|
Swift
|
xujiyou/ios-core-animation
|
/ios-animation/ios-animation/class/TreeViewSub.swift
|
UTF-8
| 786
| 2.84375
| 3
|
[] |
no_license
|
//
// TreeViewSub.swift
// ios-animation
//
// Created by jiyou xu on 2019/4/13.
// Copyright © 2019 jiyou xu. All rights reserved.
//
import UIKit
class TreeViewSub: UIView {
var startPoint: CGPoint?
var endPoint: CGPoint?
var nearPoint: CGPoint?
var farPoint: CGPoint?
lazy var imageV: UIImageView = {
let image = UIImageView()
image.contentMode = .scaleAspectFit
return image
}()
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
imageV.frame = rect
self.addSubview(imageV)
}
func setImage(imgStr: String) {
imageV.image = UIImage(named: imgStr)
}
}
| true
|
c3fcf7762ccf81307958c9be67da17782a57038a
|
Swift
|
ParkJong-Hun/Swift_Algorithm-Collection
|
/Carpet.playground/Contents.swift
|
UTF-8
| 634
| 3.53125
| 4
|
[] |
no_license
|
import Foundation
func solution(_ brown:Int, _ yellow:Int) -> [Int] {
var col = 3
var row = 3
while(true) {
let leftBrown = brown - ((col * 2) + ((row - 2) * 2))
let leftYellow = yellow - ((col - 2) * (row - 2))
if leftBrown == 0 && leftYellow == 0 {
break
} else if leftBrown < 0 {
col -= 1
} else if leftYellow < 0 {
row -= 1
} else if leftBrown > 0 {
col += 1
} else if leftYellow > 0 {
row += 1
}
}
return [col, row]
}
solution(10, 2) //4,3
solution(8, 1) //3,3
solution(24, 24)//8,6
| true
|
290903050903d655d1fbec826559fb43c8fe3428
|
Swift
|
kk-laoguo/KKSwiftPractice
|
/SwiftStudy/U17Demo/U17Demo/Classes/Home/View/BoardCollectionViewCell.swift
|
UTF-8
| 1,544
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// BoardCollectionViewCell.swift
// U17Demo
//
// Created by zainguo on 2020/7/23.
// Copyright © 2020 zainguo. All rights reserved.
//
import UIKit
class BoardCollectionViewCell: BaseCollectionViewCell {
lazy var iconView: UIImageView = {
let iconView = UIImageView()
iconView.contentMode = .scaleAspectFill
iconView.layer.masksToBounds = true
return iconView
}()
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.textColor = .black
titleLabel.font = .systemFont(ofSize: 14)
titleLabel.textAlignment = .center
return titleLabel
}()
// 继承父类方法 布局
override func setupLayout() {
clipsToBounds = true
contentView.addSubview(iconView)
iconView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(10)
make.centerX.equalToSuperview()
make.height.width.equalTo(40)
}
contentView.addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(iconView.snp.bottom)
make.left.right.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10))
make.height.equalTo(20)
}
}
var model: ItemModel? {
didSet {
guard let model = model else {
return
}
iconView.yx_setImage(model.cover)
titleLabel.text = model.title
}
}
}
| true
|
082512c505fecafef3e4ce8187927ace1ca74172
|
Swift
|
akosma/Swift-Presentation
|
/PresentationKit/Presentation.swift
|
UTF-8
| 2,492
| 3.078125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
import Foundation
public struct PresentationGenerator : GeneratorType {
var index : Int = 0
var demoDictionary : [String : BaseDemo.Type]
public init(dict: [String : BaseDemo.Type]) {
self.demoDictionary = dict
}
public typealias Element = BaseDemo
mutating public func next() -> Element? {
var demoSequence = demoDictionary.values.array
if index < demoSequence.count {
var type = demoSequence[index]
self.index += 1
return type()
}
return nil
}
}
public class Presentation : NSObject, SequenceType {
public typealias GeneratorType = PresentationGenerator
private let name : String
private let demoDictionary : [String : BaseDemo.Type] = [
"ar": ActiveRecordDemo.self,
"angry": AngryDemo.self,
"99b": NinetyNineBeersDemo.self,
"filt": FiltersDemo.self,
"noah": UnicodeDemo.self,
"curry": CurriedDemo.self,
"sets": SetsDemo.self,
"js": JavaScriptDemo.self,
"math": MathDemo.self,
"gene": GenericsDemo.self,
"objc": ObjCDemo.self
]
public init (name: String) {
self.name = name
super.init()
let today = date()
println("Welcome to the \(name) presentation!")
println("Today is \(today).")
println()
}
public subscript(number: Int) -> Demo? {
return getDemo(number)
}
public subscript(name: String) -> Demo? {
return getDemo(name)
}
public func getDemo(number: Int) -> Demo? {
var demoSequence = demoDictionary.values.array
if number < demoSequence.count {
return demoSequence[number]()
}
return nil
}
public func getDemo(name: String) -> Demo? {
var type : BaseDemo.Type? = demoDictionary[name]
if type != nil {
return type!()
}
return nil
}
private func date() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .NoStyle
dateFormatter.dateStyle = .LongStyle
let us = NSLocale(localeIdentifier:"en_US");
dateFormatter.locale = us
let date = NSDate()
return dateFormatter.stringFromDate(date)
}
public func generate() -> GeneratorType {
var gen = PresentationGenerator(dict: demoDictionary)
return gen
}
}
| true
|
e24726041580a32124b5e730157ce52998729f7b
|
Swift
|
bigtreenono/LearnSwift
|
/SlideMenu/SlideMenu/MomentCell.swift
|
UTF-8
| 1,902
| 2.8125
| 3
|
[] |
no_license
|
//
// MomentCell.swift
// SlideMenu
//
// Created by Jeff on 17/11/2016.
// Copyright © 2016 Jeff. All rights reserved.
//
import UIKit
struct Moment {
let backgroundImageName: String
let avatarImageName: String
let title: String
let name: String
}
class MomentCell: UITableViewCell {
var moment: Moment! {
didSet {
backgroundImageView.image = UIImage(named: moment.backgroundImageName)
avatarImageView.image = UIImage(named: moment.avatarImageName)
}
}
var backgroundImageView: UIImageView!
var avatarImageView: UIImageView!
var titleLabel: UILabel!
var nameLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundImageView = UIImageView(frame: contentView.bounds)
contentView.addSubview(backgroundImageView)
avatarImageView = UIImageView(frame: CGRect(x: 20, y: contentView.bounds.height - 60 - 20, width: 60, height: 60))
avatarImageView.layer.cornerRadius = 30
avatarImageView.clipsToBounds = true
contentView.addSubview(avatarImageView)
// titleLabel = UILabel(frame: CGRect)
}
override func layoutSubviews() {
super.layoutSubviews()
backgroundImageView.frame = contentView.bounds
avatarImageView.frame = CGRect(x: 20, y: contentView.bounds.height - 60 - 20, width: 60, height: 60)
}
required init?(coder aDecoder: NSCoder) {
fatalError("123")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| true
|
2f77d37384627680e6b9fff826739fa943d7d6ca
|
Swift
|
KYang646/NYTGroupProject
|
/NYTimesGroupProj/NYTimesGroupProj/Views/FavoritesCollectionViewCell.swift
|
UTF-8
| 3,814
| 2.625
| 3
|
[] |
no_license
|
//
// FavoritesCollectionViewCell.swift
// NYTimesGroupProj
//
// Created by Jocelyn Boyd on 10/21/19.
// Copyright © 2019 Kimball Yang. All rights reserved.
//
import UIKit
class FavoritesCollectionViewCell: UICollectionViewCell {
lazy var optionsButton: UIButton = {
let button = UIButton()
button.setTitle("...", for: .normal)
button.setTitleColor(.black, for: .normal)
button.transform = CGAffineTransform(scaleX: 3, y: 3)
self.addSubview(button)
return button
}()
lazy var bookImage: UIImageView = {
let imageView = UIImageView()
imageView.backgroundColor = .red
self.addSubview(imageView)
return imageView
}()
lazy var weeksLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.text = "Weeks Label"
label.backgroundColor = .brown
label.adjustsFontSizeToFitWidth = true
label.textColor = .black
label.font = UIFont.italicSystemFont(ofSize: 15)
self.addSubview(label)
return label
}()
lazy var summaryTextView: UITextView = {
let textView = UITextView()
textView.textAlignment = .center
textView.text = "Text View"
textView.backgroundColor = .cyan
self.addSubview(textView)
textView.isUserInteractionEnabled = false
return textView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.cornerRadius = 10
backgroundColor = .white
setConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setConstraints() {
setBookImageConstraints()
setWeeksLabelConstraints()
setSummaryTextViewConstraints()
setButtonConstraints()
}
private func setBookImageConstraints(){
bookImage.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
bookImage.centerXAnchor.constraint(equalTo: self.centerXAnchor),
bookImage.topAnchor.constraint(equalTo: self.topAnchor, constant: 40),
bookImage.widthAnchor.constraint(equalToConstant: 100),
bookImage.heightAnchor.constraint(equalToConstant: 100),
])
}
private func setWeeksLabelConstraints() {
weeksLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
weeksLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor),
weeksLabel.topAnchor.constraint(equalTo: bookImage.bottomAnchor, constant: 10),
weeksLabel.widthAnchor.constraint(equalTo: summaryTextView.widthAnchor),
weeksLabel.heightAnchor.constraint(equalToConstant: 30)
])
}
private func setSummaryTextViewConstraints(){
summaryTextView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
summaryTextView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
summaryTextView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
summaryTextView.topAnchor.constraint(equalTo: weeksLabel.bottomAnchor),
summaryTextView.widthAnchor.constraint(equalTo: self.widthAnchor),
summaryTextView.heightAnchor.constraint(equalToConstant: 90),
])
}
private func setButtonConstraints(){
optionsButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
optionsButton.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 120),
optionsButton.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: -140),
optionsButton.bottomAnchor.constraint(equalTo: self.bottomAnchor),
// optionsButton.topAnchor.constraint(equalTo: view.topAnchor)
optionsButton.widthAnchor.constraint(equalToConstant: 50),
optionsButton.heightAnchor.constraint(equalToConstant: 10),
])
}
}
| true
|
6f8a83ba54a9ec11b25e3fcf42bd5ad0d03c48e5
|
Swift
|
Punyugi2012/GravityRunner
|
/GravityRunner/HelpingClasses/ItemManager.swift
|
UTF-8
| 2,099
| 2.8125
| 3
|
[] |
no_license
|
//
// Item.swift
// GravityRunner
//
// Created by punyawee on 11/8/61.
// Copyright © พ.ศ. 2561 Punyugi. All rights reserved.
//
import SpriteKit
class ItemManger {
static func getItem(minY: CGFloat, maxY: CGFloat, positionXCamera: CGFloat) -> SKSpriteNode {
let randomForTypeItem = randomBetweenNumbers(first: 1, second: 20)
print(randomForTypeItem)
let item = SKSpriteNode()
item.size = CGSize(width: 50, height: 50)
if randomForTypeItem <= 10 {
item.texture = SKTexture(imageNamed: "ring")
item.name = "Ring"
item.physicsBody = SKPhysicsBody(circleOfRadius: item.size.height / 2)
}
else {
item.texture = SKTexture(imageNamed: "fire1")
item.name = "Fire"
item.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: item.size.width - 30, height: item.size.height - 30))
var textures = [SKTexture]()
for i in 1...12 {
textures.append(SKTexture(imageNamed: "fire\(i)"))
}
item.run(SKAction.repeatForever(SKAction.animate(with: textures, timePerFrame: 0.1, resize: true, restore: false)))
let moveAction = SKAction.moveBy(x: -4, y: 0, duration: 0.05)
item.run(SKAction.repeatForever(moveAction))
}
item.physicsBody?.categoryBitMask = ColliderType.FIRE_AND_RING
item.physicsBody?.contactTestBitMask = ColliderType.PLAYER
item.physicsBody?.collisionBitMask = ColliderType.PLAYER
item.anchorPoint = CGPoint(x: 0.5, y: 0.5)
item.physicsBody?.affectedByGravity = false
item.physicsBody?.isDynamic = false
item.physicsBody?.restitution = 0.0
item.position = CGPoint(x: positionXCamera + 800, y: randomBetweenNumbers(first: minY + 250, second: maxY - 250))
item.zPosition = 1
return item
}
static func randomBetweenNumbers(first: CGFloat, second: CGFloat) -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(first - second) + min(first, second)
}
}
| true
|
4052244fa6f0bcca4d05e29ffca81ecd747e2d2e
|
Swift
|
gjones/Simple-Swift-List
|
/SimpleSwiftList/ItemViewController.swift
|
UTF-8
| 3,620
| 2.921875
| 3
|
[] |
no_license
|
//
// ItemViewController.swift
// SimpleSwiftList
//
// Created by Gareth Jones on 2/14/15.
// Copyright (c) 2015 Gareth Jones. All rights reserved.
//
import UIKit
import CoreData
class ItemViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textFieldItem: UITextField!
@IBOutlet var textFieldQuantity: UITextField!
@IBOutlet var textFieldInfo: UITextField!
var item: String?
var quantity: String?
var info: String?
var existingItem: NSManagedObject!
override func viewDidLoad() {
super.viewDidLoad()
if (existingItem != nil) {
textFieldItem.text = item
textFieldQuantity.text = quantity
textFieldInfo.text = info
}
// This makes it so that textFieldShouldReturn works and the keyboard hides when the user clicks return
textFieldItem.delegate = self
textFieldQuantity.delegate = self
textFieldInfo.delegate = self
if item != nil {
title = item
}
// Adding ability to swipe back to previous page
var swipeRight = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipeRight)
}
func swiped(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right:
print("User swiped right")
self.navigationController?.popToRootViewControllerAnimated(true)
default:
break
}
}
}
@IBAction func saveTapped(sender: AnyObject) {
// Reference to our app delegate
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// Reference NSManaged object context
let context: NSManagedObjectContext = appDel.managedObjectContext! //I unwrapped but tutorial didn't say that
let entity = NSEntityDescription.entityForName("List", inManagedObjectContext: context)
// Check if item exists
if (existingItem != nil) {
existingItem.setValue(textFieldItem.text as String, forKey: "item")
existingItem.setValue(textFieldQuantity.text as String, forKey: "quantity")
existingItem.setValue(textFieldInfo.text as String, forKey: "info")
} else {
// Create instance of our data model and initialize
var newItem = Model(entity: entity!, insertIntoManagedObjectContext: context)
// Map our properties
newItem.item = textFieldItem.text
newItem.quantity = textFieldQuantity.text
newItem.info = textFieldInfo.text
}
// Save our context
context.save(nil)
// Navigate back to previous controller
self.navigationController?.popToRootViewControllerAnimated(true)
}
@IBAction func cancelTapped(sender: AnyObject) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| true
|
a6cd308814413e4f684346cdb95cc5b78bdea956
|
Swift
|
SolnyshkinSM/MyChat
|
/MyChat/Classes/PresentationLayer/Shared/Extensions/UIButton.swift
|
UTF-8
| 1,777
| 2.8125
| 3
|
[] |
no_license
|
//
// UIButton.swift
// MyChat
//
// Created by Administrator on 24.02.2021.
//
import UIKit
// MARK: - UIButton
extension UIButton {
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let circlePath = UIBezierPath(ovalIn: self.bounds)
return circlePath.contains(point)
}
func configereCircleButton(theme: Theme) {
layer.masksToBounds = true
backgroundColor = theme.profileImageButtonColor
layer.cornerRadius = bounds.height / 2
}
func shake() {
if self.layer.animation(forKey: "shakeIt") != nil {
self.layer.removeAnimation(forKey: "shakeIt")
let animation = CABasicAnimation(keyPath: "transform")
animation.duration = 2.0
self.layer.add(animation, forKey: "transform")
return
}
let rotation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotation.values = [-18.0, 18.0].map { (degrees: Double) -> Double in
let radians: Double = (.pi * degrees) / 180.0
return radians
}
let translationX = CAKeyframeAnimation(keyPath: "transform.translation.x")
translationX.values = [-5.0, 5.0]
let translationY = CAKeyframeAnimation(keyPath: "transform.translation.y")
translationY.values = [-5.0, 5.0]
let shakeGroup: CAAnimationGroup = CAAnimationGroup()
shakeGroup.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
shakeGroup.animations = [rotation, translationX, translationY]
shakeGroup.duration = 0.3
shakeGroup.repeatCount = .infinity
shakeGroup.autoreverses = true
self.layer.add(shakeGroup, forKey: "shakeIt")
}
}
| true
|
0e7aec7146571e53360038433625e094bdfb417d
|
Swift
|
blad90/CalorApp
|
/Calorapp - Calories Tracker/HistoryVC.swift
|
UTF-8
| 3,185
| 2.609375
| 3
|
[] |
no_license
|
//
// HistoryVC.swift
// Calorapp - Calories Tracker
//
// Created by Bladimir Baez on 5/8/17.
// Copyright © 2017 Apple Inc. All rights reserved.
//
import UIKit
import Charts
import Parse
class HistoryVC: UIViewController {
@IBOutlet var pieChartView: PieChartView!
var foodItem = ""
var foodItems: [String] = []
var calorieString = ""
var calorie = 0.0
var calories: [Double] = []
var foodNames: [String] = []
var foodCalories: [Double] = []
override func viewDidLoad() {
super.viewDidLoad()
let query = PFQuery(className:"FoodList")
query.whereKey("user", equalTo: PFUser.current()!)
query.findObjectsInBackground { (objects, error) in
if error == nil {
for object in objects! {
self.foodItem = NSString(format: "%@", object["foodItem"] as! CVarArg) as String
self.calorieString = NSString(format: "%@", object["calories"] as! CVarArg) as String
self.calorie = Double(self.calorieString)!
self.foodItems.append(self.foodItem)
self.calories.append(self.calorie)
}
}
self.foodNames = self.foodItems
self.foodCalories = self.calories
self.setChart(dataPoints: self.foodNames, values: self.foodCalories)
self.pieChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .easeInBack)
self.pieChartView.chartDescription?.text = "";
}
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x: Double(i), y:values[i])
dataEntries.append(dataEntry)
}
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "Calories")
let pieChartData = PieChartData()
pieChartData.addDataSet(pieChartDataSet)
pieChartView.data = pieChartData
var colors: [UIColor] = []
for i in 0..<dataPoints.count {
let red = Double(arc4random_uniform(256))
let green = Double(arc4random_uniform(256))
let blue = Double(arc4random_uniform(256))
let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
colors.append(color)
}
pieChartDataSet.colors = colors
}
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
|
9048ee3ced9cb86b4b4c64d055505519d3e9043b
|
Swift
|
imweihuang/pocket-usa
|
/pocket-usa-app/Pocket USA/DataFeed.swift
|
UTF-8
| 439
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// DataManager.swift
// Pocket USA
//
// Created by Wei Huang on 3/2/17.
// Copyright © 2017 Wei Huang. All rights reserved.
//
import Foundation
// Source feed in the JSON
public struct DataFeed: Decodable {
public var dataFeed: [AnyObject]!
public init?(json: JSON) {
guard let dataFeed: [AnyObject] = "data" <~~ json else {
return nil
}
self.dataFeed = dataFeed
}
}
| true
|
1724bd27e49109346b81aa5d4b05593808778fc4
|
Swift
|
agustindc-rga/ReactiveUI
|
/ReactiveUI/ReactiveUI/UIGestureRecognizer.swift
|
UTF-8
| 1,155
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// UIGestureRecognizer.swift
// ReactiveControl
//
// Created by Zhixuan Lai on 1/8/15.
// Copyright (c) 2015 Zhixuan Lai. All rights reserved.
//
import UIKit
public extension UIGestureRecognizer {
convenience init(action: @escaping (UIGestureRecognizer) -> ()) {
self.init()
addAction(action)
}
func addAction(_ action: @escaping (UIGestureRecognizer) -> ()) {
removeAction()
let target = ProxyTarget(action: action)
addTarget(target, action: target.actionSelector())
proxyTarget = target
}
func removeAction() {
if let target = proxyTarget {
removeTarget(target, action: target.actionSelector())
proxyTarget = nil
}
}
}
internal extension UIGestureRecognizer {
typealias ProxyTarget = RUIProxyTarget<UIGestureRecognizer>
var proxyTarget: ProxyTarget? {
get {
return objc_getAssociatedObject(self, &RUIProxyTargetsKey) as? ProxyTarget
}
set {
objc_setAssociatedObject(self, &RUIProxyTargetsKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
| true
|
aa438df04d5c3cad268f57951d13a636fe378996
|
Swift
|
facile-it/FunctionalKit
|
/Sources/FunctionalKit/Lens.swift
|
UTF-8
| 4,315
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
#if SWIFT_PACKAGE
import Operadics
#endif
import Abstract
/// A Lens is a reference to a subpart of some data structure
public struct LensFull<S,T,A,B> {
public let get: (S) -> A
public let set: (B) -> (S) -> T
public init(get: @escaping (S) -> A, set: @escaping (B) -> (S) -> T) {
self.get = get
self.set = set
}
}
public typealias Lens<Whole,Part> = LensFull<Whole,Whole,Part,Part>
public extension LensFull where S == T, A == B {
typealias Whole = S
typealias Part = A
}
public extension LensFull {
func modify(_ transform: @escaping (A) -> B) -> (S) -> T {
return { s in self.set(transform(self.get(s)))(s) }
}
func then <C,D> (_ other: LensFull<A,B,C,D>) -> LensFull<S,T,C,D> {
return LensFull<S,T,C,D>.init(
get: { other.get(self.get($0)) },
set: { bp in
return { s in
return self.set(other.set(bp)(self.get(s)))(s)
}
})
}
static func >>> <C,D> (left: LensFull, right: LensFull<A,B,C,D>) -> LensFull<S,T,C,D> {
return left.then(right)
}
}
/// zipped lenses will hold the laws only if the involved lenses are focusing on different parts
public extension Lens where S == T, A == B {
static func zip <X,Y> (_ a: Lens<S,X>, _ b: Lens<S,Y>) -> Lens<S,(X,Y)> where A == (X,Y) {
return Lens<S,(X,Y)>.init(
get: { s in (a.get(s),b.get(s)) },
set: { (tuple) in
{ s in b.set(tuple.1)(a.set(tuple.0)(s)) }
})
}
static func zip <X,Y,Z> (_ a: Lens<S,X>, _ b: Lens<S,Y>, _ c: Lens<S,Z>) -> Lens<S,(X,Y,Z)> where A == (X,Y,Z) {
return Lens<S,(X,Y,Z)>.init(
get: { s in (a.get(s),b.get(s),c.get(s)) },
set: { (tuple) in
{ s in c.set(tuple.2)(b.set(tuple.1)(a.set(tuple.0)(s))) }
})
}
}
// MARK: - Utilities
public extension Dictionary {
static func lens(at key: Key) -> Lens<Dictionary,Value?> {
return Lens<Dictionary,Value?>(
get: { $0[key] },
set: { part in
{ whole in
var m_dict = whole
m_dict[key] = part
return m_dict
}
})
}
}
extension Writer {
public enum lens {
public static var log: Lens<Writer,Log> {
return iso.product >>> Product.lens.first
}
public static var value: Lens<Writer,Parameter> {
return iso.product >>> Product.lens.second
}
}
}
public extension WritableKeyPath {
func lens() -> Lens<Root,Value> {
return Lens<Root,Value>.init(
get: { $0[keyPath: self] },
set: { part in
{ whole in
var m = whole
m[keyPath: self] = part
return m
}
})
}
}
prefix operator °
public prefix func ° <Root,Value> (_ keyPath: WritableKeyPath<Root,Value>) -> Lens<Root,Value> {
return keyPath.lens()
}
// MARK: - Lens Laws
/*:
## Enforcing lens laws
Lenses are not just bags of syntax: for a lens to make sense it's important that some invariants are respected.
A Lens is defined as just a couple of functions, but what matters are the "semantics" attached to those lenses.
For a lens to be "well-behaved" it has to follow two invariants:
- SetGet: if a value is `set` through a lens, when you `get` it you obtain the same value;
- GetSet: if a value is `get` through a lens, `set`ting it back doesn't change the `whole` structure.
There's also and additional law (for a "very well-behaved lens) that, if enforced, guarantees that the `set` operation is idempotent:
- SetSet: if a value is `set` and then is `set` again, the `whole` is the same as the one after the first `set`.
When defining a Lens, it's important to test it after these laws with a property-based testing framework.
:*/
public enum LensLaw {
public static func setGet <S,A> (lens: Lens<S,A>, whole: S, part: A) -> Bool where A: Equatable {
return lens.get(lens.set(part)(whole)) == part
}
public static func setGet <S,X,Y> (lens: Lens<S,(X,Y)>, whole: S, part: (X,Y)) -> Bool where X: Equatable, Y: Equatable {
return lens.get(lens.set(part)(whole)) == part
}
public static func getSet <S,A> (lens: Lens<S,A>, whole: S) -> Bool where S: Equatable {
return lens.set(lens.get(whole))(whole) == whole
}
public static func setSet <S,A> (lens: Lens<S,A>, whole: S, part: A) -> Bool where S: Equatable {
return lens.set(part)(whole) == lens.set(part)(lens.set(part)(whole))
}
}
| true
|
8b3fd3e77a10aacfcec9cae85f83119cdda9783f
|
Swift
|
wslbxx123/HideSeekiOS
|
/HideSeek/Common/Model/Reward.swift
|
UTF-8
| 687
| 2.546875
| 3
|
[] |
no_license
|
//
// Reward.swift
// HideSeek
//
// Created by apple on 8/2/16.
// Copyright © 2016 mj. All rights reserved.
//
class Reward {
var pkId: Int64
var name: String
var imageUrl: String?
var record: Int = 0
var exchangeCount: Int
var introduction: String?
var version: Int64 = 0
init(pkId: Int64, name: String, imageUrl: String?, record: Int, exchangeCount: Int,
introduction: String?, version: Int64) {
self.pkId = pkId
self.name = name
self.imageUrl = imageUrl
self.record = record
self.exchangeCount = exchangeCount
self.introduction = introduction
self.version = version
}
}
| true
|
c20cb8a9d424f48de7b89df28462e06f4a636693
|
Swift
|
gmarson/randm-ref
|
/NetworkLayer/Sources/NetworkLayer/ServiceCalls/GetImageOfCharacter.swift
|
UTF-8
| 828
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//
// GetImageOfCharacter.swift
// RickAndMorty
//
// Created by Gabriel Augusto Marson on 02/08/20.
// Copyright © 2020 Gabriel Augusto Marson. All rights reserved.
//
import Foundation
public final class GetImageOfCharacter {
private let dispatcher: NetworkDispatcher
public init(dispatcher: NetworkDispatcher = .init(urlPath: "")) {
self.dispatcher = dispatcher
}
public func getAllCharacters(
absoluteUrl: String,
completionHandler: @escaping (Result<Data, NetworkError>) -> Void
) {
guard let url = URL(string: absoluteUrl) else {
completionHandler(.failure(.badURL))
return
}
dispatcher.downloadImage(
url: url,
method: .get) { result in
completionHandler(result)
}
}
}
| true
|
a6a80b04679fe8c0c3338db12038a8a51f7b53a9
|
Swift
|
jbrunhuber/neural-net
|
/NeuralNet/Neurons/InputNeuron.swift
|
UTF-8
| 364
| 2.734375
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
//
// InputNeuron.swift
// NeuralNet
//
// Created by Joshua Brunhuber on 02.06.18.
// Copyright © 2018 Joshua Brunhuber. All rights reserved.
//
import Foundation
class InputNeuron: Neuron {
var neuronValue: Double
init(value: Double) {
neuronValue = value
}
func value() -> Double {
return neuronValue
}
}
| true
|
f23d190034eece027bbd6d9af44f514c91a410fc
|
Swift
|
tiasn/TXLive
|
/TXLive/TXLive/Classes/Main/View/PageTitleView.swift
|
UTF-8
| 6,424
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// PageTitleView.swift
// TXLive
//
// Created by LTX on 2016/12/11.
// Copyright © 2016年 LTX. All rights reserved.
//
import UIKit
//代理的协议
protocol pageTitleViewDelegate : class {
func pageTitleView(titleView : PageTitleView, selectedIndex index : Int)
}
fileprivate let kScrollLineH : CGFloat = 2
fileprivate let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85,85)
fileprivate let kSelectorColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0)
class PageTitleView: UIView {
//自定义属性:标题数组
fileprivate var titles : [String]
fileprivate var currentIndex = 0;
weak var delegate : pageTitleViewDelegate?
// 懒加载属性
fileprivate lazy var titleLables : [UILabel] = [UILabel]()
// 懒加载属性
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
// 懒加载属性
fileprivate lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
//自定义构造方法
init(frame: CGRect, titles : [String]) {
self.titles = titles
super.init(frame: frame)
//设置UI界面
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面
extension PageTitleView{
fileprivate func setupUI() {
// 添加ScrollView
addSubview(scrollView)
scrollView.frame = bounds
//添加title Lable
setupTitleLables()
//添加TitleView底部滚动线
setupBottomLineAndScrollLine()
}
fileprivate func setupTitleLables() {
//labe的值
let lableW : CGFloat = frame.width / CGFloat(titles.count)
let lableH : CGFloat = frame.height - kScrollLineH
let lableY : CGFloat = 0
for (index, title) in titles.enumerated() {
// 创建lable
let lable = UILabel()
//设置lable属性
lable.text = title
lable.tag = index
lable.font = UIFont.systemFont(ofSize: 15)
lable.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
lable.textAlignment = .center
//设置labe的Frame
let labelX : CGFloat = lableW * CGFloat(index)
lable.frame = CGRect(x: labelX, y: lableY, width: lableW, height: lableH)
// 添加点击事件
lable.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLableClick(_ :)))
lable.addGestureRecognizer(tapGes)
//添加lable到ScrollView
scrollView.addSubview(lable)
//添加到数组
titleLables.append(lable)
}
}
fileprivate func setupBottomLineAndScrollLine() {
// 添加底线
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
//添加scrollLine
guard let firstLable = titleLables.first else {
return
}
firstLable.textColor = UIColor(r: kSelectorColor.0, g: kSelectorColor.1, b: kSelectorColor.2)
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLable.frame.origin.x, y: frame.height - kScrollLineH, width: firstLable.frame.size.width, height: kScrollLineH)
}
}
// MARK:- 监听事件
extension PageTitleView{
@objc fileprivate func titleLableClick(_ tapGes : UIGestureRecognizer){
//点击的lable
guard let currentLable = tapGes.view as? UILabel else {
return
}
if currentIndex == currentLable.tag {
return
}
// 旧的lable
let oldLable = titleLables[currentIndex]
// 修改颜色
currentLable.textColor = UIColor(r: kSelectorColor.0, g: kSelectorColor.1, b: kSelectorColor.2)
oldLable.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
let scrollLineX = CGFloat(currentLable.tag) * scrollLine.frame.width
UIView .animate(withDuration: 0.25) {
self.scrollLine.frame.origin.x = scrollLineX
}
//保存最新的lable下标
currentIndex = currentLable.tag
//通知代理
delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex)
}
}
// MARK:- 对外暴露的方法
extension PageTitleView {
func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) {
//取出lable
let sourceLable = titleLables[sourceIndex]
let targetLable = titleLables[targetIndex]
let moveTotal = targetLable.frame.origin.x - sourceLable.frame.origin.x
let moveX = moveTotal * progress
//指示线联动
scrollLine.frame.origin.x = sourceLable.frame.origin.x + moveX
//颜色渐变
//取出渐变范围
let colorDelta = (kSelectorColor.0 - kNormalColor.0, kSelectorColor.1 - kNormalColor.1, kSelectorColor.2 - kNormalColor.2)
//sourceLabel变色
sourceLable.textColor = UIColor(r: kSelectorColor.0 - colorDelta.0 * progress, g: kSelectorColor.1 - colorDelta.1 * progress, b: kSelectorColor.2 - colorDelta.2 * progress)
//targetLable变色
targetLable.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1*progress, b: kNormalColor.2 + colorDelta.2*progress)
//保存最新的index
currentIndex = targetIndex
}
}
| true
|
c5e9148cdff3d4639c936782eed3940fe3daf71e
|
Swift
|
smalljd/Landmarks
|
/Landmarks/Views/LandmarkRow.swift
|
UTF-8
| 749
| 2.875
| 3
|
[] |
no_license
|
//
// LandmarkRow.swift
// Landmarks
//
// Created by Jeff on 6/30/19.
// Copyright © 2019 Jeff Small. All rights reserved.
//
import SwiftUI
struct LandmarkRow : View {
var landmark: Landmark
var body: some View {
HStack(spacing: 12) {
landmark.image(forSize: 30)
.cornerRadius(15)
Text(landmark.name)
Spacer()
if landmark.isFavorite {
Image(systemName: "star.fill")
.imageScale(.medium)
.foregroundColor(.yellow)
}
}
}
}
#if DEBUG
struct LandmarkRow_Previews : PreviewProvider {
static var previews: some View {
LandmarkRow(landmark: landmarkData[0])
}
}
#endif
| true
|
81eabc8eb42a7aeb5ee5d3e60e66158dd1fc5938
|
Swift
|
salometsiramua/ImagesGallery
|
/ImageGallery/Model/Network/Manager/NetworkManager.swift
|
UTF-8
| 2,418
| 2.953125
| 3
|
[] |
no_license
|
//
// NetworkManager.swift
// ImageGallery
//
// Created by Salome Tsiramua on 3/11/21.
//
import Foundation
protocol MappableResponse {
init(data: Data) throws
}
final class ServiceManager<Response: MappableResponse> {
private(set) var isRunning: Bool = false
typealias ResponseObject = Response
private let service: Endpoint
private let session: NetworkSession
public let httpService: HTTPRequestSession
private var onSuccessCallback: ServiceSuccessCallback?
private var onFailureCallback: ServiceFailureCallback?
init(session: NetworkSession = URLSession.shared, _ service: Endpoint) {
self.session = session
self.service = service
self.httpService = HTTPSession(session: session)
}
@discardableResult
convenience init(session: NetworkSession = URLSession.shared, _ service: Endpoint, onSuccess: @escaping ServiceSuccessCallback, onFailure: @escaping ServiceFailureCallback) {
self.init(session: session, service)
onSuccessCallback = onSuccess
onFailureCallback = onFailure
call()
}
}
extension ServiceManager {
private func call() {
guard let request = HTTPServiceRequest(endpoint: service) else {
onFailureCallback?(NetworkError.urlIsInvalid)
return
}
isRunning = true
httpService.request(request) { (data, response, error) in
self.isRunning = false
if let error = error {
self.onFailureCallback?(error)
return
}
guard let data = data else {
self.onFailureCallback?(NetworkError.responseDataIsNil)
return
}
do {
let mapped = try Response(data: data)
self.onSuccessCallback?(mapped)
} catch {
self.onFailureCallback?(error)
}
}
}
}
//MARK: - HTTPManagerService functions
extension ServiceManager: HTTPManagerService {
func onSuccess(_ callback: @escaping ServiceSuccessCallback) -> Self {
onSuccessCallback = callback
return self
}
func onFail(_ callback: @escaping ServiceFailureCallback) -> Self {
onFailureCallback = callback
return self
}
}
| true
|
eef1bf5265551bfeb2deca133ca17648aeebd762
|
Swift
|
kemmo/KC-PracticaiOSAvanzado
|
/Everpobre/ViewControllers/ReassignNotes/ReassignNoteTableViewCell.swift
|
UTF-8
| 2,536
| 2.578125
| 3
|
[] |
no_license
|
//
// ReassignNoteTableViewCell.swift
// Everpobre
//
// Created by VINACHES LOPEZ JORGE on 17/04/2018.
// Copyright © 2018 Jorge Vinaches. All rights reserved.
//
import UIKit
protocol ReassignNoteTableViewCellDelegate: class {
func didChangePickerView(row: Int, selectedOption: Int)
}
class ReassignNoteTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var notebooksPickerView: UIPickerView!
var tableIndex: Int!
var notebooks: [Notebook]!
var delegate: ReassignNoteTableViewCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
notebooksPickerView.dataSource = self
notebooksPickerView.delegate = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func selectedOption(_ option: Int) {
notebooksPickerView.selectRow(option, inComponent: 0, animated: false)
}
}
extension ReassignNoteTableViewCell: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return notebooks.count + 1
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
var pickerLabel = view as? UILabel
if (pickerLabel == nil) {
pickerLabel = UILabel()
pickerLabel?.textAlignment = NSTextAlignment.center
}
let mutableString: NSMutableAttributedString?
if row == 0 {
pickerLabel?.font = UIFont.systemFont(ofSize: 20)
mutableString = NSMutableAttributedString(string: "Delete note")
mutableString!.addAttribute(.foregroundColor, value: UIColor.red, range: NSMakeRange(0, mutableString!.length))
} else {
pickerLabel?.font = UIFont.systemFont(ofSize: 14)
mutableString = NSMutableAttributedString(string: notebooks[row-1].name ?? "")
}
pickerLabel?.attributedText = mutableString
return pickerLabel!;
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
delegate?.didChangePickerView(row: tableIndex, selectedOption: row)
}
}
| true
|
4cae3efc734259b3324b5d96b13ae2acfa9fdea3
|
Swift
|
chokyungjin/MovieMoon
|
/DemoProject/DiaryResultSecondCell.swift
|
UTF-8
| 4,590
| 2.65625
| 3
|
[] |
no_license
|
//
// DiaryContentSecond.swift
// DemoProject
//
// Created by 조경진 on 2019/11/17.
// Copyright © 2019 조경진. All rights reserved.
//
import Foundation
protocol PlusActionDelegate {
func didClickedPlus()
func didClickedOk()
func didClickedCancel()
}
class DiaryResultSecondCell : UITableViewCell , UITextViewDelegate {
var delegate : PlusActionDelegate?
var plusBtn: UIButton = {
let button = UIButton()
button.backgroundColor = UIColor.init(red: 104/255, green: 104/255, blue: 104/255, alpha: 1)
button.setImage(#imageLiteral(resourceName: "plusBut"), for: .normal)
button.frame = CGRect(x: 15, y: 0, width: 30, height: 30)
return button
}()
var addLabel: UILabel = {
let label = UILabel()
label.text = "Add Photo : (3장 다 넣으세요)"
label.textColor = .textGray
label.frame = CGRect(x: 70, y: 5, width: 250, height: 20)
return label
}()
var plotField: UITextView = {
let label = UITextView()
label.textColor = .black
label.font = UIFont.systemFont(ofSize: 16)
label.frame = CGRect(x: 39, y: 240, width: 298, height: 250)
return label
}()
var stillcutImage: UIImageView = {
let ImageView = UIImageView()
let defaultImage = UIImage(named: "img_placeholder")
ImageView.image = defaultImage
ImageView.frame = CGRect(x: 20, y: 50, width: 100, height: 150)
return ImageView
}()
var stillcutImage2: UIImageView = {
let ImageView = UIImageView()
let defaultImage = UIImage(named: "img_placeholder")
ImageView.image = defaultImage
ImageView.frame = CGRect(x: 140, y: 50, width: 100, height: 150)
return ImageView
}()
var stillcutImage3: UIImageView = {
let ImageView = UIImageView()
let defaultImage = UIImage(named: "img_placeholder")
ImageView.image = defaultImage
ImageView.frame = CGRect(x: 260, y: 50, width: 100, height: 150)
return ImageView
}()
var OkButton : UIButton = {
let button = UIButton()
button.setTitle("Ok", for: .normal)
button.setTitleColor(.textGray, for: UIControl.State.normal)
button.frame = CGRect(x: 0 , y: 600, width: 375 / 2, height: 69.5)
return button
}()
var CancelButton : UIButton = {
let button = UIButton()
button.setTitle("Cancel", for: .normal)
button.setTitleColor(.textGray, for: UIControl.State.normal)
button.frame = CGRect(x: 375 / 2, y: 600, width: 375 / 2, height: 69.5)
return button
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.addSubview(plotField)
self.addSubview(stillcutImage)
self.addSubview(stillcutImage2)
self.addSubview(stillcutImage3)
self.addSubview(OkButton)
self.addSubview(addLabel)
self.addSubview(CancelButton)
plusBtn.makeRounded(cornerRadius: nil)
OkButton.layer.addBorder([.top , .right , .bottom], color: .color130, width: 1)
CancelButton.layer.addBorder([.top , .bottom], color: .color130, width: 1)
self.addSubview(plusBtn)
plusBtn.addTarget(self, action: #selector(didClick(_:)), for: .touchUpInside)
OkButton.addTarget(self, action: #selector(didOk(_:)), for: .touchUpInside)
CancelButton.addTarget(self, action: #selector(didCancel(_:)), for: .touchUpInside)
self.plotField.delegate = self
textViewDidChange(plotField)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
@objc func didClick(_ sender: Any) {
self.delegate?.didClickedPlus()
}
@objc func didOk(_ sender: Any) {
self.delegate?.didClickedOk()
}
@objc func didCancel(_ sender: Any) {
self.delegate?.didClickedCancel()
}
// MARK: UITextViewDelegate methods
func textViewDidChange(_ textView: UITextView) { //Handle the text changes here
print(textView.text!) //the textView parameter is the textView where text was changed
UserDefaults.standard.set(plotField.text, forKey: "memo")
}
}
| true
|
83459489a31e690c3bc7ab9b3d797ba5ef4169fb
|
Swift
|
givehighfive/TFS-Chat
|
/TFS Chat/Core/Network/JsonParser.swift
|
UTF-8
| 650
| 2.796875
| 3
|
[] |
no_license
|
//
// Parser.swift
// TFS Chat
//
// Created by dmitry on 19.11.2020.
// Copyright © 2020 dmitry. All rights reserved.
//
import Foundation
import UIKit
class JsonParser: ParserProtocol {
typealias Model = DataModel
func parse(data: Data) -> DataModel? {
do {
return try JSONDecoder().decode(DataModel.self, from: data)
} catch {
print("Error trying to convert data to JSON")
return nil
}
}
}
struct DataModel: Decodable {
let hits: [ImageData]
struct ImageData: Decodable {
let previewURL: String
let webformatURL: String
}
}
| true
|
ef6abccdafd738a9bb5425746c3aa4786df0531c
|
Swift
|
iAlirezaKML/AssetsGen
|
/Sources/AssetsGenLib/Utils/TextFiles.swift
|
UTF-8
| 4,219
| 2.609375
| 3
|
[] |
no_license
|
import Foundation
import DeepDiff
class TextFile: TextOutputStream {
let fileName: String
init(fileName: String) {
self.fileName = fileName
}
func write(_ string: String) {
let path = Configs.outputPath / fileName
FileUtils.makeSurePathExists(at: path)
let log = URL(fileURLWithPath: path)
do {
let handle = try FileHandle(forWritingTo: log)
handle.seekToEndOfFile()
handle.write(string.data(using: .utf8)!)
handle.closeFile()
} catch {
print(error.localizedDescription)
do {
try string.data(using: .utf8)?.write(to: log)
} catch {
print(error.localizedDescription)
}
}
}
func batchWrite(_ strings: [String]) {
write(strings.joined())
}
}
class CSVFile: TextFile {
override init(fileName: String) {
super.init(fileName: fileName + ".csv")
}
func join(_ values: [String]) -> String {
values.joined(separator: ",") + "\n"
}
func escape(_ content: String?) -> String {
"\"\(content ?? "")\""
}
}
final class ParseReplacesFile: CSVFile {
static let shared = ParseReplacesFile()
private init() {
super.init(fileName: "Replaces")
write(join([
"index",
"key",
"oldValue",
"newValue",
]))
}
func string(_ item: Replace<StringsSource.StringItem>) -> String {
join([
String(item.index),
item.oldItem.key,
escape(item.oldItem.value(for: Configs.baseLang, with: Configs.os)?.localizableValue),
escape(item.newItem.value(for: Configs.baseLang, with: Configs.os)?.localizableValue),
])
}
func write(_ items: [Replace<StringsSource.StringItem>]) {
batchWrite(items.map { string($0) })
}
}
final class ParseInsertsFile: CSVFile {
static let shared = ParseInsertsFile()
private init() {
super.init(fileName: "Inserts")
write(join([
"index",
"key",
"value",
]))
}
func string(_ item: Insert<StringsSource.StringItem>) -> String {
join([
String(item.index),
item.item.key,
escape(item.item.value(for: Configs.baseLang, with: Configs.os)?.localizableValue),
])
}
func write(_ items: [Insert<StringsSource.StringItem>]) {
batchWrite(items.map { string($0) })
}
}
final class ParseDeletesFile: CSVFile {
static let shared = ParseDeletesFile()
private init() {
super.init(fileName: "Deletes")
write(join([
"index",
"key",
"value",
]))
}
func string(_ item: Delete<StringsSource.StringItem>) -> String {
join([
String(item.index),
item.item.key,
escape(item.item.value(for: Configs.baseLang, with: Configs.os)?.localizableValue),
])
}
func write(_ items: [Delete<StringsSource.StringItem>]) {
batchWrite(items.map { string($0) })
}
}
final class ParseMovesFile: CSVFile {
static let shared = ParseMovesFile()
private init() {
super.init(fileName: "Moves")
write(join([
"fromIndex",
"toIndex",
"key",
"value",
]))
}
func string(_ item: Move<StringsSource.StringItem>) -> String {
join([
String(item.fromIndex),
String(item.toIndex),
item.item.key,
escape(item.item.value(for: Configs.baseLang, with: Configs.os)?.localizableValue),
])
}
func write(_ items: [Move<StringsSource.StringItem>]) {
batchWrite(items.map { string($0) })
}
}
final class ParseXLIFFFile: CSVFile {
static let shared = ParseXLIFFFile()
private init() {
super.init(fileName: "ParseXLIFFReconciliation")
write(join([
"key",
"jsonBaseValue",
"translatedBaseValue",
]))
}
func write(key: String, base: String, translated: String) {
write(join([
key,
escape(base),
escape(translated),
]))
}
}
final class DuplicateValuesFile: CSVFile {
static let shared = DuplicateValuesFile()
private init() {
super.init(fileName: "DuplicateValuesFile")
write(join([
"source",
"value",
"duplicatedKeys",
]))
}
func write(source: String, value: String, duplicatedKeys: [String]) {
write(join([
source,
value,
escape(duplicatedKeys.joined(separator: ";")),
]))
}
}
final class DuplicateKeysFile: CSVFile {
static let shared = DuplicateKeysFile()
private init() {
super.init(fileName: "DuplicateKeysFile")
write(join([
"source",
"key"
]))
}
func write(source: String, key: String) {
write(join([
source,
key
]))
}
}
| true
|
8b9ae501f17a0aa4a8f4cd3bfe96ec2aaac2e134
|
Swift
|
SamLee1990/Drink
|
/Drink/MenuTableViewCell.swift
|
UTF-8
| 1,098
| 2.640625
| 3
|
[] |
no_license
|
//
// MenuTableViewCell.swift
// Drink
//
// Created by 李世文 on 2020/8/18.
//
import UIKit
class MenuTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var introductionLabel: UILabel!
@IBOutlet weak var priceMiddleLabel: UILabel!
@IBOutlet weak var priceLargeLabel: UILabel!
@IBOutlet weak var largeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func update(with menu: Menu) {
nameLabel.text = menu.name
introductionLabel.text = menu.introduction
priceMiddleLabel.text = menu.priceMiddle.description
if menu.priceLarge == 0{
largeLabel.text = ""
priceLargeLabel.text = ""
}else{
largeLabel.text = "大:"
priceLargeLabel.text = menu.priceLarge.description
}
}
}
| true
|
e09fbf75d2a14c43de7828effec74654664e4688
|
Swift
|
mborsten/using-realm
|
/UsingRealm/RWSApi.swift
|
UTF-8
| 2,219
| 2.546875
| 3
|
[] |
no_license
|
//
// RWSApi.swift
// UsingRealm
//
// Created by Marcel Borsten on 30-04-17.
// Copyright © 2017 Impart IT. All rights reserved.
//
import Foundation
import RealmSwift
import Alamofire
import SwiftDate
struct RWSApi {
let url = "https://waterinfo.rws.nl/api/point/latestmeasurements?parameterid=golfhoogte"
let realm = try! Realm()
func syncWaves() {
Alamofire.request(url)
.validate()
.responseJSON() { jsonResponse in
switch jsonResponse.result {
case .failure(let error):
print("\(error)")
case .success(let json):
if let json = json as? [String:Any] {
if let features = json["features"] as? [[String:Any]] {
for f in features {
if let properties = f["properties"] as? [String:Any] {
if let name = properties["name"] as? String,
let measurements = properties["measurements"] as? [[String:Any]],
let measurement = measurements.first,
let latestValue = measurement["latestValue"] as? Double,
let dateString = measurement["dateTime"] as? String,
let locationCode = properties["locationCode"] as? Int {
let loc = Location()
loc.locationCode = locationCode
loc.name = name
loc.latestValue = latestValue
loc.date = dateString.date(formats: [.iso8601Auto])?.absoluteDate ?? Date()
try! self.realm.write {
self.realm.add(loc, update: true)
}
}
}
}
}
}
}
}
}
}
| true
|
d47954144e9ced04041b8208d706e48c5257466b
|
Swift
|
iataylor15/COVID-Lens-App
|
/Project Code/Swift/CovidLens/COVID Lens/Models/UserData.swift
|
UTF-8
| 17,411
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// Created by Seth Goodwin on 10/5/20.
//
import SwiftUI
import CoreLocation
import Foundation
import SwiftKeychainWrapper
import CommonCrypto
class UserData {
static let USER_ID = "USER_ID"
static let PASSWORD = "PASSWORD"
static let SIGNED_IN = "SIGNED_IN"
static let GOOGLE_ID = "GOOGLE_ID"
static let USER_EMAIL = "EMAIL"
static let NO_USER = "NO_USER"
static let USER_STORE = "USER_STORE"
private let REQUEST_CATCHER_URL = "https://www.covidlensapp.com/request-catcher"
private let USER_CREATION = "USER_CREATION"
private let USER_SIGN_IN = "USER_SIGN_IN"
private let USER_SIGN_OUT = "USER_SIGN_OUT"
private let USER_DATA_REQUEST = "USER_DATA_REQUEST"
private let USER_SAVE = "USER_SAVE"
private var dataResponse: [String: Any]!
private let submissionSemaphore = DispatchSemaphore(value: 0)
/**
This function creates a new user
- Returns: true is returned if creation was successful otherwise false
*/
func createUser(newUser: User) -> Bool {
UserDefaults.standard.setValue(false, forKey: UserData.SIGNED_IN)
if UserDefaults.standard.bool(forKey: UserData.SIGNED_IN) == false {
var uuid = createUUID()
if isValidEmail(newUser.getEmail()) && isValidPassword(newUser.getPassword()) {
// attempt multiple times in case ID already existed for another user
var attempt = 5
repeat {
var parameters = [String: Any]()
let userID = uuid
var userWithID = newUser
//giving a new user an id
userWithID.setBasicID(basicID: userID)
parameters["request"] = USER_CREATION
do {
parameters["userData"] = String(data: try JSONEncoder().encode(userWithID), encoding: .utf8)
//parameters["userData"] = "some data"
} catch {
// probably should handle this better...
parameters["userData"] = ""
}
parameters["userEmail"] = userWithID.getEmail()
// if user has a google id
if userWithID.getGoogleID() != "" {
parameters["userPassword"] = userWithID.getGoogleID()
}else{
//user does not have a google id
parameters["userPassword"] = userWithID.getPassword()
}
parameters["userPassword"] = userWithID.getPassword()
parameters["userID"] = userID
parameters["googleID"] = userWithID.getGoogleID()
parameters["signedIn"] = true
postData(parameters: parameters, postUrl: REQUEST_CATCHER_URL)
// waiting for response from server
submissionSemaphore.wait()
if dataResponse != nil && dataResponse!["status"] as? String == "SUCCESS" {
// user is now logged in
UserDefaults.standard.setValue(userWithID.getLoggedIn(), forKey: UserData.SIGNED_IN) //storing data securely using keychain
return storeCredentials(user: userWithID)
} else {
uuid = createUUID()
attempt -= attempt
}
} while attempt > 0
}
}
return false
}
/**
This function loads an existing user or signs them in if they were logged out
- Returns: true is returned if load/signin was successful
*/
func loadUser(user: User) -> Bool {
var parameters = [String: Any]()
parameters["request"] = USER_SIGN_IN
do {
parameters["userData"] = String(data: try JSONEncoder().encode(user), encoding: .utf8)
} catch {
// probably should handle this better...
parameters["userData"] = ""
}
parameters["signedIn"] = user.getLoggedIn() //false
// not signed in
if UserDefaults.standard.bool(forKey: UserData.SIGNED_IN) == false {
parameters["email"] = user.getEmail()
parameters["password"] = user.getPassword()
parameters["userID"] = user.getBasicId()
parameters["googleID"] = user.getGoogleID()
// check if user credentials found in database
postData(parameters: parameters, postUrl: REQUEST_CATCHER_URL)
// waiting for response from server
submissionSemaphore.wait()
if dataResponse != nil && dataResponse!["status"] as? String == "SUCCESS" {
//store credentials
let str = (dataResponse["data"] as! String).base64Decoded
let data = Data(str!.utf8)
do {
// make sure this JSON is in the format we expect
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
dataResponse["data"] = json
return storeCredentials(user: user)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
}else{
// retrieve credentials from keychain
let credentials = retreiveCredentials()
parameters["email"] = credentials[UserData.USER_EMAIL]
parameters["password"] = credentials[UserData.PASSWORD]
parameters["userID"] = credentials[UserData.USER_ID]
parameters["googleID"] = credentials[UserData.GOOGLE_ID]
postData(parameters: parameters, postUrl: REQUEST_CATCHER_URL)
// waiting for response from server
submissionSemaphore.wait()
if dataResponse!["status"] as? String == "SUCCESS"{
// signed in
UserDefaults.standard.setValue(user.getLoggedIn(), forKey: UserData.SIGNED_IN)
return true
}
}
return false
}
/**
This function stores the users credentials securely using keychain
- Returns true if successfully stored
*/
func storeCredentials(user: User) ->Bool {
//storing data securely using keychain
let emailSaved: Bool = KeychainWrapper.standard.set(user.getEmail(), forKey: UserData.USER_EMAIL)
let passwordSaved: Bool = KeychainWrapper.standard.set(user.getPassword(), forKey: UserData.PASSWORD)
let userIDSaved: Bool = KeychainWrapper.standard.set(user.getBasicId(), forKey: UserData.USER_ID)
if user.getGoogleID() != "" {
let googleUser = KeychainWrapper.standard.set(user.getGoogleID(), forKey: UserData.GOOGLE_ID)
return emailSaved && passwordSaved && userIDSaved && googleUser
}
return emailSaved && passwordSaved && userIDSaved
}
func retreiveCredentials() -> [String:Any] {
if UserDefaults.standard.bool(forKey: UserData.SIGNED_IN){
return [UserData.USER_EMAIL: KeychainWrapper.standard.string(forKey: UserData.USER_EMAIL) ?? "",UserData.PASSWORD: KeychainWrapper.standard.string(forKey: UserData.PASSWORD) ?? "",
UserData.USER_ID: KeychainWrapper.standard.string(forKey: UserData.USER_ID) ?? "",
UserData.GOOGLE_ID: KeychainWrapper.standard.string(forKey: UserData.GOOGLE_ID) ?? ""]
}
return [:]
}
func removeCredentials() -> Bool {
return KeychainWrapper.standard.removeAllKeys()
}
func save(user: User) -> Bool{
if UserDefaults.standard.bool(forKey: UserData.SIGNED_IN){
var parameters = [String: Any]()
parameters["request"] = USER_SAVE
do {
parameters["userData"] = String(data: try JSONEncoder().encode(user), encoding: .utf8)
} catch {
// probably should handle this better...
parameters["userData"] = ""
}
parameters["email"] = user.getEmail()
parameters["password"] = user.getPassword()
parameters["userID"] = user.getBasicId()
parameters["googleID"] = user.getGoogleID()
parameters["signedIn"] = user.getLoggedIn()
if user.getLoggedIn() == false {
parameters["request"] = USER_SIGN_OUT
}
postData(parameters: parameters, postUrl: REQUEST_CATCHER_URL)
// waiting for response from server
submissionSemaphore.wait()
if dataResponse != nil, dataResponse!["status"] as? String == "SUCCESS" {
// simple storage of user in defaults after removing sensitive data
/*
var simpleUser = user
simpleUser.setBasicID(basicID: "")
simpleUser.setPassword(password: "")
simpleUser.setEmail(email: "")
simpleUser.setGoogleID(googleID: "")
simpleUser.setReport(report: Report(age: 0, phoneNumber: "NA", residenceHall: "NA", affiliation: "NA", locationID: "NA", reportStatus: "NA", reportInfo: "NA", situationDescription: "NA", confirmerID: "NA", submitterID:"NA", reportID: "NA"))
//storing json user
var userJson = ""
do {
userJson = String(data: try JSONEncoder().encode(simpleUser), encoding: .utf8) ?? ""
} catch {
}
UserDefaults.standard.setValue(userJson, forKey: UserData.USER_STORE)
*/
// store credentials just in case they have been updated
return storeCredentials(user: user)
}
}
return false
}
func logout(user: User) -> Bool{
var loggedOutUser = user
loggedOutUser.setLoggedIn(status: true)
let response = save(user: loggedOutUser)
// if save was successful, user will be logged out
if response{
UserDefaults.standard.setValue(loggedOutUser.getLoggedIn(), forKey: UserData.SIGNED_IN)
}
return response && removeCredentials()
}
/**
This function is used for updating the apps data
- Returns:true if update was successful and false if not
*/
func DataRequest(user: User?) -> Bool {
var parameters = [String: Any]()
// if already logged in
if UserDefaults.standard.bool(forKey: UserData.SIGNED_IN){
// retrieve credentials from keychain
let credentials = retreiveCredentials()
parameters["email"] = credentials[UserData.USER_EMAIL]
parameters["password"] = credentials[UserData.PASSWORD]
parameters["userID"] = credentials[UserData.USER_ID]
parameters["googleID"] = credentials[UserData.GOOGLE_ID]
postData(parameters: parameters, postUrl: REQUEST_CATCHER_URL)
submissionSemaphore.wait()
} else {
print("in else")
parameters["request"] = USER_DATA_REQUEST
do {
parameters["userData"] = String(data: try JSONEncoder().encode(user), encoding: .utf8)
} catch {
// probably should handle this better...
parameters["userData"] = ""
}
print("setting post values")
parameters["email"] = user?.getEmail()
parameters["password"] = user?.getPassword()
parameters["userID"] = user?.getBasicId()
parameters["googleID"] = user?.getGoogleID()
parameters["signedIn"] = user?.getLoggedIn()
postData(parameters: parameters, postUrl: REQUEST_CATCHER_URL)
// waiting for response from server
submissionSemaphore.wait()
}
//dataResponse = ["status": "SUCCESS", "data": ""]
if dataResponse != nil && dataResponse!["status"] as? String == "SUCCESS" {
// do something
print("success")
return true
}
return false
}
/**
This function returns the data received from the most recent request
- Returns: [String:Any]
*/
func getResponse() -> [String:Any]{
var dict: [String:Any] = [:]
if self.dataResponse != nil{
dump(dataResponse)
for (key, value) in self.dataResponse{
dict[key] = value is NSNull ? "": value
}
} else {
print("data is nil")
}
return dict
}
func decodeUser(jsonUserData: String) -> User {
let jsonDecoder = JSONDecoder()
var user:User
do{
user = try jsonDecoder.decode(User.self, from: Data(jsonUserData.utf8))
} catch{
user = User()
}
return user
}
/**
This function creates a unique identifier for the app user
*/
private func createUUID() -> String {
return NSUUID().uuidString
}
/**
This function checks a string to see if it is a valid email address
- Returns: true if valid, false if invalid
*/
private func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format: "SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
/**
This function checks a string to see if it is a valid password
- Returns: true if valid, false if invlid
*/
private func isValidPassword(_ testStr: String?) -> Bool {
guard testStr != nil else { return false }
// at least one uppercase,
// at least one digit
// at least one lowercase
// 8 characters total
let passwordTest = NSPredicate(format: "SELF MATCHES %@", "(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,}")
return passwordTest.evaluate(with: testStr)
}
/**
This function sends data to the server
*/
private func postData(parameters: [String: Any], postUrl: String) {
let url = URL(string: postUrl)!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = parameters.percentEncoded()
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else { // check for fundamental networking error
print("error", error ?? "Unknown error")
return
}
guard (200 ... 299) ~= response.statusCode else { // check for http errors
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
print(String(data: data, encoding: .utf8)!)
self.dataResponse = self.convertToDictionary(text: String(data: data, encoding: .utf8)!)
// using semaphores to signal other processes to let them execute after data transfers
if postUrl == self.REQUEST_CATCHER_URL {
self.submissionSemaphore.signal()
}
}
task.resume()
}
//
//
func randomString(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map{ _ in letters.randomElement()! })
}
/**
This function converts a json string to a dictionary
*/
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
}
extension Dictionary {
func percentEncoded() -> Data? {
return map { key, value in
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
.data(using: .utf8)
}
}
extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}
public extension String {
var base64Decoded: String? {
guard let decodedData = Data(base64Encoded: self) else { return nil }
return String(data: decodedData, encoding: .utf8)
}
}
| true
|
8145216f4be2145a96165181bbfce2e4049b1ec7
|
Swift
|
Chidiemeh184/SwiftLearningExercises
|
/DogAndCat.playground/DogAndCat.playground/Contents.swift
|
UTF-8
| 4,488
| 3.90625
| 4
|
[] |
no_license
|
//============================================================
// NAME: CHIDI EMEH
// COURSE: CSCI 2994 (iOS Programming Fundamentals)
// FILENAME: DogAndCat.playground
// DATE: 4/15/2016
// EXERCISE 8: This program demonstrates creating classes
// and its properties and methods
//=============================================================
import UIKit
class Dog: CustomDebugStringConvertible, Hashable {
var breed: String!
var color: String!
var age: Int!
var name: String!
//Property Observers
var growingHeight: Int = 0 {
willSet{
print("\(name)'s new height is \(newValue)ft")
}
didSet{
print("\(name)'s old height was \(oldValue)ft")
}
}
var hashValue: Int {
return "\(breed), \(color), \(age), \(name)".hashValue
}
init(breed: String, color:String, age:Int, name:String){
self.breed = breed
self.color = color
self.age = age
self.name = name
}
convenience init(){
self.init(breed: "pit", color: "white", age: 0 , name: "Gertrude")
}
//Read only computed Properties
var getName: String {
return self.name
}
var getBreed: String {
return self.breed
}
var getColor: String {
return self.color
}
var getAge: Int {
return self.age
}
//Methods
func barking(barkingSound sound: String) -> String {
return "\(self.name): BARKING!! (\(sound))"
}
func eating(food food: String) -> String {
return "\(self.name): ... eating (\(food))"
}
func sleeping(sleepingWhere sleepingWhere: String) -> String {
return "\(self.name): ... sleeping on (\(sleepingWhere))"
}
func playing( with with: String) -> String{
return "\(self.name): ... playing with (\(with))"
}
func chase(what what: String) -> String {
return "\(self.name): ... chasing a (\(what))"
}
deinit{
print("\(self.name) has been removed from memory")
}
var debugDescription: String {
return " \(self.name)"
}
}
class Cat: CustomDebugStringConvertible, Hashable{
var breed: String!
var color: String!
var age: Int!
var name: String
//Property Observers
var growingHeight: Int = 0 {
willSet{
print("\(name)'s new height is \(newValue)ft")
}
didSet{
print("\(name)'s old height was \(oldValue)ft")
}
}
var hashValue: Int {
return "\(breed), \(color), \(age), \(name)".hashValue
}
init(breed: String, color:String, age:Int, name:String){
self.breed = breed
self.color = color
self.age = age
self.name = name
}
convenience init(){
self.init(breed: "short", color: "", age: 0 , name: "Garfield")
}
var getName: String {
return self.name
}
var getBreed: String {
return self.breed
}
var getColor: String {
return self.color
}
var getAge: Int {
return self.age
}
func meow() -> String {
return "\(self.name): Meowing!"
}
func eating(food food: String) -> String {
return "\(self.name): ... eating (\(food))"
}
func sleeping(sleepingWhere sleepingWhere: String) -> String {
return "\(self.name): ... sleeping on (\(sleepingWhere))"
}
func playing( with with: String) -> String{
return "\(self.name): ... playing with (\(with))"
}
func chase(what what: String) -> String {
return "\(self.name): ... chasing a (\(what))"
}
deinit{
print("\(self.name) has been removed from memory")
}
var debugDescription: String {
return " \(self.name)"
}
}
func ==(lhs: Cat, rhs: Cat) -> Bool{
return lhs.hashValue == rhs.hashValue
}
func ==(lhs: Dog, rhs: Dog) -> Bool{
return lhs.hashValue == rhs.hashValue
}
//Creating Dog
var groot = Dog(breed: "bull", color: "brown", age: 3, name: "groot")
groot.growingHeight = 3
groot.playing(with: "biscuit bone")
groot.eating(food: "wafer")
//Creating Cat
var tom = Cat(breed: "cartoon", color: "Blue and white", age: 9, name: "Tom cat")
tom.growingHeight = 5
tom.chase(what: "Jerry the mouse")
tom.sleeping(sleepingWhere: "the counch")
| true
|
183ebea03f7523a73a10f2548cd990bd2e36293f
|
Swift
|
baveku/MVVM-ViewInjection
|
/MVVM Project Template.xctemplate/Extensions/Number+Extensions.swift
|
UTF-8
| 409
| 2.796875
| 3
|
[] |
no_license
|
//
// Number+Extensions.swift
// ___PROJECTNAME___
//
// Created ___FULLUSERNAME___ on ___DATE___.
// Copyright © ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import Foundation
extension Double {
func toDollars() -> String {
return String(format: "$%.02f", self)
}
func roundTwoDecimal() -> String {
return String(format: "%.02f", self)
}
}
| true
|
2464aa9f8634d2a7f9ae35ba3f4dd1668cbb3fb1
|
Swift
|
dkeso611/Coding-Challenges
|
/LinkedListProblems.playground/Contents.swift
|
UTF-8
| 1,778
| 4.0625
| 4
|
[] |
no_license
|
import UIKit
class Node {
var value: Int
var next: Node?
weak var previous: Node?
init(value: Int) {
self.value = value
}
}
struct LinkedList {
var head: Node?
var isEmpty: Bool
init(node: Node) {
self.head = node
isEmpty = false
}
mutating func checkIsEmpty() -> Bool {
if head != nil {
isEmpty = false
} else {
isEmpty = true
}
return isEmpty
}
mutating func append(node: Node){
guard head != nil else {
head = node
return
}
var currentNode = head
while currentNode?.next != nil {
currentNode = currentNode?.next
}
currentNode?.next = node
node.previous = currentNode
}
//insert node by value in sorted linked list
mutating func insert(node: Node){
var currentNode = head?.next
if (head?.value)! > node.value {
node.next = head
head = node
} else {
print(currentNode?.value, node.value)
while (currentNode?.value)! < node.value {
currentNode = currentNode?.next
}
// var prev = currentNode?.previous
// currentNode?.previous = node
// prev?.next = currentNode?.previous
currentNode?.previous?.next = node
currentNode?.previous = node
}
}
}
var list = LinkedList(node: Node(value: 5))
list.isEmpty
list.append(node: Node(value: 7))
list.append(node: Node(value: 10))
list.insert(node: Node(value: 9))
list.head?.next?.next?.value
list.head = nil
list.head?.value
list.isEmpty
list.checkIsEmpty()
| true
|
ce30929eee0c1257cfb7e9a2a61168552b0b00ee
|
Swift
|
jsshotts/DrawingUnitCircle
|
/DrawingUnitCircle/LearnViewController.swift
|
UTF-8
| 23,997
| 2.671875
| 3
|
[] |
no_license
|
//
// LearnViewController.swift
// DrawingUnitCircle
//
// Created by CheckoutUser on 11/18/17.
// Copyright © 2017 Jason. All rights reserved.
//
import UIKit
class LearnViewController: UIViewController {
var question = ""
var angle = CGFloat(0)
var valueLocation: UInt32 = 0
let trigSet = ["sin", "cos", "tan", "csc", "sec", "cot"]
let divisorSet = ["", "/2", "/3", "/3", "/4", "/4", "/4", "/6", "/6", "/6"]
let π = CGFloat.pi
let answerSet = ["1", "-1", "0", "1/2", "-1/2", "sqrt(2)/2", "-sqrt(2)/2", "sqrt(3)/2", "-sqrt(3)/2", "undefined", "2", "-2", "2/sqrt(2)", "-2/sqrt(2)", "2/sqrt(3)", "-2/sqrt(3)"]
var tempTrigFunc = ""
var tempDivisor = ""
var tempAnswer = CGFloat(0)
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var button1: UIButton!
@IBAction func button1Pressed(_ sender: Any) {
if button1.titleLabel?.text == ("\(tempAnswer)"){
performSegue(withIdentifier: "ShowCorrectScene", sender: nil)
}
if button1.titleLabel?.text != ("\(tempAnswer)"){
performSegue(withIdentifier: "ShowIncorrectScene", sender: nil)
}
}
@IBOutlet weak var button2: UIButton!
@IBAction func button2Pressed(_ sender: Any) {
if button2.titleLabel?.text == ("\(tempAnswer)"){
performSegue(withIdentifier: "ShowCorrectScene", sender: nil)
}
if button2.titleLabel?.text != ("\(tempAnswer)"){
performSegue(withIdentifier: "ShowIncorrectScene", sender: nil)
}
}
@IBOutlet weak var button3: UIButton!
@IBAction func button3Pressed(_ sender: Any) {
if button3.titleLabel?.text == ("\(tempAnswer)"){
performSegue(withIdentifier: "ShowCorrectScene", sender: nil)
}
if button3.titleLabel?.text != ("\(tempAnswer)"){
performSegue(withIdentifier: "ShowIncorrectScene", sender: nil)
}
}
@IBOutlet weak var button4: UIButton!
@IBAction func button4Pressed(_ sender: Any) {
if button4.titleLabel?.text == ("\(tempAnswer)"){
performSegue(withIdentifier: "ShowCorrectScene", sender: nil)
}
if button4.titleLabel?.text != ("\(tempAnswer)"){
performSegue(withIdentifier: "ShowIncorrectScene", sender: nil)
}
}
override func viewWillAppear(_ animated: Bool) {
questionLabel.text = question
var buttonSet = [button1, button2, button3, button4]
var tempAnswerSet = answerSet
// print (tempAnswer)
// print ("rounded: \(round(tempAnswer))")
buttonSet[Int(valueLocation)]!.setTitle("\(tempAnswer)", for: UIControlState.normal)
buttonSet.remove(at: Int(valueLocation))
let button1tempAnswerIndex = Int(arc4random_uniform(15))
buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
tempAnswerSet.remove(at: button1tempAnswerIndex)
let button2tempAnswerIndex = Int(arc4random_uniform(14))
buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
tempAnswerSet.remove(at: button2tempAnswerIndex)
let button3tempAnswerIndex = Int(arc4random_uniform(13))
buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// if tempAnswer == 1.0{
//
// print ("if statement()")
//
// buttonSet[Int(valueLocation)]!.setTitle("1", for: UIControlState.normal)
// buttonSet.remove(at: Int(valueLocation))
// tempAnswerSet.remove(at: 0)
// print(tempAnswerSet)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
// print(tempAnswerSet)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
// print(tempAnswerSet)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// print(tempAnswerSet)
// }
// if tempAnswer == -1.0{
//
// buttonSet[Int(valueLocation)]!.setTitle("-1", for: UIControlState.normal)
// buttonSet.remove(at: Int(valueLocation))
// tempAnswerSet.remove(at: 1)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if tempAnswer <= 0.0{
// if tempAnswer > -0.00000000000001{
// buttonSet[Int(valueLocation)]!.setTitle("0", for: UIControlState.normal)
// buttonSet.remove(at: Int(valueLocation))
// tempAnswerSet.remove(at: 2)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// }
// if tempAnswer >= 0.0{
// if tempAnswer < 0.00000000000001{
//
// buttonSet[Int(valueLocation)]!.setTitle("0", for: UIControlState.normal)
// buttonSet.remove(at: Int(valueLocation))
// tempAnswerSet.remove(at: 2)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// }
// if tempAnswer == 0.5{
//
// buttonSet[Int(valueLocation)]!.setTitle("1/2", for: UIControlState.normal)
// buttonSet.remove(at: Int(valueLocation))
// tempAnswerSet.remove(at: 3)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if tempAnswer == -0.5{
//
// buttonSet[Int(valueLocation)]!.setTitle("-1/2", for: UIControlState.normal)
// buttonSet.remove(at: Int(valueLocation))
// tempAnswerSet.remove(at: 4)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if round(tempAnswer) == round(sqrt(2)/2){
//
// buttonSet[Int(valueLocation)]!.setTitle("sqrtf(2)/2", for: UIControlState.normal)
// tempAnswerSet.remove(at: 5)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if round(tempAnswer) == -round(sqrt(2)/2){
//
// buttonSet[Int(valueLocation)]!.setTitle("-sqrtf(2)/2", for: UIControlState.normal)
// tempAnswerSet.remove(at: 6)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if round(tempAnswer) == round(sqrt(3)/2){
//
// buttonSet[Int(valueLocation)]!.setTitle("sqrtf(3)/2", for: UIControlState.normal)
// tempAnswerSet.remove(at: 7)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if round(tempAnswer) == -round(sqrt(3)/2){
//
// buttonSet[Int(valueLocation)]!.setTitle("-sqrtf(3)/2", for: UIControlState.normal)
// tempAnswerSet.remove(at: 8)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if tempAnswer > 10000.0{
//
// buttonSet[Int(valueLocation)]!.setTitle("undefined", for: UIControlState.normal)
// tempAnswerSet.remove(at: 9)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
//
// }
// if tempAnswer < -10000.0{
//
// buttonSet[Int(valueLocation)]!.setTitle("undefined", for: UIControlState.normal)
// tempAnswerSet.remove(at: 9)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if tempAnswer == 2.0{
//
// buttonSet[Int(valueLocation)]!.setTitle("2", for: UIControlState.normal)
// tempAnswerSet.remove(at: 10)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if tempAnswer == -2.0{
//
// buttonSet[Int(valueLocation)]!.setTitle("-2", for: UIControlState.normal)
// tempAnswerSet.remove(at: 11)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if round(tempAnswer) == round(2.0/sqrt(2)){
//
// buttonSet[Int(valueLocation)]!.setTitle("2/sqrt(2)", for: UIControlState.normal)
// tempAnswerSet.remove(at: 12)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if round(tempAnswer) == -round(2.0/sqrt(2)){
//
// buttonSet[Int(valueLocation)]!.setTitle("-2/sqrt(2)", for: UIControlState.normal)
// tempAnswerSet.remove(at: 13)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if round(tempAnswer) == round(2.0/sqrt(3)){
//
// buttonSet[Int(valueLocation)]!.setTitle("2/sqrt(3)", for: UIControlState.normal)
// tempAnswerSet.remove(at: 14)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
// if round(tempAnswer) == -round(2.0/sqrt(3)){
//
// buttonSet[Int(valueLocation)]!.setTitle("-2/sqrt(3)", for: UIControlState.normal)
// tempAnswerSet.remove(at: 15)
//
// let button1tempAnswerIndex = Int(arc4random_uniform(15))
// buttonSet[0]!.setTitle(tempAnswerSet[button1tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button1tempAnswerIndex)
//
// let button2tempAnswerIndex = Int(arc4random_uniform(14))
// buttonSet[1]!.setTitle(tempAnswerSet[button2tempAnswerIndex], for: UIControlState.normal)
// tempAnswerSet.remove(at: button2tempAnswerIndex)
//
// let button3tempAnswerIndex = Int(arc4random_uniform(13))
// buttonSet[2]!.setTitle(tempAnswerSet[button3tempAnswerIndex], for: UIControlState.normal)
// }
}
// override func viewDidDisappear(_ animated: Bool) {
//
// tempTrigFunc = trigSet[Int(arc4random_uniform(6))]
// tempDivisor = divisorSet[Int(arc4random_uniform(10))]
//
// let number = Int(arc4random_uniform(10))
// let numberFloat = CGFloat(number)
//
// question = "\(tempTrigFunc) \(number)π\(tempDivisor)"
//
// if number == 0 {
// question = "\(tempTrigFunc) 0"
// }
// if number == 1 {
// question = "\(tempTrigFunc) π\(tempDivisor)"
// }
//
//
//
// //divisor check
// if tempDivisor == divisorSet[0]{
// angle = numberFloat * π
// }
// if tempDivisor == divisorSet[1]{
// angle = numberFloat/2
// }
// if tempDivisor == divisorSet[2]{
// angle = numberFloat/3
// }
// if tempDivisor == divisorSet[4]{
// angle = numberFloat/4
// }
// if tempDivisor == divisorSet[7]{
// angle = numberFloat/6
// }
//
//
//
// //temporary answer
// if tempTrigFunc == trigSet[0]{
// tempAnswer = sin(angle)
// }
// if tempTrigFunc == trigSet[1]{
// tempAnswer = cos(angle)
// }
// if tempTrigFunc == trigSet[2]{
// tempAnswer = tan(angle)
// }
// if tempTrigFunc == trigSet[3]{
// tempAnswer = 1/sin(angle)
// }
// if tempTrigFunc == trigSet[4]{
// tempAnswer = 1/cos(angle)
// }
// if tempTrigFunc == trigSet[5]{
// tempAnswer = 1/tan(angle)
// }
//
//
// valueLocation = arc4random_uniform(4)
// print(tempTrigFunc)
// print(tempAnswer)
// }
override func viewDidLoad() {
super.viewDidLoad()
tempTrigFunc = trigSet[Int(arc4random_uniform(6))]
tempDivisor = divisorSet[Int(arc4random_uniform(10))]
let number = Int(arc4random_uniform(10))
let numberFloat = CGFloat(number)
question = "\(tempTrigFunc) \(number)π\(tempDivisor)"
if number == 0 {
question = "\(tempTrigFunc) 0"
}
if number == 1 {
question = "\(tempTrigFunc) π\(tempDivisor)"
}
if tempDivisor == divisorSet[0]{
angle = numberFloat * π
}
if tempDivisor == divisorSet[1]{
angle = (numberFloat * π)/2
}
if tempDivisor == divisorSet[2]{
angle = (numberFloat * π)/3
}
if tempDivisor == divisorSet[4]{
angle = (numberFloat * π)/4
}
if tempDivisor == divisorSet[7]{
angle = (numberFloat * π)/6
}
if tempTrigFunc == trigSet[0]{
tempAnswer = sin(angle)
}
if tempTrigFunc == trigSet[1]{
tempAnswer = cos(angle)
}
if tempTrigFunc == trigSet[2]{
tempAnswer = sin(angle)/cos(angle)
}
if tempTrigFunc == trigSet[3]{
tempAnswer = 1/(sin(angle))
}
if tempTrigFunc == trigSet[4]{
tempAnswer = 1/(cos(angle))
}
if tempTrigFunc == trigSet[5]{
tempAnswer = cos(angle)/sin(angle)
}
valueLocation = arc4random_uniform(4)
}
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?) {
if segue.identifier == "ShowIncorrectScene" {
let destination = segue.destination as? IncorrectViewController
destination?.angle = angle
destination?.labelText = "\(question) = \(tempAnswer)"
}
if segue.identifier == "ShowCorrectScene" {
let destination = segue.destination as? CorrectViewController
destination?.angle = angle
destination?.labelText = "\(question) = \(tempAnswer)"
}
}
}
| true
|
2ab7bf61b6dc537d55735608c72906ab5d358c83
|
Swift
|
Radwa5aled/Repository-list-online-and-offline
|
/JakeWhartonRepos/Cells/ReposCell.swift
|
UTF-8
| 2,726
| 2.546875
| 3
|
[] |
no_license
|
//
// ReposCell.swift
// JakeWhartonRepos
//
// Created by Radwa Khaled on 8/27/19.
// Copyright © 2019 Radwa Khaled. All rights reserved.
//
import UIKit
class ReposCell: UITableViewCell {
@IBOutlet weak var lblRepoName: UILabel!
@IBOutlet weak var lblArchived: UILabel!
@IBOutlet weak var lblDescription: UILabel!
@IBOutlet weak var lblLanguage: UILabel!
@IBOutlet weak var lblWatchersCount: UILabel!
@IBOutlet weak var lblForksCount: UILabel!
@IBOutlet weak var lblLicense: UILabel!
@IBOutlet weak var licenseView: UIView!
@IBOutlet weak var lblUpdateAt: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setData(model:ReposModel) {
lblRepoName.text = model.name
lblDescription.text = model.repoDescription
lblLanguage.text = model.language
lblWatchersCount.text = String(model.watchers)
lblForksCount.text = String(model.forks)
if let date = model.pushedAt {
lblUpdateAt.text = "Updated " + Utilities.shared.calculateDateStrToComponent(date: date)
lblUpdateAt.isHidden = false
}else {
lblUpdateAt.isHidden = true
}
if let license = model.license {
lblLicense.text = license.name
licenseView.isHidden = false
}else {
licenseView.isHidden = true
}
if model.archived {
lblArchived.isHidden = false
}else {
lblArchived.isHidden = true
}
}
func setOfflineData(model:Repositories) {
lblRepoName.text = model.name
lblDescription.text = model.repoDescription
lblLanguage.text = model.language
lblWatchersCount.text = String(model.watchers)
lblForksCount.text = String(model.forks)
if let date = model.pushedAt {
lblUpdateAt.text = "Updated " + Utilities.shared.calculateDateStrToComponent(date: date)
lblUpdateAt.isHidden = false
}else {
lblUpdateAt.isHidden = true
}
if let license = model.licenseName {
lblLicense.text = license
licenseView.isHidden = false
}else {
licenseView.isHidden = true
}
if model.archived {
lblArchived.isHidden = false
}else {
lblArchived.isHidden = true
}
}
}
| true
|
8bfe024bc910660dd22fbe3079ff80796bbd46d3
|
Swift
|
dewo3276/Woods_MAD_Spring2021
|
/CU Majors/CU Majors/TableViewController.swift
|
UTF-8
| 2,475
| 2.71875
| 3
|
[] |
no_license
|
//
// TableViewController.swift
// CU Majors
//
// Created by Dusty on 2/16/21.
//
import UIKit
class TableViewController: UITableViewController {
var collegeList = [String]()
var collegeData = collegeMajorLoader()
var dataFile = "collegeMajors"
var selectedCollege = Int()
override func viewDidLoad() {
super.viewDidLoad()
collegeData.loadData(filename: dataFile)
collegeList=collegeData.getCollege()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
navigationController?.navigationBar.prefersLargeTitles = true
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return collegeList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "collegeIdentifier", for: indexPath)
cell.textLabel?.text = collegeList[indexPath.row]
selectedCollege=indexPath.row
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "majorViewer" {
if let detailVC = segue.destination as? DetailTableViewController {
if let indexPath = tableView.indexPath(for: (sender as? UITableViewCell)!) {
//sets the data for the destination controller
detailVC.title = collegeList[indexPath.row]
detailVC.collegeData = collegeData
detailVC.selectedCollege = indexPath.row
}
}
} //for detail disclosure
else if segue.identifier == "webService"{
let infoVC = segue.destination as! webViewController
let URL = collegeData.getURL(index: selectedCollege)
infoVC.websiteURL=URL
}
}
}
| true
|
30c6fa9392617e5e95596e81633cc7836dd40f07
|
Swift
|
emn-mun/UserPosts
|
/UserPosts/UserPosts/UserPostsKit/Subsystems/Controllers/Handlers.swift
|
UTF-8
| 206
| 2.59375
| 3
|
[] |
no_license
|
protocol UsersHandler {
func fetchUsers(completion: @escaping (Result<[User]>) -> ())
}
protocol PostsHandler {
func fetchPosts(forUser userID: Int, completion: @escaping (Result<[Post]>) -> ())
}
| true
|
14d37ddca5ec78534fd7ebfd01243ab7a5f2bc32
|
Swift
|
barajs/bara-studio
|
/Bara Studio/ContentView.swift
|
UTF-8
| 1,129
| 3.03125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// Bara Studio
//
// Created by VGM Builder on 1/17/20.
// Copyright © 2020 BaraJS. All rights reserved.
//
import SwiftUI
struct Location {
static let allLocations = [
"New York",
"London",
"Tokyo",
"Berlin",
"Paris"
]
}
struct ContentView: View {
@State private var firstname = ""
@State private var lastname = ""
@State private var location = ""
var body: some View {
NavigationView {
Form {
TextField("Firstname",
text: $firstname)
TextField("Lastname",
text: $lastname)
Picker(selection: $location,
label: Text("Location")) {
ForEach(Location.allLocations, id: \.self) { location in
Text(location).tag(location)
}
}
}.navigationBarTitle(Text("Profile"))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
501572362a817bbab09f37bb550c08b69897c363
|
Swift
|
knyghtmare/knyght-swift
|
/MyPlayground.playground/Contents.swift
|
UTF-8
| 445
| 4.25
| 4
|
[
"MIT"
] |
permissive
|
import Cocoa
// in swift, variables holds data
// the var keyword is used to declare a new
// varaible
// equal key is the assignment operator
var str = "Hello, playground"
// prints with a new line
print(str)
var a = 1
var b = 2
b = 1
print(a+b)
print(a-b)
print(a*b)
print(a/b)
// let keyword will NOT
// allow you to change the
// variable
let c = 10
// Data Types
var str2:String = "Hello World!"
var d:Int = 23
var e:Float = 2.3
| true
|
d31adbd8f8bee8ed5d199e43ff2ae7ba531bfff2
|
Swift
|
matsubo0516/dippaStore
|
/dippaStore3/Entity/Shop.swift
|
UTF-8
| 2,426
| 2.578125
| 3
|
[] |
no_license
|
//
// Shop.swift
// dippaStore3
//
// Created by 松本直樹 on 2019/01/07.
// Copyright © 2019年 松本直樹. All rights reserved.
//
import UIKit
struct Shop: Codable {
let id: String?
let name: String
let phone: String
let address: String
let mondayOpenHours: String?
let tuesdayOpenHours: String?
let wednesdayOpenHours: String?
let thursdayOpenHours: String?
let fridayOpenHours: String?
let saturdayOpenHours: String?
let sundayOpenHours: String?
let holidayOpenHours: String?
let insidePhoto: String
let outsidePhoto: String
init(id: String?,
name: String,
phone: String,
address: String,
mondayOpenHours: String?,
tuesdayOpenHours: String?,
wednesdayOpenHours: String?,
thursdayOpenHours: String?,
fridayOpenHours: String?,
saturdayOpenHours: String?,
sundayOpenHours: String?,
holidayOpenHours: String?,
insidePhoto: String,
outsidePhoto: String){
self.id = id
self.name = name
self.phone = phone
self.address = address
self.mondayOpenHours = mondayOpenHours
self.tuesdayOpenHours = tuesdayOpenHours
self.wednesdayOpenHours = wednesdayOpenHours
self.thursdayOpenHours = thursdayOpenHours
self.fridayOpenHours = fridayOpenHours
self.saturdayOpenHours = saturdayOpenHours
self.sundayOpenHours = sundayOpenHours
self.holidayOpenHours = holidayOpenHours
self.insidePhoto = insidePhoto
self.outsidePhoto = outsidePhoto
}
func toData() -> [String: Any] {
return [
"id": self.id as Any,
"name": self.name,
"phone": self.phone,
"address": self.address,
"mondayOpenHours": self.mondayOpenHours as Any,
"tuesdayOpenHours": self.tuesdayOpenHours as Any,
"wednesdayOpenHours": self.wednesdayOpenHours as Any,
"thursdayOpenHours": self.thursdayOpenHours as Any,
"fridayOpenHours": self.fridayOpenHours as Any,
"saturdayOpenHours": self.saturdayOpenHours as Any,
"sundayOpenHours": self.sundayOpenHours as Any,
"holidayOpenHours": self.holidayOpenHours as Any,
"insidePhoto": self.insidePhoto,
"outsidePhoto": self.outsidePhoto
]
}
}
| true
|
259eaedaa3962b334ae066ec5d01d8560ebf4b0f
|
Swift
|
chhabrapiyush/kinsight-multiplatform
|
/native/testWatch2/testWatch2 WatchKit Extension/AnimatedBackground.swift
|
UTF-8
| 1,274
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// AnimatedBackground.swift
// testWatch2 WatchKit Extension
//
// Created by Dmitri Shpinar on 12/14/19.
// Copyright © 2019 spb. All rights reserved.
//
//
// AnimatedBackground.swift
// TryMacOS
//
// Created by Dmitri Shpinar on 12/12/19.
// Copyright © 2019 spb. All rights reserved.
//
//
// AnimatedBackground.swift
// KotlinIOS
//
// Created by Dmitri Shpinar on 11/26/19.
// Copyright © 2019 Kinsight. All rights reserved.
//
import SwiftUI
struct AnimatedBackground: View {
@State var gradient = [Color.blue, Color.purple, Color.red]
@State var startPoint = UnitPoint(x: 0, y: 0)
@State var endPoint = UnitPoint(x: 0, y: 2)
var body: some View {
RoundedRectangle(cornerRadius: 0)
.fill(LinearGradient(gradient: Gradient(colors: self.gradient), startPoint: self.startPoint, endPoint: self.endPoint))
.edgesIgnoringSafeArea(.all)
.onAppear() {
withAnimation (Animation.easeInOut(duration: 5).repeatForever()){
self.startPoint = UnitPoint(x: 1, y: -1)
self.endPoint = UnitPoint(x: 0, y: 1)
}
}
}
}
struct AnimatedBackground_Previews: PreviewProvider {
static var previews: some View {
AnimatedBackground()
}
}
| true
|
f0866b3fb34fd702e1b877616bc90e9e6e753787
|
Swift
|
leontedev/Friends
|
/Friends/Views/ContentView.swift
|
UTF-8
| 3,776
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//
// ContentView.swift
// Friends
//
// Created by Mihai Leonte on 25/11/2019.
// Copyright © 2019 Mihai Leonte. All rights reserved.
//
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: SavedUsers.entity(), sortDescriptors: []) var savedUsers: FetchedResults<SavedUsers>
@ObservedObject var userList = Users()
var body: some View {
NavigationView {
VStack {
Text("savedUsers \(self.savedUsers.count)")
Text("userList \(self.userList.users.count)")
List {
ForEach(self.savedUsers, id:\.self) { user in
NavigationLink(destination: DetailView(user: user)) {
VStack(alignment: .leading) {
HStack {
Text(user.name ?? "")
Spacer()
Text("Friends: \(user.friends?.count ?? 0)").font(.caption)
}
Text(user.address ?? "")
.font(.caption)
.foregroundColor(.gray)
}
}
}
}
.navigationBarTitle(Text("Friends"))
}
}
.onAppear {
// Check SceneDelegate - I am deleting all Core Data on each launch
if self.savedUsers.isEmpty {
let url = URLRequest(url: URL(string: "https://www.hackingwithswift.com/samples/friendface.json")!)
URLSession.shared.dataTask(with: url) { (data, resp, error) in
let decoder = JSONDecoder()
if let userData = data {
DispatchQueue.main.async {
do {
self.userList.users = try decoder.decode([User].self, from: userData)
var counter = 0
for user in self.userList.users {
counter += 1
let newUser = SavedUsers(context: self.moc)
newUser.id = user.id
newUser.name = user.name
newUser.age = user.age
newUser.address = user.address
newUser.about = user.about
for friend in user.friends {
let newFriend = Friends(context: self.moc)
newFriend.id = friend.id
newFriend.name = friend.name
newFriend.friendOf = newUser
}
}
if self.moc.hasChanges {
try? self.moc.save()
print("Core Data saved, \(counter)")
}
} catch {
print(error.localizedDescription)
}
}
}
}.resume()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
0851d00e018bb44e9bc6bb5baafe60b32828ad35
|
Swift
|
benstone1/RxSwiftIntroduction
|
/RxSwiftTryout/RXTipViewController.swift
|
UTF-8
| 2,632
| 2.796875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// RxSwiftTryout
//
// Created by Gabe Heafitz on 6/13/18.
// Copyright © 2018 ShopKeep. All rights reserved.
//
import UIKit
import RxSwift
class RXTipViewController: UIViewController {
static let startingPrice: Double = 20
let viewModel: ViewModel = {
return ViewModel(priceBeforeTip: startingPrice)
}()
@IBOutlet weak var tipAmountLabel: UILabel!
@IBOutlet weak var tipPercentageLabel: UILabel!
private let disposeBag = DisposeBag()
@IBAction func stepperValueChanged(_ sender: UIStepper) {
viewModel.updateTipAmount(to: sender.value)
}
override func viewDidLoad() {
super.viewDidLoad()
bindUIToViewModel()
}
func bindUIToViewModel() {
viewModel.tipAmountText
.observeOn(MainScheduler.instance)
.subscribe(onNext: {[weak self] (newString: String) in
self?.tipAmountLabel.text = newString
})
.disposed(by: disposeBag)
viewModel.tipPercentageText
.observeOn(MainScheduler.instance)
.subscribe(onNext: {[weak self] (newString: String) in
self?.tipPercentageLabel.text = newString
})
.disposed(by: disposeBag)
}
}
extension RXTipViewController {
class ViewModel {
//Public API
init(priceBeforeTip: Double) {
self.priceBeforeTip = priceBeforeTip
}
var tipAmountText: Observable<String> { return tipAmountTextSubject.asObservable() }
var tipPercentageText: Observable<String> { return tipPercentageTextSubject.asObservable() }
func updateTipAmount(to newValue: Double) {
tipAmount = newValue
}
//Private implementation
private let priceBeforeTip: Double
private(set) var tipAmount: Double = 0 {
didSet {
updateTipAmountText()
updateTipPercentageText()
}
}
lazy private var tipAmountTextSubject: BehaviorSubject<String> = {
return BehaviorSubject<String>(value: tipAmount.stringFormatted())
}()
lazy private var tipPercentageTextSubject: BehaviorSubject<String> = {
return BehaviorSubject<String>(value: tipAmount.percentageFormatted(of: priceBeforeTip))
}()
private func updateTipAmountText() {
tipAmountTextSubject.onNext(tipAmount.stringFormatted())
}
private func updateTipPercentageText() {
tipPercentageTextSubject.onNext(tipAmount.percentageFormatted(of: priceBeforeTip))
}
}
}
| true
|
5b76cdb8f98438af0a3cf749c08a869edd1e4315
|
Swift
|
rsnively/magic
|
/magic/nodes/CardNode.swift
|
UTF-8
| 4,870
| 2.71875
| 3
|
[] |
no_license
|
import Foundation
import SpriteKit
class CardNode: SKSpriteNode {
unowned var card:Object
var abilitySelector: AbilitySelector?
private static let cardAspectRatio:CGFloat = 0.714
private static func getMaximumCardSize(for size:CGSize) -> CGSize {
return size.width > size.height * cardAspectRatio
? CGSize(width:size.height * cardAspectRatio, height:size.height)
: CGSize(width:size.width, height:size.width / cardAspectRatio)
}
private static func getImageNode(card:Object, cardSize: CGSize, full: Bool) -> SKNode {
var texture: SKTexture
if !card.isRevealedToHuman() {
texture = SKTexture(imageNamed: "cardback.jpg")
} else if let token = card as? Token {
texture = SKTexture(imageNamed: token.getSetCode() + "t" + String(token.getCollectorsNumber()) + (full ? "full" : ""))
} else if let emblem = card as? Emblem {
texture = SKTexture(imageNamed: emblem.getSetCode() + "t" + String(emblem.getCollectorsNumber()) + (full ? "full" : ""))
} else if let nontoken = card as? Card {
texture = SKTexture(imageNamed: nontoken.getSetCode() + String(nontoken.getCollectorsNumber()) + (full ? "full" : ""))
} else {
texture = SKTexture()
assert(false)
}
let node = SKSpriteNode(texture: texture)
let aspectRatio = texture.size().width / texture.size().height
node.scale(to:CGSize(width: cardSize.width, height: cardSize.width / aspectRatio))
return node
}
private static func getCounterLabelNode(type: Counter, amount: Int, index: Int, cardSize: CGSize) -> SKNode {
let node = SKShapeNode(rectOf: CGSize(width: cardSize.width * 0.5, height: cardSize.height * 0.12))
node.strokeColor = UIColor(white: 0, alpha: 0.8)
node.fillColor = UIColor(white: 0, alpha: 0.8)
node.zPosition = 0.1
node.position = CGPoint(x: cardSize.width / 2.0, y: cardSize.height / 2.0 - cardSize.height * 0.11 * CGFloat(1 + index))
let labelNode = SKLabelNode(text: type.rawValue + ": " + String(amount))
labelNode.fontColor = UIColor.green // todo, red when detrimental
labelNode.fontSize = cardSize.height * 0.09
labelNode.zPosition = 0.2
labelNode.position = CGPoint(x: 0, y: -labelNode.fontSize / 2.0)
node.addChild(labelNode)
return node
}
init(card:Object, allowedSize:CGSize) {
self.card = card
let size = CardNode.getMaximumCardSize(for: allowedSize)
super.init(texture:nil, color: SKColor.clear, size:size)
if card.isAttacking {
let attackBorder = SKShapeNode(rectOf: self.size * 1.1, cornerRadius: 3.0)
attackBorder.strokeColor = SKColor.red
attackBorder.fillColor = SKColor.red
addChild(attackBorder)
} else if card.blocking {
let blockingBorder = SKShapeNode(rectOf: self.size * 1.1, cornerRadius: 3.0)
blockingBorder.strokeColor = SKColor.yellow
blockingBorder.fillColor = SKColor.yellow
addChild(blockingBorder)
}
if card.isType(.Creature) && (card.powerOrToughnessUndefined() || (card.getPower() != card.getBasePower() || card.getToughness() != card.getBaseToughness())) {
let powerToughnessNode = SKLabelNode(text: String(card.getPower()) + "/" + String(card.getToughness()))
powerToughnessNode.fontColor = UIColor.blue // todo, red when less
powerToughnessNode.fontSize = allowedSize.height * 0.1;
powerToughnessNode.position = CGPoint(x: 0, y: size.height * -0.4)
powerToughnessNode.zPosition = 0.1
addChild(powerToughnessNode)
}
addChild(CardNode.getImageNode(card: self.card, cardSize: self.size, full: true))
var numCounterLabelNodes = 0
for (counter, amount) in card.counters {
if amount > 0 {
addChild(CardNode.getCounterLabelNode(type: counter, amount: amount, index: numCounterLabelNodes, cardSize: size))
numCounterLabelNodes += 1
}
}
if card.isSelectingAbility() {
abilitySelector = AbilitySelector(object: card, cardSize: size)
abilitySelector!.zPosition = 0.2
addChild(abilitySelector!)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func touchDown(atPoint pos: CGPoint) { assert(false) }
func touchMoved(toPoint pos: CGPoint) { assert(false) }
func touchUp(atPoint pos : CGPoint) { assert(false) }
public var touchPoint:CGPoint? = nil
var touching:Bool {
return self.touchPoint != nil
}
}
| true
|
a7d12d1cea1da570a591d8f0ab82cec45bce85ae
|
Swift
|
erosfrancesco/Swift5_Tutorials_And_Templates
|
/00-styling/styling/Gradients.swift
|
UTF-8
| 792
| 3.21875
| 3
|
[] |
no_license
|
//
// Gradients.swift
// gradients
//
// Created by Eros Reale on 05/03/2020.
// Copyright © 2020 Eros Reale. All rights reserved.
//
import SwiftUI
struct Gradients {
static func rainbow() -> some View {
let colors = Gradient(colors: [.red, .yellow, .green, .blue, .purple, .red])
return AngularGradient(gradient: colors, center: .center)
}
static func linear(_ colors: [Color]) -> some View {
let colors = Gradient(colors: colors)
return LinearGradient(gradient: colors, startPoint: .top, endPoint: .center)
}
static func circular(_ colors: [Color], size: CGFloat) -> some View {
let colors = Gradient(colors: colors)
return RadialGradient(gradient: colors, center: .center, startRadius: 0, endRadius: size / 2)
}
}
| true
|
605aaf94737668d657d7cfc0f5122bd149589876
|
Swift
|
tammanache-nikhil/SwiftLearning
|
/SwiftPropertyWrappers.playground/Contents.swift
|
UTF-8
| 808
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
@propertyWrapper struct UserDefaultsHandler<Value> {
let key: String
let defaultValue: Value
var storage: UserDefaults = .standard
var wrappedValue: Value {
set {
storage.set(newValue, forKey: key)
}
get {
storage.value(forKey: key) as? Value ?? defaultValue
}
}
}
extension UserDefaultsHandler where Value: ExpressibleByNilLiteral {
init(key: String, storage: UserDefaults = .standard) {
self.init(key: key, defaultValue: nil, storage: storage)
}
}
struct Settings {
@UserDefaultsHandler(key: "first_launch", defaultValue: false)
var isFirstLaunch: Bool
}
// Usage
var settings = Settings()
print(settings.isFirstLaunch)
settings.isFirstLaunch = true
print(settings.isFirstLaunch)
| true
|
2a7789bddf768a9b2471f899204f1f30aa277d5d
|
Swift
|
Tianid/Notes
|
/Notes/Operations/DBOperations/SaveNoteDBOperation.swift
|
UTF-8
| 3,803
| 2.6875
| 3
|
[] |
no_license
|
import Foundation
import CoreData
import UIKit
class SaveNoteDBOperation: BaseDBOperation {
private let note: Note
private let backgroundContext: NSManagedObjectContext!
private let backgroundContextAction: BackgroundContextAction
private let noteUIDForUpdating: String?
init(note: Note,
notebook: FileNotebook,
backgroundContext: NSManagedObjectContext,
backgroundContextAction: BackgroundContextAction,
noteUIDForUpdating: String? = nil) {
self.note = note
self.backgroundContext = backgroundContext
self.backgroundContextAction = backgroundContextAction
self.noteUIDForUpdating = noteUIDForUpdating
super.init(notebook: notebook)
}
override func main() {
switch backgroundContextAction {
case .Create:
createRecord()
case .Update:
updateRecord()
}
// notebook.saveToFile()
finish()
}
private func createRecord() {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
guard let `self` = self else { return }
let notesEntity = NotesEntity(context: self.backgroundContext)
var red: CGFloat = 0, green:CGFloat = 0, blue:CGFloat = 0, alpha:CGFloat = 0
self.note.color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
notesEntity.uid = self.note.uid
notesEntity.title = self.note.title
notesEntity.content = self.note.content
notesEntity.red = Double(red)
notesEntity.green = Double(green)
notesEntity.blue = Double(blue)
notesEntity.alpha = Double(alpha)
notesEntity.importance = self.note.importance.rawValue
notesEntity.selfDestructionDate = self.note.selfDestructionDate
self.backgroundContext.performAndWait {
do {
try self.backgroundContext.save()
} catch {
print(error)
}
}
}
// notebook.add(note)
}
private func updateRecord() {
guard let uid = noteUIDForUpdating else { return }
let fetchRequest = NSFetchRequest<NotesEntity>.init(entityName: "NotesEntity")
fetchRequest.predicate = NSPredicate(format: "uid = %@", uid)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "uid", ascending: true)]
do {
let notes = try backgroundContext.fetch(fetchRequest)
let objectUpdate = notes[0] as NSManagedObject
objectUpdate.setValue(note.uid, forKey: "uid")
objectUpdate.setValue(note.title, forKey: "title")
objectUpdate.setValue(note.content, forKey: "content")
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
note.color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
objectUpdate.setValue(red, forKey: "red")
objectUpdate.setValue(green, forKey: "green")
objectUpdate.setValue(blue, forKey: "blue")
objectUpdate.setValue(alpha, forKey: "alpha")
objectUpdate.setValue(note.importance.rawValue, forKey: "importance")
objectUpdate.setValue(note.selfDestructionDate, forKey: "selfDestructionDate")
backgroundContext.performAndWait {
do {
try backgroundContext.save()
print("saved into store")
} catch {
print(error)
}
}
} catch {
print(error)
}
// notebook.remove(with: uid)
}
}
| true
|
bba3146a88b8b04ff77ec56103fb524fa89f016b
|
Swift
|
shamilcm/AltSwiftUI
|
/Sources/AltSwiftUI/Source/CoreUI/LayoutSolver.swift
|
UTF-8
| 5,569
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// LayoutSolver.swift
// AltSwiftUI
//
// Created by Wong, Kevin a on 2020/07/29.
// Copyright © 2020 Rakuten Travel. All rights reserved.
//
import UIKit
/// In charge of setting the correct layout constraints for a `View` configuration.
enum LayoutSolver {
// swiftlint:disable:next function_body_length
static func solveLayout(parentView: UIView, contentView: UIView, content: View, parentContext: Context, expand: Bool = false, alignment: Alignment = .center) {
var safeTop = true
var safeLeft = true
var safeRight = true
var safeBottom = true
let content = content.firstRenderableView(parentContext: parentContext)
let edges = content.viewStore.edgesIgnoringSafeArea
let rootView = edges != nil
if let ignoringEdges = edges {
if ignoringEdges.contains(.top) {
safeTop = false
}
if ignoringEdges.contains(.leading) {
safeLeft = false
}
if ignoringEdges.contains(.bottom) {
safeBottom = false
}
if ignoringEdges.contains(.trailing) {
safeRight = false
}
}
let originalParentView = parentView
var parentView = parentView
var lazy = false
if let contextController = parentContext.rootController, rootView {
parentView = contextController.view
lazy = true
}
var constraints = [NSLayoutConstraint]()
if expand {
constraints = contentView.edgesAnchorEqualTo(view: parentView, safeLeft: safeLeft, safeTop: safeTop, safeRight: safeRight, safeBottom: safeBottom)
} else {
switch alignment {
case .center:
if safeLeft && safeRight {
constraints.append(contentsOf: [contentView.centerXAnchor.constraint(equalTo: parentView.safeAreaLayoutGuide.centerXAnchor)])
} else if !rootView {
constraints.append(contentsOf: [contentView.centerXAnchor.constraint(equalTo: parentView.centerXAnchor)])
}
if safeTop && safeBottom {
constraints.append(contentsOf: [contentView.centerYAnchor.constraint(equalTo: parentView.safeAreaLayoutGuide.centerYAnchor)])
} else if !rootView {
constraints.append(contentsOf: [contentView.centerYAnchor.constraint(equalTo: parentView.centerYAnchor)])
}
case .leading:
constraints = [contentView.leftAnchorEquals(parentView, safe: safeLeft),
contentView.centerYAnchor.constraint(equalTo: parentView.centerYAnchor)]
case .trailing:
constraints = [contentView.rightAnchorEquals(parentView, safe: safeRight),
contentView.centerYAnchor.constraint(equalTo: parentView.centerYAnchor)]
case .top:
constraints = [contentView.topAnchorEquals(parentView, safe: safeTop),
contentView.centerXAnchor.constraint(equalTo: parentView.centerXAnchor)]
case .bottom:
constraints = [contentView.bottomAnchorEquals(parentView, safe: safeBottom),
contentView.centerXAnchor.constraint(equalTo: parentView.centerXAnchor)]
case .bottomLeading:
constraints = [contentView.bottomAnchorEquals(parentView, safe: safeBottom),
contentView.leftAnchorEquals(parentView, safe: safeLeft)]
case .bottomTrailing:
constraints = [contentView.bottomAnchorEquals(parentView, safe: safeBottom),
contentView.rightAnchorEquals(parentView, safe: safeRight)]
case .topLeading:
constraints = [contentView.topAnchorEquals(parentView, safe: safeTop),
contentView.leftAnchorEquals(parentView, safe: safeLeft)]
case .topTrailing:
constraints = [contentView.topAnchorEquals(parentView, safe: safeTop),
contentView.rightAnchorEquals(parentView, safe: safeRight)]
default: break
}
if rootView {
if !safeTop {
constraints.append(contentView.topAnchor.constraint(equalTo: parentView.topAnchor))
}
if !safeBottom {
constraints.append(contentView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor))
}
if !safeLeft {
constraints.append(contentView.leftAnchor.constraint(equalTo: parentView.leftAnchor))
}
if !safeRight {
constraints.append(contentView.rightAnchor.constraint(equalTo: parentView.rightAnchor))
}
}
constraints.append(contentsOf: contentView.edgesGreaterOrEqualTo(view: parentView, safeLeft: safeLeft, safeTop: safeTop, safeRight: safeRight, safeBottom: safeBottom))
if rootView && parentView != originalParentView {
constraints.append(contentsOf: contentView.edgesGreaterOrEqualTo(view: originalParentView, safeLeft: safeLeft, safeTop: safeTop, safeRight: safeRight, safeBottom: safeBottom, priority: .defaultHigh))
}
}
if !lazy {
constraints.activate()
} else if let controller = parentContext.rootController {
controller.lazyLayoutConstraints.append(contentsOf: constraints)
}
}
}
| true
|
a5c89be12be542757a8a0f2dcd83d9a5b8eefe45
|
Swift
|
Meister-P/rentacar
|
/Rentacar/CarsListViewController.swift
|
UTF-8
| 3,455
| 2.671875
| 3
|
[] |
no_license
|
//
// CarsListViewController.swift
// Rentacar
//
// Created by Mikk Pavelson on 08/04/2019.
// Copyright © 2019 Mikk Pavelson. All rights reserved.
//
import UIKit
fileprivate extension Selector {
static let logout = #selector(CarsListViewController.logout)
}
let CarsListNavigationControllerStoryboardID = "CarsListNavigationController"
class CarsListViewModel: NSObject {
var viewController: CarsListViewController!
var carsListUpdated: (([Car]) -> ())?
var carSelected: ((Car) -> ())?
var logoutAction: Action?
func refreshCarsList() {
let cars = dataStore.fetchAllEntitiesOfType(Car.self)
carsListUpdated?(cars)
}
@objc func logout() {
logoutAction?()
}
}
class CarsListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var viewModel = CarsListViewModel()
private var cars = [Car]()
@IBOutlet private var tableView: UITableView!
class func getNavigationController() -> UINavigationController {
let navigationController = UIStoryboard.mainStoryboard().instantiateViewController(withIdentifier: CarsListNavigationControllerStoryboardID) as! UINavigationController
return navigationController
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Cars"
let cancelButtonItem = UIBarButtonItem(title: "Log out", style: .plain, target: viewModel, action: .logout)
UIBarButtonItem.appearance().tintColor = RentacarColor
navigationItem.leftBarButtonItem = cancelButtonItem
tableView.dataSource = self
tableView.delegate = self
tableView.register(UINib(nibName: CarsListCell.className, bundle: nil), forCellReuseIdentifier: CarsListCell.className)
viewModel.carsListUpdated = { [weak self] cars in
self?.cars = cars
self?.tableView.reloadData()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.refreshCarsList()
}
@objc func logout() {
let alertController = UIAlertController(title: "Log out", message: "Are you sure you want to log out?", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let okAction = UIAlertAction(title: "Log out", style: .default) { [weak self] _ in
self?.viewModel.logout()
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
// MARK: - Table view
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cars.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CarsListCell = tableView.dequeueReusableCell(withIdentifier: CarsListCell.className) as! CarsListCell
let car = cars[indexPath.row]
cell.populateWith(car: car)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let car = cars[indexPath.row]
viewModel.carSelected?(car)
}
}
| true
|
f5a72287e5f3f7f94ce123c8a3fbbb0039b8ab4e
|
Swift
|
ivolnov/mweather
|
/mweather/mweather/Viper/Cities/CitiesPresenter.swift
|
UTF-8
| 2,859
| 2.890625
| 3
|
[] |
no_license
|
//
// CitiesPresenter.swift
// mweather
//
// Created by ivan volnov on 7/6/19.
// Copyright © 2019 ivolnov. All rights reserved.
//
import Foundation
protocol CitiesPresenter: class {
var view: CitiesView { get }
func cities() -> [CitiesPresenterModel]
func select(at: Int)
func delete(at: Int)
func refresh()
}
protocol CitiesPresenterModel {
var temperature: String { get }
var city: String { get }
}
extension Dependencies {
func citiesPresenter() -> CitiesPresenter {
return Presenter(dependencies: self)
}
}
fileprivate class Presenter: CitiesPresenter {
private var models: [CitiesInteractorCityModel]?
private let interactor: CitiesInteractor
private let router: CitiesRouter
var view: CitiesView
init(dependencies: CitiesDependencies) {
interactor = dependencies.citiesInteractor()
router = dependencies.citiesRouter()
view = dependencies.citiesView()
view.presenter = self
}
func cities() -> [CitiesPresenterModel] {
if models == nil {
load()
}
let cities = models?.map { convert($0) }
return cities ?? []
}
func select(at position: Int) {
guard let models = models else {
return
}
if position == models.count {
return
}
if let model = models.get(at: position) {
interactor.choose(model)
router.closeCities()
}
}
func delete(at position: Int) {
if let model = models?.get(at: position) {
interactor.remove(model)
}
}
func refresh() {
var cities = models ?? []
if let standard = AppDelegate.defaults.first, cities.isEmpty {
cities = [InteractorModel(temperature: 0, name: standard)]
}
interactor.refresh(cities: cities)
}
private func load() {
interactor.cities { [weak self] result in
switch result {
case .success(let models):
self?.models = models
self?.view.reload()
case .failure(let error):
self?.router.citiesAlert(error)
}
self?.view.hideRefreshControl()
}
}
private func convert(_ model: CitiesInteractorCityModel) -> CitiesPresenterModel {
let temperature = "\(Int(model.temperature))º"
let city = model.name.capitalizeFirstLetter()
return Model(temperature: temperature, city: city)
}
}
fileprivate struct InteractorModel: CitiesInteractorCityModel {
var temperature: Double
var name: String
}
fileprivate struct Model: CitiesPresenterModel {
let temperature: String
let city: String
}
| true
|
b49649cfa5d3532ed317eedd237f75b2c5ee2a88
|
Swift
|
MaxFerrara/FocusStartFinalProject
|
/ArenaComps_v1/ArenaComps_v1/Model/MateProperties/Name.swift
|
UTF-8
| 274
| 2.921875
| 3
|
[] |
no_license
|
//
// Name.swift
// ArenaComps_v1
//
// Created by Max on 20.12.2020.
//
enum Name: String {
case druid
case hunter
case mage
case paladin
case priest
case rogue
case shaman
case warlock
case warrior
var name: String {
return String(describing: self)
}
}
| true
|
ad8f2a3ea1d888688c0030ce0f4f29e57764dc7d
|
Swift
|
supreemMishra/Nasa
|
/Nasa/Nasa/Extensions/Extension.swift
|
UTF-8
| 905
| 2.9375
| 3
|
[] |
no_license
|
//
// Extension.swift
// Nasa
//
// Created by Supreem Mishra on 19/09/21.
//
import Foundation
import UIKit
extension UIViewController {
//MARK: - global method to present alert on view
@objc func presentAlert(withTitle title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { _ in
}
alertController.addAction(OKAction)
self.presentCustomAlert(alertController, animated: true, completion: nil)
}
func presentCustomAlert(_ alertControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
self.present(alertControllerToPresent, animated: flag, completion: completion)
if let _ = alertControllerToPresent as? UIAlertController {
}
}
}
| true
|
35e426e845b1ef58f6420e30d774526849158c94
|
Swift
|
bwork35/Journal-SwiftUI
|
/Journal-SwiftUI/CreateView.swift
|
UTF-8
| 849
| 3.046875
| 3
|
[] |
no_license
|
//
// CreateView.swift
// Journal-SwiftUI
//
// Created by Bryan Workman on 1/6/21.
//
import SwiftUI
struct CreateView: View {
@State private var newTitle = ""
@State private var newBody = ""
var body: some View {
ZStack {
Color(#colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1))
.ignoresSafeArea()
VStack {
TextField("Title", text: $newTitle)
.background(Color(.white))
.padding(.bottom)
TextView(text: $newBody)
Spacer()
}
.padding()
}
.navigationTitle("New Entry")
}
}
struct CreateView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
CreateView()
}
}
}
| true
|
f3b0526499f330a3140dec0302abac4226af017f
|
Swift
|
vishaldaher/ReactiveSwiftPOC
|
/CustomTextFieldViewModel.swift
|
UTF-8
| 956
| 3.046875
| 3
|
[] |
no_license
|
import UIKit
import ReactiveSwift
protocol CustomTextFieldViewModelInput {
var isTextValid: MutableProperty<Int> { get }
}
protocol CustomTextFieldViewModelOutput {
var textOne: ValidatingProperty<String?, FormError> { get }
}
protocol CustomTextFieldViewModelType {
var input: CustomTextFieldViewModelInput { get }
var output: CustomTextFieldViewModelOutput { get }
}
class CustomTextFieldViewModel: NSObject, CustomTextFieldViewModelType, CustomTextFieldViewModelInput, CustomTextFieldViewModelOutput{
var isTextValid: MutableProperty<Int> = MutableProperty(0)
var textOne: ValidatingProperty<String?, FormError> = ValidatingProperty("") { input in
return (input?.count)! > 0 ? .valid : .invalid(.invalidText)
}
var input: CustomTextFieldViewModelInput { return self }
var output: CustomTextFieldViewModelOutput { return self }
override init() {
}
}
| true
|
5fed6caa4063c5e561d44b8c210b43608341cb00
|
Swift
|
selfso2014/WebGazeBasics
|
/WebGazeBasics/WebData.swift
|
UTF-8
| 4,724
| 2.921875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// WebGazeBasics
//
// Created by Steve on 26/10/2019.
// Copyright © 2019 Visualcamp. All rights reserved.
//
import UIKit
import WebKit
struct WebData {
var webPathURL: String = ""
var webFromIndex : Int = 0
var webToIndex : Int = 0
var prdData = [ProductData]()
}
struct ProductData {
var prdRect: (x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) = (0.0, 0.0, 0.0, 0.0)
var prdName: String = ""
var prdPrice: String = ""
var prdSeller: String = ""
var prdImageURL: URL = URL(string: "https://www.google.com")!
var prdFixDensity: CGFloat = 0.0 // product_fixation_density: gaze fixation denesity of each product AOI(Area Of Interests)
}
class WebDataHandler {
var webData : [WebData] = []
var webIndex: Int = 0
var prdIndex: Int = 0
/* initializer */
init() {
// initial web page URL to be analyzed with gaze tracking
webData.append(WebData())
webData[0].prdData.append(ProductData())
print("@init, webData_count: \(webData.count) productData.count:\(webData[0].prdData.count)")
}
/* web <--> app communication protocal example
prdIndex|catetory|data ...
setWebData(), 187|webPathURL|/
setWebData(), 187|prdRect|23.34375|25506.15625|157.4375|256
setWebData(), 187|prdName|스트랩 벨트 롱코트
setWebData(), 187|prdPrice|32,300
setWebData(), 187|prdSeller|아이무드유
setWebData(), 187|prdImageURL|https://image.brandi.me/cproduct/2019/10/28/11431797_1572255506_image1_M.jpg
*/
func setWebData(str: String) {
let strData = str.components(separatedBy: "|")
//print("setWebData(), \(str)")
let strIndex = strData.count - 1
if strIndex <= 0 { return }
else {
switch strData[1] {
case "webPathURL":
webData[webIndex].webPathURL = strData[2]
if Int(strData[0])! > webData[webIndex].prdData.count - 1 {
webData[webIndex].prdData.append(ProductData())
prdIndex = Int(strData[0])! // prdIndex incrases only in this parsing section
}
//print("\n")
//print(" webIndex#\(webIndex) prdIndex#\(prdIndex) webPathURL|\(webData[webIndex].webPathURL)")
break
case "prdRect":
if let n = NumberFormatter().number(from: strData[2]) {
webData[webIndex].prdData[prdIndex].prdRect.x = CGFloat(truncating: n)
}
if let n = NumberFormatter().number(from: strData[3]) {
webData[webIndex].prdData[prdIndex].prdRect.y = CGFloat(truncating: n)
}
if let n = NumberFormatter().number(from: strData[4]) {
webData[webIndex].prdData[prdIndex].prdRect.w = CGFloat(truncating: n)
}
if let n = NumberFormatter().number(from: strData[5]) {
webData[webIndex].prdData[prdIndex].prdRect.h = CGFloat(truncating: n)
}
//print(" webIndex#\(webIndex) prdIndex#\(prdIndex) prdRect|\(webData[webIndex].prdData[prdIndex].prdRect.x) \(webData[webIndex].prdData[prdIndex].prdRect.y) \(webData[webIndex].prdData[prdIndex].prdRect.w) \(webData[webIndex].prdData[prdIndex].prdRect.h)")
break
case "prdName":
webData[webIndex].prdData[prdIndex].prdName = strData[2]
//print(" webIndex#\(webIndex) prdIndex#\(prdIndex) prdName|\(webData[webIndex].prdData[prdIndex].prdName)")
break
case "prdPrice":
webData[webIndex].prdData[prdIndex].prdPrice = strData[2]
//print(" webIndex#\(webIndex) prdIndex#\(prdIndex) prdPrice|\(webData[webIndex].prdData[prdIndex].prdPrice)")
break
case "prdSeller":
webData[webIndex].prdData[prdIndex].prdSeller = strData[2]
//print(" webIndex#\(webIndex) prdIndex#\(prdIndex) prdSeller|\(webData[webIndex].prdData[prdIndex].prdSeller)")
break
case "prdImageURL":
webData[webIndex].prdData[prdIndex].prdImageURL = URL(string: (strData[2]))!
//print(" webIndex#\(webIndex) prdIndex#\(prdIndex) prdImageURL|\(webData[webIndex].prdData[prdIndex].prdImageURL)")
break
default:
print(" default:\(str)")
break
}
}
}
}
| true
|
4912897f5aef25df228c63d9971494a09f5be38f
|
Swift
|
mibarbou/SuperHeroes
|
/SuperHeroes/SuperHeroes/Controllers/HeroDetail/SuperHeroDetailViewController.swift
|
UTF-8
| 1,378
| 2.609375
| 3
|
[] |
no_license
|
//
// SuperHeroDetailViewController.swift
// SuperHeroes
//
// Created by Michel Barbou Salvador on 20/04/2018.
// Copyright © 2018 mibarbou. All rights reserved.
//
import UIKit
import Kingfisher
class SuperHeroDetailViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var realNameLabel: UILabel!
@IBOutlet weak var powerLabel: UILabel!
@IBOutlet weak var abilitiesLabel: UILabel!
@IBOutlet weak var groupsLabel: UILabel!
let hero: SuperHero
init(hero: SuperHero) {
self.hero = hero
super.init(nibName: nil, bundle: Bundle(for: type(of: self)))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setup() {
self.title = hero.name
self.realNameLabel.text = hero.realName
self.imageView.kf.setImage(with: hero.photo)
self.powerLabel.text = hero.power
self.abilitiesLabel.text = hero.abilities
let groupsString = hero.groups.joined(separator: "\n✪")
self.groupsLabel.text = "✪ " + groupsString
}
}
| true
|
b49413a1a0cbb8988161271823e2a289a64729b3
|
Swift
|
NSViking/iOS-Marvel
|
/Marvel/Marvel/Entities/DomainData/Pagination.swift
|
UTF-8
| 841
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
//
// Pagination.swift
// Marvel
//
// Created by Víctor Vicente on 11/11/2018.
// Copyright © 2018 DevSouls. All rights reserved.
//
import Foundation
class Pagination {
private var currentPage = 0
private var objectsPerPage = 6
init() {
self.currentPage = 0
self.objectsPerPage = 6
}
init(page: Int, total: Int) {
setupData()
}
}
extension Pagination {
func getCurrentPage() -> Int {
return self.currentPage
}
func setCurrentPage(page: Int) {
self.currentPage = page;
}
func getObjectsPerPage() -> Int {
return self.objectsPerPage
}
func setObjectsPerPage(total: Int) {
self.objectsPerPage = total;
}
func next() {
self.currentPage += objectsPerPage
}
func reset() {
setupData()
}
}
private extension Pagination {
func setupData() {
self.currentPage = 0
self.objectsPerPage = 6
}
}
| true
|
82157830d912ef760a1ef258ff7f69099fcfa9ea
|
Swift
|
GSerjo/Algorithms-Swift
|
/Algorithms-Swift/Algorithms-Swift/StackNodeOf.swift
|
UTF-8
| 883
| 3.4375
| 3
|
[] |
no_license
|
//
// StackNodeOf.swift
// Algorithms-Swift
//
// Created by Serjo on 19/06/15.
// Copyright © 2015 Serjo. All rights reserved.
//
import UIKit
class StackNodeOf<T> {
private var _first: Node<T>?
private var _count: Int = 0
var isEmpty: Bool {
get {
return count == 0
}
}
var count: Int {
return _count
}
func push(item: T) {
let old = _first
_first = Node<T>(next: old, value: item)
_count++
}
func pop() -> T? {
if let result = _first?.value {
_count--
_first = _first?.next
return result
}
return .None
}
}
private class Node<T> {
var next: Node<T>?
var value: T
init(next: Node<T>?, value: T){
self.next = next
self.value = value
}
}
| true
|
e86217ba146805207a41be957b3a1aa2c16cb637
|
Swift
|
Hardikkyada/RecipeApp
|
/RecipeApp/webview.swift
|
UTF-8
| 1,038
| 2.84375
| 3
|
[] |
no_license
|
//
// webview.swift
// RecipeApp
//
// Created by DCS on 24/06/21.
// Copyright © 2021 DCS. All rights reserved.
//
import UIKit
import WebKit
class webview: UIViewController,WKUIDelegate {
var webview: WKWebView?
var query:String?
init(search:String)
{
super.init(nibName: nil, bundle: nil)
query = search
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
let webc = WKWebViewConfiguration()
webview = WKWebView(frame: .zero,configuration: webc)
webview?.uiDelegate = self
view = webview
}
override func viewDidLoad() {
super.viewDidLoad()
//let myurl = URL(string: "https://www.indianhealthyrecipes.com/?s=\(query!)")
let myurl = URL(string: "https://www.indianhealthyrecipes.com/\(query!)")
let req = URLRequest(url: myurl!)
webview?.load(req)
}
}
| true
|
3be8a1d7e9923ab2d1908558ca2ad05134ec5c7b
|
Swift
|
Hitesh136/SwiftUI
|
/Movie/Movie/Resources/MovieTab.swift
|
UTF-8
| 1,354
| 3.171875
| 3
|
[] |
no_license
|
//
// MovieTab.swift
// Movie
//
// Created by Hitesh Agarwal on 06/02/20.
// Copyright © 2020 Hitesh Agarwal. All rights reserved.
//
import Foundation
class MoiveSelection: ObservableObject {
@Published var selectedMovie: MovieTab
init(selectedMovie: MovieTab) {
self.selectedMovie = selectedMovie
}
}
enum MovieTab: Int, CaseIterable {
var id: String {
return description
}
case nowPlaying
case upcoming
case trending
case popular
case topRated
case genre
var description: String {
switch self {
case .nowPlaying:
return "Now Playing"
case .upcoming:
return "Upcoming"
case .trending:
return "Trending"
case .popular:
return "Popular"
case .topRated:
return "Top Rated"
case .genre:
return "Genres"
}
}
var apiKey: String {
switch self {
case .nowPlaying:
return "movie/now_playing"
case .upcoming:
return "movie/upcoming"
case .trending:
return "trending/movie/day"
case .popular:
return "movie/popular"
case .topRated:
return "movie/top_rated"
case .genre:
return "genre/movie/list"
}
}
}
| true
|
bbf500e18bd376e539497443631de99144623d04
|
Swift
|
ace-rivera/ballclub
|
/BallClub/BallClub/Custom Views/Friends/EditInvitedFriendsCollectionViewCell.swift
|
UTF-8
| 801
| 2.515625
| 3
|
[] |
no_license
|
//
// EditInvitedFriendsCollectionViewCell.swift
// BallClub
//
// Created by Joshua Relova on 5/9/17.
// Copyright © 2017 Geraldine Forto. All rights reserved.
//
import UIKit
import Nuke
class EditInvitedFriendsCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var userImageView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setUserName (userName: String) {
userNameLabel.text = userName
}
func setImageOfFriend(imageUrlString : String) {
userImageView.image = UIImage(named: "sample_profile")
if let imageUrl = URL(string: imageUrlString) {
Nuke.loadImage(with: imageUrl, into: userImageView)
}
}
}
| true
|
adf44d4cb65be09b4d82f50a43dcd4682b00f0e4
|
Swift
|
kubiat/westeros
|
/Westeros/Controllers/EpisodeDetailViewController.swift
|
UTF-8
| 1,432
| 2.609375
| 3
|
[] |
no_license
|
//
// EpisodeDetailViewController.swift
// Westeros
//
// Created by Joaquín Gracia López on 30/9/18.
// Copyright © 2018 Web Cor. All rights reserved.
//
import UIKit
class EpisodeDetailViewController: UIViewController {
//MARK: - Properties
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var digestText: UITextView!
var model: Episode
//MARK: - Initialization
init(model: Episode){
self.model = model
super.init(nibName: nil, bundle: nil)
title = model.name
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Lifecycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
syncModelEpisodeDetail()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - Sync
func syncModelEpisodeDetail(){
nameLabel.text = model.name
dateLabel.text = model.releaseDateString
digestText.text = model.digest
}
}
extension EpisodeDetailViewController: EpisodeListViewControllerDelegate{
func episodeListViewController(_ vc: EpisodeListViewController) {
navigationController?.pushViewController(self, animated: true)
}
}
| true
|
292231f18740481ba863bf0157fd664700d84164
|
Swift
|
Marcus1012/Touche
|
/Touche-ios/ToucheStatusBar.swift
|
UTF-8
| 4,944
| 2.5625
| 3
|
[] |
no_license
|
//
// Created by Marcus Korpi on 7/14/17.
// Copyright (c) 2017 toucheapp. All rights reserved.
//
import Foundation
import UIKit
import Cupcake
import MapKit
import SwiftDate
import SwiftyJSON
class ToucheStatusBar: UIView {
private var distanceInMeters: Double!
private var lastSeen: String!;
private var distLabel: UILabel!
private var seenLabel: UILabel!
private var polyLabel: UILabel!
private var dot: UIImageView!
private var polys: [JSON]!
public init(frame: CGRect, distance: Double, lastSeen: String) {
super.init(frame: frame)
self.distanceInMeters = distance
self.lastSeen = lastSeen
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup() {
self.distLabel = Label.str(buildDistanceString()).font("Montserrat-Regular,12").color("white")
self.seenLabel = Label.str(buildLastSeenString()).font("Montserrat-Regular,12").color("green")
self.polyLabel = Label.str(buildPolyString()).font("Montserrat-Regular,12").color("white")
self.dot = buildDot()
self.dot.tint(buildDotColor())
VStack(
"<-->",
HStack(
10,
self.polyLabel,
10
),
5,
HStack(
10,
HStack(
ImageView.img("002-navigation").pin(.wh(10, 10)),
5,
self.distLabel
),
10,
HStack(
dot.pin(.wh(10, 10)),
5,
self.seenLabel
),
10
),
"<-->"
).embedIn(self)
}
private func buildLastSeenString() -> String {
if let date = DateManager.getDateFromMillis(self.lastSeen) {
let d_str = try! date.colloquialSinceNow()
return d_str.colloquial
}
return ""
}
private func buildPolyString() -> String {
if polys != nil && polys.count > 0 {
return self.polys.map {
"📍 \($0.stringValue)"
}.first!
}
return ""
}
private func buildDot() -> UIImageView {
return ImageView.img("$001-circle").tint(UIColor.clear)
}
private func buildDistanceString() -> String {
if self.distanceInMeters == 0.0 {
return ""
}
return "\(self.formatDistance(self.distanceInMeters))"
}
func formatDistance(_ dist: Double) -> String {
let formatter = MeasurementFormatter()
var distanceInMeters = Measurement(value: round(dist), unit: UnitLength.meters)
// let locale = Locale(identifier: Locale.preferredLanguages[0])
//
// let numberFormatter = NumberFormatter()
// numberFormatter.numberStyle = .decimal
// numberFormatter.locale = locale
// numberFormatter.maximumFractionDigits = 0
// formatter.numberFormatter = numberFormatter
//
// formatter.locale = locale
//
// formatter.unitStyle = MeasurementFormatter.UnitStyle.short
// formatter.unitOptions = .naturalScale
// return formatter.string(from: distanceInMeters)
let locale = Locale(identifier: Locale.preferredLanguages[0])
let n = NumberFormatter()
n.maximumFractionDigits = 0
n.minimumFractionDigits = 0
//n.locale = locale
let m = MeasurementFormatter()
m.numberFormatter = n
//m.locale = locale
m.unitOptions = .naturalScale
return m.string(from: distanceInMeters)
}
func refresh(_ dist: Double, _ seen: String, _ polys: [JSON]) {
self.lastSeen = seen
self.distanceInMeters = dist
self.polys = polys
self.distLabel.str(buildDistanceString())
self.seenLabel.str(buildLastSeenString()).color(buildLabelColor())
self.polyLabel.str(buildPolyString())
self.dot.tint(buildDotColor())
}
private func buildLabelColor() -> UIColor {
if let date = DateManager.getDateFromMillis(self.lastSeen) {
if date.isAfter(date: (60.minutes).ago()!, granularity: Calendar.Component.minute) {
return Color("green")!
}
return Color("white")!
}
return UIColor.clear
}
private func buildDotColor() -> UIColor {
if let date = DateManager.getDateFromMillis(self.lastSeen) {
if date.isAfter(date: (60.minutes).ago()!, granularity: Calendar.Component.minute) {
return Color("green")!
}
return UIColor.gray
}
return UIColor.clear
}
}
| true
|
55c3359e879c6466f6a2d91f35e5787a3fb1f20e
|
Swift
|
niegaotao/NXKit
|
/NXKit/Classes/Foundation/NXString.swift
|
UTF-8
| 2,993
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// NXString.swift
// NXKit
//
// Created by niegaotao on 2020/1/12.
// Copyright (c) 2020 niegaotao. All rights reserved.
//
import UIKit
open class NXString {
open var frame = CGRect.zero
open var color = NX.blackColor
open var lineSpacing : CGFloat = 0.0
open var text = ""
open var font = NX.font(15)
open var query = [String:Any]()
public init(){}
}
extension NXString {
public class func string(_ text:String, _ font:UIFont, _ color:UIColor, _ lineSpacing:CGFloat) -> NXString {
let textWrapper = NXString()
textWrapper.text = text
textWrapper.font = font
textWrapper.color = color
textWrapper.lineSpacing = lineSpacing
return textWrapper
}
public class func string(_ text:String, _ font:UIFont, _ color:UIColor, _ lineSpacing:CGFloat, _ query:[String:Any]) -> NXString {
let textWrapper = NXString()
textWrapper.text = text
textWrapper.font = font
textWrapper.color = color
textWrapper.lineSpacing = lineSpacing
textWrapper.query = query
return textWrapper
}
public class func attributedString(_ text:String, _ font:UIFont, _ color:UIColor, _ lineSpacing:CGFloat) -> NSMutableAttributedString {
var mapValue = [NSAttributedString.Key:Any]()
mapValue[NSAttributedString.Key.font] = font
mapValue[NSAttributedString.Key.foregroundColor] = color
mapValue[NSAttributedString.Key.paragraphStyle] = {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
return paragraphStyle
}()
let attributedText = NSMutableAttributedString(string: text, attributes: mapValue)
return attributedText
}
public class func attributedString(_ strings:[NXString], _ lineSpacing:CGFloat) -> NSMutableAttributedString {
let attributedText = NSMutableAttributedString()
for string in strings {
var mapValue = [NSAttributedString.Key:Any]()
mapValue[NSAttributedString.Key.font] = string.font
mapValue[NSAttributedString.Key.foregroundColor] = string.color
mapValue[NSAttributedString.Key.paragraphStyle] = {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.lineHeightMultiple = 1.25
return paragraphStyle
}()
let subattributedText = NSMutableAttributedString(string: string.text, attributes: mapValue)
if string.query.count > 0 {
subattributedText.addAttribute(NSAttributedString.Key.link, value: "app://query?query="+NXSerialization.JSONObject(toString: string.query, encode: true), range: NSMakeRange(0, (string.text as NSString).length))
}
attributedText.append(subattributedText)
}
return attributedText
}
}
| true
|
bf7a96ed0d1882eb88db2f93d6f11ef2318be1d3
|
Swift
|
kv-023/EmoChat
|
/EmoChat/Controller/Extensions/DateExtension.swift
|
UTF-8
| 1,183
| 3.03125
| 3
|
[] |
no_license
|
//
// DateExtension.swift
// EmoChat
//
// Created by Admin on 20.06.17.
// Copyright © 2017 SoftServe. All rights reserved.
//
import Foundation
extension Date {
var millisecondsSince1970:Int {
return Int((self.timeIntervalSince1970 * 1000).rounded())
}
init(milliseconds:Int) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
}
init(milliseconds:Double) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
}
func formatDate() -> String {
let dataformatter = DateFormatter.init()
dataformatter.timeStyle = .short
let date = dataformatter.string(from: self)
return date
}
func dayFormatStyle() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d.MM.yy"
let date = dateFormatter.string(from: self)
return date
}
func dayFormatStyleDate() -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d.MM.yy"
let date = dateFormatter.date(from: dateFormatter.string(from: self))
return date!
}
}
| true
|
108f815ab6ca2d4951282b2dad78e04c5eb13303
|
Swift
|
RobYang1024/CoopMaster-iOS
|
/CoopMaster/CoopMaster/ViewController.swift
|
UTF-8
| 5,424
| 2.84375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// CoopMaster
//
// Created by Robert Yang on 1/28/17.
// Copyright © 2017 Robert Yang. All rights reserved.
//
import UIKit
import SwiftChart
class ViewController: UIViewController {
var dateStringArray: [String]!
var eggCountArray: [Int]!
var waterCountArray: [Double]!
var feedCountArray: [Double]!
var dateArray: [Date]!
var dateSubtractedFloatArray: [Float]!
var dateFloatArray: [Float]!
override func viewDidLoad() {
super.viewDidLoad()
let defaults = UserDefaults.standard
let dateStringArray = defaults.stringArray(forKey: "date") ?? [String]()
let eggCountArray = defaults.array(forKey: "numberOfEggs") as? [Int] ?? [Int]()
view.backgroundColor = .white
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
/*dateStringArray = [String]()
dateStringArray.append("2017/01/27")
dateStringArray.append("2017/01/28")
dateStringArray.append("2017/01/29")
dateStringArray.append("2017/01/30")
dateStringArray.append("2017/01/31")
dateStringArray.append("2017/02/01")*/
dateArray = [Date]()
//Append Date objects from dateStringArray to dateArray
for dateString in dateStringArray{
dateArray.append(formatter.date(from:dateString)!)
}
//What to subtract from each Date value such that the smallest date is assigned the origin (x=0) value
let secondsToSubtract = leastSecondsSince1970()
let chart = Chart(frame: CGRect(x: view.frame.width*0.1, y: view.frame.height*0.1, width: view.frame.width*0.8, height: view.frame.height*0.8))
//let series = ChartSeries([0, 6.5, 2, 8, 4.1, 7, -3.1, 10, 8])
//let point1 = (x: 5.0, y: 9.0)
//let point2 = (x: 6.0, y: 8.0)
//let point3 = (x: 3.0, y: 14.0)
var array1: Array<(x: Double, y: Double)> = Array()
var i = 0
for dateObject in dateArray{
let secondsSinceFirstDay = dateObject.timeIntervalSince1970-secondsToSubtract
array1.append((x: secondsSinceFirstDay, y: Double(eggCountArray[i])))
i+=1
}
let series = ChartSeries(data: array1)
//Keeping an array of number of seconds since 1970 for use in the xLabels and the formatter
dateSubtractedFloatArray = [Float]()
dateFloatArray = [Float]()
for dateDate in dateArray{
let secondsSince1970 = Float(dateDate.timeIntervalSince1970)
let floatSecondsToSubtract = Float(secondsToSubtract)
dateSubtractedFloatArray.append(secondsSince1970-floatSecondsToSubtract)
dateFloatArray.append(Float(secondsSince1970))
}
chart.xLabels = dateSubtractedFloatArray
chart.xLabelsFormatter = { self.convertSubtractedSince1970ToDateString(subtractedSecondsSince1970: $1) }
var yLabelEggArray = [Float]()
let maxEggValue = eggCountArray.max()!
for i in 0...maxEggValue {
yLabelEggArray.append(Float(i))
}
chart.yLabels = yLabelEggArray
chart.yLabelsFormatter = { String(Int($1)) }
chart.add(series)
view.addSubview(chart)
//Labels for eggs chart
let yAxisEggsLabel = UILabel(frame: CGRect(x: -10, y: view.frame.height*0.45+30, width: 60, height: 40))
yAxisEggsLabel.text = "Eggs"
yAxisEggsLabel.textAlignment = .center
yAxisEggsLabel.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2)
view.addSubview(yAxisEggsLabel)
let xAxisEggsLabel = UILabel(frame: CGRect(x: view.frame.width*0.5-30, y: view.frame.height*0.9, width: 60, height: 40))
xAxisEggsLabel.text = "Date"
xAxisEggsLabel.textAlignment = .center
view.addSubview(xAxisEggsLabel)
/*let chart2 = Chart(frame: CGRect(x: view.frame.width*0.1, y: view.frame.height*0.5, width: view.frame.width*0.8, height: view.frame.height*0.8))
chart2.xLabels = dateSubtractedFloatArray
chart2.xLabelsFormatter = { self.convertSubtractedSince1970ToDateString(subtractedSecondsSince1970: $1) }
chart2.yLabels = yLabelEggArray
chart2.yLabelsFormatter = { String(Int($1)) }
view.addSubview(chart2)*/
}
//This converts subtracted since 1970 by leastSecondsSince1970() Float values into the appropriate date String. This is for the xLabelsFormatter field of the chart.
func convertSubtractedSince1970ToDateString(subtractedSecondsSince1970: Float) -> String{
let date = NSDate(timeIntervalSince1970: Double(subtractedSecondsSince1970)+leastSecondsSince1970())
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd"
let dateString = dateFormatter.string(from: date as Date)
return dateString
}
//This is such that the earliest date is placed at x pixels = 0 for the chart view
func leastSecondsSince1970() -> Double {
let secondsToReturn = dateArray[0].timeIntervalSince1970
return secondsToReturn
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
1c3485b1a142ec2c05d0bfdffb3b15be0cfe3dea
|
Swift
|
yujinqiu/Capture
|
/Capture/WindowList/View/CollectionViewItemView.swift
|
UTF-8
| 739
| 3
| 3
|
[] |
no_license
|
import Cocoa
class CollectionViewItemView: NSView {
required init?(coder: NSCoder) {
super.init(coder: coder)
wantsLayer = true
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
wantsLayer = true
}
var selected: Bool = false {
didSet {
needsDisplay = true
}
}
override var wantsUpdateLayer: Bool {
return true
}
override func updateLayer() {
let layer = self.layer!
layer.cornerRadius = 10.0
switch selected {
case true:
layer.backgroundColor = NSColor.windowBackgroundColor.cgColor
case false:
layer.backgroundColor = nil
}
}
}
| true
|
a95a3f9a10b2059ec67985defd72a3dceb73bba2
|
Swift
|
schlaBAM/CoreGraphicsPractice
|
/CoreGraphicsPractice/CounterView.swift
|
UTF-8
| 2,794
| 3.21875
| 3
|
[] |
no_license
|
//
// CounterView.swift
// CoreGraphicsPractice
//
// Created by BAM on 2017-10-20.
// Copyright © 2017 BAM. All rights reserved.
//
import UIKit
@IBDesignable
class CounterView: UIView {
private struct Constants {
static let numberOfGlasses = 8
static let lineWidth : CGFloat = 5.0
static let arcWidth : CGFloat = 76
static var halfOfLineWidth: CGFloat {
return lineWidth / 2
}
}
@IBInspectable var counter: Int = 5 {
didSet {
if counter <= Constants.numberOfGlasses {
//view needs to be refreshed
setNeedsDisplay()
}
}
}
@IBInspectable var outlineColor: UIColor = .blue
@IBInspectable var counterColor: UIColor = .orange
override func draw(_ rect: CGRect) {
//define the center point of the view to rotate arc
let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
//calculate the radius based on the max dimension of the view
let radius : CGFloat = max(bounds.width, bounds.height)
//define the start/end angles for the arc
let startAngle: CGFloat = 3 * .pi / 4
let endAngle: CGFloat = .pi / 4
//create a path based on the center point, radius, and defined angles
let path = UIBezierPath(arcCenter: center, radius: radius/2 - Constants.arcWidth/2, startAngle: startAngle, endAngle: endAngle, clockwise: true)
//set the line width / color before stroking the path
path.lineWidth = Constants.arcWidth
counterColor.setStroke()
path.stroke()
//Draw the outline
//calculate the difference between the 2 angles ensuring positivity
let angleDifference: CGFloat = 2 * .pi - startAngle + endAngle
//calculate the arc for each glass
let arcLengthPerGlass = angleDifference / CGFloat(Constants.numberOfGlasses)
//multiply out by actual glasses drunk
let outlineEndAngle = arcLengthPerGlass * CGFloat(counter) + startAngle
//draw outer arc
let outlinePath = UIBezierPath(arcCenter: center, radius: bounds.width / 2 - Constants.halfOfLineWidth, startAngle: startAngle, endAngle: outlineEndAngle, clockwise: true)
//draw inner arc
outlinePath.addArc(withCenter: center, radius: bounds.width/2 - Constants.arcWidth + Constants.halfOfLineWidth, startAngle: outlineEndAngle, endAngle: startAngle, clockwise: false)
//close path
outlinePath.close()
outlineColor.setStroke()
outlinePath.lineWidth = Constants.lineWidth
outlinePath.stroke()
}
}
| true
|
506e126e12bd13447230c66c1e1a9134c8bde64e
|
Swift
|
syllerim/ApiConnector
|
/ApiConnector/Environment.swift
|
UTF-8
| 908
| 2.921875
| 3
|
[] |
no_license
|
//
// Environment.swift
// ApiConnector
//
// Created by Oleksii on 01/02/2017.
// Copyright © 2017 WeAreReasonablePeople. All rights reserved.
//
import Foundation
public protocol ApiEnvironment {
var value: URLEnvironment { get }
}
public struct URLEnvironment {
public let scheme: Scheme
public let host: String
public let port: Int?
public static func localhost(_ scheme: Scheme, _ port: Int? = nil) -> URLEnvironment {
return URLEnvironment(scheme, "localhost", port)
}
public static func localhost(_ port: Int? = nil) -> URLEnvironment {
return localhost(.http, port)
}
public init(_ scheme: Scheme, _ host: String, _ port: Int? = nil) {
self.scheme = scheme
self.host = host
self.port = port
}
public init(_ host: String, _ port: Int? = nil) {
self.init(.http, host, port)
}
}
| true
|
5067c581bee2782a1936d95424e35e1e44374485
|
Swift
|
Delio/Ahead
|
/Ahead/Player.swift
|
UTF-8
| 716
| 3.015625
| 3
|
[] |
no_license
|
//
// Player.swift
// Ahead
//
// Created by Adel Salikhov on 18/05/2019.
// Copyright © 2019 Adel Salikhov. All rights reserved.
//
import Foundation
import SpriteKit
class Player: SKSpriteNode {
//MARK: - Init
init() {
let playerSize = CGSize(width: 31, height: 31)
super.init(texture: Circle, color: .red, size: playerSize)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Setup
func setup() {
name = "player"
physicsBody = SKPhysicsBody(circleOfRadius: frame.size.width / 2)
position = CGPoint(x: 200, y: 200)
physicsBody?.isDynamic = false
}
}
| true
|
af2c83e7f0025faee6adbbcfd5d5b740215f07cb
|
Swift
|
Taeminator1/Data-Structure
|
/DataStructure/Heap/Heap.swift
|
UTF-8
| 5,042
| 4.03125
| 4
|
[] |
no_license
|
//
// Heap.swift
// DataStructure
//
// Created by 윤태민 on 5/31/21.
//
import Foundation
/// The Heap is made by using Array.
public class Heap<Element: Comparable> {
public typealias HandlerType = (HeapNode<Element>, HeapNode<Element>) -> Bool
var hNodes: [HeapNode<Element>] = []
public var count: Int { hNodes.count } // The number of elements in the collection.
let handler: HandlerType
/// A Boolean value indicating whether the collection is empty.
public var isEmpty: Bool {
return count == 0
}
/// Sets a type of heap, as in the lollowing example:
///
/// var minHeap: Heap = Heap<Int>(handler: >) // min heap
/// var maxHeap: Heap = Heap<Int>(handler: >) // max heap
/// - Parameter handler: you can transfer function that decide condition for comparing two hNodes.
public init(handler: @escaping HandlerType = { $0 > $1 }) {
self.handler = handler
}
}
extension Heap {
/// - Parameter index: The position of the target node.
/// - Returns: The parent node of the collection.
func getParent(at index: Int) -> HeapNode<Element> {
guard index > 0 && index < count else {
fatalError("Index out of range")
}
return hNodes[(index - 1) / 2]
}
/// - Parameter index: The position of the target node.
/// - Returns: The left child node of the collection.
func getLeftChild(at index: Int) -> HeapNode<Element> {
guard index >= 0 && index * 2 + 1 < count else {
fatalError("Index out of range")
}
return hNodes[index * 2 + 1]
}
/// - Parameter index: The position of the target node.
/// - Returns: The right child node of the collection.
func getRightChild(at index: Int) -> HeapNode<Element> {
guard index >= 0 && index * 2 + 2 < count else {
fatalError("Index out of range")
}
return hNodes[index * 2 + 2]
}
}
extension Heap {
/// Displays every element of the collection.
///
/// var h: Heap = Heap<Int>(handler: >)
/// h.insert(data: 2)
/// h.insert(data: 1)
/// h.insert(data: 3)
/// h.insert(data: 4)
///
/// h.displayElements()
/// // prints "4 3 2 1 "
public func displayElements() {
hNodes.forEach {
print($0.data, terminator: " ")
}
print("")
}
}
extension Heap {
/// Inserts elemet into the collection to comply with arrangement of the type.
///
/// The following example insert data in the collection.
///
/// var h: Heap = Heap<Int>(handler: >)
/// h.insert(data: 2)
/// h.insert(data: 1)
/// h.insert(data: 3)
/// h.insert(data: 4)
///
/// - Parameter data: The new data to insert into the collection.
///
/// - Complexity: O(log *n*), where *n* is the number of the elements.
public func insert(data: Element) {
var index = count
hNodes.append(HeapNode(data)) // hNodes의 자리만 늘리기 위한 목적
while index > 0 && handler(HeapNode(data), getParent(at: index)){
hNodes[index].data = hNodes[(index - 1) / 2].data
index = (index - 1) / 2
}
hNodes[index].data = data
}
/// Rmoves elemet of the collection. And arrange to comply with arrangement of the type.
///
/// The following example insert data in the collection.
///
/// var h: Heap = Heap<Int>(handler: >)
/// h.insert(data: 2)
/// h.insert(data: 1)
/// h.insert(data: 3)
/// h.insert(data: 4)
///
/// print(h.remove(at: 2)!.data)
/// // Prints "2"
///
/// - Parameter index: The position of the element to remove. index must be a valid index of the collection that is not equal to the collection's end index.
/// - Returns: The node at the specified index.
///
/// - Complexity: O(log *n*), where *n* is the number of the elements.
@discardableResult public func remove(at index: Int = 0) -> HeapNode<Element>? {
guard index >= 0 && index < count else {
return nil
}
let result: HeapNode<Element> = hNodes[index]
let lastHeapNode: HeapNode<Element> = hNodes.removeLast()
if hNodes.isEmpty { return result }
var pIndex: Int = index // parent index
var cIndex: Int = pIndex * 2 + 1 // child index
while cIndex < count {
if cIndex < count - 1 && handler(getRightChild(at: pIndex), getLeftChild(at: pIndex)) {
cIndex += 1
}
if lastHeapNode == hNodes[cIndex] || handler(lastHeapNode, hNodes[cIndex]) { break }
hNodes[pIndex] = hNodes[cIndex]
pIndex = cIndex
cIndex = cIndex * 2 + 1
}
hNodes[pIndex] = lastHeapNode
return result
}
}
| true
|
8e3984818bfd7d5e17ecdc7876f600eca38c5de8
|
Swift
|
zzBelieve/BeachBum
|
/BeachBum/Controller/Model Controller/BeachForecastController.swift
|
UTF-8
| 3,031
| 3.1875
| 3
|
[] |
no_license
|
//
// BeachForecastController.swift
// JSON Weather
//
// Created by Jordan Dumlao on 8/9/18.
// Copyright © 2018 Jordan Dumlao. All rights reserved.
//
import Foundation
class BeachForecastController: NSObject {
private var beachForecasts = [BeachForecast]()
private var filteredBeachForecasts: [BeachForecast]?
//Vars for sorting and filtering
private var isFiltered = false
private var temperatureSortDownward = true
private var weatherSortedDownward = true
}
//Helper Interface Variable and Method
extension BeachForecastController {
var beachForecastsCount: Int { return filteredBeachForecasts?.count ?? beachForecasts.count }
var _beachForecastsArray: [BeachForecast] {
get { return beachForecasts }
set { beachForecasts = newValue }
}
func beachForecastForIndexAt(_ index: Int) -> BeachForecast { return filteredBeachForecasts?[index] ?? beachForecasts[index] }
func addBeachForecast(_ beachForecast: BeachForecast) { beachForecasts.append(beachForecast) }
func removeBeach(_ beachForecast: BeachForecast) {
if let index = beachForecasts.index(where: { $0.beach.name == beachForecast.beach.name }) {
beachForecasts.remove(at: index)
}
}
func removeBeach(at index: Int) {
if filteredBeachForecasts != nil {
if let removedBeach = filteredBeachForecasts?.remove(at: index) {
removeBeach(removedBeach)
}
} else {
beachForecasts.remove(at: index)
}
}
}
//Mark: Sorting and filtering functions
extension BeachForecastController {
func sortBeachForecasts(_ sortType: Sort) {
beachForecasts.sort { (b1, b2) -> Bool in
switch sortType {
case .temperature:
return temperatureSortDownward ? b1.forecast!.currently.temperature < b2.forecast!.currently.temperature : b1.forecast!.currently.temperature > b2.forecast!.currently.temperature
case .weatherCondition:
return weatherSortedDownward ? (b1.forecast!.currently.icon < b2.forecast!.currently.icon) : (b1.forecast!.currently.icon > b2.forecast!.currently.icon)
case .distance:
return false
}
}
switch sortType {
case .temperature: temperatureSortDownward = !temperatureSortDownward
case .weatherCondition: weatherSortedDownward = !weatherSortedDownward
default: break
}
}
func filterBeachesBy(_ searchString: String?) {
guard let searchString = searchString else { return }
switch searchString.lowercased() {
case "all": filteredBeachForecasts = nil; return
case "north": filteredBeachForecasts = beachForecasts.filter { $0.beach.side == "North" }
case "east": filteredBeachForecasts = beachForecasts.filter { $0.beach.side == "East" }
case "south": filteredBeachForecasts = beachForecasts.filter { $0.beach.side == "South" }
case "west": filteredBeachForecasts = beachForecasts.filter { $0.beach.side == "West" }
default: filteredBeachForecasts = beachForecasts.filter { $0.beach.name.lowercased().contains(searchString.lowercased()) }
}
}
}
| true
|
9d604aa78305b14998820c2a42309a34dbcef936
|
Swift
|
ketyung/SwiftJson
|
/Shared/JsonProvider.swift
|
UTF-8
| 1,544
| 2.90625
| 3
|
[
"Unlicense"
] |
permissive
|
//
// JsonProvider.swift
// SwiftJson
//
// Created by Chee Ket Yung on 01/01/2021.
//
import Foundation
class JsonProvider {
static func jsonString1() -> String {
return """
[
{ "id": 1, "name" : "Apple TV", "imageName" : "appletv"},
{ "id": 2, "name" : "Apple Watch", "imageName" : "applewatch"},
{ "id": 3, "name" : "Car", "imageName" : "car"},
{ "id": 4, "name" : "iPhone", "imageName" : "iphone"},
]
"""
}
static func jsonString2() -> String {
return """
[
{ "tshirt_color_in_hex": "#0000A0", "qty" : 12, "name" : "Dark Blue"},
{ "tshirt_color_in_hex": "#a52a2a", "qty" : 10, "name" : "Brown"},
{ "tshirt_color_in_hex": "#FF0000", "qty" : 5, "name" : "Red"},
{ "tshirt_color_in_hex": "#00FF00", "qty" : 3, "name" : "Lime"},
{ "tshirt_color_in_hex": "#FFA500", "qty" : 2, "name" : "Orange"},
{ "tshirt_color_in_hex": "#808000", "qty" : 1, "name" : "Olive"},
{ "tshirt_color_in_hex": "#2B547E", "qty" : 1, "name" : "Blue Jay"},
]
"""
}
static func getTShirts() -> [TShirt]{
let jsonStr = jsonString2()
return jsonStr.decodeJson([TShirt].self)
}
static func getMenuItems() -> [MenuItem]{
let jsonStr = jsonString1()
return jsonStr.decodeJson([MenuItem].self)
}
}
| true
|
255750f7965c8554400946b089a7828e775e4224
|
Swift
|
sam-meech-ward-lighthouse-labs/Core-Data-Genius
|
/Genius/Genius/DataManager.swift
|
UTF-8
| 2,324
| 2.921875
| 3
|
[] |
no_license
|
//
// DataManager.swift
// Genius
//
// Created by Sam Meech-Ward on 2019-07-03.
// Copyright © 2019 meech-ward. All rights reserved.
//
import Foundation
import CoreData
class DataManager {
static let shared = DataManager()
// The persistent container manages the core data stack for us
// Without this, we would have to do a bunch of setup manually
// https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Genius")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
var viewContext: NSManagedObjectContext {
return persistentContainer.viewContext
}
var backgroundContext: NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
context.parent = viewContext
return context
}
// MARK: - Core Data Saving support
func saveContext () {
let context = viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func getQuizzes() throws -> [Quiz] {
// Like creating a sql query
let fetch: NSFetchRequest<Quiz> = Quiz.fetchRequest()
// Executing the query
return try viewContext.fetch(fetch)
}
func getQuestions(category: String) throws -> [Question] {
// Like creating a sql query
let fetch: NSFetchRequest<Question> = Question.fetchRequest()
fetch.predicate = NSPredicate(format: "category == %@", category)
// Executing the query
return try viewContext.fetch(fetch)
}
func getQuizzes2(completion: @escaping ([Quiz]) -> ()) {
// Like creating a sql query
let fetch: NSFetchRequest<Quiz> = Quiz.fetchRequest()
backgroundContext.perform {
// All of this happens on a background queue, so be careful
let quizzes = try! fetch.execute()
completion(quizzes)
}
}
}
| true
|
93683cc76a0db49557c2efdfcd521a95aff58bef
|
Swift
|
e0046793/FetchMeDemo
|
/CathayDemo/CathayDemo/Models/MovieDetail.swift
|
UTF-8
| 1,366
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
//
// MovieDetail.swift
// CathayDemo
//
// Created by Kyle Truong on 14/07/2017.
// Copyright © 2017 Kyle Truong. All rights reserved.
//
import Foundation
fileprivate struct Key {
static let Id = "id"
static let Original_Title = "original_title"
static let Genres = "genres"
static let Spoken_Language = "spoken_languages"
static let Runtime = "runtime"
}
class MovieDetail: Deserializable {
private(set) var id: String?
private(set) var title: String?
private(set) var genres: [Genre]?
private(set) var languages: [Language]?
private(set) var duration: Int?
required init(dictionary: [String : AnyObject]) {
do {
try id = String.convert(json: dictionary[Key.Id])
try title = String.convert(json: dictionary[Key.Original_Title])
try duration = Int.convert(json: dictionary[Key.Runtime])
if let genreJSONarray = dictionary[Key.Genres] as? [AnyObject] {
try Deserialization.parse(array: &genres, jsonArray: genreJSONarray)
}
if let languageJSONarray = dictionary[Key.Spoken_Language] as? [AnyObject] {
try Deserialization.parse(array: &languages, jsonArray: languageJSONarray)
}
} catch let error as NSError {
print("Parsing error \(error)")
}
}
}
| true
|
2e303ac7201271c70517ac8b3eb67d6d68463787
|
Swift
|
danielsoutar/OnTheMap
|
/OnTheMap/Controller/LinkEntryViewController.swift
|
UTF-8
| 5,468
| 2.609375
| 3
|
[] |
no_license
|
//
// LinkEntryViewController.swift
// OnTheMap
//
// Created by Daniel Soutar on 16/09/2020.
// Copyright © 2020 Daniel Soutar. All rights reserved.
//
import MapKit
import UIKit
class LinkEntryViewController: UIViewController, MKMapViewDelegate {
// MARK: - Outlets
@IBOutlet weak var linkEntryTextField: UITextField!
@IBOutlet weak var mapView: MKMapView!
// MARK: - Constants and Variables
// The location from the parent view controller.
var location: MKMapItem?
// MARK: - View-related Methods
override func viewDidLoad() {
super.viewDidLoad()
// Make the media URL text field look a bit nicer.
linkEntryTextField.attributedPlaceholder = NSAttributedString(string: "Enter Your URL Here",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
// Also set this controller as the text field's delegate.
linkEntryTextField.delegate = self
// Set up the annotation for the map view to display to the user.
let annotation = MKPointAnnotation()
annotation.coordinate = location!.placemark.coordinate
annotation.title = "\(location?.placemark.title ?? "")"
self.mapView.delegate = self
self.mapView.addAnnotation(annotation)
// Centers the map around the location provided.
self.mapView.setCenter(annotation.coordinate, animated: true)
}
// MARK: - MKMapViewDelegate
// Only show the solitary pin, don't allow any editing or other actions.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.pinTintColor = .red
pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
else {
pinView!.annotation = annotation
}
return pinView
}
// MARK: - Actions
@IBAction func addStudentInfoButtonPressed(_ sender: Any) {
let newLatitude = location?.placemark.coordinate.latitude
let newLongitude = location?.placemark.coordinate.longitude
let newMediaURL = linkEntryTextField.text
if validateAndVerifyURL(newMediaURL) {
let locationString = location!.placemark.title!
MapClient.addOrUpdateWithLocation(with: newLatitude!,
newLongitude: newLongitude!,
locationString: locationString,
newMediaURL: newMediaURL ?? "") {
(wasSuccessful, error) in
if wasSuccessful {
LocationModel.currentUserLocation?.latitude = newLatitude!
LocationModel.currentUserLocation?.longitude = newLongitude!
LocationModel.currentUserLocation?.mapString = locationString
LocationModel.currentUserLocation?.mediaURL = newMediaURL ?? ""
LocationModel.currentUserLocationKnown = true
self.returnToMainPage()
} else {
let alert = Alert(title: "Map Pin Post Failed",
message: "Unfortunately your post didn't go through successfully (error message was \(error!.localizedDescription).\nCheck your connection and try again.",
actionTitles: ["OK"],
actionStyles: [nil],
actions: [nil])
self.showAlert(from: alert)
}
}
} else {
displayURLError()
}
}
@IBAction func handleCancelButtonPressed(_ sender: Any) {
returnToMainPage()
}
// MARK: - Helpers
func returnToMainPage() {
// I don't like this, but not sure how else to properly
// dismiss the view with the programmatic style I've used
// (without recourse to a detail view or navigation stack
// approach, which include undesirable presentation
// features).
DataModelRefresher.refresh()
self.presentingViewController?.presentingViewController?.dismiss(
animated: true, completion: nil)
}
func validateAndVerifyURL(_ newMediaURL: String?) -> Bool {
return newMediaURL?.count ?? 0 > 0 && verifyUrl(urlString: newMediaURL)
}
func verifyUrl (urlString: String?) -> Bool {
if let urlString = urlString {
if NSURL(string: urlString) != nil {
return true
}
}
return false
}
func displayURLError() {
let alert = Alert(title: "Invalid URL",
message: "Unfortunately the URL presented is invalid.",
actionTitles: ["OK"],
actionStyles: [nil],
actions: [nil])
showAlert(from: alert)
}
}
extension LinkEntryViewController : UITextFieldDelegate {
// Dismiss the keyboard when pressing enter.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return textField.resignFirstResponder()
}
}
| true
|
bb6c9376f5c9fabd4675bee84f32fe57373bee64
|
Swift
|
JJingLee/JJJSBridge
|
/JJJSBridge/Classes/openWebComponents/BaseComponents/JJWebJSModule.swift
|
UTF-8
| 447
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// JJWebJSModule.swift
// JJJSBridge
//
// Created by 李杰駿 on 2021/7/21.
//
import Foundation
open class JJWebJSModule {
public var name : String
public var jsFunctions : [JJWebJSFunction]
public var jsScripts : [String]
public init(name : String, functions : [JJWebJSFunction] = [], jsScripts : [String] = []) {
self.name = name
self.jsFunctions = functions
self.jsScripts = jsScripts
}
}
| true
|
99e05bf7b1ec06e7d45918c2e7a11838947c9bcf
|
Swift
|
amirdew/CollectionViewPagingLayout
|
/Lib/Utilities/CGFloat+Interpolate.swift
|
UTF-8
| 710
| 2.9375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// CGFloat+Interpolate.swift
// CollectionViewPagingLayout
//
// Created by Amir Khorsandi on 2/22/20.
// Copyright © 2020 Amir Khorsandi. All rights reserved.
//
import UIKit
extension CGFloat {
public func interpolate(in inputRange: Range = .init(0, 1), out outputRange: Range = .init(0, 1)) -> CGFloat {
var current = self
if current > inputRange.upper {
current = inputRange.upper
}
if current < inputRange.lower {
current = inputRange.lower
}
let progress = abs(current - inputRange.lower) / abs(inputRange.upper - inputRange.lower)
return outputRange.lower + progress * abs(outputRange.upper - outputRange.lower)
}
}
| true
|
aa847e2b0e7c3cd9fd5954cb9155a9cd2ed09583
|
Swift
|
KimSeongHeon/ARoha_SwiftUI
|
/Aroha_SwiftUI/Aroha_SwiftUI/Tab1/Tab1Tour.swift
|
UTF-8
| 1,466
| 2.625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// Tab1Tour.swift
// Aroha_SwiftUI
//
// Created by 김성헌 on 2020/07/25.
// Copyright © 2020 김성헌. All rights reserved.
//
import Foundation
import SwiftUI
import AVFoundation
struct Tab1TourView : View{
@EnvironmentObject var settings:UserSettings
@State var log:String = "초기값"
var body:some View{
VStack{
DemoVideoStreaming(log:$log).frame(width: 100, height: 100, alignment: .center)
HStack{
Text("현재위치: \(log)").frame(maxWidth: .infinity, alignment: .center)
Button(action: {
print("스탬프 인식")
}){
Text("스탬프 인식").foregroundColor(.black)
.frame(width : 100,alignment: .trailing)
}.padding()
}
//Image(uiImage: self.settings.test).frame(width: 100, height: 100, alignment: .center)
AR_MaPWebView( request: URLRequest(url: URL(string : "https://ar.konk.uk/kdh/rsync/map.html")!))
}
}
private func checkPermission(){
AVCaptureDevice.requestAccess(for: AVMediaType.video) { response in
if response {
print("response \(response)")
} else {
print("response \(response)")
}
}
}
}
struct Tab1Tour_Previews: PreviewProvider {
static var previews: some View {
Tab1TourView()
}
}
| true
|
104b4dbca893e9716421e7eb706a302d8d778402
|
Swift
|
rabelhmd/DesignPattern
|
/swift/Bridge/Bridge/GraphicsAPI.swift
|
UTF-8
| 171
| 3.234375
| 3
|
[] |
no_license
|
import Foundation
protocol GraphicsAPI {
func drawRectangle(_ x: Int, _ y: Int, _ width: Int, _ height: Int)
func drawCircle(_ x: Int, _ y: Int, _ radius: Int)
}
| true
|
fac0a9160cd3af99d2df6602d16ebab09455b635
|
Swift
|
thanduchuy/SwiftUI-CinemaApp
|
/Cinema/Admin/UpdatePopup.swift
|
UTF-8
| 8,937
| 2.515625
| 3
|
[] |
no_license
|
//
// UpdatePopup.swift
// Cinema
//
// Created by MacBook Pro on 4/14/20.
// Copyright © 2020 MacBook Pro. All rights reserved.
//
import SwiftUI
import SDWebImageSwiftUI
struct UpdatePopup: View {
@State var film = Film()
@Binding var showPopup : Bool
@State var showGenres = false
@State var selectGenres = 0
@State var dateSelected = Date()
@State var indexDate = 0
@State var imageData : Data = .init(count: 0)
@State var picker : Bool = false
@State var loading : Bool = false
let maxDate = Calendar.current.date(byAdding: .day,value: 20 , to: Date())!
var body: some View {
VStack {
ScrollView(.vertical, showsIndicators: false) {
HStack {
Spacer()
Button(action: {
self.picker.toggle()
}) {
if self.imageData.count == 0 {
AnimatedImage(url: URL(string: self.film.image))
.resizable()
.frame(width: 300, height: 300)
.clipShape(Circle())
} else {
Image(uiImage: UIImage(data: self.imageData)!).resizable().renderingMode(.original).frame(width: 300, height: 300).clipShape(Circle())
}
}
Spacer()
}.padding()
TextField("Name", text: self.$film.name)
.padding()
.background(Color("Color"))
.clipShape(RoundedRectangle(cornerRadius: 10))
TextField("Time", text: self.$film.time)
.padding()
.background(Color("Color"))
.clipShape(RoundedRectangle(cornerRadius: 10))
Mutiline(text: self.$film.info)
.frame(height: 300)
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color.orange, lineWidth: 1)
.shadow(color: .orange, radius: 10, x: 2, y: 2)
)
HStack {
HStack {
VStack(spacing : 5) {
HStack {
Text("Picker Genre")
.fontWeight(.bold)
Image(systemName: self.showGenres ? "chevron.up":"chevron.down")
.resizable()
.frame(width: 13, height: 6)
}.foregroundColor(.white)
.onTapGesture {
if self.showGenres {
self.showGenres.toggle()
}
}
if showGenres {
ForEach(dataGenres , id: \.self) { i in
Button(action: {
self.film.category[self.selectGenres] = i
self.showGenres.toggle()
}) {
Text(i).padding()
}.foregroundColor(.white)
}
}
}.padding()
.background(LinearGradient(gradient: .init(colors: [Color("Color"),.orange]), startPoint: .top, endPoint: .bottom))
.cornerRadius(15)
.shadow(color: .gray, radius: 5)
.animation(.spring())
Spacer()
}.padding()
Spacer()
VStack {
ForEach(0..<self.film.category.count, id: \.self) { item in
HStack(spacing: 0) {
Text(self.film.category[item]).font(.subheadline)
Spacer()
Image(systemName: "trash.circle.fill")
.resizable()
.frame(width: 20, height: 20)
.onTapGesture {
self.film.category.remove(at: item)
}
}.padding()
.foregroundColor(.white)
.background(Color.orange)
.cornerRadius(5)
.onTapGesture {
self.showGenres.toggle()
self.selectGenres = item
}
}
}.padding()
}
VStack(spacing : 10) {
DatePicker("", selection: self.$dateSelected,in: Date()...maxDate)
.labelsHidden()
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(0..<self.film.movieDay.count, id : \.self) { index in
VStack(alignment : .center) {
Text(fomartDaytoDate(date: self.film.movieDay[index]))
Text(fomartTimetoDate(date: self.film.movieDay[index]))
Button(action: {
self.film.movieDay.remove(at: index)
}) {
Image(systemName: "bin.xmark.fill")
.resizable()
.frame(width: 15, height: 15)
}.padding()
.foregroundColor(.orange)
.background(Color.white)
.clipShape(Circle())
}.padding()
.foregroundColor(.white)
.background(Color.orange.opacity(0.8))
.cornerRadius(10)
.onTapGesture {
self.dateSelected = self.film.movieDay[index]
self.indexDate = index
}
}
}
}
Button(action: {
self.film.movieDay[self.indexDate] = self.dateSelected
self.dateSelected = Date()
}) {
Text("Update Movie Day").foregroundColor(.white).padding()
}.frame(maxWidth : .infinity)
.background(self.dateSelected != Date() ? Color.black.opacity(0.7):Color.orange.opacity(0.6))
.cornerRadius(500)
.shadow(color: .orange, radius: 10, x: 2, y: 2)
.disabled(self.dateSelected != Date())
if self.loading {
HStack {
Spacer()
Indicator()
Spacer()
}
} else {
Button(action: {
if !self.film.name.isEmpty && !self.film.time.isEmpty && !self.film.info.isEmpty {
self.loading.toggle()
updateMovie(film: self.film, imageData: self.imageData) { (Bool) in
if Bool {
self.loading.toggle()
self.showPopup.toggle()
}
}
}
}) {
Text("Update").frame(width: UIScreen.main.bounds.width - 30, height: 50)
}.foregroundColor(.white)
.background(Color.orange)
.cornerRadius(10)
}
}.padding()
}
}.padding()
.sheet(isPresented: self.$picker, content: {
imagePicker(picker: self.$picker, imageData: self.$imageData)
})
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.