repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mobicast/mobicast-cocoapods | refs/heads/master | Example/Mobicast/ListViewController.swift | mit | 1 | import UIKit
import Mobicast
class ListViewController: UIViewControllerExtension, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var discoveryPlaylist: DiscoveryPlaylist?
var channelsList: ChannelsList?
internal var tableViewData = [[String: String]]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
UIApplication.shared.setStatusBarHidden(false, with: UIStatusBarAnimation.fade)
setupTableViewData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
internal func setupTableViewData() {
tableViewData.append(["type": "widget",
"title": "Discovery Widget",
"description": ""])
tableViewData.append(["type": "vertical_playlist",
"title": "Discovery Vertical Playlist",
"description": ""])
tableViewData.append(["type": "channels",
"title": "Channels",
"description": ""])
tableView.reloadData()
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableViewData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier")
let cellData = tableViewData[indexPath.row]
cell?.textLabel?.text = cellData["title"]
cell?.detailTextLabel?.text = cellData["description"]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView .deselectRow(at: indexPath, animated: true)
let cellData = tableViewData[indexPath.row]
if cellData["type"] == "widget" {
performSegue(withIdentifier: "widgetSegue", sender: self)
} else if cellData["type"] == "vertical_playlist" {
openDiscoveryPlayList()
} else if cellData["type"] == "channels" {
openChannelsList()
}
}
// MARK: -
func openDiscoveryPlayList() {
discoveryPlaylist = DiscoveryPlaylist.init(showInNavigationController: self.navigationController!, playerToken: "102")
discoveryPlaylist?.isDeveloperMode = true
}
func openChannelsList() {
channelsList = ChannelsList.init(showInNavigationController: self.navigationController!)
}
}
| eb044d9c7c6fdcccf5fc29bbd6f7a069 | 28.327103 | 126 | 0.623646 | false | false | false | false |
yageek/LazyBug | refs/heads/develop | LazyBug/FeedbackWindow.swift | mit | 1 | //
// FeedbackWindow.swift
// LazyBug
//
// Created by Yannick Heinrich on 04.05.17.
//
//
import UIKit
// MARK: - Dragging View
fileprivate class RectView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var startPoint:CGPoint?{
didSet{
self.setNeedsDisplay()
}
}
var endPoint:CGPoint?{
didSet{
self.setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
guard let start = startPoint, let end = endPoint else {
return
}
let rect = CGRect(x: min(start.x, end.x), y: min(start.y, end.y), width: fabs(start.x - end.x), height: fabs(start.y - end.y))
UIColor.red.setStroke()
let path = UIBezierPath(rect: rect)
path.lineWidth = 5
path.stroke()
}
}
// MARK: - Feadback
fileprivate protocol FeedbackControllerDelegate {
func controllerDidClose(_ feedbackController: FeedbackController)
}
class FeedbackController: UIViewController {
fileprivate var snapshot: UIImage? {
didSet {
startAnimation(image: snapshot)
}
}
fileprivate var annotedSnapshot: UIImage?
private var imageView: UIImageView!
private var dragView: RectView!
fileprivate let dimmingTransitionDelegate = FeedbackTransitionDelegate()
fileprivate var delegate: FeedbackControllerDelegate?
private var snapGesture: UIPanGestureRecognizer!
private func startAnimation(image: UIImage?) {
let imageV = UIImageView(image: snapshot)
imageV.isUserInteractionEnabled = true
imageV.frame = self.view.bounds
self.view.addSubview(imageV)
let ratio: CGFloat = 0.80
UIView.animate(withDuration: 1.0, animations: {
imageV.layer.transform = CATransform3DMakeScale(ratio, ratio, 1);
}) { (finished) in
if finished {
self.enablePinch(view: self.imageView)
}
}
self.imageView = imageV
let rect = RectView(frame: imageV.bounds)
dragView = rect
imageV.addSubview(rect)
}
@IBAction func closeTriggered(_ sender: UIButton) {
self.delegate?.controllerDidClose(self)
}
@objc func panTriggered(_ src: UIPinchGestureRecognizer) {
switch src.state {
case .began:
self.dragView.startPoint = src.location(in: self.imageView)
case .changed:
self.dragView.endPoint = src.location(in: self.imageView)
case .ended:
takeSnapshot()
displayController()
default:
break
}
}
private func takeSnapshot() {
UIGraphicsBeginImageContext(self.imageView.bounds.size)
// View
self.imageView.drawHierarchy(in: imageView.bounds, afterScreenUpdates: true)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.annotedSnapshot = img
}
private func enablePinch(view: UIView) {
// Pinch
let gesture = UIPanGestureRecognizer(target: self, action: #selector(FeedbackController.panTriggered(_:)))
view.addGestureRecognizer(gesture)
snapGesture = gesture
}
private func displayController() {
performSegue(withIdentifier: "DimmingSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DimmingSegue" {
let dst = segue.destination as! FeedbackFormController
dst.snapshot = annotedSnapshot
dst.transitioningDelegate = dimmingTransitionDelegate
dst.modalPresentationStyle = .custom
}
}
}
// MARK: - FeedbackWindow
protocol FeedBackWindowDelegate {
func windowDidCancel(_ window: FeedbackWindow)
}
class FeedbackWindow: UIWindow, FeedbackControllerDelegate {
fileprivate let controller: FeedbackController
var delegate: FeedBackWindowDelegate?
init(snapshot: UIImage) {
controller = UIStoryboard(name: "Feedback", bundle: Bundle(for: Feedback.self)).instantiateInitialViewController() as! FeedbackController
super.init(frame: UIScreen.main.bounds)
windowLevel = UIWindowLevelAlert + 2
rootViewController = controller
isUserInteractionEnabled = true
screen = UIScreen.main
controller.delegate = self
controller.snapshot = snapshot
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func controllerDidClose(_ feedbackController: FeedbackController) {
delegate?.windowDidCancel(self)
}
}
fileprivate class FeedbackTransitionDelegate: NSObject, UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return FeedbackPresentationController(presentedViewController: presented, presenting: presenting)
}
}
// MARK: - Presentation
fileprivate class FeedbackPresentationController: UIPresentationController {
let dimmingView = UIView()
override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
dimmingView.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
}
override func presentationTransitionWillBegin() {
dimmingView.frame = containerView?.bounds ?? CGRect.zero
dimmingView.alpha = 0.0
containerView?.insertSubview(dimmingView, at: 0)
presentedViewController.transitionCoordinator?.animate(alongsideTransition: {
context in
self.dimmingView.alpha = 1.0
}, completion: nil)
}
override func dismissalTransitionDidEnd(_ completed: Bool) {
if completed {
NotificationCenter.default.post(name: FeedbackFormController.DidCloseNotification, object: nil)
}
}
override var frameOfPresentedViewInContainerView: CGRect {
let screenBounds = UIScreen.main.bounds
let inset = screenBounds.insetBy(dx: 20, dy: 20)
return CGRect(origin: inset.origin, size: CGSize(width: inset.width, height: 250))
}
}
// MARK: - Feedback form
class FeedbackFormController: UIViewController {
static let DidCloseNotification = Notification.Name("net.yageek.lazybug.feebackformDidClose")
var snapshot: UIImage?
@IBOutlet weak var snapshotImageView: UIImageView!
@IBOutlet weak var feedbackTextView: UITextView!
override func loadView() {
super.loadView()
self.view.layer.cornerRadius = 10.0
self.snapshotImageView.image = snapshot
}
@IBAction func addingTriggered(_ sender: Any) {
guard let image = snapshotImageView.image else { return }
Store.shared.addFeedback(content: feedbackTextView.text ?? "<Empty>", image: image) {
LazyBug.shared.performSync()
}
dismiss(animated: true)
}
@IBAction func cancelTriggered(_ sender: Any) {
dismiss(animated: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
feedbackTextView.becomeFirstResponder()
}
}
| b06487f6329919ea4bfca9665ccbcb8b | 30.127572 | 161 | 0.669223 | false | false | false | false |
che1404/RGViperChat | refs/heads/master | RGViperChat/Authorization/View/AuthorizationView.swift | mit | 1 | //
// Created by Roberto Garrido
// Copyright (c) 2017 Roberto Garrido. All rights reserved.
//
import Foundation
import UIKit
import FontAwesome_swift
class AuthorizationView: UIViewController, AuthorizationViewProtocol {
@IBOutlet weak var textFieldEmail: UITextField!
@IBOutlet weak var textFieldPassword: UITextField!
@IBOutlet weak var buttonLogin: UIButton!
@IBOutlet weak var buttonSignup: UIButton!
var presenter: AuthorizationPresenterProtocol?
override func viewDidLoad() {
super.viewDidLoad()
buttonLogin.layer.cornerRadius = 5
buttonSignup.layer.cornerRadius = 5
let textFieldUsernameLeftView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
textFieldUsernameLeftView.backgroundColor = UIColor.clear
textFieldUsernameLeftView.image = UIImage.fontAwesomeIcon(name: .envelope, textColor: UIColor.white, size: CGSize(width: 15.0, height: 15.0))
textFieldEmail.leftView = textFieldUsernameLeftView
textFieldEmail.leftViewMode = .always
let textFieldPasswordLeftView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
textFieldPasswordLeftView.backgroundColor = UIColor.clear
textFieldPasswordLeftView.image = UIImage.fontAwesomeIcon(name: .lock, textColor: UIColor.white, size: CGSize(width: 15.0, height: 15.0))
textFieldPassword.leftView = textFieldPasswordLeftView
textFieldPassword.leftViewMode = .always
}
@IBAction func buttonSignupTapped(_ sender: Any) {
presenter?.buttonSignupTapped()
}
@IBAction func buttonLoginTapped(_ sender: Any) {
guard let email = textFieldEmail.text, let password = textFieldPassword.text else {
return
}
presenter?.buttonLoginTapped(withEmail: email, andPassword: password)
}
}
| d527eaa33fc74e95930d8e82d8f1b6de | 37.5625 | 149 | 0.720692 | false | false | false | false |
Bartlebys/Bartleby | refs/heads/master | Tests.shared/TestsConfiguration.swift | apache-2.0 | 1 | //
// TestsConfiguration.swift
// bsync
//
// Created by Benoit Pereira da silva on 29/12/2015.
// Copyright © 2015 Benoit Pereira da silva. All rights reserved.
//
import Foundation
#if !USE_EMBEDDED_MODULES && !IN_YOUDUBROBOT && !IN_BARTLEBY_KIT
import BartlebyKit
#endif
// A shared configuration Model
open class TestsConfiguration: BartlebyConfiguration {
// The cryptographic key used to encrypt/decrypt the data
open static let KEY: String=Bartleby.randomStringWithLength(1024)
open static let SHARED_SALT: String="xyx38-d890x-899h-123e-30x6-3234e"
// To conform to crypto legal context
open static var KEY_SIZE: KeySize = .s128bits
//MARK: - URLS
static let trackAllApiCalls=true
open static var API_BASE_URL=__BASE_URL
public static var defaultBaseURLList: [String] {
return ["http://yd.local:8001/api/v1","https://dev.api.lylo.tv/api/v1","https://api.lylo.tv/api/v1","https://demo.bartlebys.org/www/api/v1"]
}
// Bartleby Bprint
open static var ENABLE_GLOG: Bool=true
// Should Bprint entries be printed
public static var PRINT_GLOG_ENTRIES: Bool=true
// Use NoCrypto as CryptoDelegate (should be false)
open static var DISABLE_DATA_CRYPTO: Bool=false
//If set to true the created instances will be remove on maintenance Purge
open static var EPHEMERAL_MODE=true
//Should the app try to be online by default
open static var ONLINE_BY_DEFAULT=true
// Consignation
open static var API_CALL_TRACKING_IS_ENABLED: Bool=true
open static var BPRINT_API_TRACKED_CALLS: Bool=true
// Should we save the password by Default ?
open static var SAVE_PASSWORD_BY_DEFAULT: Bool=false
// If set to JSON for example would be Indented
open static var HUMAN_FORMATTED_SERIALIZATON_FORMAT: Bool=false
// Supervision loop interval (1 second min )
open static var LOOP_TIME_INTERVAL_IN_SECONDS: Double = 1
// To guarantee the sequential Execution use 1
open static var MAX_OPERATIONS_BUNCH_SIZE: Int = 10
// The min password size
open static var MIN_PASSWORD_SIZE: UInt=6
// E.g : Default.DEFAULT_PASSWORD_CHAR_CART
open static var PASSWORD_CHAR_CART: String="ABCDEFGH1234567890"
// If set to true the keyed changes are stored in the ManagedModel - When opening the Inspector this default value is remplaced by true
public static var CHANGES_ARE_INSPECTABLES_BY_DEFAULT: Bool = false
// If set to true the confirmation code will be for example printed in the console...
open static let DEVELOPER_MODE: Bool = true // Should be turned to false in production
// If set to true identification will not require second auth factor.
open static var SECOND_AUTHENTICATION_FACTOR_IS_DISABLED:Bool = false
// Supports by default KeyChained password synchronization between multiple local accounts (false is more secured)
public static let SUPPORTS_PASSWORD_SYNDICATION_BY_DEFAULT: Bool = false
// Supports by default the ability to update the password. Recovery procedure for accounts that have allready be saved in the KeyChain (false is more secured)
public static var SUPPORTS_PASSWORD_UPDATE_BY_DEFAULT: Bool = false
// Allows by default users to memorize password (false is more secured)
public static var SUPPORTS_PASSWORD_MEMORIZATION_BY_DEFAULT: Bool = false
// If set to true the user can skip the account creation and stay fully offline.
public static var ALLOW_ISOLATED_MODE: Bool = false
// If set to true each document has it own isolated user
public static var AUTO_CREATE_A_USER_AUTOMATICALLY_IN_ISOLATED_MODE: Bool = false
//MARK: - Variable base URL
enum Environment {
case local
case development
case alternative
case production
}
static var currentEnvironment: Environment = .development
static fileprivate var __BASE_URL: URL {
get {
switch currentEnvironment {
case .local:
// On macOS you should point "yd.local" to your IP by editing /etc/host
return URL(string:"http://yd.local:8001/api/v1")!
case .development:
return URL(string:"https://dev.api.lylo.tv/api/v1")!
case .alternative:
return URL(string: "https://demo.bartlebys.org/www/api/v1")!
case .production:
return URL(string:"https://api.lylo.tv/api/v1")!
}
}
}
open static let TIME_OUT_DURATION = 10.0
open static let LONG_TIME_OUT_DURATION = 360.0
open static let ENABLE_TEST_OBSERVATION=true
}
| e5fc2ecd3d43d5b791fdbbf536aa41ce | 32.992701 | 162 | 0.693365 | false | false | false | false |
rene-dohan/CS-IOS | refs/heads/master | Renetik/Renetik/Classes/Core/Extensions/UIKit/UIViewController+CSExtension.swift | mit | 1 | //
// UIViewController+CSExtension.swift
// Renetik
//
// Created by Rene Dohan on 2/19/19.
//
import Foundation
import UIKit
import RenetikObjc
public extension UIViewController {
@discardableResult
func push() -> Self {
navigation.push(self)
return self
}
@discardableResult
func pushAsLast() -> Self {
navigation.pushAsLast(self)
return self
}
@discardableResult
func push(key: String) -> Self {
navigation.push(key, self)
return self
}
@discardableResult
func pushMain() -> Self {
push(key: "mainController")
return self
}
@discardableResult
func pushFromTop() -> Self {
navigation.push(fromTop: self)
return self
}
@discardableResult
func add(controller: UIViewController) -> UIViewController {
add(controller: controller, to: view)
}
@discardableResult
func add(controller: UIViewController, to parenView: UIView) -> UIViewController {
addChild(controller)
parenView.add(view: controller.view)
controller.didMove(toParent: self)
(controller as? CSViewController)?.isShowing = true
return controller
}
@discardableResult
@objc open func dismissChild(controller: UIViewController) -> UIViewController {
controller.willMove(toParent: nil)
controller.view.removeFromSuperview()
controller.removeFromParent()
(controller as? CSMainController)?.isShowing = false
return controller
}
func present(from element: CSDisplayElement) -> Self {
element.view.notNil { present(from: $0) }
element.item.notNil { present(from: $0) }
return self
}
@discardableResult
public func present(from view: UIView) -> Self {
modalPresentationStyle = .popover
popoverPresentationController?.sourceView = view.superview
popoverPresentationController?.sourceRect = view.frame
present()
return self
}
@discardableResult
public func present(from item: UIBarButtonItem) -> Self {
modalPresentationStyle = .popover
popoverPresentationController?.barButtonItem = item
present()
return self
}
public func present() -> Self {
navigation.last!.present(self, animated: true, completion: nil); return self
}
var isDarkMode: Bool {
if #available(iOS 12, *) { return traitCollection.isDarkMode } else { return false }
}
func findControllerInNavigation() -> UIViewController? {
var foundController: UIViewController? = self
while foundController.notNil && foundController?.parent != navigation {
foundController = foundController?.parent
}
return foundController?.parent == navigation ? foundController : nil
}
var isLastInNavigation: Bool { navigation.last == self }
@discardableResult
func backButtonWithoutPreviousTitle() -> Self {
navigationItem.backBarButtonItem = UIBarButtonItem(title: nil, style: .plain, target: nil, action: nil)
return self
}
@discardableResult
func backButtonTitle(_ title: String?) -> Self {
navigationItem.backBarButtonItem?.title = title; return self
}
@discardableResult
func present(_ modalViewController: UIViewController) -> Self {
present(modalViewController, animated: true); return self
}
@discardableResult
func dismiss() -> Self { dismiss(animated: true); return self }
@discardableResult
func updateLayout() -> Self { view.setNeedsLayout(); return self }
} | b9dfd50be1f5539c39416093e5824020 | 27.294574 | 111 | 0.656618 | false | false | false | false |
zoeyzhong520/SlidingMenu | refs/heads/master | SlidingMenu/SwiftyJSON-master/Tests/SwiftyJSONTests/MutabilityTests.swift | mit | 1 | // MutabilityTests.swift
//
// Copyright (c) 2014 - 2017 Zigii Wong
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import SwiftyJSON
class MutabilityTests: XCTestCase {
func testDictionaryMutability() {
let dictionary: [String: Any] = [
"string": "STRING",
"number": 9823.212,
"bool": true,
"empty": ["nothing"],
"foo": ["bar": ["1"]],
"bar": ["foo": ["1": "a"]]
]
var json = JSON(dictionary)
XCTAssertEqual(json["string"], "STRING")
XCTAssertEqual(json["number"], 9823.212)
XCTAssertEqual(json["bool"], true)
XCTAssertEqual(json["empty"], ["nothing"])
json["string"] = "muted"
XCTAssertEqual(json["string"], "muted")
json["number"] = 9999.0
XCTAssertEqual(json["number"], 9999.0)
json["bool"] = false
XCTAssertEqual(json["bool"], false)
json["empty"] = []
XCTAssertEqual(json["empty"], [])
json["new"] = JSON(["foo": "bar"])
XCTAssertEqual(json["new"], ["foo": "bar"])
json["foo"]["bar"] = JSON([])
XCTAssertEqual(json["foo"]["bar"], [])
json["bar"]["foo"] = JSON(["2": "b"])
XCTAssertEqual(json["bar"]["foo"], ["2": "b"])
}
func testArrayMutability() {
let array: [Any] = ["1", "2", 3, true, []]
var json = JSON(array)
XCTAssertEqual(json[0], "1")
XCTAssertEqual(json[1], "2")
XCTAssertEqual(json[2], 3)
XCTAssertEqual(json[3], true)
XCTAssertEqual(json[4], [])
json[0] = false
XCTAssertEqual(json[0], false)
json[1] = 2
XCTAssertEqual(json[1], 2)
json[2] = "3"
XCTAssertEqual(json[2], "3")
json[3] = [:]
XCTAssertEqual(json[3], [:])
json[4] = [1, 2]
XCTAssertEqual(json[4], [1, 2])
}
func testValueMutability() {
var intArray = JSON([0, 1, 2])
intArray[0] = JSON(55)
XCTAssertEqual(intArray[0], 55)
XCTAssertEqual(intArray[0].intValue, 55)
var dictionary = JSON(["foo": "bar"])
dictionary["foo"] = JSON("foo")
XCTAssertEqual(dictionary["foo"], "foo")
XCTAssertEqual(dictionary["foo"].stringValue, "foo")
var number = JSON(1)
number = JSON("111")
XCTAssertEqual(number, "111")
XCTAssertEqual(number.intValue, 111)
XCTAssertEqual(number.stringValue, "111")
var boolean = JSON(true)
boolean = JSON(false)
XCTAssertEqual(boolean, false)
XCTAssertEqual(boolean.boolValue, false)
}
func testArrayRemovability() {
let array = ["Test", "Test2", "Test3"]
var json = JSON(array)
json.arrayObject?.removeFirst()
XCTAssertEqual(false, json.arrayValue.isEmpty)
XCTAssertEqual(json.arrayValue, ["Test2", "Test3"])
json.arrayObject?.removeLast()
XCTAssertEqual(false, json.arrayValue.isEmpty)
XCTAssertEqual(json.arrayValue, ["Test2"])
json.arrayObject?.removeAll()
XCTAssertEqual(true, json.arrayValue.isEmpty)
XCTAssertEqual(JSON([]), json)
}
func testDictionaryRemovability() {
let dictionary: [String : Any] = ["key1": "Value1", "key2": 2, "key3": true]
var json = JSON(dictionary)
json.dictionaryObject?.removeValue(forKey: "key1")
XCTAssertEqual(false, json.dictionaryValue.isEmpty)
XCTAssertEqual(json.dictionaryValue, ["key2": 2, "key3": true])
json.dictionaryObject?.removeValue(forKey: "key3")
XCTAssertEqual(false, json.dictionaryValue.isEmpty)
XCTAssertEqual(json.dictionaryValue, ["key2": 2])
json.dictionaryObject?.removeAll()
XCTAssertEqual(true, json.dictionaryValue.isEmpty)
XCTAssertEqual(json.dictionaryValue, [:])
}
}
| dd91cadc85b6aa38ea325bac28000bf6 | 32.398649 | 84 | 0.608133 | false | true | false | false |
ricealexanderb/forager | refs/heads/master | NewPinViewController.swift | mit | 1 | //
// NewPinViewController.swift
// Foragr
//
// Created by Alex on 8/13/14.
// Copyright (c) 2014 Alex Rice. All rights reserved.
//
import UIKit
import MapKit
//import CoreLocation
class NewPinViewController: UIViewController, MKMapViewDelegate {
var storage = NSUserDefaults.standardUserDefaults()
var mapView : MKMapView!
//variables that will be saved to Patch record
var lat : Double!
var lon : Double!
var plantName : String!
var nextHarvest : NSDate!
var reminder : Bool!
override func viewDidLoad() {
super.viewDidLoad()
//Display mapview
self.mapView = MKMapView(frame: self.view.frame)
self.view.addSubview(self.mapView)
self.mapView.showsUserLocation = true
self.mapView.showsUserLocation = true
//Register to handle longpress so that we can add a pin
var longPress = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
self.mapView.addGestureRecognizer(longPress)
self.mapView.delegate = self
//By default, set coordinates of new pin to be the current location
self.lat = self.mapView.userLocation.coordinate.latitude
self.lon = self.mapView.userLocation.coordinate.longitude
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "savePatch")
self.navigationItem.rightBarButtonItem = doneButton
if reminder == true {
println("Set reminder")
var notification = UILocalNotification()
notification.timeZone = NSTimeZone.localTimeZone()
notification.alertBody = "A patch of \(self.plantName) that you bookmarked is ready for harvest"
notification.alertBody = "Ok"
var app = UIApplication.sharedApplication()
app.scheduleLocalNotification(notification)
if debug == true {
//app.presentLocalNotificationNow(notification)
}
} else {
println("don't set reminder")
}
}
func savePatch() {
var newPatch = Patch()
newPatch.lat = self.lat
newPatch.lon = self.lon
newPatch.plantName = self.plantName
println("I think my name is: \(self.plantName)")
newPatch.nextHarvest = self.nextHarvest
println("lat \(newPatch.lat)")
println("lon \(newPatch.lon)")
println("name \(newPatch.plantName)")
println("next \(newPatch.nextHarvest)")
if patchListGlobal.count == 0 {
patchListGlobal.append(newPatch)
} else {
var index = 0
for patch in patchListGlobal {
if (newPatch.nextHarvest == newPatch.nextHarvest.earlierDate(patch.nextHarvest)) {
patchListGlobal.insert(newPatch, atIndex: index)
println("inserted at index \(index)")
break
} else if (index == patchListGlobal.count - 1){
patchListGlobal.append(newPatch)
println("added to end of array")
}
index++
}
}
var serializedPLG = NSKeyedArchiver.archivedDataWithRootObject(patchListGlobal)
storage.setObject(serializedPLG, forKey: "ForagerPatchList")
storage.synchronize()
println("saved")
self.navigationController.popToRootViewControllerAnimated(true)
}
//MARK: Map Delegate Stuff
func handleLongPress(sender: AnyObject) {
if let longPress = sender as? UILongPressGestureRecognizer {
switch longPress.state {
case .Began:
var touchpoint = longPress.locationInView(self.mapView)
var touchCoordinate = self.mapView.convertPoint(touchpoint, toCoordinateFromView: self.mapView)
var annotation = MKPointAnnotation()
annotation.coordinate = touchCoordinate
//Remove previous pin
self.mapView.removeAnnotations(mapView.annotations)
//Update the coordinates that will be set when user saves
self.lat = touchCoordinate.latitude
self.lon = touchCoordinate.longitude
self.mapView.addAnnotation(annotation)
default:
return
}
}
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
// var userlat = mapView.userLocation.coordinate.latitude
// var userlon = mapView.userLocation.coordinate.longitude
// var anlat = annotation.coordinate.latitude
// var anlon = annotation.coordinate.latitude
// // I was getting bizzare type errors when comparing the coordinates directly, so I resorted to this
// if ((userlat == anlat) && (userlon == anlon)) {
// println("coordinate match")
// return nil
// }
if let title = annotation.title {
//In the debugger, why can't I see "title" at this point?
if title != nil {
if title == "Current Location" {
println("title was 'Current Location'")
return nil
}
} else {
println("I should never execute")
}
}
var annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "id")
annotationView.animatesDrop = true
annotationView.canShowCallout = true
var rightButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as UIButton
annotationView.rightCalloutAccessoryView = rightButton
return annotationView
}
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
var annotation = view.annotation
var coordinates = annotation.coordinate
var lat = coordinates.latitude
}
func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
var region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 500, 500)
mapView.setRegion(region, animated: true)
}
}
| d8981d41006f5f49e26700496931058b | 37.202381 | 130 | 0.610471 | false | false | false | false |
NathanE73/Blackboard | refs/heads/main | Sources/BlackboardFramework/Source Code/SwiftSource.swift | mit | 1 | //
// Copyright (c) 2022 Nathan E. Walczak
//
// MIT License
//
// 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
class SwiftSource {
private var lines: [(indentLevel: Int, line: String)] = []
func append(_ line: String = "") {
if line.isEmpty && line == lines.last?.line {
return // don't allow multiple blank lines
}
if insideCommentBlock {
line.components(separatedBy: CharacterSet.newlines)
.forEach { comment in
lines.append((indentLevel, "/// \(comment)"))
}
} else {
lines.append((indentLevel, line))
}
}
func append(_ line: String, block: () -> Void) {
append("\(line) {")
let initialCount = lines.count
indent(block)
if lines.count - initialCount == 1, lines.last?.line.isEmpty == true {
lines.removeLast()
}
append("}")
}
var source: String {
var source: [String] = []
var indentLevel = 0
var indent = ""
lines.forEach { entry in
if indentLevel != entry.indentLevel {
indentLevel = entry.indentLevel
indent = ""
for _ in 0 ..< (indentLevel) {
indent.append(" ")
}
}
source.append("\(indent)\(entry.line)")
}
return source.joined(separator: "\n")
}
// MARK: Indent Level
var indentLevel = 0
func indent() {
indentLevel += 1
}
func unindent() {
indentLevel = max(0, indentLevel - 1)
}
func indent(_ block: (() -> Void)) {
indent()
block()
unindent()
}
// MARK: Comment Block
var insideCommentBlock = false
}
extension SwiftSource {
func append(source: String) -> Self {
source.components(separatedBy: CharacterSet.newlines)
.forEach(append)
return self
}
func commentBlock(block: () -> Void) {
insideCommentBlock = true
block()
insideCommentBlock = false
}
func appendHeading(filename: String, modules: [String], includeBundle: Bool = false) {
append("//")
append("// \(filename)")
append("//")
append("// This file is automatically generated; do not modify.")
append("//")
append()
modules.forEach { module in
append("import \(module)")
}
append()
if includeBundle {
append("private let bundle: Bundle = {")
indent {
append("class Object: NSObject { }")
append("return Bundle(for: Object.self)")
}
append("}()")
append()
}
}
}
| 0e508b4aa2710ea0ce26f96364812203 | 26.854167 | 90 | 0.548492 | false | false | false | false |
festrs/DotaComp | refs/heads/master | DotaComp/EventSoonGamesTableViewCell.swift | mit | 1 | //
// EventSoonGamesTableViewCell.swift
// DotaComp
//
// Created by Felipe Dias Pereira on 2017-03-08.
// Copyright © 2017 Felipe Dias Pereira. All rights reserved.
//
import UIKit
class EventSoonGamesTableViewCell: UITableViewCell {
@IBOutlet weak var bestOfLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var direLabel: UILabel!
@IBOutlet weak var radiantLabel: UILabel!
func setUpCellForUpComingGame(upComingGame: EventSoon) {
radiantLabel.text = upComingGame.team1
direLabel.text = upComingGame.team2
timeLabel.text = upComingGame.fullDate?.condensedWhitespace
bestOfLabel.text = "Best of \(upComingGame.bestof!)"
}
}
extension String {
var condensedWhitespace: String {
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
| cb863f821add5135689e27aa70e64cbb | 27.909091 | 92 | 0.707547 | false | false | false | false |
thankmelater23/relliK | refs/heads/master | relliK/Player.swift | unlicense | 1 | //
// Player.swift
// relliK
//
// Created by Andre Villanueva on 7/30/15.
// Copyright © 2015 Bang Bang Studios. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
class Player: Entity {
private static var __once: () = {
GlobalMainQueue.async {
let textureView = SKView()
}
SharedTexture.texture = SKTexture.init(image: UIImage.init(named: imagesString.player)!)
SharedTexture.texture.filteringMode = .nearest
}()
init(entityPosition: CGPoint) {
var entityTexture = SKTexture()
entityTexture = Player.generateTexture()!
// GlobalRellikPlayerConcurrent.async(group: nil, qos: .userInteractive, flags: .barrier, execute: {[weak self] in
super.init(position: entityPosition, texture: entityTexture)
name = "player"
setScale(playerScale)
directionOf = entityDirection.down
zPosition = 100.00
updateSpriteAtrributes()
setEntityTypeAttribures()
// })
}
override class func generateTexture() -> SKTexture? {
_ = Player.__once
return SharedTexture.texture
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal override func setAngle() {
switch (directionOf) {
case entityDirection.right:
run(SKAction.rotate(toAngle: 2 * π, duration: TimeInterval(0.0), shortestUnitArc: true))
case entityDirection.left:
run(SKAction.rotate(toAngle: π, duration: TimeInterval(0.0), shortestUnitArc: true))
case entityDirection.down:
run(SKAction.rotate(toAngle: (3 / 2) + π, duration: TimeInterval(0.0), shortestUnitArc: true))
case entityDirection.up:
run(SKAction.rotate(toAngle: π / 2, duration: TimeInterval(0.0), shortestUnitArc: true))
case entityDirection.unSelected:
//Dont run
directionOf = entityDirection.unSelected
log.verbose("direction unselected")
}
}
override func updateSpriteAtrributes() {
super.updateSpriteAtrributes()
self.physicsBody = SKPhysicsBody(rectangleOf: (self.frame.size))
// GlobalRellikPlayerConcurrent.async(group: nil, qos: .userInteractive, flags: .barrier, execute: {[weak self] in
self.physicsBody?.usesPreciseCollisionDetection = true
self.physicsBody?.categoryBitMask = PhysicsCategory.Player
self.physicsBody?.contactTestBitMask = PhysicsCategory.Enemy
self.physicsBody?.collisionBitMask = PhysicsCategory.None
// })
}
override func setEntityTypeAttribures() {
maxHealth = 3
health = maxHealth
hurtSoundString = "player hurt.wav"
attackSoundString = "attack.wav"
moveSoundString = "move.wav"
diedSoundString = "player died.wav"
directionOf = entityDirection.unSelected
entityCurrentBlock = blockPlace.unSelected
entityInRangeBlock = blockPlace.fourth
self.flashRedEffect = hurtEffects()
//childNodeWithName("bulletNode")
}
override func hurt() {
run(SKAction.sequence([
SKAction.colorize(
with: SKColor.red,
colorBlendFactor: 1.0,
duration: 0.0),
SKAction.wait(forDuration: 0.3), SKAction.run {
super.hurt()
}]))
}
override func died() {
run(SKAction.sequence([
SKAction.colorize(
with: SKColor.red,
colorBlendFactor: 1.0,
duration: 0.0),
SKAction.wait(forDuration: 0.3), SKAction.run {
super.died()
}]))
}
deinit {
log.verbose(#function)
log.verbose(self)
}
}
| b9948387b16f68263cd3cc1b0b4e6dff | 30.306306 | 117 | 0.680288 | false | false | false | false |
Instagram/IGListKit | refs/heads/main | Examples/Examples-iOS/IGListKitExamples/Views/EmbeddedCollectionViewCell.swift | mit | 1 | /*
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import IGListKit
import UIKit
final class EmbeddedCollectionViewCell: UICollectionViewCell {
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
view.backgroundColor = .clear
view.alwaysBounceVertical = false
view.alwaysBounceHorizontal = true
self.contentView.addSubview(view)
return view
}()
override func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = contentView.frame
}
}
| 6d3adb2471dcb15332a53dba39044bd3 | 27.793103 | 79 | 0.699401 | false | false | false | false |
cwwise/CWWeChat | refs/heads/master | CWWeChat/ChatModule/CWInput/Keyboard/InputTextView.swift | mit | 3 | //
// InputTextView.swift
// Keyboard
//
// Created by chenwei on 2017/7/23.
// Copyright © 2017年 cwwise. All rights reserved.
//
import UIKit
class InputTextView: UITextView {
//MARK: 属性
var placeHolder: String? {
didSet {
let maxChars = InputTextView.maxCharactersPerLine()
guard var placeHolder = placeHolder else {
return
}
if placeHolder.characters.count > maxChars {
let index = placeHolder.characters.index(placeHolder.startIndex, offsetBy: -8)
placeHolder = String(placeHolder[..<index])
self.placeHolder = placeHolder + "..."
}
self.setNeedsDisplay()
}
}
var placeHolderTextColor: UIColor? {
didSet {
self.setNeedsDisplay()
}
}
//MARK: Text view overrides
override var text: String! {
didSet {
self.setNeedsDisplay()
}
}
override var attributedText: NSAttributedString! {
didSet {
self.setNeedsDisplay()
}
}
override var contentInset: UIEdgeInsets {
didSet {
self.setNeedsDisplay()
}
}
override var font: UIFont? {
didSet {
self.setNeedsDisplay()
}
}
override var textAlignment: NSTextAlignment {
didSet {
self.setNeedsDisplay()
}
}
override func insertText(_ text: String) {
super.insertText(text)
self.setNeedsDisplay()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
placeHolderTextColor = UIColor.lightGray
self.enablesReturnKeyAutomatically = true
self.keyboardType = .default;
self.autoresizingMask = .flexibleWidth;
self.scrollIndicatorInsets = UIEdgeInsetsMake(10.0, 0.0, 10.0, 8.0)
self.contentInset = UIEdgeInsets.zero;
self.isScrollEnabled = true;
self.scrollsToTop = false;
self.isUserInteractionEnabled = true;
self.layer.borderWidth = 0.5
self.layer.borderColor = UIColor.gray.cgColor
self.layer.cornerRadius = 4
self.clipsToBounds = true
self.autocorrectionType = .no
self.autocapitalizationType = .none
self.font = UIFont.systemFont(ofSize: 16.0)
self.textColor = UIColor.black
self.backgroundColor = UIColor.white
self.keyboardAppearance = .default;
self.returnKeyType = .send;
self.textAlignment = .left;
}
deinit {
placeHolder = nil
placeHolderTextColor = nil
NotificationCenter.default.removeObserver(self)
}
//MARK: Drawing
override func draw(_ rect: CGRect) {
super.draw(rect)
if self.text.characters.count == 0 && (placeHolder != nil) {
let placeHolderRect = CGRect(x: 10.0,
y: 7.0,
width: rect.size.width,
height: rect.size.height);
self.placeHolderTextColor?.set()
let string = self.placeHolder! as NSString
string.draw(in: placeHolderRect, withAttributes: [NSAttributedStringKey.font:self.font!])
}
}
//最大行数
func numberOfLinesOfText() -> Int {
return InputTextView.numberOfLinesForMessage(self.text)
}
class func maxCharactersPerLine() -> Int {
return 33
}
class func numberOfLinesForMessage(_ text:String) -> Int {
return text.characters.count / InputTextView.maxCharactersPerLine() + 1
}
}
| 2c419d777191a180dff5576f34b0eb38 | 26.818182 | 101 | 0.5636 | false | false | false | false |
shaps80/InkKit | refs/heads/master | Example/Pods/GraphicsRenderer/GraphicsRenderer/Classes/ImageRenderer.swift | mit | 1 | //
// ImageRenderer.swift
// GraphicsRenderer
//
// Created by Shaps Benkau on 02/10/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
/**
* Represents an image renderer format
*/
public final class ImageRendererFormat: RendererFormat {
/**
Returns a default format, configured for this device. On OSX, this will flip the context to match iOS drawing.
- returns: A new format
*/
public static func `default`() -> ImageRendererFormat {
#if os(OSX)
return ImageRendererFormat(flipped: true)
#else
return ImageRendererFormat(flipped: false)
#endif
}
/// Returns the bounds for this format
public var bounds: CGRect
/// Get/set whether or not the resulting image should be opaque
public var opaque: Bool
/// Get/set the scale of the resulting image
public var scale: CGFloat
/// Get/set whether or not the context should be flipped while drawing
public var isFlipped: Bool
/**
Creates a new format with the specified bounds
- parameter bounds: The bounds of this format
- parameter opaque: Whether or not the resulting image should be opaque
- parameter scale: The scale of the resulting image
- returns: A new format
*/
internal init(bounds: CGRect, opaque: Bool = false, scale: CGFloat = screenScale(), flipped: Bool) {
self.bounds = bounds
self.opaque = opaque
self.scale = scale
self.isFlipped = flipped
}
public init(opaque: Bool = false, scale: CGFloat = screenScale(), flipped: Bool) {
self.bounds = .zero
self.scale = scale
self.isFlipped = flipped
self.opaque = opaque
}
}
/**
* Represents a new renderer context
*/
public final class ImageRendererContext: RendererContext {
/// The associated format
public let format: ImageRendererFormat
/// The associated CGContext
public let cgContext: CGContext
/// Returns a UIImage representing the current state of the renderer's CGContext
public var currentImage: Image {
#if os(OSX)
let cgImage = CGContext.current!.makeImage()!
return NSImage(cgImage: cgImage, size: format.bounds.size)
#else
return UIGraphicsGetImageFromCurrentImageContext()!
#endif
}
/**
Creates a new renderer context
- parameter format: The format for this context
- parameter cgContext: The associated CGContext to use for all drawing
- returns: A new renderer context
*/
internal init(format: ImageRendererFormat, cgContext: CGContext) {
self.format = format
self.cgContext = cgContext
}
}
/**
* Represents an image renderer used for drawing into a UIImage
*/
public final class ImageRenderer: Renderer {
/// The associated context type
public typealias Context = ImageRendererContext
/// Returns true
public let allowsImageOutput: Bool = true
/// Returns the format for this renderer
public let format: ImageRendererFormat
/**
Creates a new renderer with the specified size and format
- parameter size: The size of the resulting image
- parameter format: The format, provides additional options for this renderer
- returns: A new image renderer
*/
public init(size: CGSize, format: ImageRendererFormat? = nil) {
guard size != .zero else { fatalError("size cannot be zero") }
let bounds = CGRect(origin: .zero, size: size)
let opaque = format?.opaque ?? false
let scale = format?.scale ?? screenScale()
self.format = ImageRendererFormat(bounds: bounds, opaque: opaque, scale: scale, flipped: format?.isFlipped ?? false)
}
/**
Returns a new image with the specified drawing actions applied
- parameter actions: The drawing actions to apply
- returns: A new image
*/
public func image(actions: (Context) -> Void) -> Image {
var image: Image?
try? runDrawingActions(actions) { context in
image = context.currentImage
}
return image!
}
/**
Returns a PNG data representation of the resulting image
- parameter actions: The drawing actions to apply
- returns: A PNG data representation
*/
public func pngData(actions: (Context) -> Void) -> Data {
let image = self.image(actions: actions)
return image.pngRepresentation()!
}
/**
Returns a JPEG data representation of the resulting image
- parameter actions: The drawing actions to apply
- returns: A JPEG data representation
*/
public func jpegData(withCompressionQuality compressionQuality: CGFloat, actions: (Context) -> Void) -> Data {
let image = self.image(actions: actions)
return image.jpgRepresentation(quality: compressionQuality)!
}
private func runDrawingActions(_ drawingActions: (Context) -> Void, completionActions: ((Context) -> Void)? = nil) throws {
#if os(OSX)
let bitmap = NSImage(size: format.bounds.size)
bitmap.lockFocusFlipped(format.isFlipped)
let cgContext = CGContext.current!
let context = Context(format: format, cgContext: cgContext)
drawingActions(context)
completionActions?(context)
bitmap.unlockFocus()
#endif
#if os(iOS)
UIGraphicsBeginImageContextWithOptions(format.bounds.size, format.opaque, format.scale)
let cgContext = CGContext.current!
if format.isFlipped {
let transform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: format.bounds.height)
cgContext.concatenate(transform)
}
let context = Context(format: format, cgContext: cgContext)
drawingActions(context)
completionActions?(context)
UIGraphicsEndImageContext()
#endif
}
}
| aa1beb8fb41675649b27986b02adfebb | 30.343434 | 127 | 0.624718 | false | false | false | false |
tokyovigilante/CesiumKit | refs/heads/master | CesiumKit/Renderer/Imagebuffer.swift | apache-2.0 | 1 | //
// ImageBuffer.swift
// CesiumKit
//
// Created by Ryan Walklin on 16/08/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
/// raw image data, default 32-bit RGBA
class Imagebuffer {
let array: [UInt8]
let width: Int
let height: Int
let bytesPerPixel: Int
init(array: [UInt8], width: Int, height: Int, bytesPerPixel bpp: Int = 4) {
self.array = array
self.width = width
self.height = height
self.bytesPerPixel = bpp
}
} | 7d3840da910d8c0cdef99ac9a2cad99d | 21 | 79 | 0.607921 | false | false | false | false |
xxxAIRINxxx/ViewPagerController | refs/heads/master | Proj/Demo/NavSampleViewController.swift | mit | 1 | //
// NavSampleViewController.swift
// Demo
//
// Created by xxxAIRINxxx on 2016/01/05.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import UIKit
import ViewPagerController
class NavSampleViewController : UIViewController {
@IBOutlet weak var layerView : UIView!
var pagerController : ViewPagerController?
override func viewDidLoad() {
super.viewDidLoad()
let pagerController = ViewPagerController()
pagerController.setParentController(self, parentView: self.layerView)
var appearance = ViewPagerControllerAppearance()
appearance.tabMenuHeight = 44.0
appearance.scrollViewMinPositionY = 20.0
appearance.scrollViewObservingType = .navigationBar(targetNavigationBar: self.navigationController!.navigationBar)
appearance.tabMenuAppearance.backgroundColor = UIColor.darkGray
appearance.tabMenuAppearance.selectedViewBackgroundColor = UIColor.blue
appearance.tabMenuAppearance.selectedViewInsets = UIEdgeInsets(top: 39, left: 0, bottom: 0, right: 0)
pagerController.updateAppearance(appearance)
pagerController.willBeginTabMenuUserScrollingHandler = { selectedView in
selectedView.alpha = 0.0
}
pagerController.didEndTabMenuUserScrollingHandler = { selectedView in
selectedView.alpha = 1.0
}
pagerController.changeObserveScrollViewHandler = { controller in
let detailController = controller as! DetailViewController
return detailController.tableView
}
pagerController.didChangeHeaderViewHeightHandler = { height in
print("call didShowViewControllerHandler : \(height)")
}
for title in sampleDataTitles {
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
controller.view.clipsToBounds = true
controller.title = title
controller.parentController = self
pagerController.addContent(title, viewController: controller)
}
self.pagerController = pagerController
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "remove", style: .plain, target: self, action: #selector(NavSampleViewController.remove))
}
@objc fileprivate func remove() {
guard let c = self.pagerController?.childViewControllers.first else { return }
self.pagerController?.removeContent(c)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.pagerController?.resetNavigationBarHeight(true)
}
}
| 0c2f2b6ceb53644b9a40a02bb3eee500 | 35.896104 | 161 | 0.675466 | false | false | false | false |
DeepestDesire/GC | refs/heads/master | Pods/ReactiveSwift/Sources/Action.swift | apache-2.0 | 3 | import Dispatch
import Foundation
import Result
/// `Action` represents a repeatable work like `SignalProducer`. But on top of the
/// isolation of produced `Signal`s from a `SignalProducer`, `Action` provides
/// higher-order features like availability and mutual exclusion.
///
/// Similar to a produced `Signal` from a `SignalProducer`, each unit of the repreatable
/// work may output zero or more values, and terminate with or without an error at some
/// point.
///
/// The core of `Action` is the `execute` closure it created with. For every execution
/// attempt with a varying input, if the `Action` is enabled, it would request from the
/// `execute` closure a customized unit of work — represented by a `SignalProducer`.
/// Specifically, the `execute` closure would be supplied with the latest state of
/// `Action` and the external input from `apply()`.
///
/// `Action` enforces serial execution, and disables the `Action` during the execution.
public final class Action<Input, Output, Error: Swift.Error> {
private struct ActionState<Value> {
var isEnabled: Bool {
return isUserEnabled && !isExecuting
}
var isUserEnabled: Bool
var isExecuting: Bool
var value: Value
}
private let execute: (Action<Input, Output, Error>, Input) -> SignalProducer<Output, ActionError<Error>>
private let eventsObserver: Signal<Signal<Output, Error>.Event, NoError>.Observer
private let disabledErrorsObserver: Signal<(), NoError>.Observer
private let deinitToken: Lifetime.Token
/// The lifetime of the `Action`.
public let lifetime: Lifetime
/// A signal of all events generated from all units of work of the `Action`.
///
/// In other words, this sends every `Event` from every unit of work that the `Action`
/// executes.
public let events: Signal<Signal<Output, Error>.Event, NoError>
/// A signal of all values generated from all units of work of the `Action`.
///
/// In other words, this sends every value from every unit of work that the `Action`
/// executes.
public let values: Signal<Output, NoError>
/// A signal of all errors generated from all units of work of the `Action`.
///
/// In other words, this sends every error from every unit of work that the `Action`
/// executes.
public let errors: Signal<Error, NoError>
/// A signal of all failed attempts to start a unit of work of the `Action`.
public let disabledErrors: Signal<(), NoError>
/// A signal of all completed events generated from applications of the action.
///
/// In other words, this will send completed events from every signal generated
/// by each SignalProducer returned from apply().
public let completed: Signal<(), NoError>
/// Whether the action is currently executing.
public let isExecuting: Property<Bool>
/// Whether the action is currently enabled.
public let isEnabled: Property<Bool>
/// Initializes an `Action` that would be conditionally enabled depending on its
/// state.
///
/// When the `Action` is asked to start the execution with an input value, a unit of
/// work — represented by a `SignalProducer` — would be created by invoking
/// `execute` with the latest state and the input value.
///
/// - note: `Action` guarantees that changes to `state` are observed in a
/// thread-safe way. Thus, the value passed to `isEnabled` will
/// always be identical to the value passed to `execute`, for each
/// application of the action.
///
/// - note: This initializer should only be used if you need to provide
/// custom input can also influence whether the action is enabled.
/// The various convenience initializers should cover most use cases.
///
/// - parameters:
/// - state: A property to be the state of the `Action`.
/// - isEnabled: A predicate which determines the availability of the `Action`,
/// given the latest `Action` state.
/// - execute: A closure that produces a unit of work, as `SignalProducer`, to be
/// executed by the `Action`.
public init<State: PropertyProtocol>(state: State, enabledIf isEnabled: @escaping (State.Value) -> Bool, execute: @escaping (State.Value, Input) -> SignalProducer<Output, Error>) {
let isUserEnabled = isEnabled
(lifetime, deinitToken) = Lifetime.make()
// `Action` retains its state property.
lifetime.observeEnded { _ = state }
(events, eventsObserver) = Signal<Signal<Output, Error>.Event, NoError>.pipe()
(disabledErrors, disabledErrorsObserver) = Signal<(), NoError>.pipe()
values = events.filterMap { $0.value }
errors = events.filterMap { $0.error }
completed = events.filterMap { $0.isCompleted ? () : nil }
let actionState = MutableProperty(ActionState<State.Value>(isUserEnabled: true, isExecuting: false, value: state.value))
// `isEnabled` and `isExecuting` have their own backing so that when the observers
// of these synchronously affects the action state, the signal of the action state
// does not deadlock due to the recursion.
let isExecuting = MutableProperty(false)
self.isExecuting = Property(capturing: isExecuting)
let isEnabled = MutableProperty(actionState.value.isEnabled)
self.isEnabled = Property(capturing: isEnabled)
func modifyActionState<Result>(_ action: (inout ActionState<State.Value>) throws -> Result) rethrows -> Result {
return try actionState.begin { storage in
let oldState = storage.value
defer {
let newState = storage.value
if oldState.isEnabled != newState.isEnabled {
isEnabled.value = newState.isEnabled
}
if oldState.isExecuting != newState.isExecuting {
isExecuting.value = newState.isExecuting
}
}
return try storage.modify(action)
}
}
lifetime += state.producer.startWithValues { value in
modifyActionState { state in
state.value = value
state.isUserEnabled = isUserEnabled(value)
}
}
self.execute = { action, input in
return SignalProducer { observer, lifetime in
let latestState: State.Value? = modifyActionState { state in
guard state.isEnabled else {
return nil
}
state.isExecuting = true
return state.value
}
guard let state = latestState else {
observer.send(error: .disabled)
action.disabledErrorsObserver.send(value: ())
return
}
let interruptHandle = execute(state, input).start { event in
observer.send(event.mapError(ActionError.producerFailed))
action.eventsObserver.send(value: event)
}
lifetime.observeEnded {
interruptHandle.dispose()
modifyActionState { $0.isExecuting = false }
}
}
}
}
/// Initializes an `Action` that uses a property as its state.
///
/// When the `Action` is asked to start the execution, a unit of work — represented by
/// a `SignalProducer` — would be created by invoking `execute` with the latest value
/// of the state.
///
/// - parameters:
/// - state: A property to be the state of the `Action`.
/// - execute: A closure that produces a unit of work, as `SignalProducer`, to
/// be executed by the `Action`.
public convenience init<P: PropertyProtocol>(state: P, execute: @escaping (P.Value, Input) -> SignalProducer<Output, Error>) {
self.init(state: state, enabledIf: { _ in true }, execute: execute)
}
/// Initializes an `Action` that would be conditionally enabled.
///
/// When the `Action` is asked to start the execution with an input value, a unit of
/// work — represented by a `SignalProducer` — would be created by invoking
/// `execute` with the input value.
///
/// - parameters:
/// - isEnabled: A property which determines the availability of the `Action`.
/// - execute: A closure that produces a unit of work, as `SignalProducer`, to be
/// executed by the `Action`.
public convenience init<P: PropertyProtocol>(enabledIf isEnabled: P, execute: @escaping (Input) -> SignalProducer<Output, Error>) where P.Value == Bool {
self.init(state: isEnabled, enabledIf: { $0 }) { _, input in
execute(input)
}
}
/// Initializes an `Action` that uses a property of optional as its state.
///
/// When the `Action` is asked to start executing, a unit of work (represented by
/// a `SignalProducer`) is created by invoking `execute` with the latest value
/// of the state and the `input` that was passed to `apply()`.
///
/// If the property holds a `nil`, the `Action` would be disabled until it is not
/// `nil`.
///
/// - parameters:
/// - state: A property of optional to be the state of the `Action`.
/// - execute: A closure that produces a unit of work, as `SignalProducer`, to
/// be executed by the `Action`.
public convenience init<P: PropertyProtocol, T>(unwrapping state: P, execute: @escaping (T, Input) -> SignalProducer<Output, Error>) where P.Value == T? {
self.init(state: state, enabledIf: { $0 != nil }) { state, input in
execute(state!, input)
}
}
/// Initializes an `Action` that would always be enabled.
///
/// When the `Action` is asked to start the execution with an input value, a unit of
/// work — represented by a `SignalProducer` — would be created by invoking
/// `execute` with the input value.
///
/// - parameters:
/// - execute: A closure that produces a unit of work, as `SignalProducer`, to be
/// executed by the `Action`.
public convenience init(execute: @escaping (Input) -> SignalProducer<Output, Error>) {
self.init(enabledIf: Property(value: true), execute: execute)
}
deinit {
eventsObserver.sendCompleted()
disabledErrorsObserver.sendCompleted()
}
/// Create a `SignalProducer` that would attempt to create and start a unit of work of
/// the `Action`. The `SignalProducer` would forward only events generated by the unit
/// of work it created.
///
/// If the execution attempt is failed, the producer would fail with
/// `ActionError.disabled`.
///
/// - parameters:
/// - input: A value to be used to create the unit of work.
///
/// - returns: A producer that forwards events generated by its started unit of work,
/// or emits `ActionError.disabled` if the execution attempt is failed.
public func apply(_ input: Input) -> SignalProducer<Output, ActionError<Error>> {
return execute(self, input)
}
}
extension Action: BindingTargetProvider {
public var bindingTarget: BindingTarget<Input> {
return BindingTarget(lifetime: lifetime) { [weak self] in self?.apply($0).start() }
}
}
extension Action where Input == Void {
/// Create a `SignalProducer` that would attempt to create and start a unit of work of
/// the `Action`. The `SignalProducer` would forward only events generated by the unit
/// of work it created.
///
/// If the execution attempt is failed, the producer would fail with
/// `ActionError.disabled`.
///
/// - returns: A producer that forwards events generated by its started unit of work,
/// or emits `ActionError.disabled` if the execution attempt is failed.
public func apply() -> SignalProducer<Output, ActionError<Error>> {
return apply(())
}
/// Initializes an `Action` that uses a property of optional as its state.
///
/// When the `Action` is asked to start the execution, a unit of work — represented by
/// a `SignalProducer` — would be created by invoking `execute` with the latest value
/// of the state.
///
/// If the property holds a `nil`, the `Action` would be disabled until it is not
/// `nil`.
///
/// - parameters:
/// - state: A property of optional to be the state of the `Action`.
/// - execute: A closure that produces a unit of work, as `SignalProducer`, to
/// be executed by the `Action`.
public convenience init<P: PropertyProtocol, T>(unwrapping state: P, execute: @escaping (T) -> SignalProducer<Output, Error>) where P.Value == T? {
self.init(unwrapping: state) { state, _ in
execute(state)
}
}
/// Initializes an `Action` that uses a property as its state.
///
/// When the `Action` is asked to start the execution, a unit of work — represented by
/// a `SignalProducer` — would be created by invoking `execute` with the latest value
/// of the state.
///
/// - parameters:
/// - state: A property to be the state of the `Action`.
/// - execute: A closure that produces a unit of work, as `SignalProducer`, to
/// be executed by the `Action`.
public convenience init<P: PropertyProtocol, T>(state: P, execute: @escaping (T) -> SignalProducer<Output, Error>) where P.Value == T {
self.init(state: state) { state, _ in
execute(state)
}
}
}
/// `ActionError` represents the error that could be emitted by a unit of work of a
/// certain `Action`.
public enum ActionError<Error: Swift.Error>: Swift.Error {
/// The execution attempt was failed, since the `Action` was disabled.
case disabled
/// The unit of work emitted an error.
case producerFailed(Error)
}
extension ActionError where Error: Equatable {
public static func == (lhs: ActionError<Error>, rhs: ActionError<Error>) -> Bool {
switch (lhs, rhs) {
case (.disabled, .disabled):
return true
case let (.producerFailed(left), .producerFailed(right)):
return left == right
default:
return false
}
}
}
| 21d1887e750f0ca35f45f9fe74bd5630 | 38.3125 | 181 | 0.691271 | false | false | false | false |
0x4a616e/ArtlessEdit | refs/heads/master | ArtlessEdit/DefaultSettingsViewController.swift | bsd-3-clause | 1 | //
// DefaultSettingsViewController.swift
// ArtlessEdit
//
// Created by Jan Gassen on 28/12/14.
// Copyright (c) 2014 Jan Gassen. All rights reserved.
//
import Foundation
class DefaultSettingsViewController: NSViewController {
var editorSettingsController: EditorSettingsViewController? = nil
var settingsModeController: ModeSettingsViewController? = nil
@IBOutlet weak var editorSettings: NSScrollView!
override func viewDidLoad() {
let stackView = SideBarStackView()
let settings = EditorDefaultSettings()
editorSettingsController = EditorSettingsViewController(nibName: "EditorSettings", handler: settings)
if let settingsView = editorSettingsController?.view {
stackView.addView(settingsView, inGravity: NSStackViewGravity.Center)
}
settingsModeController = ModeSettingsViewController(nibName: "ModeSettings", bundle: nil, settings: settings, controller: editorSettingsController)
if let settingsView = settingsModeController?.view {
stackView.addView(settingsView, inGravity: NSStackViewGravity.Top)
}
editorSettings?.documentView = stackView
}
} | facc7a720bfa86ed28251b20d56a7982 | 35.787879 | 155 | 0.716406 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Legacy/Neocom/Neocom II Tests/Router_Tests.swift | lgpl-2.1 | 2 | //
// Router_Tests.swift
// Neocom II Tests
//
// Created by Artem Shimanski on 03.09.2018.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import XCTest
@testable import Neocom
import Futures
class Router_Tests: TestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testPush() {
let exp = expectation(description: "wait")
let root = try! RouterTests.default.instantiate().get()
let navigationController = UINavigationController(rootViewController: root)
var window: UIWindow? = UIWindow(frame: navigationController.view.frame)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
Route<RouterTests>(assembly: RouterTests.default, kind: .push).perform(from: root).then(on: .main) { result in
XCTAssertEqual(navigationController.viewControllers.count, 2)
let last = navigationController.viewControllers.last as! RouterTestsViewController
Route<RouterTests>(assembly: RouterTests.default, kind: .push).perform(from: last).then(on: .main) { result in
XCTAssertEqual(navigationController.viewControllers.count, 3)
let last = navigationController.viewControllers.last as! RouterTestsViewController
last.unwinder!.unwind(to: root).then(on: .main) { _ in
XCTAssertEqual(navigationController.viewControllers.count, 1)
exp.fulfill()
}
}
}
wait(for: [exp], timeout: 10)
window = nil
}
func testModal() {
let exp = expectation(description: "wait")
let root = try! RouterTests.default.instantiate().get()
let navigationController = UINavigationController(rootViewController: root)
var window: UIWindow? = UIWindow(frame: navigationController.view.frame)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
Route<RouterTests>(assembly: RouterTests.default, kind: .modal).perform(from: root).then(on: .main) { result in
let chain = sequence(first: navigationController, next: {$0.presentedViewController}).map{$0}
XCTAssertEqual(chain.count, 2)
let last = chain.last as! RouterTestsViewController
Route<RouterTests>(assembly: RouterTests.default, kind: .modal).perform(from: last).then(on: .main) { result in
let chain = sequence(first: navigationController, next: {$0.presentedViewController}).map{$0}
XCTAssertEqual(chain.count, 3)
let last = chain.last as! RouterTestsViewController
last.unwinder!.unwind(to: root).then(on: .main) { _ in
let chain = sequence(first: navigationController, next: {$0.presentedViewController}).map{$0}
XCTAssertEqual(chain.count, 1)
exp.fulfill()
}
}
}
wait(for: [exp], timeout: 10)
window = nil
}
func testPushModal() {
let exp = expectation(description: "wait")
let root = try! RouterTests.default.instantiate().get()
let navigationController = UINavigationController(rootViewController: root)
var window: UIWindow? = UIWindow(frame: navigationController.view.frame)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
Route<RouterTests>(assembly: RouterTests.default, kind: .push).perform(from: root).then(on: .main) { result in
XCTAssertEqual(navigationController.viewControllers.count, 2)
let last = navigationController.viewControllers.last as! RouterTestsViewController
Route<RouterTests>(assembly: RouterTests.default, kind: .modal).perform(from: last).then(on: .main) { result in
let chain = sequence(first: navigationController, next: {$0.presentedViewController}).map{$0}
XCTAssertEqual(chain.count, 2)
let last = chain.last as! RouterTestsViewController
last.unwinder!.unwind(to: root).then(on: .main) { _ in
XCTAssertEqual(navigationController.viewControllers.count, 1)
let chain = sequence(first: navigationController, next: {$0.presentedViewController}).map{$0}
XCTAssertEqual(chain.count, 1)
exp.fulfill()
}
}
}
wait(for: [exp], timeout: 10)
window = nil
}
}
enum RouterTests: Assembly {
case `default`
func instantiate(_ input: RouterTestsViewController.Input) -> Future<RouterTestsViewController> {
return .init(RouterTestsViewController())
}
}
class RouterTestsViewController: UIViewController, View {
var unwinder: Unwinder?
lazy var presenter: RouterTestsPresenter! = RouterTestsPresenter(view: self)
}
class RouterTestsPresenter: Presenter {
weak var view: RouterTestsViewController?
lazy var interactor: RouterTestsInteractor! = RouterTestsInteractor(presenter: self)
required init(view: RouterTestsViewController) {
self.view = view
}
}
class RouterTestsInteractor: Interactor {
weak var presenter: RouterTestsPresenter?
required init(presenter: RouterTestsPresenter) {
self.presenter = presenter
}
}
| f5e0f219fe56fdce457dbdf0b7f444b4 | 34.133803 | 114 | 0.734416 | false | true | false | false |
amraboelela/swift | refs/heads/master | test/decl/ext/generic.swift | apache-2.0 | 6 | // RUN: %target-typecheck-verify-swift
protocol P1 { associatedtype AssocType }
protocol P2 : P1 { }
protocol P3 { }
struct X<T : P1, U : P2, V> {
struct Inner<A, B : P3> { }
struct NonGenericInner { }
}
extension Int : P1 {
typealias AssocType = Int
}
extension Double : P2 {
typealias AssocType = Double
}
extension X<Int, Double, String> {
// expected-error@-1{{constrained extension must be declared on the unspecialized generic type 'X' with constraints specified by a 'where' clause}}
let x = 0
// expected-error@-1 {{extensions must not contain stored properties}}
static let x = 0
// expected-error@-1 {{static stored properties not supported in generic types}}
func f() -> Int {}
class C<T> {}
}
typealias GGG = X<Int, Double, String>
extension GGG { } // okay through a typealias
// Lvalue check when the archetypes are not the same.
struct LValueCheck<T> {
let x = 0
}
extension LValueCheck {
init(newY: Int) {
x = 42
}
}
// Member type references into another extension.
struct MemberTypeCheckA<T> { }
protocol MemberTypeProto {
associatedtype AssocType
func foo(_ a: AssocType)
init(_ assoc: MemberTypeCheckA<AssocType>)
}
struct MemberTypeCheckB<T> : MemberTypeProto {
func foo(_ a: T) {}
typealias Element = T
var t1: T
}
extension MemberTypeCheckB {
typealias Underlying = MemberTypeCheckA<T>
}
extension MemberTypeCheckB {
init(_ x: Underlying) { }
}
extension MemberTypeCheckB {
var t2: Element { return t1 }
}
// rdar://problem/19795284
extension Array {
var pairs: [(Element, Element)] {
get {
return []
}
}
}
// rdar://problem/21001937
struct GenericOverloads<T, U> {
var t: T
var u: U
init(t: T, u: U) { self.t = t; self.u = u }
func foo() { }
var prop: Int { return 0 }
subscript (i: Int) -> Int { return i }
}
extension GenericOverloads where T : P1, U : P2 {
init(t: T, u: U) { self.t = t; self.u = u }
func foo() { }
var prop: Int { return 1 }
subscript (i: Int) -> Int { return i }
}
extension Array where Element : Hashable { // expected-note {{where 'Element' = 'T'}}
var worseHashEver: Int {
var result = 0
for elt in self {
result = (result << 1) ^ elt.hashValue
}
return result
}
}
func notHashableArray<T>(_ x: [T]) {
x.worseHashEver // expected-error{{property 'worseHashEver' requires that 'T' conform to 'Hashable'}}
}
func hashableArray<T : Hashable>(_ x: [T]) {
// expected-warning @+1 {{unused}}
x.worseHashEver // okay
}
func intArray(_ x: [Int]) {
// expected-warning @+1 {{unused}}
x.worseHashEver
}
class GenericClass<T> { }
extension GenericClass where T : Equatable {
func foo(_ x: T, y: T) -> Bool { return x == y }
}
func genericClassEquatable<T : Equatable>(_ gc: GenericClass<T>, x: T, y: T) {
_ = gc.foo(x, y: y)
}
func genericClassNotEquatable<T>(_ gc: GenericClass<T>, x: T, y: T) {
gc.foo(x, y: y) // expected-error{{argument type 'T' does not conform to expected type 'Equatable'}}
}
extension Array where Element == String { }
extension GenericClass : P3 where T : P3 { }
extension GenericClass where Self : P3 { }
// expected-error@-1{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'GenericClass'?}} {{30-34=GenericClass}}
protocol P4 {
associatedtype T
init(_: T)
}
protocol P5 { }
struct S4<Q>: P4 {
init(_: Q) { }
}
extension S4 where T : P5 {}
struct S5<Q> {
init(_: Q) { }
}
extension S5 : P4 {}
// rdar://problem/21607421
public typealias Array2 = Array
extension Array2 where QQQ : VVV {}
// expected-error@-1 {{use of undeclared type 'QQQ'}}
// expected-error@-2 {{use of undeclared type 'VVV'}}
// https://bugs.swift.org/browse/SR-9009
func foo() {
extension Array where Element : P1 {
// expected-error@-1 {{declaration is only valid at file scope}}
func foo() -> Element.AssocType {}
}
}
// Deeply nested
protocol P6 {
associatedtype Assoc1
associatedtype Assoc2
}
struct A<T, U, V> {
struct B<W, X, Y> {
struct C<Z: P6> {
}
}
}
extension A.B.C where T == V, X == Z.Assoc2 {
func f() { }
}
// Extensions of nested non-generics within generics.
extension A.B {
struct D { }
}
extension A.B.D {
func g() { }
}
// rdar://problem/43955962
struct OldGeneric<T> {}
typealias NewGeneric<T> = OldGeneric<T>
extension NewGeneric {
static func oldMember() -> OldGeneric {
return OldGeneric()
}
static func newMember() -> NewGeneric {
return NewGeneric()
}
}
| 08ef44213be72660bd1ff8aab1008af5 | 19.026667 | 155 | 0.643586 | false | false | false | false |
ianyh/Highball | refs/heads/master | Highball/NSAttributedString+Trim.swift | mit | 1 | //
// NSAttributedString+Trim.swift
// Highball
//
// Created by Ian Ynda-Hummel on 4/4/16.
// Copyright © 2016 ianynda. All rights reserved.
//
import Foundation
public extension NSAttributedString {
public func attributedStringByTrimmingNewlines() -> NSAttributedString {
var attributedString = self
while attributedString.string.characters.first == "\n" {
attributedString = attributedString.attributedSubstringFromRange(NSMakeRange(1, attributedString.string.characters.count - 1))
}
while attributedString.string.characters.last == "\n" {
attributedString = attributedString.attributedSubstringFromRange(NSMakeRange(0, attributedString.string.characters.count - 1))
}
return attributedString
}
}
| 85b1b841b256428733299411569207a1 | 32.045455 | 129 | 0.771664 | false | false | false | false |
qinting513/SwiftNote | refs/heads/master | PullToRefreshKit-master 自定义刷新控件/PullToRefreshKit/YahooWeatherRefreshHeader.swift | apache-2.0 | 1 | //
// YahooWeatherRefreshHeader.swift
// PullToRefreshKit
//
// Created by huangwenchen on 16/8/2.
// Copyright © 2016年 Leo. All rights reserved.
//
import Foundation
import UIKit
class YahooWeatherRefreshHeader: UIView,RefreshableHeader{
let imageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 40, height: 40))
let logoImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 60, height: 14))
let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor(white: 0.0, alpha: 0.25)
logoImage.center = CGPoint(x: self.bounds.width/2.0, y: frame.height - 30 - 7.0)
imageView.center = CGPoint(x: self.bounds.width/2.0 - 60.0, y: frame.height - 30)
imageView.image = UIImage(named: "sun_000000")
logoImage.image = UIImage(named: "yahoo_logo")
label.frame = CGRect(x: logoImage.frame.origin.x, y: logoImage.frame.origin.y + logoImage.frame.height + 2,width: 200, height: 20)
label.textColor = UIColor.white
label.font = UIFont.systemFont(ofSize: 12)
label.text = "Last update: 5 minutes ago"
addSubview(imageView)
addSubview(logoImage)
addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - RefreshableHeader -
func heightForRefreshingState()->CGFloat{
return 60
}
func percentUpdateDuringScrolling(_ percent: CGFloat) {
let adjustPercent = max(min(1.0, percent),0.0)
let index = Int(adjustPercent * 27)
let imageName = index < 10 ? "sun_0000\(index)" : "sun_000\(index)"
imageView.image = UIImage(named:imageName)
}
func startTransitionAnimation(){
imageView.image = UIImage(named: "sun_00073")
let images = (27...72).map({"sun_000\($0)"}).map({UIImage(named:$0)!})
imageView.animationImages = images
imageView.animationDuration = Double(images.count) * 0.02
imageView.animationRepeatCount = 1
imageView.startAnimating()
self.perform(#selector(YahooWeatherRefreshHeader.transitionFinihsed), with: nil, afterDelay: imageView.animationDuration)
}
func transitionFinihsed(){
imageView.stopAnimating()
let images = (73...109).map({return $0 < 100 ? "sun_000\($0)" : "sun_00\($0)"}).map({UIImage(named:$0)!})
imageView.animationImages = images
imageView.animationDuration = Double(images.count) * 0.03
imageView.animationRepeatCount = 1000000
imageView.startAnimating()
}
//松手即将刷新的状态
func didBeginRefreshingState(){
imageView.image = nil
startTransitionAnimation()
}
//刷新结束,将要隐藏header
func didBeginEndRefershingAnimation(_ result:RefreshResult){
}
//刷新结束,完全隐藏header
func didCompleteEndRefershingAnimation(_ result:RefreshResult){
imageView.stopAnimating()
imageView.animationImages = nil
imageView.image = UIImage(named: "sun_000000")
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(YahooWeatherRefreshHeader.transitionFinihsed), object: nil)
}
}
| 41704066c3d3668ce10f7ff1b3252a98 | 39.25 | 144 | 0.657764 | false | false | false | false |
SergeMaslyakov/audio-player | refs/heads/master | app/src/controllers/music/cells/MusicSongTableViewCell.swift | apache-2.0 | 1 | //
// MusicSongTableViewCell.swift
// AudioPlayer
//
// Created by Serge Maslyakov on 07/07/2017.
// Copyright © 2017 Maslyakov. All rights reserved.
//
import UIKit
import MediaPlayer
import TableKit
final class MusicSongTableViewCell: UITableViewCell, ConfigurableCell, DecoratableCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var albumImage: UIImageView!
@IBOutlet weak var controlImage: UIImageView!
static var estimatedHeight: CGFloat? {
return ThemeHeightHelper.Songs.cellHeight
}
static var defaultHeight: CGFloat? {
return ThemeHeightHelper.Songs.cellHeight
}
override func awakeFromNib() {
super.awakeFromNib()
decorate()
}
/// MARK: ConfigurableCell
func configure(with item: SongCellData) {
nameLabel.text = item.song.title
descriptionLabel.text = trackDescription(fromItem: item.song)
var defaultImage = true
var image: UIImage? = item.defaultCoverImage
let imageSize = CGSize(width: round(albumImage.bounds.size.width), height: round(albumImage.bounds.size.height))
// For best performance. Image rendering in the background thread
DispatchQueue.global(qos: .userInitiated).async {
if let artwork = item.song.artwork {
defaultImage = false
image = artwork.image(at: imageSize)
}
DispatchQueue.main.async {
// see apple bug "https://stackoverflow.com/questions/7667631/mpmediaitemartwork-returning-wrong-sized-artwork"
self.controlImage.image = item.controlImage
self.albumImage.contentMode = defaultImage ? .center : .scaleToFill
self.albumImage.image = image
}
}
}
/// MARK: Formatters
func trackDescription(fromItem item: MPMediaItem) -> String {
var description: String = ""
if let artist = item.albumArtist {
description = artist + " - "
}
description += formattedDuration(fromItem: item)
return description
}
func formattedDuration(fromItem item: MPMediaItem) -> String {
if item.playbackDuration < 3600 {
return TimeFormatter.msFrom(seconds: Int(item.playbackDuration))
} else {
return TimeFormatter.hmsFrom(seconds: Int(item.playbackDuration))
}
}
/// MARK: DecoratableCell
func decorate() {
nameLabel.textColor = UIColor.MusicSongCell.titleText
descriptionLabel.textColor = UIColor.MusicSongCell.descriptionText
}
}
| 80b67f97c87f559863032655930eb092 | 29.25 | 127 | 0.653644 | false | false | false | false |
royratcliffe/Snippets | refs/heads/master | Sources/Sequence+Snippets.swift | mit | 1 | // Snippets SequenceType+Snippets.swift
//
// Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom
//
// 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, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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.
//
//------------------------------------------------------------------------------
extension Sequence {
/// Groups a sequence by the results of the given block.
/// - parameter block: answers a group for a given element.
/// - returns: a dictionary of groups where the keys derive from the evaluated
/// results of the block, and the values are arrays of elements belonging to
/// each group. The array values preserve the order of the original
/// sequence.
public func groupBy(_ block: (Iterator.Element) -> AnyHashable) -> [AnyHashable: [Iterator.Element]] {
typealias Element = Iterator.Element
var groups = [AnyHashable: [Element]]()
forEach { (element) -> () in
let group = block(element)
if var values = groups[group] {
values.append(element)
groups[group] = values
} else {
groups[group] = [element]
}
}
return groups
}
/// - parameter block: Block answering true or false for each given element.
/// - returns: True if all blocks answer true or there are no elements in the
/// sequence; in other words, true if there are no blocks answering false.
///
/// Searches for false returned by the block with each sequence element. The
/// implementation optimises the sequence iteration by searching the sequence
/// for the first false, then returning. A less-efficient implementation might
/// first map all the blocks to a sequence of booleans, then search for false;
/// as follows.
///
/// return map { (element) -> Bool in
/// block(element)
/// }.all
///
public func all(_ block: (Iterator.Element) -> Bool) -> Bool {
for element in self {
if !block(element) {
return false
}
}
return true
}
/// - parameter block: Block that answers a true or false condition for a
/// given sequence element.
/// - returns: True if any element answers true, false otherwise; false also
/// for empty sequences.
///
/// Searches for true. The implementation performs an early-out
/// optimisation. It calls the block for all the elements until a block
/// returns true, and immediately returns true thereafter. It does not
/// continue to iterate through any remaining elements, nor continue to call
/// the block as the straightforward implementation might, see below. There is
/// no need.
///
/// return map { (element) -> Bool in
/// block(element)
/// }.any
///
public func any(_ block: (Iterator.Element) -> Bool) -> Bool {
for element in self {
if block(element) {
return true
}
}
return false
}
}
| a4267adae5e182944ceb9faf54aee961 | 39.25 | 104 | 0.669255 | false | false | false | false |
radoslavyordanov/QuizGames-iOS | refs/heads/master | QuizGames/LoginViewController.swift | apache-2.0 | 1 | /*
* Copyright 2016 Radoslav Yordanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import Alamofire
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var rememberMe: UISwitch!
@IBOutlet weak var login: UIButton!
@IBOutlet weak var register: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
login.layer.cornerRadius = 5
login.layer.borderWidth = 1
login.layer.borderColor = UIColor.whiteColor().CGColor
register.layer.cornerRadius = 5
register.layer.borderWidth = 1
register.layer.borderColor = UIColor.whiteColor().CGColor
username.delegate = self
username.tag = 1
password.delegate = self
password.tag = 2
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let preferences = NSUserDefaults.standardUserDefaults()
let userId = preferences.integerForKey(Util.USER_ID_PREF)
if userId != 0 {
Util.userId = userId
Util.userRoleId = preferences.integerForKey(Util.USER_ROLE_ID)
self.performSegueWithIdentifier("showMainView", sender: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLoginTap(sender: AnyObject) {
let params = [
"username": username.text!,
"password": password.text!
]
Alamofire.request(.POST, "\(Util.quizGamesAPI)/login", parameters: params, headers: nil, encoding: .JSON)
.responseJSON { response in
// print(response.request) // original URL request
// print(response.response) // URL response
// print(response.data) // server data
// print(response.result) // result of response serialization
if let results = response.result.value {
// print("JSON: \(results)")
if results["status"] as! String == "failure" {
// invalid credentials
let invalidCredentials = NSLocalizedString("invalidCredentials", comment: "")
let alert = UIAlertController(title: nil, message: invalidCredentials, preferredStyle: .Alert)
let okAction: UIAlertAction = UIAlertAction(title: "Okay", style: .Default) { action -> Void in
}
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
} else {
if self.rememberMe.on {
let preferences = NSUserDefaults.standardUserDefaults()
preferences.setInteger(results["id"] as! Int, forKey: Util.USER_ID_PREF)
preferences.setInteger(results["user_roleId"] as! Int, forKey: Util.USER_ROLE_ID)
}
Util.userId = results["id"] as! Int
Util.userRoleId = results["user_roleId"] as! Int
self.performSegueWithIdentifier("showMainView", sender: sender)
}
} else {
// failed to connect
let connectionMsg = NSLocalizedString("connectionMsg", comment: "")
let alert = UIAlertController(title: nil, message: connectionMsg, preferredStyle: .Alert)
let okAction: UIAlertAction = UIAlertAction(title: "Okay", style: .Default) { action -> Void in
}
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField.tag == 1 {
textField.resignFirstResponder()
password.becomeFirstResponder()
} else if textField.tag == 2 {
onLoginTap(textField)
}
return true
}
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
}
| 1794c1fd8a546dd417842fe31ca85034 | 39.421875 | 119 | 0.579242 | false | false | false | false |
QuarkX/Quark | refs/heads/master | Sources/Quark/Venice/TCP/TCPConnection.swift | mit | 1 | import CLibvenice
public final class TCPConnection : Connection {
public var ip: IP
var socket: tcpsock?
public private(set) var closed = true
internal init(with socket: tcpsock) throws {
let address = tcpaddr(socket)
try ensureLastOperationSucceeded()
self.ip = IP(address: address)
self.socket = socket
self.closed = false
}
public init(host: String, port: Int, deadline: Double = .never) throws {
self.ip = try IP(remoteAddress: host, port: port, deadline: deadline)
}
public func open(deadline: Double = .never) throws {
self.socket = tcpconnect(ip.address, deadline.int64milliseconds)
try ensureLastOperationSucceeded()
self.closed = false
}
public func write(_ buffer: Data, length: Int, deadline: Double) throws -> Int {
let socket = try getSocket()
try ensureStreamIsOpen()
let bytesWritten = buffer.withUnsafeBytes {
tcpsend(socket, $0, length, deadline.int64milliseconds)
}
if bytesWritten == 0 {
try ensureLastOperationSucceeded()
}
return bytesWritten
}
public func flush(deadline: Double) throws {
let socket = try getSocket()
try ensureStreamIsOpen()
tcpflush(socket, deadline.int64milliseconds)
try ensureLastOperationSucceeded()
}
public func read(into buffer: inout Data, length: Int, deadline: Double = .never) throws -> Int {
let socket = try getSocket()
try ensureStreamIsOpen()
let bytesRead = buffer.withUnsafeMutableBytes {
tcprecvlh(socket, $0, 1, length, deadline.int64milliseconds)
}
if bytesRead == 0 {
do {
try ensureLastOperationSucceeded()
} catch SystemError.connectionResetByPeer {
closed = true
throw StreamError.closedStream(data: Data())
}
}
return bytesRead
}
public func close() {
if !closed, let socket = try? getSocket() {
tcpclose(socket)
}
closed = true
}
private func getSocket() throws -> tcpsock {
guard let socket = self.socket else {
throw SystemError.socketIsNotConnected
}
return socket
}
private func ensureStreamIsOpen() throws {
if closed {
throw StreamError.closedStream(data: Data())
}
}
deinit {
if let socket = socket, !closed {
tcpclose(socket)
}
}
}
| 7c9b4ea886f702db59784f76a0a5d2f7 | 26.178947 | 101 | 0.592951 | false | false | false | false |
prebid/prebid-mobile-ios | refs/heads/master | PrebidMobile/ConfigurationAndTargeting/Targeting.swift | apache-2.0 | 1 | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import CoreLocation
import MapKit
fileprivate let PrebidTargetingKey_AGE = "age"
fileprivate let PrebidTargetingKey_GENDER = "gen"
fileprivate let PrebidTargetingKey_USER_ID = "xid"
fileprivate let PrebidTargetingKey_PUB_PROVIDED_PREFIX = "c."
@objcMembers
public class Targeting: NSObject {
public static var shared = Targeting()
// MARK: - OMID Partner
public var omidPartnerName: String?
public var omidPartnerVersion: String?
// MARK: - User Information
/**
Indicates user birth year.
*/
public var yearOfBirth: Int {
get { yearofbirth }
set { setYearOfBirth(yob: newValue) }
}
/**
* This method set the year of birth value
*/
public func setYearOfBirth(yob: Int) {
if AgeUtils.isYOBValid(yob) {
yearofbirth = yob
} else {
Log.error("Incorrect birth year. It will be ignored.")
}
}
// Objective C API
public func getYearOfBirth() -> NSNumber {
NSNumber(value: yearOfBirth)
}
/**
* This method clears year of birth value set by the application developer
*/
public func clearYearOfBirth() {
yearofbirth = 0
}
/**
Indicates the end-user's gender.
*/
public var userGender: Gender {
get {
guard let currentValue = parameterDictionary[PrebidTargetingKey_GENDER] else {
return .unknown
}
return GenderFromDescription(currentValue)
}
set {
parameterDictionary[PrebidTargetingKey_GENDER] = DescriptionOfGender(newValue)
}
}
/**
String representation of the users gender,
where “M” = male, “F” = female, “O” = known to be other (i.e., omitted is unknown)
*/
public func userGenderDescription() -> String? {
guard let currentValue = parameterDictionary[PrebidTargetingKey_GENDER] else {
return nil
}
return GenderDescription(rawValue: currentValue)?.rawValue
}
/**
Indicates the customer-provided user ID, if different from the Device ID.
*/
public var userID: String? {
get { parameterDictionary[PrebidTargetingKey_USER_ID] }
set { parameterDictionary[PrebidTargetingKey_USER_ID] = newValue }
}
/**
Buyer-specific ID for the user as mapped by the exchange for the buyer.
*/
public var buyerUID: String?
/**
Comma separated list of keywords, interests, or intent.
*/
public var keywords: String?
/**
Optional feature to pass bidder data that was set in the
exchange’s cookie. The string must be in base85 cookie safe
characters and be in any format. Proper JSON encoding must
be used to include “escaped” quotation marks.
*/
public var userCustomData: String?
/**
Placeholder for User Identity Links.
The data from this property will be added to usr.ext.eids
*/
public var eids: [[String : AnyHashable]]?
/**
Placeholder for exchange-specific extensions to OpenRTB.
*/
public var userExt: [String : AnyHashable]?
// MARK: - COPPA
/**
Objective C analog of subjectToCOPPA
*/
public var coppa: NSNumber? {
set { UserConsentDataManager.shared.subjectToCOPPA = newValue.boolValue }
get { UserConsentDataManager.shared.subjectToCOPPA.nsNumberValue }
}
/**
Integer flag indicating if this request is subject to the COPPA regulations
established by the USA FTC, where 0 = no, 1 = yes
*/
public var subjectToCOPPA: Bool? {
set { UserConsentDataManager.shared.subjectToCOPPA = newValue}
get { UserConsentDataManager.shared.subjectToCOPPA }
}
// MARK: - GDPR
/**
* The boolean value set by the user to collect user data
*/
public var subjectToGDPR: Bool? {
set { UserConsentDataManager.shared.subjectToGDPR = newValue }
get { UserConsentDataManager.shared.subjectToGDPR }
}
public func setSubjectToGDPR(_ newValue: NSNumber?) {
UserConsentDataManager.shared.subjectToGDPR = newValue?.boolValue
}
public func getSubjectToGDPR() -> NSNumber? {
return UserConsentDataManager.shared.subjectToGDPR_NSNumber
}
// MARK: - GDPR Consent
/**
* The consent string for sending the GDPR consent
*/
public var gdprConsentString: String? {
set { UserConsentDataManager.shared.gdprConsentString = newValue }
get { UserConsentDataManager.shared.gdprConsentString }
}
// MARK: - TCFv2
public var purposeConsents: String? {
set { UserConsentDataManager.shared.purposeConsents = newValue }
get { UserConsentDataManager.shared.purposeConsents }
}
/*
Purpose 1 - Store and/or access information on a device
*/
public func getDeviceAccessConsent() -> Bool? {
UserConsentDataManager.shared.getDeviceAccessConsent()
}
public func getDeviceAccessConsentObjc() -> NSNumber? {
UserConsentDataManager.shared.getDeviceAccessConsent() as NSNumber?
}
public func getPurposeConsent(index: Int) -> Bool? {
UserConsentDataManager.shared.getPurposeConsent(index: index)
}
public func isAllowedAccessDeviceData() -> Bool {
UserConsentDataManager.shared.isAllowedAccessDeviceData()
}
// MARK: - External User Ids
public var externalUserIds = [ExternalUserId]()
/**
* This method allows to save External User Id in the User Defaults
*/
public func storeExternalUserId(_ externalUserId: ExternalUserId) {
if let index = externalUserIds.firstIndex(where: {$0.source == externalUserId.source}) {
externalUserIds[index] = externalUserId
} else {
externalUserIds.append(externalUserId)
}
StorageUtils.setExternalUserIds(value: externalUserIds)
}
/**
* This method allows to get All External User Ids from User Defaults
*/
public func fetchStoredExternalUserIds()->[ExternalUserId]? {
return StorageUtils.getExternalUserIds()
}
/**
* This method allows to get External User Id from User Defaults by passing respective 'source' string as param
*/
public func fetchStoredExternalUserId(_ source : String)->ExternalUserId? {
guard let array = StorageUtils.getExternalUserIds(), let externalUserId = array.first(where: {$0.source == source}) else{
return nil
}
return externalUserId
}
/**
* This method allows to remove specific External User Id from User Defaults by passing respective 'source' string as param
*/
public func removeStoredExternalUserId(_ source : String) {
if let index = externalUserIds.firstIndex(where: {$0.source == source}) {
externalUserIds.remove(at: index)
StorageUtils.setExternalUserIds(value: externalUserIds)
}
}
/**
* This method allows to remove all the External User Ids from User Defaults
*/
public func removeStoredExternalUserIds() {
if var arrayExternalUserIds = StorageUtils.getExternalUserIds(){
arrayExternalUserIds.removeAll()
StorageUtils.setExternalUserIds(value: arrayExternalUserIds)
}
}
public func getExternalUserIds() -> [[AnyHashable: Any]]? {
var externalUserIdArray = [ExternalUserId]()
if Prebid.shared.externalUserIdArray.count != 0 {
externalUserIdArray = Prebid.shared.externalUserIdArray
} else {
externalUserIdArray = externalUserIds
}
var transformedUserIdArray = [[AnyHashable: Any]]()
for externalUserId in externalUserIdArray {
transformedUserIdArray.append(externalUserId.toJSONDictionary())
}
if let eids = eids {
transformedUserIdArray.append(contentsOf: eids)
}
return transformedUserIdArray.isEmpty ? nil : transformedUserIdArray
}
// MARK: - Application Information
/**
This is the deep-link URL for the app screen that is displaying the ad. This can be an iOS universal link.
*/
public var contentUrl: String?
/**
App's publisher name.
*/
public var publisherName: String?
/**
ID of publisher app in Apple’s App Store.
*/
public var sourceapp: String?
public var storeURL: String? {
get { parameterDictionary[PBMParameterKeys.APP_STORE_URL.rawValue] }
set { parameterDictionary[PBMParameterKeys.APP_STORE_URL.rawValue] = newValue }
}
public var domain: String?
/**
* The itunes app id for targeting
*/
public var itunesID: String?
/**
* The application location for targeting
*/
public var location: CLLocation?
/**
* The application location precision for targeting
*/
public var locationPrecision: Int?
public func setLocationPrecision(_ newValue: NSNumber?) {
locationPrecision = newValue?.intValue
}
public func getLocationPrecision() -> NSNumber? {
return locationPrecision as NSNumber?
}
// MARK: - Location and connection information
/**
CLLocationCoordinate2D.
See CoreLocation framework documentation.
*/
public var coordinate: NSValue?
// MARK: - Public Methods
public func addParam(_ value: String, withName: String?) {
guard let name = withName else {
Log.error("Invalid user parameter.")
return
}
if value.isEmpty {
parameterDictionary.removeValue(forKey: name)
} else {
parameterDictionary[name] = value
}
}
public func setCustomParams(_ params: [String : String]?) {
guard let params = params else {
return
}
params.keys.forEach { key in
if let value = params[key] {
addCustomParam(value, withName: key)
}
}
}
public func addCustomParam(_ value: String, withName: String?) {
guard let name = withName else {
return
}
let prefixedName = makeCustomParamFromName(name)
addParam(value, withName:prefixedName)
}
// Store location in the user's section
public func setLatitude(_ latitude: Double, longitude: Double) {
coordinate = NSValue(mkCoordinate: CLLocationCoordinate2DMake(latitude, longitude))
}
// MARK: - Access Control List (ext.prebid.data)
public func addBidderToAccessControlList(_ bidderName: String) {
rawAccessControlList.insert(bidderName)
}
public func removeBidderFromAccessControlList(_ bidderName: String) {
rawAccessControlList.remove(bidderName)
}
public func clearAccessControlList() {
rawAccessControlList.removeAll()
}
public func getAccessControlList() -> [String] {
Array(rawAccessControlList)
}
public var accessControlList: [String] {
Array(rawAccessControlList)
}
// MARK: - Global User Data (user.ext.data)
public func addUserData(key: String, value: String) {
var values = rawUserDataDictionary[key] ?? Set<String>()
values.insert(value)
rawUserDataDictionary[key] = values
}
public func updateUserData(key: String, value: Set<String>) {
rawUserDataDictionary[key] = value
}
public func removeUserData(for key: String) {
rawUserDataDictionary.removeValue(forKey: key)
}
public func clearUserData() {
rawUserDataDictionary.removeAll()
}
public func getUserData() -> [String: [String]] {
rawUserDataDictionary.mapValues { Array($0) }
}
public var userDataDictionary: [String : [String]] {
rawUserDataDictionary.mapValues { Array($0) }
}
// MARK: - Global User Keywords (user.keywords)
public func addUserKeyword(_ newElement: String) {
userKeywordsSet.insert(newElement)
}
public func addUserKeywords(_ newElements: Set<String>) {
userKeywordsSet.formUnion(newElements)
}
public func removeUserKeyword(_ element: String) {
userKeywordsSet.remove(element)
}
public func clearUserKeywords() {
userKeywordsSet.removeAll()
}
public func getUserKeywords() -> [String] {
Log.info("global user keywords set is \(userKeywordsSet)")
return Array(userKeywordsSet)
}
public var userKeywords: [String] {
Array(userKeywordsSet)
}
// MARK: - Global Context Data (app.ext.data)
public func addContextData(key: String, value: String) {
var values = rawContextDataDictionary[key] ?? Set<String>()
values.insert(value)
rawContextDataDictionary[key] = values
}
public func updateContextData(key: String, value: Set<String>) {
rawContextDataDictionary[key] = value
}
public func removeContextData(for key: String) {
rawContextDataDictionary.removeValue(forKey: key)
}
public func clearContextData() {
rawContextDataDictionary.removeAll()
}
public func getContextData() -> [String : [String]] {
Log.info("gloabal context data dictionary is \(contextDataDictionary)")
return contextDataDictionary.mapValues { Array($0) }
}
public var contextDataDictionary: [String : [String]] {
rawContextDataDictionary.mapValues { Array($0) }
}
// MARK: - Global Context Keywords (app.keywords)
public func addContextKeyword(_ newElement: String) {
contextKeywordsSet.insert(newElement)
}
public func addContextKeywords(_ newElements: Set<String>) {
contextKeywordsSet.formUnion(newElements)
}
public func removeContextKeyword(_ element: String) {
contextKeywordsSet.remove(element)
}
public func clearContextKeywords() {
contextKeywordsSet.removeAll()
}
public func getContextKeywords() -> [String] {
Log.info("global context keywords set is \(contextKeywordsSet)")
return Array(contextKeywordsSet)
}
public var contextKeywords: [String] {
Array(contextKeywordsSet)
}
// MARK: - Internal Properties
public var parameterDictionary = [String : String]()
private var userKeywordsSet = Set<String>()
private var contextKeywordsSet = Set<String>()
private var rawAccessControlList = Set<String>()
private var rawUserDataDictionary = [String : Set<String>]()
private var rawContextDataDictionary = [String : Set<String>]()
private var yearofbirth = 0
// MARK: - Internal Methods
func makeCustomParamFromName(_ name: String) -> String {
if name.hasPrefix(PrebidTargetingKey_PUB_PROVIDED_PREFIX) {
return name
}
return PrebidTargetingKey_PUB_PROVIDED_PREFIX + name
}
}
| dd24f2acdfd05b9ddeb7456980d171de | 28.941948 | 129 | 0.633998 | false | false | false | false |
avenwu/swift_basic | refs/heads/master | IntroductionToAlgrithms/InsertionSort.swift | apache-2.0 | 1 | //
// InsertionSort.swift
// IntroductionToAlgrithms
//
// Created by aven wu on 14/10/26.
// Copyright (c) 2014年 avenwu. All rights reserved.
//
import Foundation
//sort the number array from min to max
func sortIncreace(inout arrayData:[Int]) -> [Int] {
for var i = 1; i < arrayData.count; i++ {
var key = arrayData[i];
var j = i-1
println("current data = \(key), index = \(i)")
while j >= 0 && arrayData[j] > key {
println("switch elements: j=\(j), data=\(arrayData[j])")
arrayData[j+1] = arrayData[j]
j--
}
arrayData[j+1] = key
}
return arrayData
}
//sort the inputed number array by decreasing the value
func sortDecrease(inout arrayData:[Int]) -> [Int] {
for var i = 1; i < arrayData.count; i++ {
var key = arrayData[i]
var j = i-1
while j>=0 && arrayData[j] < key {
arrayData[j+1] = arrayData[j]
j--
}
arrayData[j+1] = key
}
return arrayData
}
func executeSort(){
var dataArray = [3,2,5,7,1,9]
println("array=\(dataArray), \nsorted=\(sortIncreace(&dataArray))")
println("array=\(dataArray), \nsorted=\(sortDecrease(&dataArray))")
} | 2954a9fab2a4c00eaaf9d62eb426996f | 26.355556 | 71 | 0.564228 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | refs/heads/dev | byuSuite/Apps/Parking/model/Registration/TrafficCode.swift | apache-2.0 | 2 | //
// TrafficCode.swift
// byuSuite
//
// Created by Erik Brady on 11/16/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
let STATE_CODESET_ID = "STA"
let MAKE_CODESET_ID = "MAK"
let COLOR_CODESET_ID = "CLR"
let RELATION_TO_OWNER_CODESET_ID = "RELTOOWNER"
let TYPE_CODESET_ID = "VEHTYPE"
class TrafficCode: Comparable {
var codeId: String
var codesetId: String
var descr: String
init(dict: [String: Any]) throws {
guard let tempCodeId = dict["codeId"] as? String,
let tempCodesetId = dict["codesetId"] as? String,
let tempDescr = dict["description"] as? String else {
throw InvalidModelError()
}
codeId = tempCodeId
codesetId = tempCodesetId
descr = tempDescr
}
func toDictionary() -> [String: Any] {
return ["codeId": codeId, "codesetId": codesetId, "description": descr]
}
//MARK: Comparable Methods
static func <(lhs: TrafficCode, rhs: TrafficCode) -> Bool {
return lhs.descr < rhs.descr
}
static func ==(lhs: TrafficCode, rhs: TrafficCode) -> Bool {
return lhs.descr == rhs.descr
}
}
| 0967514f1f2f668560cbacf475b4ebf9 | 21.458333 | 73 | 0.676252 | false | false | false | false |
KyoheiG3/SimpleAlert | refs/heads/master | SimpleAlert/AlertController.swift | mit | 1 | //
// AlertController.swift
// SimpleAlert
//
// Created by Kyohei Ito on 2019/06/13.
// Copyright © 2019 kyohei_ito. All rights reserved.
//
import UIKit
open class AlertController: UIViewController {
enum Const {
static let alertWidth: CGFloat = 270
static let actionSheetMargin: CGFloat = 16
static let cornerRadius: CGFloat = 13
static let textFieldHeight: CGFloat = 25
}
@IBOutlet weak var containerView: UIView! {
didSet {
if preferredStyle == .actionSheet {
tapGesture.addTarget(self, action: #selector(AlertController.backgroundViewTapAction(_:)))
containerView.addGestureRecognizer(tapGesture)
}
}
}
@IBOutlet weak var containerStackView: UIStackView!
@IBOutlet weak var contentEffectView: UIVisualEffectView! {
didSet {
contentEffectView.clipsToBounds = true
}
}
@IBOutlet weak var cancelEffectView: UIVisualEffectView! {
didSet {
cancelEffectView.clipsToBounds = true
cancelEffectView.isHidden = preferredStyle == .alert
}
}
@IBOutlet weak var contentStackView: UIStackView!
@IBOutlet weak var contentScrollView: UIScrollView! {
didSet {
contentScrollView.showsVerticalScrollIndicator = false
contentScrollView.showsHorizontalScrollIndicator = false
if #available(iOS 11.0, *) {
contentScrollView.contentInsetAdjustmentBehavior = .never
}
}
}
@IBOutlet weak var alertButtonScrollView: UIScrollView! {
didSet {
alertButtonScrollView.showsVerticalScrollIndicator = false
alertButtonScrollView.showsHorizontalScrollIndicator = false
if #available(iOS 11.0, *) {
alertButtonScrollView.contentInsetAdjustmentBehavior = .never
}
}
}
@IBOutlet weak var cancelButtonScrollView: UIScrollView! {
didSet {
alertButtonScrollView.showsVerticalScrollIndicator = false
alertButtonScrollView.showsHorizontalScrollIndicator = false
if #available(iOS 11.0, *) {
cancelButtonScrollView.contentInsetAdjustmentBehavior = .never
}
}
}
@IBOutlet weak var alertContentView: AlertContentView!
@IBOutlet weak var alertButtonStackView: UIStackView!
@IBOutlet weak var cancelButtonStackView: UIStackView!
@IBOutlet weak var containerViewBottom: NSLayoutConstraint!
@IBOutlet weak var containerStackViewWidth: NSLayoutConstraint!
public private(set) var actions: [AlertAction] = []
public private(set) var textFields: [UITextField] = []
open var contentWidth: CGFloat?
open var contentColor: UIColor?
open var contentCornerRadius: CGFloat?
open var coverColor: UIColor = .black
open var message: String?
private var contentViewHandler: ((AlertContentView) -> Void)?
private var customView: UIView?
private var preferredStyle: UIAlertController.Style = .alert
private let tapGesture = UITapGestureRecognizer()
private weak var customViewHeightConstraint: NSLayoutConstraint? {
didSet {
oldValue?.isActive = false
}
}
private weak var containerStackViewYAxisConstraint: NSLayoutConstraint? {
didSet {
oldValue?.isActive = false
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private convenience init() {
let type = AlertController.self
self.init(nibName: String(describing: type), bundle: Bundle(for: type))
}
public convenience init(title: String?, message: String?, style: UIAlertController.Style) {
self.init()
self.title = title
self.message = message
self.preferredStyle = style
}
public convenience init(title: String? = nil, message: String? = nil, view: UIView?, style: UIAlertController.Style) {
self.init()
self.title = title
self.message = message
customView = view
preferredStyle = style
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
modalPresentationStyle = .custom
modalTransitionStyle = .crossDissolve
transitioningDelegate = self
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let color = contentColor {
contentEffectView.backgroundColor = color
cancelEffectView.backgroundColor = color
contentEffectView.effect = nil
cancelEffectView.effect = nil
} else {
contentEffectView.backgroundColor = .white
cancelEffectView.backgroundColor = .white
}
contentEffectView.layer.cornerRadius = contentCornerRadius ?? Const.cornerRadius
cancelEffectView.layer.cornerRadius = contentCornerRadius ?? Const.cornerRadius
alertContentView.titleLabel.text = title
alertContentView.messageLabel.text = message
if preferredStyle == .alert {
textFields.forEach { textField in
alertContentView.append(textField)
(textField as? TextField)?.handler?(textField)
}
textFields.first?.becomeFirstResponder()
}
if let view = customView {
alertContentView.contentStackView.addArrangedSubview(view)
}
configureContentView(alertContentView)
alertContentView.layoutIfNeeded()
layoutButtons()
view.layoutIfNeeded()
NotificationCenter.default.addObserver(self, selector: #selector(AlertController.keyboardFrameWillChange), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(AlertController.keyboardFrameWillChange), name: UIResponder.keyboardWillHideNotification, object: nil)
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
alertContentView.endEditing(true)
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
alertContentView.removeAllTextField()
if let view = customView {
alertContentView.contentStackView.removeArrangedSubview(view)
view.removeFromSuperview()
}
alertButtonStackView.removeAllArrangedSubviews()
cancelButtonStackView.removeAllArrangedSubviews()
contentStackView.arrangedSubviews
.filter { !($0 is UIScrollView) }
.forEach { view in
contentStackView.removeArrangedSubview(view)
view.removeFromSuperview()
}
}
open override func updateViewConstraints() {
super.updateViewConstraints()
customViewHeightConstraint?.isActive = false
containerStackViewYAxisConstraint?.isActive = false
let minWidth = min(view.bounds.width, view.bounds.height)
containerStackViewWidth.constant = contentWidth ?? (preferredStyle == .alert ? Const.alertWidth : minWidth - Const.actionSheetMargin)
let constraint: NSLayoutConstraint
switch preferredStyle {
case .alert:
constraint = containerStackView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor)
case .actionSheet:
let bottomAnchor: NSLayoutYAxisAnchor
if #available(iOS 11.0, *) {
bottomAnchor = containerView.safeAreaLayoutGuide.bottomAnchor
} else {
bottomAnchor = containerView.bottomAnchor
}
constraint = containerStackView.bottomAnchor.constraint(equalTo: bottomAnchor)
@unknown default:
constraint = containerStackView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor)
}
constraint.priority = .defaultHigh
constraint.isActive = true
containerStackViewYAxisConstraint = constraint
if let view = customView {
let constraint = view.heightAnchor.constraint(equalToConstant: view.bounds.height)
constraint.isActive = true
customViewHeightConstraint = constraint
}
}
open func addTextField(configurationHandler: ((UITextField) -> Void)? = nil) {
let textField = TextField()
textField.handler = configurationHandler
textField.heightAnchor.constraint(equalToConstant: Const.textFieldHeight).isActive = true
textFields.append(textField)
}
open func addAction(_ action: AlertAction) {
action.button.frame.size.height = preferredStyle.buttonHeight
action.button.addTarget(self, action: #selector(AlertController.buttonDidTap), for: .touchUpInside)
configureActionButton(action.button, at: action.style)
actions.append(action)
}
open func configureActionButton(_ button: UIButton, at style: AlertAction.Style) {
if style == .destructive {
button.setTitleColor(.red, for: .normal)
}
button.titleLabel?.font = style.font(of: preferredStyle)
}
open func configureContentView(_ contentView: AlertContentView) {
contentViewHandler?(contentView)
}
@discardableResult
public func configureContentView(configurationHandler: @escaping (AlertContentView) -> Void) -> Self {
contentViewHandler = configurationHandler
return self
}
}
extension AlertController {
func layoutButtons() {
alertButtonStackView.axis = preferredStyle == .alert && actions.count == 2 ? .horizontal : .vertical
switch (preferredStyle, alertButtonStackView.axis) {
case (.actionSheet, _):
actions.lazy
.filter { $0.style != .cancel }
.forEach(alertButtonStackView.addAction)
actions.lazy
.filter { $0.style == .cancel }
.forEach(cancelButtonStackView.addAction)
if alertContentView.isHidden, let borderView = alertButtonStackView.arrangedSubviews.first {
alertButtonStackView.removeArrangedSubview(borderView)
borderView.removeFromSuperview()
}
if let borderView = cancelButtonStackView.arrangedSubviews.first {
cancelButtonStackView.removeArrangedSubview(borderView)
borderView.removeFromSuperview()
}
case (.alert, .horizontal):
actions.forEach(alertButtonStackView.addAction)
if let borderView = alertButtonStackView.arrangedSubviews.first {
alertButtonStackView.removeArrangedSubview(borderView)
borderView.removeFromSuperview()
}
if !alertContentView.isHidden {
contentStackView.insertArrangedSubview(contentStackView.makeBorderView(), at: 1)
}
case (.alert, .vertical):
actions.forEach(alertButtonStackView.addAction)
if alertContentView.isHidden, let borderView = alertButtonStackView.arrangedSubviews.first {
alertButtonStackView.removeArrangedSubview(borderView)
borderView.removeFromSuperview()
}
@unknown default:
break
}
zip(actions, actions.dropFirst()).forEach { top, bottom in
top.button.widthAnchor.constraint(equalTo: bottom.button.widthAnchor).isActive = true
}
}
func dismiss(with sender: UIButton) {
guard let action = actions.filter({ $0.button == sender }).first else {
dismiss()
return
}
if action.shouldDismisses {
dismiss {
action.handler?(action)
}
} else {
action.handler?(action)
}
}
func dismiss(withCompletion block: @escaping () -> Void = {}) {
dismiss(animated: true) {
block()
self.actions.removeAll()
self.textFields.removeAll()
}
}
}
// MARK: - Action Methods
extension AlertController {
@objc func buttonDidTap(_ button: UIButton) {
dismiss(with: button)
}
@objc func backgroundViewTapAction(_ gesture: UITapGestureRecognizer) {
if !containerStackView.frame.contains(gesture.location(in: containerView)) {
dismiss()
}
}
}
// MARK: - NSNotificationCenter Methods
extension AlertController {
@objc func keyboardFrameWillChange(_ notification: Notification) {
let info = notification.info
if let frame = info.keyboardFrameEnd,
let duration = info.duration,
let curve = info.curve {
UIView.animate(withDuration: duration, delay: 0, options: curve, animations: {
self.containerViewBottom.constant = self.view.bounds.height - frame.origin.y
self.view.layoutIfNeeded()
})
}
}
}
// MARK: - UIViewControllerTransitioningDelegate Methods
extension AlertController: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch preferredStyle {
case .alert:
return AlertControllerPresentTransition(backgroundColor: coverColor)
case .actionSheet:
return ActionSheetControllerPresentTransition(backgroundColor: coverColor)
@unknown default:
fatalError()
}
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch preferredStyle {
case .alert:
return AlertControllerDismissTransition(backgroundColor: coverColor)
case .actionSheet:
return ActionSheetControllerDismissTransition(backgroundColor: coverColor)
@unknown default:
fatalError()
}
}
}
| 0f8f6c3604d3534ec76ded5b2d13438f | 34.075795 | 177 | 0.654956 | false | false | false | false |
iOSWizards/MVUIHacks | refs/heads/master | MVUIHacks/Classes/Designable/DesignableView.swift | mit | 1 | //
// DesignableView.swift
// MV UI Hacks
//
// Created by Evandro Harrison Hoffmann on 06/07/2016.
// Copyright © 2016 It's Day Off. All rights reserved.
//
import UIKit
enum ShapeType: Int {
case `default` = 0
case hexagon = 1
case hexagonVertical = 2
}
@IBDesignable
open class DesignableView: UIView {
// MARK: - Shapes
@IBInspectable open var shapeType: Int = 0{
didSet{
updateShape(shapeType)
}
}
@IBInspectable var autoRadius:Bool = false {
didSet {
if autoRadius {
cornerRadius = layer.frame.height / 2
}
}
}
open func updateShape(_ shapeType: Int){
switch shapeType {
case ShapeType.hexagon.rawValue:
self.addHexagonalMask(0)
break
case ShapeType.hexagonVertical.rawValue:
self.addHexagonalMask(CGFloat(Double.pi/2))
break
default:
break
}
}
@IBInspectable open var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable open var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable open var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
}
}
// MARK: - Colors
@IBInspectable open var gradientTopColor: UIColor = UIColor.clear {
didSet{
self.addGradientLayer(gradientTopColor, bottomColor: gradientBottomColor)
}
}
@IBInspectable open var gradientBottomColor: UIColor = UIColor.clear {
didSet{
self.addGradientLayer(gradientTopColor, bottomColor: gradientBottomColor)
}
}
open override func layoutSubviews() {
addGradientLayer(gradientTopColor, bottomColor: gradientBottomColor)
updateShape(shapeType)
if autoRadius {
cornerRadius = layer.frame.height / 2
}
}
}
| 7a1455bd9ebeba4b20c1f08795ad637d | 23.067416 | 85 | 0.578898 | false | false | false | false |
Beaver/Beaver | refs/heads/master | BeaverTestKit/Type/ActionMock.swift | mit | 2 | import Beaver
public struct ActionMock: Action, Equatable {
public typealias StateType = StateMock
public var name: String
public init(name: String = "ActionMock") {
self.name = name
}
public static func ==(lhs: ActionMock, rhs: ActionMock) -> Bool {
return lhs.name == rhs.name
}
}
| e75262247db60105568df55030e1d04c | 21.066667 | 69 | 0.63142 | false | false | false | false |
omiz/CarBooking | refs/heads/master | CarBooking/Classes/UI/Booking/Cell/BookingDayPickerCell.swift | mit | 1 | //
// BookingDayPickerCell.swift
// CarBooking
//
// Created by Omar Allaham on 10/22/17.
// Copyright © 2017 Omar Allaham. All rights reserved.
//
import Foundation
import UIKit
protocol BookingDayDelegate {
func bookingDay(changed days: Int)
}
class BookingDayPickerCell: UITableViewCell, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var dayLabel: UILabel!
@IBOutlet weak var dayPicker: UIPickerView!
@IBOutlet weak var pickerTopLabel: UILabel!
@IBOutlet weak var pickerHeightConstraint: NSLayoutConstraint!
var extended: Bool = false { didSet {
pickerHeightConstraint.constant = extended ? 200 : 0
dayPicker.layoutIfNeeded()
}
}
var dataSouce: [String] = Booking.allowedDaysCount.map { $0.description }
var delegate: BookingDayDelegate?
override func awakeFromNib() {
super.awakeFromNib()
dayLabel.adjustsFontSizeToFitWidth = true
pickerTopLabel.text = "You can not change the days count for old Bookings".localized
}
@objc func timeChanged(_ picker: UIDatePicker) {
dayLabel.text = String(format: "Starting date: %@".localized, picker.date.formatted)
delegate?.bookingDay(changed: 0)
}
func setup(_ booking: Booking?, delegate: BookingDayDelegate?) {
let date = booking?.date?.formatted ?? ""
dayLabel.text = date.isEmpty ? "Booking date is not available".localized :
String(format: "Starting date: %@".localized, date)
check(isInPast: booking)
let duration = booking?.duration ?? 1
let index = dataSouce.index(of: duration.description) ?? 0
dayPicker.selectRow(index, inComponent: 0, animated: false)
setDayLabel(count: booking?.duration)
self.delegate = delegate
}
func check(isInPast booking: Booking?) {
let isInTheFuture = (booking?.date?.timeIntervalSinceNow ?? -1) >= 0
dayPicker.isUserInteractionEnabled = isInTheFuture
pickerTopLabel.isHidden = isInTheFuture
}
func setDayLabel(count: Int?) {
let days = (count ?? 0) > 1 ? "days" : "day"
dayLabel.text = count == nil ? "Booking duration is not available".localized :
String(format: "For: %d %@".localized, count ?? 0, days)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataSouce.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return dataSouce[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
delegate?.bookingDay(changed: Int(dataSouce[row]) ?? 0)
}
}
| b312686e575614c4988e8f23930953ad | 29.575758 | 111 | 0.627684 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureWithdrawalLocks/Sources/FeatureWithdrawalLocksDomain/Service/Model/WithdrawalLocks.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public struct WithdrawalLocks: Hashable {
public init(items: [WithdrawalLocks.Item], amount: String) {
self.items = items
self.amount = amount
}
public struct Item: Hashable, Identifiable {
public init(date: String, amount: String) {
self.date = date
self.amount = amount
}
public var id = UUID()
public let date: String
public let amount: String
}
public let items: [Item]
public let amount: String
}
| dd919a4e41154f8411a4e9ed4300936f | 23.666667 | 64 | 0.616554 | false | false | false | false |
youngsoft/TangramKit | refs/heads/master | TangramKitDemo/FlowLayoutDemo/FLLTest5ViewController.swift | mit | 1 | //
// FLLTest5ViewController.swift
// TangramKit
//
// Created by apple on 16/7/18.
// Copyright © 2016年 youngsoft. All rights reserved.
//
import UIKit
/**
*5.FlowLayout - Paging
*/
class FLLTest5ViewController: UIViewController {
override func loadView() {
/*
这个例子主要是用来展示数量约束流式布局对分页滚动能力的支持。
*/
let scrollView = UIScrollView()
scrollView.delaysContentTouches = false //因为里面也有滚动视图,优先处理子滚动视图的事件。
self.view = scrollView
let rootLayout = TGFlowLayout(.vert, arrangedCount:1)
rootLayout.backgroundColor = .white
rootLayout.tg_width.equal(.fill)
rootLayout.tg_height.equal(.wrap)
rootLayout.tg_gravity = TGGravity.horz.fill //里面的所有子视图和布局视图宽度一致。
scrollView.addSubview(rootLayout)
//创建一个水平数量流式布局分页从左到右滚动
self.createHorzPagingFlowLayout1(rootLayout)
//创建一个水平数量流式布局分页从上到下滚动的流式布局。
self.createHorzPagingFlowLayout2(rootLayout)
//创建一个垂直数量流式布局分页从上到下滚动
self.createVertPagingFlowLayout1(rootLayout)
//创建一个垂直数量流式布局分页从左到右滚动
self.createVertPagingFlowLayout2(rootLayout)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension FLLTest5ViewController {
//添加所有测试子条目视图。
func addAllItemSubviews(_ flowLayout:TGFlowLayout)
{
for i in 0 ..< 40
{
let label = UILabel()
label.textAlignment = .center
label.backgroundColor = CFTool.color(Int(arc4random()) % 14 + 1)
label.text = "\(i)"
flowLayout.addSubview(label)
}
}
/**
* 创建一个水平分页从左向右滚动的流式布局
*/
func createHorzPagingFlowLayout1(_ rootLayout: UIView)
{
let titleLabel = UILabel()
titleLabel.text = "水平流式布局分页从左往右滚动:➡︎"
titleLabel.sizeToFit()
titleLabel.tg_top.equal(20)
rootLayout.addSubview(titleLabel)
//要开启分页功能,必须要将流式布局加入到一个滚动视图里面作为子视图!!!
let scrollView = UIScrollView()
scrollView.isPagingEnabled = true //开启分页滚动模式!!您可以注释这句话看看非分页滚动的布局滚动效果。
scrollView.tg_height.equal(200) //设置明确的高度为200,因为宽度已经由父线性布局的gravity属性确定了,所以不需要设置了。
rootLayout.addSubview(scrollView)
//建立一个水平数量约束流式布局:每列展示3个子视图,每页展示9个子视图,整体从左往右滚动。
let flowLayout = TGFlowLayout(.horz, arrangedCount:3)
flowLayout.tg_pagedCount = 9 //tg_pagedCount设置为非0时表示开始分页展示的功能,这里表示每页展示9个子视图,这个数量必须是tg_arrangedCount的倍数。
flowLayout.tg_width.equal(.wrap) //设置布局视图的宽度由子视图包裹,当水平流式布局的这个属性设置为YES,并和pagedCount搭配使用会产生分页从左到右滚动的效果。
flowLayout.tg_height.equal(scrollView) //因为是分页从左到右滚动,因此布局视图的高度必须设置为和父滚动视图相等。
/*
上面是实现一个水平流式布局分页且从左往右滚动的标准属性设置方法。
*/
flowLayout.tg_hspace = 10
flowLayout.tg_vspace = 10 //设置子视图的水平和垂直间距。
flowLayout.tg_padding = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5) //布局视图的内边距设置!您可以注释掉这句话看看效果!如果设置内边距且也有分页时请将这个值设置和子视图间距相等。
scrollView.addSubview(flowLayout)
flowLayout.backgroundColor = CFTool.color(0)
self.addAllItemSubviews(flowLayout)
//获取流式布局的横屏size classes,并且设置当设备处于横屏时每页的数量由9个变为了18个。您可以注释掉这段代码,然后横竖屏切换看看效果。
let flowLayoutSC = flowLayout.tg_fetchSizeClass(with:.landscape, from:.default) as! TGFlowLayoutViewSizeClass
flowLayoutSC.tg_pagedCount = 18
}
/**
* 创建一个水平分页从上向下滚动的流式布局
*/
func createHorzPagingFlowLayout2(_ rootLayout: UIView)
{
let titleLabel = UILabel()
titleLabel.text = "水平流式布局分页从上往下滚动:⬇︎"
titleLabel.sizeToFit()
titleLabel.tg_top.equal(20)
rootLayout.addSubview(titleLabel)
//要开启分页功能,必须要将流式布局加入到一个滚动视图里面作为子视图!!!
let scrollView = UIScrollView()
scrollView.isPagingEnabled = true //开启分页滚动模式!!您可以注释这句话看看非分页滚动的布局滚动效果。
scrollView.tg_height.equal(250) //设置明确的高度为200,因为宽度已经由父线性布局的gravity属性确定了,所以不需要设置了。
rootLayout.addSubview(scrollView)
//建立一个水平数量约束流式布局:每列展示3个子视图,每页展示9个子视图,整体从上往下滚动。
let flowLayout = TGFlowLayout(.horz, arrangedCount:3)
flowLayout.tg_pagedCount = 9; //pagedCount设置为非0时表示开始分页展示的功能,这里表示每页展示9个子视图,这个数量必须是arrangedCount的倍数。
flowLayout.tg_height.equal(.wrap) //设置布局视图的高度由子视图包裹,当水平流式布局的高度设置为.wrap,并和pagedCount搭配使用会产生分页从上到下滚动的效果。
flowLayout.tg_width.equal(scrollView) //因为是分页从左到右滚动,因此布局视图的宽度必须设置为和父滚动视图相等。
/*
上面是实现一个水平流式布局分页且从上往下滚动的标准属性设置方法。
*/
flowLayout.tg_hspace = 10
flowLayout.tg_vspace = 10 //设置子视图的水平和垂直间距。
flowLayout.tg_padding = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5) //布局视图的内边距设置!您可以注释掉这句话看看效果!如果设置内边距且也有分页时请将这个值设置和子视图间距相等。
scrollView.addSubview(flowLayout)
flowLayout.backgroundColor = CFTool.color(0)
self.addAllItemSubviews(flowLayout)
//获取流式布局的横屏size classes,并且设置当设备处于横屏时每页的数量由9个变为了18个。您可以注释掉这段代码,然后横竖屏切换看看效果。
let flowLayoutSC = flowLayout.tg_fetchSizeClass(with:.landscape, from:.default) as! TGFlowLayoutViewSizeClass
flowLayoutSC.tg_pagedCount = 18
}
/**
* 创建一个垂直分页从上向下滚动的流式布局
*/
func createVertPagingFlowLayout1(_ rootLayout: UIView)
{
let titleLabel = UILabel()
titleLabel.text = "垂直流式布局分页从上往下滚动:⬇︎"
titleLabel.sizeToFit()
titleLabel.tg_top.equal(20)
rootLayout.addSubview(titleLabel)
//要开启分页功能,必须要将流式布局加入到一个滚动视图里面作为子视图!!!
let scrollView = UIScrollView()
scrollView.isPagingEnabled = true //开启分页滚动模式!!您可以注释这句话看看非分页滚动的布局滚动效果。
scrollView.tg_height.equal(250) //设置明确的高度为200,因为宽度已经由父线性布局的gravity属性确定了,所以不需要设置了。
rootLayout.addSubview(scrollView)
//建立一个垂直数量约束流式布局:每列展示3个子视图,每页展示9个子视图,整体从上往下滚动。
let flowLayout = TGFlowLayout(.vert, arrangedCount:3)
flowLayout.tg_pagedCount = 9 //pagedCount设置为非0时表示开始分页展示的功能,这里表示每页展示9个子视图,这个数量必须是arrangedCount的倍数。
flowLayout.tg_height.equal(.wrap) //设置布局视图的高度由子视图包裹,当垂直流式布局高度设置为.wrap,并和pagedCount搭配使用会产生分页从上到下滚动的效果。
flowLayout.tg_width.equal(scrollView)
/*
上面是实现一个垂直流式布局分页且从上往下滚动的标准属性设置方法。
*/
flowLayout.tg_hspace = 10
flowLayout.tg_vspace = 10 //设置子视图的水平和垂直间距。
flowLayout.tg_padding = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5) //布局视图的内边距设置!您可以注释掉这句话看看效果!如果设置内边距且也有分页时请将这个值设置和子视图间距相等。
scrollView.addSubview(flowLayout)
flowLayout.backgroundColor = CFTool.color(0)
self.addAllItemSubviews(flowLayout)
//获取流式布局的横屏size classes,并且设置当设备处于横屏时每页的数量由9个变为了18个。您可以注释掉这段代码,然后横竖屏切换看看效果。
let flowLayoutSC = flowLayout.tg_fetchSizeClass(with:.landscape, from:.default) as! TGFlowLayoutViewSizeClass
flowLayoutSC.tg_arrangedCount = 6
flowLayoutSC.tg_pagedCount = 18
}
/**
* 创建一个垂直分页从左向右滚动的流式布局
*/
func createVertPagingFlowLayout2(_ rootLayout: UIView)
{
let titleLabel = UILabel()
titleLabel.text = "垂直流式布局分页从左往右滚动:➡︎"
titleLabel.sizeToFit()
titleLabel.tg_top.equal(20)
rootLayout.addSubview(titleLabel)
//要开启分页功能,必须要将流式布局加入到一个滚动视图里面作为子视图!!!
let scrollView = UIScrollView()
scrollView.isPagingEnabled = true //开启分页滚动模式!!您可以注释这句话看看非分页滚动的布局滚动效果。
scrollView.tg_height.equal(200) //设置明确的高度为200,因为宽度已经由父线性布局的gravity属性确定了,所以不需要设置了。
rootLayout.addSubview(scrollView)
//建立一个垂直数量约束流式布局:每列展示3个子视图,每页展示9个子视图,整体从左往右滚动。
let flowLayout = TGFlowLayout(.vert, arrangedCount:3)
flowLayout.tg_pagedCount = 9 //pagedCount设置为非0时表示开始分页展示的功能,这里表示每页展示9个子视图,这个数量必须是arrangedCount的倍数。
flowLayout.tg_width.equal(.wrap) //设置布局视图的宽度由子视图包裹,当垂直流式布局的宽度设置为.wrap,并和pagedCount搭配使用会产生分页从左到右滚动的效果。
flowLayout.tg_height.equal(scrollView)
/*
上面是实现一个垂直流式布局分页且从左往右滚动的标准属性设置方法。
*/
flowLayout.tg_hspace = 10
flowLayout.tg_vspace = 10 //设置子视图的水平和垂直间距。
flowLayout.tg_padding = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5) //布局视图的内边距设置!您可以注释掉这句话看看效果!如果设置内边距且也有分页时请将这个值设置和子视图间距相等。
scrollView.addSubview(flowLayout)
flowLayout.backgroundColor = CFTool.color(0)
self.addAllItemSubviews(flowLayout)
//获取流式布局的横屏size classes,并且设置当设备处于横屏时每页的数量由9个变为了18个。您可以注释掉这段代码,然后横竖屏切换看看效果。
let flowLayoutSC = flowLayout.tg_fetchSizeClass(with:.landscape, from:.default) as! TGFlowLayoutViewSizeClass
flowLayoutSC.tg_arrangedCount = 6
flowLayoutSC.tg_pagedCount = 18
}
}
| 56db23bb962a962f89fb31073877eae7 | 33.856031 | 144 | 0.64981 | false | false | false | false |
tomtom5005/SideMenu | refs/heads/master | SideMenu/MenuViewController.swift | mit | 1 | //
// MenuViewController.swift
// SideMenu
//
// Created by Thomas Thompson on 10/19/16.
// Copyright © 2016 Thomas Thompson. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, DashboardViewControllerDelegateProtocol{
@IBOutlet weak var menuTableView: UITableView!
@IBOutlet var leadingConstraint: NSLayoutConstraint!
var dashboardVC: DashboardViewController?
let menuItems = ["Campaigns", "Contacts"]
let menuWidth:CGFloat = 300.0
let animationDuration:NSTimeInterval = 0.4
override func viewDidLoad() {
super.viewDidLoad()
menuTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
//MARK: - DashboardViewControllerDelegateProtocol method
func didTapPancakeButton(sender: UIButton) {
self.leadingConstraint?.constant = self.leadingConstraint?.constant > 0.0 ? 0.0 : menuWidth
UIView.animateWithDuration(animationDuration) {
self.view.layoutIfNeeded()
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EmbedSegue_MenuVC_ContentVC"
{
dashboardVC = segue.destinationViewController as? DashboardViewController
dashboardVC!.delegate = self
}
}
//MARK: - TableView Data Source Method
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
return 1;
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int{
return 2
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell:UITableViewCell = menuTableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.text = menuItems[indexPath.row];
return cell
}
//MARK: - TableView Delegate Method
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
leadingConstraint.constant = 0.0
dashboardVC?.label.text = menuItems[indexPath.row]
UIView.animateWithDuration(animationDuration) {
self.view.layoutIfNeeded()
}
}
}
| e2c67f6e1b66c5e5524e8f50fe9aba9c | 31.608108 | 128 | 0.682138 | false | false | false | false |
IngmarStein/swift | refs/heads/master | test/stdlib/Strideable.swift | apache-2.0 | 4 | //===--- Strideable.swift - Tests for strided iteration -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
//
import StdlibUnittest
// Check that the generic parameter is called 'Element'.
protocol TestProtocol1 {}
extension StrideToIterator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideTo where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideThroughIterator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideThrough where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
var StrideTestSuite = TestSuite("Strideable")
struct R : Strideable {
typealias Distance = Int
var x: Int
init(_ x: Int) {
self.x = x
}
func distance(to rhs: R) -> Int {
return rhs.x - x
}
func advanced(by n: Int) -> R {
return R(x + n)
}
}
StrideTestSuite.test("Double") {
func checkOpen(from start: Double, to end: Double, by stepSize: Double, sum: Double) {
// Work on Doubles
expectEqual(
sum,
stride(from: start, to: end, by: stepSize).reduce(0.0, +))
}
func checkClosed(from start: Double, through end: Double, by stepSize: Double, sum: Double) {
// Work on Doubles
expectEqual(
sum,
stride(from: start, through: end, by: stepSize).reduce(0.0, +))
}
checkOpen(from: 1.0, to: 15.0, by: 3.0, sum: 35.0)
checkOpen(from: 1.0, to: 16.0, by: 3.0, sum: 35.0)
checkOpen(from: 1.0, to: 17.0, by: 3.0, sum: 51.0)
checkOpen(from: 1.0, to: -13.0, by: -3.0, sum: -25.0)
checkOpen(from: 1.0, to: -14.0, by: -3.0, sum: -25.0)
checkOpen(from: 1.0, to: -15.0, by: -3.0, sum: -39.0)
checkOpen(from: 4.0, to: 16.0, by: -3.0, sum: 0.0)
checkOpen(from: 1.0, to: -16.0, by: 3.0, sum: 0.0)
checkClosed(from: 1.0, through: 15.0, by: 3.0, sum: 35.0)
checkClosed(from: 1.0, through: 16.0, by: 3.0, sum: 51.0)
checkClosed(from: 1.0, through: 17.0, by: 3.0, sum: 51.0)
checkClosed(from: 1.0, through: -13.0, by: -3.0, sum: -25.0)
checkClosed(from: 1.0, through: -14.0, by: -3.0, sum: -39.0)
checkClosed(from: 1.0, through: -15.0, by: -3.0, sum: -39.0)
checkClosed(from: 4.0, through: 16.0, by: -3.0, sum: 0.0)
checkClosed(from: 1.0, through: -16.0, by: 3.0, sum: 0.0)
}
StrideTestSuite.test("HalfOpen") {
func check(from start: Int, to end: Int, by stepSize: Int, sum: Int) {
// Work on Ints
expectEqual(
sum,
stride(from: start, to: end, by: stepSize).reduce(
0, +))
// Work on an arbitrary RandomAccessIndex
expectEqual(
sum,
stride(from: R(start), to: R(end), by: stepSize).reduce(0) { $0 + $1.x })
}
check(from: 1, to: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, to: 16, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, to: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, to: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, to: -14, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, to: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 4, to: 16, by: -3, sum: 0)
check(from: 1, to: -16, by: 3, sum: 0)
}
StrideTestSuite.test("Closed") {
func check(from start: Int, through end: Int, by stepSize: Int, sum: Int) {
// Work on Ints
expectEqual(
sum,
stride(from: start, through: end, by: stepSize).reduce(
0, +))
// Work on an arbitrary RandomAccessIndex
expectEqual(
sum,
stride(from: R(start), through: R(end), by: stepSize).reduce(
0, { $0 + $1.x })
)
}
check(from: 1, through: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, through: 16, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, through: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, through: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, through: -14, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 1, through: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 4, through: 16, by: -3, sum: 0)
check(from: 1, through: -16, by: 3, sum: 0)
}
StrideTestSuite.test("OperatorOverloads") {
var r1 = R(50)
var r2 = R(70)
var stride: Int = 5
do {
var result = r1 + stride
expectType(R.self, &result)
expectEqual(55, result.x)
}
do {
var result = stride + r1
expectType(R.self, &result)
expectEqual(55, result.x)
}
do {
var result = r1 - stride
expectType(R.self, &result)
expectEqual(45, result.x)
}
do {
var result = r1 - r2
expectType(Int.self, &result)
expectEqual(-20, result)
}
do {
var result = r1
result += stride
expectType(R.self, &result)
expectEqual(55, result.x)
}
do {
var result = r1
result -= stride
expectType(R.self, &result)
expectEqual(45, result.x)
}
}
StrideTestSuite.test("FloatingPointStride") {
var result = [Double]()
for i in stride(from: 1.4, through: 3.4, by: 1) {
result.append(i)
}
expectEqual([ 1.4, 2.4, 3.4 ], result)
}
StrideTestSuite.test("ErrorAccumulation") {
let a = Array(stride(from: Float(1.0), through: Float(2.0), by: Float(0.1)))
expectEqual(11, a.count)
expectEqual(Float(2.0), a.last)
let b = Array(stride(from: Float(1.0), to: Float(10.0), by: Float(0.9)))
expectEqual(10, b.count)
}
func strideIteratorTest<
Stride : Sequence
>(_ stride: Stride, nonNilResults: Int) {
var i = stride.makeIterator()
for _ in 0..<nonNilResults {
expectNotNil(i.next())
}
for _ in 0..<10 {
expectNil(i.next())
}
}
StrideTestSuite.test("StrideThroughIterator/past end") {
strideIteratorTest(stride(from: 0, through: 3, by: 1), nonNilResults: 4)
strideIteratorTest(
stride(from: UInt8(0), through: 255, by: 5), nonNilResults: 52)
}
StrideTestSuite.test("StrideThroughIterator/past end/backward") {
strideIteratorTest(stride(from: 3, through: 0, by: -1), nonNilResults: 4)
}
StrideTestSuite.test("StrideToIterator/past end") {
strideIteratorTest(stride(from: 0, to: 3, by: 1), nonNilResults: 3)
}
StrideTestSuite.test("StrideToIterator/past end/backward") {
strideIteratorTest(stride(from: 3, to: 0, by: -1), nonNilResults: 3)
}
runAllTests()
| f34447ba9a9ca915eca51d39045b771e | 27.479339 | 95 | 0.598375 | false | true | false | false |
TJRoger/Go-RSS | refs/heads/master | Go RSS/NewTableViewController.swift | mit | 1 | //
// MasterViewController.swift
// Go RSS
//
// Created by Roger on 7/22/15.
// Copyright (c) 2015 Roger. All rights reserved.
//
import UIKit
import MWFeedParser
import MBProgressHUD
import KINWebBrowser
class NewsTableViewController: UITableViewController, MWFeedParserDelegate {
// var detailViewController: DetailViewController? = nil
var source: RSSSource? = RSSSource(title: "Tongji University", url: NSURL(string: "http://news.tongji.edu.cn/rss.php?classid=12")!, brief: "Tongji News")
var objects = [MWFeedItem]()
var progressHUD: MBProgressHUD?
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// self.navigationItem.leftBarButtonItem = self.editButtonItem()
//
// let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
// self.navigationItem.rightBarButtonItem = addButton
// if let split = self.splitViewController {
// let controllers = split.viewControllers
// self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
// }
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
// self.tableView.registerClass(NewsTableViewCell.self, forCellReuseIdentifier: "newsCell")
fetch()
}
func fetch() {
if let url = source?.url {
let feedParser = MWFeedParser(feedURL: url)
feedParser.delegate = self
feedParser.parse()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// func insertNewObject(sender: AnyObject) {
// objects.insert(NSDate(), atIndex: 0)
// let indexPath = NSIndexPath(forRow: 0, inSection: 0)
// self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
// }
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
// let object = objects[indexPath.row]
// let controller = (segue.destinationViewController as! UINavigationController).topViewController as! KINWebBrowserViewController
// controller.detailItem = object
// controller.loadURL(NSURL(string: object.link))
// controller.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "dismiss:")
// controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// func dismiss(sender: AnyObject){
// self.navigationController?.visibleViewController.dismissViewControllerAnimated(true, completion: nil)
// }
//MARK: - MWFeedParserDelegate
func feedParserDidStart(parser: MWFeedParser!) {
progressHUD = MBProgressHUD()
progressHUD?.show(true)
// self.objects = [MWFeedItem]()
}
func feedParserDidFinish(parser: MWFeedParser!) {
progressHUD?.hide(true)
self.tableView.reloadData()
}
func feedParser(parser: MWFeedParser!, didFailWithError error: NSError!) {
progressHUD?.hide(true)
}
func feedParser(parser: MWFeedParser!, didParseFeedInfo info: MWFeedInfo!) {
println(info)
self.title = info.title
}
func feedParser(parser: MWFeedParser!, didParseFeedItem item: MWFeedItem!) {
println(item)
self.objects.append(item)
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("newsCell", forIndexPath: indexPath) as! NewsTableViewCell
// let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! NewsTableViewCell
cell.object = objects[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = objects[indexPath.row] as MWFeedItem
let con = KINWebBrowserViewController()
con.loadURL(NSURL(string: item.link))
self.navigationController?.pushViewController(con, animated: true)
}
}
| 57912201da70c76ffc984b1c46adf76b | 37.589404 | 164 | 0.674961 | false | false | false | false |
Jaelene/PhotoBroswer | refs/heads/master | PhotoBroswer/PhotoBroswer/Controller/PhotoBroswer+Indicator.swift | mit | 2 | //
// PhotoBroswer+Indicator.swift
// PhotoBroswer
//
// Created by 冯成林 on 15/8/13.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
extension PhotoBroswer{
/** pagecontrol准备 */
func pagecontrolPrepare(){
if !hideMsgForZoomAndDismissWithSingleTap {return}
view.addSubview(pagecontrol)
pagecontrol.make_bottomInsets_bottomHeight(left: 0, bottom: 0, right: 0, bottomHeight: 37)
pagecontrol.numberOfPages = photoModels.count
pagecontrol.enabled = false
}
/** pageControl页面变动 */
func pageControlPageChanged(page: Int){
if page<0 || page>=photoModels.count {return}
if showType == PhotoBroswer.ShowType.ZoomAndDismissWithSingleTap && hideMsgForZoomAndDismissWithSingleTap{
pagecontrol.currentPage = page
}
}
}
| 11a5fee139e005da62afa1fc1ed78cd3 | 24.941176 | 114 | 0.639456 | false | false | false | false |
Khan/Swiftx | refs/heads/master | Swiftx/Result.swift | bsd-3-clause | 1 | //
// Result.swift
// swiftz
//
// Created by Maxwell Swadling on 9/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
import class Foundation.NSError
import typealias Foundation.NSErrorPointer
/// Result is similar to an Either, except specialized to have an Error case that can
/// only contain an NSError.
public enum Result<V> {
case Error(NSError)
case Value(Box<V>)
public init(_ e: NSError?, _ v: V) {
if let ex = e {
self = Result.Error(ex)
} else {
self = Result.Value(Box(v))
}
}
/// Converts a Result to a more general Either type.
public func toEither() -> Either<NSError, V> {
switch self {
case let Error(e):
return .Left(Box(e))
case let Value(v):
return Either.Right(Box(v.value))
}
}
/// Much like the ?? operator for Optional types, takes a value and a function,
/// and if the Result is Error, returns the error, otherwise maps the function over
/// the value in Value and returns that value.
public func fold<B>(value: B, f: V -> B) -> B {
switch self {
case Error(_):
return value
case let Value(v):
return f(v.value)
}
}
/// Named function for `>>-`. If the Result is Error, simply returns
/// a New Error with the value of the receiver. If Value, applies the function `f`
/// and returns the result.
public func flatMap<S>(f: V -> Result<S>) -> Result<S> {
return self >>- f
}
/// Creates an Error with the given value.
public static func error(e: NSError) -> Result<V> {
return .Error(e)
}
/// Creates a Value with the given value.
public static func value(v: V) -> Result<V> {
return .Value(Box(v))
}
}
/// MARK: Function Constructors
/// Takes a function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A>(fn : (NSErrorPointer) -> A) -> Result<A> {
var err : NSError? = nil
let b = fn(&err)
return (err != nil) ? .Error(err!) : .Value(Box(b))
}
/// Takes a 1-ary function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A, B>(fn : (A, NSErrorPointer) -> B) -> A -> Result<B> {
return { a in
var err : NSError? = nil
let b = fn(a, &err)
return (err != nil) ? .Error(err!) : .Value(Box(b))
}
}
/// Takes a 2-ary function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A, B, C>(fn : (A, B, NSErrorPointer) -> C) -> A -> B -> Result<C> {
return { a in { b in
var err : NSError? = nil
let c = fn(a, b, &err)
return (err != nil) ? .Error(err!) : .Value(Box(c))
} }
}
/// Takes a 3-ary function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A, B, C, D>(fn : (A, B, C, NSErrorPointer) -> D) -> A -> B -> C -> Result<D> {
return { a in { b in { c in
var err : NSError? = nil
let d = fn(a, b, c, &err)
return (err != nil) ? .Error(err!) : .Value(Box(d))
} } }
}
/// Takes a 4-ary function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A, B, C, D, E>(fn : (A, B, C, D, NSErrorPointer) -> E) -> A -> B -> C -> D -> Result<E> {
return { a in { b in { c in { d in
var err : NSError? = nil
let e = fn(a, b, c, d, &err)
return (err != nil) ? .Error(err!) : .Value(Box(e))
} } } }
}
/// Takes a 5-ary function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A, B, C, D, E, F>(fn : (A, B, C, D, E, NSErrorPointer) -> F) -> A -> B -> C -> D -> E -> Result<F> {
return { a in { b in { c in { d in { e in
var err : NSError? = nil
let f = fn(a, b, c, d, e, &err)
return (err != nil) ? .Error(err!) : .Value(Box(f))
} } } } }
}
/// Infix 1-ary from
public func !! <A, B>(fn : (A, NSErrorPointer) -> B, a : A) -> Result<B> {
var err : NSError? = nil
let b = fn(a, &err)
return (err != nil) ? .Error(err!) : .Value(Box(b))
}
/// Infix 2-ary from
public func !! <A, B, C>(fn : (A, B, NSErrorPointer) -> C, t : (A, B)) -> Result<C> {
var err : NSError? = nil
let c = fn(t.0, t.1, &err)
return (err != nil) ? .Error(err!) : .Value(Box(c))
}
/// Infix 3-ary from
public func !! <A, B, C, D>(fn : (A, B, C, NSErrorPointer) -> D, t : (A, B, C)) -> Result<D> {
var err : NSError? = nil
let d = fn(t.0, t.1, t.2, &err)
return (err != nil) ? .Error(err!) : .Value(Box(d))
}
/// Infix 4-ary from
public func !! <A, B, C, D, E>(fn : (A, B, C, D, NSErrorPointer) -> E, t : (A, B, C, D)) -> Result<E> {
var err : NSError? = nil
let e = fn(t.0, t.1, t.2, t.3, &err)
return (err != nil) ? .Error(err!) : .Value(Box(e))
}
/// Infix 5-ary from
public func !! <A, B, C, D, E, F>(fn : (A, B, C, D, E, NSErrorPointer) -> F, t : (A, B, C, D, E)) -> Result<F> {
var err : NSError? = nil
let f = fn(t.0, t.1, t.2, t.3, t.4, &err)
return (err != nil) ? .Error(err!) : .Value(Box(f))
}
/// MARK: Equatable
public func == <V: Equatable>(lhs: Result<V>, rhs: Result<V>) -> Bool {
switch (lhs, rhs) {
case let (.Error(l), .Error(r)) where l == r:
return true
case let (.Value(l), .Value(r)) where l.value == r.value:
return true
default:
return false
}
}
public func != <V: Equatable>(lhs: Result<V>, rhs: Result<V>) -> Bool {
return !(lhs == rhs)
}
/// MARK: Functor, Applicative, Monad
/// Applicative `pure` function, lifts a value into a Value.
public func pure<V>(a: V) -> Result<V> {
return .Value(Box(a))
}
/// Functor `fmap`. If the Result is Error, ignores the function and returns the Error.
/// If the Result is Value, applies the function to the Right value and returns the result
/// in a new Value.
public func <^> <VA, VB>(f: VA -> VB, a: Result<VA>) -> Result<VB> {
switch a {
case let .Error(l):
return .Error(l)
case let .Value(r):
return Result.Value(Box(f(r.value)))
}
}
/// Applicative Functor `apply`. Given an Result<VA -> VB> and an Result<VA>,
/// returns a Result<VB>. If the `f` or `a' param is an Error, simply returns an Error with the
/// same value. Otherwise the function taken from Value(f) is applied to the value from Value(a)
/// And a Value is returned.
public func <*> <VA, VB>(f: Result<VA -> VB>, a: Result<VA>) -> Result<VB> {
switch (a, f) {
case let (.Error(l), _):
return .Error(l)
case let (.Value(r), .Error(m)):
return .Error(m)
case let (.Value(r), .Value(g)):
return Result<VB>.Value(Box(g.value(r.value)))
}
}
/// Monadic `bind`. Given an Result<VA>, and a function from VA -> Result<VB>,
/// applies the function `f` if `a` is Value, otherwise the function is ignored and an Error
/// with the Error value from `a` is returned.
public func >>- <VA, VB>(a: Result<VA>, f: VA -> Result<VB>) -> Result<VB> {
switch a {
case let .Error(l):
return .Error(l)
case let .Value(r):
return f(r.value)
}
}
| aced2a18a4608b0c83eb45c0117f9fb0 | 30.45045 | 117 | 0.608851 | false | false | false | false |
YoungGary/DYTV | refs/heads/master | DouyuTV/DouyuTV/Class/First(首页)/Controller/GameViewController.swift | mit | 1 | //
// GameViewController.swift
// DouyuTV
//
// Created by YOUNG on 2017/4/7.
// Copyright © 2017年 Young. All rights reserved.
//GameViewController
import UIKit
private let enterCellID = "entertainment"
private let kTopicViewH : CGFloat = 200
class GameViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate{
lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10)
layout.headerReferenceSize = CGSize(width: kScreenWidth, height: 50)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.white
collectionView.register(UINib(nibName: "VideoCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: enterCellID)
collectionView.register( UINib(nibName: "HeaderReusablleView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerID)
collectionView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
return collectionView
}()
var viewModel : GameViewModel = GameViewModel()
lazy var topicView : TopicCollectionView = {
let topicView = TopicCollectionView.loadViewWithNib()
topicView.frame = CGRect(x: 0, y: -(kTopicViewH), width: kScreenWidth, height: kTopicViewH)
return topicView
}()
override func viewDidLoad() {
super.viewDidLoad()
//界面
setupInterface()
//fetch data
fetchDataFromNet()
collectionView.contentInset = UIEdgeInsetsMake(kTopicViewH, 0, 0, 0)
}
}
extension GameViewController{
func setupInterface() -> () {
view.addSubview(collectionView)
collectionView.addSubview(topicView)
}
func fetchDataFromNet() -> () {
viewModel.fetchPhoneGameData {
self.collectionView.reloadData()
self.topicView.dataArr = self.viewModel.groupArr
}
}
}
extension GameViewController{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return viewModel.groupArr.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let group = viewModel.groupArr[section]
return group.authors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: enterCellID, for: indexPath) as! VideoCollectionViewCell
let group = viewModel.groupArr[indexPath.section]
cell.normalModel = group.authors[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerID, for: indexPath) as? HeaderReusablleView
headerView?.headerModel = viewModel.groupArr[indexPath.section]
return headerView!
}
}
| 0634e8ff4183e100087606f4921741ac | 34.960784 | 189 | 0.690022 | false | false | false | false |
LDlalala/LDZBLiving | refs/heads/master | LDZBLiving/LDZBLiving/Classes/Home/Model/LDAnchorModel.swift | mit | 1 | //
// LDAnchorModel.swift
// LDZBLiving
//
// Created by 李丹 on 17/8/9.
// Copyright © 2017年 LD. All rights reserved.
//
import UIKit
class LDAnchorModel: LDBaseModel {
var roomid : Int = 0
var name : String = ""
var pic51 : String = ""
var pic74 : String = ""
var live : Int = 0 // 是否在直播
var push : Int = 0 // 直播显示方式
var focus : Int = 0 // 关注数
var isEvenIndex : Bool = false
}
| 4cc389b2f49c78a3c97c5da90b63ab7d | 19 | 46 | 0.578571 | false | false | false | false |
midoks/Swift-Learning | refs/heads/master | GitHubStar/GitHubStar/GitHubStar/Vendor/MDGitHubWait/MDGitHubWait.swift | apache-2.0 | 1 | //
// MDGitHubWait.swift
// GitHubStar
//
// Created by midoks on 16/3/7.
// Copyright © 2016年 midoks. All rights reserved.
//
import UIKit
class MDGitHubWait: UIView {
var imageBackColor = UIView()
var imageGit:UIImageView = UIImageView()
var imageGitWH:CGFloat = 60
var imageStar:UIImageView = UIImageView()
var imageStars = Array<UIImageView>()
var imageStarWH:CGFloat = 12
var listFrame:Array<CGRect> = Array<CGRect>()
var space:CGFloat = 0.0
var time:CGFloat = 3.0
override init(frame: CGRect) {
super.init(frame:frame)
self.initView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initView(){
initBackColor()
let imageGitR = floor(sqrt(pow(imageGitWH/2, 2)*2))
let imageStarR = sqrt(pow(imageStarWH/2, 2)*2)
let starBL = sqrt(pow((imageGitR + imageStarR + space),2)/2)
print(imageGitR)
print(imageStarR)
print(starBL)
imageGit.image = UIImage(named: "welcome")
addSubview(imageGit)
imageGit.frame = CGRect(x: 0, y: 0, width: imageGitWH, height: imageGitWH)
imageGit.center = center
for _ in 0 ..< 6 {
listFrame.append(CGRect(x: 0, y: 0 , width: imageStarWH, height: imageStarWH))
}
var c = 0
for i in listFrame {
let img = UIImageView(image: UIImage(named: "github_starred"))
img.frame = i
imageStars.append(img)
addSubview(img)
let start = -((Double.pi*2) / Double(listFrame.count)) * Double(c)
let end = Double.pi + start
c += 1
print(start,end)
let path_a = UIBezierPath()
path_a.addArc(withCenter: center, radius: imageGitR, startAngle: CGFloat(start), endAngle: CGFloat(end), clockwise: false)
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = path_a.cgPath
animation.isRemovedOnCompletion = false
animation.repeatCount = 1000000
animation.duration = 1
animation.autoreverses = true
animation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)]
img.layer.add(animation, forKey: "animation")
}
//rotationAnimation()
}
func rotationAnimation(){
}
func initBackColor(){
//imageBackColor.frame = UIApplication.sharedApplication().windows.first!.frame
//imageBackColor.backgroundColor = UIColor.blackColor()
//imageBackColor.layer.opacity = 0.1
//addSubview(imageBackColor)
//UIApplication.sharedApplication().windows.first?.addSubview(imageBackColor)
}
override func layoutSubviews() {
super.layoutSubviews()
print(self.imageGit.frame)
}
}
| e111d4cf7f62e6369cf5a122b7f8c7e1 | 26.33913 | 134 | 0.56743 | false | false | false | false |
DarrenKong/firefox-ios | refs/heads/master | Shared/SentryIntegration.swift | mpl-2.0 | 5 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Sentry
public enum SentryTag: String {
case swiftData = "SwiftData"
case browserDB = "BrowserDB"
case notificationService = "NotificationService"
case unifiedTelemetry = "UnifiedTelemetry"
case general = "General"
case tabManager = "TabManager"
case bookmarks = "Bookmarks"
}
public class Sentry {
public static let shared = Sentry()
public static var crashedLastLaunch: Bool {
return Client.shared?.crashedLastLaunch() ?? false
}
private let SentryDSNKey = "SentryDSN"
private let SentryDeviceAppHashKey = "SentryDeviceAppHash"
private let DefaultDeviceAppHash = "0000000000000000000000000000000000000000"
private let DeviceAppHashLength = UInt(20)
private var enabled = false
private var attributes: [String: Any] = [:]
public func setup(sendUsageData: Bool) {
assert(!enabled, "Sentry.setup() should only be called once")
if DeviceInfo.isSimulator() {
Logger.browserLogger.debug("Not enabling Sentry; Running in Simulator")
return
}
if !sendUsageData {
Logger.browserLogger.debug("Not enabling Sentry; Not enabled by user choice")
return
}
guard let dsn = Bundle.main.object(forInfoDictionaryKey: SentryDSNKey) as? String, !dsn.isEmpty else {
Logger.browserLogger.debug("Not enabling Sentry; Not configured in Info.plist")
return
}
Logger.browserLogger.debug("Enabling Sentry crash handler")
do {
Client.shared = try Client(dsn: dsn)
try Client.shared?.startCrashHandler()
enabled = true
// If we have not already for this install, generate a completely random identifier
// for this device. It is stored in the app group so that the same value will
// be used for both the main application and the app extensions.
if let defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier), defaults.string(forKey: SentryDeviceAppHashKey) == nil {
defaults.set(Bytes.generateRandomBytes(DeviceAppHashLength).hexEncodedString, forKey: SentryDeviceAppHashKey)
defaults.synchronize()
}
// For all outgoing reports, override the default device identifier with our own random
// version. Default to a blank (zero) identifier in case of errors.
Client.shared?.beforeSerializeEvent = { event in
let deviceAppHash = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)?.string(forKey: self.SentryDeviceAppHashKey)
event.context?.appContext?["device_app_hash"] = deviceAppHash ?? self.DefaultDeviceAppHash
var attributes = event.extra ?? [:]
attributes.merge(with: self.attributes)
event.extra = attributes
}
} catch let error {
Logger.browserLogger.error("Failed to initialize Sentry: \(error)")
}
}
public func crash() {
Client.shared?.crash()
}
/*
This is the behaviour we want for Sentry logging
.info .error .severe
Debug y y y
Beta y y y
Relase n n y
*/
private func shouldNotSendEventFor(_ severity: SentrySeverity) -> Bool {
return !enabled || (AppConstants.BuildChannel == .release && severity != .fatal)
}
private func makeEvent(message: String, tag: String, severity: SentrySeverity, extra: [String: Any]?) -> Event {
let event = Event(level: severity)
event.message = message
event.tags = ["tag": tag]
if let extra = extra {
event.extra = extra
}
return event
}
public func send(message: String, tag: SentryTag = .general, severity: SentrySeverity = .info, extra: [String: Any]? = nil, description: String? = nil, completion: SentryRequestFinished? = nil) {
// Build the dictionary
var extraEvents: [String: Any] = [:]
if let paramEvents = extra {
extraEvents.merge(with: paramEvents)
}
if let extraString = description {
extraEvents.merge(with: ["errorDescription": extraString])
}
printMessage(message: message, extra: extraEvents)
// Only report fatal errors on release
if shouldNotSendEventFor(severity) {
completion?(nil)
return
}
let event = makeEvent(message: message, tag: tag.rawValue, severity: severity, extra: extraEvents)
Client.shared?.send(event: event, completion: completion)
}
public func sendWithStacktrace(message: String, tag: SentryTag = .general, severity: SentrySeverity = .info, extra: [String: Any]? = nil, description: String? = nil, completion: SentryRequestFinished? = nil) {
var extraEvents: [String: Any] = [:]
if let paramEvents = extra {
extraEvents.merge(with: paramEvents)
}
if let extraString = description {
extraEvents.merge(with: ["errorDescription": extraString])
}
printMessage(message: message, extra: extraEvents)
// Do not send messages to Sentry if disabled OR if we are not on beta and the severity isnt severe
if shouldNotSendEventFor(severity) {
completion?(nil)
return
}
Client.shared?.snapshotStacktrace {
let event = self.makeEvent(message: message, tag: tag.rawValue, severity: severity, extra: extraEvents)
Client.shared?.appendStacktrace(to: event)
event.debugMeta = nil
Client.shared?.send(event: event, completion: completion)
}
}
public func addAttributes(_ attributes: [String: Any]) {
self.attributes.merge(with: attributes)
}
private func printMessage(message: String, extra: [String: Any]? = nil) {
let string = extra?.reduce("") { (result: String, arg1) in
let (key, value) = arg1
return "\(result), \(key): \(value)"
}
Logger.browserLogger.debug("Sentry: \(message) \(string ??? "")")
}
}
| 6227ec191a19edc82a5e3bb2da5dc238 | 38.674847 | 213 | 0.625174 | false | false | false | false |
FuckBoilerplate/RxCache | refs/heads/master | Examples/Pods/Gloss/Sources/ExtensionArray.swift | mit | 1 | //
// ExtensionArray.swift
// Gloss
//
// Copyright (c) 2016 Rahul Katariya
//
// 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
// MARK: - Decodable
public extension Array where Element: Decodable {
// MARK: Public functions
/**
Returns array of new objects created from provided JSON array.
If any decodings fail, nil is returned.
- parameter jsonArray: Array of JSON representations of objects.
- returns: Array of objects created from JSON.
*/
static func fromJSONArray(_ jsonArray: [JSON]) -> [Element]? {
var models: [Element] = []
for json in jsonArray {
let model = Element(json: json)
if let model = model {
models.append(model)
} else {
return nil
}
}
return models
}
}
// MARK: - Encodable
public extension Array where Element: Encodable {
// MARK: Public functions
/**
Encodes array of objects as JSON array.
If any encodings fail, nil is returned.
- returns: Array of JSON created from objects.
*/
func toJSONArray() -> [JSON]? {
var jsonArray: [JSON] = []
for json in self {
if let json = json.toJSON() {
jsonArray.append(json)
} else {
return nil
}
}
return jsonArray
}
}
| 1de5032b45510475eda1a6d45fef1359 | 28.290698 | 80 | 0.62763 | false | false | false | false |
geasscode/TodoList | refs/heads/master | ToDoListApp/ToDoListApp/controllers/SideBarNavigation.swift | mit | 1 | //
// SideBarNavigation.swift
// ToDoListApp
//
// Created by desmond on 12/8/14.
// Copyright (c) 2014 Phoenix. All rights reserved.
//
import UIKit
class SideBarNavigation: ENSideMenuNavigationController, ENSideMenuDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let sideBarList = self.storyboard?.instantiateViewControllerWithIdentifier("sideBarList") as SideBarTableViewController
sideMenu = ENSideMenu(sourceView: self.view, menuTableViewController: sideBarList, menuPosition:.Left)
sideMenu?.delegate = self //optional
sideMenu?.menuWidth = 250 // optional, default is 160
//sideMenu?.bouncingEnabled = false
// make navigation bar showing over side menu
view.bringSubviewToFront(navigationBar)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - ENSideMenu Delegate
func sideMenuWillOpen() {
println("sideMenuWillOpen")
}
func sideMenuWillClose() {
println("sideMenuWillClose")
}
}
| f6ed8507de81da35453a81454ce35f0a | 27.804878 | 136 | 0.665538 | false | false | false | false |
yunhan0/ChineseChess | refs/heads/master | ChineseChess/Model/Pieces/King.swift | mit | 1 | //
// King.swift
// ChineseChess
//
// Created by Yunhan Li on 5/15/17.
// Copyright © 2017 Yunhan Li. All rights reserved.
//
import Foundation
class King : Piece {
override func nextPossibleMoves(boardStates: [[Piece?]]) -> [Vector2] {
// King can move 1 step in four directions.
let possibleMoves: [Vector2] = [
Vector2(x: position.x + 1, y: position.y),
Vector2(x: position.x - 1, y: position.y),
Vector2(x: position.x, y: position.y + 1),
Vector2(x: position.x, y: position.y - 1)]
var ret : [Vector2] = []
for _move in possibleMoves {
if isValidMove(_move, boardStates) {
ret.append(_move)
}
}
return ret
}
override func isValidMove(_ move: Vector2, _ boardStates: [[Piece?]]) -> Bool {
// King can only move inside forbidden area
if !Board.isForbidden(position: move) {
return false
}
let nextState = boardStates[move.x][move.y]
if nextState != nil {
if nextState?.owner == self.owner {
return false
}
}
return true
}
}
| 92a6170e06d882e4d676013bfc58fe29 | 25.638298 | 83 | 0.510383 | false | false | false | false |
team-pie/DDDKit | refs/heads/master | DDDKit/Classes/DDD360VideoView.swift | mit | 1 | //
// DDD360VideoView.swift
// Pods
//
// Created by Guillaume Sabran on 1/23/17.
//
//
import UIKit
import GLKit
import AVFoundation
import GLMatrix
/// A convenience view controller to display a 360 video
open class DDD360VideoViewController: DDDViewController {
/// display the corresponding video
public func show(video: AVPlayerItem) {
let player = AVPlayer(playerItem: video)
self.player = player
setUpPlayback(for: video.asset)
let videoTexture = DDDVideoTexture(player: player)
videoNode.material.set(property: videoTexture, for: "SamplerY", and: "SamplerUV")
}
/// display the corresponding video
public func show(from url: URL) {
show(video: AVPlayerItem(asset: AVAsset(url: url)))
}
/// The player corresponding to the current video
public internal(set) var player: AVPlayer?
/// The default shader for videos
public internal(set) var defaultShader: DDDFragmentShader!
/// The scene's node that holds the video
public fileprivate(set) var videoNode: DDDNode!
private let kTracksKey = "tracks"
private let kPlayableKey = "playable"
private let kRateKey = "rate"
private let kCurrentItemKey = "currentItem"
private let kStatusKey = "status"
private var playerItem: AVPlayerItem?
override open func viewDidLoad() {
super.viewDidLoad()
setUpScene()
setupGestureRecognizer()
}
private func setUpPlayback(for asset: AVAsset) {
let requestedKeys = [kTracksKey, kPlayableKey]
asset.loadValuesAsynchronously(forKeys: requestedKeys, completionHandler: {
DispatchQueue.main.async {
let status = asset.statusOfValue(forKey: self.kTracksKey, error: nil)
if status == AVKeyValueStatus.loaded {
self.playerItem = AVPlayerItem(asset: asset)
self.player?.replaceCurrentItem(with: self.playerItem!)
self.player?.play()
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.playerItem!, queue: .main) { [weak self] _ in
self?.player?.seek(to: kCMTimeZero)
self?.player?.play()
}
}
}
})
}
private func setUpScene() {
videoNode = DDDNode()
videoNode.geometry = DDDGeometry.Sphere(radius: 20.0, orientation: .inward)
do {
defaultShader = DDDFragmentShader(from:
"""
precision mediump float;
uniform sampler2D SamplerY;
uniform sampler2D SamplerUV;
uniform sampler2D u_image;
uniform mediump vec3 color;
varying mediump vec2 v_textureCoordinate;
// header modifier here
mediump vec3 pixelAt(mediump vec2 textureCoordinate) {
mediump vec3 yuv;
yuv.x = texture2D(SamplerY, textureCoordinate).r;
yuv.yz = texture2D(SamplerUV, textureCoordinate).rg - vec2(0.5, 0.5);
// Using BT.709 which is the standard for HDTV
return mat3( 1, 1, 1,
0, -.18732, 1.8556,
1.57481, -.46813, 0) * vec3(yuv.xyz);
}
void main() {
gl_FragColor = vec4(pixelAt(v_textureCoordinate), 1.0);
// body modifier here
}
"""
)
let program = try DDDShaderProgram(fragment: defaultShader)
videoNode.material.shaderProgram = program
} catch {
print("could not set shaders: \(error)")
}
scene.add(node: videoNode)
videoNode.position = Vec3(v: (0, 0, -30))
}
private func setupGestureRecognizer() {
let panGesture = UIPanGestureRecognizer(
target: self,
action: #selector(didPan(sender:))
)
panGesture.maximumNumberOfTouches = 1
view.addGestureRecognizer(panGesture)
}
private var hAngle: CGFloat = 0.0
private var vAngle: CGFloat = 0.0
private var lastRecorderVector = CGPoint.zero
@objc private func didPan(sender: UIPanGestureRecognizer) {
if sender.state == .began {
lastRecorderVector = .zero
}
guard let view = sender.view else { return }
let vector = sender.translation(in: view)
hAngle += -CGFloat((vector.x - lastRecorderVector.x) / view.frame.width / 5) * 20
vAngle += CGFloat((vector.y - lastRecorderVector.y) / view.frame.height / 10) * 20
lastRecorderVector = vector
let q = GLKQuaternionInvert(GLKQuaternion(right: hAngle, top: vAngle)).q
videoNode.rotation = Quat(x: q.0, y: q.1, z: q.2, w: q.3)
}
}
| 98c75b47b59e7edffb90002a3603a03d | 28.180556 | 157 | 0.690148 | false | false | false | false |
jasonsturges/SwiftLabs | refs/heads/master | SpriteKitDrawSprite/SpriteKitDrawSprite/GameViewController.swift | mit | 2 | //
// GameViewController.swift
// SpriteKitDrawSprite
//
// Created by Jason Sturges on 11/1/15.
// Copyright (c) 2015 Jason Sturges. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .aspectFill
skView.presentScene(scene)
}
}
override var shouldAutorotate : Bool {
return true
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden : Bool {
return true
}
}
| 821e6bfdab0711f635bb0ac06fdf19ba | 25.433962 | 94 | 0.608851 | false | false | false | false |
mleiv/MEGameTracker | refs/heads/master | MEGameTracker/Views/Common/Data Rows/Notes/Notes Editor/NotesEditorController.swift | mit | 1 | //
// NotesEditorController.swift
// MEGameTracker
//
// Created by Emily Ivie on 3/14/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import UIKit
final public class NotesEditorController: UIViewController {
@IBOutlet weak var textView: UITextView?
@IBOutlet weak var keyboardHeightConstraint: NSLayoutConstraint?
public var note: Note?
public var isPopover: Bool { return popover?.arrowDirection != .unknown }
public weak var popover: UIPopoverPresentationController?
// OriginHintable
@IBOutlet weak var originHintView: TextDataRow?
lazy var originHintType: OriginHintType = { return OriginHintType(controller: self, view: self.originHintView) }()
public var originHint: String?
public var originPrefix: String?
override public func viewDidLoad() {
super.viewDidLoad()
setup()
if !isPopover {
registerForKeyboardNotifications()
}
}
deinit {
if !isPopover {
deregisterForKeyboardNotifications()
}
}
var didSetup = false
func setup() {
textView?.text = note?.text ?? ""
if isPopover {
originHint = nil
}
setupOriginHint()
didSetup = true
startEditing()
}
func startEditing() {
// open keyboard
textView?.becomeFirstResponder()
// go to end of note
textView?.selectedRange = NSMakeRange(textView?.text.length ?? 0, 0)
}
@IBAction func cancel(_ sender: AnyObject) {
textView?.resignFirstResponder()
closeWindow()
}
@IBAction func save(_ sender: AnyObject) {
textView?.resignFirstResponder()
if var note = note {
note.change(text: textView?.text ?? "", isSave: false)
if note.saveAnyChanges() {
closeWindow()
}
}
}
func closeWindow() {
presentingViewController?.dismiss(animated: true, completion: nil)
}
func registerForKeyboardNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(NotesEditorController.keyboardWillBeShown(_:)),
name: UIResponder.keyboardDidShowNotification,
object: nil
)
notificationCenter.addObserver(self,
selector: #selector(NotesEditorController.keyboardWillBeHidden(_:)),
name: UIResponder.keyboardDidHideNotification,
object: nil
)
}
func deregisterForKeyboardNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil)
notificationCenter.removeObserver(self, name: UIResponder.keyboardDidHideNotification, object: nil)
}
@objc func keyboardWillBeShown(_ notification: Notification) {
if let userInfo = (notification as NSNotification).userInfo {
let keyboardSize = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size
keyboardHeightConstraint?.constant = CGFloat(keyboardSize.height)
}
}
@objc func keyboardWillBeHidden(_ notification: Notification) {
keyboardHeightConstraint?.constant = 0
}
}
extension NotesEditorController: OriginHintable {
// var originHint: String? // already declared
public func setupOriginHint() {
originHintType.setupView()
}
}
| ec0d74fb626f31709255015eb49bc13a | 25.534483 | 115 | 0.750487 | false | false | false | false |
WeTransfer/UINotifications | refs/heads/master | Sources/UINotificationPresentationContext.swift | mit | 1 | //
// UINotificationPresentationContext.swift
// Coyote
//
// Created by Antoine van der Lee on 18/05/2017.
// Copyright © 2017 WeTransfer. All rights reserved.
//
import UIKit
/// Provides information about an in-progress notification presentation.
public final class UINotificationPresentationContext {
/// The window in which the `UINotificationView` will be presented.
public let containerWindow: UIWindow
/// The level the container window should be on when presenting the notification
private let windowLevel: UIWindow.Level
/// The `UINotificationView` containing the visual representation of the `UINotification`.
public let notificationView: UINotificationView
/// The notification request currenly being handled.
private let request: UINotificationRequest
/// Public getter for the current notification which is handled.
public var notification: UINotification {
return request.notification
}
internal init(request: UINotificationRequest, containerWindow: UIWindow, windowLevel: UIWindow.Level, notificationView: UINotificationView) {
self.request = request
self.containerWindow = containerWindow
self.notificationView = notificationView
self.windowLevel = windowLevel
prepareContainerWindow()
prepareNotificationView()
}
/// Completes the presentation. Resets the container window and updates the state of the `UINotificationRequest`.
public func completePresentation() {
resetContainerWindow()
notificationView.removeFromSuperview()
request.finish()
// This releases all objects.
// We can't define the presenter weak inside the notificationView, because it's needed for dismissing after a pan gesture.
notificationView.presenter = nil
}
private func prepareContainerWindow() {
containerWindow.windowLevel = windowLevel
#if !TEST
containerWindow.isHidden = false
#endif
}
private func prepareNotificationView() {
/// Create a container view controller to let it handle orientation changes.
let containerViewController = UIViewController(nibName: nil, bundle: nil)
containerViewController.view.addSubview(notificationView)
containerWindow.rootViewController = containerViewController
/// Set the top constraint.
var notificationViewTopConstraint = notificationView.topAnchor.constraint(equalTo: containerViewController.view.topAnchor, constant: -notification.style.height.value)
/// For iPhone X we need to use the safe area layout guide, which is only available in iOS 11 and up.
if #available(iOS 11.0, *) {
notificationViewTopConstraint = notificationView.topAnchor.constraint(equalTo: containerViewController.view.safeAreaLayoutGuide.topAnchor, constant: -notification.style.height.value)
}
notificationView.topConstraint = notificationViewTopConstraint
var constraints = [
notificationView.leadingAnchor.constraint(equalTo: containerViewController.view.leadingAnchor).usingPriority(.almostRequired),
notificationView.trailingAnchor.constraint(equalTo: containerViewController.view.trailingAnchor).usingPriority(.almostRequired),
notificationView.heightAnchor.constraint(equalToConstant: notification.style.height.value),
notificationViewTopConstraint
]
if let maxWidth = notification.style.maxWidth {
constraints.append(contentsOf: [
notificationView.widthAnchor.constraint(lessThanOrEqualToConstant: maxWidth),
notificationView.centerXAnchor.constraint(equalTo: containerViewController.view.centerXAnchor)
])
}
NSLayoutConstraint.activate(constraints)
containerViewController.view.layoutIfNeeded()
}
private func resetContainerWindow() {
/// Move the window behind the key application window.
containerWindow.windowLevel = UIWindow.Level.normal - 1
containerWindow.rootViewController = nil
containerWindow.isHidden = true
}
}
private extension UILayoutPriority {
/// Creates a priority which is almost required, but not 100%.
static var almostRequired: UILayoutPriority {
UILayoutPriority(rawValue: 999)
}
}
| 5fc1c7fb1643f1deb09e3308c40ee5d3 | 40.301887 | 194 | 0.725217 | false | false | false | false |
kildevaeld/FALocationManager | refs/heads/master | Pod/Classes/Queue.swift | mit | 1 | //
// Queue.swift
// Pods
//
// Created by Rasmus Kildevæld on 25/06/15.
//
//
import Foundation
import MapKit
class QueueItem {
let handler : AddressUpdateHandler
var key : String?
var location: CLLocation?
init (key: String, handler: AddressUpdateHandler) {
self.handler = handler
self.key = key
}
init (location:CLLocation, handler: AddressUpdateHandler) {
self.handler = handler
self.location = location
}
func check(key: String) -> Bool {
return self.key != nil && self.key == key
}
func check(location:CLLocation) -> Bool {
return self.location != nil && self.location! == location
}
}
class Queue {
var stack : [QueueItem] = []
func pop(location:CLLocation) -> [AddressUpdateHandler] {
var out : [AddressUpdateHandler] = []
for item in stack {
if item.check(location) {
out.append(item.handler)
}
}
return out
}
func pop(key: String) -> [AddressUpdateHandler] {
var out : [AddressUpdateHandler] = []
for item in stack {
if item.check(key) {
out.append(item.handler)
}
}
return out
}
func pop () -> QueueItem? {
return self.stack.first
}
func push(key:String, handler: AddressUpdateHandler) {
self.stack.append(QueueItem(key: key, handler: handler))
}
func push(location:CLLocation, handler: AddressUpdateHandler) {
self.stack.append(QueueItem(location: location, handler: handler))
}
} | f9365f208c1aa90349ce1ca5cba333c0 | 21.917808 | 74 | 0.559809 | false | false | false | false |
MichelKansou/Vapor-Blog | refs/heads/master | Sources/App/main.swift | mit | 1 | import Foundation
import Fluent
import Vapor
import VaporMySQL
import SwiftyBeaverVapor
import SwiftyBeaver
import Auth
let drop = Droplet()
try drop.addProvider(VaporMySQL.Provider.self)
drop.middleware.append(AuthMiddleware(user: User.self))
drop.preparations.append(User.self)
drop.preparations.append(Post.self)
// Log config with SwiftyBeaver
let console = ConsoleDestination() // log to Xcode Console in color
let file = FileDestination() // log to file in color
file.logFileURL = URL(fileURLWithPath: "/tmp/VaporLogs.log") // set log file
let sbProvider = SwiftyBeaverProvider(destinations: [console, file])
try drop.addProvider(sbProvider)
let log = drop.log.self
let authController = AuthController()
authController.addRoutes(to: drop)
drop.get("/") { req in
let posts = try JSON(node: Post.query().sort("created_at", Sort.Direction.descending).all().makeNode())
return try drop.view.make("home", [
"posts": posts,
"homePage": true
])
}
drop.get("about") { req in
return try drop.view.make("about", [
"aboutPage": true
])
}
drop.get("contact") { req in
return try drop.view.make("contact")
}
let protect = ProtectMiddleware(error: Abort.custom(status: .unauthorized, message: "Unauthorized"))
drop.grouped(CheckUser(), protect).group("admin") { admin in
let userController = UserController()
userController.addRoutes(to: drop)
let postController = PostController()
postController.addRoutes(to: drop)
admin.resource("posts", postController)
admin.resource("users", userController)
admin.get("my-profile") { req in
guard let authUser = try req.user() as? User else {
print("unable to get authenticated user")
}
return try drop.view.make("Admin/User/show", [
"user": authUser
])
}
}
drop.run()
| 2128bb6388375214e479963c293648bb | 24.777778 | 107 | 0.693966 | false | false | false | false |
xivol/MCS-V3-Mobile | refs/heads/master | examples/swift/SwiftBasics.playground/Pages/Optionals.xcplaygroundpage/Contents.swift | mit | 1 | /*:
## Optionals
[Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
****
*/
import Foundation
var helloString: String? = nil
type(of: helloString)
helloString = "Hello, Optional!"
//: ### Optional Initialisation
//: - `nil`
//: - Wrapped value
//:
//: Values can be wrapped into an opional type
var optInt = Int?(4) // Int?(4)
var optInt2: Int? = 4
optInt = nil
if optInt == nil {
"empty"
}
else {
optInt
}
//: Some methods return optionals in case of a failure:
let stringPi = "3.1415926535897932"
let pi = Double(stringPi)
type(of: pi)
//: ### Conditional Unwrapping
let conditionalThree = pi?.rounded()
type(of: conditionalThree)
helloString = nil
let conditionalLowerString = helloString?.lowercased()
type(of: conditionalLowerString)
//: ### Optional Binding
if let boundPi = Double(stringPi) {
type(of: boundPi)
"rounded pi is \(boundPi.rounded())"
}
if let str = helloString {
str.lowercased()
} else {
"empty string"
}
//: Guarded optional
guard let guardedPi = Double(stringPi)
else {
fatalError("pi is nil")
}
type(of: guardedPi)
//: ### Forced Unwrapping
let forcedThree = pi!.rounded()
type(of: forcedThree)
//let forcedLowerString = helloString!.lowercased()
//type(of: forcedLowerString)
//: Forcedly Unwrapped Optional
var forcedPi: Double! = nil
forcedPi = Double(stringPi)
let threeFromForcedPi = forcedPi.rounded()
//: Optional Chaining
helloString = "Hello, Playground"
let chainedIndexOfSubstr = helloString?.range(of: "Hello")?.lowerBound
let chainedBase64 = helloString?.data(using: .utf8)?.base64EncodedString()
//: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
| 13c3f353d134f72ae02184f8ff73037f | 22.388889 | 80 | 0.699525 | false | false | false | false |
mlpqaz/V2ex | refs/heads/master | ZZV2ex/ZZV2ex/Common/Extension/Request+Extension.swift | apache-2.0 | 1 | //
// Request+Extension.swift
// ZZV2ex
//
// Created by ios on 2017/5/3.
// Copyright © 2017年 张璋. All rights reserved.
//
import Foundation
import Alamofire
import Ji
extension DataRequest {
enum ErrorCode: Int {
case noData = 1
case dataSerializationFailed = 2
}
internal static func newError(_ code:ErrorCode,failureReason: String) -> NSError {
let errorDomain = "me.fin.v2ex.error"
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
let returnError = NSError(domain: errorDomain, code: code.rawValue,userInfo: userInfo)
return returnError
}
static func JIHTMLResponseSerializer() -> DataResponseSerializer<Ji> {
return DataResponseSerializer { request, response,data,error in
guard error == nil else { return .failure(error!) }
guard let validData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
if let jiHtml = Ji(htmlData: validData) {
return .success(jiHtml)
}
let failureReason = "ObjectMapper failed to serialize response."
let error = newError(.dataSerializationFailed, failureReason: failureReason)
return .failure(error)
}
}
@discardableResult
public func responseJiHtml(queue: DispatchQueue? = nil, completionHandler:@escaping (DataResponse<Ji>) -> Void) -> Self {
return response(responseSerializer: Alamofire.DataRequest.JIHTMLResponseSerializer(),completionHandler:completionHandler);
}
}
| 087a22b7845442c984460be8b5c79822 | 33.25 | 130 | 0.65146 | false | false | false | false |
ltcarbonell/deckstravaganza | refs/heads/master | Deckstravaganza/Solitaire.swift | mit | 1 | //
// Solitaire.swift
// Deckstravaganza
//
// Created by LT Carbonell on 9/20/15.
// Copyright © 2015 University of Florida. All rights reserved.
//
import UIKit
import SpriteKit
class Solitaire: CardGame {
let selectedOptions: [AdjustableSetting]?
//Properties from protocol of card game
var deck: Deck
var players = [Player]()
var diff: Difficulty
// properties of the game rules that can be changed
var adjustableSettings = [
AdjustableSetting(
settingName: "Card Type",
formType: FormType.cards,
dataType: DataType.image,
options: []
)
];
// Difficulty levels possibly in solitaire
enum Difficulty : Int {
case easy = 1
case hard = 3
}
// Properties of Solitaire
var wastePile: StackPile // where the three cards are placed that you can chose from
// where you have to place A -> King by suit
var foundations:[StackPile]
var foundation1: StackPile
var foundation2: StackPile
var foundation3: StackPile
var foundation4: StackPile
// The piles of cards you can add onto
var tableus: [StackPile]
var tableu1: StackPile
var tableu2: StackPile
var tableu3: StackPile
var tableu4: StackPile
var tableu5: StackPile
var tableu6: StackPile
var tableu7: StackPile
let gameDelegate = SolitaireDelegate()
// initializer
init(selectedOptions: [AdjustableSetting]?) {
self.diff = .easy
self.selectedOptions = selectedOptions
// deals the cards out for the first and only time
// calls from Solitaire delagate
self.deck = Deck(deckFront: Deck.DeckFronts.Deck2, deckBack: Deck.DeckBacks.Default)
self.deck.name = "Deck"
self.wastePile = StackPile()
self.wastePile.name = "WastePile"
// initializes the foundations and adds them to array
self.foundation1 = StackPile()
self.foundation2 = StackPile()
self.foundation3 = StackPile()
self.foundation4 = StackPile()
self.foundations = [self.foundation1, self.foundation2, self.foundation3, self.foundation4]
for foundation in self.foundations {
foundation.name = "Foundation"
}
// initializes the tableu and adds them to array
self.tableu1 = StackPile()
self.tableu2 = StackPile()
self.tableu3 = StackPile()
self.tableu4 = StackPile()
self.tableu5 = StackPile()
self.tableu6 = StackPile()
self.tableu7 = StackPile()
self.tableus = [self.tableu1, self.tableu2, self.tableu3, self.tableu4, self.tableu5, self.tableu6, self.tableu7]
for tableu in self.tableus {
tableu.name = "Tableu"
}
self.setPlayers(1)
//gameDelegate.deal(self)
}
// Methods
/**
* Return the game options.
*/
func getGameOptions() -> [AdjustableSetting] {
return adjustableSettings;
}
// play function is run to play the game
func play() {
gameDelegate.deal(self)
gameDelegate.gameDidStart(self)
while !gameDelegate.isWinner(self) {
gameDelegate.roundDidStart(self)
// take a turn
//turn()
gameDelegate.roundDidEnd(self)
gameDelegate.numberOfRounds += 1
gameDelegate.increaseScore(self)
}
gameDelegate.gameDidEnd(self)
}
func setPlayers(_ numberOfPlayers: Int) {
self.players = [Player(userName: "Player 1", score: 0, playerNumber: 1, isComputer: false)] // only one player... hence Solitaire
}
// Moves the top card of a pile and moves it to the new pile
func moveTopCard(_ fromPile: StackPile, toPile: StackPile) {
toPile.push(fromPile.pull()!)
}
// Moves multiple cards from a pile to a new pile
// uses a temporary pile to help moves them
func moveGroupedCards(_ numberOfCardsToMove: Int, fromPile: StackPile, toPile: StackPile) {
let tempPile = StackPile()
for _ in 0..<numberOfCardsToMove {
tempPile.push(fromPile.pull()!)
}
toPile.addToStackFromFirstCardOf(tempPile)
}
func checkMove(_ card: Card, previousPile: StackPile, newPile: StackPile) -> Bool {
// if coming from wastePile and going to tableu, has to be one less and opposite color as tableu.top or king and empty space
if previousPile.name == wastePile.name && newPile.name == tableus[0].name {
// if the tableu it is going to is empty, it must be a king of any suit
if newPile.isEmpty() {
if card.getRank() == .king {
return true
} else {
return false
}
} else { // if the tableu is not empty, the top card of the tableu must be 1 more than the rank of the moved card and the opposite color
if card.hasOppositeColorThan(newPile.topCard()!) && card.getRank().hashValue == newPile.topCard()!.getRank().hashValue - 1 {
return true
} else {
return false
}
}
}
// if coming from wastePile and going to foundation, has to be one more and same suit
else if previousPile.name == wastePile.name && newPile.name == foundations[0].name {
// checks if foundation is empty, if so it must be an ace that goes to the foundation
if newPile.isEmpty() {
if card.getRank() == .ace {
return true
} else {
return false
}
} else { // if it is not empty is has to be the same suit and one less than the new card
if card.hasSameSuitAs(newPile.topCard()!) && card.getRank().hashValue == newPile.topCard()!.getRank().hashValue + 1 {
return true
} else {
return false
}
}
}
// if coming from tableu to foundation, has to be one more and same suit
else if previousPile.name == tableus[0].name && newPile.name == foundations[0].name {
// checks if foundation is empty, if so it must be an ace that goes to the foundation
if newPile.isEmpty() {
if card.getRank() == .ace {
return true
} else {
return false
}
} else { // if it is not empty is has to be the same suit and one less than the new card
if card.hasSameSuitAs(newPile.topCard()!) && card.getRank().hashValue == newPile.topCard()!.getRank().hashValue + 1 {
return true
} else {
return false
}
}
}
// if coming from foundation to tableu has to be one less and opposite color
else if foundations[0].name == previousPile.name && tableus[0].name == newPile.name {
// if the tableu it is going to is empty, it must be a king of any suit
if newPile.isEmpty() {
if card.getRank() == .king {
return true
} else {
return false
}
} else { // if the tableu is not empty, the top card of the tableu must be 1 more than the rank of the moved card and the opposite color
if card.hasOppositeColorThan(newPile.topCard()!) && card.getRank().hashValue == newPile.topCard()!.getRank().hashValue - 1 {
return true
} else {
return false
}
}
}
// if coming from tableu to different tableu, has to be one less and opposite color as tableu.top or king and empty space
else if tableus[0].name == previousPile.name && tableus[0].name == newPile.name {
// HAVE TO BE ABLE TO MOVE MULTIPLE CARDS AT ONE TIME
if newPile.isEmpty() {
if card.getRank() == .king {
return true
} else {
return false
}
}
else {
if card.hasOppositeColorThan(newPile.topCard()!) && card.getRank().hashValue == newPile.topCard()!.getRank().hashValue - 1 {
return true
} else {
return false
}
}
}
else {
return false
}
}
// helpful methods to check the number of cards in each pile
func printPileNumbers() {
print("Deck: \(self.deck.numberOfCards())")
print("Waste: \(self.wastePile.numberOfCards())")
var Count = 0
for tableu in self.tableus {
print("Tableu\(Count): \(tableu.numberOfCards())")
Count += 1
}
var count = 0
for foundation in self.foundations {
print("Foundation\(count): \(foundation.numberOfCards())")
count += 1
}
}
}
class SolitaireDelegate: CardGameDelegate {
var numberOfRounds = 0
typealias cardGameType = Solitaire
func deal(_ Game: Solitaire) {
var newCard: Card
// calls a brand new, newly shuffled deck
Game.deck.newDeck()
// creates empty stacks for all three piles
Game.wastePile.removeAllCards()
for foundation in Game.foundations {
foundation.removeAllCards()
}
for tableu in Game.tableus {
tableu.removeAllCards()
}
// places the cards into the tableus 1->7
for i in 0 ..< 7 {
for _ in 0 ..< i+1 {
newCard = Game.deck.pull()!
Game.tableus[i].push(newCard)
}
}
}
// these are used to keep track of the status of the game
func gameDidStart(_ Game: Solitaire) {
numberOfRounds = 0
}
func gameDidEnd(_ Game: Solitaire) {
}
func isWinner(_ Game: Solitaire) -> Bool {
// if Game.foundations[0].numberOfCards() == 13 && Game.foundations[1].numberOfCards() == 13 && Game.foundations[2].numberOfCards() == 13 && Game.foundations[3].numberOfCards() == 13 {
// return true
// } else {
// return false
// }
if numberOfRounds > 10 {
return true
} else {
return false
}
}
// used to keep track of the rounds which are when all players take their turn
func roundDidStart(_ Game: Solitaire) {
}
//
func roundDidEnd(_ Game: Solitaire) {
}
// keeps score for the player
func increaseScore(_ Game: Solitaire) {
Game.players[0].score += 1
}
}
| 6ed38fd21b6324a53b6786b82006b513 | 34.079365 | 200 | 0.551584 | false | false | false | false |
Eccelor/material-components-ios | refs/heads/stable | catalog/MDCCatalog/MDCCatalogComponentsController.swift | apache-2.0 | 1 | /*
Copyright 2015-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import CatalogByConvention
import MaterialComponents.MaterialFlexibleHeader
import MaterialComponents.MaterialIcons_ic_arrow_back
import MaterialComponents.MaterialInk
import MaterialComponents.MaterialShadowLayer
import MaterialComponents.MaterialTypography
import UIKit
class MDCCatalogComponentsController: UICollectionViewController, MDCInkTouchControllerDelegate {
let spacing = CGFloat(1)
let inset = CGFloat(16)
let node: CBCNode
var headerViewController: MDCFlexibleHeaderViewController
let imageNames = NSMutableArray()
private lazy var inkController: MDCInkTouchController = {
let controller = MDCInkTouchController(view: self.collectionView!)
controller.delaysInkSpread = true
controller.delegate = self
return controller
}()
init(collectionViewLayout ignoredLayout: UICollectionViewLayout, node: CBCNode) {
self.node = node
let layout = UICollectionViewFlowLayout()
let sectionInset: CGFloat = spacing
layout.sectionInset = UIEdgeInsets(top: sectionInset,
left: sectionInset,
bottom: sectionInset,
right: sectionInset)
layout.minimumInteritemSpacing = spacing
layout.minimumLineSpacing = spacing
self.headerViewController = MDCFlexibleHeaderViewController()
super.init(collectionViewLayout: layout)
self.title = "Material Design Components"
self.addChildViewController(self.headerViewController)
self.headerViewController.headerView.maximumHeight = 128
self.headerViewController.headerView.minimumHeight = 72
self.collectionView?.register(MDCCatalogCollectionViewCell.self,
forCellWithReuseIdentifier: "MDCCatalogCollectionViewCell")
self.collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1)
MDCIcons.ic_arrow_backUseNewStyle(true)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.colorThemeChanged),
name: NSNotification.Name(rawValue: "ColorThemeChangeNotification"),
object: nil)
}
func colorThemeChanged(notification: NSNotification) {
let colorScheme = notification.userInfo?["colorScheme"]
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.colorScheme = colorScheme as? (MDCColorScheme & NSObjectProtocol)!
collectionView?.collectionViewLayout.invalidateLayout()
collectionView?.reloadData()
}
convenience init(node: CBCNode) {
self.init(collectionViewLayout: UICollectionViewLayout(), node: node)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
inkController.addInkView()
let containerView = UIView(frame: self.headerViewController.headerView.bounds)
containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let titleLabel = UILabel()
titleLabel.text = self.title!.uppercased()
titleLabel.textColor = UIColor(white: 1, alpha: 1)
titleLabel.font = UIFont(name: "RobotoMono-Regular", size: 14)
titleLabel.sizeToFit()
if inset + titleLabel.frame.size.width > containerView.frame.size.width {
titleLabel.font = MDCTypography.body2Font()
}
let titleInsets = UIEdgeInsets(top: 0, left: inset, bottom: inset, right: inset)
let titleSize = titleLabel.sizeThatFits(containerView.bounds.size)
titleLabel.frame = CGRect(
x: titleInsets.left,
y: containerView.bounds.size.height - titleSize.height - titleInsets.bottom,
width: containerView.bounds.size.width,
height: titleSize.height)
titleLabel.autoresizingMask = [.flexibleTopMargin, .flexibleWidth]
titleLabel.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(titleLabel)
constrainLabel(label: titleLabel,
containerView: containerView,
insets: titleInsets,
height: titleSize.height)
self.headerViewController.headerView.addSubview(containerView)
self.headerViewController.headerView.forwardTouchEvents(for: containerView)
self.headerViewController.headerView.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
self.headerViewController.headerView.trackingScrollView = self.collectionView
self.headerViewController.headerView.setShadowLayer(MDCShadowLayer()) { (layer, intensity) in
let shadowLayer = layer as? MDCShadowLayer
shadowLayer!.elevation = intensity * MDCShadowElevationAppBar
}
self.view.addSubview(self.headerViewController.view)
self.headerViewController.didMove(toParentViewController: self)
self.collectionView?.accessibilityIdentifier = "collectionView"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.collectionView?.collectionViewLayout.invalidateLayout()
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func willAnimateRotation(
to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
self.collectionView?.collectionViewLayout.invalidateLayout()
}
override var childViewControllerForStatusBarStyle: UIViewController? {
return self.headerViewController
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return node.children.count
}
func inkViewForView(_ view: UIView) -> MDCInkView {
let foundInkView = MDCInkTouchController.injectedInkView(for: view)
foundInkView.inkStyle = .unbounded
foundInkView.inkColor = UIColor(white:0.957, alpha: 0.2)
return foundInkView
}
// MARK: MDCInkTouchControllerDelegate
func inkTouchController(_ inkTouchController: MDCInkTouchController,
shouldProcessInkTouchesAtTouchLocation location: CGPoint) -> Bool {
return self.collectionView!.indexPathForItem(at: location) != nil
}
func inkTouchController(_ inkTouchController: MDCInkTouchController,
inkViewAtTouchLocation location: CGPoint) -> MDCInkView? {
if let indexPath = self.collectionView!.indexPathForItem(at: location) {
let cell = self.collectionView!.cellForItem(at: indexPath)
return self.inkViewForView(cell!)
}
return MDCInkView()
}
// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell =
collectionView.dequeueReusableCell(withReuseIdentifier: "MDCCatalogCollectionViewCell",
for: indexPath)
cell.backgroundColor = UIColor.white
let componentName = self.node.children[indexPath.row].title
if let catalogCell = cell as? MDCCatalogCollectionViewCell {
catalogCell.populateView(componentName)
}
// Ensure that ink animations aren't recycled.
MDCInkTouchController.injectedInkView(for: view).cancelAllAnimations(animated: false)
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let pad = CGFloat(1)
var cellWidth = (self.view.frame.size.width - 3 * pad) / 2
if self.view.frame.size.width > self.view.frame.size.height {
cellWidth = (self.view.frame.size.width - 4 * pad) / 3
}
return CGSize(width: cellWidth, height: cellWidth * 0.825)
}
override func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
let node = self.node.children[indexPath.row]
var vc: UIViewController
if node.isExample() {
vc = node.createExampleViewController()
} else {
vc = MDCNodeListViewController(node: node)
}
self.navigationController?.pushViewController(vc, animated: true)
}
// MARK: Private
func constrainLabel(label: UILabel,
containerView: UIView,
insets: UIEdgeInsets,
height: CGFloat) {
_ = NSLayoutConstraint(
item: label,
attribute: .leading,
relatedBy: .equal,
toItem: containerView,
attribute: .leading,
multiplier: 1.0,
constant: insets.left).isActive = true
_ = NSLayoutConstraint(
item: label,
attribute: .trailing,
relatedBy: .equal,
toItem: containerView,
attribute: .trailing,
multiplier: 1.0,
constant: 0).isActive = true
_ = NSLayoutConstraint(
item: label,
attribute: .bottom,
relatedBy: .equal,
toItem: containerView,
attribute: .bottom,
multiplier: 1.0,
constant: -insets.bottom).isActive = true
_ = NSLayoutConstraint(
item: label,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: height).isActive = true
}
}
// UIScrollViewDelegate
extension MDCCatalogComponentsController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == self.headerViewController.headerView.trackingScrollView {
self.headerViewController.headerView.trackingScrollDidScroll()
}
}
override func scrollViewDidEndDragging(
_ scrollView: UIScrollView,
willDecelerate decelerate: Bool) {
let headerView = self.headerViewController.headerView
if scrollView == headerView.trackingScrollView {
headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate)
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == self.headerViewController.headerView.trackingScrollView {
self.headerViewController.headerView.trackingScrollDidEndDecelerating()
}
}
override func scrollViewWillEndDragging(
_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let headerView = self.headerViewController.headerView
if scrollView == headerView.trackingScrollView {
headerView.trackingScrollWillEndDragging(
withVelocity: velocity,
targetContentOffset: targetContentOffset)
}
}
}
| 03a6a2ba43460c67d6ad43e90c6b8a4d | 34.335443 | 97 | 0.719685 | false | false | false | false |
Tarovk/Mundus_Client | refs/heads/master | Mundus_ios/TokenVC.swift | mit | 1 | //
// TokenVC.swift
// Mundus_ios
//
// Created by Team Aldo on 03/01/2017.
// Copyright (c) 2017 Team Aldo. All rights reserved.
//
import UIKit
import SwiftSpinner
import Aldo
/// ViewController for the screen requesting an authorization token.
class TokenVC: UIViewController, Callback {
let hostAddress: String = "https://expeditionmundus.herokuapp.com"
func onResponse(request: String, responseCode: Int, response: NSDictionary) {
if responseCode == 200 {
SwiftSpinner.setTitleFont(nil)
SwiftSpinner.sharedInstance.innerColor = UIColor.green.withAlphaComponent(0.5)
SwiftSpinner.show(duration: 2.0, title: "Connected", animated: false)
self.performSegue(withIdentifier: "startMainMenu", sender: nil)
return
}
SwiftSpinner.sharedInstance.outerColor = UIColor.red.withAlphaComponent(0.5)
SwiftSpinner.show("Failed to connect, tap to retry", animated: false)
.addTapHandler({
self.retrieveToken()
}, subtitle: "Do you have internet connection?")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Aldo.setHostAddress(address: hostAddress)
self.retrieveToken()
}
/// Sends a request to retrieve a token if not available,
/// otherwise starts the view corresponding to the role of the player.
func retrieveToken() {
if Aldo.hasAuthToken() {
var identifier = "startMainMenu"
if let player = Aldo.getPlayer() {
identifier = "continueJoinSession"
if player.isAdmin() {
identifier = "continueAdminSession"
}
}
self.performSegue(withIdentifier: identifier, sender: nil)
return
}
SwiftSpinner.sharedInstance.outerColor = nil
SwiftSpinner.show(delay: 0.0, title: "Setting up", animated: true)
Aldo.requestAuthToken(callback: self)
}
}
| d44d5474b9b0e0625c6c77873b65750a | 33.965517 | 90 | 0.635602 | false | false | false | false |
superk589/CGSSGuide | refs/heads/master | DereGuide/Card/Controller/CardFilterSortController.swift | mit | 2 | //
// CardFilterSortController.swift
// DereGuide
//
// Created by zzk on 2017/1/5.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
protocol CardFilterSortControllerDelegate: class {
func doneAndReturn(filter: CGSSCardFilter, sorter: CGSSSorter)
}
class CardFilterSortController: BaseFilterSortController {
weak var delegate: CardFilterSortControllerDelegate?
var filter: CGSSCardFilter!
var sorter: CGSSSorter!
var rarityTitles = ["N", "N+", "R", "R+", "SR", "SR+", "SSR", "SSR+"]
var cardTypeTitles = ["Cute", "Cool", "Passion"]
var attributeTitles = ["Vocal", "Dance", "Visual"]
var skillTypeTitles = [
CGSSSkillTypes.comboBonus.description,
CGSSSkillTypes.perfectBonus.description,
CGSSSkillTypes.overload.description,
CGSSSkillTypes.perfectLock.description,
CGSSSkillTypes.comboContinue.description,
CGSSSkillTypes.heal.description,
CGSSSkillTypes.guard.description,
CGSSSkillTypes.concentration.description,
CGSSSkillTypes.boost.description,
CGSSSkillTypes.allRound.description,
CGSSSkillTypes.deep.description,
CGSSSkillTypes.encore.description,
CGSSSkillTypes.lifeSparkle.description,
CGSSSkillTypes.synergy.description,
CGSSSkillTypes.coordination.description,
CGSSSkillTypes.longAct.description,
CGSSSkillTypes.flickAct.description,
CGSSSkillTypes.tuning.description,
CGSSSkillTypes.unknown.description,
CGSSSkillTypes.none.description
]
var procTitles = [CGSSProcTypes.high.description,
CGSSProcTypes.middle.description,
CGSSProcTypes.low.description,
CGSSProcTypes.none.description]
var conditionTitles = [CGSSConditionTypes.c4.description,
CGSSConditionTypes.c6.description,
CGSSConditionTypes.c7.description,
CGSSConditionTypes.c9.description,
CGSSConditionTypes.c11.description,
CGSSConditionTypes.c13.description,
CGSSConditionTypes.other.description]
var availableTitles = [CGSSAvailableTypes.fes.description,
CGSSAvailableTypes.limit.description,
CGSSAvailableTypes.normal.description,
CGSSAvailableTypes.event.description,
CGSSAvailableTypes.free.description]
var favoriteTitles = [NSLocalizedString("已收藏", comment: ""),
NSLocalizedString("未收藏", comment: "")]
var sorterTitles = ["Total", "Vocal", "Dance", "Visual", NSLocalizedString("更新时间", comment: ""), NSLocalizedString("稀有度", comment: ""), NSLocalizedString("相册编号", comment: "")]
var sorterMethods = ["overall", "vocal", "dance", "visual", "update_id", "sRarity", "sAlbumId"]
var sorterOrderTitles = [NSLocalizedString("降序", comment: ""), NSLocalizedString("升序", comment: "")]
func reloadData() {
self.tableView.reloadData()
}
override func doneAction() {
delegate?.doneAndReturn(filter: filter, sorter: sorter)
drawerController?.hide(animated: true)
// 使用自定义动画效果
/*let transition = CATransition()
transition.duration = 0.3
transition.type = kCATransitionReveal
navigationController?.view.layer.addAnimation(transition, forKey: kCATransition)
navigationController?.popViewControllerAnimated(false)*/
}
override func resetAction() {
if delegate is CardTableViewController {
filter = CGSSSorterFilterManager.DefaultFilter.card
sorter = CGSSSorterFilterManager.DefaultSorter.card
} else if delegate is UnitCardSelectTableViewController {
filter = CGSSSorterFilterManager.DefaultFilter.unitCard
sorter = CGSSSorterFilterManager.DefaultSorter.unitCard
} else {
filter = CGSSSorterFilterManager.DefaultFilter.gacha
sorter = CGSSSorterFilterManager.DefaultSorter.gacha
}
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - TableViewDelegate & DataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
return 8
} else {
return 2
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "FilterCell", for: indexPath) as! FilterTableViewCell
switch indexPath.row {
case 0:
cell.setup(titles: rarityTitles, index: filter.rarityTypes.rawValue, all: CGSSRarityTypes.all.rawValue)
case 1:
cell.setup(titles: cardTypeTitles, index: filter.cardTypes.rawValue, all: CGSSCardTypes.all.rawValue)
case 2:
cell.setup(titles: attributeTitles, index: filter.attributeTypes.rawValue, all: CGSSAttributeTypes.all.rawValue)
case 3:
cell.setup(titles: skillTypeTitles, index: filter.skillTypes.rawValue, all: CGSSSkillTypes.all.rawValue)
case 4:
cell.setup(titles: procTitles, index: filter.procTypes.rawValue, all: CGSSProcTypes.all.rawValue)
case 5:
cell.setup(titles: conditionTitles, index: filter.conditionTypes.rawValue, all: CGSSConditionTypes.all.rawValue)
case 6:
cell.setup(titles: availableTitles, index: filter.gachaTypes.rawValue, all: CGSSAvailableTypes.all.rawValue)
case 7:
cell.setup(titles: favoriteTitles, index: filter.favoriteTypes.rawValue, all: CGSSFavoriteTypes.all.rawValue)
default:
break
}
cell.delegate = self
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "SortCell", for: indexPath) as! SortTableViewCell
switch indexPath.row {
case 0:
cell.setup(titles: sorterOrderTitles)
cell.presetIndex(index: sorter.ascending ? 1 : 0)
case 1:
cell.setup(titles: sorterTitles)
if let index = sorterMethods.firstIndex(of: sorter.property) {
cell.presetIndex(index: UInt(index))
}
default:
break
}
cell.delegate = self
return cell
}
}
}
extension CardFilterSortController: FilterTableViewCellDelegate {
func filterTableViewCell(_ cell: FilterTableViewCell, didSelect index: Int) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.rarityTypes.insert(CGSSRarityTypes.init(rarity: index))
case 1:
filter.cardTypes.insert(CGSSCardTypes.init(type: index))
case 2:
filter.attributeTypes.insert(CGSSAttributeTypes.init(type: index))
case 3:
filter.skillTypes.insert(CGSSSkillTypes.init(rawValue: 1 << UInt(index)))
case 4:
filter.procTypes.insert(CGSSProcTypes.init(rawValue: 1 << UInt(index)))
case 5:
filter.conditionTypes.insert(CGSSConditionTypes.init(rawValue: 1 << UInt(index)))
case 6:
filter.gachaTypes.insert(CGSSAvailableTypes.init(rawValue: 1 << UInt(index)))
case 7:
filter.favoriteTypes.insert(CGSSFavoriteTypes.init(rawValue: 1 << UInt(index)))
default:
break
}
}
}
}
func filterTableViewCell(_ cell: FilterTableViewCell, didDeselect index: Int) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.rarityTypes.remove(CGSSRarityTypes.init(rarity: index))
case 1:
filter.cardTypes.remove(CGSSCardTypes.init(type: index))
case 2:
filter.attributeTypes.remove(CGSSAttributeTypes.init(type: index))
case 3:
filter.skillTypes.remove(CGSSSkillTypes.init(rawValue: 1 << UInt(index)))
case 4:
filter.procTypes.remove(CGSSProcTypes.init(rawValue: 1 << UInt(index)))
case 5:
filter.conditionTypes.remove(CGSSConditionTypes.init(rawValue: 1 << UInt(index)))
case 6:
filter.gachaTypes.remove(CGSSAvailableTypes.init(rawValue: 1 << UInt(index)))
case 7:
filter.favoriteTypes.remove(CGSSFavoriteTypes.init(rawValue: 1 << UInt(index)))
default:
break
}
}
}
}
func didSelectAll(filterTableViewCell cell: FilterTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.rarityTypes = CGSSRarityTypes.all
case 1:
filter.cardTypes = CGSSCardTypes.all
case 2:
filter.attributeTypes = CGSSAttributeTypes.all
case 3:
filter.skillTypes = CGSSSkillTypes.all
case 4:
filter.procTypes = CGSSProcTypes.all
case 5:
filter.conditionTypes = CGSSConditionTypes.all
case 6:
filter.gachaTypes = .all
case 7:
filter.favoriteTypes = CGSSFavoriteTypes.all
default:
break
}
}
}
}
func didDeselectAll(filterTableViewCell cell: FilterTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.rarityTypes = CGSSRarityTypes.init(rawValue: 0)
case 1:
filter.cardTypes = CGSSCardTypes.init(rawValue: 0)
case 2:
filter.attributeTypes = CGSSAttributeTypes.init(rawValue: 0)
case 3:
filter.skillTypes = CGSSSkillTypes.init(rawValue: 0)
case 4:
filter.procTypes = CGSSProcTypes.init(rawValue: 0)
case 5:
filter.conditionTypes = CGSSConditionTypes.init(rawValue: 0)
case 6:
filter.gachaTypes = CGSSAvailableTypes.init(rawValue: 0)
case 7:
filter.favoriteTypes = CGSSFavoriteTypes.init(rawValue: 0)
default:
break
}
}
}
}
}
extension CardFilterSortController: SortTableViewCellDelegate {
func sortTableViewCell(_ cell: SortTableViewCell, didSelect index: Int) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 1 {
switch indexPath.row {
case 0:
sorter.ascending = (index == 1)
case 1:
sorter.property = sorterMethods[index]
default:
break
}
}
}
}
}
| a430ee67964d15e6d1cbb922f188f7c5 | 40.219595 | 179 | 0.575691 | false | false | false | false |
simorgh3196/GitHubSearchApp | refs/heads/master | Carthage/Checkouts/APIKit/Tests/APIKit/TestComponents/TestRequest.swift | mit | 1 | import Foundation
import APIKit
struct TestRequest: RequestType {
var absoluteURL: NSURL? {
let URLRequest = try? buildURLRequest()
return URLRequest?.URL
}
// MARK: RequestType
typealias Response = AnyObject
init(baseURL: String = "https://example.com", path: String = "/", method: HTTPMethod = .GET, parameters: AnyObject? = [:], headerFields: [String: String] = [:], interceptURLRequest: NSMutableURLRequest throws -> NSMutableURLRequest = { $0 }) {
self.baseURL = NSURL(string: baseURL)!
self.path = path
self.method = method
self.parameters = parameters
self.headerFields = headerFields
self.interceptURLRequest = interceptURLRequest
}
let baseURL: NSURL
let method: HTTPMethod
let path: String
let parameters: AnyObject?
let headerFields: [String: String]
let interceptURLRequest: NSMutableURLRequest throws -> NSMutableURLRequest
func interceptURLRequest(URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest {
return try interceptURLRequest(URLRequest)
}
func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Response {
return object
}
}
| ecd64cec4d5abe46f57e3b4084bd5593 | 33.333333 | 247 | 0.690129 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox | refs/heads/master | nRF Toolbox/Profiles/UART/Model/Icons/CommandImage.swift | bsd-3-clause | 1 | /*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit.UIImage
struct CommandImage: Codable, Equatable {
static func == (lhs: CommandImage, rhs: CommandImage) -> Bool {
lhs.name == rhs.name && lhs.systemIcon == rhs.systemIcon
}
var name: String
var image: UIImage? {
if #available(iOS 13, *), let image = systemIcon?.image {
return image
} else {
return UIImage(named: name)?.withRenderingMode(.alwaysTemplate)
}
}
var systemIcon: ModernIcon?
init(name: String, modernIcon: ModernIcon? = nil) {
self.name = name
self.systemIcon = modernIcon
}
}
extension CommandImage: ExpressibleByStringLiteral {
init(stringLiteral value: String) {
name = value
systemIcon = nil
}
}
extension CommandImage: CaseIterable {
static let allCases: [CommandImage] = [.pause, .play, .record, .repeat, .rewind, .start, .stop, .number1, .number2, .number3, .number4, .number5, .number6, .number7, .number8, .number9, .up, .down, .left, .right]
}
extension CommandImage {
static let empty = CommandImage(name: "")
static let number1 = CommandImage(name: "NUMBER_1", modernIcon: ModernIcon(digit: 1)(.circle))
static let number2 = CommandImage(name: "NUMBER_2", modernIcon: ModernIcon(digit: 2)(.circle))
static let number3 = CommandImage(name: "NUMBER_3", modernIcon: ModernIcon(digit: 3)(.circle))
static let number4 = CommandImage(name: "NUMBER_4", modernIcon: ModernIcon(digit: 4)(.circle))
static let number5 = CommandImage(name: "NUMBER_5", modernIcon: ModernIcon(digit: 5)(.circle))
static let number6 = CommandImage(name: "NUMBER_6", modernIcon: ModernIcon(digit: 6)(.circle))
static let number7 = CommandImage(name: "NUMBER_7", modernIcon: ModernIcon(digit: 7)(.circle))
static let number8 = CommandImage(name: "NUMBER_8", modernIcon: ModernIcon(digit: 8)(.circle))
static let number9 = CommandImage(name: "NUMBER_9", modernIcon: ModernIcon(digit: 9)(.circle))
static let number0 = CommandImage(name: "NUMBER_0", modernIcon: ModernIcon(digit: 0)(.circle))
static let pause = CommandImage(name: "PAUSE", modernIcon: .pause)
static let play = CommandImage(name: "PLAY", modernIcon: .play)
static let record = CommandImage(name: "RECORD", modernIcon: .record)
static let `repeat` = CommandImage(name: "REPEAT", modernIcon: .repeat)
static let rewind = CommandImage(name: "REW", modernIcon: .backward)
static let start = CommandImage(name: "START", modernIcon: ModernIcon.backward(.end))
static let stop = CommandImage(name: "STOP", modernIcon: .stop)
static let up = CommandImage(name: "UP", modernIcon: ModernIcon.chevron(.up)(.circle))
static let down = CommandImage(name: "DOWN", modernIcon: ModernIcon.chevron(.down)(.circle))
static let left = CommandImage(name: "LEFT", modernIcon: ModernIcon.chevron(.left)(.circle))
static let right = CommandImage(name: "RIGHT", modernIcon: ModernIcon.chevron(.right)(.circle))
}
| 1f1fe4fd1cec9faf5ce8cdd5202a2848 | 48.172043 | 216 | 0.714192 | false | false | false | false |
sahandnayebaziz/Dana-Hills | refs/heads/master | Dana Hills/GradesViewController.swift | mit | 1 | //
// GradesViewController.swift
// Dana Hills
//
// Created by Nayebaziz, Sahand on 9/21/16.
// Copyright © 2016 Nayebaziz, Sahand. All rights reserved.
//
import UIKit
class GradesViewController: UIViewController, KeyboardAppearanceDelegate {
let stackView = UIStackView()
let imageView = UIImageView(image: #imageLiteral(resourceName: "School Loop"))
let usernameTextField = UITextField()
let passwordTextField = UITextField()
let rememberSwitch = UISwitch()
let signInButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
listenForKeyboardAppearance()
title = "Grades"
stackView.axis = .vertical
stackView.alignment = .center
stackView.distribution = .fill
view.addSubview(stackView)
stackView.snp.makeConstraints { make in
make.top.equalTo(topLayoutGuide.snp.bottom).offset(10)
make.bottom.equalTo(bottomLayoutGuide.snp.top).offset(-100)
make.width.equalTo(view)
make.centerX.equalTo(view)
}
imageView.snp.makeConstraints { make in
make.size.equalTo(70)
}
stackView.addArrangedSubview(imageView)
let containingView = UIView()
stackView.addArrangedSubview(containingView)
containingView.snp.makeConstraints { make in
make.width.equalTo(stackView)
make.height.greaterThanOrEqualTo((55 * 3) + 10 + 10)
}
let innerStackView = UIStackView()
containingView.addSubview(innerStackView)
innerStackView.axis = .vertical
innerStackView.distribution = .fillEqually
innerStackView.alignment = .fill
innerStackView.spacing = 10
innerStackView.snp.makeConstraints { make in
make.height.equalTo((55 * 3) + 10 + 10)
make.width.equalTo(containingView)
make.center.equalTo(containingView)
}
for textfield in [usernameTextField, passwordTextField] {
innerStackView.addArrangedSubview(textfield)
textfield.snp.makeConstraints { make in
make.height.equalTo(55)
make.width.equalTo(innerStackView)
}
textfield.autocorrectionType = .no
textfield.autocapitalizationType = .none
textfield.backgroundColor = Colors.lightGray
textfield.textAlignment = .center
textfield.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.regular)
}
usernameTextField.placeholder = "Username"
passwordTextField.placeholder = "Password"
passwordTextField.isSecureTextEntry = true
let rememberView = UIView()
innerStackView.addArrangedSubview(rememberView)
rememberView.snp.makeConstraints { make in
make.height.equalTo(55)
make.width.equalTo(innerStackView)
}
let rememberLabel = UILabel()
rememberLabel.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.regular)
rememberLabel.textColor = UIColor.gray
rememberLabel.text = "Remember login info"
rememberView.addSubview(rememberLabel)
rememberLabel.snp.makeConstraints { make in
make.left.equalTo(30)
make.centerY.equalTo(rememberView)
make.width.equalTo(rememberView)
}
rememberView.addSubview(rememberSwitch)
rememberSwitch.snp.makeConstraints { make in
make.centerY.equalTo(rememberView)
make.right.equalTo(rememberView).offset(-30)
}
rememberSwitch.addTarget(self, action: #selector(tapped(rememberSwitch:)), for: .valueChanged)
let buttonView = UIView()
stackView.addArrangedSubview(buttonView)
buttonView.snp.makeConstraints { make in
make.width.equalTo(stackView)
make.height.greaterThanOrEqualTo(50)
}
buttonView.addSubview(signInButton)
signInButton.snp.makeConstraints { make in
make.width.equalTo(150)
make.height.equalTo(50)
make.center.equalTo(buttonView)
}
signInButton.setTitle("Sign in", for: .normal)
signInButton.backgroundColor = Colors.blue
signInButton.layer.cornerRadius = 10
signInButton.addTarget(self, action: #selector(tappedSignIn), for: .touchUpInside)
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedView)))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let savedLogin = DanaHillsBack.getSavedCredentials() {
usernameTextField.text = savedLogin.username
passwordTextField.text = savedLogin.password
rememberSwitch.isOn = true
} else {
usernameTextField.text = ""
passwordTextField.text = ""
rememberSwitch.isOn = false
}
}
@objc func tappedView() {
view.endEditing(false)
}
@objc func tappedSignIn() {
guard usernameTextField.text! != "" && passwordTextField.text! != "" else {
displayAlert(forError: .MissingFields)
return
}
if rememberSwitch.isOn {
DanaHillsBack.save(username: usernameTextField.text!, password: passwordTextField.text!)
}
let login = SchoolLoopLogin(username: usernameTextField.text!, password: passwordTextField.text!)
let vc = SchoolLoopViewController(withLogin: login)
let nav = UINavigationController(rootViewController: vc)
nav.modalPresentationStyle = .overFullScreen
present(nav, animated: true, completion: nil)
}
@objc func tapped(rememberSwitch: UISwitch) {
if !rememberSwitch.isOn {
DanaHillsBack.deleteSavedCredentials()
}
}
func keyboardWillShow(toEndHeight height: CGFloat) {
imageView.isHidden = true
stackView.snp.updateConstraints { make in
make.bottom.equalTo(bottomLayoutGuide.snp.top).offset(-1 * height)
}
view.layoutIfNeeded()
}
func keyboardWillHide(toEndHeight height: CGFloat) {
imageView.isHidden = false
stackView.snp.updateConstraints { make in
make.bottom.equalTo(bottomLayoutGuide.snp.top).offset(-100)
}
view.layoutIfNeeded()
}
}
| ccb463ea93288790db05c0a1da779016 | 35.670391 | 105 | 0.631627 | false | false | false | false |
GianniCarlo/Audiobook-Player | refs/heads/BKPLY-52-player-redesign | BookPlayer/Library/RootViewController.swift | gpl-3.0 | 1 | //
// RootViewController.swift
// BookPlayer
//
// Created by Gianni Carlo on 5/12/18.
// Copyright © 2018 Tortuga Power. All rights reserved.
//
import BookPlayerKit
import Themeable
import UIKit
class RootViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet private weak var miniPlayerContainer: UIView!
private weak var miniPlayerViewController: MiniPlayerViewController?
private weak var libraryViewController: LibraryViewController!
private var pan: UIPanGestureRecognizer!
var miniPlayerIsHidden: Bool {
return self.miniPlayerContainer.isHidden
}
private var themedStatusBarStyle: UIStatusBarStyle?
override var preferredStatusBarStyle: UIStatusBarStyle {
return themedStatusBarStyle ?? super.preferredStatusBarStyle
}
// MARK: - Lifecycle
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController = segue.destination as? MiniPlayerViewController {
self.miniPlayerViewController = viewController
self.miniPlayerViewController!.showPlayer = {
guard let currentBook = PlayerManager.shared.currentBook else {
return
}
self.libraryViewController.setupPlayer(book: currentBook)
}
} else if
let navigationVC = segue.destination as? UINavigationController,
let libraryVC = navigationVC.children.first as? LibraryViewController {
self.libraryViewController = libraryVC
}
}
override func viewDidLoad() {
super.viewDidLoad()
setUpTheming()
self.miniPlayerContainer.isHidden = true
self.miniPlayerContainer.layer.shadowOffset = CGSize(width: 0.0, height: 3.0)
self.miniPlayerContainer.layer.shadowOpacity = 0.18
self.miniPlayerContainer.layer.shadowRadius = 9.0
self.miniPlayerContainer.clipsToBounds = false
NotificationCenter.default.addObserver(self, selector: #selector(self.bookChange(_:)), name: .bookChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.bookReady(_:)), name: .bookReady, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.dismissMiniPlayer), name: .playerPresented, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.presentMiniPlayer), name: .playerDismissed, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.onBookPlay), name: .bookPlayed, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.onBookPause), name: .bookPaused, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.onBookPause), name: .bookEnd, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.onBookDelete(_:)), name: .bookDelete, object: nil)
// Gestures
self.pan = UIPanGestureRecognizer(target: self, action: #selector(self.panAction))
self.pan.delegate = self
self.pan.maximumNumberOfTouches = 1
self.pan.cancelsTouchesInView = true
view.addGestureRecognizer(self.pan)
}
// MARK: -
@objc private func presentMiniPlayer() {
guard PlayerManager.shared.hasLoadedBook else { return }
self.animateView(self.miniPlayerContainer, show: true)
}
@objc private func dismissMiniPlayer() {
self.animateView(self.miniPlayerContainer, show: false)
}
@objc private func bookChange(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let book = userInfo["book"] as? Book
else {
return
}
self.setupMiniPlayer(book: book)
PlayerManager.shared.play()
}
@objc private func bookReady(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let book = userInfo["book"] as? Book
else {
return
}
self.setupMiniPlayer(book: book)
}
@objc private func onBookPlay() {
self.pan.isEnabled = false
}
@objc private func onBookPause() {
// Only enable the gesture to dismiss the Mini Player when the book is paused
self.pan.isEnabled = true
}
@objc private func onBookDelete(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let book = userInfo["book"] as? Book
else {
return
}
if book == PlayerManager.shared.currentBook, !self.miniPlayerIsHidden {
self.dismissMiniPlayer()
}
}
// MARK: - Helpers
private func setupMiniPlayer(book: Book) {
self.miniPlayerViewController?.book = book
}
// MARK: - Gesture recognizers
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == self.pan {
return limitPanAngle(self.pan, degreesOfFreedom: 45.0, comparator: .greaterThan)
}
return true
}
private func updatePresentedViewForTranslation(_ yTranslation: CGFloat) {
let translation: CGFloat = rubberBandDistance(yTranslation, dimension: self.view.frame.height, constant: 0.55)
self.miniPlayerContainer?.transform = CGAffineTransform(translationX: 0, y: max(translation, 0.0))
}
@objc private func panAction(gestureRecognizer: UIPanGestureRecognizer) {
guard gestureRecognizer.isEqual(self.pan) else {
return
}
switch gestureRecognizer.state {
case .began:
gestureRecognizer.setTranslation(CGPoint(x: 0, y: 0), in: self.view.superview)
case .changed:
let translation = gestureRecognizer.translation(in: self.view)
self.updatePresentedViewForTranslation(translation.y)
case .ended, .cancelled, .failed:
let dismissThreshold: CGFloat = self.miniPlayerContainer.bounds.height / 2
let translation = gestureRecognizer.translation(in: self.view)
if translation.y > dismissThreshold {
PlayerManager.shared.stop()
return
}
UIView.animate(withDuration: 0.3,
delay: 0.0,
usingSpringWithDamping: 0.75,
initialSpringVelocity: 1.5,
options: .preferredFramesPerSecond60,
animations: {
self.miniPlayerContainer?.transform = .identity
})
default: break
}
}
}
extension RootViewController: Themeable {
func applyTheme(_ theme: Theme) {
self.themedStatusBarStyle = theme.useDarkVariant
? .lightContent
: .default
setNeedsStatusBarAppearanceUpdate()
self.miniPlayerContainer.layer.shadowColor = theme.primaryColor.cgColor
}
}
| 2245ff78863c0bc9bbf3fa7894f0e6ee | 33.758621 | 134 | 0.654904 | false | false | false | false |
bitboylabs/selluv-ios | refs/heads/master | selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab5MyPage/SLV_919_MyPageWishAlarmController.swift | mit | 1 | //
// SLV_919_MyPageWishAlarmController.swift
// selluv-ios
//
// Created by 김택수 on 2017. 6. 3..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import UIKit
class SLV_919_MyPageWishAlarmController: SLVBaseStatusShowController {
let cellReuseIdentifier = "myPageWishAlarmCell"
var editButton: UIButton!
var isEditMode = false
var wishesArray :[SLVWishesProduct]!
@IBOutlet weak var tableView: UITableView!
//MARK:
//MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
tabController.animationTabBarHidden(true)
self.initUI()
self.settingUI()
self.loadData()
}
//MARK:
//MARK: Private
func initUI() {
}
func settingUI() {
tabController.hideFab()
self.title = "찾고 있는 아이템"
self.navigationItem.hidesBackButton = true
let back = UIButton()
back.setImage(UIImage(named:"ic-back-arrow.png"), for: .normal)
back.frame = CGRect(x: 17, y: 23, width: 12+32, height: 20)
back.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 26)
back.addTarget(self, action: #selector(SLV_919_MyPageWishAlarmController.clickBackButton(_:)), for: .touchUpInside)
let item = UIBarButtonItem(customView: back)
self.navigationItem.leftBarButtonItem = item
self.editButton = UIButton()
editButton.contentHorizontalAlignment = .right
editButton.frame = CGRect(x: 0, y: 0, width: 35, height: 27)
editButton.setTitle("편집", for: UIControlState.normal)
editButton.setTitleColor(text_color_g181, for: UIControlState.normal)
editButton.setTitle("완료", for: UIControlState.selected)
editButton.setTitleColor(bg_color_blue, for: UIControlState.selected)
editButton.titleLabel?.font = UIFont.systemFont(ofSize: 18.6)
editButton.addTarget(self, action: #selector(SLV_919_MyPageWishAlarmController.clickEditButton(_:)), for: .touchUpInside)
let editBarButton = UIBarButtonItem(customView: editButton)
self.navigationItem.rightBarButtonItem = editBarButton
self.tableView.register(UINib(nibName: "SLV919MyPageWishAlarmCell",
bundle: nil),
forCellReuseIdentifier: cellReuseIdentifier)
}
func loadData() {
MyInfoDataModel.shared.wishes { (success, wishes) in
print("\(wishes!)")
self.wishesArray = wishes
self.tableView.reloadData()
}
}
//MARK:
//MARK: IBAction
func clickBackButton(_ sender:UIButton) {
self.navigationController?.popViewController()
}
func clickEditButton(_ sender:UIButton) {
sender.isSelected = !sender.isSelected
self.tableView.reloadData()
}
}
extension SLV_919_MyPageWishAlarmController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 132
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.setSelected(false, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.wishesArray == nil {
return 0
} else {
return self.wishesArray.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! SLV919MyPageWishAlarmCell
cell.reset()
cell.editMode(editMode: self.editButton.isSelected)
var data = self.wishesArray[indexPath.row]
return cell
}
}
| 9179609944c6db7c2a3d3e5e40210171 | 30.748031 | 131 | 0.62996 | false | false | false | false |
cfraz89/RxSwift | refs/heads/master | RxExample/RxExample/Examples/ImagePicker/ImagePickerController.swift | mit | 1 | //
// ImagePickerController.swift
// RxExample
//
// Created by Segii Shulga on 1/5/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class ImagePickerController: ViewController {
@IBOutlet var imageView: UIImageView!
@IBOutlet var cameraButton: UIButton!
@IBOutlet var galleryButton: UIButton!
@IBOutlet var cropButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
cameraButton.rx.tap
.flatMapLatest { [weak self] _ in
return UIImagePickerController.rx.createWithParent(self) { picker in
picker.sourceType = .camera
picker.allowsEditing = false
}
.flatMap { $0.rx.didFinishPickingMediaWithInfo }
.take(1)
}
.map { info in
return info[UIImagePickerControllerOriginalImage] as? UIImage
}
.bindTo(imageView.rx.image)
.disposed(by: disposeBag)
galleryButton.rx.tap
.flatMapLatest { [weak self] _ in
return UIImagePickerController.rx.createWithParent(self) { picker in
picker.sourceType = .photoLibrary
picker.allowsEditing = false
}
.flatMap {
$0.rx.didFinishPickingMediaWithInfo
}
.take(1)
}
.map { info in
return info[UIImagePickerControllerOriginalImage] as? UIImage
}
.bindTo(imageView.rx.image)
.disposed(by: disposeBag)
cropButton.rx.tap
.flatMapLatest { [weak self] _ in
return UIImagePickerController.rx.createWithParent(self) { picker in
picker.sourceType = .photoLibrary
picker.allowsEditing = true
}
.flatMap { $0.rx.didFinishPickingMediaWithInfo }
.take(1)
}
.map { info in
return info[UIImagePickerControllerEditedImage] as? UIImage
}
.bindTo(imageView.rx.image)
.disposed(by: disposeBag)
}
}
| 1f6a3ee18f9de4626029fcad2d7aa459 | 30.355263 | 87 | 0.556022 | false | false | false | false |
mlburggr/OverRustleiOS | refs/heads/master | OverRustleiOS/MLG.swift | mit | 1 | //
// MLG.swift
// OverRustleiOS
//
// Created by Hayk Saakian on 8/20/15.
// Copyright (c) 2015 Maxwell Burggraf. All rights reserved.
//
import Foundation
public class MLG: RustleStream {
let PLAYER_EMBED_URL = "http://www.majorleaguegaming.com/player/embed/"
let STREAM_API_URL = "http://streamapi.majorleaguegaming.com/service/streams/playback/%@?format=all"
let stream_config_regex = "var playerConfig = (.+);"
override func getStreamURL() -> NSURL {
// warning: this is all assuming the stream exists and is live
// step 1: figure out the mlgXYZ id
// 1a: get the html containing the data
var error: NSError?
var url = NSURL(string: "\(PLAYER_EMBED_URL)\(channel)")!
var res = (try! NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding)) as String
// 1b: pull the id from the json on the page
let stream_id = findStreamId(res)
if stream_id == nil {
return NSURL()
}
// step 2: get the streams list
url = NSURL(string:String(format: STREAM_API_URL, stream_id!))!
let stream_api_data = try! NSData(contentsOfURL: url, options: [])
let streams = JSON(data: stream_api_data)["data"]["items"]
for (index, subJson): (String, JSON) in streams {
if let source_url = subJson["url"].string {
// find the first HLS playlist
if source_url.hasSuffix("m3u8") {
return NSURL(string: source_url)!
}
}
}
return NSURL()
}
func findStreamId(html: String) -> String? {
let matches = matchesForRegexInText(stream_config_regex, text: html)
if matches.count == 0 {
return nil
}
let json_string = matches[0].substringWithRange(Range<String.Index>(start: matches[0].startIndex.advancedBy(19), end: matches[0].endIndex.advancedBy(-1)))
print("json string \(json_string)")
if let dataFromString = json_string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
let id = json["media"]["stream_name"].string
return id
}
return nil
}
}
| 1233ef9622dc4054db759e952ac43137 | 32.957143 | 162 | 0.575095 | false | false | false | false |
allenngn/firefox-ios | refs/heads/master | Storage/SyncQueue.swift | mpl-2.0 | 4 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
public struct SyncCommand: Equatable {
public let value: String
public var commandID: Int?
public var clientGUID: GUID?
let version: String?
public init(value: String) {
self.value = value
self.version = nil
self.commandID = nil
self.clientGUID = nil
}
public init(id: Int, value: String) {
self.value = value
self.version = nil
self.commandID = id
self.clientGUID = nil
}
public init(id: Int?, value: String, clientGUID: GUID?) {
self.value = value
self.version = nil
self.clientGUID = clientGUID
self.commandID = id
}
public static func fromShareItem(shareItem: ShareItem, withAction action: String) -> SyncCommand {
let jsonObj: [String: AnyObject] = [
"command": action,
"args": [shareItem.url, shareItem.title ?? ""]
]
return SyncCommand(value: JSON.stringify(jsonObj, pretty: false))
}
public func withClientGUID(clientGUID: String?) -> SyncCommand {
return SyncCommand(id: self.commandID, value: self.value, clientGUID: clientGUID)
}
}
public func ==(lhs: SyncCommand, rhs: SyncCommand) -> Bool {
return lhs.value == rhs.value
}
public protocol SyncCommands {
func deleteCommands() -> Success
func deleteCommands(clientGUID: GUID) -> Success
func getCommands() -> Deferred<Result<[GUID: [SyncCommand]]>>
func insertCommand(command: SyncCommand, forClients clients: [RemoteClient]) -> Deferred<Result<Int>>
func insertCommands(commands: [SyncCommand], forClients clients: [RemoteClient]) -> Deferred<Result<Int>>
} | 99e24209f1de1eebde94b025fd8c7e2c | 29.901639 | 109 | 0.649682 | false | false | false | false |
JGiola/swift | refs/heads/main | SwiftCompilerSources/Sources/SIL/Effects.swift | apache-2.0 | 4 | //===--- Effects.swift - Defines function effects -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// An effect on a function argument.
public struct ArgumentEffect : CustomStringConvertible, CustomReflectable {
public typealias Path = SmallProjectionPath
/// Selects which argument (or return value) and which projection of the argument
/// or return value.
///
/// For example, the selection `%0.s1` would select the second struct field of `arg` in
/// func foo(_ arg: Mystruct) { ... }
public struct Selection : CustomStringConvertible {
public enum ArgumentOrReturn : Equatable {
case argument(Int)
case returnValue
}
// Which argument or return value.
public let value: ArgumentOrReturn
/// Which projection(s) of the argument or return value.
public let pathPattern: Path
public init(_ value: ArgumentOrReturn, pathPattern: Path) {
self.value = value
self.pathPattern = pathPattern
}
public init(_ arg: Argument, pathPattern: Path) {
self.init(.argument(arg.index), pathPattern: pathPattern)
}
/// Copy the selection by applying a delta on the argument index.
///
/// This is used when copying argument effects for specialized functions where
/// the indirect result is converted to a direct return value (in this case the
/// `resultArgDelta` is -1).
public init(copiedFrom src: Selection, resultArgDelta: Int) {
switch (src.value, resultArgDelta) {
case (let a, 0):
self.value = a
case (.returnValue, 1):
self.value = .argument(0)
case (.argument(0), -1):
self.value = .returnValue
case (.argument(let a), let d):
self.value = .argument(a + d)
default:
fatalError()
}
self.pathPattern = src.pathPattern
}
public var argumentIndex: Int {
switch value {
case .argument(let argIdx): return argIdx
default: fatalError("expected argument")
}
}
public var description: String {
let posStr: String
switch value {
case .argument(let argIdx):
posStr = "%\(argIdx)"
case .returnValue:
posStr = "%r"
}
let pathStr = (pathPattern.isEmpty ? "" : ".\(pathPattern)")
return "\(posStr)\(pathStr)"
}
public func matches(_ rhsValue: ArgumentOrReturn, _ rhsPath: Path) -> Bool {
return value == rhsValue && rhsPath.matches(pattern: pathPattern)
}
}
//----------------------------------------------------------------------//
// Members of ArgumentEffect
//----------------------------------------------------------------------//
public enum Kind {
/// The selected argument value does not escape.
///
/// Syntax examples:
/// !%0 // argument 0 does not escape
/// !%0.** // argument 0 and all transitively contained values do not escape
///
case notEscaping
/// The selected argument value escapes to the specified selection (= first payload).
///
/// Syntax examples:
/// %0.s1 => %r // field 2 of argument 0 exclusively escapes via return.
/// %0.s1 -> %1 // field 2 of argument 0 - and other values - escape to argument 1.
///
/// The "exclusive" flag (= second payload) is true if only the selected argument escapes
/// to the specified selection, but nothing else escapes to it.
/// For example, "exclusive" is true for the following function:
///
/// @_effect(escaping c => return)
/// func exclusiveEscape(_ c: Class) -> Class { return c }
///
/// but not in this case:
///
/// var global: Class
///
/// @_effect(escaping c -> return)
/// func notExclusiveEscape(_ c: Class) -> Class { return cond ? c : global }
///
case escaping(Selection, Bool) // to, exclusive
}
/// To which argument (and projection) does this effect apply to?
public let selectedArg: Selection
/// The kind of effect.
public let kind: Kind
/// True, if this effect is derived in an optimization pass.
/// False, if this effect is defined in the Swift source code.
public let isDerived: Bool
public init(_ kind: Kind, selectedArg: Selection, isDerived: Bool = true) {
self.selectedArg = selectedArg
self.kind = kind
self.isDerived = isDerived
}
/// Copy the ArgumentEffect by applying a delta on the argument index.
///
/// This is used when copying argument effects for specialized functions where
/// the indirect result is converted to a direct return value (in this case the
/// `resultArgDelta` is -1).
init(copiedFrom srcEffect: ArgumentEffect, resultArgDelta: Int) {
func copy(_ srcSelection: Selection) -> Selection {
return Selection(copiedFrom: srcSelection, resultArgDelta: resultArgDelta)
}
self.selectedArg = copy(srcEffect.selectedArg)
self.isDerived = srcEffect.isDerived
switch srcEffect.kind {
case .notEscaping:
self.kind = .notEscaping
case .escaping(let toSelectedArg, let exclusive):
self.kind = .escaping(copy(toSelectedArg), exclusive)
}
}
public var description: String {
switch kind {
case .notEscaping:
return "!\(selectedArg)"
case .escaping(let toSelectedArg, let exclusive):
return "\(selectedArg) \(exclusive ? "=>" : "->") \(toSelectedArg)"
}
}
public var customMirror: Mirror { Mirror(self, children: []) }
}
/// All argument effects for a function.
///
/// In future we might add non-argument-specific effects, too, like `readnone`, `readonly`.
public struct FunctionEffects : CustomStringConvertible, CustomReflectable {
public var argumentEffects: [ArgumentEffect] = []
public init() {}
public init(copiedFrom src: FunctionEffects, resultArgDelta: Int) {
self.argumentEffects = src.argumentEffects.map {
ArgumentEffect(copiedFrom: $0, resultArgDelta: resultArgDelta)
}
}
public func canEscape(argumentIndex: Int, path: ArgumentEffect.Path, analyzeAddresses: Bool) -> Bool {
return !argumentEffects.contains(where: {
if case .notEscaping = $0.kind, $0.selectedArg.value == .argument(argumentIndex) {
// Any address of a class property of an object, which is passed to the function, cannot
// escape the function. Whereas a value stored in such a property could escape.
let p = (analyzeAddresses ? path.popLastClassAndValuesFromTail() : path)
if p.matches(pattern: $0.selectedArg.pathPattern) {
return true
}
}
return false
})
}
public mutating func removeDerivedEffects() {
argumentEffects = argumentEffects.filter { !$0.isDerived }
}
public var description: String {
return "[" + argumentEffects.map { $0.description }.joined(separator: ", ") + "]"
}
public var customMirror: Mirror { Mirror(self, children: []) }
}
//===----------------------------------------------------------------------===//
// Parsing
//===----------------------------------------------------------------------===//
extension StringParser {
mutating func parseEffectFromSource(for function: Function,
params: Dictionary<String, Int>) throws -> ArgumentEffect {
if consume("notEscaping") {
let selectedArg = try parseSelectionFromSource(for: function, params: params)
return ArgumentEffect(.notEscaping, selectedArg: selectedArg, isDerived: false)
}
if consume("escaping") {
let from = try parseSelectionFromSource(for: function, params: params)
let exclusive = try parseEscapingArrow()
let to = try parseSelectionFromSource(for: function, params: params, acceptReturn: true)
return ArgumentEffect(.escaping(to, exclusive), selectedArg: from, isDerived: false)
}
try throwError("unknown effect")
}
mutating func parseEffectFromSIL(for function: Function, isDerived: Bool) throws -> ArgumentEffect {
if consume("!") {
let selectedArg = try parseSelectionFromSIL(for: function)
return ArgumentEffect(.notEscaping, selectedArg: selectedArg, isDerived: isDerived)
}
let from = try parseSelectionFromSIL(for: function)
let exclusive = try parseEscapingArrow()
let to = try parseSelectionFromSIL(for: function, acceptReturn: true)
return ArgumentEffect(.escaping(to, exclusive), selectedArg: from, isDerived: isDerived)
}
private mutating func parseEscapingArrow() throws -> Bool {
if consume("=>") { return true }
if consume("->") { return false }
try throwError("expected '=>' or '->'")
}
mutating func parseSelectionFromSource(for function: Function,
params: Dictionary<String, Int>,
acceptReturn: Bool = false) throws -> ArgumentEffect.Selection {
let value: ArgumentEffect.Selection.ArgumentOrReturn
if consume("self") {
if !function.hasSelfArgument {
try throwError("function does not have a self argument")
}
value = .argument(function.selfArgumentIndex)
} else if consume("return") {
if !acceptReturn {
try throwError("return not allowed here")
}
if function.numIndirectResultArguments > 0 {
if function.numIndirectResultArguments != 1 {
try throwError("multi-value returns not supported yet")
}
value = .argument(0)
} else {
value = .returnValue
}
} else if let name = consumeIdentifier() {
guard let argIdx = params[name] else {
try throwError("parameter not found")
}
value = .argument(argIdx + function.numIndirectResultArguments)
} else {
try throwError("parameter name or return expected")
}
let valueType: Type
switch value {
case .argument(let argIdx):
valueType = function.argumentTypes[argIdx]
case .returnValue:
valueType = function.resultType
}
if consume(".") {
let path = try parseProjectionPathFromSource(for: function, type: valueType)
return ArgumentEffect.Selection(value, pathPattern: path)
}
if !valueType.isClass {
switch value {
case .argument:
try throwError("the argument is not a class - add 'anyValueFields'")
case .returnValue:
try throwError("the return value is not a class - add 'anyValueFields'")
}
}
return ArgumentEffect.Selection(value, pathPattern: ArgumentEffect.Path())
}
mutating func parseSelectionFromSIL(for function: Function,
acceptReturn: Bool = false) throws -> ArgumentEffect.Selection {
let value: ArgumentEffect.Selection.ArgumentOrReturn
if consume("%r") {
if !acceptReturn {
try throwError("return not allowed here")
}
value = .returnValue
} else if consume("%") {
guard let argIdx = consumeInt() else {
try throwError("expected argument index")
}
value = .argument(argIdx)
} else {
try throwError("expected parameter or return")
}
if consume(".") {
return try ArgumentEffect.Selection(value, pathPattern: parseProjectionPathFromSIL())
}
return ArgumentEffect.Selection(value, pathPattern: ArgumentEffect.Path())
}
}
| b00f0cce58f0b1840724cd96eda0945a | 34.361446 | 104 | 0.62615 | false | false | false | false |
ludwigschubert/cs376-project | refs/heads/master | DesktopHeartRateMonitor/DesktopHeartRateMonitor/NSImage+TintColor.swift | mit | 1 | // http://codegists.com/snippet/swift/nsimagetintcolorswift_usagimaru_swift
import Cocoa
/*
let tintColor = NSColor(red: 1.0, green: 0.08, blue: 0.50, alpha: 1.0)
let image = NSImage(named: "NAME").imageWithTintColor(tintColor)
imageView.image = image
*/
extension NSImage {
func tinted(color: NSColor) -> NSImage
{
if self.isTemplate == false {
return self
}
let image = self.copy() as! NSImage
image.lockFocus()
color.set()
let rect = NSMakeRect(0, 0, image.size.width, image.size.height)
NSRectFillUsingOperation(rect, .sourceAtop)
image.unlockFocus()
image.isTemplate = false
return image
}
}
| 79a5c04291244a314edab1a9e55bf769 | 21.3125 | 75 | 0.62465 | false | false | false | false |
BBRick/wp | refs/heads/master | wp/General/Base/BaseCustomTableViewController.swift | apache-2.0 | 1 | //
// BaseCustomTableViewController.swift
// viossvc
//
// Created by yaowang on 2016/10/29.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import UIKit
class BaseCustomTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,TableViewHelperProtocol {
@IBOutlet weak var tableView: UITableView!
var tableViewHelper:TableViewHelper = TableViewHelper();
override func viewDidLoad() {
super.viewDidLoad()
initTableView();
}
//友盟页面统计
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
MobClick.beginLogPageView(NSStringFromClass(self.classForCoder))
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
MobClick.beginLogPageView(NSStringFromClass(self.classForCoder))
}
final func initTableView() {
if tableView == nil {
for view:UIView in self.view.subviews {
if view.isKind(of: UITableView.self) {
tableView = view as? UITableView;
break;
}
}
}
if tableView.tableFooterView == nil {
tableView.tableFooterView = UIView(frame:CGRect(x: 0,y: 0,width: 0,height: 0.5));
}
tableView.delegate = self;
tableView.dataSource = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK:TableViewHelperProtocol
func isSections() ->Bool {
return false;
}
func isCacheCellHeight() -> Bool {
return false;
}
func isCalculateCellHeight() ->Bool {
return isCacheCellHeight();
}
func tableView(_ tableView:UITableView ,cellIdentifierForRowAtIndexPath indexPath: IndexPath) -> String? {
return tableViewHelper.tableView(tableView, cellIdentifierForRowAtIndexPath: indexPath, controller: self);
}
func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? {
return nil;
}
//MARK: -UITableViewDelegate
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableViewHelper.tableView(tableView, cellForRowAtIndexPath: indexPath, controller: self);
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
tableViewHelper.tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath, controller: self);
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if( isCalculateCellHeight() ) {
let cellHeight:CGFloat = tableViewHelper.tableView(tableView, heightForRowAtIndexPath: indexPath, controller: self);
if( cellHeight != CGFloat.greatestFiniteMagnitude ) {
return cellHeight;
}
}
return tableView.rowHeight;
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0;
}
}
class BaseCustomRefreshTableViewController :BaseCustomTableViewController {
override func viewDidLoad() {
super.viewDidLoad();
self.setupRefreshControl();
}
internal func didRequestComplete(_ data:AnyObject?) {
endRefreshing();
self.tableView.reloadData();
}
func completeBlockFunc()->CompleteBlock {
return { [weak self] (obj) in
self?.didRequestComplete(obj)
}
}
override func didRequestError(_ error:NSError) {
self.endRefreshing()
super.didRequestError(error)
}
deinit {
performSelectorRemoveRefreshControl();
}
}
class BaseCustomListTableViewController :BaseCustomRefreshTableViewController {
internal var dataSource:Array<AnyObject>?;
override func didRequestComplete(_ data: AnyObject?) {
dataSource = data as? Array<AnyObject>;
super.didRequestComplete(dataSource as AnyObject?);
}
//MARK: -UITableViewDelegate
override func numberOfSections(in tableView: UITableView) -> Int {
var count:Int = dataSource != nil ? 1 : 0;
if isSections() && count != 0 {
count = dataSource!.count;
}
return count;
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var datas:Array<AnyObject>? = dataSource;
if dataSource != nil && isSections() {
datas = dataSource![section] as? Array<AnyObject>;
}
return datas == nil ? 0 : datas!.count;
}
//MARK:TableViewHelperProtocol
override func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? {
var datas:Array<AnyObject>? = dataSource;
if dataSource != nil && isSections() {
datas = dataSource![indexPath.section] as? Array<AnyObject>;
}
return (datas != nil && datas!.count > indexPath.row ) ? datas![indexPath.row] : nil;
}
}
class BaseCustomPageListTableViewController :BaseCustomListTableViewController {
override func viewDidLoad() {
super.viewDidLoad();
setupLoadMore();
}
override func didRequestComplete(_ data: AnyObject?) {
tableViewHelper.didRequestComplete(&self.dataSource,
pageDatas: data as? Array<AnyObject>, controller: self);
super.didRequestComplete(self.dataSource as AnyObject?);
}
override func didRequestError(_ error:NSError) {
if (!(self.pageIndex == 1) ) {
self.errorLoadMore()
}
self.setIsLoadData(true)
super.didRequestError(error)
}
deinit {
removeLoadMore();
}
}
| 025d13a06ddd4f736de22d90b3cde6ef | 29.959391 | 128 | 0.630595 | false | false | false | false |
ton252/EasyDAO | refs/heads/master | EasyDAO/Classes/Realm/RealmDAO.swift | mit | 1 | //
// RealmDAO.swift
// DAO
//
// Created by Антон Поляков on 13/02/2017.
// Copyright © 2017 Антон Поляков. All rights reserved.
//
import RealmSwift
import Foundation
public class RealmDAO<Translator: RealmTranslatorProtocol>: DAOProtocol {
public typealias Entry = Translator.Entry
public typealias Entity = Translator.Entity
public let translator: Translator
private let dataBase: Realm
public required init(translator: Translator, realm: Realm) {
self.translator = translator
self.dataBase = realm
}
//MARK: Persisting
@discardableResult public func persist(_ entity: Entity) -> Bool {
do {
try dataBase.write { [unowned self] in
self.persistWithoutSaving(entity)
}
} catch {
return false
}
return true
}
@discardableResult public func persist(_ entities: [Entity]) -> Bool {
do {
try dataBase.write { [unowned self] in
entities.forEach{ self.persistWithoutSaving($0) }
}
} catch {
return false
}
return true
}
private func persistWithoutSaving(_ entity: Entity) -> Void {
let pk = entity.identifier
let oldEntry = dataBase.object(ofType: Entry.self, forPrimaryKey: pk)
if let oldEntry = oldEntry {
self.dataBase.delete(oldEntry)
}
let entry = translator.toEntry(entity)
dataBase.add(entry)
}
//MARK: Reading
public func read(id: String) -> Entity? {
if let entity = dataBase.object(ofType: Entry.self, forPrimaryKey: id) {
return translator.toEntity(entity)
}
return nil
}
public func read(predicate: NSPredicate?) -> [Entity] {
var result = dataBase.objects(Translator.Entry.self)
if let predicate = predicate {
result = result.filter(predicate)
}
let entries = Array(result)
return translator.toEntities(entries)
}
//MARK: Erasing
@discardableResult public func erase(id: String) -> Bool {
let entry = dataBase.object(ofType: Entry.self, forPrimaryKey: id)
guard entry != nil else { return false }
do {
try dataBase.write {
self.dataBase.delete(entry!)
}
} catch {
return false
}
return true
}
@discardableResult public func erase() -> Bool {
let entries = dataBase.objects(Translator.Entry.self)
do {
try dataBase.write { [unowned self] in
self.dataBase.delete(entries)
}
} catch {
return false
}
return true
}
}
| 0568ceff08d16726db4fa3367e6c5170 | 25.688679 | 80 | 0.564864 | false | false | false | false |
klesh/cnodejs-swift | refs/heads/master | CNode/Libs/PHTextView.swift | apache-2.0 | 1 | //
// PHTextView.swift
// CNode
//
// Created by Klesh Wong on 1/14/16.
// Copyright © 2016 Klesh Wong. All rights reserved.
//
import UIKit
class PHTextView : UITextView, UITextViewDelegate {
var placeHolder: UILabel!
override func awakeFromNib() {
placeHolder = UILabel(frame: CGRectMake(5, 0, frame.size.width, 30))
placeHolder.textColor = UIColor(red: 0.75, green: 0.75, blue: 0.75, alpha: 1.0)
self.layer.borderColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0).CGColor
self.layer.borderWidth = 1
self.layer.cornerRadius = 5
self.delegate = self
self.addSubview(placeHolder)
}
func textViewDidChange(textView: UITextView) {
placeHolder.hidden = textView.hasText()
}
} | d9f36b4bbbbd12328a11f145faee1a9d | 26 | 93 | 0.621755 | false | false | false | false |
midoks/Swift-Learning | refs/heads/master | EampleApp/EampleApp/Framework/NineCellLockView/SudokuView.swift | apache-2.0 | 1 | //
// NineCellLockView.swift
//
// Created by midoks on 15/8/20.
// Copyright © 2015年 midoks. All rights reserved.
//
import UIKit
class SudokuView: UIView {
var delegate: SudokuViewDelegate?
var fingerPoint:CGPoint = CGPoint()
var linePointointCollection:Array<CGPoint> = Array<CGPoint>()
var ninePointCollection:Array<CGPoint> = Array<CGPoint>()
var selectPointIndexCollection:Array<Int> = Array<Int>()
//密码默认正确
var pswIsRight:Bool = true
//圆圈的宽度
var circleRadius:CGFloat = 28
//连接线宽度
var littleCircleRadius:CGFloat = 15
//密文
var ciphertext:NSString?
//初始化9个点的坐标
override init(frame:CGRect){
super.init(frame:frame)
//设置背景
self.backgroundColor = UIColor(red: 35/255.0, green: 39/255.0, blue: 54/255.0, alpha: 1)
//计算9个坐标位置
self.fillNinePointCollection()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - 计算9个坐标位置 -
func fillNinePointCollection(){
//宽度为300,找到起点
let widthLimit = (self.frame.width - 300) / 2
//高度为300,找到起点
let heightLimit = (self.frame.height - 300)/2
//1:x,y 第一个坐标点
let xRowOne = widthLimit + 50
let yColumnOne = heightLimit + 50
for row in 0...2
{
for column in 0...2
{
let tempX:CGFloat = xRowOne + CGFloat(row) * 100
let tempY:CGFloat = yColumnOne + CGFloat(column) * 100
self.ninePointCollection.append(CGPoint(x: tempX,y:tempY))
}
}
}
//MARK: - 初始化画图 -
override func draw(_ rect: CGRect) {
//print("1")
let context = UIGraphicsGetCurrentContext()
self.DrawLines()
//9个圆圈
self.drawNineCircle(context!)
//画错误时的颜色
self.DrawTriangleWhenPswIsError(context!)
}
func drawCicle(_ centerPoint:CGPoint,index:Int,context:CGContext){
context.setLineWidth(2.0)
//context.addArc(tangent1End: CGPoint(CGFloat(centerPoint.x),CGFloat(centerPoint.y)), tangent2End: CGPoint(CGFloat(M_PI * 2.0), 1), radius: self.circleRadius)
let currentIsSelected:Bool = self.selectPointIndexCollection.contains(index)
if(currentIsSelected){
if(pswIsRight){
//选中的圆圈的边框颜色不一样
context.setStrokeColor(UIColor(red: 96/255.0, green: 169/255.0, blue: 252/255.0, alpha: 1).cgColor)
}else{
context.setStrokeColor(UIColor.red.cgColor)
}
}else{
context.setStrokeColor(UIColor(red: 144/255.0, green: 149/255.0, blue: 173/255.0, alpha: 1).cgColor)
}
context.strokePath()
//为了遮住圈内的线
//CGContextAddArc(context, centerPoint.x, centerPoint.y, self.circleRadius, 0.0, CGFloat(M_PI * 2.0), 1)
context.setFillColor(UIColor(red: 35/255.0, green: 39/255.0, blue: 54/255.0, alpha: 1).cgColor)
context.fillPath()
//CGContext.addArc(CGContext)
if(currentIsSelected){
//CGContext.addArc(context, centerPoint.x, centerPoint.y, self.littleCircleRadius, 0.0, CGFloat(M_PI * 2.0), 1)
if(pswIsRight){
context.setFillColor(UIColor(red: 96/255.0, green: 169/255.0, blue: 252/255.0, alpha: 1).cgColor)
}else{
context.setFillColor(UIColor.red.cgColor)
}
context.fillPath()
}
}
func drawNineCircle(_ context:CGContext){
for p in 0...self.ninePointCollection.count - 1 {
self.drawCicle(self.ninePointCollection[p],index:p,context:context)
}
}
//画链接线
func DrawLines(){
if(self.selectPointIndexCollection.count > 0) {
let bp = UIBezierPath()
bp.lineWidth = 5
bp.lineCapStyle = CGLineCap.round
if(pswIsRight) {
UIColor(red: 96/255.0, green: 169/255.0, blue: 252/255.0, alpha: 1).setStroke()
} else {
UIColor.red.setStroke()
}
for index in 0...self.selectPointIndexCollection.count-1 {
let PointIndex = self.selectPointIndexCollection[index]
if(index == 0) {
bp.move(to: self.ninePointCollection[PointIndex])
} else {
bp.addLine(to: self.ninePointCollection[PointIndex])
}
}
if self.fingerPoint.x != -100 {
bp.addLine(to: self.fingerPoint)
}
bp.stroke()
}
}
func GetAngle(_ p1:CGPoint,p2:CGPoint)->CGFloat {
let Re:CGFloat = ((atan(CGFloat((p2.y - p1.y) / (p2.x - p1.x)))))
if p2.x < p1.x {
return Re - CGFloat(Double.pi)
}
return Re
}
//三角形的顶点距离圆心的距离
var TriangleTopPointDistanceToCircleCenterPoint:CGFloat = 20
//如果密码密码错误则在选中的圆圈内绘制三角形的路线指示标志
func DrawTriangleWhenPswIsError(_ context:CGContext)
{
if(pswIsRight)
{
return
}
if self.selectPointIndexCollection.count <= 1
{
return
}
for index in 0...self.selectPointIndexCollection.count-1
{
let preIndex:Int = index - 1
if(preIndex >= 0 )
{
let prePointIndex:Int = self.selectPointIndexCollection[preIndex]
let currentPointIndex:Int = self.selectPointIndexCollection[index]
let currentPoint :CGPoint = self.ninePointCollection[currentPointIndex]
let prePoint:CGPoint = self.ninePointCollection[prePointIndex]
context.saveGState()
context.translateBy(x: prePoint.x,y: prePoint.y )
context.rotate(by: GetAngle(prePoint,p2:currentPoint))
context.translateBy(x: 0 - prePoint.x,y: 0 - prePoint.y)
context.beginPath()
context.setFillColor(UIColor.red.cgColor)
//都是绘制在x坐标的右边 上面几行代码是旋转的逻辑
context.move(to: CGPoint(x: prePoint.x + self.TriangleTopPointDistanceToCircleCenterPoint - 6, y: prePoint.y - 6))
context.addLine(to: CGPoint(x: prePoint.x + self.TriangleTopPointDistanceToCircleCenterPoint, y: prePoint.y))
context.addLine(to: CGPoint(x: prePoint.x + self.TriangleTopPointDistanceToCircleCenterPoint - 6, y: prePoint.y + 6))
context.closePath()
context.fillPath()
context.restoreGState()
}
}
}
func distanceBetweenTwoPoint(_ p1:CGPoint,p2:CGPoint)->CGFloat{
return pow(pow((p1.x-p2.x), 2)+pow((p1.y-p2.y), 2), 0.5)
}
//加入触摸的点
func CircleIsTouchThenPushInSelectPointIndexCollection(_ fingerPoint:CGPoint){
for index in 0...self.ninePointCollection.count-1 {
if(!self.selectPointIndexCollection.contains(index)) {
if(self.distanceBetweenTwoPoint(fingerPoint,p2:self.ninePointCollection[index]) <= circleRadius) {
self.selectPointIndexCollection.append(index)
}
}
}
}
//设置密文
internal func setPwd(_ ciphertext: NSString){
self.ciphertext = ciphertext
}
//判断是否是正确的密文
func isRightPwd() -> Bool {
let ReStrVal = self.getCurrentPwd()
let ReStrLen = ReStrVal.length
if(self.ciphertext != nil){
let subRetValStr = self.ciphertext!.substring(with: NSMakeRange(0, ReStrLen))
if(subRetValStr != ReStrVal as String){
return false
}
}
return true
}
//获取正确的密码
func getCurrentPwd() -> NSString {
if( self.selectPointIndexCollection.count > 0 ) {
var ReStr:String = ""
for index in 0...self.selectPointIndexCollection.count - 1
{
ReStr += String(self.selectPointIndexCollection[index])
}
let ReStrVal = NSString(string: ReStr)
return ReStrVal
}
return ""
}
func touchesCommon(_ status: NSString){
let pwd = self.getCurrentPwd()
if(self.isRightPwd()){
pswIsRight = true
self.delegate!.SudokuViewOk!(pwd, status: status)
}else{
pswIsRight = false
self.delegate!.SudokuViewFail!(pwd, status: status)
}
}
//MARK: - touch事件 -
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let t = touches.first
self.selectPointIndexCollection.removeAll(keepingCapacity: false)
//获取触摸的坐标
self.fingerPoint = t!.location(in: self)
self.CircleIsTouchThenPushInSelectPointIndexCollection(fingerPoint)
self.touchesCommon("began")
self.setNeedsDisplay()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let t = touches.first
self.fingerPoint = t!.location(in: self)
self.CircleIsTouchThenPushInSelectPointIndexCollection(self.fingerPoint)
self.touchesCommon("moved")
self.setNeedsDisplay()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.touchesCommon("end")
self.selectPointIndexCollection = []
self.setNeedsDisplay()
}
}
@objc protocol SudokuViewDelegate {
@objc optional func SudokuViewFail(_ pwd:NSString, status: NSString)
@objc optional func SudokuViewOk(_ pwd: NSString, status: NSString)
}
| 90642113c9b6b00c8c93cac3d13e8ebd | 32.09571 | 166 | 0.562724 | false | false | false | false |
devpunk/punknote | refs/heads/master | punknote/View/Share/VShareImage.swift | mit | 1 | import UIKit
class VShareImage:UIView
{
private let kMarginHorizontal:CGFloat = 40
init(
modelHomeItem:MHomeItem,
noteFrame:DNoteFrame,
scale:CGFloat,
frame:CGRect)
{
let font:UIFont = modelHomeItem.font()
let fontSize:CGFloat = font.pointSize
let scaledFont:UIFont = font.withSize(fontSize * scale)
let marginScaled:CGFloat = kMarginHorizontal * scale
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.black
isUserInteractionEnabled = false
let background:UIView = modelHomeItem.background.view()
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.textColor = UIColor.white
label.font = scaledFont
label.text = noteFrame.text
label.numberOfLines = 0
label.textAlignment = NSTextAlignment.center
addSubview(background)
addSubview(label)
NSLayoutConstraint.equals(
view:background,
toView:self)
NSLayoutConstraint.equalsVertical(
view:label,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self,
margin:marginScaled)
}
required init?(coder:NSCoder)
{
return nil
}
}
| f65159a4e743bee20ec603850b9d9b04 | 26.745455 | 63 | 0.606815 | false | false | false | false |
alexhillc/AXPhotoViewer | refs/heads/master | Source/Classes/Views/AXOverlayView.swift | mit | 1 | //
// AXOverlayView.swift
// AXPhotoViewer
//
// Created by Alex Hill on 5/28/17.
// Copyright © 2017 Alex Hill. All rights reserved.
//
import UIKit
@objc open class AXOverlayView: UIView, AXStackableViewContainerDelegate {
#if os(iOS)
/// The toolbar used to set the `titleView`, `leftBarButtonItems`, `rightBarButtonItems`
@objc public let toolbar = UIToolbar(frame: CGRect(origin: .zero, size: CGSize(width: 320, height: 44)))
/// The title view displayed in the toolbar. This view is sized and centered between the `leftBarButtonItems` and `rightBarButtonItems`.
/// This is prioritized over `title`.
@objc public var titleView: AXOverlayTitleViewProtocol? {
didSet {
assert(self.titleView == nil ? true : self.titleView is UIView, "`titleView` must be a UIView.")
if self.window == nil {
return
}
self.updateToolbarBarButtonItems()
}
}
/// The bar button item used internally to display the `titleView` attribute in the toolbar.
var titleViewBarButtonItem: UIBarButtonItem?
/// The title displayed in the toolbar. This string is centered between the `leftBarButtonItems` and `rightBarButtonItems`.
/// Overwrites `internalTitle`.
@objc public var title: String? {
didSet {
self.updateTitleBarButtonItem()
}
}
/// The title displayed in the toolbar. This string is centered between the `leftBarButtonItems` and `rightBarButtonItems`.
/// This is used internally by the library to set a default title. Overwritten by `title`.
var internalTitle: String? {
didSet {
self.updateTitleBarButtonItem()
}
}
/// The title text attributes inherited by the `title`.
@objc public var titleTextAttributes: [NSAttributedString.Key: Any]? {
didSet {
self.updateTitleBarButtonItem()
}
}
/// The bar button item used internally to display the `title` attribute in the toolbar.
let titleBarButtonItem = UIBarButtonItem(customView: UILabel())
/// The bar button item that appears in the top left corner of the overlay.
@objc public var leftBarButtonItem: UIBarButtonItem? {
set(value) {
if let value = value {
self.leftBarButtonItems = [value]
} else {
self.leftBarButtonItems = nil
}
}
get {
return self.leftBarButtonItems?.first
}
}
/// The bar button items that appear in the top left corner of the overlay.
@objc public var leftBarButtonItems: [UIBarButtonItem]? {
didSet {
if self.window == nil {
return
}
self.updateToolbarBarButtonItems()
}
}
/// The bar button item that appears in the top right corner of the overlay.
@objc public var rightBarButtonItem: UIBarButtonItem? {
set(value) {
if let value = value {
self.rightBarButtonItems = [value]
} else {
self.rightBarButtonItems = nil
}
}
get {
return self.rightBarButtonItems?.first
}
}
/// The bar button items that appear in the top right corner of the overlay.
@objc public var rightBarButtonItems: [UIBarButtonItem]? {
didSet {
if self.window == nil {
return
}
self.updateToolbarBarButtonItems()
}
}
#endif
/// The caption view to be used in the overlay.
@objc open var captionView: AXCaptionViewProtocol = AXCaptionView() {
didSet {
guard let oldCaptionView = oldValue as? UIView else {
assertionFailure("`oldCaptionView` must be a UIView.")
return
}
guard let captionView = self.captionView as? UIView else {
assertionFailure("`captionView` must be a UIView.")
return
}
let index = self.bottomStackContainer.subviews.firstIndex(of: oldCaptionView)
oldCaptionView.removeFromSuperview()
self.bottomStackContainer.insertSubview(captionView, at: index ?? 0)
self.setNeedsLayout()
}
}
/// Whether or not to animate `captionView` changes. Defaults to true.
@objc public var animateCaptionViewChanges: Bool = true {
didSet {
self.captionView.animateCaptionInfoChanges = self.animateCaptionViewChanges
}
}
/// The inset of the contents of the `OverlayView`. Use this property to adjust layout for things such as status bar height.
/// For internal use only.
var contentInset: UIEdgeInsets = .zero {
didSet {
self.setNeedsLayout()
}
}
/// Container to embed all content anchored at the top of the `overlayView`.
/// Add custom subviews to the top container in the order that you wish to stack them. These must be self-sizing views.
@objc public var topStackContainer: AXStackableViewContainer!
/// Container to embed all content anchored at the bottom of the `overlayView`.
/// Add custom subviews to the bottom container in the order that you wish to stack them. These must be self-sizing views.
@objc public var bottomStackContainer: AXStackableViewContainer!
/// A flag that is set at the beginning and end of `OverlayView.setShowInterface(_:alongside:completion:)`
fileprivate var isShowInterfaceAnimating = false
/// Closures to be processed at the end of `OverlayView.setShowInterface(_:alongside:completion:)`
fileprivate var showInterfaceCompletions = [() -> Void]()
fileprivate var isFirstLayout: Bool = true
@objc public init() {
super.init(frame: .zero)
self.topStackContainer = AXStackableViewContainer(views: [], anchoredAt: .top)
self.topStackContainer.backgroundColor = AXConstants.overlayForegroundColor
self.topStackContainer.delegate = self
self.addSubview(self.topStackContainer)
#if os(iOS)
self.toolbar.backgroundColor = .clear
self.toolbar.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default)
self.topStackContainer.addSubview(self.toolbar)
#endif
self.bottomStackContainer = AXStackableViewContainer(views: [], anchoredAt: .bottom)
self.bottomStackContainer.backgroundColor = AXConstants.overlayForegroundColor
self.bottomStackContainer.delegate = self
self.addSubview(self.bottomStackContainer)
self.captionView.animateCaptionInfoChanges = true
if let captionView = self.captionView as? UIView {
self.bottomStackContainer.addSubview(captionView)
}
NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] (note) in
self?.setNeedsLayout()
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
open override func didMoveToWindow() {
super.didMoveToWindow()
#if os(iOS)
if self.window != nil {
self.updateToolbarBarButtonItems()
}
#endif
}
open override func layoutSubviews() {
super.layoutSubviews()
self.topStackContainer.contentInset = UIEdgeInsets(top: self.contentInset.top,
left: self.contentInset.left,
bottom: 0,
right: self.contentInset.right)
self.topStackContainer.frame = CGRect(origin: .zero, size: self.topStackContainer.sizeThatFits(self.frame.size))
self.bottomStackContainer.contentInset = UIEdgeInsets(top: 0,
left: self.contentInset.left,
bottom: self.contentInset.bottom,
right: self.contentInset.right)
let bottomStackSize = self.bottomStackContainer.sizeThatFits(self.frame.size)
self.bottomStackContainer.frame = CGRect(origin: CGPoint(x: 0, y: self.frame.size.height - bottomStackSize.height),
size: bottomStackSize)
self.isFirstLayout = false
}
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let view = super.hitTest(point, with: event) as? UIControl {
return view
}
return nil
}
// MARK: - Completions
func performAfterShowInterfaceCompletion(_ closure: @escaping () -> Void) {
self.showInterfaceCompletions.append(closure)
if !self.isShowInterfaceAnimating {
self.processShowInterfaceCompletions()
}
}
func processShowInterfaceCompletions() {
for completion in self.showInterfaceCompletions {
completion()
}
self.showInterfaceCompletions.removeAll()
}
// MARK: - Show / hide interface
func setShowInterface(_ show: Bool, animated: Bool, alongside closure: (() -> Void)? = nil, completion: ((Bool) -> Void)? = nil) {
let alpha: CGFloat = show ? 1 : 0
if abs(alpha - self.alpha) <= .ulpOfOne {
return
}
self.isShowInterfaceAnimating = true
if abs(alpha - 1) <= .ulpOfOne {
self.isHidden = false
}
let animations = { [weak self] in
self?.alpha = alpha
closure?()
}
let internalCompletion: (_ finished: Bool) -> Void = { [weak self] (finished) in
if abs(alpha) <= .ulpOfOne {
self?.isHidden = true
}
self?.isShowInterfaceAnimating = false
completion?(finished)
self?.processShowInterfaceCompletions()
}
if animated {
UIView.animate(withDuration: AXConstants.frameAnimDuration,
animations: animations,
completion: internalCompletion)
} else {
animations()
internalCompletion(true)
}
}
// MARK: - AXCaptionViewProtocol
func updateCaptionView(photo: AXPhotoProtocol) {
self.captionView.applyCaptionInfo(attributedTitle: photo.attributedTitle ?? nil,
attributedDescription: photo.attributedDescription ?? nil,
attributedCredit: photo.attributedCredit ?? nil)
if self.isFirstLayout {
self.setNeedsLayout()
return
}
let size = self.bottomStackContainer.sizeThatFits(self.frame.size)
let animations = { [weak self] in
guard let `self` = self else { return }
self.bottomStackContainer.frame = CGRect(origin: CGPoint(x: 0, y: self.frame.size.height - size.height), size: size)
self.bottomStackContainer.setNeedsLayout()
self.bottomStackContainer.layoutIfNeeded()
}
if self.animateCaptionViewChanges {
UIView.animate(withDuration: AXConstants.frameAnimDuration, animations: animations)
} else {
animations()
}
}
// MARK: - AXStackableViewContainerDelegate
func stackableViewContainer(_ stackableViewContainer: AXStackableViewContainer, didAddSubview: UIView) {
self.setNeedsLayout()
}
func stackableViewContainer(_ stackableViewContainer: AXStackableViewContainer, willRemoveSubview: UIView) {
DispatchQueue.main.async { [weak self] in
self?.setNeedsLayout()
}
}
#if os(iOS)
// MARK: - UIToolbar convenience
func updateToolbarBarButtonItems() {
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixedSpace.width = AXConstants.overlayBarButtonItemSpacing
var barButtonItems = [UIBarButtonItem]()
if let leftBarButtonItems = self.leftBarButtonItems {
let last = leftBarButtonItems.last
for barButtonItem in leftBarButtonItems {
barButtonItems.append(barButtonItem)
if barButtonItem != last {
barButtonItems.append(fixedSpace)
}
}
}
barButtonItems.append(flexibleSpace)
var centerBarButtonItem: UIBarButtonItem?
if let titleView = self.titleView as? UIView {
if let titleViewBarButtonItem = self.titleViewBarButtonItem, titleViewBarButtonItem.customView === titleView {
centerBarButtonItem = titleViewBarButtonItem
} else {
self.titleViewBarButtonItem = UIBarButtonItem(customView: titleView)
centerBarButtonItem = self.titleViewBarButtonItem
}
} else {
centerBarButtonItem = self.titleBarButtonItem
}
if let centerBarButtonItem = centerBarButtonItem {
barButtonItems.append(centerBarButtonItem)
barButtonItems.append(flexibleSpace)
}
if let rightBarButtonItems = self.rightBarButtonItems?.reversed() {
let last = rightBarButtonItems.last
for barButtonItem in rightBarButtonItems {
barButtonItems.append(barButtonItem)
if barButtonItem != last {
barButtonItems.append(fixedSpace)
}
}
}
self.toolbar.items = barButtonItems
}
func updateTitleBarButtonItem() {
func defaultAttributes() -> [NSAttributedString.Key: Any] {
let pointSize: CGFloat = 17.0
var font: UIFont
if #available(iOS 8.2, *) {
font = UIFont.systemFont(ofSize: pointSize, weight: UIFont.Weight.semibold)
} else {
font = UIFont(name: "HelveticaNeue-Medium", size: pointSize)!
}
return [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: UIColor.white
]
}
var attributedText: NSAttributedString?
if let title = self.title {
attributedText = NSAttributedString(string: title,
attributes: self.titleTextAttributes ?? defaultAttributes())
} else if let internalTitle = self.internalTitle {
attributedText = NSAttributedString(string: internalTitle,
attributes: self.titleTextAttributes ?? defaultAttributes())
}
if let attributedText = attributedText {
guard let titleBarButtonItemLabel = self.titleBarButtonItem.customView as? UILabel else { return }
if titleBarButtonItemLabel.attributedText != attributedText {
titleBarButtonItemLabel.attributedText = attributedText
titleBarButtonItemLabel.sizeToFit()
}
}
}
#endif
}
| d8a630272dae8eaf579d5c8cecd3074f | 37.167464 | 151 | 0.590259 | false | false | false | false |
evan-liu/FormationLayout | refs/heads/master | Documentation/Doc.playground/Sources/demo.swift | mit | 1 | import UIKit
public func createIcon() -> UIView {
return UIImageView(image: UIImage(named: "swift"))
}
public func createView(size: CGFloat = 100) -> UIView {
let view = UIView(frame: CGRect(x: 0, y: 0, width: size, height: size))
view.layer.backgroundColor = UIColor.white.cgColor
view.layer.borderColor = UIColor.lightGray.cgColor
view.layer.borderWidth = 0.2
return view
}
public func layoutView(view: UIView, size: CGFloat = 100) {
NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size).isActive = true
NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size).isActive = true
view.layoutIfNeeded()
}
public func demo(size: CGFloat = 100, block:(UIView, UIView) -> Void) -> UIView {
let view = createView(size: size)
block(view, createIcon())
layoutView(view: view, size: size)
return view
}
public func demo(size: CGFloat = 100, block: (UIView, UIView, UIView) -> Void) -> UIView {
let view = createView(size: size)
block(view, createIcon(), createIcon())
layoutView(view: view, size: size)
return view
}
public func demo(size: CGFloat = 100, block: (UIView, UIView, UIView, UIView) -> Void) -> UIView {
let view = createView(size: size)
block(view, createIcon(), createIcon(), createIcon())
layoutView(view: view, size: size)
return view
}
public func demo(size: CGFloat = 100, block: (UIView, UIView, UIView, UIView, UIView, UIView) -> Void) -> UIView {
let view = createView(size: size)
block(view, createIcon(), createIcon(), createIcon(), createIcon(), createIcon())
layoutView(view: view, size: size)
return view
}
| 88038c60fd18f9f24fa4248f57b15212 | 31.857143 | 161 | 0.672826 | false | false | false | false |
Shivol/Swift-CS333 | refs/heads/master | examples/uiKit/uiKitCatalog/UIKitCatalog/WebViewController.swift | mit | 3 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to use UIWebView.
*/
import UIKit
class WebViewController: UIViewController, UIWebViewDelegate, UITextFieldDelegate {
// MARK: - Properties
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var addressTextField: UITextField!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureWebView()
loadAddressURL()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
// MARK: - Convenience
func loadAddressURL() {
if let text = addressTextField.text, let requestURL = URL(string: text) {
let request = URLRequest(url: requestURL)
webView.loadRequest(request)
}
}
// MARK: - Configuration
func configureWebView() {
webView.backgroundColor = UIColor.white
webView.scalesPageToFit = true
webView.dataDetectorTypes = .all
}
// MARK: - UIWebViewDelegate
func webViewDidStartLoad(_ webView: UIWebView) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func webViewDidFinishLoad(_ webView: UIWebView) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
// Report the error inside the web view.
let localizedErrorMessage = NSLocalizedString("An error occured:", comment: "")
let errorHTML = "<!doctype html><html><body><div style=\"width: 100%%; text-align: center; font-size: 36pt;\">\(localizedErrorMessage) \(error.localizedDescription)</div></body></html>"
webView.loadHTMLString(errorHTML, baseURL: nil)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
// MARK: - UITextFieldDelegate
/// Dismisses the keyboard when the "Done" button is clicked.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
loadAddressURL()
return true
}
}
| 630277aea5a04311cd4b6e1848cf7ec4 | 27.592593 | 193 | 0.673143 | false | false | false | false |
JxbSir/JxbRefresh | refs/heads/master | JxbRefresh/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// JxbRefresh
//
// Created by Peter on 16/6/12.
// Copyright © 2016年 https://github.com/JxbSir. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let vc: ViewController = ViewController()
let nav: UINavigationController = UINavigationController.init(rootViewController: vc)
window = UIWindow.init(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.makeKey()
window?.becomeKey()
window?.rootViewController = nav
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 20a3bb19edca3ded9c6e862477f1f23d | 44.833333 | 285 | 0.736162 | false | false | false | false |
atl009/WordPress-iOS | refs/heads/develop | WordPress/Classes/Utility/WebViewControllerConfiguration.swift | gpl-2.0 | 1 | import UIKit
class WebViewControllerConfiguration: NSObject {
var url: URL
var optionsButton: UIBarButtonItem?
var secureInteraction: Bool = false
var addsWPComReferrer: Bool = false
var customTitle: String?
var authenticator: WebViewAuthenticator?
weak var navigationDelegate: WebNavigationDelegate?
init(url: URL) {
self.url = url
super.init()
}
func authenticate(blog: Blog) {
self.authenticator = WebViewAuthenticator(blog: blog)
}
func authenticate(account: WPAccount) {
self.authenticator = WebViewAuthenticator(account: account)
}
func authenticateWithDefaultAccount() {
let context = ContextManager.sharedInstance().mainContext
let service = AccountService(managedObjectContext: context)
guard let account = service.defaultWordPressComAccount() else {
return
}
authenticate(account: account)
}
}
| 6796e2b7d27a3fd35b90d43f33887b1f | 27.878788 | 71 | 0.685205 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/NewVersion/Community/ZSNotification.swift | mit | 1 | //
// ZSNotification.swift
// zhuishushenqi
//
// Created by yung on 2019/7/7.
// Copyright © 2019 QS. All rights reserved.
//
import UIKit
import HandyJSON
enum MsgType:String,HandyJSONEnum {
case none = ""
case postPush = "post_push"
case commentReply = "comment_reply"
case commentLike = "comment_like"
var image:UIImage? {
switch self {
case .postPush:
return UIImage(named: "personal_icon_topic_14_14_14x14_")
case .commentReply:
return UIImage(named: "personal_icon_reply_14_14_14x14_")
case .commentLike:
return UIImage(named: "personal_icon_reply_14_14_14x14_")
default:
return nil
}
}
}
struct ZSNotification:HandyJSON {
var _id:String = ""
var type:MsgType = .postPush
var post:ZSNotificationPost?
var title:String = ""
var trigger:ZSNotificationTrigger?
var comment:ZSNotificationComment?
var myComment:ZSNotificationMyComment?
var deleted:Bool = false
var created:String = ""
}
struct ZSNotificationPost:HandyJSON {
var _id:String = ""
var type:UserType = .normal
var title:String = ""
}
struct ZSNotificationTrigger:HandyJSON {
var _id:String = ""
var avatar:String = ""
var nickname:String = ""
var type:UserType = .normal
var lv:Int = 0
var gender:String = ""
}
struct ZSNotificationComment:HandyJSON {
var _id:String = ""
var content:String = ""
var floor:Int = 0
}
struct ZSNotificationMyComment:HandyJSON {
var _id:String = ""
var content:String = ""
}
//{
// "notifications": [{
// "_id": "5c9df5ba113ca53246a60349",
// "type": "post_push",
// "post": {
// "_id": "5c9df54461465a4c4605170a",
// "type": "normal",
// "title": "【好消息】追书喜提晋江,各路大神文应有尽有,万本精品同步更新中!"
// },
// "title": "【好消息】晋江掌阅好书来了!各路大神文应有尽有,万本精品同步更新中!",
// "trigger": null,
// "comment": null,
// "myComment": null,
// "deleted": false,
// "created": "2019-03-29T10:38:50.298Z"
// }, {
// "_id": "5c4151669cb008ec1e0a730d",
// "type": "comment_reply",
// "post": {
// "_id": "5c3fffd1b250154e3737ad54",
// "type": "normal",
// "title": "〔推书〕:读书人不得不看的三本优质网文!😉(含书评)"
// },
// "user": "57ac9879c12b61e826bd7221",
// "myComment": {
// "_id": "5c4130cc18dd9c1c65086261",
// "content": "可以\\n不错哟"
// },
// "comment": {
// "_id": "5c4151669cb008ec1e0a730c",
// "content": "谢谢💓",
// "floor": 26
// },
// "trigger": {
// "_id": "57d9fa98d466c43c346612bf",
// "avatar": "/avatar/5b/4c/5b4c8db957f7db769e251fff6681f68c",
// "nickname": "ઇGodfatherଓ",
// "type": "normal",
// "lv": 10,
// "gender": "female"
// },
// "deleted": false,
// "created": "2019-01-18T04:09:10.000Z"
// }, {
// "_id": "5be71c0b2b6cdd1000ef8bcc",
// "type": "comment_reply",
// "post": {
// "_id": "5be29607474e10bd576ec1e4",
// "type": "normal",
// "title": "随便画画"
// },
// "user": "57ac9879c12b61e826bd7221",
// "myComment": {
// "_id": "5be70b63d0074f1000171921",
// "content": "测试下评论,没有做超链接的展示"
// },
// "comment": {
// "_id": "5be71c0b2b6cdd1000ef8bcb",
// "content": "什么鬼◑▂◑◐▂◐",
// "floor": 24
// },
// "trigger": {
// "_id": "5addba11c127e26e7ef59051",
// "avatar": "/avatar/d0/ee/d0ee266d66821762d950a8096aaa8548",
// "nickname": "七月殇",
// "type": "normal",
// "lv": 7,
// "gender": "male"
// },
// "deleted": false,
// "created": "2018-11-10T17:57:31.000Z"
// }, {
// "_id": "5be4237d7ccde0c779bbbc6d",
// "type": "comment_reply",
// "post": {
// "_id": "5be29607474e10bd576ec1e4",
// "type": "normal",
// "title": "随便画画"
// },
// "user": "57ac9879c12b61e826bd7221",
// "myComment": {
// "_id": "5be41fa3acc7d9350a427903",
// "content": "试试"
// },
// "comment": {
// "_id": "5be4237d7ccde0c779bbbc6c",
// "content": "什么",
// "floor": 16
// },
// "trigger": {
// "_id": "5addba11c127e26e7ef59051",
// "avatar": "/avatar/d0/ee/d0ee266d66821762d950a8096aaa8548",
// "nickname": "七月殇",
// "type": "normal",
// "lv": 7,
// "gender": "male"
// },
// "deleted": false,
// "created": "2018-11-08T11:52:29.000Z"
// }, {
// "_id": "5bb1b0100e7abeaa7362fd86",
// "type": "post_push",
// "post": {
// "_id": "5baf14726f660bbe4fe5dc36",
// "type": "vote",
// "title": "【活动】🇨🇳国庆七天乐:红歌大比拼,更多活动豪礼砸不停~【楼层奖励名单已出】"
// },
// "title": "[有人@你]🇨🇳喜迎国庆🇨🇳追书七天福利送!最强攻略在这里!",
// "trigger": null,
// "comment": null,
// "myComment": null,
// "deleted": false,
// "created": "2018-10-01T05:26:40.131Z"
// }],
// "ok": true
//}
| 98f6aa0817afb7c7c1c23d39b5529699 | 24.413978 | 69 | 0.549609 | false | false | false | false |
banxi1988/BXCityPicker | refs/heads/master | Pod/Classes/CurrentCityHeaderView.swift | mit | 1 | //
// CurrentCityHeaderView.swift
// Pods
//
// Created by Haizhen Lee on 16/1/18.
//
//
import Foundation
// Build for target uimodel
//locale (None, None)
import UIKit
import SwiftyJSON
import BXModel
import PinAuto
// -CurrentCityHeaderView:v
// title[l15,y](f15,cdt)
open class CurrentCityHeaderView : UIView{
open let titleLabel = UILabel(frame:CGRect.zero)
open let contentLabel = UILabel(frame:CGRect.zero)
open lazy var divider:CAShapeLayer = {
let line = CAShapeLayer()
self.layer.addSublayer(line)
return line
}()
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
open override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
var allOutlets :[UIView]{
return [titleLabel,contentLabel]
}
var allUILabelOutlets :[UILabel]{
return [titleLabel,contentLabel]
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func commonInit(){
for childView in allOutlets{
addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
installConstaints()
setupAttrs()
}
func installConstaints(){
titleLabel.pa_centerY.install()
titleLabel.pa_leading.eq(15).install()
contentLabel.pa_after(titleLabel, offset: 15).install()
contentLabel.pa_trailing.eq(15).install()
contentLabel.pa_centerY.install()
contentLabel.setContentHuggingPriority(200, for: .horizontal)
}
func setupAttrs(){
titleLabel.textColor = UIColor(white: 0.6, alpha: 1.0)
titleLabel.font = UIFont.systemFont(ofSize: 15)
titleLabel.textAlignment = .left
titleLabel.text = "当前城市"
contentLabel.textColor = UIColor.darkText
contentLabel.font = UIFont.systemFont(ofSize: 15)
contentLabel.textAlignment = .left
contentLabel.text = "正在定位..."
divider.backgroundColor = UIColor(white: 0.937, alpha: 1.0).cgColor
}
open func updateContent(_ content:String){
contentLabel.text = content
}
open override func layoutSubviews() {
super.layoutSubviews()
divider.frame = bounds.divided(atDistance: 1, from: CGRectEdge.maxYEdge).slice.insetBy(dx: 10, dy: 0)
}
}
| 6e4a1dfcc19b06db260f60c5431bfe5e | 22.568421 | 105 | 0.6887 | false | false | false | false |
wikimedia/wikipedia-ios | refs/heads/main | WMF Framework/UIScrollView+Limits.swift | mit | 1 | import UIKit
extension UIScrollView {
private var topOffsetY: CGFloat {
return 0 - adjustedContentInset.top
}
public var bottomOffsetY: CGFloat {
return contentSize.height - bounds.size.height + adjustedContentInset.bottom
}
private var topOffset: CGPoint {
return CGPoint(x: contentOffset.x, y: topOffsetY)
}
private var bottomOffset: CGPoint {
return CGPoint(x: contentOffset.x, y: bottomOffsetY)
}
public var isAtTop: Bool {
// Rounded: Sometimes when we expect them to be equal, these are less than .2 different (due to rounding in earleir calculation) - and with multiple layout passes, it caused a large scrolling bug on a VC's launch.
return contentOffset.y.rounded(.up) <= topOffsetY.rounded(.up)
}
private var isAtBottom: Bool {
// Rounded: Sometimes when we expect them to be equal, these are less than .2 different (due to rounding in earleir calculation) - and with multiple layout passes, it caused a large scrolling bug on a VC's launch.
return contentOffset.y.rounded(.up) >= bottomOffsetY.rounded(.up)
}
public var verticalOffsetPercentage: CGFloat {
get {
let height = contentSize.height
guard height > 0 else {
return 0
}
return contentOffset.y / height
}
set {
let newOffsetY = contentSize.height * newValue
setContentOffset(CGPoint(x: contentOffset.x, y: newOffsetY), animated: false)
}
}
@objc(wmf_setContentInset:verticalScrollIndicatorInsets:preserveContentOffset:preserveAnimation:)
public func setContentInset(_ updatedContentInset: UIEdgeInsets, verticalScrollIndicatorInsets updatedVerticalScrollIndicatorInsets: UIEdgeInsets, preserveContentOffset: Bool = true, preserveAnimation: Bool = false) -> Bool {
guard updatedContentInset != contentInset || updatedVerticalScrollIndicatorInsets != verticalScrollIndicatorInsets else {
return false
}
let wasAtTop = isAtTop
let wasAtBottom = isAtBottom
verticalScrollIndicatorInsets = updatedVerticalScrollIndicatorInsets
if preserveAnimation {
contentInset = updatedContentInset
} else {
let wereAnimationsEnabled = UIView.areAnimationsEnabled
UIView.setAnimationsEnabled(false)
contentInset = updatedContentInset
UIView.setAnimationsEnabled(wereAnimationsEnabled)
}
guard preserveContentOffset else {
return true
}
if wasAtTop {
contentOffset = topOffset
} else if contentSize.height > bounds.inset(by: adjustedContentInset).height && wasAtBottom {
contentOffset = bottomOffset
}
return true
}
}
| cfc811c3d665d4a5dc69b24a1cd92c29 | 37.905405 | 229 | 0.663425 | false | false | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART | refs/heads/master | bluefruitconnect/Platform/iOS/Controllers/PeripheralDetails/PeripheralDetailsViewController.swift | mit | 1 | //
// PeripheralDetailsViewController.swift
// Bluefruit Connect
//
// Created by Antonio García on 06/02/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import UIKit
class PeripheralDetailsViewController: ScrollingTabBarViewController {
var selectedBlePeripheral : BlePeripheral?
private var isObservingBle = false
private var emptyViewController : EmptyDetailsViewController!
private let firmwareUpdater = FirmwareUpdater()
private var dfuTabIndex = -1
override func viewDidLoad() {
super.viewDidLoad()
if let splitViewController = self.splitViewController {
navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
navigationItem.leftItemsSupplementBackButton = true
}
emptyViewController = storyboard!.instantiateViewControllerWithIdentifier("EmptyDetailsViewController") as! EmptyDetailsViewController
if selectedBlePeripheral != nil {
didConnectToPeripheral()
}
else {
let isFullScreen = UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact
if !isFullScreen {
showEmpty(true)
self.emptyViewController.setConnecting(false)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let isFullScreen = UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact
guard !isFullScreen || selectedBlePeripheral != nil else {
DLog("detail: peripheral disconnected by viewWillAppear. Abort")
return;
}
// Subscribe to Ble Notifications
let notificationCenter = NSNotificationCenter.defaultCenter()
if !isFullScreen { // For compact mode, the connection is managed by the peripheral list
notificationCenter.addObserver(self, selector: #selector(willConnectToPeripheral(_:)), name: BleManager.BleNotifications.WillConnectToPeripheral.rawValue, object: nil)
notificationCenter.addObserver(self, selector: #selector(didConnectToPeripheral(_:)), name: BleManager.BleNotifications.DidConnectToPeripheral.rawValue, object: nil)
}
notificationCenter.addObserver(self, selector: #selector(willDisconnectFromPeripheral(_:)), name: BleManager.BleNotifications.WillDisconnectFromPeripheral.rawValue, object: nil)
notificationCenter.addObserver(self, selector: #selector(didDisconnectFromPeripheral(_:)), name: BleManager.BleNotifications.DidDisconnectFromPeripheral.rawValue, object: nil)
isObservingBle = true
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if isObservingBle {
let notificationCenter = NSNotificationCenter.defaultCenter()
let isFullScreen = UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact
if !isFullScreen {
notificationCenter.removeObserver(self, name: BleManager.BleNotifications.WillConnectToPeripheral.rawValue, object: nil)
notificationCenter.removeObserver(self, name: BleManager.BleNotifications.DidConnectToPeripheral.rawValue, object: nil)
}
notificationCenter.removeObserver(self, name: BleManager.BleNotifications.WillDisconnectFromPeripheral.rawValue, object: nil)
notificationCenter.removeObserver(self, name: BleManager.BleNotifications.DidDisconnectFromPeripheral.rawValue, object: nil)
isObservingBle = false
}
}
func willConnectToPeripheral(notification : NSNotification) {
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
self.showEmpty(true)
self.emptyViewController.setConnecting(true)
})
}
func didConnectToPeripheral(notification : NSNotification) {
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
self.didConnectToPeripheral()
})
}
func didConnectToPeripheral() {
guard BleManager.sharedInstance.blePeripheralConnected != nil else {
DLog("Warning: didConnectToPeripheral with empty blePeripheralConnected");
return
}
let blePeripheral = BleManager.sharedInstance.blePeripheralConnected!
blePeripheral.peripheral.delegate = self
// UI
self.showEmpty(false)
startUpdatesCheck()
}
private func setupConnectedPeripheral() {
// UI: Add Info tab
let infoViewController = self.storyboard!.instantiateViewControllerWithIdentifier("InfoModuleViewController") as! InfoModuleViewController
infoViewController.onServicesDiscovered = { [weak self] in
// optimization: wait till info discover services to continue, instead of discovering services by myself
self?.servicesDiscovered()
}
let localizationManager = LocalizationManager.sharedInstance
infoViewController.tabBarItem.title = localizationManager.localizedString("info_tab_title") // Tab title
infoViewController.tabBarItem.image = UIImage(named: "tab_info_icon")
setViewControllers([infoViewController], animated: false)
selectedIndex = 0
}
func willDisconnectFromPeripheral(notification : NSNotification) {
DLog("detail: peripheral willDisconnect")
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
let isFullScreen = UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact
if isFullScreen { // executed when bluetooth is stopped
// Back to peripheral list
if let parentNavigationController = (self.navigationController?.parentViewController as? UINavigationController) {
parentNavigationController.popToRootViewControllerAnimated(true)
}
}
else {
self.showEmpty(true)
self.emptyViewController.setConnecting(false)
}
//self.cancelRssiTimer()
})
let blePeripheral = BleManager.sharedInstance.blePeripheralConnected
blePeripheral?.peripheral.delegate = nil
}
func didDisconnectFromPeripheral(notification : NSNotification) {
let isFullScreen = UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
DLog("detail: disconnection")
if !isFullScreen {
DLog("detail: show empty")
self.showEmpty(true)
self.emptyViewController.setConnecting(false)
}
// Show disconnected alert (if no previous alert is shown)
if self.presentedViewController == nil {
let localizationManager = LocalizationManager.sharedInstance
let alertController = UIAlertController(title: nil, message: localizationManager.localizedString("peripherallist_peripheraldisconnected"), preferredStyle: .Alert)
let okAction = UIAlertAction(title: localizationManager.localizedString("dialog_ok"), style: .Default, handler: { (_) -> Void in
let isFullScreen = UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact
if isFullScreen {
self.goBackToPeripheralList()
}
})
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
else {
DLog("disconnection detected but cannot go to periperalList because there is a presentedViewController on screen")
}
})
}
private func goBackToPeripheralList() {
// Back to peripheral list
if let parentNavigationController = (self.navigationController?.parentViewController as? UINavigationController) {
parentNavigationController.popToRootViewControllerAnimated(true)
}
}
func showEmpty(showEmpty : Bool) {
hideTabBar(showEmpty)
if showEmpty {
// Show empty view (if needed)
if viewControllers?.count != 1 || viewControllers?.first != emptyViewController {
viewControllers = [emptyViewController]
}
emptyViewController.startAnimating()
}
else {
emptyViewController.stopAnimating()
}
}
func servicesDiscovered() {
DLog("PeripheralDetailsViewController servicesDiscovered")
if let blePeripheral = BleManager.sharedInstance.blePeripheralConnected {
if let services = blePeripheral.peripheral.services {
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
let localizationManager = LocalizationManager.sharedInstance
// Uart Modules
let hasUart = blePeripheral.hasUart()
var viewControllersToAppend: [UIViewController] = []
if (hasUart) {
// Uart Tab
if Config.isUartModuleEnabled {
let uartViewController = self.storyboard!.instantiateViewControllerWithIdentifier("UartModuleViewController") as! UartModuleViewController
uartViewController.tabBarItem.title = localizationManager.localizedString("uart_tab_title") // Tab title
uartViewController.tabBarItem.image = UIImage(named: "tab_uart_icon")
viewControllersToAppend.append(uartViewController)
}
// PinIO
if Config.isPinIOModuleEnabled {
let pinioViewController = self.storyboard!.instantiateViewControllerWithIdentifier("PinIOModuleViewController") as! PinIOModuleViewController
pinioViewController.tabBarItem.title = localizationManager.localizedString("pinio_tab_title") // Tab title
pinioViewController.tabBarItem.image = UIImage(named: "tab_pinio_icon")
viewControllersToAppend.append(pinioViewController)
}
// Controller Tab
if Config.isControllerModuleEnabled {
let controllerViewController = self.storyboard!.instantiateViewControllerWithIdentifier("ControllerModuleViewController") as! ControllerModuleViewController
controllerViewController.tabBarItem.title = localizationManager.localizedString("controller_tab_title") // Tab title
controllerViewController.tabBarItem.image = UIImage(named: "tab_controller_icon")
viewControllersToAppend.append(controllerViewController)
}
}
// DFU Tab
let kNordicDeviceFirmwareUpdateService = "00001530-1212-EFDE-1523-785FEABCD123" // DFU service UUID
let hasDFU = services.contains({ (service : CBService) -> Bool in
service.UUID.isEqual(CBUUID(string: kNordicDeviceFirmwareUpdateService))
})
if Config.isNeoPixelModuleEnabled && hasUart && hasDFU { // Neopixel is not available on old boards (those without DFU)
// Neopixel Tab
let neopixelsViewController = self.storyboard!.instantiateViewControllerWithIdentifier("NeopixelModuleViewController") as! NeopixelModuleViewController
neopixelsViewController.tabBarItem.title = localizationManager.localizedString("neopixels_tab_title") // Tab title
neopixelsViewController.tabBarItem.image = UIImage(named: "tab_neopixel_icon")
viewControllersToAppend.append(neopixelsViewController)
}
if (hasDFU) {
if Config.isDfuModuleEnabled {
let dfuViewController = self.storyboard!.instantiateViewControllerWithIdentifier("DfuModuleViewController") as! DfuModuleViewController
dfuViewController.tabBarItem.title = localizationManager.localizedString("dfu_tab_title") // Tab title
dfuViewController.tabBarItem.image = UIImage(named: "tab_dfu_icon")
viewControllersToAppend.append(dfuViewController)
self.dfuTabIndex = viewControllersToAppend.count // don't -1 because index is always present and adds 1 to the index
}
}
// Add tabs
if self.viewControllers != nil {
let numViewControllers = self.viewControllers!.count
if numViewControllers > 1 { // if we already have viewcontrollers, remove all except info (to avoud duplicates)
self.viewControllers!.removeRange(Range(1..<numViewControllers))
}
// Append viewcontrollers (do it here all together to avoid deleting/creating addchilviewcontrollers)
if viewControllersToAppend.count > 0 {
self.viewControllers!.appendContentsOf(viewControllersToAppend)
}
}
})
}
}
}
private func startUpdatesCheck() {
// Refresh updates available
if let blePeripheral = BleManager.sharedInstance.blePeripheralConnected {
let releases = FirmwareUpdater.releasesWithBetaVersions(Preferences.showBetaVersions)
firmwareUpdater.checkUpdatesForPeripheral(blePeripheral.peripheral, delegate: self, shouldDiscoverServices: true, releases: releases, shouldRecommendBetaReleases: false)
}
}
func updateRssiUI() {
/*
if let blePeripheral = BleManager.sharedInstance.blePeripheralConnected {
let rssi = blePeripheral.rssi
//DLog("rssi: \(rssi)")
infoRssiLabel.stringValue = String.format(LocalizationManager.sharedInstance.localizedString("peripheraldetails_rssi_format"), rssi) // "\(rssi) dBm"
infoRssiImageView.image = signalImageForRssi(rssi)
}
*/
}
private func showUpdateAvailableForRelease(latestRelease: FirmwareInfo!) {
let alert = UIAlertController(title:"Update available", message: "Software version \(latestRelease.version) is available", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Go to updates", style: UIAlertActionStyle.Default, handler: { [unowned self] _ in
self.selectedIndex = self.dfuTabIndex
}))
alert.addAction(UIAlertAction(title: "Ask later", style: UIAlertActionStyle.Default, handler: { _ in
}))
alert.addAction(UIAlertAction(title: "Ignore", style: UIAlertActionStyle.Cancel, handler: { _ in
Preferences.softwareUpdateIgnoredVersion = latestRelease.version
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
// MARK: - CBPeripheralDelegate
extension PeripheralDetailsViewController : CBPeripheralDelegate {
// Send peripheral delegate methods to tab active (each tab will handle these methods)
func peripheralDidUpdateName(peripheral: CBPeripheral) {
if let viewControllers = viewControllers {
for tabViewController in viewControllers {
(tabViewController as? CBPeripheralDelegate)?.peripheralDidUpdateName?(peripheral)
}
}
}
func peripheral(peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
if let viewControllers = viewControllers {
for tabViewController in viewControllers {
(tabViewController as? CBPeripheralDelegate)?.peripheral?(peripheral, didModifyServices: invalidatedServices)
}
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
if let viewControllers = viewControllers {
for var tabViewController in viewControllers {
if let childViewController = (tabViewController as? UINavigationController)?.viewControllers.last {
tabViewController = childViewController
}
(tabViewController as? CBPeripheralDelegate)?.peripheral?(peripheral, didDiscoverServices: error)
}
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
if let viewControllers = viewControllers {
for var tabViewController in viewControllers {
if let childViewController = (tabViewController as? UINavigationController)?.viewControllers.last {
tabViewController = childViewController
}
(tabViewController as? CBPeripheralDelegate)?.peripheral?(peripheral, didDiscoverCharacteristicsForService: service, error: error)
}
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverDescriptorsForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
if let viewControllers = viewControllers {
for var tabViewController in viewControllers {
if let childViewController = (tabViewController as? UINavigationController)?.viewControllers.last {
tabViewController = childViewController
}
(tabViewController as? CBPeripheralDelegate)?.peripheral?(peripheral, didDiscoverDescriptorsForCharacteristic: characteristic, error: error)
}
}
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
if let viewControllers = viewControllers {
for var tabViewController in viewControllers {
if let childViewController = (tabViewController as? UINavigationController)?.viewControllers.last {
tabViewController = childViewController
}
(tabViewController as? CBPeripheralDelegate)?.peripheral?(peripheral, didUpdateValueForCharacteristic: characteristic, error: error)
}
}
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForDescriptor descriptor: CBDescriptor, error: NSError?) {
if let viewControllers = viewControllers {
for var tabViewController in viewControllers {
if let childViewController = (tabViewController as? UINavigationController)?.viewControllers.last {
tabViewController = childViewController
}
(tabViewController as? CBPeripheralDelegate)?.peripheral?(peripheral, didUpdateValueForDescriptor: descriptor, error: error)
}
}
}
func peripheral(peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: NSError?) {
// Update peripheral rssi
let identifierString = peripheral.identifier.UUIDString
if let existingPeripheral = BleManager.sharedInstance.blePeripherals()[identifierString] {
existingPeripheral.rssi = RSSI.integerValue
// DLog("received rssi for \(existingPeripheral.name): \(rssi)")
// Update UI
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
self.updateRssiUI()
})
if let viewControllers = viewControllers {
for var tabViewController in viewControllers {
if let childViewController = (tabViewController as? UINavigationController)?.viewControllers.last {
tabViewController = childViewController
}
(tabViewController as? CBPeripheralDelegate)?.peripheral?(peripheral, didReadRSSI: RSSI, error: error)
}
}
}
}
}
// MARK: - FirmwareUpdaterDelegate
extension PeripheralDetailsViewController: FirmwareUpdaterDelegate {
func onFirmwareUpdatesAvailable(isUpdateAvailable: Bool, latestRelease: FirmwareInfo!, deviceInfoData: DeviceInfoData?, allReleases: [NSObject : AnyObject]?) {
DLog("FirmwareUpdaterDelegate isUpdateAvailable: \(isUpdateAvailable)")
dispatch_async(dispatch_get_main_queue(),{ [weak self] in
if let context = self {
context.setupConnectedPeripheral()
if isUpdateAvailable {
self?.showUpdateAvailableForRelease(latestRelease)
}
}
})
}
func onDfuServiceNotFound() {
DLog("FirmwareUpdaterDelegate: onDfuServiceNotFound")
dispatch_async(dispatch_get_main_queue(),{ [weak self] in
self?.setupConnectedPeripheral()
})
}
private func onUpdateDialogError(errorMessage:String, exitOnDismiss: Bool = false) {
DLog("FirmwareUpdaterDelegate: onUpdateDialogError")
}
}
| 127606f126f430f96b732ff3e511ba98 | 46.536842 | 185 | 0.619885 | false | false | false | false |
sivu22/AnyTracker | refs/heads/master | AnyTracker/ItemJournal.swift | mit | 1 | //
// ItemJournal.swift
// AnyTracker
//
// Created by Cristian Sava on 07/10/16.
// Copyright © 2016 Cristian Sava. All rights reserved.
//
import Foundation
class ItemJournal: Item, ItemTypeJournal {
var version: String = App.version
var name: String = ""
var ID: String = ""
var description: String = ""
fileprivate(set) var type: ItemType = ItemType.journal
var useDate: Bool = false
var startDate: Date
var endDate: Date
fileprivate(set) var entries: [Entry] = []
required init() {
self.startDate = Date()
self.endDate = self.startDate
}
convenience init(withName name: String, ID: String, description: String, useDate: Bool, startDate: Date, endDate: Date, sum: Double = 0, entries: [Entry] = []) {
self.init()
initItem(withName: name, ID: ID, description: description, useDate: useDate, startDate: startDate, endDate: endDate)
self.entries = entries
}
func isEmpty() -> Bool {
return entries.count == 0
}
func toString() -> String? {
return toJSONString()
}
func insert(entry: Entry, completionHandler: @escaping (Status?) -> Void) {
entries.insert(entry, at: 0)
DispatchQueue.global().async {
var completionError: Status?
do {
try self.saveToFile()
} catch {
self.entries.removeFirst()
if let statusError = error as? Status {
completionError = statusError
} else {
completionError = Status.errorDefault
}
}
DispatchQueue.main.async {
completionHandler(completionError)
}
}
}
func remove(atIndex index: Int, completionHandler: @escaping (Status?) -> Void) {
if index < 0 || index >= entries.count {
completionHandler(Status.errorIndex)
return
}
let deleted = Entry(name: entries[index].name, value: entries[index].value)
entries.remove(at: index)
DispatchQueue.global().async {
var completionError: Status?
do {
try self.saveToFile()
} catch {
self.entries.append(deleted)
if let statusError = error as? Status {
completionError = statusError
} else {
completionError = Status.errorDefault
}
}
DispatchQueue.main.async {
completionHandler(completionError)
}
}
}
func updateEntry(atIndex index: Int, newName name: String, newValue value: Date, completionHandler: @escaping (Status?) -> Void) {
if index < 0 || index >= entries.count {
completionHandler(Status.errorIndex)
return
}
if entries[index].name == name && entries[index].value == value {
return
}
let old = Entry(name: entries[index].name, value: entries[index].value)
let new = Entry(name: name, value: value)
entries[index] = new
DispatchQueue.global().async {
var completionError: Status?
do {
try self.saveToFile()
} catch {
self.entries[index] = old
if let statusError = error as? Status {
completionError = statusError
} else {
completionError = Status.errorDefault
}
}
DispatchQueue.main.async {
completionHandler(completionError)
}
}
}
func exchangeEntry(fromIndex src: Int, toIndex dst: Int) {
if src < 0 || dst < 0 || src >= entries.count || dst >= entries.count {
return
}
entries.swapAt(src, dst)
}
// MARK: -
}
extension ItemJournal: JSON {
// MARK: JSON Protocol
func toJSONString() -> String? {
var dict: JSONDictionary = getItemAsJSONDictionary()
var arrayEntries: JSONArray = []
for entry in entries {
var dictEntry: JSONDictionary = [:]
dictEntry["name"] = entry.name as JSONObject?
dictEntry["value"] = Utils.timeFromDate(entry.value) as JSONObject?
arrayEntries.append(dictEntry as JSONObject)
}
dict["entries"] = arrayEntries as JSONObject?
let jsonString = Utils.getJSONFromObject(dict as JSONObject?)
Utils.debugLog("Serialized journal item to JSON string \(String(describing: jsonString))")
return jsonString
}
static func fromJSONString(_ input: String?) -> ItemJournal? {
guard let (dict, version, name, ID, description, type, useDate, startDate, endDate) = getItemFromJSONDictionary(input) else {
return nil
}
Utils.debugLog(input!)
if type != ItemType.journal.rawValue {
Utils.debugLog("Item is not of type journal")
return nil
}
guard let entriesArray = dict["entries"] as? [AnyObject] else {
Utils.debugLog("Item entries are invalid")
return nil
}
var entries: [Entry] = []
for entryObject in entriesArray {
if let name = entryObject["name"] as? String, let value = Utils.dateFromTime(entryObject["value"] as? String) {
let entry = Entry(name: name, value: value)
entries.append(entry)
Utils.debugLog(entry.name + " " + Utils.stringFrom(date: entry.value, longFormat: false))
}
}
let itemJournal = ItemJournal(withName: name, ID: ID, description: description, useDate: useDate, startDate: startDate, endDate: endDate, entries: entries)
if !itemJournal.setVersion(version) {
return nil
}
return itemJournal
}
}
| e6cbff89ad1f2d14d3b5f9ee1450cb87 | 31.335079 | 165 | 0.540641 | false | false | false | false |
alloy/realm-cocoa | refs/heads/master | examples/ios/swift/Encryption/AppDelegate.swift | apache-2.0 | 2 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import UIKit
import Realm
class StringObject: RLMObject {
dynamic var stringProp = ""
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = UIViewController()
self.window!.makeKeyAndVisible()
// Realms are used to group data together
let realm = RLMRealm.defaultRealm() // Create realm pointing to default file
// Encrypt realm file
var error: NSError?
let success = NSFileManager.defaultManager().setAttributes([NSFileProtectionKey: NSFileProtectionComplete],
ofItemAtPath: RLMRealm.defaultRealm().path, error: &error)
if !success {
println("encryption attribute was not successfully set on realm file")
println("error: \(error?.localizedDescription)")
}
// Save your object
realm.transactionWithBlock() {
let obj = StringObject()
obj.stringProp = "abcd"
realm.addObject(obj)
}
// Read all string objects from the encrypted realm
println("all string objects: \(StringObject.allObjects())")
return true
}
}
| 6c39f4d6e5f186571af29a7a779d290a | 33.934426 | 118 | 0.635852 | false | false | false | false |
boxenjim/SwiftyFaker | refs/heads/master | SwiftyFaker/faker/Business.swift | mit | 1 | //
// Business.swift
// SwiftyFaker
//
// Created by Jim Schultz on 9/18/15.
// Copyright © 2015 Jim Schultz. All rights reserved.
//
import Foundation
extension Faker {
open class Business: Faker {
fileprivate var credit_card_numbers: [String]?
fileprivate var credit_card_types: [String]?
// MARK: NSKeyValueCoding
open override func setValue(_ value: Any?, forKey key: String) {
if key == "credit_card_numbers" {
credit_card_numbers = value as? [String]
} else if key == "credit_card_types" {
credit_card_types = value as? [String]
} else {
super.setValue(value, forKey: key)
}
}
fileprivate static let _business = Business(dictionary: Faker.JSON("business"))
// MARK: Methods
open static func creditCardNumber() -> String {
guard let numbers = _business.credit_card_numbers else { return "" }
return numbers.random()
}
open static func creditCardExpiry() -> Foundation.Date {
let normalizedNow = Calendar.current.startOfDay(for: Foundation.Date())
guard let expiry = (Calendar.current as NSCalendar).date(byAdding: NSCalendar.Unit.year, value: Int.random(1..<5), to: normalizedNow, options: NSCalendar.Options()) else { return Foundation.Date() }
return expiry
}
open static func creditCardType() -> String {
guard let types = _business.credit_card_types else { return "" }
return types.random()
}
}
}
| 06abc2ea36962a8382d9623b6653912d | 34.847826 | 210 | 0.579745 | false | false | false | false |
DingSoung/CCExtension | refs/heads/main | Sources/UIKit/UIResponder+Keyboard.swift | mit | 2 | // Created by Songwen on 2018/11/14.
// Copyright © 2018 DingSoung. All rights reserved.
#if canImport(UIKit) && os(iOS)
import UIKit
extension UIResponder {
@objc(UIResponderKeyboardInfo)
@objcMembers
public final class Keyboard: NSObject {
public var duration: TimeInterval = 0
// internal status
fileprivate var frameBegin = CGRect.zero
fileprivate var frameEnd = CGRect.zero
fileprivate var curve: UInt = 0
// singleton
public static let shared = Keyboard()
private override init() {
super.init()
}
deinit {
invalid()
}
}
}
extension UIResponder.Keyboard {
public var frame: CGRect {
return frameEnd
}
}
extension UIResponder.Keyboard {
@objc
public enum Action: Int {
case hide = 0
case show = 1
}
public var action: Action {
return frameEnd.maxY > UIScreen.main.bounds.maxY ? .hide : .show
}
}
extension UIResponder.Keyboard {
public var option: View.AnimationOptions {
return View.AnimationOptions.init(rawValue: curve << 16)
}
}
extension UIResponder.Keyboard {
private static let association = Association<NSMapTable<NSString, AnyObject>>()
fileprivate var blocks: NSMapTable<NSString, AnyObject> {
if let blocks = UIResponder.Keyboard.association[self] {
return blocks
} else {
let blocks = NSMapTable<NSString, AnyObject>(keyOptions: .weakMemory, valueOptions: .weakMemory)
UIResponder.Keyboard.association[self] = blocks
return blocks
}
}
public func addObserve(uid: String, updateBlock: @escaping UpdateBlock) {
let object = unsafeBitCast(updateBlock, to: AnyObject.self)
blocks.setObject(object, forKey: uid as NSString)
}
public func removeObserve(uid: String) {
blocks.removeObject(forKey: uid as NSString)
}
}
extension UIResponder.Keyboard {
/// active
public func active() {
[UIResponder.keyboardWillChangeFrameNotification].forEach { (name) in
NotificationCenter.default.addObserver(self,
selector: #selector(updateKeyboardInfo(notification:)),
name: name,
object: nil)
}
}
/// invalid
public func invalid() {
[UIResponder.keyboardWillChangeFrameNotification].forEach { (name) in
NotificationCenter.default.removeObserver(self, name: name, object: nil)
}
}
}
extension UIResponder.Keyboard {
public typealias UpdateBlock = @convention(block) (UIResponder.Keyboard) -> Void
// MARK: - Notification
@objc
private func updateKeyboardInfo(notification: Notification) {
guard let frameBegin = notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? CGRect,
let frameEnd = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval,
let curve = notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt
else { return }
self.frameBegin = frameBegin
self.frameEnd = frameEnd
self.duration = duration
self.curve = curve
let enumerator = blocks.objectEnumerator()
while let object: AnyObject = enumerator?.nextObject() as AnyObject? {
let block = unsafeBitCast(object, to: UpdateBlock.self)
block(self)
}
}
}
extension UIResponder {
@objc
public var keyboardUpdateBlock: Keyboard.UpdateBlock? {
set {
if let newValue = newValue {
Keyboard.shared.addObserve(uid: hashValue.description, updateBlock: newValue)
} else {
Keyboard.shared.removeObserve(uid: hashValue.description)
}
if Keyboard.shared.blocks.count > 0 {
Keyboard.shared.active()
} else {
Keyboard.shared.invalid()
}
}
get {
let object = Keyboard.shared.blocks.object(forKey: hashValue.description as NSString)
return unsafeBitCast(object, to: Keyboard.UpdateBlock.self)
}
}
}
#endif
| d4313b2aa142b055ad08a2f2915809ef | 32.428571 | 117 | 0.619658 | false | false | false | false |
mltbnz/pixelsynth | refs/heads/develop | pixelsynth/ImageFactory.swift | mit | 1 | //
// ImageUtil.swift
// pixelsynth
//
// Created by Malte Bünz on 22.04.17.
// Copyright © 2017 Malte Bünz. All rights reserved.
//
import Foundation
import AVFoundation
import UIKit
import MetalKit
struct ImageFactory {
// Connection to the openCV wrapper class
private let openCVWrapper: OpenCVWrapper = OpenCVWrapper()
// TODO: Observable
private var greyScaleMode: Bool = true
/**
Converts a sampleBuffer into an UIImage
- parameter sampleBuffer:The input samplebuffer
*/
public func image(from sampleBuffer: CMSampleBuffer) -> UIImage? {
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil }
let ciImage = CIImage(cvPixelBuffer: imageBuffer)
let context = CIContext()
guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { return nil }
let image = UIImage(cgImage: cgImage)
guard greyScaleMode == false else {
let greyScaleImage = OpenCVWrapper.convert2GreyscaleImage(image)
return greyScaleImage
}
return image
}
/**
Returns an array holding the brightness values of a line at the center of the screen in 1D array
- parameter image: The input image
*/
public func imageBrightnessValues(from image: UIImage) -> Array<UInt8>? {
// convert uiimage to cv::Mat
let values = OpenCVWrapper.getPixelLineBrightntessValues(image)
return values as? Array<UInt8>
}
}
| e83cf9c9c5672f35587fdd67c56d6529 | 30.75 | 101 | 0.676509 | false | false | false | false |
aiwalle/LiveProject | refs/heads/master | GYJTV/Pods/ProtocolBuffers-Swift/Source/GeneratedMessage.swift | mit | 4 | // Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public protocol GeneratedMessageProtocol: ProtocolBuffersMessage {
associatedtype BuilderType:GeneratedMessageBuilderProtocol
static func parseFrom(data: Data) throws -> Self
static func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> Self
static func parseFrom(inputStream:InputStream) throws -> Self
static func parseFrom(inputStream:InputStream, extensionRegistry:ExtensionRegistry) throws -> Self
static func parseFrom(codedInputStream:CodedInputStream) throws -> Self
static func parseFrom(codedInputStream:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Self
subscript(key: String) -> Any? { get }
}
public protocol GeneratedEnum:RawRepresentable, CustomDebugStringConvertible, CustomStringConvertible, Hashable {
func toString() -> String
static func fromString(_ str:String) throws -> Self
}
public protocol GeneratedMessageBuilderProtocol: ProtocolBuffersMessageBuilder {
subscript(key: String) -> Any? { get set }
}
open class GeneratedMessage:AbstractProtocolBuffersMessage
{
public var memoizedSerializedSize:Int32 = -1
required public init()
{
super.init()
self.unknownFields = UnknownFieldSet(fields: [:])
}
//Override
open class func className() -> String
{
return "GeneratedMessage"
}
open func className() -> String
{
return "GeneratedMessage"
}
open override class func classBuilder() -> ProtocolBuffersMessageBuilder
{
return GeneratedMessageBuilder()
}
open override func classBuilder() -> ProtocolBuffersMessageBuilder
{
return GeneratedMessageBuilder()
}
//
}
open class GeneratedMessageBuilder:AbstractProtocolBuffersMessageBuilder
{
open var internalGetResult:GeneratedMessage
{
get
{
return GeneratedMessage()
}
}
override open var unknownFields:UnknownFieldSet
{
get
{
return internalGetResult.unknownFields
}
set (fields)
{
internalGetResult.unknownFields = fields
}
}
public func checkInitialized() throws
{
let result = internalGetResult
guard result.isInitialized() else
{
throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message")
}
}
public func checkInitializedParsed() throws
{
let result = internalGetResult
guard result.isInitialized() else
{
throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message")
}
}
override open func isInitialized() -> Bool
{
return internalGetResult.isInitialized()
}
@discardableResult
override open func merge(unknownField: UnknownFieldSet) throws -> Self
{
let result:GeneratedMessage = internalGetResult
result.unknownFields = try UnknownFieldSet.builderWithUnknownFields(copyFrom: result.unknownFields).merge(unknownFields: unknownField).build()
return self
}
public func parse(codedInputStream:CodedInputStream ,unknownFields:UnknownFieldSet.Builder, extensionRegistry:ExtensionRegistry, tag:Int32) throws -> Bool {
return try unknownFields.mergeFieldFrom(tag: tag, input:codedInputStream)
}
}
extension GeneratedMessage:CustomDebugStringConvertible {
public var debugDescription:String {
return description
}
}
extension GeneratedMessage:CustomStringConvertible {
public var description:String {
get {
var output:String = ""
output += try! getDescription(indent: "")
return output
}
}
}
extension GeneratedMessageBuilder:CustomDebugStringConvertible {
public var debugDescription:String {
return internalGetResult.description
}
}
extension GeneratedMessageBuilder:CustomStringConvertible {
public var description:String {
get {
return internalGetResult.description
}
}
}
| b0f11f208947944d328678e3806a0b3d | 29.525641 | 160 | 0.695716 | false | false | false | false |
tnako/Challenge_ios | refs/heads/master | Challenge/ProfileController.swift | gpl-3.0 | 1 | //
// SecondViewController.swift
// Challenge
//
// Created by Anton Korshikov on 25.09.15.
// Copyright © 2015 Anton Korshikov. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class ProfileController: UIViewController, FBSDKLoginButtonDelegate {
@IBOutlet var imageURL: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let loginButton = FBSDKLoginButton();
loginButton.readPermissions = ["public_profile", "email", "user_friends"];
loginButton.center = self.view.center;
loginButton.delegate = self;
self.view.addSubview(loginButton);
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "name, email, friends, id, birthday, picture, gender"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
print("fetched user: \(result)")
let pictureDict = result.objectForKey("picture") as! NSDictionary
let pictureData = pictureDict.objectForKey("data") as! NSDictionary
let pictureURL = pictureData.objectForKey("url") as! String
print("picture.data.url: \(pictureURL)")
if let url = NSURL(string: pictureURL) {
if let data = NSData(contentsOfURL: url){
self.imageURL.image = UIImage(data: data)
}
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if (error != nil) {
print("Login error: \(error.localizedDescription)")
} else {
//ToDo: save data to server
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
self.performSegueWithIdentifier("Logout", sender: self);
}
}
| cd82ddb706f1ad35ff031bf1e5f81b42 | 31.901408 | 160 | 0.580908 | false | false | false | false |
lgp123456/tiantianTV | refs/heads/master | douyuTV/douyuTV/Classes/Live/Model/XTAddLiveItem.swift | mit | 1 | //
// XTAddLiveItem.swift
// douyuTV
//
// Created by 李贵鹏 on 16/9/2.
// Copyright © 2016年 李贵鹏. All rights reserved.
//
import UIKit
class XTAddLiveItem: NSObject {
//位置
var gps = ""
//直播流地址
var flv = ""
//主播名称
var myname = ""
//等级
var starlevel : NSNumber = 0
//小图地址
var smallpic = ""
//大图地址
var bigpic = ""
//粉丝数
var allnum : NSNumber = 0
init(dict : [String : NSObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
}
| cf6fc35897eaf52bf5d6d9e1975a242e | 17.029412 | 77 | 0.556281 | false | false | false | false |
arieeel1110/PokerRoom | refs/heads/master | ParseStarterProject/AppDelegate.swift | mit | 2 | /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import UIKit
import Bolts
import Parse
// If you want to use any of the UI components, uncomment this line
// import ParseUI
// If you want to use Crash Reporting - uncomment this line
// import ParseCrashReporting
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? //= UIWindow(frame: UIScreen.mainScreen().bounds)
//--------------------------------------
// MARK: - UIApplicationDelegate
//--------------------------------------
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var navigationBarAppearace = UINavigationBar.appearance()
var attributes = [
NSForegroundColorAttributeName: UIColor.whiteColor(),
NSFontAttributeName: UIFont(name: "Futura", size: 21)!
]
navigationBarAppearace.titleTextAttributes = attributes
navigationBarAppearace.tintColor = UIColor.whiteColor()
navigationBarAppearace.barTintColor = UIColor(red: 0, green: 0.35, blue: 0.7, alpha: 0.8)
var tabBarAppearance = UITabBar.appearance()
tabBarAppearance.barTintColor = UIColor.blackColor()
tabBarAppearance.tintColor = UIColor.whiteColor()
// Enable storing and querying data from Local Datastore.
// Remove this line if you don't want to use Local Datastore features or want to use cachePolicy.
Parse.enableLocalDatastore()
application.statusBarStyle = UIStatusBarStyle.LightContent
// ****************************************************************************
// Uncomment this line if you want to enable Crash Reporting
// ParseCrashReporting.enable()
//
// Uncomment and fill in with your Parse credentials:
Parse.setApplicationId("8ZBAugVjJTadoZpeY6PR5Qg0O9Lz9HUwkNFEK5fv",
clientKey: "Q0MZswjes4mnfBwcz2xU6rVe0s1KhxGuJEe9Rm7C")
//
// If you are using Facebook, uncomment and add your FacebookAppID to your bundle's plist as
// described here: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/
// Uncomment the line inside ParseStartProject-Bridging-Header and the following line here:
// PFFacebookUtils.initializeFacebook()
// ****************************************************************************
// PFUser.enableAutomaticUser()
let defaultACL = PFACL();
// If you would like all objects to be private by default, remove this line.
defaultACL.setPublicReadAccess(true)
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true)
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var noPushPayload = false;
if let options = launchOptions {
noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil;
}
if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
if application.respondsToSelector("registerUserNotificationSettings:") {
let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
let types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound
application.registerForRemoteNotificationTypes(types)
}
// self.window!.rootViewController = FirstViewController()
return true
}
//--------------------------------------
// MARK: Push Notifications
//--------------------------------------
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
PFPush.subscribeToChannelInBackground("") { (succeeded: Bool, error: NSError?) in
if succeeded {
println("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.");
} else {
println("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.", error)
}
}
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
// println("Push notifications are not supported in the iOS Simulator.")
} else {
println("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
///////////////////////////////////////////////////////////
// Uncomment this method if you want to use Push Notifications with Background App Refresh
///////////////////////////////////////////////////////////
// func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// if application.applicationState == UIApplicationState.Inactive {
// PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
// }
// }
//--------------------------------------
// MARK: Facebook SDK Integration
//--------------------------------------
///////////////////////////////////////////////////////////
// Uncomment this method if you are using Facebook
///////////////////////////////////////////////////////////
// func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
// return FBAppCall.handleOpenURL(url, sourceApplication:sourceApplication, session:PFFacebookUtils.session())
// }
}
| a55bfaeee64ecbbe4e9475c250e1f2b8 | 45.672956 | 193 | 0.634281 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/stdlib/Inputs/DictionaryKeyValueTypesObjC.swift | apache-2.0 | 29 |
#if _runtime(_ObjC)
import Swift
import SwiftPrivate
import Darwin
import StdlibUnittest
import Foundation
func convertDictionaryToNSDictionary<Key, Value>(
_ d: [Key : Value]
) -> NSDictionary {
return d._bridgeToObjectiveC()
}
public func convertNSDictionaryToDictionary<
Key : Hashable, Value
>(_ d: NSDictionary?) -> [Key : Value] {
if _slowPath(d == nil) { return [:] }
var result: [Key : Value]?
Dictionary._forceBridgeFromObjectiveC(d!, result: &result)
return result!
}
func isNativeDictionary<KeyTy : Hashable, ValueTy>(
_ d: Dictionary<KeyTy, ValueTy>) -> Bool {
return d._variant.isNative
}
func isCocoaDictionary<KeyTy : Hashable, ValueTy>(
_ d: Dictionary<KeyTy, ValueTy>) -> Bool {
return !isNativeDictionary(d)
}
func isNativeNSDictionary(_ d: NSDictionary) -> Bool {
let className: NSString = NSStringFromClass(type(of: d)) as NSString
return [
"_SwiftDeferredNSDictionary",
"__EmptyDictionarySingleton",
"_DictionaryStorage"].contains {
className.range(of: $0).length > 0
}
}
func isCocoaNSDictionary(_ d: NSDictionary) -> Bool {
let className: NSString = NSStringFromClass(type(of: d)) as NSString
return className.range(of: "NSDictionary").length > 0 ||
className.range(of: "NSCFDictionary").length > 0
}
func isNativeNSArray(_ d: NSArray) -> Bool {
let className: NSString = NSStringFromClass(type(of: d)) as NSString
return ["__SwiftDeferredNSArray", "_ContiguousArray", "_EmptyArray"].contains {
className.range(of: $0).length > 0
}
}
var _objcKeyCount = _stdlib_AtomicInt(0)
var _objcKeySerial = _stdlib_AtomicInt(0)
class TestObjCKeyTy : NSObject, NSCopying {
class var objectCount: Int {
get {
return _objcKeyCount.load()
}
set {
_objcKeyCount.store(newValue)
}
}
init(_ value: Int) {
_objcKeyCount.fetchAndAdd(1)
serial = _objcKeySerial.addAndFetch(1)
self.value = value
self._hashValue = value
super.init()
}
convenience init(value: Int, hashValue: Int) {
self.init(value)
self._hashValue = hashValue
}
deinit {
assert(serial > 0, "double destruction")
_objcKeyCount.fetchAndAdd(-1)
serial = -serial
}
@objc(copyWithZone:)
func copy(with zone: NSZone?) -> Any {
return TestObjCKeyTy(value)
}
override var description: String {
assert(serial > 0, "dead TestObjCKeyTy")
return value.description
}
override func isEqual(_ object: Any!) -> Bool {
if let other = object {
if let otherObjcKey = other as? TestObjCKeyTy {
return self.value == otherObjcKey.value
}
}
return false
}
override var hash : Int {
return _hashValue
}
func _bridgeToObjectiveC() -> TestObjCKeyTy {
return self
}
var value: Int
var _hashValue: Int
var serial: Int
}
// A type that satisfies the requirements of an NSDictionary key (or an NSSet
// member), but traps when any of its methods are called.
class TestObjCInvalidKeyTy {
init() {
_objcKeyCount.fetchAndAdd(1)
serial = _objcKeySerial.addAndFetch(1)
}
deinit {
assert(serial > 0, "double destruction")
_objcKeyCount.fetchAndAdd(-1)
serial = -serial
}
@objc
var description: String {
assert(serial > 0, "dead TestObjCInvalidKeyTy")
fatalError()
}
@objc
func isEqual(_ object: Any!) -> Bool {
fatalError()
}
@objc
var hash : Int {
fatalError()
}
var serial: Int
}
var _objcValueCount = _stdlib_AtomicInt(0)
var _objcValueSerial = _stdlib_AtomicInt(0)
class TestObjCValueTy : NSObject {
class var objectCount: Int {
get {
return _objcValueCount.load()
}
set {
_objcValueCount.store(newValue)
}
}
init(_ value: Int) {
_objcValueCount.fetchAndAdd(1)
serial = _objcValueSerial.addAndFetch(1)
self.value = value
}
deinit {
assert(serial > 0, "double destruction")
_objcValueCount.fetchAndAdd(-1)
serial = -serial
}
override var description: String {
assert(serial > 0, "dead TestObjCValueTy")
return value.description
}
var value: Int
var serial: Int
}
var _objcEquatableValueCount = _stdlib_AtomicInt(0)
var _objcEquatableValueSerial = _stdlib_AtomicInt(0)
class TestObjCEquatableValueTy : NSObject {
class var objectCount: Int {
get {
return _objcEquatableValueCount.load()
}
set {
_objcEquatableValueCount.store(newValue)
}
}
init(_ value: Int) {
_objcEquatableValueCount.fetchAndAdd(1)
serial = _objcEquatableValueSerial.addAndFetch(1)
self.value = value
}
deinit {
assert(serial > 0, "double destruction")
_objcEquatableValueCount.fetchAndAdd(-1)
serial = -serial
}
override func isEqual(_ object: Any!) -> Bool {
if let other = object {
if let otherObjcKey = other as? TestObjCEquatableValueTy {
return self.value == otherObjcKey.value
}
}
return false
}
override var description: String {
assert(serial > 0, "dead TestObjCValueTy")
return value.description
}
var value: Int
var serial: Int
}
func == (lhs: TestObjCEquatableValueTy, rhs: TestObjCEquatableValueTy) -> Bool {
return lhs.value == rhs.value
}
var _bridgedKeySerial = _stdlib_AtomicInt(0)
var _bridgedKeyBridgeOperations = _stdlib_AtomicInt(0)
struct TestBridgedKeyTy
: Equatable, Hashable, CustomStringConvertible, _ObjectiveCBridgeable {
var value: Int
var _hashValue: Int
var serial: Int
static var bridgeOperations: Int {
get {
return _bridgedKeyBridgeOperations.load()
}
set {
_bridgedKeyBridgeOperations.store(newValue)
}
}
init(_ value: Int) {
serial = _bridgedKeySerial.addAndFetch(1)
self.value = value
self._hashValue = value
}
var description: String {
assert(serial > 0, "dead TestBridgedKeyTy")
return value.description
}
var hashValue: Int {
return _hashValue
}
func hash(into hasher: inout Hasher) {
hasher.combine(_hashValue)
}
func _bridgeToObjectiveC() -> TestObjCKeyTy {
_bridgedKeyBridgeOperations.fetchAndAdd(1)
return TestObjCKeyTy(value)
}
static func _forceBridgeFromObjectiveC(
_ x: TestObjCKeyTy,
result: inout TestBridgedKeyTy?
) {
_bridgedKeyBridgeOperations.fetchAndAdd(1)
result = TestBridgedKeyTy(x.value)
}
static func _conditionallyBridgeFromObjectiveC(
_ x: TestObjCKeyTy,
result: inout TestBridgedKeyTy?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
static func _unconditionallyBridgeFromObjectiveC(_ source: TestObjCKeyTy?)
-> TestBridgedKeyTy {
var result: TestBridgedKeyTy? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
func == (lhs: TestBridgedKeyTy, rhs: TestBridgedKeyTy) -> Bool {
return lhs.value == rhs.value
}
func == (lhs: TestBridgedKeyTy, rhs: TestKeyTy) -> Bool {
return lhs.value == rhs.value
}
var _bridgedValueSerial = _stdlib_AtomicInt(0)
var _bridgedValueBridgeOperations = _stdlib_AtomicInt(0)
struct TestBridgedValueTy : CustomStringConvertible, _ObjectiveCBridgeable {
static var bridgeOperations: Int {
get {
return _bridgedValueBridgeOperations.load()
}
set {
_bridgedValueBridgeOperations.store(newValue)
}
}
init(_ value: Int) {
serial = _bridgedValueSerial.fetchAndAdd(1)
self.value = value
}
var description: String {
assert(serial > 0, "dead TestBridgedValueTy")
return value.description
}
func _bridgeToObjectiveC() -> TestObjCValueTy {
TestBridgedValueTy.bridgeOperations += 1
return TestObjCValueTy(value)
}
static func _forceBridgeFromObjectiveC(
_ x: TestObjCValueTy,
result: inout TestBridgedValueTy?
) {
TestBridgedValueTy.bridgeOperations += 1
result = TestBridgedValueTy(x.value)
}
static func _conditionallyBridgeFromObjectiveC(
_ x: TestObjCValueTy,
result: inout TestBridgedValueTy?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
static func _unconditionallyBridgeFromObjectiveC(_ source: TestObjCValueTy?)
-> TestBridgedValueTy {
var result: TestBridgedValueTy? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
var value: Int
var serial: Int
}
var _bridgedEquatableValueSerial = _stdlib_AtomicInt(0)
var _bridgedEquatableValueBridgeOperations = _stdlib_AtomicInt(0)
struct TestBridgedEquatableValueTy
: Equatable, CustomStringConvertible, _ObjectiveCBridgeable {
static var bridgeOperations: Int {
get {
return _bridgedEquatableValueBridgeOperations.load()
}
set {
_bridgedEquatableValueBridgeOperations.store(newValue)
}
}
init(_ value: Int) {
serial = _bridgedEquatableValueSerial.addAndFetch(1)
self.value = value
}
var description: String {
assert(serial > 0, "dead TestBridgedValueTy")
return value.description
}
func _bridgeToObjectiveC() -> TestObjCEquatableValueTy {
_bridgedEquatableValueBridgeOperations.fetchAndAdd(1)
return TestObjCEquatableValueTy(value)
}
static func _forceBridgeFromObjectiveC(
_ x: TestObjCEquatableValueTy,
result: inout TestBridgedEquatableValueTy?
) {
_bridgedEquatableValueBridgeOperations.fetchAndAdd(1)
result = TestBridgedEquatableValueTy(x.value)
}
static func _conditionallyBridgeFromObjectiveC(
_ x: TestObjCEquatableValueTy,
result: inout TestBridgedEquatableValueTy?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
static func _unconditionallyBridgeFromObjectiveC(
_ source: TestObjCEquatableValueTy?
) -> TestBridgedEquatableValueTy {
var result: TestBridgedEquatableValueTy? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
var value: Int
var serial: Int
}
func == (lhs: TestBridgedEquatableValueTy, rhs: TestBridgedEquatableValueTy) -> Bool {
return lhs.value == rhs.value
}
/// Expect some number of autoreleased key and value objects.
///
/// - parameter opt: applies to platforms that have the return-autoreleased
/// optimization.
///
/// - parameter unopt: applies to platforms that don't.
///
/// FIXME: Some non-zero `opt` might be cases of missed return-autorelease.
func expectAutoreleasedKeysAndValues(
opt: (Int, Int) = (0, 0), unopt: (Int, Int) = (0, 0)) {
var expectedKeys = 0
var expectedValues = 0
#if arch(i386)
(expectedKeys, expectedValues) = unopt
#else
(expectedKeys, expectedValues) = opt
#endif
TestObjCKeyTy.objectCount -= expectedKeys
TestObjCValueTy.objectCount -= expectedValues
}
/// Expect some number of autoreleased value objects.
///
/// - parameter opt: applies to platforms that have the return-autoreleased
/// optimization.
///
/// - parameter unopt: applies to platforms that don't.
///
/// FIXME: Some non-zero `opt` might be cases of missed return-autorelease.
func expectAutoreleasedValues(
opt: Int = 0, unopt: Int = 0) {
expectAutoreleasedKeysAndValues(opt: (0, opt), unopt: (0, unopt))
}
func resetLeaksOfObjCDictionaryKeysValues() {
TestObjCKeyTy.objectCount = 0
TestObjCValueTy.objectCount = 0
TestObjCEquatableValueTy.objectCount = 0
}
func expectNoLeaksOfObjCDictionaryKeysValues() {
expectEqual(0, TestObjCKeyTy.objectCount, "TestObjCKeyTy leak")
expectEqual(0, TestObjCValueTy.objectCount, "TestObjCValueTy leak")
expectEqual(
0, TestObjCEquatableValueTy.objectCount, "TestObjCEquatableValueTy leak")
}
func getBridgedNSDictionaryOfRefTypesBridgedVerbatim() -> NSDictionary {
assert(_isBridgedVerbatimToObjectiveC(TestObjCKeyTy.self))
assert(_isBridgedVerbatimToObjectiveC(TestObjCValueTy.self))
var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
let bridged = convertDictionaryToNSDictionary(d)
assert(isNativeNSDictionary(bridged))
return bridged
}
func getBridgedEmptyNSDictionary() -> NSDictionary {
let d = Dictionary<TestObjCKeyTy, TestObjCValueTy>()
let bridged = convertDictionaryToNSDictionary(d)
assert(isNativeNSDictionary(bridged))
return bridged
}
func getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged(
numElements: Int = 3
) -> NSDictionary {
assert(!_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self))
assert(!_isBridgedVerbatimToObjectiveC(TestBridgedValueTy.self))
var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>()
for i in 1..<(numElements + 1) {
d[TestBridgedKeyTy(i * 10)] = TestBridgedValueTy(i * 10 + 1000)
}
let bridged = convertDictionaryToNSDictionary(d)
assert(isNativeNSDictionary(bridged))
return bridged
}
import SlurpFastEnumeration
func slurpFastEnumerationFromSwift(
_ a: NSArray, _ fe: NSFastEnumeration, _ sink: (AnyObject) -> Void,
maxItems: Int? = nil
) {
var state = NSFastEnumerationState()
let bufferSize = 3
let buffer =
UnsafeMutableBufferPointer<AnyObject?>.allocate(capacity: bufferSize)
defer { buffer.deallocate() }
var itemsReturned = 0
while true {
let returnedCount = fe.countByEnumerating(
with: &state,
objects: AutoreleasingUnsafeMutablePointer(buffer.baseAddress!),
count: buffer.count)
expectNotEqual(0, state.state)
expectNotNil(state.mutationsPtr)
if returnedCount == 0 {
break
}
for i in 0..<returnedCount {
let value: AnyObject = state.itemsPtr![i]!
sink(value)
itemsReturned += 1
}
if maxItems != nil && itemsReturned >= maxItems! {
return
}
}
for _ in 0..<3 {
let returnedCount = fe.countByEnumerating(
with: &state,
objects: AutoreleasingUnsafeMutablePointer(buffer.baseAddress!),
count: buffer.count)
expectNotEqual(0, state.state)
expectNotNil(state.mutationsPtr)
expectEqual(0, returnedCount)
}
}
typealias AnyObjectTuple2 = (AnyObject, AnyObject)
func slurpFastEnumerationFromSwift(
_ d: NSDictionary, _ fe: NSFastEnumeration, _ sink: (AnyObjectTuple2) -> Void,
maxItems: Int? = nil
) {
var state = NSFastEnumerationState()
let bufferSize = 3
let buffer =
UnsafeMutableBufferPointer<AnyObject?>.allocate(capacity: bufferSize)
defer { buffer.deallocate() }
var itemsReturned = 0
while true {
let returnedCount = fe.countByEnumerating(
with: &state,
objects: AutoreleasingUnsafeMutablePointer(buffer.baseAddress!),
count: buffer.count)
expectNotEqual(0, state.state)
expectNotNil(state.mutationsPtr)
if returnedCount == 0 {
break
}
for i in 0..<returnedCount {
let key: AnyObject = state.itemsPtr![i]!
let value: AnyObject = d.object(forKey: key)! as AnyObject
let kv = (key, value)
sink(kv)
itemsReturned += 1
}
if maxItems != nil && itemsReturned >= maxItems! {
return
}
}
for _ in 0..<3 {
let returnedCount = fe.countByEnumerating(
with: &state,
objects: AutoreleasingUnsafeMutablePointer(buffer.baseAddress!),
count: buffer.count)
expectEqual(0, returnedCount)
}
}
func slurpFastEnumerationOfNSEnumeratorFromSwift(
_ a: NSArray, _ enumerator: NSEnumerator, _ sink: (AnyObject) -> Void,
maxFastEnumerationItems: Int
) {
slurpFastEnumerationFromSwift(
a, enumerator, sink, maxItems: maxFastEnumerationItems)
while let value = enumerator.nextObject() {
sink(value as AnyObject)
}
}
func slurpFastEnumerationOfNSEnumeratorFromSwift(
_ d: NSDictionary, _ enumerator: NSEnumerator,
_ sink: (AnyObjectTuple2) -> Void,
maxFastEnumerationItems: Int
) {
slurpFastEnumerationFromSwift(
d, enumerator, sink, maxItems: maxFastEnumerationItems)
while let key = enumerator.nextObject() {
let value: AnyObject = d.object(forKey: key)! as AnyObject
let kv = (key as AnyObject, value)
sink(kv)
}
}
func slurpFastEnumerationFromObjC(
_ a: NSArray, _ fe: NSFastEnumeration, _ sink: (AnyObject) -> Void
) {
let objcValues = NSMutableArray()
slurpFastEnumerationOfArrayFromObjCImpl(a, fe, objcValues)
for value in objcValues {
sink(value as AnyObject)
}
}
func _checkArrayFastEnumerationImpl(
_ expected: [Int],
_ a: NSArray,
_ makeEnumerator: () -> NSFastEnumeration,
_ useEnumerator: (NSArray, NSFastEnumeration, (AnyObject) -> ()) -> Void,
_ convertValue: @escaping (AnyObject) -> Int
) {
let expectedContentsWithoutIdentity =
_makeExpectedArrayContents(expected)
var expectedContents = [ExpectedArrayElement]()
for i in 0..<3 {
var actualContents = [ExpectedArrayElement]()
let sink = {
(value: AnyObject) in
actualContents.append(ExpectedArrayElement(
value: convertValue(value),
valueIdentity: unsafeBitCast(value, to: UInt.self)))
}
useEnumerator(a, makeEnumerator(), sink)
expectTrue(
_equalsWithoutElementIdentity(
expectedContentsWithoutIdentity, actualContents),
"expected: \(expectedContentsWithoutIdentity)\n" +
"actual: \(actualContents)\n")
if i == 0 {
expectedContents = actualContents
}
expectEqualSequence(expectedContents, actualContents)
}
}
func checkArrayFastEnumerationFromSwift(
_ expected: [Int],
_ a: NSArray, _ makeEnumerator: () -> NSFastEnumeration,
_ convertValue: @escaping (AnyObject) -> Int
) {
_checkArrayFastEnumerationImpl(
expected, a, makeEnumerator,
{ (a, fe, sink) in
slurpFastEnumerationFromSwift(a, fe, sink)
},
convertValue)
}
func checkArrayFastEnumerationFromObjC(
_ expected: [Int],
_ a: NSArray, _ makeEnumerator: () -> NSFastEnumeration,
_ convertValue: @escaping (AnyObject) -> Int
) {
_checkArrayFastEnumerationImpl(
expected, a, makeEnumerator,
{ (a, fe, sink) in
slurpFastEnumerationFromObjC(a, fe, sink)
},
convertValue)
}
func checkArrayEnumeratorPartialFastEnumerationFromSwift(
_ expected: [Int],
_ a: NSArray,
maxFastEnumerationItems: Int,
_ convertValue: @escaping (AnyObject) -> Int
) {
_checkArrayFastEnumerationImpl(
expected, a, { a.objectEnumerator() },
{ (a, fe, sink) in
slurpFastEnumerationOfNSEnumeratorFromSwift(
a, fe as! NSEnumerator, sink,
maxFastEnumerationItems: maxFastEnumerationItems)
},
convertValue)
}
func _checkSetFastEnumerationImpl(
_ expected: [Int],
_ s: NSSet,
_ makeEnumerator: () -> NSFastEnumeration,
_ useEnumerator: (NSSet, NSFastEnumeration, (AnyObject) -> ()) -> Void,
_ convertMember: @escaping (AnyObject) -> Int
) {
let expectedContentsWithoutIdentity =
_makeExpectedSetContents(expected)
var expectedContents = [ExpectedSetElement]()
for i in 0..<3 {
var actualContents = [ExpectedSetElement]()
let sink = {
(value: AnyObject) in
actualContents.append(ExpectedSetElement(
value: convertMember(value),
valueIdentity: unsafeBitCast(value, to: UInt.self)))
}
useEnumerator(s, makeEnumerator(), sink)
expectTrue(
_equalsUnorderedWithoutElementIdentity(
expectedContentsWithoutIdentity, actualContents),
"expected: \(expectedContentsWithoutIdentity)\n" +
"actual: \(actualContents)\n")
if i == 0 {
expectedContents = actualContents
}
expectTrue(equalsUnordered(expectedContents, actualContents))
}
}
func slurpFastEnumerationFromObjC(
_ s: NSSet, _ fe: NSFastEnumeration, _ sink: (AnyObject) -> Void
) {
let objcValues = NSMutableArray()
slurpFastEnumerationOfArrayFromObjCImpl(s, fe, objcValues)
for value in objcValues {
sink(value as AnyObject)
}
}
func slurpFastEnumerationOfNSEnumeratorFromSwift(
_ s: NSSet, _ enumerator: NSEnumerator, _ sink: (AnyObject) -> Void,
maxFastEnumerationItems: Int
) {
slurpFastEnumerationFromSwift(
s, enumerator, sink, maxItems: maxFastEnumerationItems)
while let value = enumerator.nextObject() {
sink(value as AnyObject)
}
}
func slurpFastEnumerationFromSwift(
_ s: NSSet, _ fe: NSFastEnumeration, _ sink: (AnyObject) -> Void,
maxItems: Int? = nil
) {
var state = NSFastEnumerationState()
let bufferSize = 3
let buffer =
UnsafeMutableBufferPointer<AnyObject?>.allocate(capacity: bufferSize)
defer { buffer.deallocate() }
var itemsReturned = 0
while true {
let returnedCount = fe.countByEnumerating(
with: &state,
objects: AutoreleasingUnsafeMutablePointer(buffer.baseAddress!),
count: buffer.count)
expectNotEqual(0, state.state)
expectNotNil(state.mutationsPtr)
if returnedCount == 0 {
break
}
for i in 0..<returnedCount {
let value: AnyObject = state.itemsPtr![i]!
sink(value)
itemsReturned += 1
}
if maxItems != nil && itemsReturned >= maxItems! {
return
}
}
for _ in 0..<3 {
let returnedCount = fe.countByEnumerating(
with: &state,
objects: AutoreleasingUnsafeMutablePointer(buffer.baseAddress!),
count: buffer.count)
expectNotEqual(0, state.state)
expectNotNil(state.mutationsPtr)
expectEqual(0, returnedCount)
}
}
func checkSetFastEnumerationFromSwift(
_ expected: [Int],
_ s: NSSet, _ makeEnumerator: () -> NSFastEnumeration,
_ convertMember: @escaping (AnyObject) -> Int
) {
_checkSetFastEnumerationImpl(
expected, s, makeEnumerator,
{ (s, fe, sink) in
slurpFastEnumerationFromSwift(s, fe, sink)
},
convertMember)
}
func checkSetFastEnumerationFromObjC(
_ expected: [Int],
_ s: NSSet, _ makeEnumerator: () -> NSFastEnumeration,
_ convertMember: @escaping (AnyObject) -> Int
) {
_checkSetFastEnumerationImpl(
expected, s, makeEnumerator,
{ (s, fe, sink) in
slurpFastEnumerationFromObjC(s, fe, sink)
},
convertMember)
}
func checkSetEnumeratorPartialFastEnumerationFromSwift(
_ expected: [Int],
_ s: NSSet,
maxFastEnumerationItems: Int,
_ convertMember: @escaping (AnyObject) -> Int
) {
_checkSetFastEnumerationImpl(
expected, s, { s.objectEnumerator() },
{ (s, fe, sink) in
slurpFastEnumerationOfNSEnumeratorFromSwift(
s, fe as! NSEnumerator, sink,
maxFastEnumerationItems: maxFastEnumerationItems)
},
convertMember)
}
func slurpFastEnumerationFromObjC(
_ d: NSDictionary, _ fe: NSFastEnumeration, _ sink: (AnyObjectTuple2) -> Void
) {
let objcPairs = NSMutableArray()
slurpFastEnumerationOfDictionaryFromObjCImpl(d, fe, objcPairs)
for i in 0..<objcPairs.count/2 {
let key = objcPairs[i * 2] as AnyObject
let value = objcPairs[i * 2 + 1] as AnyObject
let kv = (key, value)
sink(kv)
}
}
func _checkDictionaryFastEnumerationImpl(
_ expected: [(Int, Int)],
_ d: NSDictionary,
_ makeEnumerator: () -> NSFastEnumeration,
_ useEnumerator: (NSDictionary, NSFastEnumeration, (AnyObjectTuple2) -> ()) -> Void,
_ convertKey: @escaping (AnyObject) -> Int,
_ convertValue: @escaping (AnyObject) -> Int
) {
let expectedContentsWithoutIdentity =
_makeExpectedDictionaryContents(expected)
var expectedContents = [ExpectedDictionaryElement]()
for i in 0..<3 {
var actualContents = [ExpectedDictionaryElement]()
let sink: (AnyObjectTuple2) -> Void = {
let (key, value) = $0
actualContents.append(ExpectedDictionaryElement(
key: convertKey(key),
value: convertValue(value),
keyIdentity: unsafeBitCast(key, to: UInt.self),
valueIdentity: unsafeBitCast(value, to: UInt.self)))
}
useEnumerator(d, makeEnumerator(), sink)
expectTrue(
_equalsUnorderedWithoutElementIdentity(
expectedContentsWithoutIdentity, actualContents),
"expected: \(expectedContentsWithoutIdentity)\n" +
"actual: \(actualContents)\n")
if i == 0 {
expectedContents = actualContents
}
expectTrue(equalsUnordered(expectedContents, actualContents))
}
}
func checkDictionaryFastEnumerationFromSwift(
_ expected: [(Int, Int)],
_ d: NSDictionary, _ makeEnumerator: () -> NSFastEnumeration,
_ convertKey: @escaping (AnyObject) -> Int,
_ convertValue: @escaping (AnyObject) -> Int
) {
_checkDictionaryFastEnumerationImpl(
expected, d, makeEnumerator,
{ (d, fe, sink) in
slurpFastEnumerationFromSwift(d, fe, sink)
},
convertKey, convertValue)
}
func checkDictionaryFastEnumerationFromObjC(
_ expected: [(Int, Int)],
_ d: NSDictionary, _ makeEnumerator: () -> NSFastEnumeration,
_ convertKey: @escaping (AnyObject) -> Int,
_ convertValue: @escaping (AnyObject) -> Int
) {
_checkDictionaryFastEnumerationImpl(
expected, d, makeEnumerator,
{ (d, fe, sink) in
slurpFastEnumerationFromObjC(d, fe, sink)
},
convertKey, convertValue)
}
func checkDictionaryEnumeratorPartialFastEnumerationFromSwift(
_ expected: [(Int, Int)],
_ d: NSDictionary,
maxFastEnumerationItems: Int,
_ convertKey: @escaping (AnyObject) -> Int,
_ convertValue: @escaping (AnyObject) -> Int
) {
_checkDictionaryFastEnumerationImpl(
expected, d, { d.keyEnumerator() },
{ (d, fe, sink) in
slurpFastEnumerationOfNSEnumeratorFromSwift(
d, fe as! NSEnumerator, sink,
maxFastEnumerationItems: maxFastEnumerationItems)
},
convertKey, convertValue)
}
func getBridgedNSArrayOfRefTypeVerbatimBridged(
numElements: Int = 3,
capacity: Int? = nil
) -> NSArray {
assert(_isBridgedVerbatimToObjectiveC(TestObjCValueTy.self))
var a = [TestObjCValueTy]()
if let requestedCapacity = capacity {
a.reserveCapacity(requestedCapacity)
}
for i in 1..<(numElements + 1) {
a.append(TestObjCValueTy(i * 10))
}
let bridged = convertArrayToNSArray(a)
assert(isNativeNSArray(bridged))
return bridged
}
func convertNSArrayToArray<T>(_ source: NSArray?) -> [T] {
if _slowPath(source == nil) { return [] }
var result: [T]?
Array._forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
func convertArrayToNSArray<T>(_ array: [T]) -> NSArray {
return array._bridgeToObjectiveC()
}
func getBridgedNSArrayOfValueTypeCustomBridged(
numElements: Int = 3,
capacity: Int? = nil
) -> NSArray {
assert(!_isBridgedVerbatimToObjectiveC(TestBridgedValueTy.self))
var a = [TestBridgedValueTy]()
if let requestedCapacity = capacity {
a.reserveCapacity(requestedCapacity)
}
for i in 1..<(numElements + 1) {
a.append(TestBridgedValueTy(i * 10))
}
let bridged = convertArrayToNSArray(a)
assert(isNativeNSArray(bridged))
return bridged
}
#endif
| f3ebf4f77aec9fca3f13e0816d9699aa | 25.280198 | 86 | 0.696266 | false | true | false | false |
priya273/stockAnalyzer | refs/heads/master | Stock Analyzer/Stock Analyzer/UserManager.swift | apache-2.0 | 1 | //
// UserManager.swift
// Stock Analyzer
//
// Created by Naga sarath Thodime on 3/14/16.
// Copyright © 2016 Priyadarshini Ragupathy. All rights reserved.
//
import CoreData
import Foundation
import UIKit
protocol UserExistDelegate
{
func UserExistsOrCreated()
func UnableToRetriveOrCreateUser()
}
class UserManager : UserCreationDelegate
{
var managedObjectContext: NSManagedObjectContext? = nil
var delegate : UserExistDelegate?
init()
{
let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
self.managedObjectContext = appDel.managedObjectContext;
}
func ValidateUser(user : UserEntity)
{
PersistUserLocally(user)
PersistUserRemotely(user)
}
func PersistUserLocally(user : UserEntity)
{
(UIApplication.sharedApplication().delegate as! AppDelegate).userID = user.id;
(UIApplication.sharedApplication().delegate as! AppDelegate).User = user;
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let predicate = NSPredicate(format: "id == '\(user.id)'", argumentArray: nil)
let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
fetchRequest.predicate = predicate
do
{
let objectFetch = try self.managedObjectContext!.executeFetchRequest(fetchRequest) as! [User]
if(objectFetch.count > 0)
{
print("Already Exist")
}
else
{
AddUserLocally(user)
}
}
catch
{
print("Unable to locate the managed Context, try again")
self.delegate?.UnableToRetriveOrCreateUser()
}
}
func PersistUserRemotely(userEntity : UserEntity)
{
let userContract = UserContract();
userContract.id = userEntity.id;
userContract.Email = userEntity.email
let service = UserProvider();
service.Delegate = self
//add to presistent data and call
service.PostNewUserRecord(userContract)
}
func AddUserLocally(userEntity : UserEntity)
{
let userManagedObject = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: self.managedObjectContext!) as! User
userManagedObject.id = userEntity.id
userManagedObject.isActiveRemotely = 1
userManagedObject.email = userEntity.email
userManagedObject.name = userEntity.name
do{
try managedObjectContext?.save()
(UIApplication.sharedApplication().delegate as! AppDelegate).userID = userEntity.id;
}
catch
{
NSLog("There was a problem to add New USer");
self.delegate?.UnableToRetriveOrCreateUser()
}
}
func UserCreationSuccess()
{
self.delegate?.UserExistsOrCreated()
}
func UserCreationFailed()
{
self.delegate?.UnableToRetriveOrCreateUser()
}
func GetUserEntity(id : String) -> Bool
{
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let predicate = NSPredicate(format: "id == '\(id)'", argumentArray: nil)
let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
fetchRequest.predicate = predicate
do
{
let objectFetch = try self.managedObjectContext!.executeFetchRequest(fetchRequest) as! [User]
if(objectFetch.count > 0)
{
print("Already Exist")
let user = UserEntity()
user.id = objectFetch[0].id;
user.name = objectFetch[0].name
(UIApplication.sharedApplication().delegate as! AppDelegate).User = user
(UIApplication.sharedApplication().delegate as! AppDelegate).userID = objectFetch[0].id;
return true;
}
else if(objectFetch.count == 0)
{
return false;
}
}
catch
{
print("Unable to locate the managed Context, try again")
}
return false
}
}
| 903a687c64cf366213179b38ecd2459d | 26.567251 | 152 | 0.573186 | false | false | false | false |
JTWang4778/LearningSwiftDemos | refs/heads/master | 02-集合类型/002-Dictionary/ViewController.swift | mit | 1 | //
// ViewController.swift
// 002-Dictionary
//
// Created by 王锦涛 on 2017/4/16.
// Copyright © 2017年 JTWang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// creatDictionary()
// readAndWriteDict()
enumateDict()
}
func enumateDict() {
let dict3: [Int:String] = [1:"11",2:"22222",3:"3333333"]
for (key, value) in dict3 {
print("key = \(key), value = \(value)")
}
// 遍历keys
for key in dict3.keys {
print(key)
}
// 遍历valus
for value in dict3.values {
print(value)
}
// 按照键值递增遍历
for key in dict3.keys.sorted() {
print("key = \(key), value = \(dict3[key]!)")
}
}
func readAndWriteDict() {
var dict3: [Int:String] = [1:"1",2:"2",3:"3"]
if dict3.isEmpty {
print("字典是空的")
}else{
print("字典有 \(dict3.count) 个键值对")
}
// 修改字典中的值
dict3[1] = "111111"
print(dict3)
// 如果当前字典中 没有该键 则自动添加键值
dict3[6] = "6"
print(dict3)
// 另外一种修改方法 该方法返回一个可选值 如果之前有值的话 就返回 没有的话就返回 nil
let oldValueOptional = dict3.updateValue("66666", forKey: 6)
print(dict3)
if let oldVaule = oldValueOptional {
print(oldVaule)
}
// 删除键值 方法1
dict3[1] = nil
print(dict3)
// 方法2
if let oldValue = dict3.removeValue(forKey: 65) {
print(oldValue)
}else{
print("字典中没有该键")
}
}
func creatDictionary() {
// 创建空字典
var dict = [Int: String]()
dict[2] = "222"
print(dict)
// 利用字面量创建字典
var dict3: [Int:String] = [1:"1",2:"2",3:"3"]
print(dict3)
}
}
| 0527402eff0fff9fdc2aa644a8f7715b | 19.294118 | 68 | 0.443478 | false | false | false | false |
Mazy-ma/DemoBySwift | refs/heads/master | PullToRefresh/PullToRefresh/PullToRefresh/UIViewExtension.swift | apache-2.0 | 1 | //
// UIViewExtension.swift
// PullToRefresh
//
// Created by Mazy on 2017/12/5.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
extension UIView {
/// 给 UIView 添加点击事件
open func addTarget(_ target: Any?, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
self.isUserInteractionEnabled = true
self.addGestureRecognizer(tap)
}
open var x: CGFloat {
get {
return self.frame.origin.x
}
set {
var frame = self.frame
frame.origin.x = newValue
self.frame = frame
}
}
open var y: CGFloat {
get {
return self.frame.origin.y
}
set {
var frame = self.frame
frame.origin.y = newValue
self.frame = frame
}
}
open var width: CGFloat {
get {
return self.frame.size.width
}
set {
var frame = self.frame
frame.size.width = newValue
self.frame = frame
}
}
open var height: CGFloat {
get {
return self.frame.size.height
}
set {
var frame = self.frame
frame.size.height = newValue
self.frame = frame
}
}
open var size: CGSize {
get {
return self.frame.size
}
set {
var frame = self.frame
frame.size = newValue
self.frame = frame
}
}
open var origin: CGPoint {
get {
return self.frame.origin
}
set {
var frame = self.frame
frame.origin = newValue
self.frame = frame
}
}
open var bottom: CGFloat {
get {
return self.frame.origin.y + self.frame.size.height
}
}
open var centerX: CGFloat {
get {
return self.center.x
}
}
open var centerY: CGFloat {
get {
return self.center.y
}
}
}
| a165744ae8429cae95824d5759bdf931 | 19.091743 | 72 | 0.460274 | false | false | false | false |
smizy/DemoWebviewApsalar_ios | refs/heads/master | MainController.swift | mit | 1 | //
// MainController.swift
// DemoAppWebview
//
// Created by usr0300789 on 2014/11/14.
// Copyright (c) 2014年 smizy. All rights reserved.
//
import UIKit
class MainController: UITableViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var stopButton: UIBarButtonItem!
@IBOutlet weak var refreshButton: UIBarButtonItem!
@IBOutlet weak var rewindButton: UIBarButtonItem!
@IBOutlet weak var forwardButton: UIBarButtonItem!
@IBAction func doStop(sender: AnyObject) {
webView.stopLoading()
}
@IBAction func doRefresh(sender: AnyObject) {
webView.reload()
}
@IBAction func doRewind(sender: AnyObject) {
if webView.canGoBack {
webView.goBack()
}
}
@IBAction func doForwad(sender: AnyObject) {
if webView.canGoForward {
return webView.goForward()
}
}
func webView(view: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let url = request.URL
let ext = url.pathExtension
if url.scheme == "local" && ext == "html" {
var basename = url.lastPathComponent?.stringByDeletingPathExtension
if (basename != nil) {
let myURL = NSBundle.mainBundle().URLForResource(basename!, withExtension: ext)
let requestObj = NSURLRequest(URL: myURL!)
webView.loadRequest(requestObj)
}
return false
}
println(url)
println("shouldStartLoading:" + view.stringByEvaluatingJavaScriptFromString("typeof(Apsalar)")! )
// if view.stringByEvaluatingJavaScriptFromString("typeof(Apsalar)") == "undefined" {
// // Inject Apsalar.JS in to the HTMLs
// if let path = NSBundle.mainBundle().pathForResource("Apsalar", ofType: "js") {
// if let possibleContent = String(contentsOfFile:path, usedEncoding: nil, error: nil) {
// view.stringByEvaluatingJavaScriptFromString(possibleContent)
// }
// }
// }
if Apsalar.processJSRequest(view, withURL:request) {
// if processJSRequest handled this request it will return TRUE so
// return NO (should not start load with request)
return false;
}
return true
}
func webViewDidFinishLoad(view: UIWebView) {
println("webViewDidFinishLoad:" + view.stringByEvaluatingJavaScriptFromString("typeof(Apsalar)")! )
if view.stringByEvaluatingJavaScriptFromString("typeof(Apsalar)") == "undefined" {
// Inject Apsalar.JS in to the HTMLs
if let path = NSBundle.mainBundle().pathForResource("Apsalar", ofType: "js") {
if let possibleContent = String(contentsOfFile:path, usedEncoding: nil, error: nil) {
view.stringByEvaluatingJavaScriptFromString(possibleContent)
// event trigger
var apsalarCreated = "var event = new Event('apsalarCreated');document.dispatchEvent(event);"
view.stringByEvaluatingJavaScriptFromString(apsalarCreated)
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.s
let myURL = NSBundle.mainBundle().URLForResource("index", withExtension: "html")
let requestObj = NSURLRequest(URL: myURL!)
webView.loadRequest(requestObj)
webView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
} | d176317c07e8a28aaead266b2c22825c | 34.171171 | 134 | 0.610556 | false | false | false | false |
CoderST/XMLYDemo | refs/heads/master | XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/Model/DiscoveryColumnsModel.swift | mit | 1 | //
// DiscoveryColumnsModel.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/21.
// Copyright © 2016年 CoderST. All rights reserved.
//
import UIKit
class DiscoveryColumnsModel: BaseModel {
var title : String = ""
var list : [DiscoveryColumnsItem] = [DiscoveryColumnsItem]()
override func setValue(_ value: Any?, forKey key: String) {
if key == "list" {
if let listArray = value as? [[String : AnyObject]] {
for listDict in listArray {
list.append(DiscoveryColumnsItem(dict: listDict))
}
}
}else{
super.setValue(value, forKey: key)
}
}
}
| cae99dab322758cd47c3104618f67dfc | 23.785714 | 69 | 0.557637 | false | false | false | false |
voidException/FileKit | refs/heads/master | FileKit/Core/FKOperators.swift | mit | 1 | //
// FKOperators.swift
// FileKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Nikolai Vazquez
//
// 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
// MARK: - FKFileType
infix operator |> {}
/// Writes data to a file.
///
/// - Throws: `FKError.WriteToFileFail`
///
public func |> <FileType: FKFileType>(data: FileType.DataType, file: FileType) throws {
try file.write(data)
}
// MARK: - FKTextFile
infix operator |>> {}
/// Appends a string to a text file.
///
/// If the text file can't be read from, such in the case that it doesn't exist,
/// then it will try to write the data directly to the file.
///
/// - Throws: `FKError.WriteToFileFail`
///
public func |>> (var data: String, file: FKTextFile) throws {
if let contents = try? file.read() {
data = contents + "\n" + data
}
try data |> file
}
// MARK: - FKPath
@warn_unused_result public func == (lhs: FKPath, rhs: FKPath) -> Bool {
return lhs.standardized.rawValue == rhs.standardized.rawValue
}
/// Concatenates two `FKPath` instances and returns the result.
///
/// let systemLibrary: FKPath = "/System/Library"
/// print(systemLib + "Fonts") // "/System/Library/Fonts"
///
public func + (lhs: FKPath, rhs: FKPath) -> FKPath {
switch (lhs.rawValue.hasSuffix(FKPath.Separator), rhs.rawValue.hasPrefix(FKPath.Separator)) {
case (true, true):
return FKPath("\(lhs.rawValue)\(rhs.rawValue.substringFromIndex(rhs.rawValue.startIndex.successor()))")
case (false, false):
return FKPath("\(lhs.rawValue)\(FKPath.Separator)\(rhs.rawValue)")
default:
return FKPath("\(lhs.rawValue)\(rhs.rawValue)")
}
}
/// Appends the right path to the left path.
public func += (inout lhs: FKPath, rhs: FKPath) {
lhs = lhs + rhs
}
infix operator ->> {}
/// Moves the file at the left path to a path.
///
/// Throws an error if the file at the left path could not be moved or if a file
/// already exists at the right path.
///
/// - Throws:
/// - `FKError.FileDoesNotExist`,
/// - `FKError.MoveFileFail`
///
public func ->> (lhs: FKPath, rhs: FKPath) throws {
try lhs.moveFileToPath(rhs)
}
/// Moves a file to a path.
///
/// Throws an error if the file could not be moved or if a file already
/// exists at the destination path.
///
/// - Throws:
/// - `FKError.FileDoesNotExist`,
/// - `FKError.MoveFileFail`
///
public func ->> <FileType: FKFileType>(inout lhs: FileType, rhs: FKPath) throws {
try lhs.moveToPath(rhs)
}
infix operator ->! {}
/// Forcibly moves the file at the left path to the right path.
///
/// - Warning: If a file at the right path already exists, it will be deleted.
///
/// - Throws:
/// - `FKError.DeleteFileFail`,
/// - `FKError.FileDoesNotExist`,
/// - `FKError.CreateSymlinkFail`
///
public func ->! (lhs: FKPath, rhs: FKPath) throws {
if rhs.exists {
try rhs.deleteFile()
}
try lhs ->> rhs
}
/// Forcibly moves a file to a path.
///
/// - Warning: If a file at the right path already exists, it will be deleted.
///
/// - Throws:
/// - `FKError.DeleteFileFail`,
/// - `FKError.FileDoesNotExist`,
/// - `FKError.CreateSymlinkFail`
///
public func ->! <FileType: FKFileType>(inout lhs: FileType, rhs: FKPath) throws {
if rhs.exists {
try rhs.deleteFile()
}
try lhs ->> rhs
}
infix operator +>> {}
/// Copies the file at the left path to the right path.
///
/// Throws an error if the file at the left path could not be copied or if a file
/// already exists at the right path.
///
/// - Throws: `FKError.FileDoesNotExist`, `FKError.CopyFileFail`
///
public func +>> (lhs: FKPath, rhs: FKPath) throws {
try lhs.copyFileToPath(rhs)
}
/// Copies a file to a path.
///
/// Throws an error if the file could not be copied or if a file already
/// exists at the destination path.
///
/// - Throws:
/// - `FKError.FileDoesNotExist`,
/// - `FKError.CopyFileFail`
///
public func +>> <FileType: FKFileType>(lhs: FileType, rhs: FKPath) throws {
try lhs.copyToPath(rhs)
}
infix operator +>! {}
/// Forcibly copies the file at the left path to the right path.
///
/// - Warning: If a file at the right path already exists, it will be deleted.
///
/// - Throws:
/// - `FKError.DeleteFileFail`,
/// - `FKError.FileDoesNotExist`,
/// - `FKError.CreateSymlinkFail`
///
public func +>! (lhs: FKPath, rhs: FKPath) throws {
if rhs.exists {
try rhs.deleteFile()
}
try lhs +>> rhs
}
/// Forcibly copies a file to a path.
///
/// - Warning: If a file at the right path already exists, it will be deleted.
///
/// - Throws:
/// - `FKError.DeleteFileFail`,
/// - `FKError.FileDoesNotExist`,
/// - `FKError.CreateSymlinkFail`
///
public func +>! <FileType: FKFileType>(lhs: FileType, rhs: FKPath) throws {
if rhs.exists {
try rhs.deleteFile()
}
try lhs +>> rhs
}
infix operator ~>> {}
/// Creates a symlink of the left path at the right path.
///
/// If the symbolic link path already exists and _is not_ a directory, an
/// error will be thrown and a link will not be created.
///
/// If the symbolic link path already exists and _is_ a directory, the link
/// will be made to a file in that directory.
///
/// - Throws:
/// - `FKError.FileDoesNotExist`,
/// - `FKError.CreateSymlinkFail`
///
public func ~>> (lhs: FKPath, rhs: FKPath) throws {
try lhs.symlinkFileToPath(rhs)
}
/// Symlinks a file to a path.
///
/// If the path already exists and _is not_ a directory, an error will be
/// thrown and a link will not be created.
///
/// If the path already exists and _is_ a directory, the link will be made
/// to the file in that directory.
///
/// - Throws: `FKError.FileDoesNotExist`, `FKError.CreateSymlinkFail`
///
public func ~>> <FileType: FKFileType>(lhs: FileType, rhs: FKPath) throws {
try lhs.symlinkToPath(rhs)
}
infix operator ~>! {}
/// Forcibly creates a symlink of the left path at the right path by deleting
/// anything at the right path before creating the symlink.
///
/// - Warning: If the symbolic link path already exists, it will be deleted.
///
/// - Throws:
/// - `FKError.DeleteFileFail`,
/// - `FKError.FileDoesNotExist`,
/// - `FKError.CreateSymlinkFail`
///
public func ~>! (lhs: FKPath, rhs: FKPath) throws {
if rhs.exists {
try rhs.deleteFile()
}
try lhs ~>> rhs
}
/// Forcibly creates a symlink of a file at a path by deleting anything at the
/// path before creating the symlink.
///
/// - Warning: If the path already exists, it will be deleted.
///
/// - Throws:
/// - `FKError.DeleteFileFail`,
/// - `FKError.FileDoesNotExist`,
/// - `FKError.CreateSymlinkFail`
///
public func ~>! <FileType: FKFileType>(lhs: FileType, rhs: FKPath) throws {
if rhs.exists {
try rhs.deleteFile()
}
try lhs ~>> rhs
}
postfix operator • {}
/// Returns the standardized version of the path.
///
/// Can be typed with alt+8.
///
@warn_unused_result public postfix func • (path: FKPath) -> FKPath {
return path.standardized
}
postfix operator ^ {}
/// Returns the path's parent path.
@warn_unused_result public postfix func ^ (path: FKPath) -> FKPath {
return path.parent
}
| b635d5c2043e7d5b2e514507921c198c | 26.44702 | 111 | 0.653155 | false | false | false | false |
teroxik/open-muvr | refs/heads/master | ios/Lift/LiftServer/LiftServerURLs.swift | apache-2.0 | 1 | import Foundation
///
/// The request to the Lift server-side code
///
struct LiftServerRequest {
var path: String
var method: Method
init(path: String, method: Method) {
self.path = path
self.method = method
}
}
///
/// Defines mechanism to convert a request to LiftServerRequest
///
protocol LiftServerRequestConvertible {
var Request: LiftServerRequest { get }
}
///
/// The Lift server URLs and request data mappers
///
enum LiftServerURLs : LiftServerRequestConvertible {
///
/// Register the user
///
case UserRegister()
///
/// Login the user
///
case UserLogin()
///
/// Adds an iOS device for the user identified by ``userId``
///
case UserRegisterDevice(/*userId: */NSUUID)
///
/// Retrieves the user's profile for the ``userId``
///
case UserGetPublicProfile(/*userId: */NSUUID)
///
/// Sets the user's profile for the ``userId``
///
case UserSetPublicProfile(/*userId: */NSUUID)
///
/// Gets the user's profile image
///
case UserGetProfileImage(/*userId: */NSUUID)
///
/// Sets the user's profile image
///
case UserSetProfileImage(/*userId: */NSUUID)
///
/// Checks that the account is still there
///
case UserCheckAccount(/*userId: */NSUUID)
///
/// Get supported muscle groups
///
case ExerciseGetMuscleGroups()
///
/// Retrieves all the exercises for the given ``userId`` and ``date``
///
case ExerciseGetExerciseSessionsSummary(/*userId: */NSUUID, /*date: */NSDate)
///
/// Retrieves all the session dates for the given ``userId``
///
case ExerciseGetExerciseSessionsDates(/*userId: */NSUUID)
///
/// Retrieves all the exercises for the given ``userId`` and ``sessionId``
///
case ExerciseGetExerciseSession(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Retrieves future exercise session suggestions for give ``userId``
///
case ExerciseGetExerciseSuggestions(/*userId: */NSUUID)
///
/// Deletes all the exercises for the given ``userId`` and ``sessionId``
///
case ExerciseDeleteExerciseSession(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Starts an exercise session for the given ``userId``
///
case ExerciseSessionStart(/*userId: */NSUUID)
///
/// Abandons the exercise session for the given ``userId`` and ``sessionId``.
///
case ExerciseSessionAbandon(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Starts the replay of an existing session for the given user
///
case ExerciseSessionReplayStart(/*userId: */NSUUID, /* sessionId */ NSUUID)
///
/// Replays the exercise session for the given ``userId`` and ``sessionId``.
///
case ExerciseSessionReplayData(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Submits the data (received from the smartwatch) for the given ``userId``, ``sessionId``
///
case ExerciseSessionSubmitData(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Gets exercise classification examples for the given ``userId`` and ``sessionId``
///
case ExerciseSessionGetClassificationExamples(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Gets exercise classification examples for the given ``userId``
///
case ExerciseGetClassificationExamples(/*userId: */NSUUID)
///
/// Ends the session for the given ``userId`` and ``sessionId``
///
case ExerciseSessionEnd(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Starts the explicit exercise classification for ``userId`` and ``sessionId``
///
case ExplicitExerciseClassificationStart(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Stops the explicit exercise classification for ``userId`` and ``sessionId``
///
case ExplicitExerciseClassificationStop(/*userId: */NSUUID, /*sessionId: */NSUUID)
private struct Format {
private static let simpleDateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter
}()
static func simpleDate(date: NSDate) -> String {
return simpleDateFormatter.stringFromDate(date)
}
}
// MARK: URLStringConvertible
var Request: LiftServerRequest {
get {
let r: LiftServerRequest = {
switch self {
case let .UserRegister: return LiftServerRequest(path: "/user", method: Method.POST)
case let .UserLogin: return LiftServerRequest(path: "/user", method: Method.PUT)
case .UserRegisterDevice(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/device/ios", method: Method.POST)
case .UserGetPublicProfile(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)", method: Method.GET)
case .UserSetPublicProfile(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)", method: Method.POST)
case .UserCheckAccount(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/check", method: Method.GET)
case .UserGetProfileImage(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/image", method: Method.GET)
case .UserSetProfileImage(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/image", method: Method.POST)
case .ExerciseGetMuscleGroups(): return LiftServerRequest(path: "/exercise/musclegroups", method: Method.GET)
case .ExerciseGetExerciseSessionsSummary(let userId, let date): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)?date=\(Format.simpleDate(date))", method: Method.GET)
case .ExerciseGetExerciseSessionsDates(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)", method: Method.GET)
case .ExerciseGetExerciseSession(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.GET)
case .ExerciseDeleteExerciseSession(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.DELETE)
case .ExerciseSessionStart(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/start", method: Method.POST)
case .ExerciseSessionSubmitData(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.PUT)
case .ExerciseSessionEnd(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/end", method: Method.POST)
case .ExerciseSessionAbandon(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/abandon", method: Method.POST)
case .ExerciseSessionReplayStart(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/replay", method: Method.POST)
case .ExerciseSessionReplayData(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/replay", method: Method.PUT)
case .ExerciseSessionGetClassificationExamples(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.GET)
case .ExerciseGetClassificationExamples(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/classification", method: Method.GET)
case .ExplicitExerciseClassificationStart(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.POST)
case .ExplicitExerciseClassificationStop(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.DELETE)
case .ExerciseGetExerciseSuggestions(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/suggestions", method: Method.GET)
}
}()
return r
}
}
}
| 01f0850379a7572175a5dd02d0917665 | 42.102941 | 214 | 0.644376 | false | false | false | false |
cp3hnu/CPImageViewer | refs/heads/master | Classes/CPImageViewerAnimationTransition.swift | mit | 1 | //
// ImageViewerAnimationController.swift
// EdusnsClient
//
// Created by ZhaoWei on 16/2/2.
// Copyright © 2016年 csdept. All rights reserved.
//
import UIKit
final class CPImageViewerAnimationTransition: NSObject, UIViewControllerAnimatedTransitioning {
/// Be false when Push or Present, and true when Pop or Dismiss
var isBack = false
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let containerView = transitionContext.containerView
let style = transitionContext.presentationStyle
let finalFrame = transitionContext.finalFrame(for: toVC)
// Solving the error of location of image view after rotating device and returning to previous controller. See *CPImageViewer.init()*
// The overFullScreen style don't need add toVC.view
// The style is none when CPImageViewer.style is CPImageViewer.Style.push
if style != .overFullScreen && isBack {
containerView.addSubview(toVC.view)
containerView.sendSubviewToBack(toVC.view)
toVC.view.frame = finalFrame
toVC.view.setNeedsLayout()
toVC.view.layoutIfNeeded()
}
let backgroundView = UIView(frame: finalFrame)
backgroundView.backgroundColor = UIColor.black
containerView.addSubview(backgroundView)
let fromImageView: UIImageView! = (fromVC as! CPImageViewerProtocol).animationImageView
let toImageView: UIImageView! = (toVC as! CPImageViewerProtocol).animationImageView
let fromFrame = fromImageView.convert(fromImageView.bounds, to: containerView)
var toFrame = toImageView.convert(toImageView.bounds, to: containerView)
// Solving the error of location of image view in UICollectionView after rotating device and returning to previous controller
if let frame = (toVC as! CPImageViewerProtocol).originalFrame {
//print("frame = ", frame)
toFrame = toVC.view.convert(frame, to: containerView)
//print("toFrame = ", toFrame)
}
let newImageView = UIImageView(frame: fromFrame)
newImageView.image = fromImageView.image
newImageView.contentMode = .scaleAspectFit
containerView.addSubview(newImageView)
if !isBack {
backgroundView.alpha = 0.0
fromImageView.alpha = 0.0
} else {
backgroundView.alpha = 1.0
fromVC.view.alpha = 0.0
}
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions(), animations: {
if !self.isBack {
newImageView.frame = finalFrame
backgroundView.alpha = 1.0
} else {
newImageView.frame = toFrame
backgroundView.alpha = 0.0
}
}, completion: { finished in
newImageView.removeFromSuperview()
backgroundView.removeFromSuperview()
let cancel = transitionContext.transitionWasCancelled
if !self.isBack {
if cancel {
fromImageView.alpha = 1.0
} else {
containerView.addSubview(toVC.view)
}
} else {
if cancel {
fromVC.view.alpha = 1.0
if style != .overFullScreen {
toVC.view.removeFromSuperview()
}
} else {
toImageView.alpha = 1.0
}
}
transitionContext.completeTransition(!cancel)
})
}
}
| d46c2f7c2c0cec6a013c7de601ef2497 | 40.320388 | 141 | 0.601034 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.