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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
caf9ccd70f27e769c72f9b6f67b4244a7ebaaf2d
|
Swift
|
sharonanchel/Favorite-Spots
|
/My Favorite Places/PlacesTableViewController.swift
|
UTF-8
| 4,775
| 2.71875
| 3
|
[] |
no_license
|
//
// PlacesTableViewController.swift
// My Favorite Places
//
// Created by Lorman Lau on 9/14/17.
// Copyright © 2017 Lorman Lau. All rights reserved.
//
import UIKit
import CoreData
import CoreLocation
protocol routeViewDelegate: class {
func viewcancel()
}
class PlacesTableViewController: UITableViewController {
var place: Place?
var places = [Place]()
let moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
weak var delegate: MapDelegate?
@IBAction func cancelButtonPressed(_ sender: UIBarButtonItem) {
delegate?.cancel()
}
func fetchAllPlaces(){
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Place")
do {
let result = try moc.fetch(request)
places = result as! [Place]
} catch {
print("\(error)")
}
}
func save() {
print("Saving")
if moc.hasChanges {
do {
try moc.save()
print("save successful")
} catch {
print("\(error)")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
fetchAllPlaces()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return places.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PlaceCell") as! PlaceCell
cell.nameLabel.text = places[indexPath.row].name
var cost = ""
for _ in 0..<Int(places[indexPath.row].cost) {
cost += "$"
}
cell.costLabel.text = "Cost Level: \(cost)"
var hearts = ""
for _ in 0..<Int(places[indexPath.row].hearts) {
hearts += "<3"
}
cell.heartLabel.text = "Fav Level: \(hearts)"
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let object = places[indexPath.row]
moc.delete(object)
save()
places.remove(at: indexPath.row)
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "displayPlace", sender: places[indexPath.row])
}
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
performSegue(withIdentifier: "editPlace", sender: indexPath)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "displayPlace" {
let navController = segue.destination as! UINavigationController
let controller = navController.topViewController as! routeViewController
if let sender = sender as? Place {
controller.place = sender
}
controller.delegate = self
} else {
let navController = segue.destination as! UINavigationController
let controller = navController.topViewController as! AddItemViewController
controller.delegate = self
if let indexPath = sender as? IndexPath {
controller.place = places[indexPath.row]
controller.indexPath = indexPath
}
}
}
}
extension PlacesTableViewController: placeDelegate {
func save(name: String, desc: String, cost: Int, hearts: Int, lat: Double, lon: Double, indexPath: IndexPath?) {
if let indexPath = indexPath {
let place = places[indexPath.row]
place.name = name
place.desc = desc
place.cost = Double(cost)
place.hearts = Double(hearts)
place.lat = lat
place.lon = lon
} else {
let place = NSEntityDescription.insertNewObject(forEntityName: "Place", into: moc) as! Place
place.name = name
place.desc = desc
place.cost = Double(cost)
place.hearts = Double(hearts)
place.lat = lat
place.lon = lon
places.append(place)
}
save()
tableView.reloadData()
dismiss(animated: true, completion: nil)
}
func cancel() {
dismiss(animated: true, completion: nil)
}
}
extension PlacesTableViewController: routeViewDelegate {
func viewcancel(){
dismiss(animated: true, completion: nil)
}
}
| true
|
c7b00add463eec9ad2be7f1515b8f8256aa33a56
|
Swift
|
tadelv/oktatrack
|
/OktatrackLib/Sources/DetailFeature/DetailView.swift
|
UTF-8
| 3,490
| 2.828125
| 3
|
[] |
no_license
|
//
// DetailView.swift
// OktaTrack
//
// Created by Vid on 11/2/19.
// Copyright © 2019 Delta96. All rights reserved.
//
import Models
import Helpers
import SwiftUI
public struct DetailView: View {
struct PreferenceKey: SwiftUI.PreferenceKey {
static var defaultValue: CGPoint { .zero }
static func reduce(value: inout CGPoint, nextValue: () -> CGPoint) {
value = nextValue()
}
}
var repository: Repository
@ObservedObject private var coordinator: DetailCoordinator
@State var position: CGPoint = .zero
private let coordinateSpaceName = UUID()
public init(_ repository: Repository, _ coordinator: DetailCoordinator) {
self.repository = repository
self.coordinator = coordinator
}
public var body: some View {
ScrollView {
LazyVStack {
RepoStatsView(repository: repository, position: position.y)
.background(GeometryReader { geometry in
Color.clear.preference(
key: PreferenceKey.self,
value: geometry.frame(in: .named(coordinateSpaceName)).origin
)
})
.onPreferenceChange(PreferenceKey.self) { position in
self.position = position
}
HStack {
Text("Contributors")
.font(.headline)
Spacer()
}
.padding([.leading, .trailing, .top])
ForEach(coordinator.contributors, id: \.id) { contribution in
ContributorView(contribution: contribution)
.padding([.leading, .trailing])
}
}
}
.coordinateSpace(name: coordinateSpaceName)
.navigationTitle(repository.name)
.task {
await coordinator.fetchContributors()
}
}
}
struct RepoStatsView: View {
let repository: Repository
let position: Double
var body: some View {
VStack(spacing: spacing) {
HStack {
Text("by " + repository.owner.login)
.font(.headline)
Spacer()
}
.padding([.leading, .trailing])
Text(repository.description ?? "")
.font(.subheadline)
.padding([.leading, .trailing])
HStack {
Spacer()
VStack {
Text("🍴").font(.headline)
Text("\(repository.forks_count)")
}
Spacer()
VStack {
Text("✨").font(.headline)
Text("\(repository.stargazers_count)")
}
Spacer()
VStack {
Text("🚛").font(.headline)
Text("\(String(format:"%.2f",(Double(repository.size))/1024.0))kB")
}
Spacer()
}
}
.opacity(opacity)
}
var spacing: Double {
guard position > 0 else {
return 8
}
return 8 + position * 0.5
}
var opacity: Double {
return 1.0 * ((50 + position) / 50)
}
}
struct ContributorView: View {
let contribution: Contribution
var body: some View {
HStack {
WebImageView(url: contribution.avatar_url)
.frame(width: 40, height: 40)
.clipShape(Circle())
.overlay(Circle().stroke(Color.gray, lineWidth: 2))
Text("\(contribution.login)")
.font(.headline)
Spacer()
VStack(alignment: .trailing, spacing: 2) {
Text("🔨")
Text("\(contribution.contributions)")
}
}
}
}
struct DetailView_Previews: PreviewProvider {
static var previews: some View {
NavigationStack {
DetailView(.mock,
DetailCoordinator(.mock, fetch: { Contribution.mock }))
}
}
}
| true
|
6f0c409d214a5bb6f2b012618ad0306ee9abb681
|
Swift
|
VladimirMolchanovIOS/TestTaxi
|
/eKassirTest/Price.swift
|
UTF-8
| 549
| 2.625
| 3
|
[] |
no_license
|
//
// Price.swift
// eKassirTest
//
// Created by Владимир Молчанов on 31/07/16.
// Copyright © 2016 Владимир Молчанов. All rights reserved.
//
import UIKit
class Price: NSObject {
var amount: Int!
var currency: String!
override init() {
super.init()
amount = 0
currency = ""
}
convenience init(amount: Int?, currency: String?) {
self.init()
guard let _amount = amount, _currency = currency else { return }
self.amount = _amount
self.currency = _currency
}
}
| true
|
eea604c6026019076f00bd9b7ca055a1231af7c6
|
Swift
|
skinnyqb7/Program-9
|
/Program 9/ViewController.swift
|
UTF-8
| 1,552
| 2.625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Program 9
//
// Created by Jake McCormick on 4/29/20.
// Copyright © 2020 Jake McCormick. All rights reserved.
//
import UIKit
import WebKit
import MessageUI
class ViewController:UIViewController,MFMessageComposeViewControllerDelegate {
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
}
@IBOutlet weak var webview: WKWebView!
@IBAction func openSite(_ sender: Any) {
if URL( string: "https://www.zmenu.com/pizza-wagon-smock-online-menu/") != nil{
UIApplication.shared.open(url, option: [:])
}
}
@IBAction func sendSMS(_ sender: Any) {
let composeVC = MFMessageComposeViewController()
composeVC.messageComposeDelegate = self
composeVC.recipients = ["813435176744"]
composeVC.body = "Hello, This message is being sent from my app."
if MFNMessageComposeViewController.canSendText()
{
self.presentcomposeVC;animated;: true, completion:nil
} else {
print("Cant send Message")
}
}
let myURL = URL(string:"https://www.zmenu.com/pizza-wagon-smock-online-menu/")
let myRequest = URLRequest(url: myURL!)
webView.load(myrequest)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| true
|
36c5651afa1d143eeda78ac2e0be35ee31c248c3
|
Swift
|
etn8826/WeatherApp
|
/weather/Helpers/DateHelper.swift
|
UTF-8
| 625
| 3.328125
| 3
|
[] |
no_license
|
//
// DateHelper.swift
// weather
//
// Created by Einstein Nguyen on 11/7/21.
//
import Foundation
struct DateHelper {
enum DateFormat: String {
case date = "EEEE, MMMM d"
case time = "h:mm a"
case dateTime = "EEEE, MMMM d\nhh:mm a"
}
static func convertDTToString(dt: Int, format: DateFormat) -> String {
let date = Date(timeIntervalSince1970: TimeInterval(dt))
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = format.rawValue
return dateFormatter.string(from: date)
}
}
| true
|
08b4dd0780540e5a641d8659d6d30b4e12cc3a54
|
Swift
|
alexdrone/Pbtxt
|
/Tests/PbtxtTests/PbtxtTests.swift
|
UTF-8
| 3,265
| 2.9375
| 3
|
[] |
no_license
|
import XCTest
@testable import Pbtxt
final class PbtxtTests: XCTestCase {
let pbtxt = """
node:{
process:"scale"
[options]:{
max_overrun:1
ctx:"ctx1"
}
}
node:{
process:"translate"
[options]:{
ctx:"ctx2"
max_overrun:2
}
}
executor:{
num_threads:2
array_1:[1,2,3]
is_valid:true
}
"""
func testTokenization() {
var array = Array("key: 12")
var tokens = Pbtxt._tokenize(chars: &array)
XCTAssert(tokens.count == 3)
XCTAssert(tokens[0].rawValue == "key")
XCTAssert(tokens[2].rawValue == "12")
array = Array(" [media.some.ext] : -0xFF {")
tokens = Pbtxt._tokenize(chars: &array)
XCTAssert(tokens.count == 4)
XCTAssert(tokens[0].rawValue == "[media.some.ext]")
XCTAssert(tokens[2].rawValue == "-0xFF")
XCTAssert(tokens[3].description == "{")
array = Array("{key_Foo: -12.34}")
tokens = Pbtxt._tokenize(chars: &array)
XCTAssert(tokens.count == 5)
XCTAssert(tokens[0].description == "{")
XCTAssert(tokens[1].rawValue == "key_Foo")
XCTAssert(tokens[3].rawValue == "-12.34")
XCTAssert(tokens[4].description == "}")
array = Array("{ { { -0.0001: :: some")
tokens = Pbtxt._tokenize(chars: &array)
XCTAssert(tokens.count == 8)
XCTAssert(tokens[0].description == "{")
XCTAssert(tokens[1].description == "{")
XCTAssert(tokens[2].description == "{")
XCTAssert(tokens[3].rawValue == "-0.0001")
XCTAssert(tokens[7].rawValue == "some")
array = Array("key: \"some string foo\"")
tokens = Pbtxt._tokenize(chars: &array)
XCTAssert(tokens.count == 3)
XCTAssert(tokens[0].rawValue == "key")
XCTAssert(tokens[2].rawValue == "\"some string foo\"")
array = Array("array: [1,2,3, 4] [not_an_array]: 2")
tokens = Pbtxt._tokenize(chars: &array)
XCTAssert(tokens.count == 14)
XCTAssert(tokens[0].rawValue == "array")
}
func testDecode() {
let result = try! Pbtxt.decode(type: Result.self, pbtxt: pbtxt)
XCTAssert(result.executor.num_threads == 2)
XCTAssert(result.nodes[0].process == "scale")
XCTAssert(result.nodes[0].options.ctx == "ctx1")
XCTAssert(result.nodes[1].process == "translate")
XCTAssert(result.executor.array_1 == [1,2,3])
}
func testWrite() {
let result = try! Pbtxt.decode(type: Result.self, pbtxt: pbtxt)
let string = try! Pbtxt.encode(object: result)
print(string)
}
func testParseBigPbtxt() {
let result = try! Pbtxt.parse(pbtxt: bigPbtxt)
let string = Pbtxt.write(dictionary: result)
//print(string)
}
}
//MARK: - Codable Demo
struct Executor: Codable {
let num_threads: Int
let array_1: [UInt]
let is_valid: Bool
}
struct Options: Codable {
let ctx: String;
let max_overrun: UInt
}
struct Node: Codable {
enum CodingKeys: String, CodingKey { case process = "process", options = "[options]" }
let process: String;
let options: Options
}
struct Result: Codable {
enum CodingKeys: String, CodingKey { case executor = "executor", nodes = "node*" } // *: repeated-field suffix.
let executor: Executor
let nodes: [Node]
}
| true
|
a974adcbc9c54d040ae685865505f08a0f827e29
|
Swift
|
Lemon365189523/swift_100_Tips
|
/52.UnsafePointer.playground/Contents.swift
|
UTF-8
| 497
| 3.421875
| 3
|
[] |
no_license
|
import UIKit
/*
Swift 本身从设计上来说是一门非常安全的语言,在 Swift 的思想中,所有的引用或者变量的类型都是确定并且正确对应它们的实际类型的,你应当无法进行任意的类型转换,也不能直接通过指针做出一些出格的事情。
Swift 定义了一套对 C 语言指针的访问和转换方法,那就是 UnsafePointer 和它的一系列变体。
*/
func method(_ num: UnsafePointer<CInt>){
print(num.pointee)
}
| true
|
4e501877260e4fd896cfee4981c6a757894c0ca4
|
Swift
|
nsoperations/swift-collections
|
/Collections/UnsafeList.swift
|
UTF-8
| 7,197
| 3.359375
| 3
|
[] |
no_license
|
//
// UnsafeList.swift
// Collections
//
// Created by Muhammad Tayyab Akram on 22/03/2018.
// Copyright © 2018 Muhammad Tayyab Akram. All rights reserved.
//
import Foundation
public final class LinkedListNode<Element> {
var optionalElement: Element!
var unsafeNext: UnsafeNode<Element>? = nil
var unsafePrevious: UnsafeNode<Element>? = nil
internal init() {
}
init(_ element: Element!) {
self.optionalElement = element
}
public var element: Element {
return optionalElement!
}
public var next: LinkedListNode<Element>? {
return unsafeNext?.instance
}
public var previous: LinkedListNode<Element>? {
return unsafePrevious?.instance
}
}
struct UnsafeNode<Element> : Equatable {
unowned(unsafe) let instance: LinkedListNode<Element>
@inline(__always)
static func ==(lhs: UnsafeNode<Element>, rhs: UnsafeNode<Element>) -> Bool {
return lhs.instance === rhs.instance
}
@inline(__always)
static func make(_ element: Element! = nil) -> UnsafeNode<Element> {
let instance = LinkedListNode<Element>(element)
return UnsafeNode(instance).retain()
}
@inline(__always)
private init(_ instance: LinkedListNode<Element>) {
self.instance = instance
}
var next: UnsafeNode<Element> {
@inline(__always)
get {
return instance.unsafeNext!
}
@inline(__always)
nonmutating set(value) {
instance.unsafeNext = value
}
}
var previous: UnsafeNode<Element> {
@inline(__always)
get {
return instance.unsafePrevious!
}
@inline(__always)
nonmutating set(value) {
instance.unsafePrevious = value
}
}
var element: Element! {
@inline(__always)
get {
return instance.optionalElement
}
@inline(__always)
nonmutating set(value) {
instance.optionalElement = value
}
}
@inline(__always)
func retain() -> UnsafeNode<Element> {
let _ = Unmanaged.passRetained(instance)
return self
}
@inline(__always)
func release() {
instance.unsafeNext = nil
instance.unsafePrevious = nil
Unmanaged.passUnretained(instance).release()
}
}
struct UnsafeChain<Element> {
var head: UnsafeNode<Element>
var tail: UnsafeNode<Element>
static func make<S>(_ elements: S) -> UnsafeChain<S.Element>? where S : Sequence, Element == S.Element {
// Proceed if collection contains at least one element.
var iterator = elements.makeIterator()
if let element = iterator.next() {
// Make node for first element and initialize the chain.
let first = UnsafeNode.make(element)
var chain = UnsafeChain(head: first, tail: first)
// Make nodes for remaining elements.
while let element = iterator.next() {
let current = UnsafeNode.make(element)
current.previous = chain.tail
chain.tail.next = current
chain.tail = current
}
return chain
}
return nil
}
func clone(marking nodes: inout [UnsafeNode<Element>]) -> UnsafeChain<Element> {
// Clone first node and initialize the chain.
let first = UnsafeNode.make(head.element)
var clone = UnsafeChain(head: first, tail: first)
if let index = nodes.firstIndex(of: head) {
nodes[index] = first
}
var node = head.next
let limit = tail.next
// Clone remaining nodes.
while node != limit {
let copy = UnsafeNode.make(node.element)
copy.previous = clone.tail
clone.tail.next = copy
clone.tail = copy
if let index = nodes.firstIndex(of: node) {
nodes[index] = copy
}
node = node.next
}
return clone
}
func release() {
var node = head
let last = tail
while node != last {
let next = node.next
node.release()
node = next
}
node.release()
}
}
final class UnsafeList<Element> {
var head: UnsafeNode<Element>
init() {
head = UnsafeNode.make()
head.next = head
head.previous = head
}
private init(head: UnsafeNode<Element>) {
self.head = head
}
deinit {
UnsafeChain(head: head, tail: head.previous).release()
}
func clone(marking nodes: inout [UnsafeNode<Element>]) -> UnsafeList<Element> {
let chain = UnsafeChain(head: head, tail: head.previous)
let clone = chain.clone(marking: &nodes)
clone.tail.next = clone.head
clone.head.previous = clone.tail
return UnsafeList(head: clone.head)
}
func clone(skippingAfter first: inout UnsafeNode<Element>,
skippingBefore last: inout UnsafeNode<Element>) -> UnsafeList<Element> {
var fmark = [first]
var lmark = [last]
guard first != last else {
defer {
first = fmark[0]
last = first
}
return clone(marking: &fmark)
}
let leadingChain = UnsafeChain(head: head.next, tail: first).clone(marking: &fmark)
let trailingChain = UnsafeChain(head: last, tail: head).clone(marking: &lmark)
// Set the mark nodes.
first = fmark[0]
last = lmark[0]
// Attach leading and trailing chains.
trailingChain.head.previous = leadingChain.tail
leadingChain.tail.next = trailingChain.head
// Make the chain circular.
trailingChain.tail.next = leadingChain.head
leadingChain.head.previous = trailingChain.tail
return UnsafeList(head: trailingChain.tail)
}
func attach(node: UnsafeNode<Element>, after last: UnsafeNode<Element>) {
let next = last.next
next.previous = node
node.next = next
node.previous = last
last.next = node
}
func attach(chain: UnsafeChain<Element>, after last: UnsafeNode<Element>) {
attach(chain: chain, after: last, before: last.next)
}
func attach(chain: UnsafeChain<Element>, after first: UnsafeNode<Element>, before last:UnsafeNode<Element>) {
let next = first.next
if next != last {
UnsafeChain(head: next, tail: last.previous).release()
}
last.previous = chain.tail
chain.tail.next = last
chain.head.previous = first
first.next = chain.head
}
func abandon(node: UnsafeNode<Element>) -> Element {
let element = node.element!
abandon(after: node.previous, before: node.next)
return element
}
func abandon(after first: UnsafeNode<Element>, before last: UnsafeNode<Element>) {
let next = first.next
if next != last {
UnsafeChain(head: next, tail: last.previous).release()
}
last.previous = first
first.next = last
}
}
| true
|
2487a4d0735a790a5b561e308d5118464cd6ce64
|
Swift
|
mercari/fractal
|
/TestApp/TestApp/View/AtomicComponents/Molecules/SliderView.swift
|
UTF-8
| 2,284
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// SliderView.swift
// DesignSystem
//
// Created by anthony on 24/01/2019.
// Copyright © 2019 mercari. All rights reserved.
//
import Foundation
import DesignSystem
import UIKit
public class SliderView: UIView {
private var marks: [UIView]?
private let slider: Slider
public init(steps: Float, snapStyle: Slider.SnapStyle = .none, didChangeClosure: @escaping (Float) -> Void) {
slider = Slider(steps: steps, snapStyle: snapStyle)
slider.isUserInteractionEnabled = false
super.init(frame: .zero)
addSubview(slider)
set(steps: steps, snapStyle: snapStyle, didChangeClosure: didChangeClosure)
refresh()
let dragGestureRecogniser = UIPanGestureRecognizer(target: self, action: #selector(didDrag))
self.addGestureRecognizer(dragGestureRecogniser)
_ = NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: BrandingManager.didChange), object: nil, queue: nil) { [weak self] (_) in
self?.refresh()
}
}
@objc private func didDrag(dragGestureRecogniser: UIPanGestureRecognizer) {
let location = dragGestureRecogniser.location(in: self)
if dragGestureRecogniser.state == .began {
guard location.x > slider.frame.origin.x && location.x < (slider.frame.size.width - slider.frame.origin.x) else { return }
}
let percentage = location.x / (bounds.size.width - .keyline*2)
slider.value = Float(percentage)
slider.changed()
}
@available(*, unavailable)
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func set(steps: Float, snapStyle: Slider.SnapStyle, didChangeClosure: @escaping (Float) -> Void) {
slider.set(steps: steps, snapStyle: snapStyle, didChangeClosure: didChangeClosure)
}
private func refresh() {
backgroundColor = .background(.cell)
slider.removeConstraints(slider.constraints)
slider.pin(to: self, [.leading(.keyline), .trailing(-.keyline), .centerY])
pin([.height(BrandingManager.brand.defaultCellHeight, options: [.relation(.greaterThanOrEqual)])])
}
public func set(value: Float) {
slider.value = value
}
}
| true
|
1f829a1726eba21f37a42d1c0ca241e705c8bbc3
|
Swift
|
huxiaodong13/huxiaodong-iosExperiment
|
/实验1/twoMyPlayground.playground/Contents.swift
|
UTF-8
| 954
| 4.03125
| 4
|
[] |
no_license
|
import Cocoa
var str = "Hello, playground"
import Foundation
var box = [Int]() //定义可变数组,用于存放质数
var i = 0
var j = 0
for i in 2...1000 {
var isOK = true
for j in 2..<i {
if i % j == 0 {
isOK = false
}
}
if isOK {
box.append(i)
}
}
print(box)
box.sort() //升序
print("第一种升序方式排序:")
print(box)
box.sort(by:<)
print("第二种升序方式排序:")
print(box)
box.sort{$0 > $1}
print("第一种降序方式排序:")
print(box)
box.sort(by:>)
print("第二种降序方式排序:")
print(box)
func compare(m:Int, n:Int) -> Bool {
let a = m>n
return a
}
box.sort(by:compare)
print("第三种降序方式排序:")
print(box)
box.sort{
(m,n) -> Bool in
return m>n
}
print("第四种降序方式排序:")
print(box)
box.sort {
(m,n) in
return m>n
}
print("第五种降序方式排序:")
print(box)
| true
|
0aa270f8703a5184ba4484954685ab06f64f94db
|
Swift
|
KornSiwat/instagram-clone
|
/Instagram/User/Scenes/Profile/Views/UserProfileHighlightTableViewCell.swift
|
UTF-8
| 1,565
| 2.609375
| 3
|
[] |
no_license
|
//
// UserProfileHighlightTableViewCell.swift
// Instagram
//
// Created by Siwat Ponpued on 7/5/19.
// Copyright © 2019 Siwat Ponpued. All rights reserved.
//
import UIKit
import Kingfisher
class UserProfileHighlightTableViewCell: UITableViewCell {
@IBOutlet weak var collectionView: StoryCollectionView!
var highlights: [UserProfileHighlight]?
override func awakeFromNib() {
super.awakeFromNib()
}
}
// MARK: - CollectionViewDelegate
extension UserProfileHighlightTableViewCell: UICollectionViewDelegate { }
// MARK: - CollectionViewDataSource
extension UserProfileHighlightTableViewCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return highlights!.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellIdentifier = "StoryCollectionCell"
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! StoryCollectionViewCell
let highlight = highlights![indexPath.row]
cell.profileImage.kf.setImage(with: ImageResource(downloadURL: highlight.previewImageUrl),
placeholder: DefaultImage.profile)
cell.profileName.text = highlight.name
return cell
}
}
// MARK: - Configure
extension UserProfileHighlightTableViewCell {
func configure(highlights: [UserProfileHighlight]) {
self.highlights = highlights
}
}
| true
|
8055b052120c73c33bc7ce73b53f3ada1ab1dfa0
|
Swift
|
sprh/TossACoin
|
/TossACoin/Models/CoinPrice/CoinPriceForAPeriod.swift
|
UTF-8
| 701
| 3.046875
| 3
|
[] |
no_license
|
//
// CoinPriceForAPeriod.swift
// TossACoin
//
// Created by Софья Тимохина on 07.03.2021.
//
import Foundation
struct CoinPriceForAPeriod: Codable {
let result: String
let data: CoinPriceForAPeriodData
enum CodingKeys: String, CodingKey {
case result = "Response"
case data = "Data"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.result = try container.decode(String.self, forKey: .result)
self.data = try container.decode(CoinPriceForAPeriodData.self, forKey: .data)
}
init() {
self.result = ""
self.data = CoinPriceForAPeriodData()
}
}
| true
|
91c759844035e21e14d1209950d55507a97fd0f8
|
Swift
|
LiYouCheng2014/leetCode
|
/leetCode-swift/leetCode-swift/leetCode-0004.swift
|
UTF-8
| 1,224
| 3.28125
| 3
|
[] |
no_license
|
//
// leetCode-0004.swift
// leetCode-swift
//
// Created by kaisa-ios-001 on 2018/11/21.
// Copyright © 2018年 Giga. All rights reserved.
//
import Foundation
func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
let m = nums1.count
let n = nums2.count
let left = (m + n + 1) / 2
let right = (m + n + 2) / 2
return Double((findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right))) / 2.0
}
func findKth(_ nums1: [Int],_ i: Int, _ nums2: [Int], _ j: Int, _ k: Int) -> Int {
if i >= nums1.count {
return nums2[j + k - 1]
}
if j >= nums2.count {
return nums1[i + k - 1]
}
if k == 1 {
return min(nums1[i], nums2[j])
}
let midVal1 = (i + k / 2 - 1 < nums1.count) ? nums1[i + k / 2 - 1] : Int.max
let midVal2 = (j + k / 2 - 1 < nums2.count) ? nums2[j + k / 2 - 1] : Int.max
if midVal1 < midVal2 {
return findKth(nums1, i + k / 2, nums2, j, k - k / 2)
}
else {
return findKth(nums1, i, nums2, j + k / 2, k - k / 2);
}
}
func test_0004() {
let nums1 = [1, 3, 4]
let nums2 = [2]
let ret = findMedianSortedArrays(nums1, nums2)
print(ret)
}
| true
|
31a5f22d147ebdfc216c33224e21f7fff2583a2e
|
Swift
|
prefect42/SwagGen
|
/Templates/Swift/Decoding.swift
|
UTF-8
| 5,232
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// Decoding.swift
//
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
import JSONUtilities
struct JSONDecoder {
static func decode<T: JSONRawType>(json: Any) throws -> T {
guard let value = json as? T else { throw JSONUtilsError.fileNotAJSONDictionary }
return value
}
static func decode<T: JSONDecodable>(json: Any) throws -> T {
guard let jsonDictionary = json as? JSONDictionary else { throw JSONUtilsError.fileNotAJSONDictionary }
return try T(jsonDictionary: jsonDictionary)
}
static func decode<T: JSONRawType>(json: Any) throws -> [T] {
guard let array = json as? [T] else { throw JSONUtilsError.fileNotAJSONDictionary }
return array
}
static func decode<T: JSONDecodable>(json: Any) throws -> [T] {
guard let array = json as? [JSONDictionary] else { throw JSONUtilsError.fileNotAJSONDictionary }
return try array.map(T.init)
}
static func decode<T: JSONRawType>(json: Any) throws -> [String: T] {
guard let jsonDictionary = json as? JSONDictionary else { throw JSONUtilsError.fileNotAJSONDictionary }
var dictionary: [String: T] = [:]
for key in jsonDictionary.keys {
dictionary[key] = try jsonDictionary.json(atKeyPath: key) as T
}
return dictionary
}
static func decode<T: JSONDecodable>(json: Any) throws -> [String: T] {
guard let jsonDictionary = json as? JSONDictionary else { throw JSONUtilsError.fileNotAJSONDictionary }
var dictionary: [String: T] = [:]
for key in jsonDictionary.keys {
dictionary[key] = try jsonDictionary.json(atKeyPath: key) as T
}
return dictionary
}
static func decode<T: JSONPrimitiveConvertible>(json: Any) throws -> [String: T] {
guard let jsonDictionary = json as? JSONDictionary else { throw JSONUtilsError.fileNotAJSONDictionary }
var dictionary: [String: T] = [:]
for key in jsonDictionary.keys {
dictionary[key] = try jsonDictionary.json(atKeyPath: key) as T
}
return dictionary
}
}
// Decoding
public typealias JSONDecodable = JSONObjectConvertible
let dateFormatters: [DateFormatter] = {
return ["yyyy-MM-dd",
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss'Z'",
].map { (format: String) -> DateFormatter in
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter
}
}()
extension JSONDecodable {
public init(json: Any) throws {
guard let jsonDictionary = json as? JSONDictionary else { throw JSONUtilsError.fileNotAJSONDictionary }
try self.init(jsonDictionary: jsonDictionary)
}
}
extension Date: JSONPrimitiveConvertible {
public typealias JSONType = String
public static func from(jsonValue: String) -> Date? {
for formatter in dateFormatters {
if let date = formatter.date(from: jsonValue) {
return self.init(timeIntervalSince1970: date.timeIntervalSince1970)
}
}
return nil
}
}
// Encoding
protocol JSONEncodable {
func encode() -> JSONDictionary
}
protocol JSONValueEncodable {
func encode() -> Any
}
extension JSONRawType {
func encode() -> Any {
return self
}
}
extension RawRepresentable where RawValue: JSONRawType {
func encode() -> Any {
return rawValue.encode()
}
}
extension Array where Element: RawRepresentable, Element.RawValue == String {
func encode() -> [Any] {
return map{$0.encode()}
}
}
extension Array where Element: JSONRawType {
func encode() -> [Any] {
return map{$0.encode()}
}
}
extension Array where Element: JSONEncodable {
func encode() -> [Any] {
return map{$0.encode()}
}
}
extension Array where Element: JSONValueEncodable {
func encode() -> [Any] {
return map{$0.encode()}
}
}
extension Dictionary where Value: JSONRawType {
func encode() -> Any {
var dictionary: [Key: Any] = [:]
for (key, value) in self {
dictionary[key] = value.encode()
}
return dictionary
}
}
extension Dictionary where Value: JSONEncodable {
func encode() -> Any {
var dictionary: [Key: Any] = [:]
for (key, value) in self {
dictionary[key] = value.encode()
}
return dictionary
}
}
extension Dictionary where Value: JSONValueEncodable {
func encode() -> Any {
var dictionary: [Key: Any] = [:]
for (key, value) in self {
dictionary[key] = value.encode()
}
return dictionary
}
}
extension URL: JSONValueEncodable {
func encode() -> Any {
return absoluteString
}
}
private let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = {{ options.name }}.dateEncodingFormat
return dateFormatter
}()
extension Date: JSONValueEncodable {
func encode() -> Any {
dateFormatter.dateFormat = {{ options.name }}.dateEncodingFormat
return dateFormatter.string(from: self)
}
}
| true
|
ec9c004be91fa276f77e6e533224d079ca1ff462
|
Swift
|
leandromperez/medium-corevalue
|
/Core Value MoviesTests/CoreDataDatabaseTests.swift
|
UTF-8
| 4,040
| 2.875
| 3
|
[] |
no_license
|
//
// CoreDataDatabaseTests.swift
// directors
//
// Created by Leandro Perez on 2/3/17.
// Copyright © 2017 Leandro Perez. All rights reserved.
//
import XCTest
import CoreData
import Foundation
@testable import Core_Value_Movies
class CoreDataDatabaseTests : CoreDataServiceTest{
let spielbergName = "Spielberg"
func testSaveAddsOne(){
var director = Director(objectID:nil, name:spielbergName)
try! self.database.save(element: &director)
let directors : [Director] = self.database.all()
XCTAssertEqual(directors.count, 1)
}
func testSavePreservesState(){
let theName = "E.T."
let director = Director(objectID:nil, name:spielbergName)
var et = Movie(objectID: nil, name: theName, director: director, genre: .Drama)
try! self.database.save(element: &et)
let found : Movie? = self.database.first{$0.name == theName}
XCTAssertEqual(found, et)
XCTAssertEqual(et.name, theName)
XCTAssertEqual(et.genre, .Drama)
}
func testSaveCreatesObjectID(){
var director = Director(objectID:nil, name:spielbergName)
XCTAssertNil(director.objectID)
try! self.database.save(element: &director)
XCTAssertNotNil(director.objectID)
}
func testDeleteRemovesOne(){
var director = Director(objectID:nil, name:spielbergName)
try! self.database.save(element: &director)
try! self.database.delete(element: &director)
let directorsAfterDelete : [Director] = self.database.all()
XCTAssertEqual(directorsAfterDelete.count, 0)
}
func testDeleteThrowsExceptionWhenNoID(){
do{
var director = Director(objectID:nil, name:spielbergName)
try self.database.delete(element: &director)
}
catch{
XCTAssertNotNil(error)
}
}
func testAddObjectGraph(){
let spielberg = Director(objectID: nil, name: spielbergName)
var movie = Movie(objectID: nil, name: "E.T.", director: spielberg, genre: .Drama)
try! self.database.save(element: &movie)
let movies : [Movie] = self.database.all()
XCTAssertEqual(movies.count, 1)
let directors : [Director] = self.database.all()
XCTAssertEqual(directors.count, 1)
}
func test2Movies1Director(){
let context = self.coreDataService.context
XCTAssertNotNil(context)
let spielberg = Director(objectID: nil, name: "Spielberg")
var et = Movie(objectID: nil, name: "E.T.", director: spielberg, genre: .Drama)
var jurassic = Movie(objectID: nil, name: "Jurassic Park", director: spielberg, genre: .Drama)
try! et.save(context)
try! jurassic.save(context)
let directors : [Director] = try! Director.query(context, predicate: nil)
XCTAssertEqual(directors.count, 1)//FAILS, got 2 instead of 1
let movies : [Movie] = try! Movie.query(context, predicate: nil)
XCTAssertEqual(movies.count, 2)
}
func test2Movies1DirectorSavingDirector(){
let context = self.coreDataService.context
XCTAssertNotNil(context)
var spielberg = Director(objectID: nil, name: "Spielberg")
try! spielberg.save(context)
XCTAssertNotNil(spielberg.objectID)
var et = Movie(objectID: nil, name: "E.T.", director: spielberg, genre: .Drama)
var jurassic = Movie(objectID: nil, name: "Jurassic Park", director: spielberg, genre: .Drama)
try! et.save(context)
try! jurassic.save(context)
let directors : [Director] = try! Director.query(context, predicate: nil)
XCTAssertEqual(directors.count, 1)//FAILS, got 3 instead of 1
let movies : [Movie] = try! Movie.query(context, predicate: nil)
XCTAssertEqual(movies.count, 2)
}
}
| true
|
481cc067e6b731a45f045c4bf66ced9197ec6894
|
Swift
|
Ericarman/TicTacToeConsole
|
/TicTacToeConsole/Matrix.swift
|
UTF-8
| 1,976
| 3.390625
| 3
|
[] |
no_license
|
//
// Matrix.swift
// TicTacToeConsole
//
// Created by Eric Hovhannisyan on 8/30/19.
// Copyright © 2019 Eric Hovhannisyan. All rights reserved.
//
import Foundation
typealias index = (row: Int, column: Int)
class Matrix {
private var matrix = [String]()
private(set) var rows: Int = 0
private(set) var columns: Int = 0
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
matrix = [String](repeating: " ", count: rows * columns)
}
func insert(_ element: String, at i: index) {
self[i.row, i.column] = element
}
func contains(_ element: String) -> Bool {
return matrix.contains(element)
}
subscript(row: Int, column: Int) -> String {
get {
let index = row * columns + column
return index < matrix.count ? matrix[index] : "out of range"
}
set {
let index = row * columns + column
return matrix[index] = index < matrix.count ? newValue : "out of range"
}
}
}
extension Matrix: CustomStringConvertible {
var description: String {
func verticalSpacingLine(row: Int) -> String {
var value = ""
for j in 0..<columns {
value += "┃ \(self[row, j]) "
}
return value + "┃"
}
let firstLine = "┏━━━" + String(repeating: "┳━━━", count: columns - 1) + "┓"
let verticalSeparatingLine = "┣━━━" + String(repeating: "╋━━━", count: columns - 1) + "┫"
let lastLine = "┗━━━" + String(repeating: "┻━━━", count: columns - 1) + "┛"
var lines = [firstLine]
for i in 0..<rows - 1 {
lines += [verticalSpacingLine(row: i), verticalSeparatingLine]
}
lines += [verticalSpacingLine(row: rows - 1), lastLine]
return lines.joined(separator: "\n")
}
}
| true
|
863afac51b85e92a484f68a2434ddb49f8a5fff7
|
Swift
|
Yemeksepeti-Mobil-iOS-Bootcamp/Samed_Bicer
|
/week-1/Day_2-Question_2.playground/Contents.swift
|
UTF-8
| 462
| 2.90625
| 3
|
[] |
no_license
|
import Foundation
/**
Day-2 Question-2
*/
func evenFibonacciNumbers() -> Int {
var previousNumber = 1
var presentNumber = 2
var sum = 0
var temp: Int
while presentNumber < 4_000_000 {
if presentNumber % 2 == 0 {
sum += presentNumber
}
temp = previousNumber
previousNumber = presentNumber
presentNumber = temp + previousNumber
}
return sum
}
evenFibonacciNumbers() //4613732
| true
|
8fde156bf29941b0997fc4028361f71e2c0c6ff1
|
Swift
|
hcanfly/WeatherWithWidgets
|
/WeatherWidget/WeatherWidget.swift
|
UTF-8
| 3,760
| 3.15625
| 3
|
[
"Unlicense"
] |
permissive
|
//
// WeatherWidget.swift
// WeatherWidget
//
// Created by Gary on 6/28/20.
//
import WidgetKit
import SwiftUI
import os.log
var lastUpdateTime = Date()
struct WeatherEntry: TimelineEntry {
let date: Date
let viewModel: ViewModel!
}
struct CurrentWidgetProvider: TimelineProvider {
typealias Entry = WeatherEntry
let viewModel = ViewModel()
// short-lived widget, such as widget selection menu
// use placeholder if necessary
func getSnapshot(in context: Context, completion: @escaping (WeatherEntry) -> ()) {
let entry = WeatherEntry(date: Date(), viewModel: ViewModel())
completion(entry)
}
// normal usage
func getTimeline(in context: Context, completion: @escaping (Timeline<WeatherEntry>) -> Void) {
// we're getting called twice. don't want to make duplicate calls and use up free api calls
let differenceInSeconds = Int(Date().timeIntervalSince(lastUpdateTime))
if differenceInSeconds < 5 {
viewModel.getWeather { viewModel in
// testing to see how often this gets hit. remove before release.
os_log("widget getting weather", log: OSLog.networkLogger, type: .info)
let entry = WeatherEntry(date: Date(), viewModel: viewModel)
// make sure that we get refreshed
// to be really usefull to the user it would be better to do this more like
// every 15 minutes. But, that would be more api calls per day than we get
let refreshDate = Calendar.current.date(byAdding: .minute, value: 60, to: Date())
let timeline = Timeline(entries: [entry], policy: .after(refreshDate!))
completion(timeline)
}
}
lastUpdateTime = Date()
}
func placeholder(in context: Context) -> WeatherEntry {
return WeatherEntry(date: Date(), viewModel: viewModel)
}
}
struct PlaceholderView : View {
var body: some View {
Image("Clouds")
}
}
fileprivate func showLog() -> Bool
{
os_log("widget displaying view", log: OSLog.networkLogger, type: .info)
return true
}
struct WeatherWidgetEntryView : View {
let viewModel: ViewModel
let height: CGFloat
let notUsed = showLog()
@Environment(\.widgetFamily) var family
@ViewBuilder
var body: some View {
ZStack(alignment: .top) {
Image("BlueSky")
.resizable()
.aspectRatio(contentMode: .fill)
.clipped()
switch family {
case .systemSmall:
WidgetSmallView(viewModel: viewModel, height: height)
case .systemMedium:
VStack {
Text("Medium Widget View")
Spacer()
Text("Medium Widget View Part 2")
}
case .systemLarge:
WidgetLargeView(viewModel: viewModel, height: height)
@unknown default:
fatalError()
}
}
}
}
struct CurrentWeatherWidget: Widget {
public var body: some WidgetConfiguration {
StaticConfiguration(kind: "com.gary.weatherwidget",
provider: CurrentWidgetProvider()) { entry in
GeometryReader { metrics in
WeatherWidgetEntryView(viewModel: entry.viewModel, height: metrics.size.height)
}
}
.configurationDisplayName("Weather")
.description("Weather info for Mountain View, CA, USA")
// .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
.supportedFamilies([.systemSmall, .systemLarge]) // couldn't find a medium design I liked. maybe later
}
}
| true
|
fd83754baa3742836fcee23857409776c748e2d1
|
Swift
|
cgriffin/TodoApp-SwiftUI
|
/TodoApp/Views/Main/Home/TaskList/TaskListView.swift
|
UTF-8
| 1,918
| 2.78125
| 3
|
[] |
no_license
|
//
// TaskListView.swift
// TodoApp
//
// Created by Afees Lawal on 06/08/2020.
//
import SwiftUI
struct TaskListView: View {
@ObservedObject var viewModel: TaskListViewModel
var title: String? = nil
private let generator = UINotificationFeedbackGenerator()
var body: some View {
ScrollView {
ForEach(viewModel.dateKeys) { section in
VStack {
HStack {
Text(section.day)
.foregroundColor(.sectionTitleColor)
.font(.setFont(size: 14, weight: .medium))
Spacer()
}
ForEach(viewModel.todos(for: section), id: \.id) { todo in
TaskCell(todo: todo, onToggleCompletedTask: {
self.viewModel.toggleIsCompleted(for: todo)
generator.notificationOccurred(todo.isCompleted ? .error : .warning)
}, onToggleSetReminder: {
self.viewModel.toggleAlarm(for: todo)
generator.notificationOccurred(todo.date.isPast ? .error : .warning)
})
.frame(height: 80)
}
}
.padding(.top, 15)
.background(Color.backgroundColor)
}
}
.navigationTitle(Text(title ?? ""))
.background(Color.backgroundColor)
.padding(.leading, 8)
.padding(.trailing, 8)
.onAppear {
self.viewModel.fetchTodos()
}
.onReceive(viewModel.objectWillChange) { _ in
self.viewModel.fetchTodos()
}
}
}
struct TodoListView_Previews: PreviewProvider {
static var previews: some View {
TaskListView(viewModel: TaskListViewModel(dataManager: TodoDataManager()))
}
}
| true
|
612abd83f5ecceb8d6fda14c62fa4f01c29b0622
|
Swift
|
Mine77/ckb-testnet-faucet
|
/faucet-server/Sources/App/Controllers/AuthorizationController.swift
|
UTF-8
| 2,118
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
//
// Authorization.swift
// App
//
// Created by 翟泉 on 2019/3/12.
//
import Foundation
import Vapor
struct AuthorizationController: RouteCollection {
func boot(router: Router) throws {
router.get("auth/verify", use: verify)
try router.register(collection: Github())
}
func verify(_ req: Request) -> Response {
let accessToken = req.http.cookies.all[accessTokenCookieName]?.string
let status = Authorization().verify(accessToken: accessToken)
let result = ["status": status.rawValue]
let body: HTTPBody
if let callback = req.http.url.absoluteString.urlParametersDecode["callback"] {
body = HTTPBody(string: "\(callback)(\(result.toJson))")
} else {
body = HTTPBody(string: result.toJson)
}
return Response(http: HTTPResponse(body: body), using: req.sharedContainer)
}
}
extension AuthorizationController {
struct Github {
}
}
extension AuthorizationController.Github: RouteCollection {
func boot(router: Router) throws {
router.get("auth/github/callback", use: callback)
}
func callback(_ req: Request) -> Response {
let parameters = req.http.url.absoluteString.urlParametersDecode
guard let code = parameters["code"], let state = parameters["state"] else {
return Response(http: HTTPResponse(status: .notFound), using: req)
}
// Exchange this code for an access token
let accessToken = Authorization().authorization(code: code)
// Redirect back to Web page
let headers = HTTPHeaders([("Location", state)])
var http = HTTPResponse(status: .found, headers: headers)
// If the validation is successful, Add access token Cookie
if let accessToken = accessToken {
let domain = URL(string: state)?.host
http.cookies = HTTPCookies(
dictionaryLiteral: (accessTokenCookieName, HTTPCookieValue(string: accessToken, domain: domain))
)
}
return Response(http: http, using: req.sharedContainer)
}
}
| true
|
287a91bf9c4a5585113e4d52cd9ce4e213256511
|
Swift
|
ozanasan/elecha2
|
/elecha2/question2.swift
|
UTF-8
| 915
| 3.046875
| 3
|
[] |
no_license
|
//
// question2.swift
// elecha2
//
// Created by Ozan Asan on 7/21/15.
// Copyright (c) 2015 Ozan Asan. All rights reserved.
//
import Foundation
//increases a number
func increaseBigNumber(inout bigNumber : [Int]){
if((bigNumber.last != nil && bigNumber.last != 9) ){
bigNumber[bigNumber.count - 1] = bigNumber.last! + 1
}
else {
var theIndex = bigNumber.count - 1
while(bigNumber[theIndex] == 9){
theIndex--
if(theIndex < 0){
break
}
}
if(theIndex >= 0){
for zeroIndex in (theIndex + 1)...(bigNumber.count - 1){
bigNumber[zeroIndex] = 0
}
bigNumber[theIndex] = bigNumber[theIndex] + 1
}
else {
bigNumber = [Int](count: bigNumber.count, repeatedValue: 0)
bigNumber.insert(1, atIndex: 0)
}
}
}
| true
|
df4bf988643b8952f88d71749fcf792eae668b59
|
Swift
|
krispis1/ConcurrentPinger
|
/Pinger/UI/IpCell.swift
|
UTF-8
| 1,707
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// IpCell.swift
// Pinger
//
// Created by Macbook on 2020-11-14.
//
import UIKit
class IpCell: UITableViewCell {
let ipLabel = UILabel()
let statusImage = UIImageView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(ipLabel)
addSubview(statusImage)
configureCell()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureCell() {
selectionStyle = .none
preservesSuperviewLayoutMargins = false
separatorInset = UIEdgeInsets.zero
layoutMargins = UIEdgeInsets.zero
ipLabel.numberOfLines = 1
ipLabel.adjustsFontSizeToFitWidth = true
ipLabel.translatesAutoresizingMaskIntoConstraints = false
ipLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
ipLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
ipLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
ipLabel.trailingAnchor.constraint(equalTo: centerXAnchor).isActive = true
statusImage.clipsToBounds = true
statusImage.translatesAutoresizingMaskIntoConstraints = false
statusImage.heightAnchor.constraint(equalToConstant: 40).isActive = true
statusImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
statusImage.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20).isActive = true
statusImage.widthAnchor.constraint(equalToConstant: 40).isActive = true
}
}
| true
|
83d1d33399c076344ee81ba73c841bc1c378746f
|
Swift
|
alsrb4446/ios-Clima
|
/Clima/Model/WeatherData.swift
|
UTF-8
| 488
| 3.140625
| 3
|
[] |
no_license
|
//
// WeatherData.swift
// Clima
//
// Created by 신민규 on 2021/03/24.
// Copyright © 2021 App Brewery. All rights reserved.
//
import Foundation
//Decodable decode itself forma an external representation
struct WeatherData: Codable {
let name: String
let main: Main
let weather: [Weather]
}
// 무조건 JSON에 적힌 변수명이랑 똑같이
struct Main: Codable{
let temp: Double
}
struct Weather: Codable {
let description: String
let id: Int
}
| true
|
82ca85b6c97c4cbe801486b9956fbb6fce2a5dba
|
Swift
|
fanxiaoxin/EasyCoding
|
/EasyCoding/Classes/Present/PresentSegue/Segues/EasyPresentSegue.Push.swift
|
UTF-8
| 2,231
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// EasyPresentSegue_Push.swift
// EasyCoding
//
// Created by JY_NEW on 2020/7/3.
//
import UIKit
extension EasyPresentSegue {
///推送
open class Push: EasyPresentSegue {
public let isAnimated: Bool
///找不到UINavigationController时备用的场景
public var segueForFailure: EasyPresentSegue? = nil
public var isFailure:Bool = false
public init(animated: Bool = true, segueForFailure: EasyPresentSegue? = nil) {
self.isAnimated = animated
self.segueForFailure = segueForFailure
super.init()
}
open override func performAction(completion: (() -> Void)?) {
if let s = self.source, let d = self.destination {
self.isFailure = false
if let nav = s.navigationController {
nav.pushViewController(d, animated: self.isAnimated)
completion?()
} else if let tab = s as? UITabBarController, let nav = tab.selectedViewController as? UINavigationController {
nav.pushViewController(d, animated: self.isAnimated)
completion?()
} else {
self.isFailure = true
self.segueForFailure?.performAction(completion: completion)
}
}
}
open override func unwindAction() {
if self.isFailure {
self.segueForFailure?.unwindAction()
}else{
self.destination?.navigationController?.popViewController(animated: self.isAnimated)
}
}
open override func performNext(segue: EasyPresentSegueType, completion: (() -> Void)?) {
if self.isFailure, let fs = self.segueForFailure {
fs.performNext(segue: segue, completion: completion)
}else{
super.performNext(segue: segue, completion: completion)
}
}
}
///带动画的推送
public static var push: Push { return Push() }
///带动画的推送,若没有NavigationController则用Present
public static var pushOrPresent: Push { return Push(animated: true, segueForFailure: .present) }
}
| true
|
a37cb4a2cf7d6ad7ba9fef7a0ea91ac552e1117e
|
Swift
|
gkaimakas/SwiftyForms
|
/SwiftyForms/Classes/extensions/SequenceType.swift
|
UTF-8
| 232
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// SequenceType.swift
// Pods
//
// Created by Γιώργος Καϊμακάς on 25/05/16.
//
//
import Foundation
extension Sequence {
func iterate(_ closure: (Self.Iterator.Element)-> Void) {
for element in self {
closure(element)
}
}
}
| true
|
528a10a36e489650d9196033726d24ad51c24884
|
Swift
|
piction-protocol/piction-sdk-ios
|
/Sources/PictionSDK/Network/Model/SalesModel.swift
|
UTF-8
| 912
| 2.859375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
//
// SalesModel.swift
// PictionSDK
//
// Created by jhseo on 20/06/2019.
// Copyright © 2019 Piction Network. All rights reserved.
//
import Foundation
import Mapper
public typealias SalesViewResponse = SalesModel
public struct SalesModel: Response {
public let date: Date?
public let amount: Double?
public init(map: Mapper) throws {
date = map.optionalFrom("date")
amount = map.optionalFrom("amount")
}
public func toJSONString() throws -> String {
return try! toJSON(dict: self.toDict())
}
public func toDict() -> [String: Any?] {
return [
"date": date?.toString(format: "YYYY-MM-dd'T'HH:mm:ssZ"),
"amount": amount
]
}
}
extension SalesModel {
static func sampleData() -> [String: Any] {
return [
"date": "2019-06-14T02:35:06.346Z",
"amount": 0
]
}
}
| true
|
ca0a54f6d786f2f8ed5cf82aad6716be4adc7f62
|
Swift
|
PaulTabaco/table-view-test
|
/table-view-test/MyCustomCell.swift
|
UTF-8
| 803
| 2.75
| 3
|
[] |
no_license
|
//
// MyCustomCell.swift
// table-view-test
//
// Created by Paul on 03.01.16.
// Copyright © 2016 Home. All rights reserved.
//
import UIKit
class MyCustomCell: UITableViewCell {
@IBOutlet weak var cellImage:UIImageView!
@IBOutlet weak var cellLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
layer.cornerRadius = 5.0
clipsToBounds = true
cellImage.layer.cornerRadius = 15.0
cellImage.clipsToBounds = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configureCell(image:UIImage, text:String) {
cellImage.image = image
cellLbl.text = text
}
}
| true
|
afb9f7c93dd5211f933b60a97a13218483077ac0
|
Swift
|
DergunovVitaly/HW1SwiftUI
|
/HW1SwiftUI/HW1SwiftUI/ContentView.swift
|
UTF-8
| 1,066
| 2.6875
| 3
|
[] |
no_license
|
//
// ContentView.swift
// HW1SwiftUI
//
// Created by Vitalii Dergunov on 28.02.2021.
//
import SwiftUI
struct ContentView: View {
@EnvironmentObject var router: Router
var body: some View {
TabView(selection: $router.selection) {
DashboardScreen()
.tabItem {
VStack {
Image(systemName: "star")
Text("Main")
}
}
.tag(0)
FoodScreen()
.tabItem {
VStack {
Image(systemName: "pills")
Text("Food")
}
}
.tag(1)
AboutScreen()
.tabItem {
VStack {
Image(systemName: "star")
Text("About")
}
}
.tag(2)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
5f7bd3cc4dc39ee34d2f3a44d03701683f794254
|
Swift
|
vladimird1988/PartyOrganizer
|
/Party Organizer/Party Organizer/MVVM/Model/Entities/Member.swift
|
UTF-8
| 4,457
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//
// Member.swift
// Party Organizer
//
// Created by Vladimir Dinic on 2/14/19.
// Copyright © 2019 Vladimir Dinic. All rights reserved.
//
import Foundation
import AERecord
import SwiftyJSON
/// Member entity
final class Member: NSObject {
// MARK: - Internal types
/// Properties keys used for parsing data from the server and for the CoreData querying
///
/// - id: Member id
/// - username: Member username (full name)
/// - cell: Member cell (phone number)
/// - email: Member email
/// - gender: Member gender
/// - photo: Member photo url
/// - aboutMe: Member 'about me'
private enum Key: String {
case id
case username
case cell
case email
case gender
case photo
case aboutMe
}
// MARK: - Instance properties
/// Member id
var id: Int64
/// Member username (full name)
var username: String = ""
/// Member cell (phone number)
var cell: String = ""
/// Member photo url
var photo: String = ""
/// Member email
var email: String = ""
/// Member gender
var gender: String = ""
/// Member 'about me'
var aboutMe: String = ""
/// Member parties
var parties = [Party]() {
didSet {
parties.forEach {
if !$0.partyMembers.value.contains(self) {
$0.partyMembers.accept($0.partyMembers.value + [self])
}
}
}
}
// MARK: - Constructors
/// Constructor which generates new instance using DBMember instance fetched from the CoreData
///
/// - Parameter dbMember: Member from the CoreData
init(dbMember: DBMember) {
id = dbMember.id
aboutMe = dbMember.aboutMe ?? ""
cell = dbMember.cell ?? ""
email = dbMember.email ?? ""
gender = dbMember.gender ?? ""
photo = dbMember.photo ?? ""
username = dbMember.username ?? ""
}
/// Constructor which generates new instance using data fetched from the server / backend
///
/// - Parameter data: Data fetched from the backend
init(data: [String: Any]) {
let json = JSON(data)
id = json[Key.id.rawValue].int64Value
super.init()
update(data: data)
}
// MARK: Instance methods
/// Helper method for updating instance properties with data / json pulled from the backend
///
/// - Parameter data: Data / json fetched from the server
private func update(data: [String: Any]) {
let json = JSON(data)
id = json[Key.id.rawValue].int64Value
aboutMe = json[Key.aboutMe.rawValue].stringValue
cell = json[Key.cell.rawValue].stringValue
email = json[Key.email.rawValue].stringValue
gender = json[Key.gender.rawValue].stringValue
username = json[Key.username.rawValue].stringValue
photo = json[Key.photo.rawValue].stringValue
}
// MARK: - Static methods
/// Static method for creating new Member instance or updating existing if there is a member with the same id
///
/// - Parameter data: Data / json fetched from the server
/// - Returns: Generated Member instance
static func createOrUpdate(data: [String: Any]) -> Member {
let json = JSON(data)
let id = json[Key.id.rawValue].int64Value
if let member = AppData.shared.members.value.first(where: { $0.id == id }) {
member.update(data: data)
return member
} else {
return Member(data: data)
}
}
/// Save Member instance in CoreData
///
/// - Returns: DBmember instane, i.e. object saved in CoreData
@discardableResult func save() -> DBMember {
let dbMember = DBMember.first(with: [Key.id.rawValue: id]) ?? DBMember.create()
dbMember.id = id
dbMember.aboutMe = aboutMe
dbMember.cell = cell
dbMember.email = email
dbMember.gender = gender
dbMember.photo = photo
dbMember.username = username
dbMember.parties?.forEach {
if let dbParty = $0 as? DBParty {
dbMember.removeFromParties(dbParty)
}
}
parties.forEach {
dbMember.addToParties($0.save())
}
CoreDataManager.shared.saveContext()
return dbMember
}
}
| true
|
88b723e24775c4102ab2d92e8434c58280230bb5
|
Swift
|
hoffsilva/bop
|
/Bop/Bop/Network/ServiceConnection.swift
|
UTF-8
| 1,228
| 2.96875
| 3
|
[] |
no_license
|
//
// ServiceConnection.swift
// Bop
//
// Created by Hoff Henry Pereira da Silva on 19/02/2018.
// Copyright © 2018 Hoff Henry Pereira da Silva. All rights reserved.
//
import Foundation
import Alamofire
import FCAlertView
typealias obj = (Alamofire.DataResponse<Any>) -> Swift.Void
class ServiceConnection {
static func fetchData(endPointURL: String, responseJSON: @escaping obj) {
if !verifyConnection() {
let alert = FCAlertView()
alert.showAlert(withTitle: "Error", withSubtitle: "The internet connection has some problem", withCustomImage: nil, withDoneButtonTitle: nil, andButtons: nil)
alert.dismissOnOutsideTouch = true
alert.hideDoneButton = true
alert.makeAlertTypeCaution()
}
Alamofire.request(endPointURL.trimmingCharacters(in: .whitespaces)).responseJSON { (response) in
responseJSON(response)
}
}
private static func verifyConnection() -> Bool{
if let reachabilityNetwork = Alamofire.NetworkReachabilityManager(host: "www.google.com") {
if reachabilityNetwork.isReachable {
return true
}
}
return false
}
}
| true
|
1bcc8f1bcd64e44f58a01a0249b71cf784f1f44d
|
Swift
|
Pircate/MoyaCache
|
/Example/MoyaCache/StoryAPI.swift
|
UTF-8
| 792
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// StoryAPI.swift
// MoyaCache_Example
//
// Created by Pircate(swifter.dev@gmail.com) on 2019/4/22
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Moya
import MoyaCache
import Storable
enum StoryAPI {
case latest
}
extension StoryAPI: TargetType {
var baseURL: URL {
return URL(string: "https://news-at.zhihu.com/api")!
}
var path: String {
return "4/news/latest"
}
var method: Moya.Method {
return .get
}
var sampleData: Data {
return "".data(using: .utf8)!
}
var task: Task {
return .requestPlain
}
var headers: [String : String]? {
return nil
}
}
extension StoryAPI: Cacheable {
var expiry: Expiry {
return .seconds(10)
}
}
| true
|
ffb5ae9d3d1aa0293b75126d4fbe32a41bf98cf1
|
Swift
|
maxmamis/simcoe
|
/Simcoe/Simcoe.swift
|
UTF-8
| 5,203
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
//
// Simcoe.swift
// Simcoe
//
// Created by Christopher Jones on 2/8/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
import CoreLocation
/// The root analytics engine.
public final class Simcoe {
/// The default analytics logging engine.
public static let engine = Simcoe(tracker: Tracker())
/// The analytics data tracker.
public let tracker: Tracker
var providers = [AnalyticsTracking]() {
didSet {
for provider in providers {
provider.start()
}
}
}
/**
Retrieves the provider based on its kind from the current list of providers.
- parameter _: The kind of provider to retrieve.
- returns: The provider if it is exists; otherwise nil.
*/
public static func provider<T: AnalyticsTracking>(ofKind _: T) -> T? {
return engine.providers.filter({ provider in return provider is T }).first as? T
}
/**
Begins running using the input providers.
- parameter providers: The providers to use for analytics tracking.
*/
public static func run(with providers: [AnalyticsTracking] = [AnalyticsTracking]()) {
var analyticsProviders = providers
if analyticsProviders.isEmpty {
analyticsProviders.append(EmptyProvider())
}
engine.providers = analyticsProviders
}
/**
Tracks a page view.
- parameter pageView: The page view event.
*/
public static func trackPageView(pageView: String, withAdditionalProperties properties: Properties? = nil) {
engine.trackPageView(pageView, withAdditionalProperties: properties)
}
/**
Tracks an analytics action or event.
- parameter event: The event that occurred.
- parameter properties: The event properties.
*/
public static func trackEvent(event: String, withAdditionalProperties properties: Properties? = nil) {
engine.trackEvent(event, withAdditionalProperties: properties)
}
/**
Tracks the lifetime value increase.
- parameter value: The value whose lifetime value is to be increased.
- parameter amount: The amount to increase that lifetime value for.
*/
public static func trackLifetimeIncrease(byAmount amount: Double = 1, forItem item: String? = nil,
withAdditionalProperties properties: Properties? = nil) {
engine.trackLifetimeIncrease(byAmount: amount, forItem: item, withAdditionalProperties: properties)
}
/**
Tracks a user's location.
- parameter location: The user's location.
*/
public static func trackLocation(location: CLLocation, withAdditionalProperties properties: Properties?) {
engine.trackLocation(location, withAdditionalProperties: properties)
}
init(tracker: Tracker) {
self.tracker = tracker
}
public func write<T>(toProviders providers: [T], description: String, action: T -> TrackingResult) {
let writeEvents = providers.map { provider -> WriteEvent in
let result = action(provider)
return WriteEvent(provider: provider as! AnalyticsTracking, trackingResult: result)
}
let event = Event(writeEvents: writeEvents, description: description)
tracker.track(event: event)
}
func trackPageView(pageView: String, withAdditionalProperties properties: Properties? = nil) {
let providers: [PageViewTracking] = findProviders()
write(toProviders: providers, description: "Page View: \(pageView)") { (provider: PageViewTracking) in
return provider.trackPageView(pageView, withAdditionalProperties: properties)
}
}
func trackEvent(event: String, withAdditionalProperties properties: Properties? = nil) {
let providers: [EventTracking] = findProviders()
let propertiesString = properties != nil ? "=> \(properties!.description)" : ""
write(toProviders: providers, description: "Event: \(event) \(propertiesString)") { eventTracker in
return eventTracker.trackEvent(event, withAdditionalProperties: properties)
}
}
func trackLifetimeIncrease(byAmount amount: Double = 1, forItem item: String? = nil,
withAdditionalProperties properties: Properties? = nil) {
let providers: [LifetimeValueIncreasing] = findProviders()
write(toProviders: providers, description: "Lifetime Value increased by \(amount) for \(item ?? "")") { lifeTimeValueIncreaser in
return lifeTimeValueIncreaser
.increaseLifetimeValue(byAmount: amount, forItem: item, withAdditionalProperties: properties)
}
}
func trackLocation(location: CLLocation, withAdditionalProperties properties: Properties?) {
let providers: [LocationTracking] = findProviders()
write(toProviders: providers, description: "User's Location") { locationTracker in
locationTracker.trackLocation(location, withAdditionalProperties: properties)
}
}
private func findProviders<T>() -> [T] {
return providers
.map({ provider in return provider as? T })
.flatMap({ $0 })
}
}
| true
|
077662dd0a37ce576e746cc74def18abe2af57ff
|
Swift
|
87kangsw/GitTime
|
/GitTime/Sources/Utils/Enum/FollowTypes.swift
|
UTF-8
| 413
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// FollowTypes.swift
// GitTime
//
// Created by Kanz on 04/06/2019.
// Copyright © 2019 KanzDevelop. All rights reserved.
//
import Foundation
enum FollowTypes: CaseIterable {
case followers
case following
var segmentTitle: String {
switch self {
case .followers:
return "Followers"
case .following:
return "Following"
}
}
}
| true
|
6b7e761bc4fe4280e2f1669924e6e3a51de79782
|
Swift
|
voronindim/OOD
|
/lab_6/ClassAdapter/ClassAdapter/libs/graphics_lib.swift
|
UTF-8
| 723
| 3.453125
| 3
|
[] |
no_license
|
//
// graphics_lib.swift
// Adapter
//
// Created by Dmitrii Voronin on 14.10.2020.
//
import Foundation
protocol Canvas {
func moveTo(x: Double, y: Double)
func lineTo(x: Double, y: Double)
func setColor(_ color: UInt32)
}
class CanvasImpl: Canvas {
let stream: Stream
init(stream: Stream) {
self.stream = stream
}
func moveTo(x: Double, y: Double) {
stream.write(string: "MoveTo (\(x), \(y))")
}
func lineTo(x: Double, y: Double) {
stream.write(string: "\tLineTo (\(x), \(y))")
}
func setColor(_ color: UInt32) {
let hex = String(color, radix: 16, uppercase: false)
stream.write(string: "SetColor #\(hex)")
}
}
| true
|
8427b1ddc4106ae9a82937c446b256057f67608c
|
Swift
|
AtanasX/WeatherForecast
|
/WeatherForecast/Models/Model.swift
|
UTF-8
| 460
| 3.171875
| 3
|
[] |
no_license
|
//
// Model.swift
// WeatherForecast
//
// Created by Atanas Nachkov on 31.10.20.
//
import Foundation
struct Place {
var name: String
var temperature: Double
var temperatureF: Double {
return (temperature * 5/9) + 32
}
init(name: String, temperature: Double) {
self.name = name
self.temperature = temperature
}
}
struct API: Codable {
var main: Info
}
struct Info: Codable {
var temp: Double
}
| true
|
3ed22e738b801781af3f7e161b23ba30a84165b5
|
Swift
|
sathvik-k/Hearth
|
/Heap.swift
|
UTF-8
| 2,179
| 3.84375
| 4
|
[
"MIT"
] |
permissive
|
//
// Heap.swift
// Hearth
//
// Created by Sathvik Koneru on 5/21/16.
// Copyright © 2016 Sathvik Koneru. All rights reserved.
//
import Foundation
import UIKit
//a heap is a specialized tree-based data structure that satisfies the heap property
//this heap structure returns the ones with the smallest priorities
//that is why I made my frequencies negative - so that when we pop the addresses
//with greatest "magnitude" are outputted
class PriorityQueue<T> {
//local variable to hold the data structure
var heap = Array<(Int, T)>()
//this method adds a value to the heap structure in the tree structure
func push(priority: Int, item: T) {
heap.append((priority, item))
if heap.count == 1 {
return
}
var current = heap.count - 1
while current > 0 {
let parent = (current - 1) >> 1
if heap[parent].0 <= heap[current].0 {
break
}
(heap[parent], heap[current]) = (heap[current], heap[parent])
current = parent
}
}
//this method "pops" and returns the value with lowest priority
func pop() -> (Int, T) {
(heap[0], heap[heap.count - 1]) = (heap[heap.count - 1], heap[0])
let pop = heap.removeLast()
heapify(0)
return pop
}
//this method "heapifies" or orders the heap variable
//into following the heap data structre
//every time you pop or push you will need to implement this to make sure the heap
//variable conforms
func heapify(index: Int) {
let left = index * 2 + 1
let right = index * 2 + 2
var smallest = index
if left < heap.count && heap[left].0 < heap[smallest].0 {
smallest = left
}
if right < heap.count && heap[right].0 < heap[smallest].0 {
smallest = right
}
if smallest != index {
(heap[index], heap[smallest]) = (heap[smallest], heap[index])
heapify(smallest)
}
}
//getting total entries
var count: Int {
get {
return heap.count
}
}
}
| true
|
11f098152ad765540d2fedd661821de827f93c52
|
Swift
|
ReinaldoV/SpotiSearch
|
/SpotiSearch/Modules/Search/Cells/SearchTypeCell.swift
|
UTF-8
| 1,679
| 2.8125
| 3
|
[] |
no_license
|
//
// SearchTypeCell.swift
// SpotiSearch
//
// Created by Reinaldo Villanueva Javierre on 8/2/21.
//
import UIKit
class SearchTypeCell: UICollectionViewCell {
enum CellType: String, CaseIterable {
case Top
case Tracks
case Artist
case Album
}
@IBOutlet weak var whiteBackgroundView: UIView!
@IBOutlet weak var typeLabel: UILabel!
func configureCell(type: CellType) {
self.typeLabel.text = type.rawValue
self.setUnnselected()
}
override var isSelected: Bool {
didSet {
if isSelected {
self.setSelected()
} else {
self.setUnnselected()
}
}
}
override func layoutSubviews() {
roundImageView()
}
private func roundImageView() {
whiteBackgroundView.layer.cornerRadius = 15
}
private func setSelected() {
let whiteColor = UIColor(red: 240 / 255, green: 240 / 255, blue: 240 / 255, alpha: 1)
let darkGreyColor = UIColor(red: 30 / 255, green: 30 / 255, blue: 30 / 255, alpha: 1)
self.whiteBackgroundView.backgroundColor = whiteColor
self.typeLabel.backgroundColor = whiteColor
self.typeLabel.textColor = darkGreyColor
}
private func setUnnselected() {
self.whiteBackgroundView.backgroundColor = UIColor.clear
self.whiteBackgroundView.layer.borderWidth = 1
let whiteColor = UIColor(red: 240 / 255, green: 240 / 255, blue: 240 / 255, alpha: 1)
self.whiteBackgroundView.layer.borderColor = whiteColor.cgColor
self.typeLabel.backgroundColor = UIColor.clear
self.typeLabel.textColor = whiteColor
}
}
| true
|
5d6972fc0e1aa3dec0993c25f459c3e112deaee2
|
Swift
|
milanhorvatovic/imobility-weather
|
/iMobility Weather/Model/Content/ModelContentWeather.swift
|
UTF-8
| 638
| 2.65625
| 3
|
[] |
no_license
|
//
// ModelContentWeather.swift
// iMobility Weather
//
// Created by worker on 18/12/2019.
// Copyright © 2019 Milan Horvatovic. All rights reserved.
//
import Foundation
extension Model.Content {
struct Weather: Identifiable {
let id: Int
let service: Model.Service.Weather?
}
}
extension Model.Content.Weather: Equatable { }
extension Model.Content.Weather {
init(id: Int) {
self.init(id: id,
service: nil)
}
init(with service: Model.Service.Weather) {
self.init(id: service.id,
service: service)
}
}
| true
|
a812a636e98624372e1369b8173d58a7d3f3fe53
|
Swift
|
PoojaBhatS/STVNews
|
/STV News/ViewControllers/STVTopStoriesTableViewController.swift
|
UTF-8
| 4,153
| 2.53125
| 3
|
[] |
no_license
|
//
// STVTopStoriesTableViewController.swift
// STV News
//
// Created by Pooja Harsha on 26/11/18.
// Copyright © 2018 Pooja. All rights reserved.
//
import UIKit
import Alamofire
class STVTopStoriesTableViewController: UITableViewController {
private var topStories = [TopStories]()
private var topStoriesDataSource = [STVTableRowViewData]()
private var storyContent : String = ""
private var storyImage : String = ""
// Activity indicator view
private var activityIndicator: STVActivityIndicator?
private let tblRefreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
loadTopStories()
addRefreshControl()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if topStoriesDataSource.count == 0 {
tableView.separatorStyle = .none
tableView.backgroundView?.isHidden = false
} else {
tableView.separatorStyle = .singleLine
tableView.backgroundView?.isHidden = true
}
return topStoriesDataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier:"STVTableViewCell", for: indexPath)
as! STVTableViewCell
let data = topStoriesDataSource[indexPath.row]
cell.viewData = data
cell.accessibilityIdentifier = "topStoriesTable.cell.\(indexPath.row)"
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! STVTableViewCell
let viewData = topStories[indexPath.row]
guard let newsStory = topStories.first(where: { $0.id == viewData.id }) else {
return
}
storyImage = cell.imageURL ?? ""
storyContent = newsStory.contentHTML ?? ""
performSegue(withIdentifier: "StoryDetailSegue", sender: self)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
let destinationVC = segue.destination as? STVStoryDetailViewController
// Pass the selected object to the new view controller.
destinationVC?.articleContent = storyContent
destinationVC?.articleImageURL = storyImage
}
}
extension STVTopStoriesTableViewController {
private func loadTopStories() {
// Initiate activity indicator view
activityIndicator = STVActivityIndicator.init(frame: self.view.frame)
self.view.addSubview(activityIndicator!)
activityIndicator?.startAnimating()
getTopStories()
}
private func addRefreshControl() {
tblRefreshControl.addTarget(self, action: #selector(refreshWeatherData(_:)), for: .valueChanged)
tableView.refreshControl = tblRefreshControl
}
@objc private func refreshWeatherData(_ sender: Any) {
// Fetch Weather Data
getTopStories()
self.tblRefreshControl.endRefreshing()
}
private func getTopStories() {
STVServiceManager.shared.fetchTopStoriesFromAPI { (topStoryArray) in
guard let stories = topStoryArray, !stories.isEmpty else {
//Set Tableview placeholder view
return;
}
self.topStories = stories
self.topStoriesDataSource = self.topStories.map({ (newsStory) -> STVTableRowViewData in
return STVTableRowViewData(id:newsStory.id, title: newsStory.title, description: newsStory.subHeadline, thumbnailImageID: newsStory.imageData?.id, publishDate:newsStory.publishDate)
})
self.tableView.reloadData()
self.activityIndicator?.stopAnimating()
self.activityIndicator?.removeFromSuperview()
}
}
}
| true
|
cbb8e3f54970ade3e609a6f7765a2e575f9270d6
|
Swift
|
1337mus/fakeJSONPlaceholderAPITest
|
/TabXP/ExploreTableViewSectionHeaderView.swift
|
UTF-8
| 2,412
| 2.609375
| 3
|
[] |
no_license
|
//
// ExploreTableViewSectionHeaderView.swift
// TabXP
//
// Created by Rajath Bhagavathi on 9/15/17.
// Copyright © 2017 HashMap. All rights reserved.
//
import UIKit
class ExploreTableViewSectionHeaderView: UITableViewHeaderFooterView {
let titleLabel = UILabel()
let actionButton = UIButton()
var viewModel: ExploreSectionViewModel = ExploreSectionViewModel(title: "Explore", actionText: "See All >") {
didSet {
didSetViewModel()
}
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
setupTitleLabel()
setupActionButton()
didSetViewModel()
}
private func setupTitleLabel() {
self.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 15).isActive = true
titleLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
titleLabel.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal)
titleLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal)
titleLabel.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightMedium)
titleLabel.textAlignment = .left
titleLabel.textColor = UIColor.darkGray
}
private func setupActionButton() {
self.addSubview(actionButton)
actionButton.translatesAutoresizingMaskIntoConstraints = false
actionButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
actionButton.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
actionButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightMedium)
actionButton.setTitle("See All >", for: .normal)
actionButton.setTitleColor(UIColor.lightGray, for: .normal)
}
private func didSetViewModel() {
titleLabel.text = viewModel.title
actionButton.setTitle(viewModel.actionText, for: .normal)
}
}
struct ExploreSectionViewModel {
let title: String
let actionText: String
}
| true
|
c9ab09338ad139e90b3d24a1db0b81deb4b1f3f0
|
Swift
|
sana/Swift
|
/DesignPatterns/DesignPatterns/Decorator.swift
|
UTF-8
| 1,122
| 3.8125
| 4
|
[] |
no_license
|
//
// Decorator.swift
// DesignPatterns
//
// Created by Laurentiu Dascalu on 12/22/15.
// Copyright © 2015 Laurentiu Dascalu. All rights reserved.
//
import Foundation
/**
Attach additional responsibilities to an object dynamically and transparently.
Decorators provide a flexible alternative to subclassing for extending
functionality.
*/
protocol Coffee {
func ingredients() -> [String]
}
class SimpleCoffee : Coffee {
func ingredients() -> [String] {
return ["coffee"]
}
}
class CoffeeDecorator : Coffee {
private let decoratedCoffee: Coffee
required init(decoratedCoffee: Coffee) {
self.decoratedCoffee = decoratedCoffee
}
func ingredients() -> [String] {
return decoratedCoffee.ingredients() + self.extraIngredients()
}
func extraIngredients() -> [String] {
return []
}
}
class MilkCoffee : CoffeeDecorator {
override func extraIngredients() -> [String] {
return ["milk"]
}
}
class IcedMocchaCoffee : CoffeeDecorator {
override func extraIngredients() -> [String] {
return ["milk", "ice", "caramel"]
}
}
| true
|
11a04aa637fec6eabff735c725f1655ef38e4485
|
Swift
|
jenalabidinoffice/Hajj-Travel-App
|
/Hajj Travel App/Sections/Map/Views/AnnotationView.swift
|
UTF-8
| 623
| 2.578125
| 3
|
[] |
no_license
|
//
// AnnotationView.swift
// Hajj Travel App
//
// Created by Abdulmoid Mohammed on 6/20/18.
// Copyright © 2018 Abdul-Moid. All rights reserved.
//
import UIKit
import MapKit
class AnnotationView: MKPointAnnotation {
init(user: User) {
super.init()
// Set the annotation title to user's full name
title = user.fullName
// Set the coordinates of the pin to user's location
coordinate = user.coordinates
}
init(name: String, coord: CLLocationCoordinate2D) {
super.init()
title = name
coordinate = coord
}
}
| true
|
ab59fd75b31fa11387804d2de93f4f2087d52ed9
|
Swift
|
arthurBricq/testYourself
|
/Algo/ClassToSave.swift
|
UTF-8
| 2,145
| 3.125
| 3
|
[] |
no_license
|
//
// ClassToSave.swift
// testYourself
//
// Created by Marin on 10/02/2018.
// Copyright © 2018 Arthur BRICQ. All rights reserved.
//
import Foundation
import UIKit
class OneScore: NSObject, NSCoding {
var name: String
var gender: String
var nameOfQuizz: String
var scores: [CGFloat]
init(name: String, gender: String, nameOfQuizz: String, scores: [CGFloat]) {
self.name = name
self.gender = gender
self.nameOfQuizz = nameOfQuizz
self.scores = scores
}
// Coding:
struct PropertyKeys {
static let name = "name"
static let gender = "gender"
static let nameOfQuizz = "nameOfQuizz"
static let scores = "scores"
}
required convenience init?(coder aDecoder: NSCoder) {
guard let name = aDecoder.decodeObject(forKey: PropertyKeys.name) as? String,
let gender = aDecoder.decodeObject(forKey: PropertyKeys.gender) as? String,
let nameOfQuizz = aDecoder.decodeObject(forKey: PropertyKeys.nameOfQuizz) as? String,
let scores = aDecoder.decodeObject(forKey: PropertyKeys.scores) as? [CGFloat] else { return nil }
self.init(name: name, gender: gender, nameOfQuizz: nameOfQuizz, scores: scores)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: PropertyKeys.name)
aCoder.encode(gender, forKey: PropertyKeys.gender)
aCoder.encode(nameOfQuizz, forKey: PropertyKeys.nameOfQuizz)
aCoder.encode(scores, forKey: PropertyKeys.scores)
}
}
var archiveURL: URL {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
return documentsURL.appendingPathComponent("FUCKIT4")
}
func saveToFile(toSave: [OneScore]) {
NSKeyedArchiver.archiveRootObject(toSave, toFile: archiveURL.path)
print("The array of score have been saved correctly.")
}
func loadFromFile() -> [OneScore] {
guard let toReturn = NSKeyedUnarchiver.unarchiveObject(withFile: archiveURL.path) as? [OneScore] else {
print("impossible to load files")
return []
}
return toReturn
}
| true
|
e98ffd25fe50f4b6d9370edf9d3c240e3a54ac0e
|
Swift
|
3DprintFIT/octoprint-ios-client
|
/OctoPhone/Utils/Reactive Extensions/CommonOperators.swift
|
UTF-8
| 1,068
| 2.609375
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
//
// CommonOperators.swift
// OctoPhone
//
// Created by Josef Dolezal on 23/03/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import ReactiveSwift
import Result
/// Add skipError operator for producers which may produce error
extension SignalProducerProtocol where Error == Error {
/// Add ability to skip errors produced by `self`
///
/// - Returns: Producer, which sends empty producer on error
func skipError() -> SignalProducer<Value, NoError> {
return flatMapError { _ in return SignalProducer<Self.Value, NoError>.empty }
}
}
extension SignalProducerProtocol {
/// Map each value of `self` to Void
///
/// - Returns: New producer, where original values are replaced by Void
func ignoreValues() -> SignalProducer<(), Self.Error> {
return map({ _ in })
}
}
extension SignalProtocol {
/// Map each value to Void
///
/// - Returns: New signal, where original values are replaced by Void
func ignoreValues() -> Signal<(), Self.Error> {
return map({ _ in return })
}
}
| true
|
3d6cb31e98eccaa14fb2f65ddbd5b3ff9c366662
|
Swift
|
cialvarez/eat-list
|
/EatList/Errors/RestaurantAPIError.swift
|
UTF-8
| 555
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// RestaurantAPIError.swift
// EatList
//
// Created by Christian Alvarez on 12/29/20.
//
import Foundation
enum RestaurantAPIError: Error {
case generalFailure
}
extension RestaurantAPIError: PresentableError {
var errorTitle: String {
switch self {
case .generalFailure: return R.string.localizable.errorRestaurantAPIGeneralFailureTitle()
}
}
var errorMessage: String {
switch self {
case .generalFailure: return R.string.localizable.errorRestaurantAPIGeneralFailureMessage()
}
}
}
| true
|
a8c82fad8a5e49d23247cb9d14424288a8f7be67
|
Swift
|
dawnhin/Walker
|
/Walker/MainTabViewController.swift
|
UTF-8
| 3,627
| 2.546875
| 3
|
[] |
no_license
|
//
// MainTabViewController.swift
// Walker
//
// Created by 黎铭轩 on 29/11/2020.
//
import UIKit
import HealthKit
class MainTabViewController: UITabBarController {
//MARK: - 初始化
init() {
super.init(nibName: nil, bundle: nil)
setUpTabViewController()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - 设置
func setUpTabViewController() {
let viewControllers = [
createWelcomeViewController(),
createWeeklyQuantitySampleTableViewController(),
createChartViewController(),
createWeeklyReportViewController()
]
self.viewControllers=viewControllers.map({
UINavigationController(rootViewController: $0)
})
delegate=self
selectedIndex=getLastViewedViewControllerIndex()
}
private func createWelcomeViewController() -> UIViewController{
let viewController=WelcomeViewController()
viewController.tabBarItem=UITabBarItem(title: "欢迎", image: UIImage(systemName: "circle"), selectedImage: UIImage(systemName: "circle.fill"))
return viewController
}
private func createWeeklyQuantitySampleTableViewController() -> UIViewController{
let dataTypeIdentifier=HKQuantityTypeIdentifier.stepCount.rawValue
let viewController=WeeklyQuantitySampleTableViewController(dataTypeIdentifier: dataTypeIdentifier)
viewController.tabBarItem=UITabBarItem(title: "健康数据", image: UIImage(systemName: "triangle"), selectedImage: UIImage(systemName: "triangle.fill"))
return viewController
}
private func createChartViewController() -> UIViewController{
let viewController=MobilityChartDataViewController()
viewController.tabBarItem=UITabBarItem(title: "图表", image: UIImage(systemName: "square"), selectedImage: UIImage(systemName: "square.fill"))
return viewController
}
private func createWeeklyReportViewController() -> UIViewController{
let viewController=WeeklyReportTableViewController()
viewController.tabBarItem=UITabBarItem(title: "周报", image: UIImage(systemName: "star"), selectedImage: UIImage(systemName: "star.fill"))
return viewController
}
//MARK: - 视图持续化
private static let lastViewControllerViewed="LastViewControllerViewed"
private func getLastViewedViewControllerIndex() -> Int{
if let index = UserDefaults.standard.object(forKey: MainTabViewController.lastViewControllerViewed) as? Int {
return index
}
return 0//默认是第一个视图控制器
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension MainTabViewController: UITabBarControllerDelegate{
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
guard let index = tabBar.items?.firstIndex(of: item) else { return }
setLastViewedViewControllerIndex(index)
}
private func setLastViewedViewControllerIndex(_ index: Int){
UserDefaults.standard.setValue(index, forKey: MainTabViewController.lastViewControllerViewed)
}
}
| true
|
0dba9fb84e6303c56ba33b6fa29911b656fcc683
|
Swift
|
igyvigy/IgyToast
|
/IgyToast/Private/ToastBuilder.swift
|
UTF-8
| 2,451
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
final class ToastBuilder {
var isShowing: Bool = false
var view: CKToastView?
var blurView: UIVisualEffectView
weak var vc: UIViewController?
class func make(on vc: UIViewController, view: UIView, header: UIView? = nil, footer: UIView? = nil, backgroundColor: UIColor) -> ToastBuilder {
let toast = ToastBuilder()
toast.vc = vc
toast.view = toast.makeView(view, header: header, footer: footer, backgroundColor: backgroundColor)
return toast
}
init() {
self.blurView = UIVisualEffectView(effect: nil)
self.blurView.isHidden = true
}
private func makeView(_ view: UIView, header: UIView? = nil, footer: UIView? = nil, backgroundColor: UIColor) -> CKToastView? {
guard let vc = vc else { return nil }
let toastView = CKToastView(frame: .zero)
toastView.translatesAutoresizingMaskIntoConstraints = false
vc.view.addSubview(toastView)
let leadingConstraint = toastView.leadingAnchor.constraint(equalTo: vc.view.safeAreaLayoutGuide.leadingAnchor)
let trailingConstraint = toastView.trailingAnchor.constraint(equalTo: vc.view.safeAreaLayoutGuide.trailingAnchor)
let bottomCnstraint = toastView.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor, constant: 1000)
NSLayoutConstraint.activate([bottomCnstraint, leadingConstraint, trailingConstraint])
let constraintSettings = ConstraintsSettings(left: 0, right: 0, top: 0, bottom: 0)
vc.view.addSubview(blurView, with: constraintSettings)
toastView.configure(view, blurView: blurView, bottomConstraint: bottomCnstraint, parentView: vc.view, title: nil, headerView: header, footerView: footer, backgroundColor: backgroundColor)
return toastView
}
func replaceView(_ view: UIView, header: UIView? = nil, backgroundColor: UIColor) {
self.view?.removeFromSuperview()
self.view = nil
self.view = makeView(view, header: header, backgroundColor: backgroundColor)
}
func show(grantFirstResponder: Bool = false) {
if isShowing { hide() } else { isShowing = true }
if let tv = self.view {
vc?.view.bringSubviewToFront(tv)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
if grantFirstResponder {
_ = self?.view?.becomeFirstResponder()
}
self?.view?.toggle(duration: 0.5)
}
}
func hide(_ completion: (() -> Void)? = nil) {
view?.toggle(duration: 0.25)
isShowing = false
}
}
| true
|
adeb6f39eacf363c7941e6e2ccced3fdabac9503
|
Swift
|
wblzu/eos-swift
|
/eosswift/eos-http-rpc/model/contract/request/AbiBinToJson.swift
|
UTF-8
| 308
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
import Foundation
public struct AbiBinToJson : Encodable {
public let code: String
public let action: String
public let binargs: String
public init(code: String, action: String, binargs: String) {
self.code = code
self.action = action
self.binargs = binargs
}
}
| true
|
d19faa554b9820a069061d1ca00b53dfff87f55a
|
Swift
|
algolia/instantsearch-ios
|
/Examples/Shared/View/CategoryTableViewCell+Facet.swift
|
UTF-8
| 794
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// CategoryTableViewCell+Facet.swift
// Examples
//
// Created by Vladislav Fitc on 13/12/2021.
//
import AlgoliaSearchClient
import Foundation
import UIKit
extension CategoryTableViewCell {
func setup(with facet: Facet) {
guard let textLabel = textLabel else { return }
if let rawHighlighted = facet.highlighted {
let highlightedValue = HighlightedString(string: rawHighlighted)
textLabel.attributedText = NSAttributedString(highlightedString: highlightedValue,
attributes: [
.font: UIFont.systemFont(ofSize: textLabel.font.pointSize, weight: .bold)
])
} else {
textLabel.text = facet.value
}
}
}
| true
|
4bb6da6fa64f4f90a99e29050046ac716851efa5
|
Swift
|
leshchinskaya/Notes
|
/Notes/NoteDetailViewController.swift
|
UTF-8
| 1,382
| 2.59375
| 3
|
[] |
no_license
|
//
// NoteDetailViewController.swift
// Notes
//
// Created by Marie on 07.10.17.
// Copyright © 2017 Mariya. All rights reserved.
//
import UIKit
class NoteDetailViewController: UIViewController {
//@IBOutlet weak var titleTextField: UITextField!
var note: Note!
@IBOutlet weak var contentTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
//navigationController?.navigationBar.prefersLargeTitles = false
// Add a background view to the table view
let backgroundImage = UIImage(named: "paper.jpg")
//let imageViewBackground = UIImageView(image: backgroundImage)
self.contentTextView.backgroundColor = UIColor(patternImage: backgroundImage!)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.prefersLargeTitles = false
//titleTextField.text = note.title
//contentTextField.text = note.content
contentTextView.text = note.content
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//note.title = titleTextField.text!
note.title = contentTextView.text!
//note.content = contentTextField.text!
note.content = contentTextView.text!
}
}
| true
|
8e5c0496c078ce9f22599e9cd24ae01d3f47478a
|
Swift
|
kritiagarwal13/Mcinley-RiceDemo
|
/Mckinley&RiceDemo/Controller/ViewController.swift
|
UTF-8
| 3,001
| 2.625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Mckinley&RiceDemo
//
// Created by Kriti Agarwal on 05/01/20.
// Copyright © 2020 Kriti Agarwal. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController, UITextFieldDelegate {
//MARK:- @IBOutlets
@IBOutlet weak var txtuserId: UITextField!
@IBOutlet weak var txtUserPassword: UITextField!
@IBOutlet weak var btnLogin: UIButton!
//MARK:- Variables
let leftIdView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 5.0, height: 2.0))
let leftPasswordView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 5.0, height: 2.0))
//MARK:- Life Cycle Methods
override func viewDidLoad() {
super.viewDidLoad()
addSubviews()
}
func addSubviews() {
txtuserId.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2).cgColor
txtUserPassword.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2).cgColor
txtuserId.layer.borderWidth = 2
txtUserPassword.layer.borderWidth = 2
txtuserId.leftView = leftIdView
txtuserId.leftViewMode = .always
txtUserPassword.leftView = leftPasswordView
txtUserPassword.leftViewMode = .always
btnLogin.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1).cgColor
btnLogin.layer.shadowOffset = CGSize(width: 0.0, height: 4.0)
btnLogin.layer.shadowOpacity = 1.0
btnLogin.layer.shadowRadius = 0.0
btnLogin.layer.masksToBounds = false
btnLogin.layer.cornerRadius = 4.0
}
//MARK:- @IBActions
@IBAction func didTapLoginBtn(_ sender: UIButton) {
let id = txtuserId.text ?? ""
let password = txtUserPassword.text ?? ""
login(id: id, password: password)
}
//MARK:- Login Request
func login(id: String, password: String) {
var parameters:Parameters = [String : Any]()
parameters["email"] = id
parameters["password"] = password
Alamofire.request(loginUrl, method: .post, parameters: parameters , encoding: JSONEncoding.default)
.responseJSON { (response) in
switch response.result {
case .success(let value):
let swiftyJson = JSON(value)
print ("return as JSON using swiftyJson is: \(swiftyJson)")
let responseValue = response.value as? [String: Any]
let token = responseValue?["id"]
let sb = UIStoryboard.init(name: "Main", bundle: nil)
let webVC = sb.instantiateViewController(withIdentifier: "WebViewController") as! WebViewController
webVC.urlStr = token as? String
self.navigationController?.pushViewController(webVC, animated: true)
print(value)
case .failure(let error):
print ("error: \(error)")
}
}
}
}
| true
|
cf6a1e1c9fd92f73a8c4a1317ae53556ff8e5533
|
Swift
|
RocketChat/Rocket.Chat.iOS
|
/Rocket.ChatTests/Controllers/MessagesViewModelSpec.swift
|
UTF-8
| 8,226
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// MessagesViewModelSpec.swift
// Rocket.ChatTests
//
// Created by Rafael Streit on 26/09/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
import XCTest
@testable import Rocket_Chat
final class MessagesViewModelSpec: XCTestCase {
func testInitialState() {
let model = MessagesViewModel()
XCTAssertEqual(model.data.count, 0)
XCTAssertTrue(model.requestingData == .none)
XCTAssertTrue(model.hasMoreData)
}
func testSectionCreationBasic() {
let model = MessagesViewModel()
guard
let testCaseMessage = Message.testInstance().validated()?.unmanaged,
let section = model.section(for: testCaseMessage)
else {
return XCTFail("section must be created")
}
if let object = section.base.object.base as? MessageSectionModel {
XCTAssertEqual(object.message.identifier, testCaseMessage.identifier)
XCTAssertFalse(object.isSequential)
XCTAssertFalse(object.containsDateSeparator)
XCTAssertFalse(object.containsUnreadMessageIndicator)
} else {
XCTFail("object must be a MessageSectionModel instance")
}
}
func testNumberOfSections() {
let model = MessagesViewModel()
if let testCaseMessage = Message.testInstance().validated()?.unmanaged, let section = model.section(for: testCaseMessage) {
model.data = [section]
}
XCTAssertEqual(model.numberOfSections, 1)
}
func testSequentialMessages() {
let model = MessagesViewModel()
guard
let messageFirst = Message.testInstance().validated()?.unmanaged,
var messageSecond = Message.testInstance().validated()?.unmanaged
else {
return XCTFail("messages must be created")
}
messageSecond.createdAt = Date().addingTimeInterval(-1)
if let section1 = model.section(for: messageFirst), let section2 = model.section(for: messageSecond) {
model.data = [section1, section2]
model.cacheDataSorted()
model.normalizeDataSorted()
}
XCTAssertEqual(model.numberOfSections, 2)
guard
let object1 = model.dataSorted[0].object.base as? MessageSectionModel,
let object2 = model.dataSorted[1].object.base as? MessageSectionModel
else {
return XCTFail("objects must be valid sections")
}
XCTAssertTrue(object1.isSequential)
XCTAssertFalse(object2.isSequential)
}
func testDateSeparatorMessages() {
let model = MessagesViewModel()
guard
let messageFirst = Message.testInstance().validated()?.unmanaged,
var messageSecond = Message.testInstance().validated()?.unmanaged
else {
return XCTFail("messages must be created")
}
messageSecond.createdAt = Date().addingTimeInterval(-100000)
if let section1 = model.section(for: messageFirst), let section2 = model.section(for: messageSecond) {
model.data = [section1, section2]
model.cacheDataSorted()
model.normalizeDataSorted()
}
XCTAssertEqual(model.numberOfSections, 2)
guard
let object1 = model.dataSorted[0].object.base as? MessageSectionModel,
let object2 = model.dataSorted[1].object.base as? MessageSectionModel
else {
return XCTFail("objects must be valid sections")
}
XCTAssertNotNil(object1.daySeparator)
XCTAssertNil(object2.daySeparator)
}
func testUnreadMarkerPresenceTrue() {
let model = MessagesViewModel()
let first = Message.testInstance()
first.identifier = "message-identifier-1"
let second = Message.testInstance()
second.identifier = "message-identifier-2"
guard
let messageFirst = first.validated()?.unmanaged,
var messageSecond = second.validated()?.unmanaged
else {
return XCTFail("messages must be created")
}
messageSecond.createdAt = Date().addingTimeInterval(-100000)
if let section1 = model.section(for: messageFirst), let section2 = model.section(for: messageSecond) {
model.lastSeen = Date().addingTimeInterval(-500)
model.data = [section1, section2]
model.cacheDataSorted()
model.markUnreadMarkerIfNeeded()
model.normalizeDataSorted()
}
XCTAssertEqual(model.numberOfSections, 2)
guard
let object1 = model.dataSorted[0].object.base as? MessageSectionModel,
let object2 = model.dataSorted[1].object.base as? MessageSectionModel
else {
return XCTFail("objects must be valid sections")
}
XCTAssertTrue(object1.containsUnreadMessageIndicator)
XCTAssertFalse(object2.containsUnreadMessageIndicator)
}
func testUnreadMarkerPresenceFalse() {
let model = MessagesViewModel()
guard
let messageFirst = Message.testInstance().validated()?.unmanaged,
var messageSecond = Message.testInstance().validated()?.unmanaged
else {
return XCTFail("messages must be created")
}
messageSecond.createdAt = Date().addingTimeInterval(-100000)
if let section1 = model.section(for: messageFirst), let section2 = model.section(for: messageSecond) {
model.lastSeen = Date().addingTimeInterval(500)
model.data = [section1, section2]
model.cacheDataSorted()
model.normalizeDataSorted()
}
XCTAssertEqual(model.numberOfSections, 2)
guard
let object1 = model.dataSorted[0].object.base as? MessageSectionModel,
let object2 = model.dataSorted[1].object.base as? MessageSectionModel
else {
return XCTFail("objects must be valid sections")
}
XCTAssertFalse(object1.containsUnreadMessageIndicator)
XCTAssertFalse(object2.containsUnreadMessageIndicator)
}
func testLoaderPresenceTrue() {
let model = MessagesViewModel()
guard
let messageFirst = Message.testInstance().validated()?.unmanaged,
let messageSecond = Message.testInstance().validated()?.unmanaged
else {
return XCTFail("messages must be created")
}
if let section1 = model.section(for: messageFirst), let section2 = model.section(for: messageSecond) {
model.data = [section1, section2]
model.cacheDataSorted()
model.normalizeDataSorted()
}
XCTAssertEqual(model.numberOfSections, 2)
guard
let object1 = model.dataSorted[0].object.base as? MessageSectionModel,
let object2 = model.dataSorted[1].object.base as? MessageSectionModel
else {
return XCTFail("objects must be valid sections")
}
XCTAssertFalse(object1.containsLoader)
XCTAssertTrue(object2.containsLoader)
}
func testLoaderPresenceFalse() {
let model = MessagesViewModel()
guard
let messageFirst = Message.testInstance().validated()?.unmanaged,
let messageSecond = Message.testInstance().validated()?.unmanaged
else {
return XCTFail("messages must be created")
}
if let section1 = model.section(for: messageFirst), let section2 = model.section(for: messageSecond) {
model.hasMoreData = false
model.requestingData = .none
model.data = [section1, section2]
model.cacheDataSorted()
model.normalizeDataSorted()
}
XCTAssertEqual(model.numberOfSections, 3)
guard
let object1 = model.dataSorted[0].object.base as? MessageSectionModel,
let object2 = model.dataSorted[1].object.base as? MessageSectionModel
else {
return XCTFail("objects must be valid sections")
}
XCTAssertFalse(object1.containsLoader)
XCTAssertFalse(object2.containsLoader)
}
}
| true
|
af52fa10a44821fbb5f368c3089b68fa09d03c00
|
Swift
|
neonio/datastructure101
|
/Swift/Algorithm/Algorithm/LeetCode/86Partition List.swift
|
UTF-8
| 1,515
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
//
// 86Partition List.swift
// Algorithm
//
// Created by amoyio on 2018/9/6.
// Copyright © 2018年 amoyio. All rights reserved.
//
import Foundation
class P86 {
class Solution {
func partition(_ head: ListNode?, _ x: Int) -> ListNode? {
let dummyNode = ListNode(-1)
dummyNode.next = head
var currentNode = dummyNode
let frontNodeDummy:ListNode = ListNode(-1)
var frontList: ListNode = frontNodeDummy
let tailNodeDummy: ListNode = ListNode(-1)
var tailList:ListNode = tailNodeDummy
while currentNode.next != nil {
guard let nextNodeVal = currentNode.next?.val else {
return nil
}
if nextNodeVal < x {
let nextFrontNode = ListNode(nextNodeVal)
frontList.next = nextFrontNode
frontList = frontList.next!
}else{
let nextTailNode = ListNode(nextNodeVal)
tailList.next = nextTailNode
tailList = tailList.next!
}
currentNode = currentNode.next!
}
var result: ListNode?
if frontNodeDummy.next != nil {
result = frontNodeDummy.next
frontList.next = tailNodeDummy.next
}else{
result = tailNodeDummy.next
}
return result
}
}
}
| true
|
2354f28f572d4235b858f5d97df8886e45683f4d
|
Swift
|
andrew-flipdish/NasaImageApp
|
/NasaImages/ViewModel/NasaResponseViewModel.swift
|
UTF-8
| 941
| 2.734375
| 3
|
[] |
no_license
|
//
// NasaResponseViewModel.swift
// NasaImages
//
// Created by Andrew Teeters on 25/06/2021.
//
import Foundation
class NasaResponseViewModel: ObservableObject {
@Published var results = [NasaResponse]()
private var format: DateFormatter = DateFormatter()
private var caller: ApiCaller = ApiCaller()
init(){
loadData()
}
private func getDate() -> String{
self.format.dateFormat = "yyyy-MM-dd"
let earlyDate = Calendar.current.date(
byAdding: .day,
value: -6,
to: Date())
let startDate = format.string(from: earlyDate!)
return startDate
}
func loadData(){
let startDate = getDate()
caller.getImagesForTheLastWeek(startDate: startDate) { response in
guard let response = response else {
return
}
self.results = response
}
}
}
| true
|
5233176dad73b56a15424e2cb40f4103bd0de728
|
Swift
|
mikeshep/CapitalSocial
|
/CapitalSocial/Sections/Map/PromotionsDetailViewController.swift
|
UTF-8
| 1,570
| 2.53125
| 3
|
[] |
no_license
|
//
// PromotionsDetailViewController.swift
// CapitalSocial
//
// Created by Miguel angel olmedo perez on 11/6/18.
// Copyright © 2018 Miguel angel olmedo perez. All rights reserved.
//
import UIKit
class PromotionsDetailViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var txtvDescription: UITextView!
var data:Promotion?
var promoImage:UIImage?
var promoTitle:String?
var promoImageName:String?
override func viewDidLoad() {
super.viewDidLoad()
//Navigation
self.navigationItem.title = CSString.appTitle
let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.action, target: self, action:#selector(share))
self.navigationItem.rightBarButtonItem = button
//title and image
promoTitle = data?.title ?? "Lorem ipsum"
promoImageName = data?.image ?? "placeHolder"
promoImage = UIImage(named: promoImageName!)
self.lblTitle.text = promoTitle
self.image.image = promoImage
}
//Share in social media
@objc func share(){
if let promoImage = promoImage {
let vc = UIActivityViewController(activityItems: [promoTitle!, promoImage], applicationActivities: [])
present(vc, animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
e76b47f57c3e122ddf9e0be2461faf7ab2d6daa2
|
Swift
|
vsricci/FractalIOS
|
/FractaIOS/BeersFavorites/ReuseIdentifier/FavoriteBeerResuseIdentifier.swift
|
UTF-8
| 522
| 2.546875
| 3
|
[] |
no_license
|
//
// FavoriteBeerResuseIdentifier.swift
// FractaIOS
//
// Created by Vinicius Ricci on 17/03/2018.
// Copyright © 2018 Vinicius Ricci. All rights reserved.
//
import UIKit
public protocol FavoriteBeerIdentifierProtocol: class {
//get identifier
static var defaultReuseIdentifier: String { get }
}
public extension FavoriteBeerIdentifierProtocol where Self: UIView {
static var defaultReuseIdentifier: String {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
}
| true
|
a455066587b08b5cea2b9808cf72523b08fcf977
|
Swift
|
pookjw/DateUI
|
/DateUI/ContentView.swift
|
UTF-8
| 705
| 2.921875
| 3
|
[] |
no_license
|
//
// ContentView.swift
// DateUI
//
// Created by Jinwoo Kim on 10/9/20.
//
import SwiftUI
struct ContentView: View {
@ObservedObject var viewModel: ContentViewModel = .init()
var body: some View {
VStack {
Text("\(viewModel.elapsed ?? 0)")
.font(.title)
.padding()
Button("Start") {
viewModel.start()
}
.padding()
Button("Get Elapsed") {
viewModel.getElapsed()
}
.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
29128950d3fddb880af7803999b8468978561d5f
|
Swift
|
ohlulu/FlickrDemo
|
/FlickrDemo/APIService/Decision/LogDecition.swift
|
UTF-8
| 2,064
| 2.9375
| 3
|
[] |
no_license
|
//
// LogDecition.swift
// NetworkDemo
//
// Created by Ohlulu on 2020/6/5.
// Copyright © 2020 ohlulu. All rights reserved.
//
import Foundation
public struct LogDecision: HTTPDecision {
var startTime: Date?
var endTime: Date?
fileprivate static let formatter = DateFormatter()
public func shouldApply<Req: HTTPRequest>(
request: Req,
data: Data,
response: HTTPURLResponse
) -> Bool {
true
}
public func apply<Req: HTTPRequest>(
request: Req,
data: Data,
response: HTTPURLResponse,
action: @escaping (DecisionAction<Req>) -> Void
) {
let costTime: TimeInterval
if let startTime = startTime, let endTime = endTime {
costTime = endTime.timeIntervalSince1970 - startTime.timeIntervalSince1970
} else {
costTime = 0
}
let log = """
----------------------------------------------------------------------
\(request.tag)
URL -> \(request.urlRequest?.url?.absoluteString ?? "nil")
request time -> \(startTime?.toString() ?? "nil")
cost time -> \(String(format: "%.3f", costTime)) s
headers -> \(request.urlRequest?.allHTTPHeaderFields ?? [:])
Request Body -> \(jsonString(data: request.urlRequest?.httpBody))
Response Body -> \(jsonString(data: data))
----------------------------------------------------------------------
"""
print(log)
action(.next(request, data, response))
}
private func jsonString(data: Data?) -> String {
guard let data = data,
let jsonData = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves),
let json = try? JSONSerialization.data(withJSONObject: jsonData, options: .prettyPrinted),
let string = String(data: json, encoding: .utf8) else {
return "nil"
}
return string.replacingOccurrences(of: "\\", with: "")
}
}
| true
|
745bee374b89377459b8e4c6fb45468e26692b03
|
Swift
|
pzyyll/TestAppV2
|
/TestApp/SelfInformation/SelfInformation/InsideMyInfo.swift
|
UTF-8
| 8,732
| 2.6875
| 3
|
[] |
no_license
|
//
// InsideMyInfo.swift
// SelfInformation
//
// Created by Gatsby on 15/12/17.
// Copyright © 2015年 Gatsby. All rights reserved.
//
import UIKit
import KeychainAccess
class InsideMyInfo: UIViewController, UITableViewDataSource, UITableViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var username = ""
var userpic = ""
var useremail = ""
var userphone = ""
var tableView : UITableView!
var uiphoto : UIImage!
var selected = 0;
let Dic = [
0:["","",""],
1:[""],
]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.title = "个人信息"
tableviewPrepare()
}
func tableviewPrepare(){//MARK:准备表视图
self.tableView = UITableView(frame: CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height),
style: UITableViewStyle.Grouped)//创建表视图
self.tableView.dataSource=self//数据源
self.tableView.delegate=self//委托
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "aCell")
self.view.addSubview(self.tableView)//加载表视图
}
/* 不用
func loadPicture(){
let newImage = UIImage(named: "\(self.userpic)")
let imageView = UIImageView(image:newImage);
imageView.frame=CGRectMake(30,100,200,200)
self.view.addSubview(imageView)
let name = UILabel()
name.frame=CGRectMake(30, 330, 200, 50)
name.text = self.username
name.font = UIFont.systemFontOfSize(60)
self.view.addSubview(name)
}
*/
func numberOfSectionsInTableView(tableView: UITableView) -> Int {//MARK:单元格分区数
return 2//视图中有两个分区
}
//MARK:单元格分区内部行数
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.Dic[section]!.count//每个分区的显示
}
//MARK:单元格表头高度
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
return 1//表头高度
}
//MARK:单元格选中配置
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
let secno = indexPath.section
if secno == 0{//在第一个分区
if indexPath.row == 0{//选中第一行的头像
let sheet = UIAlertController(title: "", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
sheet.addAction(UIAlertAction(title: "相册中选择", style: UIAlertActionStyle.Default, handler: {
(title:UIAlertAction) -> Void in
//print("select the \(title)")//MARK:搜索相册功能
//////MARK:read photo inside
//判断设置是否支持图片库
if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
//初始化图片控制器
let picker = UIImagePickerController()
//设置代理
picker.delegate = self
//指定图片控制器类型
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
//设置是否允许编辑
picker.allowsEditing = true
//弹出控制器,显示界面
self.presentViewController(picker, animated: true, completion: {
() -> Void in
})
}else{
print("读取相册错误")
}
//////end photo inside
}))
sheet.addAction(UIAlertAction(title: "拍照", style: UIAlertActionStyle.Default, handler: { (title:UIAlertAction) -> Void in
//print("select the \(title)");//MARK:使用相机功能
if UIImagePickerController.isSourceTypeAvailable(.Camera){
//创建图片控制器
let picker = UIImagePickerController()
//设置代理
picker.delegate = self//和相册一样相同委托
//设置来源
picker.sourceType = UIImagePickerControllerSourceType.Camera
//允许编辑
picker.allowsEditing = true
//打开相机
self.presentViewController(picker, animated: true, completion: { () -> Void in
})
}else{
let alert = UIAlertController(title: "找不到相机", message: "", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "好的", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion:nil)
print("找不到相机")
}
}))
let btdown = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
sheet.addAction(btdown)
self.presentViewController(sheet, animated: true, completion: nil)
}
if indexPath.row == 1{//选中第2行的手机
//MARK:待添加绑定手机功能
}
if indexPath.row == 2{//选中地3行的email
//MARK:待添加绑定email功能
}
}//end secno 0
else if secno == 1{//剩下的分区 //MARK:待添加注销功能
//注销用户返回登陆界面
let keychain = Keychain(service: identifier_Keychain, accessGroup: "ik1")
keychain["user"] = nil
keychain["pwd"] = nil
UIApplication.sharedApplication().keyWindow?.rootViewController = TSUINavigationController(rootViewController: LoginViewController())
}
}//end didSelectRowAtIndexPath
//MARK:单元格内部配置
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let secno = indexPath.section //分区号
if secno == 0{
if indexPath.row == 0{
let cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Selfpic")
//cell.textLabel?.text = self.username
cell.detailTextLabel?.text = self.username//用户名在右边
if selected == 0{
cell.imageView!.image = UIImage(named: "\(self.userpic)")
}
else {
cell.imageView!.image = uiphoto
//MARK:更新头像后将打包为json通知服务器用户头像更新,待添加json功能
}
return cell
}
else if indexPath.row == 1{//当在第一个分区
let cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "BindPhone")
cell.textLabel?.text = "绑定手机"
cell.detailTextLabel?.text = self.userphone//数据来自json
return cell
}else{
let cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "BindEmail")
cell.textLabel?.text = "绑定邮箱"
cell.detailTextLabel?.text = self.useremail//来自json
return cell
}
}//end secno 0
else{//其它分区
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "logout")
cell.textLabel?.text = "退出当前登陆"
cell.textLabel?.textColor = UIColor.redColor()//设置字体颜色
cell.textLabel?.textAlignment = NSTextAlignment.Center//字体居中显示
return cell
}
}//end cellForRowAtIndexPath func
//MARK:after select photo
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
print("selected\(info)")
let image = info[UIImagePickerControllerEditedImage] as! UIImage//取得裁剪后的图片
self.uiphoto = image
self.selected = 1
self.tableView.reloadData()
picker.dismissViewControllerAnimated(true, completion:nil)
}
}
| true
|
6e9a46fef3f60288a93416b360a80bee300bba3f
|
Swift
|
victorlsn/iUSDK-iOS
|
/iUSDK/Classes/FormatUtil.swift
|
UTF-8
| 3,886
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
//
// FormatUtil.swift
// iUSDK iOS
//
// Created by Victor Negrao on 18/01/19.
// Copyright © 2019 ZIG. All rights reserved.
//
import Foundation
class FormatUtil {
/**
Este método converte uma string de telefone com 8-14 dígitos para o formato (XX) YYYYY-YYYY
- Parameter phoneNumber: String contendo o número de telefone em formato fora de padrão
- Returns: String contendo o número de telefone devidamente formatado
*/
internal static func getValidPhoneNumber(_ phoneNumber: String, _ userAreaCode: String) -> String {
var validPhoneNumber = FormatUtil.stripNonNumericDigitsFromString(phoneNumber)
let startingIndex = validPhoneNumber.startIndex
switch validPhoneNumber.count {
case 14:
validPhoneNumber = validPhoneNumber.substring(from: validPhoneNumber.index(startingIndex, offsetBy: 3))
if validPhoneNumber[validPhoneNumber.index(startingIndex, offsetBy: 2)] != "9" {
validPhoneNumber = ""
}
break
case 13:
validPhoneNumber = validPhoneNumber.substring(from: validPhoneNumber.index(startingIndex, offsetBy: 2))
if validPhoneNumber[validPhoneNumber.index(startingIndex, offsetBy: 2)] != "9" {
validPhoneNumber = ""
}
break
case 12:
validPhoneNumber = validPhoneNumber.substring(from: validPhoneNumber.index(startingIndex, offsetBy: 1))
if validPhoneNumber[validPhoneNumber.index(startingIndex, offsetBy: 2)] != "9" {
validPhoneNumber = ""
}
break
case 11:
if validPhoneNumber[validPhoneNumber.index(startingIndex, offsetBy: 2)] != "9" {
validPhoneNumber = ""
}
break
case 10:
let areaCode = validPhoneNumber.substring(to: validPhoneNumber.index(startingIndex, offsetBy: 2))
validPhoneNumber = validPhoneNumber.substring(from: validPhoneNumber.index(startingIndex, offsetBy: 2))
let firstDigit = validPhoneNumber.substring(to: validPhoneNumber.index(startingIndex, offsetBy: 1))
switch firstDigit {
case "5", "6", "7", "8", "9":
validPhoneNumber = areaCode+"9"+validPhoneNumber
break
default:
validPhoneNumber = ""
break
}
case 9:
validPhoneNumber = userAreaCode + validPhoneNumber
break
case 8:
let firstDigit = validPhoneNumber.substring(to: validPhoneNumber.index(startingIndex, offsetBy: 1))
switch firstDigit {
case "5", "6", "7", "8", "9":
validPhoneNumber = userAreaCode+"9"+validPhoneNumber
break
default:
validPhoneNumber = ""
break
}
break
default:
validPhoneNumber = ""
break
}
return validPhoneNumber
}
/**
Este método limpa (remove todo caractere não numérico) de uma String de CPF
- Parameter originalString: String original, contendo quaisquer sinais de pontuação
- Returns: String contendo apenas dígitos numéricos
*/
internal static func stripNonNumericDigitsFromString(_ originalString: String) -> String {
let charactersToKeep = NSMutableCharacterSet()
charactersToKeep.addCharacters(in: "1234567890")
let result = originalString.filter { return String($0).rangeOfCharacter(from: charactersToKeep as CharacterSet) != nil }
return String(result)
}
}
| true
|
5e11e18e3a21c23a7a02e80606c1f465ed1896bf
|
Swift
|
vojtasrb/golemchanger
|
/BackpackConfigurator/ViewController.swift
|
UTF-8
| 5,841
| 2.671875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// BackpackConfigurator
//
// Created by Vojtěch Srb on 19/02/2019.
// Copyright © 2019 Vojtěch Srb. All rights reserved.
//
import UIKit
import KeychainAccess
var items = ["1", "2", "3", "4", "5", "6", "7", "8" ,"9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28"]
let keychain = Keychain(service: "com.divrlabs.BackpackConfigurator-token")
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var backpackCellView: UICollectionView!
@IBOutlet weak var GolemButton: UIButton!
@IBOutlet weak var ArachnoidButton: UIButton!
let reuseIdentifier = "cell"
var selectedBackpacks:[Int?] = []
var selectedBackpacksNumbers:[String?] = []
var oldColor = UIColor.red
var backpackIndexPaths:[IndexPath] = []
private let margin: CGFloat = 20.0
// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
collectionView.allowsMultipleSelection = true
return items.count
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.myLabel.text = items[indexPath.item]
// make cell more visible in our example project
cell.backgroundColor = UIColor.lightGray
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8
return cell
}
// get indexPath for selected Backpacks
var selectedBackpackIndexPath: IndexPath? {
didSet {
var indexPaths: [IndexPath] = []
if let selectedBackpackIndexPath = selectedBackpackIndexPath {
indexPaths.append(selectedBackpackIndexPath)
print(selectedBackpackIndexPath.item)
}
}
}
// MARK: - UICollectionViewDelegate protocol
// change color when selected
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
// alert if selected is offline
let cell = collectionView.cellForItem(at: indexPath)
if cell?.backgroundColor == UIColor.lightGray {
showAlert(message: "Backpack Offline")
backpackCellView.deselectItem(at: indexPath, animated: true)
}
else {
cell?.backgroundColor = UIColor.orange
selectedBackpackIndexPath = indexPath
backpackIndexPaths.append(indexPath)
selectedBackpacks.append(selectedBackpackIndexPath?.item)
print(selectedBackpacks)
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
// handle tap events
print("You deselected cell #\(indexPath.item)!")
selectedBackpacks.removeAll {$0 == indexPath.item}
print(selectedBackpacks)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Requests().loginRequest() { output in
do { keychain["golem"] = output
}
}
_ = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) {
timer in
DispatchQueue.global(qos: .background).async {
Network().pingBackpacks(timer: timer, collectionView: self.backpackCellView)
}
}
}
// MARK: - Button Handlers
// change game to golem
@IBAction func changeToGolem(_ sender: Any) {
guard selectedBackpacks.count > 0 else {
showAlert(message: "No Backpack Selected")
return
}
let token = try? keychain.getString("golem")
print(token ?? "token")
// change game via POST request
for i in 0...selectedBackpacks.count - 1
{
Requests().changeGameRequest(id: items[selectedBackpacks[i]!], whatGame: #""golem""#, token: token!)
print(items[selectedBackpacks[i]!])
}
// deselect backpack
backpackCellView.selectItem(at: nil, animated: true, scrollPosition: [])
// remove from selection
selectedBackpacks.removeAll()
backpackIndexPaths.removeAll()
}
// change game to arachnoid
@IBAction func changeToArachnoid(_ sender: Any) {
guard selectedBackpacks.count > 0 else {
showAlert(message: "No Backpack Selected")
return
}
let token = try? keychain.getString("golem")
print(token ?? "token")
// change game via POST request
for i in 0...selectedBackpacks.count - 1
{
Requests().changeGameRequest(id: items[selectedBackpacks[i]!], whatGame: #""arachnoid""#, token: token!)
print(items[selectedBackpacks[i]!])
}
// deselect backpack
backpackCellView.selectItem(at: nil, animated: true, scrollPosition: [])
// remove from selection
selectedBackpacks.removeAll()
backpackIndexPaths.removeAll()
}
}
| true
|
56b5acef3c3bf3767581929c158d5c63da881d43
|
Swift
|
hoshi005/AuthSample
|
/AuthSample/Classes/SignUp/CreateUserView.swift
|
UTF-8
| 1,893
| 2.765625
| 3
|
[] |
no_license
|
//
// CreateUserView.swift
// AuthSample
//
// Created by Susumu Hoshikawa on 2019/11/02.
// Copyright © 2019 SH Lab, Inc. All rights reserved.
//
import SwiftUI
struct CreateUserView: View {
@ObservedObject(initialValue: CreateUserViewModel()) var viewModel
@Environment(\.presentationMode) var presentationMode
var body: some View {
NavigationView {
VStack {
TextField("your Email Address.", text: $viewModel.email)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.emailAddress)
.border(Color.gray, width: 2)
SecureField("password.", text: $viewModel.password)
.textFieldStyle(RoundedBorderTextFieldStyle())
.border(Color.gray, width: 2)
SecureField("confirm password.", text: $viewModel.confirmPassword)
.textFieldStyle(RoundedBorderTextFieldStyle())
.border(Color.gray, width: 2)
Button(action: {
self.viewModel.createUser {
self.presentationMode.wrappedValue.dismiss()
}
}) {
HStack {
Image(systemName: "person.badge.plus.fill")
.imageScale(.large)
Text("アカウントを作成する")
}
}
.disabled(!viewModel.validInput)
.padding()
Spacer()
}
.padding()
.navigationBarTitle(.init("サインアップ"))
}
}
}
struct CreateUserView_Previews: PreviewProvider {
static var previews: some View {
CreateUserView()
}
}
| true
|
e296e759ee2cc6feaf2b1e6fb07e321d280dcba5
|
Swift
|
Hikaru-Kuroda/RxSwiftWarmingup
|
/Warmingup/ViewController.swift
|
UTF-8
| 3,043
| 2.671875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Warmingup
//
// Created by 黑田光 on 2020/08/22.
// Copyright © 2020 Hikaru Kuroda. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
@IBOutlet weak var greetingLabel: UILabel!
@IBOutlet weak var stateSegmentedControl: UISegmentedControl!
@IBOutlet weak var freeTextField: UITextField!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet var greetingButton: [UIButton]!
let disposeBag = DisposeBag()
let lastSelectedGreeting: BehaviorRelay<String> = BehaviorRelay<String>(value: "こんにちは")
enum State: Int {
case useButtons
case useTextField
}
override func viewDidLoad() {
super.viewDidLoad()
let nameObservable: Observable<String?> = nameTextField.rx.text.asObservable()
let freeObservable: Observable<String?> = freeTextField.rx.text.asObservable()
let freewordWithNameObservable: Observable<String?> = Observable.combineLatest(nameObservable, freeObservable) {
(string1: String?, string2: String?) in
return string1! + string2!
}
freewordWithNameObservable.bind(to: greetingLabel.rx.text).disposed(by: disposeBag)
let segmentControlObservable: Observable<Int> = stateSegmentedControl.rx.value.asObservable()
let stateObservable: Observable<State> = segmentControlObservable.map { (selectedIndex: Int) -> State in
return State(rawValue: selectedIndex)!
}
let greetingTextFieldEnabledObservable: Observable<Bool> = stateObservable.map { (state: State) -> Bool in
return state == .useTextField
}
greetingTextFieldEnabledObservable.bind(to: freeTextField.rx.isEnabled).disposed(by: disposeBag)
let buttonsEnabledObservable: Observable<Bool> = greetingTextFieldEnabledObservable.map { (greetingEnabled: Bool) -> Bool in
return !greetingEnabled
}
greetingButton.forEach { (button) in
buttonsEnabledObservable.bind(to: button.rx.isEnabled).disposed(by: disposeBag)
button.rx.tap.subscribe(onNext: {(nothing: Void) in
self.lastSelectedGreeting.accept(button.currentTitle!)
}).disposed(by: disposeBag)
}
let predefinedGreetingObservable: Observable<String> = lastSelectedGreeting.asObservable()
let finalGreetingObservable: Observable<String> = Observable.combineLatest(stateObservable, freeObservable, predefinedGreetingObservable, nameObservable) { (state: State, freeword: String?, predefinedGreeting: String, name: String?) -> String in
switch state {
case .useTextField: return freeword! + name!
case .useButtons: return predefinedGreeting + name!
}
}
finalGreetingObservable.bind(to: greetingLabel.rx.text).disposed(by: disposeBag)
}
}
| true
|
ce63137811d726d70516c85c68e60984e7e1ada1
|
Swift
|
AditiSrivastava20/fingerprint-passwordLOCK
|
/FingerPrintUnlock/CommonFunctions.swift
|
UTF-8
| 1,089
| 2.78125
| 3
|
[] |
no_license
|
//
// CommonFunctions.swift
// Task16March
//
// Created by Sierra 4 on 17/03/17.
// Copyright © 2017 Sierra 4. All rights reserved.
import Foundation
import UIKit
func alertbox(_Message:String,obj:UIViewController)
{
let alertmsg=UIAlertController(title: Identifier.Alert.identifier, message: _Message, preferredStyle: UIAlertControllerStyle.alert)
let OkAction=UIAlertAction(title: Identifier.ok.identifier, style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in
})
alertmsg.addAction(OkAction)
obj.present(alertmsg,animated:true,completion: nil)
}
extension UIView{
func rotateImage(_ duration: CFTimeInterval = 1.0, completionDelegate: CAAnimationDelegate? = nil) {
let rotateAnimation = CABasicAnimation(keyPath:Identifier.rotation.identifier)
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI * 1.0)
rotateAnimation.duration = duration
if let delegate: CAAnimationDelegate = completionDelegate {
rotateAnimation.delegate = delegate
}
self.layer.add(rotateAnimation, forKey: nil)
}
}
| true
|
73887b5daea57f1a40fb14fb00a3ba14ca16d8e9
|
Swift
|
x401om/Just
|
/MyPlayground.playground/Contents.swift
|
UTF-8
| 440
| 2.78125
| 3
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
import WebKit
let fileUrl = URL(fileURLWithPath: "file:///Users/agoncharov/Documents/post.html")
let str = "<article><p>some backslashed symbols</p></article>"
let s = str as NSString
print(str)
let webView = UIWebView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
let request = URLRequest(url: URL(string: "https://yandex.ru")!)
webView.loadRequest(request)
| true
|
74c9fd93c05767b3fc589e1ee91e644c1e71b5f3
|
Swift
|
thanhdonghuiit/Goposse
|
/MedlyDemo/MedlyDemo/Helpers/NetworkHelper.swift
|
UTF-8
| 2,387
| 2.78125
| 3
|
[] |
no_license
|
//
// NetworkHelper.swift
// lindenwood
//
// Created by Kevin Gray on 1/7/16.
// Copyright © 2016 Lindenwood. All rights reserved.
//
import Foundation
typealias NetworkHelperCallback = (_ result: NetworkResult) -> Void
class NetworkHelper {
// MARK: - Variables
private (set) var httpClient: HttpClient!
// MARK: - Initialization
init() {
let clientConfiguration: HttpClientConfiguration = HttpClientConfiguration()
httpClient = HttpClient(configuration: clientConfiguration)
setupCallProtocols(httpClient)
}
init(httpClient: HttpClient) {
self.httpClient = httpClient
}
// MARK: - Standard network configuration
func setupCallProtocols(_ httpClient: HttpClient) {
}
class func getBaseUrl() -> String? {
return nil
}
// MARK: - Call execution
/** Calls Haitch's HttpClient function:
`execute(request request: Request, responseKind: Response.Type?, callback: HttpClientCallback?) -> NSURLSessionDataTask?`
*/
func execute(request: Request, callback: NetworkHelperCallback?) -> URLSessionDataTask? {
return httpClient.execute(request: request, responseKind: NetworkResponse.self)
{ httpClientCallback -> Void in
let response = httpClientCallback.0
let error = httpClientCallback.1
let result: NetworkResult = NetworkResult()
result.executeError = error as NSError?
let networkResponse: NetworkResponse? = response as? NetworkResponse
if networkResponse != nil {
if result.executeError == nil {
result.statusCode = networkResponse!.statusCode
result.executeError = networkResponse!.internalError
}
result.apiResponse = networkResponse!.apiResponse
}
if callback != nil {
callback!(result)
}
}
}
// MARK: - URL helpers
class func urlString(path: String) -> String {
return urlString(path: path, params: nil)
}
class func urlString(path: String, params: RequestParams?) -> String {
var baseUrl: String = ""
if let configBaseUrl: String = getBaseUrl() {
baseUrl = configBaseUrl
if let convUrl: URL = URL(string: path, relativeTo: URL(string: baseUrl)) {
baseUrl = convUrl.absoluteString
}
return NetHelper.urlWithParams(baseUrl, params: params)
} else {
return path
}
}
}
| true
|
5c43c4ec7b4de299ecaf563259e9186e7a3183f1
|
Swift
|
uncleflower/jusaitang-ios
|
/jusaitang/library/ImagePicker/view/ImageCell.swift
|
UTF-8
| 2,473
| 2.515625
| 3
|
[] |
no_license
|
//
// ImageCell.swift
// an-xin-bang
//
// Created by Jiehao Zhang on 2020/7/25.
// Copyright © 2020 IdeThink Inc. All rights reserved.
//
import UIKit
import SnapKit
import RxSwift
import RxCocoa
class ImageCell: UICollectionViewCell {
var viewModel: ImageVM!
private let disposeBag = DisposeBag()
let imageView: UIImageView = {
let view = UIImageView()
view.contentMode = .scaleAspectFill
view.clipsToBounds = true
view.isUserInteractionEnabled = false
return view
}()
let selectImg: UIImageView = {
let view = UIImageView()
view.image = UIImage(named: "unselected_img")
view.isUserInteractionEnabled = false
return view
}()
let surfaceView: UIView = {
let view = UIView()
view.backgroundColor = .black
view.isUserInteractionEnabled = false
view.alpha = 0
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageView)
contentView.addSubview(selectImg)
contentView.addSubview(surfaceView)
makeConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func makeConstraints() {
imageView.snp.makeConstraints { (make) in
make.leading.equalToSuperview()
make.trailing.equalToSuperview()
make.top.equalToSuperview()
make.bottom.equalToSuperview()
}
selectImg.snp.makeConstraints { (make) in
make.trailing.equalToSuperview().offset(-10)
make.top.equalToSuperview().offset(10)
make.width.equalTo(16)
make.height.equalTo(16)
}
surfaceView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
func bindViewModel(viewModel: ImageVM) {
self.viewModel = viewModel
imageView.load(asset: viewModel.model.asset, size:self.imageView.frame.size)
viewModel.isSelectObservable.subscribe(onNext: {[weak self] (isSelected) in
// self?.selectImg.isHighlighted = isSelected
self?.selectImg.image = isSelected ? UIImage(named: "selected_img") : UIImage(named: "unselected_img")
self?.surfaceView.alpha = isSelected ? 0.3 : 0
}).disposed(by: disposeBag)
}
}
| true
|
89f5a039718ea6926eab0dc36f135a6207889f24
|
Swift
|
dambert/DambertIntercorp
|
/DambertIntercorp/User Interfaces/ViewController/PhoneNumberViewController.swift
|
UTF-8
| 2,725
| 2.5625
| 3
|
[] |
no_license
|
//
// PhoneNumberViewController.swift
// DambertIntercorp
//
// Created by Dambert.Munoz on 3/26/19.
// Copyright © 2019 dambert.intercorp.retail. All rights reserved.
//
import UIKit
import FirebaseAuth
class PhoneNumberViewController: UIViewController {
// MARK: Properties
@IBOutlet var phoneTextField: UITextField!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Constants.Segue.PHONE_TO_VERIFY {
let destinationVC = segue.destination as! PhoneNumberVerifyViewController
destinationVC.verificationID = (sender as? String)
}
}
// MARK: Login Phone Number
@IBAction func tapVerifyPhoneNumber(_ sender: Any) {
if(self.phoneTextField.text?.isEmpty == true){
Helper.showAlert(message: Constants.MessagesVC.PHONE_NUMBER_REQUIRED , viewController: self)
return
}else if( (self.phoneTextField.text?.count ?? 0) < 9){
Helper.showAlert(message: Constants.MessagesVC.PHONE_NUMBER_VALIDATION_LONGITUD , viewController: self)
return
}
Helper.showLoading(viewController: self)
// Defino Language Code spanish.
Auth.auth().languageCode = "es";
// Número concatenado
let number = "+51"+self.phoneTextField.text!
PhoneAuthProvider.provider().verifyPhoneNumber(number, uiDelegate: nil) { (verificationID, error) in
Helper.hideLoading(viewController: self)
if error != nil{
Helper.showAlert(message: Constants.MessagesVC.PHONE_NUMBER_VALIDATION_ERROR , viewController: self)
return
}else{
self.performSegue(withIdentifier: Constants.Segue.PHONE_TO_VERIFY, sender: verificationID)
}
}
}
}
extension PhoneNumberViewController: UITextFieldDelegate{
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count < 10
}
}
| true
|
f1e3825e398c7a2dac14858181393161d3a24719
|
Swift
|
isuru2175/Cafe-Manager
|
/Cafe-Manager/Model/Category.swift
|
UTF-8
| 433
| 2.734375
| 3
|
[] |
no_license
|
//
// Category.swift
// Cafe-Manager
//
// Created by isuru on 4/18/21.
// Copyright © 2021 isuru. All rights reserved.
//
import Foundation
class Category {
var category : String
var id : String
var isDelete : String
init(category : String,id : String,isDelete : String) {
self.category = category
self.id = id
self.isDelete = isDelete
}
}
| true
|
5acb301d3528addf3cf35eecaf10e40fb86f44df
|
Swift
|
ifobos/SOLID-Examples
|
/3 - LSP/E2/LSP p2.playground/Contents.swift
|
UTF-8
| 397
| 3.609375
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
func duplicateArea(of rectangle: Rectangle) {
print("Old area: \(rectangle.area)")
rectangle.duplicateArea()
print("New area: \(rectangle.area)")
}
let rectangle = Rectangle()
rectangle.length = 5
rectangle.width = 2
duplicateArea(of: rectangle)
let square = Square()
square.width = 2
duplicateArea(of: square)
| true
|
5be1902e26e93b6882876bb2efe3497a2147b9ed
|
Swift
|
marvinlab/quelp-app
|
/quelp-app/Screens/Reviews/ReviewCellViewModel.swift
|
UTF-8
| 1,167
| 2.921875
| 3
|
[] |
no_license
|
//
// ReviewCellModel.swift
// quelp-app
//
// Created by Marvin Labrador on 4/4/21.
//
import Foundation
class ReviewCellModel {
let userImageUrl: String
let userReviewText: String
let reviewTimeStamp: String
let rating: String
init(review: ReviewModel) {
userImageUrl = review.user?.imageUrl ?? ""
userReviewText = review.text ?? ""
reviewTimeStamp = ReviewCellModel.dateTimeChangeFormat(str: review.timeStamp ?? "", inDateFormat: "yyyy-MM-dd HH:mm:ss", outDateFormat: "MMM d, yyyy h:mm a")
rating = "\(review.rating ?? 0)"
}
private class func dateTimeChangeFormat(str stringWithDate: String, inDateFormat: String, outDateFormat: String) -> String {
let inFormatter = DateFormatter()
inFormatter.locale = Locale(identifier: "en_US_POSIX")
inFormatter.dateFormat = inDateFormat
let outFormatter = DateFormatter()
outFormatter.locale = Locale(identifier: "en_US_POSIX")
outFormatter.dateFormat = outDateFormat
let inStr = stringWithDate
let date = inFormatter.date(from: inStr)!
return outFormatter.string(from: date)
}
}
| true
|
721bd8a9ea7c2424c1e945e1a16054f328b174a2
|
Swift
|
8secz-johndpope/historyProject
|
/mm-merchant-ios/merchant-ios/Classes/ViewController/Storefront/Profile/View/TagPinView.swift
|
UTF-8
| 2,613
| 2.546875
| 3
|
[] |
no_license
|
//
// TagPin.swift
// merchant-ios
//
// Created by Sang Nguyen on 8/1/16.
// Copyright © 2016 WWE & CO. All rights reserved.
//
import Foundation
class TagPinView : UIView{
private final let CoreHeight: CGFloat = 6
private final let PinAlpha: CGFloat = 0.8
private final let PinHeight: CGFloat = 4
var animationCount : Int = 0
var circleView : CircleOverlayView!
var circleOverlayView : CircleOverlayView!
var isAnimating = false
override init(frame: CGRect) {
super.init(frame: frame)
circleView = CircleOverlayView(frame: CGRect(x: (self.width - CoreHeight) / 2, y: (self.width - CoreHeight) / 2, width: CoreHeight, height: CoreHeight))
circleView.circleLayer.fillColor = UIColor.primary1().cgColor
addSubview(circleView)
circleOverlayView = CircleOverlayView(frame: CGRect(x: (self.width - PinHeight) / 2, y: (self.width - PinHeight) / 2, width: PinHeight, height: PinHeight))
circleOverlayView.alpha = 0.0
circleOverlayView.circleLayer.fillColor = UIColor.primary1().cgColor
addSubview(circleOverlayView)
}
override func layoutSubviews() {
super.layoutSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func startAnimation() {
self.boomAnimation()
}
func stopAnimation() {
self.isAnimating = false
self.circleOverlayView.layer.removeAllAnimations()
}
func makeBoom(_ startTime: Double, relativeDuration: Double, alpha: CGFloat, scale: CGFloat){
UIView.addKeyframe(withRelativeStartTime: startTime, relativeDuration: relativeDuration, animations: {
self.circleOverlayView.transform = CGAffineTransform(scaleX: scale, y: scale)
self.circleOverlayView.alpha = alpha
})
}
func boomAnimation()
{
isAnimating = true
self.circleOverlayView.alpha = PinAlpha
self.circleOverlayView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
UIView.animateKeyframes(withDuration: 2.0, delay: 0, options: .repeat, animations: {
self.makeBoom(0, relativeDuration: 0.5, alpha: 0.0, scale: 5.0)
self.makeBoom(0.5, relativeDuration: 0.0, alpha: 1.0, scale: 1.0)
self.makeBoom(0.6, relativeDuration: 0.5, alpha: 0.0, scale: 5.0)
}, completion: { success in
self.isAnimating = false
Log.debug("Animation Tag Pin Complete")
})
}
}
| true
|
514d0f92d9e197381b32b4b1caaa1f49ab407647
|
Swift
|
DuckDeck/GrandMenu
|
/GrandMenuDemo/ViewController.swift
|
UTF-8
| 2,048
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// GrandMenuDemo
//
// Created by Stan Hu on 2020/3/17.
//
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var tbMenu:UITableView?
var arrMenu:[String] = ["使用ViewController","可以上下滑动的菜单View"]
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "GrandMenuDemo"
tbMenu = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
tbMenu?.dataSource = self
tbMenu?.delegate = self
tbMenu?.tableFooterView = UIView()
view.addSubview(tbMenu!)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrMenu.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil{
cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
}
cell?.textLabel?.text = arrMenu[(indexPath as NSIndexPath).row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch((indexPath as NSIndexPath).row){
case 0:
navigationController?.pushViewController(ViewControllerDemoViewController(), animated: true)
case 1:
navigationController?.pushViewController(ViewDemoViewController(), animated: true)
default:break
}
}
}
extension UIColor {
static func allColors()->[UIColor]{
return [UIColor.red,UIColor.black,UIColor.blue,UIColor.brown,UIColor.orange,UIColor.purple,UIColor.gray,UIColor.lightGray,UIColor.lightText,UIColor.darkGray,UIColor.darkText,UIColor.cyan,UIColor.yellow,UIColor.magenta,UIColor.clear]
}
}
| true
|
83ba09d331a1fd41dc07cdc0c71f5d92259197ab
|
Swift
|
RohithKumarAnil/WeatherAPI
|
/TCSCoding/TempeatureWorkerClass.swift
|
UTF-8
| 1,052
| 3.125
| 3
|
[] |
no_license
|
//
// TempeatureWorkerClass.swift
// TCSCoding
//
// Created by Rohith Kumar on 4/2/21.
//
import Foundation
enum HTTPError: Error {
case invalidURL
case invalidResponse(Data?, URLResponse?)
}
class TempeatureWorkerClass {
func getValueFromServer(urlValue: String, completionBlock: @escaping (Result<Data, Error>) -> Void) {
guard let url = URL(string: urlValue) else {
completionBlock(.failure(HTTPError.invalidURL))
return
}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil else {
completionBlock(.failure(HTTPError.invalidResponse(data, response)))
return
}
guard let responseData = data else {
completionBlock(.failure(HTTPError.invalidResponse(data, response)))
return
}
DispatchQueue.main.async {
completionBlock(.success(responseData))
}
}
task.resume()
}
}
| true
|
5b7e4bae74f28fcd828fa19b6860e0da21be654b
|
Swift
|
Mi57/SKB_Kontur
|
/SKB_Kontur/Extensions.swift
|
UTF-8
| 598
| 2.671875
| 3
|
[] |
no_license
|
//
// Extensions.swift
// SKB_Kontur
//
// Created by Admin on 01/08/2019.
// Copyright © 2019 Admin. All rights reserved.
//
import Foundation
extension String {
func convertFromStringToDate() -> String?{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: self)
dateFormatter.dateFormat = "dd.MM.yyyy"
return dateFormatter.string(from: date ?? Date())
}
func toNormalPhoneNumber() -> String{
return self.filter{$0.wholeNumberValue != nil}
}
}
| true
|
9e9e6e9d5b76965f225c45787e07b0e9afcb5fcf
|
Swift
|
Jeon-heaji/Task
|
/20190531CarthageExample/Carthage/Checkouts/DynamicColor/Tests/DynamicColorTests.swift
|
UTF-8
| 24,909
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import XCTest
class DynamicColorTests: XCTestCase {
func testColorFromHexString() {
let redStandard = DynamicColor(red: 1, green: 0, blue: 0, alpha: 1)
let redHex = DynamicColor(hexString: "#ff0000")
XCTAssert(redStandard.isEqual(redHex), "Color should be equals")
let customStandard = DynamicColor(red: 171 / 255, green: 63 / 255, blue: 74 / 255, alpha: 1)
let customHex = DynamicColor(hexString: "aB3F4a")
XCTAssert(customStandard.isEqual(customHex), "Color should be equals")
let wrongStandard = DynamicColor(red: 0, green: 0, blue: 0, alpha: 1)
let wrongHex = DynamicColor(hexString: "#T5RD2Z")
XCTAssert(wrongStandard.isEqual(wrongHex), "Color should be equals")
let redAlphaStandard = DynamicColor(red: 1, green: 0, blue: 0, alpha: 0.8)
let redAlphaHex = DynamicColor(hexString: "#FF0000CC")
XCTAssert(redAlphaStandard.isEqual(redAlphaHex), "Color should be equals")
let overflowedColor = DynamicColor(hexString: "#FFFFFFFF")
XCTAssert(overflowedColor.isEqual(toHex: 0xFFFFFF), "Color should be equals")
}
func testToHexString() {
let red = DynamicColor.red
let blue = DynamicColor.blue
let green = DynamicColor.green
let yellow = DynamicColor.yellow
let black = DynamicColor.black
let custom = DynamicColor(hex: 0x769a2b)
XCTAssert(red.toHexString() == "#ff0000", "Color string should be equal to #ff0000")
XCTAssert(blue.toHexString() == "#0000ff", "Color string should be equal to #0000ff")
XCTAssert(green.toHexString() == "#00ff00", "Color string should be equal to #00ff00")
XCTAssert(yellow.toHexString() == "#ffff00", "Color string should be equal to #ffff00")
XCTAssert(black.toHexString() == "#000000", "Color string should be equal to #000000")
XCTAssert(custom.toHexString() == "#769a2b", "Color string should be equal to #769a2b (not \(custom.toHexString()))")
}
func testToHex() {
let red = DynamicColor.red
let blue = DynamicColor.blue
let green = DynamicColor.green
let yellow = DynamicColor.yellow
let black = DynamicColor.black
let custom = DynamicColor(hex: 0x769a2b)
XCTAssert(red.toHex() == 0xff0000, "Color string should be equal to 0xff0000")
XCTAssert(blue.toHex() == 0x0000ff, "Color string should be equal to 0x0000ff")
XCTAssert(green.toHex() == 0x00ff00, "Color string should be equal to 0x00ff00")
XCTAssert(yellow.toHex() == 0xffff00, "Color string should be equal to 0xffff00")
XCTAssert(black.toHex() == 0x000000, "Color string should be equal to 0x000000")
XCTAssert(custom.toHex() == 0x769a2b, "Color string should be equal to 0x769a2b")
}
func testToHexWithAlpha() {
let custom = DynamicColor(hex: 0x769a2b80, useAlpha: true)
XCTAssert(custom.toHex() == 0x769a2b, "Color string should be equal to 0x769a2b")
XCTAssertEqual(custom.alphaComponent, 0.5, accuracy: 0.01, "Alpha component should be equal to 0.5 (not \(custom.alphaComponent))")
}
func testHexPrecision() {
let allHexes: CountableRange<UInt32> = 0 ..< 0xFFFFFF
let impreciseConversions = allHexes.filter { hex in
DynamicColor(hex: hex).toHex() != hex
}
XCTAssert(impreciseConversions.count == 0, "Imprecise hex convertions on \(impreciseConversions.count > 50 ? " more than 50 entries (\(impreciseConversions.count) entries exactly)" : ": \(impreciseConversions)")")
}
func testOverflowedColor() {
let positiveColor = DynamicColor(hex: 0xffffffff)
let alphaColor = DynamicColor(hex: 0xffffffff)
XCTAssert(positiveColor.toHex() == 0xffffff, "Color string should be equal to 0xffffff")
XCTAssert(alphaColor.toHex() == 0xffffff, "Color string should be equal to 0xffffff")
XCTAssertEqual(alphaColor.alphaComponent, 1, accuracy: 0.01, "Alpha component should be equal to 0.5 (not \(alphaColor.alphaComponent))")
}
func testIsEqualToHexString() {
let red = DynamicColor.red
let blue = DynamicColor.blue
let green = DynamicColor.green
let yellow = DynamicColor.yellow
let black = DynamicColor.black
let custom = DynamicColor(hex: 0x769a2b)
XCTAssert(red.isEqual(toHexString: "#ff0000"), "Color string should be equal to #ff0000")
XCTAssert(blue.isEqual(toHexString: "#0000ff"), "Color string should be equal to #0000ff")
XCTAssert(green.isEqual(toHexString: "#00ff00"), "Color string should be equal to #00ff00")
XCTAssert(yellow.isEqual(toHexString: "#ffff00"), "Color string should be equal to #ffff00")
XCTAssert(black.isEqual(toHexString: "#000000"), "Color string should be equal to #000000")
XCTAssert(custom.isEqual(toHexString: "#769a2b"), "Color string should be equal to #769a2b")
}
func testIsEqualToHex() {
let red = DynamicColor.red
let blue = DynamicColor.blue
let green = DynamicColor.green
let yellow = DynamicColor.yellow
let black = DynamicColor.black
let custom = DynamicColor(hex: 0x769a2b)
XCTAssert(red.isEqual(toHex: 0xff0000), "Color string should be equal to 0xff0000")
XCTAssert(blue.isEqual(toHex: 0x0000ff), "Color string should be equal to 0x0000ff")
XCTAssert(green.isEqual(toHex: 0x00ff00), "Color string should be equal to 0x00ff00")
XCTAssert(yellow.isEqual(toHex: 0xffff00), "Color string should be equal to 0xffff00")
XCTAssert(black.isEqual(toHex: 0x000000), "Color string should be equal to 0x000000")
XCTAssert(custom.isEqual(toHex: 0x769a2b), "Color string should be equal to 0x769a2b")
}
func testAdjustHueColor() {
let custom1 = DynamicColor(hex: 0x881111).adjustedHue(amount: 45)
let custom2 = DynamicColor(hex: 0xc0392b).adjustedHue(amount: 90)
let custom3 = DynamicColor(hex: 0xc0392b).adjustedHue(amount: -60)
let same1 = DynamicColor(hex: 0xc0392b).adjustedHue(amount: 0)
let same2 = DynamicColor(hex: 0xc0392b).adjustedHue(amount: 360)
XCTAssert(custom1.isEqual(toHexString: "#886a11"), "Should be equal to #886a11 (not \(custom1.toHexString()))")
XCTAssert(custom2.isEqual(toHexString: "#68c02b"), "Should be equal to #68c02b (not \(custom2.toHexString()))")
XCTAssert(custom3.isEqual(toHexString: "#c02bb2"), "Should be equal to #c02bb2 (not \(custom3.toHexString()))")
XCTAssert(same1.isEqual(toHexString: "#c0392b"), "Should be equal to #c0392b (not \(same1.toHexString()))")
XCTAssert(same2.isEqual(toHexString: "#c0392b"), "Should be equal to #c0392b (not \(same2.toHexString()))")
}
func testComplementColor() {
let complement = DynamicColor(hex: 0xc0392b).complemented()
let adjustedHue = DynamicColor(hex: 0xc0392b).adjustedHue(amount: 180)
XCTAssert(complement.isEqual(adjustedHue), "Colors should be the same")
}
func testLighterColor() {
let red = DynamicColor.red.lighter()
let green = DynamicColor.green.lighter()
let blue = DynamicColor.blue.lighter()
let violet = DynamicColor(red: 1, green: 0, blue: 1, alpha: 1).lighter()
let white = DynamicColor.white.lighter()
let black = DynamicColor(red: 0, green: 0, blue: 0, alpha: 1).lighter()
let gray = black.lighter()
XCTAssert(red.isEqual(toHex: 0xff6666), "Should be equal to #ff6666 (not \(red.toHexString()))")
XCTAssert(green.isEqual(toHex: 0x66ff66), "Should be equal to #66ff66 (not \(green.toHexString()))")
XCTAssert(blue.isEqual(toHex: 0x6666ff), "Should be equal to #6666ff (not \(blue.toHexString()))")
XCTAssert(violet.isEqual(toHex: 0xff66ff), "Should be equal to #ff66ff (not \(violet.toHexString()))")
XCTAssert(white.isEqual(toHex: 0xffffff), "Should be equal to #ffffff (not \(white.toHexString()))")
XCTAssert(black.isEqual(toHex: 0x333333), "Should be equal to #333333 (not \(black.toHexString()))")
XCTAssert(gray.isEqual(DynamicColor(hex: 0x666666)), "Should be equal to #666666 (not \(gray.toHexString()))")
}
func testLightenColor() {
let whiteFromBlack = DynamicColor.black.lighter(amount: 1)
let same = DynamicColor(hex: 0xc0392b).lighter(amount: 0)
let maxi = DynamicColor(hex: 0xc0392b).lighter(amount: 1)
XCTAssert(whiteFromBlack.isEqual(toHexString: "#ffffff"), "Color should be equals (not \(whiteFromBlack.toHexString()))")
XCTAssert(same.isEqual(toHexString: "#c0392b"), "Color string should be equal to #c0392b (not \(same.toHexString()))")
XCTAssert(maxi.isEqual(toHexString: "#ffffff"), "Color string should be equal to #ffffff (not \(maxi.toHexString()))")
}
func testDarkerColor() {
let red = DynamicColor.red.darkened()
let white = DynamicColor.white.darkened()
let gray = white.darkened()
let black = DynamicColor.black.darkened()
XCTAssert(red.isEqual(toHexString: "#990000"), "Color string should be equal to #990000 (not \(red.toHexString()))")
XCTAssert(white.isEqual(toHexString: "#cccccc"), "Color string should be equal to #cccccc (not \(white.toHexString()))")
XCTAssert(gray.isEqual(toHexString: "#999999"), "Color string should be equal to #999999 (not \(gray.toHexString()))")
XCTAssert(black.isEqual(toHexString: "#000000"), "Color string should be equal to #000000 (not \(black.toHexString()))")
}
func testDarkenColor() {
let blackFromWhite = DynamicColor.white.darkened(amount: 1)
let same = DynamicColor(hex: 0xc0392b).darkened(amount: 0)
let maxi = DynamicColor(hex: 0xc0392b).darkened(amount: 1)
XCTAssert(blackFromWhite.isEqual(toHexString: "#000000"), "Colors should be the same (not \(blackFromWhite.toHexString()))")
XCTAssert(same.isEqual(toHexString: "#c0392b"), "Color string should be equal to #c0392b (not \(same.toHexString()))")
XCTAssert(maxi.isEqual(toHexString: "#000000"), "Color string should be equal to #000000 (not \(maxi.toHexString()))")
}
func testSaturatedColor() {
let primary = DynamicColor.red.saturated()
let white = DynamicColor.white.saturated()
let black = DynamicColor.black.saturated()
let custom = DynamicColor(hex: 0xc0392b).saturated()
XCTAssert(primary.isEqual(toHexString: "#ff0000"), "Color string should be equal to #ff0000 (not \(primary.toHexString()))")
XCTAssert(white.isEqual(toHexString: "#ffffff"), "Color string should be equal to #ffffff (not \(white.toHexString()))")
XCTAssert(black.isEqual(toHexString: "#000000"), "Color string should be equal to #000000 (not \(black.toHexString()))")
XCTAssert(custom.isEqual(toHexString: "#d82614"), "Color string should be equal to #d82614 (not \(custom.toHexString()))")
}
func testSaturateColor() {
let same = DynamicColor(hex: 0xc0392b).saturated(amount: 0)
let maxi = DynamicColor(hex: 0xc0392b).saturated(amount: 1)
XCTAssert(same.isEqual(toHexString: "#c0392b"), "Color string should be equal to #c0392b (not \(same.toHexString()))")
XCTAssert(maxi.isEqual(toHexString: "#eb1600"), "Color string should be equal to #eb1600 (not \(maxi.toHexString()))")
}
func testDesaturatedColor() {
let primary = DynamicColor.red.desaturated()
let white = DynamicColor.white.desaturated()
let black = DynamicColor.black.desaturated()
let custom = DynamicColor(hex: 0xc0392b).desaturated()
XCTAssert(primary.isEqual(toHexString: "#e61919"), "Color string should be equal to #e61919 (not \(primary.toHexString()))")
XCTAssert(white.isEqual(toHexString: "#ffffff"), "Color string should be equal to #ffffff (not \(white.toHexString()))")
XCTAssert(black.isEqual(toHexString: "#000000"), "Color string should be equal to #000000 (not \(black.toHexString()))")
XCTAssert(custom.isEqual(toHexString: "#a94c43"), "Color string should be equal to #a94c43 (not \(custom.toHexString()))")
}
func testDesaturateColor() {
let same = DynamicColor(hex: 0xc0392b).desaturated(amount: 0)
let maxi = DynamicColor(hex: 0xc0392b).desaturated(amount: 1)
XCTAssert(same.isEqual(toHexString: "#c0392b"), "Color string should be equal to #c0392b (not \(same.toHexString()))")
XCTAssert(maxi.isEqual(toHexString: "#767676"), "Color string should be equal to #767676 (not \(maxi.toHexString()))")
}
func testGrayscaleColor() {
let grayscale = DynamicColor(hex: 0xc0392b).grayscaled()
let desaturated = DynamicColor(hex: 0xc0392b).desaturated(amount: 1)
XCTAssert(grayscale.isEqual(desaturated), "Colors should be the same")
}
func testInvertColor() {
let inverted = DynamicColor(hex: 0xff0000).inverted()
let original = inverted.inverted()
XCTAssert(inverted.isEqual(toHexString: "#00ffff"), "Color string should be equal to #00ffff")
XCTAssert(original.isEqual(toHexString: "#ff0000"), "Color string should be equal to #ff0000")
}
func testIsLightColor() {
let l1 = DynamicColor.white
let l2 = DynamicColor.green
let d1 = DynamicColor.black
let d2 = DynamicColor.red
let d3 = DynamicColor.blue
XCTAssert(l1.isLight(), "White should be light")
XCTAssert(l2.isLight(), "Green should be light")
XCTAssertFalse(d1.isLight(), "Black should be dark")
XCTAssertFalse(d2.isLight(), "Red should be dark")
XCTAssertFalse(d3.isLight(), "Blue should be dark")
}
func testMixRGBColors() {
let red = DynamicColor.red
let blue = DynamicColor.blue
let green = DynamicColor.green
var midMix = red.mixed(withColor: blue)
XCTAssert(midMix.isEqual(toHexString: "#800080"), "Color string should be equal to #800080 (not \(midMix.toHexString()))")
midMix = blue.mixed(withColor: red)
XCTAssert(midMix.isEqual(toHexString: "#800080"), "Color string should be equal to #800080 (not \(midMix.toHexString())")
let sameMix = green.mixed(withColor: green)
XCTAssert(sameMix.isEqual(toHexString: "#00ff00"), "Color string should be equal to #00ff00")
let noMix = red.mixed(withColor: blue, weight: 0)
let noMixOverflow = red.mixed(withColor: blue, weight: -20)
XCTAssert(noMix.isEqual(toHexString: "#ff0000"), "Color string should be equal to #ff0000")
XCTAssert(noMix.isEqual(noMixOverflow), "Colors should be the same")
let fullMix = red.mixed(withColor: blue, weight: 1)
let fullMixOverflow = red.mixed(withColor: blue, weight: 24)
XCTAssert(fullMix.isEqual(toHexString: "#0000ff"), "Color string should be equal to #0000ff")
XCTAssert(fullMix.isEqual(fullMixOverflow), "Colors should be the same")
}
func testMixLabColors() {
let red = DynamicColor.red
let blue = DynamicColor.blue
let green = DynamicColor.green
var midMix = red.mixed(withColor: blue, inColorSpace: .lab)
XCTAssert(midMix.isEqual(toHexString: "#c93b88"), "Color string should be equal to #c93b88 (not \(midMix.toHexString()))")
midMix = blue.mixed(withColor: red, inColorSpace: .lab)
XCTAssert(midMix.isEqual(toHexString: "#c93b88"), "Color string should be equal to #c93b88 (not \(midMix.toHexString()))")
let sameMix = green.mixed(withColor: green, inColorSpace: .lab)
XCTAssert(sameMix.isEqual(toHexString: "#00ff00"), "Color string should be equal to #00ff00")
let noMix = red.mixed(withColor: blue, weight: 0, inColorSpace: .lab)
let noMixOverflow = red.mixed(withColor: blue, weight: -20, inColorSpace: .lab)
XCTAssert(noMix.isEqual(toHexString: "#ff0000"), "Color string should be equal to #ff0000")
XCTAssert(noMix.isEqual(noMixOverflow), "Colors should be the same")
let fullMix = red.mixed(withColor: blue, weight: 1, inColorSpace: .lab)
let fullMixOverflow = red.mixed(withColor: blue, weight: 24, inColorSpace: .lab)
XCTAssert(fullMix.isEqual(toHexString: "#0000ff"), "Color string should be equal to #0000ff")
XCTAssert(fullMix.isEqual(fullMixOverflow), "Colors should be the same")
}
func testMixHSLColors() {
let red = DynamicColor.red
let blue = DynamicColor.blue
let green = DynamicColor.green
var midMix = red.mixed(withColor: blue, inColorSpace: .hsl)
XCTAssert(midMix.isEqual(toHexString: "#ff00ff"), "Color string should be equal to #ff00ff (not \(midMix.toHexString()))")
midMix = blue.mixed(withColor: red, inColorSpace: .hsl)
XCTAssert(midMix.isEqual(toHexString: "#ff00ff"), "Color string should be equal to #ff00ff")
let sameMix = green.mixed(withColor: green, inColorSpace: .hsl)
XCTAssert(sameMix.isEqual(toHexString: "#00ff00"), "Color string should be equal to #00ff00")
let noMix = red.mixed(withColor: blue, weight: 0, inColorSpace: .hsl)
let noMixOverflow = red.mixed(withColor: blue, weight: -20, inColorSpace: .hsl)
XCTAssert(noMix.isEqual(toHexString: "#ff0000"), "Color string should be equal to #ff0000")
XCTAssert(noMix.isEqual(noMixOverflow), "Colors should be the same")
let fullMix = red.mixed(withColor: blue, weight: 1, inColorSpace: .hsl)
let fullMixOverflow = red.mixed(withColor: blue, weight: 24, inColorSpace: .hsl)
XCTAssert(fullMix.isEqual(toHexString: "#0000ff"), "Color string should be equal to #0000ff")
XCTAssert(fullMix.isEqual(fullMixOverflow), "Colors should be the same")
}
func testMixHSBColors() {
let red = DynamicColor.red
let blue = DynamicColor.blue
let green = DynamicColor.green
var midMix = red.mixed(withColor: blue, inColorSpace: .hsb)
XCTAssert(midMix.isEqual(toHexString: "#ff00ff") || midMix.isEqual(toHexString: "#00ff00"), "Color string should be equal to #ff00ff or #00ff00 (not \(midMix.toHexString()))")
midMix = blue.mixed(withColor: red, inColorSpace: .hsb)
XCTAssert(midMix.isEqual(toHexString: "#ff00ff") || midMix.isEqual(toHexString: "#00ff00"), "Color string should be equal to #ff00ff or #00ff00")
let sameMix = green.mixed(withColor: green, inColorSpace: .hsb)
XCTAssert(sameMix.isEqual(toHexString: "#00ff00"), "Color string should be equal to #00ff00")
let noMix = red.mixed(withColor: blue, weight: 0, inColorSpace: .hsb)
let noMixOverflow = red.mixed(withColor: blue, weight: -20, inColorSpace: .hsb)
XCTAssert(noMix.isEqual(toHexString: "#ff0000"), "Color string should be equal to #ff0000")
XCTAssert(noMix.isEqual(noMixOverflow), "Colors should be the same")
let fullMix = red.mixed(withColor: blue, weight: 1, inColorSpace: .hsb)
let fullMixOverflow = red.mixed(withColor: blue, weight: 24, inColorSpace: .hsb)
XCTAssert(fullMix.isEqual(toHexString: "#0000ff"), "Color string should be equal to #0000ff")
XCTAssert(fullMix.isEqual(fullMixOverflow), "Colors should be the same")
}
func testTintColor() {
let tint = DynamicColor(hex: 0xc0392b).tinted()
XCTAssert(tint.isEqual(toHexString: "#cd6155"), "Color string should be equal to #cd6155 (not \(tint.toHexString())")
let white = DynamicColor(hex: 0xc0392b).tinted(amount: 1)
XCTAssert(white.isEqual(toHexString: "#ffffff"), "Color string should be equal to #ffffff")
let alwaysWhite = DynamicColor.white.tinted()
XCTAssert(alwaysWhite.isEqual(toHexString: "#ffffff"), "Color string should be equal to #ffffff")
}
func testShadeColor() {
let shade = DynamicColor(hex: 0xc0392b).shaded()
XCTAssert(shade.isEqual(toHexString: "#9a2e22"), "Color string should be equal to #9a2e22 (not \(shade.toHexString())")
let black = DynamicColor(hex: 0xc0392b).shaded(amount: 1)
XCTAssert(black.isEqual(toHexString: "#000000"), "Color string should be equal to #000000")
let alwaysBlack = DynamicColor.black.shaded()
XCTAssert(alwaysBlack.isEqual(toHexString: "#000000"), "Color string should be equal to #000000")
}
func testLuminance() {
let blackLuminance = DynamicColor.black.luminance
XCTAssertEqual(blackLuminance, 0, "Luminance for black color should be 0")
let whiteLuminance = DynamicColor.white.luminance
XCTAssertEqual(whiteLuminance, 1, "Luminance for white color should be 1")
XCTAssertEqual(DynamicColor(hexString: "#F18F2E").luminance, 0.38542950354028, accuracy: 0.000001)
XCTAssertEqual(DynamicColor(hexString: "#FFFF00").luminance, 0.9278, accuracy: 0.000001)
XCTAssertEqual(DynamicColor(hexString: "#ffb0ef").luminance, 0.58542663140357, accuracy: 0.000001)
}
func testContrastRatio() {
XCTAssertEqual(DynamicColor.black.contrastRatio(with: .white), 21, "Contrast between black and white should be 21")
XCTAssertEqual(DynamicColor.white.contrastRatio(with: .black), 21, "Contrast between white and black should be 21")
let color1 = DynamicColor(hexString: "F18F2E")
let color2 = DynamicColor(hexString: "FFFF00")
let color3 = DynamicColor(hexString: "ffb0ef")
XCTAssertEqual(color1.contrastRatio(with: color2), 2.2455988, accuracy: TestsAcceptedAccuracy)
XCTAssertEqual(color2.contrastRatio(with: color1), 2.2455988, accuracy: TestsAcceptedAccuracy)
XCTAssertEqual(color3.contrastRatio(with: color2), 1.5388086, accuracy: TestsAcceptedAccuracy)
XCTAssertEqual(color2.contrastRatio(with: color3), 1.5388086, accuracy: TestsAcceptedAccuracy)
XCTAssertEqual(color3.contrastRatio(with: color1), 1.4593100, accuracy: TestsAcceptedAccuracy)
XCTAssertEqual(color1.contrastRatio(with: color3), 1.4593100, accuracy: TestsAcceptedAccuracy)
}
func testIsContrasting() {
XCTAssertFalse(DynamicColor.black.isContrasting(with: .black), "A color cannot contrast with itself")
XCTAssertTrue(DynamicColor.black.isContrasting(with: .white), "Black and white are always contrasting")
XCTAssertTrue(DynamicColor.black.isContrasting(with: .white, inContext: .standard), "Black and white are always contrasting")
XCTAssertTrue(DynamicColor.black.isContrasting(with: .white, inContext: .standardLargeText), "Black and white are always contrasting")
XCTAssertTrue(DynamicColor.black.isContrasting(with: .white, inContext: .enhanced), "Black and white are always contrasting")
XCTAssertTrue(DynamicColor.black.isContrasting(with: .white, inContext: .enhancedLargeText), "Black and white are always contrasting")
// Contrast ratio between white and red = 4. So, we should only return true in StandardLargeText
XCTAssertFalse(DynamicColor.white.isContrasting(with: .red), "White and red are only contrasting in StandardLargeText")
XCTAssertFalse(DynamicColor.white.isContrasting(with: .red, inContext: .standard), "White and red are only contrasting in StandardLargeText")
XCTAssertTrue(DynamicColor.white.isContrasting(with: .red, inContext: .standardLargeText), "White and red are only contrasting in StandardLargeText")
XCTAssertFalse(DynamicColor.white.isContrasting(with: .red, inContext: .enhanced), "White and red are only contrasting in StandardLargeText")
XCTAssertFalse(DynamicColor.white.isContrasting(with: .red, inContext: .enhancedLargeText), "White and red are only contrasting in StandardLargeText")
let pink = DynamicColor(hexString: "FF00FF")
// Contrast ration between FF00FF and black = 6.7, . So, we should only return false in Enhanced
XCTAssertTrue(DynamicColor.black.isContrasting(with: pink), "Black and pink are always contrasting except in Enhanced")
XCTAssertTrue(DynamicColor.black.isContrasting(with: pink, inContext: .standard), "Black and pink are always contrasting except in Enhanced")
XCTAssertTrue(DynamicColor.black.isContrasting(with: pink, inContext: .standardLargeText), "Black and pink are always contrasting except in Enhanced")
XCTAssertFalse(DynamicColor.black.isContrasting(with: pink, inContext: .enhanced), "Black and pink are always contrasting except in Enhanced")
XCTAssertTrue(DynamicColor.black.isContrasting(with: pink, inContext: .enhancedLargeText), "Black and pink are always contrasting except in Enhanced")
}
}
| true
|
375e0e96099d8208a25c7e87179af65fa38768cf
|
Swift
|
joshueis/Salut
|
/Salut/View/ChannelViewCell.swift
|
UTF-8
| 1,381
| 2.8125
| 3
|
[] |
no_license
|
//
// ChannelViewCell.swift
// Salut
//
// Created by Israel Carvajal on 11/14/17.
// Copyright © 2017 Israel Carvajal. All rights reserved.
//
import UIKit
class ChannelViewCell: UITableViewCell {
@IBOutlet weak var channelName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected{
// don't forget to select non in selection attribute for cell in instpector
self.layer.backgroundColor = UIColor(white: 1, alpha: 0.2).cgColor
}else{
self.layer.backgroundColor = UIColor.clear.cgColor
}
// Configure the view for the selected state
}
func configureCell(channel: Channel){
// ?? if not found or nil then do ""
let tittle = channel.tittle ?? ""
channelName.text = "#\(tittle)"
//set default font to be able to distinguish it from bold font when channel has new items
channelName.font = UIFont(name: "HelveticaNeue-Regular", size: 17)
//if the channel has unread messages then bold it's name
if MsgService.instance.unreadChannels.contains(channel.id){
channelName.font = UIFont(name: "HelveticaNeue-Bold", size: 22)
}
}
}
| true
|
5691f2dd722fd0e77a7267e100458e8944a97c28
|
Swift
|
zixzelz/love-of-music
|
/love-of-music/Releases/ViewController.swift
|
UTF-8
| 1,288
| 2.59375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// love-of-music
//
// Created by Ruslan Maslouski on 6/5/18.
// Copyright © 2018 Ruslan Maslouski. All rights reserved.
//
import UIKit
protocol ViewControllerViewModeling {
var listViewModel: ListViewModel<ReleasesCellViewModel> { get }
}
class ViewController: UIViewController {
@IBOutlet var tableView: UITableView!
private var contentDataSource: TableViewDataSource<ReleasesCellViewModel>? {
didSet {
tableView.dataSource = contentDataSource
}
}
private var viewModel: ViewControllerViewModeling! {
didSet {
if isViewLoaded {
bind(with: viewModel)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel = ViewControllerViewModel()
// bind(with: viewModel)
}
private func bind(with viewModel: ViewControllerViewModeling) {
contentDataSource = TableViewDataSource(tableView: tableView, listViewModel: viewModel.listViewModel, map: { (tableView, indexpath, cellVM) -> UITableViewCell in
let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultCell", for: indexpath) as! DefaultTableViewCell
cell.configure(viewModel: cellVM)
return cell
})
}
}
| true
|
7152010522da6c0e07ee2b021ae56b9634085e8f
|
Swift
|
Sweeper777/BlackHoleGame
|
/BlackHoleGame/AIGameViewController.swift
|
UTF-8
| 4,298
| 2.75
| 3
|
[] |
no_license
|
import UIKit
import SnapKit
import SwiftyButton
import SCLAlertView
class AIGameViewController: GameViewControllerBase {
var aiQueue = DispatchQueue(label: "aiQueue")
var turn = 1
var myColor: PlayerSide!
override func viewDidLoad() {
super.viewDidLoad()
myColor = [PlayerSide.red, .blue].randomElement()!
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: showPlayerSide)
}
func showPlayerSide() {
if myColor == .red {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 56, height: 56), false, 0)
UIColor.red.setFill()
let path = UIBezierPath(ovalIn: CGRect.zero.with(width: 56).with(height: 56))
path.fill()
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let alert = SCLAlertView(appearance: SCLAlertView.SCLAppearance(kCircleIconHeight: 56, showCloseButton: false))
alert.addButton("OK".localized, action: {})
_ = alert.showCustom("Your color is red. You go first.", subTitle: "", color: .black, icon: image)
} else {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 56, height: 56), false, 0)
UIColor.blue.setFill()
let path = UIBezierPath(ovalIn: CGRect.zero.with(width: 56).with(height: 56))
path.fill()
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let alert = SCLAlertView(appearance: SCLAlertView.SCLAppearance(kCircleIconHeight: 56, showCloseButton: false))
alert.addButton("OK".localized, action: aiTurn)
_ = alert.showCustom("Your color is blue. The AI goes first.", subTitle: "", color: .black, icon: image)
}
}
func searchDepth(forTurn turn: Int) -> Int {
if game.totalMoves - turn - 1 > 10 {
return 3
}
if game.totalMoves - turn - 1 > 6 {
return 4
}
return 6
}
override func didTouchCircle(inRow row: Int, atIndex index: Int) {
if game.currentTurn != myColor || game.ended{
return
}
let color = game.currentTurn == .blue ? UIColor.blue : .red
let number = game.currentNumber
if game.makeMove(row: row, index: index) {
self.board.appearAnimationForCircleView(
inRow: row,
atIndex: index,
backgroundColor: color,
number: number
).do(block: aiTurn).perform()
updateNextMoveView()
}
}
func aiTurn() {
guard !game.ended else { return }
self.board.board = self.game.board
self.turn += 1
aiQueue.async {
[weak self] in
guard let `self` = self else { return }
let move: (row: Int, index: Int)
let ai: GameAI
if self.turn >= 8 {
ai = HeuristicAI(game: Game(copyOf: self.game), myColor: self.game.currentTurn)
move = (ai as! HeuristicAI).getNextMove(searchDepth: self.searchDepth(forTurn: self.turn))
} else {
ai = RandomAI(game: Game(copyOf: self.game), myColor: self.game.currentTurn)
move = ai.getNextMove()
}
let aiNumber = self.game.currentNumber
self.game.makeMove(row: move.row, index: move.index)
self.board.board = self.game.board
DispatchQueue.main.async {
[weak self] in
self?.board.appearAnimationForCircleView(
inRow: move.row,
atIndex: move.index,
backgroundColor: ai.myColor == .blue ? .blue : .red,
number: aiNumber).perform()
self?.turn += 1
self?.updateNextMoveView()
}
}
}
override func restartGame() {
game = Game(boardSize: 6)
game.delegate = self
turn = 1
myColor = [PlayerSide.red, .blue].randomElement()
board.board = game.board
board.setNeedsDisplay()
updateNextMoveView()
showPlayerSide()
}
}
| true
|
0db179dbad402cd755d72f8943827a944ac60df8
|
Swift
|
miguelPalaciosAPPDeveloper/LinioChallengeMVVM
|
/LinioMVVM/Code/Modules/Favorites/Repositories/FavoritesRepository.swift
|
UTF-8
| 841
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// FavoritesRepository.swift
// LinioMVVM
//
// Created by Miguel De León Palacios on 9/1/19.
// Copyright © 2019 MiguelPalacios. All rights reserved.
//
import Foundation
protocol FavoritesRepositoryProtocol {
@discardableResult
func fetchFavorites(path: String, completion: @escaping ServicesRouterCompletion<[LinioFavoritesList]>) -> Cancellable?
}
class FavoritesRepository: FavoritesRepositoryProtocol {
private let serviceManager: LinioChallengeServiceManager
init(serviceRouter: Router<LinioChallengeEndPoint>) {
self.serviceManager = LinioChallengeServiceManager(router: serviceRouter)
}
func fetchFavorites(path: String, completion: @escaping ServicesRouterCompletion<[LinioFavoritesList]>) -> Cancellable? {
return serviceManager.getFavoritesList(withPath: path, completion: completion)
}
}
| true
|
d36554325d6150a7de778fd567ce65a18bdb4677
|
Swift
|
AnkoTop/On-the-Map
|
/On The Map/StatisticsViewController.swift
|
UTF-8
| 3,440
| 2.75
| 3
|
[] |
no_license
|
//
// StatisticsViewController.swift
// On The Map
//
// Created by Anko Top on 23/04/15.
// Copyright (c) 2015 Anko Top. All rights reserved.
//
import UIKit
import CoreLocation
class StatisticsViewController: UIViewController {
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!
@IBOutlet weak var label4: UILabel!
@IBOutlet weak var label5: UILabel!
@IBOutlet weak var label6: UILabel!
@IBOutlet weak var label7: UILabel!
@IBOutlet weak var label8: UILabel!
@IBOutlet weak var label9: UILabel!
@IBOutlet weak var label10: UILabel!
@IBOutlet weak var label11: UILabel!
@IBOutlet weak var label12: UILabel!
@IBOutlet weak var label13: UILabel!
@IBOutlet weak var label14: UILabel!
@IBOutlet weak var label15: UILabel!
@IBOutlet weak var label16: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
updateStatistics()
// register for updates of the StudenLocation data
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateStatistics", name: StudentLocationNotificationKey , object: nil)
}
func updateStatistics() {
let newStats = AppStatistics()
let statisticsDictionary = newStats.returnStatistics()
//Headings
let attributedStringLocations = NSAttributedString(string: "Student Locations", attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
let attributedStringHQ = NSAttributedString(string: "Distances to Udacity HQ", attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
let attributedStringURL = NSAttributedString(string: "URL's", attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
// text
label1.attributedText = attributedStringLocations
label2.text = "There are \(statisticsDictionary[AppStatistics.totalStudentLocations]!) locations registered,"
label3.text = "added by \(statisticsDictionary[AppStatistics.totalUniqueStudents]!) different students."
var end = "locations."
if (Int(statisticsDictionary[AppStatistics.totalUserLocations]!)) == 1 {
end = "location."
}
label4.text = "You have \(statisticsDictionary[AppStatistics.totalUserLocations]!) active \(end)"
label5.text = " "
label6.attributedText = attributedStringURL
label7.text = "\(statisticsDictionary[AppStatistics.totalValidUrls]!) locations have a valid URL and"
label8.text = "\(statisticsDictionary[AppStatistics.totalInvalidUrls]!) have invalid URL's."
label9.text = " "
label10.attributedText = attributedStringHQ
label11.text = "The average distance is \(statisticsDictionary[AppStatistics.averageDistanceToUdacityHQ]!) km."
label12.text = "The minimum distance is \(statisticsDictionary[AppStatistics.minDistanceToUdacityHQ]!) km,"
label13.text = "added by \(statisticsDictionary[AppStatistics.nameMinDistanceToUdacityHQ]!)."
label14.text = "The maximum is a whopping \(statisticsDictionary[AppStatistics.maxDistanceToUdacityHQ]!) km,"
label15.text = "added by \(statisticsDictionary[AppStatistics.nameMaxDistanceToUdacityHQ]!)."
label16.text = "---"
}
}
| true
|
0ebcd5f42e91b938bd61d4dfad18811061b7525b
|
Swift
|
wilsonperez53/splitwise
|
/splitwise/Views/DetallesDeudor.swift
|
UTF-8
| 1,887
| 2.9375
| 3
|
[] |
no_license
|
//
// DetallesDeudor.swift
// splitwise
//
// Created by Estudiantes on 4/14/21.
//
import Foundation
import SwiftUI
struct DetallesDeudorView: View {
let deudor: SplitwiseEntity
@State var montoDolares: String = ""
@State var montoColones: String = ""
@Environment(\.presentationMode) var presentationMode
@ObservedObject var coreDataVM = CoreDataViewModel()
var body: some View {
//NavigationView{
VStack {
Form{
Text(deudor.deudor ?? "No Name")
Text("Total dolares\(deudor.montoDolares)" )
Text("Total colones \(deudor.montoColones)" )
Text("Agregar deuda en dolares")
TextField("\(deudor.montoDolares)", text: $montoDolares)
Text("Agregar deuda en colones")
TextField("\(deudor.montoColones)", text: $montoColones)
}
Button(action: Save) {
HStack {
Text("Modificar deudas")
}
}
.foregroundColor(Color.white)
.padding()
.background(Color.green)
}
.toolbar {
ToolbarItem(placement: .principal) {
VStack {
Text("Deudas").font(.headline)
}
}
}
}
func Save(){
deudor.montoColones += Double(montoColones) ?? 0
deudor.montoDolares += Double(montoDolares) ?? 0
self.coreDataVM.actualizarDeudas(deudor: deudor)
self.presentationMode.wrappedValue.dismiss()
}
}
struct DetallesDeudorView_Previews: PreviewProvider {
static var previews: some View {
let deudor = SplitwiseEntity()
DetallesDeudorView(deudor: deudor)
}
}
| true
|
e4b1616d40e5315a9d9c90ca2c58d13cfce7f154
|
Swift
|
RebeccaZR/iOSLearning
|
/CodeWar/CodeWarTests/StringRepeatTests.swift
|
UTF-8
| 1,124
| 2.640625
| 3
|
[] |
no_license
|
//
// StringRepeatTests.swift
// CodeWarTests
//
// Created by Rebecca Zhang on 2019/2/7.
// Copyright © 2019 Rebecca Zhang. All rights reserved.
//
import XCTest
@testable import CodeWar
class StringRepeatTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
let repeatObj = StringRepeat()
XCTAssertEqual(repeatObj.repeatStr(0, "Hello"), "")
XCTAssertEqual(repeatObj.repeatStr(6, "I"), "IIIIII")
XCTAssertEqual(repeatObj.repeatStr(20, "L L"), "L LL LL LL LL LL LL LL LL LL LL LL LL LL LL LL LL LL LL LL L")
XCTAssertEqual(repeatObj.repeatStr(7, "RADAR"), "RADARRADARRADARRADARRADARRADARRADAR")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| true
|
aabef6e1926e065565cb21810866c72a86f4ecc2
|
Swift
|
detryo/QuizApp
|
/QuizApp/Model/QuestionsFactory.swift
|
UTF-8
| 1,652
| 3.03125
| 3
|
[] |
no_license
|
//
// QuestionsFactory.swift
// QuizApp
//
// Created by Cristian Sedano Arenas on 20/2/19.
// Copyright © 2019 Cristian Sedano Arenas. All rights reserved.
//
import Foundation
class QuestionsFactory {
var questionsBank : QuestionsBank!
init(){
/*
if let path = Bundle.main.path(forResource: "QuestionsBank", ofType: "plist") {
if let pList = NSDictionary(contentsOfFile: path) {
let questionData = pList["Questions"] as! [AnyObject]
for question in questionData {
if let text = question["question"], let ans = question["answer"]{
questions.append(Question(text: text as! String, correctAnswer: ans as! Bool))
}
}
}
}*/
// Procesado Automatico Codable
do{
if let url = Bundle.main.url(forResource: "QuestionsBank", withExtension: "plist"){
let data = try Data(contentsOf: url)
self.questionsBank = try PropertyListDecoder().decode(QuestionsBank.self, from: data)
}
}catch{
print(error)
}
}
func getQuestionAt(index : Int) -> Question? {
if index < 0 || index >= self.questionsBank.Questions.count {
return nil
} else {
return self.questionsBank.Questions[index]
}
}
func getRandomQuestion() -> Question {
let index = Int (arc4random_uniform(UInt32 (self.questionsBank.Questions.count)))
return self.questionsBank.Questions[index]
}
}
| true
|
07509b463023d76aa44f90b911b91f2793210f45
|
Swift
|
vandanpatelgithub/MissingPersons-iOS-App
|
/MissingPersons/PersonCell.swift
|
UTF-8
| 1,749
| 2.890625
| 3
|
[] |
no_license
|
import UIKit
class PersonCell: UICollectionViewCell {
@IBOutlet weak var personImg: UIImageView!
var person: Person!
func configureCell(person: Person, selected: Bool) {
self.person = person
if let url = NSURL(string: "\(baseURL)\(person.personImageURL!)") {
downloadImage(url, selected: selected)
}
}
func downloadImage(url: NSURL, selected: Bool) {
getDataFromURL(url) { (data, response, error) in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
guard let data = data where error == nil else { return }
self.personImg.image = UIImage(data: data)
self.person.personImage = self.personImg.image
if !selected {
self.markUnselected()
} else {
self.markSelected()
}
}
}
}
func getDataFromURL(url: NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError?) -> Void)) {
NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
completion(data: data, response: response, error: error)
}.resume()
}
func setSelected() {
markSelected()
if self.person.faceID == nil {
self.person.downloadFaceID()
}
}
func markSelected() {
personImg.layer.borderWidth = 2.0
personImg.layer.borderColor = UIColor.redColor().CGColor
}
func markUnselected() {
self.personImg.layer.borderWidth = 2.0
self.personImg.layer.borderColor = UIColor.whiteColor().CGColor
}
}
| true
|
a3d0c952510546cf2f863522f36a4bf3d22ec738
|
Swift
|
skunkworker/ascollection-view-bug-testapp
|
/TestApp/ContentView.swift
|
UTF-8
| 1,452
| 3.140625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// TestApp
//
// Created by John Bolliger on 10/3/20.
//
import SwiftUI
import ASCollectionView
struct ContentView: View {
@State var dataExample = (0 ..< 200).map { $0 }
@State var presentingModal = false
var body: some View {
HStack() {
Button(action: {
print("clicked button to show sheet")
self.presentingModal = true
}) {
Image(systemName: "plus.circle.fill")
.font(.system(size: 24))
.padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 10))
.foregroundColor(.primary)
}
}
// remove below NavigationView to remove the bug.
NavigationView
{
ASCollectionView(data: dataExample, dataID: \.self) { item, _ in
RowItem(model: Item(name: "\(item)"))
}
.layout {
.grid(layoutMode: .adaptive(withMinItemSize: 330),
itemSpacing: 20,
lineSpacing: 20,
itemSize: .estimated(90))
}
.alwaysBounceVertical()
.navigationTitle("Foobar")
.edgesIgnoringSafeArea(.all)
.sheet(isPresented: $presentingModal) {
EditSheet(dismiss: {
print("dismissed")
self.presentingModal = false
})
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
16c95cd65662cb695e09529245ba74121d5108b6
|
Swift
|
elina-smnko/test-app-movie
|
/test-app-movie/Utilities/Utilities.swift
|
UTF-8
| 1,850
| 3.140625
| 3
|
[] |
no_license
|
//
// Utilities.swift
// test-app-movie
//
// Created by Элина on 20.11.2020.
// Copyright © 2020 Элина. All rights reserved.
//
//trending:
//https://api.themoviedb.org/3/trending/movie/day?api_key=95217d31a2a874647ed506649cde5eb5
//find by name:
//https://api.themoviedb.org/3/search/movie?api_key=95217d31a2a874647ed506649cde5eb5&query=mulan&page=1
//details:
//https://api.themoviedb.org/3/movie/590706?api_key=95217d31a2a874647ed506649cde5eb5
import Foundation
class Utilities {
static let apikey = "95217d31a2a874647ed506649cde5eb5"
func formURL(path: Path, id: Int?, parameters: [Parameters:String]) -> URL? {
var urlComponents = URLComponents()
urlComponents.scheme = Components.scheme.url
urlComponents.host = Components.moviehost.url
if let id = id {
urlComponents.path = path.url+"\(id)"
}else{
urlComponents.path = path.url
}
urlComponents.queryItems = [URLQueryItem]()
for (param, value) in parameters {
urlComponents.queryItems?.append(URLQueryItem(name: param.url, value: value))
}
return urlComponents.url
}
}
enum Components {
case scheme, moviehost
var url: String {
switch self {
case .scheme:
return "https"
case .moviehost:
return "api.themoviedb.org"
}
}
}
enum Path {
case trendingpath, namepath, detailspath
var url : String {
switch self{
case .trendingpath:
return "/3/trending/movie/day"
case .namepath:
return "/3/search/movie"
case .detailspath:
return "/3/movie/"
}
}
}
enum Parameters {
case apikey, query
var url: String {
switch self{
case .apikey:
return "api_key"
case .query:
return "query"
}
}
}
| true
|
ae05dc754907fa64cd5d08ed2613467209217d2f
|
Swift
|
Billideveloper/BMI
|
/BMI/model/BMI_Brain.swift
|
UTF-8
| 1,715
| 2.828125
| 3
|
[] |
no_license
|
//
// BMI_Brain.swift
// BMI
//
// Created by Ravi Thakur on 15/07/20.
// Copyright © 2020 billidevelopers. All rights reserved.
//
import Foundation
import UIKit
struct BMI_Brain {
var bmiValue: bmi_category?
var advice = ""
var color = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
func getbmivalue() -> String{
let bmi = String(format: "%.1f", bmiValue?.value ?? 0.0 )
return bmi
}
mutating func calculate_Bmi(weight:Float,height:Float){
let bmival = weight / (height * height)
if bmival < 18.5{
bmiValue = bmi_category(value: bmival, advice: " Hey please! eat more", color: #colorLiteral(red: 0.9450980392, green: 0.768627451, blue: 0.05882352941, alpha: 1))
}else if bmival < 24.9{
bmiValue = bmi_category(value: bmival, advice: "Hey congrats you are healthy keep it up!", color: #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1))
}else{
bmiValue = bmi_category(value: bmival, advice: " hey you are Overweight please do some excercise", color: #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1))
}
}
func getcolor() -> UIColor{
return bmiValue?.color ?? #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
func getadvice() -> String{
return bmiValue?.advice ?? "No Advice"
}
}
| true
|
258821600cbe7bc0c68cdc9c0224f87003106c9d
|
Swift
|
abhinavroy23/Leetcode-Swift
|
/Easy/238. Product of Array Except Self.playground/Contents.swift
|
UTF-8
| 1,181
| 3.515625
| 4
|
[] |
no_license
|
import UIKit
/*
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
*/
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
guard nums.count > 0 else{
return nums
}
var prod : [Int] = Array(repeating: 1, count: nums.count)
var temp : Int = 1
for i in 0..<nums.count{
prod[i] = temp
temp = temp * nums[i]
}
temp = 1
for i in stride(from: nums.count-1, through: 0, by: -1){
prod[i] = prod[i] * temp
temp = temp * nums[i]
}
return prod
}
}
| true
|
a5b3da25c1212703ac8bf670494642fba2324795
|
Swift
|
vidovalianto/InstagramLikeSwiftUI
|
/InstaLikeApplication/InstaLikeApplication/Model/PostNetworkRespond.swift
|
UTF-8
| 1,347
| 2.921875
| 3
|
[] |
no_license
|
//
// NetworkRespond.swift
// InstaLikeApplication
//
// Created by Vido Valianto on 6/16/19.
// Copyright © 2019 Vido Valianto. All rights reserved.
//
import Foundation
import Foundation
import SwiftUI
final class PostNetworkRespond: Codable, Identifiable {
let id: String
let author: String
let width: Int
let url: URL
let downloadUrl: URL
var image: UIImage?
enum CodingKeys: String, CodingKey {
case id, author, width, url
case downloadUrl = "download_url"
}
init(id: String, author: String, width: Int, url: URL, downloadUrl: URL, image: UIImage) {
self.id = id
self.author = author
self.width = width
self.url = url
self.downloadUrl = downloadUrl
self.image = image
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.author = try container.decode(String.self, forKey: .author)
self.width = try container.decode(Int.self, forKey: .width)
self.url = try container.decode(URL.self, forKey: .url)
self.downloadUrl = try container.decode(URL.self, forKey: .downloadUrl)
let data = try Data(contentsOf: self.downloadUrl)
self.image = UIImage(data: data)
}
}
| true
|
1ce1f8fcf9e642d5e083373df94f5a82bf7c8e5b
|
Swift
|
tapwork/swiftui-tips
|
/Cocoaheads2/6./StateObject.swift
|
UTF-8
| 919
| 3.4375
| 3
|
[
"MIT"
] |
permissive
|
//
// StateObject.swift
// Cocoaheads2
//
// Created by Christian Menschel on 24.09.20.
//
import SwiftUI
import Combine
struct StateObjectDemo: View {
@State private var items = ["Hello"]
var body: some View {
VStack(spacing: 20) {
Counter()
Button("Update List") {
items.append("World")
}
List(items, id: \.self) { name in
Text(name)
}
}
}
}
struct Counter: View {
@StateObject var dataSource = DataSource()
// @ObservedObject var dataSource = DataSource()
init() {
print("Created Counter")
}
var body: some View {
VStack {
Button("Increment counter") {
dataSource.counter += 1
}
Text("Count is \(dataSource.counter)")
}
}
}
class DataSource: ObservableObject {
@Published var counter = 0
}
| true
|
bbce8b6cad362501f26f6bd4bea3c78f27d03d18
|
Swift
|
akshitzaveri/CodilityLessons
|
/CodilityLessons/Lesson3-Time Complexity/FrogJmp.swift
|
UTF-8
| 342
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// FrogJmp.swift
// CodilityLessons
//
// Created by Akshit Zaveri on 04/06/19.
// Copyright © 2019 Akshit Zaveri. All rights reserved.
//
import Foundation
final class FrogJmp {
public func solution(_ X : Int, _ Y : Int, _ D : Int) -> Int {
let steps = (Double(Y - X) / Double(D)).rounded(.up)
return Int(steps)
}
}
| true
|
f6ead303380d096ec92b67474421471d40902609
|
Swift
|
sudiptasahoo/Swippy-iOS
|
/Swippy/Source/Module/PaymentCards/Protocols/PaymentCardsProtocols.swift
|
UTF-8
| 2,606
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//
// PaymentCardsProtocols.swift
// Swippy
//
// Created by Sudipta Sahoo on 03/01/20.
// Copyright © 2020 Sudipta Sahoo. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
enum ViewState : Equatable {
case none
case loading
case content
case error(message: String)
}
//MARK: View
protocol PaymentCardsViewInput: AnyObject {
/// Refreshes the search screen UI
/// - Parameter state: intended view state
func updateViewState(with state: ViewState)
/// Insert Cards at specified index path of tableview
/// - Parameter indexPaths: list of index paths to be inserted at
func insertCards(at indexPaths: [IndexPath])
}
//MARK: Presenter
protocol PaymentCardsViewOutput: AnyObject {
/// The single source of truth about the current state
var pCardViewModel: PCardViewModel { get }
/// Fetches cards from the Presenter
func fetchCards()
/// Card was tapped by the user
/// - Parameter index: the index location of the card
func viewCardDetails(at index: Int)
/// Pay Now was tapped for the card
/// - Parameter index: the index location of the card
func payNowCard(at index: Int)
///View Last Statement tapped on the card
/// - Parameter index: the index location of the card
func viewLastStatement(at index: Int)
///Add New card button tapped by the user
func addNewCardTapped()
}
protocol PaymentCardsModuleInput: AnyObject {
//MARK: Presenter Variables
var view: PaymentCardsViewInput? { get set }
var interactor: PaymentCardsInteractorInput! { get set }
var router: PaymentCardsRouterInput! { get set }
}
//MARK: Interactor
protocol PaymentCardsInteractorInput: AnyObject {
///Fetch new/next set of Payment Cards from the server
func fetchCards(from page: Int) -> Observable<PCardResponse>
}
//MARK: Router
protocol PaymentCardsRouterInput: AnyObject {
///Pay now using the selected card
/// - Parameter card: the payment card selected by the user
func payNow(with card: PCard)
///View details of the selected card
/// - Parameter card: the payment card selected by the user
func viewDetails(of card: PCard)
///View last statement details of the selected card
/// - Parameter card: the payment card selected by the user
func viewLastStatment(of card: PCard)
///Routes to Add New payment card module
func addNewCard()
}
//MARK: PaymentCardsModuleBuilder
protocol PaymentCardsBuilder {
static func buildModule() -> PaymentCardsViewController
}
| true
|
0eabeeb5128352255f4a626f807a84ea8066a440
|
Swift
|
hoofsc/campsites_ios
|
/Campsites/Campsites/Models/Camper.swift
|
UTF-8
| 2,536
| 3.046875
| 3
|
[] |
no_license
|
//
// Camper.swift
// Campsites
//
// Created by DH on 11/7/19.
// Copyright © 2019 Retinal Media. All rights reserved.
//
import Foundation
import CoreLocation
struct Camper: Codable, Identifiable, Equatable {
let id: String
let firstName: String
let lastName: String
let phone: String
var location: CLLocation
public enum CodingKeys: String, CodingKey {
case id
case firstName = "first_name"
case lastName = "last_name"
case phone
case location
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
firstName = try container.decode(String.self, forKey: .firstName)
lastName = try container.decode(String.self, forKey: .lastName)
phone = try container.decode(String.self, forKey: .phone)
let locationContainer = try container.nestedContainer(keyedBy: CLLocation.CodingKeys.self, forKey: .location)
let latitude = try locationContainer.decode(CLLocationDegrees.self, forKey: .latitude)
let longitude = try locationContainer.decode(CLLocationDegrees.self, forKey: .longitude)
let altitude = try locationContainer.decode(CLLocationDistance.self, forKey: .altitude)
let horizontalAccuracy = try locationContainer.decode(CLLocationAccuracy.self, forKey: .horizontalAccuracy)
let verticalAccuracy = try locationContainer.decode(CLLocationAccuracy.self, forKey: .verticalAccuracy)
let speed = try locationContainer.decode(CLLocationSpeed.self, forKey: .speed)
let course = try locationContainer.decode(CLLocationDirection.self, forKey: .course)
let timestamp = try locationContainer.decode(Date.self, forKey: .timestamp)
location = CLLocation(coordinate: CLLocationCoordinate2DMake(latitude, longitude),
altitude: altitude,
horizontalAccuracy: horizontalAccuracy,
verticalAccuracy: verticalAccuracy,
course: course,
speed: speed,
timestamp: timestamp)
}
init(id: String, firstName: String, lastName: String, phone: String, location: CLLocation) {
self.id = id
self.firstName = firstName
self.lastName = lastName
self.phone = phone
self.location = location
}
}
| true
|
8cc4a3bb52108bb932bd0cfcd442c7c7b7afe642
|
Swift
|
Oleygen/SpritesheetCutter
|
/SpritesheetCutter/SpritesheetCutter/Extensions.swift
|
UTF-8
| 1,637
| 2.921875
| 3
|
[] |
no_license
|
//
// Extensions.swift
// SpritesheetCutter
//
// Created by oleygen ua on 11/18/18.
// Copyright © 2018 oleygen. All rights reserved.
//
import Foundation
import Cocoa
extension NSTextField
{
var cgfloat : CGFloat?
{
let string = self.stringValue
if let double = Double(string)
{
let cgfloat = CGFloat(double)
return cgfloat
}
else
{
return nil
}
}
}
extension NSImageView
{
var renderedImageSize : CGSize
{
let originalSize = self.image!.size
switch self.imageScaling {
case .scaleNone:
return originalSize
case .scaleAxesIndependently:
let sx = self.frame.size.width / originalSize.width
let sy = self.frame.size.height / originalSize.height
return CGSize(width: originalSize.width * sx, height: originalSize.height * sy)
case .scaleProportionallyDown, .scaleProportionallyUpOrDown:
#warning ("this part is incorrect")
let sx = self.frame.size.width / originalSize.width
let sy = self.frame.size.height / originalSize.height
return CGSize(width: originalSize.width * sx, height: originalSize.height * sy)
}
}
}
extension NSImage
{
var pngData :Data
{
let imgData = self.tiffRepresentation
let imageRep = NSBitmapImageRep(data: imgData!)
let imageProps = [NSBitmapImageRep.PropertyKey.compressionFactor:1.0]
return imageRep!.representation(using: NSBitmapImageRep.FileType.png, properties: imageProps)!
}
}
| true
|
17fcaac5441225823c298c8ef0785876c0df762a
|
Swift
|
akuzminskyi/FlickrSampleApp
|
/FlickrSampleApp/Services/Network/NetworkProvider/URLSession+NetworkProviderInterface.swift
|
UTF-8
| 1,322
| 2.8125
| 3
|
[] |
no_license
|
//
// URLSession+NetworkProviderInterface.swift
// FlickrSampleApp
//
// Created by Andrii Kuzminskyi on 27/04/2019.
// Copyright © 2019 akuzminskyi. All rights reserved.
//
import Foundation
extension URLSession: NetworkProviderInterface {
func downloadData(
from url: URL,
timeout: TimeInterval,
completionHandler: @escaping (Result<Data, Error>) -> Void
) {
var request = URLRequest(
url: url,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: timeout
)
request.httpMethod = HTTPMethod.get.stringValue
let dataTask = self.dataTask(with: request) { [] (data, _, error) in
guard let data = data, error == nil else {
completionHandler(.failure(error ?? NetworkError.unexpectedError))
return
}
completionHandler(.success(data))
}
dataTask.resume()
}
// MARK: - private methods
private func networkDomainError(withLocalizedDescription localizedDescription: String) -> Error {
let domainError = [Bundle.main.bundleIdentifier, "network"].compactMap { $0 }.joined(separator: ".")
return NSError(domain: domainError, code: -1, userInfo: [NSLocalizedDescriptionKey: localizedDescription])
}
}
| true
|
127dcc73074a45a94f0e83a248f979852c8efff3
|
Swift
|
blkbrds/intern16-practice
|
/03_SwiftOOP/ChungPhamV/BaiTap07.playground/Contents.swift
|
UTF-8
| 1,422
| 3.375
| 3
|
[] |
no_license
|
//import UIKit
class HocSinh{
var hoTen :String
var namSinh: Int
var tong : Double
init(hoTen: String, namSinh: Int, tong : Double) {
self.hoTen = hoTen
self.namSinh = namSinh
self.tong = tong
}
func inDanhSach() -> String {
return "Ho ten: \(hoTen.vietHoa()), nam sinh: \(namSinh), tong: \(tong)"
}
}
extension String {
func vietHoa() -> String {
guard let kiTuDau = first, kiTuDau.isLowercase else { return self }
return String(kiTuDau).uppercased() + dropFirst()
}
}
extension Array where Element: HocSinh{
func bubbleSapXepHS() -> [HocSinh]{
var listHS : [HocSinh] = self
listHS.sort { (hocSinh1, hocSinh2) -> Bool in
if hocSinh1.tong == hocSinh2.tong {
return hocSinh1.namSinh < hocSinh2.namSinh
} else {
return hocSinh1.tong > hocSinh2.tong
}
}
return listHS
}
func inDsHocSinh() {
let listHS : [HocSinh] = self
for i in 0..<listHS.count {
print(listHS[i].inDanhSach())
}
}
}
var listHS: [HocSinh] = [HocSinh(hoTen: "chung", namSinh: 92, tong: 9), HocSinh(hoTen: "van", namSinh: 93, tong: 9), HocSinh(hoTen: "pham", namSinh: 93, tong: 8), HocSinh(hoTen: "nguye", namSinh: 92, tong: 10)
]
print("Sap xep danh sach")
var dsHS = listHS.bubbleSapXepHS()
dsHS.inDsHocSinh()
| true
|
299d014063202ff1da59ca52234c180394ee04f6
|
Swift
|
nishirken/Swift
|
/FirstTask/MainView.swift
|
UTF-8
| 2,630
| 2.640625
| 3
|
[] |
no_license
|
//
// MainView.swift
// First Task
//
// Created by Дмитрий Скурихин on 01.02.2019.
// Copyright © 2019 Дмитрий Скурихин. All rights reserved.
//
import UIKit
class MainView: UIView {
public static let sidePadding = 16
public static let topPadding = 32
public static let bottomPadding = 16
public static let resultLabelHeight = 60
public static let labelFontSize = 17
public static let fullWidth: Int = {
return Int(UIScreen.main.bounds.width) - MainView.sidePadding * 2
}()
public var firstOperandView: FirstOperandView!
public var secondOperandView: SecondOperandView!
let calculateButton: UIButton = {
let button = UIButton(type: .custom)
button.setTitle("Calculate", for: .normal)
button.backgroundColor = UIColor(named: "Primary")
button.setTitleColor(.white, for: .normal)
let buttonHeight = 60
let y = Int(UIScreen.main.bounds.height) - MainView.bottomPadding - buttonHeight
button.frame = CGRect(x: MainView.sidePadding, y: y, width: MainView.fullWidth, height: 60)
return button
}()
let resultLabel: UILabel = {
let label = UILabel()
label.backgroundColor = UIColor(named: "InputBackground")
label.textColor = .black
label.textAlignment = .right
label.font = UIFont(name: label.font.fontName, size: 32)
label.frame = CGRect(x: MainView.sidePadding, y: MainView.topPadding, width: MainView.fullWidth, height: 60)
return label
}()
private func styleMainView() {
self.backgroundColor = UIColor(named: "Background")
}
override init(frame: CGRect) {
super.init(frame: frame)
self.styleMainView()
self.addSubview(self.resultLabel)
self.addSubview(self.calculateButton)
self.firstOperandView = FirstOperandView(frame: CGRect(
x: MainView.sidePadding,
y: MainView.topPadding + MainView.resultLabelHeight + 32,
width: MainView.fullWidth,
height: 17 + 16 + FirstOperandView.segmentedControlHeight
))
self.addSubview(self.firstOperandView)
self.secondOperandView = SecondOperandView(frame: CGRect(
x: MainView.sidePadding,
y: MainView.topPadding + MainView.resultLabelHeight + 32 + Int(firstOperandView.bounds.height) + 32,
width: MainView.fullWidth,
height: 17 + 16 + SecondOperandView.sliderHeight
))
self.addSubview(self.secondOperandView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| true
|
59fc7b878e3e1c4af9e59d6cf8d7bcb32ef3928b
|
Swift
|
a841223o/EasyAction
|
/EasyAction/Classes/Target.swift
|
UTF-8
| 1,216
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//
// Target.swift
// EasyAction
//
// Created by DongLunYou on 2019/6/3.
//
import Foundation
import UIKit
public class Target {
var action : Action?
var control : UIControl
var event : UIControl.Event
init(control : UIControl , event : UIControl.Event , action : Action? = nil) {
self.action = action
self.control = control
self.event = event
start()
}
public func start(){
control.addTarget(self, action: #selector(handleFunc), for: event)
}
public func stop(){
control.removeTarget(self, action: #selector(handleFunc), for: event)
}
@objc func handleFunc(){
guard let action = self.action else {
return
}
action()
}
}
class TargetManager {
public static let shareInstanced = TargetManager()
var targets : [Target] = []
@discardableResult
func createTarget(action: @escaping ()->Void , uiControl: UIControl, event: UIControl.Event)->Target{
let target = Target(control: uiControl, event: event,action:action)
addTarget(target: target)
return target
}
func addTarget(target : Target){
targets.append(target)
}
}
| true
|
1573210d3364fbdcc8f3c331f9dee0258efef4e5
|
Swift
|
RobinDeBock/phone-library
|
/PhoneLibrary/Other controllers/DeviceNetworkController.swift
|
UTF-8
| 6,181
| 2.96875
| 3
|
[] |
no_license
|
//
// DeviceNetworkController.swift
// PhoneLibrary
//
// Created by Robin De Bock on 20/12/2018.
// Copyright © 2018 Robin De Bock. All rights reserved.
//
import Foundation
import Alamofire
class DeviceNetworkController {
static let instance:DeviceNetworkController = DeviceNetworkController()
private let baseURL = URL(string: "https://fonoapi.freshpixl.com/v1/")!
private struct PropertyKeys {
static let DevicesByBrandPathComponent = "getlatest"
static let DevicesByNamePathComponent = "getdevice"
}
enum NetworkError : Error {
case InvalidApiKey
case EmptyApiKey
}
//Check if internet connection is available
var isConnected:Bool {
return NetworkReachabilityManager()!.isReachable
}
//Execute the URLSession datatask with the complete URL
private func executeUrlSessionDataTask(with url:URL, completion: @escaping ([Device]?, NetworkError?) -> Void){
if !isConnected{
//No internet connection
print("ERROR: no internet connection")
completion(nil, nil)
return
}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
//Check for error
guard error == nil else{
print(error!.localizedDescription)
completion(nil, nil)
return
}
let jsonDecoder = JSONDecoder()
if let data = data, let devices = try? jsonDecoder.decode([Device].self, from: data){
completion(devices, nil)
return
}
//Something went wrong
//Check if data is an empty 2-dimensional array (aka Json="[[]]")
//Only if all requirements are met we know there is an empty array
if let parsedData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments), let dataArray = parsedData as? [[Any]]{
if dataArray.count == 1, dataArray[0].isEmpty{
//return an empty list
completion([], nil)
return
}
}
if let data = data, let errorMessage = try? jsonDecoder.decode(ErrorResult.self, from: data){
if errorMessage.message.contains("No Matching Results Found"){
completion([], nil)
return
}
if errorMessage.message.contains("Invalid or Blocked Token"){
completion(nil, NetworkError.InvalidApiKey)
return
}
//A different error message was sent
print("ERROR: \(errorMessage.message)")
completion(nil, nil)
return
}
//Result sets were not empty, something went wrong in decoding
print("ERROR: Data was not correctly serialized")
completion(nil, nil)
return
}
task.resume()
}
func fetchDevicesByBrand(_ brand:String, completion: @escaping([Device]?, NetworkError?) -> Void) {
let token = AppSettingsController.instance.networkApiKey
//Check API token
guard !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else{
//No api token specified
completion(nil, NetworkError.EmptyApiKey)
return
}
//Adding path to base URL
let url = baseURL.appendingPathComponent(PropertyKeys.DevicesByBrandPathComponent)
//Define the query
let query: [String: String] = [
"token": token,
"brand": brand
]
//Adding the queries to the URL
guard let completeUrl = url.withQueries(query) else {
completion(nil, nil)
print("ERROR: Unable to build URL with supplied queries.")
return
}
//Callback function to fetch phones with the complete URL
executeUrlSessionDataTask(with: completeUrl){(devices, error) in
completion(devices, error)
}
}
func fetchDevicesByName(_ name:String, completion: @escaping([Device]?, NetworkError?) -> Void) {
let token = AppSettingsController.instance.networkApiKey
//Check API token
guard !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else{
//No api token specified
completion(nil, NetworkError.EmptyApiKey)
return
}
//Adding path to base URL
let url = baseURL.appendingPathComponent(PropertyKeys.DevicesByNamePathComponent)
//Define the query
let query: [String: String] = [
"token": token,
"device": name
]
//Adding the queries to the URL
guard let completeUrl = url.withQueries(query) else {
completion(nil, nil)
print("ERROR: Unable to build URL with supplied queries.")
return
}
//Callback function to fetch phones with the complete URL
executeUrlSessionDataTask(with: completeUrl){(devices, error) in
completion(devices, error)
}
}
}
//ErrorResult class
extension DeviceNetworkController{
class ErrorResult:Decodable{
var status:String
var message:String
var innerException:String
required init(from decoder: Decoder) throws {
let valueContainer = try decoder.container(keyedBy:CodingKeys.self)
self.status = (try? valueContainer.decode(String.self, forKey: CodingKeys.status)) ?? ""
self.message = (try? valueContainer.decode(String.self, forKey: CodingKeys.message)) ?? ""
self.innerException = (try? valueContainer.decode(String.self, forKey: CodingKeys.innerException)) ?? ""
}
enum CodingKeys: String, CodingKey {
case status
case message
case innerException
}
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.