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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d6212f49879982ada81f3d3c651378957969e67d
|
Swift
|
RENCHILIU/BookExplore
|
/BookExplore/Book.swift
|
UTF-8
| 948
| 2.78125
| 3
|
[] |
no_license
|
//
// Book.swift
// BookExplore
//
// Created by liurenchi on 2/6/18.
// Copyright © 2018 lrc. All rights reserved.
//
import Foundation
import Parse
class Book {
var title:String?
var rate:String?
var author: String?
var year: String?
var price: String?
var ISBN: String?
var image: String?
var bookDetail: String?
var authorDetail: String?
var url: String?
init(thisbook: PFObject) {
title = thisbook["title"] as? String
rate = thisbook["rating"] as? String
author = thisbook["author"] as? String
year = thisbook["year"] as? String
price = thisbook["price"] as? String
ISBN = thisbook["isbn10"] as? String
image = thisbook["images"] as? String
bookDetail = thisbook["summary"] as? String
authorDetail = thisbook["author_intro"] as? String
url = thisbook["url"] as? String
}
}
| true
|
c04b25e4e35683cf8db409bd26f2878dfc68f0a7
|
Swift
|
menttofly/LeetCode-Swift
|
/DFS/binary_tree_right_side_view.swift
|
UTF-8
| 1,240
| 3.6875
| 4
|
[] |
no_license
|
//
// binary_tree_right_side_view.swift
// LeetCode-Swift
//
// Created by menttofly on 2018/11/4.
// Copyright © 2018 menttofly. All rights reserved.
//
import Foundation
class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
/**
* Question Link: https://leetcode.com/problems/binary-tree-right-side-view/ (199)
* Primary idea: 总是通过 dfs 先访问右子树,然后在每一层存储第一个节点(右侧节点)
*
* Time Complexity: O(n), Space Complexity: O(n)
*/
class BinaryTreeRightSideView {
func rightSideView(_ root: TreeNode?) -> [Int] {
var res = [Int]()
dfs(root, 0, &res)
return res
}
private func dfs(_ node: TreeNode?, _ depth: Int, _ res: inout [Int]) {
/// 保证每一层只保存一个最右侧节点
if let val = node?.val, res.count <= depth {
res.append(val)
}
if let right = node?.right {
dfs(right, depth + 1, &res)
}
if let left = node?.left {
dfs(left, depth + 1, &res)
}
}
}
| true
|
8daa94851790c37e845fbefabeb26cb89d480369
|
Swift
|
ritvikbanakar/dvhacksIII
|
/DVHacks3/DVHacks3/SpinVC.swift
|
UTF-8
| 13,914
| 2.578125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// DVHacks3
//
// Created by Sid on 3/19/21.
//
import UIKit
import CoreLocation
import RecordButton
import SceneKit
import ARKit
import SpeechRecognizerButton
//Protocol to edit the main view functionality
protocol SpinARTestResult{
func didPassTest(isDrunk: Bool, testNumber: Int)
}
class SpinVC: UIViewController ,CLLocationManagerDelegate, ARSCNViewDelegate {
var button: SFButton! //Round Progress bar
var locateButton: UIButton! //Locate button for AR object
var currentHeading: CLLocationDirection! //Heading of the phone at any given moment
var initHeading: CLLocationDirection! //Heading of the phone the moment before this one
var startingHeading: CLLocationDirection = -10 //Initial heading of the phone, set to a negative value so we know that is has or hasn't been set
var lm:CLLocationManager! //Location manager to get the location
var progressTimer : Timer! //Progress timer
var progress : CGFloat = 0 //Progress percentage
var passed_half = false //Passed 180 degrees so we know that we are nearly about to make a full round
var recordButton : RecordButton! //Recording button inside the round progress bar
var stop_updated = false //When the button is released, stop updating
var rounds = 0 //Number of rounds
var progressLabel: UILabel! //Progress Label
var visualEffectView: UIVisualEffectView!
var sceneView: ARSCNView! //Scene view for AR
var textLabel: UILabel!
var e:EchoAR!; //Echo AR module
var s = [[0.25,0,0,0],[0,0.25,0,0],[0,0,0.25,0],[0,0,0,1]] //Scaling of the AR object
var successButton: UIButton! //Button that shows success
var numErrors = 0 //Number of errors that the user has made
var spinResult: SpinARTestResult! //Instantiation of the spin delegate
let defaults = UserDefaults.standard //User defaults
override func viewDidLoad() {
super.viewDidLoad()
sceneView = ARSCNView(frame: self.view.frame)
self.view.addSubview(sceneView)
// Set the view's delegate
sceneView.delegate = self
//let scene = SCNScene(named: "art.scnassets/River otter.usdz")!
// Show statistics such as fps and timing information
sceneView.showsStatistics = true
let e = EchoAR();
let scene = SCNScene()
e.loadAllNodes(){ (nodes) in
for node in nodes{
node.transform = SCNMatrix4(m11: 0.01, m12: 0, m13: 0, m14: 0, m21: 0, m22: 0.01, m23: 0, m24: 0, m31: 0, m32: 0, m33: 0.01, m34: 0, m41: 0, m42: 0, m43: 0, m44: 1)
let x2 = Double.random(in: -0.5...0.5)
let z2 = Double.random(in: -0.5...0.5)
node.position = SCNVector3(x2, 0, z2)
scene.rootNode.addChildNode(node);
}
}
// Set the scene to the view
sceneView.scene=scene;
visualEffectView = UIVisualEffectView()
visualEffectView.frame = self.view.frame
self.view.addSubview(visualEffectView)
visualEffectView.isUserInteractionEnabled = false
let blurAnimator = UIViewPropertyAnimator(duration: 0.5, dampingRatio: 1) {
self.visualEffectView.effect = UIBlurEffect(style: .dark)
}
blurAnimator.startAnimation()
//Sets the buttons and views to the screen
button = SFButton(frame: CGRect(x: self.view.frame.width / 2 - 50,y: self.view.frame.height / 2 + 100 ,width: 100,height: 100))
button.setImage(UIImage(named: "mic"), for: .normal)
button.isHidden = true
successButton = UIButton(frame: CGRect(x: self.view.frame.width / 2 - 100,y: self.view.frame.height + 200 ,width: 200,height: 200))
successButton.setImage(UIImage(named: "check"), for: .normal)
self.view.addSubview(successButton)
self.view.addSubview(button)
button.isUserInteractionEnabled = false
button.resultHandler = {
var up_50_px = CGAffineTransform(translationX: 0, y: -500)
self.textLabel.text = $1?.bestTranscription.formattedString
//Gets NLP text and sees if it matches the correct value to determine correct or not
if(self.textLabel.text == "Building")
{
self.button.isHidden = true
UIView.animateKeyframes(withDuration: 0.5, delay: 0, options: .calculationModeLinear, animations: {
self.successButton.transform = up_50_px
self.textLabel.text = "Success!"
self.textLabel.textColor = .green
}, completion: {
(value: Bool) in
do {
sleep(1)
}
self.spinResult.didPassTest(isDrunk: false, testNumber: 2)
self.dismiss(animated: true, completion: nil)
})
}
else
{
self.textLabel.textColor = .red
self.numErrors += 1
if(self.numErrors >= 2){
self.spinResult.didPassTest(isDrunk: true, testNumber: 2)
self.dismiss(animated: true, completion: nil)
}
}
}
//handles errors with the recording button
button.errorHandler = {
guard let error = $0 else {
self.textLabel.text = "Unknown error."
return
}
switch error {
case .authorization(let reason):
switch reason {
case .denied:
self.textLabel.text = "Authorization denied."
case .restricted:
self.textLabel.text = "Authorization restricted."
case .usageDescription(let key):
self.textLabel.text = "Info.plist \"\(key)\" key is missing."
}
case .cancelled(let reason):
switch reason {
case .notFound:
self.textLabel.text = "Cancelled, not found."
case .user:
self.textLabel.text = "Cancelled by user."
}
case .invalid(let locale):
self.textLabel.text = "Locale \"\(locale)\" not supported."
case .unknown(let unknownError):
self.textLabel.text = unknownError?.localizedDescription
default:
self.textLabel.text = error.localizedDescription
}
}
//Sets the locate button to the view
locateButton = UIButton(frame: CGRect(x: self.view.frame.width / 2 - 100, y: self.view.frame.height / 2 + 300, width: 200, height: 30))
locateButton.backgroundColor = .black
locateButton.setTitleColor(.white, for: .normal)
locateButton.setTitle("Locate the object.", for: .normal)
locateButton.titleLabel?.font = UIFont(name: "GTWalsheimProTrial-Medium", size: 20)
locateButton.isHidden = true
self.view.addSubview(locateButton)
locateButton.addTarget(self, action: #selector(self.buttonTapped), for: .touchUpInside)
//Sets the text label to the view
textLabel = UILabel(frame: CGRect(x: self.view.frame.width/2 , y: self.view.frame.height / 2 - 200, width: 300, height: 31))
textLabel.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)
textLabel.textAlignment = .center
textLabel.text = ""
textLabel.font = UIFont(name: "GTWalsheimProTrial-Medium", size: 30)
self.view.addSubview(textLabel)
lm = CLLocationManager()
lm.delegate = self
//Adds the progress label and record button to the view directly
recordButton = RecordButton(frame: CGRect(x: self.view.frame.width / 2 - 100,y: self.view.frame.height / 2 - 100,width: 200,height: 200))
view.addSubview(recordButton)
progressLabel = UILabel(frame: CGRect(x: self.view.frame.width/2 , y: self.view.frame.height / 2 - 200, width: 300, height: 31))
progressLabel.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2 + 200)
progressLabel.textAlignment = .center
progressLabel.text = "0/3 rounds completed"
progressLabel.font = UIFont(name: "GTWalsheimProTrial-Medium", size: 30)
self.view.addSubview(progressLabel)
recordButton.addTarget(self, action: #selector(self.record), for: .touchDown)
recordButton.addTarget(self, action: #selector(self.stop), for: UIControl.Event.touchUpInside)
}
//Starts an animation when the button is tapped to create a blur and show the visual effect view
@objc func buttonTapped()
{
var up_50_px = CGAffineTransform(translationX: 0, y: 300)
visualEffectView.isUserInteractionEnabled = false
let blurAnimator = UIViewPropertyAnimator(duration: 1, dampingRatio: 1) {
self.visualEffectView.effect = UIBlurEffect(style: .dark)
}
UIView.animate(withDuration: 0.5, animations: {
self.locateButton.transform = up_50_px
})
blurAnimator.startAnimation()
button.isHidden = false
button.isUserInteractionEnabled = true
}
//Begins recording location
@objc func record() {
lm.startUpdatingHeading()
stop_updated = false
progressLabel.isHidden = false
}
//When the user lets go of the rotation button, it will stop the rotation view
@objc func stop() {
recordButton.setProgress(0)
stop_updated = true
// progressTimer.invalidate
recordButton.buttonState = .idle
var up_50_px = CGAffineTransform(translationX: 0, y: -550)
var down_50_px = CGAffineTransform(translationX: 0, y: 300)
UIView.animate(withDuration: 1, animations: {
self.recordButton.transform = up_50_px
self.progressLabel.transform = down_50_px
})
let blurAnimator = UIViewPropertyAnimator(duration: 1, dampingRatio: 1) {
self.visualEffectView.effect = nil
self.visualEffectView.isUserInteractionEnabled = false
}
blurAnimator.startAnimation()
locateButton.isHidden = false
locateButton.isUserInteractionEnabled = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//Updates progress, algorithm to find the angle traversed and the percent traversed
func updateProgress() {
var angle_traversed = 0
if(currentHeading >= startingHeading){
angle_traversed = Int(currentHeading) - Int(startingHeading) //If the currentHeading is greater than starting, then subtract them
} else {
angle_traversed = 360 - Int(startingHeading) + Int(currentHeading) //If the current is less than the starting then offset it by adding 360
}
progress = CGFloat(angle_traversed)/360.0 //Finds the progress percentage
if(!passed_half && angle_traversed > 180){
passed_half = true
}
if(passed_half){
if(angle_traversed + 10 > 360 && angle_traversed - 10 < 360){
rounds += 1
print("DONE WITH ONE ROUND")
startingHeading = -10
}
}
//Determines round amounts
if(rounds == 1)
{
progressLabel.text = "1/3 rounds completed"
progressLabel.textColor = .yellow
}
else if(rounds == 2)
{
progressLabel.text = "2/3 rounds completed"
progressLabel.textColor = .orange
}
else if(rounds == 3)
{
progressLabel.text = "completed!"
progressLabel.textColor = .green
lm.stopUpdatingHeading()
}
//Sets progress
recordButton.setProgress(progress)
}
//Updates headings whenever the GPS updates the values
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading)
{
if(startingHeading < 0){
startingHeading = newHeading.trueHeading
initHeading = 0
currentHeading = newHeading.trueHeading
} else{
initHeading = currentHeading
currentHeading = newHeading.trueHeading
}
if(!stop_updated){
updateProgress()
}
}
//Starting some functionality before the view starts
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
//configuration.planeDetection = .horizontal
// Run the view's session
sceneView.session.run(configuration)
}
//Clean up for memory purposes after the view has disappeared
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
// MARK: - ARSCNViewDelegate
}
| true
|
b8ea4ef20618db1f7f8382ae5f8777224d241aa0
|
Swift
|
jilong10/SOA-Demo-App
|
/SOA-SimpsonQuotes/Classes/BusinessLogicLayer/Services/KingfisherService.swift
|
UTF-8
| 1,490
| 3.15625
| 3
|
[] |
no_license
|
import UIKit
import Kingfisher
private let kingfisherServiceName = "KingfisherService"
protocol KingfisherService: Service {
func loadImageFrom(urlString: String, success: @escaping (Data) -> (), failure: @escaping (KingfisherError) -> ())
}
extension KingfisherService {
var serviceName: String {
get {
kingfisherServiceName
}
}
func loadImageFrom(urlString: String, success: @escaping (Data) -> (), failure: @escaping (KingfisherError) -> ()) {
guard let url = URL(string: urlString) else {
return
}
ImageDownloader.default.downloadImage(with: url, options: nil, progressBlock: nil) { result in
switch result {
case .success(let value):
print("Data: \(value.originalData)")
success(value.originalData)
case .failure(let error):
print("Error: \(error)")
failure(error)
}
}
}
}
class KingfisherServiceImplementation: KingfisherService {
static func register() {
ServiceRegistry.add(service: LazyService(serviceName: kingfisherServiceName, serviceGetter: { () -> Service in
return KingfisherServiceImplementation()
}))
}
}
extension ServiceRegistryImplementation {
var kingfisherService: KingfisherService {
get {
return serviceWith(name: kingfisherServiceName) as! KingfisherService
}
}
}
| true
|
fff2eb6490d98eb3aaf5f903600963b1610b66e5
|
Swift
|
unawares/IOS-PaintApp
|
/PaintApp/Models/Shape.swift
|
UTF-8
| 923
| 3.203125
| 3
|
[] |
no_license
|
//
// Shape.swift
// PaintApp
//
// Created by Theodore Teddy on 9/28/19.
// Copyright © 2019 Theodore Teddy. All rights reserved.
//
import Foundation
import UIKit
class Shape {
var strokeWidth: CGFloat?
var strokeColor: UIColor?
var fillColor: UIColor?
init(withFillColor fillColor: UIColor?,
withStrokeColor strokeColor: UIColor?,
withStrokeWidth strokeWidth: CGFloat?) {
self.fillColor = fillColor
self.strokeColor = strokeColor
self.strokeWidth = strokeWidth
}
func drawPath(path: UIBezierPath) {
if let wrappedStrokeWidth = strokeWidth, let wrappedStrokeColor = strokeColor {
path.lineWidth = wrappedStrokeWidth
wrappedStrokeColor.setStroke()
path.stroke()
}
if let wrappedFillColor = fillColor {
wrappedFillColor.setFill()
path.fill()
}
}
}
| true
|
420cb9702f3350b305714cc57ce9a60dd16a9f7c
|
Swift
|
adamaszhu/iCombine
|
/iCombine/iCombine/Publishers/Filter/Filter.swift
|
UTF-8
| 3,813
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
//
// Filter.swift
// iCombine
//
// Created by Leon Nguyen on 11/8/21.
//
import RxCocoa
import RxSwift
#if canImport(Combine)
import Combine
#endif
extension Publishers {
/// A publisher that republishes all elements that match a provided closure.
public struct Filter<Upstream> : Publisher where Upstream : Publisher {
public let observable: Any
/// The kind of values published by this publisher.
public typealias Output = Upstream.Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = Upstream.Failure
public init(upstream: Upstream, isIncluded: @escaping (Upstream.Output) -> Bool) {
#if canImport(Combine)
if #available(iOS 14, macOS 10.15, *),
let publisher = upstream.observable as? Combine.AnyPublisher<Upstream.Output, Upstream.Failure> {
observable = Combine.Publishers.Filter(upstream: publisher, isIncluded: isIncluded)
.eraseToAnyPublisher()
return
}
#endif
if let upstreamObservable = upstream.observable as? Observable<Upstream.Output> {
observable = upstreamObservable.filter(isIncluded)
} else {
fatalError("failed to init Filter")
}
}
}
/// A publisher that republishes all elements that match a provided error-throwing closure.
public struct TryFilter<Upstream> : Publisher where Upstream : Publisher {
public let observable: Any
/// The kind of values published by this publisher.
public typealias Output = Upstream.Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = Error
public init(upstream: Upstream, isIncluded: @escaping (Upstream.Output) throws -> Bool) {
#if canImport(Combine)
if #available(iOS 14, macOS 10.15, *),
let publisher = upstream.observable as? Combine.AnyPublisher<Upstream.Output, Upstream.Failure> {
observable = Combine.Publishers.TryFilter(upstream: publisher, isIncluded: isIncluded)
.eraseToAnyPublisher()
return
}
#endif
if let upstreamObservable = upstream.observable as? Observable<Upstream.Output> {
observable = upstreamObservable.filter(isIncluded)
} else {
fatalError("failed to init TryFilter")
}
}
}
}
extension Publisher {
/// Republishes all elements that match a provided closure.
///
/// - Parameter isIncluded: A closure that takes one element and returns a Boolean value indicating whether to republish the element.
/// - Returns: A publisher that republishes all elements that satisfy the closure.
public func filter(_ isIncluded: @escaping (Self.Output) -> Bool) -> Publishers.Filter<Self> {
return Publishers.Filter(upstream: self, isIncluded: isIncluded)
}
/// Republishes all elements that match a provided error-throwing closure.
///
/// If the `isIncluded` closure throws an error, the publisher fails with that error.
///
/// - Parameter isIncluded: A closure that takes one element and returns a Boolean value indicating whether to republish the element.
/// - Returns: A publisher that republishes all elements that satisfy the closure.
public func tryFilter(_ isIncluded: @escaping (Self.Output) throws -> Bool) -> Publishers.TryFilter<Self> {
return Publishers.TryFilter(upstream: self, isIncluded: isIncluded)
}
}
| true
|
d6f18903f3c17da5f471bbfbdcbc489fd3ee1020
|
Swift
|
Wayssman/FoodDelivery
|
/FoodDelivery/Recipe/Protocols/RecipeProtocols.swift
|
UTF-8
| 774
| 2.640625
| 3
|
[] |
no_license
|
//
// RecipeProtocols.swift
// FoodDelivery
//
// Created by Желанов Александр Валентинович on 28.05.2021.
//
import UIKit
protocol RecipeRouterProtocol: AnyObject {
static func createRecipeModule(forMeal: MealObject) -> UIViewController
// Запрос от Presenter к Router
func dismissRecipeScreen(from view: RecipeViewProtocol)
}
protocol RecipeViewProtocol: AnyObject {
var presenter: RecipePresenterProtocol? { get set }
// Запрос от Presenter к View
func showRecipe(forMeal: MealObject)
}
protocol RecipePresenterProtocol: AnyObject {
var view: RecipeViewProtocol? { get set }
var router: RecipeRouterProtocol? { get set }
var meal: MealObject? { get set }
// Запрос от View к Presenter
func viewDidLoad()
func dismissRecipe()
}
| true
|
b99e9ce2e0b0f715aaacb610fcdb5c462724cf92
|
Swift
|
iSapozhnik/WeatherMiddleLayer
|
/Sources/App/Models/Weather.swift
|
UTF-8
| 1,286
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
//
// Weather.swift
// Run
//
// Created by Ivan Sapozhnik on 02.02.18.
//
import Vapor
import FluentProvider
import HTTP
final class Weather {
let storage = Storage()
var id: Int
var temperature: String
var city: String
struct RequestKeys {
static let id = "id"
static let temperature = "main.temp"
static let city = "name"
}
struct ResponseKeys {
static let id = "id"
static let temperature = "temp"
static let city = "city"
}
init(id: Int, temperature: String, city: String) {
self.id = id
self.temperature = temperature
self.city = city
}
}
extension Weather: JSONConvertible {
convenience init(json: JSON) throws {
self.init(
id: try json.get(Weather.RequestKeys.id),
temperature: try json.get(Weather.RequestKeys.temperature),
city: try json.get(Weather.RequestKeys.city)
)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set(Weather.ResponseKeys.id, id)
try json.set(Weather.ResponseKeys.temperature, temperature)
try json.set(Weather.ResponseKeys.city, city)
return json
}
}
extension Weather: ResponseRepresentable { }
| true
|
435a5115270420ef0143ece9f0a56631c5cd86af
|
Swift
|
ctufaro/KickShow.IOS
|
/KickShow/Utils/ViewRouter.swift
|
UTF-8
| 854
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewRouter.swift
// NavigateInSwiftUIComplete
//
// Created by Andreas Schultz on 19.07.19.
// Copyright © 2019 Andreas Schultz. All rights reserved.
//
import Foundation
import Combine
import SwiftUI
class ViewRouter: ObservableObject {
//@Published var showToolBar : Bool = false{
//didSet{
//print("Show toolbar?: \(showToolBar)")
//}
//}
let objectWillChange = PassthroughSubject<ViewRouter,Never>()
var currentView: String = "home" {
didSet {
withAnimation() {
objectWillChange.send(self)
}
}
}
var showToolBar : Bool = true{
didSet{
withAnimation() {
objectWillChange.send(self)
}
}
}
func toggleView(){
showToolBar = !showToolBar
}
}
| true
|
79e280898cc444c5d6eff7bdd241f8a091eadc0a
|
Swift
|
Constantine1995/RecipePizza
|
/RecipePizza/RecipePizza/Model/HeaderSectionsDetail.swift
|
UTF-8
| 548
| 2.65625
| 3
|
[] |
no_license
|
//
// HeaderSectionsDetail.swift
// RecipePizza
//
// Created by mac on 3/17/19.
// Copyright © 2019 mac. All rights reserved.
//
import Foundation
struct HeaderSectionsDetail {
var title: String!
static func fetchSections() -> [HeaderSectionsDetail] {
let firstSetion = HeaderSectionsDetail(title: "Необходимые ингредиенты")
let secondSection = HeaderSectionsDetail(title: "Направления \nПодготовка")
return [firstSetion, secondSection]
}
}
| true
|
25f7665db39ea1b41215eb41d4ee9188cb99a231
|
Swift
|
voxqhuy/iOS-MediumApps
|
/Pictogram/Pictogram/New Group/ImageStore.swift
|
UTF-8
| 2,335
| 3.46875
| 3
|
[] |
no_license
|
//
// ImageStore.swift
// Pictogram
//
// Created by Vo Huy on 5/28/18.
// Copyright © 2018 Vo Huy. All rights reserved.
//
import UIKit
class ImageStore {
// MARK: Properties
// a cache (like a dictionary) keeps keys and values. It is a temporary
// store. It removes objects if the system gets low on memory.
let cache = NSCache<NSString, UIImage>()
// MARK: Methods
// URL for writing and reading in the "Documents" directories of the OS
func imageURL(forKey key: String) -> URL {
// userDomainMask = The user's home directory, place for personal items
let documentsDirectories = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = documentsDirectories.first!
return documentDirectory.appendingPathComponent(key)
}
}
// manage Images (caching)
extension ImageStore {
func setImage(_ image: UIImage, forKey key: String) {
// Create URL for the image
let url = imageURL(forKey: key)
// Turn an image into JPEG
if let data = UIImageJPEGRepresentation(image, 0.5) {
// Write it to full URL
let _ = try? data.write(to: url, options: [.atomic])
// "wirte is not archiving, its copying the bytes in the Data directly to the filesystem
}
cache.setObject(image, forKey: key as NSString)
}
func getImage(forKey key: String) -> UIImage? {
// check the cache
if let existingImage = cache.object(forKey: key as NSString) {
return existingImage
}
// load from the filesystem
let url = imageURL(forKey: key)
guard let imageFromDisk = UIImage(contentsOfFile: url.path) else {
return nil
}
cache.setObject(imageFromDisk, forKey: key as NSString)
return imageFromDisk
}
func deleteImage(forKey key: String) {
cache.removeObject(forKey: key as NSString)
// also delete from the file system
let url = imageURL(forKey: key)
do {
try FileManager.default.removeItem(at: url)
} catch let deleteError {
print("Error removing the image from disk: \(deleteError)")
}
}
}
| true
|
9155173617c70ad721444e657dfa68449be0c2a9
|
Swift
|
thanhphong-tran/TwitSplit
|
/TwitSplit/TwitSplitter.swift
|
UTF-8
| 2,121
| 3.140625
| 3
|
[] |
no_license
|
//
// TwitSplitter.swift
// TwitSplit
//
// Created by ThanhPhong-Tran on 6/24/18.
// Copyright © 2018 ECDC. All rights reserved.
//
import Foundation
public enum TwitSplittingError: Error {
case charactersExceedLimit
public var localizedDescription: String {
switch self {
case .charactersExceedLimit:
return "The message contains a span of non-whitespace characters longer than 50 characters."
}
}
}
public class TwitSplitter {
private static let CHARACTER_LIMIT: Int = 50
public func splitMessage(_ message: String) throws -> [String] {
// Return if message count less than or equal limit
if message.count < TwitSplitter.CHARACTER_LIMIT { return [message] }
let words: [String] = message.components(separatedBy: " ")
var _message: String = ""
var results = [String]()
let maxRow: Int = message.count / TwitSplitter.CHARACTER_LIMIT + (message.count % TwitSplitter.CHARACTER_LIMIT != 0 ? 1 : 0) + 1
let indicatorLength: Int = String(maxRow).count * 2 + 2
for word in words {
let temp = _message + " " + word
if temp.count + indicatorLength > TwitSplitter.CHARACTER_LIMIT {
// If message exceed limit before adding final word
if _message.count + indicatorLength > TwitSplitter.CHARACTER_LIMIT { throw TwitSplittingError.charactersExceedLimit }
results.append(_message)
_message = " " + word
} else {
_message += " " + word
}
}
// Check final message before adding it
if _message.count + indicatorLength > TwitSplitter.CHARACTER_LIMIT { throw TwitSplittingError.charactersExceedLimit }
results.append(_message)
let n = results.count
let format: String = "%0\(String(maxRow).count)d/\(n)%@"
for i in 0..<n { results[i] = String.init(format: format, i+1, results[i]) }
return results
}
}
| true
|
9d62b9da54c315464d2db621679f7f295eae759b
|
Swift
|
goodpizzaman/treeoftheusa
|
/TheRepublic/Executive (President)/executive.swift
|
UTF-8
| 5,838
| 2.515625
| 3
|
[] |
no_license
|
//
// executive.swift
// Tree of the USA
//
// Created by x on 09/01/18.
// Copyright © 2018 x. All rights reserved.
//
import UIKit
import Alamofire
import DeviceKit
class executive: UIViewController {
//---Executive
//Shows the president with social networks, website, c-span, etc.
var tool = tools()
override func viewDidLoad() {
super.viewDidLoad()
//Setup custom back button
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
let yourBackImage = UIImage(named: "backButton")
self.navigationController?.navigationBar.backIndicatorImage = yourBackImage
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = yourBackImage
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func www(_ sender: Any) {
//Website
print("executive - www")
let urlVC = UIStoryboard(name: self.tool.sbName(), bundle: nil).instantiateViewController(withIdentifier: "urlWebview") as! urlWeb
urlVC.urlPass = "https://www.donaldjtrump.com"
self.navigationController?.pushViewController(urlVC, animated: true)
}
@IBAction func twitter(_ sender: Any) {
//Twitter
print("executive - twitter")
if(UIApplication.shared.canOpenURL(NSURL(string: "twitterrific://")! as URL)){
let url = NSURL(string: "twitterrific://current/profile?screen_name=realDonaldTrump")
//Example: twitterrific://current/profile?screen_name=lil_algo
UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
print("Twitterrific App")
}
else if(UIApplication.shared.canOpenURL(NSURL(string: "tweetbot://")! as URL)){
let url = NSURL(string: "tweetbot://realDonaldTrump/user_profile/realDonaldTrump")
//Example: tweetbot://lil_algo/user_profile/lil_algo
UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
print("Tweetbot App")
}
else if (UIApplication.shared.canOpenURL(NSURL(string: "twitter:///")! as URL)){
let url = NSURL(string: "twitter:///user?screen_name=realDonaldTrump")
//Example: twitter:///user?screen_name=lil_algo
UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
print("Twitter App")
}
else{
let urlVC = UIStoryboard(name: self.tool.sbName(), bundle: nil).instantiateViewController(withIdentifier: "urlWebview") as! urlWeb
urlVC.urlPass = "https://twitter.com/realDonaldTrump"
self.navigationController?.pushViewController(urlVC, animated: true)
}
}
@IBAction func facebook(_ sender: Any) {
//Facebook
print("executive - facebook")
if (UIApplication.shared.canOpenURL(NSURL(string: "fb://")! as URL)){
let url = NSURL(string: "fb://profile/1220332944702810")
//Example: fb://profile/130323453724097
UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
print("Facebook App")
}
else{
let urlVC = UIStoryboard(name: self.tool.sbName(), bundle: nil).instantiateViewController(withIdentifier: "urlWebview") as! urlWeb
urlVC.urlPass = "https://www.facebook.com/DonaldTrump/"
self.navigationController?.pushViewController(urlVC, animated: true)
}
}
@IBAction func opensecret(_ sender: Any) {
//Opensecret
print("executive - opensecret")
let urlVC = UIStoryboard(name: self.tool.sbName(), bundle: nil).instantiateViewController(withIdentifier: "urlWebview") as! urlWeb
urlVC.urlPass = "https://www.opensecrets.org/pres16/candidate.php?id=N00023864"
self.navigationController?.pushViewController(urlVC, animated: true)
}
@IBAction func votesmart(_ sender: Any) {
//Votesmart
print("executive - votesmart")
let urlVC = UIStoryboard(name: self.tool.sbName(), bundle: nil).instantiateViewController(withIdentifier: "urlWebview") as! urlWeb
urlVC.urlPass = "https://votesmart.org/candidate/biography/15723/donald-trump"
self.navigationController?.pushViewController(urlVC, animated: true)
}
@IBAction func cspan(_ sender: Any) {
//C-SPAN
print("executive - cspan")
let urlVC = UIStoryboard(name: self.tool.sbName(), bundle: nil).instantiateViewController(withIdentifier: "urlWebview") as! urlWeb
urlVC.urlPass = "https://www.c-span.org/person/?donaldtrump"
self.navigationController?.pushViewController(urlVC, animated: true)
}
@IBAction func executive(_ sender: Any) {
//Executive Orders
print("executive - executive orders")
let vc = UIStoryboard(name: self.tool.sbName(), bundle: nil).instantiateViewController(withIdentifier: "executiveOrderTable") as! executiveOrders
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func signedLegislation(_ sender: Any) {
//Signed legislation
print("executive - signedLegislation")
let vc = UIStoryboard(name: self.tool.sbName(), bundle: nil).instantiateViewController(withIdentifier: "signedLegislationTable") as! signedLegislations
self.navigationController?.pushViewController(vc, animated: true)
}
}
| true
|
32d1b102481d9f6b4fd85d8d23f2de63e4c4f025
|
Swift
|
stevencurtis/SwiftCoding
|
/EfficientShadows/EfficientShadows/ShadowViewWithPath.swift
|
UTF-8
| 784
| 2.75
| 3
|
[] |
no_license
|
//
// ShadowViewWithPath.swift
// EfficientShadows
//
// Created by Steven Curtis on 30/11/2020.
//
import UIKit
class ShadowViewWithPath: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupColor()
}
override func layoutSubviews() {
super.layoutSubviews()
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shadowRadius = 8
layer.shadowOffset = CGSize(width: 3, height: 3)
layer.shadowOpacity = 0.5
layer.cornerRadius = 15
}
func setupColor() {
self.backgroundColor = .systemBlue
self.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupColor()
}
}
| true
|
36c3fb2de33f1297a974044863603a0894790792
|
Swift
|
chelsichristmas/Pursuit-Projects
|
/Unit-3/Practice/Podcasts-Review/Network Services/PodcastAPIClient.swift
|
UTF-8
| 2,508
| 2.75
| 3
|
[] |
no_license
|
//
// PodcastAPIClient.swift
// Podcasts-Review
//
// Created by Chelsi Christmas on 12/18/19.
// Copyright © 2019 Chelsi Christmas. All rights reserved.
//
import Foundation
struct PodcastAPIClient {
static func getPodcasts(for searchQuery: String, completion: @escaping (Result<[PodcastInfo], AppError>) -> ()) {
let searchQuery = searchQuery.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? "love"
let podcastEndpointURLString = "https://itunes.apple.com/search?media=podcast&limit=200&term=\(searchQuery)"
guard let url = URL(string: podcastEndpointURLString) else {
completion(.failure(.badURL(podcastEndpointURLString)))
return
}
let request = URLRequest(url: url)
NetworkHelper.shared.performDataTask(with: request) { (result) in
switch result {
case .failure(let appError):
completion(.failure(.networkClientError(appError)))
case .success(let data):
do {
let searchResults = try JSONDecoder().decode(Podcast.self, from: data)
let podcasts = searchResults.results
completion(.success(podcasts))
} catch {
completion(.failure(.decodingError(error)))
}
}
}
}
static func postFavorite(favoritePodcast: Podcast,completion: @escaping (Result<Bool,AppError>) ->()) {
let favoritePodcastEndPoint = "https://5c2e2a592fffe80014bd6904.mockapi.io/api/v1/favorites"
guard let url = URL(string: favoritePodcastEndPoint) else {
return
}
do {
let data = try JSONEncoder().encode(favoritePodcast)
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = data
request.httpMethod = "POST"
NetworkHelper.shared.performDataTask(with: request) { (result) in
switch result {
case .failure(let appError):
completion(.failure(.networkClientError(appError)))
case .success:
completion(.success(true))
}
}
} catch {
completion(.failure(.encodingError(error)))
}
}
}
| true
|
38b9df83adab2fd65536cb4b36c81d5b3efbb442
|
Swift
|
s1022577/GuessNumber
|
/gm/ViewController.swift
|
UTF-8
| 4,316
| 2.71875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// gm
//
// Created by Joanna on 2014/12/10.
// Copyright (c) 2014年 ClassroomM. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var one: UIButton!
@IBOutlet weak var two: UIButton!
@IBOutlet weak var three: UIButton!
@IBOutlet weak var four: UIButton!
@IBOutlet weak var five: UIButton!
@IBOutlet weak var six: UIButton!
@IBOutlet weak var seven: UIButton!
@IBOutlet weak var eight: UIButton!
@IBOutlet weak var nine: UIButton!
@IBOutlet weak var zero: UIButton!
@IBOutlet weak var aOutput: UILabel!
@IBOutlet weak var bOutput: UILabel!
@IBOutlet weak var record: UIButton!
@IBOutlet weak var restart: UIButton!
@IBOutlet weak var result: UILabel!
@IBOutlet weak var answer: UILabel!
var tempStr = ""
var ans = [Int]()
var ansPrint = [0, 0, 0, 0]
var userInput = [Int]()
var count = 0
var a = 0
var b = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setUp()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func restart(sender: AnyObject) {
self.setUp()
}
@IBAction func oneTouch(sender: AnyObject) {
one.enabled = false
detect("1")
}
@IBAction func twoTouch(sender: AnyObject) {
two.enabled = false
detect("2")
}
@IBAction func threeTouch(sender: AnyObject) {
three.enabled = false
detect("3")
}
@IBAction func fourTouch(sender: AnyObject) {
four.enabled = false
detect("4")
}
@IBAction func fiveTouch(sender: AnyObject) {
five.enabled = false
detect("5")
}
@IBAction func sixTouch(sender: AnyObject) {
six.enabled = false
detect("6")
}
@IBAction func sevenTouch(sender: AnyObject) {
seven.enabled = false
detect("7")
}
@IBAction func eightTouch(sender: AnyObject) {
eight.enabled = false
detect("8")
}
@IBAction func nineTouch(sender: AnyObject) {
nine.enabled = false
detect("9")
}
@IBAction func zeroTouch(sender: AnyObject) {
zero.enabled = false
detect("0")
}
func detect(touchWatch: String){
if count < 4 {
count++
tempStr += touchWatch
result.text = tempStr
}
if count == 4 {
//userAns = Array(tempStr)
for c in tempStr {
userInput.append(String(c).toInt()!)
}
for i in 0...3 {
for j in 0...3 {
if ans[i] == userInput[j] {
if i == j {
println("a++")
a++
}
b++
println("b++")
}
}
}
b = b-a
aOutput.text = String(a)
bOutput.text = String(b)
self.reset()
println(userInput)
}
}
func setUp() {
for i in 0...9 {
println("break point 1")
ans.append(i)
}
for i in 0...9 {
println("break point 2")
let random = Int(arc4random_uniform(UInt32(10)))
var tepm = ans[random]
ans[random] = ans[i]
ans[i] = tepm
}
for d in 0...3 {
println("break point 3")
ansPrint[d] = ans[d]
println(ansPrint[d])
}
answer.text = "\(ansPrint)"
}
func reset() {
one.enabled = true
two.enabled = true
three.enabled = true
four.enabled = true
five.enabled = true
six.enabled = true
seven.enabled = true
eight.enabled = true
nine.enabled = true
zero.enabled = true
count = 0
tempStr = ""
a = 0
b = 0
userInput.removeAll(keepCapacity: false)
}
}
| true
|
a34677dd14787038722d7a078166ec2804455132
|
Swift
|
Cart00nHero/Enrollment_iOS
|
/iOS/Stage/Scene/iOSQRCodeView.swift
|
UTF-8
| 2,978
| 2.609375
| 3
|
[] |
no_license
|
//
// iOSQRCodeView.swift
// Enrollment (iOS)
//
// Created by YuCheng on 2021/5/27.
//
import SwiftUI
fileprivate let scenario: QRCodeScenario = QRCodeScenario()
struct iOSQRCodeView: View {
@State private var presentPhotoLibrary = false
@State private var selectedImage: UIImage = UIImage()
@State private var qrMessage = localized("wait_for_qrcode")
@State private var copyText: String = "Copy"
var body: some View {
VStack {
Image(uiImage: selectedImage)
.resizable().scaledToFit()
Divider()
chooseView()
}.navigationBarHidden(true)
.onAppear() {
scenario.beSubscribeRedux { newState in
}
if SingletonStorage.shared.currentRole == "Visitor" {
scenario.beSubscribeQRCode { image in
selectedImage = image
qrMessage = "\(localized("scanning"))..."
scenario.beScanQrCode(image: selectedImage) { qrMsgs in
qrMessage =
qrMsgs.first ?? localized("\(localized("empty_qrcode_message"))!!!")
}
}
}
}
.sheet(isPresented: $presentPhotoLibrary) {
SwiftUIPhotoPicker(
sourceType: .photoLibrary, selectedImage: $selectedImage)
}
.onDisappear() {
scenario.beUnSubscribe()
}
}
private func chooseView() -> AnyView {
let role = SingletonStorage.shared.currentRole
if role == "Visitor" {
return AnyView(
HStack {
Spacer().frame(width: autoUISize(10.0))
Text(qrMessage).foregroundColor(golden(1.0))
Spacer()
Button {
if qrMessage != localized("wait_for_qrcode") {
UIPasteboard.general.string = qrMessage
copyText = "Copied"
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
// Code you want to be delayed
copyText = "Copy"
}
}
} label: {
Text(copyText)
.foregroundColor(flameScarlet(1.0))
.font(.system(size: autoFont(value: 16.0)))
}
Spacer().frame(width: autoUISize(10.0))
}
)
}
return AnyView(
Button {
presentPhotoLibrary = true
} label: {
Text(localized("select_qrcode_image"))
.foregroundColor(flameScarlet(1.0))
}
)
}
}
struct iOSQRCodeView_Previews: PreviewProvider {
static var previews: some View {
iOSQRCodeView()
}
}
| true
|
2545cf099918079eec239786da066c5e1b1b5a6c
|
Swift
|
LipliStyle/Liplis-iOS
|
/Liplis/CtvCellWidgetCtrlRescueWIdget.swift
|
UTF-8
| 3,629
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// CtvCellWidgetCtrlRescueWIdget.swift
// Liplis
//
//ウィジェット操作 要素 ウィジェット全復帰
//
//アップデート履歴
// 2015/05/07 ver0.1.0 作成
// 2015/05/09 ver1.0.0 リリース
// 2015/05/16 ver1.4.0 リファクタリング
//
// Created by sachin on 2015/05/07.
// Copyright (c) 2015年 sachin. All rights reserved.
//
import UIKit
class CtvCellWidgetCtrlRescueWIdget : UITableViewCell
{
///=============================
///カスタムセル要素
internal var parView : ViewWidgetCtrl!
///=============================
///カスタムセル要素
internal var lblTitle = UILabel();
internal var btnHelp = UIButton();
///=============================
///レイアウト情報
internal var viewWidth : CGFloat! = 0
//============================================================
//
//初期化処理
//
//============================================================
internal override init(style: UITableViewCellStyle, reuseIdentifier: String!)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.lblTitle = UILabel(frame: CGRectMake(10, 23, 300, 15));
self.lblTitle.text = "全てのウィジェットを画面内に呼び戻します。";
self.lblTitle.font = UIFont.systemFontOfSize(15)
self.lblTitle.numberOfLines = 2
self.addSubview(self.lblTitle);
//ボタン
self.btnHelp = UIButton()
self.btnHelp.titleLabel?.font = UIFont.systemFontOfSize(16)
self.btnHelp.frame = CGRectMake(0,5,40,48)
self.btnHelp.layer.masksToBounds = true
self.btnHelp.setTitle("実行", forState: UIControlState.Normal)
self.btnHelp.addTarget(self, action: "onClick:", forControlEvents: .TouchDown)
self.btnHelp.layer.cornerRadius = 3.0
self.btnHelp.backgroundColor = UIColor.hexStr("DF7401", alpha: 255)
self.addSubview(self.btnHelp)
}
/*
ビューを設定する
*/
internal func setView(parView : ViewWidgetCtrl)
{
self.parView = parView
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
/*
要素の位置を調整する
*/
internal func setSize(viewWidth : CGFloat)
{
self.viewWidth = viewWidth
let locationX : CGFloat = CGFloat(viewWidth - viewWidth/4 - 5)
self.btnHelp.frame = CGRectMake(locationX, 5,viewWidth/4,60)
self.lblTitle.frame = CGRectMake(10, 5,viewWidth * 3/4 - 20,50)
}
//============================================================
//
//イベントハンドラ
//
//============================================================
/*
スイッチ選択
*/
internal func onClick(sender: UIButton) {
let myAlert: UIAlertController = UIAlertController(title: "ウィジェット復帰", message: "全てのウィジェットを画面上に復帰させますか?", preferredStyle: .Alert)
let myOkAction = UIAlertAction(title: "実行", style: .Default) { action in
self.parView.app.activityDeskTop.rescueWidgetAll()
print("実行しました。")
}
let myCancelAction = UIAlertAction(title: "キャンセル", style: .Default) { action in
print("中止しました。")
}
myAlert.addAction(myOkAction)
myAlert.addAction(myCancelAction)
self.parView.presentViewController(myAlert, animated: true, completion: nil)
}
}
| true
|
5d3cfd3416f479d026587802157f352aea738b8d
|
Swift
|
nelyflores/ECC-Laboratoria
|
/Week2/ProblemSet/RPS/RPS/ViewController.swift
|
UTF-8
| 1,200
| 2.90625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// RPS
//
// Created by Apple Device 7 on 10/5/19.
// Copyright © 2019 NelyFlores. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var IconResult: UILabel!
@IBOutlet weak var LabeTitle: UILabel!
@IBAction func scissorbutton(_ sender: UIButton) {
}
@IBAction func paperbutton(_ sender: UIButton) {
}
@IBAction func rockbutton(_ sender: UIButton) {
let computerSign = randomSign()
print(computerSign.emojis)
let rock = Sign.Piedra
let result = rock.giveMeResults(computerSign)
print("El resultado es \(result)")
determeneAppState(result: result)
}
func determeneAppState( result: Gamestate){
switch result {
case .Win:
view.backgroundColor = .green
case .Lose:
view.backgroundColor = .red
default:
view.backgroundColor = .yellow
}
}
@IBAction func playagain(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| true
|
a66f0e23e1a6fcc069f2ea0d08181123d30e9d29
|
Swift
|
MaksymHavrosh/VK
|
/HomeProjectSwift 31/Controllers/UserViewController.swift
|
UTF-8
| 1,925
| 2.796875
| 3
|
[] |
no_license
|
//
// UserViewController.swift
// HomeProjectSwift 31
//
// Created by MG on 18.03.2020.
// Copyright © 2020 MG. All rights reserved.
//
import UIKit
class UserViewController: UIViewController {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var fullNameLabel: UILabel!
var userId: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
getUserFromServer()
}
func getUserFromServer() {
ServerManager.manager.getUserWithID(userID: userId,
success: { (user: User) in
if let url = user.bigImageURL {
self.avatarImageView.af.setImage(withURL: url)
}
self.fullNameLabel.text = "\(user.firstName) \(user.lastName)"
}) { (error: Error) in
print("Error = \(error)")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination.isKind(of: SubscriptionsTableViewController.self),
let userController = segue.destination as? SubscriptionsTableViewController {
userController.userID = userId
}
if segue.destination.isKind(of: FollowersTableViewController.self),
let userController = segue.destination as? FollowersTableViewController {
userController.userID = userId
}
if segue.destination.isKind(of: WallTableViewController.self),
let userController = segue.destination as? WallTableViewController {
userController.userID = userId
}
}
}
| true
|
ae12b8cca5ae8cf1bed80e328abb7a33eb1aee54
|
Swift
|
applicaster/ZappPlugins.2.0-iOS
|
/ZappPlugins/Components/LayoutComponents/Protocols/ZLComponentBuilder/ZLComponentBuilderProtocol.swift
|
UTF-8
| 3,280
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ZLComponentBuilderProtocol.swift
// ZappPlugins
//
// Created by Anton Kononenko on 15/11/2016.
// Copyright © 2016 Anton Kononenko. All rights reserved.
//
import Foundation
/// This struct representation for request component to search styles in another components
public struct ZLZappLayoutDependantComponentStyles {
public init(componentType:ZLComponentTypeProtocol, containerCell:Bool) {
self.componentType = componentType
self.containerCell = containerCell
}
/// Type of component that will be used as dependant
public let componentType:ZLComponentTypeProtocol
/// Explain to search if dependent component need to be searched in containerCell
public let containerCell:Bool
}
public protocol ZLComponentBuilderProtocol {
static func componentSkeletonForContainerCellLayout(_ zappParentLayoutName:String?,
baseModel:ZLComponentModel?,
zappParentComponentType:String?,
zappParentFamily:String?,
uniqueDataSourceIdentifier:String?,
actions: [String: Any]?,
uiTag:String?,
parentСomponentModel:CAComponentModelProtocol?) -> CAComponentModelProtocol?
static func dictionaryForSkeletonComponent(_ zappLayoutName:String?,
zappComponentType:String?,
zappFamily: String?,
uniqueDataSourceIdentifier:String?,
actions: [String: Any]?,
uiTag:String?,
dependentStyles:[ZLZappLayoutDependantComponentStyles]?) -> [String: Any]?
static func dictionaryForSkeletonContainerCellComponent(_ zappParentLayoutName:String?,
zappParentComponentType:String?,
zappParentFamily: String?,
uniqueDataSourceIdentifier:String?,
actions: [String: Any]?,
uiTag:String?) -> [String: Any]?
static func componentFromDictionary(_ dictionary: [String: Any]?,
baseModel:ZLComponentModel?,
parentСomponentModel:CAComponentModelProtocol?) -> CAComponentModelProtocol?
static func createHeaderComponent(_ model:ZLComponentModel,
uniqueDataSourceIdentifier: String,
parentСomponentModel:CAComponentModelProtocol?) -> CAComponentModelProtocol?
static func addDataSourceToComponentModel(_ componentModel: CAComponentModelProtocol,
dataSource:ZLDataSource)
}
| true
|
1a5a959edf9dd64c6f86886fdcc24e0480f9fbe8
|
Swift
|
microsoft/fluentui-apple
|
/ios/FluentUI/Core/Theme/Tokens/EmptyTokenSet.swift
|
UTF-8
| 664
| 2.78125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
/// An empty `ControlTokenSet` for components that want to use some of the perks
/// of being tokenized, but are not fully at that stage yet.
public class EmptyTokenSet: ControlTokenSet<EmptyTokenSet.Tokens> {
/// The set of tokens associated with this `EmptyTokenSet`.
public enum Tokens: TokenSetKey {
/// A default token, which only exists because Swift requires at least one value in this enum.
case none
}
init() {
super.init { _, _ in
preconditionFailure("Should not fetch values")
}
}
}
| true
|
33d56e9cdb033152c07ca8036f089068571c2a3b
|
Swift
|
dmatushkin/CommonError
|
/Sources/CommonError/CommonError.swift
|
UTF-8
| 1,524
| 2.546875
| 3
|
[] |
no_license
|
import Foundation
import SwiftyBeaver
import CloudKit
public class CommonError: LocalizedError {
private let description: String
public init(description: String) {
self.description = description
}
public var errorDescription: String? {
return self.description
}
public class func logDebug(_ text: String, file: String = #file, function: String = #function, line: Int = #line) {
SwiftyBeaver.debug(text, file, function, line: line)
}
public static func logError(_ text: String, file: String = #file, function: String = #function, line: Int = #line) {
SwiftyBeaver.error(text, file, function, line: line)
}
}
public extension Error {
func log(file: String = #file, line: Int = #line, function: String = #function) {
if let ckError = self as? CKError {
let serverRecord = String(describing: ckError.serverRecord)
let clientRecord = String(describing: ckError.clientRecord)
let ancestorRecord = String(describing: ckError.ancestorRecord)
let partialErrors = String(describing: ckError.partialErrorsByItemID)
let additionalDescription = "Error code \(ckError.code.rawValue), serverRecord \(serverRecord), clientRecord \(clientRecord), ancestorRecord \(ancestorRecord), partialErrors \(partialErrors)\n"
CommonError.logError(self.localizedDescription + "\nAdditional: " + additionalDescription, file: file, function: function, line: line)
} else {
CommonError.logError(self.localizedDescription, file: file, function: function, line: line)
}
}
}
| true
|
f44a6a62e659c9bf4d9f60571edd0cdff04b19c3
|
Swift
|
indragiek/AttributedString.swift
|
/AttributedStringTests/AttributedStringTests.swift
|
UTF-8
| 10,826
| 3.0625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// AttributedStringTests.swift
// AttributedStringTests
//
// Created by Indragie Karunaratne on 2/18/19.
// Copyright © 2019 Indragie Karunaratne. All rights reserved.
//
import XCTest
@testable import AttributedString
#if os(macOS)
import AppKit
#else
import UIKit
#endif
class AttributedStringTests: XCTestCase {
func testNSAttributedStringConcatenation() {
let str1 = NSAttributedString(string: "Hello")
let str2 = NSAttributedString(string: " World")
let concatenated = str1 + str2
XCTAssertEqual(NSAttributedString(string: "Hello World"), concatenated)
XCTAssertFalse(concatenated === str1)
XCTAssertFalse(concatenated === str2)
}
func testAttributedStringConcatenation() {
let str1: AttributedString = "Hello"
let str2: AttributedString = " World"
let concatenated = str1 + str2
XCTAssertEqual("Hello World", concatenated)
}
func testAttributedStringEquality() {
let str1: AttributedString = "Hello"
XCTAssertEqual("Hello", str1)
XCTAssertNotEqual("World", str1)
}
func testApplyingStyleAttributesToEntireRangeOfNSMutableAttributedString() {
let attrString = NSMutableAttributedString(string: "Hello World")
attrString.style(withAttributes: [.color(.red), .underlineColor(.white)])
var range = NSRange(location: 0, length: 0)
let attributes = attrString.attributes(at: 0, effectiveRange: &range)
XCTAssertEqual(AttributedString.Color.red, attributes[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(AttributedString.Color.white, attributes[.underlineColor] as! AttributedString.Color)
XCTAssertEqual(NSRange(location: 0, length: attrString.length), range)
}
func testApplyingStyleAttributesToPartialRangeOfNSMutableAttributedString() {
let expectedRange = NSRange(location: 0, length: 5)
let attrString = NSMutableAttributedString(string: "Hello World")
attrString.style(withAttributes: [.color(.red)], range: expectedRange)
var range = NSRange(location: 0, length: 0)
let attributes = attrString.attributes(at: 0, effectiveRange: &range)
XCTAssertEqual(AttributedString.Color.red, attributes[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(expectedRange, range)
}
func testCreateNewNSAttributedStringByApplyingAttributesToEntireRange() {
let attrString = NSMutableAttributedString(string: "Hello World")
let newAttrString = attrString.styled(withAttributes: [.color(.red)])
XCTAssertFalse(attrString === newAttrString)
var range = NSRange(location: 0, length: 0)
let attributes = newAttrString.attributes(at: 0, effectiveRange: &range)
XCTAssertEqual(AttributedString.Color.red, attributes[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(NSRange(location: 0, length: newAttrString.length), range)
}
func testCreateNewNSAttributedStringByApplyingAttributesToPartialRange() {
let expectedRange = NSRange(location: 6, length: 5)
let attrString = NSMutableAttributedString(string: "Hello World")
let newAttrString = attrString.styled(withAttributes: [.color(.red), .underlineColor(.white)], range: expectedRange)
XCTAssertFalse(attrString === newAttrString)
var range = NSRange(location: 0, length: 0)
let attributes = newAttrString.attributes(at: 6, effectiveRange: &range)
XCTAssertEqual(AttributedString.Color.red, attributes[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(AttributedString.Color.white, attributes[.underlineColor] as! AttributedString.Color)
XCTAssertEqual(expectedRange, range)
}
func testApplyingStyleAttributesToEntireRangeOfAttributedString() {
var attrString: AttributedString = "Hello World"
attrString.style(withAttributes: [.color(.red), .underlineColor(.white)])
var range = NSRange(location: 0, length: 0)
let attributes = attrString.nsAttributedString.attributes(at: 0, effectiveRange: &range)
XCTAssertEqual(AttributedString.Color.red, attributes[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(AttributedString.Color.white, attributes[.underlineColor] as! AttributedString.Color)
XCTAssertEqual(NSRange(location: 0, length: attrString.nsAttributedString.length), range)
}
func testApplyingStyleAttributesToPartialRangeOfAttributedString() {
var attrString: AttributedString = "Hello World"
attrString.style(withAttributes: [.color(.red)], range: attrString.string.startIndex..<attrString.string.index(attrString.string.startIndex, offsetBy: 2))
var range = NSRange(location: 0, length: 0)
let attributes = attrString.nsAttributedString.attributes(at: 0, effectiveRange: &range)
XCTAssertEqual(AttributedString.Color.red, attributes[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(NSRange(location: 0, length: 2), range)
}
func testCreateNewAttributedStringByApplyingAttributesToEntireRange() {
let attrString: AttributedString = "Hello World"
let newAttrString = attrString.styled(withAttributes: [.color(.red)])
var range = NSRange(location: 0, length: 0)
let attributes = newAttrString.nsAttributedString.attributes(at: 0, effectiveRange: &range)
XCTAssertEqual(AttributedString.Color.red, attributes[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(NSRange(location: 0, length: newAttrString.nsAttributedString.length), range)
}
func testCreateNewAttributedStringByApplyingAttributesToPartialRange() {
let attrString: AttributedString = "Hello World"
let newAttrString = attrString.styled(withAttributes: [.color(.red), .underlineColor(.white)], range: attrString.string.index(attrString.string.startIndex, offsetBy: 3)..<attrString.string.index(attrString.string.startIndex, offsetBy: 6))
var range = NSRange(location: 0, length: 0)
let attributes = newAttrString.nsAttributedString.attributes(at: 3, effectiveRange: &range)
XCTAssertEqual(AttributedString.Color.red, attributes[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(AttributedString.Color.white, attributes[.underlineColor] as! AttributedString.Color)
XCTAssertEqual(NSRange(location: 3, length: 3), range)
}
func testStringInterpolationWithForegroundColorAttribute() {
let attrString: AttributedString = "\("Hello", .red) World"
var range = NSRange(location: 0, length: 0)
let attributes = attrString.nsAttributedString.attributes(at: 0, effectiveRange: &range)
XCTAssertEqual(AttributedString.Color.red, attributes[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(NSRange(location: 0, length: 5), range)
}
func testStringInterpolationWithFontAttribute() {
let font = AttributedString.Font.systemFont(ofSize: 10)
let attrString: AttributedString = "\("Hello", font) World"
var range = NSRange(location: 0, length: 0)
let attributes = attrString.nsAttributedString.attributes(at: 0, effectiveRange: &range)
XCTAssertEqual(font, attributes[.font] as! AttributedString.Font)
XCTAssertEqual(NSRange(location: 0, length: 5), range)
}
func testStringInterpolationWithTextAlignmentAttribute() {
let attrString: AttributedString = "\("Hello", .center) World"
var range = NSRange(location: 0, length: 0)
let attributes = attrString.nsAttributedString.attributes(at: 0, effectiveRange: &range)
let paragraphStyle = attributes[.paragraphStyle] as! NSParagraphStyle
XCTAssertEqual(.center, paragraphStyle.alignment)
XCTAssertEqual(NSRange(location: 0, length: 5), range)
}
func testStringInterpolationWithLineBreakModeAttribute() {
let attrString: AttributedString = "\("Hello", .byTruncatingTail) World"
var range = NSRange(location: 0, length: 0)
let attributes = attrString.nsAttributedString.attributes(at: 0, effectiveRange: &range)
let paragraphStyle = attributes[.paragraphStyle] as! NSParagraphStyle
XCTAssertEqual(.byTruncatingTail, paragraphStyle.lineBreakMode)
XCTAssertEqual(NSRange(location: 0, length: 5), range)
}
func testStringInterpolationWithWritingDirectionAttribute() {
let attrString: AttributedString = "\("Hello", .rightToLeft) World"
var range = NSRange(location: 0, length: 0)
let attributes = attrString.nsAttributedString.attributes(at: 0, effectiveRange: &range)
let paragraphStyle = attributes[.paragraphStyle] as! NSParagraphStyle
XCTAssertEqual(.rightToLeft, paragraphStyle.baseWritingDirection)
XCTAssertEqual(NSRange(location: 0, length: 5), range)
}
func testStringInterpolationWithMultipleStyledRanges() {
let attrString: AttributedString = "\("Hello", .color(.red), .underlineColor(.white)) \("World", .color(.blue))"
var range1 = NSRange(location: 0, length: 0)
let attributes1 = attrString.nsAttributedString.attributes(at: 0, effectiveRange: &range1)
XCTAssertEqual(AttributedString.Color.red, attributes1[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(AttributedString.Color.white, attributes1[.underlineColor] as! AttributedString.Color)
XCTAssertEqual(NSRange(location: 0, length: 5), range1)
var range2 = NSRange(location: 0, length: 0)
let attributes2 = attrString.nsAttributedString.attributes(at: 6, effectiveRange: &range2)
XCTAssertEqual(AttributedString.Color.blue, attributes2[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(NSRange(location: 6, length: 5), range2)
}
func testStringInterpolationWithNestedStyledRanges() {
let attrString: AttributedString = "\("Hello \("World", .blue)", .underlineColor(.white))"
var range1 = NSRange(location: 0, length: 0)
let attributes1 = attrString.nsAttributedString.attributes(at: 0, effectiveRange: &range1)
XCTAssertEqual(AttributedString.Color.white, attributes1[.underlineColor] as! AttributedString.Color)
XCTAssertEqual(NSRange(location: 0, length: 6), range1)
var range2 = NSRange(location: 0, length: 0)
let attributes2 = attrString.nsAttributedString.attributes(at: 6, effectiveRange: &range2)
XCTAssertEqual(AttributedString.Color.blue, attributes2[.foregroundColor] as! AttributedString.Color)
XCTAssertEqual(NSRange(location: 6, length: 5), range2)
}
}
| true
|
ef326e58edc88aa6bec8739e6f6f86e8920f9e54
|
Swift
|
jekahy/CardValidator
|
/CardValidator/APIService.swift
|
UTF-8
| 3,098
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
//
// APIService.swift
// CardValidator
//
// Created by Eugene on 19.07.17.
// Copyright © 2017 Eugene. All rights reserved.
//
import Foundation
typealias JSON = [String:Any]
enum Result<T> {
case success(T)
case failure(Error)
}
enum APIError: Error, CustomStringConvertible {
case noData
case JSONSerializationError
case failedToConstructURL
case responseError(String)
var description: String {
switch self {
case .noData: return "No data was received."
case .JSONSerializationError: return "Failed to serialize data."
case .failedToConstructURL: return "Failed to construct URL."
case .responseError(let error): return "Received server error: \(error)"
}
}
}
protocol APIProtocol:class {
var baseURL: URL {get}
func getJSON(path: String, parameters: [String:String], completion:@escaping (Result<JSON>) -> Void)
func getJSON(parameters: [String:String], completion:@escaping (Result<JSON>) -> Void)
}
class APIService: APIProtocol {
struct HTTPMethod {
static let GET = "GET"
static let POST = "POST"
static let DELETE = "DELETE"
}
let baseURL: URL
init(baseURL: URL = APIService.defaultBaseURL) {
self.baseURL = baseURL
}
func getJSON(parameters: [String:String], completion:@escaping (Result<JSON>) -> Void) {
getJSON(path: "", parameters: parameters, completion: completion)
}
func getJSON(path: String, parameters: [String:String], completion:@escaping (Result<JSON>) -> Void) {
let url = baseURL.appendingPathComponent(path)
guard let fullURL = parameters.urlWithQueryParameters(url:url) else {
completion(.failure(APIError.failedToConstructURL))
return
}
let session = URLSession.shared
var request = URLRequest(url: fullURL)
request.httpMethod = HTTPMethod.DELETE
session.dataTask(with: request) { data, _, error in
guard error==nil else {
completion(.failure(error!))
return
}
guard let data = data else {
completion(.failure(APIError.noData))
return
}
guard let serialiizedObj = try? JSONSerialization.jsonObject(with: data, options: []),
let json = serialiizedObj as? JSON else {
completion(.failure(APIError.JSONSerializationError))
return
}
if let error = self.checkJSONForError(json) {
completion(.failure(error))
} else {
completion(.success(json))
}
}.resume()
}
private func checkJSONForError(_ json: JSON) -> APIError? {
if json["error"] != nil, let errorMessage = json["message"] as? String {
return APIError.responseError(errorMessage)
}
return nil
}
}
extension APIService {
static let defaultBaseURL = URL(string: "https://api.bincodes.com/cc/")!
}
| true
|
493ad6290333b5c2f6350a752741022633f80e14
|
Swift
|
robertbtown/BtownToolkit
|
/Example/BtownToolkit/Source/ActionSheet/ActionSheetViewController.swift
|
UTF-8
| 1,559
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// ActionSheetViewController.swift
// BtownToolkit
//
// Created by Robert Magnusson on 2017-08-09.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import BtownToolkit
class ActionSheetViewController: UIViewController, BTWLocalize {
@IBOutlet var actionSheetBarButtonItem: UIBarButtonItem!
@IBOutlet var actionSheetButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Localized title string
title = btwTypeString("Title")
}
@IBAction func showActionSheetFromButton() {
let actionSheet = createActionSheet()
actionSheet.presentFromView = self.actionSheetButton
actionSheet.show()
}
@IBAction func showActionSheetFromBarButtonItem() {
let actionSheet = createActionSheet()
actionSheet.presentFromBarButtonItem = self.actionSheetBarButtonItem
actionSheet.show()
}
private func createActionSheet() -> ActionSheet {
let actionSheet = ActionSheet(title: "Some title", message: "Some message")
actionSheet.addAction(title: "Main Action", actionType: .normal) {
print("User tapped main action")
}
actionSheet.addAction(title: "Cancel", actionType: .cancel) {
print("User tapped cancel")
}
actionSheet.addAction(title: "Delete", actionType: .destructive) {
print("User tapped delete")
}
actionSheet.wasDismissedClosure = {
print("ActionSheet was dismissed.")
}
return actionSheet
}
}
| true
|
9299656588014e6d918b965dbd9adfbb61efac57
|
Swift
|
Harsh061/PropertyWrappers_SwiftUI
|
/PropertyWrappers/ProductFiles/Screens/HomeScreen/ViewModel/HomeVM.swift
|
UTF-8
| 795
| 2.8125
| 3
|
[] |
no_license
|
//
// HomeVM.swift
// PropertyWrappers
//
// Created by Harshit Parikh on 06/04/21.
//
import Foundation
class HomeVM: ObservableObject {
// MARK:- Properties
@Published var booksArray: [BooksModel] = []
// MARK:- Methods
init() {
self.loadBooksData()
}
private func loadBooksData() {
guard let url = Bundle.main.url(forResource: "BooksData", withExtension: "json") else {
return
}
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let books = try? decoder.decode([BooksModel].self, from: data)
self.booksArray = books ?? []
} catch let error {
print("Error in reading books data: \(error.localizedDescription)")
}
}
}
| true
|
22d1681d5fc284582fea35a58a018733a3453cb4
|
Swift
|
niceoasi/Share-Your-Travel
|
/ShareYourTravel/ShareYourTravel/SimpleTableHeaderView.swift
|
UTF-8
| 684
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// SimpleTableHeaderView.swift
// ShareYourTravel
//
// Created by Daeyun Ethan Kim on 07/09/2017.
// Copyright © 2017 Daeyun Ethan Kim. All rights reserved.
//
import UIKit
class SimpleTableHeaderView: UITableViewHeaderFooterView {
// MARK: Properties
// constant
@IBOutlet weak var headerTitleLabel: UILabel?
// MARK: Outlets
// MARK: Init
func initVars() {}
func initTitleLabel() {
headerTitleLabel?.font = UIFont(name: kDefaultFont, size: 14.0)
headerTitleLabel?.textColor = .darkGray
}
func configureView(title: String) {
headerTitleLabel?.text = title
initTitleLabel()
}
}
| true
|
2783b6521ff7d84180d2d6cbf35c5a128f361e3c
|
Swift
|
billydowning/WildMan
|
/WildMan/Model/Headline.swift
|
UTF-8
| 422
| 2.78125
| 3
|
[] |
no_license
|
//
// Headline.swift
// WildMan
//
// Created by William Downing on 2/14/21.
//
import UIKit
struct Headline {
let headline: String
let answer: String
let choice1: String
let choice2: String
let choice3: String
init(h: String, a: String, c1: String, c2: String, c3: String) {
headline = h
answer = a
choice1 = c1
choice2 = c2
choice3 = c3
}
}
| true
|
d9ce319c95bbdcdece46fbe468ed59f65487f79a
|
Swift
|
badrinrs/Vanilai-ios
|
/Vanilai/EarthquakeController.swift
|
UTF-8
| 2,037
| 2.5625
| 3
|
[] |
no_license
|
//
// EarthquakeController.swift
// Vanilai
//
// Created by Ravichandran Ramachandran on 3/8/17.
// Copyright © 2017 Ravichandran Ramachandran. All rights reserved.
//
import UIKit
import GoogleMobileAds
class EarthquakeController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var earthquakes: [Earthquake]!
@IBOutlet weak var earthquakeTableView: UITableView!
@IBOutlet weak var bannerAd: GADBannerView!
override func viewDidLoad() {
bannerAd.adUnitID = VanilaiConstants.MOBILE_ADS_UNIT_ID
bannerAd.rootViewController = self
bannerAd.load(GADRequest())
self.navigationItem.title = "Earthquakes"
earthquakeTableView.dataSource = self
earthquakeTableView.delegate = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return earthquakes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "earthquakeCell"
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! EarthquakeCell
cell.location.text = earthquakes[indexPath.row].place
cell.magnitude.text = "\(earthquakes[indexPath.row].magnitude)"
if earthquakes[indexPath.row].tsunami == TsunamiEnum.TSUNAMI_WARN {
cell.tsunamiImage.image = #imageLiteral(resourceName: "tsunami").imageWithColor(color: .red)
} else {
cell.tsunamiImage.image = #imageLiteral(resourceName: "earthquake")
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let earthquakeSelected = earthquakes[indexPath.row]
let detailViewController = self.storyboard?.instantiateViewController(withIdentifier: "earthquakeDetailVC") as! EarthquakeDetailController
detailViewController.earthquake = earthquakeSelected
self.navigationController?.pushViewController(detailViewController, animated: true)
}
}
| true
|
394968066d14710fa7584af21d6539dfc7c2d0e5
|
Swift
|
samehmahmoud5515/LadyBug
|
/LadyBug/Modules/product/Products/Presenter/ProductsPresenter.swift
|
UTF-8
| 1,369
| 2.53125
| 3
|
[] |
no_license
|
//
// ProductsPresenter.swift
// LadyBug
//
// Created by Sameh on 2/20/21.
//
import Moya
class ProductsPresenter: ProductsPresenterProtocol {
var localizer = ProductsLocalizer()
var images = ProductsImages()
let productsProvider = MoyaProvider<ProductsEndPoint>(plugins: [AuthorizableTokenPlugin()])
var products = [Product]()
weak var view: ProductsViewProtocol?
init(view: ProductsViewProtocol) {
self.view = view
}
func attach() {
}
func getProductsCount() -> Int {
return 10
}
func getproducts() {
productsProvider.request(.products) { result in
switch result {
case let .success(moyaResponse):
do {
let productsResponse = try? moyaResponse.map(ProductsResponse.self)
guard let products = productsResponse?.data?.all else { return }
self.products = products
print(self.products)
self.view?.reloadData()
self.view?.stopIndicator()
} catch {
print("Parsing Error")
}
case let .failure(error):
self.view?.stopIndicator()
break
}
}
}
}
| true
|
cd7c5373b41b602815fec5a0105888b33f4ab18b
|
Swift
|
cryptobuks1/AltCoin-1
|
/Sources/Altcoin/core/Time.swift
|
UTF-8
| 3,719
| 3.03125
| 3
|
[] |
no_license
|
//
// Time.swift
// altcoin-simulator
//
// Created by Timothy Prepscius on 6/16/19.
//
import Foundation
// this stuff needs to be changed to use an actual calendar object, but I'm lazy for now
public class TimeQuantities
{
public static let Second = 1.0
public static let Minute = 60.0 * Second
public static let Hour = 60.0 * Minute
public static let Day = 24 * Hour
public static let Week = 6 * Day
}
// this stuff needs to be changed to use an actual calendar object, but I'm lazy for now
public class StandardTimeEquations
{
public static let nextMinute : Equation_P1_R1 = { return $0 + TimeQuantities.Minute }
public static let nextHour : Equation_P1_R1 = { return $0 + TimeQuantities.Hour }
public static let nextDay : Equation_P1_R1 = { return $0 + TimeQuantities.Day }
}
// this stuff needs to be changed to use an actual calendar object, but I'm lazy for now
public class StandardTimeRanges
{
public static let relativeNow : Time = 0
public static let oneDay : TimeRange = -TimeQuantities.Day ... relativeNow
public static let oneWeek : TimeRange = -TimeQuantities.Week ... relativeNow
public static let twoWeeks : TimeRange = (2.0 * -TimeQuantities.Week) ... relativeNow
public static let fourWeeks : TimeRange = (4.0 * -TimeQuantities.Week) ... relativeNow
}
public class TimeEvents
{
public static func roundDown (_ t: TimeInterval, range r: TimeInterval) -> TimeInterval
{
return floor(t/r) * r
}
public static func roundUp (_ t: TimeInterval, range r: TimeInterval) -> TimeInterval
{
return ceil(t/r) * r
}
public static func toUnix(_ t: TimeInterval) -> Int64
{
return Int64(Date(timeIntervalSinceReferenceDate: t).timeIntervalSince1970) * 1000
}
public static func toTimeInterval(_ t: Double) -> TimeInterval
{
return Date(timeIntervalSince1970: t/1000.0).timeIntervalSinceReferenceDate
}
public static func toDate(_ isoDate: String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
let date = dateFormatter.date(from:isoDate)!
return date
}
public static func toString(_ time: TimeInterval) -> String
{
return Date(timeIntervalSinceReferenceDate: time).description
}
public static func toString(_ range: TimeRange) -> String
{
return "(\(TimeEvents.toString(range.lowerBound)) ... \(TimeEvents.toString(range.upperBound)))"
}
public static func findTo12am () -> Date
{
let date = Date()
let cal = Calendar(identifier: .gregorian)
let components = cal.dateComponents([.day , .month, .year ], from: date)
let newDate = cal.date(from: components)
return newDate!
}
public static let firstBubbleStart = toDate("2017-03-01T00:00:00+0000").timeIntervalSinceReferenceDate
public static let firstBubbleStartJustAfter = toDate("2017-03-31T00:00:00+0000").timeIntervalSinceReferenceDate
public static let firstBubbleCrash = toDate("2017-12-16T00:00:00+0000").timeIntervalSinceReferenceDate
public static let secondBubbleStart = toDate("2019-02-01T00:00:00+0000").timeIntervalSinceReferenceDate
public static let year2019 = toDate("2019-01-01T00:00:00+0000").timeIntervalSinceReferenceDate
public static let oneMonthAgo = Date().timeIntervalSinceReferenceDate - 4 * TimeQuantities.Week
public static let july1st2019 = toDate("2019-07-01T00:00:00+0000").timeIntervalSinceReferenceDate
public static let august1st2019 = toDate("2019-08-01T00:00:00+0000").timeIntervalSinceReferenceDate
public static let today12am = findTo12am().timeIntervalSinceReferenceDate
public static let now = Date().timeIntervalSinceReferenceDate
public static let safeNow = now - TimeQuantities.Hour
}
| true
|
6ce61b325200df12058261ea2ca501ee43fef85e
|
Swift
|
MauroAlvarenga/iOS-Trivia
|
/Trivia/Services/QuestionsService.swift
|
UTF-8
| 1,710
| 3.140625
| 3
|
[] |
no_license
|
//
// QuestionsService.swift
// Trivia
//
// Created by Mauro Alvarenga on 05/11/2021.
//
import Foundation
import Alamofire
class QuestionsService {
private struct Questions: Codable {
let response_code: Int
let results: [Question]
}
let apiClient = AlamofireAPIClient()
func getQuestion(for category: Int, completion: @escaping (Question) -> Void) {
var questionURL: String
if category == 0 {
questionURL = "https://opentdb.com/api.php?amount=1&type=boolean"
} else {
let stringCategory = String(category)
questionURL = "https://opentdb.com/api.php?amount=1&category=" + stringCategory + "&type=boolean"
}
apiClient.get(url: questionURL) { response in
switch response {
case .success(let data):
do {
if let dataOK = data {
NSLog(dataOK.description)
print(dataOK)
let question = try JSONDecoder().decode(Questions.self, from: dataOK)
completion(question.results[0])
}
} catch {
print(error)
completion(Question(category: "catch error", type: "catch error", difficulty: "catch error", question: "catch error", correct_answer: "catch error", incorrect_answers: [String]()))
}
case .failure(let error):
print(error)
completion(Question(category: "failure", type: "failure", difficulty: "failure", question: "failure", correct_answer: "failure", incorrect_answers: [String]()))
}
}
}
}
| true
|
7d9229aae02ba36305b1fa5540c5e371e84a9cb1
|
Swift
|
paulba71/54321-Breathe
|
/54321 Breathe/ViewController.swift
|
UTF-8
| 716
| 2.75
| 3
|
[] |
no_license
|
//
// ViewController.swift
// 54321 Breathe
//
// Created by Paul Barnes on 16/07/2020.
// Copyright © 2020 Paul Barnes. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// read out the intro
let synth = AVSpeechSynthesizer()
let intro = AVSpeechUtterance(string: "Welcome to 5,4,3,2,1 and Breathe. A simple exercise you do when you are feeling anxious or tense. Please press start to begin.")
intro.rate = 0.4
intro.voice = AVSpeechSynthesisVoice(language: "en-IE")
synth.speak(intro)
}
}
| true
|
aa1bd7b4e0a7e1c3d52aa9ce48348b3c167b2d4b
|
Swift
|
arpesenti/learn-swift
|
/5. Control Flow.playground/section-27.swift
|
UTF-8
| 33
| 2.78125
| 3
|
[] |
no_license
|
do
{
++index
} while (index < 3)
| true
|
b2e694c0eed8f9f0013a338ea7bd8dca596cf92f
|
Swift
|
sekcja-memow/mobilki-ios
|
/Shared/ContentView.swift
|
UTF-8
| 1,311
| 3.125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// Shared
//
// Created by Guest User on 04/05/2021.
//
import SwiftUI
struct ContentView: View {
@ObservedObject var viewModel: WeatherViewModel
var body: some View {
VStack {
ForEach(viewModel.records) {
record in WeatherView(record: record, viewModel: viewModel)
}
}.padding()
}
}
struct WeatherView: View {
var record: WeatherModel.WeatherRecord
var viewModel: WeatherViewModel
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/).stroke()
HStack {
Text(verbatim: viewModel.getIcon(record: record)).font(.largeTitle)
VStack {
Text(record.cityName)
Text("Temperature: \(record.temperature, specifier: "%.2f")'C")
.font(.caption)
}
Text("🔁")
.font(.largeTitle)
.onTapGesture {
viewModel.refresh(record: record)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(viewModel: WeatherViewModel())
}
}
| true
|
2972f3cd86edef3e60766afaaa8a74eef6d56f84
|
Swift
|
iBicha/Tunisian-Red-Crescent---iOS
|
/Tunisian Red Crescent/Utils/JsDateTransform.swift
|
UTF-8
| 789
| 2.609375
| 3
|
[
"ISC"
] |
permissive
|
//
// JsDateTransform.swift
// Tunisian Red Crescent
//
// Created by Brahim Hadriche on 4/30/16.
// Copyright © 2016 Esprit. All rights reserved.
//
import Foundation
import ObjectMapper
import EZSwiftExtensions
public class JsDateTransform: TransformType {
public typealias Object = NSDate
public typealias JSON = String
public init() {}
public func transformFromJSON(value: AnyObject?) -> NSDate? {
if let date = value as? String {
return NSDate(fromString: date , format: "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
}
return nil
}
public func transformToJSON(value: NSDate?) -> String? {
if let value = value {
return value.toString(format: "yyyy/MM/dd HH:mm:ss")
}
return nil
}
}
| true
|
a301a9e1b2d7ee0b2fd26b60261f74013027963b
|
Swift
|
elefantel/LunoSwiftStream
|
/LunoSwiftStreamer/Services/Streaming.swift
|
UTF-8
| 5,665
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// Streaming.swift
// Elefantel
//
// Created by Mpendulo Ndlovu on 2020/03/16.
// Copyright © 2020 Elefantel. All rights reserved.
//
import Foundation
protocol Streaming: AnyObject {
var timer: Timer? { get }
var session: URLSession { get }
var webSocketTask: URLSessionWebSocketTask? { get }
var endpoint: Endpoint { get }
func stream<T: Codable, U: Codable>(resource: String,
completion: ((T?, U?) -> Void)?,
failure: ((StreamError) -> Void)?)
func receive<T: Codable, U: Codable>(completion: ((T?, U?) -> Void)?,
failure: ((StreamError) -> Void)?)
func cancel()
func ping()
}
enum Endpoint {
case exchange
var url: String {
switch self {
case .exchange:
return "wss://ws.luno.com/api/1/stream"
}
}
}
protocol StreamingService: AnyObject {
var streamer: Streaming { get }
}
//TODO: implement streamer exponential backoff
class Streamer: NSObject, Streaming {
var timer: Timer?
let endpoint: Endpoint
var session: URLSession
static let timeout = 60.0
private let privilege: Privilege
var webSocketTask: URLSessionWebSocketTask?
init(endpoint: Endpoint,
session: URLSession = URLSession.shared,
privilege: Privilege = .trading) {
self.session = session
self.endpoint = endpoint
self.privilege = privilege
}
func stream<T: Codable, U: Codable>(resource: String,
completion: ((T?, U?) -> Void)?,
failure: ((StreamError) -> Void)?) {
guard
let url = URL(string: endpoint.url)?
.appendingPathComponent(resource)
else { return }
webSocketTask = session.webSocketTask(with: url)
webSocketTask?.resume()
guard
let credentialsData = try? JSONEncoder().encode(privilege.credentials),
let credentialsJSON = String(
data: credentialsData,
encoding: .ascii)
else { return }
webSocketTask?.send(.string(credentialsJSON)) { error in
print(error?.localizedDescription ?? "")
}
ping()
receive(completion: completion, failure: failure)
}
func receive<T: Codable, U: Codable>(completion: ((T?, U?) -> Void)?,
failure: ((StreamError) -> Void)?) {
webSocketTask?.receive { result in
switch result {
case .failure(let error):
failure?(StreamError(error))
case .success(let message):
switch message {
case .data(let data):
if let model = try? JSONDecoder().decode(T.self, from: data) {
completion?(model, nil)
} else if let model = try? JSONDecoder().decode(U.self, from: data) {
completion?(nil, model)
} else {
failure?(StreamError.dataDecodingError)
}
case .string(let string):
if string.count < 3 {
print("server keep-alive")
self.receive(completion: completion, failure: failure)
return
}
guard let data = string.data(using: .utf8) else {
print(string)
failure?(StreamError.stringDataError)
return
}
if let model = try? JSONDecoder().decode(T.self, from: data) {
completion?(model, nil)
} else if let model = try? JSONDecoder().decode(U.self, from: data) {
completion?(nil, model)
} else {
print("string char count: \(string.count)")
print("\(string)\ncould not convert to \(T.self) or \(U.self)")
failure?(StreamError.stringDecodingError)
}
@unknown default:
fatalError("Unknown response")
}
self.receive(completion: completion, failure: failure)
}
}
}
func cancel() {
print("cancel...")
timer?.invalidate()
webSocketTask?.cancel(with: .normalClosure, reason: nil)
}
func ping() {
print("ping...")
webSocketTask?.sendPing(pongReceiveHandler: { [weak self] error in
if let error = error {
print("ping error: \(error.localizedDescription)")
}
print("pong...")
self?.timer = Timer.scheduledTimer(
withTimeInterval: Streamer.timeout,
repeats: true,
block: { _ in
self?.ping()
})
})
}
}
//TODO: make delegate a little clever & connected
extension Streamer: URLSessionWebSocketDelegate {
func urlSession(_ session: URLSession,
webSocketTask: URLSessionWebSocketTask,
didOpenWithProtocol protocol: String?) {
print("web socket connected")
}
func urlSession(_ session: URLSession,
webSocketTask: URLSessionWebSocketTask,
didCloseWith closeCode: URLSessionWebSocketTask.CloseCode,
reason: Data?) {
print("web socket disconnected")
}
}
| true
|
6ed2dc1772b635e01b1578341f76b80c79c80095
|
Swift
|
mcgraw/AdventOfCode2015
|
/AdventOfCode.playground/Pages/Day 6.xcplaygroundpage/Contents.swift
|
UTF-8
| 4,354
| 3.625
| 4
|
[] |
no_license
|
/*:
[http://adventofcode.com/day/6](http://adventofcode.com/day/6)
###--- Day 6: Probably a Fire Hazard ---
Because your neighbors keep defeating you in the holiday house decorating contest year after year, you've decided to deploy one million lights in a 1000x1000 grid.
Furthermore, because you've been especially nice this year, Santa has mailed you instructions on how to display the ideal lighting configuration.
Lights in your grid are numbered from 0 to 999 in each direction; the lights at each corner are at 0,0, 0,999, 999,999, and 999,0. The instructions include whether to turn on, turn off, or toggle various inclusive ranges given as coordinate pairs. Each coordinate pair represents opposite corners of a rectangle, inclusive; a coordinate pair like 0,0 through 2,2 therefore refers to 9 lights in a 3x3 square. The lights all start turned off.
To defeat your neighbors this year, all you have to do is set up your lights by doing the instructions Santa sent you in order.
For example:
- turn on 0,0 through 999,999 would turn on (or leave on) every light.
- toggle 0,0 through 999,0 would toggle the first line of 1000 lights, turning off the ones that were on, and turning on the ones that were off.
- turn off 499,499 through 500,500 would turn off (or leave off) the middle four lights.
After following the instructions, how many lights are lit?
Your puzzle answer was 400410.
###--- Part Two ---
You just finish implementing your winning light pattern when you realize you mistranslated Santa's message from Ancient Nordic Elvish.
The light grid you bought actually has individual brightness controls; each light can have a brightness of zero or more. The lights all start at zero.
The phrase turn on actually means that you should increase the brightness of those lights by 1.
The phrase turn off actually means that you should decrease the brightness of those lights by 1, to a minimum of zero.
The phrase toggle actually means that you should increase the brightness of those lights by 2.
What is the total brightness of all lights combined after following Santa's instructions?
For example:
- turn on 0,0 through 0,0 would increase the total brightness by 1.
- toggle 0,0 through 999,999 would increase the total brightness by 2000000.
Your puzzle answer was 15343601.
[Contents](Contents) | [Go Back To Day 5](Day%205) | [Continue to Day 7](@next)
*/
// WARNING: Insanely slow. Really need to circle back and implement more of a rect+intersection model. If you're familiar with a better way, please hit me up!
import CoreGraphics
// Used to access NSCharacterSet
import Foundation
// Used so we can get access to the timing functions
import CoreFoundation
// Load in the puzzle input (switch to day5-quick to use a smaller set)
let input = XMFileManager.shared.loadStringInputFromResource("day6")
// Split the input
var strings = input.componentsSeparatedByString("\n")
let startTime = CFAbsoluteTimeGetCurrent()
var lights = Array(count: 1000, repeatedValue: Array(count: 1000, repeatedValue: 0))
var brightness = Array(count: 1000, repeatedValue: Array(count: 1000, repeatedValue: 0))
var on = 0
var bright = 0
for (idx, instruction) in strings.enumerate() {
let separators = NSCharacterSet(charactersInString: " ,")
let parts = instruction.componentsSeparatedByCharactersInSet(separators)
let isToggle = (parts[0] == "toggle") ? true : false
let x1 = isToggle ? Int(parts[1])! : Int(parts[2])!
let x2 = isToggle ? Int(parts[2])! : Int(parts[3])!
let y1 = isToggle ? Int(parts[4])! : Int(parts[5])!
let y2 = isToggle ? Int(parts[5])! : Int(parts[6])!
for var x = x1; x <= y1; x++ {
for var y = x2; y <= y2; y++ {
if isToggle {
lights[x][y] = (lights[x][y] == 1) ? 0 : 1
on += (lights[x][y] == 1) ? 1 : 0
bright += (lights[x][y] == 1) ? 2 : -2
} else {
on += ((parts[1] == "on") && (lights[x][y] == 0)) ? 1 : 0
bright += ((parts[1] == "on") && (lights[x][y] == 0)) ? 1 : -1
lights[x][y] = (parts[1] == "on") ? 1 : 0
}
}
}
print("Progress! Line \(idx+1) of \(strings.count) done")
}
print("\(on) lights were turned on with a brightness of \(bright)")
| true
|
e9d01aefc270b8a18bf782c9480ce0d1113b3b54
|
Swift
|
Barry0327/ARFoodie
|
/ARFoodieApp/Main/Domain/Restaurant.swift
|
UTF-8
| 1,557
| 3.078125
| 3
|
[] |
no_license
|
//
// Restaurant.swift
// ARFoodie
//
// Created by Chen Yi-Wei on 2019/3/28.
// Copyright © 2019 Chen Yi-Wei. All rights reserved.
//
import Foundation
import CoreLocation
struct Restaurant {
let placeID: String
let name: String
let lat: Double
let lng: Double
let rating: Double?
let userRatingsTotal: Double?
var location: CLLocation {
return CLLocation(latitude: lat, longitude: lng)
}
private enum CodingKeys: String, CodingKey {
case geometry, name, placeID = "place_id", rating, userRatingsTotal = "user_ratings_total"
}
private enum Location: String, CodingKey {
case location
}
private enum LatAndLng: String, CodingKey {
case lat, lng
}
}
extension Restaurant: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
placeID = try container.decode(String.self, forKey: .placeID)
name = try container.decode(String.self, forKey: .name)
rating = try container.decodeIfPresent(Double.self, forKey: .rating)
userRatingsTotal = try container.decodeIfPresent(Double.self, forKey: .userRatingsTotal)
let locationContainer = try container.nestedContainer(keyedBy: Location.self, forKey: .geometry)
let latLngContainer = try locationContainer.nestedContainer(keyedBy: LatAndLng.self, forKey: .location)
lng = try latLngContainer.decode(Double.self, forKey: .lng)
lat = try latLngContainer.decode(Double.self, forKey: .lat)
}
}
| true
|
baaa0ee4ac3aad6c8c1a1646b5464cbc07242f6b
|
Swift
|
marinofelipe/UITableViewWrapper
|
/UITableViewWrapper/Classes/TableDataSourceWrapper.swift
|
UTF-8
| 1,269
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
//
// TableDataSourceWrapper.swift
// Pods-UITableViewWrapper_Example
//
// Created by Felipe Lefèvre Marino on 2/21/18.
//
import Foundation
public class TableDataSourceWrapper: NSObject {
var numOfSections: Int? = 0
var numOfRowsBySection: [Int] = [0] {
didSet {
self.numOfSections = numOfRowsBySection.count
}
}
var cell: UITableViewCell?
}
extension TableDataSourceWrapper: UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return numOfSections!
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numOfRowsBySection[section]
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let tableView = tableView as? UIWrappedTableView {
tableView.indexPathOfDequeueingCell = indexPath
if let cell = self.cell {
return cell
}
}
assertionFailure("Used table view should inherit from UIWrappedTableView OR cell block was not set for the table (use .cell(CellForRowAtIndexPathBlock) to define cell for each row!!")
return UITableViewCell()
}
}
| true
|
75c47fdef0a49b38284dba3ee8ab3c7d144b6cbc
|
Swift
|
IamAScappy/learn-rxswift
|
/RxSwiftExamples2/RxSwiftExamples2/AnimationViewController.swift
|
UTF-8
| 3,263
| 2.65625
| 3
|
[] |
no_license
|
//
// AnimationViewController.swift
// RxSwiftExamples2
//
// Created by yuaming on 18/07/2018.
// Copyright © 2018 yuaming. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class AnimationViewController: UIViewController {
@IBOutlet weak var upButton: UIButton!
@IBOutlet weak var downButton: UIButton!
@IBOutlet weak var leftButton: UIButton!
@IBOutlet weak var rightButton: UIButton!
@IBOutlet weak var box: UIView!
fileprivate let disposeBag: DisposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
bind()
}
}
extension AnimationViewController {
fileprivate func bind() {
upButton.rx.tap
.map { Animation.up }
.bind(to: box.rx.animation)
.disposed(by: disposeBag)
downButton.rx.tap
.map { Animation.down }
.bind(to: box.rx.animation)
.disposed(by: disposeBag)
leftButton.rx.tap
.map { Animation.left }
.bind(to: box.rx.animation)
.disposed(by: disposeBag)
rightButton.rx.tap
.map { Animation.right }
.bind(to: box.rx.animation)
.disposed(by: disposeBag)
// upButton.rx.tap
// .map { Animation.up }
// .subscribe(onNext: { [weak self] animation in
// guard let `self` = self else { return }
//
// UIView.animate(withDuration: 0.5) {
// self.box.transform = animation.transform(self.box.transform)
// }
// }).disposed(by: disposeBag)
//
// downButton.rx.tap
// .map { Animation.down }
// .subscribe(onNext: { [weak self] animation in
// guard let `self` = self else { return }
//
// UIView.animate(withDuration: 0.5) {
// self.box.transform = animation.transform(self.box.transform)
// }
// }).disposed(by: disposeBag)
//
// leftButton.rx.tap
// .map { Animation.left }
// .subscribe(onNext: { [weak self] animation in
// guard let `self` = self else { return }
//
// UIView.animate(withDuration: 0.5) {
// self.box.transform = animation.transform(self.box.transform)
// }
// }).disposed(by: disposeBag)
//
// rightButton.rx.tap
// .map { Animation.right }
// .subscribe(onNext: { [weak self] animation in
// guard let `self` = self else { return }
//
// UIView.animate(withDuration: 0.5) {
// self.box.transform = animation.transform(self.box.transform)
// }
// }).disposed(by: disposeBag)
}
}
// Binder
// - Boxing => view.rx.animation
// - Binder 안에서 코드가 길어지는 것을 경계해야 함
extension Reactive where Base: UIView {
var animation: Binder<Animation> {
return Binder(self.base, binding: { (view, animation) in
UIView.animate(withDuration: 0.5) {
view.transform = animation.transform(view.transform)
}
})
}
}
enum Animation {
case left, right, up, down
}
extension Animation {
func transform(_ transform: CGAffineTransform) -> CGAffineTransform {
switch self {
case .left: return transform.translatedBy(x: -50, y: 0)
case .right: return transform.translatedBy(x: 50, y: 0)
case .up: return transform.translatedBy(x: 0, y: -50)
case .down: return transform.translatedBy(x: 0, y: 50)
}
}
}
| true
|
4e95964f33a750e530882b30308aa0b5b4ce83b0
|
Swift
|
lxuan2/IOS6SwiftUI
|
/Demo/Demo/MaterialView.swift
|
UTF-8
| 4,695
| 2.90625
| 3
|
[] |
no_license
|
//
// MaterialView.swift
// test
//
// Created by Xuan Li on 8/2/20.
//
import SwiftUI
import IOS6SwiftUI
struct MaterialView: View {
@State private var selection: UIBlurEffect.Style = .systemThinMaterial
@State private var offset: CGPoint = .init(x: 0, y: 0)
@State private var selection1: UIVibrancyEffectStyle = .fill
var body: some View {
VStack {
ZStack {
Image("ins").resizable()
ZStack {
BlurEffect(blurStyle: selection)
.frame(width: 100, height: 100, alignment: .center)
.offset(x: offset.x, y: offset.y)
VibrancyEffect(blurStyle: selection, vibrancyStyle: selection1) {
Image(systemName: "star.fill")
.resizable()
}
.frame(width: 50, height: 50, alignment: .center)
}
.simultaneousGesture(
DragGesture()
.onChanged { value in
self.offset = .init(x: value.translation.width, y: value.translation.height)
}
.onEnded { _ in
withAnimation {
self.offset = .init(x: 0, y: 0)
}
}
)
}
ScrollView(.vertical) {
VStack(spacing: 0) {
Picker(selection: self.$selection, label: Text("Background")) {
HStack {
Image(systemName: "person.fill")
Text("tick")
}.tag(UIBlurEffect.Style.systemThickMaterial)
HStack {
Image(systemName: "person.2.fill")
Text("regular")
}.tag(UIBlurEffect.Style.systemMaterial)
HStack {
Image(systemName: "person.3.fill")
Text("thin")
}.tag(UIBlurEffect.Style.systemThinMaterial)
HStack {
Image(systemName: "person.3.fill")
Text("ultra thin")
}.tag(UIBlurEffect.Style.systemUltraThinMaterial)
}
Picker(selection: self.$selection1, label: Text("Foreground")) {
HStack {
Image(systemName: "person.fill")
Text("fill")
}.tag(UIVibrancyEffectStyle.fill)
HStack {
Image(systemName: "person.2.fill")
Text("label")
}.tag(UIVibrancyEffectStyle.label)
HStack {
Image(systemName: "person.3.fill")
Text("quaternaryLabel")
}.tag(UIVibrancyEffectStyle.quaternaryLabel)
HStack {
Image(systemName: "person.3.fill")
Text("secondaryFill")
}.tag(UIVibrancyEffectStyle.secondaryFill)
HStack {
Image(systemName: "person.3.fill")
Text("secondaryLabel")
}.tag(UIVibrancyEffectStyle.secondaryLabel)
HStack {
Image(systemName: "person.3.fill")
Text("separator")
}.tag(UIVibrancyEffectStyle.separator)
HStack {
Image(systemName: "person.3.fill")
Text("tertiaryFill")
}.tag(UIVibrancyEffectStyle.tertiaryFill)
HStack {
Image(systemName: "person.3.fill")
Text("tertiaryLabel")
}.tag(UIVibrancyEffectStyle.tertiaryLabel)
}
}
}
}.edgesIgnoringSafeArea(.all)
}
}
struct MaterialView_Previews: PreviewProvider {
static var previews: some View {
MaterialView()
}
}
| true
|
23887bd62aa7b7692caafcb0007862a2226c308e
|
Swift
|
shadyabdou/elfariq
|
/ElFariq/Competetion.swift
|
UTF-8
| 644
| 2.6875
| 3
|
[] |
no_license
|
//
// Competetion.swift
//
// Create by Shady Abdou on 3/1/2017
// Copyright © 2017 LinkDev. All rights reserved.
// Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
class Competetion{
var championship : String!
var iD : String!
var logo : String!
var name : String!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: NSDictionary){
championship = dictionary["Championship"] as? String
iD = dictionary["ID"] as? String
logo = dictionary["Logo"] as? String
name = dictionary["Name"] as? String
}
}
| true
|
dd595aa40fa2a499e2a475c5c8d04664cdaddee4
|
Swift
|
weixiao3989/TCAR
|
/TCAR/Network_Access.swift
|
UTF-8
| 5,088
| 2.5625
| 3
|
[] |
no_license
|
//
// Network_Access.swift
// TCAR
//
// Created by Chris on 2018/1/20.
// Copyright © 2018年 MUST. All rights reserved.
//
import Alamofire
import AlamofireImage
class AccessAPIs {
static fileprivate let queue = DispatchQueue(label: "requests.queue", qos: .utility)
static fileprivate let mainQueue = DispatchQueue.main
/*
* Get API Response JSON Data.
*/
fileprivate class func make(request: DataRequest, closure: @escaping (_ json: [String: Any]?, _ error: Error?)->()) {
request.responseJSON(queue: AccessAPIs.queue) { response in
switch response.result {
case .failure(let error):
AccessAPIs.mainQueue.async {
closure(nil, error)
}
case .success(let data):
AccessAPIs.mainQueue.async {
closure((data as? [String: Any]) ?? [:], nil)
}
}
}
}
class func sendRequest_hasParameters(url: String, method: HTTPMethod, headers: HTTPHeaders, parameters: [String : Any], closure: @escaping (_ json: [String: Any]?, _ error: Error?)->()) {
let request = Alamofire.request(url, method: method, parameters: parameters, encoding: JSONEncoding(options: []), headers: headers).validate().responseJSON {
response in
switch response.result {
case .success:
print("Access url : \(url) is Successful")
case .failure(let error):
print(error)
}
// Only Signin need Save Session.
if (url == TCAR_API.getSigninURL()) {
// Cookies - Session ID.
let url = URL(string: TCAR_API.APIBaseURL)!
let cstorage = HTTPCookieStorage.shared
if let cookies = cstorage.cookies(for: url) {
for cookie:HTTPCookie in cookies {
print("name:\(cookie.name)", "value:\(cookie.value)")
// Write session ID to the local data, for WhoamI API;
UserDefaults.standard.removeObject(forKey: "userSessionID")
UserDefaults.standard.set(cookie.value, forKey: "userSessionID")
UserDefaults.standard.synchronize()
}
}
}
}
AccessAPIs.make(request: request) { json, error in
closure(json, error)
}
}
class func sendRequest_noParameters(url: String, method: HTTPMethod, headers: HTTPHeaders, closure: @escaping (_ json: [String: Any]?, _ error: Error?)->()) {
let request = Alamofire.request(url, method: method, encoding: JSONEncoding(options: []), headers: headers).validate().responseJSON {
response in
switch response.result {
case .success:
print("Access url : \(url) is Successful")
case .failure(let error):
print(error)
}
}
AccessAPIs.make(request: request) { json, error in
closure(json, error)
}
}
/*
* Get and Set Avatar API Response Image Data.
*/
fileprivate class func makeImage(request: DataRequest, closure: @escaping (_ img: Image?, _ error: Error?)->()) {
request.responseImage { response in
switch response.result {
case .failure(let error):
AccessAPIs.mainQueue.async {
closure(nil, error)
}
case .success(let data):
AccessAPIs.mainQueue.async {
closure(data, nil)
}
}
}
}
class func getAvatar(url: String, closure: @escaping (_ img: Image?, _ error: Error?)->()) {
let request = Alamofire.request(url)
AccessAPIs.makeImage(request: request) { image, error in
closure (image, error)
}
}
class func setAvatar(image: UIImage, closure: @escaping (_ json: Any?, _ error: Error?)->()) {
let headers = TCAR_API.getHeader_HasSession()
let URL = try! URLRequest(url: TCAR_API.getAvatarURL(), method: .post, headers: headers)
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(UIImageJPEGRepresentation(image, 1.0)!, withName: "avatar", fileName: "image.png", mimeType: "image/png")
}, with: URL, encodingCompletion: {
encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print("Access url : \(URL) is Successful")
closure (response.result.value, nil)
}
case .failure(let encodingError):
print("Errot to upload photo, Response is : \(encodingError)")
closure (nil, encodingError)
}
})
}
}
| true
|
a7673eca0f4bd61ae6cdae39d246ea9afab54e87
|
Swift
|
maikelgh/Marvel
|
/Marvel/Services/Repository/MarvelAPIRepository.swift
|
UTF-8
| 2,039
| 2.671875
| 3
|
[] |
no_license
|
//
// MarvelAPIRepository.swift
// Marvel
//
// Created by michael on 12/9/21.
//
import Foundation
class MarvelAPIRepository: MarvelRepository {
//Obtener listado.
func getCharacters(data: AltaSimplificadaRequestVO?, result: @escaping (BaseResult<AltaSimplificadaResponseVO>) -> Void) {
background {
CustomLog.log(type: .info, category: .repository, item: "altaSimplificada called")
RegistroSimplificadoControllerAPI.altaSimplificada(body: data) { (response, error) in
ui {
guard let response = response else {
let err = BaseRepository.getCodeError(error)
CustomLog.log(type: .error, category: .repository, item: err.message)
result(BaseResult.failure(error: err))
return
}
CustomLog.log(type: .success, category: .repository, item: response)
result(BaseResult.success(result: response))
}
}
}
}
//Obtener detalle.
func getCharacter(data: ValidarIdentificadorRequestVO?, result: @escaping (BaseResult<ValidarIdentificadorResponseVO>) -> Void) {
background {
CustomLog.log(type: .info, category: .repository, item: "validarIdentificadorMacSimpl called")
RegistroSimplificadoControllerAPI.validarIdentificadorMacSimpl(body: data) { (response, error) in
ui {
guard let response = response else {
let err = BaseRepository.getCodeError(error)
CustomLog.log(type: .error, category: .repository, item: err.message)
result(BaseResult.failure(error: err))
return
}
CustomLog.log(type: .success, category: .repository, item: response)
result(BaseResult.success(result: response))
}
}
}
}
}
| true
|
27a6e07205feae94c2de8c3343316afef030ef1a
|
Swift
|
cherrybeard/Uniq
|
/Uniq/Animation/Cards/RepositionHandAnimation.swift
|
UTF-8
| 1,273
| 3.09375
| 3
|
[] |
no_license
|
//
// RepositionHandAnimation.swift
// Uniq
//
// Created by Steven Gusev on 25/06/2019.
// Copyright © 2019 Steven Gusev. All rights reserved.
//
import SpriteKit
class RepositionHandAnimation: Animation {
private static let DURATION: TimeInterval = 0.3
private let hand: HandSprite
private let addCard: Bool
init(hand: HandSprite, addCard: Bool = false) {
self.hand = hand
self.addCard = addCard
}
override func play() {
let cards = hand.children.filter {
if let card = $0 as? CardSprite {
return !card.isDiscarded
}
return false
}
var cardsCount = cards.count
if addCard {
cardsCount += 1
}
for (index, card) in cards.enumerated() {
let (position, rotation) = HandSprite.cardPosition(at: index + 1, total: cardsCount)
let move = SKAction.move(to: position, duration: RepositionHandAnimation.DURATION)
let rotate = SKAction.rotate(toAngle: rotation, duration: RepositionHandAnimation.DURATION)
let action = SKAction.group([move, rotate])
action.timingMode = .easeOut
card.run(action)
}
state = .finished
}
}
| true
|
b834dd9d8db294439cf87dd4b1e158effc8aec3d
|
Swift
|
dmaulikr/MusicalTrivia
|
/MusicalTrivia/Interval.swift
|
UTF-8
| 1,389
| 3.203125
| 3
|
[] |
no_license
|
//
// Interval.swift
// MusicalTrivia
//
// Created by David Wolgemuth on 1/26/16.
// Copyright © 2016 David. All rights reserved.
//
import Foundation
class Interval: JSONCompatable
{
let startNote: Int
let interval: Int
let name: String
var dictionary: [String: AnyObject] {
get {
return ["startNote": startNote, "interval": interval, "name": name]
}
}
init(startNote: Int, interval: Int, name: String)
{
self.startNote = startNote
self.interval = interval
self.name = name
}
static let intervalNames = ["Unison", "Minor 2nd", "Major 2nd", "Minor 3rd", "Major 3rd", "Perfect 4th", "Tritone", "Perfect 5th", "Minor 6th", "Major 6th", "Minor 7th", "Major 7th", "Octave"]
static func random() -> Interval
{
let startNote = Int(rand()) % 20 + 50
let interval = Int(arc4random_uniform(UInt32(Interval.intervalNames.count)))
let name = Interval.intervalNames[interval]
return Interval(startNote: startNote, interval: interval, name: name)
}
static func initFromJSON(json: [String: AnyObject]) -> Interval
{
let startNote = json["startNote"] as! Int!
let interval = json["interval"] as! Int!
let name = json["name"] as! String!
return Interval(startNote: startNote, interval: interval, name: name)
}
}
| true
|
1b33cdf45e33b0d7fa7afa22b686fab9bbfbf1c6
|
Swift
|
dkainm/NewsApp
|
/NewsApp/controllers/ArticlesViewController.swift
|
UTF-8
| 4,315
| 2.59375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// NewsApp
//
// Created by Alex Rudoi on 9/8/21.
//
import UIKit
import Nuke
class ArticlesTableViewController: MainTableViewController {
var keyword = "Apple"
override func setup() {
super.setup()
searchController.searchBar.delegate = self
tableView.refreshControl?.addTarget(self, action: #selector(refresh), for: .valueChanged)
}
override func fetchData() {
setViewToLoad()
ApiManager.shared.getArticlesByKeyword(keyword, sources: nil, country: nil, category: nil) { [weak self] result in
self?.articles = result
DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
self?.tableView.refreshControl?.endRefreshing()
}
}
}
//MARK: – Refresh Control
@objc func refresh(_ sender: Any) {
fetchData()
}
private func setViewToLoad() {
articles = []
tableView.reloadData()
}
@IBAction func filterTapped(_ sender: UIBarButtonItem) {
let filterController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "FilterTableViewController")
present(filterController, animated: true)
}
//MARK: – TableView Delegate & Data Source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles.isEmpty ? 8 : articles.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "article", for: indexPath) as! ArticleTableViewCell
if articles.count - 1 > indexPath.row {
let currentArticle = articles[indexPath.row]
Nuke.loadImage(with: URL(string: currentArticle.urlToImage)!, options: nukeOptions, into: cell.articleImageView)
cell.configure(article: currentArticle)
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if !articles.isEmpty {
let articleView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ArticleWebViewController") as! ArticleWebViewController
articleView.title = articles[indexPath.row].source.name
articleView.urlString = articles[indexPath.row].url
navigationController?.pushViewController(articleView, animated: true)
}
}
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let save = UIContextualAction(style: .normal, title: nil) { [weak self] (contexualAction, view, complitionHandler) in
let article = self?.articles[indexPath.row]
self?.saveArticle(article!)
complitionHandler(true)
}
save.image = UIGraphicsImageRenderer(size: CGSize(width: 30, height: 30)).image { _ in
UIImage.saveIcon?.draw(in: CGRect(x: 0, y: 0, width: 30, height: 30))
}
save.backgroundColor = .secondaryGreen
let configuration = UISwipeActionsConfiguration(actions: [save])
configuration.performsFirstActionWithFullSwipe = true
return configuration
}
private func saveArticle(_ article: Article) {
let object = ArticleObject()
object.author = article.author
object.content = article.content
object.desc = article.desc
object.publishedAt = article.publishedAt
object.title = article.title
object.url = article.url
object.urlToImage = article.urlToImage
object.sourceName = article.source.name
DatabaseManager.shared.addArticle(object)
}
}
//MARK: – Search Controller Delegate
extension ArticlesTableViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
filterContentForSearchText(searchBar.text!)
}
func filterContentForSearchText(_ searchText: String) {
keyword = searchText
fetchData()
}
}
| true
|
6d902b7b8de8e31bd38b562669d61676c9c12d93
|
Swift
|
lhp3851/Swift_Demo
|
/Swift_Demo/CocoaTouch/UIKit/View/KKInfiniteScrollView.swift
|
UTF-8
| 4,837
| 2.671875
| 3
|
[] |
no_license
|
//
// KKInfiniteScrollView.swift
// Swift_Demo
//
// Created by lhp3851 on 2017/11/12.
// Copyright © 2017年 Jerry. All rights reserved.
//
import UIKit
protocol KKInfiniteScrollViewDelegate {
func clickAt(index:Int) -> Void //点击
func scrollAt(index:Int) -> Void //滚动到
}
class KKInfiniteScrollView: UIScrollView,UIScrollViewDelegate {
let viewWidth = UIScreen.width
let viewHeight = 256.yfit
private(set) var currentPage = 0 //当前页数
var datasArray:[String] = [String]()//存放图片的名字
var isScrolling = true//是否正在滚动
var scrollViewDelegate : KKInfiniteScrollViewDelegate?
var interval = 1.0 //定时器触发间隔
var timeLine = 10.0
lazy var timer : DispatchSourceTimer = {
let timeTool = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
timeTool.schedule(deadline: DispatchTime.now(), repeating: self.interval)
return timeTool
}()
init(frame: CGRect,datas:[String]) {
super.init(frame: frame)
self.isPagingEnabled = true
self.showsVerticalScrollIndicator = false
self.showsVerticalScrollIndicator = false
self.delegate = self
self.initDatas(datas: datas)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initDatas(datas:[String]) -> Void {
self.interval = 1
self.isScrolling = true
self.datasArray = datas
self.datasArray.append(datas.last!)
self.datasArray.insert(datas.first!, at: 0)
for (idx,imageName) in self.datasArray.enumerated() {
let frame = CGRect.init(x: CGFloat(idx)*viewWidth, y: 0, width: viewWidth, height: viewHeight)
print("frame.origin.x:",frame.origin.x,viewWidth)
let imageView = KKImageView.init(frame: frame, action: { (imageView) in
print("clicked imageView")
})
imageView.image = UIImage.named(imageName)
imageView.isUserInteractionEnabled = true
imageView.contentMode = UIView.ContentMode.redraw
self.addSubview(imageView)
}
self.contentSize = CGSize.init(width: CGFloat(self.datasArray.count)*viewWidth, height: 0)
self.contentOffset = CGPoint.init(x: viewWidth, y: 0)
self.startAutoScroll()
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.makeInfiniteScrolling()
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
self.makeInfiniteScrolling()
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.stopScroll()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.startAutoScroll()
}
func startAutoScroll() -> Void {
if self.interval == 0 {
return
}
self.isScrolling = true
print("start")
self.timer.setEventHandler {
self.timeLine -= self.interval
if self.timeLine < 0{
self.timer.cancel()
}
DispatchQueue.main.async(execute: {
let offset :CGFloat = self.contentOffset.x + self.viewWidth;
self.setContentOffset(CGPoint.init(x: offset, y: 0), animated: true)
})
}
self.timer.resume()
}
func makeInfiniteScrolling() -> Void {
let page : Int = Int(self.contentOffset.x / viewWidth)
if page == self.datasArray.count - 1 {
self.currentPage = 0
self.setContentOffset(CGPoint.init(x: viewWidth, y: 0), animated: false)
}
else if page == 0 {
self.currentPage = page - 2
self.setContentOffset(CGPoint.init(x: CGFloat((self.datasArray.count - 2))*viewWidth, y: 0), animated: false)
}
else{
self.currentPage = page - 1
}
guard let delegateLocal = self.scrollViewDelegate else { return }
delegateLocal.scrollAt(index: self.currentPage)
}
func stopScroll() -> Void {
print("stop")
self.isScrolling = false
self.timer.suspend()
}
//调到指定页面去
func jumTo(page:Int) -> Void {
if page>self.datasArray.count || page < 0 {
return
}
self.setContentOffset(CGPoint.init(x: CGFloat(page+1)*viewWidth, y: 0), animated: false)
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| true
|
545e53c87f082fe26dcefe217fafddb480702194
|
Swift
|
wonwoo518/swiftlibs
|
/algorithms/mergesort2.playground/Contents.swift
|
UTF-8
| 937
| 3.5625
| 4
|
[] |
no_license
|
// Created by wonwoo518 on 2018. 12. 25.
import UIKit
func mergesort<T:Comparable>(_ input:Array<T>)->Array<T>{
if input.count == 1{
return input
}
let firstCnt:Int = input.count - input.count/2
let lastCnt:Int = input.count - firstCnt
let re1 = mergesort(Array<T>(input.dropFirst(firstCnt)))
let re2 = mergesort(Array<T>(input.dropLast(lastCnt)))
return arrange(re1, re2)
}
func arrange<T:Comparable>(_ arr1:Array<T>, _ arr2:Array<T>)->Array<T>{
var arr3:Array<T> = []
var src1 = arr1
var src2 = arr2
while src1.count != 0 && src2.count != 0 {
if src1[0] > src2[0]{
arr3.append(src2.removeFirst())
}else{
arr3.append(src1.removeFirst())
}
}
(src1 + src2).map{
arr3.append($0)
}
return arr3
}
print(mergesort(["3","a","c","d","E","f","G","0","1"]))
print(mergesort([2,1,3,4,8,7,6]))
| true
|
13ba98f23fe0106acc5eab195541b8c181f0193a
|
Swift
|
SHurtado91112/BattleDatabase
|
/BattleDatabase/InsertRecordViewController.swift
|
UTF-8
| 4,350
| 2.53125
| 3
|
[] |
no_license
|
//
// InsertRecordViewController.swift
// BattleDatabase
//
// Created by Steven Hurtado on 6/4/16.
// Copyright © 2016 Hurtado_Steven. All rights reserved.
//
import UIKit
class InsertRecordViewController: UIViewController {
@IBOutlet weak var txtName: UITextField!
@IBOutlet weak var txtMarks: UITextField!
@IBOutlet weak var txtRank: UITextField!
@IBOutlet weak var txtStrength: UITextField!
@IBOutlet weak var btnSave: UIButton!
@IBOutlet weak var imageView: UIImageView!
var isEdit : Bool = false
var ninjaData : NinjaInfo!
override func viewDidLoad()
{
super.viewDidLoad()
if(isEdit)
{
txtName.text = ninjaData.Name
txtMarks.text = ninjaData.RegisNum
txtRank.text = ninjaData.Rank
txtStrength.text = ninjaData.Strength
}
self.imageView.image = UIImage(named: "Drawing (2)")
// Do any additional setup after loading the view.
btnSave.layer.cornerRadius = 10
btnSave.layer.shadowOffset = CGSize(width: 5,height: 5)
btnSave.layer.shadowRadius = 1
btnSave.layer.shadowOpacity = 0.5
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnBackClicked(_ sender: AnyObject)
{
}
@IBAction func btnSaveClicked(_ sender: AnyObject)
{
if(txtName.text == "")
{
Util.invokeAlertMethod("", strBody: "Please enter ninja name.", delegate: nil)
}
else if(txtMarks.text == "")
{
Util.invokeAlertMethod("", strBody: "Please enter ninja registry number.", delegate: nil)
}
else if(txtRank.text == "")
{
Util.invokeAlertMethod("", strBody: "Please enter ninja rank.", delegate: nil)
}
else if(txtStrength.text == "")
{
Util.invokeAlertMethod("", strBody: "Please enter main strength.", delegate: nil)
}
else
{
if(isEdit)
{
let ninjaInfo: NinjaInfo = NinjaInfo()
ninjaInfo.RollNo = ninjaData.RollNo
ninjaInfo.Name = txtName.text!
ninjaInfo.RegisNum = txtMarks.text!
ninjaInfo.Rank = txtRank.text!
ninjaInfo.Strength = txtStrength.text!
let isUpdated = ModelManager.getInstance().updateNinjaData(ninjaInfo)
if isUpdated {
self.performSegue(withIdentifier: "savedSegue", sender: self)
Util.invokeAlertMethod("", strBody: "Record updated successfully.", delegate: nil)
} else {
self.performSegue(withIdentifier: "savedSegue", sender: self)
Util.invokeAlertMethod("", strBody: "Error in updating record.", delegate: nil)
}
}
else
{
let ninjaInfo: NinjaInfo = NinjaInfo()
ninjaInfo.Name = txtName.text!
ninjaInfo.RegisNum = txtMarks.text!
ninjaInfo.Rank = txtRank.text!
ninjaInfo.Strength = txtStrength.text!
ninjaInfo.UserName = Globals.currentUser
ninjaInfo.PassWord = Globals.currentPass
let isInserted = ModelManager.getInstance().addNinjaData(ninjaInfo)
if isInserted {
self.performSegue(withIdentifier: "savedSegue", sender: self)
Util.invokeAlertMethod("", strBody: "Record inserted successfully.", delegate: nil)
} else {
self.performSegue(withIdentifier: "savedSegue", sender: self)
Util.invokeAlertMethod("", strBody: "Error in inserting record.", delegate: nil)
}
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
9fd22e3c9a88ba75c704be1736d9f4fbbb400ae8
|
Swift
|
Ramandeep12345/directed-studies
|
/FloClu/FloClu/controllers/PostsVCS/CollectionPostView.swift
|
UTF-8
| 5,261
| 2.546875
| 3
|
[] |
no_license
|
//
// CollectionPostView.swift
// FloClu
//
// Created by Ashish Ashish on 2019-07-29.
// Copyright © 2019 capstoneProject. All rights reserved.
//
import Foundation
import UIKit
class CollectionPostView: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
// let data = DataSet()
var arrdata = [Post]()
fileprivate var alertStyle: UIAlertController.Style = .actionSheet
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getdata()
collectionView.delegate = self
collectionView.dataSource = self
}
func getdata() {
let url = URL(string: "https://floclu.ca/posts.php")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do {
if error == nil {
self.arrdata = try JSONDecoder().decode([Post].self, from: data!)
for mainarr in self.arrdata {
print(mainarr.title, " : ", mainarr.detail)
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
}
catch {
print("Error in getting json data")
}
}.resume()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.arrdata.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
// cell.locationName.text = locationNames[indexPath.row]
// cell.locationDescription.text = locationDescription[indexPath.row]
cell.titleLebel.text = self.arrdata[indexPath.row].title
cell.descriptionLabel.text = self.arrdata[indexPath.row].detail
cell.Author.text = self.arrdata[indexPath.row].username
if( indexPath.row % 2 == 0){
cell.backgroundColor = color2
}
else{
cell.backgroundColor = color3
}
// Do any additional setup after loading the view, typically from a nib.
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumInteritemSpacing = 20
layout.minimumLineSpacing = 20
collectionView.collectionViewLayout = layout
//This creates the shadows and modifies the cards a little bit
cell.contentView.layer.cornerRadius = 4.0
cell.contentView.layer.borderWidth = 1.0
cell.layer.cornerRadius = 8
cell.contentView.layer.borderColor = UIColor.clear.cgColor
cell.contentView.layer.masksToBounds = false
cell.layer.shadowColor = UIColor.gray.cgColor
cell.layer.shadowOffset = CGSize(width: 0, height: 1.0)
cell.layer.shadowRadius = 4.0
cell.layer.shadowOpacity = 1.0
cell.layer.masksToBounds = false
cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: cell.contentView.layer.cornerRadius).cgPath
return cell
}
func collectionView(_ collectionView: UICollectionView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func collectionView(_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
// 1
switch kind {
// 2
case UICollectionView.elementKindSectionHeader:
// 3
guard
let headerView = collectionView.dequeueReusableSupplementaryView(
ofKind: kind,
withReuseIdentifier: "postHeaderView",
for: indexPath) as? PostHeaderView
else {
fatalError("Invalid view type")
}
let searchTerm = "Latest Posts"
headerView.postHeaderLabel.text = searchTerm
return headerView
default:
// 4
assert(false, "Invalid element type")
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let alert = UIAlertController(style: self.alertStyle)
let text: [AttributedTextBlock] = [
.normal(""),
.header1(arrdata[indexPath.row].title),
.normal(self.arrdata[indexPath.row].detail),
]
alert.addTextViewer(text: .attributedText(text))
alert.addAction(title: "SendMessage")
alert.addAction(title: "OK", style: .cancel)
self.present(alert, animated: true, completion: nil)
}
}
| true
|
2376e5c36d484206855d024960f7b0700900f173
|
Swift
|
Feanor007/Swift_proj
|
/Concentrations/Concentrations/ConcentrationViewController.swift
|
UTF-8
| 3,405
| 2.65625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Concentrations
//
// Created by 唐泽宇 on 2018/7/26.
// Copyright © 2018 唐泽宇. All rights reserved.
//
import UIKit
class ConcentrationViewController: UIViewController {
private lazy var game = Concentration(numberOfPairsOfCards:numberOfPairsOfCards )
var numberOfPairsOfCards: Int {
return (cardButtons.count + 1) / 2
}
private(set) var flipNumber = 0 {
didSet{
updateFlipLabel()
}
}
private func updateFlipLabel (){
let attributes:[NSAttributedString.Key:Any] = [
.strokeWidth : 5.0,
.strokeColor : #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
]
let attributedString = NSAttributedString(string: "Flips: \(flipNumber)", attributes: attributes)
flipCountLabel.attributedText = attributedString
}
@IBOutlet private weak var flipCountLabel: UILabel!{
didSet{
updateFlipLabel()
}
}
@IBOutlet private var cardButtons: [UIButton]!
@IBAction private func touchCard(_ sender: UIButton) {
flipNumber += 1
if let cardNumber = cardButtons.index(of: sender){
game.chooseCard(at : cardNumber )
updateViewFromModel()
}
}
private func updateViewFromModel(){
if cardButtons != nil {
for index in cardButtons.indices {
let button = cardButtons[index]
let card = game.cards[index]
if card.isFaceUp{
button.setTitle(emoji(for:card) , for: UIControl.State.normal)
button.backgroundColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
}
else{
button.setTitle(" ", for: UIControl.State.normal)
button.backgroundColor = card.isMatched ? #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0) : #colorLiteral(red: 0.01680417731, green: 0.1983509958, blue: 1, alpha: 1)
}
}
}
}
// private var emojiChoices = ["🐍","🔮","🦇","🌓","🐀","🦉","👁","🎃","💀","🧟♀️"]
var theme: String?{
didSet{
emojiChoices = theme ?? ""
emoji = [:]
updateViewFromModel()
}
}
private var emojiChoices = "🐍🔮🦇🌓🐀🦉👁🎃💀🧟♀️"
private var emoji = [Card:String]()
private func emoji (for card : Card)->String{
if emoji[card] == nil, emojiChoices.count > 0 {
let randomStringIndex = emojiChoices.index(emojiChoices.startIndex, offsetBy:emojiChoices.count.arc4random)
emoji[card] = String(emojiChoices.remove(at: randomStringIndex))
}
return emoji[card] ?? "?"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension Int {
var arc4random: Int {
if self > 0{
return Int(arc4random_uniform(UInt32(self)))
}
else if self < 0 {
return -Int(arc4random_uniform(UInt32(abs(self))))
}
else {
return 0
}
}
}
| true
|
4db384c99ef0f9a848c7a53080495a5215fcbf42
|
Swift
|
ivabra/MKUnits
|
/MKUnits/Classes/TimeUnit.swift
|
UTF-8
| 7,300
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// TimeUnit.swift
// MKUnits
//
// Copyright (c) 2016 Michal Konturek <michal.konturek@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public final class TimeUnit: Unit {
/**
Returns century `[c]` time unit.
- author: Michal Konturek
*/
public static var century: TimeUnit {
return TimeUnit(
name: "century",
symbol: "c",
ratio: NSDecimalNumber(mantissa: 31557600, exponent: 2, isNegative: false)
)
}
/**
Returns decade `[dec]` time unit.
- author: Michal Konturek
*/
public static var decade: TimeUnit {
return TimeUnit(
name: "decade",
symbol: "dec",
ratio: NSDecimalNumber(mantissa: 31557600, exponent: 1, isNegative: false)
)
}
/**
Returns year `[y]` time unit.
- author: Michal Konturek
*/
public static var year: TimeUnit {
return TimeUnit(
name: "year",
symbol: "y",
ratio: NSDecimalNumber(mantissa: 31557600, exponent: 0, isNegative: false)
)
}
/**
Returns month `[mo]` time unit.
- author: Michal Konturek
*/
public static var month: TimeUnit {
return TimeUnit(
name: "month",
symbol: "mo",
ratio: NSDecimalNumber(mantissa: 2592000, exponent: 0, isNegative: false)
)
}
/**
Returns week `[wk]` time unit.
- author: Michal Konturek
*/
public static var week: TimeUnit {
return TimeUnit(
name: "week",
symbol: "wk",
ratio: NSDecimalNumber(mantissa: 604800, exponent: 0, isNegative: false)
)
}
/**
Returns day `[d]` time unit.
- author: Michal Konturek
*/
public static var day: TimeUnit {
return TimeUnit(
name: "day",
symbol: "d",
ratio: NSDecimalNumber(mantissa: 86400, exponent: 0, isNegative: false)
)
}
/**
Returns hour `[h]` time unit.
- author: Michal Konturek
*/
public static var hour: TimeUnit {
return TimeUnit(
name: "hour",
symbol: "h",
ratio: NSDecimalNumber(mantissa: 3600, exponent: 0, isNegative: false)
)
}
/**
Returns minute `[m]` time unit.
- author: Michal Konturek
*/
public static var minute: TimeUnit {
return TimeUnit(
name: "minute",
symbol: "m",
ratio: NSDecimalNumber(mantissa: 60, exponent: 0, isNegative: false)
)
}
/**
Returns second `[s]` time unit.
- author: Michal Konturek
*/
public static var second: TimeUnit {
return TimeUnit(
name: "second",
symbol: "s",
ratio: NSDecimalNumber.one
)
}
/**
Returns millisecond `[ms]` time unit.
- author: Michal Konturek
*/
public static var millisecond: TimeUnit {
return TimeUnit(
name: "millisecond",
symbol: "ms",
ratio: NSDecimalNumber(mantissa: 1, exponent: -3, isNegative: false)
)
}
/**
Returns microsecond `[μs]` time unit.
- author: Michal Konturek
*/
public static var microsecond: TimeUnit {
return TimeUnit(
name: "microsecond",
symbol: "μs",
ratio: NSDecimalNumber(mantissa: 1, exponent: -6, isNegative: false)
)
}
/**
Returns nanosecond `[ns]` time unit.
- author: Michal Konturek
*/
public static var nanosecond: TimeUnit {
return TimeUnit(
name: "nanosecond",
symbol: "ns",
ratio: NSDecimalNumber(mantissa: 1, exponent: -9, isNegative: false)
)
}
}
extension NSNumber {
/**
Returns instance converted as century quantity.
- author: Michal Konturek
*/
public func century() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.century)
}
/**
Returns instance converted as decade quantity.
- author: Michal Konturek
*/
public func decade() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.decade)
}
/**
Returns instance converted as year quantity.
- author: Michal Konturek
*/
public func year() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.year)
}
/**
Returns instance converted as month quantity.
- author: Michal Konturek
*/
public func month() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.month)
}
/**
Returns instance converted as week quantity.
- author: Michal Konturek
*/
public func week() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.week)
}
/**
Returns instance converted as day quantity.
- author: Michal Konturek
*/
public func day() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.day)
}
/**
Returns instance converted as hour quantity.
- author: Michal Konturek
*/
public func hour() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.hour)
}
/**
Returns instance converted as minute quantity.
- author: Michal Konturek
*/
public func minute() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.minute)
}
/**
Returns instance converted as second quantity.
- author: Michal Konturek
*/
public func second() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.second)
}
/**
Returns instance converted as millisecond quantity.
- author: Michal Konturek
*/
public func millisecond() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.millisecond)
}
/**
Returns instance converted as microsecond quantity.
- author: Michal Konturek
*/
public func microsecond() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.microsecond)
}
/**
Returns instance converted as nanosecond quantity.
- author: Michal Konturek
*/
public func nanosecond() -> Quantity {
return Quantity(amount: self, unit: TimeUnit.nanosecond)
}
}
| true
|
8ddfe1bb34a7628bdf347eeb216ce8b4f05c020d
|
Swift
|
kookmincapstone2/IKIK_iOS
|
/IK IK/IK IK/Controller/Main/AttendanceViewController.swift
|
UTF-8
| 4,312
| 2.640625
| 3
|
[] |
no_license
|
//
// AttendanceViewController.swift
// IK IK
//
// Created by 서민주 on 2020/10/16.
// Copyright © 2020 minjuseo. All rights reserved.
//
import UIKit
class AttendanceViewController: UIViewController, UITableViewDataSource {
var userId: String?
var roomData: Room?
var dates = [String]()
var images = [String?]()
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
@IBOutlet weak var attendanceRateLabel: UILabel!
@IBOutlet weak var editBarButtonItem: UIBarButtonItem!
@IBOutlet weak var tableView: UITableView!
let networkingService = NetworkingService()
override func viewDidLoad() {
super.viewDidLoad()
if let rank = UserDefaults.standard.string(forKey: "rank"), rank == "teacher" {
self.navigationItem.rightBarButtonItem = nil
} else {
self.navigationItem.rightBarButtonItem = self.editBarButtonItem
userId = UserDefaults.standard.string(forKey: "userid")
}
titleLabel.text = roomData?.title
detailLabel.text = roomData?.inviteCode
if let roomId = roomData?.roomId {
getAttendances(userId: userId!, roomId: String(roomId))
}
}
func getAttendances(userId: String, roomId: String) {
let parameters = ["user_id": userId, "room_id": roomId]
networkingService.request(endpoint: "/room/attendance/check/all", parameters: parameters, completion: { [weak self] (result) in
print(result)
switch result {
case .success(let attendanceDict):
for (date, isChecked) in attendanceDict![0] as! [String:Bool] {
self?.dates.append(date)
let image: String = isChecked ? "checkmark.circle" : "xmark.circle"
self?.images.append(image)
}
self?.tableView.reloadData()
self?.updateRate()
case .failure(let error):
self?.dates = []
self?.images = []
print("getting student list error", error) // did not enter any room yet
break
}
})
}
func updateRate() {
let days = images.filter { $0 == "checkmark.circle" }.count
let total = dates.count
let rate = round(Double(days * 100) / Double(total) * 10) / 10
attendanceRateLabel.text = "출석율 \(days)/\(total) ( \(rate)% )"
}
// MARK: - tableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dates.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AttendanceCell", for: indexPath) as! AttendanceCell
let date = dates[indexPath.row]
let image = images[indexPath.row]
cell.dateLabel.text = date
cell.attendanceImageView.image = UIImage(systemName: image!)
switch image {
case "xmark.circle":
cell.attendanceImageView.tintColor = UIColor.systemRed
// case "ellipsis.circle":
// cell.attendanceImageView.image = UIImage(systemName: "ellipsis.circle")
// cell.attendanceImageView.tintColor = UIColor.systemGray4
default:
break
}
return cell
}
// func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// return true
// }
//
// func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// if (editingStyle == .delete) {
// // handle delete (by removing the data from your array and updating the tableview)
// }
// }
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "editView" {
let destination = segue.destination as! RoomEditViewController
destination.roomData = roomData
}
}
}
| true
|
673c1f43a992e72887d38b1f513b540f478f256c
|
Swift
|
jonasman/TeslaSwift
|
/Sources/TeslaSwift/Model/WindowControlCommandOptions.swift
|
UTF-8
| 677
| 3
| 3
|
[
"MIT"
] |
permissive
|
//
// WindowControlCommandOptions.swift
// TeslaSwift
//
// Created by Joao Nunes on 19/10/2019.
// Copyright © 2019 Joao Nunes. All rights reserved.
//
import Foundation
import CoreLocation
public enum WindowState: String, Codable {
case close
case vent
}
open class WindowControlCommandOptions: Encodable {
open var latitude: CLLocationDegrees = 0
open var longitude: CLLocationDegrees = 0
open var command: WindowState
public init(command: WindowState) {
self.command = command
}
enum CodingKeys: String, CodingKey {
case latitude = "lat"
case longitude = "lon"
case command = "command"
}
}
| true
|
1441c0f328280cba1f4a5006a67e4d0b826ec8ec
|
Swift
|
Arpit-Soft/SwiftUI-CoffeeOrdering_App
|
/SwiftUI-CoffeeOrdering_App/Views/OrderListView.swift
|
UTF-8
| 1,943
| 3.15625
| 3
|
[] |
no_license
|
//
// OrderListView.swift
// SwiftUI-CoffeeOrdering_App
//
// Created by Arpit Dixit on 26/06/21.
//
import SwiftUI
struct OrderListView: View {
var orders: [OrderViewModel]
init(orders: [OrderViewModel]) {
self.orders = orders
}
var body: some View {
List(self.orders, id: \.id) { order in
HStack {
Image(order.coffeeName)
.resizable()
.frame(width: 100, height: 100)
.cornerRadius(20)
VStack(alignment: .leading, spacing: /*@START_MENU_TOKEN@*/nil/*@END_MENU_TOKEN@*/, content: {
Text(order.name)
.font(.title)
.foregroundColor(.primary)
HStack {
Text(order.coffeeName)
.padding(EdgeInsets(top: 7, leading: 10, bottom: 7, trailing: 10))
.font(.headline)
.background(Color(red: 68/255, green: 68/255, blue: 68/255))
.foregroundColor(.white)
Text(order.size)
.padding(EdgeInsets(top: 7, leading: 10, bottom: 7, trailing: 10))
.font(.headline)
.background(Color(red: 218/255, green: 0/255, blue: 55/255))
.foregroundColor(.white)
}
.padding([.top], 2)
})
}
}
.padding(0)
}
}
struct OrderListView_Previews: PreviewProvider {
static var previews: some View {
OrderListView(orders: [OrderViewModel(order: Order(name: "Mary", size: "Medium", coffeeName: "Regular", total: 3.0))])
}
}
| true
|
e26e30d07d2f65d17531a41548e294c6ea0ae423
|
Swift
|
linseb325/Engauge
|
/Engauge/Controller/TransactionListVC.swift
|
UTF-8
| 6,574
| 2.578125
| 3
|
[] |
no_license
|
//
// TransactionListVC.swift
// Engauge
//
// Created by Brennan Linse on 4/26/18.
// Copyright © 2018 Brennan Linse. All rights reserved.
//
// PURPOSE: View all transactions at the Admin's school.
import UIKit
import FirebaseDatabase
import FirebaseAuth
class TransactionListVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
// MARK: Outlets
@IBOutlet weak var searchBar: UISearchBar! { didSet { searchBar.delegate = self } }
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.dataSource = self
tableView.delegate = self
}
}
// MARK: Properties
// Storing transaction data
private var transactions = [Transaction]()
private var filteredTransactions: [Transaction]?
// Searching
private var searchOn: Bool { return searchText != nil }
private var searchText: String? {
didSet {
if searchOn {
applySearch()
} else {
filteredTransactions = nil
}
tableView.reloadData()
}
}
// For observing database events
private var schoolTransactionsRef: DatabaseReference?
private var schoolTransactionsChildAddedHandle: DatabaseHandle?
private var authStateListenerHandle: AuthStateDidChangeListenerHandle?
// MARK: View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
guard let currUser = Auth.auth().currentUser else {
// TODO: There's nobody signed in!
return
}
// Someone is signed in. Retrieve the transactions for his/her school.
DataService.instance.getSchoolIDForUser(withUID: currUser.uid) { (currUserSchoolID) in
if currUserSchoolID != nil {
self.schoolTransactionsRef = DataService.instance.REF_SCHOOL_TRANSACTIONS.child(currUserSchoolID!)
self.attachDatabaseObserver()
}
}
}
override func viewDidAppear(_ animated: Bool) {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: selectedIndexPath, animated: true)
}
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "toTransactionDetailsVC":
if let transactionScreen = segue.destination as? TransactionDetailsVC, let pickedTransaction = sender as? Transaction {
transactionScreen.transaction = pickedTransaction
}
default:
break
}
}
// MARK: Table View methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchOn ? (filteredTransactions?.count ?? 0) : transactions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("TransactionTableViewCell", owner: self, options: nil)?.first as? TransactionTableViewCell
let currTransaction = (searchOn ? filteredTransactions! : transactions)[indexPath.row]
cell?.configureCell(transaction: currTransaction, forVCWithTypeName: "TransactionListVC")
return cell ?? UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "toTransactionDetailsVC", sender: (searchOn ? self.filteredTransactions! : self.transactions)[indexPath.row])
}
// MARK: Search Bar methods
// Clears out the existing search text when the user erases all of the text in the search bar.
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchText.isEmpty {
self.searchText = nil
}
}
// User tapped "Search." Sets the search text to whatever the user typed in the bar.
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
dismissKeyboard()
guard let search = searchBar.text, !search.isEmpty else {
// Searched without typing anything in the search bar.
searchText = nil
return
}
searchText = search
}
// User tapped "Cancel" on the search bar. Resets the search bar's text to reflect the current search.
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = searchText
dismissKeyboard()
}
// Show the cancel button when the keyboard is visible.
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
// Hide the cancel button when the keyboard is not visible.
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
}
private func applySearch() {
// Searching by TID
if searchOn {
self.filteredTransactions = self.transactions.filter { $0.transactionID.lowercased().contains(searchText!.lowercased()) }
}
}
// MARK: Observing Database Events
/** Assumes that self.schoolTransactionsRef is already set. */
private func attachDatabaseObserver() {
// A new transaction occurred
self.schoolTransactionsChildAddedHandle = self.schoolTransactionsRef?.observe(.childAdded) { [weak self] (snapshot) in
DataService.instance.getTransaction(withID: snapshot.key) { (addedTransaction) in
if addedTransaction != nil {
self?.transactions.insert(addedTransaction!, at: 0)
self?.transactions.sort { $0.timestamp > $1.timestamp }
self?.applySearch()
self?.tableView.reloadData()
}
}
}
}
// MARK: Removing Observers
private func removeDatabaseObserversIfNecessary() {
if self.schoolTransactionsChildAddedHandle != nil {
schoolTransactionsRef?.removeObserver(withHandle: schoolTransactionsChildAddedHandle!)
}
}
// MARK: Deinitializer
deinit {
print("Deallocating an instance of TransactionListVC")
removeDatabaseObserversIfNecessary()
}
}
| true
|
bf5cae3bf5b51785e93f16382b7cdc65ddbcdae7
|
Swift
|
qixin1106/LearnSwiftUI
|
/LearnSwiftUI/LearnSwiftUI/Demo/Text/LSTextView.swift
|
UTF-8
| 3,231
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
//
// LSTextView.swift
// LearnSwiftUI
//
// Created by Qixin on 2021/6/8.
//
import SwiftUI
struct LSTextView: View {
var body: some View {
VStack {
Text("Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!")
//字体设置
.font(.largeTitle)
//大小设置
.frame(minWidth: 64, idealWidth: 128, maxWidth: 256, minHeight: 64, idealHeight: 128, maxHeight: 128, alignment: .center)
//文字颜色
.foregroundColor(Color.red)
//背景颜色
.background(Color.black)
//填充内边距,如CSS
.padding(20)
//行间距
.lineSpacing(10.0)
Text("Hello, World!Hello, World!Hello, World!Hello, World!")
//设置自定义字体大小
.font(.system(size: 20))
.frame(width: 100, height: 100, alignment: .center)
.foregroundColor(Color.green)
.background(Color.black)
//单独设置内边距
.padding(EdgeInsets(top: 20, leading: 0, bottom: 0, trailing: 0))
//截断模式,如UIKit
.truncationMode(.tail)
Text("Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!")
.foregroundColor(Color.purple)
.background(Color.black)
.lineLimit(2)
.frame(width: 256)
.font(.system(size: 20))
//超长之后比例缩放,如UIKit
.minimumScaleFactor(0.5)
//转大小写
.textCase(.uppercase)
Text("Hello World")
.italic()
.redacted(reason: .placeholder)
Text("Hello World")
.bold()
.italic()
/**
public static let ultraLight: Font.Weight
public static let thin: Font.Weight
public static let light: Font.Weight
public static let regular: Font.Weight
public static let medium: Font.Weight
public static let semibold: Font.Weight
public static let bold: Font.Weight
public static let heavy: Font.Weight
public static let black: Font.Weight
*/
/**
case `default`
@available(watchOS 7.0, *)
case serif
case rounded
@available(watchOS 7.0, *)
case monospaced
*/
Text("Hello World")
.font(.system(size: 20, weight: Font.Weight.black, design: Font.Design.monospaced))
}
}
}
struct LSTextView_Previews: PreviewProvider {
static var previews: some View {
LSTextView()
}
}
| true
|
842d2a7d056ebc67f30eb985a37d6a153bf26ac7
|
Swift
|
JS1993/Swift_Sina
|
/Swift_Sina/Swift_Sina/Classes/Publish/JSPlaceHolderTextView.swift
|
UTF-8
| 987
| 2.625
| 3
|
[] |
no_license
|
//
// JSPlaceHolderTextView.swift
// Swift_Sina
//
// Created by 江苏 on 16/8/14.
// Copyright © 2016年 Hunter. All rights reserved.
//
import UIKit
import SnapKit
class JSPlaceHolderTextView: UITextView {
lazy var placeHolderLabel : UILabel = UILabel()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpUI()
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
// MARK: - 设置UI
extension JSPlaceHolderTextView{
private func setUpUI() {
addSubview(placeHolderLabel)
placeHolderLabel.snp_makeConstraints { (make) in
make.top.equalTo(8)
make.left.equalTo(7)
}
placeHolderLabel.textColor = UIColor.lightGrayColor()
placeHolderLabel.font = font
placeHolderLabel.text = "分享新鲜事..."
textContainerInset = UIEdgeInsets(top: 8, left: 4, bottom: 8, right: 4)
}
}
| true
|
5e5df4b84396200982de9fc0683bd26ba8f249cb
|
Swift
|
DarmBeene/GuoAltas
|
/AtalasDream/TownsController.swift
|
UTF-8
| 3,393
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// TownsController.swift
// AtalasDream
//
// Created by GuoGongbin on 7/4/17.
// Copyright © 2017 GuoGongbin. All rights reserved.
//
import UIKit
private let cellId = "cellId"
class TownsController: UITableViewController {
var towns = [String]()
var townsConstant = [String]()
// var alphabeticTowns = [[String]]()
// var sectionTitles = [String]()
let searchController: UISearchController = {
let sc = UISearchController(searchResultsController: nil)
sc.dimsBackgroundDuringPresentation = false
return sc
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "选择城市"
setupNaviBarButtons()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
loadData()
searchController.searchResultsUpdater = self
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
}
deinit {
self.searchController.view.removeFromSuperview()
}
func setupNaviBarButtons() {
}
func loadData() {
if let filepath = Bundle.main.path(forResource: "towns", ofType: "plist") {
towns = NSArray(contentsOfFile: filepath) as! [String]
townsConstant = towns
// var preInitial: Character? = nil
// for town in towns {
// let initial = town.characters.first
// if initial != preInitial {
// alphabeticTowns.append([])
// preInitial = initial
// sectionTitles.append(String(initial!))
// }
// alphabeticTowns[alphabeticTowns.count - 1].append(town)
// }
// townsConstant = alphabeticTowns
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return towns.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
cell.textLabel?.text = towns[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
pushToUniversityController(indexPath: indexPath)
}
func pushToUniversityController(indexPath: IndexPath) {
let vc = UniversityController()
vc.town = towns[indexPath.row]
// vc.town = alphabeticTowns[indexPath.section][indexPath.row]
navigationController?.pushViewController(vc, animated: true)
}
}
extension TownsController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
let text = searchController.searchBar.text?.lowercased()
if text != nil && text != "" {
self.towns = townsConstant.filter { $0.lowercased().contains(text!) }
self.tableView.reloadData()
}
if text == "" {
self.towns = townsConstant
self.tableView.reloadData()
}
}
}
| true
|
6d1dd41b4f1ad640adbec39fba2ca5f5a159b967
|
Swift
|
james-learns-to-code/SwiftUtility
|
/UIColor+Fill.swift
|
UTF-8
| 371
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// UIColor+Fill.swift
// SwiftUtilityKit
//
// Created by dongseok lee on 2019/12/15.
//
import Foundation
public extension UIColor {
func filledImage(frame: CGRect) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: frame.size)
return renderer.image { context in
set()
context.cgContext.fill(frame)
}
}
}
| true
|
77961188f8aac7f365a22344b7a156b16cc152e0
|
Swift
|
IsaAliev/FlexibleNetworkLayer
|
/FlexibleNetworkLayer/NetworkLayer/RequestPreparators/MarvelRequestPreparator.swift
|
UTF-8
| 696
| 2.5625
| 3
|
[] |
no_license
|
//
// MarvelRequestPreparator.swift
// FlexibleNetworkLayer
//
// Created by Isa Aliev on 26.03.18.
// Copyright © 2018 IA. All rights reserved.
//
import Foundation
struct MarvelRequestPreparator: RequestPreparator {
func prepareRequest(_ request: inout HTTPRequestRepresentable) {
let timeStampString = String(Date().timeIntervalSince1970)
let stringToMakeHashFrom = timeStampString + APIStrings.APIKey.marvelPrivateKey + APIStrings.APIKey.marvelPublicKey
request.parameters?["ts"] = timeStampString
request.parameters?["apikey"] = APIStrings.APIKey.marvelPublicKey
request.parameters?["hash"] = stringToMakeHashFrom.MD5String()
}
}
| true
|
04b9cdc46bc435e8952c5f46380168c62ddeb9a8
|
Swift
|
vfxdrummer/jwplayer-sdk-ios-demo
|
/WolfCore/WolfCore/Sources-Foundation/DescriptiveError.swift
|
UTF-8
| 498
| 2.609375
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
//
// DescriptiveError.swift
// WolfCore
//
// Created by Wolf McNally on 12/3/16.
// Copyright © 2016 Arciem. All rights reserved.
//
import Foundation
public protocol DescriptiveError: Error, CustomStringConvertible {
/// A human-readable error message.
var message: String { get }
/// A numeric code for the error.
var code: Int { get }
/// A non-user-facing identifier used for automated UI testing
var identifier: String { get }
var isCancelled: Bool { get }
}
| true
|
8779107f3a5a65b37c19ab00e1d4de9c638eab8d
|
Swift
|
toastersocks/Ratios
|
/Ratios/OnboardingViewController.swift
|
UTF-8
| 891
| 2.8125
| 3
|
[] |
no_license
|
//
// OnboardingViewController.swift
// Ratios
//
// Created by Justin Reed on 4/7/18.
// Copyright © 2018 James Pamplona. All rights reserved.
//
import UIKit
enum ChallengeAnswer: Int {
case minorOrUnanswered = 0
case over21 = 1
}
class OnboardingViewController: UIViewController, StoryboardInitializable {
weak var delegate: OnboardingViewDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.isNavigationBarHidden = true
}
@IBAction func answeredMinor() {
delegate?.challengeAnswered(answer: .minorOrUnanswered)
}
@IBAction func answeredOver21() {
navigationController?.isNavigationBarHidden = false
delegate?.challengeAnswered(answer: .over21)
}
}
| true
|
bcd07ecec1055cb69bb2b9c1d9178718b3f88f74
|
Swift
|
guilhermerosa/sample-themoviedb
|
/TheMovieDB/TheMovieDB/Features/Views/Builders/CollectionCell/MovieErrorCollectionCellBuilder.swift
|
UTF-8
| 852
| 2.625
| 3
|
[] |
no_license
|
//
// MovieErrorCollectionCellBuilder.swift
// ChallengeCIEC
//
// Created by Guilherme Camilo Rosa on 26/07/19.
// Copyright © 2019 Guilherme Rosa. All rights reserved.
//
import Foundation
import UIKit
class MovieErrorCollectionCellBuilder: CollectionCellBuilder {
private var error: String?
init(properties: CollectionCellBuilderProperties, error: String?) {
super.init(properties: properties, identifier: "MovieErrorCollectionCell")
self.error = error
}
override func getCell() -> UICollectionViewCell {
let cell = self.collection.dequeueReusableCell(withReuseIdentifier: self.identifier,
for: self.indexPath) as! MovieErrorCollectionCell
if let err = self.error {
cell.setup(error: err)
}
return cell
}
}
| true
|
244961fcb8031885c2e70218dc2329b10b1a2624
|
Swift
|
guseulalio/SentiaRealState
|
/SentiaRealEstate/SentiaRealEstate/Support/FormFactor.swift
|
UTF-8
| 1,113
| 3.609375
| 4
|
[] |
no_license
|
//
// FormFactor.swift
// WindowShape
//
// Created by Gustavo E M Cabral on 7/3/21.
//
import SwiftUI
/// Roughly represents different form factors of the screen.
enum FormFactor
{
case tall // , split screen (compact)
case flat //
case fat // (portrait or landscape, full screen)
case other
}
extension EnvironmentValues
{
/// Analyses different variables to fit the representation into the FormFactor enum.
var formFactor: FormFactor
{
get {
let idiom = UIDevice.current.userInterfaceIdiom
switch idiom {
case .phone:
if horizontalSizeClass == . compact
{ return .tall }
else
{ return .flat }
case .pad:
if horizontalSizeClass == . compact
{ return .tall }
else
{ return .fat }
default:
return .other
}
}
set { }
}
}
extension View
{
/// Adds the FormFactor variable to the environment of the view.
/// - Parameter formFactor: Device's form factor
/// - Returns: A view with the environment value.
func formFactor(_ formFactor: FormFactor) -> some View
{
self.environment(\.formFactor, formFactor)
}
}
| true
|
3b821dd75ceb7dcdf625d78ecdeca3c80633b643
|
Swift
|
liguoliangiOS/ZZBaseKit
|
/ZZBaseKit/BaseKit/Tools/QRCodeImage.swift
|
UTF-8
| 3,564
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// QRCodeImage.swift
// ZZbaseKitTestDemo
//
// Created by Passer on 2019/5/28.
// Copyright © 2019 ZZbaseKitTestDemo. All rights reserved.
//
import UIKit
import CoreImage
///生成二维码
class QRCodeImage: NSObject {
///传入二维码的内容
class func qr_generateQR(content: String) -> CIImage? {
if content.count > 0 {
let filter = CIFilter.init(name: "CIQRCodeGenerator")
filter?.setDefaults()
let imageData = content.data(using: .utf8, allowLossyConversion: true)
filter?.setValue(imageData, forKey: "inputMessage")
return filter?.outputImage
}
return nil
}
///给图片添加icon,并传入图片的宽高
class func qr_getImageWithIcon(_ qrImage: UIImage, _ iconImage:UIImage, _ iconWidth: CGFloat, _ iconHeight: CGFloat) -> UIImage{
UIGraphicsBeginImageContext(qrImage.size)
qrImage.draw(in: CGRect(origin: CGPoint.zero, size: qrImage.size))
let x = (qrImage.size.width - iconWidth) * 0.5
let y = (qrImage.size.height - iconHeight) * 0.5
iconImage.draw(in: CGRect(x: x, y: y, width: iconWidth, height: iconHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let newImage = newImage {
return newImage
}
return UIImage()
}
///生成指定尺寸的高清图片
class func qr_getHDImage(_ ciImage: CIImage, _ size: CGFloat) -> UIImage {
let integral: CGRect = ciImage.extent.integral
let proportion: CGFloat = min(size / integral.width, size / integral.height)
let width = integral.width * proportion
let height = integral.height * proportion
let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()
let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: 0)!
let context = CIContext(options: nil)
let bitmapImage: CGImage = context.createCGImage(ciImage, from: integral)!
bitmapRef.interpolationQuality = CGInterpolationQuality.none
bitmapRef.scaleBy(x: proportion, y: proportion);
bitmapRef.draw(bitmapImage, in: integral);
let image: CGImage = bitmapRef.makeImage()!
return UIImage(cgImage: image)
}
///给图片生成边框
class func qr_circleImage(_ sourceImage: UIImage, size:CGFloat, radius:CGFloat, borderWidth: CGFloat, borderColor: UIColor) -> UIImage {
let scale = sourceImage.size.width / size ;
//初始值
let defaultBorderWidth : CGFloat = borderWidth * scale
let defaultBorderColor = borderColor
let radius = radius * scale
let react = CGRect(x: defaultBorderWidth, y: defaultBorderWidth, width: sourceImage.size.width - 2 * defaultBorderWidth, height: sourceImage.size.height - 2 * defaultBorderWidth)
//绘制图片设置
UIGraphicsBeginImageContextWithOptions(sourceImage.size, false, UIScreen.main.scale)
let path = UIBezierPath(roundedRect:react , cornerRadius: radius)
//绘制边框
path.lineWidth = defaultBorderWidth
defaultBorderColor.setStroke()
path.stroke()
path.addClip()
//画图片
sourceImage.draw(in: react)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!;
}
}
| true
|
441e40e2c9699d48b77e8a09c40c08c30a8434ff
|
Swift
|
ademozay/SwiftMandrill
|
/SwiftMandrill/Util/ObjectParser.swift
|
UTF-8
| 1,259
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// ObjectParser.swift
// SwiftMandrill
//
// Created by Christopher Jimenez on 1/20/16.
// Copyright © 2016 greenpixels. All rights reserved.
//
import Foundation
import ObjectMapper
open class ObjectParser
{
/**
Converts and parse and object from a json file for testing
- parameter fileName: file name
- returns: object conforming to Mappable
*/
open class func objectFromJson<T: Mappable>(_ json: AnyObject?) -> T? {
return Mapper<T>().map(JSON: json as! [String : Any])
}
/**
Converts and parse and object from a json string
- parameter json: String
- returns:
*/
open class func objectFromJsonString<T: Mappable>(_ json: String?) -> T? {
if let _json = json {
return Mapper<T>().map(JSONString: _json)
}
return nil
}
/**
Converts and parse and object to an array
- parameter fileName: filename
- returns: array of objects
*/
open class func objectFromJsonArray<T: Mappable>(_ json: AnyObject?) -> [T]? {
if let _json = json as? [[String : Any]] {
return Mapper<T>().mapArray(JSONArray: _json)
}
return nil
}
}
| true
|
37f4d6afd055daeb52ce924b416a256e9a2c7cf0
|
Swift
|
sushantubale/iOSRepo
|
/Getter Setter/Getter Setter/ViewController.swift
|
UTF-8
| 770
| 3.234375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Getter Setter
//
// Created by Sushant Ubale on 11/18/18.
// Copyright © 2018 Sushant Ubale. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var adddButton: UIButton!
var myValue: Double {
get {
return Double(myLabel.text!)!
}
set {
myLabel.text = "\(newValue)"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func addButtonclicked(_ sender: UIButton) {
add()
}
func add() {
myValue = myValue + 2
}
}
| true
|
bb7398cd4c0f7452d0e753880d160751a75e8991
|
Swift
|
PWhittle86/FootballFinder
|
/HungrrrTechTest/View Controllers/FavouritesViewController/FavouritesTableViewController.swift
|
UTF-8
| 3,756
| 2.71875
| 3
|
[] |
no_license
|
//
// FavouritesTableViewController.swift
// HungrrrTechTest
//
// Created by Peter Whittle on 13/09/2020.
// Copyright © 2020 Whittle Productions. All rights reserved.
//
import UIKit
import RealmSwift
class FavouritesTableViewController: UITableViewController {
let db = DBUtility.sharedInstance
var favouritePlayers: Results<FavouritePlayer>?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setUpTableview()
getFavouritePlayerData()
}
//MARK: Setup Functions
func setupUI() {
self.title = "Favourite Players"
}
func getFavouritePlayerData() {
self.favouritePlayers = db.getAllFavouritePlayers()
}
func setUpTableview() {
tableView.register(UINib(nibName: TableViewCellIdentifier.playerCell, bundle: nil),
forCellReuseIdentifier: TableViewCellIdentifier.playerCell)
tableView.register(UINib(nibName: TableViewCellIdentifier.genericCell, bundle: nil),
forCellReuseIdentifier: TableViewCellIdentifier.genericCell)
}
//MARK: Tableview Delegate Functions
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let players = favouritePlayers else { return 1 }
//If players array is empty, return 1 row for the No Data cell.
return players.isEmpty ? 1 : players.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let players = favouritePlayers else { return UITableViewCell() }
if players.isEmpty {
//Show generic cell with a label indicating no favourites saved on device.
guard let genericCell = tableView.dequeueReusableCell(withIdentifier: TableViewCellIdentifier.genericCell,
for: indexPath) as? GenericTableViewCell else { return UITableViewCell() }
genericCell.centerLabel.text = "No Favourites saved!"
return genericCell
} else {
//Show player cell.
guard let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCellIdentifier.playerCell,
for: indexPath) as? PlayerTableViewCell else { return UITableViewCell() }
let player = players[indexPath.row]
cell.populatePlayerData(name: "\(player.firstName) \(player.secondName)",
age: "\(player.age)",
club: "\(player.club)")
cell.showDoubleLeftImage()
return cell
}
}
//Standard iOS swipe tableview cell left to expose delete button and tap to delete.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
guard let players = self.favouritePlayers else { return }
if !players.isEmpty{
let player = players[indexPath.row]
db.deleteFavouritePlayer(playerID: player.ID)
DispatchQueue.main.async {
if players.count >= 1 {
tableView.deleteRows(at: [indexPath], with: .fade)
} else {
tableView.reloadData()
}
}
}
}
}
}
| true
|
85699be00837cfad38075464eb37b17a89d9d13d
|
Swift
|
jburgoyn/pokedex
|
/pokedex/PokeCell.swift
|
UTF-8
| 841
| 3.078125
| 3
|
[] |
no_license
|
//
// PokeCell.swift
// pokedex
//
// Created by Jonny B on 12/18/15.
// Copyright © 2015 Jonny B. All rights reserved.
//
import UIKit
// This file contains the information for each collection cell template.
class PokeCell: UICollectionViewCell {
// These are the variable for each item inside each cell.
@IBOutlet weak var thumbImg: UIImageView!
@IBOutlet weak var nameLbl: UILabel!
// Store a class Pokemon item.
var pokemon: Pokemon!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.cornerRadius = 5.0
}
func configureCell(pokemon: Pokemon) {
self.pokemon = pokemon
nameLbl.text = self.pokemon.name.capitalizedString
thumbImg.image = UIImage(named: "\(self.pokemon.pokedexId)")
}
}
| true
|
c3c3a07143fe921e7ac9a3a72c713aeeb566cd63
|
Swift
|
liudhzhyym/SoundFonts
|
/SoundFontsFramework/Core Data/Entities/AppState.swift
|
UTF-8
| 3,744
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
// Copyright © 2020 Brad Howes. All rights reserved.
import Foundation
import CoreData
@objc(AppState)
public final class AppState: NSManagedObject, Managed {
static var fetchRequest: FetchRequest {
let request = typedFetchRequest
request.returnsObjectsAsFaults = false
request.resultType = .managedObjectResultType
return request
}
@NSManaged private var lastUpdated: Date?
@NSManaged private var orderedFavorites: NSOrderedSet
@NSManaged public private(set) var activePreset: Preset?
}
extension AppState {
public static func get(context: NSManagedObjectContext) -> AppState {
if let appState: AppState = context.object(forSingleObjectCacheKey: "AppState") { return appState }
let appState = findOrCreate(in: context, request: typedFetchRequest) { _ in }
context.set(appState, forSingleObjectCacheKey: "AppState")
context.saveChangesAsync()
return appState
}
}
extension AppState {
public var favorites: EntityCollection<Favorite> { EntityCollection<Favorite>(orderedFavorites) }
public func createFavorite(preset: Preset, keyboardLowestNote: Int) -> Favorite {
guard let context = managedObjectContext else { fatalError() }
let fav = Favorite(in: context, preset: preset, keyboardLowestNote: keyboardLowestNote)
self.addToOrderedFavorites(fav)
context.saveChangesAsync()
return fav
}
public func deleteFavorite(favorite: Favorite) {
guard let context = managedObjectContext else { fatalError() }
self.removeFromFavorites(favorite)
favorite.delete()
context.saveChangesAsync()
}
public func move(favorite: Favorite, to newIndex: Int) {
guard let context = managedObjectContext else { fatalError() }
let oldIndex = self.orderedFavorites.index(of: favorite)
guard oldIndex != newIndex else { return }
guard let mutableFavorites = self.orderedFavorites.mutableCopy() as? NSMutableOrderedSet else { fatalError() }
mutableFavorites.moveObjects(at: IndexSet(integer: oldIndex), to: newIndex)
self.orderedFavorites = mutableFavorites
context.saveChangesAsync()
}
}
extension AppState {
public func setActive(preset: Preset?) {
guard let context = managedObjectContext else { fatalError() }
self.activePreset?.setActivated(nil)
self.activePreset = preset
preset?.setActivated(self)
context.saveChangesAsync()
}
}
private extension AppState {
@objc(insertObject:inOrderedFavoritesAtIndex:)
@NSManaged func insertIntoOrderedFavorites(_ value: Favorite, at idx: Int)
@objc(removeObjectFromOrderedFavoritesAtIndex:)
@NSManaged func removeFromOrderedFavorites(at idx: Int)
@objc(insertOrderedFavorites:atIndexes:)
@NSManaged func insertIntoOrderedFavorites(_ values: [Favorite], at indexes: NSIndexSet)
@objc(removeOrderedFavoritesAtIndexes:)
@NSManaged func removeFromOrderedFavorites(at indexes: NSIndexSet)
@objc(replaceObjectInOrderedFavoritesAtIndex:withObject:)
@NSManaged func replaceOrderedFavorites(at idx: Int, with value: Favorite)
@objc(replaceOrderedFavoritesAtIndexes:withFavorites:)
@NSManaged func replaceOrderedFavorites(at indexes: NSIndexSet, with values: [Favorite])
@objc(addOrderedFavoritesObject:)
@NSManaged func addToOrderedFavorites(_ value: Favorite)
@objc(removeOrderedFavoritesObject:)
@NSManaged func removeFromFavorites(_ value: Favorite)
@objc(addOrderedFavorites:)
@NSManaged func addToOrderedFavorites(_ values: NSOrderedSet)
@objc(removeOrderedFavorites:)
@NSManaged func removeFromFavorites(_ values: NSOrderedSet)
}
| true
|
6f6af4f376046da791017b1e93d73f0fbb948831
|
Swift
|
malhal/Kraftstoff
|
/Classes/Formatters.swift
|
UTF-8
| 5,511
| 2.59375
| 3
|
[
"Zlib"
] |
permissive
|
//
// Formatters.swift
// kraftstoff
//
// Created by Ingmar Stein on 01.05.15.
//
//
import UIKit
final class Formatters {
static let sharedLongDateFormatter : NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
dateFormatter.dateStyle = .LongStyle
return dateFormatter
}()
static let sharedDateFormatter : NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .NoStyle
dateFormatter.dateStyle = .MediumStyle
return dateFormatter
}()
static let sharedDateTimeFormatter : NSDateFormatter = {
let dateTimeFormatter = NSDateFormatter()
dateTimeFormatter.timeStyle = .ShortStyle
dateTimeFormatter.dateStyle = .MediumStyle
return dateTimeFormatter
}()
static let sharedDistanceFormatter : NSNumberFormatter = {
let distanceFormatter = NSNumberFormatter()
distanceFormatter.generatesDecimalNumbers = true
distanceFormatter.numberStyle = .DecimalStyle
distanceFormatter.minimumFractionDigits = 1
distanceFormatter.maximumFractionDigits = 1
return distanceFormatter
}()
static let sharedFuelVolumeFormatter : NSNumberFormatter = {
let fuelVolumeFormatter = NSNumberFormatter()
fuelVolumeFormatter.generatesDecimalNumbers = true
fuelVolumeFormatter.numberStyle = .DecimalStyle
fuelVolumeFormatter.minimumFractionDigits = 2
fuelVolumeFormatter.maximumFractionDigits = 2
return fuelVolumeFormatter
}()
static let sharedPreciseFuelVolumeFormatter : NSNumberFormatter = {
let preciseFuelVolumeFormatter = NSNumberFormatter()
preciseFuelVolumeFormatter.generatesDecimalNumbers = true
preciseFuelVolumeFormatter.numberStyle = .DecimalStyle
preciseFuelVolumeFormatter.minimumFractionDigits = 3
preciseFuelVolumeFormatter.maximumFractionDigits = 3
return preciseFuelVolumeFormatter
}()
// Standard currency formatter
static let sharedCurrencyFormatter : NSNumberFormatter = {
let currencyFormatter = NSNumberFormatter()
currencyFormatter.generatesDecimalNumbers = true
currencyFormatter.numberStyle = .CurrencyStyle
return currencyFormatter
}()
// Currency formatter with empty currency symbol for axis of statistic graphs
static let sharedAxisCurrencyFormatter : NSNumberFormatter = {
let axisCurrencyFormatter = NSNumberFormatter()
axisCurrencyFormatter.generatesDecimalNumbers = true
axisCurrencyFormatter.numberStyle = .CurrencyStyle
axisCurrencyFormatter.currencySymbol = ""
return axisCurrencyFormatter
}()
// Currency formatter with empty currency symbol and one additional fractional digit - used for active textfields
static let sharedEditPreciseCurrencyFormatter : NSNumberFormatter = {
var fractionDigits = sharedCurrencyFormatter.maximumFractionDigits
// Don't introduce fractional digits if the currency has none
if fractionDigits > 0 {
fractionDigits += 1
}
let editPreciseCurrencyFormatter = NSNumberFormatter()
editPreciseCurrencyFormatter.generatesDecimalNumbers = true
editPreciseCurrencyFormatter.numberStyle = .CurrencyStyle
editPreciseCurrencyFormatter.minimumFractionDigits = fractionDigits
editPreciseCurrencyFormatter.maximumFractionDigits = fractionDigits
editPreciseCurrencyFormatter.currencySymbol = ""
// Needed e.g. for CHF
editPreciseCurrencyFormatter.roundingIncrement = 0
// Needed since NSNumberFormatters can't parse their own € output
editPreciseCurrencyFormatter.lenient = true
return editPreciseCurrencyFormatter
}()
// Currency formatter with one additional fractional digit - used for inactive textfields
static let sharedPreciseCurrencyFormatter : NSNumberFormatter = {
var fractionDigits = sharedCurrencyFormatter.maximumFractionDigits
// Don't introduce fractional digits if the currency has none
if fractionDigits > 0 {
fractionDigits += 1
}
let preciseCurrencyFormatter = NSNumberFormatter()
preciseCurrencyFormatter.generatesDecimalNumbers = true
preciseCurrencyFormatter.numberStyle = .CurrencyStyle
preciseCurrencyFormatter.minimumFractionDigits = fractionDigits
preciseCurrencyFormatter.maximumFractionDigits = fractionDigits
// Needed e.g. for CHF
preciseCurrencyFormatter.roundingIncrement = 0
// Needed since NSNumberFormatters can't parse their own € output
preciseCurrencyFormatter.lenient = true
return preciseCurrencyFormatter
}()
// Rounding handler for computation of average consumption
static let sharedConsumptionRoundingHandler : NSDecimalNumberHandler = {
let fractionDigits = sharedFuelVolumeFormatter.maximumFractionDigits
return NSDecimalNumberHandler(
roundingMode: .RoundPlain,
scale: Int16(fractionDigits),
raiseOnExactness: false,
raiseOnOverflow: false,
raiseOnUnderflow: false,
raiseOnDivideByZero: false)
}()
// Rounding handler for precise price computations
static let sharedPriceRoundingHandler : NSDecimalNumberHandler = {
let fractionDigits = sharedEditPreciseCurrencyFormatter.maximumFractionDigits
return NSDecimalNumberHandler(
roundingMode: .RoundUp,
scale: Int16(fractionDigits),
raiseOnExactness: false,
raiseOnOverflow: false,
raiseOnUnderflow: false,
raiseOnDivideByZero: false)
}()
}
| true
|
ecf72f68c51a5aea01f867868a105818e86349c7
|
Swift
|
aaronfisher77/triviaToWin
|
/triviaToWin/ViewController.swift
|
UTF-8
| 9,266
| 3.1875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// triviaToWin
//
// Created by Aaron Fisher on 10/18/18.
// Copyright © 2018 Aaron Fisher. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var QuestionDisplay: UILabel!
@IBOutlet weak var AnswerADisplay: UIButton!
@IBOutlet weak var AnswerBDisplay: UIButton!
@IBOutlet weak var AnswerCDisplay: UIButton!
@IBOutlet weak var AnswerDDisplay: UIButton!
@IBOutlet weak var scoreLabel: UILabel!
var score = 0 {
didSet {
scoreLabel.text = "\(score) Points"
}
}
let backroundColors = [ // Creates different backround colors
UIColor(red: 177/255, green:183/255, blue: 188/255, alpha: 1.0),
UIColor(red: 150/255, green:158/255, blue:164/255, alpha: 1.0),
UIColor(red: 123/255, green:133/255, blue:140/255, alpha: 1.0),
UIColor(red: 91/255, green:103/255, blue:112/255, alpha: 1.0)]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
startQuestions()
getNewQuestion()
setnewColor()
TitleScreenViewController.quizPlayed += 1
}
var currentIndex: Int! // Allows for the variable currentIndex
var questionsPlaceHolder: [TriviaQuestion] = [] // sets a place holder for the questions when they have been answered
@IBAction func AnswerTapped(_ sender: UIButton) {
print(sender.tag)
if sender.tag == currentQuestion.correctAnswerIndex { // checks to see if the answer is correct
showCorrectAnswerAlert() // shows correct screen
score += 1 // adds to points
}else{
showIncorrectAnswerAlert() // shows incorrect screen if answer is wrong
}
}
func showCorrectAnswerAlert () {
let correctAnswerArray = ["Nice! You are correct!", "Wow, your pretty smart!", "How high is your IQ?", "Man on a scale of 1-10, you did great!", "That would be correct!"] // This in an array of Phases that tell the user they are correct
let correctrandomnumber = Int.random(in: 0..<correctAnswerArray.count) // Sets a random number
let correctAlert = UIAlertController(title: "Correct", message: correctAnswerArray[correctrandomnumber], preferredStyle: UIAlertController.Style.actionSheet) //Creates an alert witht the title of Correct then prints one of the randomly selected phrase in the Array
let okAction = UIAlertAction(title: "Thank You", style: UIAlertAction.Style.default) {UIAlertAction in // Creates a user interactable button to dismiss the alert
self.questionsPlaceHolder.append(self.TriviaQuestionsArray[self.currentIndex]) //Adds the question to the place holder array
self.TriviaQuestionsArray.remove(at: self.currentIndex)// Takes question out of the questionTriviaArray
self.getNewQuestion()// prepares the new question
}
correctAlert.addAction(okAction)
self.present(correctAlert, animated: true, completion: nil) // makes a smoother transition when the alert pops up
}
func showIncorrectAnswerAlert () {
let incorrectAnswerArray = ["Nope, thats incorrect.", "*beep*I'm sorry, the answer you have chose is incorrect*beep*", "On a scale of 1-10 that was very incorrect.", "Awe... so close... kind of..."] // This in an array of Phases that tell the user they are incorrect
let incorrectrandomnumber = Int.random(in: 0..<incorrectAnswerArray.count)
let incorrectAlert = UIAlertController(title: "Wrong", message: incorrectAnswerArray[incorrectrandomnumber], preferredStyle: UIAlertController.Style.actionSheet)//Creates an alert witht the title of "Wrong" then prints one of the randomly selected phrase in the Array
let okAction = UIAlertAction(title: "Thank You", style: UIAlertAction.Style.default) {UIAlertAction in // Creates a user interactable button to dismiss the alert
self.questionsPlaceHolder.append(self.TriviaQuestionsArray[self.currentIndex])//Adds the question to the place holder array
self.TriviaQuestionsArray.remove(at: self.currentIndex)// Takes question out of the questionTriviaArray
self.getNewQuestion()// prepares the new question
}
incorrectAlert.addAction(okAction)
self.present(incorrectAlert, animated: true, completion: nil)// makes a smoother transition when the alert pops up
}
func showGameOverAlert() {
let endAlert = UIAlertController(title: "Game Over", message: "Your final score was \(score)", preferredStyle: UIAlertController.Style.alert) // Creates alert
let resetAction = UIAlertAction(title: "Reset", style: UIAlertAction.Style.default) {UIAlertAction in
self.resetGame() // Resets the game
}
endAlert.addAction(resetAction)
self.present(endAlert, animated: true, completion: nil)// Makes a smoother transition when the alert pops up
}
var currentQuestion: TriviaQuestion! {
didSet {
if let currentQuestion = currentQuestion {
QuestionDisplay.text = currentQuestion.question // Show the new text visually after the code is changed
AnswerADisplay.setTitle(currentQuestion.answerArray[0], for: .normal)// Show the new text visually after the code is changed
AnswerBDisplay.setTitle(currentQuestion.answerArray[1], for: .normal)// Show the new text visually after the code is changed
AnswerCDisplay.setTitle(currentQuestion.answerArray[2], for: .normal)// Show the new text visually after the code is changed
AnswerDDisplay.setTitle(currentQuestion.answerArray[3], for: .normal)// Show the new text visually after the code is changed
setnewColor() // Sets different colors
}
}
}
func getNewQuestion(){
if TriviaQuestionsArray.count > 0 {
currentIndex = Int.random(in: 0..<TriviaQuestionsArray.count) // picks a random question from the Array
currentQuestion = TriviaQuestionsArray[currentIndex]
}else{
showGameOverAlert() // ends game when thereis no more questions left
}
}
var TriviaQuestionsArray: [TriviaQuestion] = [] // creates the array of original questions
@IBAction func resetButton(_ sender: Any) { // Resets the game
resetGame()
}
func startQuestions() {
let question1 = TriviaQuestion(question: "How many books are in the bible?", answerArray: ["7","77","66","1"], correctAnswerIndex: 2) // creates an instance of the first question
let question2 = TriviaQuestion(question: "Who was swallowed by a whale at sthe end of the old testiment?", answerArray: ["Moses","Judas","David","Jonah"], correctAnswerIndex: 3) // creates an instance of the second question
let question3 = TriviaQuestion(question: "Who betrayed Jesus in the story of The Last Supper?", answerArray: ["Judas","Jonah","Johnathan","Jimmy"], correctAnswerIndex: 0) // creates an instance of the third question
let question4 = TriviaQuestion(question: "What is it called when Jesus is reffered to as The Father, The Son, and The Holy Spirit?", answerArray: ["3 Musketeers","Tri-Gods" ,"Trinity" ,"Three Amigos"], correctAnswerIndex: 2) // creates an instance of the fourth question
let question5 = TriviaQuestion(question: "Which of the following is not a book of the bible?", answerArray: ["Habakkuk","David","Ruth","Nahum"], correctAnswerIndex: 1) // creates an instance of the fith question
// Adds the questions to the Array
TriviaQuestionsArray.append(question1)
TriviaQuestionsArray.append(question2)
TriviaQuestionsArray.append(question3)
TriviaQuestionsArray.append(question4)
TriviaQuestionsArray.append(question5)
}
func setnewColor() { // Sets a random number ti each color that are not the same number
let randomNumber = Int.random(in: 1...100)
let randomColorA = backroundColors[randomNumber % 4]
let randomColorB = backroundColors[(randomNumber + 2 ) % 4]
let randomColorC = backroundColors[(randomNumber + 3 ) % 4]
let randomColorD = backroundColors[(randomNumber + 1 ) % 4]
// Sets the random color to the answer options
AnswerADisplay.backgroundColor = randomColorA
AnswerBDisplay.backgroundColor = randomColorB
AnswerCDisplay.backgroundColor = randomColorC
AnswerDDisplay.backgroundColor = randomColorD
}
func resetGame() {
//need to call this everytime a new question is added and everytime the reset button is pushed
score = 0 // resets score to 0
if !TriviaQuestionsArray.isEmpty { // sets trivia question to all one array
questionsPlaceHolder.append(contentsOf: TriviaQuestionsArray)
}
TriviaQuestionsArray = questionsPlaceHolder
questionsPlaceHolder.removeAll() // removes all trivia question from the original screen
getNewQuestion()
}
}
| true
|
c40fe4dfc556f06e57cff2287f640075a4f37b70
|
Swift
|
ravisharmaa/Nepali-Calendar-POC
|
/CalendarPOC/Views/CollectionViewCells/DateCell.swift
|
UTF-8
| 1,851
| 3.015625
| 3
|
[] |
no_license
|
//
// DateCell.swift
// CalendarPOC
//
// Created by Ravi Bastola on 3/13/20.
// Copyright © 2020 Ravi Bastola. All rights reserved.
//
import UIKit
class DateCell: UICollectionViewCell {
//MARK:- SubViews
lazy var dateLabel: UILabel = {
let label = UILabel()
label.textColor = .label
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont(name: Font.YantramanavMedium.rawValue, size: 17)
return label
}()
lazy var containerView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
//MARK:- Properties
var date: Int? {
didSet {
self.dateLabel.text = "\(String(describing: self.date!))"
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(containerView)
containerView.addSubview(dateLabel)
containerView.layer.cornerRadius = (self.frame.height - 10 ) / 2
containerView.alpha = 1
NSLayoutConstraint.activate([
containerView.heightAnchor.constraint(equalToConstant: contentView.frame.height - 10),
containerView.widthAnchor.constraint(equalToConstant: contentView.frame.width - 10),
dateLabel.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
dateLabel.centerYAnchor.constraint(equalTo: containerView.centerYAnchor)
])
}
required init?(coder: NSCoder) {
fatalError()
}
func populate(date: Int) {
containerView.backgroundColor = (date == 1) ? .systemGray2 : .systemBackground
dateLabel.textColor = (date == 1 ) ? .tertiarySystemBackground : .label
self.date = date
}
}
| true
|
9c434c1af5dee82e366ff65a4e1a8967b3b8365e
|
Swift
|
devedbox/Sledge
|
/Sources/Generator/Generator.swift
|
UTF-8
| 4,563
| 3.296875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Generator.swift
// Generator
//
// Created by devedbox on 2018/3/21.
//
import Core
// MARK: - GeneratorProtocol.
/// A protocol represents a generator to generate any associated `Result` instance using the
/// formers to form the result.
public protocol GeneratorProtocol: EmptyInitializable {
/// The `Result` type of the generator.
associatedtype Result: EmptyInitializable
/// The former closure to form the result.
typealias Former = (Result) -> Void
/// Returns all the formers to form the initialized result instance.
var formers: [Former] { get }
/// Forms and adds the `Former` to `Result`.
mutating func form(_ former: @escaping Former)
/// Returns the initialized result of `Result` if any.
func initialize() -> Result?
/// Generate the instace of `Result`.
func generate() -> Result
}
extension GeneratorProtocol {
public func initialize() -> Result? {
return Result.init() // swiftlint:disable:this explicit_init
}
public func generate() -> Result {
let result = initialize() ?? Result.init() // swiftlint:disable:this explicit_init
formers.forEach { $0(result) }
return result
}
}
/// Concrete generator of `GeneratorProtocol` by wrapping the `Base` type.
open class Generator<Base: EmptyInitializable>: GeneratorProtocol {
/// Base type.
public typealias Result = Base
/// Formers as read-write property.
public var formers: [Former]
public func form(_ former: @escaping Former) {
formers.append(former)
}
public convenience required init() {
self.init(formers: [])
}
public init(formers: [Former] = []) {
self.formers = formers
}
}
// MARK: Operator.
/// Infix operator to add a former to a view generator.
infix operator +=>: AdditionPrecedence
extension GeneratorProtocol {
/// Form the right handler to the left handler by calling the `form(:)` of the left `ViewGenerator` type.
///
/// - Parameter left: The left handler of `ViewGeneratorProtocol` to be formed.
/// - Parameter right: The former to be added to the view generator.
///
/// - Returns: The new generator with the former added.
@discardableResult
public static func +=> (left: Self, right: @escaping Former) -> Self {
var gen = left
gen.form(right)
return gen
}
/// Form the right handlers to the left handler by calling the `form(:)` of the left `ViewGenerator` type
/// one at a time repeatly.
///
/// - Parameter left: The left handler of `ViewGeneratorProtocol` to be formed.
/// - Parameter rights: The formers to be added to the view generator.
///
/// - Returns: The new generator with the formers added.
@discardableResult
public static func +=> (left: Self, rights: [Former]) -> Self {
var gen = left
rights.forEach { gen.form($0) }
return gen
}
}
// MARK: - Generic.
/// A type configuring the given parameter.
public typealias Configuration<T> = (T) -> Void
/// A type configuring the given parameter and returns a new result after the configuration.
public typealias ReConfiguration<T> = (inout T) -> Void
/// Generate an instance of the given `G.View` type using the generator and configure the view via the
/// configuration closure if needed.
///
/// - Parameter t: The type of the ui element to be created.
/// - Parameter generator: The generator related withe the ui element type.
/// - Parameter configuration: A closure of `Configuration<G.View>` to handle the view after creating
/// and forming by the generator.
///
/// - Returns: An instance of `G.View`.
public func generate<G: GeneratorProtocol>(_ t: G.Result.Type,
using generator: G,
configuration: Configuration<G.Result>? = nil) -> G.Result {
let result = generator.initialize() ?? t.init()
generator.formers.forEach { $0(result) }
configuration?(result)
return result
}
/// Generate an instance of the given `G.View` by using the default generator of `G` to form the instance
/// of the ui element type.
///
/// - Parameter g: The given type `G` of generator.
/// - Parameter forming: An closure of `ReConfiguration<G>` to handle the generator after the default instance
/// created and returns a new generator with formed info.
///
/// - Returns: An instance of `G.View`.
public func generate<G: GeneratorProtocol>(via g: G.Type, forming: ReConfiguration<G>? = nil) -> G.Result {
var generator = g.init()
forming?(&generator)
return generate(G.Result.self, using: generator)
}
| true
|
9b7e42552db076388a0b60943373be8d6b9ad8a5
|
Swift
|
Vzhukov74/unicorn_melody
|
/guess the melody/model/GTMCameLevelManager.swift
|
UTF-8
| 2,939
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// GTMGameLevelManager.swift
// guess the melody
//
// Created by Vlad on 09.05.2018.
// Copyright © 2018 VZ. All rights reserved.
//
import Foundation
class GTMGameLevelManager {
var level: GTMLevelCD!
private var swaps = 0
private var life = 0
private var wasRightAnswers = 0
var didEndGame: ((_ userWin: Bool) -> Void)?
init(level: GTMLevelCD) {
self.level = level
self.life = Int(level.life)
self.swaps = Int(level.swaps)
}
func getSongDuration() -> Int {
return Int(level.timeToAnswer)
}
func getSwaps() -> Int {
return swaps
}
func getLife() -> Int {
return life
}
func totalLives() -> Int {
return Int(level.life)
}
func totalAnswers() -> Int {
return Int(level.numberOfAnswers)
}
func swapsTotal() -> Int {
return Int(level.swaps)
}
func userDidSwap() {
swaps -= 1
}
func getNumberOfAnswers() -> Int {
return wasRightAnswers
}
func reset() {
self.life = Int(level.life)
self.swaps = Int(level.swaps)
self.wasRightAnswers = 0
}
func userDidRightAnswer() {
wasRightAnswers += 1
if Int(level.numberOfAnswers) == wasRightAnswers {
calculateStatistics()
GTMLevelsManager.shared.setLevelAsPassed(level: level)
self.didEndGame?(true)
}
}
func userDidWrongAnswer() {
life -= 1
if life == 0 {
self.didEndGame?(false)
}
}
func calculateStatistics() {
let statistics = GTMLevelStatCD(context: GTMCoreDataManager.shared.managedObjectContext)
let numberOfError = Int(level.life) - life
let numberOfSwaps = Int(level.swaps) - swaps
statistics.numberOfError = Int64(numberOfError)
statistics.numberOfSwaps = Int64(numberOfSwaps)
statistics.score = Int64(calculateScore(numberOfSwap: numberOfSwaps, numberOfError: numberOfError))
statistics.stars = Int64(calculateStars(numberOfSwap: numberOfSwaps, numberOfError: numberOfError))
level.levelStat = statistics
}
func getResult() -> GTMLevelStatCD? {
return level.levelStat
}
private func calculateStars(numberOfSwap: Int, numberOfError: Int) -> Int {
let swaps = Int(level.swaps) - numberOfSwap
if swaps == 0 && numberOfError == 0 {
return 3
} else if numberOfSwap < 2 && numberOfError < 2 {
return 2
} else {
return 1
}
}
private func calculateScore(numberOfSwap: Int, numberOfError: Int) -> Int {
var score = Int(level.life) * 30 + Int(level.swaps) * 15
score -= numberOfSwap * 10 + numberOfError * 25
return Int(score)
}
}
| true
|
fca5c222fc9e49710a5bb6eaf0f950ea28959a28
|
Swift
|
mchirino89/MauriUtils
|
/Sources/MauriUtils/Extensions/Secuences/Array+Helper.swift
|
UTF-8
| 549
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
//
// File.swift
//
//
// Created by Mauricio Chirino on 05/12/20.
//
import Foundation
public extension Array {
/// Evaluates whether an array contains a single element
var isSingleElement: Bool {
return self.count == 1
}
/// Rearranges an item in the array from the given index into a new one
mutating func rearrange(from: Int, to newIndex: Int) {
guard from >= 0 && from < self.count, newIndex >= 0 && newIndex < self.count, from != newIndex else { return }
insert(remove(at: from), at: newIndex)
}
}
| true
|
5172b8aa364341f1985c08d73f5e463b3b4909f2
|
Swift
|
tanbtd-1747/MovieDB-14052019
|
/MovieDB/MovieDB/Application/Scenes/Favorites/FavoritesUseCase.swift
|
UTF-8
| 735
| 2.6875
| 3
|
[] |
no_license
|
//
// FavoritesUseCase.swift
// MovieDB
//
// Created by pham.van.ducd on 5/22/19.
// Copyright © 2019 tranductanb. All rights reserved.
//
protocol FavoritesUseCaseType {
func getFavoriteList() -> Observable<PagingInfo<Favorite>>
func loadMoreFavoriteList(page: Int) -> Observable<PagingInfo<Favorite>>
}
struct FavoriteUseCase: FavoritesUseCaseType {
let favoriteRepository: FavoriteRepositoryType
func getFavoriteList() -> Observable<PagingInfo<Favorite>> {
return favoriteRepository
.getFavorites()
.map { PagingInfo(page: 1, items: $0) }
}
func loadMoreFavoriteList(page: Int) -> Observable<PagingInfo<Favorite>> {
return Observable.empty()
}
}
| true
|
e33700f3a0a60859b35319ef65e19e3cb970eef7
|
Swift
|
iHackSubhodip/TinderReplication
|
/TinderReplication/TinderReplication/Model/UserModel.swift
|
UTF-8
| 1,535
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// UserModel.swift
// TinderReplication
//
// Created by Banerjee,Subhodip on 26/02/19.
// Copyright © 2019 Banerjee,Subhodip. All rights reserved.
//
import UIKit
struct UserModel: TinderCardViewModelProtocol{
var name: String?
var age: Int?
var profession: String?
var imageNames: String?
let uid: String?
init(_ dictionary: [String: Any]){
self.name = dictionary["fullName"] as? String ?? ""
self.imageNames = dictionary["imageUrls"] as? String ?? ""
self.age = dictionary["age"] as? Int
self.profession = dictionary["profession"] as? String
self.uid = dictionary["uid"] as? String ?? ""
}
func convertToCardViewModel() -> TinderCardViewModel{
let attributedUserInfoText = NSMutableAttributedString(string: name ?? "", attributes:[.font: UIFont.systemFont(ofSize: 34, weight: .heavy)])
let ageString = age != nil ? "\(age!)" : "N\\A"
attributedUserInfoText.append(NSMutableAttributedString(string: " \(ageString)", attributes:[.font: UIFont.systemFont(ofSize: 24, weight: .regular)]))
let professionString = profession != nil ? profession! : "Not available"
attributedUserInfoText.append(NSMutableAttributedString(string: "\n\(professionString)", attributes:[.font: UIFont.systemFont(ofSize: 20, weight: .regular)]))
return TinderCardViewModel(imageNamesArray: [imageNames ?? ""], attributedString: attributedUserInfoText, textAlignment: .left)
}
}
| true
|
4a9701ae3151d586ce2ecaf32ea484669c2f031f
|
Swift
|
prayash/algorithm-dojo
|
/LRUCache.playground/Contents.swift
|
UTF-8
| 2,830
| 4.09375
| 4
|
[] |
no_license
|
/**
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
*/
class LRUCache {
/// A `Node` class in order to create an internal Linked List
class Node {
var key: Int
var value: Int
var prev: Node?
var next: Node?
init(_ key: Int, _ value: Int) {
self.key = key
self.value = value
}
}
var capacity: Int
var count: Int
var head: Node?
var tail: Node?
var map: [Int: Node] = [:]
init(_ capacity: Int) {
self.capacity = capacity
self.count = 0
// We will use "dummy" nodes for the "head" and "tail". This will
// let us omit head == null checks for adding to the list, which also
// improves performance on the common operation of inserting into our list.
self.head = Node(-1, -1)
self.tail = Node(-1, -1)
self.head?.next = tail
self.tail?.prev = head
}
func get(_ key: Int) -> Int {
guard let node = map[key] else {
return -1
}
delete(node)
moveToHead(node)
return node.value
}
func put(_ key: Int, _ value: Int) {
if let node = map[key] {
node.value = value
delete(node)
moveToHead(node)
return
}
let node = Node(key, value)
map[key] = node
if count == capacity, let node = tail?.prev {
delete(node)
map[node.key] = nil
count = count - 1
}
moveToHead(node)
count = count + 1
}
func delete(_ node: Node) {
node.next?.prev = node.prev
node.prev?.next = node.next
}
func moveToHead(_ node: Node) {
node.next = head?.next
node.next?.prev = node
node.prev = head
head?.next = node
}
}
extension LRUCache: CustomStringConvertible {
var description: String {
var text = "["
var node = head
while node != nil {
text += "\(node!.value)"
node = node?.next
if node != nil {
text += "] <-> ["
}
}
return "\(text)]"
}
}
let cache = LRUCache(4)
cache.put(0, 0)
cache.put(1, 1)
cache.put(2, 3)
print(cache)
cache.get(0)
print(cache)
| true
|
c6f74cf9b356806042cd5a130fa5f291645e699f
|
Swift
|
kN3TT3R/Dogs
|
/Dogs/ViewController.swift
|
UTF-8
| 4,031
| 3.109375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Dogs
// Version 1.2
//
// Created by Kenneth Debruyn on 10/01/17.
// Copyright © 2017 kN3TT3R. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: - Global properties
let dogImageArray = [#imageLiteral(resourceName: "Chuck"), #imageLiteral(resourceName: "Happy"), #imageLiteral(resourceName: "Wobbes"), #imageLiteral(resourceName: "Wimpie")]
let dogInfoArray = [ (name: "Chuck", birthPlace: "Torhout", breed: "Berner-Sennen", age: 6),
(name: "Wobbes", birthPlace: "Werchter", breed: "Jack-Russell", age: 4),
(name: "Wimpie", birthPlace: "Leuven", breed: "Labrador", age: 2),
(name: "Happy", birthPlace: "Brugge", breed: "Golden Retriever", age: 8)]
var dog = Dog()
var dogCounter = 0
// MARK: - Structures
/// Structure Dog
/// properties
/// - name: the name of the dog
/// - birthPlace: the birthplace of the dog
/// - breed: the breed of the dog
/// - description: the description of the dog
/// - age: the age of the dog
/// - image: the image for the dog
struct Dog {
var name = ""
var birthPlace = ""
var breed = ""
var age = 0
var description = ""
var image = UIImage()
}
// MARK: - IBOutlets
@IBOutlet weak var dogNameLabel: UILabel!
@IBOutlet weak var dogImageView: UIImageView!
@IBOutlet weak var dogDescriptionView: UITextView!
// MARK: - IBAction
@IBAction func displayNextDog(_ sender: UIButton) {
loadNextDog()
}
@IBAction func displayPreviousDog(_ sender: UIButton) {
loadPreviousDog()
}
// MARK: - Overridden Functions
override func viewDidLoad() {
super.viewDidLoad()
loadNextDog()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Homemade Functions
/// Function which will:
/// -> create a new instance of Dog
/// -> add a name, description and image to the dog based on the Tuple
/// -> call updateView to update the info to the view
func loadNextDog() {
// checks on 'index out of bound'
if dogCounter == dogImageArray.count {
dogCounter = 0
}
let dogInfoTuple = dogInfoArray[dogCounter]
dog.name = dogInfoTuple.name
dog.birthPlace = dogInfoTuple.birthPlace
dog.breed = dogInfoTuple.breed
dog.age = dogInfoTuple.age
dog.description = "Ik ben \(dog.name). Ik kom uit \(dog.birthPlace). Net zoals mijn moeder ben ik een \(dog.breed). Ik ben nu \(dog.age) jaar oud."
dog.image = dogImageArray[dogCounter]
updateView()
dogCounter += 1
}
/// Function which will:
/// -> create a new instance of Dog
/// -> add a name, description and image to the dog based on the Tuple
/// -> call updateView to update the info to the view
func loadPreviousDog() {
// checks on 'index out of bound'
if dogCounter == 0 {
dogCounter = dogImageArray.count
}
dogCounter -= 1
let dogInfoTuple = dogInfoArray[dogCounter]
dog.name = dogInfoTuple.name
dog.birthPlace = dogInfoTuple.birthPlace
dog.breed = dogInfoTuple.breed
dog.age = dogInfoTuple.age
dog.description = "Ik ben \(dog.name). Ik kom uit \(dog.birthPlace). Net zoals mijn moeder ben ik een \(dog.breed). Ik ben nu \(dog.age) jaar oud."
dog.image = dogImageArray[dogCounter]
updateView()
}
/// Function which will update the view based on a specific instance of Dog
func updateView() {
dogNameLabel.text = dog.name
dogImageView.image = dog.image
dogDescriptionView.text = dog.description
}
}
| true
|
2de24a8e13b0bb777b5358334fc49f8940883472
|
Swift
|
ian-mcdowell/UserInterface
|
/Sources/Extension/UITableView+Custom.swift
|
UTF-8
| 925
| 2.671875
| 3
|
[] |
no_license
|
//
// UITableView+Custom.swift
// Source
//
// Created by Ian McDowell on 12/27/16.
// Copyright © 2016 Ian McDowell. All rights reserved.
//
import UIKit
extension UITableView {
/// Registers a cell for reuse with the tableView. The reuse identifier is set to the class name.
///
/// - Parameter cellClass: class of a UITableViewCell
public func register(_ cellClass: UITableViewCell.Type) {
self.register(cellClass, forCellReuseIdentifier: NSStringFromClass(cellClass))
}
/// Dequeues a reusable cell with the reuse identifier equal to the class name.
///
/// - Parameters:
/// - cellClass: class of the cell
/// - indexPath: indexPath for the cell
public func dequeueReusableCell<T: UITableViewCell>(_ cellClass: T.Type, for indexPath: IndexPath) -> T {
return self.dequeueReusableCell(withIdentifier: NSStringFromClass(cellClass), for: indexPath) as! T
}
}
| true
|
236ad71ebc87063c6d6bcaaac3678b5852809912
|
Swift
|
WhistlerW/VP
|
/VP/Modifiers/ButtonModifier.swift
|
UTF-8
| 827
| 2.96875
| 3
|
[] |
no_license
|
//
// ButtonModifier.swift
// VP
//
// Created by Demir Kovacevic on 30/12/2019.
// Copyright © 2019 Demir Kovacevic. All rights reserved.
//
import SwiftUI
struct ButtonModifier: ViewModifier {
@Binding var isValid: Bool
func body(content: Content) -> some View {
content
.frame(minWidth: 0,maxWidth: .infinity, maxHeight: 35)
.background(ColorHelper.lightBlue.color())
.cornerRadius(7, corners: [.bottomLeft, .bottomRight])
.opacity(!isValid ? 0.4 : 1.0)
.disabled(!isValid)
.padding([.leading, .trailing], 20)
}
}
extension View {
func customizeNexButton(_ isValid: Binding<Bool>) -> some View {
ModifiedContent(
content: self,
modifier: ButtonModifier(isValid: isValid)
)
}
}
| true
|
26fd85f69db0a1ebc0813e2095e93939ee2735db
|
Swift
|
skorulis/mcber-ios
|
/Mcber/controllers/user/UserCell.swift
|
UTF-8
| 2,517
| 2.734375
| 3
|
[] |
no_license
|
// Created by Alexander Skorulis on 8/10/17.
// Copyright © 2017 Alex Skorulis. All rights reserved.
import UIKit
import FontAwesomeKit
final class UserCell: ThemedCollectionViewCell, AutoSizeModelCell {
let usernameLabel = UILabel()
let currencyLabel = UILabel()
let avatarCountLabel = UILabel()
let buyAvatarButton = UIButton()
let optionsButton = UIButton()
static var sizingCell: UserCell = setupCell(cell: UserCell())
typealias ModelType = UserModel
var model: UserModel? {
didSet {
guard let model = model else { return }
usernameLabel.text = model.email ?? "Unknown"
currencyLabel.text = "Credits: \(model.currency)"
avatarCountLabel.text = "Avatars: \(model.avatars.count) / \(model.maxAvatars)"
}
}
override func buildView(theme: ThemeService) {
buyAvatarButton.setTitleColor(UIColor.blue, for: .normal)
buyAvatarButton.setTitle("+", for: .normal)
let cogIcon = FAKFontAwesome.cogIcon(withSize: 40)
cogIcon?.addAttribute(NSAttributedStringKey.foregroundColor.rawValue, value: theme.color.defaultText)
optionsButton.setAttributedTitle(cogIcon?.attributedString(), for: .normal)
contentView.addSubview(usernameLabel)
contentView.addSubview(currencyLabel)
contentView.addSubview(avatarCountLabel)
contentView.addSubview(buyAvatarButton)
contentView.addSubview(optionsButton)
}
override func buildLayout(theme: ThemeService) {
usernameLabel.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalToSuperview().inset(theme.padding.top)
}
currencyLabel.snp.makeConstraints { (make) in
make.top.equalTo(usernameLabel.snp.bottom).offset(theme.padding.innerY)
make.left.equalToSuperview()
}
avatarCountLabel.snp.makeConstraints { (make) in
make.top.equalTo(currencyLabel.snp.bottom).offset(theme.padding.innerY)
make.left.equalToSuperview()
make.bottom.equalToSuperview().inset(theme.padding.bot)
}
buyAvatarButton.snp.makeConstraints { (make) in
make.centerY.equalTo(avatarCountLabel)
make.left.equalTo(avatarCountLabel.snp.right).offset(10);
}
optionsButton.snp.makeConstraints { (make) in
make.right.top.equalToSuperview().inset(theme.padding.edges)
}
}
}
| true
|
f7ba48cfb6f42e8f44605b7fd8a9a1d2ee472cd8
|
Swift
|
thehyve/BlueSteel
|
/Sources/BlueSteel/coding/BinaryAvroDecoder.swift
|
UTF-8
| 7,453
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// BinaryAvroDecoder.swift
// BlueSteel
//
// Created by Joris Borgdorff on 16/01/2019.
// Copyright © 2019 Gilt Groupe. All rights reserved.
//
import Foundation
/// Decoder for the binary Avro encoding.
open class BinaryAvroDecoder : AvroDecoder {
public init() {
}
open func decode(_ data: Data, as schema: Schema) throws -> AvroValue {
let deserializer = BinaryAvroDeserializer(data)
return try decode(with: deserializer, as: schema)
}
private func decode(with deserializer: BinaryAvroDeserializer, as schema: Schema) throws -> AvroValue {
switch schema {
case .avroNull :
return .avroNull
case .avroBoolean :
guard let decoded = deserializer.decodeBoolean() else {
throw AvroCodingError.schemaMismatch
}
return .avroBoolean(decoded)
case .avroInt :
guard let decoded = deserializer.decodeInt() else {
throw AvroCodingError.schemaMismatch
}
return .avroInt(decoded)
case .avroLong :
guard let decoded = deserializer.decodeLong() else {
throw AvroCodingError.schemaMismatch
}
return .avroLong(decoded)
case .avroFloat :
guard let decoded = deserializer.decodeFloat() else {
throw AvroCodingError.schemaMismatch
}
return .avroFloat(decoded)
case .avroDouble :
guard let decoded = deserializer.decodeDouble() else {
throw AvroCodingError.schemaMismatch
}
return .avroDouble(decoded)
case .avroString:
guard let decoded = deserializer.decodeString() else {
throw AvroCodingError.schemaMismatch
}
return .avroString(decoded)
case .avroBytes:
guard let decoded = deserializer.decodeBytes() else {
throw AvroCodingError.schemaMismatch
}
return .avroBytes(decoded)
case .avroArray(let itemsSchema):
var values: [AvroValue] = []
while let count = try decoderBlockCount(with: deserializer) {
if count == 0 {
return .avroArray(itemSchema: itemsSchema, values)
}
values.reserveCapacity(values.count + count)
for _ in 0 ..< count {
values.append(try decode(with: deserializer, as: itemsSchema))
}
}
throw AvroCodingError.arraySizeMismatch
case .avroMap(let valuesSchema) :
var pairs: [String: AvroValue] = [:]
while let count = try decoderBlockCount(with: deserializer) {
if count == 0 {
return .avroMap(valueSchema: valuesSchema, pairs)
}
pairs.reserveCapacity(pairs.count + count)
for _ in 0 ..< count {
guard let key = deserializer.decodeString() else {
throw AvroCodingError.mapKeyTypeMismatch
}
pairs[key] = try decode(with: deserializer, as: valuesSchema)
}
}
throw AvroCodingError.mapSizeMismatch
case .avroEnum(_, let enumValues) :
guard let index = deserializer.decodeInt(), Int(index) < enumValues.count else {
throw AvroCodingError.enumMismatch
}
return .avroEnum(schema, index: Int(index), enumValues[Int(index)])
case .avroRecord(_, let fields) :
var pairs: [String: AvroValue] = [:]
for field in fields {
pairs[field.name] = try decode(with: deserializer, as: field.schema)
}
return .avroRecord(schema, pairs)
case .avroFixed(_, let size) :
guard let bytes = deserializer.decodeFixed(size) else {
throw AvroCodingError.fixedSizeMismatch
}
return .avroFixed(schema, bytes)
case .avroUnion(let schemas) :
guard let index = deserializer.decodeLong(), Int(index) < schemas.count else {
throw AvroCodingError.unionSizeMismatch
}
let unionValue = try decode(with: deserializer, as: schemas[Int(index)])
return .avroUnion(schemaOptions: schemas, index: Int(index), unionValue)
default :
throw AvroCodingError.schemaMismatch
}
}
private func decoderBlockCount(with deserializer: BinaryAvroDeserializer) throws -> Int? {
guard let count = deserializer.decodeLong() else { return nil }
if count < 0 {
guard deserializer.decodeLong() != nil else { throw AvroCodingError.schemaMismatch }
return -Int(count)
} else {
return Int(count)
}
}
}
fileprivate class BinaryAvroDeserializer {
let data: Data
var offset: Int
init(_ data: Data) {
self.data = data
self.offset = 0
}
func decodeNull() {
// Nulls aren't actually encoded.
return
}
func decodeBoolean() -> Bool? {
guard offset + 1 <= data.count else { return nil }
defer { offset += 1 }
return data[offset] > 0
}
func decodeDouble() -> Double? {
guard offset + 8 <= data.count else { return nil }
defer { offset += 8 }
let bitValue: UInt64 = data.advanced(by: offset).withUnsafeBytes { $0.load(as: UInt64.self) }
var value = UInt64(littleEndian: bitValue)
return withUnsafePointer(to: &value) { ptr in
ptr.withMemoryRebound(to: Double.self, capacity: 1) { $0.pointee }
}
}
func decodeFloat() -> Float? {
guard offset + 4 <= data.count else { return nil }
defer { offset += 4 }
let bitValue: UInt32 = data.advanced(by: offset).withUnsafeBytes { $0.load(as: UInt32.self) }
var value = UInt32(littleEndian: bitValue)
return withUnsafePointer(to: &value, { (ptr: UnsafePointer<UInt32>) -> Float in
ptr.withMemoryRebound(to: Float.self, capacity: 1) { $0.pointee }
})
}
func decodeInt() -> Int32? {
guard offset + 1 <= data.count,
let x = ZigZagInt(from: data.subdata(in: offset ..< min(offset + 4, data.count))),
x.count > 0 else { return nil }
offset += x.count
return Int32(x.value)
}
func decodeLong() -> Int64? {
guard offset + 1 <= data.count,
let x = ZigZagInt(from: data.subdata(in: offset ..< min(offset + 8, data.count))),
x.count > 0 else { return nil }
offset += x.count
return x.value
}
func decodeBytes() -> Data? {
guard let size = decodeLong(), Int(size) + offset <= data.count, size != 0 else {
return nil
}
defer { offset += Int(size) }
return data.subdata(in: offset ..< offset + Int(size))
}
func decodeString() -> String? {
guard let rawString = decodeBytes() else {
return nil
}
return String(bytes: rawString, encoding: .utf8)
}
func decodeFixed(_ size: Int) -> Data? {
guard size + offset <= data.count else {
return nil
}
defer { offset += size }
return data.subdata(in: offset ..< offset + size)
}
}
| true
|
96680a476babe4157ca5ba1e1fdfa0261f88a9ee
|
Swift
|
yuhongli1989/PhotoDemo
|
/PHPhotoDemo/PHPhotoDemo/HLPhoto/HLPhotoStatus.swift
|
UTF-8
| 864
| 2.625
| 3
|
[] |
no_license
|
//
// HLPhotoStatus.swift
// PHPhotoDemo
//
// Created by yunfu on 2019/2/13.
// Copyright © 2019 yuhongli. All rights reserved.
//
import UIKit
import Photos
class HLPhotoStatus: NSObject {
//NSPhotoLibraryUsageDescription info 添加白名单
public init(_ isSuccess:@escaping (_ isOk:Bool)->()) {
super.init()
PHPhotoLibrary.requestAuthorization { (status) in
let isok:Bool
switch status{
case .authorized://授权访问
isok = true
break
case .denied,.notDetermined,.restricted://用户拒绝访问 没有授权 无权访问,用户无法授权
isok = false
break
}
DispatchQueue.main.async {
isSuccess(isok)
}
}
}
}
| true
|
ec68516e42c10d3bc8311a9d7ec728d37e465b3e
|
Swift
|
OscarSantosGH/MovieOSLite
|
/MovieOSLite/Custom Views/Cells/FavoriteMovieCell.swift
|
UTF-8
| 2,342
| 2.578125
| 3
|
[] |
no_license
|
//
// FavoriteMovieCell.swift
// MovieOSLite
//
// Created by Oscar Santos on 8/19/20.
// Copyright © 2020 Oscar Santos. All rights reserved.
//
import UIKit
class FavoriteMovieCell: UITableViewCell {
static let reuseID = "FavoriteMovieCell"
let containerView = UIView()
let blurView = UIVisualEffectView()
let backdropImageView = MOBackdropImageView(withCornerRadius: false)
var titleLabel = MOTitleLabel(ofSize: 20, textAlignment: .left, textColor: .white)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configure()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func set(withTitle title:String, andImage image:UIImage?){
backdropImageView.image = image
titleLabel.text = title
}
private func configure(){
clipsToBounds = true
selectionStyle = .none
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.layer.cornerRadius = 10
containerView.clipsToBounds = true
let blurFX = UIBlurEffect(style: .systemUltraThinMaterialDark)
blurView.effect = blurFX
blurView.translatesAutoresizingMaskIntoConstraints = false
addSubview(containerView)
containerView.pinToEdgesWithSafeArea(of: contentView, withPadding: 8)
containerView.addSubviews(backdropImageView, blurView, titleLabel)
backdropImageView.pinToEdges(of: containerView)
NSLayoutConstraint.activate([
blurView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
blurView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
blurView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
blurView.heightAnchor.constraint(equalToConstant: 55),
titleLabel.topAnchor.constraint(equalTo: blurView.topAnchor),
titleLabel.leadingAnchor.constraint(equalTo: blurView.leadingAnchor, constant: 8),
titleLabel.bottomAnchor.constraint(equalTo: blurView.bottomAnchor),
titleLabel.trailingAnchor.constraint(equalTo: blurView.trailingAnchor, constant: 8)
])
}
}
| true
|
6c3152e841e12c11d53baf055642e95842019be8
|
Swift
|
Bryan-Guner-Backup/DOWN_ARCHIVE_V2
|
/LAMBDA_LABS/community-calendar-ios/Community Calendar/Community Calendar/Models/Filter.swift
|
UTF-8
| 3,177
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// Filter.swift
// Community Calendar
//
// Created by Jordan Christensen on 1/28/20.
// Copyright © 2020 Lambda School All rights reserved.
//
import Foundation
struct Filter: Codable, Equatable {
init(index: String? = nil, tags: [Tag]? = nil, location: LocationFilter? = nil, zipCode: Int? = nil, ticketPrice: (Int, Int)? = nil, dateRange: (Date, Date)? = nil) {
self.index = index
self.tags = tags
self.location = location
self.zipCode = zipCode
if let dateRange = dateRange {
self.dateRange = DateRangeFilter(dateRange: dateRange)
}
if let ticketPrice = ticketPrice {
self.ticketPrice = TicketPriceFilter(ticketFilter: ticketPrice)
}
}
var index: String?
var tags: [Tag]?
var location: LocationFilter?
var zipCode: Int?
var ticketPrice: TicketPriceFilter?
var dateRange: DateRangeFilter?
// var searchFilter: SearchFilters? {
// let locationFilter: LocationSearchInput?
// let dateRangeFilter: DateRangeSearchInput?
// var ticketPriceFilter: [TicketPriceSearchInput]?
//
// if let location = location {
// locationFilter = LocationSearchInput(userLongitude: location.longitude, userLatitude: location.latitude, radius: location.radius)
// } else { locationFilter = nil }
//
// if let dateRange = dateRange {
// dateRangeFilter = DateRangeSearchInput(start: backendDateFormatter.string(from: dateRange.min), end: backendDateFormatter.string(from: dateRange.max))
// } else { dateRangeFilter = nil }
//
// if let ticketRange = ticketPrice {
// ticketPriceFilter = [TicketPriceSearchInput(minPrice: ticketRange.min, maxPrice: ticketRange.max)]
// } else { ticketPriceFilter = nil }
//
// if index == nil && locationFilter == nil && dateRangeFilter == nil && ticketPriceFilter == nil && (tags == nil || tags?.count == 0) {
// return nil
// }
//
// return SearchFilters(index: index, location: locationFilter, tags: self.tags?.map({ $0.title }), ticketPrice: ticketPriceFilter, dateRange: dateRangeFilter)
// }
static func == (lhs: Filter, rhs: Filter) -> Bool {
return lhs.index == rhs.index &&
lhs.location == rhs.location &&
lhs.dateRange == rhs.dateRange &&
lhs.ticketPrice == rhs.ticketPrice &&
lhs.tags == rhs.tags
}
// static func == (lhs: Filter, rhs: Filter?) -> Bool { // To check if object is nil
// // Object can be initialized, but it will return true if the searchFilter is nil
// if let rhs = rhs {
// return lhs == rhs
// } else {
// return lhs.searchFilter != nil
// }
// }
}
struct TicketPriceFilter: Codable, Equatable {
init(ticketFilter: (Int, Int)) {
self.min = ticketFilter.0
self.max = ticketFilter.1
}
var min: Int
var max: Int
}
struct DateRangeFilter: Codable, Equatable {
init(dateRange: (Date, Date)) {
self.min = dateRange.0
self.max = dateRange.1
}
var min: Date
var max: Date
}
| true
|
36513a18effa6c6de5e8b1dffd18ecb12df0ec51
|
Swift
|
ahmettuztasi/Trader
|
/Trader/Trader/Models/Item.swift
|
UTF-8
| 642
| 2.875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Item.swift
// Trader
//
// Created by admin on 3.05.2020.
// Copyright © 2020 ahmet. All rights reserved.
//
import Foundation
// MARK: - Item
class Item: Codable {
let accountID, symbol: String
let qtyT2: Int
let lastPx: Double
enum CodingKeys: String, CodingKey {
case accountID = "AccountID"
case symbol = "Symbol"
case qtyT2 = "Qty_T2"
case lastPx = "LastPx"
}
init(accountID: String, symbol: String, qtyT2: Int, lastPx: Double) {
self.accountID = accountID
self.symbol = symbol
self.qtyT2 = qtyT2
self.lastPx = lastPx
}
}
| true
|
ea572ba5286deadf7015fae62f31ceaf660e8a21
|
Swift
|
sandervdb123/iOS-Examen
|
/iOS-Examen/ViewModels/MovieTableCell.swift
|
UTF-8
| 2,435
| 2.640625
| 3
|
[] |
no_license
|
//
// MovieTableCell.swift
// iOS-Examen
//
// Created by Sander Vdb on 13/01/2021.
// Copyright © 2021 Sander Vdb. All rights reserved.
//
import UIKit
final class MovieTableCell: UITableViewCell {
let covImage = UIImageView()
let movTitle = UILabel()
let overview = UILabel()
let svHead = UIStackView()
let sv = UIStackView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configCell()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configCell()
}
private func configCell() {
movTitle.numberOfLines = 3
movTitle.textColor = .white
movTitle.font = UIFont.preferredFont(forTextStyle: .largeTitle)
movTitle.textAlignment = .center
overview.textColor = .white
overview.numberOfLines = 2
covImage.contentMode = .scaleAspectFit
covImage.layer.masksToBounds = true
covImage.layer.cornerRadius = 50
svHead.spacing = 5
svHead.alignment = .center
sv.axis = .vertical
sv.spacing = 10
svHead.addArrangedSubview(covImage)
svHead.addArrangedSubview(movTitle)
sv.translatesAutoresizingMaskIntoConstraints = false
sv.addArrangedSubview(svHead)
sv.addArrangedSubview(overview)
contentView.addSubview(sv)
contentView.backgroundColor = .black
setupConstraints()
}
func setupConstraints() {
NSLayoutConstraint.activate([
sv.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor),
sv.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor),
sv.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor, constant: 8),
sv.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor, constant: -8),
covImage.widthAnchor.constraint(equalToConstant: 180),
covImage.heightAnchor.constraint(equalToConstant: 320)
])
}
func setCell(_ movie: Movie) {
movTitle.text = movie.title
overview.text = movie.overview
covImage.setImageCover(poster: movie.posterPath)
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
| true
|
4a49b25830496e996c5b68bda8ce15e2b21795d7
|
Swift
|
Jiar/J2M
|
/Demo/J2M-macOS-Demo/ViewController.swift
|
UTF-8
| 2,488
| 3.203125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//
// ViewController.swift
// J2M-macOS-Demo
//
// Created by Jiar on 2017/8/22.
// Copyright © 2017年 Jiar. All rights reserved.
//
import Cocoa
import J2M
//////////////////// Codable Model
struct Article: Codable {
enum `Type`: String, Codable {
case story = "story"
case job = "job"
}
let id: Int
let deleted: Bool
let type: Type
let title: String
let text: String?
let authorId: Int
let authorName: String
let created: TimeInterval
let comments: [Int]?
// Key Mapping
private enum CodingKeys : String, CodingKey {
case id = "articleId", deleted, type, title, text, authorId, authorName, created = "createTime", comments
}
}
class ViewController: NSViewController {
@IBOutlet weak var label: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
label.stringValue = ""
//////////////////// Encodable Encode
let article = Article(id: 1, deleted: false, type: .story, title: "标题", text: "内容", authorId: 1, authorName: "Jiar", created: Date().timeIntervalSince1970, comments: [1, 2, 3])
if let json = article.j2m.toJson() {
let str = "\n\(json)\n"
print(str)
label.stringValue = label.stringValue + str
}
//////////////////// String Decode
let json2 =
"""
{"deleted":false,"authorId":2,"title":"标题2","text":"内容2","authorName":"Jiar","type":"job","articleId":1,"createTime":1503384985.8531871}
"""
if let article2 = json2.j2m.toModel(type: Article.self) {
let str = "\n\(article2)\n"
print(str)
label.stringValue = label.stringValue + str
}
//////////////////// Data Decode
let data3 =
"""
{"deleted":true,"authorId":3,"title":"标题3","authorName":"Jiar","type":"story","articleId":1,"createTime":1503384985.8531871,"comments":[4,5]}
"""
.data(using: .utf8)!
if let article3 = data3.j2m.toModel(type: Article.self) {
let str = "\n\(article3)\n"
print(str)
label.stringValue = label.stringValue + str
}
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| true
|
fa9beb23ea3a5c58a88910fe1dafbb5a82249258
|
Swift
|
rein-petre/iOS-JUST-DO-IT.
|
/JUST DO IT./JUST DO IT./Models/Project.swift
|
UTF-8
| 254
| 2.875
| 3
|
[] |
no_license
|
import Foundation
class Project {
var id: String?
var title: String
var todos: [Todo]
var activeTodos: Int
init(title: String) {
self.title = title
self.todos = [Todo]()
self.activeTodos = 0
}
}
| true
|
a8ff970532bbeef2f4b3286428c91cc57feffff3
|
Swift
|
Nightscou2018/fingerstick
|
/NightScout/JsonController.swift
|
UTF-8
| 2,580
| 2.875
| 3
|
[] |
no_license
|
//
// JsonController.swift
// SwiftLoginScreen
//
// Created by Sam Wang on 8/9/14, co-authored with Sam Burba.//
import UIKit
class JsonController {
func postDataNew(urlString:String, postString:NSString, handler:ResponseHandler)
{
var session = NSURLSession.sharedSession()
if let url = NSURL(string: urlString)
{
if let task = session.dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
var jsonError:NSError?
if let jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as NSMutableArray?
{
if (jsonError != nil) {
handler.onFailure("Error parsing json: \(jsonError)")
}
else {
let responseStr = NSString(data: data, encoding:NSUTF8StringEncoding)
NSLog("Response ==> %@", responseStr!);
handler.onSuccess(jsonData)
}
} else {
handler.onFailure("Connection Failed")
}
}) as NSURLSessionDataTask?
{
task.resume()
} else
{
handler.onFailure("URL Error")
}
}
}
func postData(urlString:String, postString:NSString, handler:ResponseHandler)
{
var postData:NSData = postString.dataUsingEncoding(NSASCIIStringEncoding)!
var jsonData:NSMutableArray = []
if let url: NSURL = NSURL(string: urlString)
{
let request: NSURLRequest = NSURLRequest(URL: url)
let response: AutoreleasingUnsafeMutablePointer <NSURLResponse?> = nil
var error: AutoreleasingUnsafeMutablePointer <NSErrorPointer?> = nil
let queue = NSOperationQueue.currentQueue()
//let queue = NSOperationQueue.mainQueue()
println("Making NSURL connection")
NSURLConnection.sendAsynchronousRequest(
request,
queue: queue,
completionHandler: {response, data, error in
if (error == nil)
{
println("Processing data")
self.processData(data, handler: handler)
} else
{
handler.onFailure("\(error.localizedDescription)")
}
}
)
}
else
{
handler.onFailure("URL entered incorrectly")
}
}
func processData(response:NSData, handler:ResponseHandler)
{
let responseStr = NSString(data:response, encoding:NSUTF8StringEncoding)
NSLog("Response ==> %@", responseStr!);
if let jsonData = NSJSONSerialization.JSONObjectWithData(response, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSMutableArray {
handler.onSuccess(jsonData)
}
else
{
handler.onFailure("Error")
// more to do here
}
}
}
| true
|
392f99a09ba6e377557ec9ea96be2f9428c3d953
|
Swift
|
dipen30/Qmote
|
/KodiRemote/KodiRemote/Controllers/GenreTableViewController.swift
|
UTF-8
| 3,371
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// GenreTableViewController.swift
// Kodi Remote
//
// Created by Quixom Technology on 05/01/16.
// Copyright © 2016 Quixom Technology. All rights reserved.
//
import UIKit
class GenreTableViewController: UITableViewController {
var genreNames = [String]()
var genreIds = [Int]()
var genreInitials = [String]()
var genreObjs = NSArray()
var rc: RemoteCalls!
override func viewDidLoad() {
super.viewDidLoad()
rc = RemoteCalls(ipaddress: global_ipaddress, port: global_port)
rc.jsonRpcCall("AudioLibrary.GetGenres", params: "{\"properties\":[]}"){ (response: AnyObject?) in
self.generateResponse(response as! NSDictionary)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.genreObjs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GenreTableViewCell", for: indexPath) as! GenreTableViewCell
let genereDetails = self.genreObjs[(indexPath as NSIndexPath).row] as! NSDictionary
cell.genreName.text = genereDetails["label"] as? String
let randomColor = backgroundColors[Int(arc4random_uniform(UInt32(backgroundColors.count)))]
let name = genereDetails["label"] as! String
let index1 = name.characters.index(name.startIndex, offsetBy: 1)
cell.genreInitial.text = name.substring(to: index1)
cell.genreInitial.backgroundColor = UIColor(hex: randomColor)
return cell
}
func generateResponse(_ jsonData: AnyObject){
let total = (jsonData["limits"] as! NSDictionary)["total"] as! Int
if total != 0 {
let genreDetails = jsonData["genres"] as! NSArray
self.genreObjs = genreDetails
for item in genreDetails{
let obj = item as! NSDictionary
for (key, value) in obj {
if key as! String == "label" {
let name = value as! String
self.genreNames.append(name)
let index1 = name.characters.index(name.startIndex, offsetBy: 1)
self.genreInitials.append(name.substring(to: index1))
}
if key as! String == "genreid"{
self.genreIds.append(value as! Int)
}
}
}
}else {
// Display No data found message
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowAlbumsByGenre" {
let destination = segue.destination as! AlbumsTableViewController
if let albumIndex = (tableView.indexPathForSelectedRow as NSIndexPath?)?.row {
destination.artistId = self.genreIds[albumIndex]
destination.artistName = self.genreNames[albumIndex]
}
}
}
}
| true
|
c563bb3006089f8ca2c82f4b18604d792ff5db2d
|
Swift
|
TitikJumpa/TitikJumpaMac
|
/TitikJumpaMac/cell/EventCell.swift
|
UTF-8
| 951
| 2.6875
| 3
|
[] |
no_license
|
//
// EventCell.swift
// TitikJumpaMac
//
// Created by Sufiandy Elmy on 17/08/20.
// Copyright © 2020 Sufiandy Elmy. All rights reserved.
//
import Foundation
import UIKit
class EventCell: UITableViewCell {
@IBOutlet weak var name: UILabel!
//@IBOutlet weak var Description: UILabel!
@IBOutlet weak var Date: UILabel!
@IBOutlet weak var Location: UILabel!
@IBOutlet weak var Points: UILabel!
@IBOutlet weak var Volunteer: UILabel!
//@IBOutlet weak var PosterView: UIImageView!
func configure(event:Event){
let df = DateFormatter()
df.dateFormat = "yyyy MMM dd"
print(event.name)
name.text = event.name
//PosterView.image = event.photo
Date.text = df.string(from: event.start_date)
Location.text = event.location
Points.text = "\(event.points) Points"
Volunteer.text = "\(event.total_vol) Volunteer"
}
}
| true
|
ccccf732ac6fba2ff00cac565ee35bbca17f33c6
|
Swift
|
traning-ios/LearningSwiftUI
|
/SwiftDux/Sources/SwiftDux/UI/MappedState.swift
|
UTF-8
| 771
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import SwiftUI
/// Retrieves a mapping of the application state from the environment and provides it to a property in a SwiftUI view.
/// Use the `connect(updateWhen:mapState:)` method to first inject the state from a parent view.
/// ```
/// struct MyView : View {
///
/// @MappedState var todoList: TodoList
///
/// }
/// ```
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper
public struct MappedState<State>: DynamicProperty where State: Equatable {
@EnvironmentObject private var connection: StateConnection<State>
public var wrappedValue: State {
guard let state = connection.state else {
fatalError("State was not connected before using @MappedState")
}
return state
}
public init() {}
}
| true
|
fb7caccb66902561334cc2e8f3a15ad45344a34d
|
Swift
|
dastrobu/NdArray
|
/Sources/NdArray/matrix/MatrixSequence.swift
|
UTF-8
| 795
| 3.390625
| 3
|
[
"MIT"
] |
permissive
|
/// simple matrix iterator
public struct MatrixIterator<T>: IteratorProtocol {
fileprivate init(_ mat: Matrix<T>) {
self.mat = mat
}
private let mat: Matrix<T>
private var index: Int = 0
/// - Returns: next element or nil if there is no next element
public mutating func next() -> Vector<T>? {
if index >= mat.shape[0] || mat.isEmpty {
return nil
}
let element = Vector<T>(mat[Slice(index)])
index += 1
return element
}
}
/// make vector conform to sequence protocol
public extension Matrix {
func makeIterator() -> MatrixIterator<T> {
MatrixIterator(self)
}
/// - Returns: shape[0] or 0 if matrix is empty
var underestimatedCount: Int {
isEmpty ? 0 : shape[0]
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.