repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
zhangao0086/DrawingBoard
|
DrawingBoard/ViewController.swift
|
1
|
7361
|
//
// ViewController.swift
// DrawingBoard
//
// Created by ZhangAo on 15-2-15.
// Copyright (c) 2015年 zhangao. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var brushes = [PencilBrush(), LineBrush(), DashLineBrush(), RectangleBrush(), EllipseBrush(), EraserBrush()]
@IBOutlet var board: Board!
@IBOutlet var topView: UIView!
@IBOutlet var toolbar: UIToolbar!
@IBOutlet var undoButton: UIButton!
@IBOutlet var redoButton: UIButton!
var toolbarEditingItems: [UIBarButtonItem]?
var currentSettingsView: UIView?
@IBOutlet var topViewConstraintY: NSLayoutConstraint!
@IBOutlet var toolbarConstraintBottom: NSLayoutConstraint!
@IBOutlet var toolbarConstraintHeight: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.board.brush = brushes[0]
self.toolbarEditingItems = [
UIBarButtonItem(barButtonSystemItem:.FlexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "完成", style:.Plain, target: self, action: "endSetting")
]
self.toolbarItems = self.toolbar.items
self.setupBrushSettingsView()
self.setupBackgroundSettingsView()
self.board.drawingStateChangedBlock = {(state: DrawingState) -> () in
if state != .Moved {
UIView.beginAnimations(nil, context: nil)
if state == .Began {
self.topViewConstraintY.constant = -self.topView.frame.size.height
self.toolbarConstraintBottom.constant = -self.toolbar.frame.size.height
self.topView.layoutIfNeeded()
self.toolbar.layoutIfNeeded()
self.undoButton.alpha = 0
self.redoButton.alpha = 0
} else if state == .Ended {
UIView.setAnimationDelay(1.0)
self.topViewConstraintY.constant = 0
self.toolbarConstraintBottom.constant = 0
self.topView.layoutIfNeeded()
self.toolbar.layoutIfNeeded()
self.undoButton.alpha = 1
self.redoButton.alpha = 1
}
UIView.commitAnimations()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupBrushSettingsView() {
let brushSettingsView = UINib(nibName: "PaintingBrushSettingsView", bundle: nil).instantiateWithOwner(nil, options: nil).first as! PaintingBrushSettingsView
self.addConstraintsToToolbarForSettingsView(brushSettingsView)
brushSettingsView.hidden = true
brushSettingsView.tag = 1
brushSettingsView.backgroundColor = self.board.strokeColor
brushSettingsView.strokeWidthChangedBlock = {
[unowned self] (strokeWidth: CGFloat) -> Void in
self.board.strokeWidth = strokeWidth
}
brushSettingsView.strokeColorChangedBlock = {
[unowned self] (strokeColor: UIColor) -> Void in
self.board.strokeColor = strokeColor
}
}
func setupBackgroundSettingsView() {
let backgroundSettingsVC = UINib(nibName: "BackgroundSettingsVC", bundle: nil).instantiateWithOwner(nil, options: nil).first as! BackgroundSettingsVC
self.addConstraintsToToolbarForSettingsView(backgroundSettingsVC.view)
backgroundSettingsVC.view.hidden = true
backgroundSettingsVC.view.tag = 2
backgroundSettingsVC.setBackgroundColor(self.board.backgroundColor!)
self.addChildViewController(backgroundSettingsVC)
backgroundSettingsVC.backgroundImageChangedBlock = {
[unowned self] (backgroundImage: UIImage) in
self.board.backgroundColor = UIColor(patternImage: backgroundImage)
}
backgroundSettingsVC.backgroundColorChangedBlock = {
[unowned self] (backgroundColor: UIColor) in
self.board.backgroundColor = backgroundColor
}
}
func addConstraintsToToolbarForSettingsView(view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
self.toolbar.addSubview(view)
self.toolbar.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[settingsView]-0-|",
options: .DirectionLeadingToTrailing,
metrics: nil,
views: ["settingsView" : view]))
self.toolbar.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[settingsView(==height)]",
options: .DirectionLeadingToTrailing,
metrics: ["height" : view.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height],
views: ["settingsView" : view]))
}
func updateToolbarForSettingsView() {
self.toolbarConstraintHeight.constant = self.currentSettingsView!.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height + 44
self.toolbar.setItems(self.toolbarEditingItems, animated: true)
UIView.beginAnimations(nil, context: nil)
self.toolbar.layoutIfNeeded()
UIView.commitAnimations()
self.toolbar.bringSubviewToFront(self.currentSettingsView!)
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
if let err = error {
UIAlertView(title: "错误", message: err.localizedDescription, delegate: nil, cancelButtonTitle: "确定").show()
} else {
UIAlertView(title: "提示", message: "保存成功", delegate: nil, cancelButtonTitle: "确定").show()
}
}
@IBAction func switchBrush(sender: UISegmentedControl) {
assert(sender.tag < self.brushes.count, "!!!")
self.board.brush = self.brushes[sender.selectedSegmentIndex]
}
@IBAction func undo(sender: UIButton) {
self.board.undo()
}
@IBAction func redo(sneder: UIButton) {
self.board.redo()
}
@IBAction func paintingBrushSettings() {
self.currentSettingsView = self.toolbar.viewWithTag(1)
self.currentSettingsView?.hidden = false
self.updateToolbarForSettingsView()
}
@IBAction func backgroundSettings() {
self.currentSettingsView = self.toolbar.viewWithTag(2)
self.currentSettingsView?.hidden = false
self.updateToolbarForSettingsView()
}
@IBAction func saveToAlbum() {
UIImageWriteToSavedPhotosAlbum(self.board.takeImage(), self, "image:didFinishSavingWithError:contextInfo:", nil)
}
@IBAction func endSetting() {
self.toolbarConstraintHeight.constant = 44
self.toolbar.setItems(self.toolbarItems, animated: true)
UIView.beginAnimations(nil, context: nil)
self.toolbar.layoutIfNeeded()
UIView.commitAnimations()
self.currentSettingsView?.hidden = true
}
}
|
mit
|
71c36afd4b00229d34cd0ab0576b6411
| 36.213198 | 164 | 0.636202 | 5.308472 | false | false | false | false |
DanHouk/LocationFlickr-iOS
|
LocationFlickr/ImageViewController.swift
|
1
|
1853
|
//
// ImageViewController.swift
// LocationFlickr
//
// Created by Daniel Houk on 8/13/15.
// Copyright (c) 2015 houkcorp. All rights reserved.
//
import UIKit
class ImageViewController: UIViewController {
@IBOutlet var titleLabel: UILabel!
@IBOutlet var imageImageView: UIImageView!
var flickrImage: FlickrImage!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
loadfullImage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setFlickrImage(_ flickrImage: FlickrImage) {
self.flickrImage = flickrImage
}
func loadfullImage() -> Void {
let url = self.flickrImage.getImageURL("z")
let urlRequest = URLRequest(url: url)
let operationQue:OperationQueue = OperationQueue()
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: operationQue) { response, data, error -> Void in
if(error != nil) {
NSLog("Main Image View Controller", error?.localizedDescription ?? "No message returned")
return
}
if(data != nil) {
self.flickrImage.fullImage = UIImage(data: data!)
self.imageImageView.image = self.flickrImage.fullImage
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
3651b202f83037b6b7c470320ef2a5a1
| 29.883333 | 115 | 0.625472 | 5.035326 | false | false | false | false |
auth0/Lock.swift
|
LockUITests/LockUITests.swift
|
2
|
6579
|
// LockUITests.swift
//
// Copyright (c) 2017 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import Lock
class LockUITests: XCTestCase {
let app = XCUIApplication()
var counter: Int = 0
var prefix: String = ""
override func setUp() {
super.setUp()
setupSnapshot(app)
app.launch()
}
override func tearDown() {
super.tearDown()
}
func testClassicScreenshots() {
// 3 Social, Database, Password Policy Fair, Enterprise AD `bar.com` with ActiveAuth
let app = XCUIApplication()
self.prefix = "A"
self.counter = 0
app.buttons["LOGIN WITH CDN CLASSIC"].tap()
screenshot("Database Social Login")
app.textFields["Email"].tap()
app.textFields["Email"].clearAndEnter(text: "foo")
screenshot("Database Login Email Input Error")
app.textFields["Email"].clearAndEnter(text: "[email protected]")
let passwordLoginSecureTextField = XCUIApplication().scrollViews.otherElements.secureTextFields["Password"]
passwordLoginSecureTextField.tap()
passwordLoginSecureTextField.clearAndEnter(text: " ")
screenshot("Database Login Password Input Error")
passwordLoginSecureTextField.clearAndEnter(text: "Password")
app.scrollViews.otherElements.buttons["Log In"].tap()
sleep(1)
screenshot("Database Login Failed")
sleep(3)
app.scrollViews.otherElements/*@START_MENU_TOKEN@*/.buttons["Sign Up"]/*[[".segmentedControls.buttons[\"Sign Up\"]",".buttons[\"Sign Up\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
screenshot("Database Signup")
app.textFields["Email"].tap()
app.textFields["Email"].clearAndEnter(text: "foo")
screenshot("Database Signup Input Error")
let passwordSignupSecureTextField = XCUIApplication().scrollViews.otherElements.secureTextFields["Password"]
passwordSignupSecureTextField.tap()
screenshot("Database Social Password Policy Empty")
passwordSignupSecureTextField.clearAndEnter(text: "test1")
screenshot("Database Social Password Policy Validation")
app.scrollViews.otherElements.buttons["Log In"].tap()
app.scrollViews.otherElements.buttons["Don’t remember your password?"].tap()
screenshot("Database Forgot Password")
app.textFields["Email"].tap()
app.textFields["Email"].clearAndEnter(text: "foo")
screenshot("Database Forgot Password Email Error")
app.textFields["Email"].clearAndEnter(text: "[email protected]")
app.scrollViews.otherElements.buttons["SEND EMAIL "].tap()
screenshot("Database Forgot Password Send Email Success")
sleep(3)
app.textFields["Email"].tap()
app.textFields["Email"].clearAndEnter(text: "[email protected]")
screenshot("Database Enterprise SSO")
app.scrollViews.otherElements.buttons["LOG IN "].tap()
screenshot("Database Enterprise ActiveAuth")
}
func testPasswordlessScreenshots() {
// Passwordless SMS
let app = XCUIApplication()
self.prefix = "Y"
self.counter = 0
app.buttons["LOGIN WITH CDN PASSWORDLESS"].tap()
screenshot("Passwordless SMS")
app.scrollViews.otherElements.staticTexts["United States"].tap()
screenshot("Passwordless SMS Country Table")
let tablesQuery = app.tables
tablesQuery.searchFields["Search"].tap()
app.searchFields["Search"].typeText("united kingdom")
screenshot("Passwordless SMS Country Table Search")
tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["United Kingdom"]/*[[".cells.staticTexts[\"United Kingdom\"]",".staticTexts[\"United Kingdom\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
let phoneNumberTextField = app.scrollViews.otherElements.textFields["Phone Number"]
phoneNumberTextField.tap()
phoneNumberTextField.clearAndEnter(text: "07")
screenshot("Passwordless SMS Error")
phoneNumberTextField.clearAndEnter(text: "07966000000")
let button = app.scrollViews.children(matching: .other).element(boundBy: 1).children(matching: .other).element(boundBy: 1).children(matching: .button).element
button.tap()
screenshot("Passwordless SMS Login Success")
sleep(3)
let codeTextField = app.scrollViews.otherElements.textFields["Code"]
codeTextField.tap()
codeTextField.typeText("12345")
app.scrollViews.otherElements.buttons["ic submit"].tap()
screenshot("Passwordless SMS Code Failed")
}
private func screenshot(_ description: String) {
self.counter += 1
snapshot("\(prefix)\(String(format: "%02d", counter))-\(description)")
}
}
extension XCUIElement {
func clearAndEnter(text: String) {
guard let stringValue = self.value as? String else {
XCTFail("Tried to clear and enter text into a non string value")
return
}
self.tap()
#if swift(>=4.0)
let deleteString = stringValue.map { _ in XCUIKeyboardKey.delete.rawValue }.joined(separator: "")
#elseif swift(>=3.2)
let deleteString = stringValue.map { _ in XCUIKeyboardKeyDelete }.joined(separator: "")
#else
let deleteString = stringValue.characters.map { _ in XCUIKeyboardKeyDelete }.joined(separator: "")
#endif
self.typeText(deleteString)
self.typeText(text)
}
}
|
mit
|
56360403024f5b6844ebf716bd381a97
| 39.103659 | 198 | 0.672039 | 4.759045 | false | true | false | false |
jjatie/Charts
|
ChartsDemo-macOS/PlaygroundChart.playground/Pages/LineChart.xcplaygroundpage/Contents.swift
|
1
|
4804
|
//
// PlayGround
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// Copyright © 2017 thierry Hentic.
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
/*:
****
[Menu](Menu)
[Previous](@previous) | [Next](@next)
****
*/
import Charts
//: # Line Chart
import Cocoa
import PlaygroundSupport
let r = CGRect(x: 0, y: 0, width: 600, height: 600)
var chartView = LineChartView(frame: r)
//: ### General
chartView.dragEnabled = true
chartView.setScaleEnabled(true)
chartView.drawGridBackgroundEnabled = false
chartView.pinchZoomEnabled = true
chartView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
chartView.borderColor = NSUIColor.black
chartView.borderLineWidth = 1.0
chartView.drawBordersEnabled = true
//: ### xAxis
let xAxis = chartView.xAxis
xAxis.labelFont = NSUIFont.systemFont(ofSize: CGFloat(12.0))
xAxis.labelTextColor = #colorLiteral(red: 0.1764705926, green: 0.01176470611, blue: 0.5607843399, alpha: 1)
xAxis.drawGridLinesEnabled = true
xAxis.drawAxisLineEnabled = true
xAxis.labelPosition = .bottom
xAxis.labelRotationAngle = 0
xAxis.axisMinimum = 0
//: ### LeftAxis
let leftAxis = chartView.leftAxis
leftAxis.labelTextColor = #colorLiteral(red: 0.215686274509804, green: 0.709803921568627, blue: 0.898039215686275, alpha: 1.0)
leftAxis.axisMaximum = 200.0
leftAxis.axisMinimum = 0.0
leftAxis.drawGridLinesEnabled = true
leftAxis.drawZeroLineEnabled = false
leftAxis.granularityEnabled = true
//: ### RightAxis
let rightAxis = chartView.rightAxis
rightAxis.labelTextColor = #colorLiteral(red: 1, green: 0.1474981606, blue: 0, alpha: 1)
rightAxis.axisMaximum = 900.0
rightAxis.axisMinimum = -200.0
rightAxis.drawGridLinesEnabled = false
rightAxis.granularityEnabled = false
//: ### Legend
let legend = chartView.legend
legend.font = NSUIFont(name: "HelveticaNeue-Light", size: CGFloat(12.0))!
legend.textColor = NSUIColor.labelOrBlack
legend.form = .square
legend.drawInside = false
legend.orientation = .horizontal
legend.verticalAlignment = .bottom
legend.horizontalAlignment = .left
//: ### Description
chartView.chartDescription?.enabled = false
//: ### ChartDataEntry
var yVals1 = [ChartDataEntry]()
var yVals2 = [ChartDataEntry]()
var yVals3 = [ChartDataEntry]()
let range = 30.0
for i in 0 ..< 20 {
let mult: Double = range / 2.0
let val = Double(arc4random_uniform(UInt32(mult))) + 50
yVals1.append(ChartDataEntry(x: Double(i), y: val))
}
for i in 0 ..< 20 - 1 {
let mult: Double = range
let val = Double(arc4random_uniform(UInt32(mult))) + 450
yVals2.append(ChartDataEntry(x: Double(i), y: val))
}
for i in 0 ..< 20 {
let mult: Double = range
let val = Double(arc4random_uniform(UInt32(mult))) + 500
yVals3.append(ChartDataEntry(x: Double(i), y: val))
}
var set1 = LineChartDataSet()
var set2 = LineChartDataSet()
var set3 = LineChartDataSet()
set1 = LineChartDataSet(values: yVals1, label: "DataSet 1")
set1.axisDependency = .left
set1.colors = [#colorLiteral(red: 0.215686274509804, green: 0.709803921568627, blue: 0.898039215686275, alpha: 1.0)]
set1.circleColors = [NSUIColor.white]
set1.lineWidth = 2.0
set1.circleRadius = 3.0
set1.fillAlpha = 65 / 255.0
set1.fillColor = #colorLiteral(red: 0.215686274509804, green: 0.709803921568627, blue: 0.898039215686275, alpha: 1.0)
set1.highlightColor = NSUIColor.blue
set1.highlightEnabled = true
set1.drawCircleHoleEnabled = false
set2 = LineChartDataSet(values: yVals2, label: "DataSet 2")
set2.axisDependency = .right
set2.colors = [NSUIColor.red]
set2.circleColors = [NSUIColor.white]
set2.lineWidth = 2.0
set2.circleRadius = 3.0
set2.fillAlpha = 65 / 255.0
set2.fillColor = NSUIColor.red
set2.highlightColor = NSUIColor.red
set2.highlightEnabled = true
set2.drawCircleHoleEnabled = false
set3 = LineChartDataSet(values: yVals3, label: "DataSet 3")
set3.axisDependency = .right
set3.colors = [NSUIColor.green]
set3.circleColors = [NSUIColor.white]
set3.lineWidth = 2.0
set3.circleRadius = 3.0
set3.fillAlpha = 65 / 255.0
set3.fillColor = NSUIColor.yellow.withAlphaComponent(200 / 255.0)
set3.highlightColor = NSUIColor.green
set3.highlightEnabled = true
set3.drawCircleHoleEnabled = false
var dataSets = [LineChartDataSet]()
dataSets.append(set1)
dataSets.append(set2)
dataSets.append(set3)
//: ### LineChartData
let data = LineChartData(dataSets: dataSets)
data.setValueTextColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1))
data.setValueFont(NSUIFont(name: "HelveticaNeue-Light", size: CGFloat(9.0)))
chartView.data = data
chartView.data?.notifyDataChanged()
chartView.notifyDataSetChanged()
/*:---*/
//: ### Setup for the live view
PlaygroundPage.current.liveView = chartView
/*:
****
[Previous](@previous) | [Next](@next)
*/
|
apache-2.0
|
5d95ea44cc89232200989ccfcd1cf476
| 30.392157 | 126 | 0.745367 | 3.571004 | false | false | false | false |
liuduoios/DynamicCollectionView
|
DynamicCollectionView/DynamicCollectionView/DynamicCollectionViewDataSource.swift
|
1
|
1828
|
//
// DynamicCollectionViewDataSource.swift
// DynamicCollectionView
//
// Created by 刘铎 on 15/11/24.
// Copyright © 2015年 liuduoios. All rights reserved.
//
import Foundation
class DynamicCollectionViewDataSource<T>: NSObject, UICollectionViewDataSource, UICollectionViewDelegate {
// ------------------
// MARK: - Properties
// ------------------
weak var collectionView: UICollectionView?
var datas: [T] = [T]()
// --------------------
// MARK: - Internal API
// --------------------
func addData(data: T) {
datas.append(data)
collectionView?.insertItemsAtIndexPaths([NSIndexPath(forItem: datas.count - 1, inSection: 0)])
}
func removeLastData() {
if datas.count == 0 { return }
datas.removeLast()
collectionView?.deleteItemsAtIndexPaths([NSIndexPath(forItem: datas.count, inSection: 0)])
}
func removeAllDatas() {
if datas.count == 0 { return }
datas.removeAll()
collectionView?.reloadData()
}
// ----------------------------------
// MARK: - UICollectionViewDataSource
// ----------------------------------
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return datas.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! DynamicCollectionViewCell<T>
let data = datas[indexPath.row]
cell.bindModel(data)
return cell
}
}
|
mit
|
f3eb40ba7b3405edc10f69dcac43b14b
| 28.868852 | 138 | 0.598572 | 5.551829 | false | false | false | false |
iThinkersTeam/Reports
|
Whats-new-in-Swift-4.playground/Pages/Associated type constraints.xcplaygroundpage/Contents.swift
|
1
|
2606
|
/*:
[Table of contents](Table%20of%20contents) • [Previous page](@previous) • [Next page](@next)
## Associated type constraints
[SE-0142][SE-0142]: associated types in protocols can now be constrained with `where` clauses. This seemingly small change makes the type system much more expressive and facilitates a significant simplification of the standard library. In particular, working with `Sequence` and `Collection` is a lot more intuitive in Swift 4.
[SE-0142]: https://github.com/apple/swift-evolution/blob/master/proposals/0142-associated-types-constraints.md "Swift Evolution Proposal SE-0142: Permit where clauses to constrain associated types"
### `Sequence.Element`
`Sequence` now has its own `Element` associated type. This is made possible by the new generics feature because `associatedtype Element where Element == Iterator.Element` can now be expressed in the type system.
Anywhere you had to write `Iterator.Element` in Swift 3, you can now just write `Element`:
*/
extension Sequence where Element: Numeric {
var sum: Element {
var result: Element = 0
for element in self {
result += element
}
return result
}
}
[1,2,3,4].sum
/*:
Another example: In Swift 3, this extension required more constraints because the type system could not express the idea that the elements of `Collection`’s associated `Indices` type had the same type as `Collection.Index`:
// Required in Swift 3
extension MutableCollection where Index == Indices.Iterator.Element {
*/
extension MutableCollection {
/// Maps over the elements in the collection in place, replacing the existing
/// elements with their transformed values.
mutating func mapInPlace(_ transform: (Element) throws -> Element) rethrows {
for index in indices {
self[index] = try transform(self[index])
}
}
}
/*:
## More generics features
Two more important generics improvements have been accepted for Swift 4, but aren’t implemented yet:
* [SE-0143 Conditional protocol conformances][SE-0143]
* [SE-0157 Recursive protocol constraints][SE-0157]
It looks like recursive constraints will still make it into Swift 4, whereas conditional conformance won’t make the cut.
[SE-0143]: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md
[SE-0157]: https://github.com/apple/swift-evolution/blob/master/proposals/0157-recursive-protocol-constraints.md
*/
/*:
[Table of contents](Table%20of%20contents) • [Previous page](@previous) • [Next page](@next)
*/
|
apache-2.0
|
8c327aaa9e9ee23f99c3577272619814
| 42.2 | 328 | 0.731096 | 4.270181 | false | false | false | false |
cubixlabs/GIST-Framework
|
GISTFramework/Classes/BaseClasses/BaseUISegmentedControl.swift
|
1
|
3527
|
//
// BaseUISegmentedControl.swift
// GISTFramework
//
// Created by Shoaib Abdul on 14/06/2016.
// Copyright © 2016 Social Cubix. All rights reserved.
//
import UIKit
/// BaseUISegmentedControl is a subclass of UISegmentedControl and implements BaseView. It has some extra proporties and support for SyncEngine.
open class BaseUISegmentedControl: UISegmentedControl, BaseView {
//MARK: - Properties
/// Flag for whether to resize the values for iPad.
@IBInspectable open var sizeForIPad:Bool = GIST_CONFIG.sizeForIPad;
/// Background color key from Sync Engine.
@IBInspectable open var bgColorStyle:String? = nil {
didSet {
self.backgroundColor = SyncedColors.color(forKey: bgColorStyle);
}
}
/// Navigation tint Color key from SyncEngine.
@IBInspectable open var tintColorStyle:String? {
didSet {
self.tintColor = SyncedColors.color(forKey: tintColorStyle);
}
}
/// Font name key from Sync Engine.
@IBInspectable open var fontName:String = GIST_CONFIG.fontName {
didSet {
self.font = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad);
}
}
/// Font size/style key from Sync Engine.
@IBInspectable open var fontStyle:String = GIST_CONFIG.fontStyle {
didSet {
self.font = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad);
}
}
/// Extended proprty font for Segmented Controler Items
open var font:UIFont? = nil {
didSet {
self.setTitleTextAttributes([NSAttributedString.Key.font:self.font!], for: UIControl.State());
}
};
/// Overridden constructor to setup/ initialize components.
///
/// - Parameter items: Segment Items
public override init(items: [Any]?) {
super.init(items: items);
self.commontInit();
}
/// Overridden constructor to setup/ initialize components.
///
/// - Parameter frame: View frame
public override init(frame: CGRect) {
super.init(frame: frame);
self.commontInit();
}
/// Required constructor implemented.
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
/// Overridden method to setup/ initialize components.
override open func awakeFromNib() {
super.awakeFromNib();
self.commontInit();
} //F.E.
/// Overridden method to set title using Sync Engine key (Hint '#').
///
/// - Parameters:
/// - title: Segment Title
/// - segment: Segment Index
override open func setTitle(_ title: String?, forSegmentAt segment: Int) {
if let key:String = title , key.hasPrefix("#") == true {
super.setTitle(SyncedText.text(forKey: key), forSegmentAt: segment);
} else {
super.setTitle(title, forSegmentAt: segment);
}
} //P.E.
//MARK: - Methods
/// Common initazier for setting up items.
private func commontInit() {
self.font = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad);
for i:Int in 0..<numberOfSegments {
if let txt:String = titleForSegment(at: i) , txt.hasPrefix("#") == true {
self.setTitle(txt, forSegmentAt: i); // Assigning again to set value from synced data
}
}
} //F.E.
} //CLS END
|
agpl-3.0
|
41d54c82b90577f7d5fada0186a84c16
| 31.054545 | 144 | 0.614294 | 4.70761 | false | false | false | false |
neonichu/NBMaterialDialogIOS
|
Pod/Classes/NBMaterialLoadingDialog.swift
|
1
|
4453
|
//
// NBMaterialLoadingDialog.swift
// NBMaterialDialogIOS
//
// Created by Torstein Skulbru on 02/05/15.
// Copyright (c) 2015 Torstein Skulbru. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Torstein Skulbru
//
// 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.
/**
A simple loading dialog with text message
*/
@objc public class NBMaterialLoadingDialog : NBMaterialDialog {
public var dismissOnBgTap: Bool = false
internal override var kMinimumHeight: CGFloat {
return 72.0
}
/**
Displays a loading dialog with a loading spinner, and a message
- parameter message: The message displayed to the user while its loading
- returns: The Loading Dialog
*/
public class func showLoadingDialogWithText(windowView: UIView, message: String) -> NBMaterialLoadingDialog {
let containerView = UIView()
let circularLoadingActivity = NBMaterialCircularActivityIndicator()
let loadingLabel = UILabel()
circularLoadingActivity.initialize()
circularLoadingActivity.translatesAutoresizingMaskIntoConstraints = false
circularLoadingActivity.lineWidth = 3.5
circularLoadingActivity.tintColor = NBConfig.AccentColor
containerView.addSubview(circularLoadingActivity)
loadingLabel.translatesAutoresizingMaskIntoConstraints = false
loadingLabel.translatesAutoresizingMaskIntoConstraints = false
loadingLabel.font = UIFont.robotoRegularOfSize(14)
loadingLabel.textColor = NBConfig.PrimaryTextDark
loadingLabel.text = message
// TODO: Add support for multiple lines, probably need to fix the dynamic dialog height todo first
loadingLabel.numberOfLines = 1
containerView.addSubview(loadingLabel)
// Setup constraints
let constraintViews = ["spinner": circularLoadingActivity, "label": loadingLabel]
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[spinner(==32)]-16-[label]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[spinner(==32)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
// Center Y needs to be set manually, not through VFL
containerView.addConstraint(
NSLayoutConstraint(
item: circularLoadingActivity,
attribute: NSLayoutAttribute.CenterY,
relatedBy: NSLayoutRelation.Equal,
toItem: containerView,
attribute: NSLayoutAttribute.CenterY,
multiplier: 1,
constant: 0))
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
// Initialize dialog and display
let dialog = NBMaterialLoadingDialog()
dialog.showDialog(windowView, title: nil, content: containerView)
// Start spinner
circularLoadingActivity.startAnimating()
return dialog
}
/**
We dont want to dismiss the loading dialog when user taps bg, so we override it and do nothing
*/
internal override func tappedBg() {
if dismissOnBgTap {
super.tappedBg()
}
}
}
|
mit
|
27eac87b5cb09de327c126f5bd629cb1
| 42.242718 | 201 | 0.713452 | 5.282325 | false | false | false | false |
0x73/SwiftIconFont
|
SwiftIconFont/Classes/AppKit/SwiftIconFont+NSImage.swift
|
1
|
1835
|
//
// SwiftIconFont+NSImage.swift
// SwiftIconFont
//
// Created by Sedat G. ÇİFTÇİ on 4.06.2020.
// Copyright © 2020 Sedat Gökbek ÇİFTÇİ. All rights reserved.
//
#if os(OSX)
import AppKit
import CoreGraphics
public extension NSImage {
convenience init(from font: Fonts, code: String, textColor: NSColor = .black, backgroundColor: NSColor = .clear, size: CGSize) {
if
let image = NSImage.GetSwiftIcon(from: font, code: code, textColor: textColor, backgroundColor: backgroundColor, size: size),
let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil)
{
self.init(cgImage: cgImage, size: size)
} else {
self.init()
}
}
static func GetSwiftIcon(from font: Fonts, code: String, textColor: Color = .black, backgroundColor: Color = .clear, size: CGSize) -> NSImage? {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let fontSize = min(size.width / 1.28571429, size.height)
guard let icon = String.getIcon(from: font, code: code) else { return nil }
let attributes: [NSAttributedString.Key: Any] = [
.font: Font.icon(from: font, ofSize: fontSize),
.foregroundColor: textColor,
.backgroundColor: backgroundColor,
.paragraphStyle: paragraphStyle
]
let attributedString = NSAttributedString(string:icon, attributes: attributes)
let stringSize = attributedString.size()
let image = NSImage(size: stringSize)
image.lockFocus()
attributedString.draw(in: CGRect(x: 0, y: (size.height - fontSize) * 0.5, width: size.width, height: fontSize))
image.unlockFocus()
return image
}
}
#endif
|
mit
|
5560649ed32175ffca3eeb7841c34fa4
| 35.5 | 148 | 0.629589 | 4.324645 | false | false | false | false |
powerytg/Accented
|
Accented/UI/Home/Stream/Templates/StreamJournalLayoutGenerator.swift
|
1
|
4137
|
//
// StreamJournalLayoutGenerator.swift
// Accented
//
// Created by Tiangong You on 5/20/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
class StreamJournalLayoutGenerator: StreamTemplateGenerator {
// Title measuring label
private var titleMeasuringLabel = UILabel()
// Subtitle measuring label
private var subtitleMeasuringLabel = UILabel()
// Description measuring label
private var descMeasuringLabel = UILabel()
required init(maxWidth: CGFloat) {
super.init(maxWidth: maxWidth)
// Initialize labels for measuring
// Title
titleMeasuringLabel.font = StreamCardLayoutSpec.titleFont
titleMeasuringLabel.numberOfLines = StreamCardLayoutSpec.titleLabelLineCount
titleMeasuringLabel.textAlignment = .center
titleMeasuringLabel.lineBreakMode = .byTruncatingMiddle
// Subtitle
subtitleMeasuringLabel.font = StreamCardLayoutSpec.subtitleFont
subtitleMeasuringLabel.numberOfLines = StreamCardLayoutSpec.subtitleLineCount
subtitleMeasuringLabel.textAlignment = .center
subtitleMeasuringLabel.lineBreakMode = .byTruncatingMiddle
// Descriptions
descMeasuringLabel.font = ThemeManager.sharedInstance.currentTheme.descFont
descMeasuringLabel.numberOfLines = StreamCardLayoutSpec.descLineCount
descMeasuringLabel.textAlignment = .center
descMeasuringLabel.lineBreakMode = .byTruncatingTail
}
override func generateLayoutMetadata(_ photos : [PhotoModel]) -> [StreamLayoutTemplate]{
if photos.count == 0 {
return []
}
var templates : [StreamLayoutTemplate] = []
for photo in photos {
let calculatedHeight = estimatedHeightForPhoto(photo)
let template = JournalLayoutTemplate(width: availableWidth, height: calculatedHeight)
templates.append(template)
}
return templates
}
private func estimatedHeightForPhoto(_ photo : PhotoModel) -> CGFloat {
var nextY : CGFloat = StreamCardLayoutSpec.topPadding
// Measure title
titleMeasuringLabel.text = photo.title
titleMeasuringLabel.frame = CGRect(x: 0, y: 0, width: availableWidth - StreamCardLayoutSpec.titleHPadding * 2, height: 0)
titleMeasuringLabel.sizeToFit()
nextY += titleMeasuringLabel.bounds.height + StreamCardLayoutSpec.titleVPadding
// Measure subtitle
subtitleMeasuringLabel.text = photo.user.firstName
subtitleMeasuringLabel.frame = CGRect(x: 0, y: 0, width: availableWidth - StreamCardLayoutSpec.subtitleHPadding * 2, height: 0)
subtitleMeasuringLabel.sizeToFit()
nextY += subtitleMeasuringLabel.bounds.height + StreamCardLayoutSpec.photoVPadding
// Measure photo
let aspectRatio = photo.width / photo.height
let desiredHeight = availableWidth / aspectRatio
let measuredPhotoHeight = min(desiredHeight, StreamCardLayoutSpec.maxPhotoHeight)
nextY += measuredPhotoHeight + StreamCardLayoutSpec.photoVPadding
// Measure description
var descText : String?
if let descData = photo.desc?.data(using: String.Encoding.utf8) {
do {
let strippedText = try NSAttributedString(data: descData, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
descText = strippedText.string
} catch _ {
descText = nil
}
} else {
descText = nil
}
if descText != nil && descText!.characters.count > 0 {
descMeasuringLabel.text = descText
descMeasuringLabel.frame = CGRect(x: 0, y: 0, width: availableWidth - StreamCardLayoutSpec.descHPadding * 2, height: 0)
descMeasuringLabel.sizeToFit()
nextY += descMeasuringLabel.bounds.height
}
nextY += StreamCardLayoutSpec.bottomPadding
return nextY
}
}
|
mit
|
33139c88540fd79e08075d9375648440
| 37.654206 | 167 | 0.667795 | 5.282248 | false | false | false | false |
calkinssean/woodshopBMX
|
WoodshopBMX/Pods/Charts/Charts/Classes/Utils/ChartUtils.swift
|
7
|
12170
|
//
// Utils.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class ChartUtils
{
private static var _defaultValueFormatter: NSNumberFormatter = ChartUtils.generateDefaultValueFormatter()
internal struct Math
{
internal static let FDEG2RAD = CGFloat(M_PI / 180.0)
internal static let FRAD2DEG = CGFloat(180.0 / M_PI)
internal static let DEG2RAD = M_PI / 180.0
internal static let RAD2DEG = 180.0 / M_PI
}
internal class func roundToNextSignificant(number number: Double) -> Double
{
if (isinf(number) || isnan(number) || number == 0)
{
return number
}
let d = ceil(log10(number < 0.0 ? -number : number))
let pw = 1 - Int(d)
let magnitude = pow(Double(10.0), Double(pw))
let shifted = round(number * magnitude)
return shifted / magnitude
}
internal class func decimals(number: Double) -> Int
{
if (number == 0.0)
{
return 0
}
let i = roundToNextSignificant(number: Double(number))
return Int(ceil(-log10(i))) + 2
}
internal class func nextUp(number: Double) -> Double
{
if (isinf(number) || isnan(number))
{
return number
}
else
{
return number + DBL_EPSILON
}
}
/// - returns: the index of the DataSet that contains the closest value on the y-axis. This will return -Integer.MAX_VALUE if failure.
internal class func closestDataSetIndex(valsAtIndex: [ChartSelectionDetail], value: Double, axis: ChartYAxis.AxisDependency?) -> Int
{
var index = -Int.max
var distance = DBL_MAX
for i in 0 ..< valsAtIndex.count
{
let sel = valsAtIndex[i]
if (axis == nil || sel.dataSet?.axisDependency == axis)
{
let cdistance = abs(sel.value - value)
if (cdistance < distance)
{
index = valsAtIndex[i].dataSetIndex
distance = cdistance
}
}
}
return index
}
/// - returns: the minimum distance from a touch-y-value (in pixels) to the closest y-value (in pixels) that is displayed in the chart.
internal class func getMinimumDistance(valsAtIndex: [ChartSelectionDetail], val: Double, axis: ChartYAxis.AxisDependency) -> Double
{
var distance = DBL_MAX
for i in 0 ..< valsAtIndex.count
{
let sel = valsAtIndex[i]
if (sel.dataSet!.axisDependency == axis)
{
let cdistance = abs(sel.value - val)
if (cdistance < distance)
{
distance = cdistance
}
}
}
return distance
}
/// Calculates the position around a center point, depending on the distance from the center, and the angle of the position around the center.
internal class func getPosition(center center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint
{
return CGPoint(
x: center.x + dist * cos(angle * Math.FDEG2RAD),
y: center.y + dist * sin(angle * Math.FDEG2RAD)
)
}
public class func drawText(context context: CGContext, text: String, point: CGPoint, align: NSTextAlignment, attributes: [String : AnyObject]?)
{
var point = point
if (align == .Center)
{
point.x -= text.sizeWithAttributes(attributes).width / 2.0
}
else if (align == .Right)
{
point.x -= text.sizeWithAttributes(attributes).width
}
NSUIGraphicsPushContext(context)
(text as NSString).drawAtPoint(point, withAttributes: attributes)
NSUIGraphicsPopContext()
}
public class func drawText(context context: CGContext, text: String, point: CGPoint, attributes: [String : AnyObject]?, anchor: CGPoint, angleRadians: CGFloat)
{
var drawOffset = CGPoint()
NSUIGraphicsPushContext(context)
if angleRadians != 0.0
{
let size = text.sizeWithAttributes(attributes)
// Move the text drawing rect in a way that it always rotates around its center
drawOffset.x = -size.width * 0.5
drawOffset.y = -size.height * 0.5
var translate = point
// Move the "outer" rect relative to the anchor, assuming its centered
if anchor.x != 0.5 || anchor.y != 0.5
{
let rotatedSize = sizeOfRotatedRectangle(size, radians: angleRadians)
translate.x -= rotatedSize.width * (anchor.x - 0.5)
translate.y -= rotatedSize.height * (anchor.y - 0.5)
}
CGContextSaveGState(context)
CGContextTranslateCTM(context, translate.x, translate.y)
CGContextRotateCTM(context, angleRadians)
(text as NSString).drawAtPoint(drawOffset, withAttributes: attributes)
CGContextRestoreGState(context)
}
else
{
if anchor.x != 0.0 || anchor.y != 0.0
{
let size = text.sizeWithAttributes(attributes)
drawOffset.x = -size.width * anchor.x
drawOffset.y = -size.height * anchor.y
}
drawOffset.x += point.x
drawOffset.y += point.y
(text as NSString).drawAtPoint(drawOffset, withAttributes: attributes)
}
NSUIGraphicsPopContext()
}
internal class func drawMultilineText(context context: CGContext, text: String, knownTextSize: CGSize, point: CGPoint, attributes: [String : AnyObject]?, constrainedToSize: CGSize, anchor: CGPoint, angleRadians: CGFloat)
{
var rect = CGRect(origin: CGPoint(), size: knownTextSize)
NSUIGraphicsPushContext(context)
if angleRadians != 0.0
{
// Move the text drawing rect in a way that it always rotates around its center
rect.origin.x = -knownTextSize.width * 0.5
rect.origin.y = -knownTextSize.height * 0.5
var translate = point
// Move the "outer" rect relative to the anchor, assuming its centered
if anchor.x != 0.5 || anchor.y != 0.5
{
let rotatedSize = sizeOfRotatedRectangle(knownTextSize, radians: angleRadians)
translate.x -= rotatedSize.width * (anchor.x - 0.5)
translate.y -= rotatedSize.height * (anchor.y - 0.5)
}
CGContextSaveGState(context)
CGContextTranslateCTM(context, translate.x, translate.y)
CGContextRotateCTM(context, angleRadians)
(text as NSString).drawWithRect(rect, options: .UsesLineFragmentOrigin, attributes: attributes, context: nil)
CGContextRestoreGState(context)
}
else
{
if anchor.x != 0.0 || anchor.y != 0.0
{
rect.origin.x = -knownTextSize.width * anchor.x
rect.origin.y = -knownTextSize.height * anchor.y
}
rect.origin.x += point.x
rect.origin.y += point.y
(text as NSString).drawWithRect(rect, options: .UsesLineFragmentOrigin, attributes: attributes, context: nil)
}
NSUIGraphicsPopContext()
}
internal class func drawMultilineText(context context: CGContext, text: String, point: CGPoint, attributes: [String : AnyObject]?, constrainedToSize: CGSize, anchor: CGPoint, angleRadians: CGFloat)
{
let rect = text.boundingRectWithSize(constrainedToSize, options: .UsesLineFragmentOrigin, attributes: attributes, context: nil)
drawMultilineText(context: context, text: text, knownTextSize: rect.size, point: point, attributes: attributes, constrainedToSize: constrainedToSize, anchor: anchor, angleRadians: angleRadians)
}
/// - returns: an angle between 0.0 < 360.0 (not less than zero, less than 360)
internal class func normalizedAngleFromAngle(angle: CGFloat) -> CGFloat
{
var angle = angle
while (angle < 0.0)
{
angle += 360.0
}
return angle % 360.0
}
private class func generateDefaultValueFormatter() -> NSNumberFormatter
{
let formatter = NSNumberFormatter()
formatter.minimumIntegerDigits = 1
formatter.maximumFractionDigits = 1
formatter.minimumFractionDigits = 1
formatter.usesGroupingSeparator = true
return formatter
}
/// - returns: the default value formatter used for all chart components that needs a default
internal class func defaultValueFormatter() -> NSNumberFormatter
{
return _defaultValueFormatter
}
internal class func sizeOfRotatedRectangle(rectangleSize: CGSize, degrees: CGFloat) -> CGSize
{
let radians = degrees * Math.FDEG2RAD
return sizeOfRotatedRectangle(rectangleWidth: rectangleSize.width, rectangleHeight: rectangleSize.height, radians: radians)
}
internal class func sizeOfRotatedRectangle(rectangleSize: CGSize, radians: CGFloat) -> CGSize
{
return sizeOfRotatedRectangle(rectangleWidth: rectangleSize.width, rectangleHeight: rectangleSize.height, radians: radians)
}
internal class func sizeOfRotatedRectangle(rectangleWidth rectangleWidth: CGFloat, rectangleHeight: CGFloat, degrees: CGFloat) -> CGSize
{
let radians = degrees * Math.FDEG2RAD
return sizeOfRotatedRectangle(rectangleWidth: rectangleWidth, rectangleHeight: rectangleHeight, radians: radians)
}
internal class func sizeOfRotatedRectangle(rectangleWidth rectangleWidth: CGFloat, rectangleHeight: CGFloat, radians: CGFloat) -> CGSize
{
return CGSize(
width: abs(rectangleWidth * cos(radians)) + abs(rectangleHeight * sin(radians)),
height: abs(rectangleWidth * sin(radians)) + abs(rectangleHeight * cos(radians))
)
}
/// MARK: - Bridging functions
internal class func bridgedObjCGetNSUIColorArray (swift array: [NSUIColor?]) -> [NSObject]
{
var newArray = [NSObject]()
for val in array
{
if (val == nil)
{
newArray.append(NSNull())
}
else
{
newArray.append(val!)
}
}
return newArray
}
internal class func bridgedObjCGetNSUIColorArray (objc array: [NSObject]) -> [NSUIColor?]
{
var newArray = [NSUIColor?]()
for object in array
{
newArray.append(object as? NSUIColor)
}
return newArray
}
internal class func bridgedObjCGetStringArray (swift array: [String?]) -> [NSObject]
{
var newArray = [NSObject]()
for val in array
{
if (val == nil)
{
newArray.append(NSNull())
}
else
{
newArray.append(val!)
}
}
return newArray
}
internal class func bridgedObjCGetStringArray (objc array: [NSObject]) -> [String?]
{
var newArray = [String?]()
for object in array
{
newArray.append(object as? String)
}
return newArray
}
}
|
apache-2.0
|
5cf4bec5c076eaf2b8a4cf8cd6bb311f
| 32.714681 | 224 | 0.572884 | 5.139358 | false | false | false | false |
cwwise/CWWeChat
|
CWWeChat/MainClass/Mine/CWAccountSafetyController.swift
|
2
|
2711
|
//
// CWAccountSafetyController.swift
// CWWeChat
//
// Created by chenwei on 2017/4/11.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
class CWAccountSafetyController: CWBaseTableViewController {
lazy var tableViewManager: CWTableViewManager = {
let tableViewManager = CWTableViewManager(tableView: self.tableView)
tableViewManager.delegate = self
return tableViewManager
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "账号与安全"
setupItemData()
}
func setupItemData() {
let weixinName: String? = "chenwei"
var weixinItem: CWTableViewItem
if weixinName != nil {
weixinItem = CWTableViewItem(title: "微信号", subTitle: weixinName)
weixinItem.showDisclosureIndicator = false
} else {
weixinItem = CWTableViewItem(title: "")
}
let phoneItem = CWTableViewItem(title: "手机号", subTitle: "18810109052")
let section1 = CWTableViewSection(items: [weixinItem, phoneItem])
tableViewManager.addSection(section1)
let passwordItem = CWTableViewItem(title: "微信密码", subTitle: "已设置")
let soundItem = CWTableViewItem(title: "声音锁", subTitle: "已开启")
let section2 = CWTableViewSection(items: [passwordItem, soundItem])
tableViewManager.addSection(section2)
let loginDeviceItem = CWTableViewItem(title: "登陆设备管理")
let moreDeviceItem = CWTableViewItem(title: "更多安全设置")
let section3 = CWTableViewSection(items: [loginDeviceItem, moreDeviceItem])
tableViewManager.addSection(section3)
let weixinSaftItem = CWTableViewItem(title: "微信安全中心")
weixinSaftItem.selectionAction = { (item: CWTableViewItem) in
let url = URL(string: "https://weixin110.qq.com")!
let webViewController = CWWebViewController(url: url)
self.navigationController?.pushViewController(webViewController, animated: true)
}
let footerString = "如果遇到账户信息泄漏, 忘记密码,诈骗等账号安全问题,可前往微信安全中心"
let section4 = CWTableViewSection(footerTitle: footerString, items: [weixinSaftItem])
tableViewManager.addSection(section4)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - CWTableViewManagerDelegate
extension CWAccountSafetyController: CWTableViewManagerDelegate {
}
|
mit
|
15177e4ddd34560873f8e4f282e62a5f
| 32.194805 | 93 | 0.660798 | 4.414508 | false | false | false | false |
Limon-O-O/Lego
|
Frameworks/LegoAPI/Example/LegoAPI/ViewController.swift
|
1
|
4073
|
//
// ViewController.swift
// LegoAPI
//
// Created by Limon-O-O on 03/16/2017.
// Copyright (c) 2017 Limon-O-O. All rights reserved.
//
import UIKit
import RxSwift
import Moya
import LegoProvider
import Decodable
struct Template: Decodable {
init?(json: [String: Any]) {
print("json \(json)")
}
}
class ViewController: UIViewController {
private let disposeBag = DisposeBag()
private let provider = LegoProvider<GitHubUserContent>()
override func viewDidLoad() {
super.viewDidLoad()
downloadRepositories("Limon-O-O")
}
private func downloadRepositories(_ username: String) {
// provider.request(.userRepositories(username)).mapObjects(type: Template.self).subscribe(onNext: { event in
// print(event)
// }, onError: { error in
// self.showAlert("GitHub Fetch", message: error.localizedDescription)
// }).disposed(by: disposeBag)
provider.requestWithProgress((.downloadMoyaWebContent("logo_github.png"))) { progress in
print("progress \(progress) \(Thread.current.name)")
}.mapObjects(type: Template.self).subscribe(onNext: { event in
print(event)
}, onError: { error in
print((error as! ProviderError))
}).disposed(by: disposeBag)
}
fileprivate func showAlert(_ title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(ok)
present(alertController, animated: true, completion: nil)
}
}
// MARK: - Provider support
public enum GitHubUserContent {
case downloadMoyaWebContent(String)
}
extension GitHubUserContent: LegoAPI {
public var baseURL: URL { return URL(string: "https://raw.githubusercontent.com")! }
public var path: String {
switch self {
case .downloadMoyaWebContent(let contentPath):
return "/Moya/Moya/master/web/\(contentPath)"
}
}
public var method: Moya.Method {
switch self {
case .downloadMoyaWebContent:
return .get
}
}
public var parameters: [String: Any]? {
switch self {
case .downloadMoyaWebContent:
return nil
}
}
public var parameterEncoding: ParameterEncoding {
return URLEncoding.default
}
public var task: Task {
switch self {
case .downloadMoyaWebContent:
return .download(.request(DefaultDownloadDestination))
}
}
public var sampleData: Data {
return Data()
}
}
private let DefaultDownloadDestination: DownloadDestination = { temporaryURL, response in
let directoryURLs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
if !directoryURLs.isEmpty {
return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
}
return (temporaryURL, [])
}
private extension String {
var urlEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
}
public enum GitHub {
case zen
case userProfile(String)
case userRepositories(String)
}
extension GitHub: LegoAPI {
public var baseURL: URL { return URL(string: "https://api.github.com")! }
public var path: String {
switch self {
case .zen:
return "/zen"
case .userProfile(let name):
return "/users/\(name.urlEscaped)"
case .userRepositories(let name):
return "/users/\(name.urlEscaped)/repos"
}
}
public var method: Moya.Method {
return .get
}
public var parameters: [String: Any]? {
switch self {
case .userRepositories(_):
return ["sort": "pushed"]
default:
return nil
}
}
/// Provides stub data for use in testing.
public var sampleData: Data {
return Data()
}
}
|
mit
|
de1c273bafdfc4704002f25d67103096
| 24.778481 | 116 | 0.627793 | 4.545759 | false | false | false | false |
brianpartridge/Life
|
Life/Board+Random.swift
|
1
|
1271
|
//
// Board+Random.swift
// Life
//
// Created by Brian Partridge on 10/25/15.
// Copyright © 2015 PearTreeLabs. All rights reserved.
//
import Foundation
public extension Board {
/// Generates a random Board with the give population density.
/// @param populationDensity Approximate percentage of Cells on the generated Board which should be alive.
public static func randomBoard(size: Size, populationDensity: Float) -> Board {
var cells = [Cell]()
for _ in 0..<(size.volume) {
let pivot = Int(populationDensity * 100)
let state = Int(arc4random_uniform(100))
let cell: Cell = state < pivot ? .Alive : .Dead
cells.append(cell)
}
let board = Board(size: size, cells: cells)
return board
}
/// Generate a board filled with dead cells.
public static func emptyBoard(size: Size) -> Board {
let cells = [Cell](count: size.volume, repeatedValue: .Dead)
return Board(size: size, cells: cells)
}
/// Generate a board filled with alive cells.
public static func fullBoard(size: Size) -> Board {
let cells = [Cell](count: size.volume, repeatedValue: .Alive)
return Board(size: size, cells: cells)
}
}
|
mit
|
c6a74d00f50d7995ad047dcee39cc4f2
| 32.421053 | 110 | 0.625984 | 4.136808 | false | false | false | false |
mauriciosantos/Buckets-Swift
|
Source/Bimap.swift
|
3
|
7938
|
//
// Bimap.swift
// Buckets
//
// Created by Mauricio Santos on 4/2/15.
// Copyright (c) 2015 Mauricio Santos. All rights reserved.
//
import Foundation
/// A Bimap is a special kind of dictionary that allows bidirectional lookup between keys and values.
/// All keys and values must be unique.
/// It allows to get, set, or delete a key-value pairs using
/// subscript notation: `bimap[value: aValue] = aKey` or `bimap[key: aKey] = aValue`
///
/// Conforms to `Sequence`, `Collection`, `ExpressibleByDictionaryLiteral`,
/// `Equatable`, `Hashable` and `CustomStringConvertible`.
public struct Bimap<Key: Hashable, Value: Hashable> {
// MARK: Creating a Bimap
/// Constructs an empty bimap.
public init() {}
/// Constructs a bimap with at least the given number of
/// elements worth of storage. The actual capacity will be the
/// smallest power of 2 that's >= `minimumCapacity`.
public init(minimumCapacity: Int) {
keysToValues = [Key: Value](minimumCapacity: minimumCapacity)
valuesToKeys = [Value: Key](minimumCapacity: minimumCapacity)
}
/// Constructs a bimap from a dictionary.
public init(_ elements: Dictionary<Key, Value>) {
for (k, value) in elements {
self[key: k] = value
}
}
/// Constructs a bimap from a sequence of key-value pairs.
public init<S:Sequence>(_ elements: S) where S.Iterator.Element == (Key, Value) {
for (k, value) in elements {
self[key: k] = value
}
}
// MARK: Querying a Bimap
/// Number of key-value pairs stored in the bimap.
public var count: Int {
return keysToValues.count
}
/// Returns `true` if and only if `count == 0`.
public var isEmpty: Bool {
return keysToValues.isEmpty
}
/// A collection containing all the bimap's keys.
public var keys: AnyCollection<Key> {
return AnyCollection(keysToValues.keys)
}
/// A collection containing all the bimap's values.
public var values: AnyCollection<Value> {
return AnyCollection(valuesToKeys.keys)
}
// MARK: Accessing and Changing Bimap Elements
// Gets, sets, or deletes a key-value pair in the bimap using square bracket subscripting.
public subscript(value value: Value) -> Key? {
get {
return valuesToKeys[value]
}
set(newKey) {
let oldKey = valuesToKeys.removeValue(forKey: value)
if let oldKey = oldKey {
keysToValues.removeValue(forKey: oldKey)
}
valuesToKeys[value] = newKey
if let newKey = newKey {
keysToValues[newKey] = value
}
}
}
// Gets, sets, or deletes a key-value pair in the bimap using square bracket subscripting.
public subscript(key key: Key) -> Value? {
get {
return keysToValues[key]
}
set {
let oldValue = keysToValues.removeValue(forKey: key)
if let oldValue = oldValue {
valuesToKeys.removeValue(forKey: oldValue)
}
keysToValues[key] = newValue
if let newValue = newValue {
valuesToKeys[newValue] = key
}
}
}
/// Inserts or updates a value for a given key and returns the previous value
/// for that key if one existed, or `nil` if a previous value did not exist.
/// Subscript access is preferred.
@discardableResult
public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? {
let previous = self[key: key]
self[key: key] = value
return previous
}
/// Removes the key-value pair for the given key and returns its value,
/// or `nil` if a value for that key did not previously exist.
/// Subscript access is preferred.
@discardableResult
public mutating func removeValueForKey(_ key: Key) -> Value? {
let previous = self[key: key]
self[key: key] = nil
return previous
}
/// Removes the key-value pair for the given value and returns its key,
/// or `nil` if a key for that value did not previously exist.
/// Subscript access is preferred.
@discardableResult
public mutating func removeKeyForValue(_ value: Value) -> Key? {
let previous = self[value: value]
self[value: value] = nil
return previous
}
/// Removes all the elements from the bimap, and by default
/// clears the underlying storage buffer.
public mutating func removeAll(keepCapacity keep: Bool = true) {
valuesToKeys.removeAll(keepingCapacity: keep)
keysToValues.removeAll(keepingCapacity: keep)
}
// MARK: Private Properties and Helper Methods
/// Internal structure mapping keys to values.
fileprivate var keysToValues = [Key: Value]()
/// Internal structure values keys to keys.
fileprivate var valuesToKeys = [Value: Key]()
}
extension Bimap: Sequence {
// MARK: Sequence Protocol Conformance
/// Provides for-in loop functionality.
///
/// - returns: A generator over the elements.
public func makeIterator() -> DictionaryIterator<Key, Value> {
return keysToValues.makeIterator()
}
}
extension Bimap: Collection {
// MARK: Collection Protocol Conformance
/// The position of the first element in a non-empty bimap.
///
/// Identical to `endIndex` in an empty bimap
///
/// Complexity: amortized O(1)
public var startIndex: DictionaryIndex<Key, Value> {
return keysToValues.startIndex
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
///
/// Complexity: amortized O(1)
public var endIndex: DictionaryIndex<Key, Value> {
return keysToValues.endIndex
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: DictionaryIndex<Key, Value>) -> DictionaryIndex<Key, Value> {
return keysToValues.index(after: i)
}
public subscript(position: DictionaryIndex<Key, Value>) -> (key: Key, value: Value) {
return keysToValues[position]
}
}
extension Bimap: ExpressibleByDictionaryLiteral {
// MARK: ExpressibleByDictionaryLiteral Protocol Conformance
/// Constructs a bimap using a dictionary literal.
public init(dictionaryLiteral elements: (Key, Value)...) {
self.init(elements)
}
}
extension Bimap: CustomStringConvertible {
// MARK: CustomStringConvertible Protocol Conformance
/// A string containing a suitable textual
/// representation of the bimap.
public var description: String {
return keysToValues.description
}
}
extension Bimap: Hashable {
// MARK: Hashable Protocol Conformance
/// The hash value.
/// `x == y` implies `x.hashValue == y.hashValue`
public var hashValue: Int {
var result = 78
for (key, value) in self {
result = (31 ^ result) ^ key.hashValue
result = (31 ^ result) ^ value.hashValue
}
return result
}
}
// MARK: Bimap Equatable Conformance
/// Returns `true` if and only if the bimaps contain the same key-value pairs.
public func ==<Key, Value>(lhs: Bimap<Key, Value>, rhs: Bimap<Key, Value>) -> Bool {
if lhs.count != rhs.count{
return false
}
for (k,v) in lhs {
if rhs[key: k] != v {
return false
}
}
return true
}
|
mit
|
135211cc00817a6af1c52403cc80b935
| 30.375494 | 101 | 0.617788 | 4.567319 | false | false | false | false |
TrustWallet/trust-wallet-ios
|
Trust/Wallet/ViewControllers/SelectCoinViewController.swift
|
1
|
2052
|
// Copyright DApps Platform Inc. All rights reserved.
import Foundation
import UIKit
import TrustCore
protocol SelectCoinViewControllerDelegate: class {
func didSelect(coin: Coin, in controller: SelectCoinViewController)
}
class SelectCoinViewController: UITableViewController {
lazy var viewModel: SelectCoinsViewModel = {
let elements = coins.map { CoinViewModel(coin: $0) }
return SelectCoinsViewModel(elements: elements)
}()
let coins: [Coin]
weak var delegate: SelectCoinViewControllerDelegate?
init(
coins: [Coin]
) {
self.coins = coins
super.init(style: .grouped)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorColor = StyleLayout.TableView.separatorColor
tableView.rowHeight = UITableViewAutomaticDimension
tableView.register(R.nib.coinViewCell(), forCellReuseIdentifier: R.nib.coinViewCell.name)
tableView.tableFooterView = UIView()
navigationItem.title = viewModel.title
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: R.nib.coinViewCell.name, for: indexPath) as! CoinViewCell
cell.configure(for: viewModel.cellViewModel(for: indexPath))
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSection
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRows(in: section)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewModel = self.viewModel.cellViewModel(for: indexPath)
tableView.deselectRow(at: indexPath, animated: true)
delegate?.didSelect(coin: viewModel.coin, in: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-3.0
|
afc131794442d6b79ef390d1b427baed
| 33.2 | 122 | 0.707602 | 5.029412 | false | false | false | false |
matt-deboer/kuill
|
vendor/github.com/googleapis/gnostic/plugins/gnostic-swift-generator/Sources/gnostic-swift-generator/RenderTypes.swift
|
25
|
5195
|
// Copyright 2017 Google Inc. 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 Foundation
import Gnostic
extension ServiceRenderer {
func renderTypes() -> String {
var code = CodePrinter()
code.print(header)
code.print()
code.print("// Common type declarations")
for serviceType in self.types {
code.print()
code.print("public class " + serviceType.name + " : CustomStringConvertible {")
code.indent()
for serviceTypeField in serviceType.fields {
code.print("public var " + serviceTypeField.name + " : " + serviceTypeField.typeName + " = " + serviceTypeField.initialValue)
}
code.print()
code.print("public init() {}")
code.print()
if serviceType.isInterfaceType {
code.print("public init?(jsonObject: Any?) {")
code.indent()
code.print("if let jsonDictionary = jsonObject as? [String:Any] {")
code.indent()
for serviceTypeField in serviceType.fields {
code.print("if let value : Any = jsonDictionary[\"" + serviceTypeField.jsonName + "\"] {")
code.indent()
if serviceTypeField.isArrayType {
code.print("var outArray : [" + serviceTypeField.elementType + "] = []")
code.print("let array = value as! [Any]")
code.print("for arrayValue in array {")
code.indent()
code.print("if let element = " + serviceTypeField.elementType + "(jsonObject:arrayValue) {")
code.indent()
code.print("outArray.append(element)")
code.outdent()
code.print("}")
code.outdent()
code.print("}")
code.print("self." + serviceTypeField.name + " = outArray")
} else if serviceTypeField.isCastableType {
code.print("self." + serviceTypeField.name + " = value as! " + serviceTypeField.typeName)
} else if serviceTypeField.isConvertibleType {
code.print("self." + serviceTypeField.name + " = " + serviceTypeField.typeName + "(value)")
}
code.outdent()
code.print("}")
}
code.outdent()
code.print("} else {")
code.indent()
code.print("return nil")
code.outdent()
code.print("}")
code.outdent()
code.print("}")
code.print()
code.print("public func jsonObject() -> Any {")
code.indent()
code.print("var result : [String:Any] = [:]")
for serviceTypeField in serviceType.fields {
if serviceTypeField.isArrayType {
code.print("var outArray : [Any] = []")
code.print("for arrayValue in self." + serviceTypeField.name + " {")
code.indent()
code.print("outArray.append(arrayValue.jsonObject())")
code.outdent()
code.print("}")
code.print("result[\"" + serviceTypeField.jsonName + "\"] = outArray")
}
if serviceTypeField.isCastableType {
code.print("result[\"" + serviceTypeField.jsonName + "\"] = self." + serviceTypeField.name)
}
if serviceTypeField.isConvertibleType {
code.print("result[\"" + serviceTypeField.jsonName + "\"] = self." + serviceTypeField.name + ".jsonObject()")
}
}
code.print("return result")
code.outdent()
code.print("}")
code.print()
}
code.print("public var description : String {")
code.indent()
code.print("return \"[" + serviceType.name + "\" + ")
for serviceTypeField in serviceType.fields {
code.print(" \" " + serviceTypeField.name + ": \" + String(describing:self." + serviceTypeField.name + ") + ")
}
code.print("\"]\"")
code.outdent()
code.print("}")
code.outdent()
code.print("}")
}
return code.content
}
}
|
mit
|
73ed9630cbc1933905d2feda3fc2b232
| 45.383929 | 141 | 0.497979 | 5.258097 | false | false | false | false |
crazypoo/PTools
|
Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift
|
2
|
1875
|
//
// AEAD.swift
// CryptoSwift
//
// Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
//
// https://www.iana.org/assignments/aead-parameters/aead-parameters.xhtml
/// Authenticated Encryption with Associated Data (AEAD)
public protocol AEAD {
static var kLen: Int { get } // key length
static var ivRange: Range<Int> { get } // nonce length
}
extension AEAD {
static func calculateAuthenticationTag(authenticator: Authenticator, cipherText: Array<UInt8>, authenticationHeader: Array<UInt8>) throws -> Array<UInt8> {
let headerPadding = ((16 - (authenticationHeader.count & 0xf)) & 0xf)
let cipherPadding = ((16 - (cipherText.count & 0xf)) & 0xf)
var mac = authenticationHeader
mac += Array<UInt8>(repeating: 0, count: headerPadding)
mac += cipherText
mac += Array<UInt8>(repeating: 0, count: cipherPadding)
mac += UInt64(bigEndian: UInt64(authenticationHeader.count)).bytes()
mac += UInt64(bigEndian: UInt64(cipherText.count)).bytes()
return try authenticator.authenticate(mac)
}
}
|
mit
|
69bfa18f53533e56d504bc9e92f2148e
| 45.85 | 217 | 0.738527 | 4.118681 | false | false | false | false |
movabletype/smartphone-app
|
MT_iOS/MT_iOS/Classes/Model/User.swift
|
1
|
1177
|
//
// User.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/05/27.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
import SwiftyJSON
class User: BaseObject {
var displayName: String = ""
var userpicUrl: String = ""
var isSuperuser: Bool = false
override init(json: JSON) {
super.init(json: json)
displayName = json["displayName"].stringValue
userpicUrl = json["userpicUrl"].stringValue
isSuperuser = (json["isSuperuser"].stringValue == "true")
}
override func encodeWithCoder(aCoder: NSCoder) {
super.encodeWithCoder(aCoder)
aCoder.encodeObject(self.displayName, forKey: "displayName")
aCoder.encodeObject(self.userpicUrl, forKey: "userpicUrl")
aCoder.encodeBool(self.isSuperuser, forKey: "isSuperuser")
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.displayName = aDecoder.decodeObjectForKey("displayName") as! String
self.userpicUrl = aDecoder.decodeObjectForKey("userpicUrl") as! String
self.isSuperuser = aDecoder.decodeBoolForKey("isSuperuser")
}
}
|
mit
|
b0b26310387d83961c3e1f09a7a7bbe8
| 29.128205 | 80 | 0.659574 | 4.319853 | false | false | false | false |
ls1intum/sReto
|
Source/sReto/Core/Utils/Logging.swift
|
1
|
3363
|
//
// File.swift
// sReto
//
// Created by Julian Asamer on 13/11/14.
// Copyright (c) 2014 - 2016 Chair for Applied Software Engineering
//
// Licensed under the 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
/**
* Some Logging functionality used within the framework.
*/
// Set the verbosity setting to control the amount of output given by Reto.
let verbositySetting: LogOutputLevel = .verbose
/** The available output levels */
enum LogOutputLevel: Int {
/** Print everything */
case verbose = 4
/** Print medium + high priority */
case normal = 3
/** Print high priority messages only */
case low = 2
/** Do not print messages */
case silent = 1
}
/** Output priority options */
enum LogPriority: Int {
/** Printed only in the "Verbose" setting */
case low = 4
/** Printed in "Nomal" and "Verbose" setting */
case medium = 3
/** Printed in all settings except "Silent" */
case high = 2
}
/** Available message types */
enum LogType {
/** Used for error messages */
case error
/** Used for warning messages*/
case warning
/** Used for information messages*/
case info
}
/**
* Logs a message of given type and priority.
* All messages are prefixed with "Reto", the type and the date of the message.
*
* @param type The type of the message.
* @param priority The priority of the message.
* @param message The message to print.
*/
func log(_ type: LogType, priority: LogPriority, message: String) {
if priority.rawValue > verbositySetting.rawValue { return }
switch type {
case .info: print("Reto[Info] \(Date()): \(message)")
case .warning: print("Reto[Warn] \(Date()): \(message)")
case .error: print("Reto[Error] \(Date()): \(message)")
}
}
/** Convenice method, prints a information message with a given priority. */
func log(_ priority: LogPriority, info: String) {
log(.info, priority: priority, message: info)
}
/** Convenice method, prints a warning message with a given priority. */
func log(_ priority: LogPriority, warning: String) {
log(.warning, priority: priority, message: warning)
}
/** Convenice method, prints a error message with a given priority. */
func log(_ priority: LogPriority, error: String) {
log(.error, priority: priority, message: error)
}
|
mit
|
b94928be7d789b898a8bd953511a11b1
| 35.956044 | 159 | 0.698483 | 4.116279 | false | false | false | false |
wbraynen/SwiftMusicPlayer
|
MusicPlayer/DetailViewController.swift
|
1
|
5124
|
//
// DetailViewController.swift
// MusicPlayer2
//
// Created by William Braynen on 12/2/15.
// Copyright © 2015 Will Braynen. All rights reserved.
//
import UIKit
import AVFoundation
class DetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, AVAudioPlayerDelegate {
@IBOutlet weak var imageview: UIImageView!
@IBOutlet weak var tableview: UITableView!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var backButton: UIButton!
var player: Player!
var paused: Bool
var album: Album! { // This is our `detailItem`. should be an optional?
didSet {
self.player = Player( album: album )! // yeah, i'd rather this crash at this point
self.player.delegate = self
// Update the view.
self.configureView()
}
}
@IBAction func playButtonPressed(sender: UIButton) {
if player.playing {
player.pause()
} else {
player.play()
}
updatePlayButton()
updateNextButton()
self.paused = !self.paused
}
@IBAction func nextButtonPressed(sender: UIButton) {
player.nextTrack()
updateBackButton()
updateNextButton()
}
@IBAction func backButtonPressed(sender: AnyObject) {
player.previousTrack()
updateBackButton()
updateNextButton()
}
required init?(coder aDecoder: NSCoder) {
paused = true
super.init(coder: aDecoder)
}
func configureView() {
if album != nil {
let newTitle = album.description
self.title = newTitle
if self.imageview != nil {
self.imageview.image = UIImage( named: album.filenameFor1400image )
}
self.paused = false
if backButton != nil {
updateBackButton()
}
}
}
override func viewWillDisappear(animated: Bool) {
self.player.stop()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return album.totalTracks
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: DetailCell = tableView.dequeueReusableCellWithIdentifier("DetailCell_ReuseID") as! DetailCell
cell.backgroundColor = UIColor.outerSpaceColor()
let trackNumber = indexPath.row + 1
cell.trackNumberButton.setImage( nil, forState:UIControlState.Normal )
if (trackNumber != self.player.trackNumber) {
// for most tracks, just displaying the track number. no icon. simple.
cell.trackNumberButton.setTitle( "\(trackNumber)", forState: UIControlState.Normal )
} else {
// for current track, display an icon (so the user knows which track is currently playing or will play if the user pressed "play")
let filename = self.player.playing ? "thisTrackIsPlaying.png" : "thisTrackIsPaused.png"
let image = UIImage( named: filename )
cell.trackNumberButton.setImage( image, forState: UIControlState.Normal )
}
cell.trackNameLabel.text = self.player.album.tracks[indexPath.row]
cell.trackDurationLabel.text = "3:54"
return cell
}
func tableView( tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath )
{
let trackNumber = indexPath.row + 1
player.selectTrack( trackNumber )
player.play()
updatePlayButton()
updateBackButton()
updateNextButton()
}
func updateTableRows() {
if let indexPaths = self.tableview.indexPathsForVisibleRows {
self.tableview.reloadRowsAtIndexPaths( indexPaths, withRowAnimation:UITableViewRowAnimation.None )
}
}
func updatePlayButton() {
let filename = player.playing ? "pause.png" : "play.png"
let image = UIImage( named: filename )
playButton.setImage( image, forState: UIControlState.Normal )
}
func updateBackButton() {
self.backButton.enabled = !self.player.firstTrack
updateTableRows()
}
func updateNextButton() {
self.nextButton.enabled = !self.player.lastTrack
updateTableRows()
}
func audioPlayerDidFinishPlaying( playerNotToUse: AVAudioPlayer, successfully flag: Bool) {
if self.player.lastTrack {
updatePlayButton()
} else {
self.player.nextTrack()
self.player.play()
updateNextButton()
updateBackButton()
}
}
}
|
mit
|
5560dccce4933b6775ad73589989e87c
| 30.429448 | 142 | 0.619168 | 5.10259 | false | false | false | false |
bootstraponline/elements_of_interest
|
swift/elements_of_interest/elements_of_interest/main.swift
|
1
|
684
|
// First argument is the app path.
var arguments = Process.arguments.dropFirst()
var snapshotFilePath = arguments.popFirst()
var outputFilePath = arguments.popFirst()
if snapshotFilePath != nil && outputFilePath != nil {
let manager = NSFileManager.defaultManager()
if !manager.fileExistsAtPath(snapshotFilePath!) {
print("Snapshot doesn't exist: \(snapshotFilePath)")
exit(1)
}
let result = Xml().recursiveDescription(Elements.getSnapshotFromFile(snapshotFilePath!))
try! result.writeToFile(outputFilePath!, atomically: false, encoding: NSUTF8StringEncoding)
} else {
print("Usage: elements_of_interest path/to/input path/to/output.uix")
}
|
apache-2.0
|
06492d8f90a11f23d30d31b2e91b5c23
| 37 | 95 | 0.73538 | 4.441558 | false | false | false | false |
lstn-ltd/lstn-sdk-ios
|
Example/Tests/Utilities/MockURLSessionDataTask.swift
|
1
|
796
|
//
// MockURLSessionDataTask.swift
// Lstn
//
// Created by Dan Halliday on 18/10/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
@testable import Lstn
class MockURLSessionDataTask: URLSessionDataTaskType {
var resumeFired = false
var cancelFired = false
var completionHandler: () -> Void
init(completionHandler: @escaping () -> Void) {
self.completionHandler = completionHandler
}
func resume() {
self.resumeFired = true
self.completionHandler()
}
func cancel() {
self.cancelFired = true
}
var state: URLSessionTask.State {
switch (self.resumeFired, self.cancelFired) {
case (false, false): return .suspended
default: return .completed
}
}
}
|
mit
|
71637ff672c579c80c1d523e72a9d3ff
| 19.384615 | 54 | 0.640252 | 4.368132 | false | false | false | false |
Donny8028/Swift-Animation
|
Animated TableViewCell/Animated TableViewCell/FirstTableViewController.swift
|
1
|
2499
|
//
// FirstTableViewController.swift
// Animated TableViewCell
//
// Created by 賢瑭 何 on 2016/5/19.
// Copyright © 2016年 Donny. All rights reserved.
//
import UIKit
class FirstTableViewController: UITableViewController {
var data = ["Personal Life", "Buddy Company", "#30 days Swift Project", "Body movement training", "AppKitchen Studio", "Project Read", "Others" ]
var height: CGFloat?
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 65
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return data.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Constants.CellName, forIndexPath: indexPath) as UITableViewCell
let colorDegrees = CGFloat(indexPath.row) * 0.1
cell.textLabel?.text = data[indexPath.row]
cell.textLabel?.font = UIFont(name: "Avenir Next", size: 16)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.backgroundColor = UIColor(red: colorDegrees, green: 0.0, blue: 1.0, alpha: 1.0)
return cell
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
// Must call it!
height = tableView.bounds.height
let cells = tableView.visibleCells
for cell in cells {
cell.transform = CGAffineTransformMakeTranslation(0.0, height!)
}
var index: NSTimeInterval = 0
for av in cells {
UIView.animateWithDuration(1.0, delay: 0.05 * index, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
av.transform = CGAffineTransformIdentity
}, completion: nil)
index += 1
}
}
struct Constants {
static let CellName = "FirstCell"
}
}
|
mit
|
2c23fb7929510f3d8d74b315103733c3
| 32.2 | 149 | 0.646988 | 4.98998 | false | false | false | false |
SwiftBond/Bond
|
Tests/BondTests/DynamicSubjectTests.swift
|
2
|
2455
|
//
// DynamicSubjectTests.swift
// Bond
//
// Created by Srdan Rasic on 22/09/2016.
// Copyright © 2016 Swift Bond. All rights reserved.
//
import XCTest
import ReactiveKit
@testable import Bond
private class DummyTarget: NSObject {
var value: Int = 5
var recordedElements: [Int] = []
let changes = PublishSubject1<Void>()
}
class DynamicSubjectTests: XCTestCase {
// Starts with current value
// Update signal triggers next event
// Bound signal events are propagated
// Value property is being updated (set closure is called)
func testExecutes() {
let target = DummyTarget()
let subject = DynamicSubject(
target: target,
signal: target.changes.toSignal(),
context: .immediate,
get: { (target) -> Int in target.value },
set: { (target, new) in target.value = new; target.recordedElements.append(new) }
)
subject.expectNext([5, 6, 7, 1, 2, 3])
target.value = 6
target.changes.next(())
XCTAssert(target.value == 6)
subject.on(.next(7))
XCTAssert(target.value == 7)
SafeSignal.sequence([1, 2, 3]).bind(to: subject)
XCTAssert(target.recordedElements == [7, 1, 2, 3])
XCTAssert(target.value == 3)
}
// Target is weakly referenced
// Disposable is disposed when target is deallocated
// Completed event is sent when target is deallocated
func testDisposesOnTargetDeallocation() {
var target: DummyTarget! = DummyTarget()
weak var weakTarget = target
let subject = DynamicSubject(
target: target,
signal: target.changes.toSignal(),
context: .immediate,
get: { (target) -> Int in target.value },
set: { (target, new) in target.value = new; target.recordedElements.append(new) }
)
let signal = PublishSubject1<Int>()
let disposable = signal.bind(to: subject)
subject.expect([.next(5), .next(1), .completed], expectation: expectation(description: "completed"))
signal.next(1)
XCTAssert(weakTarget != nil)
XCTAssert(disposable.isDisposed == false)
XCTAssert(target.recordedElements == [1])
target = nil
signal.next(2)
XCTAssert(weakTarget == nil)
XCTAssert(disposable.isDisposed == true)
waitForExpectations(timeout: 1, handler: nil)
}
}
|
mit
|
6bcf256b76705de21dc7e6d3db31cf76
| 29.675 | 108 | 0.611654 | 4.31283 | false | true | false | false |
charmaex/tama-golem
|
TamaGolem/ViewController.swift
|
2
|
3787
|
//
// ViewController.swift
// TamaGolem
//
// Created by Jan Dammshäuser on 03.02.16.
// Copyright © 2016 Jan Dammshäuser. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController {
var model = Model()
var currentAction: Int = 0
@IBOutlet weak var groundImg: UIImageView!
@IBOutlet weak var skull1: UIImageView!
@IBOutlet weak var skull2: UIImageView!
@IBOutlet weak var skull3: UIImageView!
@IBOutlet var skulls: [UIImageView]!
@IBOutlet weak var heartImg: DragImage!
@IBOutlet weak var foodImg: DragImage!
@IBOutlet weak var petImg: PetImg!
@IBOutlet weak var flowerRockImg: UIImageView!
@IBOutlet weak var playerChooseMenu: UIView!
override func viewDidLoad() {
super.viewDidLoad()
setPet()
view.setBackgroundImage("bg.png")
groundImg.setBackgroundImage("ground.png")
heartImg.targetView = petImg
foodImg.targetView = petImg
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.itemDropped(_:)), name: "droppedOnTarget", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.petLostLife), name: "petLostLife", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.newItem), name: "petHappy", object: nil)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func newItem() {
let rand = arc4random_uniform(2)
currentAction = Int(rand)
switch currentAction {
case Model.ActionsForPet.Food.rawValue:
foodImg.dimImgViewAndDisable(dimming: false)
heartImg.dimImgViewAndDisable(dimming: true)
case Model.ActionsForPet.Heart.rawValue:
foodImg.dimImgViewAndDisable(dimming: true)
heartImg.dimImgViewAndDisable(dimming: false)
default: break
}
}
func setPet() {
let pet = model.pet
petImg.setPlayer(pet.0, deadCount: pet.1)
}
func petLostLife() {
let lifes = model.lifes
if lifes == 1 {
skull1.dimImgView(dimming: false)
} else if lifes == 2 {
skull2.dimImgView(dimming: false)
} else if lifes == 3 {
skull3.dimImgView(dimming: false)
}
if model.isDead {
petImg.deathAnimation()
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
self.playerChooseMenu.hidden = false
})
} else {
newItem()
}
}
func itemDropped(notif: AnyObject) {
heartImg.dimImgViewAndDisable(dimming: true)
foodImg.dimImgViewAndDisable(dimming: true)
model.itemDropped(currentAction)
}
func startGame(pet: Model.Pets, image: UIImage) {
playerChooseMenu.hidden = true
heartImg.dimImgViewAndDisable(dimming: true)
foodImg.dimImgViewAndDisable(dimming: true)
for skull in skulls {
skull.dimImgView(dimming: true)
}
model.startGame(withPet: pet)
flowerRockImg.image = image
setPet()
newItem()
}
@IBAction func playerGolem(sender: AnyObject) {
startGame(.Golem, image: UIImage(named: "rock.png")!)
}
@IBAction func playerSnail(sender: AnyObject) {
startGame(.Snail, image: UIImage(named: "plant.png")!)
}
}
|
gpl-3.0
|
38a2f5b6bdb2571a9859d9dcc0b1c839
| 28.795276 | 153 | 0.609408 | 4.37963 | false | false | false | false |
xmartlabs/Eureka
|
Source/Core/Cell.swift
|
1
|
5483
|
// Cell.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
/// Base class for the Eureka cells
@objc(EurekaBaseCell)
open class BaseCell: UITableViewCell, BaseCellType {
/// Untyped row associated to this cell.
public var baseRow: BaseRow! { return nil }
/// Block that returns the height for this cell.
public var height: (() -> CGFloat)?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public required override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
/**
Function that returns the FormViewController this cell belongs to.
*/
public func formViewController() -> FormViewController? {
var responder: UIResponder? = self
while responder != nil {
if let formVC = responder as? FormViewController {
return formVC
}
responder = responder?.next
}
return nil
}
open func setup() {}
open func update() {}
open func didSelect() {}
/**
If the cell can become first responder. By default returns false
*/
open func cellCanBecomeFirstResponder() -> Bool {
return false
}
/**
Called when the cell becomes first responder
*/
@discardableResult
open func cellBecomeFirstResponder(withDirection: Direction = .down) -> Bool {
return becomeFirstResponder()
}
/**
Called when the cell resigns first responder
*/
@discardableResult
open func cellResignFirstResponder() -> Bool {
return resignFirstResponder()
}
}
/// Generic class that represents the Eureka cells.
open class Cell<T>: BaseCell, TypedCellType where T: Equatable {
public typealias Value = T
/// The row associated to this cell
public weak var row: RowOf<T>!
private var updatingCellForTintColorDidChange = false
/// Returns the navigationAccessoryView if it is defined or calls super if not.
override open var inputAccessoryView: UIView? {
if let v = formViewController()?.inputAccessoryView(for: row) {
return v
}
return super.inputAccessoryView
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
/**
Function responsible for setting up the cell at creation time.
*/
open override func setup() {
super.setup()
}
/**
Function responsible for updating the cell each time it is reloaded.
*/
open override func update() {
super.update()
textLabel?.text = row.title
if #available(iOS 13.0, *) {
textLabel?.textColor = row.isDisabled ? .tertiaryLabel : .label
} else {
textLabel?.textColor = row.isDisabled ? .gray : .black
}
detailTextLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText
}
/**
Called when the cell was selected.
*/
open override func didSelect() {}
override open var canBecomeFirstResponder: Bool {
return false
}
open override func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
if result {
formViewController()?.beginEditing(of: self)
}
return result
}
open override func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
if result {
formViewController()?.endEditing(of: self)
}
return result
}
open override func tintColorDidChange() {
super.tintColorDidChange()
/* Protection from infinite recursion in case an update method changes the tintColor */
if !updatingCellForTintColorDidChange && row != nil {
updatingCellForTintColorDidChange = true
row.updateCell()
updatingCellForTintColorDidChange = false
}
}
/// The untyped row associated to this cell.
public override var baseRow: BaseRow! { return row }
}
|
mit
|
ec7ced4d1e56a03244c5bdda96373e3d
| 30.511494 | 126 | 0.662046 | 5.076852 | false | false | false | false |
malaonline/iOS
|
mala-ios/View/CourseChoosingView/CourseChoosingGradeCell.swift
|
1
|
6013
|
//
// CourseChoosingGradeCell.swift
// mala-ios
//
// Created by 王新宇 on 1/22/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
class CourseChoosingGradeCell: MalaBaseCell {
// MARK: - Property
var prices: [GradeModel]? = [] {
didSet {
self.collectionView.prices = prices
var collectionRow = CGFloat(Int(prices?.count ?? 0)/2)
collectionRow = (prices?.count ?? 0)%2 == 0 ? collectionRow : collectionRow + 1
let collectionHeight = (MalaLayout_GradeSelectionWidth*0.20) * collectionRow + (14*(collectionRow-1))
collectionView.snp.updateConstraints({ (maker) -> Void in
maker.height.equalTo(collectionHeight)
})
}
}
// MARK: - Compontents
private lazy var collectionView: GradeSelectCollectionView = {
let collectionView = GradeSelectCollectionView(
frame: CGRect.zero,
collectionViewLayout: CommonFlowLayout(type: .gradeSelection)
)
return collectionView
}()
// MARK: - Contructed
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func setupUserInterface() {
// Style
adjustForCourseChoosing()
// SubViews
content.addSubview(collectionView)
// Autolayout
content.snp.updateConstraints { (maker) -> Void in
maker.top.equalTo(headerView.snp.bottom).offset(14)
}
collectionView.snp.makeConstraints({ (maker) -> Void in
maker.top.equalTo(content)
maker.left.equalTo(content)
maker.right.equalTo(content)
maker.bottom.equalTo(content)
maker.height.equalTo(10)
})
}
}
// MARK: - GradeSelectCollectionView
private let GradeSelectionCellReuseId = "GradeSelectionCellReuseId"
class GradeSelectCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource {
// MARK: - Property
/// 年级价格数据模型
var prices: [GradeModel]? = [] {
didSet {
self.reloadData()
}
}
/// 当前选择项IndexPath标记
private var currentSelectedIndexPath: IndexPath = IndexPath(item: 0, section: 0)
// MARK: - Constructed
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
configure()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func configure() {
dataSource = self
delegate = self
backgroundColor = UIColor.white
isScrollEnabled = false
register(GradeSelectionCell.self, forCellWithReuseIdentifier: GradeSelectionCellReuseId)
}
// MARK: - Delegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! GradeSelectionCell
// 选中当前选择Cell,并取消其他Cell选择
cell.isSelected = true
(collectionView.cellForItem(at: currentSelectedIndexPath)?.isSelected = false)
currentSelectedIndexPath = indexPath
}
// MARK: - DataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return prices?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GradeSelectionCellReuseId, for: indexPath) as! GradeSelectionCell
cell.grade = prices?[indexPath.row]
// 选中当前选择项
if indexPath == currentSelectedIndexPath {
cell.isSelected = true
MalaOrderOverView.gradeName = cell.grade?.name
}
return cell
}
}
// MARK: - GradeSelectionCell
class GradeSelectionCell: UICollectionViewCell {
// MARK: - Property
var grade: GradeModel? {
didSet {
let title = String(format: "%@ %@/小时", (grade?.name) ?? "", (grade?.prices?[0].price.money) ?? "")
self.button.setTitle(title, for: .normal)
}
}
override var isSelected: Bool {
didSet {
self.button.isSelected = isSelected
if isSelected {
NotificationCenter.default.post(name: MalaNotification_ChoosingGrade, object: self.grade!)
}
}
}
// MARK: - Compontents
private lazy var button: UIButton = {
let button = UIButton(
title: "年级——价格",
borderColor: UIColor(named: .ThemeBlue),
target: self,
action: nil,
borderWidth: 1
)
button.isUserInteractionEnabled = false
return button
}()
// MARK: - Constructed
override init(frame: CGRect) {
super.init(frame: frame)
setupUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func setupUserInterface() {
// SubViews
contentView.addSubview(button)
// Autolayout
button.snp.makeConstraints({ (maker) -> Void in
maker.top.equalTo(contentView)
maker.left.equalTo(contentView)
maker.right.equalTo(contentView)
maker.bottom.equalTo(contentView)
})
}
}
|
mit
|
a483fb24735a030aa8998015f0af2a00
| 29.822917 | 140 | 0.611693 | 5.066781 | false | false | false | false |
whitepixelstudios/Material
|
Sources/iOS/Material+UIImage.swift
|
1
|
15249
|
/*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of CosmicMind 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
import Accelerate
import Motion
@objc(ImageFormat)
public enum ImageFormat: Int {
case png
case jpeg
}
extension UIImage {
/// Width of the UIImage.
open var width: CGFloat {
return size.width
}
/// Height of the UIImage.
open var height: CGFloat {
return size.height
}
}
extension UIImage {
/**
Resizes an image based on a given width.
- Parameter toWidth w: A width value.
- Returns: An optional UIImage.
*/
open func resize(toWidth w: CGFloat) -> UIImage? {
return internalResize(toWidth: w)
}
/**
Resizes an image based on a given height.
- Parameter toHeight h: A height value.
- Returns: An optional UIImage.
*/
open func resize(toHeight h: CGFloat) -> UIImage? {
return internalResize(toHeight: h)
}
/**
Internally resizes the image.
- Parameter toWidth tw: A width.
- Parameter toHeight th: A height.
- Returns: An optional UIImage.
*/
private func internalResize(toWidth tw: CGFloat = 0, toHeight th: CGFloat = 0) -> UIImage? {
var w: CGFloat?
var h: CGFloat?
if 0 < tw {
h = height * tw / width
} else if 0 < th {
w = width * th / height
}
let g: UIImage?
let t: CGRect = CGRect(x: 0, y: 0, width: w ?? tw, height: h ?? th)
UIGraphicsBeginImageContextWithOptions(t.size, false, Screen.scale)
draw(in: t, blendMode: .normal, alpha: 1)
g = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return g
}
}
extension UIImage {
/**
Creates a new image with the passed in color.
- Parameter color: The UIColor to create the image from.
- Returns: A UIImage that is the color passed in.
*/
open func tint(with color: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, Screen.scale)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0.0, y: -size.height)
context.setBlendMode(.multiply)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
context.clip(to: rect, mask: cgImage!)
color.setFill()
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image?.withRenderingMode(.alwaysOriginal)
}
}
extension UIImage {
/**
Creates an Image that is a color.
- Parameter color: The UIColor to create the image from.
- Parameter size: The size of the image to create.
- Returns: A UIImage that is the color passed in.
*/
open class func image(with color: UIColor, size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, Screen.scale)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0.0, y: -size.height)
context.setBlendMode(.multiply)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
color.setFill()
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image?.withRenderingMode(.alwaysOriginal)
}
}
extension UIImage {
/**
Crops an image to a specified width and height.
- Parameter toWidth tw: A specified width.
- Parameter toHeight th: A specified height.
- Returns: An optional UIImage.
*/
open func crop(toWidth tw: CGFloat, toHeight th: CGFloat) -> UIImage? {
let g: UIImage?
let b: Bool = width > height
let s: CGFloat = b ? th / height : tw / width
let t: CGSize = CGSize(width: tw, height: th)
let w = width * s
let h = height * s
UIGraphicsBeginImageContext(t)
draw(in: b ? CGRect(x: -1 * (w - t.width) / 2, y: 0, width: w, height: h) : CGRect(x: 0, y: -1 * (h - t.height) / 2, width: w, height: h), blendMode: .normal, alpha: 1)
g = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return g
}
}
extension UIImage {
/**
Creates a clear image.
- Returns: A UIImage that is clear.
*/
open class func clear(size: CGSize = CGSize(width: 16, height: 16)) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
extension UIImage {
/**
Asynchronously load images with a completion block.
- Parameter URL: A URL destination to fetch the image from.
- Parameter completion: A completion block that is executed once the image
has been retrieved.
*/
open class func contentsOfURL(url: URL, completion: @escaping ((UIImage?, Error?) -> Void)) {
URLSession.shared.dataTask(with: URLRequest(url: url)) { [completion = completion] (data: Data?, response: URLResponse?, error: Error?) in
Motion.async {
if let v = error {
completion(nil, v)
} else if let v = data {
completion(UIImage(data: v), nil)
}
}
}.resume()
}
}
extension UIImage {
/**
Adjusts the orientation of the image from the capture orientation.
This is an issue when taking images, the capture orientation is not set correctly
when using Portrait.
- Returns: An optional UIImage if successful.
*/
open func adjustOrientation() -> UIImage? {
guard .up != imageOrientation else {
return self
}
var transform: CGAffineTransform = .identity
// Rotate if Left, Right, or Down.
switch imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: size.width, y: size.height)
transform = transform.rotated(by: CGFloat(Double.pi))
case .left, .leftMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.rotated(by: CGFloat(Double.pi / 2))
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: size.height)
transform = transform.rotated(by: -CGFloat(Double.pi / 2))
default:break
}
// Flip if mirrored.
switch imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
default:break
}
// Draw the underlying cgImage with the calculated transform.
guard let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: cgImage!.bitsPerComponent, bytesPerRow: 0, space: cgImage!.colorSpace!, bitmapInfo: cgImage!.bitmapInfo.rawValue) else {
return nil
}
context.concatenate(transform)
switch imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
default:
context.draw(cgImage!, in: CGRect(origin: .zero, size: size))
}
guard let cgImage = context.makeImage() else {
return nil
}
return UIImage(cgImage: cgImage)
}
}
/**
Creates an effect buffer for images that already have effects.
- Parameter context: A CGContext.
- Returns: vImage_Buffer.
*/
fileprivate func createEffectBuffer(context: CGContext) -> vImage_Buffer {
let data = context.data
let width = vImagePixelCount(context.width)
let height = vImagePixelCount(context.height)
let rowBytes = context.bytesPerRow
return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
}
extension UIImage {
/**
Applies a blur effect to a UIImage.
- Parameter radius: The radius of the blur effect.
- Parameter tintColor: The color used for the blur effect (optional).
- Parameter saturationDeltaFactor: The delta factor for the saturation of the blur effect.
- Returns: a UIImage.
*/
open func blur(radius: CGFloat = 0, tintColor: UIColor? = nil, saturationDeltaFactor: CGFloat = 0) -> UIImage? {
var effectImage = self
let screenScale = Screen.scale
let imageRect = CGRect(origin: .zero, size: size)
let hasBlur = radius > CGFloat(Float.ulpOfOne)
let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > CGFloat(Float.ulpOfOne)
if hasBlur || hasSaturationChange {
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let inContext = UIGraphicsGetCurrentContext()!
inContext.scaleBy(x: 1.0, y: -1.0)
inContext.translateBy(x: 0, y: -size.height)
inContext.draw(cgImage!, in: imageRect)
var inBuffer = createEffectBuffer(context: inContext)
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let outContext = UIGraphicsGetCurrentContext()!
var outBuffer = createEffectBuffer(context: outContext)
if hasBlur {
let a = sqrt(2 * .pi)
let b = CGFloat(a) / 4
let c = radius * screenScale
let d = c * 3.0 * b
var e = UInt32(floor(d + 0.5))
if 1 != e % 2 {
e += 1 // force radius to be odd so that the three box-blur methodology works.
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, e, e, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&outBuffer, &inBuffer, nil, 0, 0, e, e, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, e, e, nil, imageEdgeExtendFlags)
}
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s = saturationDeltaFactor
let floatingPointSaturationMatrix: [CGFloat] = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
]
let divisor: CGFloat = 256
let matrixSize = floatingPointSaturationMatrix.count
var saturationMatrix = [Int16](repeating: 0, count: matrixSize)
for i in 0..<matrixSize {
saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor))
}
if hasBlur {
vImageMatrixMultiply_ARGB8888(&outBuffer, &inBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
effectImageBuffersAreSwapped = true
} else {
vImageMatrixMultiply_ARGB8888(&inBuffer, &outBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
}
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
if effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
}
// Set up output context.
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let outputContext = UIGraphicsGetCurrentContext()!
outputContext.scaleBy(x: 1.0, y: -1.0)
outputContext.translateBy(x: 0, y: -size.height)
// Draw base image.
outputContext.draw(cgImage!, in: imageRect)
// Draw effect image.
if hasBlur {
outputContext.saveGState()
outputContext.draw(effectImage.cgImage!, in: imageRect)
outputContext.restoreGState()
}
// Add in color tint.
if let v = tintColor {
outputContext.saveGState()
outputContext.setFillColor(v.cgColor)
outputContext.fill(imageRect)
outputContext.restoreGState()
}
// Output image is ready.
let outputImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return outputImage
}
}
|
bsd-3-clause
|
61d136e7a020fd6e0a93f64d23b094d8
| 36.375 | 237 | 0.599056 | 4.845567 | false | false | false | false |
alexbasson/swift-experiment
|
SwiftExperimentTests/Presenters/MovieCellPresenterSpec.swift
|
1
|
1933
|
import Quick
import Nimble
import SwiftExperiment
class MockUITableView: UITableView {
var identifier: String!
override func registerClass(cellClass: AnyClass?,forCellReuseIdentifier identifier: String) {
self.identifier = identifier
}
}
class MovieCellPresenterSpec: QuickSpec {
override func spec() {
var subject: MovieCellPresenter!
let movie = Movie()
let imageService = MockImageService()
beforeEach {
imageService.resetSentMessages()
subject = MovieCellPresenter(movie: movie, imageService: imageService)
}
describe("registerInTableView()") {
var tableView: MockUITableView!
beforeEach {
tableView = MockUITableView()
MovieCellPresenter.register(tableView: tableView)
}
it("registers the movie cell in the table view") {
expect(tableView.identifier).to(equal("MovieTableViewCell"))
}
}
describe("presentInCell") {
var movieCell: MovieTableViewCell!
beforeEach {
let vc = MoviesViewController.getInstanceFromStoryboard("Main") as! MoviesViewController
let tableView = vc.moviesView.tableView
if let tableView = tableView {
movieCell = tableView.dequeueReusableCellWithIdentifier(MovieTableViewCell.reuseIdentifier()) as! MovieTableViewCell
subject.present(movieCell)
} else {
XCTFail()
}
}
it("sets the title label on the cell") {
expect(movieCell.titleLabel.text).to(equal("A title"))
}
it("messages the image service to fetch the poster image") {
expect(imageService.fetchImage.wasReceived).to(beTrue())
}
}
describe("cellIdentifier()") {
it("returns the cell's reuse identifier") {
expect(subject.cellIdentifier()).to(equal("MovieTableViewCell"))
}
}
}
}
|
mit
|
ca367479533f9eee1c60720a14aae8d2
| 28.287879 | 128 | 0.640973 | 5.26703 | false | false | false | false |
exponent/exponent
|
packages/expo-dev-launcher/ios/EXDevLauncherPendingDeepLinkRegistry.swift
|
2
|
809
|
// Copyright 2015-present 650 Industries. All rights reserved.
import Foundation
@objc
public class EXDevLauncherPendingDeepLinkRegistry: NSObject {
private var listeners: [EXDevLauncherPendingDeepLinkListener] = []
@objc
public var pendingDeepLink: URL? {
didSet {
if pendingDeepLink != nil {
listeners.forEach { $0.onNewPendingDeepLink(pendingDeepLink!) }
}
}
}
@objc
public func subscribe(_ listener: EXDevLauncherPendingDeepLinkListener) {
self.listeners.append(listener)
}
@objc
public func unsubscribe(_ listener: EXDevLauncherPendingDeepLinkListener) {
self.listeners.removeAll { $0 === listener }
}
@objc
public func consumePendingDeepLink() -> URL? {
let result = pendingDeepLink
pendingDeepLink = nil
return result
}
}
|
bsd-3-clause
|
eb35ba2a52873b9a504c0e013ba308f1
| 22.794118 | 77 | 0.71199 | 4.372973 | false | false | false | false |
praca-japao/156
|
PMC156Inteligente/MyRequestTableViewController.swift
|
1
|
2935
|
//
// MyRequestTableViewController.swift
// PMC156Inteligente
//
// Created by Giovanni Pietrangelo on 11/29/15.
// Copyright © 2015 Sigma Apps. All rights reserved.
//
import UIKit
class MyRequestTableViewController: UITableViewController {
// MARK: - Attributes
private let reuseIdentifier = "MyRequest"
override func viewDidLoad() {
super.viewDidLoad()
tableViewSettings()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableViewSettings() {
tableView.backgroundColor = UIColor(red: 179.0/255, green: 210.0/255, blue: 58.0/255, alpha: 1.0)
tableView.separatorStyle = .None
tableView.rowHeight = 325
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as? MyRequestTableViewCell
return cell!
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
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 to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
gpl-2.0
|
7fd19993af7784ad42f96b0a5242a2af
| 31.966292 | 157 | 0.687117 | 5.296029 | false | false | false | false |
dndydon/ParticleTracker
|
ParticleTracker/ParticleTracker.swift
|
1
|
1185
|
//
// ParticleTracker.swift
// ParticleTracker
//
// Created by Don Sleeter on 7/28/17.
// Copyright © 2017 Don Sleeter. All rights reserved.
//
import Foundation
enum OptionType: String {
case palindrome = "p"
case anagram = "a"
case help = "h"
case unknown
init(value: String) {
switch value {
case "p": self = .palindrome
case "a": self = .anagram
case "h": self = .help
default: self = .unknown
}
}
}
class ParticleTracker {
let consoleIO = ConsoleIO()
func commandLineMode() {
consoleIO.printUsage()
//1
let argCount = CommandLine.argc
//2
let argument = CommandLine.arguments.dropFirst()
//let argument = CommandLine.arguments[1]
//3
let args = argument.split(separator: " ")
// let (option, value) = getOption(argument[.from(argument.startIndex, offsetBy: 1)..<index])
let (option, value) = getOption(String(describing: args))
//4
consoleIO.writeMessage("Argument count: \(argCount) Option: \(option) value: \(value)")
}
func getOption(_ option: String) -> (option:OptionType, value: String) {
return (OptionType(value: option), option)
}
}
|
mit
|
8982f2062c6150eaf528563a10258a59
| 20.527273 | 96 | 0.629223 | 3.665635 | false | false | false | false |
Druware/Common
|
CGIScript/showEnvironment/RESTfulEnvironment.swift
|
2
|
4877
|
//
// RESTfulEnvironment.swift
// CGIScript
//
// Created by Andy Satori on 12/27/15.
// Copyright © 2015 Druware Software Designs. All rights reserved.
//
import Foundation
import CGIScript
public class RESTfulEnvironment {
var _request : Request;
var _errorCode : Int?;
var _errorCondition : String?;
var _exitStatus : Int;
public init(request : Request) {
_request = request;
_exitStatus = 0;
print("");
if (_request.method == "DELETE")
{
self.delete();
} else if (_request.method == "PUT")
{
self.put();
} else if (_request.method == "POST")
{
self.post();
} else {
self.get(); // this is the default
}
_request.response.write();
}
public func dictionaryForError() -> Dictionary<String, AnyObject> {
var child : Dictionary<String, String> = Dictionary<String, String>();
var this : Dictionary<String, AnyObject> = Dictionary<String, AnyObject>();
child["errorCode"] = String(_errorCode!);
child["errorCondition"] = _errorCondition!;
this["error"] = child;
return this;
}
public func delete() {
// delete. not valid in this implementation
}
public func put() {
// update. not valid in this implementation
}
public func post() {
// create. not valid in this implementation
}
public func get() {
// read. all functionality is demonstrated here.
print("1");
// for the moment, we are sending plain text
_request.response.contentType = "text/plain";
// no parameters, *, or all passed in
var parameter : String?;
parameter = nil;
var shouldShowAll : Bool = false;
if (_request.parameters == nil) {
shouldShowAll = true;
} else {
print("debug: param count \(_request.parameters!.count)");
if (_request.parameters!.count > 0) {
parameter = _request.parameters![0];
}
shouldShowAll = (parameter == nil);
if (shouldShowAll == false) {
shouldShowAll = (parameter == "");
}
if (shouldShowAll == false) {
shouldShowAll = (parameter == "*");
}
if (shouldShowAll == false) {
shouldShowAll = (parameter == "all");
}
}
print("debug: shouldShowAll \(shouldShowAll)");
if (shouldShowAll == true) {
// move the environment variables into a JSON conforming object
var dictionary : Dictionary<String, AnyObject> = Dictionary<String, AnyObject>();
for (keyName, _) in _request.server.allVariables() {
if let value = _request.server.allVariables()[keyName] {
dictionary[keyName] = value;
}
}
// show all
// for the moment, just send it as text, but this should format
// the entire thing in a properly formed JSON object.
let json : String = CreateJSONFromObject(dictionary);
_request.response.content = json;
} else {
var dictionary : Dictionary<String, AnyObject> = Dictionary<String, AnyObject>();
if let value = _request.server.allVariables()[_request.parameters![0]] {
dictionary[_request.parameters![0]] = value;
}
// show all
// for the moment, just send it as text, but this should format
// the entire thing in a properly formed JSON object.
let json : String = CreateJSONFromObject(dictionary);
_request.response.content = json;
}
_exitStatus = 0;
}
func CreateJSONFromObject(object: AnyObject, prettyPrinted:Bool = true) -> String {
let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0)
if NSJSONSerialization.isValidJSONObject(object) {
do{
let data = try NSJSONSerialization.dataWithJSONObject(object, options: options)
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string as String
}
}catch {
print("error")
//Access error here
}
}
return ""
}
public var exitStatus : Int {
get {
return _exitStatus;
}
}
}
|
bsd-2-clause
|
3aded825789c9e58613de5124b8e9ade
| 29.475 | 108 | 0.513126 | 5.214973 | false | false | false | false |
jkolb/midnightbacon
|
MidnightBacon/Services/OAuthService.swift
|
1
|
4965
|
//
// OAuthService.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// 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 FranticApparatus
import Common
import Reddit
class OAuthService {
var gateway: Gateway!
var redditRequest: RedditRequest!
var insecureStore: InsecureStore!
var secureStore: SecureStore!
private var promise: Promise<OAuthAccessToken>!
private var isResetting = false
func lurkerMode() {
insecureStore.lastAuthenticatedUsername = nil
isResetting = true
}
func switchToUsername(username: String) {
insecureStore.lastAuthenticatedUsername = username
isResetting = true
}
func aquireAccessToken(forceRefresh forceRefresh: Bool = false) -> Promise<OAuthAccessToken> {
if promise == nil || isResetting || forceRefresh {
isResetting = false
if let username = insecureStore.lastAuthenticatedUsername {
if username.isEmpty {
promise = aquireApplicationAccessToken(forceRefresh: forceRefresh)
} else {
promise = aquireUserAccessToken(username, forceRefresh: forceRefresh)
}
} else {
promise = aquireApplicationAccessToken(forceRefresh: forceRefresh)
}
}
return promise
}
func aquireUserAccessToken(username: String, forceRefresh: Bool) -> Promise<OAuthAccessToken> {
return secureStore.loadAccessTokenForUsername(username).thenWithContext(self, { (strongSelf, accessToken) -> Promise<OAuthAccessToken> in
if accessToken.isExpired || forceRefresh {
return strongSelf.refreshUserAccessToken(accessToken)
} else {
return Promise(accessToken)
}
}).recoverWithContext(self, { (strongSelf, reason) -> Promise<OAuthAccessToken> in
return strongSelf.aquireApplicationAccessToken(forceRefresh: forceRefresh)
})
}
func aquireApplicationAccessToken(forceRefresh forceRefresh: Bool) -> Promise<OAuthAccessToken> {
return secureStore.loadDeviceID().recoverWithContext(self, { (strongSelf, reason) -> Promise<NSUUID> in
return strongSelf.secureStore.saveDeviceID(NSUUID())
}).thenWithContext(self, { (strongSelf, deviceID) -> Promise<OAuthAccessToken> in
return strongSelf.aquireApplicationAccessTokenForDeviceID(deviceID, forceRefresh: forceRefresh)
})
}
func aquireApplicationAccessTokenForDeviceID(deviceID: NSUUID, forceRefresh: Bool) -> Promise<OAuthAccessToken> {
return secureStore.loadAccessTokenForDeviceID(deviceID).thenWithContext(self, { (strongSelf, accessToken) -> Promise<OAuthAccessToken> in
if accessToken.isExpired || forceRefresh {
return strongSelf.generateApplicationAccessTokenForDeviceID(deviceID)
} else {
return Promise(accessToken)
}
}).recoverWithContext(self, { (strongSelf, reason) -> Promise<OAuthAccessToken> in
return strongSelf.generateApplicationAccessTokenForDeviceID(deviceID)
})
}
func generateApplicationAccessTokenForDeviceID(deviceID: NSUUID) -> Promise<OAuthAccessToken> {
let installedClientRequest = redditRequest.applicationAccessToken(deviceID)
return gateway.performRequest(installedClientRequest).thenWithContext(self, { (strongSelf, accessToken) -> Promise<OAuthAccessToken> in
return strongSelf.secureStore.saveAccessToken(accessToken, forDeviceID: deviceID)
})
}
func refreshUserAccessToken(accessToken: OAuthAccessToken) -> Promise<OAuthAccessToken> {
let refreshTokenRequest = redditRequest.refreshAccessToken(accessToken)
return gateway.performRequest(refreshTokenRequest)
}
}
|
mit
|
fae995c1382fdff092cbe43e88b2b61a
| 44.550459 | 145 | 0.700101 | 5.315846 | false | false | false | false |
Swiftodon/Leviathan
|
Leviathan/Sources/Model/Session/SessionModel.swift
|
1
|
4925
|
//
// SessionModel.swift
// Leviathan
//
// Created by Thomas Bonk on 12.11.22.
// Copyright 2022 The Swiftodon Team
//
// 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 MastodonSwift
import Valet
fileprivate extension String {
static let Sessions = "\(String.ApplicationBundleId).SESSIONS"
}
class SessionModel: ObservableObject, Codable {
// MARK: - Public Static Properties
static var shared: SessionModel = { decodeSessionModel() }()
// MARK: - Public Properties
@Published
private(set) var sessions: [Session]
@Published
private(set) var currentSessionIndex: Int = -1 {
didSet {
save()
}
}
var currentSession: Session? {
guard
currentSessionIndex >= 0 && currentSessionIndex < sessions.count
else {
return nil
}
let session = sessions[currentSessionIndex]
if session.auth == nil {
session.auth = MastodonClient(baseURL: session.url).getAuthenticated(token: session.accessToken.token)
}
return session
}
// MARK: - Private Static Properties
private static var valet: Valet = {
Valet.iCloudValet(with: Identifier(nonEmpty: .ApplicationBundleId)!, accessibility: .whenUnlocked)
}()
// MARK: - Initialization
private class func decodeSessionModel() -> SessionModel {
if
let data = try? valet.object(forKey: .Sessions),
let model = try? JSONDecoder().decode(SessionModel.self, from: data) {
return model
}
return SessionModel()
}
private init() {
sessions = []
}
// MARK: - Public Methods
func save() {
DispatchQueue.global(qos: .background).async {
if let data = try? JSONEncoder().encode(self) {
try? SessionModel.valet.setObject(data, forKey: .Sessions)
}
}
}
func logon(instanceURL: URL) {
Task {
let scopes = ["read", "write", "follow"]
let client = MastodonClient(baseURL: instanceURL)
let app = try await client.createApp(
named: "Leviathan",
redirectUri: "leviathan://oauth-callback",
scopes: scopes,
website: URL(string: "https://github.com/Swiftodon/Leviathan")!)
let authToken = try await client.authenticate(app: app, scope: scopes)
let auth = client.getAuthenticated(token: authToken.oauthToken)
let account = try await auth.verifyCredentials()
let session = Session(
url: instanceURL,
accessToken: AccessToken(credential: authToken),
account: account)
update {
self.sessions.append(session)
self.save()
}
}
}
func remove(session: Session) {
if let index = sessions.firstIndex(where: { $0 == session }) {
var oldSelectedSession: Session! = nil
if index == currentSessionIndex {
currentSessionIndex = -1
} else {
oldSelectedSession = sessions[currentSessionIndex]
}
sessions.remove(at: index)
if let oldSelectedSession {
select(session: oldSelectedSession)
}
save()
}
}
func select(session: Session) {
guard
currentSession != session
else {
return
}
if let index = sessions.firstIndex(where: { $0 == session }) {
currentSessionIndex = index
}
}
// MARK: - Codable
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
sessions = try container.decode([Session].self, forKey: .sessions)
currentSessionIndex = try container.decode(Int.self, forKey: .currentSessionIndex)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(sessions, forKey: .sessions)
try container.encode(currentSessionIndex, forKey: .currentSessionIndex)
}
private enum CodingKeys: CodingKey {
case sessions
case currentSessionIndex
}
}
|
apache-2.0
|
81eaf784d35eb4fc57d9004fce7b9641
| 26.982955 | 114 | 0.594721 | 4.758454 | false | false | false | false |
yonaskolb/SwagGen
|
Sources/Swagger/Schema/IntegerSchema.swift
|
1
|
1393
|
import JSONUtilities
public struct IntegerSchema {
public let format: IntegerFormat?
public let minimum: Int?
public let maximum: Int?
public let exclusiveMinimum: Int?
public let exclusiveMaximum: Int?
public let multipleOf: Int?
public init(format: IntegerFormat? = nil,
minimum: Int? = nil,
maximum: Int? = nil,
exclusiveMinimum: Int? = nil,
exclusiveMaximum: Int? = nil,
multipleOf: Int? = nil) {
self.format = format
self.minimum = minimum
self.maximum = maximum
self.exclusiveMinimum = exclusiveMinimum
self.exclusiveMaximum = exclusiveMaximum
self.multipleOf = multipleOf
}
}
public enum IntegerFormat: String {
case int8
case int16
case int32
case int64
case uint8
case uint16
case uint32
case uint64
}
extension IntegerSchema {
public init(jsonDictionary: JSONDictionary) {
format = jsonDictionary.json(atKeyPath: "format")
minimum = jsonDictionary.json(atKeyPath: "minimum")
maximum = jsonDictionary.json(atKeyPath: "maximum")
exclusiveMinimum = jsonDictionary.json(atKeyPath: "exclusiveMinimum")
exclusiveMaximum = jsonDictionary.json(atKeyPath: "exclusiveMaximum")
multipleOf = jsonDictionary.json(atKeyPath: "multipleOf")
}
}
|
mit
|
303f0735ccbe06626ec53d108f0fe7df
| 28.020833 | 77 | 0.648241 | 4.722034 | false | false | false | false |
zwaldowski/OneTimePad
|
OneTimePad/Random.swift
|
1
|
3694
|
//
// Random.swift
// OneTimePad
//
// Created by Zachary Waldowski on 9/20/15.
// Copyright © 2015 Zachary Waldowski. All rights reserved.
//
import CommonCryptoShim.Private
/// A collection that may be accessed efficiently in a contiguous manner from C.
public protocol BufferType: RangeReplaceableCollectionType {
/// Construct an instance that contains `count` elements having the
/// value `repeatedValue`.
init(count: Index.Distance, repeatedValue: Generator.Element)
/// Call `body(p)`, where `p` is a pointer to the type's mutable
/// contiguous storage. If no such storage exists, it must first be created.
///
/// Often, the optimizer can eliminate bounds- and uniqueness-checks
/// within an algorithm, but when that fails, invoking the same algorithm
/// on the contiguous storage lets you trade safety for speed.
///
/// - warning: Do not rely on anything about `self` (the reciever of this
/// method) during the execution of `body`: it may not appear to have its
/// correct value. Instead, use only the buffer passed to `body`.
mutating func withUnsafeMutableBufferPointer(@noescape body: (inout UnsafeMutableBufferPointer<Generator.Element>) throws -> ()) rethrows
}
public extension BufferType where Generator.Element: IntegerType {
/// Construct an instance that contains `count` elements having the
/// value `repeatedValue`.
public init(count: Index.Distance, repeatedValue: Generator.Element) {
self.init()
appendContentsOf(Repeat(count: numericCast(count), repeatedValue: repeatedValue))
}
}
extension Array: BufferType {}
extension ArraySlice: BufferType {}
extension ContiguousArray: BufferType {}
public extension BufferType where Generator.Element: IntegerType {
private typealias Element = Generator.Element
private mutating func fillWithRandomData() throws {
try withUnsafeMutableBufferPointer { buffer in
let byteCount = sizeof(Element) * numericCast(buffer.count)
try cc_call {
CCRandomGenerateBytes(buffer.baseAddress, byteCount)
}
}
}
/// Create a collection filled with random bytes.
///
/// The random number generator, provided by the hardware or platform, can
/// create cryptographically strong random data suitable for use as
/// cryptographic keys, IVs, nonces etc.
///
/// - throws:
/// - `CryptoError.RNGFailure` if the source of random numbers could not
/// produce cryptographically-strong random data.
init(randomCount count: Index.Distance) throws {
self.init(count: count, repeatedValue: Element.allZeros)
try fillWithRandomData()
}
}
public extension MutableCollectionType where SubSequence: BufferType, SubSequence.Generator.Element: IntegerType {
private typealias Element = Generator.Element
/// Fill a pre-allocated buffer with random bytes.
///
/// The random number generator, provided by the hardware or platform, can
/// create cryptographically strong random data suitable for use as
/// cryptographic keys, IVs, nonces etc.
///
/// - parameter range: Optional sub-range to fill with data. If not
/// provided, the entire contents of the collection will be replaced.
/// - throws:
/// - `CryptoError.RNGFailure` if the source of random numbers could not
/// produce cryptographically-strong random data.
mutating func fillWithRandomData(inRange range: Range<Index>? = nil) throws {
let range = range ?? indices
try self[range].fillWithRandomData()
}
}
|
mit
|
2555c74ec22bd8aa1558734ab16f2e48
| 37.46875 | 141 | 0.689412 | 4.840105 | false | false | false | false |
hermantai/samples
|
ios/cs193p/EmojiArt/EmojiArt/UtilityViews.swift
|
1
|
1846
|
//
// UtilityViews.swift
// EmojiArt
//
// Created by CS193p Instructor on 4/26/21.
// Copyright © 2021 Stanford University. All rights reserved.
//
import SwiftUI
// syntactic sure to be able to pass an optional UIImage to Image
// (normally it would only take a non-optional UIImage)
struct OptionalImage: View {
var uiImage: UIImage?
var body: some View {
if uiImage != nil {
Image(uiImage: uiImage!)
}
}
}
// syntactic sugar
// lots of times we want a simple button
// with just text or a label or a systemImage
// but we want the action it performs to be animated
// (i.e. withAnimation)
// this just makes it easy to create such a button
// and thus cleans up our code
struct AnimatedActionButton: View {
var title: String? = nil
var systemImage: String? = nil
let action: () -> Void
var body: some View {
Button {
withAnimation {
action()
}
} label: {
if title != nil && systemImage != nil {
Label(title!, systemImage: systemImage!)
} else if title != nil {
Text(title!)
} else if systemImage != nil {
Image(systemName: systemImage!)
}
}
}
}
// simple struct to make it easier to show configurable Alerts
// just an Identifiable struct that can create an Alert on demand
// use .alert(item: $alertToShow) { theIdentifiableAlert in ... }
// where alertToShow is a Binding<IdentifiableAlert>?
// then any time you want to show an alert
// just set alertToShow = IdentifiableAlert(id: "my alert") { Alert(title: ...) }
// of course, the string identifier has to be unique for all your different kinds of alerts
struct IdentifiableAlert: Identifiable {
var id: String
var alert: () -> Alert
}
|
apache-2.0
|
e6d65aa371c47aeaf0ab82d7b0629bb3
| 27.384615 | 91 | 0.622764 | 4.320843 | false | false | false | false |
xcs-go/swift-Learning
|
Protocol.playground/Contents.swift
|
1
|
12200
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
// 协议
// 协议规定了用来实现某一特定工作或者功能所必需的方法和属性。类,结构体或枚举类型都可以遵循协议,并提供具体实现来完成协议定义的方法和功能。
// 协议的语法
//protocol SomeProtocol {
//// 协议内容
//}
// 某个类遵循某个协议,需要在类型名称后加上协议名称,中间以:分隔,作为类型定义的一部分。遵循多个协议时,各协议之间用,分隔
//struct SomeStructure:FistProtocol,AnotherProtocol {
//// 结构体内容
//}
// 如果类在遵循协议的同时拥有父类,应该将父类名称放在协议名前,以,分隔
//class SomeClass:SomeSuperClass,FirstProtocol,AnotherProtocol {
//// 类的内容
//}
// 对属性的规定
// 协议可以规定其遵循者提供特定名称和类型的实例属性或类属性,而不用指定是存储属性还是计算型属性。此外还必须指明是只读的还是可读可写的。
// 协议中的通常用var来声明变量属性,在类声明后加上{set get}来表示属性是可读可写的,只读属性则用{get}来表示
//protocol SomeProtocol {
// var mustBeSettable :Int { get set }
// var doesNotNeedToBeSettable: Int { get }
//}
// 在协议中定义类属性时,总是使用static关键字作为前缀。当协议的遵循者是类时,可以使用class或关键字来声明类属性
//protocol AnotherProtocol {
// static var someTypeProperty: Int { get set }
//}
protocol FullyNamed {
var fullName: String { get }
}
struct Person: FullyNamed {
var fullName: String
}
let john = Person(fullName: "John Appleseed")
//struct Person: FullyNamed {
// var fullName: String = "john"
//}
//let john = Person()
class Starship: FullyNamed {
var prefix: String?
var name: String
init(name: String, prefix: String? = nil) {
self.name = name
self.prefix = prefix
}
var fullName: String {
return (prefix != nil ? prefix! + " " : "") + name
}
}
var ncc1701 = Starship(name: "Enterprise", prefix: "USS")
print(ncc1701.fullName)
// 对方法的规定
// 协议可以要求其遵循者实现某些指定的实例或类方法。这些方法作为协议的一部分,像普通的方法一样放在协议的定义中,但是不需要大括号和方法体。可以在协议中定义具有可变参数的方法,和普通方法的定义方式相同。但是在协议的方法定义中,不支持参数默认值。
// 在协议中定义类方法的时候,总是使用static关键字作为前缀。当协议的遵循者是类的时候,可以在类的实例中使用class或者static来实现类方法
//protocol SomeProtocol {
// static func someTypeMethod()
//}
protocol RandomNumberGenerator {
func random() -> Double
}
class LinearCongruentialGenerator: RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29573.0
func random() -> Double {
lastRandom = ((lastRandom * a + c) % m)
return lastRandom / m
}
}
let generator = LinearCongruentialGenerator()
print(generator.random())
print(generator.random())
// 对mutating方法的规定
// 如果在协议中定义了一个方法旨在改变遵循改协议的实例,那么在协议定义时需要在方法前加mutating关键字。
// 用类实现协议中的mutating方法时,不用写mutating关键字,用结构体,枚举实现协议中的mutating方法时,必须写mutating关键字
protocol Togglable {
mutating func toggle()
}
enum OnOffSwitch: Togglable {
case Off
case On
mutating func toggle() {
switch self {
case Off:
self = On
case On:
self = Off
}
}
}
var lightSwitch = OnOffSwitch.Off
lightSwitch.toggle()
// 对构造器的规定
// 协议可以要求它的遵循者实现指定的构造器。在协议的定义里写下构造器的声明,但不需要写花括号和构造器的实体
protocol SomeProtocol {
init(someParamenter: Int)
}
// 协议构造器规定在类中的实现
// 在遵循协议的类中实现构造器,并制定其为类的指定构造器或者便利构造器。在这两种情况下,都必须给构造器实现标上"required"修饰符
//class SomeClass:SomeProtocol {
// required init(someParamenter: Int) {
//// 构造器实现
// }
//}
// 如果一个子类重写了父类的指定构造器,并且该构造器遵循了某个协议的规定,那么该构造器的实现需要被同时标记required和override修饰符
protocol SomesProtocol {
init()
}
class SomeSuperClass {
init(){
// 构造器的实现
}
}
class SomeSubClass:SomeSuperClass,SomesProtocol {
// 因为遵循协议,需要加上required,继承自父类,需要加上override
required override init() {
// 实现
}
}
// 协议类型
// 虽然协议并没有实现任何的功能,但是协议可以被当作类型来使用
// 协议可以作为:函数、方法或构造器中的参数类型或返回值类型;作为常量、变量或属性的类型;作为数组、字典或其他容器中的元素类型
class Dice {
let sides:Int
let generator:RandomNumberGenerator
init(sides:Int, generator: RandomNumberGenerator) {
self.sides = sides
self.generator = generator
}
func roll() -> Int {
return Int(generator.random() * Double(sides)) + 1
}
}
var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator())
for _ in 1...5{
print(d6.roll())
}
// 代理模式
//protocol DiceGame {
// var dice: Dice { get }
// func play()
//}
//
//protocol DiceGameDelegate {
// func gameDidStart(game:DiceGame)
// func game(game:DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
// func gameDidEnd(game:DiceGame)
//}
//
//class SnakesAndLadders: DiceGame {
// let finalSquare = 25
// let dice = Dice(sides: 6, generator: LinearCongruentialGenerator())
// var square = 0
// var board:[Int]
// init() {
// board = [Int](count: finalSquare + 1, repeatedValue: 0)
// board[03] = +08;
// board[06] = +11;
// board[09] = +09;
// board[10] = +02;
// board[14] = -10;
// board[19] = -11;
// board[22] = -02;
// board[24] = -08
// }
// var delegate: DiceGameDelegate?
// func play() {
// square = 0
// delegate?.gameDidStart(self)
// gameLoop:while square != finalSquare {
// let diceRoll = dice.roll()
// delegate?.game(self,didStartNewTurnWithDiceRoll: diceRoll)
// switch square + diceRoll {
// case finalSquare:
// break gameLoop
// case let newSquare where newSquare > finalSquare:
// continue gameLoop
// default: square += diceRoll
// square += board[square]
// }
//
// }
// delegate?.gameDidEnd(self)
// }
//}
//
//class DiceGameTracker: DiceGameDelegate {
// var numberOfTurns = 0
// func gameDidStart(game: DiceGame) {
// numberOfTurns = 0
// if game is SnakesAndLadders {
// print("Started a new game of Snakes and Ladders") } print("The game is using a \(game.dice.sides)-sided dice")
// }
// func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
// { ++numberOfTurns print("Rolled a \(diceRoll)")
// }
// func gameDidEnd(game: DiceGame) {
// print("The game lasted for \(numberOfTurns) turns")
// }
//
//}
//let tracker = DiceGameTracker()
//let game = SnakesAndLadders()
//game.delegate = tracker
//game.play()
//print("idrffh")
protocol TextRepresentable {
var textualDescription:String { get }
}
extension Dice:TextRepresentable {
var textualDescription: String {
return "frhdfu"
}
}
let dl2 = Dice(sides: 12, generator: LinearCongruentialGenerator())
print(dl2.textualDescription)
// 当一个类型已经实现了协议中的所有要求,却没有声明为遵循该协议时,可以通过扩展来补充协议声明
struct Hamster {
var name: String
var textualDescription: String {
return "ikrfifii"
}
}
extension Hamster:TextRepresentable {}
let simon = Hamster(name: "Simon")
let sujd: TextRepresentable = simon
sujd.textualDescription
sujd.textualDescription
// 协议类型的集合
// 协议类型可以在数组或者字典这样的集合中使用
let things:[TextRepresentable] = [dl2,simon]
for thing in things {
print(thing.textualDescription)
}
// 协议的继承
// 协议能够继承一个或多个其它协议,可以在继承的协议基础上增加新的内容要求。
// 类专属协议
// 在协议的继承列表中,通过添加class关键字,限制协议职能适配到类类型,结构体或枚举不能遵循该协议。class关键字必须是第一个出现在协议的继承列表中,其后,才是其他继承协议
//protocol SomeClassOnlyProtocol:class,SomeProtocol{
//// 协议定义
//}
// 协议组合
// 同时需要遵循多个协议时,可以将多个协议采用protocol<SomeProtocol,AnotherProtocol>这样的格式进行组合,称为协议合成
protocol Named {
var name:String { get }
}
protocol Aged {
var age:Int { get }
}
struct Persons: Named, Aged {
var name: String
var age: Int
}
func wish(celebrator:protocol<Named, Aged>) {
print("\(celebrator.name)")
print(celebrator.age)
}
let birth = Persons(name: "Malcolm", age: 21)
wish(birth)
// 检验协议的一致性
// 可以使用is和as操作符来检查是否遵循某一协议或强制转化为某一类型。
// is操作符用来检查实例是否遵循了某个协议
// as?返回一个可选值,当实例遵循协议时,返回该协议类型;否则返回nil
// as用来强制向下转型,如果强转失败,会引起运行时错误
protocol HasArea {
var area: Double { get }
}
class Circle:HasArea {
let pi = 3.1415926
var radius:Double
var area:Double { return pi * radius * radius }
init(radius: Double) { self.radius = radius}
}
class Country:HasArea {
var area: Double
init(area: Double) { self.area = area }
}
class Animal {
var legs:Int
init(legs:Int) { self.legs = legs }
}
let objects: [AnyObject] = [Circle(radius: 2.0), Country(area: 25314.0), Animal(legs: 4)]
for object in objects {
if let objectWithArea = object as? HasArea {
print("\(objectWithArea.area)")
} else {
print("udfhuujhdf")
}
}
// 对可选协议的规定
// 协议可以含有可选成员,其遵循者可以选择是否实现这些成员。在协议中使用optional关键字作为前缀来定义可选成员.
// 可选协议只能在@objc前缀的协议中生效。这个前缀表示协议将暴露给object-c代码。
@objc protocol CounterDataSource {
optional func incrementForCount(count: Int) -> Int
optional var fixedIncrement: Int { get }
}
@objc class Counter {
var count = 0
var datasource:CounterDataSource?
func increment() {
if let amount = datasource?.incrementForCount?(count) {
count += amount
} else if let amount = datasource?.fixedIncrement {
count += amount
}
}
}
@objc class ThreeSourece: CounterDataSource {
let fixedIncrement = 3
}
var counter = Counter()
counter.datasource = ThreeSourece()
for _ in 1...4 {
counter.increment()
print(counter.count)
}
print("jfhdhj")
class TowardsZeroSource: CounterDataSource {
func incrementForCount(count: Int) -> Int {
if count == 0 {
return 0
} else if count < 0 {
return 1
} else {
return -1
}
}
}
counter.count = -4
counter.datasource = TowardsZeroSource()
for _ in 1...5 {
counter.increment()
print(counter.count)
}
// 协议扩展
// 使用扩展协议的方式可以为遵循者提供方法或属性的实现。
//extension RandomNumberGenerator {
// func randomBool() -> Bool {
// return random() > 0.5
// }
//}
|
apache-2.0
|
afb697cef403d8fb6b43725dc832821e
| 22.383085 | 124 | 0.657766 | 3.148024 | false | false | false | false |
0x7fffffff/Stone
|
Sources/Message.swift
|
2
|
1340
|
//
// Message.swift
// Stone
//
// Created by Michael MacCallum on 5/19/16.
// Copyright © 2016 Tethr Technologies Inc. All rights reserved.
//
import Foundation
import Unbox
import Wrap
/**
Represents a message to be sent over a Channel. Includes fields for reference, topic, event, and a payload object.
*/
public struct Message {
public let ref: String?
public let topic: String
public let event: Stone.Event
public let payload: WrappedDictionary
public init<RawType: RawRepresentable>(topic: RawType, event: Event, payload: WrappedDictionary = [:], ref: String? = UUID().uuidString) where RawType.RawValue == String {
self.init(topic: topic.rawValue, event: event, payload: payload, ref: ref)
}
public init(topic: String, event: Stone.Event, payload: WrappedDictionary = [:], ref: String? = UUID().uuidString) {
self.topic = topic
self.event = event
self.payload = payload
self.ref = ref
}
}
extension Message: Unboxable {
public init(unboxer: Unboxer) throws {
topic = try unboxer.unbox(key: "topic")
do {
payload = try unboxer.unbox(key: "payload.response")
} catch {
payload = try unboxer.unbox(key: "payload")
}
ref = unboxer.unbox(key: "ref")
let eventString: String = try unboxer.unbox(key: "event")
event = Stone.Event(rawValue: eventString) ?? Stone.Event.custom("")
}
}
|
mit
|
24ac24a191df86c3184850cdef1f1202
| 27.489362 | 172 | 0.702016 | 3.389873 | false | false | false | false |
emilstahl/swift
|
test/attr/attr_noescape.swift
|
10
|
11943
|
// RUN: %target-parse-verify-swift
@noescape var fn : () -> Int = { 4 } // expected-error {{@noescape may only be used on 'parameter' declarations}} {{1-11=}}
func doesEscape(fn : () -> Int) {}
func takesGenericClosure<T>(a : Int, @noescape _ fn : () -> T) {}
func takesNoEscapeClosure(@noescape fn : () -> Int) {
takesNoEscapeClosure { 4 } // ok
fn() // ok
var x = fn // expected-error {{@noescape parameter 'fn' may only be called}}
// This is ok, because the closure itself is noescape.
takesNoEscapeClosure { fn() }
// This is not ok, because it escapes the 'fn' closure.
doesEscape { fn() } // expected-error {{closure use of @noescape parameter 'fn' may allow it to escape}}
// This is not ok, because it escapes the 'fn' closure.
func nested_function() {
fn() // expected-error {{declaration closing over @noescape parameter 'fn' may allow it to escape}}
}
takesNoEscapeClosure(fn) // ok
doesEscape(fn) // expected-error {{invalid conversion from non-escaping function of type '@noescape () -> Int' to potentially escaping function type '() -> Int'}}
takesGenericClosure(4, fn) // ok
takesGenericClosure(4) { fn() } // ok.
}
class SomeClass {
final var x = 42
func test() {
// This should require "self."
doesEscape { x } // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
// Since 'takesNoEscapeClosure' doesn't escape its closure, it doesn't
// require "self." qualification of member references.
takesNoEscapeClosure { x }
}
func foo() -> Int {
foo()
func plain() { foo() }
let plain2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
func multi() -> Int { foo(); return 0 }
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{31-31=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
takesNoEscapeClosure { foo() } // okay
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
takesNoEscapeClosure { foo(); return 0 } // okay
func outer() {
func inner() { foo() }
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 }
let _: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{28-28=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() }
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 }
}
let outer2: () -> Void = {
func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}}
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
}
doesEscape {
func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}}
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
return 0
}
takesNoEscapeClosure {
func inner() { foo() }
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 }
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // okay
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // okay
return 0
}
struct Outer {
func bar() -> Int {
bar()
func plain() { bar() }
let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
func multi() -> Int { bar(); return 0 }
let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
takesNoEscapeClosure { bar() } // okay
doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
takesNoEscapeClosure { bar(); return 0 } // okay
return 0
}
}
func structOuter() {
struct Inner {
func bar() -> Int {
bar() // no-warning
func plain() { bar() }
let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{26-26=self.}}
func multi() -> Int { bar(); return 0 }
let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{32-32=self.}}
doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
takesNoEscapeClosure { bar() } // okay
doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
takesNoEscapeClosure { bar(); return 0 } // okay
return 0
}
}
}
return 0
}
}
// Implicit conversions (in this case to @convention(block)) are ok.
@_silgen_name("whatever")
func takeNoEscapeAsObjCBlock(@noescape _: @convention(block) () -> Void)
func takeNoEscapeTest2(@noescape fn : () -> ()) {
takeNoEscapeAsObjCBlock(fn)
}
// Autoclosure implies noescape, but produce nice diagnostics so people know
// why noescape problems happen.
func testAutoclosure(@autoclosure a : () -> Int) { // expected-note{{parameter 'a' is implicitly @noescape because it was declared @autoclosure}}
doesEscape { a() } // expected-error {{closure use of @noescape parameter 'a' may allow it to escape}}
}
// <rdar://problem/19470858> QoI: @autoclosure implies @noescape, so you shouldn't be allowed to specify both
func redundant(@noescape // expected-error {{@noescape is implied by @autoclosure and should not be redundantly specified}} {{16-25=}}
@autoclosure fn : () -> Int) {
}
protocol P1 {
typealias Element
}
protocol P2 : P1 {
typealias Element
}
func overloadedEach<O: P1, T>(source: O, _ transform: O.Element -> (), _: T) {}
func overloadedEach<P: P2, T>(source: P, _ transform: P.Element -> (), _: T) {}
struct S : P2 {
typealias Element = Int
func each(@noescape transform: Int -> ()) {
overloadedEach(self, // expected-error {{cannot invoke 'overloadedEach' with an argument list of type '(S, @noescape Int -> (), Int)'}}
transform, 1)
// expected-note @-2 {{overloads for 'overloadedEach' exist with these partially matching parameter lists: (O, O.Element -> (), T), (P, P.Element -> (), T)}}
}
}
// rdar://19763676 - False positive in @noescape analysis triggered by parameter label
func r19763676Callee(@noescape f: (param: Int) -> Int) {}
func r19763676Caller(@noescape g: (Int) -> Int) {
r19763676Callee({ _ in g(1) })
}
// <rdar://problem/19763732> False positive in @noescape analysis triggered by default arguments
func calleeWithDefaultParameters(@noescape f: () -> (), x : Int = 1) {} // expected-warning {{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}}
func callerOfDefaultParams(@noescape g: () -> ()) {
calleeWithDefaultParameters(g)
}
// <rdar://problem/19773562> Closures executed immediately { like this }() are not automatically @noescape
class NoEscapeImmediatelyApplied {
func f() {
// Shouldn't require "self.", the closure is obviously @noescape.
_ = { return ivar }()
}
final var ivar = 42
}
// Reduced example from XCTest overlay, involves a TupleShuffleExpr
public func XCTAssertTrue(@autoclosure expression: () -> BooleanType, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
}
public func XCTAssert( @autoclosure expression: () -> BooleanType, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
XCTAssertTrue(expression, message, file: file, line: line);
}
|
apache-2.0
|
938de4499e05326e2783856d1771c0bf
| 50.478448 | 199 | 0.647325 | 4.133956 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Pods/DifferenceKit/Sources/AnyDifferentiable.swift
|
1
|
3299
|
/// A type-erased differentiable value.
///
/// The `AnyDifferentiable` type hides the specific underlying types.
/// Associated type `DifferenceIdentifier` is erased by `AnyHashable`.
/// The comparisons of whether has updated is forwards to an underlying differentiable value.
///
/// You can store mixed-type elements in collection that require `Differentiable` conformance by
/// wrapping mixed-type elements in `AnyDifferentiable`:
///
/// extension String: Differentiable {}
/// extension Int: Differentiable {}
///
/// let source = [
/// AnyDifferentiable("ABC"),
/// AnyDifferentiable(100)
/// ]
/// let target = [
/// AnyDifferentiable("ABC"),
/// AnyDifferentiable(100),
/// AnyDifferentiable(200)
/// ]
///
/// let changeset = StagedChangeset(source: source, target: target)
/// print(changeset.isEmpty) // prints "false"
public struct AnyDifferentiable: Differentiable {
/// The value wrapped by this instance.
@inlinable
public var base: Any {
return box.base
}
/// A type-erased identifier value for difference calculation.
@inlinable
public var differenceIdentifier: AnyHashable {
return box.differenceIdentifier
}
@usableFromInline
internal let box: AnyDifferentiableBox
/// Creates a type-erased differentiable value that wraps the given instance.
///
/// - Parameters:
/// - base: A differentiable value to wrap.
@inlinable
public init<D: Differentiable>(_ base: D) {
if let anyDifferentiable = base as? AnyDifferentiable {
self = anyDifferentiable
}
else {
box = DifferentiableBox(base)
}
}
/// Indicate whether the content of `base` is equals to the content of the given source value.
///
/// - Parameters:
/// - source: A source value to be compared.
///
/// - Returns: A Boolean value indicating whether the content of `base` is equals
/// to the content of `base` of the given source value.
@inlinable
public func isContentEqual(to source: AnyDifferentiable) -> Bool {
return box.isContentEqual(to: source.box)
}
}
extension AnyDifferentiable: CustomDebugStringConvertible {
public var debugDescription: String {
return "AnyDifferentiable(\(String(reflecting: base)))"
}
}
@usableFromInline
internal protocol AnyDifferentiableBox {
var base: Any { get }
var differenceIdentifier: AnyHashable { get }
func isContentEqual(to source: AnyDifferentiableBox) -> Bool
}
@usableFromInline
internal struct DifferentiableBox<Base: Differentiable>: AnyDifferentiableBox {
@usableFromInline
internal let baseComponent: Base
@inlinable
internal var base: Any {
return baseComponent
}
@inlinable
internal var differenceIdentifier: AnyHashable {
return baseComponent.differenceIdentifier
}
@inlinable
internal init(_ base: Base) {
baseComponent = base
}
@inlinable
internal func isContentEqual(to source: AnyDifferentiableBox) -> Bool {
guard let sourceBase = source.base as? Base else {
return false
}
return baseComponent.isContentEqual(to: sourceBase)
}
}
|
mit
|
f6476638add382da737a9c58f5f72bd2
| 29.266055 | 98 | 0.659897 | 4.781159 | false | false | false | false |
nathantannar4/NTComponents
|
NTComponents/UI Kit/Search/NTSearchBarView.swift
|
1
|
4836
|
//
// NTSearchBarView.swift
// NTComponents
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 4/25/17.
//
public protocol NTSearchBarViewDelegate {
func searchBar(_ searchBar: NTTextField, didUpdateSearchFor query: String) -> Bool
func searchBarDidBeginEditing(_ searchBar: NTTextField)
func searchBarDidEndEditing(_ searchBar: NTTextField)
}
open class NTSearchBarView: NTView, UITextFieldDelegate {
public var delegate: NTSearchBarViewDelegate?
// open var menuButtonAction: (() -> Void)?
open var searchField: NTTextField = {
let textField = NTTextField()
textField.placeholder = "Search"
textField.backgroundColor = .clear
textField.returnKeyType = .search
textField.clearButtonMode = .whileEditing
return textField
}()
// open var searchButton: NTButton = {
// let button = NTButton()
// button.setImage(Icon.icon("Search")?.scale(to: 30), for: .normal)
// button.trackTouchLocation = false
// button.layer.cornerRadius = 5
// return button
// }()
//
// open var menuButton: NTButton = {
// let button = NTButton()
// button.setImage(Icon.icon("Menu_ffffff_100")?.scale(to: 30), for: .normal)
// button.trackTouchLocation = false
// button.layer.cornerRadius = 5
// return button
// }()
// MARK: - Initialization
public override init(frame: CGRect) {
super.init(frame: frame)
setDefaultShadow()
layer.cornerRadius = 5
searchField.delegate = self
searchField.addTarget(self, action: #selector(search), for: UIControlEvents.editingChanged)
addSubview(searchField)
searchField.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 2, leftConstant: 8, bottomConstant: 2, rightConstant: 8, widthConstant: 0, heightConstant: 0)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func layoutSubviews() {
super.layoutSubviews()
searchField.removeAllConstraints()
searchField.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 2, leftConstant: 8, bottomConstant: 2, rightConstant: 8, widthConstant: 0, heightConstant: 0)
}
// MARK: - UITextFieldDelegate
open func textFieldDidBeginEditing(_ textField: UITextField) {
Log.write(.status, "SearchBar editing began")
delegate?.searchBarDidBeginEditing(searchField)
}
open func textFieldDidEndEditing(_ textField: UITextField) {
Log.write(.status, "SearchBar editing ended")
endSearchEditing()
}
public func textFieldShouldClear(_ textField: UITextField) -> Bool {
Log.write(.status, "SearchBar text cleared")
return delegate?.searchBar(searchField, didUpdateSearchFor: searchField.text ?? String()) ?? true
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
search()
endSearchEditing()
return true
}
// MARK: - Search
@objc open func search() {
Log.write(.status, "SearchBar search executed")
let _ = delegate?.searchBar(searchField, didUpdateSearchFor: searchField.text ?? String())
}
open func endSearchEditing() {
delegate?.searchBarDidEndEditing(searchField)
searchField.resignFirstResponder()
}
// MARK: - Menu
open func menuButtonWasTapped(_ sender: NTButton) {
endSearchEditing()
// menuButtonAction?()
}
// open func setMenuButton(hidden: Bool, animated: Bool) {
//
// }
}
|
mit
|
413d94e5a112161baed4fc4c818928f2
| 33.784173 | 204 | 0.677973 | 4.689622 | false | false | false | false |
meteochu/DecisionKitchen
|
iOS/DecisionKitchen/GameDetailCell.swift
|
1
|
5310
|
//
// GameDetailCell.swift
// DecisionKitchen
//
// Created by Andy Liang on 2017-07-29.
// Copyright © 2017 Andy Liang. All rights reserved.
//
import UIKit
import Button
class GameDetailCell: UICollectionViewCell {
private let imageView = UIImageView()
private let nameLabel = UILabel()
private let addressLabel = UILabel()
private let dateLabel = UILabel()
private let dropinButton = BTNDropinButton()
var game: Game! {
didSet {
if let end = game.meta.end {
dateLabel.text = DateFormatter.localizedString(from: end, dateStyle: .medium, timeStyle: .medium)
} else {
dateLabel.text = "The game is still ongoing..."
}
var imageName: String = "🍕 🍽"
if let restaurantId = game.result?.last?[0], let restaurant = DataController.shared.restaurants[restaurantId] {
nameLabel.text = restaurant.name
addressLabel.text = restaurant.address
imageName = restaurant.name
dropinButton.isHidden = false
let location = BTNLocation()
location.setAddressLine(restaurant.address)
location.setCity(restaurant.city)
location.setState(restaurant.state)
location.setZip(restaurant.zip)
let context = BTNContext(subjectLocation: location)
dropinButton.buttonId = ButtonController.shared.buttonId(for: restaurant)
dropinButton.prepare(with: context, completion: { displayable in
print(displayable)
})
}
self.layoutIfNeeded()
self.imageView.setImage(for: imageName)
}
}
override init(frame: CGRect) {
super.init(frame: .zero)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.layer.cornerRadius = imageView.bounds.width/2
}
func commonInit() {
contentView.backgroundColor = UIColor(white: 0.96, alpha: 1)
contentView.layer.cornerRadius = 8
contentView.layer.shadowOffset = CGSize(width: 0, height: 2)
contentView.layer.shadowRadius = 2
contentView.layer.shadowOpacity = 0.15
imageView.backgroundColor = UIColor(white: 0.92, alpha: 1)
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
nameLabel.font = .systemFont(ofSize: 17, weight: UIFontWeightMedium)
addressLabel.font = .systemFont(ofSize: 14)
addressLabel.numberOfLines = 0
dateLabel.font = .systemFont(ofSize: 12)
dropinButton.isHidden = true
self.contentView.addSubview(imageView)
self.contentView.addSubview(nameLabel)
self.contentView.addSubview(addressLabel)
self.contentView.addSubview(dateLabel)
self.contentView.addSubview(dropinButton)
contentView.translatesAutoresizingMaskIntoConstraints = false
imageView.translatesAutoresizingMaskIntoConstraints = false
nameLabel.translatesAutoresizingMaskIntoConstraints = false
addressLabel.translatesAutoresizingMaskIntoConstraints = false
dateLabel.translatesAutoresizingMaskIntoConstraints = false
dropinButton.translatesAutoresizingMaskIntoConstraints = false
imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16).isActive = true
imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 16).isActive = true
imageView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.20).isActive = true
imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true
nameLabel.topAnchor.constraint(equalTo: imageView.topAnchor).isActive = true
nameLabel.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 16).isActive = true
nameLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16).isActive = true
addressLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor).isActive = true
addressLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 8).isActive = true
addressLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16).isActive = true
dateLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor).isActive = true
dateLabel.topAnchor.constraint(equalTo: addressLabel.bottomAnchor, constant: 8).isActive = true
dateLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16).isActive = true
dropinButton.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor).isActive = true
dropinButton.topAnchor.constraint(equalTo: dateLabel.bottomAnchor, constant: 8).isActive = true
dropinButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16).isActive = true
dropinButton.bottomAnchor.constraint(lessThanOrEqualTo: self.bottomAnchor, constant: -16).isActive = true
}
}
|
apache-2.0
|
1070f8c029ae24da2a43c0d78059aeab
| 43.940678 | 123 | 0.674524 | 5.250495 | false | false | false | false |
AlexIzh/Griddle
|
CollectionPresenter/UI/CustomView/ItemsView/View/ItemView.swift
|
1
|
1039
|
//
// ItemView.swift
// CollectionPresenter
//
// Created by Ravil Khusainov on 22/03/16.
// Copyright © 2016 Moqod. All rights reserved.
//
import Griddle
import UIKit
class ItemView: UIControl, ReusableView {
var contentLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.textAlignment = .center
return label
}()
var model: ItemsViewSourceFactory.Model! {
didSet {
layer.cornerRadius = model.shape == .circle ? 20 : 0
contentLabel.text = model.title
backgroundColor = model.color
setNeedsLayout()
}
}
static func size(for model: Model, container: UIView) -> CGSize? {
return CGSize(width: 40, height: 40)
}
required init() {
super.init(frame: .zero)
addSubview(contentLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
contentLabel.frame = bounds
}
}
|
mit
|
8f570f4e93a69d89178aa0a7e190c8ab
| 21.565217 | 69 | 0.631985 | 4.219512 | false | false | false | false |
NetScaleNow-Admin/ios_sdk
|
NetScaleNow/Classes/Strings.swift
|
1
|
12909
|
//
// Strings.swift
// Pods
//
// Created by Jonas Stubenrauch on 23.05.17.
//
//
import Foundation
struct Strings {
private static let bundle = Config.bundle
struct General {
static var close : String {
return NSLocalizedString("General.close", bundle: bundle, value: "Schließen", comment: "Title of a close button")
}
static var errorMessage : String {
return NSLocalizedString("General.errorMessage", bundle: bundle, value: "Es ist ein technischer Fehler aufgetreten. Bitte versuchen Sie es in Kürze erneut oder wenden Sie sich an [email protected].", comment: "Generic error message")
}
static var backToCampaignList : String {
return NSLocalizedString("General.backToCampaignList", bundle: bundle, value: "Zurück zur Übersicht", comment: "Title of the button to go back to the campaign list")
}
static var agbLink : String {
return NSLocalizedString("CampaignDetail.agbLink", bundle: bundle, value: "AGB", comment: "Title of the link to open the AGB (Terms of Conditions) ")
}
static var dataProtectionLink : String {
return NSLocalizedString("CampaignDetail.dataProtectionLink", bundle: bundle, value: "Datenschutz", comment: "Title of the link to open the data protection ")
}
static var copyrightLink : String {
guard let copyrightLink = Config.groupConfig?.copyrightText else {
return NSLocalizedString("CampaignDetail.copyrightLink", bundle: bundle, value: "© Premium Shopping", comment: "Title of the link showing the copy right")
}
return copyrightLink
}
static var agbUrl : String {
guard let agbUrl = Config.groupConfig?.termsLink else {
return NSLocalizedString("CampaignDetail.agbUrl", bundle: bundle, value: "https://www.premium-shopping.de/agb", comment: "Url to the AGB (Terms of Conditions) ")
}
return agbUrl
}
static var dataProtectionUrl : String {
guard let dataProtectionUrl = Config.groupConfig?.privacyPolicyLink else {
return NSLocalizedString("CampaignDetail.dataProtectionUrl", bundle: bundle, value: "https://www.premium-shopping.de/datenschutz", comment: "Url to the data protection")
}
return dataProtectionUrl
}
static var checkboxPrivacyTermsUrl : String {
guard let checkboxPrivacyTermsUrl = Config.groupConfig?.privacyPolicyLink else {
return NSLocalizedString("CampaignDetail.checkboxPrivacyTermsUrl", bundle: bundle, value: "http://www.premium-shopping.de/datenschutz", comment: "Url to the privacy terms (Datenschutzbedingungen) next to the checkbox")
}
return checkboxPrivacyTermsUrl
}
static var checkboxUsageTermsUrl : String {
guard let checkboxUsageTermsUrl = Config.groupConfig?.termsLink else {
return NSLocalizedString("CampaignDetail.checkboxUsageTermsUrl", bundle: bundle, value: "http://www.premium-shopping.de/agb", comment: "Url to the usage terms (Nutzungsbedingungen) next to the checkbox")
}
return checkboxUsageTermsUrl
}
static var copyrightUrl : String {
guard let copyrightUrl = Config.groupConfig?.copyrightLink else {
return NSLocalizedString("CampaignDetail.copyrightUrl", bundle: bundle, value: "https://www.premium-shopping.de", comment: "Url to copy right")
}
return copyrightUrl
}
}
struct CampaignList {
static var headline : String {
guard let headline = Config.groupConfig?.campaignListTitle.uppercased().brReplaced() else {
return NSLocalizedString("CampaignList.headline", bundle: bundle, value: "VIELEN DANK FÜR IHREN EINKAUF!", comment: "Headline of the Campaign Selection View")
}
return headline
}
static var message : String {
guard let message = Config.groupConfig?.campaignListSubtitle.brReplaced() else {
return NSLocalizedString("CampaignList.message", bundle: bundle, value: "Als Dankeschön dürfen Sie sich einen Gratisgutschein aussuchen. ", comment: "Message below the Headline of the Campaign Selection View")
}
return message
}
}
struct CampaignDetail {
private static var discountFormat: String {
return NSLocalizedString("CampaignDetail.discountFormat", bundle: bundle, value: "%@ Gutschein*", comment: "Discount Value of the Campaign together with Voucher. %@ is replaced with the actual value")
}
static func discountFormat(discount: String) -> String {
return String(format: discountFormat, discount)
}
static var voucherInformation : String {
return NSLocalizedString("CampaignDetail.voucherRestrictions", bundle: bundle, value: "*Gutscheinbedingungen", comment: "Title of the voucher information text")
}
static var checkboxText : String {
return NSLocalizedString("CampaignDetail.checkboxText", bundle: bundle, value: "Ja, hiermit bestätige ich, dass ich die Nutzungs- und Datenschutzbedingungen gelesen und akzeptiert habe.", comment: "Text shown next to the checkbox.")
}
static var checkboxTextToHighlightUsage : String {
return NSLocalizedString("CampaignDetail.checkboxTextToHighlightUsage", bundle: bundle, value: "Nutzungs", comment: "Part of the checkbox text that should be underlined for usage rules")
}
static var checkboxTextToHighlightData : String {
return NSLocalizedString("CampaignDetail.checkboxTextToHighlightData", bundle: bundle, value: "Datenschutzbedingungen", comment: "Part of the checkbox text that should be underlined for data protection")
}
static var emailPlaceholder : String {
return NSLocalizedString("CampaignDetail.emailPlaceholder", bundle: bundle, value: "E-Mail-Adresse eingeben", comment: "Placeholder for the email input field. Only shows if no email is entered")
}
static var showVoucher : String {
return NSLocalizedString("CampaignDetail.showVoucher", bundle: bundle, value: "GUTSCHEINCODE ANZEIGEN", comment: "Title of the button to request a voucher.")
}
static var backToOverview : String {
return NSLocalizedString("CampaignDetaill.backToOverview", bundle: bundle, value: "« zurück zur Übersicht", comment: "Title of the button to go back to the campaign list.")
}
struct TermsActionSheet {
static var title : String {
return NSLocalizedString("CampaignDetaill.TermsActionSheet.title", bundle: bundle, value: "Action wählen", comment: "Title of the terms action sheet.")
}
static var cancel : String {
return NSLocalizedString("CampaignDetaill.TermsActionSheet.cancel", bundle: bundle, value: "Abbrechen", comment: "Title of the cancel action of the terms action sheet.")
}
static var optionAccept : String {
return NSLocalizedString("CampaignDetaill.TermsActionSheet.optionAccept", bundle: bundle, value: "Bedingungen akzeptieren", comment: "Option to accept the terms.")
}
static var optionShowUsageTerms : String {
return NSLocalizedString("CampaignDetaill.TermsActionSheet.optionShowUsageTerms", bundle: bundle, value: "Nutzungsbedingungen anzeigen", comment: "Option to show usage terms.")
}
static var optionShowPrivacyTerms : String {
return NSLocalizedString("CampaignDetaill.TermsActionSheet.optionShowPrivacyTerms", bundle: bundle, value: "Datenschutzbedingungen anzeigen", comment: "Option to show privacy terms.")
}
}
}
struct VoucherDetail {
static var noNewsletterTitle : String {
guard let noNewsletterTitle = Config.groupConfig?.newsletterTitle.brReplaced() else {
return NSLocalizedString("VoucherDetail.noNewsletterTitle", bundle: bundle, value: "Jetzt zweiten Gutschein aussuchen?", comment: "Title if user has not subscribed to the newsletter yet.")
}
return noNewsletterTitle
}
static var noNewsletterSubTitle : String {
guard let noNewsletterSubTitle = Config.groupConfig?.newsletterSubtitle.brReplaced() else {
return NSLocalizedString("VoucherDetail.noNewsletterSubTitle", bundle: bundle, value: "Einfach zum Newsletter anmelden!", comment: "Message below the Title if user has not subscribed to the newsletter yet.")
}
return noNewsletterSubTitle
}
static var subscribeToNewsletter : String {
return NSLocalizedString("VoucherDetail.subscribeToNewsletter", bundle: bundle, value: "ANMELDEN", comment: "Title of the button to subscribe to the newsletter.")
}
static var subscribedNewsletterTitle : String {
guard let subscribedNewsletterTitle = Config.groupConfig?.nextVoucherTitle.brReplaced() else {
return NSLocalizedString("VoucherDetail.subscribedNewsletterTitle", bundle: bundle, value: "Sie wollen noch mehr sparen beim Shoppen?", comment: "Title if user has subscribed to the newsletter.")
}
return subscribedNewsletterTitle
}
static var subscribedNewsletterSubTitle : String {
guard let subscribedNewsletterSubTitle = Config.groupConfig?.nextVoucherSubtitle.brReplaced() else {
return NSLocalizedString("VoucherDetail.subscribedNewsletterSubTitle", bundle: bundle, value: "Suchen Sie sich exklusiv einen weiteren Gutschein aus!", comment: "Message below the Title if user has subscribed to the newsletter.")
}
return subscribedNewsletterSubTitle
}
static var noVouchersLeftMessage : String {
guard let noVouchersLeftMessage = Config.groupConfig?.maximumReachedText.brReplaced() else {
return NSLocalizedString("VoucherDetail.noVouchersLeftMessage", bundle: bundle, value: "Sie haben die maximale Anzahl an Gutscheinen erreicht.\nWir halten Sie über neue Gutscheine per Newsletter auf dem Laufenden.\nViel Spaß beim Shoppen!", comment: "Title if user has reached the maxium number of vouchers.")
}
return noVouchersLeftMessage
}
static var backToCampaignList : String {
return NSLocalizedString("VoucherDetail.subscribeToNewsletter", bundle: bundle, value: "ZU DEN GUTSCHEINEN", comment: "Title of the button to go back to the campaign list.")
}
static var checkboxText : String {
guard let checkboxText = Config.groupConfig?.userAgreementText.brReplaced() else {
return NSLocalizedString("VoucherDetail.checkboxText", bundle: bundle, value: "Ja, ich möchte künftig den kostenlosen Premium Shopping Newsletter per E-Mail erhalten. Das Einverständnis kann ich jederzeit widerrufen.", comment: "Text shown next to the checkbox.")
}
return checkboxText
}
static var voucherCodeTitle : String {
guard let voucherCodeTitle = Config.groupConfig?.voucherTitle.uppercased().brReplaced() else {
return NSLocalizedString("VoucherDetail.voucherCodeTitle", bundle: bundle, value: "IHR GUTSCHEINCODE", comment: "Title above the voucher code.")
}
return voucherCodeTitle
}
static var linkToShop : String {
return NSLocalizedString("VoucherDetail.linkToShop", bundle: bundle, value: "Zum Shop »", comment: "Name of the link to the shop of the advertiser.")
}
static var voucherViaMailHint : String {
guard let voucherViaMailHint = Config.groupConfig?.voucherNote.brReplaced() else {
return NSLocalizedString("VoucherDetail.voucherViaMailHint", bundle: bundle, value: "Sie erhalten den Gutschein in wenigen Augenblicken\nzusätzlich per Mail.", comment: "Hint message to indicate the voucher is send via mail.")
}
return voucherViaMailHint
}
struct OpenShopAlert {
static var title : String {
return NSLocalizedString("VoucherDetail.OpenShopAlert.title", bundle: bundle, value: "Onlineshop öffnen", comment: "Title of the alert shown before opening the shop url in the browser.")
}
static var message : String {
return NSLocalizedString("VoucherDetail.OpenShopAlert.message", bundle: bundle, value: "Sie werden jetzt zum Onlineshop des Anbieters weitergeletet. Der Gutscheincode wird automatisch in die Zwischenablage kopiert.", comment: "Message of the alert shown before opening the shop url in the browser.")
}
static var cancel : String {
return NSLocalizedString("VoucherDetail.OpenShopAlert.cancel", bundle: bundle, value: "Abbrechen", comment: "Button of the alert shown before opening the shop url in the browser to not open the shop.")
}
static var open : String {
return NSLocalizedString("VoucherDetail.OpenShopAlert.open", bundle: bundle, value: "Öffnen", comment: "Button of the alert shown before opening the shop url in the browser to open the shop.")
}
}
}
}
extension String {
func brReplaced() -> String {
return self.replacingOccurrences(of: "<br>", with: "\n")
}
}
|
mit
|
84c02b1f7f660d4fe479c20a5cdd25c4
| 50.342629 | 317 | 0.719097 | 4.337597 | false | true | false | false |
ThePacielloGroup/CCA-OSX
|
Colour Contrast Analyser/AppDelegate.swift
|
1
|
6613
|
//
// AppDelegate.swift
// Colour Contrast Analyser
//
// Created by Cédric Trévisan on 26/01/2015.
// Copyright (c) 2015 Cédric Trévisan. All rights reserved.
//
import Cocoa
import CoreGraphics
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let cca_url = "http://www.paciellogroup.com/resources/contrast-analyser.html"
var foreground: CCAColourForeground = CCAColourForeground.sharedInstance
var background: CCAColourBackground = CCAColourBackground.sharedInstance
@IBOutlet weak var mainWindow: NSWindow!
@IBOutlet weak var luminosity: CCALuminosityControler!
@IBOutlet weak var colorBrightnessDifference: CCAColourBrightnessDifferenceController!
@IBOutlet weak var colorProfilesMenu: NSMenu!
var preferencesController = CCAPreferencesController(windowNibName: NSNib.Name(rawValue: "Preferences"))
let userDefaults = UserDefaults.standard
// Called on ColorProfiles menuitem selection
@objc func setColorProfile(sender : NSMenuItem) {
let screenNumber = sender.parent?.representedObject as! CGDirectDisplayID
let colorProfile = sender.representedObject as! NSColorSpace
// Save into preferences
var data = userDefaults.object(forKey: "CCAColorProfiles") as! Data
var colorProfiles = NSKeyedUnarchiver.unarchiveObject(with: data) as! [CGDirectDisplayID : NSColorSpace]
colorProfiles[screenNumber] = colorProfile
data = NSKeyedArchiver.archivedData(withRootObject: colorProfiles as Any)
userDefaults.set(data, forKey: "CCAColorProfiles")
// Clear and set menuitems state
for menuItem in (sender.menu?.items)! {
if (colorProfile.isEqual(menuItem.representedObject)) {
menuItem.state = NSControl.StateValue(rawValue: 1)
} else {
menuItem.state = NSControl.StateValue(rawValue: 0)
}
}
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Initialise Preferences
if userDefaults.string(forKey: "CCAResultsFormat") == nil {
userDefaults.set(NSLocalizedString("results_format", comment:"Initial Results format text"), forKey: "CCAResultsFormat")
}
var colorProfiles = [CGDirectDisplayID: NSColorSpace]()
if userDefaults.object(forKey: "CCAColorProfiles") == nil {
let data = NSKeyedArchiver.archivedData(withRootObject: colorProfiles as Any)
userDefaults.set(data, forKey: "CCAColorProfiles")
} else {
let data = userDefaults.object(forKey: "CCAColorProfiles") as! Data
colorProfiles = NSKeyedUnarchiver.unarchiveObject(with: data) as! [CGDirectDisplayID : NSColorSpace]
}
// Create the color profile menu
let colorSpaces = NSColorSpace.availableColorSpaces(with: .RGB)
colorProfilesMenu.removeAllItems()
let screens = NSScreen.screens
for screen in screens {
let screenNumber = screen.number
if (colorProfiles[screenNumber] == nil) {
// Init with screen color profile
colorProfiles[screenNumber] = screen.colorSpace
}
// Save the default preferences
let data = NSKeyedArchiver.archivedData(withRootObject: colorProfiles as Any)
userDefaults.set(data, forKey: "CCAColorProfiles")
let screenColorProfile = colorProfiles[screenNumber]
let colorSpacesMenu = NSMenu()
for colorSpace in colorSpaces {
let menuItem = NSMenuItem(title: colorSpace.localizedName!, action: #selector(AppDelegate.setColorProfile(sender:)), keyEquivalent: "")
menuItem.representedObject = colorSpace
if (colorSpace.isEqual(screenColorProfile)) {
menuItem.state = NSControl.StateValue(rawValue: 1)
}
colorSpacesMenu.addItem(menuItem)
}
let menuItem = NSMenuItem(title:screen.displayName, action:nil, keyEquivalent:"")
menuItem.representedObject = screenNumber
menuItem.submenu = colorSpacesMenu
colorProfilesMenu.addItem(menuItem)
}
colorProfilesMenu.update()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
@IBAction func showHelp(_ sender: AnyObject) {
let ws = NSWorkspace.shared
ws.open(URL(string: cca_url)!)
}
@IBAction func showPreferences(_ sender: AnyObject) {
preferencesController.showWindow(nil)
}
@IBAction func copyResults(_ sender: AnyObject) {
var results:String = userDefaults.string(forKey: "CCAResultsFormat")!
results = results.replace("%F", withString: foreground.value.hexString)
results = results.replace("%B", withString: background.value.hexString)
results = results.replace("%L", withString: luminosity.contrastRatioString!)
results = results.replace("%AAN ", withString:((luminosity.passAA == true) ? NSLocalizedString("passed_normal_AA", comment:"Normal text passed at level AA") : NSLocalizedString("failed_normal_AA", comment:"Normal text failed at level AA")))
results = results.replace("%AAAN", withString:((luminosity.passAAA == true) ? NSLocalizedString("passed_normal_AAA", comment:"Normal text passed at level AAA") : NSLocalizedString("failed_normal_AAA", comment:"Normal text failed at level AAA")))
results = results.replace("%AAL", withString:((luminosity.passAALarge == true) ? NSLocalizedString("passed_large_AA", comment:"Large text passed at level AA") : NSLocalizedString("failed_large_AA", comment:"Large text failed at level AA")))
results = results.replace("%AAAL", withString:((luminosity.passAAALarge == true) ? NSLocalizedString("passed_large_AAA", comment:"Large text passed at level AAA") : NSLocalizedString("failed_large_AAA", comment:"Large text failed at level AAA")))
let pasteBoard = NSPasteboard.general
pasteBoard.clearContents()
pasteBoard.writeObjects([results as NSPasteboardWriting])
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
}
extension String
{
func replace(_ target: String, withString: String) -> String
{
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
}
|
gpl-3.0
|
1b9d507c154a7fb275b43dd9bdba9178
| 46.207143 | 254 | 0.679377 | 5.022036 | false | false | false | false |
hsusmita/SHRichTextEditorTools
|
SHRichTextEditorTools/Source/Core/TextViewDelegate.swift
|
1
|
11460
|
//
// TextViewDelegate.swift
// SHRichTextEditorTools
//
// Created by Susmita Horrow on 20/02/17.
// Copyright © 2017 hsusmita. All rights reserved.
//
import Foundation
import UIKit
open class TextViewDelegate: NSObject {
fileprivate enum Event: Int {
case textViewShouldBeginEditing
case textViewDidBeginEditing
case textViewShouldEndEditing
case textViewDidEndEditing
case textViewShouldChangeText
case textViewDidChangeSelection
case textViewDidChangeText
case textViewDidChangeTap
case textViewDidLongPress
case textViewShouldInteractWithURL
case textViewShouldInteractWithTextAttachment
case textViewDidInsertImage
case textViewDidDeleteImage
case textViewDidApplyTextFormatting
}
fileprivate var actionsForEvents: [Event: [Any]] = [:]
public override init() {
super.init()
self.observeTapChange()
}
deinit {
NotificationCenter.default.removeObserver(self, name: UITextView.UITextViewTextDidChangeTap, object: nil)
}
open func registerShouldBeginEditing(with handler: @escaping (UITextView) -> Bool) {
self.register(event: .textViewShouldBeginEditing, handler: handler)
}
open func registerDidBeginEditing(with handler: @escaping (UITextView) -> ()) {
self.register(event: .textViewDidBeginEditing, handler: handler)
}
open func registerShouldEndEditing(with handler: @escaping (UITextView) -> Bool) {
self.register(event: .textViewShouldEndEditing, handler: handler)
}
open func registerDidEndEditing(with handler: @escaping (UITextView) -> ()) {
self.register(event: .textViewDidEndEditing, handler: handler)
}
open func registerShouldChangeText(with handler: @escaping (UITextView, NSRange, String) -> (Bool)) {
self.register(event: .textViewShouldChangeText, handler: handler)
}
open func registerDidChangeText(with handler: @escaping (UITextView) -> ()) {
self.register(event: .textViewDidChangeText, handler: handler)
}
open func registerDidChangeSelection(with handler: @escaping (UITextView) -> ()) {
self.register(event: .textViewDidChangeSelection, handler: handler)
}
open func registerShouldInteractURL(with handler: @escaping (UITextView, URL, NSRange, UITextItemInteraction) -> Bool) {
self.register(event: .textViewShouldInteractWithURL, handler: handler)
}
open func registerShouldInteractTextAttachment(with handler: @escaping (UITextView, NSTextAttachment, NSRange, UITextItemInteraction) -> Bool) {
self.register(event: .textViewShouldInteractWithTextAttachment, handler: handler)
}
open func registerDidTapChange(with handler: @escaping (UITextView) -> ()) {
self.register(event: .textViewDidChangeTap, handler: handler)
}
open func registerDidLongPress(with handler: @escaping (UITextView) -> ()) {
self.register(event: .textViewDidLongPress, handler: handler)
}
open func registerDidInsertImage(with handler: @escaping (UITextView, Int, UIImage) -> ()) {
self.register(event: .textViewDidInsertImage, handler: handler)
}
open func registerDidDeleteImage(with handler: @escaping (UITextView, Int) -> ()) {
self.register(event: .textViewDidDeleteImage, handler: handler)
}
open func registerDidApplyTextFormatting(with handler: @escaping (UITextView) -> ()) {
self.register(event: .textViewDidApplyTextFormatting, handler: handler)
}
private func register(event: Event, handler: Any) {
if let _ = actionsForEvents[event] {
self.actionsForEvents[event]!.append(handler)
} else {
self.actionsForEvents[event] = [handler]
}
}
private func observeTapChange() {
NotificationCenter.default.addObserver(forName: UITextView.UITextViewTextDidChangeTap, object: nil,
queue: OperationQueue.main) { [weak self] notification in
let textView = notification.object as! UITextView
guard let actionsForTapChange: [(UITextView) -> ()] = self?.actionsForEvents[.textViewDidChangeTap] as? [(UITextView) -> ()] else {
return
}
for action in actionsForTapChange {
action(textView)
}
}
NotificationCenter.default.addObserver(forName: UITextView.UITextViewTextDidLongPress,
object: nil,
queue: OperationQueue.main) { [weak self] notification in
let textView = notification.object as! UITextView
guard let actionsForLongPress: [(UITextView) -> ()] = self?.actionsForEvents[.textViewDidLongPress] as? [(UITextView) -> ()] else {
return
}
for action in actionsForLongPress {
action(textView)
}
}
}
}
extension TextViewDelegate: UITextViewDelegate {
public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
guard let actionsForShouldBeginEditing: [(UITextView) -> (Bool)] = self.actionsForEvents[.textViewShouldBeginEditing] as? [(UITextView) -> (Bool)] else {
return true
}
var shouldBeginEditing = true
for action in actionsForShouldBeginEditing {
shouldBeginEditing = shouldBeginEditing && action(textView)
}
return shouldBeginEditing
}
public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
guard let actionsForShouldEndEditing: [(UITextView) -> (Bool)] = self.actionsForEvents[.textViewShouldEndEditing] as? [(UITextView) -> (Bool)] else {
return true
}
var shouldEndEditing = true
for action in actionsForShouldEndEditing {
shouldEndEditing = shouldEndEditing && action(textView)
}
return shouldEndEditing
}
public func textViewDidBeginEditing(_ textView: UITextView) {
guard let actionsForBeginEditing: [(UITextView) -> ()] = self.actionsForEvents[.textViewDidBeginEditing] as? [(UITextView) -> ()] else {
return
}
for action in actionsForBeginEditing {
action(textView)
}
}
public func textViewDidEndEditing(_ textView: UITextView) {
guard let actionsForEndEditing: [(UITextView) -> ()] = self.actionsForEvents[.textViewDidEndEditing] as? [(UITextView) -> ()] else {
return
}
for action in actionsForEndEditing {
action(textView)
}
}
public func textView(_ textView: UITextView,
shouldChangeTextIn range: NSRange,
replacementText text: String) -> Bool {
guard let actionsForShouldChangeText: [(UITextView, NSRange, String) -> (Bool)] =
self.actionsForEvents[.textViewShouldChangeText] as? [(UITextView, NSRange, String) -> (Bool)] else {
return true
}
var shouldChange = true
for action in actionsForShouldChangeText {
shouldChange = shouldChange && action(textView, range, text)
}
return shouldChange
}
public func textViewDidChange(_ textView: UITextView) {
guard let actionsForChangeText: [(UITextView) -> ()] = self.actionsForEvents[.textViewDidChangeText] as? [(UITextView) -> ()] else {
return
}
for action in actionsForChangeText {
action(textView)
}
}
public func textViewDidInsertImage(_ textView: UITextView, index: Int, image: UIImage) {
guard let actionsForDidInsertImage: [(UITextView, Int, UIImage) -> (Void)] =
self.actionsForEvents[.textViewDidInsertImage] as? [(UITextView, Int, UIImage) -> (Void)] else {
return
}
for action in actionsForDidInsertImage {
action(textView, index, image)
}
}
public func textViewDidDeleteImage(_ textView: UITextView, index: Int) {
guard let actionsForDidDeleteImage: [(UITextView, Int) -> (Void)] =
self.actionsForEvents[.textViewDidDeleteImage] as? [(UITextView, Int) -> (Void)] else {
return
}
for action in actionsForDidDeleteImage {
action(textView, index)
}
}
public func textViewDidApplyTextFormatting(_ textView: UITextView) {
guard let actionsForDidApplyTextFormatting: [(UITextView) -> (Void)] =
self.actionsForEvents[.textViewDidApplyTextFormatting] as? [(UITextView) -> (Void)] else {
return
}
for action in actionsForDidApplyTextFormatting {
action(textView)
}
}
public func textViewDidChangeSelection(_ textView: UITextView) {
guard let actionsForChangeSelection: [(UITextView) -> ()] = self.actionsForEvents[.textViewDidChangeSelection] as? [(UITextView) -> ()] else {
return
}
for action in actionsForChangeSelection {
action(textView)
}
}
public func textView(_ textView: UITextView,
shouldInteractWith URL: URL,
in characterRange: NSRange,
interaction: UITextItemInteraction) -> Bool {
guard let actionsForShouldInteract: [(UITextView, URL, NSRange, UITextItemInteraction) -> (Bool)] =
self.actionsForEvents[.textViewShouldInteractWithURL] as? [(UITextView, URL, NSRange, UITextItemInteraction) -> (Bool)] else {
return true
}
var shouldInteract = true
for action in actionsForShouldInteract {
shouldInteract = shouldInteract && action(textView, URL, characterRange, interaction)
}
return shouldInteract
}
public func textView(_ textView: UITextView,
shouldInteractWith textAttachment: NSTextAttachment,
in characterRange: NSRange,
interaction: UITextItemInteraction) -> Bool {
guard let actionsForShouldInteract: [(UITextView, NSTextAttachment, NSRange, UITextItemInteraction) -> (Bool)] =
self.actionsForEvents[.textViewShouldInteractWithTextAttachment] as? [(UITextView, NSTextAttachment, NSRange, UITextItemInteraction) -> (Bool)] else {
return true
}
var shouldInteract = true
for action in actionsForShouldInteract {
shouldInteract = shouldInteract && action(textView, textAttachment, characterRange, interaction)
}
return shouldInteract
}
}
|
mit
|
acaeca77d947a89b91c896a3d10c87ee
| 42.241509 | 179 | 0.601798 | 5.669965 | false | false | false | false |
noppoMan/aws-sdk-swift
|
Sources/Soto/Services/PinpointEmail/PinpointEmail_Error.swift
|
1
|
3832
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for PinpointEmail
public struct PinpointEmailErrorType: AWSErrorType {
enum Code: String {
case accountSuspendedException = "AccountSuspendedException"
case alreadyExistsException = "AlreadyExistsException"
case badRequestException = "BadRequestException"
case concurrentModificationException = "ConcurrentModificationException"
case limitExceededException = "LimitExceededException"
case mailFromDomainNotVerifiedException = "MailFromDomainNotVerifiedException"
case messageRejected = "MessageRejected"
case notFoundException = "NotFoundException"
case sendingPausedException = "SendingPausedException"
case tooManyRequestsException = "TooManyRequestsException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize PinpointEmail
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The message can't be sent because the account's ability to send email has been permanently restricted.
public static var accountSuspendedException: Self { .init(.accountSuspendedException) }
/// The resource specified in your request already exists.
public static var alreadyExistsException: Self { .init(.alreadyExistsException) }
/// The input you provided is invalid.
public static var badRequestException: Self { .init(.badRequestException) }
/// The resource is being modified by another operation or thread.
public static var concurrentModificationException: Self { .init(.concurrentModificationException) }
/// There are too many instances of the specified resource type.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// The message can't be sent because the sending domain isn't verified.
public static var mailFromDomainNotVerifiedException: Self { .init(.mailFromDomainNotVerifiedException) }
/// The message can't be sent because it contains invalid content.
public static var messageRejected: Self { .init(.messageRejected) }
/// The resource you attempted to access doesn't exist.
public static var notFoundException: Self { .init(.notFoundException) }
/// The message can't be sent because the account's ability to send email is currently paused.
public static var sendingPausedException: Self { .init(.sendingPausedException) }
/// Too many requests have been made to the operation.
public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) }
}
extension PinpointEmailErrorType: Equatable {
public static func == (lhs: PinpointEmailErrorType, rhs: PinpointEmailErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension PinpointEmailErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
|
apache-2.0
|
09d0290bf63b96e366674cb95f26dfe3
| 44.619048 | 117 | 0.701722 | 5.16442 | false | false | false | false |
ihomway/RayWenderlichCourses
|
Beginning Swift 3/Beginning Swift 3.playground/Pages/Dictionaries Challenge.xcplaygroundpage/Contents.swift
|
1
|
1539
|
//: [Previous](@previous)
import UIKit
/*:
#### Beginnng Swift Video Tutorial Series - raywenderlich.com
#### Video 12: Dictionaries
**Note:** If you're seeing this text as comments rather than nicely-rendered text, select Editor\Show Rendered Markup in the Xcode menu.
*/
//: Create a new dictionary and add the following values: Stephen King - Under the Dome, Elizabeth Peters - Crocodile on the Sandbank, Clive Cussler - The Wrecker
var authorInfo = ["Stephen King": "Under the Dome", "Elizabeth Peters": "Crocodile on the Sandbank", "Clive Cussler": "The Wrecker"]
//: Add a new key: Robert Heinlein - The Moon is a Harsh Mistress
authorInfo["Robert Heinlein"] = "The Moon is a Harsh Mistress"
//: Print out the Stephen King value
print(authorInfo["Stephen King"])
//: Now delete the Stephen King key/value pair
//: Loop through the dictionary and print out all the key/values
for (key, value) in authorInfo {
print("\(key) - \(value)")
}
//: **Ub3r H4ck3r Challenge** Declare a function occurrencesOfCharacters that calculates which characters occur in a string, as well as how often each of these characters occur. Return the result as a dictionary: func occurrencesOfCharacters(text: String) -> [Character: Int]
func occurrencesOfCharacters(text: String) -> [Character: Int] {
var chars = [Character: Int]()
for character in text.characters {
let count = chars[character] ?? 0
chars[character] = count + 1
}
return chars
}
print(occurrencesOfCharacters(text: "These are the days of our lines"))
//: [Next](@next)
|
mit
|
be6573040fed7ccd084a458c354ad68b
| 40.594595 | 275 | 0.731644 | 3.673031 | false | false | false | false |
giftbott/HandyExtensions
|
Sources/CGFloatExtensions.swift
|
1
|
709
|
//
// CGFloatExtensions.swift
// HandyExtensions
//
// Created by giftbot on 2017. 4. 29..
// Copyright © 2017년 giftbot. All rights reserved.
//
extension CGFloat {
/// ScreenSize Width & Height.
/// CGRect(x: 0, y: 0, width: screenWidthSize, screenHeightSize)
public static let screenWidthSize = UIScreen.main.nativeBounds.size.width / UIScreen.main.nativeScale
public static let screenHeightSize = UIScreen.main.nativeBounds.size.height / UIScreen.main.nativeScale
public static let screenMidX = UIScreen.main.bounds.width / 2
public static let screenMidY = UIScreen.main.bounds.height / 2
public static let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
}
|
mit
|
53c4cb7c5abe76343fd0f753460aa138
| 38.222222 | 105 | 0.749292 | 4.057471 | false | false | false | false |
hmhv/SobjectiveRecord
|
SobjectiveRecordDemo/SobjectiveRecordDemo/TweetViewController.swift
|
1
|
9217
|
//
// TweetViewController.swift
// HobjectiveRecordDemo-Swift
//
// Created by 洪明勲 on 2015/03/05.
// Copyright (c) 2015年 hmhv. All rights reserved.
//
import UIKit
import Accounts
import CoreData
class TweetViewController : UIViewController, NSFetchedResultsControllerDelegate, UITableViewDataSource, UITableViewDelegate, DetailViewControllerDelegate {
var twitterAccount: ACAccount? = nil
var use3Layer: Bool = false
var twitterStream: TwitterStream? = nil
var moc: NSManagedObjectContext? = nil
var workMoc: NSManagedObjectContext? = nil
var selectedObjectId: NSManagedObjectID? = nil
var fetchedResertController: NSFetchedResultsController? = nil
@IBOutlet weak var twitterStreamButton: UIButton!
@IBOutlet weak var indicator: UIActivityIndicatorView!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false;
if self.use3Layer {
self.moc = NSManagedObjectContext.defaultContext.createChildContextForMainQueue()
}
else {
self.moc = NSManagedObjectContext.defaultContext
}
self.workMoc = self.moc?.createChildContext()
self.indicator.startAnimating()
self.moc?.performBlock({
self.fetchedResertController = Tweets.createFetchedResultsController(order: "idStr", context: self.moc!)
self.fetchedResertController?.delegate = self
var error: NSError? = nil
if self.fetchedResertController!.performFetch(&error) {
self.reloadData()
}
else {
println("\(error)")
}
})
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.stopTwitterStream()
SDWebImageManager.sharedManager().cancelAll()
}
func reloadData() {
if self.use3Layer {
self.tableView.reloadData()
self.indicator.stopAnimating()
self.navigationItem.title = "\(self.fetchedResertController!.fetchedObjects!.count) tweets"
println("reloadData : \(self.fetchedResertController!.fetchedObjects!.count) tweets")
}
else {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
self.indicator.stopAnimating()
self.navigationItem.title = "\(self.fetchedResertController!.fetchedObjects!.count) tweets"
println("reloadData : \(self.fetchedResertController!.fetchedObjects!.count) tweets")
})
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier! == "DetailSegue" {
var vc = segue.destinationViewController as! DetailViewController
vc.delegate = self;
vc.objectId = self.selectedObjectId;
vc.parentMoc = self.moc;
}
}
@IBAction func addTweet() {
self.selectedObjectId = nil
self.performSegueWithIdentifier("DetailSegue", sender: self)
}
@IBAction func addRandomTweet() {
var tweetCount = (arc4random() % 5) + 1
self.moc?.performBlock({
for var i: UInt32 = 0; i < tweetCount; i++ {
var t = Tweets.create(attributes:
[
"idStr": "\(arc4random())",
"text": "text : \(arc4random())",
]
, context: self.moc!)
var u = Users.create(attributes:
[
"idStr": "\(arc4random())",
"screenName": "screenName : \(arc4random())"
]
, context: self.moc!)
t.user = u
}
self.moc?.save()
})
}
@IBAction func switchTwitterStream() {
if self.twitterStream != nil {
self.stopTwitterStream()
}
else {
self.startTwitterStream()
}
}
func startTwitterStream() {
if let tweetAccount = self.twitterAccount {
self.twitterStream = TwitterStream()
self.twitterStream!.twitterAccount = tweetAccount
self.twitterStream!.moc = self.workMoc
self.twitterStream!.start()
self.twitterStreamButton.setTitle("Stop Twitter Stream", forState: UIControlState.Normal)
}
else {
UIAlertView(title: "", message: "Twitter Account Error!!", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "OK").show()
}
}
func stopTwitterStream() {
if let twitterStream = self.twitterStream {
twitterStream.stop()
self.twitterStream = nil
}
self.twitterStreamButton.setTitle("Start Twitter Stream", forState: UIControlState.Normal)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let count = self.fetchedResertController?.fetchedObjects?.count {
return count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CELL", forIndexPath: indexPath) as! UITableViewCell
if (NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1)
{
cell.contentView.frame = cell.bounds;
cell.contentView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
}
self.configureCell(cell, indexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) {
var t = self.fetchedResertController?.objectAtIndexPath(indexPath) as! Tweet
if self.use3Layer {
var upper = cell.viewWithTag(1) as! UILabel
if let _screenName = t.user?.screenName {
upper.text = "\(indexPath.row) - \(_screenName)"
}
else {
upper.text = "\(indexPath.row) - no screen name"
}
var lower = cell.viewWithTag(2) as! UILabel
lower.text = t.text
var imageView = cell.viewWithTag(3) as! UIImageView
if let _profileImageUrl = t.user?.profileImageUrl {
imageView.sd_setImageWithURL(NSURL(string: _profileImageUrl), placeholderImage: nil)
}
else {
imageView.image = nil
}
}
else {
t.performBlock() {
var screenName : String = ""
if let _screenName = t.user?.screenName {
screenName = "\(indexPath.row) - \(_screenName)"
}
else {
screenName = "\(indexPath.row) - no screen name"
}
var text = t.text
var profileImageUrl = t.user?.profileImageUrl
dispatch_async(dispatch_get_main_queue(), { () -> Void in
var upper = cell.viewWithTag(1) as! UILabel
upper.text = screenName
var lower = cell.viewWithTag(2) as! UILabel
lower.text = text
var imageView = cell.viewWithTag(3) as! UIImageView
if let _profileImageUrl = profileImageUrl {
imageView.sd_setImageWithURL(NSURL(string: _profileImageUrl), placeholderImage: nil)
}
else {
imageView.image = nil
}
})
}
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
var t = self.fetchedResertController?.objectAtIndexPath(indexPath) as! Tweet
self.selectedObjectId = t.objectID
self.performSegueWithIdentifier("DetailSegue", sender: self)
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
var t = self.fetchedResertController?.objectAtIndexPath(indexPath) as! Tweet
t.performBlock({ () -> Void in
if t.user?.tweets?.count == 1 {
t.user!.delete()
}
t.delete()
t.save()
})
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self .reloadData()
}
func detailViewControllerFinished(sender: DetailViewController) {
self.reloadData()
self.navigationController?.popViewControllerAnimated(true)
}
}
|
mit
|
870f7195687201301ce9cd81ddd9a840
| 34.832685 | 156 | 0.569009 | 5.49463 | false | false | false | false |
GhostSK/SpriteKitPractice
|
TileMap/TileMap/GameViewController.swift
|
1
|
1440
|
//
// GameViewController.swift
// TileMap
//
// Created by 胡杨林 on 17/3/20.
// Copyright © 2017年 胡杨林. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
let scene = GameScene(size:CGSize(width: 22 * 32, height: 7 * 32))
// Set the scale mode to scale to fit the window
scene.scaleMode = .resizeFill
print("scene.width = \(scene.frame.width) scene.height = \(scene.frame.height)")
// Present the scene
view.presentScene(scene)
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
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
}
}
|
apache-2.0
|
985147c70f0cfe5a931c2e5065b507f5
| 24.909091 | 98 | 0.581053 | 5.089286 | false | false | false | false |
kevinskyba/ReadyForCoffee
|
ReadyForCoffee/Bond+NSSlider.swift
|
1
|
1420
|
//
// Bond+NSSlider.swift
// ReadyForCoffee
//
// Created by Kevin Skyba on 14.08.15.
// Copyright (c) 2015 Kevin Skyba. All rights reserved.
//
import Foundation
import Cocoa
import Bond
var valueDynamicHandleNSSlider: UInt8 = 0;
extension NSSlider: Dynamical, Bondable {
public var designatedDynamic: Dynamic<Double> {
return self.dynValue
}
public var designatedBond: Bond<Double> {
return self.designatedDynamic.valueBond
}
public var dynValue: Dynamic<Double> {
if let d: AnyObject = objc_getAssociatedObject(self, &valueDynamicHandleNSSlider) {
return (d as? Dynamic<Double>)!
} else {
let d = InternalDynamic<Double>(self.doubleValue)
let bond = Bond<Double>() { [weak self] v in // NSTextView cannot be referenced weakly
if let s = self {
s.doubleValue = v
}
}
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &valueDynamicHandleNSSlider, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
}
public func <->> (left: Dynamic<Double>, right: NSSlider) {
left <->> right.designatedDynamic
}
public func <->> (left: NSSlider, right: Dynamic<Double>) {
left.designatedDynamic <->> right
}
|
mit
|
91229ef18e51d693d337c255071d670a
| 26.326923 | 133 | 0.611268 | 4.369231 | false | false | false | false |
wrld3d/wrld-example-app
|
ios/Include/WrldSDK/iphoneos12.0/WrldUtils.framework/Headers/WRLDUtilsTextField.swift
|
6
|
5817
|
/**
Implement this protocol to receive click events from the image buttons within the text field.
*/
@objc
public protocol WRLDUtilsTextFieldDelegate: class
{
/**
Called when the left image button is pressed.
*/
@objc optional func leftButtonClicked(textField: WRLDUtilsTextField)
/**
Called when the right image button is pressed.
*/
@objc optional func rightButtonClicked(textField: WRLDUtilsTextField)
}
/**
A text field that contains images to the left and right of the text field. These images can be
loaded from a different bundle.
*/
@objc
public class WRLDUtilsTextField: UITextField
{
/**
The identifier of the bundle to load the images from, for example this framework would be
'com.wrld.WrldUtils'.
*/
@IBInspectable public var bundleID: String? {
set { _bundleID = newValue; loadImages() }
get { return _bundleID }
}
private var _bundleID:String?
/**
The name of the image to use for the left icon when the button is in the normal state.
*/
@IBInspectable public var leftImageName: String? {
set { _leftImageName = newValue; loadImages() }
get { return _leftImageName }
}
private var _leftImageName:String?
/**
The name of the image to use for the left icon when the button is in the highlighted state.
*/
@IBInspectable public var leftDownName: String? {
set { _leftDownName = newValue; loadImages() }
get { return _leftDownName }
}
private var _leftDownName:String?
/**
Padding to the left of the left image.
*/
@IBInspectable public var leftPadding: CGFloat {
set { _leftPadding = newValue;}
get { return _leftPadding }
}
private var _leftPadding:CGFloat = 0
/**
The name of the image to use for the right icon when the button is in the normal state.
*/
@IBInspectable public var rightImageName: String? {
set { _rightImageName = newValue; loadImages() }
get { return _rightImageName }
}
private var _rightImageName:String?
/**
The name of the image to use for the right icon when the button is in the highlighted state.
*/
@IBInspectable public var rightDownName: String? {
set { _rightDownName = newValue; loadImages() }
get { return _rightDownName }
}
private var _rightDownName:String?
/**
Padding to the right of the right image.
*/
@IBInspectable public var rightPadding: CGFloat {
set { _rightPadding = newValue;}
get { return _rightPadding }
}
private var _rightPadding:CGFloat = 0
private var _rightButtonView: UIButton?
private var _leftButtonView: UIButton?
public weak var buttonDelegate: WRLDUtilsTextFieldDelegate?
open override func rightViewRect(forBounds bounds: CGRect) -> CGRect
{
var rect = super.rightViewRect(forBounds: bounds)
rect.origin.x -= _rightPadding
return rect
}
open override func leftViewRect(forBounds bounds: CGRect) -> CGRect
{
var rect = super.leftViewRect(forBounds: bounds)
rect.origin.x += _leftPadding
return rect
}
enum ButtonSide
{
case right
case left
}
private func getButton(side: ButtonSide) -> UIButton
{
var button: UIButton? = (side == .right) ? _rightButtonView : _leftButtonView
if(button == nil)
{
button = UIButton(type: .custom)
button?.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
if(side == .right)
{
button?.addTarget(self, action:#selector(self.rightButtonClicked), for: .touchUpInside)
_rightButtonView = button
rightView = button
rightViewMode = .always
}
else
{
button?.addTarget(self, action:#selector(self.leftButtonClicked), for: .touchUpInside)
_leftButtonView = button
leftView = button
leftViewMode = .always
}
}
return button!
}
@objc public func rightButtonClicked()
{
buttonDelegate?.rightButtonClicked?(textField: self)
}
@objc public func leftButtonClicked()
{
buttonDelegate?.leftButtonClicked?(textField: self)
}
private func loadImage(_ bundle: Bundle, _ path: String?) -> UIImage?
{
if let imagePath = path
{
return UIImage(named: imagePath, in: bundle, compatibleWith: nil)
}
return nil
}
private func loadImages()
{
if let bundleID = _bundleID
{
if let bundle = Bundle(identifier: bundleID)
{
if let image = loadImage(bundle, _leftImageName)
{
getButton(side: .left).setImage(image, for: .normal)
}
if let image = loadImage(bundle, _rightImageName)
{
getButton(side: .right).setImage(image, for: .normal)
}
if let image = loadImage(bundle, _leftDownName)
{
getButton(side: .left).setImage(image, for: .selected)
getButton(side: .left).setImage(image, for: .highlighted)
}
if let image = loadImage(bundle, _rightDownName)
{
getButton(side: .right).setImage(image, for: .selected)
getButton(side: .right).setImage(image, for: .highlighted)
}
}
}
}
}
|
bsd-2-clause
|
9ef23519d69c11cb5a67bb7b1a5eac8b
| 29.296875 | 103 | 0.574523 | 4.831395 | false | false | false | false |
iJason92/Geographical-scenery
|
Geographical-scenery/Geographical-scenery/classes/module/home/JHomeCollectionVC.swift
|
1
|
1979
|
//
// JHomeCollectionVC.swift
// Geographical-scenery
//
// Created by Jason on 31/5/15.
// Copyright (c) 2015 Shepherd. All rights reserved.
//
import UIKit
private let reuseId = "JHomeCell"
class JHomeCollectionVC: UICollectionViewController {
@IBOutlet weak var layout: UICollectionViewFlowLayout!
override func viewDidLoad() {
super.viewDidLoad()
// 使用图片设置collectionView的背景色
collectionView?.backgroundColor = UIColor(patternImage: UIImage(named: "bj")!)
}
// MARK: - UICollection的数据源方法
// 每一组有多少个cell
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 60
}
// 每个cell的内容
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseId, forIndexPath: indexPath) as! JHomeCell
return cell
}
}
/*** 图片概览的cell */
class JHomeCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
prepareLoad()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
prepareLoad()
}
// 初始化视图
private func prepareLoad() {
// 图片
// 背景色
backgroundColor = UIColor.whiteColor()
// 圆角
layer.cornerRadius = 8
layer.masksToBounds = true
// 选中的背景视图
let bgView = JCustomCellBg()
selectedBackgroundView = bgView
}
/*** 日期 */
@IBOutlet weak var dateLabel: UILabel!
/** 相册缩略视图 */
@IBOutlet weak var albumThumbView: UIImageView!
/*** 是否已读缩略图 */
@IBOutlet weak var readButton: UIButton!
}
|
mit
|
ca189b3ec5a9478f821948366f5ec8fe
| 24.985915 | 139 | 0.64607 | 4.742931 | false | false | false | false |
whiteshadow-gr/HatForIOS
|
HAT/Objects/Fitbit/HATFitbitWeight.swift
|
1
|
1470
|
/**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* 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/
*/
// MARK: Struct
public struct HATFitbitWeight: HATObject {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `bmi` in JSON is `bmi`
* `fat` in JSON is `fat`
* `date` in JSON is `date`
* `time` in JSON is `time`
* `logId` in JSON is `logId`
* `source` in JSON is `source`
* `weight` in JSON is `weight`
*/
private enum CodingKeys: String, CodingKey {
case bmi
case fat
case date
case time
case logId
case source
case weight
}
// MARK: - Variables
/// User's BMI
public var bmi: Float = 0
/// User's fat
public var fat: Float = 0
/// User's weight date recorded in yyyy-MM-dd format
public var date: String = ""
/// User's weight time recorder in HH:MM:SS format
public var time: String = ""
/// Weight log ID
public var logId: Int = 0
/// User's weight source, most probably API
public var source: String = ""
/// User's weight
public var weight: Float = 0
}
|
mpl-2.0
|
cf4765825da6b7eda12587ac3d5d876a
| 24.344828 | 70 | 0.585034 | 3.848168 | false | false | false | false |
Chaosspeeder/YourGoals
|
YourGoals/Business/DataSource/ActiveLifeDataSource.swift
|
1
|
3850
|
//
// ActiveLifeDataSource.swift
// YourGoals
//
// Created by André Claaßen on 22.06.19.
// Copyright © 2019 André Claaßen. All rights reserved.
//
import Foundation
/// protocol for fetching actionables (tasks or habits) in various controllers
protocol ActionableLifeDataSource {
/// fetch a ordered array of items for an active life view from the data source
///
/// - Parameter
/// - date: fetch items for this date
///
/// - Returns: an ordered array of time infos
/// - Throws: core data exception
func fetchTimeInfos(forDate date: Date, withBackburned backburnedGoals: Bool?) throws -> [ActionableTimeInfo]
/// retrieve the reordering protocol, if the datasource allows task reordering
///
/// - Returns: a protocol for exchange items
func positioningProtocol() -> ActionablePositioningProtocol?
/// get a switch protocol for a specific behavior if available for this actionable data source
///
/// - Returns: a switch protol
func switchProtocol(forBehavior behavior: ActionableBehavior) -> ActionableSwitchProtocol?
}
/// a data source, which simulates the active life view
///
/// This data source generates only actionable time infos out of done progress and active task items
class ActiveLifeDataSource: ActionableDataSource, ActionablePositioningProtocol {
let manager:GoalsStorageManager
let taskManager:TaskCommitmentManager
let switchProtocolProvider:TaskSwitchProtocolProvider
/// intialize with a core data storage manager
///
/// - Parameter manager: the storage manager
init(manager: GoalsStorageManager) {
self.manager = manager
self.taskManager = TaskCommitmentManager(manager: manager)
self.switchProtocolProvider = TaskSwitchProtocolProvider(manager: manager)
}
// MARK: ActionableLifeDataSource
/// there are no sections in this data source
func fetchSections(forDate date: Date, withBackburned backburnedGoals: Bool) throws -> [ActionableSection] {
return []
}
/// fetch the time infos needed for the active life data source
///
/// - Parameters:
/// - date: date/time to calculate the items
/// - backburnedGoals: true, if backburned tasks should be considered
///
/// - Returns: time infos which represent the active life data view
/// - Throws: core data exceptions
func fetchItems(forDate date: Date, withBackburned backburnedGoals: Bool, andSection: ActionableSection?) throws -> [ActionableItem] {
let committedTasks = try taskManager.committedTasks(forDate: date, backburnedGoals: backburnedGoals)
let calculator = ActiveLifeScheduleCalculator(manager: self.manager)
let timeInfos = try! calculator.calculateTimeInfoForActiveLife(forTime: date, actionables: committedTasks)
return timeInfos
}
/// retrieve the positioning protocoll for redordering the ites
func positioningProtocol() -> ActionablePositioningProtocol? {
return self
}
/// retrieve the switch protocol for starting stopping items
func switchProtocol(forBehavior behavior: ActionableBehavior) -> ActionableSwitchProtocol? {
return self.switchProtocolProvider.switchProtocol(forBehavior: behavior)
}
// MARK: ActionablePositioningProtocol
func updatePosition(items: [ActionableItem], fromPosition: Int, toPosition: Int) throws {
assertionFailure("this method needs to be coded!")
// try self.taskManager.updateTaskPosition(tasks: actionables.map { $0 as! Task }, fromPosition: fromPosition, toPosition: toPosition)
}
func moveIntoSection(item: ActionableItem, section: ActionableSection, toPosition: Int) throws {
assertionFailure("this method shouldn't be called")
}
}
|
lgpl-3.0
|
2e73679b3e0273b712fa2bf9587440fa
| 39.473684 | 142 | 0.712094 | 4.935815 | false | false | false | false |
blg-andreasbraun/ProcedureKit
|
Tests/Cloud/TestableCloudKitContainer.swift
|
2
|
1868
|
//
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
import XCTest
import CloudKit
import ProcedureKit
import TestingProcedureKit
@testable import ProcedureKitCloud
class TestableCloudKitContainerRegistrar: CloudKitContainerRegistrar {
var accountStatus: CKAccountStatus = .couldNotDetermine
var accountStatusError: Error? = nil
var verifyApplicationPermissionStatus: CKApplicationPermissionStatus = .initialState
var verifyApplicationPermissionsError: Error? = nil
var verifyApplicationPermissions: CKApplicationPermissions? = nil
var requestApplicationPermissionStatus: CKApplicationPermissionStatus = .granted
var requestApplicationPermissionsError: Error? = nil
var requestApplicationPermissions: CKApplicationPermissions? = nil
var didGetAccountStatus = false
var didVerifyApplicationStatus = false
var didRequestApplicationStatus = false
func pk_accountStatus(withCompletionHandler completionHandler: @escaping (CKAccountStatus, Error?) -> Void) {
didGetAccountStatus = true
completionHandler(accountStatus, accountStatusError)
}
func pk_status(forApplicationPermission applicationPermission: CKApplicationPermissions, completionHandler: @escaping CKApplicationPermissionBlock) {
didVerifyApplicationStatus = true
verifyApplicationPermissions = applicationPermission
completionHandler(verifyApplicationPermissionStatus, verifyApplicationPermissionsError)
}
func pk_requestApplicationPermission(_ applicationPermission: CKApplicationPermissions, completionHandler: @escaping CKApplicationPermissionBlock) {
didRequestApplicationStatus = true
requestApplicationPermissions = applicationPermission
completionHandler(requestApplicationPermissionStatus, requestApplicationPermissionsError)
}
}
|
mit
|
e5ab8aa1c26c6ceb661c5c164c806ce0
| 37.895833 | 153 | 0.804499 | 6.121311 | false | true | false | false |
skedgo/tripkit-ios
|
Sources/TripKit/model/CoreData/Alert+CoreDataClass.swift
|
1
|
1873
|
//
// Alert+CoreDataClass.swift
// TripKit
//
// Created by Adrian Schönig on 12/8/21.
// Copyright © 2021 SkedGo Pty Ltd. All rights reserved.
//
//
#if canImport(CoreData)
import Foundation
import CoreData
import MapKit
@objc(Alert)
public class Alert: NSManagedObject {
}
public enum TKAlertSeverity: Int {
case info = -1
case warning = 0
case alert = 1
}
extension Alert {
// Constants
public enum ActionTypeIdentifier {
static let excludingStopsFromRouting: String = "excludedStopCodes"
}
public static func fetch(hashCode: NSNumber, in context: NSManagedObjectContext) -> Alert? {
return context.fetchUniqueObject(Alert.self, predicate: NSPredicate(format: "hashCode = %@", hashCode))
}
public var alertSeverity: TKAlertSeverity {
get {
TKAlertSeverity(rawValue: Int(severity)) ?? .warning
}
set {
severity = Int16(newValue.rawValue)
}
}
public var imageURL: URL? {
remoteIcon.flatMap { TKServer.imageURL(iconFileNamePart: $0, iconType: .alert) }
}
@objc public var infoIconType: TKInfoIconType {
switch alertSeverity {
case .info, .warning: return .warning
case .alert: return .alert
}
}
/// This is an array of `stopCode`. A non-empty value indicates the alert requires a
/// reroute action because, e.g., the stops have become inaccessible. This property
/// is typically passed to a routing request as stops to avoid during routing.
public var stopsExcludedFromRouting: [String] {
return action?[ActionTypeIdentifier.excludingStopsFromRouting] as? [String] ?? []
}
}
// MARK: - MKAnnotation
extension Alert: MKAnnotation {
public var coordinate: CLLocationCoordinate2D {
if let location = location {
return location.coordinate
} else {
return kCLLocationCoordinate2DInvalid
}
}
}
#endif
|
apache-2.0
|
1a7685452e438e98cd81626359f2416d
| 22.098765 | 107 | 0.69054 | 4.094092 | false | false | false | false |
darlinghq/darling
|
src/configd/SCTest-Swift/main.swift
|
1
|
4395
|
/*
* Copyright (c) 2015, 2018 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* Modification History
*
* April 21, 2015 Sushant Chavan
* - initial revision
*/
/*
* A Swift test target to test SC APIs
*/
import Foundation
import SystemConfiguration
import SystemConfiguration_Private
let target_host = "www.apple.com"
var application = "SCTest-Swift" as CFString
#if !targetEnvironment(simulator)
func
test_SCDynamicStore ()
{
//SCDynamicStore APIs
NSLog("\n\n*** SCDynamicStore ***\n\n")
let key:CFString
let store:SCDynamicStore?
let dict:[String:String]?
let primaryIntf:String?
store = SCDynamicStoreCreate(nil, application, nil, nil)
if store == nil {
NSLog("Error creating session: %s", SCErrorString(SCError()))
return
}
key = SCDynamicStoreKeyCreateNetworkGlobalEntity(nil, kSCDynamicStoreDomainState, kSCEntNetIPv4)
dict = SCDynamicStoreCopyValue(store, key) as? [String:String]
primaryIntf = dict?[kSCDynamicStorePropNetPrimaryInterface as String]
if (primaryIntf != nil) {
NSLog("Primary interface is %@", primaryIntf!)
} else {
NSLog("Primary interface is unavailable")
}
}
#endif // !targetEnvironment(simulator)
#if !targetEnvironment(simulator)
func
test_SCNetworkConfiguration ()
{
//SCNetworkConfiguration APIs
NSLog("\n\n*** SCNetworkConfiguration ***\n\n")
let interfaceArray:[CFArray]
NSLog("Network Interfaces:")
interfaceArray = SCNetworkInterfaceCopyAll() as! [CFArray]
for idx in 0...interfaceArray.count {
let interface = interfaceArray[idx]
if let bsdName = SCNetworkInterfaceGetBSDName(interface as! SCNetworkInterface) {
NSLog("- %@", bsdName as String)
}
}
}
#endif // !targetEnvironment(simulator)
func
test_SCNetworkReachability ()
{
//SCNetworkReachability APIs
NSLog("\n\n*** SCNetworkReachability ***\n\n")
let target:SCNetworkReachability?
var flags:SCNetworkReachabilityFlags = SCNetworkReachabilityFlags.init(rawValue: 0)
target = SCNetworkReachabilityCreateWithName(nil, target_host)
if target == nil {
NSLog("Error creating target: %s", SCErrorString(SCError()))
return
}
SCNetworkReachabilityGetFlags(target!, &flags)
NSLog("SCNetworkReachability flags for %@ is %#x", String(target_host), flags.rawValue)
}
#if !targetEnvironment(simulator)
func
test_SCPreferences ()
{
//SCPreferences APIs
NSLog("\n\n*** SCPreferences ***\n\n")
let prefs:SCPreferences?
let networkServices:[CFArray]?
prefs = SCPreferencesCreate(nil, application, nil)
if prefs == nil {
NSLog("Error creating prefs: %s", SCErrorString(SCError()))
return
}
if let model = SCPreferencesGetValue(prefs!, "Model" as CFString) {
NSLog("Current system model is %@", model as! String)
}
networkServices = SCNetworkServiceCopyAll(prefs!) as? [CFArray]
if networkServices == nil {
NSLog("Error retrieving network services", SCErrorString(SCError()))
return
}
NSLog("Network Services:")
for idx in 0...(networkServices?.count)! {
let service = networkServices?[idx]
if let serviceName = SCNetworkServiceGetName(service as! SCNetworkService) {
NSLog("- %@", serviceName as String)
}
}
}
#endif // !targetEnvironment(simulator)
func
my_main ()
{
#if !targetEnvironment(simulator)
test_SCDynamicStore()
#endif // !targetEnvironment(simulator)
#if !targetEnvironment(simulator)
test_SCNetworkConfiguration()
#endif // !targetEnvironment(simulator)
test_SCNetworkReachability()
#if !targetEnvironment(simulator)
test_SCPreferences()
#endif // !targetEnvironment(simulator)
}
// Run the test
my_main()
|
gpl-3.0
|
9c94a1994c5a904b9fcc70f1c6ee686e
| 25.79878 | 97 | 0.745165 | 3.650332 | false | true | false | false |
mattrajca/swift-corelibs-foundation
|
Foundation/NSArray.swift
|
4
|
32795
|
// 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
//
import CoreFoundation
open class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
private let _cfinfo = _CFInfo(typeID: CFArrayGetTypeID())
internal var _storage = [AnyObject]()
open var count: Int {
guard type(of: self) === NSArray.self || type(of: self) === NSMutableArray.self else {
NSRequiresConcreteImplementation()
}
return _storage.count
}
open func object(at index: Int) -> Any {
guard type(of: self) === NSArray.self || type(of: self) === NSMutableArray.self else {
NSRequiresConcreteImplementation()
}
return _SwiftValue.fetch(nonOptional: _storage[index])
}
public override init() {
_storage.reserveCapacity(0)
}
public required init(objects: UnsafePointer<AnyObject>?, count: Int) {
precondition(count >= 0)
precondition(count == 0 || objects != nil)
_storage.reserveCapacity(count)
for idx in 0..<count {
_storage.append(objects![idx])
}
}
public convenience init(objects: UnsafePointer<AnyObject>, count: Int) {
self.init()
_storage.reserveCapacity(count)
for idx in 0..<count {
_storage.append(objects[idx])
}
}
public convenience init(objects elements: AnyObject...) {
self.init(objects: elements, count: elements.count)
}
public required convenience init(arrayLiteral elements: Any...) {
self.init(array: elements)
}
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.objects") {
let objects = aDecoder._decodeArrayOfObjectsForKey("NS.objects")
self.init(array: objects as! [NSObject])
} else {
var objects = [AnyObject]()
var count = 0
while let object = aDecoder.decodeObject(forKey: "NS.object.\(count)") {
objects.append(object as! NSObject)
count += 1
}
self.init(array: objects)
}
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if let keyedArchiver = aCoder as? NSKeyedArchiver {
keyedArchiver._encodeArrayOfObjects(self, forKey:"NS.objects")
} else {
for object in self {
if let codable = object as? NSCoding {
codable.encode(with: aCoder)
}
}
}
}
public static var supportsSecureCoding: Bool {
return true
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSArray.self {
// return self for immutable type
return self
} else if type(of: self) === NSMutableArray.self {
let array = NSArray()
array._storage = self._storage
return array
}
return NSArray(array: self.allObjects)
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSArray.self || type(of: self) === NSMutableArray.self {
// always create and return an NSMutableArray
let mutableArray = NSMutableArray()
mutableArray._storage = self._storage
return mutableArray
}
return NSMutableArray(array: self.allObjects)
}
public convenience init(object anObject: Any) {
self.init(array: [anObject])
}
public convenience init(array: [Any]) {
self.init(array: array, copyItems: false)
}
public convenience init(array: [Any], copyItems: Bool) {
let optionalArray : [AnyObject] =
copyItems ?
array.map { return _SwiftValue.store($0).copy() as! NSObject } :
array.map { return _SwiftValue.store($0) }
// This would have been nice, but "initializer delegation cannot be nested in another expression"
// optionalArray.withUnsafeBufferPointer { ptr in
// self.init(objects: ptr.baseAddress, count: array.count)
// }
let cnt = array.count
let buffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: cnt)
buffer.initialize(from: optionalArray, count: cnt)
self.init(objects: buffer, count: cnt)
buffer.deinitialize(count: cnt)
buffer.deallocate()
}
open override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as [Any]:
return self.isEqual(to: other)
case let other as NSArray:
return self.isEqual(to: other.allObjects)
default:
return false
}
}
open override var hash: Int {
return self.count
}
internal var allObjects: [Any] {
if type(of: self) === NSArray.self || type(of: self) === NSMutableArray.self {
return _storage.map { _SwiftValue.fetch(nonOptional: $0) }
} else {
return (0..<count).map { idx in
return self[idx]
}
}
}
open func adding(_ anObject: Any) -> [Any] {
return allObjects + [anObject]
}
open func addingObjects(from otherArray: [Any]) -> [Any] {
return allObjects + otherArray
}
open func componentsJoined(by separator: String) -> String {
// make certain to call NSObject's description rather than asking the string interpolator for the swift description
return allObjects.map { "\($0)" }.joined(separator: separator)
}
open func contains(_ anObject: Any) -> Bool {
guard let other = anObject as? AnyHashable else {
return false
}
for idx in 0..<count {
if let obj = self[idx] as? AnyHashable {
if obj == other {
return true
}
}
}
return false
}
override open var description: String {
return description(withLocale: nil)
}
open func description(withLocale locale: Locale?) -> String {
return description(withLocale: locale, indent: 0)
}
open func description(withLocale locale: Locale?, indent level: Int) -> String {
var descriptions = [String]()
let cnt = count
for idx in 0..<cnt {
let obj = self[idx]
if let string = obj as? String {
descriptions.append(string)
} else if let array = obj as? [Any] {
descriptions.append(NSArray(array: array).description(withLocale: locale, indent: level + 1))
} else if let dict = obj as? [AnyHashable : Any] {
descriptions.append(dict._bridgeToObjectiveC().description(withLocale: locale, indent: level + 1))
} else {
descriptions.append("\(obj)")
}
}
var indent = ""
for _ in 0..<level {
indent += " "
}
var result = indent + "(\n"
for idx in 0..<cnt {
result += indent + " " + descriptions[idx]
if idx + 1 < cnt {
result += ",\n"
} else {
result += "\n"
}
}
result += indent + ")"
return result
}
open func firstObjectCommon(with otherArray: [Any]) -> Any? {
let set = otherArray.map { _SwiftValue.store($0) }
for idx in 0..<count {
let item = _SwiftValue.store(self[idx])
if set.contains(item) {
return _SwiftValue.fetch(nonOptional: item)
}
}
return nil
}
internal func getObjects(_ objects: inout [Any], range: NSRange) {
objects.reserveCapacity(objects.count + range.length)
if type(of: self) === NSArray.self || type(of: self) === NSMutableArray.self {
objects += _storage[Range(range)!].map { _SwiftValue.fetch(nonOptional: $0) }
return
}
objects += range.toCountableRange()!.map { self[$0] }
}
open func index(of anObject: Any) -> Int {
guard let val = anObject as? AnyHashable else {
return NSNotFound
}
for idx in 0..<count {
if let obj = object(at: idx) as? AnyHashable {
if val == obj {
return idx
}
}
}
return NSNotFound
}
open func index(of anObject: Any, in range: NSRange) -> Int {
guard let val = anObject as? AnyHashable else {
return NSNotFound
}
for idx in 0..<range.length {
if let obj = object(at: idx + range.location) as? AnyHashable {
if val == obj {
return idx
}
}
}
return NSNotFound
}
open func indexOfObjectIdentical(to anObject: Any) -> Int {
guard let val = anObject as? NSObject else {
return NSNotFound
}
for idx in 0..<count {
if let obj = object(at: idx) as? NSObject {
if val === obj {
return idx
}
}
}
return NSNotFound
}
open func indexOfObjectIdentical(to anObject: Any, in range: NSRange) -> Int {
guard let val = anObject as? NSObject else {
return NSNotFound
}
for idx in 0..<range.length {
if let obj = object(at: idx + range.location) as? NSObject {
if val === obj {
return idx
}
}
}
return NSNotFound
}
open func isEqual(to otherArray: [Any]) -> Bool {
if count != otherArray.count {
return false
}
for idx in 0..<count {
if let val1 = object(at: idx) as? AnyHashable,
let val2 = otherArray[idx] as? AnyHashable {
if val1 != val2 {
return false
}
} else if let val1 = object(at: idx) as? _ObjectBridgeable,
let val2 = otherArray[idx] as? _ObjectBridgeable {
if !(val1._bridgeToAnyObject() as! NSObject).isEqual(val2._bridgeToAnyObject()) {
return false
}
} else {
return false
}
}
return true
}
open var firstObject: Any? {
if count > 0 {
return object(at: 0)
} else {
return nil
}
}
open var lastObject: Any? {
if count > 0 {
return object(at: count - 1)
} else {
return nil
}
}
public struct Iterator : IteratorProtocol {
// TODO: Detect mutations
// TODO: Use IndexingGenerator instead?
let array : NSArray
let sentinel : Int
let reverse : Bool
var idx : Int
public mutating func next() -> Any? {
guard idx != sentinel else {
return nil
}
let result = array.object(at: reverse ? idx - 1 : idx)
idx += reverse ? -1 : 1
return result
}
init(_ array : NSArray, reverse : Bool = false) {
self.array = array
self.sentinel = reverse ? 0 : array.count
self.idx = reverse ? array.count : 0
self.reverse = reverse
}
}
open func objectEnumerator() -> NSEnumerator {
return NSGeneratorEnumerator(Iterator(self))
}
open func reverseObjectEnumerator() -> NSEnumerator {
return NSGeneratorEnumerator(Iterator(self, reverse: true))
}
open var sortedArrayHint: Data {
let size = MemoryLayout<Int32>.size * count
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
buffer.withMemoryRebound(to: Int32.self, capacity: count) { (ptr) in
for idx in 0..<count {
let item = object(at: idx) as! NSObject
let hash = item.hash
ptr.advanced(by: idx).pointee = Int32(hash).littleEndian
}
}
return Data(bytesNoCopy: buffer, count: size, deallocator: .custom({ (_, _) in
buffer.deallocate()
}))
}
open func sortedArray(_ comparator: (Any, Any, UnsafeMutableRawPointer?) -> Int, context: UnsafeMutableRawPointer?) -> [Any] {
return sortedArray(options: []) { lhs, rhs in
return ComparisonResult(rawValue: comparator(lhs, rhs, context))!
}
}
open func sortedArray(_ comparator: (Any, Any, UnsafeMutableRawPointer?) -> Int, context: UnsafeMutableRawPointer?, hint: Data?) -> [Any] {
return sortedArray(options: []) { lhs, rhs in
return ComparisonResult(rawValue: comparator(lhs, rhs, context))!
}
}
open func subarray(with range: NSRange) -> [Any] {
if range.length == 0 {
return []
}
var objects = [Any]()
getObjects(&objects, range: range)
return objects
}
open func write(to url: URL) throws {
let pListData = try PropertyListSerialization.data(fromPropertyList: self, format: .xml, options: 0)
try pListData.write(to: url, options: .atomic)
}
@available(*, deprecated)
open func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool {
return write(to: URL(fileURLWithPath: path), atomically: useAuxiliaryFile)
}
// the atomically flag is ignored if url of a type that cannot be written atomically.
@available(*, deprecated)
open func write(to url: URL, atomically: Bool) -> Bool {
do {
let pListData = try PropertyListSerialization.data(fromPropertyList: self, format: .xml, options: 0)
try pListData.write(to: url, options: atomically ? .atomic : [])
return true
} catch {
return false
}
}
open func objects(at indexes: IndexSet) -> [Any] {
var objs = [Any]()
indexes.rangeView.forEach {
objs.append(contentsOf: self.subarray(with: NSRange(location: $0.lowerBound, length: $0.upperBound - $0.lowerBound)))
}
return objs
}
open subscript (idx: Int) -> Any {
guard idx < count && idx >= 0 else {
fatalError("\(self): Index out of bounds")
}
return object(at: idx)
}
open func enumerateObjects(_ block: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
self.enumerateObjects(options: [], using: block)
}
open func enumerateObjects(options opts: NSEnumerationOptions = [], using block: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
self.enumerateObjects(at: IndexSet(integersIn: 0..<count), options: opts, using: block)
}
open func enumerateObjects(at s: IndexSet, options opts: NSEnumerationOptions = [], using block: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
s._bridgeToObjectiveC().enumerate(options: opts) { (idx, stop) in
block(self.object(at: idx), idx, stop)
}
}
open func indexOfObject(passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
return indexOfObject(options: [], passingTest: predicate)
}
open func indexOfObject(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
return indexOfObject(at: IndexSet(integersIn: 0..<count), options: opts, passingTest: predicate)
}
open func indexOfObject(at s: IndexSet, options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
var result = NSNotFound
enumerateObjects(at: s, options: opts) { (obj, idx, stop) -> Void in
if predicate(obj, idx, stop) {
result = idx
stop.pointee = true
}
}
return result
}
open func indexesOfObjects(passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet {
return indexesOfObjects(options: [], passingTest: predicate)
}
open func indexesOfObjects(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet {
return indexesOfObjects(at: IndexSet(integersIn: 0..<count), options: opts, passingTest: predicate)
}
open func indexesOfObjects(at s: IndexSet, options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet {
var result = IndexSet()
enumerateObjects(at: s, options: opts) { (obj, idx, stop) in
if predicate(obj, idx, stop) {
result.insert(idx)
}
}
return result
}
internal func sortedArray(from range: NSRange, options: NSSortOptions, usingComparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] {
// The sort options are not available. We use the Array's sorting algorithm. It is not stable neither concurrent.
guard options.isEmpty else {
NSUnimplemented()
}
let count = self.count
if range.length == 0 || count == 0 {
return []
}
let swiftRange = Range(range)!
return allObjects[swiftRange].sorted { lhs, rhs in
return cmptr(lhs, rhs) == .orderedAscending
}
}
open func sortedArray(comparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] {
return sortedArray(from: NSRange(location: 0, length: count), options: [], usingComparator: cmptr)
}
open func sortedArray(options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] {
return sortedArray(from: NSRange(location: 0, length: count), options: opts, usingComparator: cmptr)
}
open func index(of obj: Any, inSortedRange r: NSRange, options opts: NSBinarySearchingOptions = [], usingComparator cmp: (Any, Any) -> ComparisonResult) -> Int {
let lastIndex = r.location + r.length - 1
// argument validation
guard lastIndex < count else {
let bounds = count == 0 ? "for empty array" : "[0 .. \(count - 1)]"
NSInvalidArgument("range \(r) extends beyond bounds \(bounds)")
}
if opts.contains(.firstEqual) && opts.contains(.lastEqual) {
NSInvalidArgument("both NSBinarySearching.firstEqual and NSBinarySearching.lastEqual options cannot be specified")
}
let searchForInsertionIndex = opts.contains(.insertionIndex)
// fringe cases
if r.length == 0 {
return searchForInsertionIndex ? r.location : NSNotFound
}
let leastObj = object(at: r.location)
if cmp(obj, leastObj) == .orderedAscending {
return searchForInsertionIndex ? r.location : NSNotFound
}
let greatestObj = object(at: lastIndex)
if cmp(obj, greatestObj) == .orderedDescending {
return searchForInsertionIndex ? lastIndex + 1 : NSNotFound
}
// common processing
let firstEqual = opts.contains(.firstEqual)
let lastEqual = opts.contains(.lastEqual)
let anyEqual = !(firstEqual || lastEqual)
var result = NSNotFound
var indexOfLeastGreaterThanObj = NSNotFound
var start = r.location
var end = lastIndex
loop: while start <= end {
let middle = start + (end - start) / 2
let item = object(at: middle)
switch cmp(item, obj) {
case .orderedSame where anyEqual:
result = middle
break loop
case .orderedSame where lastEqual:
result = middle
fallthrough
case .orderedAscending:
start = middle + 1
case .orderedSame where firstEqual:
result = middle
fallthrough
case .orderedDescending:
indexOfLeastGreaterThanObj = middle
end = middle - 1
default:
fatalError("Implementation error.")
}
}
if !searchForInsertionIndex {
return result
}
if result == NSNotFound {
return indexOfLeastGreaterThanObj
}
return lastEqual ? result + 1 : result
}
public convenience init(contentsOf url: URL, error: ()) throws {
let plistDoc = try Data(contentsOf: url)
guard let plistArray = try PropertyListSerialization.propertyList(from: plistDoc, options: [], format: nil) as? Array<Any>
else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [NSURLErrorKey : url])
}
self.init(array: plistArray)
}
@available(*, deprecated)
public convenience init?(contentsOfFile path: String) {
do {
try self.init(contentsOf: URL(fileURLWithPath: path), error: ())
} catch {
return nil
}
}
@available(*, deprecated)
public convenience init?(contentsOf url: URL) {
do {
try self.init(contentsOf: url, error: ())
} catch {
return nil
}
}
open func pathsMatchingExtensions(_ filterTypes: [String]) -> [String] {
guard filterTypes.count > 0 else {
return []
}
let extensions: [String] = filterTypes.map {
var ext = "."
ext.append($0)
return ext
}
return self.filter {
// The force unwrap will abort if the element is not a String but this behaviour matches Dawrin, which throws an exception.
let filename = $0 as! String
for ext in extensions {
if filename.hasSuffix(ext) && filename.count > ext.count {
return true
}
}
return false
} as! [String]
}
override open var _cfTypeID: CFTypeID {
return CFArrayGetTypeID()
}
}
extension NSArray : _CFBridgeable, _SwiftBridgeable {
internal var _cfObject: CFArray { return unsafeBitCast(self, to: CFArray.self) }
internal var _swiftObject: [AnyObject] { return Array._unconditionallyBridgeFromObjectiveC(self) }
}
extension NSMutableArray {
internal var _cfMutableObject: CFMutableArray { return unsafeBitCast(self, to: CFMutableArray.self) }
}
extension CFArray : _NSBridgeable, _SwiftBridgeable {
internal var _nsObject: NSArray { return unsafeBitCast(self, to: NSArray.self) }
internal var _swiftObject: Array<Any> { return _nsObject._swiftObject }
}
extension CFArray {
/// Bridge something returned from CF to an Array<T>. Useful when we already know that a CFArray contains objects that are toll-free bridged with Swift objects, e.g. CFArray<CFURLRef>.
/// - Note: This bridging operation is unfortunately still O(n), but it only traverses the NSArray once, creating the Swift array and casting at the same time.
func _unsafeTypedBridge<T : _CFBridgeable>() -> Array<T> {
var result = Array<T>()
let count = CFArrayGetCount(self)
result.reserveCapacity(count)
for i in 0..<count {
result.append(unsafeBitCast(CFArrayGetValueAtIndex(self, i), to: T.self))
}
return result
}
}
extension Array : _NSBridgeable, _CFBridgeable {
internal var _nsObject: NSArray { return _bridgeToObjectiveC() }
internal var _cfObject: CFArray { return _nsObject._cfObject }
}
public struct NSBinarySearchingOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let firstEqual = NSBinarySearchingOptions(rawValue: 1 << 8)
public static let lastEqual = NSBinarySearchingOptions(rawValue: 1 << 9)
public static let insertionIndex = NSBinarySearchingOptions(rawValue: 1 << 10)
}
open class NSMutableArray : NSArray {
open func add(_ anObject: Any) {
insert(anObject, at: count)
}
open func insert(_ anObject: Any, at index: Int) {
guard type(of: self) === NSMutableArray.self else {
NSRequiresConcreteImplementation()
}
_storage.insert(_SwiftValue.store(anObject), at: index)
}
open func insert(_ objects: [Any], at indexes: IndexSet) {
precondition(objects.count == indexes.count)
if type(of: self) === NSMutableArray.self {
_storage.reserveCapacity(count + indexes.count)
}
var objectIdx = 0
for insertionIndex in indexes {
self.insert(objects[objectIdx], at: insertionIndex)
objectIdx += 1
}
}
open func removeLastObject() {
if count > 0 {
removeObject(at: count - 1)
}
}
open func removeObject(at index: Int) {
guard type(of: self) === NSMutableArray.self else {
NSRequiresConcreteImplementation()
}
_storage.remove(at: index)
}
open func replaceObject(at index: Int, with anObject: Any) {
guard type(of: self) === NSMutableArray.self else {
NSRequiresConcreteImplementation()
}
let min = index
let max = index + 1
_storage.replaceSubrange(min..<max, with: [_SwiftValue.store(anObject) as AnyObject])
}
public override init() {
super.init()
}
public init(capacity numItems: Int) {
super.init(objects: nil, count: 0)
if type(of: self) === NSMutableArray.self {
_storage.reserveCapacity(numItems)
}
}
public required init(objects: UnsafePointer<AnyObject>?, count: Int) {
precondition(count >= 0)
precondition(count == 0 || objects != nil)
super.init()
_storage.reserveCapacity(count)
for idx in 0..<count {
_storage.append(objects![idx])
}
}
open override subscript (idx: Int) -> Any {
get {
return object(at: idx)
}
set(newObject) {
self.replaceObject(at: idx, with: newObject)
}
}
open func addObjects(from otherArray: [Any]) {
if type(of: self) === NSMutableArray.self {
_storage += otherArray.map { _SwiftValue.store($0) as AnyObject }
} else {
for obj in otherArray {
add(obj)
}
}
}
open func exchangeObject(at idx1: Int, withObjectAt idx2: Int) {
if type(of: self) === NSMutableArray.self {
swap(&_storage[idx1], &_storage[idx2])
} else {
NSUnimplemented()
}
}
open func removeAllObjects() {
if type(of: self) === NSMutableArray.self {
_storage.removeAll()
} else {
while count > 0 {
removeObject(at: 0)
}
}
}
open func remove(_ anObject: Any, in range: NSRange) {
let idx = index(of: anObject, in: range)
if idx != NSNotFound {
removeObject(at: idx)
}
}
open func remove(_ anObject: Any) {
let idx = index(of: anObject)
if idx != NSNotFound {
removeObject(at: idx)
}
}
open func removeObject(identicalTo anObject: Any, in range: NSRange) {
let idx = indexOfObjectIdentical(to: anObject, in: range)
if idx != NSNotFound {
removeObject(at: idx)
}
}
open func removeObject(identicalTo anObject: Any) {
let idx = indexOfObjectIdentical(to: anObject)
if idx != NSNotFound {
removeObject(at: idx)
}
}
open func removeObjects(in otherArray: [Any]) {
let set = Set(otherArray.map { $0 as! AnyHashable } )
for idx in (0..<count).reversed() {
if let value = object(at: idx) as? AnyHashable {
if set.contains(value) {
removeObject(at: idx)
}
}
}
}
open func removeObjects(in range: NSRange) {
if type(of: self) === NSMutableArray.self {
_storage.removeSubrange(Range(range)!)
} else {
for idx in range.toCountableRange()!.reversed() {
removeObject(at: idx)
}
}
}
open func replaceObjects(in range: NSRange, withObjectsFrom otherArray: [Any], range otherRange: NSRange) {
var list = [Any]()
otherArray._bridgeToObjectiveC().getObjects(&list, range:otherRange)
replaceObjects(in: range, withObjectsFrom: list)
}
open func replaceObjects(in range: NSRange, withObjectsFrom otherArray: [Any]) {
if type(of: self) === NSMutableArray.self {
_storage.reserveCapacity(count - range.length + otherArray.count)
for idx in 0..<range.length {
_storage[idx + range.location] = _SwiftValue.store(otherArray[idx])
}
for idx in range.length..<otherArray.count {
_storage.insert(_SwiftValue.store(otherArray[idx]), at: idx + range.location)
}
} else {
NSUnimplemented()
}
}
open func setArray(_ otherArray: [Any]) {
if type(of: self) === NSMutableArray.self {
_storage = otherArray.map { _SwiftValue.store($0) }
} else {
replaceObjects(in: NSRange(location: 0, length: count), withObjectsFrom: otherArray)
}
}
open func removeObjects(at indexes: IndexSet) {
for range in indexes.rangeView.reversed() {
self.removeObjects(in: NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound))
}
}
open func replaceObjects(at indexes: IndexSet, with objects: [Any]) {
var objectIndex = 0
for countedRange in indexes.rangeView {
let range = NSRange(location: countedRange.lowerBound, length: countedRange.upperBound - countedRange.lowerBound)
let subObjects = objects[objectIndex..<objectIndex + range.length]
self.replaceObjects(in: range, withObjectsFrom: Array(subObjects))
objectIndex += range.length
}
}
open func sort(_ compare: (Any, Any, UnsafeMutableRawPointer?) -> Int, context: UnsafeMutableRawPointer?) {
self.setArray(self.sortedArray(compare, context: context))
}
open func sort(comparator: Comparator) {
self.sort(options: [], usingComparator: comparator)
}
open func sort(options opts: NSSortOptions = [], usingComparator cmptr: Comparator) {
self.setArray(self.sortedArray(options: opts, usingComparator: cmptr))
}
}
extension NSArray : Sequence {
final public func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension NSArray : ExpressibleByArrayLiteral {
/// Create an instance initialized with `elements`.
// required public convenience init(arrayLiteral elements: Any...) {
//
// }
}
extension NSArray : CustomReflectable {
public var customMirror: Mirror { NSUnimplemented() }
}
extension NSArray : _StructTypeBridgeable {
public typealias _StructType = Array<Any>
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
|
apache-2.0
|
695cc16e30cc9c1914b63b6d23d7d26f
| 33.055036 | 188 | 0.570758 | 4.775739 | false | false | false | false |
dokun1/Lumina
|
Sources/Lumina/UI/LuminaViewController.swift
|
1
|
13033
|
//
// CameraViewController.swift
// CameraFramework
//
// Created by David Okun on 8/29/17.
// Copyright © 2017 David Okun. All rights reserved.
//
import UIKit
import AVFoundation
import CoreML
import Logging
/// The main class that developers should interact with and instantiate when using Lumina
open class LuminaViewController: UIViewController {
internal var logger = Logger(label: "com.okun.Lumina")
var camera: LuminaCamera?
public var torchState: TorchState {
get {
return camera?.torchState ?? .off
}
set(newValue) {
camera?.torchState = newValue
}
}
private var _previewLayer: AVCaptureVideoPreviewLayer?
var previewLayer: AVCaptureVideoPreviewLayer {
if let currentLayer = _previewLayer {
return currentLayer
}
guard let camera = self.camera, let layer = camera.getPreviewLayer() else {
return AVCaptureVideoPreviewLayer()
}
layer.frame = self.view.bounds
_previewLayer = layer
return layer
}
private var _zoomRecognizer: UIPinchGestureRecognizer?
var zoomRecognizer: UIPinchGestureRecognizer {
if let currentRecognizer = _zoomRecognizer {
return currentRecognizer
}
let recognizer = UIPinchGestureRecognizer(target: self, action: #selector(handlePinchGestureRecognizer(recognizer:)))
recognizer.delegate = self
_zoomRecognizer = recognizer
return recognizer
}
private var _focusRecognizer: UITapGestureRecognizer?
var focusRecognizer: UITapGestureRecognizer {
if let currentRecognizer = _focusRecognizer {
return currentRecognizer
}
let recognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGestureRecognizer(recognizer:)))
recognizer.delegate = self
_focusRecognizer = recognizer
return recognizer
}
private var _feedbackGenerator: LuminaHapticFeedbackGenerator?
var feedbackGenerator: LuminaHapticFeedbackGenerator {
if let currentGenerator = _feedbackGenerator {
return currentGenerator
}
let generator = LuminaHapticFeedbackGenerator()
_feedbackGenerator = generator
return generator
}
private var _cancelButton: LuminaButton?
var cancelButton: LuminaButton {
if let currentButton = _cancelButton {
return currentButton
}
let button = LuminaButton(with: SystemButtonType.cancel)
button.addTarget(self, action: #selector(cancelButtonTapped), for: .touchUpInside)
_cancelButton = button
return button
}
private var _shutterButton: LuminaButton?
var shutterButton: LuminaButton {
if let currentButton = _shutterButton {
return currentButton
}
let button = LuminaButton(with: SystemButtonType.shutter)
button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(shutterButtonTapped)))
button.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(shutterButtonLongPressed)))
_shutterButton = button
return button
}
private var _switchButton: LuminaButton?
var switchButton: LuminaButton {
if let currentButton = _switchButton {
return currentButton
}
let button = LuminaButton(with: SystemButtonType.cameraSwitch)
button.addTarget(self, action: #selector(switchButtonTapped), for: .touchUpInside)
_switchButton = button
return button
}
private var _torchButton: LuminaButton?
var torchButton: LuminaButton {
if let currentButton = _torchButton {
return currentButton
}
let button = LuminaButton(with: SystemButtonType.torch)
button.addTarget(self, action: #selector(torchButtonTapped), for: .touchUpInside)
_torchButton = button
return button
}
private var _textPromptView: LuminaTextPromptView?
var textPromptView: LuminaTextPromptView {
if let existingView = _textPromptView {
return existingView
}
let promptView = LuminaTextPromptView()
_textPromptView = promptView
return promptView
}
var isUpdating = false
/// The delegate for streaming output from Lumina
weak open var delegate: LuminaDelegate?
/// The position of the camera
///
/// - Note: Responds live to being set at any time, and will update automatically
open var position: CameraPosition = .back {
didSet {
LuminaLogger.notice(message: "Switching camera position to \(position.rawValue)")
guard let camera = self.camera else {
return
}
camera.position = position
}
}
/// Set this to choose whether or not Lumina will be able to record video by holding down the capture button
///
/// - Note: Responds live to being set at any time, and will update automatically
///
/// - Warning: This setting takes precedence over video data streaming - if this is turned on, frames cannot be streamed, nor can CoreML be used via Lumina's recognizer mechanism.
open var recordsVideo = false {
didSet {
LuminaLogger.notice(message: "Setting video recording mode to \(recordsVideo)")
self.camera?.recordsVideo = recordsVideo
if recordsVideo {
LuminaLogger.warning(message: "frames cannot be streamed, nor can CoreML be used via Lumina's recognizer mechanism")
}
}
}
/// Set this to choose whether or not Lumina will stream video frames through the delegate
///
/// - Note: Responds live to being set at any time, and will update automatically
///
/// - Warning: Will not do anything if delegate is not implemented
open var streamFrames = false {
didSet {
LuminaLogger.notice(message: "Setting frame streaming mode to \(streamFrames)")
self.camera?.streamFrames = streamFrames
}
}
/// Set this to choose whether or not Lumina will stream machine readable metadata through the delegate
///
/// - Note: Responds live to being set at any time, and will update automatically
///
/// - Warning: Will not do anything if delegate is not implemented
open var trackMetadata = false {
didSet {
LuminaLogger.notice(message: "Setting metadata tracking mode to \(trackMetadata)")
self.camera?.trackMetadata = trackMetadata
}
}
/// Lumina comes ready with a view for a text prompt to give instructions to the user, and this is where you can set the text of that prompt
///
/// - Note: Responds live to being set at any time, and will update automatically
///
/// - Warning: If left empty, or unset, no view will be present, but view will be created if changed
open var textPrompt = "" {
didSet {
LuminaLogger.notice(message: "Updating text prompt view to: \(textPrompt)")
self.textPromptView.updateText(to: textPrompt)
}
}
/// Set this to choose a resolution for the camera at any time - defaults to highest resolution possible for camera
///
/// - Note: Responds live to being set at any time, and will update automatically
open var resolution: CameraResolution = .highest {
didSet {
LuminaLogger.notice(message: "Updating camera resolution to \(resolution.rawValue)")
self.camera?.resolution = resolution
}
}
/// Set this to choose a frame rate for the camera at any time - defaults to 30 if query is not available
///
/// - Note: Responds live to being set at any time, and will update automatically
open var frameRate: Int = 30 {
didSet {
LuminaLogger.notice(message: "Attempting to update camera frame rate to \(frameRate) FPS")
self.camera?.frameRate = frameRate
}
}
/// Setting visibility of the buttons (default: all buttons are visible)
public func setCancelButton(visible: Bool) {
cancelButton.isHidden = !visible
}
public func setShutterButton(visible: Bool) {
shutterButton.isHidden = !visible
}
public func setSwitchButton(visible: Bool) {
switchButton.isHidden = !visible
}
public func setTorchButton(visible: Bool) {
torchButton.isHidden = !visible
}
public func pauseCamera() {
self.camera?.stop()
}
public func startCamera() {
self.camera?.start()
}
/// A collection of model types that will be used when streaming images for object recognition
/// - Warning: If this is set, streamFrames is over-ridden to true
open var streamingModels: [LuminaModel]? {
didSet {
self.camera?.streamingModels = streamingModels
self.streamFrames = true
}
}
/// The maximum amount of zoom that Lumina can use
///
/// - Note: Default value will rely on whatever the active device can handle, if this is not explicitly set
open var maxZoomScale: Float = MAXFLOAT {
didSet {
LuminaLogger.notice(message: "Max zoom scale set to \(maxZoomScale)x")
self.camera?.maxZoomScale = maxZoomScale
}
}
/// Set this to decide whether live photos will be captured whenever a still image is captured.
///
/// - Note: Overrides cameraResolution to .photo
///
/// - Warning: If video recording is enabled, live photos will not work.
open var captureLivePhotos: Bool = false {
didSet {
LuminaLogger.notice(message: "Attempting to set live photo capture mode to \(captureLivePhotos)")
self.camera?.captureLivePhotos = captureLivePhotos
}
}
/// Set this to return AVDepthData with a still captured image
///
/// - Note: Only works with .photo, .medium1280x720, and .vga640x480 resolutions
open var captureDepthData: Bool = false {
didSet {
LuminaLogger.notice(message: "Attempting to set depth data capture mode to \(captureDepthData)")
self.camera?.captureDepthData = captureDepthData
}
}
/// Set this to return AVDepthData with streamed video frames
///
/// - Note: Only works on iOS 11.0 or higher
/// - Note: Only works with .photo, .medium1280x720, and .vga640x480 resolutions
open var streamDepthData: Bool = false {
didSet {
LuminaLogger.notice(message: "Attempting to set depth data streaming mode to \(streamDepthData)")
self.camera?.streamDepthData = streamDepthData
}
}
/// Set this to apply a level of logging to Lumina, to track activity within the framework
public static var loggingLevel: Logger.Level = .critical {
didSet {
LuminaLogger.level = loggingLevel
}
}
public var currentZoomScale: Float = 1.0 {
didSet {
self.camera?.currentZoomScale = currentZoomScale
}
}
var beginZoomScale: Float = 1.0
/// run this in order to create Lumina
public init() {
super.init(nibName: nil, bundle: nil)
let camera = LuminaCamera()
camera.delegate = self
self.camera = camera
if let version = LuminaViewController.getVersion() {
LuminaLogger.info(message: "Loading Lumina v\(version)")
}
}
/// run this in order to create Lumina with a storyboard
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let camera = LuminaCamera()
camera.delegate = self
self.camera = camera
if let version = LuminaViewController.getVersion() {
LuminaLogger.info(message: "Loading Lumina v\(version)")
}
}
/// override with caution
open override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
LuminaLogger.error(message: "Camera framework is overloading on memory")
}
/// override with caution
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
createUI()
updateUI(orientation: LuminaViewController.orientation)
self.camera?.updateVideo { result in
self.handleCameraSetupResult(result)
}
if self.recordsVideo {
self.camera?.updateAudio { result in
self.handleCameraSetupResult(result)
}
}
}
static var orientation: UIInterfaceOrientation {
UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.windowScene?.interfaceOrientation ?? .portrait
}
/// override with caution
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
feedbackGenerator.prepare()
}
open override var shouldAutorotate: Bool {
guard let camera = self.camera else {
return true
}
return !camera.recordingVideo
}
/// override with caution
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(true)
self.camera?.stop()
}
/// override with caution
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if self.camera?.recordingVideo == true {
return
}
updateUI(orientation: LuminaViewController.orientation)
updateButtonFrames()
}
/// override with caution
open override var prefersStatusBarHidden: Bool {
return true
}
/// returns a string of the version of Lumina currently in use, follows semantic versioning.
open class func getVersion() -> String? {
let bundle = Bundle(for: LuminaViewController.self)
guard let infoDictionary = bundle.infoDictionary else {
return nil
}
guard let versionString = infoDictionary["CFBundleShortVersionString"] as? String else {
return nil
}
return versionString
}
}
|
mit
|
d997b170b2d41ee42204c2fd16155282
| 31.58 | 181 | 0.707259 | 4.682716 | false | false | false | false |
vahidajimine/RESTController
|
RESTController/ContentType.swift
|
1
|
571
|
//
// RESTController/ContentType.swift
//
// Created by Vahid Ajimine on 2/9/16.
// Copyright © 2018 Vahid Ajimine. All rights reserved.
import Foundation
//MARK: ContentType
/// The HTTP header field for the various MIME types of the body of the request (used with `POST` and `PUT` requests)
public enum ContentType: String {
case json = "application/json"
case urlEncode = "application/x-www-form-urlencoded"
case multipartForm = "multipart/form-data"
case textHTML = "text/html"
static public let headerFieldValue = "Content-Type"
}
|
apache-2.0
|
747004bde4639d212560d897b11aa449
| 30.666667 | 117 | 0.710526 | 3.774834 | false | false | false | false |
Authman2/Pix
|
Pix/ProfilePageCell.swift
|
1
|
3149
|
//
// ProfilePageCell.swift
// Pix
//
// Created by Adeola Uthman on 12/23/16.
// Copyright © 2016 Adeola Uthman. All rights reserved.
//
import UIKit
import SnapKit
class ProfilePageCell: UICollectionViewCell {
/********************************
*
* VARIABLES
*
********************************/
/* A Post object for data grabbing. */
var post: Post!
let imageView: UIImageView = {
let a = UIImageView();
a.translatesAutoresizingMaskIntoConstraints = false;
a.backgroundColor = UIColor(red: 150/255, green: 150/255, blue: 150/255, alpha: 1);
a.isUserInteractionEnabled = true;
return a;
}();
let captionLabel: UILabel = {
let c = UILabel();
c.translatesAutoresizingMaskIntoConstraints = false;
c.textColor = .black;
c.backgroundColor = UIColor(red: 239/255, green: 255/255, blue:245/255, alpha: 1);
c.numberOfLines = 0;
c.font = UIFont(name: c.font.fontName, size: 15);
return c;
}();
let likesLabel: UILabel = {
let l = UILabel();
l.translatesAutoresizingMaskIntoConstraints = false;
l.textColor = .black;
l.backgroundColor = UIColor(red: 239/255, green: 255/255, blue:245/255, alpha: 1);
return l;
}();
let uploaderLabel: UILabel = {
let l = UILabel();
l.translatesAutoresizingMaskIntoConstraints = false;
l.textColor = .black;
l.backgroundColor = UIColor(red: 239/255, green: 255/255, blue:245/255, alpha: 1);
return l;
}();
public func setup() {
addSubview(imageView);
addSubview(captionLabel);
addSubview(likesLabel);
addSubview(uploaderLabel);
sendSubview(toBack: captionLabel);
sendSubview(toBack: likesLabel);
sendSubview(toBack: uploaderLabel);
imageView.snp.makeConstraints { (maker: ConstraintMaker) in
maker.width.equalTo(width);
maker.height.equalTo(height);
maker.centerX.equalTo(snp.centerX);
maker.centerY.equalTo(snp.centerY);
}
uploaderLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.width.equalTo(width);
maker.height.equalTo(50);
maker.top.equalTo(imageView.snp.bottom);
maker.left.equalTo(snp.left);
maker.right.equalTo(snp.right);
}
captionLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.width.equalTo(width);
maker.height.equalTo(50);
maker.top.equalTo(uploaderLabel.snp.bottom);
maker.left.equalTo(snp.left);
maker.right.equalTo(snp.right);
}
likesLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.width.equalTo(width);
maker.height.equalTo(50);
maker.top.equalTo(captionLabel.snp.bottom);
maker.left.equalTo(snp.left);
maker.right.equalTo(snp.right);
}
}
}
|
gpl-3.0
|
02c69f51a0c4da8c08b766d75d27d5b5
| 28.980952 | 91 | 0.566709 | 4.582242 | false | false | false | false |
podkovyrin/Parse-SDK-iOS-OSX
|
ParseStarterProject/iOS/ParseStarterProject-Swift/ParseStarterProject/AppDelegate.swift
|
2
|
6338
|
/**
* 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 Parse
// If you want to use any of the UI components, uncomment this line
// import ParseUI
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//--------------------------------------
// MARK: - UIApplicationDelegate
//--------------------------------------
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// ****************************************************************************
// Initialize Parse SDK
// ****************************************************************************
let configuration = ParseClientConfiguration {
// Add your Parse applicationId:
$0.applicationId = "your_application_id"
// Uncomment and add your clientKey (it's not required if you are using Parse Server):
$0.clientKey = "your_client_key"
// Uncomment the following line and change to your Parse Server address;
$0.server = "https://YOUR_PARSE_SERVER/parse"
// 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.
$0.localDatastoreEnabled = true
}
Parse.initializeWithConfiguration(configuration)
// ****************************************************************************
// 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.publicReadAccess = 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 oldPushHandlerOnly = !respondsToSelector(#selector(UIApplicationDelegate.application(_:didReceiveRemoteNotification:fetchCompletionHandler:)))
var noPushPayload = false
if let options = launchOptions {
noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] == nil
}
if oldPushHandlerOnly || noPushPayload {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
let types: UIUserNotificationType = [.Alert, .Badge, .Sound]
let settings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
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 {
print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.\n")
} else {
print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.\n", error)
}
}
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.\n")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %@\n", 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())
// }
}
|
bsd-3-clause
|
74a904f1d3a8431c4d3c980150dc9693
| 45.262774 | 193 | 0.600189 | 6.171373 | false | false | false | false |
Cellane/iWeb
|
Sources/App/Controllers/Web/UserController+Web.swift
|
1
|
3177
|
import Vapor
import AuthProvider
import Flash
extension Controllers.Web {
final class UserController {
let droplet: Droplet
private let context = UserContext()
init(droplet: Droplet) {
self.droplet = droplet
}
func addRoutes() {
let user = droplet.grouped("user")
user.get("login", handler: showLogin)
user.post("login", handler: logIn)
user.get("logout", handler: logOut)
user.get("register", handler: showRegister)
user.post("register", handler: register)
user.get(User.parameter, handler: showProfile)
}
func showLogin(req: Request) throws -> ResponseRepresentable {
return try droplet.view.makeDefault("user/login", for: req)
}
func logIn(req: Request) throws -> ResponseRepresentable {
guard let username = req.data["username"]?.string,
let password = req.data["password"]?.string else {
return Response(redirect: "/user/login")
.flash(.error, "Don't think we'll get anywhere without username and password.")
}
do {
let credentials = Password(username: username, password: password)
let user = try User.authenticate(credentials)
req.auth.authenticate(user)
return Response(redirect: "/")
} catch {
return Response(redirect: "/user/login")
.flash(.error, "Stop hacking me, Russia!")
}
}
func logOut(req: Request) throws -> ResponseRepresentable {
do {
try req.auth.unauthenticate()
return Response(redirect: "/")
.flash(.success, "Successfully logged out.")
} catch {
return Response(redirect: "/")
.flash(.error, "Unable to log you out.")
}
}
func showRegister(req: Request) throws -> ResponseRepresentable {
return try droplet.view.makeDefault("user/register", for: req)
}
func register(req: Request) throws -> ResponseRepresentable {
do {
guard req.formURLEncoded?["password"]?.string == req.formURLEncoded?["confirmation"]?.string else {
return Response(redirect: "/user/register")
.flash(.error, "Password and password confirmation doesn't match.")
}
guard let node = req.formURLEncoded else {
throw Abort(.internalServerError)
}
let user = try User(node: node)
guard try User.makeQuery().filter(User.Properties.username, user.username).first() == nil else {
return Response(redirect: "/user/register")
.flash(.error, "An user with that username already exists.")
}
if try User.count() == 0 {
let adminRole = try Role.makeQuery().filter(Role.Properties.name, Role.admin).first()
user.roleId = try adminRole?.assertExists()
try? req.flash.add(.info, "As a first user of the system, you were promoted to the role of administrator.")
}
try user.save()
return Response(redirect: "/user/login")
.flash(.success, "Registration complete, you can log in.")
} catch {
return Response(redirect: "/user/register")
.flash(.error, "Unexpected error occurred.")
}
}
func showProfile(req: Request) throws -> ResponseRepresentable {
let user = try req.parameters.next(User.self)
return try droplet.view.makeDefault("user/profile", for: req, [
"user": user.makeNode(in: context)
])
}
}
}
|
mit
|
5158280bf815e1e690f20e5a90a6f55e
| 28.146789 | 112 | 0.673906 | 3.720141 | false | false | false | false |
3DprintFIT/octoprint-ios-client
|
OctoPhone/View Related/BaseCollectionViewController.swift
|
1
|
915
|
//
// BaseCollectionViewController.swift
// OctoPhone
//
// Created by Josef Dolezal on 10/03/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import UIKit
/// Common logic and configuration for all collection view controllers
class BaseCollectionViewController: UICollectionViewController, ErrorPresentable {
/// View displayed when detail is not available
let emptyView: DetailUnavailableView = {
let view = DetailUnavailableView()
view.isHidden = true
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = Colors.Views.defaultControllerBackground
collectionView?.bounces = true
collectionView?.alwaysBounceVertical = true
view.addSubview(emptyView)
emptyView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
}
|
mit
|
97f7c7337513bde50dc3c22be65d24d3
| 25.114286 | 82 | 0.69256 | 5.345029 | false | false | false | false |
JaSpa/swift
|
test/IRGen/struct_resilience.swift
|
3
|
10344
|
// RUN: rm -rf %t && mkdir %t
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -O %s
import resilient_struct
import resilient_enum
// CHECK: %Si = type <{ [[INT:i32|i64]] }>
// CHECK-LABEL: @_TMfV17struct_resilience26StructWithResilientStorage = internal global
// Resilient structs from outside our resilience domain are manipulated via
// value witnesses
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience26functionWithResilientTypesFTV16resilient_struct4Size1fFS1_S1__S1_(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i8*, %swift.refcounted*)
public func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct4Size()
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 17
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FOR_SIZE:%.*]] = ptrtoint i8* [[WITNESS]]
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[STRUCT_ADDR:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque*
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 6
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[initializeWithCopy:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[STRUCT_LOC:%.*]] = call %swift.opaque* [[initializeWithCopy]](%swift.opaque* [[STRUCT_ADDR]], %swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%swift.opaque*, %swift.opaque*, %swift.refcounted*)*
// CHECK: call void [[FN]](%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture [[STRUCT_ADDR]], %swift.refcounted* %3)
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[destroy:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.type*)*
// CHECK: call void [[destroy]](%swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK: ret void
return f(s)
}
// CHECK-LABEL: declare %swift.type* @_TMaV16resilient_struct4Size()
// Rectangle has fixed layout inside its resilience domain, and dynamic
// layout on the outside.
//
// Make sure we use a type metadata accessor function, and load indirect
// field offsets from it.
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience26functionWithResilientTypesFV16resilient_struct9RectangleT_(%V16resilient_struct9Rectangle* noalias nocapture)
public func functionWithResilientTypes(_ r: Rectangle) {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct9Rectangle()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], i32 3
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %V16resilient_struct9Rectangle* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Si*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
_ = r.color
// CHECK: ret void
}
// Resilient structs from inside our resilience domain are manipulated
// directly.
public struct MySize {
public let w: Int
public let h: Int
}
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience28functionWithMyResilientTypesFTVS_6MySize1fFS0_S0__S0_(%V17struct_resilience6MySize* {{.*}}, %V17struct_resilience6MySize* {{.*}}, i8*, %swift.refcounted*)
public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize {
// CHECK: [[TEMP:%.*]] = alloca %V17struct_resilience6MySize
// CHECK: bitcast
// CHECK: llvm.lifetime.start
// CHECK: [[COPY:%.*]] = bitcast %V17struct_resilience6MySize* %4 to i8*
// CHECK: [[ARG:%.*]] = bitcast %V17struct_resilience6MySize* %1 to i8*
// CHECK: call void @llvm.memcpy{{.*}}(i8* [[COPY]], i8* [[ARG]], {{i32 8|i64 16}}, i32 {{.*}}, i1 false)
// CHECK: [[FN:%.*]] = bitcast i8* %2
// CHECK: call void [[FN]](%V17struct_resilience6MySize* {{.*}} %0, {{.*}} [[TEMP]], %swift.refcounted* %3)
// CHECK: ret void
return f(s)
}
// Structs with resilient storage from a different resilience domain require
// runtime metadata instantiation, just like generics.
public struct StructWithResilientStorage {
public let s: Size
public let ss: (Size, Size)
public let n: Int
public let i: ResilientInt
}
// Make sure we call a function to access metadata of structs with
// resilient layout, and go through the field offset vector in the
// metadata when accessing stored properties.
// CHECK-LABEL: define{{( protected)?}} {{i32|i64}} @_TFV17struct_resilience26StructWithResilientStorageg1nSi(%V17struct_resilience26StructWithResilientStorage* {{.*}})
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV17struct_resilience26StructWithResilientStorage()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], i32 3
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %V17struct_resilience26StructWithResilientStorage* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Si*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Indirect enums with resilient payloads are still fixed-size.
public struct StructWithIndirectResilientEnum {
public let s: FunnyShape
public let n: Int
}
// CHECK-LABEL: define{{( protected)?}} {{i32|i64}} @_TFV17struct_resilience31StructWithIndirectResilientEnumg1nSi(%V17struct_resilience31StructWithIndirectResilientEnum* {{.*}})
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %V17struct_resilience31StructWithIndirectResilientEnum, %V17struct_resilience31StructWithIndirectResilientEnum* %0, i32 0, i32 1
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Partial application of methods on resilient value types
public struct ResilientStructWithMethod {
public func method() {}
}
// Corner case -- type is address-only in SIL, but empty in IRGen
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience29partialApplyOfResilientMethodFT1rVS_25ResilientStructWithMethod_T_(%V17struct_resilience25ResilientStructWithMethod* noalias nocapture)
public func partialApplyOfResilientMethod(r: ResilientStructWithMethod) {
_ = r.method
}
// Type is address-only in SIL, and resilient in IRGen
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience29partialApplyOfResilientMethodFT1sV16resilient_struct4Size_T_(%swift.opaque* noalias nocapture)
public func partialApplyOfResilientMethod(s: Size) {
_ = s.method
}
// Public metadata accessor for our resilient struct
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_TMaV17struct_resilience6MySize()
// CHECK: ret %swift.type* bitcast ([[INT]]* getelementptr inbounds {{.*}} @_TMfV17struct_resilience6MySize, i32 0, i32 1) to %swift.type*)
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_StructWithResilientStorage(i8*)
// CHECK: [[FIELDS:%.*]] = alloca [4 x i8**]
// CHECK: [[VWT:%.*]] = load i8**, i8*** getelementptr inbounds ({{.*}} @_TMfV17struct_resilience26StructWithResilientStorage{{.*}}, [[INT]] -1)
// CHECK: [[FIELDS_ADDR:%.*]] = getelementptr inbounds [4 x i8**], [4 x i8**]* [[FIELDS]], i32 0, i32 0
// public let s: Size
// CHECK: [[FIELD_1:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 0
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_1]]
// public let ss: (Size, Size)
// CHECK: [[FIELD_2:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 1
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_2]]
// Fixed-layout aggregate -- we can reference a static value witness table
// public let n: Int
// CHECK: [[FIELD_3:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 2
// CHECK: store i8** getelementptr inbounds (i8*, i8** @_TWVBi{{32|64}}_, i32 {{.*}}), i8*** [[FIELD_3]]
// Resilient aggregate with one field -- make sure we don't look inside it
// public let i: ResilientInt
// CHECK: [[FIELD_4:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 3
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_4]]
// CHECK: call void @swift_initStructMetadata_UniversalStrategy([[INT]] 4, i8*** [[FIELDS_ADDR]], [[INT]]* {{.*}}, i8** [[VWT]])
// CHECK: store atomic %swift.type* {{.*}} @_TMfV17struct_resilience26StructWithResilientStorage{{.*}}, %swift.type** @_TMLV17struct_resilience26StructWithResilientStorage release,
// CHECK: ret void
|
apache-2.0
|
5becb3d83f6706a9eb48575d91376053
| 50.72 | 233 | 0.673627 | 3.600418 | false | false | false | false |
xivol/Swift-CS333
|
playgrounds/swift/SwiftClasses.playground/Pages/Extensions.xcplaygroundpage/Contents.swift
|
3
|
2203
|
//: ## Extensions
//: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
//: ****
//: ### Computed Properties
extension Double {
// metric
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
// imperial
var i: Double { return self.cm * 2.54 }
var ft: Double { return self / 3.28084 }
var mil: Double { return self * 1609.34 }
}
let height = 5.0.ft + 6.0.i
let length = 1.0.km
//: ### Methods
extension Int {
func times(action: (Int) -> Void) {
for i in 0..<self {
action(i)
}
}
}
3.times { print("\($0): Hello, Extension!") }
extension String {
mutating func transform(with closure: (String) -> String) {
self = closure(self)
}
}
var str = "Hello, Exception"
str.transform { $0 + "!!!" }
str
//: ### Extension for Protocol Confarmance
struct Point {
var x = 0.0, y = 0.0
}
extension Point: CustomStringConvertible { // standart protocol for string representation
var description: String {
return "(\(x), \(y))"
}
}
Point(x: 1, y: 1)
//: ### Protocol Extension
extension CustomStringConvertible {
func printMe() {
print("I am \(self)")
}
}
Point(x: 12, y: 24).printMe()
3.14.printMe()
(0...10).printMe()
//: ### Protocol Extension with Default Implementation
protocol Repeatable {
func repeated(times: Int) -> [Self]
}
extension Repeatable {
func repeated(times: Int) -> [Self] {
return [Self](repeating: self, count: times)
}
}
extension String: Repeatable {}
extension Double: Repeatable {}
"😀".repeated(times: 3)
3.14.repeated(times: 5)
//: ### Protocol Extension with Constraints
import Foundation
extension Collection where Iterator.Element: Repeatable {
func expand(times: Int) -> [[Iterator.Element]] {
var result = Array<[Iterator.Element]>()
for el in self {
result.append(el.repeated(times: times))
}
return result
}
}
let matrix = [0.0, 0.1, 0.2, 0.3].expand(times: 4)
//: ****
//: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
|
mit
|
ddb44a42f433faff724a32c56a7031e0
| 25.780488 | 89 | 0.602914 | 3.530547 | false | false | false | false |
eastsss/NavigationBarStyles
|
NavigationBarStyles/Sources/Core/BarButtonItemConfigurations.swift
|
1
|
2567
|
//
// BarButtonItemConfigurations.swift
// NavigationBarStyles
//
// Created by Anatoliy Radchenko on 17/07/2017.
// Copyright © 2017 NavigationBarStyles. All rights reserved.
//
import UIKit
public enum ButtonSideSizingPolicy {
case contentBased
case fixed(CGFloat)
}
public struct SpinnerParams {
public let color: UIColor
public let isLarge: Bool
public init(color: UIColor = UIColor.gray, isLarge: Bool = false) {
self.color = color
self.isLarge = isLarge
}
}
public struct ImageButtonParams {
public let normalImage: UIImage
public let highlightedImage: UIImage?
public let widthPolicy: ButtonSideSizingPolicy
public let spinnerParams: SpinnerParams?
public let target: AnyObject?
public let action: Selector
public init(normalImage: UIImage,
highlightedImage: UIImage? = nil,
widthPolicy: ButtonSideSizingPolicy = .contentBased,
spinnerParams: SpinnerParams? = nil,
target: AnyObject?,
action: Selector) {
self.normalImage = normalImage
self.highlightedImage = highlightedImage
self.widthPolicy = widthPolicy
self.spinnerParams = spinnerParams
self.target = target
self.action = action
}
}
public struct TextButtonParams {
public let title: String
public let titleColor: UIColor
public let titleFont: UIFont
public let backgroundColor: UIColor
public let contentEdgeInsets: UIEdgeInsets
public let cornerRadius: CGFloat
public let heightPolicy: ButtonSideSizingPolicy
public let spinnerParams: SpinnerParams?
public let target: AnyObject?
public let action: Selector
public init(title: String,
titleColor: UIColor,
titleFont: UIFont,
backgroundColor: UIColor,
contentEdgeInsets: UIEdgeInsets = .zero,
cornerRadius: CGFloat = 0,
heightPolicy: ButtonSideSizingPolicy = .contentBased,
spinnerParams: SpinnerParams? = nil,
target: AnyObject?,
action: Selector) {
self.title = title
self.titleColor = titleColor
self.titleFont = titleFont
self.backgroundColor = backgroundColor
self.contentEdgeInsets = contentEdgeInsets
self.cornerRadius = cornerRadius
self.heightPolicy = heightPolicy
self.spinnerParams = spinnerParams
self.target = target
self.action = action
}
}
|
mit
|
4143715b47acfad9d3678b77abbe2cb2
| 29.915663 | 71 | 0.654326 | 5.258197 | false | false | false | false |
nerdishbynature/RequestKit
|
Sources/RequestKit/RequestKitSession.swift
|
1
|
3076
|
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
public protocol RequestKitURLSession {
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTaskProtocol
func uploadTask(with request: URLRequest, fromData bodyData: Data?, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol
#if compiler(>=5.5.2) && canImport(_Concurrency)
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
func data(for request: URLRequest, delegate: URLSessionTaskDelegate?) async throws -> (Data, URLResponse)
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
func upload(for request: URLRequest, from bodyData: Data, delegate: URLSessionTaskDelegate?) async throws -> (Data, URLResponse)
#endif
}
public protocol URLSessionDataTaskProtocol {
func resume()
}
extension URLSessionDataTask: URLSessionDataTaskProtocol {}
extension URLSession: RequestKitURLSession {
public func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTaskProtocol {
return (dataTask(with: request, completionHandler: completionHandler) as URLSessionDataTask)
}
public func uploadTask(with request: URLRequest, fromData bodyData: Data?, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol {
return uploadTask(with: request, from: bodyData, completionHandler: completionHandler)
}
#if compiler(>=5.5.2) && canImport(_Concurrency) && canImport(FoundationNetworking)
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
public func data(for request: URLRequest, delegate _: URLSessionTaskDelegate?) async throws -> (Data, URLResponse) {
return try await withCheckedThrowingContinuation { continuation in
let task = dataTask(with: request) { data, response, error in
if let error = error {
continuation.resume(throwing: error)
}
if let data = data, let response = response {
continuation.resume(returning: (data, response))
}
} as URLSessionDataTask
task.resume()
}
}
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
public func upload(for request: URLRequest, from bodyData: Data, delegate _: URLSessionTaskDelegate?) async throws -> (Data, URLResponse) {
return try await withCheckedThrowingContinuation { continuation in
let task = uploadTask(with: request, from: bodyData) { data, response, error in
if let error = error {
continuation.resume(throwing: error)
}
if let data = data, let response = response {
continuation.resume(returning: (data, response))
}
}
task.resume()
}
}
#endif
}
|
mit
|
10b7659a9e13a4493c4d0e72a9994d69
| 46.323077 | 178 | 0.664824 | 5.017945 | false | false | false | false |
fellipecaetano/Democracy-iOS
|
Sources/Politicians/Redux/PoliticiansState.swift
|
1
|
398
|
struct PoliticiansState: Equatable {
let data: [Politician]
let isLoading: Bool
let error: Error?
static let initial = PoliticiansState(data: [], isLoading: false, error: nil)
static func == (lhs: PoliticiansState, rhs: PoliticiansState) -> Bool {
return lhs.data == rhs.data
&& lhs.isLoading == rhs.isLoading
&& lhs.error ~= rhs.error
}
}
|
mit
|
0dbeb776347ad1e215efc3288b122867
| 29.615385 | 81 | 0.620603 | 3.685185 | false | false | false | false |
alexandresoliveira/IosSwiftExamples
|
Sacolao/Sacolao/Controllers/ViewController.swift
|
1
|
2340
|
//
// ViewController.swift
// Sacolao
//
// Created by padrao on 6/9/16.
// Copyright © 2016 Alexandre Oliveira. All rights reserved.
//
import UIKit
class ViewController: ProdutoViewController {
@IBOutlet weak var produto: UITextField!
@IBOutlet weak var quantidade: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func addProduto(sender: UIButton) {
if !isValidDecimalNumber(quantidade.text!) {
let errorAlert = UIAlertController(title: "Error!",
message: "Número inválido",
preferredStyle: .Alert)
let okAlertAction = UIAlertAction(title: "Ok",
style: .Default,
handler: nil)
errorAlert.addAction(okAlertAction)
self.presentViewController(errorAlert,
animated: true,
completion: nil)
return
}
let model = Produto(codigo: nil,
nome: produto.text!,
quantidade: NSString(string: quantidade.text!).doubleValue)
do {
try ProdutoDAO().insert(model)
voltar()
} catch {
let errorAlert = UIAlertController(title: "Error!",
message: "Erro ao salvar o produto \(error)",
preferredStyle: .Alert)
let okAlertAction = UIAlertAction(title: "Ok",
style: .Cancel,
handler: { (alert: UIAlertAction!) in self.voltar() })
errorAlert.addAction(okAlertAction)
self.presentViewController(errorAlert,
animated: true,
completion: nil)
}
}
private func voltar() {
if let navigation = navigationController {
navigation.popViewControllerAnimated(true)
}
}
}
|
gpl-3.0
|
a8ad746dafe21075af7e6cf0d8b80807
| 32.869565 | 100 | 0.473684 | 5.82793 | false | false | false | false |
kenwilcox/TaskIt-Swift
|
TaskIt/ModelManager.swift
|
1
|
9788
|
//
// ModelManager.swift
// TaskIt
//
// Created by John Nichols on 11/14/14.
// Copyright (c) 2014 BitFountain. All rights reserved.
//
import Foundation
import CoreData
let kCoreDataUpdated: String = "coreDataUpdated"
class ModelManager: NSObject {
// MARK: - Singleton init
struct Static {
static var token : dispatch_once_t = 0
static var instance : ModelManager?
}
class var instance: ModelManager {
dispatch_once(&Static.token) { Static.instance = ModelManager() }
return Static.instance!
}
override init () {
assert(Static.instance == nil, "Singleton already initialized!")
}
// MARK: - CoreData methods
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "self.com.AG.TaskIt" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("TaskItModel", withExtension: "momd")
return NSManagedObjectModel(contentsOfURL: modelURL!)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
println("persistentStoreCoordinator")
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
// iCloud notification subscriptions
var notificacionCenter: NSNotificationCenter = NSNotificationCenter.defaultCenter()
notificacionCenter.addObserver(self, selector: Selector("storesWillChange:"), name:NSPersistentStoreCoordinatorStoresWillChangeNotification, object: coordinator)
notificacionCenter.addObserver(self, selector: Selector("storesDidChange:"), name:NSPersistentStoreCoordinatorStoresDidChangeNotification, object: coordinator)
notificacionCenter.addObserver(self, selector: Selector("persistentStoreDidImportUbiquitousContentChanges:"), name:NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: coordinator)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TaskItModel.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
var options: NSDictionary = [NSMigratePersistentStoresAutomaticallyOption : NSNumber(bool: true), NSInferMappingModelAutomaticallyOption : NSNumber(bool: true), NSPersistentStoreUbiquitousContentNameKey : "TaskItCloud"]
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options as [NSObject : AnyObject], error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Methods
func startModel() {
let moc = self.managedObjectContext
}
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
// MARK: - Core Data discard changes
func discardChanges() {
self.managedObjectContext?.rollback()
}
// MARK: - iCloud Notifications
func persistentStoreDidImportUbiquitousContentChanges(notification: NSNotification) {
println("iCloud")
println(notification.userInfo?.description)
var moc: NSManagedObjectContext = self.managedObjectContext!
moc.performBlock { () -> Void in
moc.mergeChangesFromContextDidSaveNotification(notification)
var changes: NSDictionary = notification.userInfo!
var allChanges: NSMutableSet = NSMutableSet()
allChanges.unionSet(changes.valueForKey(NSInsertedObjectsKey) as! NSSet as Set<NSObject>)
allChanges.unionSet(changes.valueForKey(NSUpdatedObjectsKey) as! NSSet as Set<NSObject>)
allChanges.unionSet(changes.valueForKey(NSDeletedObjectsKey) as! NSSet as Set<NSObject>)
}
NSNotificationCenter.defaultCenter().postNotificationName(kCoreDataUpdated, object: self)
}
func storesWillChange(notification: NSNotification) {
var moc: NSManagedObjectContext = self.managedObjectContext!
moc.performBlockAndWait { () -> Void in
var error: NSError?
if moc.hasChanges {
moc.save(&error)
}
moc.reset()
}
}
func storesDidChange(notification: NSNotification) {
// here is when you can refresh your UI and
// load new data from the new store
NSNotificationCenter.defaultCenter().postNotificationName(kCoreDataUpdated, object: self)
}
// MARK: - Object creation
func insertNewEntityName (entityName: String) -> AnyObject {
return NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: self.managedObjectContext!);
}
// MARK: - Object deletion
func deleteObject(object:NSManagedObject) {
self.managedObjectContext?.deleteObject(object)
}
// MARK: - Object search
func fetchEntity(entityName: String, identifier: String?, managedObjectContext: NSManagedObjectContext) -> AnyObject? {
var predicate: NSPredicate?
if identifier != nil {
predicate = NSPredicate(format: "identifier == %@", identifier!)
}
let results: [AnyObject]? = self.fetchEntities(entityName, predicate: predicate, sortDescriptors: [], fetchLimit: 1, context: self.managedObjectContext!)
var result: AnyObject? = nil
if results?.count > 0 {
result = results?[0]
}
return result
}
func fetchEntity(entityName: String, identifier: NSNumber) -> AnyObject? {
return self.fetchEntity(entityName, identifier: identifier);
}
func fetchEntities(entityName: String) -> [AnyObject]? {
return self.fetchEntities(entityName, predicate: nil, sortDescriptors: nil, fetchLimit: 0)
}
func fetchEntities(entityName: String, predicate: NSPredicate?) -> [AnyObject]? {
return self.fetchEntities(entityName, predicate: predicate, sortDescriptors: nil, fetchLimit: 0)
}
func fetchEntities(entityName: String, predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?, fetchLimit: Int) -> [AnyObject]? {
return self.fetchEntities(entityName, predicate: predicate, sortDescriptors: sortDescriptors, fetchLimit: fetchLimit, context: self.managedObjectContext!)
}
func fetchEntities(entityName: String, predicate: NSPredicate?, sortKey: String?, fetchLimit: Int) -> [AnyObject]? {
var sortDescriptors: [NSSortDescriptor]? = nil
if sortKey != nil {
sortDescriptors = [NSSortDescriptor(key: sortKey!, ascending: true)]
}
return self.fetchEntities(entityName, predicate: predicate, sortDescriptors: sortDescriptors, fetchLimit: fetchLimit)
}
func fetchEntities(entityName: String, predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?, fetchLimit: Int, context: NSManagedObjectContext!) -> [AnyObject]! {
var fetchRequest: NSFetchRequest! = NSFetchRequest(entityName: entityName)
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = sortDescriptors
if fetchLimit != 0 {
fetchRequest.fetchLimit = fetchLimit
}
var error: NSError? = nil
var results = context.executeFetchRequest(fetchRequest, error: &error)
if error != nil {
println("Error fetching entity \(entityName): \(error), \(error?.userInfo)")
}
return results
}
}
|
mit
|
376fdd94cc0e97e46f5c5082e83fddf7
| 43.490909 | 286 | 0.736923 | 5.293672 | false | false | false | false |
kylry/KTSpectrum
|
Sample-Project/KTSpectrum Sample Project/ViewController.swift
|
1
|
2810
|
/*
Copyright (c) 2016 Kyle Ryan
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 UIKit
import KTSpectrum
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var paletteView1: UIView!
@IBOutlet weak var paletteView2: UIView!
@IBOutlet weak var paletteView3: UIView!
@IBOutlet weak var paletteView4: UIView!
@IBOutlet weak var paletteView5: UIView!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = UIImage(named: "sample-image")
}
@IBAction func evaluateImage() {
let colors = imageView.image!.dominantColors()
paletteView1.backgroundColor = colors[0]
paletteView2.backgroundColor = colors[1]
paletteView3.backgroundColor = colors[2]
paletteView4.backgroundColor = colors[3]
paletteView5.backgroundColor = colors[4]
}
// MARK: UITapGestureRecognizer
@IBAction func changeImage(sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
pickerController.allowsEditing = false
self.presentViewController(pickerController, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
let selectedImage : UIImage = image
imageView.image = selectedImage.resizeImage(500)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
c7793c79c4a00a7ca31c0965f621653d
| 49.178571 | 460 | 0.748754 | 5.342205 | false | false | false | false |
uny/SwiftyTimer
|
Tests/SwiftyTimerTests/main.swift
|
1
|
2071
|
import Cocoa
let app = NSApplication.sharedApplication()
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
test()
}
func test() {
assert(1.second == 1.0)
assert(1.minute == 60.0)
assert(1.hour == 1.minute * 60)
assert(1.2.seconds == 1.2)
assert(1.5.minutes == 90.0)
assert(1.5.hours == 5400.0)
test2()
}
func test2() {
var fired = false
NSTimer.after(0.1.seconds) {
assert(!fired)
fired = true
self.test3()
}
}
var timer1: NSTimer!
func test3() {
var fired = false
timer1 = NSTimer.every(0.1.seconds) {
if fired {
self.test4()
self.timer1.invalidate()
} else {
fired = true
}
}
}
let timer2 = NSTimer.new(after: 0.1.seconds) { fatalError() }
let timer3 = NSTimer.new(every: 0.1.seconds) { fatalError() }
func test4() {
let timer = NSTimer.new(after: 0.1.seconds) {
self.test5()
}
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
}
var timer4: NSTimer!
func test5() {
var fired = false
timer4 = NSTimer.new(every: 0.1.seconds) {
if fired {
self.timer4.invalidate()
self.test6()
} else {
fired = true
}
}
timer4.start()
}
func test6() {
let timer = NSTimer.new(after: 0.1.seconds) {
self.test7()
}
timer.start(runLoop: NSRunLoop.currentRunLoop(), modes: NSDefaultRunLoopMode, NSEventTrackingRunLoopMode)
}
func test7() {
NSTimer.after(0.1.seconds, done)
}
func done() {
print("All tests passed")
app.terminate(self)
}
}
let delegate = AppDelegate()
app.delegate = delegate
app.run()
|
mit
|
48b3cd9492cb6b999e974ac7e4f04f22
| 22.545455 | 113 | 0.507484 | 4.117296 | false | true | false | false |
eridbardhaj/Weather
|
Weather/Classes/ViewModels/TodayViewModel.swift
|
1
|
1890
|
//
// WeatherViewModel.swift
// Weather
//
// Created by Erid Bardhaj on 30/04/15.
// Copyright (c) 2015 STRV. All rights reserved.
//
import UIKit
class TodayViewModel: NSObject
{
var m_weatherImageName: String = ""
var m_currentLocation: String = ""
var m_currentWeatherInfo: String = ""
var m_humidity: String = ""
var m_directionAngle: String = ""
var m_windSpeed: String = ""
var m_pressure: String = ""
var m_precipitation: String = ""
//Optional for iWatch
var m_temp: String = ""
var m_weatherCondition: String = ""
init(model: Weather)
{
//Get local data preferences
let current_lengthType = DataManager.shared.m_length_unit
let current_tempType = DataManager.shared.m_tempUnit
//Set the values to the format that views need
m_weatherImageName = ValueTransformUtil.getWeatherCondition(model.m_weather_code).todayWeatherIconName
m_currentLocation = "\(model.m_city)"
m_currentLocation += (count(model.m_state)>0) ? ", \(model.m_state)" : ""
m_humidity = "\(model.m_humidity)%"
m_directionAngle = ValueTransformUtil.getWindDirection(model.m_windDirectionAngle)
//FIXME: Need to be converted correctly
m_precipitation = "0.2 mm"
m_pressure = String(format: "%.0f", model.m_pressure) + " hPa"
m_windSpeed = String(format: "%.1f", current_lengthType.getSpeed(model.m_windSpeed)) + " \(current_lengthType.description)"
m_currentWeatherInfo = String(format: "%.0f", current_tempType.getDegree(model.m_temperature)) + "\(current_tempType.description) | \(model.m_weather_description)"
m_temp = String(format: "%.0f", current_tempType.getDegree(model.m_temperature)) + "°"
m_weatherCondition = model.m_weather_description
}
}
|
mit
|
be5355ee4081e2f75cb5486f376f7c3e
| 35.326923 | 171 | 0.633669 | 3.862986 | false | false | false | false |
ello/ello-ios
|
Specs/Controllers/Stream/StreamKindSpec.swift
|
1
|
13710
|
////
/// StreamKindSpec.swift
//
@testable import Ello
import Quick
import Nimble
import Moya
class StreamKindSpec: QuickSpec {
override func spec() {
describe("StreamKind") {
// TODO: convert these tests to the looping input/output style used on other enums
describe("name") {
it("is correct for all cases") {
expect(StreamKind.following.name) == "Following"
expect(StreamKind.notifications(category: "").name) == "Notifications"
expect(StreamKind.postDetail(postParam: "param").name) == ""
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
).name
) == "meat"
expect(StreamKind.unknown.name) == ""
expect(StreamKind.userStream(userParam: "n/a").name) == ""
}
}
describe("cacheKey") {
it("is correct for all cases") {
expect(StreamKind.category(.all, .featured).cacheKey) == "Category"
expect(StreamKind.following.cacheKey) == "Following"
expect(StreamKind.notifications(category: "").cacheKey) == "Notifications"
expect(StreamKind.postDetail(postParam: "param").cacheKey) == "PostDetail"
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
).cacheKey
) == "SearchForPosts"
expect(StreamKind.unknown.cacheKey) == "unknown"
expect(StreamKind.userStream(userParam: "NA").cacheKey) == "UserStream"
}
}
describe("lastViewedCreatedAtKey") {
it("is correct for all cases") {
expect(StreamKind.following.lastViewedCreatedAtKey) == "Following_createdAt"
expect(StreamKind.notifications(category: "").lastViewedCreatedAtKey)
== "Notifications_createdAt"
expect(StreamKind.postDetail(postParam: "param").lastViewedCreatedAtKey).to(
beNil()
)
expect(StreamKind.unknown.lastViewedCreatedAtKey).to(beNil())
}
}
describe("showsCategory") {
let expectations: [(StreamKind, Bool)] = [
(.manageCategories, false),
(.category(.category("art"), .featured), false),
(.following, false),
(.notifications(category: nil), false),
(.notifications(category: "comments"), false),
(.postDetail(postParam: "postId"), false),
(.userStream(userParam: "userId"), false),
(.unknown, false),
]
for (streamKind, expectedValue) in expectations {
it("\(streamKind) \(expectedValue ? "can" : "cannot") show category") {
expect(streamKind.showsCategory) == expectedValue
}
}
}
describe("isProfileStream") {
let expectations: [(StreamKind, Bool)] = [
(.category(.category("art"), .featured), false),
(.following, false),
(.notifications(category: ""), false),
(.postDetail(postParam: "param"), false),
(
.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
), false
),
(.unknown, false),
(.userStream(userParam: "NA"), true),
]
for (streamKind, expected) in expectations {
it("is \(expected) for \(streamKind)") {
expect(streamKind.isProfileStream) == expected
}
}
}
describe("endpoint") {
it("is correct for all cases") {
expect(StreamKind.following.endpoint!.path)
== "/api/\(ElloAPI.apiVersion)/following/posts/recent"
expect(StreamKind.notifications(category: "").endpoint!.path)
== "/api/\(ElloAPI.apiVersion)/notifications"
expect(StreamKind.postDetail(postParam: "param").endpoint!.path)
== "/api/\(ElloAPI.apiVersion)/posts/param"
expect(
StreamKind.postDetail(postParam: "param").endpoint!.parameters![
"comment_count"] as? Int
) == 0
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
).endpoint!.path
) == "/api/\(ElloAPI.apiVersion)/posts"
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForUsers(terms: "meat"),
title: "meat"
).endpoint!.path
) == "/api/\(ElloAPI.apiVersion)/users"
expect(StreamKind.userStream(userParam: "NA").endpoint!.path)
== "/api/\(ElloAPI.apiVersion)/users/NA"
expect(StreamKind.unknown.endpoint).to(beNil())
expect(StreamKind.userLoves(username: "").endpoint).to(beNil())
expect(StreamKind.userFollowing(username: "").endpoint).to(beNil())
expect(StreamKind.userFollowers(username: "").endpoint).to(beNil())
}
}
describe("isGridView") {
beforeEach {
StreamKind.category(.category("art"), .featured).setIsGridView(false)
StreamKind.following.setIsGridView(false)
StreamKind.notifications(category: "").setIsGridView(false)
StreamKind.postDetail(postParam: "param").setIsGridView(false)
StreamKind.following.setIsGridView(false)
StreamKind.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
).setIsGridView(false)
StreamKind.unknown.setIsGridView(false)
StreamKind.userStream(userParam: "NA").setIsGridView(false)
}
it("is correct for all cases") {
StreamKind.category(.category("art"), .featured).setIsGridView(true)
expect(StreamKind.category(.category("art"), .featured).isGridView) == true
StreamKind.category(.category("art"), .featured).setIsGridView(false)
expect(StreamKind.category(.category("art"), .featured).isGridView) == false
StreamKind.following.setIsGridView(false)
expect(StreamKind.following.isGridView) == false
StreamKind.following.setIsGridView(true)
expect(StreamKind.following.isGridView) == true
expect(StreamKind.notifications(category: "").isGridView) == false
expect(StreamKind.postDetail(postParam: "param").isGridView) == false
StreamKind.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
).setIsGridView(true)
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
).isGridView
) == true
StreamKind.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
).setIsGridView(false)
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
).isGridView
) == false
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForUsers(terms: "meat"),
title: "meat"
).isGridView
) == false
expect(StreamKind.unknown.isGridView) == false
expect(StreamKind.userStream(userParam: "NA").isGridView) == false
}
}
describe("hasGridViewToggle") {
it("is correct for all cases") {
expect(StreamKind.category(.category("art"), .featured).hasGridViewToggle)
== true
expect(StreamKind.manageCategories.hasGridViewToggle) == false
expect(StreamKind.following.hasGridViewToggle) == true
expect(StreamKind.notifications(category: "").hasGridViewToggle) == false
expect(StreamKind.postDetail(postParam: "param").hasGridViewToggle) == false
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
).hasGridViewToggle
) == true
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForUsers(terms: "meat"),
title: "meat"
).hasGridViewToggle
) == false
expect(StreamKind.unknown.hasGridViewToggle) == false
expect(StreamKind.userStream(userParam: "NA").hasGridViewToggle) == false
}
}
describe("isDetail") {
it("is correct for all cases") {
expect(
StreamKind.category(.category("art"), .featured).isDetail(
post: Post.stub([:])
)
) == false
expect(StreamKind.following.isDetail(post: Post.stub([:]))) == false
expect(StreamKind.notifications(category: "").isDetail(post: Post.stub([:])))
== false
expect(
StreamKind.postDetail(postParam: "~param").isDetail(
post: Post.stub(["token": "param"])
)
) == true
expect(
StreamKind.postDetail(postParam: "postId").isDetail(
post: Post.stub(["id": "postId"])
)
) == true
expect(StreamKind.postDetail(postParam: "wrong").isDetail(post: Post.stub([:])))
== false
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
).isDetail(post: Post.stub([:]))
) == false
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForUsers(terms: "meat"),
title: "meat"
).isDetail(post: Post.stub([:]))
) == false
expect(StreamKind.unknown.isDetail(post: Post.stub([:]))) == false
expect(StreamKind.userStream(userParam: "NA").isDetail(post: Post.stub([:])))
== false
}
}
describe("supportsLargeImages") {
it("is correct for all cases") {
expect(StreamKind.category(.category("art"), .featured).supportsLargeImages)
== false
expect(StreamKind.following.supportsLargeImages) == false
expect(StreamKind.notifications(category: "").supportsLargeImages) == false
expect(StreamKind.postDetail(postParam: "param").supportsLargeImages) == true
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForPosts(terms: "meat"),
title: "meat"
).supportsLargeImages
) == false
expect(
StreamKind.simpleStream(
endpoint: ElloAPI.searchForUsers(terms: "meat"),
title: "meat"
).supportsLargeImages
) == false
expect(StreamKind.unknown.supportsLargeImages) == false
expect(StreamKind.userStream(userParam: "NA").supportsLargeImages) == false
}
}
}
}
}
|
mit
|
29b7a8eb9979b7b37ed85663f161962b
| 44.852843 | 100 | 0.458206 | 5.762926 | false | false | false | false |
PodRepo/firefox-ios
|
Client/Frontend/Home/BookmarksPanel.swift
|
9
|
8233
|
/* 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 UIKit
import Storage
import Shared
import XCGLogger
private let log = Logger.browserLogger
let BookmarkStatusChangedNotification = "BookmarkStatusChangedNotification"
class BookmarksPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate? = nil
var source: BookmarksModel?
private lazy var defaultIcon: UIImage = {
return UIImage(named: "defaultFavicon")!
}()
override var profile: Profile! {
didSet {
// Until we have something useful to show for desktop bookmarks,
// only show mobile bookmarks.
// Note that we also need to build a similar kind of virtual hierarchy
// to what we have on Android.
profile.bookmarks.modelForFolder(BookmarkRoots.MobileFolderGUID, success: self.onNewModel, failure: self.onModelFailure)
// profile.bookmarks.modelForRoot(self.onNewModel, failure: self.onModelFailure)
}
}
init() {
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationPrivateDataCleared, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationPrivateDataCleared, object: nil)
}
func notificationReceived(notification: NSNotification) {
switch notification.name {
case NotificationFirefoxAccountChanged, NotificationPrivateDataCleared:
self.reloadData()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
private func onNewModel(model: BookmarksModel) {
self.source = model
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
private func onModelFailure(e: Any) {
print("Error: failed to get data: \(e)")
}
override func reloadData() {
self.source?.reloadData(self.onNewModel, failure: self.onModelFailure)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return source?.current.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
if let source = source {
if let bookmark = source.current[indexPath.row] {
if let url = bookmark.favicon?.url.asURL where url.scheme == "asset" {
cell.imageView?.image = UIImage(named: url.host!)
} else {
cell.imageView?.setIcon(bookmark.favicon, withPlaceholder: self.defaultIcon)
}
switch (bookmark) {
case let item as BookmarkItem:
if item.title.isEmpty {
cell.textLabel?.text = item.url
} else {
cell.textLabel?.text = item.title
}
default:
// Bookmark folders don't have a good fallback if there's no title. :(
cell.textLabel?.text = bookmark.title
}
}
}
return cell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// Don't show a header for the root
if source == nil || source?.current.guid == BookmarkRoots.MobileFolderGUID {
return nil
}
// Note: If there's no root (i.e. source == nil), we'll also show no header.
return source?.current.title
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Don't show a header for the root. If there's no root (i.e. source == nil), we'll also show no header.
if source == nil || source?.current.guid == BookmarkRoots.MobileFolderGUID {
return 0
}
return super.tableView(tableView, heightForHeaderInSection: section)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if let source = source {
let bookmark = source.current[indexPath.row]
switch (bookmark) {
case let item as BookmarkItem:
homePanelDelegate?.homePanel(self, didSelectURL: NSURL(string: item.url)!, visitType: VisitType.Bookmark)
break
case let folder as BookmarkFolder:
// Descend into the folder.
source.selectFolder(folder, success: self.onNewModel, failure: self.onModelFailure)
break
default:
// Weird.
break // Just here until there's another executable statement (compiler requires one).
}
}
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// Intentionally blank. Required to use UITableViewRowActions
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if source == nil {
return .None
}
if source!.current.itemIsEditableAtIndex(indexPath.row) ?? false {
return .Delete
}
return .None
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
if source == nil {
return [AnyObject]()
}
let title = NSLocalizedString("Delete", tableName: "BookmarkPanel", comment: "Action button for deleting bookmarks in the bookmarks panel.")
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: title, handler: { (action, indexPath) in
if let bookmark = self.source?.current[indexPath.row] {
// Why the dispatches? Because we call success and failure on the DB
// queue, and so calling anything else that calls through to the DB will
// deadlock. This problem will go away when the bookmarks API switches to
// Deferred instead of using callbacks.
self.profile.bookmarks.remove(bookmark).uponQueue(dispatch_get_main_queue()) { res in
if let err = res.failureValue {
self.onModelFailure(err)
return
}
dispatch_async(dispatch_get_main_queue()) {
self.source?.reloadData({ model in
dispatch_async(dispatch_get_main_queue()) {
tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
self.source = model
tableView.endUpdates()
NSNotificationCenter.defaultCenter().postNotificationName(BookmarkStatusChangedNotification, object: bookmark, userInfo:["added":false])
}
}, failure: self.onModelFailure)
}
}
}
})
return [delete]
}
}
|
mpl-2.0
|
7ba36cdd477ee4c150962ef7474a3108
| 39.960199 | 168 | 0.611563 | 5.646776 | false | false | false | false |
AaronMT/firefox-ios
|
RustFxA/RustFirefoxAccounts.swift
|
4
|
15458
|
/* 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
import MozillaAppServices
import SwiftKeychainWrapper
let PendingAccountDisconnectedKey = "PendingAccountDisconnect"
// Used to ignore unknown classes when de-archiving
final class Unknown: NSObject, NSCoding {
func encode(with coder: NSCoder) {}
init(coder aDecoder: NSCoder) {
super.init()
}
}
/**
A singleton that wraps the Rust FxA library.
The singleton design is poor for testability through dependency injection and may need to be changed in future.
*/
// TODO: renamed FirefoxAccounts.swift once the old code is removed fully.
open class RustFirefoxAccounts {
public static let prefKeyLastDeviceName = "prefKeyLastDeviceName"
private static let clientID = "1b1a3e44c54fbb58"
public static let redirectURL = "urn:ietf:wg:oauth:2.0:oob:oauth-redirect-webchannel"
public static var shared = RustFirefoxAccounts()
public var accountManager = Deferred<FxAccountManager>()
private static var isInitializingAccountManager = false
public var avatar: Avatar?
public let syncAuthState: SyncAuthState
fileprivate static var prefs: Prefs?
public let pushNotifications = PushNotificationSetup()
// This is used so that if a migration failed, show a UI indicator for the user to manually log in to their account.
public var accountMigrationFailed: Bool {
get {
return UserDefaults.standard.bool(forKey: "fxaccount-migration-failed")
}
set {
UserDefaults.standard.set(newValue, forKey: "fxaccount-migration-failed")
}
}
/** Must be called before this class is fully usable. Until this function is complete,
all methods in this class will behave as if there is no Fx account.
It will be called on app startup, and extensions must call this before using the class.
If it is possible code could access `shared` before initialize() is complete, these callers should also
hook into notifications like `.accountProfileUpdate` to refresh once initialize() is complete.
Or they can wait on the accountManager deferred to fill.
*/
public static func startup(prefs: Prefs) -> Deferred<FxAccountManager> {
assert(Thread.isMainThread)
RustFirefoxAccounts.prefs = prefs
if RustFirefoxAccounts.shared.accountManager.isFilled || isInitializingAccountManager {
return RustFirefoxAccounts.shared.accountManager
}
// Setup the re-entrancy guard so consecutive calls to startup() won't do manager.initialize(). This flag is cleared when initialize is complete, or by calling reconfig().
isInitializingAccountManager = true
let manager = RustFirefoxAccounts.shared.createAccountManager()
manager.initialize { result in
assert(Thread.isMainThread)
isInitializingAccountManager = false
let hasAttemptedMigration = UserDefaults.standard.bool(forKey: "hasAttemptedMigration")
// Note this checks if startup() is called in an app extensions, and if so, do not try account migration
if Bundle.main.bundleURL.pathExtension != "appex", let tokens = migrationTokens(), !hasAttemptedMigration {
UserDefaults.standard.set(true, forKey: "hasAttemptedMigration")
// The client app only needs to trigger this one time. If it fails due to offline state, the rust library
// will automatically re-try until success or permanent failure (notifications accountAuthenticated / accountMigrationFailed respectively).
// See also `init()` use of `.accountAuthenticated` below.
manager.authenticateViaMigration(sessionToken: tokens.session, kSync: tokens.ksync, kXCS: tokens.kxcs) { _ in }
}
RustFirefoxAccounts.shared.accountManager.fill(manager)
// After everthing is setup, register for push notifications
if manager.hasAccount() {
NotificationCenter.default.post(name: .RegisterForPushNotifications, object: nil)
}
}
return RustFirefoxAccounts.shared.accountManager
}
private static let prefKeySyncAuthStateUniqueID = "PrefKeySyncAuthStateUniqueID"
private static func syncAuthStateUniqueId(prefs: Prefs?) -> String {
let id: String
let key = RustFirefoxAccounts.prefKeySyncAuthStateUniqueID
if let _id = prefs?.stringForKey(key) {
id = _id
} else {
id = UUID().uuidString
prefs?.setString(id, forKey: key)
}
return id
}
@discardableResult
public static func reconfig(prefs: Prefs) -> Deferred<FxAccountManager> {
if isInitializingAccountManager {
// This func is for reconfiguring a completed FxA init, if FxA init is in-progress, let it complete the init as-is
return shared.accountManager
}
isInitializingAccountManager = false
shared.accountManager = Deferred<FxAccountManager>()
return startup(prefs: prefs)
}
public var isChinaSyncServiceEnabled: Bool {
return RustFirefoxAccounts.prefs?.boolForKey(PrefsKeys.KeyEnableChinaSyncService) ?? AppInfo.isChinaEdition
}
private func createAccountManager() -> FxAccountManager {
let prefs = RustFirefoxAccounts.prefs
assert(prefs != nil)
let server: FxAConfig.Server
if prefs?.intForKey(PrefsKeys.UseStageServer) == 1 {
server = FxAConfig.Server.stage
} else {
server = isChinaSyncServiceEnabled ? FxAConfig.Server.china : FxAConfig.Server.release
}
let config: FxAConfig
let useCustom = prefs?.boolForKey(PrefsKeys.KeyUseCustomFxAContentServer) ?? false || prefs?.boolForKey(PrefsKeys.KeyUseCustomSyncTokenServerOverride) ?? false
if useCustom {
let contentUrl: String
if prefs?.boolForKey(PrefsKeys.KeyUseCustomFxAContentServer) ?? false, let url = prefs?.stringForKey(PrefsKeys.KeyCustomFxAContentServer) {
contentUrl = url
} else {
contentUrl = "https://stable.dev.lcip.org"
}
let tokenServer = prefs?.boolForKey(PrefsKeys.KeyUseCustomSyncTokenServerOverride) ?? false ? prefs?.stringForKey(PrefsKeys.KeyCustomSyncTokenServerOverride) : nil
config = FxAConfig(contentUrl: contentUrl, clientId: RustFirefoxAccounts.clientID, redirectUri: RustFirefoxAccounts.redirectURL, tokenServerUrlOverride: tokenServer)
} else {
config = FxAConfig(server: server, clientId: RustFirefoxAccounts.clientID, redirectUri: RustFirefoxAccounts.redirectURL)
}
let type = UIDevice.current.userInterfaceIdiom == .pad ? DeviceType.tablet : DeviceType.mobile
let deviceConfig = DeviceConfig(name: DeviceInfo.defaultClientName(), type: type, capabilities: [.sendTab])
let accessGroupPrefix = Bundle.main.object(forInfoDictionaryKey: "MozDevelopmentTeam") as! String
let accessGroupIdentifier = AppInfo.keychainAccessGroupWithPrefix(accessGroupPrefix)
return FxAccountManager(config: config, deviceConfig: deviceConfig, applicationScopes: [OAuthScope.profile, OAuthScope.oldSync, OAuthScope.session], keychainAccessGroup: accessGroupIdentifier)
}
private init() {
// Set-up Rust network stack. Note that this has to be called
// before any Application Services component gets used.
Viaduct.shared.useReqwestBackend()
let prefs = RustFirefoxAccounts.prefs
syncAuthState = FirefoxAccountSyncAuthState(
cache: KeychainCache.fromBranch("rustAccounts.syncAuthState",
withLabel: RustFirefoxAccounts.syncAuthStateUniqueId(prefs: prefs),
factory: syncAuthStateCachefromJSON))
// Called when account is logged in for the first time, on every app start when the account is found (even if offline), and when migration of an account is completed.
NotificationCenter.default.addObserver(forName: .accountAuthenticated, object: nil, queue: .main) { [weak self] notification in
// Handle account migration completed successfully. Need to clear the old stored apnsToken and re-register push.
if let type = notification.userInfo?["authType"] as? FxaAuthType, case .migrated = type {
KeychainWrapper.sharedAppContainerKeychain.removeObject(forKey: KeychainKey.apnsToken, withAccessibility: .afterFirstUnlock)
NotificationCenter.default.post(name: .RegisterForPushNotifications, object: nil)
}
self?.update()
}
NotificationCenter.default.addObserver(forName: .accountProfileUpdate, object: nil, queue: .main) { [weak self] notification in
self?.update()
}
NotificationCenter.default.addObserver(forName: .accountMigrationFailed, object: nil, queue: .main) { [weak self] notification in
var info = ""
if let error = notification.userInfo?["error"] as? Error {
info = error.localizedDescription
}
Sentry.shared.send(message: "RustFxa failed account migration", tag: .rustLog, severity: .error, description: info)
self?.accountMigrationFailed = true
NotificationCenter.default.post(name: .FirefoxAccountStateChange, object: nil)
}
}
/// When migrating to new rust FxA, grab the old session tokens and try to re-use them.
private class func migrationTokens() -> (session: String, ksync: String, kxcs: String)? {
// Keychain forKey("profile.account"), return dictionary, from there
// forKey("account.state.<guid>"), guid is dictionary["stateKeyLabel"]
// that returns JSON string.
let keychain = KeychainWrapper.sharedAppContainerKeychain
let key = "profile.account"
keychain.ensureObjectItemAccessibility(.afterFirstUnlock, forKey: key)
// Ignore this class when de-archiving, it isn't needed.
NSKeyedUnarchiver.setClass(Unknown.self, forClassName: "Account.FxADeviceRegistration")
guard let dict = keychain.object(forKey: key) as? [String: AnyObject], let guid = dict["stateKeyLabel"] else {
return nil
}
let key2 = "account.state.\(guid)"
keychain.ensureObjectItemAccessibility(.afterFirstUnlock, forKey: key2)
guard let jsonData = keychain.data(forKey: key2) else {
return nil
}
guard let json = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String: Any] else {
return nil
}
guard let sessionToken = json["sessionToken"] as? String, let ksync = json["kSync"] as? String, let kxcs = json["kXCS"] as? String else {
return nil
}
return (session: sessionToken, ksync: ksync, kxcs: kxcs)
}
/// This is typically used to add a UI indicator that FxA needs attention (usually re-login manually).
public var isActionNeeded: Bool {
guard let accountManager = accountManager.peek() else { return false }
if accountManager.accountMigrationInFlight() || accountMigrationFailed { return true }
if !hasAccount() { return false }
return accountNeedsReauth()
}
/// Rust FxA notification handlers can call this to update caches and the UI.
private func update() {
guard let accountManager = accountManager.peek() else { return }
let avatarUrl = accountManager.accountProfile()?.avatar?.url
if let str = avatarUrl, let url = URL(string: str) {
avatar = Avatar(url: url)
}
// The userProfile (email, display name, etc) and the device name need to be cached for when the app starts in an offline state. Now is a good time to update those caches.
// Accessing the profile will trigger a cache update if needed
_ = userProfile
// Update the device name cache
if let deviceName = accountManager.deviceConstellation()?.state()?.localDevice?.displayName {
UserDefaults.standard.set(deviceName, forKey: RustFirefoxAccounts.prefKeyLastDeviceName)
}
// The legacy system had both of these notifications for UI updates. Possibly they could be made into a single notification
NotificationCenter.default.post(name: .FirefoxAccountProfileChanged, object: self)
NotificationCenter.default.post(name: .FirefoxAccountStateChange, object: self)
}
/// Cache the user profile (i.e. email, user name) for when the app starts offline. Notice this gets cleared when an account is disconnected.
private let prefKeyCachedUserProfile = "prefKeyCachedUserProfile"
private var cachedUserProfile: FxAUserProfile?
public var userProfile: FxAUserProfile? {
get {
let prefs = RustFirefoxAccounts.prefs
if let accountManager = accountManager.peek(), let profile = accountManager.accountProfile() {
if let p = cachedUserProfile, FxAUserProfile(profile: profile) == p {
return cachedUserProfile
}
cachedUserProfile = FxAUserProfile(profile: profile)
if let data = try? JSONEncoder().encode(cachedUserProfile!) {
prefs?.setObject(data, forKey: prefKeyCachedUserProfile)
}
} else if cachedUserProfile == nil {
if let data: Data = prefs?.objectForKey(prefKeyCachedUserProfile) {
cachedUserProfile = try? JSONDecoder().decode(FxAUserProfile.self, from: data)
}
}
return cachedUserProfile
}
}
public func disconnect() {
guard let accountManager = accountManager.peek() else { return }
accountManager.logout() { _ in }
let prefs = RustFirefoxAccounts.prefs
prefs?.removeObjectForKey(RustFirefoxAccounts.prefKeySyncAuthStateUniqueID)
prefs?.removeObjectForKey(prefKeyCachedUserProfile)
prefs?.removeObjectForKey(PendingAccountDisconnectedKey)
cachedUserProfile = nil
pushNotifications.unregister()
KeychainWrapper.sharedAppContainerKeychain.removeObject(forKey: KeychainKey.apnsToken, withAccessibility: .afterFirstUnlock)
}
public func hasAccount() -> Bool {
guard let accountManager = accountManager.peek() else { return false }
return accountManager.hasAccount()
}
public func accountNeedsReauth() -> Bool {
guard let accountManager = accountManager.peek() else { return false }
return accountManager.accountNeedsReauth()
}
}
/**
Wrap MozillaAppServices.Profile in an easy-to-serialize (and cache) FxAUserProfile.
Caching of this is required for when the app starts offline.
*/
public struct FxAUserProfile: Codable, Equatable {
public let uid: String
public let email: String
public let avatarUrl: String?
public let displayName: String?
init(profile: MozillaAppServices.Profile) {
uid = profile.uid
email = profile.email
avatarUrl = profile.avatar?.url
displayName = profile.displayName
}
}
|
mpl-2.0
|
09c21aac4e4083c4a245913f486455f7
| 47.45768 | 200 | 0.684823 | 5.113463 | false | true | false | false |
DarthRumata/EventsTree
|
EventsTreeiOSExample/Sources/IOSExample/Main/MainViewController.swift
|
1
|
3659
|
//
// MainViewController.swift
// EventNodeExample
//
// Created by Rumata on 6/21/17.
// Copyright © 2017 DarthRumata. All rights reserved.
//
import UIKit
import EventsTree
extension MainViewController {
enum Events {
struct SendTestEvent: Event {}
struct AddHandler: Event { let info: HandlerInfo }
struct RemoveHandler: Event {}
}
}
/// EventNode is used here only for TreeViews to make main functionality more clear
/// Of course it can be used for other tasks occurred in this app
class MainViewController: UIViewController {
/// DEMO: Simplified access to node for easier app structure
@IBOutlet fileprivate weak var rootNodeView: TreeNodeView!
@IBOutlet private weak var leftBranchOne: TreeNodeView!
@IBOutlet private weak var leftBranchTwo: TreeNodeView!
@IBOutlet private weak var leftBranchThree: TreeNodeView!
@IBOutlet private weak var rightBranchOne: TreeNodeView!
@IBOutlet weak var bottomToolbarConstraint: NSLayoutConstraint!
fileprivate var toolbarState: ToolbarState = .hidden
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
/// Also just a demo version. In real app you should inject
/// instance of EventNode in some Model/Logic class
/// at the same time as its Module created
let rootEventNode = EventNode(parent: nil)
rootNodeView.eventNode = rootEventNode
rightBranchOne.eventNode = EventNode(parent: rootEventNode)
let firstLeftEventNode = EventNode(parent: rootEventNode)
leftBranchOne.eventNode = firstLeftEventNode
let secondLeftEventNode = EventNode(parent: firstLeftEventNode)
leftBranchTwo.eventNode = secondLeftEventNode
leftBranchThree.eventNode = EventNode(parent: secondLeftEventNode)
rootEventNode.addHandler { [weak self] (event: TreeNodeView.Events.NodeSelected) in
if event.view != nil {
self?.changeToolbarState(to: .shown)
}
}
/// Added recognizer to delesect current node
let recognizer = UITapGestureRecognizer(target: self, action: #selector(didTapOnScreen))
view.addGestureRecognizer(recognizer)
}
// MARK: Actions
@IBAction func didTapAddHandler(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationId = String(describing: AddHandlerViewController.self)
let controller = storyboard.instantiateViewController(withIdentifier: destinationId) as! AddHandlerViewController
controller.saveHandler = { [weak self] handlerInfo in
let event = Events.AddHandler(info: handlerInfo)
self?.rootNodeView.eventNode.raise(event: event)
}
present(controller, animated: true, completion: nil)
}
@IBAction func removeHandler(_ sender: Any) {
rootNodeView.eventNode.raise(event: Events.RemoveHandler())
}
@IBAction func didTapRaiseEvent(_ sender: Any) {
rootNodeView.eventNode.raise(event: Events.SendTestEvent())
}
}
private extension MainViewController {
enum ToolbarState {
case shown, hidden
var bottomOffset: CGFloat {
switch self {
case .shown:
return 0
case .hidden:
return -44
}
}
}
func changeToolbarState(to state: ToolbarState) {
if toolbarState == state {
return
}
toolbarState = state
bottomToolbarConstraint.constant = toolbarState.bottomOffset
UIView.animate(withDuration: 0.2) {
self.view.layoutIfNeeded()
}
}
@objc func didTapOnScreen() {
changeToolbarState(to: .hidden)
/// DEMO: better to use event from that class where it is emitted
rootNodeView.eventNode.raise(event: TreeNodeView.Events.NodeSelected(view: nil))
}
}
|
mit
|
15afa58f43c7d57879ef7114712e4cd8
| 28.739837 | 117 | 0.724713 | 4.328994 | false | false | false | false |
JimCampagno/Overwatch
|
Overwatch/HeroTableViewController.swift
|
1
|
6985
|
//
// HeroTableViewController.swift
// Overwatch
//
// Created by Jim Campagno on 10/22/16.
// Copyright © 2016 Gamesmith, LLC. All rights reserved.
//
import UIKit
import AVFoundation
class HeroTableViewController: UITableViewController {
var heroes: [Type : [Hero]]!
var audioPlayer: AVAudioPlayer!
var sectionViews: [HeroSectionView]!
var heroview: HeroView!
var selectedFrame: CGRect!
var selectedHero: Hero!
var topConstraint: NSLayoutConstraint!
var heightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
setup()
addGestureRecognizer(to: tableView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
createSectionViews()
}
}
// MARK: - UITableView Methods
extension HeroTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return heroes.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sortedTypes = Array(heroes.keys).sorted { $0 < $1 }
let type = sortedTypes[section]
let heroesForType = heroes[type]!
return heroesForType.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HeroCell", for: indexPath) as! HeroTableViewCell
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let heroCell = cell as! HeroTableViewCell
let type = Type.allTypes[indexPath.section]
let heroesForType = heroes[type]!
heroCell.hero = heroesForType[indexPath.row]
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let heroSectionView = sectionViews[section]
heroSectionView.type = Type.allTypes[section]
heroSectionView.willDisplay()
return heroSectionView
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(HeroSectionView.height)
}
func retrieveCell(for indexPath: IndexPath, at point: CGPoint) -> HeroTableViewCell {
let cell = self.tableView.cellForRow(at: indexPath) as! HeroTableViewCell
return cell
}
func visibleCells(excluding cell: HeroTableViewCell) -> [HeroTableViewCell] {
let viewableCells = self.tableView.visibleCells as! [HeroTableViewCell]
let nonTappedCells = viewableCells.filter { $0 != cell }
return nonTappedCells
}
}
// MARK: - Setup Methods
extension HeroTableViewController {
func setup() {
setupAudioPlayer()
setupBarButtonItem()
heroes = [.offense : Hero.offense, .defense : Hero.defense]
view.backgroundColor = UIColor.lightBlack
}
func setupAudioPlayer() {
let filePath = Bundle.main.path(forResource: "ElectricSound", ofType: "wav")!
let url = URL(fileURLWithPath: filePath)
audioPlayer = try! AVAudioPlayer(contentsOf: url)
}
func setupBarButtonItem() {
let mcCreeWeapon = McCreeWeaponView(frame: CGRect(x: 0, y: 0, width: 70, height: 35))
let barButtonItem = UIBarButtonItem(customView: mcCreeWeapon)
navigationItem.rightBarButtonItem = barButtonItem
}
func addGestureRecognizer(to view: UIView) {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
view.addGestureRecognizer(gestureRecognizer)
}
}
// MARK: - Section Header Views
extension HeroTableViewController {
func createSectionViews() {
let width = Int(tableView.frame.size.width)
let height = HeroSectionView.height
let frame = CGRect(x: 0, y: 0, width: width, height: height)
let offense = HeroSectionView(frame: frame, type: .offense)
let defense = HeroSectionView(frame: frame, type: .defense)
let tank = HeroSectionView(frame: frame, type: .tank)
let support = HeroSectionView(frame: frame, type: .support)
sectionViews = [offense, defense, tank, support]
}
}
// MARK: - Action Methods
extension HeroTableViewController {
func viewTapped(_ sender: UITapGestureRecognizer) {
let point = sender.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: point) else { return }
let cell = retrieveCell(for: indexPath, at: point)
tableView.isUserInteractionEnabled = false
runAnimations(with: cell, indexPath: indexPath)
animateSelection(at: point)
audioPlayer.play()
}
func animateSelection(at point: CGPoint) {
UIView.animateRainbow(in: tableView, center: point) { _ in }
}
func runAnimations(with cell: HeroTableViewCell, indexPath: IndexPath) {
scale(cell: cell, indexPath: indexPath) { _ in
self.tableView.isUserInteractionEnabled = true
}
}
func scale(cell: HeroTableViewCell, indexPath: IndexPath, handler: @escaping () -> Void) {
let rect = tableView.rectForRow(at: indexPath)
let y = abs(self.tableView.contentOffset.y - rect.origin.y)
let origin = CGPoint(x: 0.0, y: y)
let frame = CGRect(origin: origin, size: rect.size)
heroview = cell.heroView.copy(with: rect) as! HeroView
selectedHero = heroview.hero
selectedFrame = frame
tableView.addSubview(heroview)
delay(0.1) { [unowned self] _ in
self.performSegue(withIdentifier: "DetailSegue", sender: nil)
}
UIView.animate(withDuration: 0.3, animations: {
self.heroview.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.heroview.alpha = 0.5
}) { [unowned self] _ in
DispatchQueue.main.async {
self.tableView.willRemoveSubview(self.heroview)
self.heroview.removeFromSuperview()
handler()
}
}
}
func delay(_ delay:Double, closure:@escaping ()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
}
// MARK: - Segue Methods
extension HeroTableViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destVC = segue.destination as! HeroDetailViewController
destVC.selectedFrame = selectedFrame
destVC.hero = selectedHero
}
}
|
mit
|
c22987a444e6a76e0d5575fe75882e71
| 30.459459 | 121 | 0.64791 | 4.770492 | false | false | false | false |
JackVaughn23/pingit
|
Pingit/AppDelegate.swift
|
1
|
1748
|
//
// AppDelegate.swift
// Pingit
//
// Created by Vaughn, Jack on 10/9/15.
// Copyright © 2015 Rutherford County Schools. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
//IBOutlets
@IBOutlet weak var menu: NSMenu!
@IBOutlet weak var versionItem: NSMenuItem!
@IBOutlet weak var computerNameItem: NSMenuItem!
@IBOutlet weak var statusItem: NSMenuItem!
@IBOutlet weak var screenshareItem: NSMenuItem!
func applicationDidFinishLaunching(aNotification: NSNotification) {
setIcon(name: "normal")
let version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString")!
versionItem.title = "Pingit v\(version)"
}
@IBAction func statusClicked(sender: AnyObject) {
storeClipboardContent()
if (statusItem.title == "Check status of computer in clipboard.....") {
startChecking()
} else {
stopChecking()
}
}
@IBAction func screenshareClicked(sender: AnyObject) {
if (screenshareItem.title == "Screenshare computer in clipboard....") {
storeClipboardContent()
NSWorkspace.sharedWorkspace().openURL(NSURL(string: "vnc://\(Storage.clipboardContent)")!)
} else {
NSWorkspace.sharedWorkspace().openURL(NSURL(string: "vnc://\(Storage.currentComputer)")!)
}
}
func storeClipboardContent() {
Storage.clipboardContent = Pasteboard().getContent()
}
@IBAction func quitClicked(sender: NSMenuItem) {
NSApplication.sharedApplication().terminate(self)
}
func applicationWillTerminate(aNotification: NSNotification) {
}
}
|
mit
|
3460fc7f23d128c33b12a45cf8cf09be
| 30.781818 | 102 | 0.659416 | 4.991429 | false | false | false | false |
LiulietLee/BilibiliCD
|
BCD/waifu2x/MetalBicubic.swift
|
1
|
4307
|
//
// MetalBicubic.swift
// waifu2x
//
// Created by 谢宜 on 2018/1/23.
// Copyright © 2018年 xieyi. All rights reserved.
//
import Foundation
import Metal
import MetalKit
/// Bicubic interpolation running on GPU.
class MetalBicubic {
let device: MTLDevice!
let library: MTLLibrary!
let commandQueue: MTLCommandQueue!
public init() throws {
device = MTLCreateSystemDefaultDevice()
library = try device.makeDefaultLibrary(bundle: Bundle(for: type(of: self)))
commandQueue = device.makeCommandQueue()
}
func maxTextureSize() -> Int {
if device.supportsFeatureSet(.iOS_GPUFamily3_v1) || device.supportsFeatureSet(.iOS_GPUFamily3_v2) || device.supportsFeatureSet(.iOS_GPUFamily3_v3) || device.supportsFeatureSet(.iOS_GPUFamily4_v1) {
return 16384
}
if device.supportsFeatureSet(.iOS_GPUFamily1_v2) || device.supportsFeatureSet(.iOS_GPUFamily2_v2) || device.supportsFeatureSet(.iOS_GPUFamily1_v3) || device.supportsFeatureSet(.iOS_GPUFamily2_v3) || device.supportsFeatureSet(.iOS_GPUFamily1_v4) || device.supportsFeatureSet(.iOS_GPUFamily2_v4) {
return 8192
}
if device.supportsFeatureSet(.iOS_GPUFamily1_v1) || device.supportsFeatureSet(.iOS_GPUFamily2_v1) {
return 4096
}
return 16384
}
func resizeSingle(_ input: [UInt8], _ width: Int, _ height: Int, _ factor: Float = 1.0) -> [UInt8]? {
// Get image size
var inW = width
var inH = height
var sf = factor
// Convert to metal texture
let inTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: MTLPixelFormat.r8Unorm, width: inW, height: inH, mipmapped: true)
let inTexture = device.makeTexture(descriptor: inTextureDescriptor)
let inRegion = MTLRegionMake2D(0, 0, inW, inH)
inTexture?.replace(region: inRegion, mipmapLevel: 0, withBytes: input, bytesPerRow: width)
// Prepare output texture
var outW = Int(Float(inW) * factor)
var outH = Int(Float(inH) * factor)
var outP = outW
let outTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: MTLPixelFormat.r8Unorm, width: outW, height: outH, mipmapped: false)
outTextureDescriptor.usage = .shaderWrite
guard let outTexture = device.makeTexture(descriptor: outTextureDescriptor) else {
return nil
}
// Set constants
let constants = MTLFunctionConstantValues()
constants.setConstantValue(&sf, type: MTLDataType.float, index: 0)
constants.setConstantValue(&inW, type: MTLDataType.uint, index: 1)
constants.setConstantValue(&inH, type: MTLDataType.uint, index: 2)
constants.setConstantValue(&outW, type: MTLDataType.uint, index: 3)
constants.setConstantValue(&outH, type: MTLDataType.uint, index: 4)
constants.setConstantValue(&outP, type: MTLDataType.uint, index: 5)
let sampleMain = try! library.makeFunction(name: "BicubicSingleMain", constantValues: constants)
let pipelineState = try! device.makeComputePipelineState(function: sampleMain)
// Invoke kernel function
let commandBuffer = commandQueue.makeCommandBuffer()
let commandEncoder = commandBuffer?.makeComputeCommandEncoder()
commandEncoder?.setComputePipelineState(pipelineState)
commandEncoder?.setTexture(inTexture, index: 0)
commandEncoder?.setTexture(outTexture, index: 1)
let threadGroupCount = MTLSize(width: 1, height: 1, depth: 1)
let threadGroups = MTLSize(width: outW / threadGroupCount.width, height: outH / threadGroupCount.height, depth: 1)
commandEncoder?.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadGroupCount)
commandEncoder?.endEncoding()
commandBuffer?.commit()
commandBuffer?.waitUntilCompleted()
// Get output texture
let outByteCount = outW * outH
let outBytesPerRow = outW
var outBytes = [UInt8](repeating: 0, count: outByteCount)
let outRegion = MTLRegionMake2D(0, 0, outW, outH)
outTexture.getBytes(&outBytes, bytesPerRow: outBytesPerRow, from: outRegion, mipmapLevel: 0)
return outBytes
}
}
|
gpl-3.0
|
f0a0c86bb29390ff5ca208f3fec32772
| 47.314607 | 303 | 0.683953 | 4.186952 | false | false | false | false |
LYM-mg/GoodBookDemo
|
GoodBookDemo/GoodBookDemo/PushNewBook/C/MGPhotoSelectController.swift
|
1
|
3682
|
//
// MGPhotoSelectController.swift
// GoodBookDemo
//
// Created by ming on 16/5/6.
// Copyright © 2016年 ming. All rights reserved.
//
import UIKit
protocol MGPhotoSelectControllerDelegate: NSObjectProtocol{
func getImageFromPicker(image: UIImage)
}
class MGPhotoSelectController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var alertVC: UIAlertController?
var imagePickerVC: UIImagePickerController = UIImagePickerController()
var delegate: MGPhotoSelectControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clearColor()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
dismissViewControllerAnimated(true, completion: nil)
}
init(){
super.init(nibName: nil, bundle: nil)
self.modalPresentationStyle = .OverFullScreen
self.view.backgroundColor = UIColor.clearColor()
imagePickerVC.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if alertVC == nil {
alertVC =
UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
alertVC!.addAction(UIAlertAction(title: "从相册中选择", style: .Default, handler: { (action) -> Void in
self.getImageFormPhoto()
}))
alertVC!.addAction(UIAlertAction(title: "从相机选择", style: .Default, handler: { (action) -> Void in
self.getImageFromCamera()
}))
alertVC!.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: { (action) -> Void in
}))
presentViewController(alertVC!, animated: true, completion: nil)
}
}
// 从相册中获取
private func getImageFormPhoto(){
if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
imagePickerVC.sourceType = .PhotoLibrary
imagePickerVC.allowsEditing = true
presentViewController(imagePickerVC, animated: true, completion: nil)
return
}else {
let alert = UIAlertController(title: "友情提示", message: "相册不可用", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "关闭", style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
}
// 从相机中获取
private func getImageFromCamera(){
if UIImagePickerController.isSourceTypeAvailable(.Camera){
imagePickerVC.sourceType = .Camera
imagePickerVC.allowsEditing = true
presentViewController(imagePickerVC, animated: true, completion: nil)
}else {
let alert = UIAlertController(title: "友情提示", message: "此设备没有摄像头", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "关闭", style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
}
// 代理方法
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let newImage = info[UIImagePickerControllerOriginalImage] as! UIImage
self.delegate?.getImageFromPicker(newImage)
self.dismissViewControllerAnimated(false, completion: nil)
}
}
|
mit
|
49eb84021836877f9c83028a4b96534b
| 35.438776 | 123 | 0.645757 | 5.321908 | false | false | false | false |
gu704823/huobanyun
|
huobanyun/Spring/DesignableTextView.swift
|
4
|
2448
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// 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 UIKit
@IBDesignable public class DesignableTextView: SpringTextView {
@IBInspectable public var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable public var lineHeight: CGFloat = 1.5 {
didSet {
let font = UIFont(name: self.font!.fontName, size: self.font!.pointSize)
let text = self.text
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineHeight
let attributedString = NSMutableAttributedString(string: text!)
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
attributedString.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: attributedString.length))
self.attributedText = attributedString
}
}
}
|
mit
|
79e2ef733f946f98e628021339ddc93d
| 39.131148 | 157 | 0.69281 | 5.132075 | false | false | false | false |
sadeslandes/SplitScreen
|
OSX/SplitScreen/File.swift
|
1
|
4588
|
//
// File.swift
// SplitScreen
//
// Created by Tausif Ahmed on 4/26/16.
// Copyright © 2016 SplitScreen. All rights reserved.
//
import Foundation
import AppKit
class File: Equatable {
fileprivate var path: URL
fileprivate var file_name: String
/**
Inits the `File` with the `dirPath` and `name`
- Parameter dirPath: `NSURL` that is where the file will be located
- Parameter name: `String` that to the name of the `File`
*/
init(dirPath: URL, name: String) {
file_name = name
path = dirPath.appendingPathComponent(name)
}
/**
Returns `file_name`
- Returns: `String` that is the name of the `File`
*/
func getFileName() -> String {
return file_name
}
/**
Returns `path`
- Returns: `String` representation of the `NSURL` for the `File`
*/
func getPathString() -> String {
return path.path
}
/**
Parses the contents of a file from a text file to an `array` of `arrays` of `Int` values
- Parameter height: `Int` that corresponds to screen's height
- Parameter width: `Int` that corresponds to screen's width
- Returns: `array` of `arrays` of `Int` that contains values for a `SnapPoint` for each `array`
*/
func parseFileContent(_ height: Int, width: Int) -> [[Int]] {
var text: String = String()
var snap_params: [[Int]] = []
// Attempt to get text from file
do {
try text = String(contentsOfFile: path.path, encoding: String.Encoding.utf8)
} catch _ {
print("Could not read from \(file_name)")
}
// Split the text into lines
let lines = text.characters.split(separator: "\n").map(String.init)
for line in lines {
// Split line into the different values of a SnapPoint
let components = line.characters.split(separator: ",").map(String.init)
var snap_param: [Int] = []
for component in components {
// General values
if component == "HEIGHT" {
snap_param.append(height)
} else if component == "WIDTH" {
snap_param.append(width)
} else if component == "0" {
snap_param.append(0)
} else if component != components.last {
if component.range(of: "/") != nil {
let dividends = component.characters.split(separator: "/").map(String.init)
if dividends[0] == "HEIGHT" {
snap_param.append(height/Int(dividends[1])!)
} else {
snap_param.append(width/Int(dividends[1])!)
}
} else if component.range(of: "-") != nil {
let dividends = component.characters.split(separator: "-").map(String.init)
if dividends[0] == "HEIGHT" {
snap_param.append(height - Int(dividends[1])!)
} else {
snap_param.append(width - Int(dividends[1])!)
}
}
// For the snap points that are stored as pairs
} else {
let snap_points = component.characters.split(separator: ":").map(String.init)
for snap_point in snap_points {
var xCoord: Int
var yCoord: Int
var tuple: String = snap_point
tuple.remove(at: tuple.startIndex)
tuple.remove(at: tuple.characters.index(before: tuple.endIndex))
let coords = tuple.characters.split(separator: ";").map(String.init)
if coords[0] == "0" {
xCoord = 0
} else if coords[0].range(of: "-") != nil {
let dividends = coords[0].characters.split(separator: "-").map(String.init)
xCoord = width - Int(dividends[1])!
} else if coords[0].range(of: "/") != nil {
let dividends = coords[0].characters.split(separator: "/").map(String.init)
xCoord = width/Int(dividends[1])!
} else {
xCoord = width
}
if coords[1] == "0" {
yCoord = 0
} else if coords[1].range(of: "-") != nil {
let dividends = coords[1].characters.split(separator: "-").map(String.init)
yCoord = height - Int(dividends[1])!
} else if coords[1].range(of: "/") != nil {
let dividends = coords[1].characters.split(separator: "/").map(String.init)
yCoord = height/Int(dividends[1])!
} else {
yCoord = height
}
snap_param.append(xCoord)
snap_param.append(yCoord)
}
}
}
snap_params.append(snap_param)
}
return snap_params
}
}
/**
Creates an equality function for files based on their `path` and `file_name`
- Parameter lhs: `File` that is the left hand `File`
- Parameter rhs: `File` that is the right hand `File`
- Returns: `Bool` that teels whether or not the 2 `File` objects are the same
*/
func ==(lhs: File, rhs: File) -> Bool {
return lhs.getPathString() == rhs.getPathString() && lhs.getFileName() == rhs.getFileName()
}
|
apache-2.0
|
78f3ef486dfece326d3205641b512eb9
| 28.403846 | 97 | 0.619359 | 3.3 | false | false | false | false |
son11592/STNavigationViewController
|
STNavigationViewController/Classes/STNavigationViewController.swift
|
1
|
7386
|
//
// STNavigationViewController.swift
// STNavigationViewController
//
// Created by Sơn Thái on 7/17/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
open class STNavigationViewController: UINavigationController {
// MARK: - Static properites
open static var isPanGestureEnabling = false
// MARK: - Internal properties
open var isPushInteractionEnabled = false
// MARK: - Private properties
open var isPushingViewController = false
open var leftGesture: UIPanGestureRecognizer?
// MARK: - Initiation
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
}
override public init(nibName: String?, bundle: Bundle?) {
super.init(nibName: nibName, bundle: bundle)
self.commonInit()
}
override open func pushViewController(_ viewController: UIViewController, animated: Bool) {
isPushingViewController = true
super.pushViewController(viewController, animated: animated)
}
override open func viewDidLoad() {
super.viewDidLoad()
self.attachGestures()
}
open func commonInit() {
self.delegate = self
self.transitioningDelegate = self
self.navigationBar.isHidden = true
self.interactivePopGestureRecognizer?.isEnabled = false
}
open func attachGestures() {
let left = UIPanGestureRecognizer(target: self, action: #selector(handleSwipeFromLeft(_:)))
left.delegate = self
left.cancelsTouchesInView = false
left.delaysTouchesBegan = false
left.delaysTouchesEnded = false
self.view.addGestureRecognizer(left)
self.leftGesture = left
if self.isPushInteractionEnabled {
let right = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleSwipeFromRight(_:)))
right.edges = .right
right.cancelsTouchesInView = false
right.delaysTouchesBegan = false
right.delaysTouchesEnded = false
self.view.addGestureRecognizer(right)
}
}
fileprivate var interactionController: UIPercentDrivenInteractiveTransition?
@objc public func handleSwipeFromLeft(_ gesture: UIScreenEdgePanGestureRecognizer) {
let percent = gesture.translation(in: gesture.view!).x / gesture.view!.bounds.size.width
if gesture.state == .began {
interactionController = UIPercentDrivenInteractiveTransition()
if viewControllers.count > 1 {
STNavigationViewController.isPanGestureEnabling = true
popViewController(animated: true)
} else {
dismiss(animated: true)
}
} else if gesture.state == .changed {
interactionController?.update(percent)
} else if gesture.state == .ended {
if percent > 0.2 && gesture.state != .cancelled {
interactionController?.finish()
} else {
interactionController?.cancel()
}
interactionController = nil
// Unlock pan gesture state
let delayTimeDispatch = DispatchTime.now() + Double(0.23)
DispatchQueue.main.asyncAfter(deadline: delayTimeDispatch) {
STNavigationViewController.isPanGestureEnabling = false
}
}
}
@objc public func handleSwipeFromRight(_ gesture: UIScreenEdgePanGestureRecognizer) {
let percent = -gesture.translation(in: gesture.view!).x / gesture.view!.bounds.size.width
if gesture.state == .began {
guard let currentViewController = viewControllers.last as? STViewController else {
return
}
interactionController = UIPercentDrivenInteractiveTransition()
currentViewController.pushInteractionController()
} else if gesture.state == .changed {
interactionController?.update(percent)
} else if gesture.state == .ended {
if percent > 0.5 {
interactionController?.finish()
} else {
interactionController?.cancel()
}
interactionController = nil
}
}
open func lockLeftInteractionGesture(_ isLocked: Bool) {
self.leftGesture?.isEnabled = !isLocked
}
}
extension STNavigationViewController: UINavigationControllerDelegate {
public func navigationController(_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationControllerOperation,
from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
guard interactionController == nil else {
return (fromVC as? STViewController)?.getPopInteractionAnimatedTransitioning(from: fromVC, to: toVC)
}
if operation == UINavigationControllerOperation.push {
return (fromVC as? STViewController)?.getPushAnimatedTransitioning(from: fromVC, to: toVC)
} else if operation == UINavigationControllerOperation.pop {
return (fromVC as? STViewController)?.getPopAnimatedTransitioning(from: fromVC, to: toVC)
}
return nil
}
public func navigationController(_ navigationController: UINavigationController,
didShow viewController: UIViewController,
animated: Bool) {
isPushingViewController = false
}
public func navigationController(_ navigationController: UINavigationController,
interactionControllerFor animationController: UIViewControllerAnimatedTransitioning)
-> UIViewControllerInteractiveTransitioning? {
return interactionController
}
}
extension STNavigationViewController: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return (source as? STViewController)?.getPushAnimatedTransitioning(from: source, to: presenting)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return (dismissed as? STViewController)?.getPopAnimatedTransitioning(from: STViewController(), to: dismissed)
}
public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning)
-> UIViewControllerInteractiveTransitioning? {
return interactionController
}
public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning)
-> UIViewControllerInteractiveTransitioning? {
return interactionController
}
public func presentationController(forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController) -> UIPresentationController? {
return PresentationController(presentedViewController: presented, presenting: presenting)
}
}
extension STNavigationViewController: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer is UIScreenEdgePanGestureRecognizer else { return true }
return viewControllers.count > 1 && !isPushingViewController
}
}
class PresentationController: UIPresentationController {
override var shouldRemovePresentersView: Bool { return true }
}
|
mit
|
36b662a40f04b693e9ae51783985583b
| 36.100503 | 119 | 0.718272 | 5.93012 | false | false | false | false |
wireapp/wire-ios-data-model
|
Source/Model/Message/ConversationMessage+Reaction.swift
|
1
|
4147
|
//
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
@objc public enum MessageReaction: UInt16 {
case like
public var unicodeValue: String {
switch self {
case .like: return "❤️"
}
}
}
extension ZMMessage {
static func appendReaction(_ unicodeValue: String?, toMessage message: ZMConversationMessage) -> ZMClientMessage? {
guard let message = message as? ZMMessage, let context = message.managedObjectContext, let messageID = message.nonce else { return nil }
guard message.isSent else { return nil }
let emoji = unicodeValue ?? ""
let reaction = WireProtos.Reaction.createReaction(emoji: emoji, messageID: messageID)
let genericMessage = GenericMessage(content: reaction)
guard let conversation = message.conversation else { return nil }
do {
let clientMessage = try conversation.appendClientMessage(with: genericMessage, expires: false, hidden: true)
message.addReaction(unicodeValue, forUser: .selfUser(in: context))
return clientMessage
} catch {
Logging.messageProcessing.warn("Failed to append reaction. Reason: \(error.localizedDescription)")
return nil
}
}
@discardableResult
@objc public static func addReaction(_ reaction: MessageReaction, toMessage message: ZMConversationMessage) -> ZMClientMessage? {
// confirmation that we understand the emoji
// the UI should never send an emoji we dont handle
if Reaction.transportReaction(from: reaction.unicodeValue) == .none {
fatal("We can't append this reaction \(reaction.unicodeValue), this is a programmer error.")
}
return appendReaction(reaction.unicodeValue, toMessage: message)
}
@objc public static func removeReaction(onMessage message: ZMConversationMessage) {
_ = appendReaction(nil, toMessage: message)
}
@objc public func addReaction(_ unicodeValue: String?, forUser user: ZMUser) {
removeReaction(forUser: user)
guard let unicodeValue = unicodeValue,
unicodeValue.count > 0 else {
updateCategoryCache()
return
}
guard let reaction = self.reactions.first(where: {$0.unicodeValue! == unicodeValue}) else {
// we didn't find a reaction, need to add a new one
let newReaction = Reaction.insertReaction(unicodeValue, users: [user], inMessage: self)
self.mutableSetValue(forKey: "reactions").add(newReaction)
updateCategoryCache()
return
}
reaction.mutableSetValue(forKey: ZMReactionUsersValueKey).add(user)
}
fileprivate func removeReaction(forUser user: ZMUser) {
guard let reaction = self.reactions.first(where: {$0.users.contains(user)}) else {
return
}
reaction.mutableSetValue(forKey: ZMReactionUsersValueKey).remove(user)
}
@objc public func clearAllReactions() {
let oldReactions = self.reactions
reactions.removeAll()
guard let moc = managedObjectContext else { return }
oldReactions.forEach(moc.delete)
}
@objc public func clearConfirmations() {
let oldConfirmations = self.confirmations
mutableSetValue(forKey: ZMMessageConfirmationKey).removeAllObjects()
guard let moc = managedObjectContext else { return }
oldConfirmations.forEach(moc.delete)
}
}
|
gpl-3.0
|
1d061ed65ca9eabbe14e61ffe8ef46e4
| 38.084906 | 144 | 0.676563 | 4.82305 | false | false | false | false |
Virpik/T
|
src/UI/[UIView]/[UIView][Debug].swift
|
1
|
1388
|
//
// [TView][Debug].swift
// Pods-TDemo
//
// Created by Virpik on 31/01/2018.
//
import Foundation
extension UIView {
public func debugBackground(_ alpha: CGFloat = 0.3) {
self.backgroundColor = UIColor.random().transparency(alpha)
}
public static func point(at center: CGPoint) -> UIView {
let bgColor = UIColor.red.transparency(0.3)
let crosshairsBgColor = UIColor.green.transparency(0.3)
let frameSize = CGSize(width: 20, height: 20)
let crosshairsWidth: CGFloat = 1
let view = UIView(size: frameSize)
view.backgroundColor = bgColor
view.tBRadius = (min(frameSize.width, frameSize.height)/2.cgFloat).float
view.clipsToBounds = true
view.center = center
let _hView = UIView(width: frameSize.width, height: crosshairsWidth)
let _wView = UIView(width: crosshairsWidth, height: frameSize.height)
_wView.center = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
_hView.center = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
_hView.backgroundColor = crosshairsBgColor
_wView.backgroundColor = crosshairsBgColor
view.addSubview(view: _hView)
view.addSubview(view: _wView)
return view
}
}
|
mit
|
b10d476182e7824f4cef1ee0597bd9d0
| 27.916667 | 80 | 0.602305 | 4.180723 | false | false | false | false |
sharath-cliqz/browser-ios
|
Client/Cliqz/Frontend/Browser/Connect/AddConnectionViewController.swift
|
2
|
10587
|
//
// AddConnectionViewController.swift
// Client
//
// Created by Mahmoud Adam on 5/10/17.
// Copyright © 2017 Mozilla. All rights reserved.
//
import UIKit
import AVFoundation
class AddConnectionViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
private var captureSession:AVCaptureSession?
private var videoPreviewLayer:AVCaptureVideoPreviewLayer?
private var qrCodeFrameView:UIView?
private let instructionsLabel = UILabel()
private var qrCodeScannerReady = false
private var qrCodeScanned = false
private let supportedBarCodes = [AVMetadataObjectTypeQRCode]
var viewOpenTime: Double?
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("Scan QR-Code", tableName: "Cliqz", comment: "[Settings -> Connect] Scan QR-Code")
configureInstructionLabel()
configureScanningView()
showNotificationAlert()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.viewOpenTime = Date.getCurrentMillis()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let openTime = viewOpenTime, !qrCodeScanned {
let duration = Int(Date.getCurrentMillis() - openTime)
self.logTelemetrySignal("click", customData: ["target": "back", "view": "scan_intro", "show_duration": duration])
}
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
adjustVideoPreviewLayerFrame()
}
// MARK: - Private Helpers
private func configureInstructionLabel() {
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "connectDesktopMenu")
let attachmentString = NSAttributedString(attachment: attachment)
let attributedString = NSMutableAttributedString(string: NSLocalizedString("Go to ", tableName: "Cliqz", comment: "[Connect] instructions text part#1"))
attributedString.append(attachmentString)
attributedString.append(NSAttributedString(string: NSLocalizedString(" and select connect to scan the QR-Code", tableName: "Cliqz", comment: "[Connect] instructions text part#2")))
instructionsLabel.attributedText = attributedString
instructionsLabel.numberOfLines = 2
self.view.addSubview(instructionsLabel)
let margin = 15
instructionsLabel.snp_makeConstraints { make in
make.leading.equalTo(self.view).offset(margin)
make.trailing.equalTo(self.view).offset(-1 * margin)
make.bottom.equalTo(self.view).offset(-2 * margin)
}
}
private func configureScanningView() {
// Get an instance of the AVCaptureDevice class to initialize a device object and provide the video
// as the media type parameter.
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
// Get an instance of the AVCaptureDeviceInput class using the previous device object.
let input = try AVCaptureDeviceInput(device: captureDevice)
// Initialize the captureSession object.
captureSession = AVCaptureSession()
// Set the input device on the capture session.
captureSession?.addInput(input)
// Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
// Set delegate and use the default dispatch queue to execute the call back
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
// Detect all the supported bar code
captureMetadataOutput.metadataObjectTypes = supportedBarCodes
// Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
adjustVideoPreviewLayerFrame()
view.layer.addSublayer(videoPreviewLayer!)
// Start video capture
captureSession?.startRunning()
// Initialize QR Code Frame to highlight the QR code
qrCodeFrameView = UIView()
if let qrCodeFrameView = qrCodeFrameView {
qrCodeFrameView.layer.borderColor = UIColor.green.cgColor
qrCodeFrameView.layer.borderWidth = 2
view.addSubview(qrCodeFrameView)
view.bringSubview(toFront: qrCodeFrameView)
}
} catch {
showAllowCameraAccessAlert()
return
}
}
private func showAllowCameraAccessAlert() {
let settingsOptionTitle = NSLocalizedString("Settings", tableName: "Cliqz", comment: "Settings option for turning on Camera access")
let message = NSLocalizedString("Cliqz Browser does not have access to your camera. To enable access, tap ‘Settings’ and turn on camera.", tableName: "Cliqz", comment: "[Connect] Alert message for turning on Camera access when Scanning QR Code")
let settingsAction = UIAlertAction(title: settingsOptionTitle, style: .default) { (_) -> Void in
if let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.openURL(settingsUrl)
}
}
let title = NSLocalizedString("Allow Camera Access", tableName: "Cliqz", comment: "[Connect] Alert title for turning on Camera access when scanning QRCode")
let alertController = UIAlertController (title: title, message: message, preferredStyle: .alert)
let notNowOptionTitle = NSLocalizedString("Not Now", tableName: "Cliqz", comment: "Not now option for turning on Camera access")
let cancelAction = UIAlertAction(title: notNowOptionTitle, style: .default, handler: nil)
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
present(alertController, animated: true, completion: nil)
}
private func adjustVideoPreviewLayerFrame() {
let width = view.frame.width
let height = view.frame.height * 0.8
videoPreviewLayer?.frame = CGRect(x: 0, y: 0, width: width, height: height)
switch UIDevice.current.orientation {
case .portrait:
videoPreviewLayer?.connection.videoOrientation = .portrait
case .landscapeLeft:
videoPreviewLayer?.connection.videoOrientation = .landscapeRight
case .landscapeRight:
videoPreviewLayer?.connection.videoOrientation = .landscapeLeft
default:
videoPreviewLayer?.connection.videoOrientation = .portrait
}
}
private func showNotificationAlert() {
let alertTitle = NSLocalizedString("Open Cliqz Browser", tableName: "Cliqz", comment: "[Connect] Scan QR-Code alert title")
let alertMessage = NSLocalizedString("Please open Cliqz Browser on your computer (or get it from cliqz.com).", tableName: "Cliqz", comment: "[Connect] Scan QR-Code alert message")
let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("Ok", tableName: "Cliqz", comment: "Ok"), style: .default, handler: {[weak self] (_) in
self?.qrCodeScannerReady = true
self?.logTelemetrySignal("click", customData: ["target": "confirm", "view": "scan_intro"])
}))
self.present(alertController, animated: true, completion: nil)
}
//MARK: - AVCaptureMetadataOutputObjectsDelegate
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
guard qrCodeScannerReady == true else {
return
}
// Check if the metadataObjects array is not nil and it contains at least one object.
if metadataObjects == nil || metadataObjects.count == 0 {
qrCodeFrameView?.frame = CGRect.zero
return
}
// Get the metadata object.
let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
// Here we use filter method to check if the type of metadataObj is supported
// Instead of hardcoding the AVMetadataObjectTypeQRCode, we check if the type
// can be found in the array of supported bar codes.
if supportedBarCodes.contains(metadataObj.type) {
// If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds
let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
qrCodeFrameView?.frame = barCodeObject!.bounds
if let qrCode = metadataObj.stringValue {
qrCodeScannerReady = false
self.processScannedCode(qrCode)
}
}
}
private func processScannedCode(_ qrCode: String) {
ConnectManager.sharedInstance.qrcodeScanned(qrCode)
qrCodeScanned = true
// telemetry
if let openTime = viewOpenTime {
let duration = Int(Date.getCurrentMillis() - openTime)
self.logTelemetrySignal("scan", customData: ["view": "scan_intro", "scan_duration": duration])
}
// give user some time to notice the action, as scanning is done very quickly
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { [weak self] in
self?.navigationController?.popViewController(animated: true)
})
}
// MARK: - Telemetry
private func logTelemetrySignal(_ action: String, customData: [String: Any]) {
let signal = TelemetryLogEventType.Connect(action, customData)
TelemetryLogger.sharedInstance.logEvent(signal)
}
}
|
mpl-2.0
|
99c97d3577e1c0dce215bd1a9b1d7c00
| 45.008696 | 253 | 0.660461 | 5.68619 | false | false | false | false |
adamgraham/STween
|
STween/STween/Tweening/Extensions/Tween+Chaining.swift
|
1
|
4607
|
//
// Tween+Chaining.swift
// STween
//
// Created by Adam Graham on 6/20/16.
// Copyright © 2016 Adam Graham. All rights reserved.
//
import Foundation
/**
Provides method chaining to a tween. This allows multiple properties to be assigned in
a single statement without requiring a variable to store the intermediate results.
```
view.tween(to: ...)
.duration(1.0)
.ease(.backOut)
.onComplete({ ... })
```
*/
public extension Tween {
// MARK: Chaining Methods
/// Assigns a value to the `ease` property of the tween.
/// - parameter value: The `Ease` value to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func ease(_ value: Ease) -> Tween {
self.ease = value
return self
}
/// Assigns a value to the `delay` property of the tween.
/// - parameter value: The amount of seconds to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func delay(_ value: TimeInterval) -> Tween {
self.delay = value
return self
}
/// Assigns a value to the `duration` property of the tween.
/// - parameter value: The amount of seconds to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func duration(_ value: TimeInterval) -> Tween {
self.duration = value
return self
}
/// Assigns a value to the `onUpdate` property of the tween.
/// - parameter value: The callback closure to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func onUpdate(_ callback: @escaping Callback) -> Tween {
self.onUpdate = callback
return self
}
/// Assigns a value to the `onStart` property of the tween.
/// - parameter value: The callback closure to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func onStart(_ callback: @escaping Callback) -> Tween {
self.onStart = callback
return self
}
/// Assigns a value to the `onStop` property of the tween.
/// - parameter value: The callback closure to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func onStop(_ callback: @escaping Callback) -> Tween {
self.onStop = callback
return self
}
/// Assigns a value to the `onRestart` property of the tween.
/// - parameter value: The callback closure to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func onRestart(_ callback: @escaping Callback) -> Tween {
self.onRestart = callback
return self
}
/// Assigns a value to the `onPause` property of the tween.
/// - parameter value: The callback closure to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func onPause(_ callback: @escaping Callback) -> Tween {
self.onPause = callback
return self
}
/// Assigns a value to the `onResume` property of the tween.
/// - parameter value: The callback closure to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func onResume(_ callback: @escaping Callback) -> Tween {
self.onResume = callback
return self
}
/// Assigns a value to the `onComplete` property of the tween.
/// - parameter value: The callback closure to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func onComplete(_ callback: @escaping Callback) -> Tween {
self.onComplete = callback
return self
}
/// Assigns a value to the `onKill` property of the tween.
/// - parameter value: The callback closure to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func onKill(_ callback: @escaping Callback) -> Tween {
self.onKill = callback
return self
}
/// Assigns a value to the `onRevive` property of the tween.
/// - parameter value: The callback closure to be assigned.
/// - returns: The current tween to allow for additional customization.
@discardableResult
func onRevive(_ callback: @escaping Callback) -> Tween {
self.onRevive = callback
return self
}
}
|
mit
|
5cf4cf1d5cbec0608878f409d93816f1
| 33.373134 | 87 | 0.657186 | 4.7 | false | false | false | false |
khizkhiz/swift
|
test/decl/func/keyword-argument-labels.swift
|
4
|
1167
|
// RUN: %target-parse-verify-swift
struct SomeRange { }
// Function declarations.
func paramName(func: Int, in: SomeRange) { }
func firstArgumentLabelWithParamName(in range: SomeRange) { }
func firstArgumentLabelWithParamName2(range in: SomeRange) { }
func escapedInout(`inout` value: SomeRange) { }
struct SomeType {
// Initializers
init(func: () -> ()) { }
init(init func: () -> ()) { }
// Subscripts
subscript (class index: AnyClass) -> Int {
return 0
}
subscript (class: AnyClass) -> Int {
return 0
}
subscript (struct: Any.Type) -> Int {
return 0
}
}
class SomeClass { }
// Function types.
typealias functionType = (in: SomeRange) -> Bool
// Calls
func testCalls(range: SomeRange) {
paramName(0, in: range)
firstArgumentLabelWithParamName(in: range)
firstArgumentLabelWithParamName2(range: range)
var st = SomeType(func: {})
st = SomeType(init: {})
_ = st[class: SomeClass.self]
_ = st[SomeClass.self]
_ = st[SomeType.self]
escapedInout(`inout`: range)
// Fix-Its
paramName(0, `in`: range) // expected-warning{{keyword 'in' does not need to be escaped in argument list}}{{16-17=}}{{19-20=}}
}
|
apache-2.0
|
e40fdaf5c368d1c2aa8254b4aea8750c
| 21.882353 | 128 | 0.660668 | 3.557927 | false | false | false | false |
akkakks/firefox-ios
|
Client/Frontend/Browser/OpenSearch.swift
|
2
|
6781
|
/* 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 UIKit
private let TypeSearch = "text/html"
private let TypeSuggest = "application/x-suggestions+json"
class OpenSearchEngine {
let shortName: String
let description: String?
let image: UIImage?
private let searchTemplate: String
private let suggestTemplate: String?
init(shortName: String, description: String?, image: UIImage?, searchTemplate: String, suggestTemplate: String?) {
self.shortName = shortName
self.description = description
self.image = image
self.searchTemplate = searchTemplate
self.suggestTemplate = suggestTemplate
}
/**
* Returns the search URL for the given query.
*/
func searchURLForQuery(query: String) -> NSURL? {
return getURLFromTemplate(searchTemplate, query: query)
}
/**
* Returns the search suggestion URL for the given query.
*/
func suggestURLForQuery(query: String) -> NSURL? {
if let suggestTemplate = suggestTemplate {
return getURLFromTemplate(suggestTemplate, query: query)
}
return nil
}
private func getURLFromTemplate(searchTemplate: String, query: String) -> NSURL? {
if let escapedQuery = query.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
let urlString = searchTemplate.stringByReplacingOccurrencesOfString("{searchTerms}", withString: escapedQuery, options: NSStringCompareOptions.LiteralSearch, range: nil)
return NSURL(string: urlString)
}
return nil
}
}
/**
* OpenSearch XML parser.
*
* This parser accepts standards-compliant OpenSearch 1.1 XML documents in addition to
* the Firefox-specific search plugin format.
*
* OpenSearch spec: http://www.opensearch.org/Specifications/OpenSearch/1.1
*/
class OpenSearchParser {
private let pluginMode: Bool
init(pluginMode: Bool) {
self.pluginMode = pluginMode
}
func parse(file: String) -> OpenSearchEngine? {
let data = NSData(contentsOfFile: file)
if data == nil {
println("Invalid search file")
return nil
}
let rootName = pluginMode ? "SearchPlugin" : "OpenSearchDescription"
let docIndexer: XMLIndexer! = SWXMLHash.parse(data!)[rootName][0]
if docIndexer.element == nil {
println("Invalid XML document")
return nil
}
let shortNameIndexer = docIndexer["ShortName"]
if shortNameIndexer.all.count != 1 {
println("ShortName must appear exactly once")
return nil
}
let shortName = shortNameIndexer.element?.text
if shortName == nil {
println("ShortName must contain text")
return nil
}
let descriptionIndexer = docIndexer["Description"]
if !pluginMode && descriptionIndexer.all.count != 1 {
println("Description must appear exactly once")
return nil
}
let description = descriptionIndexer.element?.text
var urlIndexers = docIndexer["Url"].all
if urlIndexers.isEmpty {
println("Url must appear at least once")
return nil
}
var searchTemplate: String!
var suggestTemplate: String?
for urlIndexer in urlIndexers {
let type = urlIndexer.element?.attributes["type"]
if type == nil {
println("Url element requires a type attribute")
return nil
}
if type != TypeSearch && type != TypeSuggest {
// Not a supported search type.
continue
}
var template = urlIndexer.element?.attributes["template"]
if template == nil {
println("Url element requires a template attribute")
return nil
}
if pluginMode {
var paramIndexers = urlIndexer["Param"].all
if !paramIndexers.isEmpty {
template! += "?"
var firstAdded = false
for paramIndexer in paramIndexers {
if firstAdded {
template! += "&"
} else {
firstAdded = true
}
let name = paramIndexer.element?.attributes["name"]
let value = paramIndexer.element?.attributes["value"]
if name == nil || value == nil {
println("Param element must have name and value attributes")
return nil
}
template! += name! + "=" + value!
}
}
}
if type == TypeSearch {
searchTemplate = template
} else {
suggestTemplate = template
}
}
if searchTemplate == nil {
println("Search engine must have a text/html type")
return nil
}
var uiImage: UIImage?
var imageIndexers = docIndexer["Image"].all
for imageIndexer in imageIndexers {
// TODO: For now, we only look for 16x16 search icons.
let imageWidth = imageIndexer.element?.attributes["width"]
let imageHeight = imageIndexer.element?.attributes["height"]
if imageWidth?.toInt() != 16 || imageHeight?.toInt() != 16 {
continue
}
if imageIndexer.element?.text == nil {
continue
}
let imageURL = NSURL(string: imageIndexer.element!.text!)
if let imageURL = imageURL {
let imageData = NSData(contentsOfURL: imageURL)
if let imageData = imageData {
let image = UIImage(data: imageData)
if let image = image {
uiImage = image
} else {
println("Error: Invalid search image data")
}
} else {
println("Error: Invalid search image data")
}
} else {
println("Error: Invalid search image data")
}
}
return OpenSearchEngine(shortName: shortName!, description: description, image: uiImage, searchTemplate: searchTemplate, suggestTemplate: suggestTemplate)
}
}
|
mpl-2.0
|
1b50ceed23afc922b88be7717369248d
| 32.741294 | 181 | 0.559947 | 5.530995 | false | false | false | false |
airander/redis-framework
|
Redis-Framework/Redis-Framework/RedisClient+Hashes.swift
|
1
|
14412
|
//
// RedisClient+Hashes.swift
// Redis-Framework
//
// Copyright (c) 2015, Eric Orion Anderson
// 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.
//
// 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 Foundation
extension RedisClient {
/// HDEL key field [field ...]
///
/// Removes the specified fields from the hash stored at key. Specified fields that do not exist within this hash are ignored.
/// If key does not exist, it is treated as an empty hash and this command returns 0.
///
/// - returns: Integer reply: the number of fields that were removed from the hash, not including specified but non existing fields.
public func hDel(key:String, fields:[String], completionHandler:@escaping RedisCommandIntegerBlock) {
var command = "HDEL \(RESPUtilities.respString(from: key))"
for field in fields {
command = command + " \(RESPUtilities.respString(from: field))"
}
self.send(command, completionHandler: completionHandler)
}
/// HEXISTS key field
///
/// Returns if field is an existing field in the hash stored at key.
///
/// - returns: Integer reply, specifically: 1 if the hash contains field. 0 if the hash does not contain field, or key does not exist.
public func hExists(key:String, field:String, completionHandler:@escaping RedisCommandIntegerBlock) {
self.send("HEXISTS \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: field))", completionHandler: completionHandler)
}
/// HGET key field
///
/// Returns the value associated with field in the hash stored at key.
///
/// - returns: Bulk string reply: the value associated with field, or nil when field is not present in the hash or key does not exist.
public func hGet(key:String, field:String, completionHandler:@escaping RedisCommandStringBlock) {
self.send("HGET \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: field))", completionHandler: completionHandler)
}
/// HGETALL key
///
/// Returns all fields and values of the hash stored at key. In the returned value, every field name is followed by its value,
/// so the length of the reply is twice the size of the hash.
///
/// - returns: Array reply: list of fields and their values stored in the hash, or an empty list when key does not exist.
public func hGetAll(_ key:String, completionHandler:@escaping RedisCommandArrayBlock) {
self.send("HGETALL \(RESPUtilities.respString(from: key))", completionHandler: completionHandler)
}
///// HSTRLEN key field
/////
///// Returns the string length of the value associated with field in the hash stored at key. If the key or the field do not exist, 0 is returned.
/////
///// - returns: Integer reply: the string length of the value associated with field, or zero when field is not present in the hash or key does not exist at all.
// public func hStrlen(key:String, field:String, completionHandler:RedisCommandIntegerBlock)
// {
// self.send("HSTRLEN \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: field))", completionHandler: completionHandler)
// }
/// HINCRBY key field increment
///
/// Increments the number stored at field in the hash stored at key by increment. If key does not exist, a new key holding a hash is created. If field does not exist the value is set to 0 before the operation is performed.
/// The range of values supported by HINCRBY is limited to 64 bit signed integers.
///
/// - returns: Integer reply: the value at field after the increment operation.
public func hIncr(key:String, field:String, increment:Int, completionHandler:@escaping RedisCommandIntegerBlock) {
self.send("HINCRBY \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: field)) \(increment)", completionHandler: completionHandler)
}
/// HINCRBYFLOAT key field increment
///
/// Increment the specified field of an hash stored at key, and representing a floating point number, by the specified increment.
/// If the field does not exist, it is set to 0 before performing the operation. An error is returned if one of the following conditions occur:
/// The field contains a value of the wrong type (not a string).
/// The current field content or the specified increment are not parsable as a double precision floating point number.
/// The exact behavior of this command is identical to the one of the INCRBYFLOAT command, please refer to the documentation of INCRBYFLOAT for further information.
///
/// - returns: Bulk string reply: the value of field after the increment.
public func hIncr(key:String, field:String, increment:Double, completionHandler:@escaping RedisCommandStringBlock) {
self.send("HINCRBYFLOAT \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: field)) \(increment)", completionHandler: completionHandler)
}
/// HKEYS key
///
/// Returns all field names in the hash stored at key.
///
/// - returns: Array reply: list of fields in the hash, or an empty list when key does not exist.
public func hKeys(key:String, completionHandler:@escaping RedisCommandArrayBlock) {
self.send("HKEYS \(RESPUtilities.respString(from: key))", completionHandler: completionHandler)
}
/// HLEN key
///
/// Returns the number of fields contained in the hash stored at key.
///
/// - returns: Integer reply: number of fields in the hash, or 0 when key does not exist.
public func hLen(key:String, completionHandler:@escaping RedisCommandIntegerBlock) {
self.send("HLEN \(RESPUtilities.respString(from: key))", completionHandler: completionHandler)
}
/// HMGET key field [field ...]
///
/// Returns the values associated with the specified fields in the hash stored at key.
/// For every field that does not exist in the hash, a nil value is returned. Because a non-existing keys are treated as empty hashes,
/// running HMGET against a non-existing key will return a list of nil values.
///
/// - returns: Array reply: list of values associated with the given fields, in the same order as they are requested.
public func hMGet(key:String, fields:[String], completionHandler:@escaping RedisCommandArrayBlock)
{
var command = "HMGET \(RESPUtilities.respString(from: key))"
for field:String in fields {
command = command + " \(RESPUtilities.respString(from: field))"
}
self.send(command, completionHandler: completionHandler)
}
/// HMSET key field value [field value ...]
///
/// Sets the specified fields to their respective values in the hash stored at key. This command overwrites any existing fields in the hash.
/// If key does not exist, a new key holding a hash is created.
///
/// - returns: Simple string reply
public func hMSet(key:String, fieldAndValues:[(field:String, value:String)], completionHandler:@escaping RedisCommandStringBlock)
{
var command = "HMSET \(RESPUtilities.respString(from: key))"
for (field, value): (String, String) in fieldAndValues {
command = command + " \(RESPUtilities.respString(from: field)) \(RESPUtilities.respString(from: value))"
}
self.send(command, completionHandler: completionHandler)
}
/// HSET key field value
///
/// Sets field in the hash stored at key to value. If key does not exist, a new key holding a hash is created. If field already exists in the hash, it is overwritten.
///
/// - returns: Integer reply, specifically: 1 if field is a new field in the hash and value was set. 0 if field already exists in the hash and the value was updated.
public func hSet(key:String, field:String, value:String, completionHandler:@escaping RedisCommandIntegerBlock) {
self.send("HSET \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: field)) \(RESPUtilities.respString(from: value))", completionHandler: completionHandler)
}
/// HSETNX key field value
///
/// Sets field in the hash stored at key to value, only if field does not yet exist. If key does not exist, a new key holding a hash is created. If field already exists, this operation has no effect.
///
/// - returns: Integer reply, specifically: 1 if field is a new field in the hash and value was set. 0 if field already exists in the hash and no operation was performed.
public func hSetNX(key:String, field:String, value:String, completionHandler:@escaping RedisCommandIntegerBlock) {
self.send("HSETNX \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: field)) \(RESPUtilities.respString(from: value))", completionHandler: completionHandler)
}
/// HVALS key
///
/// Returns all values in the hash stored at key.
///
/// - returns: Array reply: list of values in the hash, or an empty list when key does not exist.
public func hVals(key:String, completionHandler:@escaping RedisCommandArrayBlock) {
self.send("HVALS \(RESPUtilities.respString(from: key))", completionHandler: completionHandler)
}
/// HSCAN key cursor [MATCH pattern] [COUNT count]
///
/// HSCAN basic usage
///
/// HSCAN is a cursor based iterator. This means that at every call of the command, the server returns an updated cursor that the user
/// needs to use as the cursor argument in the next call.
///
/// Scan guarantees
///
/// The HSCAN command, and the other commands in the SCAN family, are able to provide to the user a set of guarantees associated to full iterations.
/// A full iteration always retrieves all the elements that were present in the collection from the start to the end of a full iteration.
/// This means that if a given element is inside the collection when an iteration is started, and is still there when an iteration terminates,
/// then at some point SCAN returned it to the user.
/// A full iteration never returns any element that was NOT present in the collection from the start to the end of a full iteration.
/// So if an element was removed before the start of an iteration, and is never added back to the collection for all the time an iteration lasts,
/// SCAN ensures that this element will never be returned.
///
/// Number of elements returned at every SCAN call
///
/// SCAN family functions do not guarantee that the number of elements returned per call are in a given range.
/// The commands are also allowed to return zero elements, and the client should not consider the iteration complete as long as the returned cursor is not zero.
///
/// The COUNT option
///
/// While HSCAN does not provide guarantees about the number of elements returned at every iteration,
/// it is possible to empirically adjust the behavior of SCAN using the COUNT option.
/// Basically with COUNT the user specified the amount of work that should be done at every call in order to retrieve elements from the collection.
/// This is just an hint for the implementation, however generally speaking this is what you could expect most of the times from the implementation.
/// The default COUNT value is 10.
/// When iterating the key space, or a Set, Hash or Sorted Set that is big enough to be represented by an hash table, assuming no MATCH option is used,
/// the server will usually return count or a bit more than count elements per call.
/// When iterating Sets encoded as intsets (small sets composed of just integers), or Hashes and Sorted Sets encoded as ziplists
/// (small hashes and sets composed of small individual values), usually all the elements are returned in the first SCAN call regardless of the COUNT value.
///
/// The MATCH option
///
/// It is possible to only iterate elements matching a given glob-style pattern, similarly to the behavior of the KEYS command that takes a pattern as only argument.
/// To do so, just append the MATCH <pattern> arguments at the end of the SCAN command (it works with all the SCAN family commands).
///
/// - returns: HSCAN return a two elements multi-bulk reply, where the first element is a string representing an unsigned 64 bit number (the cursor), and the second element is a multi-bulk with an array of elements. HSCAN array of elements is a list of keys.
public func hScan(key:String, cursor:UInt, pattern:String? = nil, count:UInt? = nil, completionHandler:@escaping RedisCommandArrayBlock) {
var command:String = "HSCAN \(RESPUtilities.respString(from: key)) \(cursor)"
if let pattern = pattern {
command = command + " MATCH \(RESPUtilities.respString(from: pattern))"
}
if let count = count {
command = command + " COUNT \(count)"
}
self.send(command, completionHandler: completionHandler)
}
}
|
bsd-2-clause
|
33e997802a9ca6a51198059abe218c39
| 60.589744 | 262 | 0.70698 | 4.505158 | false | false | false | false |
TJRoger/Go-RSS
|
Go RSS/SourceTableViewController.swift
|
1
|
3464
|
//
// SourceTableViewController.swift
// Go RSS
//
// Created by Roger on 7/22/15.
// Copyright (c) 2015 Roger. All rights reserved.
//
import UIKit
class SourceTableViewController: UITableViewController {
var objects: [RSSSource]?
override func viewDidLoad() {
super.viewDidLoad()
// self.tableView.registerClass(SourceTableViewCell.self, forCellReuseIdentifier: "sourceCell")
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return objects?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("sourceCell", forIndexPath: indexPath) as! SourceTableViewCell
// Configure the cell...
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
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 to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
5a0d888779e544cd8a77e8e52681f7c5
| 33.64 | 157 | 0.685912 | 5.533546 | false | false | false | false |
skyefreeman/OnTap
|
OnTap/Classes/UIBarButtonItem+OnTap.swift
|
1
|
1904
|
//
// UIBarButtonItem+OnTap.swift
// OnTap
//
// Created by Skye Freeman on 1/27/17.
// Copyright © 2017 Skye Freeman. All rights reserved.
//
import UIKit
public extension UIBarButtonItem {
@discardableResult func onTap(completion: @escaping OTStandardClosure) -> Self {
touchHandler?.onTap = completion
return self
}
convenience init(barButtonSystemItem: UIBarButtonSystemItem, onTap: @escaping OTStandardClosure) {
self.init(barButtonSystemItem: barButtonSystemItem, target: nil, action: nil)
touchHandler = UIBarButtonItemTouchHandler(barButtonItem: self, onTap: onTap)
}
convenience init(image: UIImage?, style: UIBarButtonItemStyle, onTap: @escaping OTStandardClosure) {
self.init(image: image, style: style, target: nil, action: nil)
touchHandler = UIBarButtonItemTouchHandler(barButtonItem: self, onTap: onTap)
}
convenience init(title: String?, style: UIBarButtonItemStyle, onTap: @escaping OTStandardClosure) {
self.init(title: title, style: style, target: nil, action: nil)
touchHandler = UIBarButtonItemTouchHandler(barButtonItem: self, onTap: onTap)
}
// MARK: Private
private struct AssociatedKeys {
static var touchHandlerKey = "OTBarButtonTouchHandlerKey"
}
private var touchHandler: UIBarButtonItemTouchHandler? {
get {
if let handler = objc_getAssociatedObject(self, &AssociatedKeys.touchHandlerKey) as? UIBarButtonItemTouchHandler? {
return handler
} else {
self.touchHandler = UIBarButtonItemTouchHandler(barButtonItem: self, onTap: nil)
return self.touchHandler
}
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.touchHandlerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
|
mit
|
6259b0785ddbe6604bd49d0c8f72241e
| 35.596154 | 128 | 0.674724 | 4.817722 | false | false | false | false |
aktowns/swen
|
Sources/Swen/Physics/PhyBoundingBox.swift
|
1
|
1798
|
//
// PhyBoundingBox.swift created on 2/01/16
// Swen project
//
// Copyright 2016 Ashley Towns <[email protected]>
//
// 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 CChipmunk
public final class PhyBoundingBox {
public let handle: cpBB
public init(fromHandle handle: cpBB) {
self.handle = handle
}
public convenience init(rect: Rect) {
let bb = cpBBNew(rect.x, rect.y, rect.sizeX, rect.sizeY)
self.init(fromHandle: bb)
}
public convenience init(size: Size) {
let bb = cpBBNew(0, 0, size.sizeX, size.sizeY)
self.init(fromHandle: bb)
}
public convenience init(p: Vector, r: Double) {
let bb = cpBBNewForCircle(cpVect.fromVector(p), r)
self.init(fromHandle: bb)
}
public func intersects(b: PhyBoundingBox) -> Bool {
return cpBBIntersects(self.handle, b.handle) == PhyMisc.cpTrue
}
public func contains(b: PhyBoundingBox) -> Bool {
return cpBBContainsBB(self.handle, b.handle) == PhyMisc.cpTrue
}
public func merge(b: PhyBoundingBox) -> PhyBoundingBox {
return PhyBoundingBox(fromHandle: cpBBMerge(self.handle, b.handle))
}
public var center: Vector {
return cpBBCenter(self.handle).toVector()
}
public var area: Double {
return cpBBArea(self.handle)
}
}
|
apache-2.0
|
9edf14941029b6f5a4e8a471aee438df
| 26.242424 | 77 | 0.695773 | 3.437859 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.