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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
35c022c00f5ebd719dba5558a403f29ae3729420
|
Swift
|
nperera0/Contacts-iOS-App
|
/Contacts/ContactViewController.swift
|
UTF-8
| 1,062
| 2.765625
| 3
|
[] |
no_license
|
//
// ContactViewController.swift
// Contacts
//
// Created by Nisal Perera on 2015-10-05.
// Copyright © 2015 Nisal Perera. All rights reserved.
//
import UIKit
class ContactViewController: UIViewController {
@IBOutlet var nameLabel:UILabel!
@IBOutlet var ageLabel:UILabel!
@IBOutlet var genderLabel:UILabel!
@IBOutlet var phoneNumberLabel:UILabel!
@IBOutlet var addressLabel:UILabel!
var contact:Contact?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
guard let person = self.contact else {
return
}
nameLabel.text = person.name
ageLabel.text = "Age: \(person.age)"
if person.gender == .Male { // .Male same as Gender.Male
genderLabel.text = "M"
}
else {
genderLabel.text = "F"
}
}
}
| true
|
caf70415df6487f5c9562fdba2b9330b1df0816d
|
Swift
|
GalaxyExplosion/Algorithmes
|
/code/Array/ContainsDuplicate.swift
|
UTF-8
| 497
| 2.6875
| 3
|
[] |
no_license
|
//
// ContainsDuplicate.swift
// test
//
// Created by huochaihy on 2018/7/31.
// Copyright © 2018年 huochaihy. All rights reserved.
//
import UIKit
class ContainsDuplicate: NSObject {
func containsDuplicate(_ nums: [Int]) -> Bool {
var set = Set<Int>();
for i in 0..<nums.count {
if (!set.contains(nums[i])) {
set.update(with:nums[i]);
} else {
return true;
}
}
return false;
}
}
| true
|
c843051df6441e5cc8dbd263aa0bbd699ed1821d
|
Swift
|
joao-parana/Exemplo003
|
/Exemplo003Tests/Exemplo003Tests.swift
|
UTF-8
| 1,734
| 2.765625
| 3
|
[] |
no_license
|
//
// Exemplo003Tests.swift
// Exemplo003Tests
//
// Created by Joao Ferreira on 9/30/14.
// Copyright (c) 2014 si. All rights reserved.
//
import UIKit
import XCTest
import Exemplo003
class Exemplo003Tests: XCTestCase {
// Para execução de cada método de teste é criado uma instancia de Firewood
let firewood = Firewood()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of
// each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation
// of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
func test_1_Shouldnt_be_charred_before_burning_on_first_time() {
println("testing that we have a new object in 1st test")
assert(!firewood.charred, "shouldn’t be charred before burning")
firewood.burn()
}
func test_2_Shouldnt_be_charred_before_burning() {
println("testing that we have a new object in 2nd test")
assert(!firewood.charred, "shouldn’t be charred before burning")
firewood.burn()
}
func test_3_Should_be_charred_after_burning() {
firewood.burn()
// a madeira deve estar carbonizada após a queima (incendio)
assert(firewood.charred, "should be charred after burning")
}
}
| true
|
a7aa8783648ab6cdb8ad800733ed2500bdb7c9b8
|
Swift
|
pigmasha/test
|
/loc11/Source/ShiftHH/all_shifts/ShiftHH+w0.swift
|
UTF-8
| 27,594
| 2.59375
| 3
|
[] |
no_license
|
//
// Created by M on 11.06.2022.
//
import Foundation
extension ShiftHH {
func shiftW0(_ label: String) -> Bool {
if shiftDeg > 3 { return false }
switch label {
case "w1":
if shiftDeg < 5 {
shiftDeg % 2 == 0 ? shiftW1Even() : shiftW1Odd()
}
return true
case "w2":
if shiftDeg < 5 {
shiftDeg % 2 == 0 ? shiftW2Even() : shiftW2Odd()
}
return true
case "w1'":
if shiftDeg < 5 {
shiftDeg % 2 == 0 ? shiftW1iEven() : shiftW1iOdd()
}
return true
case "w2'":
if shiftDeg < 5 {
shiftDeg % 2 == 0 ? shiftW2iEven() : shiftW2iOdd()
}
return true
default:
return false
}
}
enum KWMode {
case minus1, minus2, zero
var val: Int {
switch self {
case .minus1: return -1
case .minus2: return -2
case .zero: return 0
}
}
}
func w0(leftType: ArrType, leftFrom: Int, kMode: KWMode = .minus1) -> Comb? {
let k = PathAlg.kk
if kMode == .minus2 && k < 4 { return nil }
let kTo: Int
switch kMode {
case .minus1: kTo = k / 2 - 1
case .minus2: kTo = k / 2 - 2
case .zero: kTo = k / 2
}
let rightType = leftFrom % 2 == 0 ? leftType.next : leftType
var label = "\\sum\\limits_{i=0}^{" + (k % 2 == 0 ? "k/2" : "(k-1)/2")
switch kMode {
case .minus1: label += "-1"
case .minus2: label += "-2"
case .zero: break
}
label += "}"
if leftFrom % 2 == 0 {
label += "(" + leftType.str + leftType.next.str + ")^{2i" + (leftFrom == 0 ? "" : "+\(leftFrom/2)") + "}"
} else {
label += leftType.str + "(" + leftType.next.str + leftType.str + ")^{2i" + (leftFrom == 1 ? "" : "+\(leftFrom/2)") + "}"
}
label += "\\otimes "
if leftFrom % 2 == 1 {
label += "(" + rightType.str + rightType.next.str + ")^{k-2i-\((leftFrom+1)/2)}"
} else {
label += rightType.str + "(" + rightType.next.str + rightType.str + ")^{k-2i-\((leftFrom+2)/2)}"
}
let c = PathAlg.isTex ? Comb(label: label) : Comb()
for i in 0 ... kTo {
c.add(comb: Comb(left: Way(type: leftType, len: 4 * i + leftFrom),
right: Way(type: rightType, len: 2 * (k - 2 * i) - 1 - leftFrom),
label: ""))
}
if !PathAlg.isTex { c.updateLabel() }
return c
}
func w01(leftType: ArrType, leftFrom: Int, rightMode: KWMode, kMode: KWMode = .minus1, label ll: String? = nil) -> Comb? {
let k = PathAlg.kk
if kMode == .minus2 && k < 4 { return nil }
let kTo = k / 2 + kMode.val
let rightType = leftFrom % 2 == 0 ? leftType.next : leftType
var label = "\\sum\\limits_{i=0}^{" + (k % 2 == 0 ? "k/2" : "(k-1)/2") + (kMode.val == 0 ? "" : "\(kMode.val)")
label += "}"
if leftFrom % 2 == 0 {
label += "(" + leftType.str + leftType.next.str + ")^{2i" + (leftFrom == 0 ? "" : "+\(leftFrom/2)") + "}"
} else {
label += leftType.str + "(" + leftType.next.str + leftType.str + ")^{2i" + (leftFrom == 1 ? "" : "+\(leftFrom/2)") + "}"
}
label += "\\otimes "
if leftFrom % 2 == 0 {
label += "(" + rightType.str + rightType.next.str + ")^{k-2i-\(leftFrom/2-rightMode.val)}"
} else {
label += rightType.str + "(" + rightType.next.str + rightType.str + ")^{k-2i-\((leftFrom+1)/2-rightMode.val)}"
}
let c = PathAlg.isTex ? Comb(label: ll ?? label) : Comb()
for i in 0 ... kTo {
c.add(comb: Comb(left: Way(type: leftType, len: 4 * i + leftFrom),
right: Way(type: rightType, len: 2 * (k - 2 * i + rightMode.val) - leftFrom),
label: ""))
}
if !PathAlg.isTex { c.updateLabel() }
if PathAlg.isTex, let ll = ll {
OutputFile.writeLog(.normal, "$$"+ll+"="+label+"$$")
}
return c
}
func addW0(row: Int, col: Int, leftType: ArrType, leftFrom: Int, kMode: KWMode = .minus1) {
w0(leftType: leftType, leftFrom: leftFrom, kMode: kMode).flatMap {
matrix.rows[row][col].add(comb: $0)
}
}
// MARK: - w1
private func shiftW1Even() {
switch shiftDeg {
case 0:
matrix.rows[0][0].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[0][3].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
case 2:
matrix.rows[0][0].add(comb: SearchForMult.ex)
matrix.rows[1][0].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[2][0].add(comb: Comb(left: Way.wy, right: Way.zx, label: ""))
matrix.rows[1][1].add(comb: Comb(left: Way.wx, right: Way.zy, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.zy, right: Way.e, label: ""))
matrix.rows[1][2].add(comb: SearchForMult.ex)
matrix.rows[1][2].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[0][3].add(comb: Comb(left: Way.x, right: Way.wy, label: ""))
matrix.rows[0][4].add(comb: SearchForMult.ex)
matrix.rows[1][4].add(comb: SearchForMult.ex)
case 4:
matrix.rows[0][0].add(comb: SearchForMult.ex)
matrix.rows[1][0].add(comb: SearchForMult.delta(way: Way.x))
matrix.rows[2][0].add(comb: Comb(left: Way.wy, right: Way.zx, label: ""))
matrix.rows[0][1].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
matrix.rows[3][1].add(comb: Comb(left: Way.wx, right: Way.zy, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.zy, right: Way.e, label: ""))
matrix.rows[3][2].add(comb: Comb(left: Way.zy, right: Way.e, label: ""))
matrix.rows[0][3].add(comb: Comb(left: Way.wx, right: Way.x, label: ""))
matrix.rows[1][4].add(comb: Comb(left: Way.zy, right: Way.e, label: ""))
matrix.rows[1][4].add(comb: SearchForMult.ex)
matrix.rows[3][4].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[3][4].add(comb: SearchForMult.ex)
matrix.rows[0][5].add(comb: Comb(left: Way.wx, right: Way.x, label: ""))
matrix.rows[1][6].add(comb: SearchForMult.ex)
matrix.rows[3][6].add(comb: SearchForMult.ex)
default:
break
}
}
private func shiftW1Odd() {
addW0(row: 0, col: 0, leftType: .x, leftFrom: 0)
addW0(row: 0, col: 0, leftType: .y, leftFrom: 1)
matrix.rows[0][3].add(comb: SearchForMult.ex)
switch shiftDeg {
case 1:
addW0(row: 1, col: 0, leftType: .y, leftFrom: 0)
addW0(row: 1, col: 0, leftType: .x, leftFrom: 3)
matrix.rows[0][1].add(comb: SearchForMult.ex)
matrix.rows[0][1].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.y, right: Way.wy, label: ""))
matrix.rows[1][2].add(comb: SearchForMult.delta(way: Way.y))
addW0(row: 0, col: 3, leftType: .y, leftFrom: 1)
addW0(row: 1, col: 3, leftType: .y, leftFrom: 0)
addW0(row: 0, col: 4, leftType: .x, leftFrom: 4, kMode: .minus2)
matrix.rows[1][4].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
addW0(row: 1, col: 4, leftType: .x, leftFrom: 3)
case 3:
addW0(row: 1, col: 0, leftType: .y, leftFrom: 2)
addW0(row: 1, col: 0, leftType: .x, leftFrom: 1)
addW0(row: 0, col: 1, leftType: .y, leftFrom: 3, kMode: .minus2)
matrix.rows[1][1].add(comb: Comb(left: Way.zy, right: Way.wx, label: ""))
addW0(row: 1, col: 1, leftType: .y, leftFrom: 0)
matrix.rows[2][1].add(comb: SearchForMult.delta(way: Way.zy))
matrix.rows[2][1].add(comb: SearchForMult.delta(way: Way.x))
addW0(row: 0, col: 2, leftType: .x, leftFrom: 0)
addW0(row: 1, col: 2, leftType: .x, leftFrom: 1)
addW0(row: 0, col: 3, leftType: .y, leftFrom: 3)
matrix.rows[1][3].add(comb: Comb(left: Way.zy, right: Way.wx, label: ""))
addW0(row: 1, col: 3, leftType: .y, leftFrom: 4, kMode: .minus2)
matrix.rows[2][3].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[2][3].add(comb: SearchForMult.delta(way: Way.zy))
matrix.rows[0][4].add(comb: Comb(left: Way.y, right: Way.wy, label: ""))
addW0(row: 0, col: 4, leftType: .x, leftFrom: 4, kMode: .minus2)
addW0(row: 1, col: 4, leftType: .x, leftFrom: 1)
matrix.rows[0][5].add(comb: SearchForMult.ex)
addW0(row: 0, col: 5, leftType: .y, leftFrom: 3, kMode: .minus2)
addW0(row: 1, col: 5, leftType: .y, leftFrom: 4, kMode: .minus2)
matrix.rows[2][5].add(comb: SearchForMult.ex)
addW0(row: 0, col: 6, leftType: .x, leftFrom: 4, kMode: .minus2)
addW0(row: 1, col: 6, leftType: .x, leftFrom: 1)
default:
break
}
}
// MARK: - w2
private func shiftW2Even() {
switch shiftDeg {
case 0:
matrix.rows[0][1].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
case 2:
matrix.rows[1][0].add(comb: SearchForMult.delta(way: Way.zy))
matrix.rows[2][0].add(comb: Comb(left: Way.wy, right: Way.y, label: ""))
matrix.rows[2][0].add(comb: Comb(left: Way.y, right: Way.wx, label: ""))
matrix.rows[0][1].add(comb: SearchForMult.ey)
matrix.rows[2][1].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[0][2].add(comb: SearchForMult.ex)
matrix.rows[1][2].add(comb: Comb(left: Way.zy, right: Way.e, label: ""))
matrix.rows[2][2].add(comb: SearchForMult.delta(way: Way.x))
matrix.rows[2][2].add(comb: Comb(left: Way.y, right: Way.wx, label: ""))
matrix.rows[2][2].add(comb: Comb(left: Way.wy, right: Way.zx, label: ""))
matrix.rows[0][3].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
matrix.rows[2][3].add(comb: SearchForMult.ey)
matrix.rows[2][3].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[0][4].add(comb: SearchForMult.ex)
matrix.rows[1][4].add(comb: SearchForMult.ex)
matrix.rows[2][4].add(comb: SearchForMult.ex)
matrix.rows[0][5].add(comb: SearchForMult.ey)
matrix.rows[2][5].add(comb: SearchForMult.ey)
case 4:
matrix.rows[0][0].add(comb: SearchForMult.delta(way: Way.x))
matrix.rows[2][0].add(comb: Comb(left: Way.y, right: Way.wx, label: ""))
matrix.rows[2][0].add(comb: Comb(left: Way.wy, right: Way.y, label: ""))
matrix.rows[4][0].add(comb: Comb(left: Way.wy, right: Way.y, label: ""))
matrix.rows[4][0].add(comb: Comb(left: Way.y, right: Way.wx, label: ""))
matrix.rows[0][1].add(comb: SearchForMult.ey)
matrix.rows[2][1].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
matrix.rows[4][1].add(comb: SearchForMult.delta(way: Way.zx))
matrix.rows[0][2].add(comb: SearchForMult.ex)
matrix.rows[2][2].add(comb: Comb(left: Way.wy, right: Way.zx, label: ""))
matrix.rows[4][2].add(comb: SearchForMult.delta(way: Way.x))
matrix.rows[4][2].add(comb: Comb(left: Way.wy, right: Way.zx, label: ""))
matrix.rows[0][3].add(comb: SearchForMult.ey)
matrix.rows[1][3].add(comb: Comb(left: Way.zy, right: Way.wy, label: ""))
matrix.rows[4][3].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
matrix.rows[0][4].add(comb: SearchForMult.ex)
matrix.rows[0][4].add(comb: Comb(left: Way.y, right: Way.wx, label: ""))
matrix.rows[2][4].add(comb: Comb(left: Way.y, right: Way.wx, label: ""))
matrix.rows[4][4].add(comb: Comb(left: Way.y, right: Way.wx, label: ""))
matrix.rows[0][5].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
matrix.rows[1][5].add(comb: Comb(left: Way.zy, right: Way.wy, label: ""))
matrix.rows[2][5].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
matrix.rows[4][5].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[4][5].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
matrix.rows[0][6].add(comb: SearchForMult.ex)
matrix.rows[4][6].add(comb: SearchForMult.ex)
matrix.rows[4][7].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
default:
break
}
}
private func shiftW2Odd() {
switch shiftDeg {
case 1:
addW0(row: 0, col: 0, leftType: .x, leftFrom: 0)
addW0(row: 0, col: 0, leftType: .y, leftFrom: 3)
addW0(row: 1, col: 0, leftType: .y, leftFrom: 0)
addW0(row: 1, col: 0, leftType: .x, leftFrom: 1)
matrix.rows[1][1].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[1][1].add(comb: Comb(left: Way.x, right: Way.wx, label: ""))
matrix.rows[1][1].add(comb: SearchForMult.delta(way: Way.y))
matrix.rows[1][2].add(comb: SearchForMult.ey)
matrix.rows[1][2].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[0][3].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
addW0(row: 0, col: 3, leftType: .y, leftFrom: 3)
addW0(row: 0, col: 4, leftType: .x, leftFrom: 0)
matrix.rows[1][4].add(comb: SearchForMult.ey)
addW0(row: 1, col: 4, leftType: .x, leftFrom: 1)
addW0(row: 1, col: 3, leftType: .y, leftFrom: 4, kMode: .minus2)
case 3:
addW0(row: 0, col: 0, leftType: .x, leftFrom: 0)
addW0(row: 0, col: 0, leftType: .y, leftFrom: 3)
addW0(row: 1, col: 0, leftType: .x, leftFrom: 3)
addW0(row: 1, col: 0, leftType: .y, leftFrom: 2)
addW0(row: 0, col: 1, leftType: .y, leftFrom: 3, kMode: .minus2)
matrix.rows[1][1].add(comb: SearchForMult.ey)
addW0(row: 1, col: 1, leftType: .y, leftFrom: 2, kMode: .minus2)
matrix.rows[2][1].add(comb: SearchForMult.delta(way: Way.zy))
matrix.rows[3][1].add(comb: SearchForMult.delta(way: Way.y))
matrix.rows[3][1].add(comb: Comb(left: Way.x, right: Way.wx, label: ""))
matrix.rows[3][1].add(comb: Comb(left: Way.wy, right: Way.x, label: ""))
matrix.rows[3][1].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.wx, right: Way.zx, label: ""))
addW0(row: 0, col: 2, leftType: .x, leftFrom: 0)
addW0(row: 1, col: 2, leftType: .x, leftFrom: 3, kMode: .minus2)
matrix.rows[3][2].add(comb: SearchForMult.delta(way: Way.zx))
matrix.rows[3][2].add(comb: SearchForMult.delta(way: Way.y))
addW0(row: 0, col: 3, leftType: .y, leftFrom: 1)
addW0(row: 1, col: 3, leftType: .y, leftFrom: 0)
matrix.rows[2][3].add(comb: SearchForMult.delta(way: Way.x))
matrix.rows[3][3].add(comb: Comb(left: Way.x, right: Way.wx, label: ""))
matrix.rows[3][3].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[0][4].add(comb: Comb(left: Way.wx, right: Way.zx, label: ""))
addW0(row: 0, col: 4, leftType: .x, leftFrom: 4, kMode: .minus2)
matrix.rows[1][4].add(comb: SearchForMult.ey)
addW0(row: 1, col: 4, leftType: .x, leftFrom: 3)
matrix.rows[3][4].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
matrix.rows[3][4].add(comb: SearchForMult.delta(way: Way.zx))
addW0(row: 0, col: 5, leftType: .y, leftFrom: 3, kMode: .minus2)
addW0(row: 1, col: 5, leftType: .y, leftFrom: 2, kMode: .minus2)
matrix.rows[2][5].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[2][5].add(comb: Comb(left: Way.zy, right: Way.e, label: ""))
matrix.rows[3][5].add(comb: Comb(left: Way.wy, right: Way.x, label: ""))
addW0(row: 0, col: 6, leftType: .x, leftFrom: 4, kMode: .minus2)
matrix.rows[1][6].add(comb: SearchForMult.ey)
addW0(row: 1, col: 6, leftType: .x, leftFrom: 3, kMode: .minus2)
matrix.rows[3][6].add(comb: SearchForMult.ey)
default:
break
}
}
// MARK: - w1'
private func shiftW1iEven() {
matrix.rows[0][0].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
switch shiftDeg {
case 2:
matrix.rows[0][1].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
matrix.rows[2][1].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
matrix.rows[1][2].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[0][3].add(comb: Comb(left: Way.wx, right: Way.x, label: ""))
matrix.rows[2][3].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[0][4].add(comb: SearchForMult.ex)
matrix.rows[1][4].add(comb: SearchForMult.ex)
matrix.rows[0][5].add(comb: SearchForMult.ey)
case 4:
matrix.rows[1][1].add(comb: Comb(left: Way.zy, right: Way.wy, label: ""))
matrix.rows[2][1].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
matrix.rows[1][2].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[0][3].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[2][3].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[4][3].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[1][4].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[3][4].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[3][4].add(comb: SearchForMult.delta(way: Way.zy))
matrix.rows[0][5].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
matrix.rows[2][5].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
matrix.rows[2][5].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[3][6].add(comb: SearchForMult.ex)
matrix.rows[4][7].add(comb: SearchForMult.ey)
default:
break
}
}
private func shiftW1iOdd() {
switch shiftDeg {
case 1:
addW0(row: 0, col: 0, leftType: .y, leftFrom: 3)
addW0(row: 0, col: 0, leftType: .x, leftFrom: 2)
addW0(row: 1, col: 0, leftType: .x, leftFrom: 1, kMode: .zero)
addW0(row: 1, col: 0, leftType: .y, leftFrom: 2)
matrix.rows[0][1].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.y, right: Way.wy, label: ""))
matrix.rows[1][2].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
addW0(row: 0, col: 3, leftType: .y, leftFrom: 3)
addW0(row: 1, col: 3, leftType: .y, leftFrom: 2)
addW0(row: 0, col: 4, leftType: .x, leftFrom: 4)
addW0(row: 1, col: 4, leftType: .x, leftFrom: 3)
case 3:
matrix.rows[0][0].add(comb: Comb(left: Way.wx, right: Way.zx, label: ""))
addW0(row: 0, col: 0, leftType: .x, leftFrom: 2)
addW0(row: 0, col: 0, leftType: .y, leftFrom: 3)
addW0(row: 1, col: 0, leftType: .x, leftFrom: 1, kMode: .zero)
addW0(row: 1, col: 0, leftType: .y, leftFrom: 2)
matrix.rows[0][1].add(comb: Comb(left: Way.wx, right: Way.zx, label: ""))
matrix.rows[0][1].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
addW0(row: 0, col: 1, leftType: .y, leftFrom: 3)
matrix.rows[1][1].add(comb: Comb(left: Way.x, right: Way.wx, label: ""))
addW0(row: 1, col: 1, leftType: .y, leftFrom: 2)
addW0(row: 0, col: 2, leftType: .x, leftFrom: 2)
addW0(row: 1, col: 2, leftType: .x, leftFrom: 1, kMode: .zero)
matrix.rows[3][2].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
addW0(row: 0, col: 3, leftType: .y, leftFrom: 3)
addW0(row: 1, col: 3, leftType: .y, leftFrom: 2)
matrix.rows[2][3].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[2][3].add(comb: SearchForMult.delta(way: Way.zy))
matrix.rows[0][4].add(comb: Comb(left: Way.wx, right: Way.zx, label: ""))
matrix.rows[0][4].add(comb: Comb(left: Way.zy, right: Way.e, label: ""))
addW0(row: 0, col: 4, leftType: .x, leftFrom: 4, kMode: .minus2)
matrix.rows[1][4].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
addW0(row: 1, col: 4, leftType: .x, leftFrom: 3)
matrix.rows[3][4].add(comb: SearchForMult.delta(way: Way.y))
matrix.rows[0][5].add(comb: SearchForMult.ex)
addW0(row: 0, col: 5, leftType: .y, leftFrom: 1)
addW0(row: 1, col: 5, leftType: .y, leftFrom: 4)
matrix.rows[0][6].add(comb: Comb(left: Way.wx, right: Way.y, label: ""))
addW0(row: 0, col: 6, leftType: .x, leftFrom: 2)
matrix.rows[1][6].add(comb: SearchForMult.ey)
addW0(row: 1, col: 6, leftType: .x, leftFrom: 1)
default:
break
}
}
// MARK: - w2'
private func shiftW2iEven() {
matrix.rows[0][1].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
matrix.rows[0][3].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
switch shiftDeg {
case 2:
matrix.rows[0][0].add(comb: Comb(left: Way.zy, right: Way.e, label: ""))
matrix.rows[1][0].add(comb: Comb(left: Way.zy, right: Way.e, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.wy, right: Way.y, label: ""))
matrix.rows[1][2].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[2][3].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
matrix.rows[0][4].add(comb: SearchForMult.ex)
matrix.rows[0][5].add(comb: SearchForMult.ey)
matrix.rows[2][5].add(comb: SearchForMult.ey)
case 4:
matrix.rows[1][0].add(comb: Comb(left: Way.zy, right: Way.e, label: ""))
matrix.rows[2][0].add(comb: Comb(left: Way.zx, right: Way.wx, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[1][2].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[3][2].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[0][3].add(comb: Comb(left: Way.wx, right: Way.x, label: ""))
matrix.rows[2][3].add(comb: SearchForMult.ey)
matrix.rows[2][3].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[0][4].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[1][4].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
matrix.rows[1][4].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[2][5].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
matrix.rows[4][5].add(comb: SearchForMult.ey)
matrix.rows[4][5].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
matrix.rows[3][6].add(comb: SearchForMult.ex)
default:
break
}
}
private func shiftW2iOdd() {
switch shiftDeg {
case 1:
addW0(row: 0, col: 0, leftType: .y, leftFrom: 1, kMode: .zero)
addW0(row: 0, col: 0, leftType: .x, leftFrom: 2)
addW0(row: 1, col: 0, leftType: .x, leftFrom: 3)
addW0(row: 1, col: 0, leftType: .y, leftFrom: 2)
matrix.rows[0][1].add(comb: Comb(left: Way.e, right: Way.zy, label: ""))
matrix.rows[1][1].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[1][1].add(comb: Comb(left: Way.x, right: Way.wx, label: ""))
matrix.rows[1][2].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
addW0(row: 0, col: 3, leftType: .y, leftFrom: 3)
addW0(row: 1, col: 3, leftType: .y, leftFrom: 4)
addW0(row: 0, col: 4, leftType: .x, leftFrom: 2)
addW0(row: 1, col: 4, leftType: .x, leftFrom: 3)
case 3:
addW0(row: 0, col: 0, leftType: .x, leftFrom: 2)
addW0(row: 0, col: 0, leftType: .y, leftFrom: 1, kMode: .zero)
matrix.rows[1][0].add(comb: Comb(left: Way.wy, right: Way.zy, label: ""))
addW0(row: 1, col: 0, leftType: .x, leftFrom: 3)
addW0(row: 1, col: 0, leftType: .y, leftFrom: 2)
addW0(row: 0, col: 1, leftType: .y, leftFrom: 1, kMode: .zero)
addW0(row: 1, col: 1, leftType: .y, leftFrom: 2)
matrix.rows[2][1].add(comb: Comb(left: Way.zy, right: Way.e, label: ""))
matrix.rows[0][2].add(comb: Comb(left: Way.y, right: Way.wy, label: ""))
addW0(row: 0, col: 2, leftType: .x, leftFrom: 2)
matrix.rows[1][2].add(comb: Comb(left: Way.y, right: Way.e, label: ""))
matrix.rows[1][2].add(comb: Comb(left: Way.zy, right: Way.wx, label: ""))
addW0(row: 1, col: 2, leftType: .x, leftFrom: 3)
matrix.rows[0][3].add(comb: Comb(left: Way.x, right: Way.e, label: ""))
addW0(row: 0, col: 3, leftType: .y, leftFrom: 3)
matrix.rows[1][3].add(comb: Comb(left: Way.zx, right: Way.e, label: ""))
matrix.rows[1][3].add(comb: Comb(left: Way.wy, right: Way.zy, label: ""))
addW0(row: 1, col: 3, leftType: .y, leftFrom: 4, kMode: .minus2)
matrix.rows[2][3].add(comb: SearchForMult.delta(way: Way.x))
addW0(row: 0, col: 4, leftType: .x, leftFrom: 4)
matrix.rows[1][4].add(comb: SearchForMult.ey)
addW0(row: 1, col: 4, leftType: .x, leftFrom: 1)
matrix.rows[3][4].add(comb: SearchForMult.ey)
matrix.rows[3][4].add(comb: Comb(left: Way.e, right: Way.zx, label: ""))
matrix.rows[0][5].add(comb: SearchForMult.ex)
addW0(row: 0, col: 5, leftType: .y, leftFrom: 1)
matrix.rows[1][5].add(comb: Comb(left: Way.wy, right: Way.x, label: ""))
addW0(row: 1, col: 5, leftType: .y, leftFrom: 2)
addW0(row: 0, col: 6, leftType: .x, leftFrom: 4)
matrix.rows[1][6].add(comb: SearchForMult.ey)
addW0(row: 1, col: 6, leftType: .x, leftFrom: 1)
default:
break
}
}
}
| true
|
9ff100fe39e75e1b85d35bea28fbaa7f382627b0
|
Swift
|
LHMacCoder/Algorithm
|
/Algorithm/Algorithm/main.swift
|
UTF-8
| 8,844
| 2.890625
| 3
|
[] |
no_license
|
//
// main.swift
// Algorithm
//
// Created by LHMacCoder on 2021/7/5.
//
import Foundation
//var array = [2,3,5,1,7,44,6,8,456456,768678,2342,56758,24345,7564,-100,-999]
//print("bubble sort: \(bubbleSort(array))")
//print("selectionSort sort: \(selectionSort(array))")
//print("heapSort sort: \(heapSort(array))")
//print("insertion sort: \(insertionSort(array))")
//print("merge sort: \(mergeSort(array))")
//print("quick sort: \(quickSort(array))")
//print("shell sort: \(shellSort(array))")
//
//var union = UnionFind.init(capacity: 10)
//print("before union:")
//print(union!)
//union?.unionQF(value1: 1, value2: 0)
//print(union!)
//union?.unionQF(value1: 1, value2: 2)
//print(union!)
//union?.unionQF(value1: 3, value2: 4)
//print(union!)
//union?.unionQF(value1: 0, value2: 3)
//print(union!)
//var unionG = GenericUnionFind<Int>.init()
//unionG.makeNode(nodeValue: 0)
//unionG.makeNode(nodeValue: 1)
//unionG.makeNode(nodeValue: 2)
//unionG.makeNode(nodeValue: 3)
//unionG.makeNode(nodeValue: 4)
//unionG.makeNode(nodeValue: 5)
//unionG.makeNode(nodeValue: 6)
//unionG.makeNode(nodeValue: 7)
//unionG.makeNode(nodeValue: 8)
//unionG.makeNode(nodeValue: 9)
//print("before union:")
//print(unionG)
//unionG.union(lnv: 1, rnv: 0)
//print(unionG)
//unionG.union(lnv: 1, rnv: 2)
//print(unionG)
//unionG.union(lnv: 3, rnv: 4)
//print(unionG)
//unionG.union(lnv: 0, rnv: 3)
//print(unionG)
//let graph = Graph<String, Int>.init()
//graph.addEdge(from: "V1", to: "V0", weight: 9)
//graph.addEdge(from: "V1", to: "V2", weight: 3)
//graph.addEdge(from: "V2", to: "V3", weight: 5)
//graph.addEdge(from: "V3", to: "V4", weight: 1)
//graph.addEdge(from: "V2", to: "V0", weight: 2)
//graph.addEdge(from: "V0", to: "V4", weight: 6)
//graph.addVertex(vertex: "V5")
//graph.removeVertex(vertex: "V0")
//graph.graphPrint()
//graph.addEdge(from: "a", to: "V1", weight: 9)
//graph.addEdge(from: "V0", to: "V4", weight: 9)
//graph.addEdge(from: "V2", to: "V0", weight: 3)
//graph.addEdge(from: "V1", to: "V2", weight: 5)
//graph.addEdge(from: "V3", to: "V1", weight: 1)
//graph.addEdge(from: "V2", to: "V5", weight: 2)
//graph.addEdge(from: "V2", to: "V4", weight: 6)
//graph.addEdge(from: "V4", to: "V6", weight: 9)
//graph.addEdge(from: "V4", to: "V7", weight: 3)
//graph.addEdge(from: "V5", to: "V3", weight: 5)
//graph.addEdge(from: "V5", to: "V7", weight: 1)
//graph.addEdge(from: "V6", to: "V2", weight: 2)
//graph.addEdge(from: "V6", to: "V1", weight: 6)
//graph.bfs(vertex: "V0") {
// print($0)
// return false
//}
//let graph1 = Graph<Int, Int>.init()
//graph1.addEdge(from: 0, to: 1, weight: nil)
//graph1.addEdge(from: 1, to: 0, weight: nil)
//
//graph1.addEdge(from: 1, to: 2, weight: nil)
//graph1.addEdge(from: 2, to: 1, weight: nil)
//
//graph1.addEdge(from: 1, to: 3, weight: nil)
//graph1.addEdge(from: 3, to: 1, weight: nil)
//
//graph1.addEdge(from: 1, to: 5, weight: nil)
//graph1.addEdge(from: 5, to: 1, weight: nil)
//
//graph1.addEdge(from: 1, to: 6, weight: nil)
//graph1.addEdge(from: 6, to: 1, weight: nil)
//
//graph1.addEdge(from: 2, to: 4, weight: nil)
//graph1.addEdge(from: 4, to: 2, weight: nil)
//
//graph1.addEdge(from: 3, to: 7, weight: nil)
//graph1.addEdge(from: 7, to: 3, weight: nil)
//
//graph1.dfs(vertex: 1) {
// print($0)
// return false
//}
//let graph2 = Graph<String, Int>.init()
//graph2.addEdge(from: "a", to: "e")
//graph2.addEdge(from: "a", to: "b")
//graph2.addEdge(from: "b", to: "e")
//graph2.addEdge(from: "c", to: "b")
//graph2.addEdge(from: "d", to: "a")
//graph2.addEdge(from: "e", to: "c")
//graph2.addEdge(from: "e", to: "f")
//graph2.addEdge(from: "f", to: "c")
//graph2.dfs(vertex: "a") {
// print($0)
// return false
//}
//let graph = Graph<String, Int>.init()
//graph.addEdge(from: "A", to: "B")
//graph.addEdge(from: "A", to: "D")
//graph.addEdge(from: "B", to: "F")
//graph.addEdge(from: "C", to: "B")
//graph.addEdge(from: "C", to: "F")
//graph.addEdge(from: "E", to: "A")
//graph.addEdge(from: "E", to: "B")
//graph.addEdge(from: "E", to: "F")
//print(graph.topologicalSort())
//let heap = BinaryHeap<Int>.init()
//heap.add(element: 68)
//heap.add(element: 72)
//heap.add(element: 43)
//heap.add(element: 50)
//heap.add(element: 38)
//heap.heapPrint()
//heap.add(element: 100)
//heap.heapPrint()
//let top = heap.replae(element: 1)
//heap.heapPrint()
//print(top)
//let graph = Graph<Int, Int>.init()
//graph.addEdge(from: 0, to: 2, weight: 2)
//graph.addEdge(from: 0, to: 4, weight: 7)
//graph.addEdge(from: 2, to: 0, weight: 2)
//graph.addEdge(from: 2, to: 1, weight: 3)
//graph.addEdge(from: 2, to: 6, weight: 6)
//graph.addEdge(from: 2, to: 5, weight: 3)
//graph.addEdge(from: 2, to: 4, weight: 4)
//graph.addEdge(from: 2, to: 4, weight: 4)
//graph.addEdge(from: 1, to: 2, weight: 3)
//graph.addEdge(from: 1, to: 6, weight: 7)
//graph.addEdge(from: 1, to: 5, weight: 1)
//graph.addEdge(from: 4, to: 0, weight: 7)
//graph.addEdge(from: 4, to: 2, weight: 4)
//graph.addEdge(from: 4, to: 6, weight: 8)
//graph.addEdge(from: 6, to: 5, weight: 4)
//graph.addEdge(from: 6, to: 2, weight: 6)
//graph.addEdge(from: 6, to: 4, weight: 8)
//graph.addEdge(from: 6, to: 1, weight: 7)
//graph.addEdge(from: 5, to: 6, weight: 4)
//graph.addEdge(from: 5, to: 1, weight: 1)
//graph.addEdge(from: 5, to: 2, weight: 3)
//graph.addEdge(from: 5, to: 7, weight: 5)
//graph.addEdge(from: 7, to: 5, weight: 5)
//graph.addEdge(from: 7, to: 3, weight: 9)
//graph.addEdge(from: 3, to: 7, weight: 9)
//print(graph.prim())
//print(graph.kruskal())
//let graph = Graph<String, Int>.init()
//graph.addEdge(from: "A", to: "B", weight: 17)
//graph.addEdge(from: "B", to: "A", weight: 17)
//graph.addEdge(from: "A", to: "F", weight: 1)
//graph.addEdge(from: "F", to: "A", weight: 1)
//graph.addEdge(from: "A", to: "E", weight: 16)
//graph.addEdge(from: "E", to: "A", weight: 16)
//graph.addEdge(from: "B", to: "F", weight: 11)
//graph.addEdge(from: "F", to: "B", weight: 11)
//graph.addEdge(from: "B", to: "D", weight: 5)
//graph.addEdge(from: "D", to: "B", weight: 16)
//graph.addEdge(from: "B", to: "C", weight: 6)
//graph.addEdge(from: "C", to: "B", weight: 6)
//graph.addEdge(from: "F", to: "E", weight: 33)
//graph.addEdge(from: "E", to: "F", weight: 33)
//graph.addEdge(from: "F", to: "D", weight: 14)
//graph.addEdge(from: "D", to: "F", weight: 14)
//graph.addEdge(from: "E", to: "D", weight: 4)
//graph.addEdge(from: "D", to: "E", weight: 4)
//graph.addEdge(from: "D", to: "C", weight: 10)
//graph.addEdge(from: "C", to: "D", weight: 10)
//print(graph.prim())
//print(graph.kruskal())
//let graph = Graph<String, Int>.init()
//graph.addEdge(from: "A", to: "B", weight: 10)
//graph.addEdge(from: "A", to: "E", weight: 100)
//graph.addEdge(from: "A", to: "D", weight: 30)
//graph.addEdge(from: "B", to: "C", weight: 50)
//graph.addEdge(from: "C", to: "E", weight: 10)
//graph.addEdge(from: "D", to: "C", weight: 20)
//graph.addEdge(from: "D", to: "E", weight: 60)
//graph.addEdge(from: "B", to: "A", weight: 10)
//graph.addEdge(from: "E", to: "A", weight: 100)
//graph.addEdge(from: "D", to: "A", weight: 30)
//graph.addEdge(from: "C", to: "B", weight: 50)
//graph.addEdge(from: "E", to: "C", weight: 10)
//graph.addEdge(from: "C", to: "D", weight: 20)
//graph.addEdge(from: "E", to: "D", weight: 60)
//print(graph.dijkstra(vertex: "A", addWeightClosure: {$0 + $1}) ?? 0)
//print(graph.bellmanFord(beginVertex: "A", beginWeight: 0, addWeightClosure: {$0 + $1}) ?? 0)
//print(graph.floyd(addWeightClosure: {$0 + $1}))
//let tree = BinarySearchTree<Int>.init()
//let array = [1, 4, 88, 85, 100, 61, 63, 21, 5, 9, 92, 59, 95, 47, 44, 26, 58, 13]
//for number in array {
// tree.add(element: number)
//}
//tree.traversalClosure = { (element,stop) -> () in
// if element == 61 {
// stop = true
// }
// print(element)
//}
//print(tree.isCompleteTree())
//tree.remove(element: 67)
//print(tree.inorderTraversal())
//print(tree.preorderTraversal())
//tree.remove(element: 57)
//print(tree.inorderTraversal())
//print(tree.postorderTraversal())
//let avlTree = AVLTree<Int>.init()
//let array = [41, 97, 18, 61, 100, 80, 69, 76, 3, 78, 8, 33, 79, 75, 40]
//for number in array {
// avlTree.add(element: number)
//}
//avlTree.traversalClosure = {print($0)}
//avlTree.add(element: 90)
//print(avlTree.preorderTraversal())
//print(avlTree.inorderTraversal())
//let rbTree = RBTree<Int>.init()
//let array = [33, 11, 55, 14, 24, 47, 78, 44, 27, 70, 86, 37, 97, 61, 74, 67, 99, 21, 28]
//for number in array {
// rbTree.add(element: number)
//}
//rbTree.traversalClosure = { (element,stop) -> () in
// print(element)
//}
//rbTree.remove(element: 97)
//rbTree.remove(element: 21)
//rbTree.remove(element: 28)
//rbTree.remove(element: 11)
//
//print(rbTree.preorderTraversal())
| true
|
d63856a09b62106d96f0b811b54ee6e79d28bd46
|
Swift
|
alaydesai094/201DAP_intern
|
/CTC/New Group/Views/SignUpViewController.swift
|
UTF-8
| 4,039
| 2.734375
| 3
|
[] |
no_license
|
//
// SignUpViewController.swift
// CTC
//
// Created by Nirav Bavishi on 2019-01-09.
// Copyright © 2019 Nirav Bavishi. All rights reserved.
//
import UIKit
class SignUpViewController: UIViewController {
// variables
var dbHelper: DatabaseHelper!
//variables
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var createAccountButton: UIButton!
@IBOutlet weak var backToSignIn: UIButton!
@IBOutlet weak var passwordMessage: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
dbHelper = DatabaseHelper()
// to make text field round corner
nameTextField.clipsToBounds = true
passwordTextField.clipsToBounds = true
emailTextField.clipsToBounds = true
nameTextField.layer.cornerRadius = 10
emailTextField.layer.cornerRadius = 10
passwordTextField.layer.cornerRadius = 10
nameTextField.customePlaceHolder(text: "Enter Your Name", color: UIColor.blue.withAlphaComponent(0.4))
emailTextField.customePlaceHolder(text: "Enter Your Email", color: UIColor.blue.withAlphaComponent(0.4))
passwordTextField.customePlaceHolder(text: "Enter Your Password", color: UIColor.blue.withAlphaComponent(0.4))
nameTextField.setLeftPadding(iconName: "Name")
emailTextField.setLeftPadding(iconName: "Email")
passwordTextField.setLeftPadding(iconName: "Password")
createAccountButton.layer.cornerRadius = 10
backToSignIn.layer.cornerRadius = 10
createAccountButton.loginButton()
backToSignIn.loginButton()
// to dismiss keyboard on tap out side
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))
self.view.addGestureRecognizer(tapGesture)
// Do any additional setup after loading the view.
}
@IBAction func passwordMessage(_ sender: UITextField) {
passwordMessage.text = "Your password must contains a letter, number and a special character!! ";
}
// to dismiss keyboard on tap out side
@objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {
nameTextField.resignFirstResponder()
emailTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
}
@IBAction func createAccountButtonTapped(_ sender: Any) {
let name = nameTextField.text!
var email = emailTextField.text!
email = email.lowercased()
let password = passwordTextField.text!
if(!name.isEmpty && !email.isEmpty && !password.isEmpty){
let resultFlag = dbHelper.addUser(name: name, email: email, password: password)
if(resultFlag == 1){
showAlert(title: "Warning", message: "User Already Exist", buttonTitle: "Try Again")
}else if (resultFlag == 2){
showAlert(title: "Error", message: "Please Report an error. . .", buttonTitle: "Try Again")
}else if (resultFlag == 0){
performSegue(withIdentifier: "createAccountToHome", sender: self)
}
}
else{
print("fill the form")
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
02f7c407b9679d5a0bb48b22b92977842de66b19
|
Swift
|
codycc/myCocktail
|
/myPantry/RecipeVC.swift
|
UTF-8
| 3,903
| 2.546875
| 3
|
[] |
no_license
|
//
// RecipeVC.swift
// myPantry
//
// Created by Cody Condon on 2016-11-22.
// Copyright © 2016 Cody Condon. All rights reserved.
//
import UIKit
import Kingfisher
import Firebase
class RecipeVC: UIViewController {
@IBOutlet weak var recipeImg: UIImageView!
@IBOutlet weak var saveBtn: UIButton!
@IBOutlet weak var recipeLbl: UILabel!
@IBOutlet weak var ingredientLbl: UITextView!
var recipe: Recipe!
var recipeInformation: [Any]!
var recipeIngredients: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// unpacking the array for use
recipe = recipeInformation.last as! Recipe!
// removing the original recipe info since the needed information is parsed, the array contains new detailed recipe information
let count = recipeInformation.count
recipeInformation.remove(at: count - 1)
print("here \(recipeInformation)")
for ingredient in recipeInformation! {
recipeIngredients = "\(recipeIngredients) \(ingredient)"
}
//setting url from original info
let url = URL(string: recipe.imageUrl)
recipeImg.kf.setImage(with: url)
ingredientLbl.text = recipeIngredients
print("here is the string containing ingredients \(recipeIngredients)")
recipeLbl.text = recipe.title
self.checkIfSaved()
}
func checkIfSaved() {
let _ = DataService.ds.REF_USER_CURRENT.observeSingleEvent(of: .value, with: { (snapshot) in
let cookBookId = snapshot.childSnapshot(forPath: "cookBookID").value as! String
DataService.ds.REF_COOKBOOKS.child(cookBookId).child("recipes").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild(self.recipe.recipeID) {
self.saveBtn.setTitle("SAVED", for: .normal)
self.saveBtn.backgroundColor = UIColor.darkGray
}
})
//
})
}
@IBAction func backTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func sourceBtnTapped(_ sender: Any) {
if let url = URL(string: "\(self.recipe.sourceUrl)") {
UIApplication.shared.open(url, options: [:])
}
}
@IBAction func saveRecipe(_ sender: Any) {
let _ = DataService.ds.REF_USER_CURRENT.observeSingleEvent(of: .value, with: { (snapshot) in
let cookBookId = snapshot.childSnapshot(forPath: "cookBookID").value as! String
DataService.ds.REF_COOKBOOKS.child(cookBookId).child("recipes").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild(self.recipe.recipeID) {
let _ = DataService.ds.REF_COOKBOOKS.child(cookBookId).child("recipes").child(self.recipe.recipeID).removeValue()
self.saveBtn.setTitle("SAVE", for: .normal)
self.saveBtn.backgroundColor = UIColor(red: 49.0/255.0, green: 69.0/255.0, blue: 157.0/255.0, alpha: 1.0)
} else {
let recipeInfo = [ "ingredients" : self.recipeIngredients,
"recipe_URL" : self.recipe.imageUrl,
"source_URL" : self.recipe.sourceUrl,
"title": self.recipe.title]
let _ = DataService.ds.REF_COOKBOOKS.child(cookBookId).child("recipes").child(self.recipe.recipeID).setValue(recipeInfo)
self.saveBtn.setTitle("SAVED", for: .normal)
self.saveBtn.backgroundColor = UIColor.darkGray
}
})
})
}
}
| true
|
1676e32d26f1116dd6a4f8ec797a34b1cb6209b5
|
Swift
|
kaikaka/SwiftTips
|
/Demo/Demo/main.swift
|
UTF-8
| 1,110
| 3.1875
| 3
|
[] |
no_license
|
//
// main.swift
// Demo
//
// Created by KaiKing on 2020/12/14.
// Copyright © 2020 K. All rights reserved.
//
//import Cocoa
// var str1: String = "car"
// var str2: NSString = "tesla"
// str1.append("c") //细节 拼接在原字符串上
// var str5 = str2.appending("c") //新创建了字符串
// print(str1,str2,str5)
// var str3 = str1 as NSString
// var str4 = str2 as String
// var str6 = str3.appending("s")
// print(str6,str3)
// print(str1, str3)
// print(str2,str4)
// print(str2 == str3)
// var str9 :String = "car"
// var str10 :NSMutableString = str9 as? NSMutableString
// print(str10)
//
// var str7 :NSMutableString = "car"
// var str8 :String = str7 as String
// print(str8)
//var str1 = "0123456789"
//print(MemoryLayout.stride(ofValue: str1))
//0x3736353433323130 0xea00000000003938 /0xea a代表是长度 e 代表类型
//var str2 = "0123456789ABCDEF"
//0x100003EB0
//movabsq rdx - $0x7fffffffffffffe0 = 字符串的真实地址
//var arr = [1,2,3,4]
//print(arr)
//print(1)
| true
|
57d9110eba8ae33759993c405d289718ea2350a3
|
Swift
|
swamphacks/2017-Mobile
|
/Swamphacks/UIView+Conveniences.swift
|
UTF-8
| 2,118
| 2.859375
| 3
|
[] |
no_license
|
//
// UINavigationController+StatusBarStyle.swift
// Swamphacks
//
// Created by Gonzalo Nunez on 12/25/16.
// Copyright © 2016 Gonzalo Nunez. All rights reserved.
//
import UIKit
enum BorderLocation {
case top, bottom
func anchor(for view: UIView) -> NSLayoutYAxisAnchor {
switch self {
case .top: return view.topAnchor
case .bottom: return view.bottomAnchor
}
}
}
extension UIView {
func style(on location: BorderLocation, height: CGFloat, color: UIColor = .darkTurquoise) {
let view = UIView(frame: .zero)
view.backgroundColor = color
view.translatesAutoresizingMaskIntoConstraints = false
addSubview(view)
let borderAnchor = location.anchor(for: view).constraint(equalTo: location.anchor(for: self))
let left = view.leftAnchor.constraint(equalTo: leftAnchor)
let right = view.rightAnchor.constraint(equalTo: rightAnchor)
let height = view.heightAnchor.constraint(equalToConstant: height)
NSLayoutConstraint.activate([borderAnchor, left, right, height])
}
}
extension UINavigationController {
open override var childViewControllerForStatusBarStyle: UIViewController? {
return self.topViewController
}
func style() {
return navigationBar.style(on: .bottom, height: 4)
}
func styled() -> UINavigationController {
style()
return self
}
}
extension UITabBarController {
func style() {
return tabBar.style(on: .top, height: 2, color: .turquoise)
}
func styled() -> UITabBarController {
style()
return self
}
}
extension UIImage {
func applying(alpha:CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let ctx = UIGraphicsGetCurrentContext()!
let area = CGRect(x: 0, y: 0, width: size.width, height: size.height)
ctx.scaleBy(x: 1, y: -1)
ctx.translateBy(x: 0, y: -area.size.height)
ctx.setBlendMode(.multiply)
ctx.setAlpha(alpha)
ctx.draw(cgImage!, in: area)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
| true
|
ca8c9d7f588cc7265fe97179a865725c94a60a8b
|
Swift
|
JonathanOh/BasicChecklist
|
/BasicChecklist/CircleView.swift
|
UTF-8
| 1,476
| 3.078125
| 3
|
[] |
no_license
|
//
// CircleView.swift
// BasicChecklist
//
// Created by Jonathan Oh on 4/22/20.
// Copyright © 2020 Jonathan Oh. All rights reserved.
//
import UIKit
class CircleView: UIView {
static let width: CGFloat = 20
private var isSelected: Bool = false
override init(frame: CGRect) {
super.init(frame: .zero)
setupStyling()
setupConstraints()
setupSelf()
}
func setupSelf() {
isUserInteractionEnabled = false
}
func setupConstraints() {
// This allows us to setup view constraint via code instead of storyboard
translatesAutoresizingMaskIntoConstraints = false
// sets width and height of CircleView to be 20x20
widthAnchor.constraint(equalToConstant: CircleView.width).isActive = true
heightAnchor.constraint(equalToConstant: CircleView.width).isActive = true
}
func setupStyling() {
// Makes the view circular
layer.cornerRadius = CircleView.width / 2
// Border styling
layer.borderColor = UIColor.darkGray.cgColor
layer.borderWidth = 1
}
func toggleIsSelected() {
isSelected = !isSelected
if isSelected {
backgroundColor = UIColor.darkGray
} else {
backgroundColor = UIColor.white
}
}
// Xcode genereated
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
203f37859bed35d8eef6239cb624b0610d1e3b98
|
Swift
|
DimaPylyp/Gitty
|
/Gitty/VIew/RepoTableViewCell.swift
|
UTF-8
| 4,867
| 2.65625
| 3
|
[] |
no_license
|
//
// RepoTableViewCell.swift
// Gitty
//
// Created by DIMa on 20.09.2020.
// Copyright © 2020 DIMa. All rights reserved.
//
import UIKit
class RepoTableViewCell: UITableViewCell {
var repo: Repo? {
didSet{
guard let repoItem = repo else { return }
nameLabel.text = repoItem.name
langugeLabel.text = repoItem.language
let formater = DateFormatter()
formater.locale = Locale(identifier: "en_US_POSIX")
formater.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
guard let date = formater.date(from: repoItem.updated_at) else {return}
formater.dateStyle = .short
formater.timeStyle = .none
updatedAtLabel.text = "\(formater.string(from: date))"
starsLabel.text = String(repoItem.stargazers_count)
}
}
// var stackView: UIStackView = {
// let stackView = UIStackView()
// stackView.translatesAutoresizingMaskIntoConstraints = false
// stackView.axis = .vertical
// stackView.distribution = .fill
// stackView.alignment = .fill
// stackView.spacing = 50
// return stackView
// }()
var nameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var langugeLabel: UILabel = {
let label = UILabel()
label.textAlignment = .right
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var bottomView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
// view.isHidden = true
return view
}()
var updatedAtLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var starsLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
// contentView.addSubview(stackView)
// stackView.addSubview(nameLabel)
// stackView.addSubview(langugeLabel)
// stackView.addSubview(bottomView)
contentView.addSubview(nameLabel)
contentView.addSubview(langugeLabel)
contentView.addSubview(bottomView)
bottomView.addSubview(updatedAtLabel)
bottomView.addSubview(starsLabel)
// stackView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
// stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
// stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
// stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
nameLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true
langugeLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true
bottomView.heightAnchor.constraint(equalToConstant: 30).isActive = true
nameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 2).isActive = true
nameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 2).isActive = true
nameLabel.trailingAnchor.constraint(equalTo: langugeLabel.leadingAnchor, constant: 0).isActive = true
langugeLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 2).isActive = true
langugeLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -2).isActive = true
bottomView.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 2).isActive = true
bottomView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 2).isActive = true
bottomView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -2).isActive = true
bottomView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -2).isActive = true
updatedAtLabel.topAnchor.constraint(equalTo: bottomView.topAnchor, constant: 2).isActive = true
updatedAtLabel.leadingAnchor.constraint(equalTo: bottomView.leadingAnchor, constant: 2).isActive = true
starsLabel.topAnchor.constraint(equalTo: bottomView.topAnchor, constant: 2).isActive = true
starsLabel.trailingAnchor.constraint(equalTo: bottomView.trailingAnchor, constant: -2).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
144b3023cf9b6a438974be603bfb950334ab5780
|
Swift
|
MaximTzv/Swify-MVVM-C
|
/MVVM-C Starter/Classes/Presentation/Presenters/Coordinators/SearchNavigationCoordinator.swift
|
UTF-8
| 1,182
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// SearchNavigationCoordinator.swift
// MVVM-C Starter
//
// Created by Taylor on 2017-12-23.
// Copyright © 2017 Taylor. All rights reserved.
//
import Foundation
import UIKit
final class SearchNavigationCoordinator: Coordinator, NavigationCoordinator, TabCoordinatorType {
let tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.search, tag: 2)
override var rootViewController: UIViewController {
return rootController
}
let rootController: UINavigationController
override init() {
let vc = SearchViewController()
rootController = UINavigationController(rootViewController: vc)
rootController.tabBarItem = tabBarItem
super.init()
}
func performTransition(_ transition: TransitionType) {
}
//
// func performTransition(_ transition: TransitionType) {
// guard let transition = transition as? Transition else { return }
// switch transition {
// case .toOffer(let offer, let venue):
// showDetailForOffer(offer, venue: venue)
// case .toVenue(let venue):
// showDetailForVenue(venue)
// }
// }
}
| true
|
2da4b88aeb080e2c71a93efa9736800d460c3509
|
Swift
|
Matheus-Sousa-Matos/SpriteKit-Mario-Game
|
/mario_swift_study/mario_swift_study/GameScene.swift
|
UTF-8
| 771
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// GameScene.swift
// mario_swift_study
//
// Created by Matheus de Sousa Matos on 10/08/21.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
let player = Player(positon: CGPoint(x: size.width*0.5, y: size.height*0.5), size: CGSize(width: 50, height: 50))
self.addChild(player.node)
let joystick = Joystick(positon: CGPoint(x: size.width*0.15, y: size.height*0.15), size: CGSize(width: 50, height: 50))
self.addChild(joystick.joystickBack)
self.addChild(joystick.joystickButton)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func update(_ currentTime: TimeInterval) {
}
}
| true
|
7a7f3b659f7470a70f3ce7a8426ca7356f93c1fa
|
Swift
|
kreatimont/ios-MovieFinder
|
/MovieFinder/Helpers/ApiKeys.swift
|
UTF-8
| 481
| 2.796875
| 3
|
[] |
no_license
|
//
// ApiKeys.swift
// MovieFinder
//
// Created by Alexandr Nadtoka on 11/19/18.
// Copyright © 2018 kreatimont. All rights reserved.
//
import Foundation
func valueForAPIKey(keyname:String) -> String {
let filePath = Bundle.main.path(forResource: "keys", ofType: "plist")
let plist = NSDictionary(contentsOfFile: filePath!)
if let value = plist?.object(forKey: keyname) as? String {
return value
} else {
fatalError("API KEY REQUIRED!")
}
}
| true
|
bceaa6c8003d6e71e26cd35676d8472c15dbff5f
|
Swift
|
prakhar30/GetThatImage
|
/GetThatImage/Networking/RequestBuilder.swift
|
UTF-8
| 966
| 2.984375
| 3
|
[] |
no_license
|
//
// RequestBuilder.swift
// GetThatImage
//
// Created by Prakhar Tripathi on 06/03/21.
//
import Foundation
protocol RequestBuilder {
var method: HTTPMethod { get }
var baseURL: URL { get }
var path: String? { get }
var params: [URLQueryItem]? { get }
var headers: [String: String] { get }
func toURLRequest() -> URLRequest
func encodeRequestBody() -> Data?
}
extension RequestBuilder {
func toURLRequest() -> URLRequest {
var components = URLComponents(url: baseURL.appendingPathComponent(path ?? ""), resolvingAgainstBaseURL: false)!
components.queryItems = params
let url = components.url!
var request = URLRequest(url: url)
request.allHTTPHeaderFields = headers
request.httpMethod = method.rawValue.uppercased()
request.httpBody = encodeRequestBody()
return request
}
func encodeRequestBody() -> Data? {
return nil
}
}
| true
|
e622efae7754bb64535404869ec1df07f6c9ac00
|
Swift
|
evan-beh/Food-delivery-ios
|
/FoodDeliveryApp/Utility.swift
|
UTF-8
| 547
| 2.84375
| 3
|
[] |
no_license
|
//
// Utility.swift
// FoodDeliveryApp
//
// Created by Evan Beh on 09/09/2021.
//
import UIKit
class Utility: NSObject {
static func readLocalJSONFile(forName name: String) -> Data? {
do {
if let filePath = Bundle.main.path(forResource: name, ofType: "json") {
let fileUrl = URL(fileURLWithPath: filePath)
let data = try Data(contentsOf: fileUrl)
return data
}
} catch {
print("error: \(error)")
}
return nil
}
}
| true
|
4e75c313d0ae00289fbd21f14bd469c220d6aa8e
|
Swift
|
RadyaAlbasha/Al-Akela_iOSProject
|
/Alakela/Alakela/Screens/RestaurantScreen/View/RestaurantViewController_Extention.swift
|
UTF-8
| 3,139
| 2.65625
| 3
|
[] |
no_license
|
//
// RestaurantViewController_Extention.swift
// Alakela
//
// Created by Radya Al-Basha on 9/27/19.
// Copyright © 2019 Radya Al-Basha. All rights reserved.
//
import Foundation
import GoogleMobileAds
@available(iOS 13.0, *)
extension RestaurantViewController: RestaurantViewControllerProtocol ,GADBannerViewDelegate {
// MARK: - GADBannerViewDelegate
func adViewDidReceiveAd(_ bannerView: GADBannerView) {
print("Banner loaded successfully")
}
func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) {
print("Fail to receive ads")
print(error)
}
func makePhoneCall(number : String!) {
guard let numberStr = number , let url = URL(string: "telprompt://\(numberStr)") else {
return
}
UIApplication.shared.open(url)
}
func choosePhoneNumberToCall(numbers : [String]!) {
/* guard let numberStr = number , let url = URL(string: "telprompt://\(numberStr)") else {
return
}
UIApplication.shared.open(url)*/
let alert = UIAlertController(title: "ChooseNumberTitle".localized, message: "ChooseNumberMsg".localized, preferredStyle: .alert)
for number in numbers{
print(number)
if let url = URL(string: "telprompt://\(number)"){
if UIApplication.shared.canOpenURL(url) {
let numberAction = UIAlertAction(title: number , style: .default, handler: { _ in
UIApplication.shared.open(url)
})
alert.addAction(numberAction)
}
}
}
if alert.actions.count == 0 {
alert.title = "NoNumbers".localized
alert.message = ""
alert.addAction(UIAlertAction(title: "OK".localized, style: .default, handler: nil))
} else {
alert.addAction(UIAlertAction(title: "Cancel".localized, style: .destructive, handler: nil))
}
self.present(alert, animated: true, completion: nil)
}
// MARK: - RestaurantViewControllerProtocol
func setRestaurant(restaurant: Restaurant!) {
self.restaurant = restaurant
}
func setCollectionKey(collectionKey : String!){
self.collectionKey = collectionKey
}
//
func showRestaurantDetails(restaurant: Restaurant){
if let url = restaurant.logoUri {
restaurantImgV.sd_setImage(with: URL(string: url), placeholderImage: UIImage(named:"logo"))
}
if restaurant.location != nil {
locationLabel.text = restaurant.location
}
if restaurant.description != nil {
foodTypeLabel.text = restaurant.description
}
if restaurant.timeDelivery != nil {
timeLabel.text = "\(restaurant.timeDelivery!) \("min".localized) "
}
if restaurant.view != nil {
viewLabel.text = restaurant.view
}
}
/*func showMenuImages(menuUri : [String]!) {
}*/
}
| true
|
a5de59a9081c925ec9a310aaaffa0481eb80ba0e
|
Swift
|
terencehh/save-my-time-ios-app
|
/Tasks Functionality/CompletedTasksTableViewController.swift
|
UTF-8
| 8,674
| 2.703125
| 3
|
[] |
no_license
|
//
// CompletedTaskTableViewController.swift
// SaveMyTime
// Table View Controller displaying completed tasks
//
// Created by Terence Ng on 25/5/19.
// Copyright © 2019 Terence Ng. All rights reserved.
//
import UIKit
import UserNotifications
class CompletedTaskTableViewController: UITableViewController, DatabaseListener, UISearchResultsUpdating {
// store local lists for efficient table view display
var taskList: [Task] = []
var filteredTasks: [Task] = []
var searchController: UISearchController?
var isFiltered: Bool = false
// get reference to table view sections
var SECTION_TASK = 0
var SECTION_COUNT = 1
// get reference to cell identifiers
let CELL_TASK = "taskCell"
let CELL_COUNT = "cellCount"
weak var databaseController: DatabaseProtocol?
override func viewDidLoad() {
super.viewDidLoad()
// Get the database controller once from the App Delegate
let appDelegate = UIApplication.shared.delegate as! AppDelegate
databaseController = appDelegate.databaseController
filteredTasks = taskList
// define search controller logic
searchController = UISearchController(searchResultsController: nil)
searchController!.searchResultsUpdater = self
searchController!.obscuresBackgroundDuringPresentation = false
searchController!.searchBar.placeholder = "Search Complete Tasks"
navigationItem.searchController = searchController
definesPresentationContext = true
databaseController?.addListener(listener: self)
}
override func viewWillAppear(_ animated: Bool) {
// make sure tableview always reloads when subject is added/deleted/updated
super.viewWillAppear(animated)
print("printing task when view appeared", taskList)
databaseController?.addListener(listener: self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
databaseController?.removeListener(listener: self)
}
// Database Listener
var listenerType = ListenerType.completetask
func onIncompleteTaskListChange(change: DatabaseChange, tasks: [Task]) {
// not called
}
func onSubjectListChange(change: DatabaseChange, subjects: [Subject]) {
// not called
}
func onCompleteTaskListChange(change: DatabaseChange, tasks: [Task]) {
taskList = tasks
print("Retrieved Complete Task List", taskList)
filteredTasks = taskList
updateSearchResults(for: navigationItem.searchController!)
}
// updates the filtered task whenever search controller is interacted with
func updateSearchResults(for searchController: UISearchController) {
if let searchText = searchController.searchBar.text?.lowercased(), searchText.count > 0 {
filteredTasks = taskList.filter({(task: Task) -> Bool in
if task.taskTitle.lowercased().contains(searchText.lowercased()) == true {
isFiltered = true
} else {
isFiltered = false
}
return task.taskTitle.lowercased().contains(searchText.lowercased())
})
}
else {
filteredTasks = taskList;
}
tableView.reloadData()
}
// useful function to determine if search controller is active
func searchBarIsEmpty() -> Bool {
return searchController!.searchBar.text?.isEmpty ?? true
}
// useful function to determine if table is filtering
func isFiltering() -> Bool {
return searchController!.isActive && !searchBarIsEmpty()
}
// if filtering, return 1 section, else 2
override func numberOfSections(in tableView: UITableView) -> Int {
if isFiltering() {
return 1
}
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering() {
return filteredTasks.count
}
else if section == SECTION_TASK {
return taskList.count
}
else {
return 1
}
}
// if filtering, return the tasks from filteredTasks, else return tasks from normal taskList
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if isFiltering() {
let taskCell = (tableView.dequeueReusableCell(withIdentifier: CELL_TASK, for: indexPath) as! TaskTableViewCell)
let task = filteredTasks[indexPath.row]
taskCell.taskTitleLabel.text = task.taskTitle
// retrieve the subject description from firebase
databaseController?.getSubjectDescfromID(subjectID: task.taskSubjectID) { (subjectString) -> Void in
if let subjectString = subjectString {
DispatchQueue.main.async {
taskCell.subjectLabel.text = subjectString
}
}
}
return taskCell
}
else {
if indexPath.section == SECTION_TASK && searchBarIsEmpty() {
let taskCell = (tableView.dequeueReusableCell(withIdentifier: CELL_TASK, for: indexPath) as! TaskTableViewCell)
let task = taskList[indexPath.row]
taskCell.taskTitleLabel.text = task.taskTitle
// retrieve the subject description from firebase
databaseController?.getSubjectDescfromID(subjectID: task.taskSubjectID) { (subjectString) -> Void in
if let subjectString = subjectString {
DispatchQueue.main.async {
taskCell.subjectLabel.text = subjectString
}
}
}
return taskCell
}
let countCell = tableView.dequeueReusableCell(withIdentifier: CELL_COUNT, for: indexPath)
if taskList.count == 0 || taskList.count == 1 {
countCell.textLabel?.text = "You have \(taskList.count) Completed Task"
} else {
countCell.textLabel?.text = "You have \(taskList.count) Completed Tasks"
}
countCell.selectionStyle = .none
countCell.textLabel?.textColor = UIColor.white
return countCell
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == SECTION_TASK {
return true
}
return false
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete && indexPath.section != SECTION_COUNT {
var deletedTask: Task?
if filteredTasks.count != taskList.count {
deletedTask = filteredTasks[indexPath.row]
}
else {
deletedTask = taskList[indexPath.row]
databaseController!.deleteTask(task: deletedTask!)
tableView.reloadData()
}
if deletedTask != nil {
databaseController!.deleteTask(task: deletedTask!)
tableView.reloadData()
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "taskDetailsSegue" {
let destination = segue.destination as! TaskDetailsViewController
let selectedTaskCell = sender as? TaskTableViewCell
let indexPath = tableView.indexPath(for: selectedTaskCell!)
if isFiltering() {
let task = filteredTasks[indexPath!.row]
destination.passedTask = task
}
else {
let task = taskList[indexPath!.row]
destination.passedTask = task
}
}
}
}
| true
|
fce232deb6a0a4d4d8c4f967466d3d6575cc2780
|
Swift
|
masarapmabuhay/usbong-ios
|
/usbong/MD5.swift
|
UTF-8
| 1,919
| 2.515625
| 3
|
[
"Zlib",
"Apache-2.0",
"MIT"
] |
permissive
|
//
// MD5.swift
// usbong
//
// Created by Chris Amanse on 22/09/2015.
// Copyright 2015 Usbong Social Systems, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
// CommonCrypto required (Objective-C library, thus you need to use bridging header
extension NSData {
func hashMD5() -> String {
let digestLength = Int(CC_MD5_DIGEST_LENGTH)
let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength)
CC_MD5(bytes, CC_LONG(length), md5Buffer)
let hash = NSMutableString(capacity: Int(CC_MD5_DIGEST_LENGTH * 2))
for i in 0..<digestLength {
hash.appendFormat("%02x", md5Buffer[i])
}
md5Buffer.destroy()
return String(hash)
}
}
extension String {
func hashMD5() -> String {
let utf8 = self.cStringUsingEncoding(NSUTF8StringEncoding)
let stringLength = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLength = Int(CC_MD5_DIGEST_LENGTH)
let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength)
CC_MD5(utf8!, stringLength, md5Buffer)
let hash = NSMutableString()
for i in 0..<digestLength {
hash.appendFormat("%02x", md5Buffer[i])
}
md5Buffer.destroy()
return String(hash)
}
}
| true
|
07e794753296c9248b8a436167178670f810501d
|
Swift
|
partho-maple/coding-interview-gym
|
/leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/150_Evaluate_Reverse_Polish_Notation.swift
|
UTF-8
| 1,253
| 3.328125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
class Solution {
func evalRPN(_ tokens: [String]) -> Int {
var opes = ["+", "-", "*", "/"]
var stack = [String]()
for token in tokens {
if opes.contains(token) {
var rightOperand: Double! = Double(stack.popLast()!)
var leftOperand: Double! = Double(stack.popLast()!)
var result = 0.0
if token == "+" {
result = leftOperand + rightOperand
} else if token == "-" {
result = leftOperand - rightOperand
} else if token == "*" {
result = leftOperand * rightOperand
} else {
if (rightOperand*leftOperand < 0) && (Int(leftOperand)%Int(rightOperand) != 0) {
result = leftOperand / rightOperand + 1
} else {
result = leftOperand / rightOperand
}
}
var res = Int(result.round(.towardZero)
stack.append(String(res))
} else {
stack.append(token)
}
}
print("stack: \(stack)")
return Int(stack.popLast()!)!
}
}
| true
|
1aeb7ec62fa18174e41dc5649519744173f6827f
|
Swift
|
forest28gold/BeHereNow
|
/BeHereNow/Helpers/DateHelper.swift
|
UTF-8
| 820
| 2.5625
| 3
|
[] |
no_license
|
//
// DateHelper.swift
// BeHereNow
//
// Created by AppsCreationTech on 2/4/16.
// Copyright © 2016 AppsCreationTech. All rights reserved.
//
import Foundation
class DateHelper {
static let sharedInstance = DateHelper()
let dateFormatter: NSDateFormatter
let videoFormatter: NSDateFormatter
let monthFormatter: NSDateFormatter
let dayFormatter: NSDateFormatter
init() {
dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
videoFormatter = NSDateFormatter()
videoFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
monthFormatter = NSDateFormatter()
monthFormatter.dateFormat = "MMM"
dayFormatter = NSDateFormatter()
dayFormatter.dateFormat = "dd"
}
}
| true
|
071f491fe120b7affc3d95178adf25513d1a507b
|
Swift
|
emilsh/Petstagram
|
/Petstagram/Service Layer/Network Engine/APIEnvironment.swift
|
UTF-8
| 356
| 2.59375
| 3
|
[] |
no_license
|
//
// APIEnvironment.swift
// Petstagram
//
// Created by Emil Shafigin on 4/6/21.
//
import Foundation
struct APIEnvironment {
var baseUrl: URL
}
extension APIEnvironment {
static let prod = APIEnvironment(baseUrl: URL(string: "https://example.com/api/v1")!)
static let local = APIEnvironment(baseUrl: URL(string: "http://localhost:8080/api/v1")!)
}
| true
|
d8cdcedf3f66d7ba1aca2573610adf21f9cb5f70
|
Swift
|
AngelHernandez01/GraphView
|
/CGMGraph/Container/Model/Queue.swift
|
UTF-8
| 545
| 3.40625
| 3
|
[] |
no_license
|
//
// Queue.swift
// Graph
//
// Created by Julio Montoya on 10/24/20.
//
import Foundation
public struct Queue<T> {
// MARK: - Properties
private var items: [T] = []
public var isEmpty: Bool {
items.isEmpty
}
public var count: Int {
items.count
}
public var peek: T? {
items.first
}
// MARK: - Object Lifecycle
public init() {}
public mutating func enqueue(_ element: T) {
items.append(element)
}
public mutating func dequeue() -> T? {
isEmpty ? nil : items.removeFirst()
}
}
| true
|
8669b36b33fc68e298ba0ca69e3c368d2a5fae4a
|
Swift
|
kevaljshah/Spotlight
|
/Spotlight/WatchListDataSource.swift
|
UTF-8
| 910
| 2.53125
| 3
|
[] |
no_license
|
//
// WatchListDataSource.swift
// Spotlight
//
// Created by Keval Shah on 5/3/16.
// Copyright © 2016 Keval Shah. All rights reserved.
//
import UIKit
class WatchListDataSource: NSObject, UICollectionViewDataSource {
var watchListStore: WatchListStore!
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return watchListStore.allItems.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let identifier = "UICollectionViewCell5"
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! WatchListCollectionViewCell
let movie = watchListStore.allItems[indexPath.row]
print(movie.id)
cell.updateWithImage(movie.image)
return cell
}
}
| true
|
23a60346d2239e49d6251084c78e7dfcad07809a
|
Swift
|
pallavi10aggarwal/weatherClient
|
/weatherApp/Views/WeatherCollectionViewCell.swift
|
UTF-8
| 492
| 2.609375
| 3
|
[] |
no_license
|
//
// WeatherCollectionViewCell.swift
// weatherApp
//
// Created by Pallavi Aggarwal on 13/10/21.
//
import UIKit
class WeatherCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var weatherConditionLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
var viewModel: WeatherViewModel? {
didSet {
self.weatherConditionLabel.text = viewModel?.weatherCondition
self.temperatureLabel.text = viewModel?.temperature
}
}
}
| true
|
4ff7dd0dba70a56b96704c3570f1cb6107f351ff
|
Swift
|
adela-chang/SwURL
|
/Sources/SwURL/RemoteImage/RemoteImage.swift
|
UTF-8
| 1,350
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// RemoteImage.swift
// Landmarks
//
// Created by Callum Trounce on 06/06/2019.
// Copyright © 2019 Apple. All rights reserved.
//
import Foundation
import SwiftUI
import Combine
enum RemoteImageStatus {
case complete(result: CGImage)
case progress(fraction: Float)
}
class RemoteImage: ObservableObject {
var objectWillChange = PassthroughSubject<RemoteImageStatus, Never>()
var request: Cancellable?
var image: Image? {
guard case let .complete(image) = imageStatus else {
return nil
}
return Image.init(
image,
scale: 1,
label: Text("Image")
)
}
var progress: Float {
guard case let .progress(fraction) = imageStatus else {
return 0
}
return fraction
}
var imageStatus: RemoteImageStatus = .progress(fraction: 0) {
willSet {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.objectWillChange.send(self.imageStatus)
}
}
}
func load(url: URL) -> Self {
request = ImageLoader.shared.load(url: url).catch { error -> Just<RemoteImageStatus> in
SwURLDebug.log(
level: .warning,
message: "Failed to load image from url: " + url.absoluteString + "\nReason: " + error.localizedDescription
)
return .init(.progress(fraction: 0))
}
.eraseToAnyPublisher()
.assign(to: \RemoteImage.imageStatus, on: self)
return self
}
}
| true
|
ab47298378cbf27852aff3f2c79710c43a869903
|
Swift
|
michellewho/iQuiz
|
/iQuiz/iQuiz/FinishedViewController.swift
|
UTF-8
| 1,393
| 2.609375
| 3
|
[] |
no_license
|
//
// FinishedViewController.swift
// iQuiz
//
// Created by Michelle Ho on 11/4/18.
// Copyright © 2018 Michelle Ho. All rights reserved.
//
import UIKit
class FinishedViewController: UIViewController {
var appData = AppData.shared
@IBOutlet weak var reaction: UILabel!
@IBOutlet weak var result: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// numRight.text = String(appData.numRight)
let totalQuestions = appData.categories[appData.topicIndex].questions.count
if (appData.numRight == totalQuestions) {
reaction.text = "Perfect!"
} else {
reaction.text = "Better Luck Next Time :("
}
result.text = "You got " + String(appData.numRight) + " out of " + String(totalQuestions) + " questions right"
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swipe))
swipeLeft.direction = .left
self.view.addGestureRecognizer(swipeLeft)
}
@objc func swipe(sender: UISwipeGestureRecognizer) {
if (sender.direction == .left) {
backButtonPressed(sender)
}
}
@IBAction func backButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "segueBackHome", sender: self)
appData.numGuessed = 0
appData.numRight = 0
}
}
| true
|
fbef26622a4a8f7d23a0906d3630230bf7da9106
|
Swift
|
David249/HomeWork
|
/HW4/Groups/Friends/FriendsViewController.swift
|
UTF-8
| 8,809
| 2.625
| 3
|
[] |
no_license
|
//
// FriendsTVC.swift
// homeW1-2
//
// Created by Давид Горзолия on 05.11.2020.
//
import UIKit
import Kingfisher
let friends = Friends()
@IBDesignable class FriendsViewController: UITableViewController {
private let vkService = VKServices()
public var users = [User]()
var friendsNames = [String](Friends.allFriends.keys).sorted()
var searchedNames = [String]()
let presentTransition = PresentModalAnimator()
let dismissTransition = DismissModalAnimator()
let searchController = UISearchController(searchResultsController: nil)
// Смещение тени
@IBInspectable var shadowOffset: CGSize = CGSize(width: 3, height: 3)
// Прозрачность тени
@IBInspectable var shadowOpacity: Float = 0.3
// Радиус блура тени
@IBInspectable var shadowRadius: CGFloat = 5
// Цвет тени
@IBInspectable var shadowColor: UIColor = UIColor.black
override func viewDidLoad() {
super.viewDidLoad()
// setupSearchController()
vkService.getFriends() { [weak self] users, error in
if let error = error {
print(error)
return
} else if let users = users, let self = self {
self.users = users
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
// MARK: - Setup a Search Controller
func setupSearchController() {
// searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search Names"
navigationItem.searchController = searchController
definesPresentationContext = true
}
// MARK: - Table view data source
// override func numberOfSections(in tableView: UITableView) -> Int {
// if isFiltering() {
// return firstLetters(in: searchedNames).count
// } else {
// return firstLetters(in: friendsNames).count
//
// }
// }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
// if isFiltering() {
// return filterNames(from: searchedNames, in: section).count
// } else {
// return filterNames(from: friendsNames, in: section).count
// }
}
// override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// if isFiltering() {
// return firstLetters(in: searchedNames)[section]
// } else {
// return firstLetters(in: friendsNames)[section]
// }
// }
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// // Получаем ячейку из пула
let cell = tableView.dequeueReusableCell(withIdentifier: "FriendsCell", for: indexPath) as! FriendsTableViewCell
//
// var filteredFriendsNames = [String]()
// if isFiltering() {
// filteredFriendsNames = filterNames(from: searchedNames, in: indexPath.section)
// } else {filteredFriendsNames = filterNames(from: friendsNames, in: indexPath.section)
// }
// cell.friendNameLabel.text = filteredFriendsNames[indexPath.row]
// let border = UIView()
// border.frame = cell.friendImageView.bounds
// border.layer.cornerRadius = cell.friendImageView.bounds.height / 2
// border.layer.masksToBounds = true
// cell.friendImageView.addSubview(border)
//
// let newFriendAvatar = UIImageView()
// newFriendAvatar.image = UIImage(named: "\(filteredFriendsNames[indexPath.row])")
//
// newFriendAvatar.frame = border.bounds
// border.addSubview(newFriendAvatar)
cell.configure(with: users[indexPath.row])
return cell
}
// override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
// if isFiltering() {
// return firstLetters(in: searchedNames)
// } else {
// return firstLetters(in: friendsNames)
// }
// }
@IBAction func back() {
Data.clearCookies()
self.dismiss(animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let imageView = UIImageView()
guard segue.identifier == "friendSeque",
let friendFotoController = segue.destination as? FriendCollectionViewController,
let row = tableView.indexPathForSelectedRow?.row else { return }
friendFotoController.friendName = "\(users[row].first_name) \(users[row].last_name)"
imageView.kf.setImage(with: URL(string: users[row].avatar))
if let image = imageView.image {
friendFotoController.friendImage = image
}
// if let image = UIImage(named: users[row].avatar) {
// friendFotoController.friendImage = image
// }
// friendImage.kf.setImage(with: URL(string: user.avatar))
}
// friendImageView.kf.setImage(with: URL(string: user.avatar))
// if let indexPath = self.tableView.indexPathForSelectedRow?.row {
// var filteredFriendsNames = [String]()
// if isFiltering() {
// filteredFriendsNames = filterNames(from: searchedNames ,in: indexPath.section)
// } else {
// filteredFriendsNames = filterNames(from: friendsNames ,in: indexPath.section)
// }
// friendFotoController.friendName = filteredFriendsNames[indexPath.row]
// if let image = UIImage(named: filteredFriendsNames[indexPath.row]) {
// friendFotoController.friendImage = image
// }
// }
// }
// }
func filterNames (from names: [String], in section: Int) -> [String] {
let key = firstLetters(in: names)[section]
return names.filter {$0.first! == Character(key)}
}
func firstLetters (in names: [String]) -> [String] {
let keys = [String](names)
var firstLetters: [String] = []
for key in keys {
firstLetters.append(String(key.first!))
}
return Array(Set(firstLetters)).sorted()
}
func searchBarIsEmpty() -> Bool {
// Returns true if the text is empty or nil
return searchController.searchBar.text?.isEmpty ?? true
}
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
searchedNames = friendsNames.filter({( name ) -> Bool in
return name.lowercased().contains(searchText.lowercased())
})
tableView.reloadData()
}
func isFiltering() -> Bool {
return searchController.isActive && !searchBarIsEmpty()
}
}
extension OuterView {
@IBInspectable
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable
var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
@IBInspectable
var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable
var shadowColor: UIColor? {
get {
if let color = layer.shadowColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.shadowColor = color.cgColor
} else {
layer.shadowColor = nil
}
}
}
}
extension FriendsViewController: UISearchResultsUpdating {
// MARK: - UISearchResultsUpdating Delegate
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
extension FriendsViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return presentTransition
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return dismissTransition
}
}
| true
|
eb79feb9db8071208b5c6d7f0a19751b62d3f445
|
Swift
|
Pashovich/ioslab1
|
/SpaceInvaders/FileReader.swift
|
UTF-8
| 1,221
| 3.109375
| 3
|
[] |
no_license
|
//
// FileReader.swift
// SpaceInvaders
//
// Created by administrator on 23.03.2021.
// Copyright © 2021 administrator. All rights reserved.
//
import Foundation
class FileReader {
private func readLocalFile(forName name: String) -> Data? {
do {
if let bundlePath = Bundle.main.path(forResource: name,
ofType: "json"),
let jsonData = try String(contentsOfFile: bundlePath).data(using: .utf8) {
return jsonData
}
} catch {
print(error)
}
return nil
}
private func parse(jsonData: Data) -> JsonData? {
var decodedData = JsonData()
do {
decodedData = try JSONDecoder().decode(JsonData.self,
from: jsonData)
return decodedData
} catch {
print("decode error")
}
return decodedData
}
func read(path : String) -> JsonData?{
if let localData = self.readLocalFile(forName: path) {
let jsonData = self.parse(jsonData: localData)
return jsonData
}
return nil
}
}
| true
|
238b944b1305767bcbd2e34fbde8cb1012cb2145
|
Swift
|
rf10ster/Viper-training
|
/MovieWebServiceTests/Mocks/MockMoviesListPresenter.swift
|
UTF-8
| 906
| 2.734375
| 3
|
[] |
no_license
|
//
// MockMoviesListPresenter
// MovieWebServiceTests
//
// Created by Aleksey Kiselev on 11/16/17.
// Copyright © 2017 TestCompany. All rights reserved.
//
import Foundation
import XCTest
@testable import MovieWebService
class MockMoviesListPresenter: MoviesListPresenterProtocol {
var triggerViewIsReadyCalled = false
var fetchFilmsCalled = false
var selectFilmCalled = false
var selectFilmCalledIndex = NSNotFound
func triggerViewIsReady() {
triggerViewIsReadyCalled = true
}
func fetchFilms() {
fetchFilmsCalled = true
}
func selectFilm(with index: Int) {
selectFilmCalled = true
selectFilmCalledIndex = index
}
// MARK:- MoviesListInteractorOutput helper
var films = [Film]()
}
extension MockMoviesListPresenter: MoviesListInteractorOutput {
func fetched(films: [Film]) {
self.films = films
}
}
| true
|
18aff56aef4cb195dd09cb2a76140e5fe7b392c9
|
Swift
|
maxwyb/Graphs
|
/GraphsExample/GraphsExample/MainViewController.swift
|
UTF-8
| 9,585
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// MainViewController.swift
// GraphsExample
//
// Created by HiraiKokoro on 2016/06/15.
// Copyright © 2016年 Recruit Holdings Co., Ltd. All rights reserved.
//
import UIKit
import Graphs
enum GraphExampleType: Int {
case
BarGraph1,
BarGraph2,
BarGraph3,
LineGraph1,
LineGraph2,
LineGraph3,
PieGraph1,
PieGraph2,
PieGraph3
static func count() -> Int {
return 9
}
}
class MainViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
@IBOutlet private var collectionView: UICollectionView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
self.collectionView.reloadData()
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
self.collectionView.reloadData()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.collectionView.reloadData()
}
// MARK: - UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return GraphExampleType.count()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! GraphCollectionViewCell
cell.graphView.subviews.forEach({ $0.removeFromSuperview() })
switch GraphExampleType(rawValue: indexPath.row)! {
case .BarGraph1:
let view = (1 ... 10).barGraph(GraphRange(min: 0, max: 11)).view(cell.graphView.bounds)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cell.graphView.addSubview(view)
cell.label.text = "let view = (1 ... 10).barGraph(GraphRange(min: 0, max: 11)).view(cell.graphView.bounds)"
case .BarGraph2:
let view = [8, 12, 20, -10, 6, 20, -11, 9, 12, 16, -10, 6, 20, -12].barGraph().view(cell.graphView.bounds).barGraphConfiguration({ BarGraphViewConfig(barColor: UIColor(hex: "#ff6699"), contentInsets: UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0)) })
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cell.graphView.addSubview(view)
cell.label.text = "[8, 12, 20, -10, 6, 20, -11, 9, 12, 16, -10, 6, 20, -12].barGraph().view(cell.graphView.bounds).barGraphConfiguration({ BarGraphViewConfig(barColor: UIColor(hex: \"#ff6699\"), contentInsets: UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0)) })"
case .BarGraph3:
let view = [8.0, 12.0, 20.0, 10.0, 6.0, 20.0, 11.0, 9.0, 12.0, 16.0, 10.0, 6.0, 20.0].barGraph(GraphRange(min: 0, max: 25)).view(cell.graphView.bounds).barGraphConfiguration({ BarGraphViewConfig(barColor: UIColor(hex: "#ccff66"), barWidthScale: 0.4) })
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cell.graphView.addSubview(view)
cell.label.text = "let view = [8.0, 12.0, 20.0, 10.0, 6.0, 20.0, 11.0, 9.0, 12.0, 16.0, 10.0, 6.0, 20.0].barGraph(GraphRange(min: 0, max: 25)).view(cell.graphView.bounds).barGraphConfiguration({ BarGraphViewConfig(barColor: UIColor(hex: \"#ccff66\"), barWidthScale: 0.4) })"
case .LineGraph1:
let view = (1 ... 10).lineGraph(GraphRange(min: 0, max: 11)).view(cell.graphView.bounds)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cell.graphView.addSubview(view)
cell.label.text = "let view = (1 ... 10).lineGraph(GraphRange(min: 0, max: 11)).view(cell.graphView.bounds)"
case .LineGraph2:
let view = [8, 12, 20, -10, 6, 20, -11, 9, 12, 16, -10, 6, 20, -12].lineGraph().view(cell.graphView.bounds).lineGraphConfiguration({ LineGraphViewConfig(lineColor: UIColor(hex: "#ff6699"), contentInsets: UIEdgeInsets(top: 32.0, left: 32.0, bottom: 32.0, right: 32.0)) })
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cell.graphView.addSubview(view)
cell.label.text = "[8, 12, 20, -10, 6, 20, -11, 9, 12, 16, -10, 6, 20, -12].lineGraph().view(cell.graphView.bounds).lineGraphConfiguration({ LineGraphViewConfig(lineColor: UIColor(hex: \"#ff6699\"), contentInsets: UIEdgeInsets(top: 32.0, left: 32.0, bottom: 32.0, right: 32.0)) })"
case .LineGraph3:
let view = [8.0, 12.0, 20.0, 10.0, 6.0, 20.0, 11.0, 9.0, 12.0, 16.0, 10.0, 6.0, 20.0].lineGraph(GraphRange(min: 0, max: 25)).view(cell.graphView.bounds).lineGraphConfiguration({ LineGraphViewConfig(lineColor: UIColor(hex: "#ccff33"), lineWidth: 2.0, dotDiameter: 20.0) })
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cell.graphView.addSubview(view)
cell.label.text = "[8.0, 12.0, 20.0, 10.0, 6.0, 20.0, 11.0, 9.0, 12.0, 16.0, 10.0, 6.0, 20.0].lineGraph(GraphRange(min: 0, max: 25)).view(cell.graphView.bounds).lineGraphConfiguration({ LineGraphViewConfig(lineColor: UIColor(hex: \"#ccff66\"), lineWidth: 1.0, dotDiameter: 10.0) })"
case .PieGraph1:
let view = (5 ... 10).pieGraph().view(cell.graphView.bounds)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cell.graphView.addSubview(view)
cell.label.text = "(5 ... 10).pieGraph().view(cell.graphView.bounds)"
case .PieGraph2:
let view = [8, 12, 20, 6, 20, 11, 9].pieGraph(){ (u, t) -> String? in String(format: "%.0f%%", (Float(u.value) / Float(t)))}.view(cell.graphView.bounds).pieGraphConfiguration({ PieGraphViewConfig(textFont: UIFont(name: "DINCondensed-Bold", size: 14.0), isDounut: true, contentInsets: UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0)) })
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cell.graphView.addSubview(view)
cell.label.text = "[8, 12, 20, 6, 20, 11, 9].pieGraph(){ (u, t) -> String? in String(format: \"%.0f%%\", (Float(u.value) / Float(t)))}.view(cell.graphView.bounds).pieGraphConfiguration({ PieGraphViewConfig(textFont: UIFont(name: \"DINCondensed-Bold\", size: 14.0), isDounut: true, contentInsets: UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0)) })"
case .PieGraph3:
let view = [8.5, 20.0].pieGraph(){ (u, t) -> String? in String(format: "%.0f%%", (Float(u.value) / Float(t)))}.view(cell.graphView.bounds).pieGraphConfiguration({ PieGraphViewConfig(textFont: UIFont(name: "DINCondensed-Bold", size: 14.0), isDounut: true, contentInsets: UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0)) })
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cell.graphView.addSubview(view)
cell.label.text = "[8.5, 20.0].pieGraph(){ (u, t) -> String? in String(format: \"%.0f%%\", (Float(u.value) / Float(t)))}.view(cell.graphView.bounds).pieGraphConfiguration({ PieGraphViewConfig(textFont: UIFont(name: \"DINCondensed-Bold\", size: 14.0), isDounut: true, contentInsets: UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0)) })"
}
return cell
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath)
return view
case _:
return UICollectionReusableView()
}
}
private let cellMargin = CGFloat(8.0)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let regularCollection = UITraitCollection(horizontalSizeClass: .regular)
let horizontalCellCount = self.traitCollection.containsTraits(in: regularCollection) ? 2 : 1
let width = (collectionView.frame.size.width - cellMargin * CGFloat(horizontalCellCount + 1)) / CGFloat(horizontalCellCount)
return CGSize(
width: width,
height: width * CGFloat(1.1)
)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.size.width, height: 120.0)
}
}
| true
|
bf4b63dbd1c51629f429c32b9de93c60ec4b8716
|
Swift
|
handeslfy/AspectsMaintain
|
/性能/AspectTest/AspectTest/ViewController.swift
|
UTF-8
| 686
| 2.625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// ViewController.swift
// AspectTest
//
// Created by Jz D on 2021/5/12.
//
import UIKit
import Aspect
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
_ = try? hook(selector: #selector(ViewController.test(id:name:))) { (_, id: Int, name: String) in
print("ha ha ha")
}
}
@objc dynamic func test(id: Int, name: String) {
print("come on")
}
@IBAction func btnClick(_ sender: Any) {
test(id: 666, name: "click")
}
}
| true
|
a9c1f89a7010f148a7380e9fb11722478744f61e
|
Swift
|
udacity/ios-nd-objc-problem-set
|
/Problem Set/Animals_Swift/Animals_Swift/main.swift
|
UTF-8
| 678
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
//
// main.swift
// Animals_Swift
//
// Created by Gabrielle Miller-Messner on 4/12/16.
// Copyright © 2016 Gabrielle Miller-Messner. All rights reserved.
//
import Foundation
// Initialize some animals
let babe = Pig()
let snoopy = GoldenDoodle()
let templeton = Rat()
let sinatra = Rat()
let cary = Pigeon()
// Initialize my dwellings with some animals
let myFarm = Farm(animals:[babe, snoopy, templeton])
let myApartment = Apartment(animals:[sinatra, cary, snoopy])
// Choose an animal to invoke a method
let randomNumber = Int(arc4random_uniform(3))
let farmAnimal = myFarm.animals![randomNumber]
let cityAnimal = myApartment.animals![randomNumber]
farmAnimal.scurry()
cityAnimal.deliverMessage()
| true
|
3a3ef1be71aafb7a3af4c7daa6583e751294f0f5
|
Swift
|
green-monkeys/handmade-iOS
|
/Handmade/AppDelegate.swift
|
UTF-8
| 3,749
| 2.65625
| 3
|
[] |
no_license
|
//
// AppDelegate.swift
// Handmade
//
// Created by Patrick Beninga on 4/4/19.
// Copyright © 2019 Patrick Beninga. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var cga:CGA?
var artisan:Artisan?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return AMZNAuthorizationManager.handleOpen(url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as! String)
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func parseCgaFromJSON(data:Data) -> CGA?{
do{
print("starting CGA parse")
print(data.description)
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
data, options: [])
print(jsonResponse) //Response resul
let jsontemp = jsonResponse as? [String: [String:Any]] ?? nil
if(jsontemp == nil) {
print("something went wrong here")
return nil
}
else {
let json = jsontemp!["data"]!
let imgURL = json["imageUrl"] as? String ?? ""
let cgaRes = CGA(email: json["email"] as! String,
firstName: json["first_name"] as! String,
lastName: json["last_name"] as! String,
Id : String(json["id"] as! Int),
imageURL: imgURL,
image: nil
)
cga = cgaRes
print("parsed CGA")
return cgaRes
}
} catch let parsingError {
print("Error", parsingError)
return nil
}
}
}
| true
|
5a710f2f5ef59e5b4a2e5c7448a1486440bfcab1
|
Swift
|
emilwojtaszek/collection-view-layout-examples
|
/ExampleApp/ViewController2.swift
|
UTF-8
| 2,205
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController2.swift
// ExampleApp
//
// Created by Emil Wojtaszek on 14/03/2017.
// Copyright © 2017 AppUnite Sp. z o.o. All rights reserved.
//
import UIKit
class ViewController2: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
// register elements
collectionView?.register(TextCell.self,
forCellWithReuseIdentifier: TextCell.reuseIdentifier)
// setup collection view layout
let layout = self.collectionViewLayout as! AnimationLayout
layout.separatorColor = .blue
layout.separatorHeight = 4.0
}
/// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// dequeue cell
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: TextCell.reuseIdentifier,
for: indexPath) as! TextCell
// update text
cell.titleLabel.text = "Cell: (\(indexPath.section),\(indexPath.row))"
return cell
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 25
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
/// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
/// update layout property and set index path of selected cell
let layout = self.collectionViewLayout as! AnimationLayout
layout.expandedIndexPath = layout.expandedIndexPath == indexPath ? nil : indexPath
/// invalidation layout in animation block
UIView.animate(
withDuration: 0.4,
delay: 0.0,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.0,
options: UIViewAnimationOptions(),
animations: {
layout.invalidateLayout()
self.collectionView?.layoutIfNeeded()
},
completion: nil
)
}
}
| true
|
b3ac89be355796fafbf2b402e6ac52d04efbaac7
|
Swift
|
Babita251/NewsFeed
|
/NewsFeedApp/NewsFeedParserModel.swift
|
UTF-8
| 2,973
| 2.734375
| 3
|
[] |
no_license
|
//
// NewsFeedParserModel.swift
// NewsFeedApp
//
// Created by babita pal on 23/07/21.
//
import Foundation
class NewsFeedParserModel: NSObject {
public var thumbnail: String?
public var pubDate: String?
public var link: String?
public var title: String?
public var author: String?
init(thumbnail: String,pubDate: String, link: String, title: String, author: String) {
self.thumbnail = thumbnail
self.pubDate = pubDate
self.link = link
self.title = title
self.author = author
}
// var newsDataArray:[NSMutableDictionary] = []
// var elements = NSMutableDictionary()
// var element = String()
// var thumbnail = NSMutableString()
// var pubDate = NSMutableString()
// var link = NSMutableString()
// var author = NSMutableString()
//
// init(data: Data?) {
// super.init()
// if let newsFeedData = data {
// let parser = XMLParser(data: newsFeedData)
// parser.delegate = self
// parser.parse()
// }
// }
//
//
// func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
// {
// element = elementName
// if (elementName as NSString).isEqual(to: "items")
// {
// elements = NSMutableDictionary()
// elements = [:]
// pubDate = NSMutableString()
// pubDate = ""
// link = NSMutableString()
// link = ""
// author = NSMutableString()
// author = ""
// thumbnail = NSMutableString()
// thumbnail = ""
// }
//
// }
//
// func parser(_ parser: XMLParser, foundCharacters string: String)
// {
// if element.isEqual("pubDate") {
// pubDate.append(string)
// } else if element.isEqual("link") {
// link.append(string)
// } else if element.isEqual("author") {
// author.append(string)
// } else if element.isEqual("thumbnail") {
// thumbnail.append(string)
// }
//
// }
//
// func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
// {
// if (elementName as NSString).isEqual(to: "items") {
// if !pubDate.isEqual(nil) {
// elements.setObject(pubDate, forKey: "pubDate" as NSCopying)
// }
// if !link.isEqual(nil) {
// elements.setObject(link, forKey: "link" as NSCopying)
// }
// if !author.isEqual(nil) {
// elements.setObject(author, forKey: "author" as NSCopying)
// }
// if !thumbnail.isEqual(nil) {
// elements.setObject(thumbnail, forKey: "thumbnail" as NSCopying)
// }
//
// newsDataArray.append(elements)
// }
// }
//
}
| true
|
597e11c64151aac421d92398a8205725d3ef5c6e
|
Swift
|
marcos1262/ios-recruiting-brazil
|
/ConcreteChallenge/ConcreteChallenge/Model/Movie.swift
|
UTF-8
| 2,109
| 2.96875
| 3
|
[] |
no_license
|
//
// Movie+CoreDataClass.swift
//
//
// Created by Marcos Santos on 19/12/19.
//
//
import Foundation
import CoreData
import UIKit
@objc(Movie)
public class Movie: NSManagedObject, Decodable {
public var image: UIImage = .placeholder
enum CodingKeys: String, CodingKey {
case id
case imagePath = "poster_path"
case overview
case releaseDate = "release_date"
case title
case genres = "genres"
}
// MARK: Codable
required convenience public init(from decoder: Decoder) throws {
try self.init(saving: false)
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int64.self, forKey: .id)
imagePath = try container.decode(String.self, forKey: .imagePath)
overview = try container.decode(String.self, forKey: .overview)
title = try container.decode(String.self, forKey: .title)
releaseDate = try decoder.decode(CodingKeys.releaseDate, using: DateFormatter.databaseDate)
if let genres = try container.decodeIfPresent([Genre].self, forKey: .genres) {
for genre in genres {
addToGenres(genre)
genre.addToMovies(self)
}
}
}
func isSaved() throws -> Bool {
return (try Self.queryById(Int(id))) != nil
}
func insertIntoContext() throws {
if !isInserted {
let context = try CoreDataManager.getContext()
context.insert(self)
for genre in (genres?.allObjects as? [Genre]) ?? [] {
try genre.insertIntoContext()
}
}
}
@discardableResult
func deepCopy(saving: Bool = true) throws -> Movie {
let movie = try Movie(saving: saving)
movie.id = id
movie.imagePath = imagePath
movie.overview = overview
movie.releaseDate = releaseDate
movie.title = title
for genre in (genres?.allObjects as? [Genre]) ?? [] {
movie.addToGenres(try genre.deepCopy(saving: saving))
}
return movie
}
}
| true
|
39813b68e2f4cdd7fe38d918d3d3316a224b68d6
|
Swift
|
February33/Projects
|
/ViewController/ViewController/ViewControllerTwo.swift
|
UTF-8
| 3,572
| 2.75
| 3
|
[] |
no_license
|
//
// ViewControllerTwo.swift
// ViewController
//
// Created by XP on 6/30/19.
// Copyright © 2019 XP. All rights reserved.
//
import UIKit
class ViewControllerTwo: UIViewController {
@IBOutlet weak var beautyLabel: UILabel!
@IBOutlet weak var happyLabel: UILabel!
@IBOutlet weak var happyButton: UIButton!
override func loadView() {
super.loadView()
print("loadView")
}
override func viewDidLoad() {
super.viewDidLoad()
print("viewDidLoad")
hello()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("viewWillAppear")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print("viewDidLayoutSubviews")
}
func hello() {
print("Hi")
}
@IBAction func beautyButton(_ sender: UIButton) {
self.alertForBeauty(title: "BEAUTY", message: "What is your name?", style: .alert)
}
@IBAction func healthButton(_ sender: UIButton) {
self.alert(title: "HEALTH", message: "You can visit a doctor!", style: .actionSheet)
}
@IBAction func happyButton(_ sender: UIButton) {
self.alertForHappy(title: "HAPPY", message: "What is the secret?", style: .alert)
happyButton.backgroundColor = (happyButton.backgroundColor == #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1) ? #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1) : #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1))
}
@IBAction func foodButton(_ sender: UIButton) {
self.alert(title: "FOOD", message: "You can cook something!", style: .actionSheet)
}
//MARK: - General alert
func alert(title: String, message: String, style: UIAlertController.Style) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: style)
let action = UIAlertAction(title: "ok", style: .default, handler: nil)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
//MARK: - Alert for Beauty button
func alertForBeauty(title: String, message: String, style: UIAlertController.Style) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: style)
let action = UIAlertAction(title: "ok", style: .cancel) { (action) in
let text = alertController.textFields?.first
self.beautyLabel.text! += (text?.text)! + (" is beautiful!")
}
alertController.addTextField(configurationHandler: nil)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
//MARK: - Alert for Happy button
func alertForHappy(title: String, message: String, style: UIAlertController.Style) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: style)
let action = UIAlertAction(title: "ok", style: .cancel) { (action) in
let text = alertController.textFields?.first
self.happyLabel.text! += (text?.text)! + (" is happy secret!")
}
alertController.addTextField { (textField) in
textField.isSecureTextEntry = true
}
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
}
| true
|
37c3777d1b6864b7ca6bdf14a13ba43d57d5a628
|
Swift
|
kjk402/todo-list
|
/ios/ToDoListApp/ToDoListApp/Data/Network/Endpoint.swift
|
UTF-8
| 1,776
| 3.3125
| 3
|
[] |
no_license
|
//
// Endpoint.swift
// ToDoListApp
//
// Created by zombietux on 2021/04/08.
//
import Foundation
import Combine
struct Endpoint {
var path: String
var queryItems: [URLQueryItem] = []
}
//1. URL 생성
extension Endpoint {
var url: URL {
var components = URLComponents()
components.scheme = "http"
components.host = "localhost"
components.port = 3000
components.path = "\(path)"
guard let url = components.url else {
preconditionFailure("Invalid URL components: \(components)")
}
return url
}
}
extension Endpoint {
//GET용
static func cards(state: State) -> Self {
return Endpoint(path: "/cards/\(state.rawValue)")
}
//POST용
static func add(columnId: Int) -> Self {
print(Endpoint(path: "/cards/\(columnId+1)").url)
return Endpoint(path: "/cards/\(columnId+1)")
}
static func remove(state: State) -> Self {
return Endpoint(path: "/remove",
queryItems: [
URLQueryItem(name: "\(state.rawValue)",
value: "\(state.rawValue)_id")
]
)
}
static func update(id: Int) -> Self {
return Endpoint(path: "/update\(id)")
}
static func move(state: State) -> Self {
return Endpoint(path: "/move",
queryItems: [
URLQueryItem(name: "\(state.rawValue)",
value: "\(state.rawValue)_id")
]
)
}
}
enum State: Int {
case todo = 1
case doing = 2
case done = 3
var state: Int {
return rawValue
}
}
| true
|
44c27e0f098133ec0892131ade0cf786109628cf
|
Swift
|
timmybea/StackExploration
|
/LIFOUses/Stack.swift
|
UTF-8
| 1,405
| 3.75
| 4
|
[] |
no_license
|
//
// Stack.swift
// LIFOUses
//
// Created by Tim Beals on 2018-10-20.
// Copyright © 2018 Roobi Creative. All rights reserved.
//
import Foundation
class Node<T: CustomStringConvertible> : CustomStringConvertible {
var value: T
weak var previous: Node<T>?
var next: Node<T>?
init(value: T) {
self.value = value
}
var description: String {
return value.description
}
}
class Stack<T: CustomStringConvertible> {
var rootNode: Node<T>?
var endNode: Node<T>?
init() {}
init(values: T...) {
for val in values {
push(value: val)
}
}
func push(value: T) {
let newNode = Node<T>(value: value)
if let end = endNode {
end.next = newNode
newNode.previous = end
} else {
rootNode = newNode
}
endNode = newNode
}
func pop() -> T? {
let val = endNode?.value
if endNode === rootNode {
rootNode = nil
}
endNode = endNode?.previous
endNode?.next = nil
return val
}
func isEmpty() -> Bool {
return rootNode == nil
}
func printStack() {
var currentNode = rootNode
while currentNode != nil {
print(currentNode!.value)
currentNode = currentNode?.next
}
}
}
| true
|
fdeedcc062c554c3229f57a9bcbdbcc7da9d746f
|
Swift
|
kariipaula/lentesDeAvaliacao
|
/LentesDeAvaliacao/View+Extension.swift
|
UTF-8
| 807
| 2.859375
| 3
|
[] |
no_license
|
import SwiftUI
extension UIView {
var screenShot: UIImage {
let rect = self.bounds
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
let context: CGContext = UIGraphicsGetCurrentContext()!
self.layer.render(in: context)
let capturedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return capturedImage
}
}
extension View {
func takeScreenshot(origin: CGPoint, size: CGSize) -> UIImage {
let window = UIWindow(frame: CGRect(origin: origin, size: size))
let hosting = UIHostingController(rootView: self)
hosting.view.frame = window.frame
window.addSubview(hosting.view)
window.makeKeyAndVisible()
return hosting.view.screenShot
}
}
| true
|
223cf337f3ba70e52d45ff8f50295db06b659ca7
|
Swift
|
YonahKarp/CheeseChase
|
/Cheese Chase/GameScene.swift
|
UTF-8
| 14,833
| 2.65625
| 3
|
[] |
no_license
|
//
// GameScene.swift
// Cheese Chase
//
// Created by Yk Jt on 4/5/16.
// Copyright (c) 2016 Immersion ULTD. All rights reserved.
//
import SpriteKit
//globals
var boxWidth = CGFloat(0.0) //changed lower down
var boxHeight = CGFloat(0.0)
var boardBeginsX = CGFloat(0.0)
var boardBeginsY = CGFloat(0.0)
class GameScene: SKScene {
//variables in scene scope
var level = Level()
let board = SKSpriteNode(imageNamed: "board")
var map : [String]!
var mouse : Mouse!
var cat : Cat!
var cheese = [(node: SKSpriteNode(), x: Int(), y: Int())]
var hud : CheeseHud!
let overlayBackground = SKSpriteNode(imageNamed: "WoodGrain")
let gameMessage = SKLabelNode(fontNamed:"IowanOldStyle-Italic")
var resetMessage = SKLabelNode(fontNamed: "IowanOldStyle-Italic")
var exitMessage = SKLabelNode(fontNamed: "IowanOldStyle-Italic")
let pauseButton = SKSpriteNode(imageNamed: "Pause");
let menuButton1 = SKSpriteNode(imageNamed: "Button")
let menuButton2 = SKSpriteNode(imageNamed: "Button")
var barriers = [SKSpriteNode]();
var barriersVertical = Array(repeating: Array(repeating: Barrier(), count: 7), count: 7)
var barriersHorizontal = Array(repeating: Array(repeating: Barrier(), count: 7), count: 7)
var oneWays = [SKSpriteNode]();
var hole = SKSpriteNode()
var catsTurn = false
var cheeseCount = 0
var creditVal = PlistManager.sharedInstance.getValueForKey("cheeseCredits") as! Int
init(size: CGSize, lvlInt: Int){
super.init(size: size)
level = level.createLevel(lvlInt)
initShared(level: level)
}
//For tutorial
override init(size: CGSize){
super.init(size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initShared(level: Level){
cat = Cat(scene: self, x: level.cat.x, y: level.cat.y)
mouse = Mouse(scene: self, x: level.mouse.x, y: level.mouse.y)
map = level.map
cheese = level.cheese
hud = CheeseHud(scene: self)
hud.setUpHud()
hud.frameImage.isHidden = true
setBoard()
setUpPlayers()
setUpCheese()
}
override func didMove(to view: SKView) {
//swipe gesture recignizers
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeLeft.direction = UISwipeGestureRecognizer.Direction.left
self.view!.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeRight.direction = UISwipeGestureRecognizer.Direction.right
self.view!.addGestureRecognizer(swipeRight)
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeUp.direction = UISwipeGestureRecognizer.Direction.up
self.view!.addGestureRecognizer(swipeUp)
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeDown.direction = UISwipeGestureRecognizer.Direction.down
self.view!.addGestureRecognizer(swipeDown)
setUpOverlay() //don't know why this can't be moved to initShared, but it puts buttons in wacky places if I do
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
/* Called when a touch ends */
for touch in touches {
let location = touch.location(in: self)
//quit
if menuButton2.frame.contains(location) && !overlayBackground.isHidden{
exit()
}
//retry
else if menuButton1.frame.contains(location) && !overlayBackground.isHidden{
if((PlistManager.sharedInstance.getValueForKey("cheeseCredits") as! Int) < 3){
return
}
resetMessage.fontColor = UIColor.gray
removeCredits()
reset(lvlInt: level.lvlInt)
}
//pause
else if pauseButton.frame.contains(location) {
if((overlayBackground.isHidden)){
displayOverlay(message: "Paused")
pauseButton.texture = SKTexture(imageNamed: "Play")
}else{
overlayBackground.isHidden = true
hud.frameImage.isHidden = true
gameMessage.text = ""
pauseButton.texture = SKTexture(imageNamed: "Pause")
}
}
}
}
override func update(_ currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if(NSDate().timeIntervalSince(hud.rechargeTime as Date) > 600){
hud.manageCredits()
}
hud.setTime()
}
func setBoard(){
//board.position = CGPoint(x:CGRectGetMinX(self.frame) + board.frame.width/2, y:CGRectGetMinY(self.frame) + board.frame.width/2)
board.size.width = self.size.width
board.size.height = self.size.height
boxWidth = (board.frame.width*0.7119341563786) / 6
boxHeight = (board.frame.height*0.74209650582363) / 6
boardBeginsX = board.frame.minX + board.frame.width*0.10288065843621
boardBeginsY = board.frame.maxY - board.frame.height*0.25833333333333
for i in 0..<13{
for j in 0..<map[i].characters.count/2+1{
switch map[i][2*j]{
case "=": barriersHorizontal[j][6 - Int(i/2)] = Barrier(imageNamed: "barrier", parentScene: self, type: "horizontal", x: j, y: i/2)
case "║": barriersVertical[j][5 - Int(i/2)] = Barrier(imageNamed: "barrier", parentScene: self, type: "vertical", x: j, y: i/2+1)
case ">": barriersVertical[Int(j/2)][5 - Int(i/2)] = Barrier(imageNamed: "oneWay", parentScene: self, type: "right", x: j, y: i/2+1)
case "<": barriersVertical[Int(j/2)][5 - Int(i/2)] = Barrier(imageNamed: "oneWay", parentScene: self, type: "left", x: j, y: i/2+1)
case "^": barriersHorizontal[Int(j/2)][6 - Int(i/2)] = Barrier(imageNamed: "oneWay", parentScene: self, type: "up", x: j, y: i/2)
case "V": barriersHorizontal[Int(j/2)][6 - Int(i/2)] = Barrier(imageNamed: "oneWay", parentScene: self, type: "down", x: j, y: i/2)
case "C": barriersVertical[Int(j)][5 - Int(i/2)] = Barrier(imageNamed: "welcomeMat", parentScene: self, type: "holeVert", x: j, y: i/2+1)
case "U": barriersHorizontal[Int(j)][6 - Int(i/2)] = Barrier(imageNamed: "welcomeMat", parentScene: self, type: "holeHorz", x: j, y: i/2)
case "|","-": break;
default:
print("invalid character")
}
}//end j
}//end i
self.addChild(board)
}
func setUpPlayers(){
mouse.position = CGPoint(x: boardBeginsX + boxWidth/2 + CGFloat(mouse.x)*boxWidth, y:(board.frame.minY + boxHeight/2) + CGFloat(mouse.y)*boxHeight)
let bounce = SKAction.sequence([SKAction.moveBy(x: 0, y: 5, duration: 0.3), SKAction.moveBy(x: 0, y: -5, duration: 0.3)])
mouse.run(SKAction.repeatForever(bounce), withKey: "bounce")
self.addChild(mouse)
cat.size = CGSize(width: boxHeight, height: boxHeight*14/10)
cat.position = CGPoint(x: boardBeginsX + boxWidth/2 + CGFloat(cat.x)*boxWidth, y:(board.frame.minY + boxHeight/2) + CGFloat(cat.y)*boxHeight)
self.addChild(cat)
}
func setUpCheese(){
for tempCheese in cheese{
tempCheese.node.position = CGPoint(x: boardBeginsX + (boxWidth*CGFloat(tempCheese.x) + boxWidth/2), y: board.frame.minY+(CGFloat(tempCheese.y)*boxHeight + boxHeight/2))
tempCheese.node.zPosition = 1
tempCheese.node.xScale = 0.5
tempCheese.node.yScale = 0.5
self.addChild(tempCheese.node)
}
}
func setUpOverlay(){
self.backgroundColor = UIColor.gray
gameMessage.text = ""
gameMessage.fontSize = 40
gameMessage.zPosition = 7
gameMessage.position = CGPoint(x:self.frame.midX, y:self.frame.midY + overlayBackground.frame.height/4)
gameMessage.fontColor = UIColor.black
menuButton1.position = CGPoint(x: gameMessage.position.x - overlayBackground.frame.width/5, y: gameMessage.position.y - overlayBackground.frame.height/2)
menuButton1.zPosition = 7
menuButton2.position = CGPoint(x: gameMessage.position.x + overlayBackground.frame.width/5, y: gameMessage.position.y - overlayBackground.frame.height/2)
menuButton2.zPosition = 7
resetMessage.text = ""
resetMessage.fontSize = 35
resetMessage.zPosition = 8
resetMessage.position = CGPoint(x: 0, y: -menuButton1.frame.height/10)
resetMessage.fontColor = UIColor.black
exitMessage.text = ""
exitMessage.fontSize = 35
exitMessage.zPosition = 8
exitMessage.position = CGPoint(x: 0, y: -menuButton1.frame.height/10)
exitMessage.fontColor = UIColor.black
pauseButton.zPosition = 7
pauseButton.position = CGPoint(x: -self.frame.width/2 + pauseButton.frame.width, y: self.frame.height/2 - pauseButton.frame.height)
overlayBackground.zPosition = 6
overlayBackground.isHidden = true
self.addChild(overlayBackground)
overlayBackground.addChild(gameMessage)
overlayBackground.addChild(menuButton1)
overlayBackground.addChild(menuButton2)
menuButton1.addChild(resetMessage)
menuButton2.addChild(exitMessage)
self.addChild(pauseButton);
}
///Swipe respond
@objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
if(!catsTurn && gameMessage.text == ""){
switch swipeGesture.direction {
case UISwipeGestureRecognizer.Direction.right:
mouse.move(boxWidth, y: 0, angle: CGFloat(M_PI/2), direction: "right")
case UISwipeGestureRecognizer.Direction.down:
mouse.move(0, y: -boxHeight, angle: CGFloat(0), direction: "down")
case UISwipeGestureRecognizer.Direction.left:
mouse.move(-boxWidth, y: 0, angle: CGFloat(3*M_PI/2), direction: "left")
case UISwipeGestureRecognizer.Direction.up:
mouse.move(0, y: boxHeight, angle: CGFloat(M_PI), direction: "up")
default:
mouse.move(0, y: 0, angle: 0, direction: "null")
break
}
}
}
}
func checkCheese(){
cheese = cheese.filter{ cheese in
if (mouse.frame.intersects(cheese.node.frame)) {
cheese.node.removeFromParent()
cheeseCount += 1
return false //don't keep this cheese
}
else {
return true //keep this cheese
}
}
}
func checkTutorial(){
//overriden
}
func checkWin() -> Bool{
//if (!CGRectIntersectsRect(mouse.node.frame, board.frame) && cheeseCount == 3){
if(mouse.x < 0 || mouse.x > 5 || mouse.y < 0 || mouse.y > 5){
gameMessage.text = "Great Job!!!"
pauseButton.removeFromParent()
menuButton1.removeFromParent()
menuButton2.position = CGPoint(x: gameMessage.position.x, y: gameMessage.position.y - overlayBackground.frame.height/2)
menuButton2.size.width *= 2
exitMessage.text = "next level"
overlayBackground.isHidden = false
hud.frameImage.isHidden = false
cheeseCount = 4
return true
}
return false
}
func checkGameOver(){
//if (CGRectIntersectsRect(cat.node.frame, mouse.node.frame) && gameMessage.text == ""){
if(cat.x == mouse.x && cat.y == mouse.y){
displayOverlay(message: "Game over")
}
}
func displayOverlay(message: String){
overlayBackground.isHidden = false
hud.frameImage.isHidden = false
gameMessage.text = message
resetMessage.text = "retry"
exitMessage.text = "quit"
if(creditVal < 3){
menuButton1.color = .white
}
}
func reset(lvlInt: Int){
//let lvlInt = self.level.lvlInt
let size = self.view!.bounds.size
let gameScene : GameScene
if(lvlInt < 1){
gameScene = TutorialScene(size: size, tLvlInt: lvlInt) //tutorial
}
else{
gameScene = GameScene(size: size, lvlInt: lvlInt)
}
let transition = SKTransition.fade(with: UIColor.black, duration: 1.5)
gameScene.scaleMode = .resizeFill
gameScene.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.view?.presentScene(gameScene, transition: transition)
}
func exit(){
let stageSelect = StageSelect()
let transition = SKTransition.fade(with: UIColor.black, duration: 1)
stageSelect.scaleMode = .resizeFill
stageSelect.anchorPoint = CGPoint(x: 0.5, y: 0.5)
stageSelect.size = self.view!.bounds.size
self.view?.presentScene(stageSelect, transition: transition)
}
func removeCredits(){
if(creditVal == 15){
PlistManager.sharedInstance.saveValue(NSDate(), forKey: "rechargeTime")
}
//creditVal = creditVal - 3
PlistManager.sharedInstance.saveValue(creditVal as AnyObject, forKey: "cheeseCredits")
}
}//end
//some extension methods
extension CGFloat{
func getSign() -> CGFloat{
if(self < 0){
return -1
}
if(self > 0){
return 1
}
return 0
}
}
extension String {
subscript (i: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: i)]
}
}
| true
|
406c9a40c2b7dd97dfe3b7e9ba43b3fad54b3d82
|
Swift
|
sekyunoh/lingo-recording
|
/lingo/Scenes/QuizTableCell.swift
|
UTF-8
| 3,143
| 2.5625
| 3
|
[] |
no_license
|
//
// QuizTableCell.swift
// lingo
//
// Created by Taehyun Park on 3/8/16.
// Copyright © 2016 Tech Savvy Mobile Co., Ltd. All rights reserved.
//
import UIKit
import SnapKit
class QuizTableCell: UITableViewCell {
static let id = "Quiz"
var nameLabel: UILabel!
var authorLabel: UILabel!
var scoreLabel: UILabel!
var statusLabel: UILabel!
var syncImage: UIImageView!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier)
selectionStyle = .None
self.separatorInset = UIEdgeInsetsZero
initSubViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func initSubViews() {
nameLabel = UILabel().then {
$0.font = UIFont.boldSystemFontOfSize(18)
}
addSubview(nameLabel)
nameLabel.snp_makeConstraints {
$0.top.left.equalTo(self).offset(16)
}
syncImage = UIImageView().then {
$0.contentMode = .ScaleAspectFit
$0.image = UIImage(named: "alert-circle")
}
addSubview(syncImage)
syncImage.snp_makeConstraints {
$0.left.equalTo(nameLabel.snp_right).offset(4)
$0.centerY.equalTo(nameLabel)
$0.size.equalTo(16)
}
authorLabel = UILabel().then {
$0.font = UIFont.systemFontOfSize(14)
}
addSubview(authorLabel)
authorLabel.snp_makeConstraints {
$0.left.equalTo(self).offset(16)
$0.bottom.equalTo(self).offset(-16)
$0.top.greaterThanOrEqualTo(nameLabel).offset(8)
}
scoreLabel = UILabel().then {
$0.font = UIFont.systemFontOfSize(18)
$0.textColor = UIColor.orangeColor()
}
addSubview(scoreLabel)
scoreLabel.snp_makeConstraints {
$0.top.equalTo(self).offset(16)
$0.right.equalTo(self).offset(-16)
}
statusLabel = UILabel().then {
$0.font = UIFont.systemFontOfSize(14)
}
addSubview(statusLabel)
statusLabel.snp_makeConstraints {
$0.right.equalTo(self).offset(-16)
$0.bottom.equalTo(self).offset(-16)
}
}
func bindTo(quiz: Quiz) {
syncImage.hidden = true
nameLabel.text = quiz.name
authorLabel.text = quiz.authorName + " 선생님"
if quiz.status == QuizStatus.Solved.rawValue {
statusLabel.text = "응시 완료"
scoreLabel.text = String(format:" %.1f", quiz.score)
scoreLabel.textColor = UIColor.orangeColor()
if quiz.sync != SyncStatus.Synchronized.rawValue {
syncImage.hidden = false
}
} else {
let currentTime = NSDate()
if (quiz.startDate > currentTime) {
statusLabel.textColor = UIColor.greenColor()
statusLabel.text = "\(quiz.startDate.timespan) 응시 가능"
} else if(quiz.dueDate > currentTime) {
statusLabel.textColor = UIColor.greenColor()
statusLabel.text = "\(quiz.dueDate.timespan) 응시 마감"
} else {
statusLabel.textColor = App.errorColor
statusLabel.text = "응시 마감됨"
}
scoreLabel.text = "--"
}
}
}
| true
|
2be6a1ea427d4be89a1865b9d6512fef36911d81
|
Swift
|
djones/Cameo
|
/Cameo/QuickLookViewController.swift
|
UTF-8
| 1,021
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// QuickLookPopover.swift
// Cameo
//
// Created by Tamás Lustyik on 2018. 12. 27..
// Copyright © 2018. Tamas Lustyik. All rights reserved.
//
import Cocoa
import Carbon.HIToolbox.Events
final class QuickLookViewController: NSViewController {
@IBOutlet private var textView: NSTextView!
var content: String = "" {
didSet {
guard isViewLoaded else { return }
textView.string = content
}
}
override var nibName: NSNib.Name? {
return "QuickLookView"
}
override func viewDidLoad() {
super.viewDidLoad()
let desc = NSFontDescriptor(name: "Monaco", size: 11)
textView.font = NSFont(descriptor: desc, size: 11)
preferredContentSize = NSSize(width: 500, height: 250)
textView.string = content
}
override func keyDown(with event: NSEvent) {
if event.keyCode == kVK_Space {
dismiss(nil)
return
}
super.keyDown(with: event)
}
}
| true
|
e8c663431568fc27e3ddb908dacfda7f1361c6e8
|
Swift
|
brendanater/retrolux-1.0.0
|
/Retrolux/Response.swift
|
UTF-8
| 7,049
| 2.796875
| 3
|
[] |
no_license
|
//
// Response.swift
// Retrolux
//
// Created by Brendan Henderson on 10/25/17.
// Copyright © 2017 Christopher Bryan Henderson. All rights reserved.
//
import Foundation
extension Errors {
public struct Response_ {
private init() {_ = Response<Any>.self }
public struct NoBodyOrError: Error, CustomStringConvertible {
public var description: String {
return "No body or error in interpreted response"
}
}
}
}
public struct Response<T> {
public var body: T?
public let urlResponse: URLResponse?
public var error: Error?
public let originalRequest: URLRequest
public let metrics: URLSessionTaskMetrics?
public let resumeData: Data?
public var isValid: Bool
public init(body: T?, urlResponse: URLResponse? = nil, error: Error?, originalRequest: URLRequest, metrics: URLSessionTaskMetrics? = nil, resumeData: Data? = nil, isValid: Bool) {
self.body = body
self.urlResponse = urlResponse
self.error = error
self.originalRequest = originalRequest
self.metrics = metrics
self.resumeData = resumeData
self.isValid = isValid
}
}
extension Response {
// MARK: Interpret
public enum Interpreted {
case body(T)
case error(Error?)
}
public func interpreted() -> Interpreted {
return self.body.map { .body($0) } ?? .error(self.error)
}
public func interpret() throws -> T {
return try self.body ?? { throw self.error ?? Errors.Response_.NoBodyOrError() }()
}
// map
public func convert<U>(_ f: (Response<T>)throws->U?) -> Response<U> {
var body: U? = nil
var error: Error? = nil
do {
body = try f(self)
} catch let _error {
error = _error
}
return Response<U>(
body: body,
urlResponse: self.urlResponse,
// previous errors take precedence
error: self.error ?? error,
originalRequest: self.originalRequest,
metrics: self.metrics,
resumeData: self.resumeData,
isValid: self.isValid ? error == nil : false
)
}
// data
// convenience
public var httpURLResponse: HTTPURLResponse? {
return self.urlResponse as? HTTPURLResponse
}
public var statusCode: Int? {
return self.httpURLResponse?.statusCode
}
public var mimeType: String? {
return self.urlResponse?.mimeType
}
public var expectedContentLength: Int64? {
return self.urlResponse?.expectedContentLength
}
public var allHeaderFields: [String: String]? {
return self.httpURLResponse?.allHeaderFields as? [String: String]
}
}
extension Response where T: Equatable {
public static func ==(lhs: Response, rhs: Response) -> Bool {
return lhs.body == rhs.body
&& (type(of: lhs.error) == type(of: rhs.error) && (lhs.error.map { String(describing: $0) } == rhs.error.map { String(describing: $0) }))
&& lhs.isValid == rhs.isValid
&& lhs.originalRequest == rhs.originalRequest
&& lhs.urlResponse == rhs.urlResponse
}
}
extension Response where T == DataBody {
public func data(memoryThreshold: Int64 = Retrolux.defaultMemoryThreshold()) throws -> Data {
return try self.interpret().asData(memoryThreshold: memoryThreshold)
}
}
//// MARK: ClientResponse
//
//public struct ClientResponse: Equatable {
//
// public let originalRequest: URLRequest
// public var data: AnyData?
// public let urlResponse: URLResponse?
// public var error: Error?
//
// public var isValid: Bool
//
// /// the max data to load into memory from self.data (URL)
// public var maxStreamMemory: Int = 5_000_000
//
// public init(_ originalRequest: URLRequest, _ data: AnyData?, _ urlResponse: URLResponse?, _ error: Error?) {
//
// self.originalRequest = originalRequest
// self.data = data
// self.urlResponse = urlResponse
// self.error = error
//
// self.isValid = data != nil
// }
//
// public init(_ originalRequest: URLRequest, _ data: Data?, _ urlResponse: URLResponse?, _ error: Error?) {
// self.init(originalRequest, data.map { .data($0) }, urlResponse, error)
// }
//
// public init(_ originalRequest: URLRequest, _ url: URL?, _ urlResponse: URLResponse?, _ error: Error?) {
// self.init(originalRequest, url.map { .atURL($0) }, urlResponse, error)
// }
//
// // returns a client response with no data, urlResponse, or error
// public static func empty(_ originalRequest: URLRequest) -> ClientResponse {
// return ClientResponse(originalRequest, Data?.none, nil, nil)
// }
//
// public enum ClientResponseError: Error {
// case noDataOrError
// }
//
// // MARK: get values
//
// public func getResponse() throws -> AnyData {
//
// return try self.data ?? { throw self.error ?? ClientResponseError.noDataOrError }()
// }
//
// public func getData() throws -> Data {
// return try self.getResponse().asData(maxStreamSize: self.maxStreamMemory)
// }
//
//// public func json(options: JSONSerialization.ReadingOptions = []) throws -> Any {
////
//// return try JSONSerialization.jsonObject(with: self.getData(), options: options)
//// }
////
//// public func string(encoding: String.Encoding? = nil) throws -> String? {
////
//// let encoding = encoding ?? self.httpURLResponse?.httpHeaders.contentType?.encoding ?? .utf8
//// return try String(data: self.getData(), encoding: encoding)
//// }
////
//// public func decodable<T: Decodable>(_: T.Type = T.self, decoder: TopLevelDecoder = JSONDecoder()) throws -> T {
//// return try decoder.decode(from: self.getData())
//// }
////
// public static func ==(lhs: ClientResponse, rhs: ClientResponse) -> Bool {
//
// return lhs.data == rhs.data
// && lhs.urlResponse == rhs.urlResponse
// && (lhs.error == nil) == (rhs.error == nil)
// && lhs.originalRequest == rhs.originalRequest
// && lhs.isValid == rhs.isValid
// }
//
// public var httpURLResponse: HTTPURLResponse? {
// return self.urlResponse as? HTTPURLResponse
// }
//
// public var statusCode: Int? {
// return self.httpURLResponse?.statusCode
// }
//
// public var mimeType: String? {
// return self.urlResponse?.mimeType
// }
//
// public var allHeaderFields: [String: String]? {
// return self.httpURLResponse?.allHeaderFields as? [String: String]
// }
//}
//func tURLResponse(_ v: URLResponse) {
//
// _ = v.mimeType
// _ = v.suggestedFilename
// _ = v.textEncodingName
// _ = v.url
//
// let l = v as? HTTPURLResponse
//
// _ = l?.allHeaderFields
// _ = l?.statusCode
//}
| true
|
f0313838942c55304b24c19a21b4f9605a61f302
|
Swift
|
garrialmighty/ios
|
/Pakete/API.swift
|
UTF-8
| 3,391
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// API.swift
// Pakete
//
// Created by Royce Albert Dy on 13/03/2016.
// Copyright © 2016 Pakete. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
struct Pakete {
enum Router: URLRequestConvertible {
static let baseURLString = "https://pakete-api-staging.herokuapp.com/v1"
case TrackPackage(String, String)
case Couriers
var method: Alamofire.Method {
return .GET
}
var path: String {
switch self {
case .TrackPackage:
return "/track"
case .Couriers:
return "/couriers"
}
}
// MARK: URLRequestConvertible
var URLRequest: NSMutableURLRequest {
let parameters: [String: AnyObject] = {
switch self {
case .TrackPackage(let courier, let trackingNumber):
return ["courier": courier, "tracking_number": trackingNumber]
default:
return [:]
}
}()
let URL = NSURL(string: Router.baseURLString)!
let URLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(self.path))
URLRequest.HTTPMethod = method.rawValue
URLRequest.setValue("compress, gzip", forHTTPHeaderField: "Accept-Encoding")
URLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
URLRequest.setValue(Token().tokenString(), forHTTPHeaderField: "Authorization")
let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(URLRequest, parameters: parameters).0
}
}
}
extension Request {
public func responseSwiftyJSON(completionHandler: (request: NSURLRequest, response: NSHTTPURLResponse?, json: SwiftyJSON.JSON, error: NSError?) -> Void) -> Self {
// BigBrother.Manager.sharedInstance.incrementActivityCount()
return response(queue: nil, responseSerializer: Request.JSONResponseSerializer(options: .AllowFragments), completionHandler: { (response) -> Void in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
// BigBrother.Manager.sharedInstance.decrementActivityCount()
var responseJSON = JSON.null
var responseError: NSError?
switch response.result {
case .Success(let value):
if let httpURLResponse = response.response {
responseJSON = SwiftyJSON.JSON(value)
// if not 200 then it's a problem
if httpURLResponse.statusCode != 200 {
responseError = NSError(domain: response.request!.URLString, code: httpURLResponse.statusCode, userInfo: [NSLocalizedFailureReasonErrorKey: responseJSON["message"].stringValue])
}
}
case .Failure(let error):
responseError = error
}
dispatch_async(dispatch_get_main_queue(), {
completionHandler(request: response.request!, response: response.response, json: responseJSON, error: responseError)
})
})
})
}
}
| true
|
8b9d2a9d1b4e5c20de02cd5d783218543e8dbb9c
|
Swift
|
Profiteam/Auction.iOS
|
/Service/Models/Response/LanguageResponse.swift
|
UTF-8
| 424
| 2.609375
| 3
|
[] |
no_license
|
//
// LanguageResponse.swift
// Auction
//
// Created by Иван Меликов on 06/06/2019.
// Copyright © 2019 Oxbee. All rights reserved.
import Foundation
typealias LanguageResponse = [LanguageData]
struct LanguageData: Codable {
let id: Int
let shortName, fullName: String
enum CodingKeys: String, CodingKey {
case id
case shortName = "short_name"
case fullName = "full_name"
}
}
| true
|
bb62ead6b653a1aad14fd7d9bbecbfb411fc60b9
|
Swift
|
ArturAzarau/VIPSample
|
/PhotoAssistant/Scenes/Camera/Workers/DrawFiltersWorker.swift
|
UTF-8
| 9,033
| 3.0625
| 3
|
[] |
no_license
|
//
// DrawFiltersWorker.swift
// PhotoAssistant
//
// Created by Артур Азаров on 01.04.2018.
// Copyright © 2018 Артур Азаров. All rights reserved.
//
import UIKit
final class DrawFiltersWorker {
// MARK: - Properties
private let size: CGSize
private let item: Int
// MARK: - Object Life Cycle
init(size: CGSize,item: Int) {
self.size = size
self.item = item
}
func drawFilter() -> UIImage {
print(item)
switch self.item {
case 0: return UIImage()
case 1: return drawGrid()
case 2: return drawFibonacciSpiral()
case 3: return drawHorizonLine()
default: return UIImage()
}
}
private func drawHorizonLine() -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(UIColor.yellow.cgColor)
context?.setLineWidth(CGFloat(0.5))
context?.setLineCap(.square)
context?.setBlendMode(.normal)
UIColor.yellow.setStroke()
context?.move(to: CGPoint(x: 0, y: size.height / 2))
context?.addLine(to: CGPoint(x: size.width, y: size.height / 2))
context?.strokePath()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
private func drawGrid() -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(UIColor.yellow.cgColor)
context?.setLineWidth(CGFloat(0.5))
context?.setLineCap(.square)
context?.setBlendMode(.normal)
func drawFirstVerticalLine() {
let x = size.width / 3
let firstPoint = CGPoint(x: x, y: 0)
let secondPoint = CGPoint(x: x, y: size.height)
drawLine(from: firstPoint, to: secondPoint)
}
func drawSecondVerticalLine() {
let x = 2 * size.width / 3
let firstPoint = CGPoint(x: x, y: 0)
let secondPoint = CGPoint(x: x, y: size.height)
drawLine(from: firstPoint, to: secondPoint)
}
func drawFirstHorizontalLine() {
let y = size.height / 3
let firstPoint = CGPoint(x: 0, y: y)
let secondPoint = CGPoint(x: size.width, y: y)
drawLine(from: firstPoint, to: secondPoint)
}
func drawSecondHorizontalLine() {
let y = 2 * size.height / 3
let firstPoint = CGPoint(x: 0, y: y)
let secondPoint = CGPoint(x: size.width, y: y)
drawLine(from: firstPoint, to: secondPoint)
}
func drawLine(from firstPoint: CGPoint,to secondPoint: CGPoint) {
context?.move(to: firstPoint)
context?.addLine(to: secondPoint)
}
drawFirstVerticalLine()
drawSecondVerticalLine()
drawFirstHorizontalLine()
drawSecondHorizontalLine()
context?.strokePath()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
private func drawFibonacciSpiral() -> UIImage {
let size = self.size
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(UIColor.yellow.cgColor)
context?.setLineWidth(CGFloat(1))
context?.setLineCap(.square)
context?.setBlendMode(.normal)
var smallerWidth = size.width
var heigherWidth = size.height
var xRectCoord: CGFloat = 0
var yRectCoord: CGFloat = 0
var startAngle: CGFloat = 3 * .pi / 2
var endAngle: CGFloat = 0
func calculateNewWidthAndCoords() {
let temp = smallerWidth
smallerWidth = heigherWidth - smallerWidth
heigherWidth = temp
startAngle += .pi / 2
endAngle += .pi / 2
}
let path = UIBezierPath(rect: CGRect(x: xRectCoord, y: yRectCoord, width: smallerWidth, height: smallerWidth))
path.move(to: CGPoint(x: 0, y: 0))
path.addArc(withCenter: CGPoint(x: 0, y: smallerWidth), radius: smallerWidth, startAngle: startAngle, endAngle: endAngle, clockwise: true)
context?.addPath(path.cgPath)
calculateNewWidthAndCoords()
let secondPath = UIBezierPath(rect: CGRect(x: size.width - smallerWidth, y: heigherWidth, width: smallerWidth, height: smallerWidth))
secondPath.move(to: CGPoint(x: size.width - smallerWidth, y: heigherWidth))
secondPath.addArc(withCenter: CGPoint(x: size.width - smallerWidth, y: heigherWidth), radius: smallerWidth, startAngle: startAngle, endAngle: endAngle, clockwise: true)
context?.addPath(secondPath.cgPath)
calculateNewWidthAndCoords()
let thirdPath = UIBezierPath(rect: CGRect(x: 0, y: size.height - smallerWidth, width: smallerWidth, height: smallerWidth))
thirdPath.move(to: CGPoint(x: 0, y: size.height))
thirdPath.addArc(withCenter: CGPoint(x: smallerWidth, y: size.height - smallerWidth), radius: smallerWidth, startAngle: startAngle, endAngle: endAngle, clockwise: true)
context?.addPath(thirdPath.cgPath)
calculateNewWidthAndCoords()
let fourtPath = UIBezierPath(rect: CGRect(x: 0, y: size.height - smallerWidth - heigherWidth, width: smallerWidth, height: smallerWidth))
fourtPath.move(to: CGPoint(x: smallerWidth, y: size.height - heigherWidth))
fourtPath.addArc(withCenter: CGPoint(x: smallerWidth, y: size.height - heigherWidth), radius: smallerWidth, startAngle: startAngle, endAngle: endAngle, clockwise: true)
context?.addPath(fourtPath.cgPath)
calculateNewWidthAndCoords()
var rectOrigin: CGPoint
let fifthPath = UIBezierPath(rect: CGRect(x: heigherWidth, y: size.height - smallerWidth - 2 * heigherWidth, width: smallerWidth, height: smallerWidth))
fifthPath.move(to: CGPoint(x: heigherWidth, y: size.height - smallerWidth - heigherWidth - (heigherWidth - smallerWidth)))
fifthPath.addArc(withCenter: CGPoint(x: heigherWidth, y: size.height - smallerWidth - heigherWidth - (heigherWidth - smallerWidth)), radius: smallerWidth, startAngle: startAngle, endAngle: endAngle, clockwise: true)
context?.addPath(fifthPath.cgPath)
rectOrigin = CGPoint(x: heigherWidth, y: size.height - smallerWidth - 2 * heigherWidth)
calculateNewWidthAndCoords()
let sixthPath = UIBezierPath(rect: CGRect(x: rectOrigin.x + (heigherWidth - smallerWidth), y: rectOrigin.y + heigherWidth, width: smallerWidth, height: smallerWidth))
sixthPath.move(to: CGPoint(x: rectOrigin.x + (heigherWidth - smallerWidth), y: rectOrigin.y + heigherWidth))
sixthPath.addArc(withCenter: CGPoint(x: rectOrigin.x + (heigherWidth - smallerWidth), y: rectOrigin.y + heigherWidth), radius: smallerWidth, startAngle: startAngle, endAngle: endAngle, clockwise: true)
context?.addPath(sixthPath.cgPath)
rectOrigin = CGPoint(x: rectOrigin.x + (heigherWidth - smallerWidth), y: rectOrigin.y + heigherWidth)
calculateNewWidthAndCoords()
let seventhPath = UIBezierPath(rect: CGRect(x: rectOrigin.x - smallerWidth, y: rectOrigin.y + heigherWidth - smallerWidth, width: smallerWidth, height: smallerWidth))
seventhPath.move(to: CGPoint(x: rectOrigin.x, y: rectOrigin.y + heigherWidth - smallerWidth))
seventhPath.addArc(withCenter: CGPoint(x: rectOrigin.x, y: rectOrigin.y + heigherWidth - smallerWidth), radius: smallerWidth, startAngle: startAngle, endAngle: endAngle, clockwise: true)
context?.addPath(seventhPath.cgPath)
rectOrigin = CGPoint(x: rectOrigin.x - smallerWidth, y: rectOrigin.y + heigherWidth - smallerWidth)
calculateNewWidthAndCoords()
let eighthPath = UIBezierPath(rect: CGRect(
x: rectOrigin.x,
y: rectOrigin.y - smallerWidth, width: heigherWidth, height: smallerWidth))
eighthPath.move(to: CGPoint(
x: rectOrigin.x + smallerWidth,
y: rectOrigin.y))
eighthPath.addArc(withCenter: CGPoint(
x: rectOrigin.x + smallerWidth,
y: rectOrigin.y),
radius: smallerWidth, startAngle: startAngle, endAngle: endAngle, clockwise: true)
context?.addPath(eighthPath.cgPath)
rectOrigin = CGPoint(
x: rectOrigin.x - smallerWidth,
y: rectOrigin.y + heigherWidth - smallerWidth)
calculateNewWidthAndCoords()
context?.strokePath()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| true
|
a0ea7bfdcb54d7108ffe93f3f942fd6e76879886
|
Swift
|
djalfirevic/SwiftUI-Playground
|
/Big Mountain Studio/SwiftUI Data/SwiftUI_Data/State/StateWithModifiers.swift
|
UTF-8
| 1,459
| 3.6875
| 4
|
[] |
no_license
|
// Copyright © 2020 Mark Moeykens. All rights reserved. | @BigMtnStudio
import SwiftUI
struct StateWithModifiers: View {
@State private var isOn = true
var body: some View {
VStack(spacing: 20) {
HeaderView("State", subtitle: "With Modifiers", desc: "You can use state to control how your views look and change.", back: .blue, textColor: .white)
Spacer()
Button(action: {
self.isOn.toggle()
}) {
ZStack(alignment: isOn ? .trailing : .leading) {
HStack {
Text("ON").opacity(isOn ? 1 : 0)
Text("OFF").opacity(isOn ? 0 : 1)
}
.foregroundColor(.white)
RoundedRectangle(cornerRadius: 6)
.fill(Color.white)
.frame(width: 45, height: 50)
}
}
.padding(8)
.background(RoundedRectangle(cornerRadius: 8)
.fill(isOn ? Color.green : Color.red))
Spacer()
DescView("The button's modifiers change because the value of a state variable is changing. The changes are all data driven.", back: .blue, textColor: .white)
}
.font(.title)
.animation(.default)
}
}
struct StateWithModifiers_Previews: PreviewProvider {
static var previews: some View {
StateWithModifiers()
}
}
| true
|
84a7ee9986e8fb793f456e38cf9423a009a54734
|
Swift
|
editorscut/ec010functionalkickstart
|
/06/FlatMapFinal.playground/Pages/04Result.xcplaygroundpage/Contents.swift
|
UTF-8
| 2,697
| 3.703125
| 4
|
[] |
no_license
|
//: [Previous](@previous)
struct IsEmpty: Error {}
let emptyTrunk
= Result<Point, IsEmpty>
.failure(IsEmpty())
let trunkWithPoint
= Result<Point, IsEmpty>
.success(origin)
emptyTrunk
.map(moveRight)
emptyTrunk
.map(moveRight)
.map(moveDown)
trunkWithPoint
.map(moveRight)
trunkWithPoint
.map(moveRight)
.map(moveDown)
func movingRightInTrunk(_ point: Point) -> Result<Point, IsEmpty> {
let movedPoint = Point(x: point.x + 10, y: point.y)
if movedPoint.x <= 20 {
return .success(movedPoint)
} else {
return .failure(IsEmpty())
}
}
func movingDownInTrunk(_ point: Point) -> Result<Point, IsEmpty> {
let movedPoint = Point(x: point.x, y: point.y + 10)
if movedPoint.y <= 10 {
return .success(movedPoint)
} else {
return .failure(IsEmpty())
}
}
trunkWithPoint
.map(movingRightInTrunk)
emptyTrunk
.flatMap(movingRightInTrunk)
emptyTrunk
.flatMap(movingRightInTrunk)
.flatMap(movingDownInTrunk)
trunkWithPoint
.flatMap(movingRightInTrunk)
trunkWithPoint
.flatMap(movingRightInTrunk)
.flatMap(movingDownInTrunk)
trunkWithPoint
.flatMap(movingRightInTrunk)
.flatMap(movingDownInTrunk)
.flatMap(movingDownInTrunk)
trunkWithPoint
>=> movingRightInTrunk
>=> movingDownInTrunk
func emphasize(_ string: String) -> Result<String, Never> {
.success(string.uppercased() + "!")
}
func numberOfCharacters(in string: String) -> Result<Int, Never> {
.success(string.count)
}
let hello = Result<String, Never>.success("hello")
hello
.flatMap(emphasize)
hello
.flatMap(emphasize)
.flatMap(numberOfCharacters)
enum CutIsOutOfBounds: Error {
case cutIsNegativeNumber
case cutIsTooBig
}
func cutDeck(to index: Int) -> (Deck) -> Result<Deck, CutIsOutOfBounds> {
{deck in
if index < 0 { return .failure(CutIsOutOfBounds.cutIsNegativeNumber)}
guard index < deck.count else {return .failure(CutIsOutOfBounds.cutIsTooBig)}
return .success(deck.cut(index))
}
}
func shuffleDeck(to index: Int) -> (Deck) -> Result<Deck, CutIsOutOfBounds> {
{deck in
if index < 0 { return .failure(CutIsOutOfBounds.cutIsNegativeNumber)}
guard index < deck.count else {return .failure(CutIsOutOfBounds.cutIsTooBig)}
return .success(deck.shuffle(cutDepth: index))
}
}
let deckInTrunk = Result<Deck, CutIsOutOfBounds>.success(freshDeck)
deckInTrunk.flatMap(cutDeck(to: -5))
deckInTrunk.flatMap(shuffleDeck(to: 100))
deckInTrunk
.flatMap(shuffleDeck(to: 17))
.flatMap(cutDeck(to: 24))
.flatMap(shuffleDeck(to: 27))
.flatMap(cutDeck(to: 25))
//: [Next](@next)
| true
|
12854f3b96abbfc8d659bfe99fa38cc4b335405a
|
Swift
|
chenjiangchuan/LiveVideoDemo
|
/LiveVideoDemo/Controller/JCNavigationController.swift
|
UTF-8
| 1,067
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// JCNavigationController.swift
// LiveVideoDemo
//
// Created by chenjiangchuan on 16/7/8.
// Copyright © 2016年 JC'Chan. All rights reserved.
//
import UIKit
class JCNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName : UIColor.redColor(),
NSFontAttributeName : UIFont.systemFontOfSize(20)
]
}
override func pushViewController(viewController: UIViewController, animated: Bool) {
if self.childViewControllers.count == 0 {
self.navigationBarHidden = false
} else {
self.navigationBarHidden = true
}
super.pushViewController(viewController, animated: animated)
}
override func popViewControllerAnimated(animated: Bool) -> UIViewController? {
self.navigationBarHidden = false
return super.popViewControllerAnimated(animated)
}
}
| true
|
6a793adde4909b5d7ee2c386a36b5d7d17b2c4a8
|
Swift
|
Kota-N/match-cards-ios
|
/MatchCards/CardModel.swift
|
UTF-8
| 779
| 3.203125
| 3
|
[] |
no_license
|
//
// CardModel.swift
// MatchCards
//
// Created by Kota on 10/28/20.
//
import Foundation
class CardModel {
func getCards() -> [Card] {
// Declare an empty array
var generatedCards = [Card]()
// Randomly generate 8 pairs of cards
for _ in 1...8 {
let randomNumber = Int.random(in: 1...13)
let card1 = Card()
let card2 = Card()
card1.imageName = "card\(randomNumber)"
card2.imageName = "card\(randomNumber)"
generatedCards += [card1, card2]
print(randomNumber)
}
generatedCards.shuffle()
return generatedCards
}
}
| true
|
95b1b333c7b724687773aa6b61fdcff11b91e8bb
|
Swift
|
lexorus/FunctionalRouting
|
/FunctionalRouting/Core/ViewController.swift
|
UTF-8
| 1,192
| 3.09375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// CodeWay
//
// Created by Dmitrii Celpan on 11/20/16.
// Copyright © 2016 Lexorus. All rights reserved.
//
import UIKit
struct ViewController<Result> {
private let build: ( @escaping (Result) -> ()) -> UIViewController
init(_ build: @escaping ( @escaping (Result) -> ()) -> UIViewController) {
self.build = build
}
func run(completion: @escaping (Result) -> ()) -> UIViewController {
return build(completion)
}
}
extension UIViewController {
func presentModal<Result>(flow: NavigationController<Result>, callback: @escaping (Result) -> ()) {
let viewController = flow.build { [unowned self] result, navigationController in
callback(result)
self.dismiss(animated: true, completion: nil)
}
viewController.modalTransitionStyle = .coverVertical
present(viewController, animated: true, completion: nil)
}
}
func map<A,B>(viewConroller: ViewController<A>, transform: @escaping (A) -> B) -> ViewController<B> {
return ViewController { callback in
return viewConroller.run { result in
callback(transform(result))
}
}
}
| true
|
f0e9a749bf576c50bad3fe02e2b043424e2434fc
|
Swift
|
iAutoLife/AutoLife
|
/AutoLife/Classes/CarBranch/Controller/PickerViewController.swift
|
UTF-8
| 4,669
| 2.515625
| 3
|
[] |
no_license
|
//
// PickerViewController.swift
// AutoLife
//
// Created by xubupt218 on 16/1/22.
// Copyright © 2016年 徐成. All rights reserved.
//
import UIKit
protocol BrandPickerDelegate {
func brandPickerDidCancel()
func brandPickerDidGoback()
func brandPickerDidFinish(id:String,brand:String,hasNext: Bool)
}
class PickerViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
private var tableView:UITableView!
var brandJSON:JSON = JSON.null {
didSet{
guard self.tableView != nil else {return}
self.tableView.reloadData()
if self.brandJSON[0].count == 3 {
isEnd = true
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "上一级", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(PickerViewController.didGoback(_:)))
}else {
isEnd = false
}
}
}
var delegate:BrandPickerDelegate?
var backgroundView:UIView?
var isEnd = false
override func viewDidLoad() {
super.viewDidLoad()
backgroundView = UIView(frame: UIScreen.mainScreen().bounds)
backgroundView?.backgroundColor = UIColor.blackColor();backgroundView?.alpha = 0.0
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(didCancel(_:)))
tableView = UITableView(frame: CGRectMake(0, 0, self.view.frame.width - 45, AlStyle.size.height + 10),style: UITableViewStyle.Grouped)
self.view.addSubview(tableView)
XuSetup(tableView)
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = 36
}
override func canBecomeFirstResponder() -> Bool {
return true
}
func didCancel(sender:UIBarButtonItem) {
self.delegate?.brandPickerDidCancel()
}
func didGoback(sender:UIBarButtonItem) {
self.delegate?.brandPickerDidGoback()
}
//MARK:--UITableViewDelegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
print(brandJSON.count)
return brandJSON.count
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 20
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell")
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
cell?.backgroundColor = UIColor.clearColor()
cell?.textLabel?.font = AlStyle.font.normal
}
var text = "不确定"
if indexPath.section == 1 {
switch brandJSON[indexPath.row].count {
case 2:text = brandJSON[indexPath.row]["model_name"].string!
case 3:
text = brandJSON[indexPath.row]["type_series"].string! + " " +
brandJSON[indexPath.row]["type_name"].string!
default:print("other data")
}
}
cell?.textLabel?.text = text
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print(brandJSON[indexPath.row]["id"])
if indexPath.section == 0 {
delegate?.brandPickerDidFinish("", brand: "", hasNext: false)
return
}
if !isEnd {
let brand = self.brandJSON[indexPath.row]["model_name"].string!
let id = "\(self.brandJSON[indexPath.row]["id"])"
delegate?.brandPickerDidFinish(id, brand: brand, hasNext: true)
}else {
let brand = brandJSON[indexPath.row]["type_series"].string! + " " + brandJSON[indexPath.row]["type_name"].string!
let id = "\(self.brandJSON[indexPath.row]["id"].int!)"
delegate?.brandPickerDidFinish(id, brand: brand, hasNext: false)
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
XutableView(tableView, willDisplayCell: cell, forRowIndexPath: indexPath)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
3f54f9f0a60b77f0ac3595145100c9347bc9986f
|
Swift
|
drtyhbo/drtyhboGames
|
/SpaceShooter/SpaceShooter/Code/Renderer/TextureQueue.swift
|
UTF-8
| 914
| 3.171875
| 3
|
[] |
no_license
|
//
// TextureQueue.swift
// SpaceShooter
//
// Created by Andreas Binnewies on 11/5/15.
// Copyright © 2015 drtyhbo productions. All rights reserved.
//
import Foundation
class Texture {
let texture: MTLTexture
init(texture: MTLTexture) {
self.texture = texture
}
}
class TextureQueue {
var nextTexture: Texture {
currentTexture = (currentTexture + 1) % textures.count
return textures[currentTexture]
}
private var textures: [Texture] = []
private var currentTexture = 0
init(device: MTLDevice, width: Int, height: Int) {
let textureDescriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat(Constants.Metal.pixelFormat, width: width, height: height, mipmapped: false)
for _ in 0..<Constants.numberOfInflightFrames {
textures.append(Texture(texture: device.newTextureWithDescriptor(textureDescriptor)))
}
}
}
| true
|
cb6fe0f4a8a62d7d3d3f17d466a365d7ab10f21f
|
Swift
|
frenchdonuts/RedditTop
|
/RedditTop/RedditTop/Cache/Cache.swift
|
UTF-8
| 841
| 3
| 3
|
[] |
no_license
|
//
// ImageCache.swift
// RedditTop
//
// Created by Alexander Kharevich on 1/29/18.
// Copyright © 2018 Alexander Kharevich. All rights reserved.
//
import UIKit
private let minimumCapacity = 500
class Cache<K: Hashable,V> {
private var cacheDict: [K: V] = Dictionary<K,V>(minimumCapacity: minimumCapacity)
func value(for key: K) -> V? {
return cacheDict[key]
}
func set(value: V, for key: K) {
cacheDict[key] = value
}
func remove(for key: K) {
cacheDict[key] = nil
}
func flush() {
cacheDict.removeAll()
}
subscript(key: K) -> V? {
get {
return value(for: key)
}
set {
if let newValue = newValue {
set(value: newValue, for: key)
} else {
remove(for: key)
}
}
}
}
| true
|
adc1fddef342154337dddea84b0e33d5c79d3f0e
|
Swift
|
jayvenn/LearnCSinAR
|
/Learn CS in AR/Augmented Reality/Views/Bottom Section UIs/SubtitleView.swift
|
UTF-8
| 3,854
| 2.734375
| 3
|
[] |
no_license
|
//
// SubtitleView.swift
// Learn CS in AR
//
// Created by Jayven Nhan on 5/16/18.
// Copyright © 2018 Jayven Nhan. All rights reserved.
//
import UIKit
import SnapKit
import AVFoundation
final class SubtitleView: BaseARView {
lazy var textView = SubtitleTextView(lesson: lesson)
lazy var speakerButton: UIButton = {
let button = UIButton(type: .system)
button.setImage(#imageLiteral(resourceName: "speaker").withRenderingMode(.alwaysOriginal), for: .normal)
button.addTarget(self, action: #selector(speakerButtonDidTouchUpInside(_:)), for: .touchUpInside)
button.alpha = 0
return button
}()
override init(lesson: Lesson) {
super.init(lesson: lesson)
textView.alwaysBounceVertical = true
}
// MARK: SubtitleView - Action methods
@objc func speakerButtonDidTouchUpInside(_ sender: UIButton) {
delegate?.speakerButtonDidTouchUpInside()
}
override func setUpLayout() {
super.setUpLayout()
stackView.addArrangedSubview(textView)
mainView.addSubview(speakerButton)
speakerButton.snp.makeConstraints {
$0.size.equalTo(58)
$0.centerX.equalToSuperview()
$0.bottom.equalToSuperview().offset(-32)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: SubtitleView - Layout
extension SubtitleView {
func fadeInSpeakerButton() {
DispatchQueue.main.async {
UIView.animate(withDuration: animationDuration) {
self.speakerButton.alpha = 1
}
}
}
func fadeOutSpeakerButton() {
DispatchQueue.main.async {
UIView.animate(withDuration: animationDuration) {
self.speakerButton.alpha = 0
}
}
}
}
// MARK: SubtitleView - Ordering
extension SubtitleView {
func setOrdering() {
setOrderingTitleLabel()
textView.setOrderingText()
}
func setOrderingTitleLabel() {
let titleColor = UIColor.black
let titleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor,
NSAttributedString.Key.font: getTitleLabelFont()]
let titleAttributedText = NSMutableAttributedString(string: LocalizedString.ordering, attributes: titleTextAttributes)
titleLabel.attributedText = titleAttributedText
titleLabel.accessibilityLabel = titleAttributedText.string
}
func setOperation() {
setOperationTitleLabel()
textView.setOperationText()
}
func setOperationTitleLabel() {
let titleColor = UIColor.black
let titleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor,
NSAttributedString.Key.font: getTitleLabelFont()]
let titleAttributedText = NSMutableAttributedString(string: LocalizedString.operation, attributes: titleTextAttributes)
titleLabel.attributedText = titleAttributedText
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.accessibilityLabel = LocalizedString.operation
}
}
// MARK: SubtitleView - Big O
extension SubtitleView {
func setBigO() {
setBigOTitleLabel()
textView.setBigOText()
titleLabel.accessibilityLabel = "Big O"
}
func setBigOTitleLabel() {
let titleColor = UIColor.black
let titleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor,
NSAttributedString.Key.font: getTitleLabelFont()]
let titleAttributedText = NSMutableAttributedString(string: "Big O", attributes: titleTextAttributes)
titleLabel.attributedText = titleAttributedText
}
}
| true
|
2edc6b9eb9ca540237dcce1fc2d4cc3098145a6b
|
Swift
|
CryptoniteCEV/app-cryptonite
|
/CryptoniteCev/Constants/AboutCoins.swift
|
UTF-8
| 1,245
| 3.3125
| 3
|
[] |
no_license
|
import Foundation
class AboutCoins{
let coins:[String:String]
private init() {
//información que aparecera en la pantalla de la moneda
self.coins = ["Bitcoin":"The world’s first cryptocurrency, Bitcoin is stored and exchanged securely on the internet through a digital ledger known as a blockchain. Bitcoins are divisible into smaller units known as satoshis — each satoshi is worth 0.00000001 bitcoin.",
"Ethereum": "Ethereum is a decentralized computing platform that uses ETH (also called Ether) to pay transaction fees (or “gas”). Developers can use Ethereum to run decentralized applications (dApps) and issue new crypto assets, known as Ethereum tokens.",
"Litecoin": "Litecoin is a cryptocurrency that uses a faster payment confirmation schedule and a different cryptographic algorithm than Bitcoin.",
"DogeCoin":"Dogecoin is a cryptocurrency that was created as a joke — its name is a reference to a popular Internet meme. It shares many features with Litecoin. However, unlike Litecoin, there is no hard cap on the number of Dogecoins that can be produced."]
}
static let shared = AboutCoins()
}
| true
|
775374f743f8ae153043a22f8e992b8f40acdefd
|
Swift
|
giorgiodoueihi/tracker
|
/Tracker/Views/PlaceholderTextView.swift
|
UTF-8
| 2,262
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
//
// PlaceholderTextView.swift
// Tracker
//
// Created by Giorgio Doueihi on 2/10/20.
// Copyright © 2020 Giorgio Doueihi. All rights reserved.
//
import UIKit
import Combine
class PlaceholderTextView: UITextView {
private let placeholderLabel = UILabel()
private var textPublisher: Cancellable?
private var notificationCentrePublisher: Cancellable?
@IBInspectable var placeholderText: String? {
get {
return placeholderLabel.text
} set {
placeholderLabel.text = newValue
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupPlaceholderLabel()
setupPublishers()
}
// MARK: - Setup
private func setupPublishers() {
textPublisher = publisher(for: \.text)
.sink(receiveValue: handleTextDidChange)
notificationCentrePublisher = NotificationCenter.default.publisher(for: UITextView.textDidChangeNotification)
.sink(receiveValue: handleTextDidChange)
}
// MARK: - Configuring
private func setupPlaceholderLabel() {
placeholderLabel.textColor = .systemGray
placeholderLabel.font = .systemFont(ofSize: 17)
placeholderLabel.numberOfLines = 0
placeholderLabel.lineBreakMode = .byWordWrapping
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(placeholderLabel)
bringSubviewToFront(placeholderLabel)
placeholderLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 5).isActive = true
placeholderLabel.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
placeholderLabel.topAnchor.constraint(greaterThanOrEqualTo: topAnchor, constant: 6).isActive = true
placeholderLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
placeholderLabel.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
}
// MARK: - Actions
private var handleTextDidChange: (Any?) -> Void {
return { [unowned self] object in
let newValue = (object as? String) ?? self.text
self.placeholderLabel.isHidden = newValue?.isEmpty == false
}
}
}
| true
|
646b99330dc20f4109567af4d0780cfea279a461
|
Swift
|
janant/Rock-Paper-Scissors-for-iPhone
|
/Rock Paper Scissors for iPhone/Constants.swift
|
UTF-8
| 1,274
| 2.765625
| 3
|
[] |
no_license
|
//
// Constants.swift
// Rock Paper Scissors for iPhone
//
// Created by Anant Jain on 7/30/17.
// Copyright © 2017 Anant Jain. All rights reserved.
//
import Foundation
import CoreGraphics
struct Constants {
// Preference keys
struct UserDefaultsKeys {
static let WeaponsSoundsOn = "kWeaponsSoundsOn"
static let ClicksSoundsOn = "kClicksSoundsOn"
static let PvCWinningScore = "kPvCWinningScore"
static let PvPWinningScore = "kPvPWinningScore"
}
struct GameModes {
static let PvC = "PvC"
static let PvP = "PvP"
}
struct Difficulties {
static let Easy = 0
static let Medium = 1
static let Hard = 2
}
struct Weapons {
static let Rock = 0
static let Paper = 1
static let Scissors = 2
}
struct StatusMessages {
static let PaperCoversRock = "Paper covers Rock!"
static let ScissorsCutPaper = "Scissors cut Paper!"
static let RockSmashesScissors = "Rock smashes Scissors!"
static let NothingHappens = "Nothing happens!"
}
struct UIFrames {
static let MenuVisibleHeight: CGFloat = 165
static let DifficultyControlSpacing: CGFloat = 93
}
}
| true
|
b473a5ff344433f29db7ad380eb06bb2029b6337
|
Swift
|
comcc/Greycats.swift
|
/Greycats/Graphics/Color.swift
|
UTF-8
| 2,367
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
//
// ImageOperation.swift
// Greycats
//
// Created by Rex Sheng on 2/5/16.
// Copyright (c) 2016 Interactive Labs. All rights reserved.
//
import UIKit
extension UIColor {
public convenience init(hexRGB hex: UInt, alpha: CGFloat = 1) {
let ff: CGFloat = 255.0;
let r = CGFloat((hex & 0xff0000) >> 16) / ff
let g = CGFloat((hex & 0xff00) >> 8) / ff
let b = CGFloat(hex & 0xff) / ff
self.init(red: r, green: g, blue: b, alpha: alpha)
}
public func overlay(color: UIColor) -> UIColor {
var ra: CGFloat = 0, ga: CGFloat = 0, ba: CGFloat = 0, aa: CGFloat = 0
var rb: CGFloat = 0, gb: CGFloat = 0, bb: CGFloat = 0, ab: CGFloat = 0
color.getRed(&ra, green: &ga, blue: &ba, alpha: &aa)
func blend(b: CGFloat, _ a: CGFloat) -> CGFloat {
if a < 0.5 {
return 2 * a * b
} else {
return 1 - 2 * (1 - a) * (1 - b)
}
}
getRed(&rb, green: &gb, blue: &bb, alpha: &ab)
let r = blend(ra, rb)
let g = blend(ga, gb)
let b = blend(ba, bb)
let a = blend(aa, ab)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
public func +(lhs: UIColor, rhs: UIColor) -> UIColor {
return lhs.overlay(rhs)
}
extension CGImage {
public func blend(mode: CGBlendMode, color: CGColor, alpha: CGFloat = 1) -> CGImage? {
return op { context, rect in
CGContextSetFillColorWithColor(context, color)
CGContextFillRect(context, rect)
CGContextSetBlendMode(context, mode)
CGContextSetAlpha(context, alpha)
CGContextDrawImage(context, rect, self)
}
}
public static func create(color: CGColor, size: CGSize) -> CGImage? {
return op(Int(size.width), Int(size.height)) { (context) in
let rect = CGRect(origin: .zero, size: size)
CGContextSetFillColorWithColor(context, color)
CGContextFillRect(context, rect)
}
}
}
extension UIImage {
public func blend(color: UIColor) -> UIImage? {
return blend(CGBlendMode.DestinationIn, color: color)
}
public func blend(mode: CGBlendMode, color: UIColor, alpha: CGFloat = 1) -> UIImage? {
if let cgImage = CGImage?.blend(mode, color: color.CGColor, alpha: alpha) {
let image = UIImage(CGImage: cgImage, scale: scale, orientation: .Up)
return image
}
return nil
}
public convenience init?(fromColor: UIColor) {
if let cgImage = CGImageRef.create(fromColor.CGColor, size: CGSizeMake(1, 1)) {
self.init(CGImage: cgImage)
} else {
return nil
}
}
}
| true
|
69b8cc05540cd0fd2ffcc45f52b0add21ccc9021
|
Swift
|
Sharafutdinova705/ObserverPattern
|
/ObserverPattern/viper/view/Account/AccountViewController.swift
|
UTF-8
| 2,787
| 2.734375
| 3
|
[] |
no_license
|
//
// AccountViewController.swift
// NotificationCenter
//
// Created by Гузель on 23/02/2019.
// Copyright © 2019 Гузель. All rights reserved.
//
import UIKit
class AccountViewController: UIViewController {
/// имя
@IBOutlet weak var nameLabel: UILabel!
/// фамилия
@IBOutlet weak var surnameLabel: UILabel!
/// год рождения
@IBOutlet weak var yearOldLabel: UILabel!
/// мейл
@IBOutlet weak var emailLabel: UILabel!
/// логин
@IBOutlet weak var loginLabel: UILabel!
/// модель пользователя
var userModel: UserModel!
/// центр оповещений
var notificationCenter = NotificationCenter.default
/// константа
var switchDict = "switch"
override func viewDidLoad() {
super.viewDidLoad()
initData()
notificationCenter.addObserver(forName: .changeColorNotification, object: nil, queue: OperationQueue.main) { (notification) in
self.changeTheme(notification: notification)
}
}
deinit {
notificationCenter.removeObserver(self)
}
@objc
/// Смена темы светлой/темной
///
/// - Parameter notification: нотификация
func changeTheme(notification: Notification) {
guard let colorDict = notification.userInfo as? [String : Bool] else { return }
if colorDict[switchDict] == true {
view.backgroundColor = UIColor.darkGray
nameLabel.textColor = UIColor.white
surnameLabel.textColor = UIColor.white
yearOldLabel.textColor = UIColor.white
emailLabel.textColor = UIColor.white
loginLabel.textColor = UIColor.white
} else {
view.backgroundColor = UIColor.white
nameLabel.textColor = UIColor.black
surnameLabel.textColor = UIColor.black
yearOldLabel.textColor = UIColor.black
emailLabel.textColor = UIColor.black
loginLabel.textColor = UIColor.black
}
}
/// Инициализация данных
func initData() {
nameLabel.text = userModel.name
surnameLabel.text = userModel.surname
yearOldLabel.text = String(NSCalendar.current.component(.year, from: NSDate() as Date) - userModel.yearOfBirth)
emailLabel.text = userModel.email
loginLabel.text = userModel.login
}
/// Кнопка для того, чтобы вернуться назад
///
/// - Parameter sender: Кнопка cancelButton
@IBAction func cancelButton(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
| true
|
c8afdb86e425c0a2a9db324e2a0a805fd73cb66f
|
Swift
|
allevato/icu-swift
|
/Sources/ICU/EastAsianWidth.swift
|
UTF-8
| 3,078
| 3.046875
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2017 Tony Allevato.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import ICU4C
extension Unicode {
/// Enumerated property `East_Asian_Width`.
///
/// Described by [http://www.unicode.org/reports/tr11/](http://www.unicode.org/reports/tr11/).
public enum EastAsianWidth: ConvertibleFromUnicodeIntProperty {
/// Any character that does not appear in East Asian typography.
case neutral
/// A character that can be sometimes narrow or sometimes wide, requiring
/// additional contextual information not in the character itself to determine
/// the correct width.
case ambiguous
/// A character with a decomposition of type of `narrow` to other characters
/// that are implicitly wide but unmarked, as well as U+20A9 WON SIGN.
case halfWidth
/// A character with a decomposition of type of `wide` to other characters
/// that are implicitly narrow but unmarked.
case fullWidth
/// A character that is always narrow and has an explicit full-width or wide
/// counterpart.
case narrow
/// A character that is always wide, occurring only in the context of East
/// Asian typography. This also includes all characters that have explicit
/// half-width counterparts and all characters with emoji presentation except
/// for U+1F1E6...U+1F1FF (REGIONAL INDICATOR SYMBOL LETTER A...REGIONAL
/// INDICATOR SYMBOL LETTER Z).
case wide
/// Creates a new East Asian width value from the given ICU C API value.
///
/// - Parameter cValue: The ICU C API value.
init(cValue: UEastAsianWidth) {
switch cValue {
case U_EA_NEUTRAL: self = .neutral
case U_EA_AMBIGUOUS: self = .ambiguous
case U_EA_HALFWIDTH: self = .halfWidth
case U_EA_FULLWIDTH: self = .fullWidth
case U_EA_NARROW: self = .narrow
case U_EA_WIDE: self = .wide
default: fatalError("Invalid UEastAsianWidth value: \(cValue)")
}
}
/// The C API value of type `UEastAsianWidth` that corresponds to the
/// receiving enum case.
var cValue: UEastAsianWidth {
switch self {
case .neutral: return U_EA_NEUTRAL
case .ambiguous: return U_EA_AMBIGUOUS
case .halfWidth: return U_EA_HALFWIDTH
case .fullWidth: return U_EA_FULLWIDTH
case .narrow: return U_EA_NARROW
case .wide: return U_EA_WIDE
}
}
}
}
extension UnicodeScalar {
/// The East Asian width property of the receiver.
public var eastAsianWidth: Unicode.EastAsianWidth {
return value(of: UCHAR_EAST_ASIAN_WIDTH)
}
}
| true
|
219753b158b9508b1636160dcb53f7eca35aa0ec
|
Swift
|
5nilha/HikingsList_SwiftUI
|
/Hiking/HikingDetail.swift
|
UTF-8
| 965
| 3.203125
| 3
|
[] |
no_license
|
//
// HikingDetail.swift
// Hiking
//
// Created by Fabio Quintanilha on 11/25/19.
// Copyright © 2019 FabioQuintanilha. All rights reserved.
//
import SwiftUI
struct HikingDetail: View {
let hike: Hike
@State private var zoomed: Bool = false
var body: some View {
VStack {
Image(hike.imageURL)
.resizable()
.aspectRatio(contentMode: self.zoomed ? .fill : .fit)
.onTapGesture {
withAnimation {
self.zoomed.toggle()
}
}
Text(hike.name)
Text(String(format: "%.1f miles", hike.miles))
}.navigationBarTitle(Text(hike.name), displayMode: .inline)
}
}
struct HikingDetail_Previews: PreviewProvider {
static var previews: some View {
HikingDetail(hike: Hike(id: "4", name: "Angels Landing", imageURL: "tam", miles: 10.0))
}
}
| true
|
9fcb0bc9d7c1e5936a196dbf2bbb1d7f637b6c15
|
Swift
|
LindaAdel/Mercado
|
/Mercado/Views/Controllers/Filter/FilterViewController.swift
|
UTF-8
| 3,445
| 2.734375
| 3
|
[] |
no_license
|
//
// FilterViewController.swift
// Mercado
//
// Created by Mayar Adel on 6/12/21.
//
import UIKit
class FilterViewController: UIViewController {
var itemsArray :[ItemProtocol]!
var brandArray :[String] = ["All Brands"]
var selectedBrandArray:[String]=[]
@IBOutlet weak var brandTableView: UITableView!
@IBOutlet weak var priceTableView: UITableView!
var lessThanPrice,
greaterThanPrice,
rangePrice1,
rangePrice2 : Int!
var priceArray:[String]=[]
var selectedPriceValue:String!
var categoryName , subCategoryName :String!
var priceRadioButtonsArray : [UIButton] = []
var filteredItemsArray : [ItemProtocol]=[]
override func viewDidLoad()
{
super.viewDidLoad()
brandTableView.tableFooterView = UIView(frame: CGRect.zero)
//get only uniques values in brand
for item in itemsArray
{
brandArray.append(item.brand!)
}
brandArray = Array(Set(brandArray)).sorted()
//set price range values for each category
self.getPricesValue()
//price array
priceArray = [
"less than \(lessThanPrice!) EGP",
"\(rangePrice1!) EGP - \(rangePrice2!) EGP",
"+ \(greaterThanPrice!) EGP",
]
}
@IBAction func applyFilterButton(_ sender: UIButton)
{
var lessThanPriceChoosen , rangePriceChoosen,greaterThanPriceChoosen : Bool!
//no filter
if selectedBrandArray.count == 0 && selectedPriceValue == nil
{
filteredItemsArray = itemsArray
}
if selectedPriceValue != nil {
lessThanPriceChoosen = selectedPriceValue.contains("less than \(lessThanPrice!) EGP")
rangePriceChoosen = selectedPriceValue.contains( "\(rangePrice1!) EGP - \(rangePrice2!) EGP")
greaterThanPriceChoosen = selectedPriceValue.contains("+ \(greaterThanPrice!) EGP")
}
if selectedBrandArray.contains("All Brands")
{
//if user not choose price filter
if selectedPriceValue == nil {
filteredItemsArray = itemsArray
}
else{
filterByPriceOnly(lessThanPriceChoosen,rangePriceChoosen,greaterThanPriceChoosen)
}
}
//choose specific brands
else if selectedBrandArray.count != 0 || selectedPriceValue != nil{
if selectedPriceValue == nil {
filteredItemsArray = itemsArray.filter {
return selectedBrandArray.contains($0.brand!)
}
}
else{
filterByPriceAndBrand(lessThanPriceChoosen, rangePriceChoosen,greaterThanPriceChoosen)
}
}
//filter by price only
if selectedPriceValue != nil && selectedBrandArray.count == 0 {
filterByPriceOnly(lessThanPriceChoosen,rangePriceChoosen,greaterThanPriceChoosen)
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "filter"), object: nil, userInfo: ["filteredArray":filteredItemsArray])
self.dismiss(animated: true, completion: nil)
}
}
| true
|
dbd36b7aaf73a148d607fe598e6aa20b827f49b9
|
Swift
|
antonio081014/LeetCode-CodeBase
|
/Swift/shortest-bridge.swift
|
UTF-8
| 1,543
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
class Solution {
private let dirs = [1, 0, -1, 0, 1]
private func paint(_ x: Int, _ y: Int, _ grid: inout [[Int]], _ queue: inout [(x: Int, y: Int)]) {
let n = grid.count
if x >= 0, x < n, y >= 0 , y < n, grid[x][y] == 1 {
grid[x][y] = 2
queue.append((x, y))
for index in 0 ..< 4 {
paint(x + dirs[index], y + dirs[index + 1], &grid, &queue)
}
}
}
func shortestBridge(_ grid: [[Int]]) -> Int {
let n = grid.count
var grid = grid
var queue = [(x: Int, y: Int)]()
for x in 0 ..< n {
for y in 0 ..< n {
if queue.isEmpty == false { break }
paint(x, y, &grid, &queue)
}
}
// print(grid)
while queue.isEmpty == false {
var sz = queue.count
while sz > 0 {
let (x, y) = queue.removeFirst()
sz -= 1
for index in 0 ..< 4 {
let xx = x + dirs[index]
let yy = y + dirs[index + 1]
if xx >= 0, xx < n, yy >= 0, yy < n {
if grid[xx][yy] == 1 {
return grid[x][y] - 2
} else if grid[xx][yy] == 0 {
grid[xx][yy] = 1 + grid[x][y]
queue.append((xx, yy))
}
}
}
}
}
return -1
}
}
| true
|
63f9c3fb25a6744fe6fa8b056a77ec5736d55230
|
Swift
|
dklein42/webAndMobile-demos
|
/Codable/Codable/Employee.swift
|
UTF-8
| 458
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// File.swift
// Codable
//
// Created by Daniel Klein on 23.11.17.
// Copyright © 2017 Daniel Klein. All rights reserved.
//
import Foundation
/*
struct Employee: Codable {
let name: String
let role: String
let id: Int
let firstDayOfEmployment: Date
let gender: Gender
let car: Car?
}
enum Gender: String, Codable {
case male
case female
case other
}
struct Car: Codable {
let model: String
let make: String
}
*/
| true
|
8c8ca2a1ce8a4b81609d5d2f06a092cb4305381b
|
Swift
|
DaichiSaito/GreenRefactoring
|
/GreenRefactoring/NiftyRequest.swift
|
UTF-8
| 2,910
| 2.765625
| 3
|
[] |
no_license
|
//
// GitHubRequest.swift
// GitHubSearchRepository
//
// Created by DaichiSaito on 2017/03/15.
// Copyright © 2017年 DaichiSaito. All rights reserved.
//
import Foundation
import NCMB
enum OrderEnum {
case byDescending
case byAscending
}
struct Order {
var orderKind: OrderEnum
var value: String
}
protocol NiftyRequest {
// associatedtype Response: NCMBObject // ResponseというのがSearchResponseとして特殊化されるっぽい
var className: String { get }
// var baseURL: URL { get }
// var path: String { get }
// var method: HTTPMethod { get }
var parameters: Any? { get }
var includeKey: String? { get }
var limit: Int32 { get }
var order: Order { get }
// var responses: [NCMBObject]? { get set }
}
extension NiftyRequest {
// var baseURL: URL {
// return URL(string: "http://dsh4k2h4k2.esy.es/Green/image")!
// }
var limit: Int32 {
return 100
}
func buildQuery() -> NCMBQuery {
let query = NCMBQuery(className: className)
if let dictionary = parameters as? [String : Any] {
for (key, value) in dictionary {
query?.whereKey(key, equalTo: value)
}
}
query?.includeKey = includeKey
query?.limit = limit
switch order.orderKind {
case .byDescending:
query?.order(byDescending: order.value)
case .byAscending:
query?.order(byAscending: order.value)
}
return query!
}
// func buildURLRequest() -> URLRequest {
// let url = baseURL.appendingPathComponent(path)
// var components = URLComponents(url:url,resolvingAgainstBaseURL: true)
//
// switch method {
// case .get:
// let dictionary = parameters as? [String : Any]
// let queryItems = dictionary?.map { key, value in
// return URLQueryItem(name: key, value: String(describing: value))
// }
// components?.queryItems = queryItems
// default:
// fatalError("Unsupported method \(method)")
// }
//
// var urlRequest = URLRequest(url: url)
// urlRequest.url = components?.url
// urlRequest.httpMethod = method.rawValue
//
// return urlRequest
// }
// func response(from data:[NCMBObject]) {
// responses = data
// }
// func response(from data: Data, urlResponse:URLResponse) throws -> Response {
// let json = try JSONSerialization.jsonObject(with: data, options: [])
// if case(200..<300)? = (urlResponse as? HTTPURLResponse)?.statusCode {
// return try Response(json:json)
// } else {
// throw try GitHubAPIError(json:json)
// }
//
//
// }
}
| true
|
e2d6acf667e621419bd97becc960a751b6b210fd
|
Swift
|
alexbelij/SpinWheel
|
/SpinWheel/GameScene.swift
|
UTF-8
| 1,299
| 2.734375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//
// GameScene.swift
// SpinWheel
//
// Created by Ron Myschuk on 2018-04-07.
// Copyright © 2018 Orange Think Box. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
private var spinWheelOpen = false
private var spinWheel: SpinWheel!
override func didMove(to view: SKView) {
setup()
}
func setup() {
self.physicsWorld.contactDelegate = self
if let spinButton = self.childNode(withName: "//spinButton") as? PushButton {
spinButton.quickSetUpWith(action: { self.displaySpinWheel() })
spinButton.buttonImage = "spin_icon"
}
}
func displaySpinWheel() {
print("spin wheel")
spinWheel = SpinWheel(size: self.size)
spinWheel.zPosition = 500
addChild(spinWheel)
spinWheel.initPhysicsJoints()
spinWheelOpen = true
}
func didBegin(_ contact: SKPhysicsContact) {
if spinWheelOpen {
spinWheel.didBegin(contact)
}
}
override func update(_ currentTime: TimeInterval) {
if spinWheelOpen {
spinWheel.updateWheel(currentTime)
}
}
}
| true
|
ce985ce78f4dcc6b9f69abeea779d4d2ed548057
|
Swift
|
bay2/CavyLifeBand2
|
/CavyLifeBand2/InfoSecurity/View/AccountInfoSecurityCell.swift
|
UTF-8
| 1,420
| 2.59375
| 3
|
[] |
no_license
|
//
// AccountInfoSecurityCell.swift
// CavyLifeBand2
//
// Created by Jessica on 16/3/30.
// Copyright © 2016年 xuemincai. All rights reserved.
//
import UIKit
import Log
class AccountInfoSecurityCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var infoSwitch: UISwitch!
private var dataSource: AccountInfoSecurityListDataSource?
@IBAction func switchAction(sender: AnyObject) {
dataSource?.changeSwitchStatus(sender as! UISwitch)
// Log.info("\(titleLabel.text!) --- \(sender.on)")
}
override func awakeFromNib() {
super.awakeFromNib()
titleLabel.textColor = UIColor(named: .EColor)
titleLabel.font = UIFont.mediumSystemFontOfSize(16.0)
}
func configure(dataSource: AccountInfoSecurityListDataSource) {
self.dataSource = dataSource
infoSwitch.on = dataSource.isOpen
titleLabel.text = dataSource.title
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
protocol AccountInfoSecurityListDataSource {
var title: String { get}
var isOpen: Bool { get }
func changeSwitchStatus(sender: UISwitch)
}
| true
|
1f5474f160d13dbd8a39f68d2fb43921b98b4442
|
Swift
|
SilkeKnossen/Restaurant
|
/Restaurant/Restaurant/MenuItemDetailViewController.swift
|
UTF-8
| 1,759
| 2.796875
| 3
|
[] |
no_license
|
//
// MenuItemDetailViewController.swift
// Restaurant
//
// Created by Silke Knossen on 04/12/2018.
// Copyright © 2018 Silke Knossen. All rights reserved.
//
import UIKit
class MenuItemDetailViewController: UIViewController {
// Initialize all outlets
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var detailTextLabel: UILabel!
@IBOutlet weak var addToOrderButton: UIButton!
// Initlialize current menu item
var menuItem: MenuItem!
// When the view did load, set the order button and update the view.
override func viewDidLoad() {
super.viewDidLoad()
addToOrderButton.layer.cornerRadius = 5.0
updateUI()
}
// Update the view outlets with the details from the menu item.
func updateUI() {
titleLabel.text = menuItem.name
priceLabel.text = String(format: "$%.2f", menuItem.price)
detailTextLabel.text = menuItem.detailText
MenuController.shared.fetchImage(url: menuItem.imageURL) { (image) in
guard let image = image else { return }
DispatchQueue.main.async {
self.imageView.image = image
}
}
}
// When the order button is tapped, show an animation, and
// add the menu item to the order list.
@IBAction func orderButtonTapped(_ sender: UIButton) {
UIView.animate(withDuration: 0.3) {
self.addToOrderButton.transform =
CGAffineTransform(scaleX: 3.0, y: 3.0)
self.addToOrderButton.transform =
CGAffineTransform(scaleX: 1.0, y: 1.0)
}
MenuController.shared.order.menuItems.append(menuItem)
}
}
| true
|
5c67ad01d6d7d44c06b89036e16e35259a627e25
|
Swift
|
DrKrakus/oc-baluchon
|
/BaluchonTests/WeatherServiceTestCase.swift
|
UTF-8
| 7,618
| 2.515625
| 3
|
[] |
no_license
|
//
// WeatherServiceTestCase.swift
// BaluchonTests
//
// Created by Jerome Krakus on 10/04/2019.
// Copyright © 2019 Jerome Krakus. All rights reserved.
//
@testable import Baluchon
import XCTest
class WeatherServiceTestCase: XCTestCase {
func testGetWeatherShouldPostFailedCallbackIfError() {
// Given
let weatherService = WeatherService(
weatherSession: URLSessionFake(
data: nil, response: nil, error: FakeResponseData.error),
weatherNYSession: URLSessionFake(
data: nil, response: nil, error: nil))
// When
let expectation = XCTestExpectation(description: "Waiting for queue change")
weatherService.getWeather { (success, weatherDetails) in
// Then
XCTAssertFalse(success)
XCTAssertNil(weatherDetails)
expectation.fulfill()
}
wait(for: [expectation], timeout: 0.01)
}
func testGetWeatherShouldPostFailedCallbackIfNoData() {
// Given
let weatherService = WeatherService(
weatherSession: URLSessionFake(
data: nil, response: nil, error: nil),
weatherNYSession: URLSessionFake(
data: nil, response: nil, error: nil))
// When
let expectation = XCTestExpectation(description: "Waiting for queue change")
weatherService.getWeather { (success, weatherDetails) in
// Then
XCTAssertFalse(success)
XCTAssertNil(weatherDetails)
expectation.fulfill()
}
wait(for: [expectation], timeout: 0.01)
}
func testGetWeatherShouldPostFailedCallbackIfIncorrectResponse() {
// Given
let weatherService = WeatherService(
weatherSession: URLSessionFake(
data: FakeResponseData.weatherCorrectData,
response: FakeResponseData.reponseKO,
error: nil),
weatherNYSession: URLSessionFake(
data: nil, response: nil, error: nil))
// When
let expectation = XCTestExpectation(description: "Waiting for queue change")
weatherService.getWeather { (success, weatherDetails) in
// Then
XCTAssertFalse(success)
XCTAssertNil(weatherDetails)
expectation.fulfill()
}
wait(for: [expectation], timeout: 0.01)
}
func testGetWeatherShouldPostFailedCallbackIfIncorrectData() {
// Given
let weatherService = WeatherService(
weatherSession: URLSessionFake(
data: FakeResponseData.incorrectData,
response: FakeResponseData.reponseOK,
error: nil),
weatherNYSession: URLSessionFake(
data: nil, response: nil, error: nil))
// When
let expectation = XCTestExpectation(description: "Waiting for queue change")
weatherService.getWeather { (success, weatherDetails) in
// Then
XCTAssertFalse(success)
XCTAssertNil(weatherDetails)
expectation.fulfill()
}
wait(for: [expectation], timeout: 0.01)
}
func testGetWeatherShouldPostFailedCallbackIfNYWeatherError() {
// Given
let weatherService = WeatherService(
weatherSession: URLSessionFake(
data: FakeResponseData.weatherCorrectData,
response: FakeResponseData.reponseOK,
error: nil),
weatherNYSession: URLSessionFake(
data: nil, response: nil, error: FakeResponseData.error))
// When
let expectation = XCTestExpectation(description: "Waiting for queue change")
weatherService.getWeather { (success, weatherDetails) in
// Then
XCTAssertFalse(success)
XCTAssertNil(weatherDetails)
expectation.fulfill()
}
wait(for: [expectation], timeout: 0.01)
}
func testGetWeatherShouldPostFailedCallbackIfNoNYWeatherData() {
// Given
let weatherService = WeatherService(
weatherSession: URLSessionFake(
data: FakeResponseData.weatherCorrectData,
response: FakeResponseData.reponseOK,
error: nil),
weatherNYSession: URLSessionFake(
data: nil, response: nil, error: nil))
// When
let expectation = XCTestExpectation(description: "Waiting for queue change")
weatherService.getWeather { (success, weatherDetails) in
// Then
XCTAssertFalse(success)
XCTAssertNil(weatherDetails)
expectation.fulfill()
}
wait(for: [expectation], timeout: 0.01)
}
func testGetWeatherShouldPostFailedCallbackIfIncorrectNYWeatherData() {
// Given
let weatherService = WeatherService(
weatherSession: URLSessionFake(
data: FakeResponseData.weatherCorrectData,
response: FakeResponseData.reponseOK,
error: nil),
weatherNYSession: URLSessionFake(
data: FakeResponseData.incorrectData,
response: FakeResponseData.reponseOK,
error: nil))
// When
let expectation = XCTestExpectation(description: "Waiting for queue change")
weatherService.getWeather { (success, weatherDetails) in
// Then
XCTAssertFalse(success)
XCTAssertNil(weatherDetails)
expectation.fulfill()
}
wait(for: [expectation], timeout: 0.01)
}
func testGetWeatherShouldPostFailedCallbackIfNYWeatherIncorrectResponse() {
// Given
let weatherService = WeatherService(
weatherSession: URLSessionFake(
data: FakeResponseData.weatherCorrectData,
response: FakeResponseData.reponseOK,
error: nil),
weatherNYSession: URLSessionFake(
data: FakeResponseData.weatherNYCorrectData,
response: FakeResponseData.reponseKO,
error: nil))
// When
let expectation = XCTestExpectation(description: "Waiting for queue change")
weatherService.getWeather { (success, weatherDetails) in
// Then
XCTAssertFalse(success)
XCTAssertNil(weatherDetails)
expectation.fulfill()
}
wait(for: [expectation], timeout: 0.01)
}
func testGetWeatherShouldPostSuccessCallbackIfWeatherAndNYWeatherAreOK() {
// Given
let weatherService = WeatherService(
weatherSession: URLSessionFake(
data: FakeResponseData.weatherCorrectData,
response: FakeResponseData.reponseOK,
error: nil),
weatherNYSession: URLSessionFake(
data: FakeResponseData.weatherNYCorrectData,
response: FakeResponseData.reponseOK,
error: nil))
// When
let expectation = XCTestExpectation(description: "Waiting for queue change")
weatherService.getWeather { (success, weatherDetails) in
// Then
XCTAssertTrue(success)
XCTAssertNotNil(weatherDetails)
let parisID = weatherDetails!["selectedCity"]!.id
let newYorkID = weatherDetails!["newYork"]!.id
XCTAssertEqual(parisID, 2968815)
XCTAssertEqual(newYorkID, 5128638)
expectation.fulfill()
}
wait(for: [expectation], timeout: 0.01)
}
}
| true
|
d87139ee48a450876bc5221c642593b13088da36
|
Swift
|
berryxchange/Swift
|
/Apps/TCIOKCApp/Final/ChurchApp/TCIOKC/Model/Ministry.swift
|
UTF-8
| 483
| 2.859375
| 3
|
[] |
no_license
|
//
// Ministry.swift
// TCIApp
//
// Created by Quinton Quaye on 12/27/17.
// Copyright © 2017 Quinton Quaye. All rights reserved.
//
import Foundation
struct Ministry {
var ministryIcon = ""
var ministryTitle = ""
var ministrySubtitle = ""
init(ministryIcon: String, ministryTitle: String, ministrySubtitle: String){
self.ministryIcon = ministryIcon
self.ministryTitle = ministryTitle
self.ministrySubtitle = ministrySubtitle
}
}
| true
|
92a5f4115f116143969627bc7df353d3415efe5b
|
Swift
|
Grimsly/KOBUN-Mobile
|
/JapaneseText/JapaneseText/Question.swift
|
UTF-8
| 341
| 2.828125
| 3
|
[] |
no_license
|
//
// Questions.swift
// JapaneseText
//
// Created by Xian-Meng Low on 2019-04-08.
// Copyright © 2019 Xian-Meng Low. All rights reserved.
//
import Foundation
class Question{
var question : String
var answer : String
init? (question: String, answer: String){
self.question = question
self.answer = answer
}
}
| true
|
808e728f6c08bda3e7a5b0fca88eade79d557d73
|
Swift
|
ChangeNOW-lab/ChangeNow_Integration_iOS
|
/CNIntegration/Basic/Helpers/Action.swift
|
UTF-8
| 1,138
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
//
// Action.swift
// CNIntegration
//
// Created by Pavel Pronin on 26.07.2020.
// Copyright © 2018 Pavel Pronin. All rights reserved.
//
@objcMembers
final class Action: Equatable {
private let closure: () -> Void
init(closure: @escaping () -> Void) {
self.closure = closure
}
func perform() {
closure()
}
static func == (lhs: Action, rhs: Action) -> Bool {
return true
}
}
@objcMembers
final class ActionWith<T>: Equatable {
private let closure: (T) -> Void
init(closure: @escaping (T) -> Void) {
self.closure = closure
}
func perform(with argument: T) {
closure(argument)
}
static func == (lhs: ActionWith<T>, rhs: ActionWith<T>) -> Bool {
return true
}
}
@objcMembers
final class ActionWithResult<T, R>: Equatable {
private let closure: (T) -> R
init(closure: @escaping (T) -> R) {
self.closure = closure
}
func perform(with argument: T) -> R {
return closure(argument)
}
static func == (lhs: ActionWithResult<T, R>, rhs: ActionWithResult<T, R>) -> Bool {
return true
}
}
| true
|
1456125f5683f51c1473ce5e074f4380ca436444
|
Swift
|
argallo/Kotlin-Swift
|
/SwiftKotlin/Carthage/Checkouts/brickkit-ios/Source/Behaviors/StickyFooterLayoutBehavior.swift
|
UTF-8
| 2,686
| 2.515625
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// StickyFooterBehavior.swift
// BrickKit
//
// Created by Ruben Cagnie on 6/2/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
/// A StickyFooterLayoutBehavior will stick certain bricks (based on the dataSource) on the bottom of its section
open class StickyFooterLayoutBehavior: StickyLayoutBehavior {
open override var needsDownstreamCalculation: Bool {
return true
}
open override func shouldUseForDownstreamCalculation(for indexPath: IndexPath, with identifier: String, for collectionViewLayout: UICollectionViewLayout) -> Bool {
if dataSource?.stickyLayoutBehavior(self, shouldStickItemAtIndexPath: indexPath, withIdentifier: identifier, inCollectionViewLayout: collectionViewLayout) == true {
return true
} else {
return super.shouldUseForDownstreamCalculation(for: indexPath, with: identifier, for: collectionViewLayout)
}
}
override func updateStickyAttributesInCollectionView(_ collectionViewLayout: UICollectionViewLayout, attributesDidUpdate: (_ attributes: BrickLayoutAttributes, _ oldFrame: CGRect?) -> Void) {
//Sort the attributes ascending
stickyAttributes.sort { (attributesOne, attributesTwo) -> Bool in
let maxYOne: CGFloat = attributesOne.originalFrame.maxY
let maxYTwo: CGFloat = attributesTwo.originalFrame.maxY
return maxYOne >= maxYTwo
}
super.updateStickyAttributesInCollectionView(collectionViewLayout, attributesDidUpdate: attributesDidUpdate)
}
override func updateFrameForAttribute(_ attributes:inout BrickLayoutAttributes, sectionAttributes: BrickLayoutAttributes?, lastStickyFrame: CGRect, contentBounds: CGRect, collectionViewLayout: UICollectionViewLayout) -> Bool {
let isOnFirstSection = sectionAttributes == nil || sectionAttributes?.indexPath == IndexPath(row: 0, section: 0)
let bottomInset = collectionViewLayout.collectionView!.contentInset.bottom
if isOnFirstSection {
collectionViewLayout.collectionView?.scrollIndicatorInsets.bottom = attributes.originalFrame.height + bottomInset
attributes.frame.origin.y = contentBounds.maxY - attributes.originalFrame.size.height - bottomInset
} else {
let y = contentBounds.maxY - attributes.originalFrame.size.height - bottomInset
attributes.frame.origin.y = min(y, attributes.originalFrame.origin.y)
}
if lastStickyFrame.size != CGSize.zero {
attributes.frame.origin.y = min(lastStickyFrame.minY - attributes.originalFrame.height, attributes.originalFrame.origin.y)
}
return !isOnFirstSection
}
}
| true
|
5af0e2d5d3530e35d4af3f2dd1959b8fbd244187
|
Swift
|
min92mon/ChatBoard
|
/ChatBoard/ProfileViewController.swift
|
UTF-8
| 1,259
| 2.6875
| 3
|
[] |
no_license
|
//
// ProfileViewController.swift
// ProfileViewController
//
// Created by 정민영 on 2021/08/16.
//
import UIKit
class ProfileViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func setupLayout() {
super.setupLayout()
setupNavigtaionBar()
}
}
// MARK: - UINavigationItemFactoryDelegate Protocol
extension ProfileViewController: UINavigationItemFactoryDelegate {
func SettingButtonAction(_ Sender: Any) {
print("setting")
}
func EditButtonAction(_ Sender: Any) {
print("edit")
}
}
// MARK: - CustomableNaviBar Protocol
extension ProfileViewController: CustomableNaviBar {
var naviItemFactory : UINavigationItemFactory {
get {
return UINavigationItemFactory(delegate: self)
}
}
func MakeLeftNaviItems() -> [UIBarButtonItem]? {
return [UIBarButtonItem(customView: naviItemFactory.MakeTitleLabel(text: "프로필"))]
}
func MakeRightNaviItems() -> [UIBarButtonItem]? {
return [naviItemFactory.MakeSettingButton(),
naviItemFactory.MakeEditButton()]
}
func MakeNaviTitleView() -> UIView? {
return nil
}
}
| true
|
318fca56969d93640a9c7f3135154c054c4b4797
|
Swift
|
tobx/shairport-sync-agent
|
/Shairport Sync Agent/StatusMenuController.swift
|
UTF-8
| 1,458
| 2.65625
| 3
|
[] |
no_license
|
//
// StatusMenuController.swift
// Shairport Sync Agent
//
// Created by Tobias Strobel on 27.11.17.
// Copyright © 2017 Tobias Strobel. All rights reserved.
//
import Cocoa
class StatusMenuController: NSObject {
@IBOutlet var statusMenu: NSMenu!
private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
private var startItem: NSMenuItem?
private var stopItem: NSMenuItem?
var shairportSyncAgent: Agent? {
didSet {
self.shairportSyncAgent!.addStartCallback {
self.startItem!.isEnabled = false
self.stopItem!.isEnabled = true
}
self.shairportSyncAgent!.addTerminationCallback { terminationStatus -> Void in
self.stopItem!.isEnabled = false
self.startItem!.isEnabled = true
}
self.shairportSyncAgent!.addStartErrorCallback { error -> Void in
self.stopItem!.isEnabled = false
self.startItem!.isEnabled = true
}
}
}
override func awakeFromNib() {
self.statusItem.image = NSImage(named: NSImage.Name("Air Receiver Status Bar Icon"))
self.statusItem.menu = self.statusMenu
self.startItem = self.statusMenu.item(withTag: 1)!
self.stopItem = self.statusMenu.item(withTag: 2)!
}
@IBAction func startShairportSyncClicked(_ sender: NSMenuItem) {
self.startItem!.isEnabled = false
self.shairportSyncAgent!.start()
}
@IBAction func stopShairportSyncClicked(_ sender: NSMenuItem) {
self.stopItem!.isEnabled = false
self.shairportSyncAgent!.stop()
}
}
| true
|
969320e174f0816100bf10ea9ee05080c9a6eceb
|
Swift
|
robertoschwald/ImageUtil
|
/ImageUtil/Optional.swift
|
UTF-8
| 646
| 2.796875
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
public func >>-<A, B>(a: A?, f: A -> B?) -> B? {
if let x = a {
return f(x)
} else {
return .None
}
}
public func <^><A, B>(f: A -> B, a: A?) -> B? {
if let x = a {
return f(x)
} else {
return .None
}
}
public func <*><A, B>(f: (A -> B)?, a: A?) -> B? {
if let x = a {
if let fx = f {
return fx(x)
}
}
return .None
}
public func <|<K,V>(d: Dictionary<K,V>?, key: K) -> V? {
if let dx = d{
return dx[key]
}
return .None
}
public func <|><K,V>(d: Dictionary<K,V>?, key: K) -> Dictionary<K,V>? {
if let dx = d{
return dx[key] as? Dictionary
}
return .None
}
| true
|
28f4fa4bff6db3279880ea6173aef5fcf1c6e9eb
|
Swift
|
hoangvu9147/QRScan_IOS
|
/QRScanVNPost/ui/viewCustom/Zebra/RFID/Models/RfidReaderError.swift
|
UTF-8
| 1,877
| 2.59375
| 3
|
[] |
no_license
|
//
// RfidReaderError.swift
// Monistor
//
// Created by lhvu on 2018/12/27.
// Copyright © 2018 MoonFactory. All rights reserved.
//
import Foundation
public struct RfidReaderError {
public var id: Int
public var description: String
}
public func rfidError(_ errCode: Int) -> RfidReaderError {
switch errCode {
case 1:
return RfidReaderError(id: 1, description: "Operation Failed.")
case 2:
return RfidReaderError(id: 2, description: "Reader Not Available.")
case 4:
return RfidReaderError(id: 4, description: "Parameter does not match.")
case 5:
return RfidReaderError(id: 5, description: "Response Timeout Error.")
case 6:
return RfidReaderError(id: 6, description: "Not Supported Operation.")
case 7:
return RfidReaderError(id: 7, description: "Response From Reader Error.")
case 8:
return RfidReaderError(id: 8, description: "ASCII Password Error.")
case 9:
return RfidReaderError(id: 9, description: "ASCII Connection Required.")
default:
return RfidReaderError(id: 1, description: "Operation Failed.")
}
}
public let RFID_ERR_DEVICE_NOT_IN_PROCESS = RfidReaderError(id: 993, description: "Device is NOT working on any task")
public let RFID_ERR_DEVICE_IN_PROCESS = RfidReaderError(id: 994, description: "Device is already working on a task")
public let RFID_ERR_POWER_LEVEL_INVALID = RfidReaderError(id: 995, description: "Power Level is Invalid")
public let RFID_ERR_NO_DEVICE = RfidReaderError(id: 996, description: "No Device Available")
public let RFID_ERR_CONNECTING = RfidReaderError(id: 997, description: "(Dis)Connecting Device...")
public let RFID_ERR_CONNECTED = RfidReaderError(id: 998, description: "Already Connected Device.")
public let RFID_ERR_NOT_CONNECTED = RfidReaderError(id: 999, description: "No Connected Device.")
| true
|
f769d0a91fa00a25a727147a2a85d001656a2eb7
|
Swift
|
OLI9292/AdCrush
|
/AdCrush/Advertisement.swift
|
UTF-8
| 3,228
| 2.796875
| 3
|
[] |
no_license
|
///
/// Advertisement.swift
///
import SpriteKit
import RxSwift
import RxGesture
class Advertisement: SKSpriteNode, GameElement {
var bag = DisposeBag()
var isBeingCrushed = false
var audioNode: AudioNode!
var skScene: SKScene
init(skScene: SKScene) {
self.skScene = skScene
let texture = SKTexture(imageNamed: "ad\(10.asMaxRandom())")
super.init(texture: texture, color: UIColor.blue, size: texture.size())
addPhysics()
observeGesture()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Observer
func observeGesture() {
skScene.view?.rx
.panGesture()
.skip(1)
.take(1)
.subscribe(onNext: { gesture in
// Measured in points / sec
let velocity: CGPoint = gesture.velocity(in: self.skScene.view)
let direction = self.determineDirection(velocity: velocity)
self.crush(with: velocity, direction: direction)
})
.addDisposableTo(bag)
}
// MARK: - Physics
func addPhysics() {
self.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.size.width,
height: self.size.height))
physicsBody?.affectedByGravity = false
physicsBody?.density = 0.4
physicsBody?.collisionBitMask = 0
}
// MARK: - Animation
func crush(with velocity: CGPoint, direction: CrushDirection) {
RealmController.user.gain(karma: RealmController.user.totalKarmaPerCrush)
isBeingCrushed = true
physicsBody?.affectedByGravity = true
let flyAway = SKAction.applyImpulse(CGVector(dx: velocity.x * 10, dy: velocity.y * -10), duration: 0.2)
// print("velocity.x * 10", velocity.x * 10)
// print("velocity.y * 10", velocity.y * 10)
self.run(flyAway)
audioNode?.play()
let crush = CrushAnimation(velocity: velocity, direction: direction)
let crushAction = crush.action
let wait = SKAction.wait(forDuration: 1.5)
let remove = SKAction.removeFromParent()
let sequence = SKAction.sequence([crushAction, wait, remove])
run(sequence)
}
private func determineDirection(velocity: CGPoint) -> CrushDirection {
let isVerticalGesture = abs(velocity.y) > abs(velocity.x)
if isVerticalGesture {
return velocity.y < 0 ? CrushDirection.up : CrushDirection.down
} else {
return velocity.x > 0 ? CrushDirection.right : CrushDirection.left
}
}
// MARK: - Overrides
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let scale = SKAction.scale(by: 1.1, duration: 0.1)
self.run(scale)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let scale = SKAction.scale(by: 0.9, duration: 0.1)
self.run(scale)
}
// MARK: - Layout
func layout() {
position = CGPoint(x: skScene.size.width / 2 , y: skScene.size.height / 2)
size = CGSize(width: 300, height: 300)
isUserInteractionEnabled = true
skScene.insertChild(self, at: 0)
audioNode = AudioNode(soundString: "crumple\(4.asMaxRandom()).aif")
skScene.addChild(self.audioNode!.sound)
}
}
| true
|
22f9c271edb0b5ee7fe7db710e932487889cc4d6
|
Swift
|
famesprinter/SlideViewWithCollectionView
|
/SlideViewWithCollectionView/ViewController.swift
|
UTF-8
| 1,617
| 2.859375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// SlideViewWithCollectionView
//
// Created by Kittitat Rodphotong on 12/23/2559 BE.
// Copyright © 2559 DevGo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: - IBOutlet
@IBOutlet weak var collectionView: UICollectionView!
// MARK: - Variable
let CVCellIdentifier = "CollectionViewCell"
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CVCellIdentifier,
for: indexPath)
return cell
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let w: CGFloat = (collectionView.bounds.size.width)-50
let h: CGFloat = (collectionView.bounds.size.height)-64
return CGSize(width: w, height: h)
}
}
| true
|
4d3ae52d30e2d893de2a2d9f8dbad45860d2c73a
|
Swift
|
bessonnet/SwiftGraphKit
|
/Example/SwiftGraphKit/Complexe Sample/Date+Formater.swift
|
UTF-8
| 495
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// Date+Formater.swift
// SwiftGraphKit_Example
//
// Created by Charles Bessonnet on 24/02/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
extension Date {
static let dayFormatter = DateFormatter()
static let calendar = Calendar.current
func weekSymbol() -> String {
let index = Date.calendar.component(.weekday, from: self)
let dayString = Date.dayFormatter.weekdaySymbols[index - 1]
return String(dayString.prefix(1))
}
}
| true
|
0cee542886e16a2b824f2f40474469175c590ef2
|
Swift
|
nadeen97/MoviesApp
|
/Movies/VideoYoutubePlayer.swift
|
UTF-8
| 1,099
| 2.53125
| 3
|
[] |
no_license
|
//
// VideoYoutubePlayer.swift
// Movies
//
// Created by Sara Alaa on 3/16/20.
// Copyright © 2020 ITI. All rights reserved.
//
import UIKit
class VideoYoutubePlayer: UIViewController {
// var movieSelcted = Movie()
var movieTraile = ""
@IBOutlet weak var youtubePlayer: YTPlayerView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.init(red: 31/255, green: 33/255, blue:36/255 , alpha: 1.0)
// self.view.backgroundColor = UIColor.white.withAlphaComponent(0.1)
// youtubePlayer.loadWithVideoId("6JnN1DmbqoU")
youtubePlayer.load(withVideoId: movieTraile)
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
9061a5a7096599efcc44cf819db9056e310ca0d8
|
Swift
|
andrewnguonly/DaysSinceBeef
|
/dayssincebeef WatchKit Extension/DaysSinceBeefApp.swift
|
UTF-8
| 3,892
| 2.703125
| 3
|
[] |
no_license
|
//
// dayssincebeefApp.swift
// dayssincebeef WatchKit Extension
//
// Created by Andrew Nguonly on 10/3/20.
//
import SwiftUI
import UserNotifications
@main
struct DaysSinceBeefApp: App {
@WKExtensionDelegateAdaptor private var extensionDelegate: ExtensionDelegate
let persistenceController = PersistenceController.shared
@SceneBuilder var body: some Scene {
WindowGroup {
NavigationView {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
WKNotificationScene(controller: NotificationController.self, category: "ActionCheck")
}
}
class ExtensionDelegate: NSObject, WKExtensionDelegate, UNUserNotificationCenterDelegate {
func applicationDidFinishLaunching() {
registerNotifications()
}
func registerNotifications() {
requestNotificationAuthorization()
registerNotificationCategories()
registerActionCheckNotification()
UNUserNotificationCenter.current().delegate = self
}
func requestNotificationAuthorization() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
print("App authorized for notifications")
} else if let error = error {
print(error.localizedDescription)
}
}
}
func registerNotificationCategories() {
let confirmAction = UNNotificationAction(identifier: "ConfirmAction",
title: "👍",
options: [.foreground])
let denyAction = UNNotificationAction(identifier: "DenyAction",
title: "👎",
options: [.foreground])
let actionCheckCategory = UNNotificationCategory(identifier: "ActionCheck",
actions: [confirmAction, denyAction],
intentIdentifiers: [],
options: [])
let categories: Set<UNNotificationCategory> = [actionCheckCategory]
UNUserNotificationCenter.current().setNotificationCategories(categories)
}
func registerActionCheckNotification() {
let content = UNMutableNotificationContent()
content.title = "🥩 Check"
content.sound = UNNotificationSound.default
content.categoryIdentifier = "ActionCheck"
// show this notification at 4AM every day
var dateComponents = DateComponents()
dateComponents.hour = 4
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents,
repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString,
content: content,
trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
switch response.actionIdentifier {
case "ConfirmAction":
print("action confirmed")
break
case "DenyAction":
print("action denied")
break
default:
print(response.actionIdentifier)
break
}
completionHandler()
}
}
| true
|
a66598dd6daf6a37f5ecf2507a4b84e3825c7147
|
Swift
|
nier-spm/vapor-line
|
/Sources/Models/Object/Message/LineFlexMessageObject/LineFlexMessageComponent.swift
|
UTF-8
| 4,452
| 3.375
| 3
|
[] |
no_license
|
import Foundation
// MARK: - [ Protocol ] LineFlexMessageComponent
/**
[FlexMessageElements]: https://developers.line.biz/en/docs/messaging-api/flex-message-elements/
[FlexMessageLayout]: https://developers.line.biz/en/docs/messaging-api/flex-message-layout/
Components are elements that make up a block.
- `type`: Type of component. See **LineFlexMessageComponentType**.
For JSON samples and usage of each component, see [Flex Message elements][FlexMessageElements] and [Flex Message layout][FlexMessageLayout] in the Messaging API documentation.
*/
public protocol LineFlexMessageComponent {
var type: LineFlexMessageComponentType { get }
}
struct LineFlexMessageComponentPrototype: LineFlexMessageComponent, Codable {
var type: LineFlexMessageComponentType
}
// MARK: - LineFlexMessageComponentType
/**
- `box`
- `button`
- `image`
- `icon`
- `text`
- `span`
- `separator`
- `filler`
*/
public enum LineFlexMessageComponentType: String, Codable {
case box
case button
case image
case icon
case text
case span
case separator
case filler
}
// MARK: - LineFlexMessageComponentPosition
/**
[Offset]: https://developers.line.biz/en/docs/messaging-api/flex-message-layout/#component-offset
Reference position for placing this box.
Specify one of the following values:
- `relative`: Use the previous box as reference.
- `absolute`: Use the top left of parent element as reference.
The default value is `relative`. For more information, see [Offset] in the Messaging API documentation.
*/
public enum LineFlexMessageComponentPosition: String, Codable {
case relative
case absolute
}
// MARK: - LineFlexMessageComponentHorizontalAlignment
/**
You can use the `align` property to specify how components should be aligned horizontally.
The `align` property always applies to horizontal placement, regardless of how the parent element (box) has been configured. Specify one of these values:
- `start`: Left-aligned
- `end`: Right-aligned
- `center`: Center-aligned (default value)
*/
public enum LineFlexMessageComponentHorizontalAlignment: String, Codable {
case start
case end
case center
}
// MARK: - LineFlexMessageComponentVerticalAlignment
/**
You can use the `gravity` property to specify how components should be aligned vertically.
The `gravity` property always applies to vertical placement, regardless of how the parent element (box) has been configured. Specify one of these values:
- `top`: Top-aligned (default value)
- `bottom`: Bottom-aligned
- `center`: Center-aligned
*/
public enum LineFlexMessageComponentVerticalAlignment: String, Codable {
case top
case bottom
case center
}
// MARK: - LineFlexMessageComponentAspectMode
/**
- `cover`: The image fills the entire drawing area. Parts of the image that do not fit in the drawing area are not displayed.
- `fit`: The entire image is displayed in the drawing area. A background is displayed in the unused areas to the left and right of vertical images and in the areas above and below horizontal images.
*/
public enum LineFlexMessageComponentAspectMode: String, Codable {
case cover
case fit
}
// MARK: - LineFlexMessageComponentFontWeight
/**
- `regular`
- `bold`
*/
public enum LineFlexMessageComponentFontWeight: String, Codable {
case regular
case bold
}
// MARK: - LineFlexMessageComponentTextStyle
/**
- `normal`
- `italic`
*/
public enum LineFlexMessageComponentTextStyle: String, Codable {
case normal
case italic
}
// MARK: - LineFlexMessageComponentDecoration
/**
- `none`
- `underline`
- `lineThrough`: Strikethrough
*/
public enum LineFlexMessageComponentDecoration: String, Codable {
case none
case underline
case lineThrough = "line-through"
}
// MARK: - LineFlexMessageComponentAdjustMode
/**
[AdjustsFontsizeToFit]: https://developers.line.biz/en/docs/messaging-api/flex-message-layout/#adjusts-fontsize-to-fit
- `shrinkToFit`: Automatically shrink the font size to fit the width of the component. This property takes a "best-effort" approach that may work differently—or not at all!—on some platforms. For more information, see [Automatically shrink fonts to fit][AdjustsFontsizeToFit] in the Messaging API documentation.
- LINE 10.13.0 or later for iOS and Android
*/
public enum LineFlexMessageComponentAdjustMode: String, Codable {
case shrinkToFit = "shrink-to-fit"
}
| true
|
c933aaba19dfb991373805f5f89636bf4ca27bba
|
Swift
|
crdesai25/IOS-ObjC
|
/CodeScan/UIView/Code/BarcodeTypeTVC.swift
|
UTF-8
| 3,487
| 2.59375
| 3
|
[] |
no_license
|
//
// BarcodeTypeTVC.swift
import UIKit
import AVFoundation
class BarcodeTypeTVC: UITableViewCell {
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var validationImageView: UIImageView!
var code: AVMetadataObject.ObjectType!
override func awakeFromNib() {
super.awakeFromNib()
}
class func nib() -> UINib {
return UINib(nibName: self.nameOfClass, bundle: nil)
}
func setSelected(code: AVMetadataObject.ObjectType) {
self.code = code
var stringCode: String!
switch code
{
case AVMetadataObject.ObjectType.ean8:
stringCode = "EAN-8"
case AVMetadataObject.ObjectType.ean13:
stringCode = "EAN-13"
case AVMetadataObject.ObjectType.pdf417:
stringCode = "PDF417"
case AVMetadataObject.ObjectType.aztec:
stringCode = "Aztec"
case AVMetadataObject.ObjectType.code128:
stringCode = "Code128"
case AVMetadataObject.ObjectType.code39:
stringCode = "Code39"
case AVMetadataObject.ObjectType.code39Mod43:
stringCode = "Code39Mod43"
case AVMetadataObject.ObjectType.code93:
stringCode = "Code93"
case AVMetadataObject.ObjectType.dataMatrix:
stringCode = "DataMatrix"
case AVMetadataObject.ObjectType.face:
stringCode = "Face"
case AVMetadataObject.ObjectType.interleaved2of5:
stringCode = "Interleaved2of5"
case AVMetadataObject.ObjectType.itf14:
stringCode = "ITF14"
case AVMetadataObject.ObjectType.qr:
stringCode = "QRCode"
case AVMetadataObject.ObjectType.upce:
stringCode = "UPC-E"
default:
break
}
nameLbl.text = stringCode
nameLbl.textColor = UIColor.metallicSeaweed
validationImageView.image = UIImage(named: CHECK_BLUE)
}
func setUnselected(code: AVMetadataObject.ObjectType) {
self.code = code
var stringCode: String!
switch code {
case AVMetadataObject.ObjectType.ean8:
stringCode = "EAN-8"
case AVMetadataObject.ObjectType.ean13:
stringCode = "EAN-13"
case AVMetadataObject.ObjectType.pdf417:
stringCode = "PDF417"
case AVMetadataObject.ObjectType.aztec:
stringCode = "Aztec"
case AVMetadataObject.ObjectType.code128:
stringCode = "Code128"
case AVMetadataObject.ObjectType.code39:
stringCode = "Code39"
case AVMetadataObject.ObjectType.code39Mod43:
stringCode = "Code39Mod43"
case AVMetadataObject.ObjectType.code93:
stringCode = "Code93"
case AVMetadataObject.ObjectType.dataMatrix:
stringCode = "DataMatrix"
case AVMetadataObject.ObjectType.face:
stringCode = "Face"
case AVMetadataObject.ObjectType.interleaved2of5:
stringCode = "Interleaved2of5"
case AVMetadataObject.ObjectType.itf14:
stringCode = "ITF14"
case AVMetadataObject.ObjectType.qr:
stringCode = "QRCode"
case AVMetadataObject.ObjectType.upce:
stringCode = "UPC-E"
default:
break
}
nameLbl.text = stringCode
nameLbl.textColor = UIColor.black
validationImageView.image = nil
}
}
| true
|
e85f6e347dd3f830bf4932245b62de7eb44e2374
|
Swift
|
Rookie-iOS/RxSwiftLearn
|
/RxSymbols/Network/ResponseModel.swift
|
UTF-8
| 2,371
| 2.796875
| 3
|
[] |
no_license
|
//
// ResponseModel.swift
// RxSymbols
//
// Created by 覃孙波 on 2021/2/19.
//
import Foundation
import HandyJSON
import RxSwift
import SwiftyJSON
struct ResponseModel {
var status: Int = 0
var msg = ""
let data: Data?
var arrayData:[[String : Any]] = []
var dictData: [String : Any] = [:]
var jsonString = ""
init(_ data: Data) {
self.data = data
do {
let allDic = (try? JSON.init(data: data).dictionaryObject) ?? [:]
// let allDic = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! Dictionary<String, Any>
let dict = allDic["result"] as? Dictionary<String, Any> ?? [:]
let jsonString = JSON(data).description
self.jsonString = jsonString
let tempStatus = dict["error_code"] as? Int
if tempStatus != nil {
status = tempStatus!
}
let tempMessage = dict["reason"] as? String
if tempMessage != nil {
msg = tempMessage!
}
let tempArray = dict["data"] as? [[String : Any]]
if tempArray != nil {
arrayData = tempArray!
}
let tempDict = dict["data"] as? [String : Any]
if tempDict != nil {
dictData = tempDict!
}
} catch _ {
print("数据解析错误")
}
}
}
extension ResponseModel{
func mapModel<T:HandyJSON>(_ type:T.Type,designatedPath:String?) -> T?{
return T.deserialize(from: self.jsonString, designatedPath: designatedPath)
}
func mapArrayModel<T:HandyJSON>(_ type:T.Type,designatedPath:String? ) -> [T]{
return [T].deserialize(from: jsonString, designatedPath: designatedPath) as? [T] ?? []
}
}
extension PrimitiveSequence where Trait == SingleTrait,Element == ResponseModel{
func mapMode<T:HandyJSON>(_ type:T.Type,designatedPath:String? = "result.data") ->Single<T>{
return flatMap { response -> Single<T> in
if let value = response.mapModel(T.self, designatedPath: designatedPath){
return Single.just(value)
}
return Single.error(LYError.init(des: "解析数据错误"))
}
}
func mapArrayModel<T:HandyJSON>(_ type: T.Type,designatedPath:String? = "result.data") -> Single<[T]> {
return flatMap { response -> Single<[T]> in
return Single.just(response.mapArrayModel(T.self, designatedPath: designatedPath))
}
}
}
| true
|
212d8b0f8458b3c87ec179e223499969ff5dd258
|
Swift
|
corygreen84/RandomRestaurant
|
/RestaurantApp/RestaurantApp/Colors/Colors.swift
|
UTF-8
| 612
| 2.5625
| 3
|
[] |
no_license
|
//
// Colors.swift
// RestaurantApp
//
// Created by Cory Green on 6/28/20.
// Copyright © 2020 Cory Green. All rights reserved.
//
import UIKit
class Colors: NSObject {
static var sharedInstance = Colors()
// light blue //
var lightBlue:UIColor = UIColor(red: 0.0/255.0, green: 191.0/255.0, blue: 229.0/255.0, alpha: 1.0)
// light green //
var green:UIColor = UIColor(red: 53.0/255.0, green: 229.0/255.0, blue: 0.0/255.0, alpha: 1.0)
// black transparent //
var blackTransparent:UIColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 0.75)
}
| true
|
ac7f41a1636c4f806f39594daaec4284070f5e14
|
Swift
|
nootfly/SwiftFileKit
|
/SwiftFileUtils/SwiftFileKit.swift
|
UTF-8
| 1,425
| 3.0625
| 3
|
[
"MIT"
] |
permissive
|
//
// FileUtils.swift
// SwiftFileUtils
//
// Created by Noot on 4/10/2015.
// Copyright © 2015 NF. All rights reserved.
//
import Foundation
struct FileInfo {
var name:String
var size:UInt64
var line:Int
}
class SwiftFileUtils {
init(){
print("Class has been initialised")
}
func doSomething() {
print("Yeah, it works")
}
class func isFile(filePath:String) -> Bool? {
return NSFileManager.defaultManager().isFile(filePath)
}
class func createIOSDocumentFolder(folderName: String) -> Bool {
return NSFileManager.defaultManager().createIOSDocumentFolder(folderName)
}
class func createDir(dir:String) -> String? {
return NSFileManager.defaultManager().createDir(dir)
}
class func sortFilesInDirBySize(dir: String, filter:(String -> Bool)) -> [FileInfo]? {
let fileManager = NSFileManager.defaultManager()
let fileInfoArray = fileManager.allFilesInDirectory(dir, filter: filter)
return fileInfoArray?.sort {$0.size > $1.size }
}
class func sortFilesInDirByNumberOfLines(dir: String, filter:(String -> Bool)) -> [FileInfo]? {
let fileManager = NSFileManager.defaultManager()
let fileInfoArray = fileManager.allFilesInDirectory(dir, filter: filter)
return fileInfoArray?.sort {$0.line > $1.line }
}
}
| true
|
da7b0493285f0f361192eab7f0ea12b00beee12e
|
Swift
|
caohuoxia/MGTV-Swift-master
|
/MGTV-Swift/Share/BaseViewSource/CollectionViewModel.swift
|
UTF-8
| 3,854
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// CollectionViewModel.swift
// MGTV-Swift
//
// Created by Che Yongzi on 2016/12/22.
// Copyright © 2016年 Che Yongzi. All rights reserved.
//
import UIKit
typealias CollectionViewProtocol = UICollectionViewDelegate & UICollectionViewDataSource & UICollectionViewDelegateFlowLayout
protocol ViewModelProtocol {
associatedtype DataType
var datas: [[DataType]] { get set }
associatedtype ViewType
associatedtype CellType
func cellConfig(_ view: ViewType, datas: [[DataType]], indexPath: IndexPath) -> CellType
}
class CollectionViewModel<T>: NSObject, ViewModelProtocol,CollectionViewProtocol {
typealias DataType = T
typealias ViewType = UICollectionView
typealias CellType = UICollectionViewCell
var datas: [[T]] = []
func cellConfig(_ view: UICollectionView, datas: [[T]], indexPath: IndexPath) -> UICollectionViewCell {
return UICollectionViewCell()
}
func reusableView(_ view: UICollectionView, indexPath: IndexPath, kind: String) -> UICollectionReusableView {
return UICollectionReusableView()
}
func selectItem(_ indexPath: IndexPath) {
}
func itemSize(_ indexPath: IndexPath) -> CGSize {
return CGSize(width: 0, height: 0)
}
func insetForSection(_ section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func minimumLineSpacing(_ section: Int) -> CGFloat {
return 0
}
func minimumInteritemSpacing(_ section: Int) -> CGFloat {
return 0
}
init(_ collectionDatas: [[T]]) {
datas = collectionDatas
super.init()
}
//MARK: - UICollectionView DataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return datas.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return datas[section].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return cellConfig(collectionView, datas: datas, indexPath: indexPath)
}
//MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectItem(indexPath)
}
//MARK: UICollectionView DelegateFlowlayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//默认是page类型
let size = itemSize(indexPath);
let itemSizeWith = size.width == 0 ? collectionView.bounds.size.width : size.width
let itemSizeHeight = size.height == 0 ? collectionView.bounds.size.height : size.height
return CGSize(width: itemSizeWith, height: itemSizeHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return insetForSection(section)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return minimumLineSpacing(section)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return minimumInteritemSpacing(section)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return reusableView(collectionView, indexPath: indexPath, kind: kind)
}
}
| true
|
c902116e711f239d8e03eae636d4348531a6a963
|
Swift
|
tchapgouv/tchap-ios
|
/Tchap/Managers/AppVersionChecker/AppVersionCheckerResult+Codable.swift
|
UTF-8
| 2,059
| 2.859375
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
enum AppVersionCheckerResultDecodingError: Error {
case dataCorrupted
}
extension AppVersionCheckerResult: Codable {
/// Serialization keys associated to AppVersionCheckerResult properties.
enum CodingKeys: CodingKey {
case upToDate
case shouldUpdate
case unknown
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .upToDate:
try container.encode(true, forKey: .upToDate)
case .shouldUpdate(versionInfo: let versionInfo):
try container.encode(versionInfo, forKey: .shouldUpdate)
case .unknown:
try container.encode(true, forKey: .unknown)
}
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let value = try? container.decode(Bool.self, forKey: .upToDate), value == true {
self = .upToDate
return
} else if let versionInfo = try? container.decode(ClientVersionInfo.self, forKey: .shouldUpdate) {
self = .shouldUpdate(versionInfo: versionInfo)
return
} else if let value = try? container.decode(Bool.self, forKey: .unknown), value == true {
self = .unknown
return
} else {
throw AppVersionCheckerResultDecodingError.dataCorrupted
}
}
}
| true
|
d6f4a205dfe51b3fdd11ab5d5aea4634097eb1a3
|
Swift
|
Tambanco/Browser
|
/Browser/Extensions/MainView/Buttons.swift
|
UTF-8
| 1,781
| 2.890625
| 3
|
[] |
no_license
|
//
// Buttons.swift
// Browser
//
// Created by tambanco 🥳 on 01.06.2021.
//
import UIKit
extension MainViewController {
func configureButtons() {
let heightOfView = view.frame.height
let widthOfView = view.frame.width
let heightOfElement: CGFloat = 50.0
let widthOfElement: CGFloat = widthOfView - 40.0
let cornerRadius: CGFloat = 10
let loginButton = UIButton(frame: CGRect(x: 20, y: heightOfView * 0.85, width: widthOfElement, height: heightOfElement))
loginButton.setTitle("Go", for: .normal)
loginButton.backgroundColor = #colorLiteral(red: 0.168627451, green: 0.3921568627, blue: 0.7725490196, alpha: 1)
loginButton.layer.cornerRadius = cornerRadius
loginButton.layer.shadowOpacity = 0.1
loginButton.layer.shadowRadius = 3.0
loginButton.layer.shadowColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
loginButton.layer.shadowOffset = CGSize(width: 3.0, height: 3.0)
loginButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
elementAnimator(loginButton)
self.view.addSubview(loginButton)
}
@objc func buttonTapped(sender : UIButton) {
let webVC = self.storyboard!.instantiateViewController(withIdentifier: "WebViewController") as! WebViewController
let navController = UINavigationController(rootViewController: webVC)
navController.modalPresentationStyle = .fullScreen
if textForRequest.contains("https://") {
webVC.textFromMainVC = textForRequest
} else {
webVC.textFromMainVC = "https://\(textForRequest)"
}
self.present(navController, animated:true, completion: nil)
}
}
| true
|
68b89b405c11dd6213754ed9bcd865e60dcff388
|
Swift
|
kylef/JSONSchema.swift
|
/Tests/JSONSchemaTests/ValidationResultTests.swift
|
UTF-8
| 1,160
| 2.59375
| 3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
import Foundation
import Spectre
@testable import JSONSchema
public let testValidationResult: ((ContextType) -> Void) = {
$0.describe("valid result") {
$0.it("can be converted to JSON") {
let result = ValidationResult.valid
let jsonData = try JSONEncoder().encode(result)
let json = try! JSONSerialization.jsonObject(with: jsonData) as! NSDictionary
try expect(json) == [
"valid": true,
]
}
}
$0.describe("invalid result") {
$0.it("can be converted to JSON") {
let error = ValidationError(
"example description",
instanceLocation: JSONPointer(path: "/test/1"),
keywordLocation: JSONPointer(path: "#/example")
)
let result = ValidationResult.invalid([error])
let jsonData = try JSONEncoder().encode(result)
let json = try! JSONSerialization.jsonObject(with: jsonData) as! NSDictionary
try expect(json) == [
"valid": false,
"errors": [
[
"error": "example description",
"instanceLocation": "/test/1",
"keywordLocation": "#/example",
],
],
]
}
}
}
| true
|
88b4f9e029af1b71d246a6740e857169636cbe8a
|
Swift
|
bojanstef/BitAlarm
|
/BitAlarm/Services/CacheService.swift
|
UTF-8
| 2,478
| 2.921875
| 3
|
[] |
no_license
|
//
// CacheService.swift
// BitAlarm
//
// Created by Bojan Stefanovic on 12/17/17.
// Copyright © 2017 Stefanovic Ventures. All rights reserved.
//
import Foundation
enum Cachefilenames: String {
case cryptocoins = "ventures.stefanovic.BitAlarm.Cryptocoins.plist"
case alarms = "ventures.stefanovic.BitAlarm.Alarms.plist"
}
protocol CacheServiceable {
func saveAlarm(_ alarmToSave: Alarm) throws
func deleteAlarm(_ alarmToRemove: Alarm) throws
func updateAlarm(_ alarmToUpdate: Alarm, updated: Alarm) throws
func saveObject(_ object: Any, in filename: Cachefilenames) throws
func getObject(_ filename: Cachefilenames) throws -> Any?
}
final class CacheService {
static let `default` = CacheService()
fileprivate var alarms = [Alarm]()
private init() {
self.alarms = (try? getObject(.alarms) as? [Alarm] ?? []) ?? []
}
}
extension CacheService: CacheServiceable {
func saveAlarm(_ alarmToSave: Alarm) throws {
alarms.append(alarmToSave)
try saveObject(alarms, in: .alarms)
}
func deleteAlarm(_ alarmToRemove: Alarm) throws {
guard let index = alarms.index(of: alarmToRemove) else {
throw NSError(domain: #function, code: 1080, userInfo: nil)
}
alarms.remove(at: index)
try saveObject(alarms, in: .alarms)
}
func updateAlarm(_ alarmToUpdate: Alarm, updated: Alarm) throws {
guard let index = alarms.index(of: alarmToUpdate) else {
throw NSError(domain: #function, code: 420, userInfo: nil)
}
alarms[index] = updated
try saveObject(alarms, in: .alarms)
}
func saveObject(_ object: Any, in filename: Cachefilenames) throws {
let file = try getFile(filename).path
if !NSKeyedArchiver.archiveRootObject(object, toFile: file) {
throw NSError(domain: #function, code: 360, userInfo: nil)
}
}
func getObject(_ filename: Cachefilenames) throws -> Any? {
let file = try getFile(filename).path
return NSKeyedUnarchiver.unarchiveObject(withFile: file)
}
}
fileprivate extension CacheService {
func getFile(_ filename: Cachefilenames) throws -> URL {
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
guard let url = documentDirectoryURL else { throw NSError(domain: #function, code: 666, userInfo: nil) }
return url.appendingPathComponent(filename.rawValue)
}
}
| true
|
1db81c82e98473932e5bf174a56b64adf3ebc43d
|
Swift
|
nickpolychronakis/ColorExtensions
|
/Tests/ColorExtensionsTests/ColorExtensionsTests.swift
|
UTF-8
| 3,582
| 2.953125
| 3
|
[] |
no_license
|
import XCTest
import SwiftUI
@testable import ColorExtensions
final class ColorExtensionsTests: XCTestCase {
// MARK: - COLOR <-> DATA
// Σιγουρεύομαι ότι μετατρέπει ένα Color σε Data και επιστρέφει ακριβώς το ίδιο χρώμα.
func testColorToDataAndBack() {
let underTestColors: [Color] = [
.purple,
.red,
.green,
.blue,
.yellow,
.orange,
.black,
.white,
.blue,
.clear,
.accentColor
]
measure {
for underTestColor in underTestColors {
let colorData = underTestColor.data()
XCTAssertNotNil(colorData, "Δεν δούλεψε σωστά η μετατροπή απο color σε data")
let colorFromData = Color(colorData)
XCTAssertNotNil(colorFromData, "Δεν δούλεψε σωστά η μετατροπή απο data σε color")
let systemColorComponents = underTestColor.components
let colorFromDataComponents = colorFromData?.components
XCTAssertEqual(systemColorComponents?.red, colorFromDataComponents?.red)
XCTAssertEqual(systemColorComponents?.green, colorFromDataComponents?.green)
XCTAssertEqual(systemColorComponents?.blue, colorFromDataComponents?.blue)
XCTAssertEqual(systemColorComponents?.opacity, colorFromDataComponents?.opacity)
}
}
}
// MARK: - ACCESSIBLE COLORS
// Σιγουρεύομαι ότι επιστρέφει το σωστό χρώμα για τα fonts ανάλογα με το χρώμα του φόντου
func testAccessibleFontColor() {
let accessibleColorFontUnderTestForLightBackground = Color(.sRGB, red: 0.55, green: 0.55, blue: 0.55, opacity: 1).accessibleFontColor
XCTAssertEqual(accessibleColorFontUnderTestForLightBackground, Color.white)
let accessibleColorFontUnderTestForDarkBackground = Color(.sRGB, red: 0.6, green: 0.6, blue: 0.6, opacity: 1).accessibleFontColor
XCTAssertEqual(accessibleColorFontUnderTestForDarkBackground, Color.black)
}
// MARK: - INTERNALS
func testComponents() {
let red: CGFloat = 0.2
let green: CGFloat = 0.5
let blue: CGFloat = 0.8
let alpha: CGFloat = 1.0
#if os(macOS)
let nsColor = NSColor.init(srgbRed: red, green: green, blue: blue, alpha: alpha)
let color = Color(nsColor)
#else
let uiColor = UIColor.init(red: red, green: green, blue: blue, alpha: alpha)
let color = Color(uiColor)
#endif
let components = color.components
XCTAssertEqual(components?.red, 0.2)
XCTAssertEqual(components?.green, 0.5)
XCTAssertEqual(components?.blue, 0.8)
XCTAssertEqual(components?.opacity, 1.0)
}
func testIsLightColor() {
let sutLightColor = Color.isLightColor(red: 0.61, green: 0.61, blue: 0.61)
let sutDarkColor = Color.isLightColor(red: 0.59, green: 0.59, blue: 0.59)
XCTAssertTrue(sutLightColor)
XCTAssertFalse(sutDarkColor)
}
func testIsDarkColor() {
let sutLightColor = Color.isDarkColor(red: 0.41, green: 0.41, blue: 0.41)
let sutDarkColor = Color.isDarkColor(red: 0.39, green: 0.39, blue: 0.39)
XCTAssertFalse(sutLightColor)
XCTAssertTrue(sutDarkColor)
}
}
| true
|
da7dd7b33c17b4a4ee318fed38a1983b2a0954f2
|
Swift
|
markjarecki/FLXEnvGenerator
|
/Sources/FLXEnvGeneratorCore/Implementation/FLXEnvSpecDecoder.swift
|
UTF-8
| 1,395
| 2.734375
| 3
|
[] |
no_license
|
//
// FLXEnvSpecDecoder.swift
//
// Created by Mark Jarecki on 30/8/19.
//
import Foundation
// Third-party dependency
import PathKit
import Yams
public struct FLXEnvSpecDecoder: EnvSpecDecodable {
// MARK: - EnvSpecDecodable conformance
public static func decode(specPath: String, specName: String) throws -> EnvSpec {
let data = try readData(specPath: specPath, specName: specName)
let encodedString = String(data: data, encoding: .utf8) ?? ""
let envSpec = try FLXEnvSpecDecoder.decodeEnvSpec(yamlString: encodedString)
return envSpec
}
// MARK: - Private methods
private static func readData(specPath: String, specName: String) throws -> Data {
let filePath: String = specPath == "" ? Path.current.description : specPath
let fileName: String = specName
let path = Path(filePath) + fileName
guard let data: Data = try? path.read() else {
throw EnvError.couldNotReadData
}
return data
}
private static func decodeEnvSpec(yamlString: String) throws -> EnvSpec {
// Decode the YAML string into EnvSpec struct
let decoder = YAMLDecoder()
let envSpec = try decoder.decode(EnvSpec.self, from: yamlString)
return envSpec
}
}
| true
|
fb4ec1801fc09b3673d4cd2c7e0ff1b3a73a3576
|
Swift
|
schueda/artero
|
/Artero/Controllers/PhotoController.swift
|
UTF-8
| 2,286
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
//
// PhotoRepository.swift
// Artero
//
// Created by André Schueda on 18/06/21.
//
import UIKit
import SwiftUI
protocol PhotoRepository {
func save(image: UIImage, withIdentifier identifier: String)
func deleteImage(withIdentifier identifier: String)
func getImage(identifier: String) -> UIImage?
func getImages() -> [UIImage]
}
class PhotoDocumentRepository: PhotoRepository {
static var identifiersKey: String = "imageKeys"
var fileManager = FileManager.default
var documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
var keys: [String] {
UserDefaults.standard.array(forKey: Self.identifiersKey) as? [String] ?? []
}
func save(image: UIImage, withIdentifier identifier: String) {
if let data = image.pngData() {
let url = documents.appendingPathComponent(identifier)
do {
try data.write(to: url)
UserDefaults.standard.set(url, forKey: identifier)
addKey(key: identifier)
} catch {
print("Unable to Write Data to Disk (\(error))")
}
}
}
func deleteImage(withIdentifier identifier: String) {
let url = documents.appendingPathComponent(identifier)
do {
try fileManager.removeItem(at: url)
deleteKey(key: identifier)
UserDefaults.standard.removeObject(forKey: identifier)
} catch {
print("Unable to delete file (\(error))")
}
}
func getImage(identifier: String) -> UIImage? {
guard let photoURL = UserDefaults.standard.url(forKey: identifier),
let photoData = try? Data(contentsOf: photoURL),
let image = UIImage(data: photoData) else {
return nil
}
return image
}
func getImages() -> [UIImage] {
keys.compactMap { getImage(identifier: $0) }
}
fileprivate func addKey(key: String) {
var keys = self.keys
keys.append(key)
UserDefaults.standard.setValue(keys, forKey: Self.identifiersKey)
}
fileprivate func deleteKey(key: String) {
var keys = self.keys
keys.removeAll { $0 == key }
}
}
| true
|
99cbe442dbd4b52f7e13d6a92a8ad33ac3eaa059
|
Swift
|
tharssh/kaodim
|
/Kaodim/View Controller/MoreVC.swift
|
UTF-8
| 1,543
| 2.5625
| 3
|
[] |
no_license
|
//
// MoreVC.swift
// Kaodim
//
// Created by InsightzClub on 24/02/2020.
// Copyright © 2020 Tharsshinee. All rights reserved.
//
import UIKit
class MoreVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var moreList = [List]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
//number of cells equals number of elements displayes. No extra cells
self.tableView.tableFooterView = UIView()
self.tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return moreList[0].serviceTypes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell;
let sections = moreList[indexPath.section].serviceTypes
let name = sections[indexPath.row].name
let image = sections[indexPath.row].imageThumbURL?.md ?? ""
if image != "" {
Services.setImageFromUrl(image: image, cell: cell)
}
else{
cell.imageView?.image = UIImage(named: "no_image")
}
cell.textLabel!.text = name
return cell
}
}
| true
|
8543eb87e1b5514bff626ad8dce1480fee19cde8
|
Swift
|
maxches99/MarvelHeroes
|
/MarvelHeroes/Models/APIRequest.swift
|
UTF-8
| 340
| 2.640625
| 3
|
[] |
no_license
|
//
// APIRequest.swift
// MarvelHeroes
//
// Created by Max Chesnikov on 03.04.2021.
//
import Foundation
public protocol APIRequest: Encodable {
/// Response (will be wrapped with a DataContainer)
associatedtype Response: Decodable
/// Endpoint for this request (the last part of the URL)
var resourceName: String { get }
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.