repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
el-hoshino/NotAutoLayout | Sources/NotAutoLayout/LayoutMaker/IndividualProperties/2-Element/CenterBottom.Individual.swift | 1 | 1988 | //
// CenterBottom.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct CenterBottom {
let center: LayoutElement.Horizontal
let bottom: LayoutElement.Vertical
}
}
// MARK: - Make Frame
extension IndividualProperty.CenterBottom {
private func makeFrame(center: Float, bottom: Float, size: Size) -> Rect {
let left = center - size.width.half
let top = bottom - size.height
let origin = Point(x: left, y: top)
let size = size
let frame = Rect(origin: origin, size: size)
return frame
}
}
// MARK: - Set A Size -
// MARK: Size
extension IndividualProperty.CenterBottom: LayoutPropertyCanStoreSizeToEvaluateFrameType {
public func evaluateFrame(size: LayoutElement.Size, parameters: IndividualFrameCalculationParameters) -> Rect {
let center = self.center.evaluated(from: parameters)
let bottom = self.bottom.evaluated(from: parameters)
let size = size.evaluated(from: parameters)
return self.makeFrame(center: center, bottom: bottom, size: size)
}
}
// MARK: - Set A Length -
// MARK: Width
extension IndividualProperty.CenterBottom: LayoutPropertyCanStoreWidthType {
public func storeWidth(_ width: LayoutElement.Length) -> IndividualProperty.CenterBottomWidth {
let centerBottomWidth = IndividualProperty.CenterBottomWidth(center: self.center,
bottom: self.bottom,
width: width)
return centerBottomWidth
}
}
// MARK: Height
extension IndividualProperty.CenterBottom: LayoutPropertyCanStoreHeightType {
public func storeHeight(_ height: LayoutElement.Length) -> IndividualProperty.CenterBottomHeight {
let centerBottomHeight = IndividualProperty.CenterBottomHeight(center: self.center,
bottom: self.bottom,
height: height)
return centerBottomHeight
}
}
| apache-2.0 | 3a782eae01a6fb21a39cc24baad744d1 | 22.211765 | 112 | 0.7111 | 4.197872 | false | false | false | false |
landakram/kiwi | Kiwi/AppDelegate.swift | 1 | 11526 | //
// AppDelegate.swift
// Kiwi
//
// Created by Mark Hudnall on 2/24/15.
// Copyright (c) 2015 Mark Hudnall. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
import SwiftyDropbox
import AMScrollingNavbar
import YapDatabase
import RxSwift
import SwiftMessages
import Reachability
import RxReachability
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var filesystem: Filesystem = Filesystem.sharedInstance
var syncEngine: SyncEngine = SyncEngine.sharedInstance
var indexer: Indexer = Indexer.sharedInstance
var disposeBag: DisposeBag = DisposeBag()
var reachability: Reachability?
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
Fabric.with([Crashlytics.self])
DropboxClientsManager.setupWithAppKey(DropboxAppKey)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootNavigationController = storyboard.instantiateViewController(withIdentifier: "RootNavigationController") as? ScrollingNavigationController
let didDeleteApp = DropboxClientsManager.authorizedClient != nil && self.isLoadingForFirstTime()
if didDeleteApp {
DropboxClientsManager.unlinkClients()
}
if let client = DropboxClientsManager.authorizedClient {
syncEngine.remote.configure(client: client)
self.syncEngine.sweep()
reachability = Reachability()
try? reachability?.startNotifier()
reachability?.rx.isConnected
.subscribe(onNext: {
self.syncEngine.sweep()
})
.addDisposableTo(disposeBag)
let rootViewController = storyboard.instantiateViewController(withIdentifier: "WikiViewControllerIdentifier") as? WikiViewController
rootNavigationController?.viewControllers = [rootViewController!]
} else if self.isUpdating() {
let conn = Yap.sharedInstance.newConnection()
conn.readWrite({ (t: YapDatabaseReadWriteTransaction) in
t.removeAllObjectsInAllCollections()
})
let rootViewController = storyboard.instantiateViewController(withIdentifier: "LinkWithDropboxIdentifier") as? LinkWithDropboxViewController
rootViewController?.upgradingFromV1 = true
rootNavigationController?.viewControllers = [rootViewController!]
} else {
let rootViewController = storyboard.instantiateViewController(withIdentifier: "LinkWithDropboxIdentifier") as? LinkWithDropboxViewController
rootNavigationController?.viewControllers = [rootViewController!]
}
let deadlineTime = DispatchTime.now() + .seconds(3)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
self.markVersion()
}
setUpStatusBarMessages()
self.window?.rootViewController = rootNavigationController
self.window?.makeKeyAndVisible()
let kiwiColor = Constants.KiwiColor
UIToolbar.appearance().tintColor = kiwiColor
UINavigationBar.appearance().tintColor = kiwiColor
UISearchBar.appearance().tintColor = kiwiColor
UITextField.appearance().tintColor = kiwiColor
UITextView.appearance().tintColor = kiwiColor
UINavigationBar.appearance().titleTextAttributes = [
NSAttributedStringKey.foregroundColor: UINavigationBar.appearance().tintColor,
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 0),
]
return true
}
func setUpStatusBarMessages() {
let view = MessageView.viewFromNib(layout: .statusLine)
var config = SwiftMessages.Config()
config.presentationContext = .window(windowLevel: UIWindowLevelStatusBar)
config.duration = .indefinite(delay: 0, minimum: 1)
var lastPushFilename: String? = nil
var lastPullFilename: String? = nil
self.syncEngine.events.subscribe(onNext: { (o: Operations) in
switch o {
case .PullOperation(let operation):
switch operation.event {
case .write(let path):
let filename = path.fileName
lastPullFilename = filename
operation.stream.subscribe(onNext: { (e: Either<Progress, Path>) in
switch e {
case .left( _):
// When a file is pushed, it is then pulled right after.
// This not-so-gracefully prevents ths subsequent pull message
// from showing
if lastPushFilename != filename {
view.configureContent(body: "Downloading \(filename)...")
SwiftMessages.show(config: config, view: view)
}
case .right( _):
SwiftMessages.hide(id: view.id)
break
}
// Reset the lastPullFilename after a few seconds
// This way, we still show notifications if a remote
// file is changed repeatedly.
let deadlineTime = DispatchTime.now() + .seconds(3)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
if lastPullFilename == filename {
lastPullFilename = nil
}
}
}, onCompleted: {
SwiftMessages.hide(id: view.id)
}).disposed(by: self.disposeBag)
default: break
}
case .PushOperation(let operation):
switch operation.event {
case .write(let path):
let filename = path.fileName
lastPushFilename = filename
operation.stream.subscribe(onNext: { (e: Either<Progress, Path>) in
switch e {
case .left(_):
if lastPullFilename != filename {
view.configureContent(body: "Uploading \(filename)...")
SwiftMessages.show(config: config, view: view)
}
case .right(_): break
}
let deadlineTime = DispatchTime.now() + .seconds(3)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
if lastPushFilename == filename {
lastPushFilename = nil
}
}
}, onCompleted: {
SwiftMessages.hide(id: view.id)
}).disposed(by: self.disposeBag)
default: break
}
}
}).disposed(by: self.disposeBag)
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
if let client = DropboxClientsManager.authorizedClient {
syncEngine.remote.configure(client: client)
self.syncEngine.sweep()
}
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
if let authResult = DropboxClientsManager.handleRedirectURL(url) {
switch authResult {
case .success:
print("Success! User is logged into Dropbox.")
case .cancel:
print("Authorization flow was manually canceled by user!")
case .error(_, let description):
print("Error: \(description)")
}
EventBus.sharedInstance.publish(event: .AccountLinked(authResult: authResult))
}
return true
}
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
if self.isUpdating() || self.isLoadingForFirstTime() {
print("Not restoring state")
return false
}
print("Restoring state")
return true
}
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
return true
}
func isLoadingForFirstTime() -> Bool {
return !UserDefaults.standard.bool(forKey: "didLoadFirstTime")
}
func markVersion() {
let defaults = UserDefaults.standard
let currentAppVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
defaults.set(currentAppVersion, forKey: "appVersion")
}
func isUpdating() -> Bool {
let defaults = UserDefaults.standard
let currentAppVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let previousVersion = defaults.string(forKey: "appVersion")
if previousVersion == nil && self.isLoadingForFirstTime() {
// first launch
return false
} else if previousVersion == nil && !self.isLoadingForFirstTime() {
// First time setting the app version
return true
}
else if previousVersion == currentAppVersion {
// same version
return false
} else {
// other version
return true
}
}
}
| mit | 2e78c30b8332414a19514aeb2992a5f9 | 43.16092 | 285 | 0.59908 | 6.216828 | false | false | false | false |
jokechat/swift3-novel | swift_novels/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallGridBeat.swift | 8 | 2067 | //
// NVActivityIndicatorAnimationBallGridBeat.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/24/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationBallGridBeat: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
let circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let durations = [0.96, 0.93, 1.19, 1.13, 1.34, 0.94, 1.2, 0.82, 1.19]
let beginTime = CACurrentMediaTime()
let beginTimes = [0.36, 0.4, 0.68, 0.41, 0.71, -0.15, -0.12, 0.01, 0.32]
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
// Animation
let animation = CAKeyframeAnimation(keyPath: "opacity")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.7, 1]
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circles
for i in 0 ..< 3 {
for j in 0 ..< 3 {
let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(j) + circleSpacing * CGFloat(j),
y: y + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
width: circleSize,
height: circleSize)
animation.duration = durations[3 * i + j]
animation.beginTime = beginTime + beginTimes[3 * i + j]
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
}
| apache-2.0 | 3425f917f244d373ab5faf4095ed49e5 | 41.183673 | 137 | 0.576681 | 4.5131 | false | false | false | false |
cyrilde/IPCSocket | Sources/IPCSocket.swift | 1 | 4551 | // Copyright © 2017 Cyril Deba
//
// 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 Darwin
import Foundation
public class IPCSocket {
// MARK: Public Constants
public static let INVALID_FD = Int32(-1)
public static let INVALID_PATH = ""
// MARK: Public Properties
public internal(set) var fd: Int32 = INVALID_FD
public internal(set) var path:String = INVALID_PATH
public internal(set) var isConnected: Bool = false
// MARK: Lifecycle
public init(with path: String) throws {
try verifyPath(path)
self.path = path
self.fd = Darwin.socket(Int32(AF_UNIX), SOCK_STREAM, Int32(0))
if self.fd == IPCSocket.INVALID_FD {
throw IPCError.unableCreateSocket
}
}
deinit {
if self.fd != IPCSocket.INVALID_FD {
disconnect()
}
}
// MARK: Public Functions
public func connect() throws {
if isConnected {
throw IPCError.alreadyConnected
}
let address = getSocketAddress()
let addressLength = getSocketAddressLength()
defer {
address.deallocate(capacity: addressLength)
}
let result = address.withMemoryRebound(to: sockaddr.self, capacity: 1) {
(addressPointer:UnsafeMutablePointer<sockaddr>) -> Int32 in
return Darwin.connect(self.fd, addressPointer, socklen_t(addressLength))
}
if result < 0 {
throw IPCError.connectFailed
}
isConnected = true
}
public func disconnect() {
if self.fd != IPCSocket.INVALID_FD {
_ = Darwin.close(self.fd)
self.fd = IPCSocket.INVALID_FD
self.path = IPCSocket.INVALID_PATH
isConnected = false
}
}
public func write(from data: Data) throws -> Int {
if !self.isConnected {
throw IPCError.notConnected
}
if data.count == 0 {
return 0
}
return try data.withUnsafeBytes() { (dataPointer: UnsafePointer<UInt8>) throws -> Int in
var bytesSent = 0
while bytesSent < data.count {
let bytesSentChunk = Darwin.send(self.fd, dataPointer.advanced(by: bytesSent), Int(data.count - bytesSent), 0)
if bytesSentChunk < 0 {
throw IPCError.writeFailed
}
bytesSent += bytesSentChunk
}
return bytesSent
}
}
public func read() throws -> Data {
if !self.isConnected {
throw IPCError.notConnected
}
var buffer = [UInt8](repeating: 0, count: 1024)
var counter = Darwin.recv(self.fd, &buffer, 1024, Int32(MSG_WAITALL))
if counter < 0 {
throw IPCError.readFailed
}
let bufferPointer = UnsafeMutablePointer<UInt8>(UnsafeMutablePointer(mutating: buffer))
return Data(bytesNoCopy: bufferPointer, count: counter, deallocator: .none)
}
// MARK: Private Functions
private func verifyPath(_ path: String) throws {
guard path.isNotBlank else {
throw IPCError.malformedPath(details: "Path cannot be empty or blank")
}
}
private func getSocketAddress() -> UnsafeMutablePointer<UInt8>{
let address = UnsafeMutablePointer<UInt8>.allocate(capacity: getSocketAddressLength())
address[0] = UInt8(MemoryLayout<sockaddr_un>.size)
address[1] = UInt8(AF_UNIX)
memcpy(address + 2, Array<UInt8>(path.utf8), path.length)
return address
}
func getSocketAddressLength() -> Int {
return MemoryLayout<UInt8>.size + MemoryLayout<sa_family_t>.size + path.length
}
}
| apache-2.0 | 70f42ab361630a222562f1eeb24f4083 | 27.616352 | 126 | 0.571648 | 4.835282 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/Examples/OSX/MidiMonitor/MidiMonitor/ViewController.swift | 1 | 3378 | //
// ViewController.swift
// MidiMonitor
//
// Created by Aurelius Prochazka on 4/29/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Cocoa
import AudioKit
class ViewController: NSViewController, AKMIDIListener {
@IBOutlet var outputTextView: NSTextView!
@IBOutlet var sourcePopUpButton: NSPopUpButton!
var midi = AKMIDI()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
midi.openInput("Session 1")
midi.addListener(self)
sourcePopUpButton.removeAllItems()
sourcePopUpButton.addItemsWithTitles(midi.inputNames)
}
@IBAction func sourceChanged(sender: NSPopUpButton) {
midi.openInput(midi.inputNames[sender.indexOfSelectedItem])
}
func receivedMIDINoteOn(note: Int, velocity: Int, channel: Int) {
var newString = "Channel: \(channel+1) "
newString.appendContentsOf("noteOn: \(note) velocity: \(velocity) ")
updateText(newString)
}
func receivedMIDINoteOff(note: Int, velocity: Int, channel: Int) {
var newString = "Channel: \(channel+1) "
newString.appendContentsOf("noteOff: \(note) velocity: \(velocity) ")
updateText(newString)
}
func receivedMIDIController(controller: Int, value: Int, channel: Int) {
var newString = "Channel: \(channel+1) "
newString.appendContentsOf("controller: \(controller) value: \(value) ")
updateText(newString)
}
func receivedMIDIAftertouchOnNote(note: Int, pressure: Int, channel: Int) {
var newString = "Channel: \(channel+1) "
newString.appendContentsOf("midiAftertouchOnNote: \(note) pressure: \(pressure) ")
updateText(newString)
}
func receivedMIDIAfterTouch(pressure: Int, channel: Int) {
var newString = "Channel: \(channel+1) "
newString.appendContentsOf("midiAfterTouch pressure: \(pressure) ")
updateText(newString)
}
func receivedMIDIPitchWheel(pitchWheelValue: Int, channel: Int) {
var newString = "Channel: \(channel+1) "
newString.appendContentsOf("midiPitchWheel: \(pitchWheelValue) ")
updateText(newString)
}
func receivedMIDIProgramChange(program: Int, channel: Int) {
var newString = "Channel: \(channel+1) "
newString.appendContentsOf("programChange: \(program) ")
updateText(newString)
}
func receivedMIDISystemCommand(data: [UInt8]) {
print("MIDI System Command: \(AKMIDISystemCommand(rawValue: data[0])!)")
var newString = "MIDI System Command: \(AKMIDISystemCommand(rawValue: data[0])!) \n"
for i in 0 ..< data.count {
newString.appendContentsOf("\(data[i]) ")
}
updateText(newString)
}
func updateText(input: String) {
dispatch_async(dispatch_get_main_queue(), {
self.outputTextView.string = "\(input)\n\(self.outputTextView.string!)"
})
}
@IBAction func clearText(sender: AnyObject) {
dispatch_async(dispatch_get_main_queue(), {
self.outputTextView.string = ""
})
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
| apache-2.0 | f02d6c78372e7d82d905b0be213b3df4 | 32.77 | 92 | 0.63281 | 4.575881 | false | false | false | false |
rsyncOSX/RsyncOSX | RsyncOSX/Selectprofile.swift | 1 | 1339 | //
// Selectprofile.swift
// RsyncOSX
//
// Created by Thomas Evensen on 16/06/2019.
// Copyright © 2019 Thomas Evensen. All rights reserved.
//
// swiftlint:disable line_length
import Foundation
final class Selectprofile {
weak var newProfileDelegate: NewProfile?
init(profile: String?, selectedindex: Int?) {
newProfileDelegate = SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain
if profile == NSLocalizedString("Default profile", comment: "default profile") {
newProfileDelegate?.newprofile(profile: nil, selectedindex: selectedindex)
} else {
newProfileDelegate?.newprofile(profile: profile, selectedindex: selectedindex)
}
newProfileDelegate?.reloadprofilepopupbutton()
// Close edit and parameters view if open
if let view = SharedReference.shared.getvcref(viewcontroller: .vcrsyncparameters) as? ViewControllerRsyncParameters {
weak var closeview: ViewControllerRsyncParameters?
closeview = view
closeview?.closeview()
}
if let view = SharedReference.shared.getvcref(viewcontroller: .vcedit) as? ViewControllerEdit {
weak var closeview: ViewControllerEdit?
closeview = view
closeview?.closeview()
}
}
}
| mit | 67acf9ec5ad0569820210d0246ed57cb | 37.228571 | 125 | 0.683109 | 4.883212 | false | false | false | false |
IFTTT/RazzleDazzle | Example/RazzleDazzleTests/RAZScaleAnimationSpec.swift | 1 | 2192 | //
// ScaleAnimationSpec.swift
// RazzleDazzle
//
// Created by Laura Skelton on 6/17/15.
// Copyright (c) 2015 IFTTT. All rights reserved.
//
import RazzleDazzle
import Nimble
import Quick
class ScaleAnimationSpec: QuickSpec {
override func spec() {
var view: UIView!
var animation: ScaleAnimation!
beforeEach {
view = UIView()
animation = ScaleAnimation(view: view)
}
describe("ScaleAnimation") {
it("should add and retrieve keyframes") {
animation[2] = 5
expect(animation[2]).to(equal(5))
}
it("should add and retrieve negative keyframes") {
animation[-2] = 5
expect(animation[-2]).to(equal(5))
}
it("should add and retrieve multiple keyframes") {
animation[-2] = 3
animation[2] = 5
expect(animation[-2]).to(equal(3))
expect(animation[2]).to(equal(5))
}
it("should return the first value for times before the start time") {
animation[2] = 3
animation[4] = 5
expect(animation[1]).to(equal(3))
expect(animation[0]).to(equal(3))
}
it("should return the last value for times after the end time") {
animation[2] = 3
animation[4] = 5
expect(animation[6]).to(equal(5))
expect(animation[10]).to(equal(5))
}
it("should apply changes to the view's scale transform") {
animation[1] = 3
animation[3] = 5
animation.animate(1)
expect(view.transform == CGAffineTransform(scaleX: 3, y: 3)).to(beTruthy())
animation.animate(3)
expect(view.transform == CGAffineTransform(scaleX: 5, y: 5)).to(beTruthy())
}
it("should do nothing if no keyframes have been set") {
animation.animate(5)
expect(view.transform == CGAffineTransform.identity).to(beTruthy())
}
}
}
}
| mit | c4e63d178ffa12c92729117b5197734a | 33.25 | 91 | 0.508212 | 4.473469 | false | false | false | false |
TeamProxima/predictive-fault-tracker | mobile/SieHack/Pods/Charts/Source/Charts/Charts/BarChartView.swift | 48 | 6737 | //
// BarChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
/// Chart that draws bars.
open class BarChartView: BarLineChartViewBase, BarChartDataProvider
{
/// if set to true, all values are drawn above their bars, instead of below their top
fileprivate var _drawValueAboveBarEnabled = true
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
fileprivate var _drawBarShadowEnabled = false
internal override func initialize()
{
super.initialize()
renderer = BarChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler)
self.highlighter = BarHighlighter(chart: self)
self.xAxis.spaceMin = 0.5
self.xAxis.spaceMax = 0.5
}
internal override func calcMinMax()
{
guard let data = self.data as? BarChartData
else { return }
if fitBars
{
_xAxis.calculate(
min: data.xMin - data.barWidth / 2.0,
max: data.xMax + data.barWidth / 2.0)
}
else
{
_xAxis.calculate(min: data.xMin, max: data.xMax)
}
// calculate axis range (min / max) according to provided data
_leftAxis.calculate(
min: data.getYMin(axis: .left),
max: data.getYMax(axis: .left))
_rightAxis.calculate(
min: data.getYMin(axis: .right),
max: data.getYMax(axis: .right))
}
/// - returns: The Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart.
open override func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight?
{
if _data === nil
{
Swift.print("Can't select by touch. No data set.")
return nil
}
guard let h = self.highlighter?.getHighlight(x: pt.x, y: pt.y)
else { return nil }
if !isHighlightFullBarEnabled { return h }
// For isHighlightFullBarEnabled, remove stackIndex
return Highlight(
x: h.x, y: h.y,
xPx: h.xPx, yPx: h.yPx,
dataIndex: h.dataIndex,
dataSetIndex: h.dataSetIndex,
stackIndex: -1,
axis: h.axis)
}
/// - returns: The bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data.
open func getBarBounds(entry e: BarChartDataEntry) -> CGRect
{
guard let
data = _data as? BarChartData,
let set = data.getDataSetForEntry(e) as? IBarChartDataSet
else { return CGRect.null }
let y = e.y
let x = e.x
let barWidth = data.barWidth
let left = x - barWidth / 2.0
let right = x + barWidth / 2.0
let top = y >= 0.0 ? y : 0.0
let bottom = y <= 0.0 ? y : 0.0
var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top)
getTransformer(forAxis: set.axisDependency).rectValueToPixel(&bounds)
return bounds
}
/// Groups all BarDataSet objects this data object holds together by modifying the x-value of their entries.
/// Previously set x-values of entries will be overwritten. Leaves space between bars and groups as specified by the parameters.
/// Calls `notifyDataSetChanged()` afterwards.
///
/// - parameter fromX: the starting point on the x-axis where the grouping should begin
/// - parameter groupSpace: the space between groups of bars in values (not pixels) e.g. 0.8f for bar width 1f
/// - parameter barSpace: the space between individual bars in values (not pixels) e.g. 0.1f for bar width 1f
open func groupBars(fromX: Double, groupSpace: Double, barSpace: Double)
{
guard let barData = self.barData
else
{
Swift.print("You need to set data for the chart before grouping bars.", terminator: "\n")
return
}
barData.groupBars(fromX: fromX, groupSpace: groupSpace, barSpace: barSpace)
notifyDataSetChanged()
}
/// Highlights the value at the given x-value in the given DataSet. Provide -1 as the dataSetIndex to undo all highlighting.
/// - parameter x:
/// - parameter dataSetIndex:
/// - parameter stackIndex: the index inside the stack - only relevant for stacked entries
open func highlightValue(x: Double, dataSetIndex: Int, stackIndex: Int)
{
highlightValue(Highlight(x: x, dataSetIndex: dataSetIndex, stackIndex: stackIndex))
}
// MARK: Accessors
/// if set to true, all values are drawn above their bars, instead of below their top
open var drawValueAboveBarEnabled: Bool
{
get { return _drawValueAboveBarEnabled }
set
{
_drawValueAboveBarEnabled = newValue
setNeedsDisplay()
}
}
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
open var drawBarShadowEnabled: Bool
{
get { return _drawBarShadowEnabled }
set
{
_drawBarShadowEnabled = newValue
setNeedsDisplay()
}
}
/// Adds half of the bar width to each side of the x-axis range in order to allow the bars of the barchart to be fully displayed.
/// **default**: false
open var fitBars = false
/// Set this to `true` to make the highlight operation full-bar oriented, `false` to make it highlight single values (relevant only for stacked).
/// If enabled, highlighting operations will highlight the whole bar, even if only a single stack entry was tapped.
open var highlightFullBarEnabled: Bool = false
/// - returns: `true` the highlight is be full-bar oriented, `false` ifsingle-value
open var isHighlightFullBarEnabled: Bool { return highlightFullBarEnabled }
// MARK: - BarChartDataProbider
open var barData: BarChartData? { return _data as? BarChartData }
/// - returns: `true` if drawing values above bars is enabled, `false` ifnot
open var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled }
/// - returns: `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot
open var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled }
}
| mit | 8a44adf44e38702e107bd9ad38a7a7bb | 35.814208 | 149 | 0.620751 | 4.784801 | false | false | false | false |
steelwheels/KiwiControls | Source/Layout/KCLayoutChecker.swift | 1 | 2357 | /**
* @file KCLayoutChecker.swift
* @brief Define KCLayoutChecker class
* @par Copyright
* Copyright (C) 2022 Steel Wheels Project
*/
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
import CoconutData
public class KCLayoutChecker : KCViewVisitor
{
private var mLimitSize: CGSize = CGSize.zero
#if os(OSX)
private let mLogLevel: CNConfig.LogLevel = .warning
#else
private let mLogLevel: CNConfig.LogLevel = .error
#endif
open override func visit(rootView view: KCRootView){
guard getLimitSize(rootView: view) else {
return
}
let coreview: KCInterfaceView = view.getCoreView()
coreview.accept(visitor: self)
self.visit(coreView: view)
}
private func getLimitSize(rootView root: KCRootView) -> Bool {
#if os(OSX)
if let win = root.window {
mLimitSize = win.contentMaxSize
} else {
if let bounds = KCScreen.shared.contentBounds {
mLimitSize = bounds.size
} else {
CNLog(logLevel: .error, message: "Failed to get limit window size", atFunction: #function, inFile: #file)
return false
}
}
#else
if let bounds = KCScreen.shared.contentBounds {
mLimitSize = bounds.size
} else {
if let bounds = KCScreen.shared.contentBounds {
mLimitSize = bounds.size
} else {
CNLog(logLevel: .error, message: "Failed to get limit screen size", atFunction: #function, inFile: #file)
return false
}
}
#endif
return true
}
open override func visit(stackView view: KCStackView){
for subview in view.arrangedSubviews() {
subview.accept(visitor: self)
}
self.visit(coreView: view)
}
open override func visit(labeledStackView view: KCLabeledStackView){
view.contentsView.accept(visitor: self)
self.visit(coreView: view)
}
open override func visit(coreView view: KCInterfaceView){
/* Do nothing */
}
private func checkSize(coreView view: KCInterfaceView) {
let csize = view.intrinsicContentSize
if csize.width > mLimitSize.width {
CNLog(logLevel: mLogLevel,
message: "Contents width over limit size (\(csize.width) > \(mLimitSize.width)): at \(view)",
atFunction: #function, inFile: #file)
}
if csize.height > mLimitSize.height {
CNLog(logLevel: mLogLevel,
message: "Contents height over limit size (\(csize.height) > \(mLimitSize.height)): at \(view)",
atFunction: #function, inFile: #file)
}
}
}
| lgpl-2.1 | a2c1c26138e5de0bb7716cef8a252548 | 24.901099 | 109 | 0.697497 | 3.401154 | false | false | false | false |
gu704823/DYTV | dytv/dytv/homeViewController.swift | 1 | 3319 | //
// homeViewController.swift
// dytv
//
// Created by jason on 2017/3/23.
// Copyright © 2017年 jason. All rights reserved.
//
import UIKit
class homeViewController: UIViewController {
fileprivate lazy var pagetitlevieww:pagetitleview = {[weak self] in
let titles = ["推荐","游戏","娱乐","趣玩",]
let titleframe = CGRect(x: 0, y: kstatusbarh + knavigationh, width: kscreenw, height: 40)
let titleview = pagetitleview(frame: titleframe, titles: titles)
titleview.backgroundColor = UIColor.white
//遵循pagetitleview的代理
titleview.delegate = self
return titleview
}()
fileprivate lazy var pagecontentvieww:pagecontentview = {[weak self] in
//确定所有的子控制器
var childvcs = [UIViewController]()
childvcs.append(recommendViewController())
childvcs.append(gameViewController())
for _ in 0...1{
let vc = UIViewController()
childvcs.append(vc)
}
//确定内容的frame
let contentviewframe = CGRect(x: 0, y: kstatusbarh + knavigationh + 40, width: kscreenw, height: kscerrenh - kstatusbarh - knavigationh - 40 - 44)
let contenview = pagecontentview(frame: contentviewframe, childcontrollers: childvcs, parentcontrolller: self!)
//遵循代理
contenview.delegate = self
return contenview
}()
override func viewDidLoad() {
super.viewDidLoad()
//1.设置ui
setupui()
}
}
//设置ui界面
extension homeViewController{
fileprivate func setupui(){
automaticallyAdjustsScrollViewInsets = false
//1. 设置导航栏
setnavigationbar()
//2.添加titleview
view.addSubview(pagetitlevieww)
//3.添加contentview
view.addSubview(pagecontentvieww)
}
private func setnavigationbar(){
let size = CGSize(width: 40, height: 40)
//设置左侧的item
let btn = UIButton()
btn.setImage(UIImage(named:"logo"), for: .normal)
btn.sizeToFit()
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
//设置右侧的item
let searchitem = UIBarButtonItem.creatitem(imagename: "btn_search", hightimagename: "btn_search_clicked", size:size)
let historyitem = UIBarButtonItem.creatitem(imagename: "Image_my_history", hightimagename: "Image_my_history_click", size:size)
let qrcodeitem = UIBarButtonItem.creatitem(imagename: "Image_scan", hightimagename: "Image_scan_click", size:size)
navigationItem.rightBarButtonItems = [searchitem,historyitem,qrcodeitem]
}
}
//遵循pagetitleviewdelegate代理协议
extension homeViewController:pagetitleviewdelegate{
func Pagetitleview(titleview: pagetitleview, selectindex index: Int) {
pagecontentvieww.setcurrentindex(currentindex: index)
}
}
//遵循pagecontentviewdelegate代理协议
extension homeViewController:pagecontentviewdelegate{
func Pagecontentview(contentview: pagecontentview, progress: CGFloat, sourceindex: Int, targetindex: Int) {
pagetitlevieww.settitlewithprogress(progress: progress, sourceindex: sourceindex, targetindex: targetindex)
}
}
| mit | 4a465c934d6995a9f04e8e597fb6ca5c | 33.945055 | 154 | 0.665723 | 4.529915 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/VerseTableDS.swift | 1 | 3145 | //
// VerseTableDS.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 14.2.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// This class handles verse table content
class VerseTableDS: NSObject, UITableViewDataSource
{
// ATTRIBUTES ---------------------
// Language / section name -> Paragraph
private let data: [(title: String, paragraph: Paragraph)]
private var filteredData: [(title: String, paragraph: Paragraph)]
// The specific verse index the context is limited to
private var _targetVerseIndex: VerseIndex?
var targetVerseIndex: VerseIndex?
{
get { return _targetVerseIndex }
set
{
_targetVerseIndex = newValue
filterData()
}
}
// INIT -----------------------------
// Resource data is combination of a language name and a matching paragraph version
init(originalParagraph: Paragraph, resourceData: [(String, Paragraph)])
{
var data = [(String, Paragraph)]()
let originalTitle = NSLocalizedString("Original:", comment: "A title for the original version of a paragraph / paragraph portion in comment context")
let currentTitle = NSLocalizedString("Current:", comment: "A title for the curent version of a paragraph / paragraph portion in comment context")
// Adds the current (and original) version of the targeted paragraph first
if originalParagraph.isMostRecent
{
data.append((originalTitle, originalParagraph))
}
else
{
data.append((originalTitle, originalParagraph))
do
{
if let latestId = try ParagraphHistoryView.instance.mostRecentId(forParagraphWithId: originalParagraph.idString), let latestVersion = try Paragraph.get(latestId)
{
data.append((currentTitle, latestVersion))
}
else
{
print("ERROR: No latest version available for paragraph \(originalParagraph.idString)")
}
}
catch
{
print("ERROR: Failed to find the latest paragraph version. \(error)")
}
}
// Also includes other data
self.data = data + resourceData
self.filteredData = self.data
}
// IMPLEMENTED METHODS -------------
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return filteredData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// Finds a reusable cell first
let cell = tableView.dequeueReusableCell(withIdentifier: VerseCell.identifier, for: indexPath) as! VerseCell
let data = filteredData[indexPath.row]
cell.configure(title: data.title, paragraph: data.paragraph)
return cell
}
// OTHER METHODS --------------
func filterData()
{
if let targetVerseIndex = targetVerseIndex
{
filteredData = data.compactMap
{
let paragraph = $0.paragraph.copy()
for para in paragraph.content
{
para.verses = para.verses.filter { $0.range.contains(index: targetVerseIndex) }
}
paragraph.content = paragraph.content.filter { !$0.verses.isEmpty }
if paragraph.content.isEmpty
{
return nil
}
else
{
return ($0.title, paragraph)
}
}
}
else
{
filteredData = data
}
}
}
| mit | e0134e5e48ce203068bba76462fe696d | 24.354839 | 165 | 0.68416 | 3.979747 | false | false | false | false |
cao903775389/MRCBaseLibrary | MRCBaseLibrary/Classes/MRCExtension/UINavigationItemExtensions.swift | 1 | 2002 | //
// UINavigationItemExtensions.swift
// Pods
//
// Created by 逢阳曹 on 2017/5/27.
//
//
import Foundation
extension UINavigationItem {
/**
* !@brief 设置左侧BarButtonItems setLeftBarButtonItems
*/
public func addLeftBarButtonItems(_ items: [UIBarButtonItem], animated: Bool = false) {
var leftItems = items
//标记是否插入了一个UIBarButtonItem修复间距问题
var isInsert = false
for item in items.enumerated() {
if isInsert == false {
let negativeSeperator = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
//设置为负值 表示向左偏移16像素
negativeSeperator.width = -13
isInsert = true
leftItems.insert(negativeSeperator, at: item.offset == 0 ? 0 : item.offset - 1)
}else {
isInsert = false
}
}
self.setLeftBarButtonItems(leftItems, animated: animated)
}
/**
* !@brief 设置右侧BarButtonItems setRightBarButtonItems
*/
public func addRightBarButtonItems(_ items: [UIBarButtonItem], animated: Bool = false) {
var rightItems = items
//标记是否插入了一个UIBarButtonItem修复间距问题
var isInsert = false
for item in items.enumerated() {
if isInsert == false {
let negativeSeperator = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
//设置为负值 表示向左偏移16像素
negativeSeperator.width = -11
isInsert = true
rightItems.insert(negativeSeperator, at: item.offset == 0 ? 0 : item.offset - 1)
}else {
isInsert = false
}
self.setRightBarButtonItems(rightItems, animated: animated)
}
}
}
| mit | 3e2d13d41289146bf99b6eaa4a4cee83 | 31.206897 | 136 | 0.581906 | 4.994652 | false | false | false | false |
jakub-tucek/fit-checker-2.0 | fit-checker/utils/edux-parser/CourseListParser.swift | 1 | 3065 | //
// CourseListParser.swift
// fit-checker
//
// Created by Jakub Tucek on 14/01/17.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import Foundation
import Kanna
/// CourseListParser is implementation of CourseListParsing protocol.
/// Parses semester information and current courses (courses) from edux homepage.
class CourseListParser: CourseListParsing {
/// Struct containing selector constants
struct Consts {
/// static let
static let jsonContentKey = "widget_content"
/// Select info about semester
static let semesterInfoSelector
= "//p[contains(@class, 'semester-info')]"
/// Select course in list containing
static let courseSelector
= "//ul/li"
static let courseLinkSelector
= "a"
}
/// Parses classification from edux homepage.
///
/// - Parameter json: ajax response containing widget content in json format
/// - Returns: parsed result
func parse(json: [String: Any?]) -> CourseParsedListResult {
let result = CourseParsedListResult()
let html = getWidgetContent(json: json)
if let node = Kanna.HTML(html: html, encoding: String.Encoding.utf8) {
let semesterInfo = parseSemesterInfo(widgetDocument: node)
if let infoUnwrap = semesterInfo {
result.semesterInfo = infoUnwrap
}
result.courses = parseLectures(widgetDocument: node)
}
return result
}
/// Gets html content from JSON.
///
/// - Parameter json: response JSON of widget
/// - Returns: html or empty string if JSON is not valid
private func getWidgetContent(json: [String: Any?]) -> String {
if let str = json[Consts.jsonContentKey] as? String {
return str
} else {
return ""
}
}
/// Parses semester informations. Finds first node that matches
/// Semester info selector and returns it's text.
///
/// - Parameter widgetNode: widget node
/// - Returns: parsed semester info
private func parseSemesterInfo(widgetDocument: HTMLDocument) -> String? {
for infoNode in widgetDocument.xpath(Consts.semesterInfoSelector) {
return infoNode.text
}
return nil
}
/// Parses courses names by iterating over li elements in list.
///
/// - Parameter widgetNode: widget node
/// - Returns: parsed courses
private func parseLectures(widgetDocument: HTMLDocument) -> [CourseParsed] {
var courses = [CourseParsed]()
for courseNode in widgetDocument.xpath(Consts.courseSelector) {
let linkNodeCount
= courseNode.xpath(Consts.courseLinkSelector).count
//no link found
let classification = (linkNodeCount > 0)
if let name = courseNode.text {
courses.append(CourseParsed(name: name, classification: classification))
}
}
return courses
}
}
| mit | 34f0b1209c22a5ed32d3ca90787d377b | 27.90566 | 88 | 0.619125 | 4.825197 | false | false | false | false |
kello711/HackingWithSwift | project26/Project26/GameScene.swift | 1 | 6243 | //
// GameScene.swift
// Project26
//
// Created by Hudzilla on 17/09/2015.
// Copyright (c) 2015 Paul Hudson. All rights reserved.
//
import CoreMotion
import SpriteKit
enum CollisionTypes: UInt32 {
case Player = 1
case Wall = 2
case Star = 4
case Vortex = 8
case Finish = 16
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var player: SKSpriteNode!
var lastTouchPosition: CGPoint?
var motionManager: CMMotionManager!
var scoreLabel: SKLabelNode!
var score: Int = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
var gameOver = false
override func didMoveToView(view: SKView) {
let background = SKSpriteNode(imageNamed: "background.jpg")
background.position = CGPoint(x: 512, y: 384)
background.blendMode = .Replace
background.zPosition = -1
addChild(background)
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.text = "Score: 0"
scoreLabel.horizontalAlignmentMode = .Left
scoreLabel.position = CGPoint(x: 16, y: 16)
addChild(scoreLabel)
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
loadLevel()
createPlayer()
motionManager = CMMotionManager()
motionManager.startAccelerometerUpdates()
}
func loadLevel() {
if let levelPath = NSBundle.mainBundle().pathForResource("level1", ofType: "txt") {
if let levelString = try? String(contentsOfFile: levelPath, usedEncoding: nil) {
let lines = levelString.componentsSeparatedByString("\n")
for (row, line) in lines.reverse().enumerate() {
for (column, letter) in line.characters.enumerate() {
let position = CGPoint(x: (64 * column) + 32, y: (64 * row) + 32)
if letter == "x" {
// load wall
let node = SKSpriteNode(imageNamed: "block")
node.position = position
node.physicsBody = SKPhysicsBody(rectangleOfSize: node.size)
node.physicsBody!.categoryBitMask = CollisionTypes.Wall.rawValue
node.physicsBody!.dynamic = false
addChild(node)
} else if letter == "v" {
// load vortex
let node = SKSpriteNode(imageNamed: "vortex")
node.name = "vortex"
node.position = position
node.runAction(SKAction.repeatActionForever(SKAction.rotateByAngle(CGFloat(M_PI), duration: 1)))
node.physicsBody = SKPhysicsBody(circleOfRadius: node.size.width / 2)
node.physicsBody!.dynamic = false
node.physicsBody!.categoryBitMask = CollisionTypes.Vortex.rawValue
node.physicsBody!.contactTestBitMask = CollisionTypes.Player.rawValue
node.physicsBody!.collisionBitMask = 0
addChild(node)
} else if letter == "s" {
// load star
let node = SKSpriteNode(imageNamed: "star")
node.name = "star"
node.physicsBody = SKPhysicsBody(circleOfRadius: node.size.width / 2)
node.physicsBody!.dynamic = false
node.physicsBody!.categoryBitMask = CollisionTypes.Star.rawValue
node.physicsBody!.contactTestBitMask = CollisionTypes.Player.rawValue
node.physicsBody!.collisionBitMask = 0
node.position = position
addChild(node)
} else if letter == "f" {
// load finish
let node = SKSpriteNode(imageNamed: "finish")
node.name = "finish"
node.physicsBody = SKPhysicsBody(circleOfRadius: node.size.width / 2)
node.physicsBody!.dynamic = false
node.physicsBody!.categoryBitMask = CollisionTypes.Finish.rawValue
node.physicsBody!.contactTestBitMask = CollisionTypes.Player.rawValue
node.physicsBody!.collisionBitMask = 0
node.position = position
addChild(node)
}
}
}
}
}
}
func createPlayer() {
player = SKSpriteNode(imageNamed: "player")
player.position = CGPoint(x: 96, y: 672)
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2)
player.physicsBody!.allowsRotation = false
player.physicsBody!.linearDamping = 0.5
player.physicsBody!.categoryBitMask = CollisionTypes.Player.rawValue
player.physicsBody!.contactTestBitMask = CollisionTypes.Star.rawValue | CollisionTypes.Vortex.rawValue | CollisionTypes.Finish.rawValue
player.physicsBody!.collisionBitMask = CollisionTypes.Wall.rawValue
addChild(player)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let location = touch.locationInNode(self)
lastTouchPosition = location
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let location = touch.locationInNode(self)
lastTouchPosition = location
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
lastTouchPosition = nil
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
lastTouchPosition = nil
}
override func update(currentTime: CFTimeInterval) {
if !gameOver {
#if (arch(i386) || arch(x86_64))
if let currentTouch = lastTouchPosition {
let diff = CGPoint(x: currentTouch.x - player.position.x, y: currentTouch.y - player.position.y)
physicsWorld.gravity = CGVector(dx: diff.x / 100, dy: diff.y / 100)
}
#else
if let accelerometerData = motionManager.accelerometerData {
physicsWorld.gravity = CGVector(dx: accelerometerData.acceleration.y * -50, dy: accelerometerData.acceleration.x * 50)
}
#endif
}
}
func didBeginContact(contact: SKPhysicsContact) {
if contact.bodyA.node == player {
playerCollidedWithNode(contact.bodyB.node!)
} else if contact.bodyB.node == player {
playerCollidedWithNode(contact.bodyA.node!)
}
}
func playerCollidedWithNode(node: SKNode) {
if node.name == "vortex" {
player.physicsBody!.dynamic = false
gameOver = true
score -= 1
let move = SKAction.moveTo(node.position, duration: 0.25)
let scale = SKAction.scaleTo(0.0001, duration: 0.25)
let remove = SKAction.removeFromParent()
let sequence = SKAction.sequence([move, scale, remove])
player.runAction(sequence) { [unowned self] in
self.createPlayer()
self.gameOver = false
}
} else if node.name == "star" {
node.removeFromParent()
score += 1
} else if node.name == "finish" {
// next level?
}
}
}
| unlicense | 1c17c9faae6faf086fb129aefb354967 | 30.059701 | 137 | 0.695179 | 3.865635 | false | false | false | false |
openHPI/xikolo-ios | iOS/Data/Model/Actions/Video+Actions.swift | 1 | 6690 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Common
import UIKit
extension Video {
private static var actionDispatchQueue: DispatchQueue {
return DispatchQueue(label: "video-actions", qos: .userInitiated)
}
var streamURLForDownload: URL? {
return self.singleStream?.hlsURL
}
var actions: [Action] {
return [self.streamDownloadAction, self.slidesDownloadAction].compactMap { $0 } + self.combinedActions
}
var streamDownloadAction: Action? {
let isOffline = !ReachabilityHelper.hasConnection
let streamDownloadState = StreamPersistenceManager.shared.downloadState(for: self)
if let url = self.streamURLForDownload, streamDownloadState == .notDownloaded, !isOffline {
let downloadActionTitle = NSLocalizedString("course-item.stream-download-action.start-download.title",
comment: "start download of stream for video")
return Action(title: downloadActionTitle, image: Action.Image.download) {
Self.actionDispatchQueue.async {
StreamPersistenceManager.shared.startDownload(with: url, for: self)
}
}
}
if streamDownloadState == .pending || streamDownloadState == .downloading {
let abortActionTitle = NSLocalizedString("course-item.stream-download-action.stop-download.title",
comment: "stop stream download for video")
return Action(title: abortActionTitle, image: Action.Image.stop) {
Self.actionDispatchQueue.async {
StreamPersistenceManager.shared.cancelDownload(for: self)
}
}
}
if streamDownloadState == .downloaded {
let deleteActionTitle = NSLocalizedString("course-item.stream-download-action.delete-download.title",
comment: "delete stream download for video")
return Action(title: deleteActionTitle, image: Action.Image.delete) {
Self.actionDispatchQueue.async {
StreamPersistenceManager.shared.deleteDownload(for: self)
}
}
}
return nil
}
var slidesDownloadAction: Action? {
let isOffline = !ReachabilityHelper.hasConnection
let slidesDownloadState = SlidesPersistenceManager.shared.downloadState(for: self)
if let url = self.slidesURL, slidesDownloadState == .notDownloaded, !isOffline {
let downloadActionTitle = NSLocalizedString("course-item.slides-download-action.start-download.title",
comment: "start download of slides for video")
return Action(title: downloadActionTitle, image: Action.Image.download) {
Self.actionDispatchQueue.async {
SlidesPersistenceManager.shared.startDownload(with: url, for: self)
}
}
}
if slidesDownloadState == .pending || slidesDownloadState == .downloading {
let abortActionTitle = NSLocalizedString("course-item.slides-download-action.stop-download.title",
comment: "stop slides download for video")
return Action(title: abortActionTitle, image: Action.Image.stop) {
Self.actionDispatchQueue.async {
SlidesPersistenceManager.shared.cancelDownload(for: self)
}
}
}
if slidesDownloadState == .downloaded {
let deleteActionTitle = NSLocalizedString("course-item.slides-download-action.delete-download.title",
comment: "delete slides download for video")
return Action(title: deleteActionTitle, image: Action.Image.delete) {
Self.actionDispatchQueue.async {
SlidesPersistenceManager.shared.deleteDownload(for: self)
}
}
}
return nil
}
private var combinedActions: [Action] {
var actions: [Action] = []
let isOffline = !ReachabilityHelper.hasConnection
let streamDownloadState = StreamPersistenceManager.shared.downloadState(for: self)
let slidesDownloadState = SlidesPersistenceManager.shared.downloadState(for: self)
if let streamURL = self.streamURLForDownload, streamDownloadState == .notDownloaded,
let slidesURL = self.slidesURL, slidesDownloadState == .notDownloaded, !isOffline {
let downloadActionTitle = NSLocalizedString("course-item.combined-download-action.start-download.title",
comment: "start all downloads for video")
actions.append(Action(title: downloadActionTitle, image: Action.Image.aggregatedDownload) {
Self.actionDispatchQueue.async {
StreamPersistenceManager.shared.startDownload(with: streamURL, for: self)
SlidesPersistenceManager.shared.startDownload(with: slidesURL, for: self)
}
})
}
if streamDownloadState == .pending || streamDownloadState == .downloading, slidesDownloadState == .pending || slidesDownloadState == .downloading {
let abortActionTitle = NSLocalizedString("course-item.combined-download-action.stop-download.title",
comment: "stop all downloads for video")
actions.append(Action(title: abortActionTitle, image: Action.Image.stop) {
Self.actionDispatchQueue.async {
StreamPersistenceManager.shared.cancelDownload(for: self)
SlidesPersistenceManager.shared.cancelDownload(for: self)
}
})
}
if streamDownloadState == .downloaded, slidesDownloadState == .downloaded {
let deleteActionTitle = NSLocalizedString("course-item.combined-download-action.delete-download.title",
comment: "delete all downloads for video")
actions.append(Action(title: deleteActionTitle, image: Action.Image.delete) {
Self.actionDispatchQueue.async {
StreamPersistenceManager.shared.deleteDownload(for: self)
SlidesPersistenceManager.shared.deleteDownload(for: self)
}
})
}
return actions
}
}
| gpl-3.0 | 4e97b4c450f3fac6c8df77609d57d74c | 46.778571 | 155 | 0.605173 | 5.945778 | false | false | false | false |
alblue/swift | validation-test/Reflection/inherits_NSObject.swift | 1 | 8844 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/inherits_NSObject
// RUN: %target-codesign %t/inherits_NSObject
// RUN: %target-run %target-swift-reflection-test %t/inherits_NSObject | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
import Foundation
import simd
import SwiftReflectionTest
class BaseNSClass : NSObject {
var w: Int = 0
var x: Bool = false
}
let baseClass = BaseNSClass()
reflect(object: baseClass)
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (class inherits_NSObject.BaseNSClass)
// CHECK-64: Type info:
// CHECK-64-NEXT: (class_instance size=17 alignment=8 stride=24 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=w offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))
// CHECK-64-NEXT: (field name=x offset=16
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1)))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (class inherits_NSObject.BaseNSClass)
// CHECK-32: Type info:
// CHECK-32-NEXT: (class_instance size=9 alignment=4 stride=12 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=w offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))
// CHECK-32-NEXT: (field name=x offset=8
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1)))))
class DerivedNSClass : BaseNSClass {
var y: Bool = false
var z: Int = 0
}
let derivedClass = DerivedNSClass()
reflect(object: derivedClass)
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (class inherits_NSObject.DerivedNSClass)
// CHECK-64: Type info:
// CHECK-64-NEXT: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=y offset=17
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1))))
// CHECK-64-NEXT: (field name=z offset=24
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (class inherits_NSObject.DerivedNSClass)
// CHECK-32: Type info:
// CHECK-32-NEXT: (class_instance size=16 alignment=4 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=y offset=9
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1))))
// CHECK-32-NEXT: (field name=z offset=12
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))
// Note: dynamic layout starts at offset 8, not 16
class GenericBaseNSClass<T> : NSObject {
var w: T = 0 as! T
}
let genericBaseClass = GenericBaseNSClass<Int>()
reflect(object: genericBaseClass)
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_class inherits_NSObject.GenericBaseNSClass
// CHECK-64: (struct Swift.Int))
// CHECK-64: Type info:
// CHECK-64-NEXT: (class_instance size=16 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=w offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_class inherits_NSObject.GenericBaseNSClass
// CHECK-32: (struct Swift.Int))
// CHECK-32: Type info:
// CHECK-32-NEXT: (class_instance size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=w offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))
class AlignedNSClass : NSObject {
var w: Int = 0
var x: int4 = [1,2,3,4]
}
let alignedClass = AlignedNSClass()
reflect(object: alignedClass)
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (class inherits_NSObject.AlignedNSClass)
// CHECK-64: Type info:
// CHECK-64-NEXT: (class_instance size=32 alignment=16 stride=32 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=w offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))
// CHECK-64-NEXT: (field name=x offset=16
// CHECK-64-NEXT: (builtin size=16 alignment=16 stride=16 num_extra_inhabitants=0 bitwise_takable=1)))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (class inherits_NSObject.AlignedNSClass)
// CHECK-32: Type info:
// CHECK-32-NEXT: (class_instance size=32 alignment=16 stride=32 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=w offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))
// CHECK-32-NEXT: (field name=x offset=16
// CHECK-32-NEXT: (builtin size=16 alignment=16 stride=16 num_extra_inhabitants=0 bitwise_takable=1)))
class GenericAlignedNSClass<T> : NSObject {
var w: T = 0 as! T
var x: int4 = [1,2,3,4]
}
let genericAlignedClass = GenericAlignedNSClass<Int>()
reflect(object: genericAlignedClass)
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_class inherits_NSObject.GenericAlignedNSClass
// CHECK-64: (struct Swift.Int))
// CHECK-64: Type info:
// CHECK-64-NEXT: (class_instance size=48 alignment=16 stride=48 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=w offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))
// CHECK-64-NEXT: (field name=x offset=32
// CHECK-64-NEXT: (builtin size=16 alignment=16 stride=16 num_extra_inhabitants=0 bitwise_takable=1)))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_class inherits_NSObject.GenericAlignedNSClass
// CHECK-32: (struct Swift.Int))
// CHECK-32: Type info:
// CHECK-32-NEXT: (class_instance size=48 alignment=16 stride=48 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=w offset=16
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))
// CHECK-32-NEXT: (field name=x offset=32
// CHECK-32-NEXT: (builtin size=16 alignment=16 stride=16 num_extra_inhabitants=0 bitwise_takable=1)))
doneReflecting()
| apache-2.0 | b6aa82e4498387acc45c2c295188cfcc | 44.823834 | 144 | 0.710312 | 3.161959 | false | false | false | false |
Constructor-io/constructorio-client-swift | AutocompleteClient/FW/Logic/Request/Builder/QueryItemCollection.swift | 1 | 2358 | //
// QueryItemCollection.swift
// Constructor.io
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
struct QueryItemCollection {
private var queryItems = [String: [URLQueryItem]]()
init() {}
mutating func add(key: String, items: [URLQueryItem]) {
queryItems[key] = items
}
mutating func add(_ item: URLQueryItem) {
self[item.name] = [item]
}
mutating func addMultiple(index: Int, item: URLQueryItem) {
self[item.name + String(index)] = [item]
}
subscript(value: String) -> [URLQueryItem]? {
get {
return queryItems[value]
}
set {
if let newValue = newValue {
if var existingArray = queryItems[value] {
existingArray.append(contentsOf: newValue)
queryItems[value] = existingArray
} else {
queryItems[value] = newValue
}
} else {
queryItems.removeValue(forKey: value)
}
}
}
mutating func remove(name: String) {
self[name] = nil
}
func all() -> [URLQueryItem] {
let flattenedArray = self.queryItems.values.reduce([]) { res, next -> [URLQueryItem] in
return res + next.reduce([], { res, next in return res + [next] })
}
return flattenedArray.sorted(by: { item1, item2 -> Bool in
if item1.name == item2.name {
return (item1.value ?? "") < (item2.value ?? "")
}
return item1.name < item2.name
})
}
func allAsDictionary() -> [String: Any] {
let flattenedArray = self.queryItems.values.reduce([]) { res, next -> [URLQueryItem] in
return res + next.reduce([], { res, next in return res + [next] })
}
var dict: [String: Any] = [:]
flattenedArray.forEach { item in
if item.value != nil {
dict[item.name] = item.value
}
}
// swiftlint:disable force_cast
if dict["s"] != nil {
dict["s"] = Int64(dict["s"] as! String)
}
if dict["_dt"] != nil {
dict["_dt"] = Int64(dict["_dt"] as! String)
}
// swiftlint:enable force_cast
return dict
}
}
| mit | 75bb40362a9fc5b46e79d7533a40dba8 | 27.743902 | 95 | 0.514637 | 4.269928 | false | false | false | false |
Urinx/SomeCodes | Swift/swiftDemo/useCoreData/useCoreData/ViewController.swift | 1 | 1437 | //
// ViewController.swift
// useCoreData
//
// Created by Eular on 15/4/25.
// Copyright (c) 2015年 Eular. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// 插入数据
var row: AnyObject = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context!)
row.setValue("Dudu", forKey: "name")
row.setValue(12, forKey: "age")
context?.save(nil)
// 读取数据
var f = NSFetchRequest(entityName: "Users")
var dataArr = context?.executeFetchRequest(f, error: nil)
println(dataArr?[0].valueForKey("name"))
// 更新数据
var data = dataArr?[0] as! NSManagedObject
data.setValue("hehe", forKey: "name")
data.setValue(22, forKey: "age")
data.managedObjectContext?.save(nil)
// 删除数据
context?.deleteObject(dataArr?[0] as! NSManagedObject)
context?.save(nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-2.0 | d21033e1fdc0c429c1bdf61d7696d378 | 27.632653 | 123 | 0.627227 | 4.772109 | false | false | false | false |
parthdubal/MyNewyorkTimes | MyNewyorkTimes/Modules/NewsList/View/NewsListCell.swift | 1 | 1396 | //
// NewsListCell.swift
// MyNewyorkTimes
//
// Created by Parth Dubal on 7/11/17.
// Copyright © 2017 Parth Dubal. All rights reserved.
//
import UIKit
class NewsListCell: UITableViewCell
{
@IBOutlet weak var articleDate: UILabel!
@IBOutlet weak var articleSnippet: UILabel!
@IBOutlet weak var articleTitle: UILabel!
@IBOutlet weak var articleImage: UIImageView!
static var cellIdentifier = "NewsListCell"
weak var newsInfo: NewsInfo? {
didSet{
self.updateCellInfo()
}
}
override func awakeFromNib() {
super.awakeFromNib()
articleTitle.numberOfLines = 0
articleSnippet.numberOfLines = 0
articleDate.numberOfLines = 0
articleDate.lineBreakMode = .byWordWrapping
articleSnippet.lineBreakMode = .byWordWrapping
}
func updateCellInfo()
{
if let info = newsInfo
{
articleDate.text = info.dateStr
articleSnippet.text = info.snippet
articleTitle.text = info.title
if !info.imageUrl.isStringEmpty()
{
articleImage.asyncImageDownload(url: info.imageUrl)
}
else
{
articleImage.image = UIImage(named: "thumb-article")
}
}
}
}
| mit | ee90b9b4ff61c5f78d51d41f374ff463 | 23.051724 | 68 | 0.569176 | 5 | false | false | false | false |
dfsilva/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/SwiftExtensions/Promises.swift | 1 | 1985 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import MBProgressHUD
public extension ARPromise {
public func startUserAction(_ ignore: [String] = []) -> ARPromise {
let window = UIApplication.shared.windows[0]
// let hud = MBProgressHUD(window: window)
let hud = MBProgressHUD(view: window)
hud.mode = MBProgressHUDMode.indeterminate
hud.removeFromSuperViewOnHide = true
window.addSubview(hud)
window.bringSubview(toFront: hud)
//hud.show(true)
hud.show(animated: true)
then { (t: AnyObject!) -> () in
hud.hide(animated:true)
}
failure { (e) -> () in
hud.hide(animated:true)
if let rpc = e as? ACRpcException {
if ignore.contains(rpc.tag) {
return
}
}
AAExecutions.errorWithError(e)
}
return self
}
public func then<T>(_ closure: @escaping (T!) -> ()) -> ARPromise {
then(PromiseConsumer(closure: closure))
return self
}
public func after(_ closure: @escaping () -> ()) -> ARPromise {
then(PromiseConsumerEmpty(closure: closure))
return self
}
public func failure(withClosure closure: @escaping (JavaLangException!) -> ()) -> ARPromise {
failure(PromiseConsumer(closure: closure))
return self
}
}
open class PromiseConsumer<T>: NSObject, ARConsumer {
let closure: (T!) -> ()
init(closure: @escaping (T!) -> ()) {
self.closure = closure
}
open func apply(withId t: Any!) {
closure(t as? T)
}
}
open class PromiseConsumerEmpty: NSObject, ARConsumer {
let closure: () -> ()
init(closure: @escaping () -> ()) {
self.closure = closure
}
open func apply(withId t: Any!) {
closure()
}
}
| agpl-3.0 | 5031e96c721cdd5ff47a87667b6121dd | 23.8125 | 97 | 0.541058 | 4.450673 | false | false | false | false |
WickedColdfront/Slide-iOS | Slide for Reddit/MediaDisplayViewController.swift | 1 | 31132 | //
// MediaDisplayViewController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 8/2/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
import UIKit
import MaterialComponents.MaterialProgressView
import SDWebImage
import AVFoundation
import Alamofire
import AVKit
class MediaDisplayViewController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate, YTPlayerViewDelegate {
var baseURL: URL?
var loadedURL: URL?
var type: ContentType.CType = ContentType.CType.UNKNOWN
var lqURL: URL?
var text: String?
var size: UILabel?
var progressView: MDCProgressView?
var scrollView = UIScrollView()
var imageView = UIImageView()
var videoPlayer = AVPlayer()
var videoView = UIView()
var ytPlayer = YTPlayerView()
var playerVC = AVPlayerViewController()
var menuB : UIBarButtonItem?
var inAlbum = false
init(url: URL, text: String?, lqURL: URL?, inAlbum : Bool = false){
super.init(nibName: nil, bundle: nil)
self.baseURL = url
self.lqURL = lqURL
self.text = text
self.inAlbum = inAlbum
type = ContentType.getContentType(baseUrl: url)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func displayImage(baseImage: UIImage?){
if(baseImage == nil){
}
let image = baseImage!
self.scrollView.contentSize = CGSize.init(width: self.view.frame.size.width, height: getHeightFromAspectRatio(imageHeight: image.size.height, imageWidth: image.size.width))
self.scrollView.delegate = self
let dtap = UITapGestureRecognizer.init(target: self, action: #selector (handleDoubleTapScrollView(recognizer:)))
dtap.numberOfTapsRequired = 2
self.scrollView.addGestureRecognizer(dtap)
if(!inAlbum){
let tap = UITapGestureRecognizer.init(target: self, action: #selector (close(recognizer:)))
self.scrollView.addGestureRecognizer(tap)
}
imageView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
imageView.contentMode = .scaleAspectFit
self.scrollView.addSubview(imageView)
imageView.image = image
if(showHQ){
var items: [UIBarButtonItem] = []
if(text != nil && !(text!.isEmpty)){
let textB = UIBarButtonItem(image: UIImage(named: "size")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), style:.plain, target: self, action: #selector(MediaDisplayViewController.showTitle(_:)))
items.append(textB)
}
let space = UIBarButtonItem(barButtonSystemItem:.flexibleSpace, target: nil, action: nil)
let hdB = UIBarButtonItem(image: UIImage(named: "hd")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), style:.plain, target: self, action: #selector(MediaDisplayViewController.hd(_:)))
items.append(hdB)
items.append(space)
items.append(UIBarButtonItem(image: UIImage(named: "download")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), style:.plain, target: self, action: #selector(MediaDisplayViewController.download(_:))))
menuB = UIBarButtonItem(image: UIImage(named: "ic_more_vert_white")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), style:.plain, target: self, action: #selector(MediaDisplayViewController.showImageMenu(_:)))
items.append(menuB!)
toolbar.items = items
}
}
func close(recognizer: UITapGestureRecognizer){
self.parent?.dismiss(animated: true, completion: nil)
}
func hd(_ sender: AnyObject){
size?.isHidden = false
var items: [UIBarButtonItem] = []
if(text != nil && !(text!.isEmpty)){
let textB = UIBarButtonItem(image: UIImage(named: "size")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), style:.plain, target: self, action: #selector(MediaDisplayViewController.showTitle(_:)))
items.append(textB)
}
let space = UIBarButtonItem(barButtonSystemItem:.flexibleSpace, target: nil, action: nil)
items.append(space)
items.append(UIBarButtonItem(image: UIImage(named: "download")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), style:.plain, target: self, action: #selector(MediaDisplayViewController.download(_:))))
menuB = UIBarButtonItem(image: UIImage(named: "ic_more_vert_white")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), style:.plain, target: self, action: #selector(MediaDisplayViewController.showImageMenu(_:)))
items.append(menuB!)
toolbar.items = items
progressView?.setHidden(false, animated: true, completion: nil)
showHQ = false
loadImage(imageURL: baseURL!)
}
@IBAction func handleDoubleTapScrollView(recognizer: UITapGestureRecognizer) {
if scrollView.zoomScale == 1 {
scrollView.zoom(to: zoomRectForScale(scale: scrollView.maximumZoomScale, center: recognizer.location(in: recognizer.view)), animated: true)
} else {
scrollView.setZoomScale(1, animated: true)
}
}
func zoomRectForScale(scale: CGFloat, center: CGPoint) -> CGRect {
var zoomRect = CGRect.zero
zoomRect.size.height = imageView.frame.size.height / scale
zoomRect.size.width = imageView.frame.size.width / scale
let newCenter = imageView.convert(center, from: scrollView)
zoomRect.origin.x = newCenter.x - (zoomRect.size.width / 2.0)
zoomRect.origin.y = newCenter.y - (zoomRect.size.height / 2.0)
return zoomRect
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func loadImage(imageURL: URL){
loadedURL = imageURL
print("Found \(size!.text)")
if(SDWebImageManager.shared().cachedImageExists(for: imageURL)){
DispatchQueue.main.async {
let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: imageURL.absoluteString)
self.progressView?.setHidden(true, animated: true)
self.size?.isHidden = true
self.displayImage(baseImage: image)
}
} else {
SDWebImageDownloader.shared().downloadImage(with: imageURL, options: .allowInvalidSSLCertificates, progress: { (current:NSInteger, total:NSInteger) in
var average: Float = 0
average = (Float (current) / Float(total))
let countBytes = ByteCountFormatter()
countBytes.allowedUnits = [.useMB]
countBytes.countStyle = .file
let fileSize = countBytes.string(fromByteCount: Int64(total))
self.size!.text = fileSize
self.progressView!.progress = average
}, completed: { (image, _, error, _) in
SDWebImageManager.shared().saveImage(toCache: image, for: imageURL)
DispatchQueue.main.async {
self.progressView?.setHidden(true, animated: true)
self.size?.isHidden = true
self.displayImage(baseImage: image)
}
})
}
}
func getHeightFromAspectRatio(imageHeight:CGFloat, imageWidth: CGFloat) -> CGFloat {
let ratio = Double(imageHeight)/Double(imageWidth)
let width = Double(view.frame.size.width);
return CGFloat(width * ratio)
}
var toolbar = UIToolbar()
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
self.scrollView.minimumZoomScale=1
self.scrollView.maximumZoomScale=6.0
self.scrollView.backgroundColor = .clear
self.view.addSubview(scrollView)
view.backgroundColor = UIColor.black.withAlphaComponent(0.7)
toolbar = UIToolbar.init(frame: CGRect.init(x: 0, y: self.view.frame.size.height - 35, width: self.view.frame.size.width, height: 30))
let space = UIBarButtonItem(barButtonSystemItem:.flexibleSpace, target: nil, action: nil)
var items: [UIBarButtonItem] = []
if(text != nil && !(text!.isEmpty)){
var textB = UIBarButtonItem(image: UIImage(named: "size")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), style:.plain, target: self, action: #selector(MediaDisplayViewController.showTitle(_:)))
items.append(textB)
}
items.append(space)
items.append(UIBarButtonItem(image: UIImage(named: "download")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), style:.plain, target: self, action: #selector(MediaDisplayViewController.download(_:))))
menuB = UIBarButtonItem(image: UIImage(named: "ic_more_vert_white")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), style:.plain, target: self, action: #selector(MediaDisplayViewController.showImageMenu(_:)))
items.append(menuB!)
toolbar.items = items
toolbar.setBackgroundImage(UIImage(),
forToolbarPosition: .any,
barMetrics: .default)
toolbar.setShadowImage(UIImage(), forToolbarPosition: .any)
toolbar.tintColor = UIColor.white
size = UILabel(frame: CGRect(x:5,y: toolbar.bounds.height - 40,width: 250,height: 50))
size?.textAlignment = .left
size?.textColor = .white
size?.text="mb"
size?.font = UIFont.boldSystemFont(ofSize: 12)
toolbar.addSubview(size!)
progressView = MDCProgressView()
progressView?.progress = 0
let progressViewHeight = CGFloat(5)
progressView?.frame = CGRect(x: 0, y: toolbar.bounds.height, width: toolbar.bounds.width, height: progressViewHeight)
toolbar.addSubview(progressView!)
self.view.addSubview(toolbar)
startDisplay()
}
func showTitle(_ sender: AnyObject){
let alertController = MDCAlertController(title: nil, message: text!)
let action = MDCAlertAction(title:"DONE") { (action) in print("OK") }
alertController.addAction(action)
present(alertController, animated: true, completion: nil)
}
func download(_ sender: AnyObject){
UIImageWriteToSavedPhotosAlbum(imageView.image!, nil, nil, nil)
}
func showImageMenu(_ sender: AnyObject){
let alert = UIAlertController.init(title: baseURL?.absoluteString, message: "", preferredStyle: .actionSheet)
let open = OpenInChromeController.init()
if(open.isChromeInstalled()){
alert.addAction(
UIAlertAction(title: "Open in Chrome", style: .default) { (action) in
open.openInChrome(self.baseURL!, callbackURL: nil, createNewTab: true)
}
)
}
alert.addAction(
UIAlertAction(title: "Open in Safari", style: .default) { (action) in
if #available(iOS 10.0, *) {
UIApplication.shared.open(self.baseURL!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(self.baseURL!)
}
}
)
alert.addAction(
UIAlertAction(title: "Share URL", style: .default) { (action) in
let shareItems:Array = [self.baseURL!]
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
let window = UIApplication.shared.keyWindow!
if let modalVC = window.rootViewController?.presentedViewController {
modalVC.present(activityViewController, animated: true, completion: nil)
} else {
window.rootViewController!.present(activityViewController, animated: true, completion: nil)
}
}
)
alert.addAction(
UIAlertAction(title: "Share Image", style: .default) { (action) in
let shareItems:Array = [self.imageView.image!]
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
let window = UIApplication.shared.keyWindow!
if let modalVC = window.rootViewController?.presentedViewController {
modalVC.present(activityViewController, animated: true, completion: nil)
} else {
window.rootViewController!.present(activityViewController, animated: true, completion: nil)
}
}
)
alert.addAction(
UIAlertAction(title: "Cancel", style: .cancel) { (action) in
}
)
let window = UIApplication.shared.keyWindow!
alert.modalPresentationStyle = .popover
if let presenter = alert.popoverPresentationController {
presenter.sourceView = (menuB!.value(forKey: "view") as! UIView)
presenter.sourceRect = (menuB!.value(forKey: "view") as! UIView).bounds
}
if let modalVC = window.rootViewController?.presentedViewController {
modalVC.present(alert, animated: true, completion: nil)
} else {
window.rootViewController!.present(alert, animated: true, completion: nil)
}
}
var showHQ = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func startDisplay(){
if(type == .IMAGE ){
let shouldShowLq = SettingValues.dataSavingEnabled && !(SettingValues.dataSavingDisableWiFi && LinkCellView.checkWiFi())
if(lqURL != nil && !SettingValues.loadContentHQ && shouldShowLq){
loadImage(imageURL: lqURL!)
showHQ = true
} else {
loadImage(imageURL: baseURL!)
}
} else if(type == .GIF || type == .STREAMABLE || type == .VID_ME){
getGif(urlS: baseURL!.absoluteString)
} else if(type == .IMGUR){
loadImage(imageURL: URL.init(string: baseURL!.absoluteString + ".png")!)
} else if(type == .VIDEO){
toolbar.isHidden = true
let he = getYTHeight()
ytPlayer = YTPlayerView.init(frame: CGRect.init(x: 0, y: (self.view.frame.size.height - he)/2, width: self.view.frame.size.width, height: he))
ytPlayer.isHidden = true
self.view.addSubview(ytPlayer)
getYouTube(urlS: baseURL!.absoluteString)
}
}
func getYTHeight() -> CGFloat {
var height = ((self.view.frame.size.width / 16)*9)
return height
}
func getYouTube(urlS: String){
var url = urlS
if(url.contains("#t=")){
url = url.replacingOccurrences(of: "#t=", with: url.contains("?") ? "&t=" : "?t=")
}
let i = URL.init(string: url)
if let dictionary = i?.queryDictionary {
if let t = dictionary["t"]{
millis = getTimeFromString(t);
} else if let start = dictionary["start"] {
millis = getTimeFromString(start);
}
if let list = dictionary["list"]{
playlist = list
}
if let v = dictionary["v"]{
video = v
} else if let w = dictionary["w"]{
video = w
} else if url.lowercased().contains("youtu.be"){
video = getLastPathSegment(url)
}
if let u = dictionary["u"]{
let param = u
video = param.substring(param.indexOf("=")! + 1, length: param.contains("&") ? param.indexOf("&")! : param.length);
}
}
self.ytPlayer.delegate = self
if(!playlist.isEmpty){
ytPlayer.load(withPlaylistId: playlist)
} else {
ytPlayer.load(withVideoId: video, playerVars: ["controls":1,"playsinline":1,"start":millis,"fs":0])
}
}
func getLastPathSegment(_ path: String) -> String {
var inv = path
if(inv.endsWith("/")){
inv = inv.substring(0, length: inv.length - 1)
}
let slashindex = inv.lastIndexOf("/")!
print("Index is \(slashindex)")
inv = inv.substring(slashindex + 1, length: inv.length - slashindex - 1)
return inv
}
var millis = 0
var video = ""
var playlist = ""
func getTimeFromString(_ time: String) -> Int {
var timeAdd = 0;
for s in time.components(separatedBy: CharacterSet.init(charactersIn: "hms")){
print(s)
if(!s.isEmpty){
if(time.contains(s + "s")){
timeAdd += Int(s)!;
} else if(time.contains(s + "m")){
timeAdd += 60 * Int(s)!;
} else if(time.contains(s + "h")){
timeAdd += 3600 * Int(s)!;
}
}
}
if(timeAdd == 0 && Int(time) != nil){
timeAdd+=Int(time)!;
}
return timeAdd * 1000;
}
func loadGfycat(urlString: String){
let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
if error != nil {
print(error ?? "Error loading gif...")
} else {
do {
guard let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary else {
return
}
let gif = GfycatJSONBase.init(dictionary: json)
DispatchQueue.main.async{
self.loadVideo(urlString: (gif?.gfyItem?.mp4Url)!)
}
} catch let error as NSError {
print(error)
}
}
}.resume()
}
func getStreamableObject(urlString: String){
let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
if error != nil {
print(error ?? "Error loading gif...")
} else {
do {
guard let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary else {
return
}
let gif = StreamableJSONBase.init(dictionary: json)
DispatchQueue.main.async{
var video = ""
if let url = gif?.files?.mp4mobile?.url {
video = url
} else {
video = (gif?.files?.mp4?.url!)!
}
if(video.hasPrefix("//")){
video = "https:" + video
}
self.loadVideo(urlString: video)
}
} catch let error as NSError {
print(error)
}
}
}.resume()
}
func getVidMeObject(urlString: String){
let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
if error != nil {
print(error ?? "Error loading gif...")
} else {
do {
guard let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary else {
return
}
let gif = VidMeJSONBase.init(dictionary: json)
DispatchQueue.main.async{
self.loadVideo(urlString: (gif?.video?.complete_url)!)
}
} catch let error as NSError {
print(error)
}
}
}.resume()
}
func getSmallerGfy(gfy: String) -> String {
var gfyUrl = gfy
gfyUrl = gfyUrl.replacingOccurrences(of: "fat", with: "thumbs")
gfyUrl = gfyUrl.replacingOccurrences(of: "giant", with: "thumbs")
gfyUrl = gfyUrl.replacingOccurrences(of: "zippy", with: "thumbs")
if (!gfyUrl.endsWith("-mobile.mp4")){
gfyUrl = gfyUrl.replacingOccurrences(of: "\\.mp4", with: "-mobile.mp4")
}
return gfyUrl;
}
func transcodeGfycat(toTranscode: String){
let url = URL(string: "https://upload.gfycat.com/transcode?fetchUrl=" + toTranscode)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
if error != nil {
print(error ?? "Error loading gif...")
} else {
do {
guard let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary else {
return
}
let gif = GfycatTranscoded.init(dictionary: json)
if let url = (gif?.mobileUrl != nil ? gif?.mobileUrl : gif?.mp4Url) {
DispatchQueue.main.async{
self.loadVideo(urlString: self.getSmallerGfy(gfy: url))
}
} else{
self.loadGfycat(urlString: "https://gfycat.com/cajax/get/" + (gif?.gfyName)!)
}
} catch let error as NSError {
print(error)
}
}
}.resume()
}
func checkLoadGfycat(urlString: String){
let url = URL(string: "https://gfycat.com/cajax/checkUrl/" + urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
if error != nil {
print(error ?? "Error loading gif...")
} else {
do {
guard let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary else {
return
}
let gif = GfycatCheck.init(dictionary: json)
if(gif?.urlKnown == "true"){
DispatchQueue.main.async{
self.loadVideo(urlString: self.getSmallerGfy(gfy: (gif?.mp4Url)!))
}
} else {
self.transcodeGfycat(toTranscode: urlString)
}
} catch let error as NSError {
print(error)
}
}
}.resume()
}
func loadVideo(urlString: String){
refresh(urlString)
}
func getGif(urlS: String){
let url = formatUrl(sS: urlS)
let videoType = getVideoType(url: url)
switch (videoType) {
case .GFYCAT:
let name = url.substring(url.lastIndexOf("/")!, length:url.length - url.lastIndexOf("/")!)
let gfycatUrl = "https://gfycat.com/cajax/get" + name;
loadGfycat(urlString: gfycatUrl)
break
case .DIRECT:
fallthrough
case .IMGUR:
self.loadVideo(urlString: url)
break
case .STREAMABLE:
let hash = url.substring(url.lastIndexOf("/")! + 1, length: url.length - (url.lastIndexOf("/")! + 1));
let streamableUrl = "https://api.streamable.com/videos/" + hash;
getStreamableObject(urlString: streamableUrl)
break
case .VID_ME:
let vidmeUrl = "https://api.vid.me/videoByUrl?url=" + url;
getVidMeObject(urlString: vidmeUrl)
break
case .OTHER:
checkLoadGfycat(urlString: url)
break
}
}
func refresh(_ toLoad:String){
let disallowedChars = CharacterSet.urlPathAllowed.inverted
var key = toLoad.components(separatedBy: disallowedChars).joined(separator: "_")
key = key.replacingOccurrences(of: ":", with: "")
key = key.replacingOccurrences(of: "/", with: "")
key = key.replacingOccurrences(of: ".", with: "")
key = key + ".mp4"
print(key)
if(key.length > 200){
key = key.substring(0, length: 200)
}
if(FileManager.default.fileExists(atPath: SDImageCache.shared().makeDiskCachePath(key)) ){
display(URL.init(fileURLWithPath:SDImageCache.shared().makeDiskCachePath(key)))
} else {
let localUrl = URL.init(fileURLWithPath:SDImageCache.shared().makeDiskCachePath(key))
print(localUrl)
request = Alamofire.download(toLoad, method: .get, to: { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
return (localUrl, [.createIntermediateDirectories])
}).downloadProgress() { progress in
DispatchQueue.main.async {
self.progressView!.progress = Float(progress.fractionCompleted)
let countBytes = ByteCountFormatter()
countBytes.allowedUnits = [.useMB]
countBytes.countStyle = .file
let fileSize = countBytes.string(fromByteCount: Int64(progress.totalUnitCount))
self.size!.text = fileSize
print("Progress is \(progress.fractionCompleted)")
}
}
.responseData { response in
if let error = response.error {
print(error)
} else { //no errors
self.display(localUrl)
print("File downloaded successfully: \(localUrl)")
}
}
}
}
var request: DownloadRequest?
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
request?.cancel()
}
func playerItemDidReachEnd(notification: NSNotification) {
if let playerItem: AVPlayerItem = notification.object as? AVPlayerItem {
playerItem.seek(to: kCMTimeZero)
}
}
func display(_ file: URL){
self.progressView?.setHidden(true, animated: true)
self.size?.isHidden = true
self.scrollView.contentSize = CGSize.init(width: self.view.frame.width, height: self.view.frame.height)
self.scrollView.delegate = self
self.videoPlayer = AVPlayer.init(playerItem: AVPlayerItem.init(url: file))
NotificationCenter.default.addObserver(self,
selector: #selector(MediaDisplayViewController.playerItemDidReachEnd),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: videoPlayer.currentItem)
videoPlayer.actionAtItemEnd = AVPlayerActionAtItemEnd.none
playerVC = AVControlsPlayer()
playerVC.player = videoPlayer
playerVC.videoGravity = AVLayerVideoGravityResizeAspect
playerVC.showsPlaybackControls = false
videoView = playerVC.view
addChildViewController(playerVC)
scrollView.addSubview(videoView)
videoView.frame = CGRect.init(x: 0, y: 50, width: self.view.frame.width, height: self.view.frame.height - 80)
playerVC.didMove(toParentViewController: self)
self.scrollView.isUserInteractionEnabled = true
videoPlayer.play()
}
func formatUrl(sS: String) -> String {
var s = sS
if (s.hasSuffix("v") && !s.contains("streamable.com")) {
s = s.substring(0, length: s.length - 1);
} else if (s.contains("gfycat") && (!s.contains("mp4") && !s.contains("webm"))) {
if (s.contains("-size_restricted")) {s = s.replacingOccurrences(of: "-size_restricted", with: "")}
}
if ((s.contains(".webm") || s.contains(".gif")) && !s.contains(".gifv") && s.contains(
"imgur.com")) {
s = s.replacingOccurrences(of: ".gif", with: ".mp4");
s = s.replacingOccurrences(of: ".webm", with: ".mp4");
}
if (s.endsWith("/")) {s = s.substring(0, length: s.length - 1)}
return s;
}
func getVideoType(url: String) -> VideoType {
if (url.contains(".mp4") || url.contains("webm")) {
return VideoType.DIRECT
}
if (url.contains("gfycat") && !url.contains("mp4")) {
return VideoType.GFYCAT}
if (url.contains("imgur.com")) {return VideoType.IMGUR
}
if (url.contains("vid.me")) {
return VideoType.VID_ME
}
if (url.contains("streamable.com")) {
return VideoType.STREAMABLE
}
return VideoType.OTHER;
}
enum VideoType {
case IMGUR
case VID_ME
case STREAMABLE
case GFYCAT
case DIRECT
case OTHER
}
func playerViewDidBecomeReady(_ playerView: YTPlayerView) {
playerView.isHidden = false
self.ytPlayer.playVideo()
}
/// Prevents delivery of touch gestures to AVPlayerViewController's gesture recognizer,
/// which would cause controls to hide immediately after being shown.
///
/// `-[AVPlayerViewController _handleSingleTapGesture] goes like this:
///
/// if self._showsPlaybackControlsView() {
/// _hidePlaybackControlsViewIfPossibleUntilFurtherUserInteraction()
/// } else {
/// _showPlaybackControlsViewIfNeededAndHideIfPossibleAfterDelayIfPlaying()
/// }
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if !playerVC.showsPlaybackControls {
// print("\nshouldBeRequiredToFailByGestureRecognizer? \(otherGestureRecognizer)")
if let tapGesture = otherGestureRecognizer as? UITapGestureRecognizer {
if tapGesture.numberOfTouchesRequired == 1 {
return true
}
}
}
return false
}
}
| apache-2.0 | 0ee2fa33972b567bd2ae2d5b2d3b025d | 40.899058 | 234 | 0.561884 | 4.962697 | false | false | false | false |
Erickson0806/AdaptivePhotos | AdaptivePhotosUsingUIKitTraitsandSizeClasses/AdaptiveCode/AdaptiveCode/ConversationViewController.swift | 1 | 4261 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that shows the contents of a conversation.
*/
import UIKit
class ConversationViewController: UITableViewController {
// MARK: Properties
let conversation: Conversation
static let cellIdentifier = "PhotoCell"
// MARK: Initialization
init(conversation: Conversation) {
self.conversation = conversation
super.init(style: .Plain)
clearsSelectionOnViewWillAppear = false
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: View Controller
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: ConversationViewController.cellIdentifier)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showDetailTargetDidChange:", name: UIViewControllerShowDetailTargetDidChangeNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
for indexPath in tableView.indexPathsForSelectedRows ?? [] {
let indexPathPushes = willShowingDetailViewControllerPushWithSender(self)
if indexPathPushes {
// If we're pushing for this indexPath, deselect it when we appear.
tableView.deselectRowAtIndexPath(indexPath, animated: animated)
}
}
let visiblePhoto = currentVisibleDetailPhotoWithSender(self)
for indexPath in tableView.indexPathsForVisibleRows ?? [] {
let photo = photoForIndexPath(indexPath)
if photo == visiblePhoto {
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
}
}
}
// This method is originally declared in the PhotoContents extension on `UIViewController`.
override func containsPhoto(photo: Photo) -> Bool {
return conversation.photos.contains(photo)
}
func showDetailTargetDidChange(notification: NSNotification) {
for cell in tableView.visibleCells {
if let indexPath = tableView.indexPathForCell(cell) {
tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath)
}
}
}
// MARK: Table View
func photoForIndexPath(indexPath: NSIndexPath) -> Photo {
return conversation.photos[indexPath.row]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return conversation.photos.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier(ConversationViewController.cellIdentifier, forIndexPath: indexPath)
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let pushes = willShowingDetailViewControllerPushWithSender(self)
// Only show a disclosure indicator if we're pushing.
cell.accessoryType = pushes ? .DisclosureIndicator : .None
let photo = photoForIndexPath(indexPath)
cell.textLabel?.text = photo.comment
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let photo = photoForIndexPath(indexPath)
let controller = PhotoViewController(photo: photo)
let photoNumber = indexPath.row + 1
let photoCount = conversation.photos.count
let localizedStringFormat = NSLocalizedString("%d of %d", comment: "X of X")
controller.title = String.localizedStringWithFormat(localizedStringFormat, photoNumber, photoCount)
// Show the photo as the detail (if possible).
showDetailViewController(controller, sender: self)
}
}
| apache-2.0 | 351dccbd08183714c7d95c6776add3af | 34.789916 | 176 | 0.676919 | 5.964986 | false | false | false | false |
xingerdayu/dayu | dayu/PieView.swift | 1 | 3939 | //
// PieView.swift
// dayu
//
// Created by 王毅东 on 15/9/10.
// Copyright (c) 2015年 Xinger. All rights reserved.
//
import UIKit
class PieView: UIView , UITableViewDataSource, UITabBarDelegate {
var currencys = Array<Comb.Currency>()
var comb : Comb!
@IBOutlet weak var utvUnderPie: UITableView!
@IBOutlet weak var pieView: PieView!
var itemNum = 0
var app = UIApplication.sharedApplication().delegate as! AppDelegate
func createMagicPie(comb:Comb) {
self.comb = comb
currencys = comb.currencys
let cell = UINib(nibName: "UnderPieItem", bundle: nil)
self.utvUnderPie.registerNib(cell, forCellReuseIdentifier: "Cell")
self.utvUnderPie.reloadData()
itemNum = currencys.count % 2 == 0 ? (currencys.count/2) : (currencys.count/2 + 1)
self.utvUnderPie.frame = CGRectMake(10+(app.ScreenWidth-320)/2, 230*app.autoSizeScaleY, 320, CGFloat(45 * itemNum)*app.autoSizeScaleY)
if currencys.count > 0 {
let pieLayer = PieLayer()
pieLayer.frame = CGRectMake(0, 0, 180, 180)
pieView.frame = CGRectMake(80+(app.ScreenWidth-320)/2, 42*app.autoSizeScaleY, 180, 180)
var i = 0
// var startOffset = 160 + (4 - dic.count) * 20
for c in currencys {
let str = Colors.currencyColor[c.key]!
let color = StringUtil.colorWithHexString(str)
pieLayer.addValues([PieElement(value: (c.buyRate), color: color)], animated: true)
// var offset = startOffset + (i * 40)
// var view = UIView(frame: CGRectMake(CGFloat(offset), 250, 5, 5))
// view.backgroundColor = colorArr[i]
// var label = UILabel(frame: CGRectMake(CGFloat(offset + 5), 250, 30, 5))
// label.font = UIFont(name: "Arial", size: 7.0)
// label.text = c.key as? String
// addSubview(view)
// addSubview(label)
i++
}
pieView.layer.cornerRadius = 90
pieView.clipsToBounds = true
pieView.layer.addSublayer(pieLayer)
}
// else {
// noLabel.hidden = false
// }
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(currencys.count % 2 == 0 ? (currencys.count/2) : (currencys.count/2 + 1))
return itemNum
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("cellForRowAtIndexPath")
var cs = Array<Comb.Currency>()
let c1 = currencys[indexPath.row * 2] as Comb.Currency
cs.append(c1)
var c2 : Comb.Currency!
if (currencys.count > indexPath.row * 2 + 1) {
c2 = currencys[indexPath.row * 2 + 1] as Comb.Currency
cs.append(c2)
}
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
var i = 0;
for c in cs {
let color = StringUtil.colorWithHexString(Colors.currencyColor[c.key]!)
let dot = cell.viewWithTag(10 + i) as! UILabel
dot.backgroundColor = color
dot.layer.cornerRadius = 5
dot.clipsToBounds = true
if c.value != "可用保证金" {
dot.text = c.operation == "SELL" ? "空" : "多"
let pro = cell.viewWithTag(13 + i) as! UILabel
pro.text = "当前盈亏$\(StringUtil.formatFloat(c.earning))"
}
let name = cell.viewWithTag(11 + i) as! UILabel
name.text = c.value
let percent = cell.viewWithTag(12 + i) as! UILabel
percent.text = StringUtil.formatFloat(c.buyRate * 100) + "%"
percent.textColor = color
i = 10
}
return cell
}
} | bsd-3-clause | 9020a6eb41317faadbf557bd001e4866 | 40.157895 | 142 | 0.57406 | 4.14089 | false | false | false | false |
josherick/DailySpend | DailySpend/DayReviewViewController.swift | 1 | 7351 | //
// DayReviewViewController.swift
// DailySpend
//
// Created by Josh Sherick on 10/22/17.
// Copyright © 2017 Josh Sherick. All rights reserved.
//
import UIKit
import CoreData
class DayReviewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
var context: NSManagedObjectContext {
return appDelegate.persistentContainer.viewContext
}
var adjustments: [(desc: String, amount: String)]!
var expenses: [(desc: String, amount: String)]!
var formattedPause: (desc: String, range: String)?
var reviewCell: ReviewTableViewCell!
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
adjustments = day.sortedAdjustments?.map { adj in
let formattedAmount = String.formatAsCurrency(amount: adj.amountPerDay!)!
return (desc: adj.shortDescription!, amount: formattedAmount)
} ?? []
expenses = day.sortedExpenses?.map { exp in
let formattedAmount = String.formatAsCurrency(amount: exp.amount!)!
return (desc: exp.shortDescription!, amount: formattedAmount)
} ?? []
if let pause = day.pause {
formattedPause = (desc: pause.shortDescription!, range: pause.humanReadableRange())
}
reviewCell = ReviewTableViewCell(style: .default, reuseIdentifier: nil)
var reviewCellData = [ReviewCellDatum]()
let yesterday = Day.get(context: context, calDay: day.calendarDay!.subtract(days: 1))
let carriedFromYesterday = yesterday?.leftToCarry() ?? 0
let formattedYesterdayCarry = String.formatAsCurrency(amount: carriedFromYesterday)!
reviewCellData.append(ReviewCellDatum(description: "Yesterday's Balance",
value: formattedYesterdayCarry,
color: carriedFromYesterday < 0 ? .overspent : .black,
sign: .None))
if !adjustments.isEmpty {
let totalAdjustments = day.totalAdjustments()
let formattedAdjustments = String.formatAsCurrency(amount: totalAdjustments)!
reviewCellData.append(ReviewCellDatum(description: "Adjustments",
value: formattedAdjustments,
color: .black,
sign: totalAdjustments < 0 ? .Minus : .Plus))
}
if !expenses.isEmpty {
let totalExpenses = day.totalExpenses()
let formattedExpenses = String.formatAsCurrency(amount: totalExpenses)!
reviewCellData.append(ReviewCellDatum(description: "Expenses",
value: formattedExpenses,
color: .black,
sign: totalExpenses < 0 ? .Minus : .Plus))
}
// day.leftToCarry() takes into account pauses, but it'll have to
// recalculate yesterday's carry, which we already have, so just use
// that.
let leftToCarry = day.pause == nil ? day.leftToCarry() : carriedFromYesterday
let formattedCarry = String.formatAsCurrency(amount: leftToCarry)!
reviewCellData.append(ReviewCellDatum(description: "Today's Balance",
value: formattedCarry,
color: leftToCarry < 0 ? .overspent : .black,
sign: .None))
if day.pause != nil {
reviewCell.showPausedNote(true)
}
reviewCell.setLabelData(reviewCellData)
tableView = UITableView(frame: view.bounds, style: .grouped)
tableView.frame = view.bounds
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
enum DayReviewCellType {
case ReviewCell
case PauseCell
case AdjustmentCell
case ExpenseCell
}
func cellTypeForSection(_ section: Int) -> DayReviewCellType {
if section == 1 {
if day.pause != nil {
return .PauseCell
} else if !adjustments.isEmpty {
return .AdjustmentCell
} else {
return .ExpenseCell
}
}
if section == 2 {
if !adjustments.isEmpty {
return .AdjustmentCell
} else {
return .ExpenseCell
}
}
if section == 3 {
return .ExpenseCell
}
return .ReviewCell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "value")
if cell == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: "value")
}
cell.detailTextLabel?.textColor = UIColor.black
switch cellTypeForSection(indexPath.section) {
case .ReviewCell:
return reviewCell
case .PauseCell:
cell.textLabel!.text = formattedPause!.desc
cell.detailTextLabel!.text = formattedPause!.range
case .AdjustmentCell:
cell.textLabel!.text = adjustments[indexPath.row].desc
cell.detailTextLabel!.text = adjustments[indexPath.row].amount
case .ExpenseCell:
cell.textLabel!.text = expenses[indexPath.row].desc
cell.detailTextLabel!.text = expenses[indexPath.row].amount
}
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch cellTypeForSection(section) {
case .PauseCell:
return "Pause"
case .AdjustmentCell:
return "Adjustments"
case .ExpenseCell:
return "Expenses"
case .ReviewCell:
return nil
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch cellTypeForSection(indexPath.section) {
case .ReviewCell:
return reviewCell.desiredHeightForCurrentState()
default:
return 44
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch cellTypeForSection(section) {
case .PauseCell:
return 1
case .AdjustmentCell:
return adjustments.count
case .ExpenseCell:
return expenses.count
case .ReviewCell:
return 1
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1 +
(day.pause == nil ? 0 : 1) +
(adjustments.isEmpty ? 0 : 1) +
(expenses.isEmpty ? 0 : 1)
}
}
| mit | 7eecefa05206c9e079b40849d8b2a9ac | 36.121212 | 100 | 0.565578 | 5.572403 | false | false | false | false |
tensorflow/swift-apis | Sources/TensorFlow/StdlibExtensions.swift | 1 | 11019 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
@_exported import _Differentiation
#if TENSORFLOW_USE_STANDARD_TOOLCHAIN
@_exported import Numerics
#endif
#if !TENSORFLOW_USE_STANDARD_TOOLCHAIN
// MARK: - Array extensions
extension Array: ElementaryFunctions where Element: ElementaryFunctions {
/// The square root of `x`.
///
/// For real types, if `x` is negative the result is `.nan`. For complex
/// types there is a branch cut on the negative real axis.
public static func sqrt(_ x: Self) -> Self { x.map(Element.sqrt) }
/// The cosine of `x`, interpreted as an angle in radians.
public static func cos(_ x: Self) -> Self { x.map(Element.cos) }
/// The sine of `x`, interpreted as an angle in radians.
public static func sin(_ x: Self) -> Self { x.map(Element.sin) }
/// The tangent of `x`, interpreted as an angle in radians.
public static func tan(_ x: Self) -> Self { x.map(Element.tan) }
/// The inverse cosine of `x` in radians.
public static func acos(_ x: Self) -> Self { x.map(Element.acos) }
/// The inverse sine of `x` in radians.
public static func asin(_ x: Self) -> Self { x.map(Element.asin) }
/// The inverse tangent of `x` in radians.
public static func atan(_ x: Self) -> Self { x.map(Element.atan) }
/// The hyperbolic cosine of `x`.
public static func cosh(_ x: Self) -> Self { x.map(Element.cosh) }
/// The hyperbolic sine of `x`.
public static func sinh(_ x: Self) -> Self { x.map(Element.sinh) }
/// The hyperbolic tangent of `x`.
public static func tanh(_ x: Self) -> Self { x.map(Element.tanh) }
/// The inverse hyperbolic cosine of `x`.
public static func acosh(_ x: Self) -> Self { x.map(Element.acosh) }
/// The inverse hyperbolic sine of `x`.
public static func asinh(_ x: Self) -> Self { x.map(Element.asinh) }
/// The inverse hyperbolic tangent of `x`.
public static func atanh(_ x: Self) -> Self { x.map(Element.atanh) }
/// The exponential function applied to `x`, or `e**x`.
public static func exp(_ x: Self) -> Self { x.map(Element.exp) }
/// Two raised to to power `x`.
public static func exp2(_ x: Self) -> Self { x.map(Element.exp2) }
/// Ten raised to to power `x`.
public static func exp10(_ x: Self) -> Self { x.map(Element.exp10) }
/// `exp(x) - 1` evaluated so as to preserve accuracy close to zero.
public static func expm1(_ x: Self) -> Self { x.map(Element.expm1) }
/// The natural logarithm of `x`.
public static func log(_ x: Self) -> Self { x.map(Element.log) }
/// The base-two logarithm of `x`.
public static func log2(_ x: Self) -> Self { x.map(Element.log2) }
/// The base-ten logarithm of `x`.
public static func log10(_ x: Self) -> Self { x.map(Element.log10) }
/// `log(1 + x)` evaluated so as to preserve accuracy close to zero.
public static func log1p(_ x: Self) -> Self { x.map(Element.log1p) }
/// `exp(y log(x))` computed without loss of intermediate precision.
///
/// For real types, if `x` is negative the result is NaN, even if `y` has
/// an integral value. For complex types, there is a branch cut on the
/// negative real axis.
public static func pow(_ x: Self, _ y: Self) -> Self {
precondition(x.count == y.count)
return zip(x, y).map(Element.pow)
}
/// `x` raised to the `n`th power.
///
/// The product of `n` copies of `x`.
public static func pow(_ x: Self, _ n: Int) -> Self { x.map { Element.pow($0, n) } }
/// The `n`th root of `x`.
///
/// For real types, if `x` is negative and `n` is even, the result is NaN.
/// For complex types, there is a branch cut along the negative real axis.
public static func root(_ x: Self, _ n: Int) -> Self { x.map { Element.root($0, n) } }
}
#endif
// MARK: - Array derivative extensions
extension Array.DifferentiableView: ElementaryFunctions
where Element: Differentiable & ElementaryFunctions {
/// The square root of `x`.
///
/// For real types, if `x` is negative the result is `.nan`. For complex
/// types there is a branch cut on the negative real axis.
public static func sqrt(_ x: Self) -> Self { .init(x.map(Element.sqrt)) }
/// The cosine of `x`, interpreted as an angle in radians.
public static func cos(_ x: Self) -> Self { .init(x.map(Element.cos)) }
/// The sine of `x`, interpreted as an angle in radians.
public static func sin(_ x: Self) -> Self { .init(x.map(Element.sin)) }
/// The tangent of `x`, interpreted as an angle in radians.
public static func tan(_ x: Self) -> Self { .init(x.map(Element.tan)) }
/// The inverse cosine of `x` in radians.
public static func acos(_ x: Self) -> Self { .init(x.map(Element.acos)) }
/// The inverse sine of `x` in radians.
public static func asin(_ x: Self) -> Self { .init(x.map(Element.asin)) }
/// The inverse tangent of `x` in radians.
public static func atan(_ x: Self) -> Self { .init(x.map(Element.atan)) }
/// The hyperbolic cosine of `x`.
public static func cosh(_ x: Self) -> Self { .init(x.map(Element.cosh)) }
/// The hyperbolic sine of `x`.
public static func sinh(_ x: Self) -> Self { .init(x.map(Element.sinh)) }
/// The hyperbolic tangent of `x`.
public static func tanh(_ x: Self) -> Self { .init(x.map(Element.tanh)) }
/// The inverse hyperbolic cosine of `x`.
public static func acosh(_ x: Self) -> Self { .init(x.map(Element.acosh)) }
/// The inverse hyperbolic sine of `x`.
public static func asinh(_ x: Self) -> Self { .init(x.map(Element.asinh)) }
/// The inverse hyperbolic tangent of `x`.
public static func atanh(_ x: Self) -> Self { .init(x.map(Element.atanh)) }
/// The exponential function applied to `x`, or `e**x`.
public static func exp(_ x: Self) -> Self { .init(x.map(Element.exp)) }
#if !TENSORFLOW_USE_STANDARD_TOOLCHAIN
/// Two raised to to power `x`.
public static func exp2(_ x: Self) -> Self { .init(Array.exp2(x.base)) }
/// Ten raised to to power `x`.
public static func exp10(_ x: Self) -> Self { .init(Array.exp10(x.base)) }
/// `exp(x) - 1` evaluated so as to preserve accuracy close to zero.
public static func expm1(_ x: Self) -> Self { .init(Array.expm1(x.base)) }
#else
/// `exp(x) - 1` evaluated so as to preserve accuracy close to zero.
public static func expMinusOne(_ x: Self) -> Self { .init(x.map(Element.expMinusOne)) }
#endif
/// The natural logarithm of `x`.
public static func log(_ x: Self) -> Self { .init(x.map { Element.exp($0) }) }
#if !TENSORFLOW_USE_STANDARD_TOOLCHAIN
/// The base-two logarithm of `x`.
public static func log2(_ x: Self) -> Self { .init(Array.log2(x.base)) }
/// The base-ten logarithm of `x`.
public static func log10(_ x: Self) -> Self { .init(Array.log10(x.base)) }
/// `log(1 + x)` evaluated so as to preserve accuracy close to zero.
public static func log1p(_ x: Self) -> Self {
.init(Array.log1p(x.base))
}
#else
/// The natural logarithm of `x + 1` to preserve accuracy close to zero.
public static func log(onePlus x: Self) -> Self {
.init(x.map { Element.log(onePlus: $0) })
}
#endif
/// `exp(y log(x))` computed without loss of intermediate precision.
///
/// For real types, if `x` is negative the result is NaN, even if `y` has
/// an integral value. For complex types, there is a branch cut on the
/// negative real axis.
public static func pow(_ x: Self, _ y: Self) -> Self { .init(zip(x, y).map(Element.pow)) }
/// `x` raised to the `n`th power.
///
/// The product of `n` copies of `x`.
public static func pow(_ x: Self, _ n: Int) -> Self { .init(x.map { Element.pow($0, n) }) }
/// The `n`th root of `x`.
///
/// For real types, if `x` is negative and `n` is even, the result is NaN.
/// For complex types, there is a branch cut along the negative real axis.
public static func root(_ x: Self, _ n: Int) -> Self { .init(x.map { Element.root($0, n) }) }
}
extension Array.DifferentiableView:
BidirectionalCollection,
Collection,
MutableCollection,
RandomAccessCollection,
RangeReplaceableCollection,
Sequence
where Element: Differentiable {
public typealias Element = Array<Element>.Element
public typealias Index = Array<Element>.Index
public typealias Indices = Array<Element>.Indices
public typealias SubSequence = Array<Element>.SubSequence
@inlinable
public subscript(position: Array<Element>.Index) -> Element {
_read { yield base[position] }
set { base[position] = newValue }
}
@inlinable
public var startIndex: Index { base.startIndex }
@inlinable
public var endIndex: Index { base.endIndex }
@inlinable
public init() { self.init(.init()) }
}
extension Array.DifferentiableView: VectorProtocol
where Element: Differentiable & VectorProtocol {
public typealias VectorSpaceScalar = Element.VectorSpaceScalar
public func adding(_ x: Element.VectorSpaceScalar) -> Array<Element>.DifferentiableView {
.init(map { $0.adding(x) })
}
public mutating func add(_ x: Element.VectorSpaceScalar) {
for i in indices {
self[i].add(x)
}
}
public func subtracting(_ x: Element.VectorSpaceScalar) -> Array<Element>.DifferentiableView {
.init(map { $0.subtracting(x) })
}
public mutating func subtract(_ x: Element.VectorSpaceScalar) {
for i in indices {
self[i].subtract(x)
}
}
public func scaled(by scale: Element.VectorSpaceScalar) -> Self {
.init(map { $0.scaled(by: scale) })
}
public mutating func scale(by scale: Element.VectorSpaceScalar) {
for i in indices {
self[i].scale(by: scale)
}
}
}
extension Array.DifferentiableView: PointwiseMultiplicative
where Element: Differentiable & PointwiseMultiplicative {
// FIXME: `one` should probably be removed from the protocol. `Array` cannot represent `one`.
public static var one: Self {
fatalError("One is not array-representable")
}
public var reciprocal: Self { .init(map { $0.reciprocal }) }
public static func .* (lhs: Self, rhs: Self) -> Self {
precondition(lhs.count == rhs.count, "Count mismatch: \(lhs.count) and \(rhs.count)")
return .init(zip(lhs, rhs).map(.*))
}
public static func .*= (lhs: inout Self, rhs: Self) {
precondition(lhs.count == rhs.count, "Count mismatch: \(lhs.count) and \(rhs.count)")
for (i, x) in zip(lhs.indices, rhs) {
lhs[i] .*= x
}
}
}
extension Collection {
/// Returns the `n`th position in `self`.
func index(atOffset n: Int) -> Index { index(startIndex, offsetBy: n) }
}
| apache-2.0 | a062ba5d229e70f34a517b94a5857462 | 34.892508 | 96 | 0.654687 | 3.518199 | false | false | false | false |
erikmartens/NearbyWeather | NearbyWeather/Commons/Factory/Factory+UIButton.swift | 1 | 1591 | //
// Factory+UIButton.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 12.04.20.
// Copyright © 2020 Erik Maximilian Martens. All rights reserved.
//
import UIKit.UIButton
extension Factory {
struct Button: FactoryFunction {
enum ButtonType {
case standard(title: String? = nil, height: CGFloat)
case plain(title: String? = nil)
}
typealias InputType = ButtonType
typealias ResultType = UIButton
static func make(fromType type: InputType) -> ResultType {
let button = UIButton()
switch type {
case let .standard(title, height):
button.layer.cornerRadius = height/4
button.layer.backgroundColor = Constants.Theme.Color.InteractableElement.standardButtonBackground.cgColor
button.titleLabel?.font = .preferredFont(forTextStyle: .headline)
button.setTitleColor(.white, for: .normal)
button.setTitleColor(.white.withAlphaComponent(0.5), for: .highlighted)
if let title = title {
button.setTitle(title, for: UIControl.State())
}
case let .plain(title):
button.titleLabel?.font = .preferredFont(forTextStyle: .body)
button.setTitleColor(Constants.Theme.Color.InteractableElement.standardButtonBackground, for: .normal)
button.setTitleColor(Constants.Theme.Color.InteractableElement.standardButtonBackground.withAlphaComponent(0.5), for: .highlighted)
if let title = title {
button.setTitle(title, for: UIControl.State())
}
}
return button
}
}
}
| mit | de8b5c4b8f38f761b6b3fd510ed7988b | 29.576923 | 139 | 0.671069 | 4.608696 | false | false | false | false |
ParadropLabs/riffle-swift | Pod/Classes/BaseModel.swift | 1 | 1507 | //
// BaseModel.swift
// Pods
//
// Created by Mickey Barboi on 10/6/15.
//
//
import Foundation
import Mantle
public class RiffleModel : MTLModel, MTLJSONSerializing, Cuminicable {
// var id = Int(arc4random_uniform(UInt32.max))
// override public func isEqual(object: AnyObject?) -> Bool {
// if object_getClassName(self) != object_getClassName(object) {
// return false
// }
//
// if let object = object as? RiffleModel {
// return id == object.id
// } else {
// return false
// }
// }
//Boilerplate Mantle code
public class func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]! {
return [:]
}
public static func convert(object: AnyObject) -> Cuminicable? {
if let a = object as? [NSObject: AnyObject] {
return MTLJSONAdapter.modelOfClass(self, fromJSONDictionary: a) as? Cuminicable
}
return nil
}
//MARK: Old Placeholder Methods
// required override public init() {
// super.init()
//
// // A random integer. Have to deal with colliding ids. This is an ok base case
// id = Int(arc4random_uniform(UInt32.max))
// }
// func serialize() -> [String:AnyObject] {
// return [:]
// }
//
// func deserialize(json: [String:AnyObject]) {
//
// }
} | mit | bae75444c4bb2fc3c5a9680d6094e31d | 24.559322 | 91 | 0.523557 | 4.174515 | false | false | false | false |
jcsla/MusicoAudioPlayer | Example/MusicoAudioPlayer/ViewController.swift | 1 | 2630 | //
// ViewController.swift
// MusicoAudioPlayer
//
// Created by [email protected] on 05/11/2017.
// Copyright (c) 2017 [email protected]. All rights reserved.
//
import UIKit
import MusicoAudioPlayer
import SDWebImage
class ViewController: UIViewController, AudioPlayerDelegate {
var player: AudioPlayer?
var item: AudioItem?
@IBOutlet weak var thumbnail: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
player = AudioPlayer()
player?.delegate = self
let url = "http://api.musico.kr:8080/mp3/a.mp3";
item = AudioItem(mediumQualitySoundURL: URL(string: url))
item?.title = "title"
item?.artist = "artist"
item?.artworkImageUrl = "https://i1.sndcdn.com/artworks-000221899583-k5171v-t500x500.jpg"
}
func foo(completionHandler: @escaping CompletionHandler){
print("foo")
completionHandler(false,"fail to foo")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func clickPlayBtn(_ sender: Any) {
print("clickPlayBtn")
player?.play(item: item!)
}
func audioPlayer(_ audioPlayer: AudioPlayer, didChangeStateFrom from: AudioPlayerState,
to state: AudioPlayerState) {
print("didChangeStateFrom")
}
func audioPlayer(_ audioPlayer: AudioPlayer, willStartPlaying item: AudioItem) {
print("willStartPlaying")
self.setThumbnail(image: item.artworkImage!)
}
func audioPlayer(_ audioPlayer: AudioPlayer, didUpdateProgressionTo time: TimeInterval, percentageRead: Float) {
print("didUpdateProgressionTo")
}
func audioPlayer(_ audioPlayer: AudioPlayer, didFindDuration duration: TimeInterval, for item: AudioItem) {
print("didFindDuration")
}
func audioPlayer(_ audioPlayer: AudioPlayer, didUpdateEmptyMetadataOn item: AudioItem, withData data: Metadata) {
print("didUpdateEmptyMetadataOn")
}
func audioPlayer(_ audioPlayer: AudioPlayer, didLoad range: TimeRange, for item: AudioItem) {
print("didLoad")
}
func audioPlayer(_ audioPlayer: AudioPlayer, didGetStreamUrlFromId: AudioItem, id: Int, completionHandler: @escaping CompletionHandler) {
print("didGetStreamUrlFromId on controller")
foo(completionHandler: completionHandler)
}
func setThumbnail(image: UIImage) {
DispatchQueue.main.async {
self.thumbnail.image = image
}
}
}
| mit | 88d3b3bca56d01f4ae246c9db1b55760 | 29.941176 | 141 | 0.663118 | 4.696429 | false | false | false | false |
WE-St0r/SwiftyVK | Library/Tests/DependenciesTests.swift | 2 | 4236 | import Foundation
import XCTest
@testable import SwiftyVK
final class DependenciesTests: XCTestCase {
func test_makeAuthorizator_typeIsAuthorizatorImpl() {
// Given
let context = makeContext()
// When
let object = context.factory.authorizator
// Then
XCTAssertTrue(type(of: object) == AuthorizatorImpl.self)
}
func test_makeAttempt_typeIsAttemptImpl() {
// Given
let context = makeContext()
// When
let object = context.factory.attempt(request: URLRequest(url: URL(fileURLWithPath: "")), callbacks: .default)
// Then
XCTAssertTrue(type(of: object) == AttemptImpl.self)
}
func test_makeSession_typeIsSessionImpl() {
// Given
let context = makeContext()
context.factory.sessionsStorage = SessionsStorageMock()
context.factory.authorizator = AuthorizatorMock()
// When
let object = context.factory.session(id: "", config: .default, sessionSaver: SessionsHolderMock())
// Then
XCTAssertTrue(type(of: object) == SessionImpl.self)
}
func test_makeWebController_typeIsWebControllerPLATFORM() {
// Given
let context = makeContext()
// When
let object = context.factory.webController(onDismiss: nil)
// Then
#if os(iOS)
XCTAssertTrue(type(of: object) == WebControllerIOS.self)
#elseif os(macOS)
XCTAssertTrue(type(of: object) == WebControllerMacOS.self)
#endif
}
func test_makeCaptchaController_typeIsCaptchaControllerPLATFORM() {
// Given
let context = makeContext()
// When
let object = context.factory.captchaController(onDismiss: nil)
// Then
#if os(iOS)
XCTAssertTrue(type(of: object) == CaptchaControllerIOS.self)
#elseif os(macOS)
XCTAssertTrue(type(of: object) == CaptchaControllerMacOS.self)
#endif
}
func test_makeShareController_typeIsShareControllerImpl() {
// Given
let context = makeContext()
// When
let object = context.factory.shareController(onDismiss: nil)
// Then
#if os(iOS)
XCTAssertTrue(type(of: object) == ShareControllerIOS.self)
#elseif os(macOS)
XCTAssertTrue(type(of: object) == ShareControllerMacOS.self)
#endif
}
func test_makeTask_typeIsTaskImpl() {
// Given
let context = makeContext()
// When
let object = context.factory.task(request: Request(type: .url("")), session: SessionMock())
// Then
XCTAssertTrue(type(of: object) == TaskImpl.self)
}
func test_makeLongPollTask_typeIsLongPollTaskImpl() {
// Given
let context = makeContext()
// When
let object = context.factory.longPollTask(
session: SessionMock(),
data: LongPollTaskData(server: "", startTs: "", lpKey: "", onResponse: { _ in }, onError: { _ in } )
)
// Then
XCTAssertTrue(type(of: object) == LongPollTaskImpl.self)
}
func test_makeLongPoll_typeIsLongPollImpl() {
// Given
let context = makeContext()
// When
let object = context.factory.longPoll(session: SessionMock())
// Then
XCTAssertTrue(type(of: object) == LongPollImpl.self)
}
func test_makeToken_typeIsTokenImpl() {
// Given
let context = makeContext()
// When
let object = context.factory.token(token: "", expires: 0, info: [:])
// Then
XCTAssertTrue(type(of: object) == TokenImpl.self)
}
func test_makeSharePresenter_typeIsSharePresenterImpl() {
// Given
let context = makeContext()
// When
let object = context.factory.sharePresenter()
// Then
XCTAssertTrue(type(of: object) == SharePresenterImpl.self)
}
}
private func makeContext() -> (factory: DependenciesImpl, delegate: SwiftyVKDelegateMock) {
let delegate = SwiftyVKDelegateMock()
let factory = DependenciesImpl(appId: "123", delegate: delegate)
return (factory, delegate)
}
| mit | 768e6648dcee794c5b917021801f134f | 31.837209 | 117 | 0.602691 | 4.584416 | false | true | false | false |
kiliankoe/ParkenDD | ParkenDD/MapView/MapViewController.swift | 1 | 3265 | //
// MapViewController.swift
// ParkenDD
//
// Created by Kilian Költzsch on 09/03/15.
// Copyright (c) 2015 Kilian Koeltzsch. All rights reserved.
//
import UIKit
import MapKit
import ParkKit
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView?
var detailParkinglot: Lot!
var allParkinglots: [Lot]!
override func viewDidLoad() {
super.viewDidLoad()
mapView?.showsUserLocation = true
if #available(iOS 9, *) {
mapView?.showsTraffic = true
}
// Add annotations for all parking lots to the map
for singleLot in allParkinglots {
var subtitle = L10n.mapsubtitle("\(singleLot.free)", singleLot.total).string
switch singleLot.state {
case .closed:
subtitle = L10n.closed.string
case .nodata:
subtitle = L10n.mapsubtitle("?", singleLot.total).string
case .open, .unknown:
break
}
let lotAnnotation = ParkinglotAnnotation(title: singleLot.name, subtitle: subtitle, lot: singleLot)
mapView?.addAnnotation(lotAnnotation)
// Display the callout if this is the previously selected annotation
if singleLot.name == detailParkinglot.name {
mapView?.selectAnnotation(lotAnnotation, animated: true)
}
}
// Set the map's region to a 1km region around the selected lot
if let lat = detailParkinglot.coordinate?.latitude, let lng = detailParkinglot.coordinate?.longitude {
let parkinglotRegion = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2D(latitude: lat, longitude: lng), 1000, 1000)
mapView?.setRegion(parkinglotRegion, animated: false)
} else {
NSLog("Came to map view with a selected lot that has no coordinates. We're now showing Germany. This is probably not ideal.")
}
// Display the forecast button if this lot has forecast data
if detailParkinglot.hasForecast {
navigationItem.rightBarButtonItem = UIBarButtonItem(title: L10n.forecast.string, style: .plain, target: self, action: #selector(MapViewController.showForecastController))
}
}
/**
Transition to forecast controller
*/
@objc func showForecastController() {
let forecastController = ForecastViewController()
forecastController.lot = detailParkinglot
show(forecastController, sender: self)
}
// It's nice to show custom pin colors on the map denoting the current state of the parking lot they're referencing
// green: open, unknown (if more than 0 free, otherwise red)
// red: closed, nodata
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// We don't care about the MKUserLocation here
guard annotation.isKind(of: ParkinglotAnnotation.self) else { return nil }
let annotation = annotation as? ParkinglotAnnotation
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "parkinglotAnnotation")
if let state = annotation?.lot.state {
switch state {
case .closed:
annotationView.pinColor = .red
case .open, .unknown:
annotationView.pinColor = annotation?.lot.free != 0 ? .green : .red
case .nodata:
annotationView.pinColor = .purple
}
}
annotationView.canShowCallout = true
return annotationView
}
}
| mit | 8caa73b6745a59127a7cca7efa4c698c | 31.969697 | 173 | 0.716299 | 4.277851 | false | false | false | false |
mwise/Redux.swift | ReduxSwiftDemo-iOS/ViewController.swift | 1 | 918 | //
// ViewController.swift
// ReduxSwiftDemo-iOS
//
// Created by Mark Wise on 11/7/15.
//
//
import UIKit
import Redux
private let store = CounterStore.sharedInstance;
private let actions = bindActionCreators(CounterActionCreators, dispatch: store.dispatch)
class ViewController: UIViewController {
var label: UILabel!;
override func viewDidLoad() {
super.viewDidLoad()
label = UILabel(frame: CGRectMake(10, 100, view.frame.width, 40))
view.addSubview(label)
func render() {
let state = store.getState() as! AppState
let count = state["count"] as! Int;
label.text = "You've clicked \(count) times."
}
_ = store.subscribe(listener: render);
render()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
actions["Increment"]!()
}
}
| mit | 1816af5791b44a4c047d0f16e89a0d19 | 20.348837 | 89 | 0.681917 | 4.098214 | false | false | false | false |
benlangmuir/swift | test/Interpreter/SDK/mixed_mode_class_with_missing_properties.swift | 9 | 2314 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// CMO does not work because of a deserialization failure: rdar://86575886
// RUN: %target-build-swift -Xllvm -sil-disable-pass=cmo -whole-module-optimization -emit-module-path %t/UsingObjCStuff.swiftmodule -c -o %t/UsingObjCStuff.o -module-name UsingObjCStuff -I %t -I %S/Inputs/mixed_mode -swift-version 5 -parse-as-library %S/Inputs/mixed_mode/UsingObjCStuff.swift
// RUN: %target-build-swift -o %t/a.out.v4 -I %t -I %S/Inputs/mixed_mode -module-name main -swift-version 4 %t/main.swift %t/UsingObjCStuff.o
// RUN: %target-build-swift -o %t/a.out.v5 -I %t -I %S/Inputs/mixed_mode -module-name main -swift-version 5 %t/main.swift %t/UsingObjCStuff.o
// RUN: %target-codesign %t/a.out.v4
// RUN: %target-codesign %t/a.out.v5
// RUN: %target-run %t/a.out.v4 | %FileCheck %s
// RUN: %target-run %t/a.out.v5 | %FileCheck %s
// REQUIRES: objc_interop
// REQUIRES: executable_test
import UsingObjCStuff
print("Let's go") // CHECK: Let's go
let holder = ButtHolder()
holder.x += 17
print(holder.x) // CHECK-NEXT: 17
holder.x += 38
print(holder.x) // CHECK-NEXT: 55
holder.z += "hello"
print(holder.z) // CHECK-NEXT: hello
holder.z += " world"
print(holder.z) // CHECK-NEXT: hello world
holder.virtual() // CHECK-NEXT: 55 [:] hello world
class SubButtHolder: ButtHolder {
final var w: Double = 0
override func virtual() {
print("~* ", terminator: "")
super.virtual()
print(" \(w) *~")
}
func subVirtual() {
print("~* \(x) ~*~ \(z) ~*~ \(w) *~")
}
}
class SubSubButtHolder: SubButtHolder {
override func virtual() {
print("!!! ", terminator: "")
super.virtual()
print(" !!!")
}
override func subVirtual() {
print("!!! ", terminator: "")
super.subVirtual()
print(" !!!")
}
}
@inline(never)
func exerciseSubHolder(with subHolder: SubButtHolder) {
subHolder.x = 679
subHolder.z = "goodbye folks"
subHolder.w = 90.5
subHolder.virtual() // CHECK-NEXT: !!! ~* 679 [:] goodbye folks
// CHECK-NEXT: 90.5 *~
// CHECK-NEXT: !!!
subHolder.subVirtual() // CHECK-NEXT: !!! ~* 679 ~*~ goodbye folks ~*~ 90.5 *~
// CHECK-NEXT: !!!
}
exerciseSubHolder(with: SubSubButtHolder())
print("OK that's it") // CHECK-NEXT: OK that's it
| apache-2.0 | 9d2e2e927da96ac0c5a39379b370eddf | 29.853333 | 292 | 0.628781 | 3.093583 | false | false | false | false |
LQJJ/demo | 86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/other/custom/DZMSegmentedControl.swift | 1 | 9055 | //
// DZMSegmentedControl.swift
// DZMeBookRead
//
// Created by 邓泽淼 on 2017/3/24.
// Copyright © 2017年 DZM. All rights reserved.
//
import UIKit
@objc protocol DZMSegmentedControlDelegate:NSObjectProtocol {
/// 点击按钮
@objc optional func segmentedControl(segmentedControl:DZMSegmentedControl, clickButton button:UIButton, index:NSInteger)
}
class DZMSegmentedControl: UIView {
/// 代理
weak var delegate:DZMSegmentedControlDelegate?
/// 默认图片
var normalImages = [String]()
/// 选中图片
var selectImages = [String]()
/// 默认文字
var normalTitles = [String]()
/// 选中文字
var selectTitles = [String]()
/// 默认文字颜色
var normalTitleColor:UIColor = UIColor.black
/// 选中文字颜色
var selectTitleColor:UIColor = UIColor.orange
/// 字体大小
var font:UIFont = UIFont.systemFont(ofSize: 14)
/// 图片文字中间间距
var buttonCenterSpaceW:CGFloat = 5
/// 垂直分割线颜色
var verticalSpaceLineColor:UIColor = UIColor.lightGray
/// 垂直分割线宽
var verticalSpaceLineW:CGFloat = 0.5
/// 隐藏垂直分割线
var hiddenVerticalSpaceLine:Bool = false
/// 水平分割线颜色
var horizontalSpaceLineColor:UIColor = UIColor.lightGray
/// 水平分割线高
var horizontalSpaceLineH:CGFloat = 0.5
/// 隐藏水平分割线
var hiddenHorizontalSpaceLine:Bool = false
/// 水平分割线 YES:显示顶部 NO:显示底部
var horizontalShowTB:Bool = true
/// 开启点击自动进行选中取消
var openClickSelected:Bool = true
/// 开启点击只允许存在一个按钮选中
var openClickOnlySelected:Bool = true
/// 开启初始化选中
var openInitClickSelected:Bool = true
/// 当前选中的按钮 当 openClickOnlySelected = false 时则只会记录最后一次点击的索引
var selectIndex:NSInteger = 0 {
didSet{
if !buttons.isEmpty && selectIndex != oldValue {
clickButton(button: buttons[selectIndex])
}
}
}
/// 垂直分割线数组
private var verticalSpaceLines:[UIView] = []
/// 水平分割线
private var horizontalSpaceLine:UIView?
/// 按钮数组
private(set) var buttons:[UIButton] = []
/// 记录选中按钮 当 openClickOnlySelected = false 时则只会记录最后一次点击的按钮
private(set) var selectButton:UIButton?
/// 配置
func setup() {
for button in buttons {
button.removeFromSuperview()
}
for spaceLine in verticalSpaceLines {
spaceLine.removeFromSuperview()
}
horizontalSpaceLine?.removeFromSuperview()
buttons.removeAll()
verticalSpaceLines.removeAll()
addSubviews()
}
/// 取消全部按钮选中状态
func cancalButtonsSelected() {
for button in buttons {
button.isSelected = false
}
}
init(_ delegate:DZMSegmentedControlDelegate? = nil) {
super.init(frame: CGRect.zero)
// 代理
self.delegate = delegate
// 背景颜色
backgroundColor = UIColor.white
}
/// 创建子控件
private func addSubviews() {
// 数量
let count = max(normalTitles.count, normalImages.count)
// 创建
for i in 0..<count {
let button:UIButton = UIButton(type: .custom)
button.tag = i
if !normalTitles.isEmpty || !selectTitles.isEmpty {
button.titleLabel?.font = font
}
if !normalImages.isEmpty && !normalTitles.isEmpty {
button.titleEdgeInsets = UIEdgeInsetsMake(0, buttonCenterSpaceW, 0, 0)
}
if !normalTitles.isEmpty {
button.setTitle(normalTitles[i], for: .normal)
button.setTitleColor(normalTitleColor, for: .normal)
}
if !selectTitles.isEmpty {
button.setTitle(selectTitles[i], for: .selected)
button.setTitleColor(selectTitleColor, for: .selected)
}
if !normalImages.isEmpty {
button.setImage(UIImage(named: normalImages[i]), for: .normal)
}
if !selectImages.isEmpty {
button.setImage(UIImage(named: selectImages[i]), for: .selected)
}
button.addTarget(self, action: #selector(DZMSegmentedControl.clickButton(button:)), for: .touchDown)
addSubview(button)
buttons.append(button)
}
// 分割线
if !hiddenVerticalSpaceLine && !buttons.isEmpty {
let count = buttons.count - 1
for _ in 0..<count {
let spaceLine = SpaceLineSetup(view: self, color: verticalSpaceLineColor)
addSubview(spaceLine)
verticalSpaceLines.append(spaceLine)
}
}
if !hiddenHorizontalSpaceLine {
horizontalSpaceLine = SpaceLineSetup(view: self, color: horizontalSpaceLineColor)
}
// 选中按钮
if !buttons.isEmpty && openInitClickSelected {clickButton(button: buttons[selectIndex])}
// 布局
setNeedsLayout()
}
/// 点击按钮
@objc private func clickButton(button:UIButton) {
if openClickSelected {
if openClickOnlySelected {
if selectButton == button {return}
selectButton?.isSelected = false
}
button.isSelected = !button.isSelected
selectButton = button
}
selectIndex = button.tag
delegate?.segmentedControl?(segmentedControl: self, clickButton: button, index: selectIndex)
}
// 布局
override func layoutSubviews() {
super.layoutSubviews()
if !buttons.isEmpty {
// 数量
let count = buttons.count
// 按钮宽
var buttonW:CGFloat = width / CGFloat(count)
// 按钮高
var buttonH:CGFloat = height
// 按钮Y
var buttonY:CGFloat = horizontalSpaceLineH
// 隐藏垂直分割线
if !hiddenVerticalSpaceLine {
buttonW = (width - CGFloat(count - 1) * verticalSpaceLineW) / CGFloat(count)
}
// 隐藏水平分割线
if !hiddenHorizontalSpaceLine {
buttonH -= horizontalSpaceLineH
// 分割线显示到底部
if !horizontalShowTB {
buttonY = 0
}
}
// 布局按钮
for i in 0..<count {
let button:UIButton = buttons[i]
button.frame = CGRect(x: CGFloat(i) * (buttonW + verticalSpaceLineW), y: buttonY, width: buttonW, height: buttonH)
}
// 布局垂直分割线
if !hiddenVerticalSpaceLine {
for i in 0..<verticalSpaceLines.count {
let spaceLine = verticalSpaceLines[i]
spaceLine.frame = CGRect(x: buttonW + CGFloat(i) * (buttonW + verticalSpaceLineW), y: buttonY, width: verticalSpaceLineW, height: buttonH)
}
}
// 布局水平分割线
if !hiddenHorizontalSpaceLine {
if horizontalShowTB {
horizontalSpaceLine?.frame = CGRect(x: 0, y: 0, width: width, height: horizontalSpaceLineH)
}else{
horizontalSpaceLine?.frame = CGRect(x: 0, y: height - horizontalSpaceLineH, width: width, height: horizontalSpaceLineH)
}
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 2cf8a3ed8f8a38a60e3abc18f0992f46 | 25.48125 | 158 | 0.495398 | 5.567674 | false | false | false | false |
juvs/FormValidators | FormValidators/Classes/TypeAlias.swift | 1 | 529 | //
// TypeAlias.swift
// Pods
//
// Created by Juvenal Guzman on 6/28/17.
//
//
import Foundation
public typealias ErrorStyleTransform = ((_ textField: UITextField?, _ labelDetail: UILabel?, _ validator: ValidatorType) -> Void)
public typealias SucessStyleTransform = ((_ textField: UITextField?, _ labelDetail: UILabel?) -> Void)
public typealias ReturnCallback = ((_ textField: UITextField, _ labelDetail: UILabel?) -> ())
public typealias OnIsValidCallback = (() -> ())
public typealias OnIsInvalidCallback = (() -> ())
| mit | c4271795d5e8c60e909107a036ad1bc4 | 32.0625 | 129 | 0.701323 | 4.069231 | false | false | false | false |
Kagami-src/MerusutoChristina | ios/MerusutoChristina/Units/DataManager.swift | 1 | 5384 | import UIKit
import SwiftyJSON
import Reachability
import SystemConfiguration
class DataManager {
static var switchToReserve = false
class func loadJSONWithSuccess(key: NSString, success: ((data: JSON!) -> Void)) {
checkVersionWithSuccess("\(key).json", success: { (needUpdate) -> Void in
if needUpdate {
self.loadGithubDataWithSuccess("\(key).json", success: { (data) -> Void in
success(data: JSON(data: data))
})
} else {
self.loadDataWithSuccess("\(key).json", success: { (data) -> Void in
success(data: JSON(data: data))
})
}
})
}
class func loadImageWithSuccess(key: NSString, success: ((data: UIImage!) -> Void)) {
loadDataWithSuccess("\(key).png", success: { (data) -> Void in
success(data: UIImage(data: data))
})
}
class func checkVersionWithSuccess(key: NSString, success: ((needUpdate: Bool) -> Void)) {
if Reachability.reachabilityForLocalWiFi().currentReachabilityStatus() != NetworkStatus.ReachableViaWiFi {
success(needUpdate: false)
return
}
let localFileUrl = self.getLocalFileURL("\(key).version")
loadDataFromURL(localFileUrl, completion: { (data, readError) -> Void in
if let localData = data {
self.loadGithubDataWithSuccess("\(key).version", success: { (data) -> Void in
if localData.isEqualToData(data) {
success(needUpdate: false)
} else {
success(needUpdate: true)
}
})
} else {
self.loadGithubDataWithSuccess("\(key).version", success: { (data) -> Void in })
success(needUpdate: true)
}
})
}
class func loadDataWithSuccess(key: NSString, success: ((data: NSData!) -> Void)) {
let localFileUrl = self.getLocalFileURL(key)
loadDataFromURL(localFileUrl, completion: { (data, readError) -> Void in
if let localData = data {
print("Read file from Local System: \(localFileUrl)")
success(data: localData)
} else {
self.loadGithubDataWithSuccess(key, success: success)
}
})
}
class func loadGithubDataWithSuccess(key: NSString, success: ((data: NSData!) -> Void)) {
let localFileUrl = self.getLocalFileURL(key)
var githubUrl = self.getGithubURL(key)
loadDataFromURL(githubUrl, completion: { (data, responseError) -> Void in
if let remoteData = data {
print("Read file from Github: \(githubUrl)")
success(data: remoteData)
do {
try NSFileManager.defaultManager().createDirectoryAtURL(localFileUrl.URLByDeletingLastPathComponent!, withIntermediateDirectories: true, attributes: nil)
}
catch {
print(error)
}
remoteData.writeToURL(localFileUrl, atomically: true)
} else {
//如果加载失败,切换到备用服务器再尝试加载
switchToReserve = true
githubUrl = self.getGithubURL(key)
print("Switch to reserve")
loadDataFromURL(githubUrl, completion: { (data, error) -> Void in
if let remoteData = data {
print("Read file from Reserve: \(githubUrl)")
success(data: remoteData)
do {
try NSFileManager.defaultManager().createDirectoryAtURL(localFileUrl.URLByDeletingLastPathComponent!, withIntermediateDirectories: true, attributes: nil)
}
catch {
print(error)
}
remoteData.writeToURL(localFileUrl, atomically: true)
} else {
//如果还是失败,尝试读取本地文件
self.loadDataFromURL(localFileUrl, completion: { (data, error) -> Void in
if let localData = data {
print("Github unavailable, read file from Local System: \(localFileUrl)")
success(data: localData)
} else {
print("Github and Local System unavailable, Game over!")
}
})
}
})
}
})
}
class func getLocalFileURL(key: NSString) -> NSURL {
let baseURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
return baseURL.URLByAppendingPathComponent(key as String)
}
class func getGithubURL(key: NSString) -> NSURL {
let baseURL: NSURL!
// if (switchToReserve)
// {
baseURL = NSURL(string: "http://bbtfr.github.io/MerusutoChristina/data/")!
// }
// else
// {
// baseURL = NSURL(string: "http://merusuto.coding.me/data/")!
// }
// let baseURL = NSURL(string: "http://bbtfr.github.io/MerusutoChristina/data/")!
// let baseURL = NSURL(string: "http://merusuto.coding.me/data/")!
return baseURL.URLByAppendingPathComponent(key as String)
}
class func loadDataFromURL(url: NSURL, completion: (data: NSData?, error: NSError?) -> Void) {
let session = NSURLSession.sharedSession()
// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTaskWithURL(url, completionHandler:
{ (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let responseError = error {
completion(data: nil, error: responseError)
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
let statusError = NSError(domain: "com.bbtfr", code: httpResponse.statusCode,
userInfo: [NSLocalizedDescriptionKey: "HTTP status code has unexpected value."])
completion(data: nil, error: statusError)
} else {
completion(data: data, error: nil)
}
} else {
completion(data: data, error: nil)
}
})
loadDataTask.resume()
}
}
| gpl-3.0 | a03a7240552932a4e5f08dbe55088fc5 | 32.2125 | 160 | 0.666729 | 3.881665 | false | false | false | false |
AliSoftware/SwiftGen | SwiftGen.playground/Pages/CoreData-Demo.xcplaygroundpage/Contents.swift | 2 | 3734 | //: #### Other pages
//:
//: * [Demo for `colors` parser](Colors-Demo)
//: * Demo for `coredata` parser
//: * [Demo for `files` parser](Files-Demo)
//: * [Demo for `fonts` parser](Fonts-Demo)
//: * [Demo for `ib` parser](InterfaceBuilder-Demo)
//: * [Demo for `json` parser](JSON-Demo)
//: * [Demo for `plist` parser](Plist-Demo)
//: * [Demo for `strings` parser](Strings-Demo)
//: * [Demo for `xcassets` parser](XCAssets-Demo)
//: * [Demo for `yaml` parser](YAML-Demo)
//: #### Example of code generated by `coredata` parser with "swift5" template
import CoreData
import Foundation
public enum IntegerEnum: Int16 {
case test1
case test2
}
public enum StringEnum: String {
case test1
case test2
case test3
}
// MARK: - MainEntity
@objc(MainEntity)
internal class MainEntity: NSManagedObject {
internal class var entityName: String {
return "MainEntity"
}
internal class func entity(in managedObjectContext: NSManagedObjectContext) -> NSEntityDescription? {
return NSEntityDescription.entity(forEntityName: entityName, in: managedObjectContext)
}
@nonobjc internal class func makeFetchRequest() -> NSFetchRequest<MainEntity> {
return NSFetchRequest<MainEntity>(entityName: entityName)
}
// swiftlint:disable implicitly_unwrapped_optional
@NSManaged internal var attributedString: NSAttributedString?
@NSManaged internal var binaryData: Data?
@NSManaged internal var boolean: Bool
@NSManaged internal var date: Date?
@NSManaged internal var decimal: NSDecimalNumber?
@NSManaged internal var double: Double
@NSManaged internal var float: Float
@NSManaged internal var int16: Int16
@NSManaged internal var int32: Int32
@NSManaged internal var int64: Int64
internal var integerEnum: IntegerEnum {
get {
let key = "integerEnum"
willAccessValue(forKey: key)
defer { didAccessValue(forKey: key) }
guard let value = primitiveValue(forKey: key) as? IntegerEnum.RawValue,
let result = IntegerEnum(rawValue: value) else {
fatalError("Could not convert value for key '\(key)' to type 'IntegerEnum'")
}
return result
}
set {
let key = "integerEnum"
willChangeValue(forKey: key)
defer { didChangeValue(forKey: key) }
setPrimitiveValue(newValue.rawValue, forKey: key)
}
}
@NSManaged internal var string: String
internal var stringEnum: StringEnum? {
get {
let key = "stringEnum"
willAccessValue(forKey: key)
defer { didAccessValue(forKey: key) }
guard let value = primitiveValue(forKey: key) as? StringEnum.RawValue else {
return nil
}
return StringEnum(rawValue: value)
}
set {
let key = "stringEnum"
willChangeValue(forKey: key)
defer { didChangeValue(forKey: key) }
setPrimitiveValue(newValue?.rawValue, forKey: key)
}
}
@NSManaged internal var transformable: AnyObject?
@NSManaged internal var transient: String?
@NSManaged internal var uri: URL?
@NSManaged internal var uuid: UUID?
// swiftlint:enable implicitly_unwrapped_optional
}
//: #### Usage Example
let container: NSPersistentContainer = createContainer()
let context: NSManagedObjectContext = container.viewContext
let item = MainEntity(context: context)
item.date = Date()
item.boolean = true
item.string = "test"
do {
let newObjectsCount = context.insertedObjects.count
print("Preparing to save \(newObjectsCount)")
try context.save()
print("Saved")
} catch {
fatalError("Unresolved error \(error)")
}
do {
let fetchRequest = MainEntity.makeFetchRequest()
let count = try context.count(for: fetchRequest)
print("Found \(count) assets")
} catch {
fatalError("Unresolved error \(error)")
}
| mit | 078e22dba6b1c5a4f6ddf6dfa784a0b6 | 27.945736 | 103 | 0.698447 | 4.195506 | false | false | false | false |
elio-developer/MDInfo | MDInfo/Classes/Month.swift | 1 | 2215 | //
// Month.swift
// Pods
//
// Created by eliezer on 6/16/17.
//
//
import Foundation
public class Month {
private let df = DateFormatter()
private var monthOfTheYear: Int
/// Obtain the name of the month for the **current** locale.
public var name: String {
return name(Locale.current)
}
/// Obtain the short name of the month for the **current** locale.
public var shortName: String {
return shortName(Locale.current)
}
/// Obtain the initial of the month for the **current** locale.
public var initial: String {
return initial(Locale.current)
}
internal init(monthOfTheYear: Int) {
self.monthOfTheYear = monthOfTheYear
}
/**
Obtain the name of the month for the **specified** locale.
### Usage example ###
````
let locale = Locale(identifier: "es")
let name = Months.january.name(locale)
print(name)
````
- parameter locale: The locale for which you want the name of the month
*/
public func name(_ locale: Locale) -> String {
df.locale = locale
let name = df.monthSymbols[monthOfTheYear]
return name
}
/**
Obtain the short name of the month for the **specified** locale.
### Usage example ###
````
let locale = Locale(identifier: "es")
let name = Months.january.shortName(locale)
print(name)
````
- parameter locale: The locale for which you want the name of the month
*/
public func shortName(_ locale: Locale) -> String {
df.locale = locale
let name = df.shortMonthSymbols[monthOfTheYear]
return name
}
/**
Obtain the initial of the month for the **specified** locale.
### Usage example ###
````
let locale = Locale(identifier: "es")
let name = Months.january.initial(locale)
print(name)
````
- parameter locale: The locale for which you want the name of the month
*/
public func initial(_ locale: Locale) -> String {
df.locale = locale
let name = df.veryShortMonthSymbols[monthOfTheYear]
return name
}
}
| mit | a3e470c2c74c8eb5b80a4eb3b121ff31 | 24.45977 | 76 | 0.588262 | 4.511202 | false | false | false | false |
jjacobson93/RethinkDBSwift | Sources/RethinkDB/Query.swift | 1 | 1667 | import Foundation
import WarpCore
enum ReqlQueryType: Int {
case start = 1
case `continue` = 2
case stop = 3
case noReplyWait = 4
case serverInfo = 5
}
class Query {
var token: UInt64
var term: [Any]
var data: Data
var globalOptions: OptArgs<GlobalArg>
var isNoReply: Bool {
return self.globalOptions.get(key: "noreply") ?? false
}
init(type: ReqlQueryType, token: UInt64, term: [Any], globalOptions: OptArgs<GlobalArg>) throws {
self.globalOptions = globalOptions
let json = [type.rawValue, term, globalOptions.json]
self.data = try JSON.data(with: json) //JSONSerialization.data(withJSONObject: json, options: [])
self.term = term
self.token = token
}
static func start(_ token: UInt64, term: [Any], globalOptions: OptArgs<GlobalArg>) throws -> Query {
return try Query(type: .start, token: token, term: term, globalOptions: globalOptions)
}
static func stop(_ token: UInt64) throws -> Query {
return try Query(type: .stop, token: token, term: [], globalOptions: OptArgs<GlobalArg>([]))
}
static func continueQuery(_ token: UInt64) throws -> Query {
return try Query(type: .continue, token: token, term: [], globalOptions: OptArgs<GlobalArg>([]))
}
static func noReplyWait(_ token: UInt64) throws -> Query {
return try Query(type: .noReplyWait, token: token, term: [], globalOptions: OptArgs<GlobalArg>([]))
}
static func serverInfo(_ token: UInt64) throws -> Query {
return try Query(type: .serverInfo, token: token, term: [], globalOptions: OptArgs<GlobalArg>([]))
}
}
| mit | 37cc45be09df226133848076a63dcfd0 | 33.729167 | 107 | 0.643671 | 4.065854 | false | false | false | false |
hallelujahbaby/CFNotify | Example/CFNotifyExample/CFNotifyExample/ToastVC.swift | 1 | 2931 | //
// ToastVC.swift
// CFNotifyExample
//
// Created by Johnny Choi on 25/11/2016.
// Copyright © 2016 Johnny@Co-fire. All rights reserved.
//
import UIKit
import CFNotify
class ToastVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showToastView() {
let toastView = CFNotifyView.toastWith(text: "This is a Toast",
theme: .info(.light))
let toastViewD = CFNotifyView.toastWith(text: "Tap here to hide the toast",
theme: .info(.dark))
let toastView2 = CFNotifyView.toastWith(text: "You can try to tap 'hide' button to hide this toast.",
theme: .success(.light))
let toastView2D = CFNotifyView.toastWith(text: "You can try to tap 'hide all' button to hide all toast in queue.",
theme: .success(.dark))
let toastView3 = CFNotifyView.toastWith(text: "Urh! 404 Girlfriend not found.",
theme: .fail(.light))
let toastView3D = CFNotifyView.toastWith(text: "Too many toasts here",
theme: .fail(.dark))
let toastView4 = CFNotifyView.toastWith(text: "You are currently in Friendzone",
theme: .warning(.light))
let toastView4D = CFNotifyView.toastWith(text: "This should be the last toast in first queue",
theme: .warning(.dark))
var toastViewConfig = CFNotify.Config()
toastViewConfig.initPosition = .bottom(.random)
toastViewConfig.appearPosition = .bottom
toastViewConfig.thresholdDistance = 30
toastViewConfig.hideTime = .never
toastViewConfig.angularResistance = 1
CFNotify.present(config: toastViewConfig, view: toastView)
CFNotify.present(config: toastViewConfig, view: toastView2)
CFNotify.present(config: toastViewConfig, view: toastView3)
CFNotify.present(config: toastViewConfig, view: toastView4)
CFNotify.present(config: toastViewConfig, view: toastViewD)
CFNotify.present(config: toastViewConfig, view: toastView2D)
CFNotify.present(config: toastViewConfig, view: toastView3D)
CFNotify.present(config: toastViewConfig, view: toastView4D)
}
@IBAction func hideMessage() {
CFNotify.hide()
}
@IBAction func hideAll() {
CFNotify.hideAll()
}
}
| mit | 2b5fcfdbbe0907e4ed5fb9b49ec29fe6 | 37.051948 | 122 | 0.572696 | 5.279279 | false | true | false | false |
modulo-dm/modulo | ModuloKit/Commands/MapCommand.swift | 1 | 5766 | //
// MapCommand.swift
// modulo
//
// Created by Sneed, Brandon on 1/21/17.
// Copyright © 2017 TheHolyGrail. All rights reserved.
//
import Foundation
#if NOFRAMEWORKS
#else
import ELCLI
#endif
open class MapCommand: NSObject, Command {
// Protocol conformance
open var name: String { return "map" }
open var shortHelpDescription: String { return "Displays information about dependencies" }
open var longHelpDescription: String {
return "Displays information about this project's dependencies."
}
open var failOnUnrecognizedOptions: Bool { return true }
open var verbose: Bool = State.instance.options.alwaysVerbose
open var quiet: Bool = false
fileprivate var simple = false
open func configureOptions() {
addOption(["-s", "--simple"], usage: "shows a simple dependency map") { (option, value) in
self.simple = true
}
}
open func execute(_ otherParams: Array<String>?) -> Int {
guard let spec = ModuleSpec.workingSpec() else {
exit(ErrorCode.notInitialized)
return -1
}
writeln(.stdout, "Dependencies for `\(spec.name)`: ")
let deps = spec.allDependencies()
if (simple) {
for dep in deps {
let users = whatDependsOn(dep, outOf: deps)
printMap(dep: dep, explicit: spec.dependencies.contains(dep), users: users)
}
} else {
for (index, dep) in spec.dependencies.enumerated() {
printMapVisualAccuracy(mainSpec: spec, depth: 0, index: index, count: spec.dependencies.count, dep: dep, allDependencies: deps)
}
}
return 0
}
func printMap(dep: DependencySpec, explicit: Bool, users: [DependencySpec]) {
let names: [String] = users.map { (item) -> String in
return item.name()
}
let usedBy = names.joined(separator: ", ")
writeln(.stdout, " name : \(dep.name())")
writeln(.stdout, " explicit: \(explicit)")
if users.count > 0 {
writeln(.stdout, " used by : \(usedBy)")
}
writeln(.stdout, "")
}
func printMapReadable(mainSpec: ModuleSpec, depth: UInt, index:Int, count: Int, dep: DependencySpec, allDependencies: [DependencySpec]) {
let users = whatDependsOn(dep, outOf: allDependencies)
let names: [String] = users.map { (item) -> String in
return item.name()
}
let usedBy = names.joined(separator: ", ")
let explicit = mainSpec.dependencies.contains(dep)
let padStr = " "
let startChar = "├─"
let lineChar = "│"
var pad = padStr + lineChar
for _ in 0..<depth {
pad = padStr + lineChar + pad
}
let namePadRange = pad.range(of: lineChar, options: .backwards, range: nil, locale: nil)
let namePad = pad.replacingOccurrences(of: lineChar, with: startChar, options: .anchored, range: namePadRange)
writeln(.stdout, "\(pad)")
writeln(.stdout, "\(namePad) name : \(dep.name())")
writeln(.stdout, "\(pad) explicit: \(explicit)")
if users.count > 0 {
writeln(.stdout, "\(pad) used by : \(usedBy)")
}
if let spec = ModuleSpec.load(dep) {
for (indx, subDep) in spec.dependencies.enumerated() {
printMapReadable(mainSpec: mainSpec, depth: depth+1, index: indx, count: spec.dependencies.count, dep: subDep, allDependencies: allDependencies)
}
}
}
func printMapVisualAccuracy(mainSpec: ModuleSpec, depth: UInt, index:Int, count: Int, dep: DependencySpec, allDependencies: [DependencySpec]) {
let users = whatDependsOn(dep, outOf: allDependencies)
let names: [String] = users.map { (item) -> String in
return item.name()
}
let usedBy = names.joined(separator: ", ")
let explicit = mainSpec.dependencies.contains(dep)
let padStr = " "
var startChar = "├─"
let lineChar = "│"
let endChar = "└─"
if index == count-1 {
startChar = endChar
}
var pad = padStr + lineChar
for _ in 0..<depth {
if index == count-1 {
pad = padStr + " " + pad
} else {
pad = padStr + lineChar + pad
}
}
let namePadRange = pad.range(of: lineChar, options: .backwards, range: nil, locale: nil)
let namePad = pad.replacingOccurrences(of: lineChar, with: startChar, options: .anchored, range: namePadRange)
writeln(.stdout, "\(pad)")
writeln(.stdout, "\(namePad) name : \(dep.name())")
let otherPadRange = pad.range(of: lineChar, options: .backwards, range: nil, locale: nil)
let otherPad = pad.replacingOccurrences(of: lineChar, with: " ", options: .anchored, range: otherPadRange)
if index == count-1 {
pad = otherPad
}
writeln(.stdout, "\(pad) explicit: \(explicit)")
if users.count > 0 {
writeln(.stdout, "\(pad) used by : \(usedBy)")
}
if let spec = ModuleSpec.load(dep) {
for (indx, subDep) in spec.dependencies.enumerated() {
printMapVisualAccuracy(mainSpec: mainSpec, depth: depth+1, index: indx, count: spec.dependencies.count, dep: subDep, allDependencies: allDependencies)
}
}
}
}
| mit | fc95cf0acc22ea0b126210d6c1315e29 | 33.220238 | 166 | 0.552444 | 4.453137 | false | false | false | false |
SergeMaslyakov/audio-player | app/src/controllers/music/popover/MusicPickerTitleView.swift | 1 | 2126 | //
// MusicPickerTitleView.swift
// AudioPlayer
//
// Created by Serge Maslyakov on 07/07/2017.
// Copyright © 2017 Maslyakov. All rights reserved.
//
import UIKit
final class MusicPickerTitleView: XibView {
@IBInspectable var rawMusicState: String!
var musicState: MusicLibraryState?
weak var delegate: MusicPickerTitleDelegate? = nil
@IBOutlet weak var button: UIButton!
open override func awakeFromNib() {
super.awakeFromNib()
musicState = MusicLibraryState(rawValue: rawMusicState)
button.setAttributedTitle(titleText(for: .normal), for: .normal)
button.setAttributedTitle(titleText(for: .highlighted), for: .highlighted)
button.backgroundColor = UIColor.NavigationItem.barTint
self.backgroundColor = UIColor.NavigationItem.barTint
}
@IBAction func didTapOnButton() {
guard let uDelegate = delegate else {
return
}
uDelegate.userDidRequestPopoverPicker()
}
private func titleText(for state: UIControlState) -> NSAttributedString {
guard let titleString = musicState?.rawValue.localized(withFile: LocalizationFiles.music) else {
return NSAttributedString(string: "")
}
var attributes: [String: Any]?
if state == UIControlState.normal {
attributes = [
NSForegroundColorAttributeName: UIColor.NavigationItem.titleTint,
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)
]
} else {
attributes = [
NSForegroundColorAttributeName: UIColor.NavigationItem.titleTintHighlighted,
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)
]
}
let title = NSMutableAttributedString(string: titleString + " ", attributes: attributes)
let arrowAttachment = NSTextAttachment()
arrowAttachment.image = UIImage(asset: .arrow)
let imageString = NSAttributedString(attachment: arrowAttachment)
title.append(imageString)
return title.copy() as! NSAttributedString
}
}
| apache-2.0 | 1a2a018fcb4e3248ae164f95f52fe5fc | 30.716418 | 104 | 0.664941 | 5.299252 | false | false | false | false |
zapdroid/RXWeather | Pods/RxSwift/RxSwift/Observables/Implementations/Map.swift | 1 | 4329 | //
// Map.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class MapSink<SourceType, O: ObserverType>: Sink<O>, ObserverType {
typealias Transform = (SourceType) throws -> ResultType
typealias ResultType = O.E
typealias Element = SourceType
private let _transform: Transform
init(transform: @escaping Transform, observer: O, cancel: Cancelable) {
_transform = transform
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceType>) {
switch event {
case let .next(element):
do {
let mappedElement = try _transform(element)
forwardOn(.next(mappedElement))
} catch let e {
forwardOn(.error(e))
dispose()
}
case let .error(error):
forwardOn(.error(error))
dispose()
case .completed:
forwardOn(.completed)
dispose()
}
}
}
final class MapWithIndexSink<SourceType, O: ObserverType>: Sink<O>, ObserverType {
typealias Selector = (SourceType, Int) throws -> ResultType
typealias ResultType = O.E
typealias Element = SourceType
typealias Parent = MapWithIndex<SourceType, ResultType>
private let _selector: Selector
private var _index = 0
init(selector: @escaping Selector, observer: O, cancel: Cancelable) {
_selector = selector
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceType>) {
switch event {
case let .next(element):
do {
let mappedElement = try _selector(element, try incrementChecked(&_index))
forwardOn(.next(mappedElement))
} catch let e {
forwardOn(.error(e))
dispose()
}
case let .error(error):
forwardOn(.error(error))
dispose()
case .completed:
forwardOn(.completed)
dispose()
}
}
}
final class MapWithIndex<SourceType, ResultType>: Producer<ResultType> {
typealias Selector = (SourceType, Int) throws -> ResultType
private let _source: Observable<SourceType>
private let _selector: Selector
init(source: Observable<SourceType>, selector: @escaping Selector) {
_source = source
_selector = selector
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType {
let sink = MapWithIndexSink(selector: _selector, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
#if TRACE_RESOURCES
var _numberOfMapOperators: AtomicInt = 0
extension Resources {
public static var numberOfMapOperators: Int32 {
return _numberOfMapOperators.valueSnapshot()
}
}
#endif
final class Map<SourceType, ResultType>: Producer<ResultType> {
typealias Transform = (SourceType) throws -> ResultType
private let _source: Observable<SourceType>
private let _transform: Transform
init(source: Observable<SourceType>, transform: @escaping Transform) {
_source = source
_transform = transform
#if TRACE_RESOURCES
_ = AtomicIncrement(&_numberOfMapOperators)
#endif
}
override func composeMap<R>(_ selector: @escaping (ResultType) throws -> R) -> Observable<R> {
let originalSelector = _transform
return Map<SourceType, R>(source: _source, transform: { (s: SourceType) throws -> R in
let r: ResultType = try originalSelector(s)
return try selector(r)
})
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType {
let sink = MapSink(transform: _transform, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
#if TRACE_RESOURCES
deinit {
_ = AtomicDecrement(&_numberOfMapOperators)
}
#endif
}
| mit | 55bbd69d7e1debfd9266640fb7a6373c | 29.695035 | 147 | 0.61622 | 4.750823 | false | false | false | false |
dirkoswanepoel/CleanSwift | Clean Swift/View Controller.xctemplate/UIViewController/___FILEBASENAME___ViewController.swift | 2 | 1905 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol ___VARIABLE_sceneName___DisplayLogic: class {
}
class ___VARIABLE_sceneName___ViewController: UIViewController, ___VARIABLE_sceneName___DisplayLogic {
let interactor: ___VARIABLE_sceneName___BusinessLogic
let router: (NSObjectProtocol & ___VARIABLE_sceneName___RoutingLogic)
// MARK: Object lifecycle
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
interactor = ___VARIABLE_sceneName___Interactor()
router = ___VARIABLE_sceneName___Router()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
((interactor as? ___VARIABLE_sceneName___Interactor)?.presenter as? ___VARIABLE_sceneName___Presenter)?.viewController = self
(router as? ___VARIABLE_sceneName___Router)?.viewController = self
}
required init?(coder aDecoder: NSCoder) {
interactor = ___VARIABLE_sceneName___Interactor()
router = ___VARIABLE_sceneName___Router()
super.init(coder: aDecoder)
((interactor as? ___VARIABLE_sceneName___Interactor)?.presenter as? ___VARIABLE_sceneName___Presenter)?.viewController = self
(router as? ___VARIABLE_sceneName___Router)?.viewController = self
}
// MARK: Routing
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let scene = segue.identifier {
let selector = NSSelectorFromString("routeTo\(scene)WithSegue:")
if router.responds(to: selector) {
router.perform(selector, with: segue)
}
}
}
}
| mit | ae521e7df713a941407e84330c62e6bd | 37.1 | 133 | 0.653543 | 4.738806 | false | false | false | false |
xedin/swift | stdlib/public/core/ArrayShared.swift | 4 | 11634 | //===--- ArrayShared.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/// This type is used as a result of the _checkSubscript call to associate the
/// call with the array access call it guards.
@frozen
public struct _DependenceToken {
@inlinable
public init() {
}
}
/// Returns an Array of `_count` uninitialized elements using the
/// given `storage`, and a pointer to uninitialized memory for the
/// first element.
///
/// This function is referenced by the compiler to allocate array literals.
///
/// - Precondition: `storage` is `_ContiguousArrayStorage`.
@inlinable // FIXME(inline-always)
@inline(__always)
@_semantics("array.uninitialized_intrinsic")
public // COMPILER_INTRINSIC
func _allocateUninitializedArray<Element>(_ builtinCount: Builtin.Word)
-> (Array<Element>, Builtin.RawPointer) {
let count = Int(builtinCount)
if count > 0 {
// Doing the actual buffer allocation outside of the array.uninitialized
// semantics function enables stack propagation of the buffer.
let bufferObject = Builtin.allocWithTailElems_1(
_ContiguousArrayStorage<Element>.self, builtinCount, Element.self)
let (array, ptr) = Array<Element>._adoptStorage(bufferObject, count: count)
return (array, ptr._rawValue)
}
// For an empty array no buffer allocation is needed.
let (array, ptr) = Array<Element>._allocateUninitialized(count)
return (array, ptr._rawValue)
}
// Referenced by the compiler to deallocate array literals on the
// error path.
@inlinable
@_semantics("array.dealloc_uninitialized")
public // COMPILER_INTRINSIC
func _deallocateUninitializedArray<Element>(
_ array: __owned Array<Element>
) {
var array = array
array._deallocateUninitialized()
}
extension Collection {
// Utility method for collections that wish to implement
// CustomStringConvertible and CustomDebugStringConvertible using a bracketed
// list of elements, like an array.
internal func _makeCollectionDescription(
withTypeName type: String? = nil
) -> String {
var result = ""
if let type = type {
result += "\(type)(["
} else {
result += "["
}
var first = true
for item in self {
if first {
first = false
} else {
result += ", "
}
debugPrint(item, terminator: "", to: &result)
}
result += type != nil ? "])" : "]"
return result
}
}
extension _ArrayBufferProtocol {
@inlinable // FIXME @useableFromInline https://bugs.swift.org/browse/SR-7588
@inline(never)
internal mutating func _arrayOutOfPlaceReplace<C: Collection>(
_ bounds: Range<Int>,
with newValues: __owned C,
count insertCount: Int
) where C.Element == Element {
let growth = insertCount - bounds.count
let newCount = self.count + growth
var newBuffer = _forceCreateUniqueMutableBuffer(
newCount: newCount, requiredCapacity: newCount)
_arrayOutOfPlaceUpdate(
&newBuffer, bounds.lowerBound - startIndex, insertCount,
{ rawMemory, count in
var p = rawMemory
var q = newValues.startIndex
for _ in 0..<count {
p.initialize(to: newValues[q])
newValues.formIndex(after: &q)
p += 1
}
_expectEnd(of: newValues, is: q)
}
)
}
}
/// A _debugPrecondition check that `i` has exactly reached the end of
/// `s`. This test is never used to ensure memory safety; that is
/// always guaranteed by measuring `s` once and re-using that value.
@inlinable
internal func _expectEnd<C: Collection>(of s: C, is i: C.Index) {
_debugPrecondition(
i == s.endIndex,
"invalid Collection: count differed in successive traversals")
}
@inlinable
internal func _growArrayCapacity(_ capacity: Int) -> Int {
return capacity * 2
}
//===--- generic helpers --------------------------------------------------===//
extension _ArrayBufferProtocol {
/// Create a unique mutable buffer that has enough capacity to hold 'newCount'
/// elements and at least 'requiredCapacity' elements. Set the count of the new
/// buffer to 'newCount'. The content of the buffer is uninitialized.
/// The formula used to compute the new buffers capacity is:
/// max(requiredCapacity, source.capacity) if newCount <= source.capacity
/// max(requiredCapacity, _growArrayCapacity(source.capacity)) otherwise
@inline(never)
@inlinable // @specializable
internal func _forceCreateUniqueMutableBuffer(
newCount: Int, requiredCapacity: Int
) -> _ContiguousArrayBuffer<Element> {
return _forceCreateUniqueMutableBufferImpl(
countForBuffer: newCount, minNewCapacity: newCount,
requiredCapacity: requiredCapacity)
}
/// Create a unique mutable buffer that has enough capacity to hold
/// 'minNewCapacity' elements and set the count of the new buffer to
/// 'countForNewBuffer'. The content of the buffer uninitialized.
/// The formula used to compute the new buffers capacity is:
/// max(minNewCapacity, source.capacity) if minNewCapacity <= source.capacity
/// max(minNewCapacity, _growArrayCapacity(source.capacity)) otherwise
@inline(never)
@inlinable // @specializable
internal func _forceCreateUniqueMutableBuffer(
countForNewBuffer: Int, minNewCapacity: Int
) -> _ContiguousArrayBuffer<Element> {
return _forceCreateUniqueMutableBufferImpl(
countForBuffer: countForNewBuffer, minNewCapacity: minNewCapacity,
requiredCapacity: minNewCapacity)
}
/// Create a unique mutable buffer that has enough capacity to hold
/// 'minNewCapacity' elements and at least 'requiredCapacity' elements and set
/// the count of the new buffer to 'countForBuffer'. The content of the buffer
/// uninitialized.
/// The formula used to compute the new capacity is:
/// max(requiredCapacity, source.capacity) if minNewCapacity <= source.capacity
/// max(requiredCapacity, _growArrayCapacity(source.capacity)) otherwise
@inlinable
internal func _forceCreateUniqueMutableBufferImpl(
countForBuffer: Int, minNewCapacity: Int,
requiredCapacity: Int
) -> _ContiguousArrayBuffer<Element> {
_internalInvariant(countForBuffer >= 0)
_internalInvariant(requiredCapacity >= countForBuffer)
_internalInvariant(minNewCapacity >= countForBuffer)
let minimumCapacity = Swift.max(requiredCapacity,
minNewCapacity > capacity
? _growArrayCapacity(capacity) : capacity)
return _ContiguousArrayBuffer(
_uninitializedCount: countForBuffer, minimumCapacity: minimumCapacity)
}
}
extension _ArrayBufferProtocol {
/// Initialize the elements of dest by copying the first headCount
/// items from source, calling initializeNewElements on the next
/// uninitialized element, and finally by copying the last N items
/// from source into the N remaining uninitialized elements of dest.
///
/// As an optimization, may move elements out of source rather than
/// copying when it isUniquelyReferenced.
@inline(never)
@inlinable // @specializable
internal mutating func _arrayOutOfPlaceUpdate(
_ dest: inout _ContiguousArrayBuffer<Element>,
_ headCount: Int, // Count of initial source elements to copy/move
_ newCount: Int, // Number of new elements to insert
_ initializeNewElements:
((UnsafeMutablePointer<Element>, _ count: Int) -> ()) = { ptr, count in
_internalInvariant(count == 0)
}
) {
_internalInvariant(headCount >= 0)
_internalInvariant(newCount >= 0)
// Count of trailing source elements to copy/move
let sourceCount = self.count
let tailCount = dest.count - headCount - newCount
_internalInvariant(headCount + tailCount <= sourceCount)
let oldCount = sourceCount - headCount - tailCount
let destStart = dest.firstElementAddress
let newStart = destStart + headCount
let newEnd = newStart + newCount
// Check to see if we have storage we can move from
if let backing = requestUniqueMutableBackingBuffer(
minimumCapacity: sourceCount) {
let sourceStart = firstElementAddress
let oldStart = sourceStart + headCount
// Destroy any items that may be lurking in a _SliceBuffer before
// its real first element
let backingStart = backing.firstElementAddress
let sourceOffset = sourceStart - backingStart
backingStart.deinitialize(count: sourceOffset)
// Move the head items
destStart.moveInitialize(from: sourceStart, count: headCount)
// Destroy unused source items
oldStart.deinitialize(count: oldCount)
initializeNewElements(newStart, newCount)
// Move the tail items
newEnd.moveInitialize(from: oldStart + oldCount, count: tailCount)
// Destroy any items that may be lurking in a _SliceBuffer after
// its real last element
let backingEnd = backingStart + backing.count
let sourceEnd = sourceStart + sourceCount
sourceEnd.deinitialize(count: backingEnd - sourceEnd)
backing.count = 0
}
else {
let headStart = startIndex
let headEnd = headStart + headCount
let newStart = _copyContents(
subRange: headStart..<headEnd,
initializing: destStart)
initializeNewElements(newStart, newCount)
let tailStart = headEnd + oldCount
let tailEnd = endIndex
_copyContents(subRange: tailStart..<tailEnd, initializing: newEnd)
}
self = Self(_buffer: dest, shiftedToStartIndex: startIndex)
}
}
extension _ArrayBufferProtocol {
@inline(never)
@usableFromInline
internal mutating func _outlinedMakeUniqueBuffer(bufferCount: Int) {
if _fastPath(
requestUniqueMutableBackingBuffer(minimumCapacity: bufferCount) != nil) {
return
}
var newBuffer = _forceCreateUniqueMutableBuffer(
newCount: bufferCount, requiredCapacity: bufferCount)
_arrayOutOfPlaceUpdate(&newBuffer, bufferCount, 0)
}
/// Append items from `newItems` to a buffer.
@inlinable
internal mutating func _arrayAppendSequence<S: Sequence>(
_ newItems: __owned S
) where S.Element == Element {
// this function is only ever called from append(contentsOf:)
// which should always have exhausted its capacity before calling
_internalInvariant(count == capacity)
var newCount = self.count
// there might not be any elements to append remaining,
// so check for nil element first, then increase capacity,
// then inner-loop to fill that capacity with elements
var stream = newItems.makeIterator()
var nextItem = stream.next()
while nextItem != nil {
// grow capacity, first time around and when filled
var newBuffer = _forceCreateUniqueMutableBuffer(
countForNewBuffer: newCount,
// minNewCapacity handles the exponential growth, just
// need to request 1 more than current count/capacity
minNewCapacity: newCount + 1)
_arrayOutOfPlaceUpdate(&newBuffer, newCount, 0)
let currentCapacity = self.capacity
let base = self.firstElementAddress
// fill while there is another item and spare capacity
while let next = nextItem, newCount < currentCapacity {
(base + newCount).initialize(to: next)
newCount += 1
nextItem = stream.next()
}
self.count = newCount
}
}
}
| apache-2.0 | 59f54d169693881c1a864f14d752c62f | 34.469512 | 82 | 0.696321 | 4.929661 | false | false | false | false |
brentsimmons/Frontier | BeforeTheRename/UserTalk/UserTalk/Node/TryNode.swift | 1 | 1093 | //
// TryNode.swift
// UserTalk
//
// Created by Brent Simmons on 5/7/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
// try // TryNode
// some.thing() // BlockNode
// else // BlockNode
// other.thing()
final class TryNode: CodeTreeNode {
let operation = .bundleOp
let textPosition: TextPosition
let blockNode: BlockNode
let elseNode: BlockNode?
init(_ textPosition: TextPosition, _ blockNode: BlockNode, _ elseNode: BlockNode?) {
self.textPosition = textPosition
self.blockNode = blockNode
self.elseNode = elseNode
}
func evaluate(_ stack: Stack, _ breakOperation: inout CodeTreeOperation) throws -> Value {
do {
stack.push(self)
defer {
stack.pop()
}
return try blockNode.evaluate(stack, &tempBreakOperation)
}
catch { }
// There was an error.
do {
stack.push(self)
defer {
stack.pop()
}
breakOperation = .noOp // Possible that it was set above, so it should be reset
try return blockNode.evaluate(stack, breakOperation)
}
catch { throw error }
}
}
| gpl-2.0 | fe5436bea7c99ec6453c3d63aa15c968 | 18.854545 | 91 | 0.679487 | 3.444795 | false | false | false | false |
stomp1128/TIY-Assignments | CollectEmAll-Sports/ChoosePlayerTableViewController.swift | 1 | 1999 | //
// ChoosePlayerTableViewController.swift
// CollectEmAll-Sports
//
// Created by Chris Stomp on 11/6/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
class ChoosePlayerTableViewController: UITableViewController
{
var delegate: ChoosePlayerTableViewControllerDelegate?
var remainingPlayers: [Player] = []
override func viewDidLoad()
{
super.viewDidLoad()
remainingPlayers.sortInPlace({ $0.jerseyNumber < $1.jerseyNumber })
}
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 remainingPlayers.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PlayerInfoCell", forIndexPath: indexPath) as! PlayerInfoCell
let aPlayer = remainingPlayers[indexPath.row]
cell.name?.text = aPlayer.name
cell.jerseyNumberLabel.text = String(aPlayer.jerseyNumber)
cell.positionLabel.text = aPlayer.position
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
delegate?.playerWasChosen(remainingPlayers[indexPath.row])
}
@IBAction func cancelButtonTapped(sender: UIBarButtonItem!)
{
dismissViewControllerAnimated(true, completion: nil)
}
}
| cc0-1.0 | 68ae7ec15534c3ed98633fd5e4372dad | 27.956522 | 124 | 0.6997 | 5.31383 | false | false | false | false |
dipen30/Qmote | KodiRemote/KodiRemote/NavigationBar.swift | 1 | 1674 | //
// NavigationBar.swift
// SlideoutMenu
//
// Created by Quixom Technology on 22/02/16.
// Copyright © 2016 Quixom Technology. All rights reserved.
//
import Foundation
class NavigationBar: UITableViewController {
var TableArray = [String]()
var ImagesArray = [String]()
override func viewDidLoad() {
TableArray = ["Remote","Movies","TV Shows", "Music", "Mouse", "Add on", "Discover Media", "Cast"]
ImagesArray = ["Remote", "movie", "video", "music", "Mouse", "Add on", "Devices", "cast"]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TableArray[(indexPath as NSIndexPath).row], for: indexPath) as UITableViewCell
cell.textLabel?.text = TableArray[(indexPath as NSIndexPath).row]
cell.imageView?.image = UIImage(named: ImagesArray[(indexPath as NSIndexPath).row])
/* image resizing */
let itemSize:CGSize = CGSize(width: 20, height: 20)
UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.main.scale)
let imageRect : CGRect = CGRect(x: 0, y: 0, width: itemSize.width, height: itemSize.height)
cell.imageView!.image?.draw(in: imageRect)
cell.imageView!.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
cell.textLabel?.textColor = UIColor.black
return cell
}
}
| apache-2.0 | b4546cf545b248b8e0a76cc6d5ea40cf | 36.177778 | 143 | 0.656904 | 4.877551 | false | false | false | false |
AlexLittlejohn/ALTextInputBar | ALTextInputBar/ALTextInputBar.swift | 1 | 11002 | //
// ALTextInputBar.swift
// ALTextInputBar
//
// Created by Alex Littlejohn on 2015/04/24.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
open class ALTextInputBar: UIView, ALTextViewDelegate {
public weak var delegate: ALTextInputBarDelegate?
public weak var keyboardObserver: ALKeyboardObservingView?
// If true, display a border around the text view
public var showTextViewBorder = false {
didSet {
textViewBorderView.isHidden = !showTextViewBorder
}
}
// TextView border insets
public var textViewBorderPadding: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
// TextView corner radius
public var textViewCornerRadius: CGFloat = 4 {
didSet {
textViewBorderView.layer.cornerRadius = textViewCornerRadius
}
}
// TextView border width
public var textViewBorderWidth: CGFloat = 1 {
didSet {
textViewBorderView.layer.borderWidth = textViewBorderWidth
}
}
// TextView border color
public var textViewBorderColor = UIColor(white: 0.9, alpha: 1) {
didSet {
textViewBorderView.layer.borderColor = textViewBorderColor.cgColor
}
}
// TextView background color
public var textViewBackgroundColor = UIColor.white {
didSet {
textViewBorderView.backgroundColor = textViewBackgroundColor
}
}
/// Used for the intrinsic content size for autolayout
public var defaultHeight: CGFloat = 44
/// If true the right button will always be visible else it will only show when there is text in the text view
public var alwaysShowRightButton = false
/// The horizontal padding between the view edges and its subviews
public var horizontalPadding: CGFloat = 10
/// The horizontal spacing between subviews
public var horizontalSpacing: CGFloat = 5
/// Convenience set and retrieve the text view text
public var text: String! {
get {
return textView.text
}
set(newValue) {
textView.text = newValue
textView.delegate?.textViewDidChange?(textView)
}
}
/**
This view will be displayed on the left of the text view.
If this view is nil nothing will be displayed, and the text view will fill the space
*/
public var leftView: UIView? {
willSet(newValue) {
if let view = leftView {
view.removeFromSuperview()
}
}
didSet {
if let view = leftView {
addSubview(view)
}
}
}
/**
This view will be displayed on the right of the text view.
If this view is nil nothing will be displayed, and the text view will fill the space
If alwaysShowRightButton is false this view will animate in from the right when the text view has content
*/
public var rightView: UIView? {
willSet(newValue) {
if let view = rightView {
view.removeFromSuperview()
}
}
didSet {
if let view = rightView {
addSubview(view)
}
}
}
/// The text view instance
public let textView: ALTextView = {
let _textView = ALTextView()
_textView.textContainerInset = UIEdgeInsets(top: 6, left: 8, bottom: 6, right: 8)
_textView.textContainer.lineFragmentPadding = 0
_textView.maxNumberOfLines = defaultNumberOfLines()
_textView.placeholder = "Type here"
_textView.placeholderColor = UIColor.lightGray
_textView.font = UIFont.systemFont(ofSize: 14)
_textView.textColor = UIColor.darkGray
_textView.backgroundColor = UIColor.clear
// This changes the caret color
_textView.tintColor = UIColor.lightGray
return _textView
}()
private var showRightButton = false
private var showLeftButton = false
private var textViewBorderView: UIView!
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
textViewBorderView = createBorderView()
addSubview(textViewBorderView)
addSubview(textView)
textViewBorderView.isHidden = !showTextViewBorder
textView.textViewDelegate = self
backgroundColor = UIColor.groupTableViewBackground
}
private func createBorderView() -> UIView {
let borderView = UIView()
borderView.backgroundColor = textViewBackgroundColor
borderView.layer.borderColor = textViewBorderColor.cgColor
borderView.layer.borderWidth = textViewBorderWidth
borderView.layer.cornerRadius = textViewCornerRadius
return borderView
}
// MARK: - View positioning and layout -
override open var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: defaultHeight)
}
override open func layoutSubviews() {
super.layoutSubviews()
let size = frame.size
let height = floor(size.height)
var leftViewSize = CGSize.zero
var rightViewSize = CGSize.zero
if let view = leftView {
leftViewSize = view.bounds.size
let leftViewX: CGFloat = horizontalPadding
let leftViewVerticalPadding = (defaultHeight - leftViewSize.height) / 2
let leftViewY: CGFloat = height - (leftViewSize.height + leftViewVerticalPadding)
UIView.performWithoutAnimation {
view.frame = CGRect(x: leftViewX, y: leftViewY, width: leftViewSize.width, height: leftViewSize.height)
}
}
if let view = rightView {
rightViewSize = view.bounds.size
let rightViewVerticalPadding = (defaultHeight - rightViewSize.height) / 2
var rightViewX = size.width
let rightViewY = height - (rightViewSize.height + rightViewVerticalPadding)
if showRightButton || alwaysShowRightButton {
rightViewX -= (rightViewSize.width + horizontalPadding)
}
view.frame = CGRect(x: rightViewX, y: rightViewY, width: rightViewSize.width, height: rightViewSize.height)
}
let textViewPadding = (defaultHeight - textView.minimumHeight) / 2
var textViewX = horizontalPadding
let textViewY = textViewPadding
let textViewHeight = textView.expectedHeight
var textViewWidth = size.width - (horizontalPadding + horizontalPadding)
if leftViewSize.width > 0 {
textViewX += leftViewSize.width + horizontalSpacing
textViewWidth -= leftViewSize.width + horizontalSpacing
}
if showTextViewBorder {
textViewX += textViewBorderPadding.left
textViewWidth -= textViewBorderPadding.left + textViewBorderPadding.right
}
if (showRightButton || alwaysShowRightButton) && rightViewSize.width > 0 {
textViewWidth -= (horizontalSpacing + rightViewSize.width)
} else {
}
textView.frame = CGRect(x: textViewX, y: textViewY, width: textViewWidth, height: textViewHeight)
let offset = UIEdgeInsets.init(top: -textViewBorderPadding.top, left: -textViewBorderPadding.left, bottom: -textViewBorderPadding.bottom, right: -textViewBorderPadding.right)
textViewBorderView.frame = textView.frame.inset(by: offset)
}
public func updateViews(animated: Bool) {
if animated {
UIView.animate(withDuration: 0.2) {
self.setNeedsLayout()
self.layoutIfNeeded()
}
} else {
setNeedsLayout()
layoutIfNeeded()
}
}
// MARK: - ALTextViewDelegate -
public final func textViewHeightChanged(textView: ALTextView, newHeight: CGFloat) {
let padding = defaultHeight - textView.minimumHeight
let height = padding + newHeight
for constraint in constraints {
if constraint.firstAttribute == NSLayoutConstraint.Attribute.height && constraint.firstItem as! NSObject == self {
constraint.constant = height < defaultHeight ? defaultHeight : height
}
}
frame.size.height = height
if let ko = keyboardObserver {
ko.updateHeight(height: height)
}
if let d = delegate, let m = d.inputBarDidChangeHeight {
m(height)
}
textView.frame.size.height = newHeight
}
public final func textViewDidChange(_ textView: UITextView) {
self.textView.textViewDidChange()
let shouldShowButton = !textView.text.isEmpty
if showRightButton != shouldShowButton && !alwaysShowRightButton {
showRightButton = shouldShowButton
updateViews(animated: true)
}
if let d = delegate, let m = d.textViewDidChange {
m(self.textView)
}
}
public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
var beginEditing: Bool = true
if let d = delegate, let m = d.textViewShouldBeginEditing {
beginEditing = m(self.textView)
}
return beginEditing
}
public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
var endEditing = true
if let d = delegate, let m = d.textViewShouldEndEditing {
endEditing = m(self.textView)
}
return endEditing
}
public func textViewDidBeginEditing(_ textView: UITextView) {
if let d = delegate, let m = d.textViewDidBeginEditing {
m(self.textView)
}
}
public func textViewDidEndEditing(_ textView: UITextView) {
if let d = delegate, let m = d.textViewDidEndEditing {
m(self.textView)
}
}
public func textViewDidChangeSelection(_ textView: UITextView) {
if let d = delegate, let m = d.textViewDidChangeSelection {
m(self.textView)
}
}
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
var shouldChange = true
if let d = delegate, let m = d.textView {
shouldChange = m(self.textView, range, text)
}
return shouldChange
}
}
| mit | 5b14c897f35dde6a058a9bba9e0c2c38 | 30.982558 | 182 | 0.604708 | 5.62187 | false | false | false | false |
J3D1-WARR10R/WikiRaces | WikiRaces/Shared/Menu View Controllers/DebugInfoTableViewController/DebugInfoTableViewCell.swift | 2 | 762 | //
// DebugInfoTableViewCell.swift
// WikiRaces
//
// Created by Andrew Finke on 9/15/18.
// Copyright © 2018 Andrew Finke. All rights reserved.
//
import UIKit
final class DebugInfoTableViewCell: UITableViewCell {
// MARK: - Properties
static let reuseIdentifier = "reuseIdentifier"
// MARK: - Initialization
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
guard let textLabel = textLabel, let detailTextLabel = detailTextLabel else { fatalError() }
textLabel.numberOfLines = 0
detailTextLabel.numberOfLines = 0
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | e02f9064d6cfeea3e7d2fdb1cfbc9633 | 23.548387 | 100 | 0.691196 | 4.75625 | false | false | false | false |
epodkorytov/OCTextInput | OCTextInput/Classes/OCTextEdit.swift | 1 | 2576 | import UIKit
final internal class OCTextEdit: UITextView {
weak var textInputDelegate: TextInputDelegate?
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
fileprivate func setup() {
delegate = self
}
override func resignFirstResponder() -> Bool {
return super.resignFirstResponder()
}
}
extension OCTextEdit: TextInput {
var currentText: String? {
get { return text }
set { self.text = newValue }
}
var textAttributes: [NSAttributedString.Key: Any] {
get { return typingAttributes }
set { self.typingAttributes = textAttributes }
}
var currentSelectedTextRange: UITextRange? {
get { return self.selectedTextRange }
set { self.selectedTextRange = newValue }
}
public var currentBeginningOfDocument: UITextPosition? {
return self.beginningOfDocument
}
func changeReturnKeyType(with newReturnKeyType: UIReturnKeyType) {
returnKeyType = newReturnKeyType
}
func currentPosition(from: UITextPosition, offset: Int) -> UITextPosition? {
return position(from: from, offset: offset)
}
}
extension OCTextEdit: UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
textInputDelegate?.textInputDidBeginEditing(textInput: self)
}
func textViewDidEndEditing(_ textView: UITextView) {
textInputDelegate?.textInputDidEndEditing(textInput: self)
}
func textViewDidChange(_ textView: UITextView) {
textInputDelegate?.textInputDidChange(textInput: self)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
return textInputDelegate?.textInputShouldReturn(textInput: self) ?? true
}
return textInputDelegate?.textInput(textInput: self, shouldChangeCharactersInRange: range, replacementString: text) ?? true
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return textInputDelegate?.textInputShouldBeginEditing(textInput: self) ?? true
}
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
return textInputDelegate?.textInputShouldEndEditing(textInput: self) ?? true
}
}
| mit | d9c14df952405586b2e59fe969a21d83 | 28.953488 | 131 | 0.661491 | 5.674009 | false | false | false | false |
mperovic/my41 | my41/Classes/CPU_Class2.swift | 1 | 40747 | //
// CPU_Class2.swift
// my41
//
// Created by Miroslav Perovic on 12/21/14.
// Copyright (c) 2014 iPera. All rights reserved.
//
import Foundation
func op_Aeq0(start: Int, count: Int) -> Bit // A=0
{
/*
A=0
Clear A
=========================================================================================
A=0 operand: Time Enable Field
Operation: A<time_enable_field> <= 0
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
A=0 TEF 0000_0TEF_10 1
=========================================================================================
*/
fillDigits(
&cpu.reg.A,
value: 0,
start: start,
count: count
)
return 0
}
func op_Beq0(start: Int, count: Int) -> Bit // B=0
{
/*
B=0
Clear B
=========================================================================================
B=0 operand: Time Enable Field
Operation: B<time_enable_field> <= 0
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
B=0 TEF 0000_1TEF_10 1
=========================================================================================
*/
fillDigits(
&cpu.reg.B,
value: 0,
start: start,
count: count
)
return 0
}
func op_Ceq0(start: Int, count: Int) -> Bit // C=0
{
/*
C=0
Clear C
=========================================================================================
C=0 operand: Time Enable Field
Operation: C<time_enable_field> <= 0
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
C=0 TEF 0001_0TEF_10 1
=========================================================================================
*/
fillDigits(
&cpu.reg.C,
value: 0,
start: start,
count: count
)
return 0
}
func op_ABEX(start: Int, count: Int) -> Bit // ABEX
{
/*
ABEX
Exchange A and B
=========================================================================================
ABEX operand: Time Enable Field
Operation: fork
A<time_enable_field> <= B<time_enable_field>
B<time_enable_field> <= A<time_enable_field>
join
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
ABEX TEF 0001_1TEF_10 1
=========================================================================================
*/
var x = cpu.reg.A
var y = cpu.reg.B
exchangeDigits(
X: &x,
Y: &y,
startPos: start,
count: count
)
cpu.reg.A = x
cpu.reg.B = y
return 0
}
func op_BeqA(start: Int, count: Int) -> Bit // B=A
{
/*
B=A
Load B From A
=========================================================================================
B=A operand: Time Enable Field
Operation: B<time_enable_field> <= A<time_enable_field>
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
B=A TEF 0010_0TEF_10 1
=========================================================================================
*/
copyDigits(cpu.reg.A,
sourceStartAt: start,
destination: &cpu.reg.B,
destinationStartAt: start,
count: count
)
return 0
}
func op_ACEX(start: Int, count: Int) -> Bit // ACEX
{
/*
ACEX
Exchange A and C
=========================================================================================
ACEX operand: Time Enable Field
Operation: fork
A<time_enable_field> <= C<time_enable_field>
C<time_enable_field> <= A<time_enable_field>
join
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
ACEX TEF 0010_1TEF_10 1
=========================================================================================
*/
var x = cpu.reg.A
var y = cpu.reg.C
exchangeDigits(
X: &x,
Y: &y,
startPos: start,
count: count
)
cpu.reg.A = x
cpu.reg.C = y
return 0
}
func op_CeqB(start: Int, count: Int) -> Bit // C=B
{
/*
C=B
Load C From B
=========================================================================================
C=B operand: Time Enable Field
Operation: C<time_enable_field> <= B<time_enable_field>
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
C=B TEF 0011_0TEF_10 1
=========================================================================================
*/
copyDigits(
cpu.reg.B,
sourceStartAt: start,
destination: &cpu.reg.C,
destinationStartAt: start,
count: count
)
return 0
}
func op_BCEX(start: Int, count: Int) -> Bit // ACEX
{
/*
BCEX
Exchange B and C
=========================================================================================
BCEX operand: Time Enable Field
Operation: fork
B<time_enable_field> <= C<time_enable_field>
C<time_enable_field> <= B<time_enable_field>
join
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
BCEX TEF 0011_1TEF_10 1
=========================================================================================
*/
var x = cpu.reg.B
var y = cpu.reg.C
exchangeDigits(
X: &x,
Y: &y,
startPos: start,
count: count
)
cpu.reg.B = x
cpu.reg.C = y
return 0
}
func op_AeqC(start: Int, count: Int) -> Bit // A=C
{
/*
A=C
Load A From C
=========================================================================================
A=C operand: Time Enable Field
Operation: A<time_enable_field> <= C<time_enable_field>
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
A=C TEF 0100_0TEF_10 1
=========================================================================================
*/
copyDigits(
cpu.reg.C,
sourceStartAt: start,
destination: &cpu.reg.A,
destinationStartAt: start,
count: count
)
return 0
}
func op_AeqAplusB(start: Int, count: Int) // A=A+B
{
/*
A=A+B
Load A With A + B
=========================================================================================
A=A+B operand: Time Enable Field
Operation: {CY, A<time_enable_field>} <= A<time_enable_field> + B<time_enable_field>
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: Decimal adjusted in Decimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
A=A+B TEF 0100_1TEF_10 1
=========================================================================================
*/
// var carry: Bit = 0
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .ADD,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.A,
// secondNum: cpu.reg.B,
// destination: &cpu.reg.A,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry
for idx in start..<start+count {
cpu.reg.A[idx] = adder(nib1: cpu.reg.A[idx], nib2: cpu.reg.B[idx])
}
}
func op_AeqAplusC(start: Int, count: Int) // A=A+C
{
/*
A=A+C
Load A With A + C
=========================================================================================
A=A+C operand: Time Enable Field
Operation: {CY, A<time_enable_field>} <= A<time_enable_field> + C<time_enable_field>
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: Decimal adjusted in Decimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
A=A+C TEF 0101_0TEF_10 1
=========================================================================================
*/
// var carry: Bit = 0
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .ADD,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.A,
// secondNum: cpu.reg.C,
// destination: &cpu.reg.A,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry
for idx in start..<start+count {
cpu.reg.A[idx] = adder(nib1: cpu.reg.A[idx], nib2: cpu.reg.C[idx])
}
}
func op_AeqAplus1(start: Int, count: Int) // A=A+1
{
/*
A=A+1
Increment A
=========================================================================================
A=A+1 operand: Time Enable Field
Operation: {CY, A<time_enable_field>} <= A<time_enable_field> + 1
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: Decimal adjusted in Decimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
A=A+1 TEF 0101_1TEF_10 1
=========================================================================================
*/
// var carry: Bit = 1
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .ADD,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.A,
// secondNum: zeroes,
// destination: &cpu.reg.A,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry
cpu.reg.carry = 1
for idx in start..<start+count {
cpu.reg.A[idx] = adder(nib1: cpu.reg.A[idx], nib2: 0)
}
}
func op_AeqAminuB(start: Int, count: Int) // A=A-B
{
/*
A=A-B
Load A With A - B
=========================================================================================
A=A-B operand: Time Enable Field
Operation: {CY, A<time_enable_field>} <= A<time_enable_field> - B<time_enable_field>
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: Decimal adjusted in Decimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
A=A-B TEF 0110_0TEF_10 1
=========================================================================================
*/
// var carry: Bit = 1
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.A,
// secondNum: cpu.reg.B,
// destination: &cpu.reg.A,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry == 0 ? 1 : 0
for idx in start..<start+count {
cpu.reg.A[idx] = subtractor(nib1: cpu.reg.A[idx], nib2: cpu.reg.B[idx])
}
}
func op_AeqAminus1(start: Int, count: Int) // A=A-1
{
/*
A=A-1
Decrement A
=========================================================================================
A=A-1 operand: Time Enable Field
Operation: {CY, A<time_enable_field>} <= A<time_enable_field> - 1
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: Decimal adjusted in Decimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
A=A-1 TEF 0110_1TEF_10 1
=========================================================================================
*/
// var carry: Bit = 0
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.A,
// secondNum: zeroes,
// destination: &cpu.reg.A,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry == 0 ? 1 : 0
cpu.reg.carry = 1
for idx in start..<start+count {
cpu.reg.A[idx] = subtractor(nib1: cpu.reg.A[idx], nib2: 0)
}
}
func op_AeqAminuC(start: Int, count: Int) // A=A-C
{
/*
A=A-C
Load A With A - C
=========================================================================================
A=A-C operand: Time Enable Field
Operation: {CY, A<time_enable_field>} <= A<time_enable_field> - C<time_enable_field>
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: Decimal adjusted in Decimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
A=A-C TEF 0111_0TEF_10 1
=========================================================================================
*/
// var carry: Bit = 1
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.A,
// secondNum: cpu.reg.C,
// destination: &cpu.reg.A,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry == 0 ? 1 : 0
for idx in start..<start+count {
cpu.reg.A[idx] = subtractor(nib1: cpu.reg.A[idx], nib2: cpu.reg.C[idx])
}
}
func op_CeqCplusC(start: Int, count: Int) // C=C+C
{
/*
C=C+C
Load C With C + C
=========================================================================================
C=C+C operand: Time Enable Field
Operation: {CY, C<time_enable_field>} <= C<time_enable_field> + C<time_enable_field>
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: Decimal adjusted in Decimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
C=C+C TEF 0111_1TEF_10 1
=========================================================================================
*/
// var carry: Bit = 0
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .ADD,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.C,
// secondNum: cpu.reg.C,
// destination: &cpu.reg.C,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry
for idx in start..<start+count {
cpu.reg.C[idx] = adder(nib1: cpu.reg.C[idx], nib2: cpu.reg.C[idx])
}
}
func op_CeqAplusC(start: Int, count: Int) // C=A+C
{
/*
C=A+C
Load C With A + C
=========================================================================================
C=A+C operand: Time Enable Field
Operation: {CY, C<time_enable_field>} <= A<time_enable_field> + C<time_enable_field>
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: Decimal adjusted in Decimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
C=A+C TEF 1000_0TEF_10 1
=========================================================================================
*/
// var carry: Bit = 0
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .ADD,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.C,
// secondNum: cpu.reg.A,
// destination: &cpu.reg.C,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry
for idx in start..<start+count {
cpu.reg.C[idx] = adder(nib1: cpu.reg.C[idx], nib2: cpu.reg.A[idx])
}
}
func op_CeqCplus1(start: Int, count: Int) // C=C+1
{
/*
C=C+1
Increment C
=========================================================================================
C=C+1 operand: Time Enable Field
Operation: {CY, C<time_enable_field>} <= C<time_enable_field> + 1
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: Decimal adjusted in Decimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
C=C+1 TEF 1000_1TEF_10 1
=========================================================================================
*/
// var carry: Bit = 1
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .ADD,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.C,
// secondNum: zeroes,
// destination: &cpu.reg.C,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry
cpu.reg.carry = 1
for idx in start..<start+count {
cpu.reg.C[idx] = adder(nib1: cpu.reg.C[idx], nib2: 0)
}
}
func op_CeqAminusC(start: Int, count: Int) // C=A-C
{
/*
C=A-C
Load C With A - C
=========================================================================================
C=A-C operand: Time Enable Field
Operation: {CY, C<time_enable_field>} <= A<time_enable_field> - C<time_enable_field>
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: Decimal adjusted in Decimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
C=A-C TEF 1001_0TEF_10 1
=========================================================================================
*/
// var carry: Bit = 1
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.A,
// secondNum: cpu.reg.C,
// destination: &cpu.reg.C,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
// cpu.reg.carry = carry == 0 ? 1 : 0
//
// return carry == 0 ? 1 : 0
for idx in start..<start+count {
cpu.reg.C[idx] = subtractor(nib1: cpu.reg.A[idx], nib2: cpu.reg.C[idx])
}
}
func op_CeqCminus1(start: Int, count: Int) // C=C-1
{
/*
C=C-1
Decrement C
=========================================================================================
C=C-1 operand: Time Enable Field
Operation: {CY, C<time_enable_field>} <= C<time_enable_field> + 1
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: Decimal adjusted in Decimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
C=C-1 TEF 1001_1TEF_10 1
=========================================================================================
*/
// var carry: Bit = 0
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.C,
// secondNum: zeroes,
// destination: &cpu.reg.C,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry == 0 ? 1 : 0
cpu.reg.carry = 1
for idx in start..<start+count {
cpu.reg.C[idx] = subtractor(nib1: cpu.reg.C[idx], nib2: 0)
}
}
func op_CeqminusC(start: Int, count: Int) // C=-C
{
/*
C=-C
Negate C
=========================================================================================
C=C-1 operand: Time Enable Field
Operation: {CY, C<time_enable_field>} <= 0 - C<time_enable_field>
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: 10’s complement in Decimal Mode, 16’s complement in Hexadecimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
C=-C TEF 1010_0TEF_10 1
=========================================================================================
Note: This is the arithmetic complement, or the value subtracted from zero.
*/
// var carry: Bit = 1
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: zeroes,
// secondNum: cpu.reg.C,
// destination: &cpu.reg.C,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry == 0 ? 1 : 0
for idx in start..<start+count {
cpu.reg.C[idx] = subtractor(nib1: 0, nib2: cpu.reg.C[idx])
}
}
func op_CeqminusCminus1(start: Int, count: Int) // C=C-1
{
/*
C=-C-1
Complement C
=========================================================================================
C=-C-1 operand: Time Enable Field
Operation: {CY, C<time_enable_field>} <= 0 - C<time_enable_field> - 1
=========================================================================================
Flag: Set/Cleared as a result of the operation
=========================================================================================
Dec/Hex: 9’s complement in Decimal Mode, 15’s complement in Hexadecimal Mode
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
C=-C-1 TEF 1011_1TEF_10 1
=========================================================================================
Note: This is the logical complement, which is the same as subtracting the value from
negative one.
*/
// var carry: Bit = 0
// var zero: Bit = 0
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: zeroes,
// secondNum: cpu.reg.C,
// destination: &cpu.reg.C,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry == 0 ? 1 : 0
cpu.reg.carry = 1
for idx in start..<start+count {
cpu.reg.C[idx] = subtractor(nib1: 0, nib2: cpu.reg.C[idx])
}
}
func op_isBeq0(start: Int, count: Int) -> Bit // ?B#0
{
/*
?B=0
Test B Equal To Zero
=========================================================================================
?B=0 operand: Time Enable Field
Operation: CY <= (B<time_enable_field> != 0)
=========================================================================================
Flag: Set if B is not zero at any time during the Time Enable Field;
cleared otherwise.
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
?B#0 TEF 1011_0TEF_10 1
=========================================================================================
*/
// var carry: Bit = 1
// var zero: Bit = 0
// var emptyD14 = emptyDigit14
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.B,
// secondNum: zeroes,
// destination: &emptyD14,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return zero == 0 ? 1 : 0
for idx in start..<start+count {
if cpu.reg.B[idx] != 0 {
return 1
}
}
return 0
}
func op_isCeq0(start: Int, count: Int) -> Bit // ?C#0
{
/*
?C=0
Test C Equal To Zero
=========================================================================================
?C=0 operand: Time Enable Field
Operation: CY <= (C<time_enable_field> != 0)
=========================================================================================
Flag: Set if C is not zero at any time during the Time Enable Field;
cleared otherwise
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
?C#0 TEF 1011_1TEF_10 1
=========================================================================================
*/
// var carry: Bit = 1
// var zero: Bit = 0
// var emptyD14 = emptyDigit14
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.C,
// secondNum: zeroes,
// destination: &emptyD14,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return zero == 0 ? 1 : 0
for idx in start..<start+count {
if cpu.reg.C[idx] != 0 {
return 1
}
}
return 0
}
func op_isAlessthanC(start: Int, count: Int) // ?A<C
{
/*
?A<C
Test A Less Than C
=========================================================================================
?A<C operand: Time Enable Field
Operation: CY <= (A<time_enable_field> < C<time_enable_field>)
=========================================================================================
Flag: Set if A is less than C, for the bits during the Time Enable Field;
cleared otherwise
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
?A<C TEF 1100_0TEF_10 1
=========================================================================================
*/
// var carry: Bit = 1
// var zero: Bit = 0
// var emptyD14 = emptyDigit14
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.A,
// secondNum: cpu.reg.C,
// destination: &emptyD14,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry == 0 ? 1 : 0
for idx in start..<start+count {
_ = subtractor(nib1: cpu.reg.A[idx], nib2: cpu.reg.C[idx])
}
}
func op_isAlessthanB(start: Int, count: Int) // ?A<B
{
/*
?A<B
Test A Less Than B
=========================================================================================
?A<B operand: Time Enable Field
Operation: CY <= (A<time_enable_field> < B<time_enable_field>)
=========================================================================================
Flag: Set if A is less than B, for the bits during the Time Enable Field;
cleared otherwise
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
?A<B TEF 1100_1TEF_10 1
=========================================================================================
*/
// var carry: Bit = 1
// var zero: Bit = 0
// var emptyD14 = emptyDigit14
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.A,
// secondNum: cpu.reg.B,
// destination: &emptyD14,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return carry == 0 ? 1 : 0
for idx in start..<start+count {
_ = subtractor(nib1: cpu.reg.A[idx], nib2: cpu.reg.B[idx])
}
}
func op_isAnoteq0(start: Int, count: Int) -> Bit // ?A#0
{
/*
?A#0
Test A Not Equal To Zero
=========================================================================================
?A#0 operand: Time Enable Field
Operation: CY <= (A<time_enable_field> != 0)
=========================================================================================
Flag: Set if A is not zero at any time during the Time Enable Field;
cleared otherwise.
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
?A#0 TEF 1101_0TEF_10 1
=========================================================================================
*/
// var carry: Bit = 1
// var zero: Bit = 0
// var emptyD14 = emptyDigit14
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.A,
// secondNum: zeroes,
// destination: &emptyD14,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return zero == 0 ? 1 : 0
for idx in start..<start+count {
if cpu.reg.A[idx] != 0 {
return 1
}
}
return 0
}
func op_isAnoteqC(start: Int, count: Int) -> Bit // ?A#C
{
/*
?A#C
Test A Not Equal To C
=========================================================================================
?A#C operand: Time Enable Field
Operation: CY <= (A<time_enable_field> != C<time_enable_field>)
=========================================================================================
Flag: Set if A is not equal to C at any time during the Time Enable Field;
cleared otherwise.
=========================================================================================
Dec/Hex: Independent
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
?A#C TEF 1101_1TEF_10 1
=========================================================================================
*/
// var carry: Bit = 1
// var zero: Bit = 0
// var emptyD14 = emptyDigit14
// addOrSubtractDigits(
// arithOp: .SUB,
// arithMode: cpu.reg.mode,
// firstNum: cpu.reg.A,
// secondNum: cpu.reg.C,
// destination: &emptyD14,
// from: start,
// count: count,
// carry: &carry,
// zero: &zero
// )
//
// return zero == 0 ? 1 : 0
for idx in start..<start+count {
if cpu.reg.A[idx] != cpu.reg.C[idx] {
return 1
}
}
return 0
}
func op_shiftrigthA(start: Int, count: Int) -> Bit // ASR
{
/*
ASR
Shift Right A
=========================================================================================
ASR operand: Time Enable Field
Operation: A<time_enable_field> <= A<time_enable_field> >> 1
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent (no decimal adjust)
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
ASR TEF 1110_0TEF_10 1
=========================================================================================
Note: Zero is shifted into the most-significant (time-enabled) digit.
*/
cpu.reg.A = shiftDigitsRight(
X: cpu.reg.A,
start: start,
count: count
)
return 0
}
func op_shiftrigthB(start: Int, count: Int) -> Bit // BSR
{
/*
BSR
Shift Right B
=========================================================================================
BSR operand: Time Enable Field
Operation: B<time_enable_field> <= B<time_enable_field> >> 1
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent (no decimal adjust)
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
BSR TEF 1110_1TEF_10 1
=========================================================================================
Note: Zero is shifted into the most-significant (time-enabled) digit.
*/
cpu.reg.B = shiftDigitsRight(
X: cpu.reg.B,
start: start,
count: count
)
return 0
}
func op_shiftrigthC(start: Int, count: Int) -> Bit // CSR
{
/*
CSR
Shift Right C
=========================================================================================
CSR operand: Time Enable Field
Operation: C<time_enable_field> <= C<time_enable_field> >> 1
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent (no decimal adjust)
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
CSR TEF 1111_0TEF_10 1
=========================================================================================
Note: Zero is shifted into the most-significant (time-enabled) digit.
*/
cpu.reg.C = shiftDigitsRight(
X: cpu.reg.C,
start: start,
count: count
)
return 0
}
func op_shiftleftA(start: Int, count: Int) -> Bit // ASL
{
/*
ASL
Shift Left A
=========================================================================================
ASL operand: Time Enable Field
Operation: A<time_enable_field> <= A<time_enable_field> << 1
=========================================================================================
Flag: Cleared
=========================================================================================
Dec/Hex: Independent (no decimal adjust)
Turbo: Independent
=========================================================================================
Assembly Syntax Encoding Machine Cycles
-----------------------------------------------------------------------------------------
ASL TEF 1111_1TEF_10 1
=========================================================================================
Note: Zero is shifted into the least-significant (time-enabled) digit.
*/
cpu.reg.A = shiftDigitsLeft(
X: cpu.reg.A,
start: start,
count: count
)
return 0
}
| bsd-3-clause | 4ec059184b87a90f22f7e81a5fd0ac5a | 32.420016 | 90 | 0.341712 | 4.354784 | false | false | false | false |
nFiction/StackOverflow | StackOverflow/Classes/ViewModel/QuestionViewModel.swift | 1 | 910 | //
// QuestionViewModel.swift
// StackOverflow
//
// Created by Bruno da Luz on 9/30/17.
// Copyright © 2017 nFiction. All rights reserved.
//
import RxSwift
import RxCocoa
import ObjectMapper
final class QuestionViewModel {
var data = Variable<[Question]>([])
private let api: Synchronizing
private let disposeBag = DisposeBag()
init(api: Synchronizing) {
self.api = api
}
func find(through url: URL) {
let result = api.sync(through: url).map { value -> [Question] in
guard let items = value["items"] else {
fatalError("An error occurred with sync")
}
return try Mapper<Question>().mapArray(JSONObject: items)
}.subscribe { event in
if case .next(let element) = event {
self.data.value = element
}
}
result.addDisposableTo(disposeBag)
}
}
| mit | 6a6bd9ebe5dad1bc3ac6cd2e552ce36d | 24.25 | 72 | 0.59626 | 4.349282 | false | false | false | false |
tkersey/top | top/ViewController.swift | 1 | 4225 | import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
private let viewModel = ViewModel()
private lazy var activityIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView()
activityIndicator.center = view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = .gray
tableView.addSubview(activityIndicator)
return activityIndicator
}()
private lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshRows(_:)), for: .valueChanged)
refreshControl.tintColor = #colorLiteral(red: 0.7882352941, green: 0.5921568627, blue: 0.2, alpha: 1)
return refreshControl
}()
}
// MARK: - View lifecycle
extension ViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 100
tableView.refreshControl = refreshControl
tableView.rowHeight = UITableViewAutomaticDimension
tableView.tableFooterView = UIView()
loadOnFirstLaunch()
}
override var prefersStatusBarHidden: Bool {
return true
}
}
// MARK: - Tableview data source
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.rowCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "RowIdentifier", for: indexPath) as? Cell else {
fatalError("🤦♂️")
}
let row = viewModel.row(forIndexPath: indexPath)
cell.configure(with: row)
cell.thumbnailImage.fullScreenLongPressAction = saveImage
return cell
}
}
// MARK: - Refresh
extension ViewController {
private func loadOnFirstLaunch() {
if !UserDefaults.standard.bool(forKey: .firstLaunchOnce) {
activityIndicator.startAnimating()
viewModel.load { [weak self] in
self?.activityIndicator.stopAnimating()
UserDefaults.standard.set(true, forKey: .firstLaunchOnce)
self?.tableView.reloadData()
}
}
}
@objc private func refreshRows(_ sender: Any) {
viewModel.load(reset: true) { [weak self] in
self?.refreshControl.endRefreshing()
self?.tableView.reloadData()
}
}
}
// MARK: - Scroll view delegate
extension ViewController: UITableViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let contentOffset = scrollView.contentOffset
let contentSize = scrollView.contentSize
let contentFrame = scrollView.frame
if contentOffset.y > contentSize.height - contentFrame.height {
viewModel.update { [weak self] in
self?.tableView.reloadData()
}
}
}
}
// MARK: - State restoration
extension ViewController {
override func encodeRestorableState(with coder: NSCoder) {
viewModel.encodeRows()
UserDefaults.standard.set(true, forKey: .firstLaunchOnce)
super.encodeRestorableState(with: coder)
}
override func decodeRestorableState(with coder: NSCoder) {
viewModel.decodeRows()
super.decodeRestorableState(with: coder)
}
override func applicationFinishedRestoringState() {
if viewModel.rowCount == 0 {
viewModel.load { [weak self] in
self?.tableView.reloadData()
}
}
}
}
// MARK: - Save image
extension ViewController {
private func saveImage(_ image: UIImage) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Save Image", style: .default, handler: { _ in UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) }))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alert, animated: true)
}
}
| mit | 30ab90af5d16d66d891adc5c9fa1b101 | 31.682171 | 148 | 0.663899 | 5.309824 | false | false | false | false |
jigneshsheth/Datastructures | DataStructure/DataStructure/Google/UniqueEmailAddresses.swift | 1 | 1676 | //
// UniqueEmailAddresses.swift
// DataStructure
//
// Created by Jigs Sheth on 11/8/21.
// Copyright © 2021 jigneshsheth.com. All rights reserved.
//
import Foundation
class UniqueEmailAddresses {
func numUniqueEmails(_ emails: [String]) -> Int {
var dict = [String:Bool]()
for email in emails {
let e = email.components(separatedBy:"@")
if e.count != 2 {
continue
}
var localName = e[0]
let domainName = e[1]
if localName.contains("+") {
localName = localName.components(separatedBy:"+")[0]
}
localName = localName.replacingOccurrences(of: ".", with: "")
let modifiedEmail = localName + "@" + domainName
if dict[modifiedEmail] == nil {
dict[modifiedEmail] = true
}
}
return dict.count
}
func numUniqueEmailsWithSet(_ emails: [String]) -> Int {
var uniqueEmails = Set<String>()
for email in emails {
let e = email.components(separatedBy:"@")
if e.count != 2 {
continue
}
var localName = e[0]
let domainName = e[1]
if localName.contains("+") {
localName = localName.components(separatedBy:"+")[0]
}
localName = localName.replacingOccurrences(of: ".", with: "")
uniqueEmails.insert(localName + "@" + domainName)
}
return uniqueEmails.count
}
func licenseKeyFormatting(_ s: String, _ k: Int) -> String {
let charArray = Array(s)
var result = ""
var counter = 0
for i in (0...charArray.count - 1).reversed() {
if charArray[i] != "-" && counter != 2 {
result.append(String(charArray[i]))
}
if counter == 2 {
counter = 0
}else {
counter += 1
}
}
return result
}
}
| mit | 9f2ccd66c6034651b074dd6b2f35dcb6 | 18.940476 | 64 | 0.601194 | 3.418367 | false | false | false | false |
aryshin2016/swfWeibo | WeiBoSwift/WeiBoSwift/Classes/SwiftClass/Mine/MeTableViewController.swift | 1 | 3661 | //
// MeTableViewController.swift
// WeiBoSwift
//
// Created by itogame on 2017/8/15.
// Copyright © 2017年 itogame. All rights reserved.
//
import UIKit
class MeTableViewController: BaseTableViewController {
@objc lazy var visitorMeController : VisitorMeController = {
let visitorMeVC :VisitorMeController = VisitorMeController(nibName: "VisitorMeController", bundle: nil)
return visitorMeVC
}()
override func viewDidLoad() {
super.viewDidLoad()
///
navigationController?.automaticallyAdjustsScrollViewInsets = false
/// 设置返回按钮的样式
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "设置", style: UIBarButtonItemStyle.plain, target: self, action: #selector(settings))
navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.black], for: UIControlState.normal)
///
addChildViewController(visitorMeController)
view.addSubview(visitorMeController.view)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
visitorMeController.view.frame = CGRect(x: 0, y: -64, width: view.frame.size.width, height: UIScreen.main.bounds.size.height)
}
@objc private func settings() ->(){
hidesBottomBarWhenPushed = true // push 过去时隐藏tabbar
let settingsVC = UIStoryboard(name: "SettingsTableViewController", bundle: nil).instantiateInitialViewController()
navigationController?.pushViewController(settingsVC!, animated: true)
hidesBottomBarWhenPushed = false // pop 回来时显示tabbar
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 8bdb068d643a5f9385ebce4460318a0d | 34.80198 | 150 | 0.675332 | 5.28655 | false | false | false | false |
brokenseal/iOS-exercises | Team Treehouse/Interactive Story/Interactive Story/PageController.swift | 1 | 5184 | //
// PageController.swift
// Interactive Story
//
// Created by Davide Callegari on 28/02/17.
// Copyright © 2017 Davide Callegari. All rights reserved.
//
import UIKit
extension NSAttributedString {
var stringRange: NSRange {
return NSMakeRange(0, self.length)
}
}
extension Story {
var attributedText: NSAttributedString {
let label = NSMutableAttributedString(string: text)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10
label.addAttribute(NSParagraphStyleAttributeName,
value: paragraphStyle,
range: label.stringRange)
return label
}
}
extension Page {
func story(attributed: Bool) -> NSAttributedString {
if attributed {
return self.story.attributedText
}
return NSAttributedString(string: story.text)
}
}
class PageController: UIViewController {
var page: Page?
let soundEffectsPlayer = SoundEffectsPlayer()
// MARK: - User Interface Properties
// let artwork = UIImageView()
lazy var artwork: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = self.page?.story.artwork
return imageView
}()
// let storyLabel = UILabel()
lazy var storyLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
label.attributedText = self.page?.story(attributed: true)
return label
}()
//let firstChoiceButton = UIButton(type: .system)
lazy var firstChoiceButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
let title = self.page?.firstChoice?.title ?? "Play Again"
let selector = self.page?.firstChoice != nil ? #selector(PageController.loadFirstChoice) : #selector(PageController.playAgain)
button.setTitle(title, for: .normal)
button.addTarget(self, action: selector, for: .touchUpInside)
return button
}()
lazy var secondChoiceButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(self.page?.secondChoice?.title, for: .normal)
button.addTarget(self, action: #selector(PageController.loadSecondChoice), for: .touchUpInside)
return button
}()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(page: Page) {
self.page = page
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
soundEffectsPlayer.playSoundFor(story: page!.story)
view.backgroundColor = .white
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
view.addSubview(artwork)
NSLayoutConstraint.activate([
artwork.topAnchor.constraint(equalTo: view.topAnchor),
//artwork.bottomAnchor.constraint(equalTo: view.bottomAnchor),
artwork.rightAnchor.constraint(equalTo: view.rightAnchor),
artwork.leftAnchor.constraint(equalTo: view.leftAnchor),
])
view.addSubview(storyLabel)
NSLayoutConstraint.activate([
storyLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16.0),
storyLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16.0),
storyLabel.topAnchor.constraint(equalTo: view.centerYAnchor, constant: -48.0),
])
view.addSubview(firstChoiceButton)
NSLayoutConstraint.activate([
firstChoiceButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
firstChoiceButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -80.0)
])
view.addSubview(secondChoiceButton)
NSLayoutConstraint.activate([
secondChoiceButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
secondChoiceButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32)
])
}
func loadFirstChoice() {
if let page = page, let firstChoice = page.firstChoice {
loadChoice(firstChoice)
}
}
func loadSecondChoice(){
if let page = page, let secondChoice = page.secondChoice {
loadChoice(secondChoice)
}
}
func loadChoice(_ choice: Choice){
let nextPage = choice.page;
let pageController = PageController(page: nextPage)
navigationController?.pushViewController(pageController, animated: true)
}
func playAgain(){
navigationController?.popToRootViewController(animated: true)
}
}
| mit | e7eddb17e1f9eb37e24874a4523ee6a0 | 31.39375 | 134 | 0.6448 | 5.251266 | false | false | false | false |
minimoog/MetalToy | MetalToy/Shaders.swift | 1 | 1875 | //
// Shaders.swift
// MetalToy
//
// Created by Toni Jovanoski on 8/24/17.
// Copyright © 2017 Toni Jovanoski. All rights reserved.
//
import Foundation
public let DefaultVertexShader = """
#include <metal_stdlib>
using namespace metal;
typedef struct
{
packed_float2 position;
} Vertex;
typedef struct
{
float4 fragCoord [[position]];
} FragmentData;
vertex FragmentData
vertexShader(uint vertexID [[vertex_id]],
constant Vertex *vertices [[buffer(0)]])
{
FragmentData out;
out.fragCoord = float4(0.0, 0.0, 0.0, 1.0);
float2 pixelSpacePosition = vertices[vertexID].position;
out.fragCoord.xy = pixelSpacePosition;
return out;
}
//--------------------------------------------------
"""
public let DefaultComputeShader = """
#include <metal_stdlib>
using namespace metal;
typedef struct
{
float time;
} Uniforms;
constexpr sampler textureSampler (mag_filter::linear, min_filter::linear);
kernel void shader(texture2d<float, access::read> texture0 [[texture(0)]],
texture2d<float, access::read> texture1 [[texture(1)]],
texture2d<float, access::read> texture2 [[texture(2)]],
texture2d<float, access::read> texture3 [[texture(3)]],
texture2d<float, access::write> output [[texture(4)]],
constant Uniforms& uniforms [[buffer(0)]],
uint2 gid [[thread_position_in_grid]])
{
int width = output.get_width();
int height = output.get_height();
float2 uv = float2(gid) / float2(width, height);
float4 result = float4(uv, 0.5 + 0.5 * sin(uniforms.time), 1.0);
output.write(result, gid);
}
"""
| mit | f5bb14c2150219b04df905fd63cb5f80 | 27.393939 | 78 | 0.554963 | 4.100656 | false | false | false | false |
archpoint/sparkmap | app/Spark/LocationManager.swift | 1 | 2334 | //
// LocationManager.swift
// Spark
//
// Created by Edvard Holst on 01/11/15.
// Copyright © 2015 Zygote Labs. All rights reserved.
//
import CoreLocation
class LocationManager: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager?
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Location has been updated.
if let location = locations.last {
// let currentLocation = location.coordinate
let locationCoordinate: CLLocationCoordinate2D = location.coordinate
NotificationCenter.default.post(name: Notification.Name(rawValue: "LocationUpdate"), object: nil, userInfo: ["latitude": locationCoordinate.latitude, "longitude": locationCoordinate.longitude])
// Stop location update
self.locationManager?.stopUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
// Authorization has been responded to by the user.
switch status {
case CLAuthorizationStatus.authorizedWhenInUse:
startLocationUpdate()
NotificationCenter.default.post(name: Notification.Name(rawValue: "LocationAuthorized"), object: nil, userInfo: ["isAuthorized": true])
default:
break
}
}
func stopLocationUpdate(){
locationManager?.stopUpdatingLocation()
}
func requestStartLocationUpdate(){
let authStatus = CLLocationManager.authorizationStatus()
switch authStatus {
case CLAuthorizationStatus.authorizedWhenInUse:
// Permission already granted
locationManager = CLLocationManager()
locationManager?.delegate = self
startLocationUpdate()
default:
// Request permission
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestWhenInUseAuthorization()
}
}
func startLocationUpdate() {
locationManager?.desiredAccuracy = 50
locationManager?.distanceFilter = 100
locationManager?.startUpdatingLocation()
}
}
| mit | 3d8ed42f6d510cc16ddafdf39474148a | 32.811594 | 205 | 0.64895 | 6.462604 | false | false | false | false |
BananosTeam/CreativeLab | Assistant/SlackAPI/SlackFetcher.swift | 1 | 4624 | //
// SlackFetcher.swift
// Assistant
//
// Created by Bananos on 5/14/16.
// Copyright © 2016 Bananos. All rights reserved.
//
import Foundation
private let SlackCurrentUserKeyForUserDefaults = "com.bananos.SlackAPI.SlackCurrentUser"
struct SlackFetcher {
static func FetchUsers(tokenQuery: String, callback: [SlackUser] -> ()) {
guard let usersURL = NSURL(string: SlackAPI + "users.list?" + tokenQuery) else { return callback([]) }
let task = NSURLSession.sharedSession().dataTaskWithURL(usersURL) { data, _, error in
guard let data = data,
json = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
dictionary = json as? [String: AnyObject],
usersArray = dictionary["members"] as? [[String: AnyObject]] else {
return callback([])
}
callback(usersArray.flatMap { SlackUser(json: $0) })
}
task.resume()
}
static func FetchChannels(tokenQuery: String, callback: [SlackChannel] -> ()) {
guard let channelsURL = NSURL(string: SlackAPI + "channels.list?" + tokenQuery) else { return callback([]) }
let task = NSURLSession.sharedSession().dataTaskWithURL(channelsURL) { data, _, error in
guard let data = data,
json = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
dictionary = json as? [String: AnyObject],
usersArray = dictionary["channels"] as? [[String: AnyObject]] else {
return callback([])
}
callback(usersArray.flatMap { SlackChannel(json: $0) })
}
task.resume()
}
static func FetchHistory(tokenQuery: String, channel: String, callback: [SlackMessage] -> ()) {
guard let historyURL = NSURL(string: SlackAPI + "channels.history?channel=\(channel)" + tokenQuery) else {
return callback([])
}
let task = NSURLSession.sharedSession().dataTaskWithURL(historyURL) { data, _, error in
guard let data = data,
json = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
dictionary = json as? [String: AnyObject],
usersArray = dictionary["messages"] as? [[String: AnyObject]] else {
return callback([])
}
callback(usersArray.flatMap { SlackMessage(json: $0) })
}
task.resume()
}
static func FetchCurrentUser(tokenQuery: String, callback: SlackUser? -> ()) {
guard let userURL = NSURL(string: SlackAPI + "auth.test?" + tokenQuery) else {
return callback(nil)
}
let task = NSURLSession.sharedSession().dataTaskWithURL(userURL) { data, _, error in
guard let data = data,
json = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
dictionary = json as? [String: AnyObject],
userID = dictionary["user_id"] as? String else {
return callback(nil)
}
FetchUserInfo(tokenQuery, userID: userID, callback: callback)
}
task.resume()
}
static func FetchUserInfo(tokenQuery: String, userID: String , callback: SlackUser? -> ()) {
if let userDictData = NSUserDefaults.standardUserDefaults().objectForKey(SlackCurrentUserKeyForUserDefaults) as? NSData,
dictionary = NSKeyedUnarchiver.unarchiveObjectWithData(userDictData) as? [String: AnyObject],
user = SlackUser(json: dictionary) {
callback(user)
return
}
guard let userURL = NSURL(string: SlackAPI + "users.info?user=\(userID)&" + tokenQuery) else {
return callback(nil)
}
let task = NSURLSession.sharedSession().dataTaskWithURL(userURL) { data, _, error in
guard let data = data,
json = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
dictionary = json["user"] as? [String: AnyObject],
user = SlackUser(json: dictionary) else {
return callback(nil)
}
let userDictData = NSKeyedArchiver.archivedDataWithRootObject(dictionary)
NSUserDefaults.standardUserDefaults().setObject(userDictData, forKey: SlackCurrentUserKeyForUserDefaults)
callback(user)
}
task.resume()
}
}
| mit | 243fbfe911ffe8653974d7b9fd9ae912 | 46.659794 | 128 | 0.608696 | 5.052459 | false | false | false | false |
willpowell8/JIRAMobileKit | JIRAMobileKit/Classes/Model/JIRAImageCell.swift | 1 | 5811 | //
// JIRAImageCell.swift
// JIRAMobileKit
//
// Created by Will Powell on 11/10/2017.
//
import Foundation
protocol JIRAImageCellDelegate {
func jiraImageCellSelected(cell:JIRACell,any:Any, index:Int)
}
class JIRAImageCell:JIRACell,UICollectionViewDelegate, UICollectionViewDataSource{
var collectionView:UICollectionView?
var attachments:[Any]?
var delegateSelection:JIRAImageCellDelegate?
var label = UILabel()
override func setup(){
self.addSubview(label)
label.text = field?.name
self.textLabel?.text = ""
self.textLabel?.isHidden = true
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 16).isActive = true
label.topAnchor.constraint(equalTo: self.topAnchor, constant:10).isActive = true
self.accessoryType = .disclosureIndicator
let flow = UICollectionViewFlowLayout()
flow.scrollDirection = .horizontal
flow.itemSize = CGSize(width: 120, height: 150)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: flow)
collectionView?.backgroundColor = .clear
self.addSubview(collectionView!)
//imageViewArea = UIImageView()
//imageViewArea?.backgroundColor = .clear
//self.addSubview(imageViewArea!)
//imageViewArea?.translatesAutoresizingMaskIntoConstraints = false
collectionView?.translatesAutoresizingMaskIntoConstraints = false
collectionView?.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true
collectionView?.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -30).isActive = true
collectionView?.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -1).isActive = true
collectionView?.topAnchor.constraint(equalTo: self.label.bottomAnchor, constant: 1).isActive = true
collectionView?.delegate = self
collectionView?.dataSource = self
collectionView?.backgroundColor = .clear
collectionView?.register(JIRAImageCollectionCell.self, forCellWithReuseIdentifier: "Attachment")
}
override func applyData(data:[String:Any]){
if let field = field, let identifier = field.identifier {
if let element = data[identifier] as? [Any] {
attachments = element
collectionView?.reloadData()
}
}
}
override func height()->CGFloat{
return 200
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Attachment", for: indexPath) as! JIRAImageCollectionCell
if let item = attachments?[indexPath.row] {
cell.applyData(item)
}
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return attachments?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let item = attachments?[indexPath.row] {
delegateSelection?.jiraImageCellSelected(cell:self, any: item, index: indexPath.row)
}
}
}
class JIRAImageCollectionCell:UICollectionViewCell{
let name = UILabel()
let imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}
func applyData(_ any:Any){
if let image = any as? UIImage {
imageView.image = image
name.text = "Image"
}else if let urlStr = any as? String, let url = URL(string:urlStr){
imageView.image = getImage(url.pathExtension)
name.text = url.lastPathComponent
}else if let url = any as? URL{
imageView.image = getImage(url.pathExtension)
name.text = url.lastPathComponent
}
}
func getImage(_ extensionStr:String)->UIImage? {
let podBundle = Bundle(for: JIRAImageCell.self)
let bundleURL = podBundle.url(forResource: "JIRAMobileKit" , withExtension: "bundle")
let bundle = Bundle(url: bundleURL!)!
return UIImage(named: extensionStr, in: bundle, compatibleWith: nil)
}
func setup(){
self.addSubview(name)
self.addSubview(imageView)
name.translatesAutoresizingMaskIntoConstraints = false
name.textAlignment = .center
name.font = UIFont.systemFont(ofSize: 12)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
name.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 3).isActive = true
name.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -3).isActive = true
name.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -1).isActive = true
name.heightAnchor.constraint(equalToConstant: 13) .isActive = true
imageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
imageView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -23).isActive = true
imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
}
}
| mit | ccd03abed425b90127795bc4321608f8 | 39.075862 | 132 | 0.673378 | 5.151596 | false | false | false | false |
shivansal/Trill-Play | iOS Application/SocketIOTester/MyCollectionViewController.swift | 1 | 3804 | //
// MyCollectionViewController.swift
// Trill
//
// Created by Gagan Kaushik on 1/31/16.
// Copyright © 2016 gk. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
private let reuseIdentifier = "Cell"
class MyCollectionViewController: UICollectionViewController {
var username: String = ""
var json: JSON = JSON.null
var songNum: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: "MyCollectionViewCell")
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return json["playlist"].count/3 + 1
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> MyCollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCollectionViewCell", forIndexPath: indexPath) as! MyCollectionViewCell
if let name = json["playlist"][songNum]["song_name"].string{
cell.label.text = name
}
// cell.buttonWithImage.imageView?.image = UI
// Configure the cell
self.collectionView?.registerNib(UINib(nibName: "MyCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "MyCollectionViewCell")
return cell
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
}
| mit | a53f2b7aba032c75e5b263100f973018 | 34.212963 | 185 | 0.712332 | 5.942188 | false | false | false | false |
zhouguangjie/DynamicColor | DynamicColor/UIColor.swift | 1 | 12280 | /*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
/**
Extension to manipulate colours easily.
It allows you to work hexadecimal strings and value, HSV and RGB components, derivating colours, and many more...
*/
public typealias DynamicColor = UIColor
public extension DynamicColor {
// MARK: - Manipulating Hexa-decimal Values and Strings
/**
Creates a color from an hex string.
:param: hexString A hexa-decimal color string representation.
*/
public convenience init(hexString: String) {
let hexString = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let scanner = NSScanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color: UInt32 = 0
if scanner.scanHexInt(&color) {
self.init(hex: color)
}
else {
self.init(hex: 0x000000)
}
}
/**
Creates a color from an hex integer.
:param: hex A hexa-decimal UInt32 that represents a color.
*/
public convenience init(hex: UInt32) {
let mask = 0x000000FF
let r = Int(hex >> 16) & mask
let g = Int(hex >> 8) & mask
let b = Int(hex) & mask
let red = CGFloat(r) / 255
let green = CGFloat(g) / 255
let blue = CGFloat(b) / 255
self.init(red:red, green:green, blue:blue, alpha:1)
}
/**
Returns the color representation as hexadecimal string.
:returns: A string similar to this pattern "#f4003b".
*/
public final func toHexString() -> String {
return String(format:"#%06x", toHex())
}
/**
Returns the color representation as an integer.
:returns: A UInt32 that represents the hexa-decimal color.
*/
public final func toHex() -> UInt32 {
let rgba = toRGBAComponents()
let colorToInt = (UInt32)(rgba.r * 255) << 16 | (UInt32)(rgba.g * 255) << 8 | (UInt32)(rgba.b * 255) << 0
return colorToInt
}
// MARK: - Getting the RGBA Components
/**
Returns the RGBA (red, green, blue, alpha) components.
:returns: The RGBA components as a tuple (r, g, b, a).
*/
public final func toRGBAComponents() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
return (r, g, b, a)
}
return (0, 0, 0, 0)
}
/**
Returns the red component.
:returns: The red component as CGFloat.
*/
public final func redComponent() -> CGFloat {
return toRGBAComponents().r
}
/**
Returns the green component.
:returns: The green component as CGFloat.
*/
public final func greenComponent() -> CGFloat {
return toRGBAComponents().g
}
/**
Returns the blue component.
:returns: The blue component as CGFloat.
*/
public final func blueComponent() -> CGFloat {
return toRGBAComponents().b
}
/**
Returns the alpha component.
:returns: The alpha component as CGFloat.
*/
public final func alphaComponent() -> CGFloat {
return toRGBAComponents().a
}
// MARK: - Working with HSL Components
/**
Initializes and returns a color object using the specified opacity and HSL component values.
:param: hue The hue component of the color object, specified as a value from 0.0 to 1.0 (0.0 for 0 degree and 1.0 for 360 degree).
:param: saturation The saturation component of the color object, specified as a value from 0.0 to 1.0.
:param: lightness The lightness component of the color object, specified as a value from 0.0 to 1.0.
:param: alpha The opacity value of the color object, specified as a value from 0.0 to 1.0.
*/
public convenience init(hue: CGFloat, saturation: CGFloat, lightness: CGFloat, alpha: CGFloat = 1) {
let color = HSL(hue: hue, saturation: saturation, lightness: lightness, alpha: alpha).toUIColor()
let components = color.toRGBAComponents()
self.init(red: components.r, green: components.g, blue: components.b, alpha: components.a)
}
/**
Returns the HSLA (hue, saturation, lightness, alpha) components.
Notes that the hue value is between 0.0 and 1.0 (0.0 for 0 degree and 1.0 for 360 degree).
:returns: The HSLA components as a tuple (h, s, l, a).
*/
public final func toHSLAComponents() -> (h: CGFloat, s: CGFloat, l: CGFloat, a: CGFloat) {
let hsl = HSL(color: self)
return (hsl.h, hsl.s, hsl.l, hsl.a)
}
// MARK: - Identifying and Comparing Colors
/**
Returns a boolean value that indicates whether the receiver is equal to the given hexa-decimal string.
:param: hexString A hexa-decimal color number representation to be compared to the receiver.
:returns: true if the receiver and the string are equals, otherwise false.
*/
public func isEqualToHexString(hexString: String) -> Bool {
return self.toHexString() == hexString
}
/**
Returns a boolean value that indicates whether the receiver is equal to the given hexa-decimal integer.
:param: hex A UInt32 that represents the hexa-decimal color.
:returns: true if the receiver and the integer are equals, otherwise false.
*/
public func isEqualToHex(hex: UInt32) -> Bool {
return self.toHex() == hex
}
// MARK: - Deriving Colors
/**
Creates and returns a color object with the hue rotated along the color wheel by the given amount.
:param: amount A float representing the number of degrees as ratio (usually -1.0 for -360 degree and 1.0 for 360 degree).
:returns: A UIColor object with the hue changed.
*/
public final func adjustedHueColor(amount: CGFloat) -> UIColor {
return HSL(color: self).adjustHue(amount).toUIColor()
}
/**
Creates and returns the complement of the color object.
This is identical to adjustedHueColor(0.5).
:returns: The complement UIColor.
:see: adjustedHueColor:
*/
public final func complementColor() -> UIColor {
return adjustedHueColor(0.5)
}
/**
Creates and returns a lighter color object.
:returns: An UIColor lightened with an amount of 0.2.
:see: lightenColor:
*/
public final func lighterColor() -> UIColor {
return lightenColor(0.2)
}
/**
Creates and returns a color object with the lightness increased by the given amount.
:param: amount Float between 0.0 and 1.0.
:returns: A lighter UIColor.
*/
public final func lightenColor(amount: CGFloat) -> UIColor {
let normalizedAmount = min(1, max(0, amount))
return HSL(color: self).lighten(normalizedAmount).toUIColor()
}
/**
Creates and returns a darker color object.
:returns: A UIColor darkened with an amount of 0.2.
:see: darkenColor:
*/
public final func darkerColor() -> UIColor {
return darkenColor(0.2)
}
/**
Creates and returns a color object with the lightness decreased by the given amount.
:param: amount Float between 0.0 and 1.0.
:returns: A darker UIColor.
*/
public final func darkenColor(amount: CGFloat) -> UIColor {
let normalizedAmount = min(1, max(0, amount))
return HSL(color: self).darken(normalizedAmount).toUIColor()
}
/**
Creates and returns a color object with the saturation increased by the given amount.
:returns: A UIColor more saturated with an amount of 0.2.
:see: saturateColor:
*/
public final func saturatedColor() -> UIColor {
return saturateColor(0.2)
}
/**
Creates and returns a color object with the saturation increased by the given amount.
:param: amount Float between 0.0 and 1.0.
:returns: A UIColor more saturated.
*/
public final func saturateColor(amount: CGFloat) -> UIColor {
let normalizedAmount = min(1, max(0, amount))
return HSL(color: self).saturate(normalizedAmount).toUIColor()
}
/**
Creates and returns a color object with the saturation decreased by the given amount.
:returns: A UIColor less saturated with an amount of 0.2.
:see: desaturateColor:
*/
public final func desaturatedColor() -> UIColor {
return desaturateColor(0.2)
}
/**
Creates and returns a color object with the saturation decreased by the given amount.
:param: amount Float between 0.0 and 1.0.
:returns: A UIColor less saturated.
*/
public final func desaturateColor(amount: CGFloat) -> UIColor {
let normalizedAmount = min(1, max(0, amount))
return HSL(color: self).desaturate(normalizedAmount).toUIColor()
}
/**
Creates and returns a color object converted to grayscale.
This is identical to desaturateColor(1).
:returns: A grayscale UIColor.
:see: desaturateColor:
*/
public final func grayscaledColor() -> UIColor {
return desaturateColor(1)
}
/**
Creates and return a color object where the red, green, and blue values are inverted, while the opacity is left alone.
:returns: An inverse (negative) of the original color.
*/
public final func invertColor() -> UIColor {
let rgba = toRGBAComponents()
return UIColor(red: 1 - rgba.r, green: 1 - rgba.g, blue: 1 - rgba.b, alpha: rgba.a)
}
// MARK: - Mixing Colors
/**
Mixes the given color object with the receiver.
Specifically, takes the average of each of the RGB components, optionally weighted by the given percentage. The opacity of the colors object is also considered when weighting the components.
:param: color A color object to mix with the receiver.
:param: weight The weight specifies the amount of the given color object (between 0 and 1). The default value is 0.5, which means that half the given color and half the receiver color object should be used. 0.25 means that a quarter of the given color object and three quarters of the receiver color object should be used.
:returns: A color object corresponding to the two colors object mixed together.
*/
public final func mixWithColor(color: UIColor, weight: CGFloat = 0.5) -> UIColor {
let normalizedWeight = min(1, max(0, weight))
let c1 = toRGBAComponents()
let c2 = color.toRGBAComponents()
let w = 2 * normalizedWeight - 1
let a = c1.a - c2.a
let w2 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2
let w1 = 1 - w2
let red = (w1 * c1.r + w2 * c2.r)
let green = (w1 * c1.g + w2 * c2.g)
let blue = (w1 * c1.b + w2 * c2.b)
let alpha = (c1.a * normalizedWeight + c2.a * (1 - normalizedWeight))
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
/**
Creates and returns a color object corresponding to the mix of the receiver and an amount of white color, which increases lightness.
:param: amount Float between 0.0 and 1.0. The default amount is equal to 0.2.
:returns: A lighter UIColor.
*/
public final func tintColor(amount: CGFloat = 0.2) -> UIColor {
return mixWithColor(UIColor.whiteColor(), weight: amount)
}
/**
Creates and returns a color object corresponding to the mix of the receiver and an amount of black color, which reduces lightness.
:param: amount Float between 0.0 and 1.0. The default amount is equal to 0.2.
:returns: A darker UIColor.
*/
public final func shadeColor(amount: CGFloat = 0.2) -> UIColor {
return mixWithColor(UIColor.blackColor(), weight: amount)
}
}
| mit | 3270cf73aae2bc1c073469192c49a03d | 28.878345 | 324 | 0.688111 | 4.010451 | false | false | false | false |
gmilos/swift | test/SILGen/objc_init_ref_delegation.swift | 2 | 1343 | // RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
extension Gizmo {
// CHECK-LABEL: sil hidden @_TFE24objc_init_ref_delegationCSo5Gizmoc
convenience init(int i: Int) {
// CHECK: bb0([[I:%[0-9]+]] : $Int, [[ORIG_SELF:%[0-9]+]] : $Gizmo):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Gizmo }
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELFMUI:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*Gizmo
// CHECK: store [[ORIG_SELF]] to [init] [[SELFMUI]] : $*Gizmo
// SEMANTIC ARC TODO: Another case of needing a mutable borrow load.
// CHECK: [[SELF:%[0-9]+]] = load_borrow [[SELFMUI]] : $*Gizmo
// CHECK: [[INIT_DELEG:%[0-9]+]] = class_method [volatile] [[SELF]] : $Gizmo, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo! , $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: [[SELF_RET:%[0-9]+]] = apply [[INIT_DELEG]]([[I]], [[SELF]]) : $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: [[SELF4:%.*]] = load [copy] [[SELFMUI]]
// CHECK: destroy_value [[SELF_BOX:%[0-9]+]] : ${ var Gizmo }
// CHECK: return [[SELF4]] : $Gizmo
self.init(bellsOn:i)
}
}
| apache-2.0 | b4affc326c17b4c2235f0bf9977a65f1 | 54.958333 | 225 | 0.578555 | 3.152582 | false | false | false | false |
gmilos/swift | test/SILGen/switch.swift | 4 | 33147 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
func markUsed<T>(_ t: T) {}
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int, Int), y: (Int, Int)) -> Bool {
return x.0 == y.0 && x.1 == y.1
}
// Some fake predicates for pattern guards.
func runced() -> Bool { return true }
func funged() -> Bool { return true }
func ansed() -> Bool { return true }
func foo() -> Int { return 0 }
func bar() -> Int { return 0 }
func foobar() -> (Int, Int) { return (0, 0) }
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func f() {}
func g() {}
// CHECK-LABEL: sil hidden @_TF6switch5test1FT_T_
func test1() {
switch foo() {
// CHECK: function_ref @_TF6switch3fooFT_Si
case _:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1bFT_T_
b()
}
// CHECK-LABEL: sil hidden @_TF6switch5test2FT_T_
func test2() {
switch foo() {
// CHECK: function_ref @_TF6switch3fooFT_Si
case _:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
case _: // The second case is unreachable.
b()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1cFT_T_
c()
}
// CHECK-LABEL: sil hidden @_TF6switch5test3FT_T_
func test3() {
switch foo() {
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: function_ref @_TF6switch6runcedFT_Sb
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case _ where runced():
// CHECK: [[CASE1]]:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NO_CASE2]]:
// CHECK: br [[CASE2:bb[0-9]+]]
case _:
// CHECK: [[CASE2]]:
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1cFT_T_
c()
}
// CHECK-LABEL: sil hidden @_TF6switch5test4FT_T_
func test4() {
switch (foo(), bar()) {
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: function_ref @_TF6switch3barFT_Si
case _:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1bFT_T_
b()
}
// CHECK-LABEL: sil hidden @_TF6switch5test5FT_T_
func test5() {
switch (foo(), bar()) {
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: function_ref @_TF6switch3barFT_Si
// CHECK: function_ref @_TF6switch6runcedFT_Sb
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
case _ where runced():
// CHECK: [[CASE1]]:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NOT_CASE1]]:
// CHECK: function_ref @_TF6switch6fungedFT_Sb
// CHECK: cond_br {{%.*}}, [[YES_CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]]
// CHECK: [[YES_CASE2]]:
case (_, _) where funged():
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
// CHECK: [[NOT_CASE2]]:
// CHECK: br [[CASE3:bb[0-9]+]]
case _:
// CHECK: [[CASE3]]:
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[CONT]]
c()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1dFT_T_
d()
}
// CHECK-LABEL: sil hidden @_TF6switch5test6FT_T_
func test6() {
switch (foo(), bar()) {
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: function_ref @_TF6switch3barFT_Si
case (_, _):
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
case (_, _): // The second case is unreachable.
b()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1cFT_T_
c()
}
// CHECK-LABEL: sil hidden @_TF6switch5test7FT_T_
func test7() {
switch (foo(), bar()) {
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: function_ref @_TF6switch3barFT_Si
// CHECK: function_ref @_TF6switch6runcedFT_Sb
// CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
// CHECK: [[YES_CASE1]]:
case (_, _) where runced():
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NOT_CASE1]]:
// CHECK: br [[CASE2:bb[0-9]+]]
case (_, _):
// CHECK: [[CASE2]]:
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
}
c()
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1cFT_T_
}
// CHECK-LABEL: sil hidden @_TF6switch5test8FT_T_
func test8() {
switch (foo(), bar()) {
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: function_ref @_TF6switch3barFT_Si
// CHECK: function_ref @_TF6switch6foobarFT_TSiSi_
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
case foobar():
// CHECK: [[CASE1]]:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NOT_CASE1]]:
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]]
case (foo(), _):
// CHECK: [[CASE2]]:
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
// CHECK: [[NOT_CASE2]]:
// CHECK: function_ref @_TF6switch3barFT_Si
// CHECK: cond_br {{%.*}}, [[CASE3_GUARD:bb[0-9]+]], [[NOT_CASE3:bb[0-9]+]]
// CHECK: [[CASE3_GUARD]]:
// CHECK: function_ref @_TF6switch6runcedFT_Sb
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NOT_CASE3_GUARD:bb[0-9]+]]
case (_, bar()) where runced():
// CHECK: [[CASE3]]:
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[CONT]]
c()
// CHECK: [[NOT_CASE3_GUARD]]:
// CHECK: [[NOT_CASE3]]:
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: cond_br {{%.*}}, [[CASE4_GUARD_1:bb[0-9]+]], [[NOT_CASE4_1:bb[0-9]+]]
// CHECK: [[CASE4_GUARD_1]]:
// CHECK: function_ref @_TF6switch3barFT_Si
// CHECK: cond_br {{%.*}}, [[CASE4_GUARD_2:bb[0-9]+]], [[NOT_CASE4_2:bb[0-9]+]]
// CHECK: [[CASE4_GUARD_2]]:
// CHECK: function_ref @_TF6switch6fungedFT_Sb
// CHECK: cond_br {{%.*}}, [[CASE4:bb[0-9]+]], [[NOT_CASE4_3:bb[0-9]+]]
case (foo(), bar()) where funged():
// CHECK: [[CASE4]]:
// CHECK: function_ref @_TF6switch1dFT_T_
// CHECK: br [[CONT]]
d()
// CHECK: [[NOT_CASE4_3]]:
// CHECK: [[NOT_CASE4_2]]:
// CHECK: [[NOT_CASE4_1]]:
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: cond_br {{%.*}}, [[CASE5_GUARD_1:bb[0-9]+]], [[NOT_CASE5:bb[0-9]+]]
// CHECK: [[CASE5_GUARD_1]]:
// CHECK: function_ref @_TF6switch3barFT_Si
// CHECK: cond_br {{%.*}}, [[YES_CASE5:bb[0-9]+]], [[NOT_CASE5:bb[0-9]+]]
// CHECK: [[YES_CASE5]]:
case (foo(), bar()):
// CHECK: function_ref @_TF6switch1eFT_T_
// CHECK: br [[CONT]]
e()
// CHECK: [[NOT_CASE5]]:
// CHECK: br [[CASE6:bb[0-9]+]]
case _:
// CHECK: [[CASE6]]:
// CHECK: function_ref @_TF6switch1fFT_T_
// CHECK: br [[CONT]]
f()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1gFT_T_
g()
}
// CHECK-LABEL: sil hidden @_TF6switch5test9FT_T_
func test9() {
switch (foo(), bar()) {
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: function_ref @_TF6switch3barFT_Si
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
// CHECK: [[YES_CASE1]]:
case (foo(), _):
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NOT_CASE1]]:
// CHECK: function_ref @_TF6switch6foobarFT_TSiSi_
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]]
case foobar():
// CHECK: [[CASE2]]:
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
// CHECK: [[NOT_CASE2]]:
// CHECK: br [[CASE3:bb[0-9]+]]
case _:
// CHECK: [[CASE3]]:
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[CONT]]
c()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1dFT_T_
d()
}
// CHECK-LABEL: sil hidden @_TF6switch6test10FT_T_
func test10() {
switch (foo(), bar()) {
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: function_ref @_TF6switch3barFT_Si
// CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
// CHECK: [[YES_CASE1]]:
case (foo()...bar(), _):
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NOT_CASE1]]:
// CHECK: br [[CASE2:bb[0-9]+]]
case _:
// CHECK: [[CASE2]]:
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1cFT_T_
c()
}
protocol P { func p() }
struct X : P { func p() {} }
struct Y : P { func p() {} }
struct Z : P { func p() {} }
// CHECK-LABEL: sil hidden @_TF6switch10test_isa_1FT1pPS_1P__T_
func test_isa_1(p: P) {
// CHECK: [[PTMPBUF:%[0-9]+]] = alloc_stack $P
// CHECK-NEXT: copy_addr %0 to [initialization] [[PTMPBUF]] : $*P
switch p {
// CHECK: [[TMPBUF:%[0-9]+]] = alloc_stack $X
// CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in [[TMPBUF]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
case is X:
// CHECK: [[IS_X]]:
// CHECK-NEXT: load [trivial] [[TMPBUF]]
// CHECK-NEXT: dealloc_stack [[TMPBUF]]
// CHECK-NEXT: destroy_addr [[PTMPBUF]]
// CHECK-NEXT: dealloc_stack [[PTMPBUF]]
a()
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
// CHECK: [[IS_NOT_X]]:
// CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
case is Y:
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[Y_CONT:bb[0-9]+]]
b()
// CHECK: [[IS_NOT_Y]]:
// CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Z in {{%.*}} : $*Z, [[IS_Z:bb[0-9]+]], [[IS_NOT_Z:bb[0-9]+]]
// CHECK: [[IS_Z]]:
case is Z:
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[Z_CONT:bb[0-9]+]]
c()
// CHECK: [[IS_NOT_Z]]:
case _:
// CHECK: function_ref @_TF6switch1dFT_T_
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1eFT_T_
e()
}
// CHECK-LABEL: sil hidden @_TF6switch10test_isa_2FT1pPS_1P__T_
func test_isa_2(p: P) {
switch (p, foo()) {
// CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in {{%.*}} : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
// CHECK: [[IS_X]]:
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
case (is X, foo()):
// CHECK: [[CASE1]]:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_NOT_X]]:
// CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
// CHECK: function_ref @_TF6switch3fooFT_Si
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]]
case (is Y, foo()):
// CHECK: [[CASE2]]:
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
// CHECK: [[NOT_CASE2]]:
// CHECK: [[IS_NOT_Y]]:
// CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in {{%.*}} : $*X, [[CASE3:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
case (is X, _):
// CHECK: [[CASE3]]:
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[CONT]]
c()
// -- case (is Y, foo()):
// CHECK: [[IS_NOT_X]]:
// CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
// CHECK: function_ref @_TF6switch3barFT_Si
// CHECK: cond_br {{%.*}}, [[CASE4:bb[0-9]+]], [[NOT_CASE4:bb[0-9]+]]
case (is Y, bar()):
// CHECK: [[CASE4]]:
// CHECK: function_ref @_TF6switch1dFT_T_
// CHECK: br [[CONT]]
d()
// CHECK: [[NOT_CASE4]]:
// CHECK: br [[CASE5:bb[0-9]+]]
// CHECK: [[IS_NOT_Y]]:
// CHECK: br [[CASE5]]
case _:
// CHECK: [[CASE5]]:
// CHECK: function_ref @_TF6switch1eFT_T_
// CHECK: br [[CONT]]
e()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1fFT_T_
f()
}
class B {}
class C : B {}
class D1 : C {}
class D2 : D1 {}
class E : C {}
// CHECK-LABEL: sil hidden @_TF6switch16test_isa_class_1FT1xCS_1B_T_ : $@convention(thin) (@owned B) -> () {
func test_isa_class_1(x: B) {
// CHECK: bb0([[X:%.*]] : $B):
// CHECK: [[X_COPY:%.*]] = copy_value [[X]]
// CHECK: checked_cast_br [[X_COPY]] : $B to $D1, [[IS_D1:bb[0-9]+]], [[IS_NOT_D1:bb[0-9]+]]
switch x {
// CHECK: [[IS_D1]]([[CAST_D1:%.*]]):
// CHECK: [[CAST_D1_COPY:%.*]] = copy_value [[CAST_D1]]
// CHECK: function_ref @_TF6switch6runcedFT_Sb : $@convention(thin) () -> Bool
// CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
// CHECK: [[YES_CASE1]]:
case is D1 where runced():
// CHECK: destroy_value [[CAST_D1_COPY]]
// CHECK: destroy_value [[X_COPY]]
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[CAST_D1_COPY]]
// CHECK: br [[NEXT_CASE:bb5]]
// CHECK: [[IS_NOT_D1]]:
// CHECK: br [[NEXT_CASE]]
// CHECK: [[NEXT_CASE]]
// CHECK: checked_cast_br [[X_COPY]] : $B to $D2, [[IS_D2:bb[0-9]+]], [[IS_NOT_D2:bb[0-9]+]]
case is D2:
// CHECK: [[IS_D2]]([[CAST_D2:%.*]]):
// CHECK: [[CAST_D2_COPY:%.*]] = copy_value [[CAST_D2]]
// CHECK: destroy_value [[CAST_D2_COPY]]
// CHECK: destroy_value [[X_COPY]]
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_NOT_D2]]:
// CHECK: br [[NEXT_CASE:bb8]]
// CHECK: [[NEXT_CASE]]:
// CHECK: checked_cast_br [[X_COPY]] : $B to $E, [[IS_E:bb[0-9]+]], [[IS_NOT_E:bb[0-9]+]]
case is E where funged():
// CHECK: [[IS_E]]([[CAST_E:%.*]]):
// CHECK: [[CAST_E_COPY:%.*]] = copy_value [[CAST_E]]
// CHECK: function_ref @_TF6switch6fungedFT_Sb
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// CHECK: [[CASE3]]:
// CHECK: destroy_value [[CAST_E_COPY]]
// CHECK: destroy_value [[X_COPY]]
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[CAST_E_COPY]]
// CHECK: br [[NEXT_CASE:bb13]]
// CHECK: [[IS_NOT_E]]:
// CHECK: br [[NEXT_CASE]]
// CHECK: [[NEXT_CASE]]
// CHECK: checked_cast_br [[X_COPY]] : $B to $C, [[IS_C:bb[0-9]+]], [[IS_NOT_C:bb[0-9]+]]
case is C:
// CHECK: [[IS_C]]([[CAST_C:%.*]]):
// CHECK: [[CAST_C_COPY:%.*]] = copy_value [[CAST_C]]
// CHECK: destroy_value [[CAST_C_COPY]]
// CHECK: destroy_value [[X_COPY]]
// CHECK: function_ref @_TF6switch1dFT_T_
// CHECK: br [[CONT]]
d()
// CHECK: [[IS_NOT_C]]:
// CHECK: br [[NEXT_CASE:bb16]]
// CHECK: [[NEXT_CASE]]:
default:
// CHECK: destroy_value [[X_COPY]]
// CHECK: function_ref @_TF6switch1eFT_T_
// CHECK: br [[CONT]]
e()
}
// CHECK: [[CONT]]:
// CHECK: [[F_FUNC:%.*]] = function_ref @_TF6switch1fFT_T_ : $@convention(thin) () -> ()
// CHECK: apply [[F_FUNC]]()
// CHECK: destroy_value [[X]]
f()
}
// CHECK: } // end sil function '_TF6switch16test_isa_class_1FT1xCS_1B_T_'
// CHECK-LABEL: sil hidden @_TF6switch16test_isa_class_2FT1xCS_1B_Ps9AnyObject_ : $@convention(thin)
func test_isa_class_2(x: B) -> AnyObject {
// CHECK: bb0([[X:%.*]] : $B):
// CHECK: [[X_COPY:%.*]] = copy_value [[X]]
switch x {
// CHECK: checked_cast_br [[X_COPY]] : $B to $D1, [[IS_D1:bb[0-9]+]], [[IS_NOT_D1:bb[0-9]+]]
case let y as D1 where runced():
// CHECK: [[IS_D1]]([[CAST_D1:%.*]] : $D1):
// CHECK: [[CAST_D1_COPY:%.*]] = copy_value [[CAST_D1]]
// CHECK: function_ref @_TF6switch6runcedFT_Sb
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
// CHECK: [[CASE1]]:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: [[CAST_D1_COPY_COPY:%.*]] = copy_value [[CAST_D1_COPY]]
// CHECK: [[RET:%.*]] = init_existential_ref [[CAST_D1_COPY_COPY]]
// CHECK: destroy_value [[CAST_D1_COPY]]
// CHECK: destroy_value [[X_COPY]] : $B
// CHECK: br [[CONT:bb[0-9]+]]([[RET]] : $AnyObject)
a()
return y
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[CAST_D1_COPY]]
// CHECK: br [[NEXT_CASE:bb5]]
// CHECK: [[IS_NOT_D1]]:
// CHECK: br [[NEXT_CASE]]
// CHECK: [[NEXT_CASE]]:
// CHECK: checked_cast_br [[X_COPY]] : $B to $D2, [[CASE2:bb[0-9]+]], [[IS_NOT_D2:bb[0-9]+]]
case let y as D2:
// CHECK: [[CASE2]]([[CAST_D2:%.*]]):
// CHECK: [[CAST_D2_COPY:%.*]] = copy_value [[CAST_D2]]
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: [[CAST_D2_COPY_COPY:%.*]] = copy_value [[CAST_D2_COPY]]
// CHECK: [[RET:%.*]] = init_existential_ref [[CAST_D2_COPY_COPY]]
// CHECK: destroy_value [[CAST_D2_COPY]]
// CHECK: destroy_value [[X_COPY]]
// CHECK: br [[CONT]]([[RET]] : $AnyObject)
b()
return y
// CHECK: [[IS_NOT_D2]]:
// CHECK: br [[NEXT_CASE:bb8]]
// CHECK: [[NEXT_CASE]]:
// CHECK: checked_cast_br [[X_COPY]] : $B to $E, [[IS_E:bb[0-9]+]], [[IS_NOT_E:bb[0-9]+]]
case let y as E where funged():
// CHECK: [[IS_E]]([[CAST_E:%.*]]):
// CHECK: [[CAST_E_COPY:%.*]] = copy_value [[CAST_E]]
// CHECK: function_ref @_TF6switch6fungedFT_Sb
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// CHECK: [[CASE3]]:
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: [[CAST_E_COPY_COPY:%.*]] = copy_value [[CAST_E_COPY]]
// CHECK: [[RET:%.*]] = init_existential_ref [[CAST_E_COPY_COPY]]
// CHECK: destroy_value [[CAST_E_COPY]]
// CHECK: destroy_value [[X_COPY]] : $B
// CHECK: br [[CONT]]([[RET]] : $AnyObject)
c()
return y
// CHECK: [[NO_CASE3]]:
// CHECK destroy_value [[CAST_E_COPY]]
// CHECK: br [[NEXT_CASE:bb13]]
// CHECK: [[IS_NOT_E]]:
// CHECK: br [[NEXT_CASE]]
// CHECK: [[NEXT_CASE]]
// CHECK: checked_cast_br [[X_COPY]] : $B to $C, [[CASE4:bb[0-9]+]], [[IS_NOT_C:bb[0-9]+]]
case let y as C:
// CHECK: [[CASE4]]([[CAST_C:%.*]]):
// CHECK: [[CAST_C_COPY:%.*]] = copy_value [[CAST_C]]
// CHECK: function_ref @_TF6switch1dFT_T_
// CHECK: [[CAST_C_COPY_COPY:%.*]] = copy_value [[CAST_C_COPY]]
// CHECK: [[RET:%.*]] = init_existential_ref [[CAST_C_COPY_COPY]]
// CHECK: destroy_value [[CAST_C_COPY]]
// CHECK: destroy_value [[X_COPY]]
// CHECK: br [[CONT]]([[RET]] : $AnyObject)
d()
return y
// CHECK: [[IS_NOT_C]]:
// CHECK: br [[NEXT_CASE:bb16]]
// CHECK: [[NEXT_CASE]]:
default:
// CHECK: destroy_value [[X_COPY]]
// CHECK: function_ref @_TF6switch1eFT_T_
// CHECK: [[X_COPY_2:%.*]] = copy_value [[X]]
// CHECK: [[RET:%.*]] = init_existential_ref [[X_COPY_2]]
// CHECK: br [[CONT]]([[RET]] : $AnyObject)
e()
return x
}
// CHECK: [[CONT]]([[T0:%.*]] : $AnyObject):
// CHECK: destroy_value [[X]]
// CHECK: return [[T0]]
}
// CHECK: } // end sil function '_TF6switch16test_isa_class_2FT1xCS_1B_Ps9AnyObject_'
enum MaybePair {
case Neither
case Left(Int)
case Right(String)
case Both(Int, String)
}
// CHECK-LABEL: sil hidden @_TF6switch12test_union_1FT1uOS_9MaybePair_T_
func test_union_1(u: MaybePair) {
switch u {
// CHECK: switch_enum [[SUBJECT:%.*]] : $MaybePair,
// CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]],
// CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]],
// CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]],
// CHECK: case #MaybePair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]]
// CHECK: [[IS_NEITHER]]:
// CHECK-NOT: destroy_value
case .Neither:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_LEFT]]({{%.*}}):
// CHECK-NOT: destroy_value
case (.Left):
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_RIGHT]]([[STR:%.*]] : $String):
case var .Right:
// CHECK: destroy_value [[STR]] : $String
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[CONT]]
c()
// CHECK: [[IS_BOTH]]([[TUP:%.*]] : $(Int, String)):
case .Both:
// CHECK: destroy_value [[TUP]] : $(Int, String)
// CHECK: function_ref @_TF6switch1dFT_T_
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK-NOT: switch_enum [[SUBJECT]]
// CHECK: function_ref @_TF6switch1eFT_T_
e()
}
// CHECK-LABEL: sil hidden @_TF6switch12test_union_2FT1uOS_9MaybePair_T_
func test_union_2(u: MaybePair) {
switch u {
// CHECK: switch_enum {{%.*}} : $MaybePair,
// CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]],
// CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]],
// CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]],
// CHECK: default [[DEFAULT:bb[0-9]+]]
// CHECK: [[IS_NEITHER]]:
case .Neither:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_LEFT]]({{%.*}}):
case .Left:
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_RIGHT]]({{%.*}}):
case .Right:
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[CONT]]
c()
// -- missing .Both case
// CHECK: [[DEFAULT]]:
// CHECK: unreachable
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1dFT_T_
d()
}
// CHECK-LABEL: sil hidden @_TF6switch12test_union_3FT1uOS_9MaybePair_T_ : $@convention(thin) (@owned MaybePair) -> () {
func test_union_3(u: MaybePair) {
// CHECK: bb0([[ARG:%.*]] : $MaybePair):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[SUBJECT]] : $MaybePair,
// CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]],
// CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]],
// CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]],
// CHECK: default [[DEFAULT:bb[0-9]+]]
switch u {
// CHECK: [[IS_NEITHER]]:
case .Neither:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_LEFT]]({{%.*}}):
case .Left:
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_RIGHT]]([[STR:%.*]] : $String):
case .Right:
// CHECK: destroy_value [[STR]] : $String
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[CONT]]
c()
// CHECK: [[DEFAULT]]:
// -- Ensure the fully-opaque value is destroyed in the default case.
// CHECK: destroy_value [[ARG_COPY]] :
// CHECK: function_ref @_TF6switch1dFT_T_
// CHECK: br [[CONT]]
default:
d()
}
// CHECK: [[CONT]]:
// CHECK-NOT: switch_enum [[ARG]]
// CHECK: function_ref @_TF6switch1eFT_T_
// CHECK: destroy_value [[ARG]]
e()
}
// CHECK-LABEL: sil hidden @_TF6switch12test_union_4FT1uOS_9MaybePair_T_
func test_union_4(u: MaybePair) {
switch u {
// CHECK: switch_enum {{%.*}} : $MaybePair,
// CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]],
// CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]],
// CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]],
// CHECK: case #MaybePair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]]
// CHECK: [[IS_NEITHER]]:
case .Neither(_):
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_LEFT]]({{%.*}}):
case .Left(_):
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_RIGHT]]({{%.*}}):
case .Right(_):
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[CONT]]
c()
// CHECK: [[IS_BOTH]]({{%.*}}):
case .Both(_):
// CHECK: function_ref @_TF6switch1dFT_T_
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1eFT_T_
e()
}
// CHECK-LABEL: sil hidden @_TF6switch12test_union_5FT1uOS_9MaybePair_T_
func test_union_5(u: MaybePair) {
switch u {
// CHECK: switch_enum {{%.*}} : $MaybePair,
// CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]],
// CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]],
// CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]],
// CHECK: case #MaybePair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]]
// CHECK: [[IS_NEITHER]]:
case .Neither():
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_LEFT]]({{%.*}}):
case .Left(_):
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_RIGHT]]({{%.*}}):
case .Right(_):
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[CONT]]
c()
// CHECK: [[IS_BOTH]]({{%.*}}):
case .Both(_, _):
// CHECK: function_ref @_TF6switch1dFT_T_
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1eFT_T_
e()
}
enum MaybeAddressOnlyPair {
case Neither
case Left(P)
case Right(String)
case Both(P, String)
}
// CHECK-LABEL: sil hidden @_TF6switch22test_union_addr_only_1FT1uOS_20MaybeAddressOnlyPair_T_
func test_union_addr_only_1(u: MaybeAddressOnlyPair) {
switch u {
// CHECK: switch_enum_addr [[ENUM_ADDR:%.*]] : $*MaybeAddressOnlyPair,
// CHECK: case #MaybeAddressOnlyPair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]],
// CHECK: case #MaybeAddressOnlyPair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]],
// CHECK: case #MaybeAddressOnlyPair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]],
// CHECK: case #MaybeAddressOnlyPair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]]
// CHECK: [[IS_NEITHER]]:
case .Neither:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_LEFT]]:
// CHECK: [[P:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Left!enumelt.1
case .Left(_):
// CHECK: destroy_addr [[P]]
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_RIGHT]]:
// CHECK: [[STR_ADDR:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Right!enumelt.1
// CHECK: [[STR:%.*]] = load [take] [[STR_ADDR]]
case .Right(_):
// CHECK: destroy_value [[STR]] : $String
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: br [[CONT]]
c()
// CHECK: [[IS_BOTH]]:
// CHECK: [[P_STR_TUPLE:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Both!enumelt.1
case .Both(_):
// CHECK: destroy_addr [[P_STR_TUPLE]]
// CHECK: function_ref @_TF6switch1dFT_T_
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_TF6switch1eFT_T_
e()
}
enum Generic<T, U> {
case Foo(T)
case Bar(U)
}
// Check that switching over a generic instance generates verified SIL.
func test_union_generic_instance(u: Generic<Int, String>) {
switch u {
case .Foo(var x):
a()
case .Bar(var y):
b()
}
c()
}
enum Foo { case A, B }
// CHECK-LABEL: sil hidden @_TF6switch22test_switch_two_unionsFT1xOS_3Foo1yS0__T_
func test_switch_two_unions(x: Foo, y: Foo) {
// CHECK: [[T0:%.*]] = tuple (%0 : $Foo, %1 : $Foo)
// CHECK: [[X:%.*]] = tuple_extract [[T0]] : $(Foo, Foo), 0
// CHECK: [[Y:%.*]] = tuple_extract [[T0]] : $(Foo, Foo), 1
// CHECK: switch_enum [[Y]] : $Foo, case #Foo.A!enumelt: [[IS_CASE1:bb[0-9]+]], default [[IS_NOT_CASE1:bb[0-9]+]]
switch (x, y) {
// CHECK: [[IS_CASE1]]:
case (_, Foo.A):
// CHECK: function_ref @_TF6switch1aFT_T_
a()
// CHECK: [[IS_NOT_CASE1]]:
// CHECK: switch_enum [[X]] : $Foo, case #Foo.B!enumelt: [[IS_CASE2:bb[0-9]+]], default [[IS_NOT_CASE2:bb[0-9]+]]
// CHECK: [[IS_CASE2]]:
case (Foo.B, _):
// CHECK: function_ref @_TF6switch1bFT_T_
b()
// CHECK: [[IS_NOT_CASE2]]:
// CHECK: switch_enum [[Y]] : $Foo, case #Foo.B!enumelt: [[IS_CASE3:bb[0-9]+]], default [[UNREACHABLE:bb[0-9]+]]
// CHECK: [[IS_CASE3]]:
case (_, Foo.B):
// CHECK: function_ref @_TF6switch1cFT_T_
c()
// CHECK: [[UNREACHABLE]]:
// CHECK: unreachable
}
}
// <rdar://problem/14826416>
func rdar14826416<T, U>(t: T, u: U) {
switch t {
case is Int: markUsed("Int")
case is U: markUsed("U")
case _: markUsed("other")
}
}
// CHECK-LABEL: sil hidden @_TF6switch12rdar14826416
// CHECK: checked_cast_addr_br copy_on_success T in {{%.*}} : $*T to Int in {{%.*}} : $*Int, [[IS_INT:bb[0-9]+]], [[ISNT_INT:bb[0-9]+]]
// CHECK: [[ISNT_INT]]:
// CHECK: checked_cast_addr_br copy_on_success T in {{%.*}} : $*T to U in {{%.*}} : $*U, [[ISNT_INT_IS_U:bb[0-9]+]], [[ISNT_INT_ISNT_U:bb[0-9]+]]
// <rdar://problem/14835992>
class Rdar14835992 {}
class SubRdar14835992 : Rdar14835992 {}
// CHECK-LABEL: sil hidden @_TF6switch12rdar14835992
func rdar14835992<T, U>(t: Rdar14835992, tt: T, uu: U) {
switch t {
case is SubRdar14835992: markUsed("Sub")
case is T: markUsed("T")
case is U: markUsed("U")
case _: markUsed("other")
}
}
// <rdar://problem/17272985>
enum ABC { case A, B, C }
// CHECK-LABEL: sil hidden @_TF6switch18testTupleWildcardsFTOS_3ABCS0__T_
// CHECK: [[X:%.*]] = tuple_extract {{%.*}} : $(ABC, ABC), 0
// CHECK: [[Y:%.*]] = tuple_extract {{%.*}} : $(ABC, ABC), 1
// CHECK: switch_enum [[X]] : $ABC, case #ABC.A!enumelt: [[X_A:bb[0-9]+]], default [[X_NOT_A:bb[0-9]+]]
// CHECK: [[X_A]]:
// CHECK: function_ref @_TF6switch1aFT_T_
// CHECK: [[X_NOT_A]]:
// CHECK: switch_enum [[Y]] : $ABC, case #ABC.A!enumelt: [[Y_A:bb[0-9]+]], case #ABC.B!enumelt: [[Y_B:bb[0-9]+]], case #ABC.C!enumelt: [[Y_C:bb[0-9]+]]
// CHECK-NOT: default
// CHECK: [[Y_A]]:
// CHECK: function_ref @_TF6switch1bFT_T_
// CHECK: [[Y_B]]:
// CHECK: function_ref @_TF6switch1cFT_T_
// CHECK: [[Y_C]]:
// CHECK: switch_enum [[X]] : $ABC, case #ABC.C!enumelt: [[X_C:bb[0-9]+]], default [[X_NOT_C:bb[0-9]+]]
// CHECK: [[X_C]]:
// CHECK: function_ref @_TF6switch1dFT_T_
// CHECK: [[X_NOT_C]]:
// CHECK: function_ref @_TF6switch1eFT_T_
func testTupleWildcards(_ x: ABC, _ y: ABC) {
switch (x, y) {
case (.A, _):
a()
case (_, .A):
b()
case (_, .B):
c()
case (.C, .C):
d()
default:
e()
}
}
enum LabeledScalarPayload {
case Payload(name: Int)
}
// CHECK-LABEL: sil hidden @_TF6switch24testLabeledScalarPayloadFOS_20LabeledScalarPayloadP_
func testLabeledScalarPayload(_ lsp: LabeledScalarPayload) -> Any {
// CHECK: switch_enum {{%.*}}, case #LabeledScalarPayload.Payload!enumelt.1: bb1
switch lsp {
// CHECK: bb1([[TUPLE:%.*]] : $(name: Int)):
// CHECK: [[X:%.*]] = tuple_extract [[TUPLE]]
// CHECK: [[ANY_X_ADDR:%.*]] = init_existential_addr {{%.*}}, $Int
// CHECK: store [[X]] to [trivial] [[ANY_X_ADDR]]
case let .Payload(x):
return x
}
}
// There should be no unreachable generated.
// CHECK-LABEL: sil hidden @_TF6switch19testOptionalPatternFGSqSi_T_
func testOptionalPattern(_ value : Int?) {
// CHECK: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
switch value {
case 1?: a()
case 2?: b()
case nil: d()
default: e()
}
}
// x? and .none should both be considered "similar" and thus handled in the same
// switch on the enum kind. There should be no unreachable generated.
// CHECK-LABEL: sil hidden @_TF6switch19testOptionalEnumMixFGSqSi_Si
func testOptionalEnumMix(_ a : Int?) -> Int {
// CHECK: debug_value %0 : $Optional<Int>, let, name "a"
// CHECK-NEXT: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt.1: [[SOMEBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
switch a {
case let x?:
return 0
// CHECK: [[SOMEBB]](%3 : $Int):
// CHECK-NEXT: debug_value %3 : $Int, let, name "x"
// CHECK: integer_literal $Builtin.Int2048, 0
case .none:
return 42
// CHECK: [[NILBB]]:
// CHECK: integer_literal $Builtin.Int2048, 42
}
}
// x? and nil should both be considered "similar" and thus handled in the same
// switch on the enum kind. There should be no unreachable generated.
// CHECK-LABEL: sil hidden @_TF6switch26testOptionalEnumMixWithNilFGSqSi_Si
func testOptionalEnumMixWithNil(_ a : Int?) -> Int {
// CHECK: debug_value %0 : $Optional<Int>, let, name "a"
// CHECK-NEXT: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt.1: [[SOMEBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
switch a {
case let x?:
return 0
// CHECK: [[SOMEBB]](%3 : $Int):
// CHECK-NEXT: debug_value %3 : $Int, let, name "x"
// CHECK: integer_literal $Builtin.Int2048, 0
case nil:
return 42
// CHECK: [[NILBB]]:
// CHECK: integer_literal $Builtin.Int2048, 42
}
}
| apache-2.0 | 6b59d688b870c9788a28525788b7cf9f | 29.49402 | 159 | 0.547259 | 2.787102 | false | true | false | false |
hirohisa/RxSwift | RxExample/RxExample/Examples/TableView/RandomUserAPI.swift | 3 | 2081 | //
// RandomUserAPI.swift
// RxExample
//
// Created by carlos on 28/5/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
class RandomUserAPI {
static let sharedAPI = RandomUserAPI()
private init() {}
func getExampleUserResultSet() -> Observable<[User]> {
let url = NSURL(string: "http://api.randomuser.me/?results=20")!
return NSURLSession.sharedSession().rx_JSON(url)
>- observeSingleOn(Dependencies.sharedDependencies.backgroundWorkScheduler)
>- mapOrDie { json in
return castOrFail(json).flatMap { (json: [String: AnyObject]) in
return self.parseJSON(json)
}
}
>- observeSingleOn(Dependencies.sharedDependencies.mainScheduler)
}
private func parseJSON(json: [String: AnyObject]) -> RxResult<[User]> {
let results = json["results"] as? [[String: AnyObject]]
let users = results?.map { $0["user"] as? [String: AnyObject] }
let error = NSError(domain: "UserAPI", code: 0, userInfo: nil)
if let users = users {
let searchResults: [RxResult<User>] = users.map { user in
let name = user?["name"] as? [String: String]
let pictures = user?["picture"] as? [String: String]
if let firstName = name?["first"], let lastName = name?["last"], let imageURL = pictures?["medium"] {
let returnUser = User(firstName: firstName.uppercaseFirstCharacter(),
lastName: lastName.uppercaseFirstCharacter(),
imageURL: imageURL)
return success(returnUser)
}
else {
return failure(error)
}
}
let values = (searchResults.filter { $0.isSuccess }).map { $0.get() }
return success(values)
}
return failure(error)
}
} | mit | d86efcfe1845cff267bbe73778a13f3f | 33.7 | 117 | 0.547333 | 4.794931 | false | false | false | false |
christopherhelf/fastica-swift | Matrix.swift | 1 | 9312 | // Matrix.swift
// A lot of things borrowed from https://github.com/mattt/Surge/blob/master/Source/
// see Mattt Thompson (http://mattt.me)
import Accelerate
public struct Matrix<T where T: FloatingPointType, T: FloatLiteralConvertible> {
typealias Element = T
let rows: Int
let columns: Int
var grid: [Element]
public init(rows: Int, columns: Int, repeatedValue: Element) {
self.rows = rows
self.columns = columns
self.grid = [Element](count: rows * columns, repeatedValue: repeatedValue)
}
public init(_ contents: [[Element]]) {
let m: Int = contents.count
let n: Int = contents[0].count
let repeatedValue: Element = 0.0
self.init(rows: m, columns: n, repeatedValue: repeatedValue)
for (i, row) in enumerate(contents) {
grid.replaceRange(i*n..<i*n+min(m, row.count), with: row)
}
}
// Initialize directly with a grid
public init(grid: [Element], rows: Int, columns: Int) {
self.grid = grid
self.rows = rows
self.columns = columns
}
// Initialize a zero matrix with the provided vector as diagonale
public init(diagonalMatrixwithVector: [Element]) {
self.init(rows: diagonalMatrixwithVector.count, columns: diagonalMatrixwithVector.count, repeatedValue: 0.0)
for i in 0...diagonalMatrixwithVector.count-1 {
self[i,i] = diagonalMatrixwithVector[i];
}
}
// Access functions
public subscript(row: Int, column: Int) -> Element {
get {
assert(indexIsValidForRow(row, column: column))
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column))
grid[(row * columns) + column] = newValue
}
}
private func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
}
// MARK: - Printable
extension Matrix: Printable {
public var description: String {
var description = ""
for i in 0..<rows {
let contents = join("\t", map(0..<columns){"\(self[i, $0])"})
switch (i, rows) {
case (0, 1):
description += "\(contents)\t"
case (0, _):
description += "\(contents)\t"
case (rows - 1, _):
description += "\(contents)\t"
default:
description += "\(contents)\t"
}
description += "\n"
}
return description
}
}
// MARK: - SequenceType
extension Matrix: SequenceType {
public func generate() -> GeneratorOf<ArraySlice<Element>> {
let endIndex = rows * columns
var nextRowStartIndex = 0
return GeneratorOf<ArraySlice<Element>> {
if nextRowStartIndex == endIndex {
return nil
}
let currentRowStartIndex = nextRowStartIndex
nextRowStartIndex += self.columns
return self.grid[currentRowStartIndex..<nextRowStartIndex]
}
}
}
// MARK: -
public func add(x: Matrix<Double>, y: Matrix<Double>) -> Matrix<Double> {
precondition(x.rows == y.rows && x.columns == y.columns, "Matrix dimensions not compatible with addition")
var results = y
cblas_daxpy(Int32(x.grid.count), 1.0, x.grid, 1, &(results.grid), 1)
return results
}
public func mul(alpha: Double, x: Matrix<Double>) -> Matrix<Double> {
var results = x
cblas_dscal(Int32(x.grid.count), alpha, &(results.grid), 1)
return results
}
public func mul(x: Matrix<Double>, y: Matrix<Double>) -> Matrix<Double> {
precondition(x.columns == y.rows, "Matrix dimensions not compatible with multiplication")
var results = Matrix<Double>(rows: x.rows, columns: y.columns, repeatedValue: 0.0)
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(x.rows), Int32(y.columns), Int32(x.columns), 1.0, x.grid, Int32(x.columns), y.grid, Int32(y.columns), 0.0, &(results.grid), Int32(results.columns))
return results
}
public func inv(x : Matrix<Double>) -> Matrix<Double> {
precondition(x.rows == x.columns, "Matrix must be square")
var results = x
var ipiv = [__CLPK_integer](count: x.rows * x.rows, repeatedValue: 0)
var lwork = __CLPK_integer(x.columns * x.columns)
var work = [CDouble](count: Int(lwork), repeatedValue: 0.0)
var error: __CLPK_integer = 0
var nc = __CLPK_integer(x.columns)
dgetrf_(&nc, &nc, &(results.grid), &nc, &ipiv, &error)
dgetri_(&nc, &(results.grid), &nc, &ipiv, &work, &lwork, &error)
assert(error == 0, "Matrix not invertible")
return results
}
public func transpose(x: Matrix<Float>) -> Matrix<Float> {
var results = Matrix<Float>(rows: x.columns, columns: x.rows, repeatedValue: 0.0)
vDSP_mtrans(x.grid, 1, &(results.grid), 1, vDSP_Length(results.rows), vDSP_Length(results.columns))
return results
}
public func transpose(x: Matrix<Double>) -> Matrix<Double> {
var results = Matrix<Double>(rows: x.columns, columns: x.rows, repeatedValue: 0.0)
vDSP_mtransD(x.grid, 1, &(results.grid), 1, vDSP_Length(results.rows), vDSP_Length(results.columns))
return results
}
// MARK: - Operators
public func + (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> {
return add(lhs, rhs)
}
public func * (lhs: Double, rhs: Matrix<Double>) -> Matrix<Double> {
return mul(lhs, rhs)
}
public func * (lhs: Double, rhs: [Double]) -> [Double] {
var res = rhs;
for i in 0...rhs.count-1 {
res[i] = res[i] * lhs;
}
return res;
}
public func * (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> {
return mul(lhs, rhs)
}
postfix operator ′ {}
public postfix func ′ (value: Matrix<Double>) -> Matrix<Double> {
return transpose(value)
}
public func mean(x: [Double]) -> Double {
var result: Double = 0.0
vDSP_meanvD(x, 1, &result, vDSP_Length(x.count))
return result
}
public func add(x: [Double], y: [Double]) -> [Double] {
var results = [Double](y)
cblas_daxpy(Int32(x.count), 1.0, x, 1, &results, 1)
return results
}
func + (lhs: [Double], rhs: Double) -> [Double] {
return add(lhs, [Double](count: lhs.count, repeatedValue: rhs))
}
/**
* Centers mat M. (Subtracts the mean from every column)
*/
public func centerColumns(x: Matrix<Double>) -> (x: Matrix<Double>, meanValues: [Double]) {
// Get rows & cols
var rows = x.rows;
var columns = x.columns;
// Create output variables
var meanValues = [Double](count: columns, repeatedValue: 0.0)
var outMatrix = [Double](count: columns*rows, repeatedValue: 0.0)
// Transpose first so we can access the columns easier
var xT = transpose(x);
// Select values based on range, compute mean, and replace the original values
for i in 0...columns-1 {
let range = rows*i..<rows*(i+1)
var currentColumn : [Double] = Array(xT.grid[range])
var result = -mean(currentColumn)
currentColumn = currentColumn+result
meanValues[i] = -result
xT.grid.replaceRange(range, with: currentColumn)
}
// Transpose back
return (transpose(xT), meanValues)
}
/**
* DeCenters mat M. (Adds the mean to every column according to the vector provided)
*/
public func deCenterColumns(x: Matrix<Double>, meanValues: [Double]) -> Matrix<Double> {
assert(x.columns == meanValues.count)
var result = x
for i in 0...x.rows-1 {
for j in 0...x.columns-1 {
result[i,j] = meanValues[j]
}
}
return x
}
/**
* Computes the mean of every row.
*/
public func meanOfRows(x: Matrix<Double>) -> [Double]
{
// Get rows & cols
var rows = x.rows;
var columns = x.columns;
var sum = 0.0
var meanValues = [Double](count: rows, repeatedValue: 0.0)
for i in 0...rows-1 {
sum = 0.0
for j in 0...columns-1 {
sum += x[i,j]
}
meanValues[i] = sum/Double(columns)
}
return meanValues
}
/**
* Returns the maximal element on the diagonal
* of the matrix M.
*/
public func maxDiag(x: Matrix<Double>) -> Double
{
var max = x[0,0];
for i in 1...x.rows-1 {
if (x[i,i] > max) {
max = x[i,i];
}
}
return max;
}
/**
* Applyies function fx() with parameter par on
* every matrix element.
*/
public func applyFunc(x: Matrix<Double>, par: Double, function: (Double, Double) -> Double) -> Matrix<Double> {
var result = x
for i in 0...(result.rows*result.columns)-1 {
result.grid[i] = function(result.grid[i], par)
}
return result
}
/**
* Applyies function fx() with parameter par on
* every vector element.
*/
public func applyFunc(x: [Double], par: Double, function: (Double, Double) -> Double) -> [Double] {
var result = x
for i in 0...x.count-1 {
result[i] = function(result[i], par)
}
return result
} | mit | ab4f117e387dd76f8ae213b7b5a40f3c | 25.75 | 212 | 0.586162 | 3.711324 | false | false | false | false |
Zewo/Epoch | Sources/Media/Media/MediaDecoder/MediaKeyedDecodingContainer.swift | 2 | 8881 | struct MediaKeyedDecodingContainer<K : CodingKey, Map : DecodingMedia> : KeyedDecodingContainerProtocol {
typealias Key = K
let decoder: MediaDecoder<Map>
let map: DecodingMedia
var codingPath: [CodingKey]
init(referencing decoder: MediaDecoder<Map>, wrapping map: DecodingMedia) {
self.decoder = decoder
self.map = map
self.codingPath = decoder.codingPath
}
var allKeys: [Key] {
return map.allKeys(keyedBy: Key.self)
}
func contains(_ key: Key) -> Bool {
return map.contains(key)
}
func decodeNil(forKey key: K) throws -> Bool {
return decoder.with(pushedKey: key) {
map.decodeNil()
}
}
func decode(_ type: Bool.Type, forKey key: K) throws -> Bool {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: Int.Type, forKey key: K) throws -> Int {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: Int8.Type, forKey key: K) throws -> Int8 {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: Int16.Type, forKey key: K) throws -> Int16 {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: Int32.Type, forKey key: K) throws -> Int32 {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: Int64.Type, forKey key: K) throws -> Int64 {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: UInt.Type, forKey key: K) throws -> UInt {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: UInt8.Type, forKey key: K) throws -> UInt8 {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: UInt16.Type, forKey key: K) throws -> UInt16 {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: UInt32.Type, forKey key: K) throws -> UInt32 {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: UInt64.Type, forKey key: K) throws -> UInt64 {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: Float.Type, forKey key: K) throws -> Float {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: Double.Type, forKey key: K) throws -> Double {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode(_ type: String.Type, forKey key: K) throws -> String {
return try decoder.with(pushedKey: key) {
try map.decode(type, forKey: key)
}
}
func decode<T : Decodable >(_ type: T.Type, forKey key: K) throws -> T {
return try decoder.with(pushedKey: key) {
let value = try map.decode(Map.self, forKey: key)
decoder.stack.push(value)
let result: T = try T(from: decoder)
decoder.stack.pop()
return result
}
}
func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? {
return try decoder.with(pushedKey: key) {
try map.decodeIfPresent(type, forKey: key)
}
}
func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? {
return try decoder.with(pushedKey: key) {
guard let value = try map.decodeIfPresent(Map.self, forKey: key) else {
return nil
}
decoder.stack.push(value)
let result: T = try T(from: decoder)
decoder.stack.pop()
return result
}
}
func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey> {
return try decoder.with(pushedKey: key) {
let container = MediaKeyedDecodingContainer<NestedKey, Map>(
referencing: decoder,
wrapping: try map.keyedContainer(forKey: key)
)
return KeyedDecodingContainer(container)
}
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
return try decoder.with(pushedKey: key) {
return MediaUnkeyedDecodingContainer(
referencing: decoder,
wrapping: try map.unkeyedContainer(forKey: key)
)
}
}
func superDecoder() throws -> Decoder {
return try _superDecoder(forKey: MapSuperKey.super)
}
func superDecoder(forKey key: Key) throws -> Decoder {
return try _superDecoder(forKey: key)
}
func _superDecoder(forKey key: CodingKey) throws -> Decoder {
return try decoder.with(pushedKey: key) {
guard let value = try map.decodeIfPresent(Map.self, forKey: key) else {
var path = codingPath
path.append(key)
let context = DecodingError.Context(
codingPath: path,
debugDescription: "Key not found when expecting non-optional type \(Map.self) for coding key \"\(key)\""
)
throw DecodingError.keyNotFound(key, context)
}
return MediaDecoder<Map>(
referencing: value,
at: decoder.codingPath,
userInfo: decoder.userInfo
)
}
}
}
| mit | 4f7260d40438548569b84959c2af9cc4 | 31.531136 | 124 | 0.560748 | 4.370571 | false | false | false | false |
eoger/firefox-ios | Client/Frontend/Home/HomePanelViewController.swift | 2 | 15221 | /* 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 SnapKit
import UIKit
import Storage
private struct HomePanelViewControllerUX {
// Height of the top panel switcher button toolbar.
static let ButtonContainerHeight: CGFloat = 40
static let ButtonHighlightLineHeight: CGFloat = 2
static let ButtonSelectionAnimationDuration = 0.2
}
protocol HomePanelViewControllerDelegate: AnyObject {
func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType)
func homePanelViewController(_ HomePanelViewController: HomePanelViewController, didSelectPanel panel: Int)
func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController)
func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController)
func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool)
}
protocol HomePanel: AnyObject, Themeable {
var homePanelDelegate: HomePanelDelegate? { get set }
}
struct HomePanelUX {
static let EmptyTabContentOffset = -180
}
protocol HomePanelDelegate: AnyObject {
func homePanelDidRequestToSignIn(_ homePanel: HomePanel)
func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel)
func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool)
func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType)
func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType)
}
struct HomePanelState {
var selectedIndex: Int = 0
}
enum HomePanelType: Int {
case topSites = 0
case bookmarks = 1
case history = 2
case readingList = 3
case downloads = 4
var localhostURL: URL {
return URL(string: "#panel=\(self.rawValue)", relativeTo: UIConstants.AboutHomePage as URL)!
}
}
class HomePanelViewController: UIViewController, UITextFieldDelegate, HomePanelDelegate {
var profile: Profile!
var notificationToken: NSObjectProtocol!
var panels: [HomePanelDescriptor]!
var url: URL?
weak var delegate: HomePanelViewControllerDelegate?
fileprivate var buttonContainerView = UIStackView()
fileprivate var buttonContainerBottomBorderView: UIView!
fileprivate var controllerContainerView: UIView!
fileprivate var buttons: [UIButton] = []
fileprivate var highlightLine = UIView() //The line underneath a panel button that shows which one is selected
fileprivate var buttonTintColor: UIColor?
fileprivate var buttonSelectedTintColor: UIColor?
var homePanelState: HomePanelState {
return HomePanelState(selectedIndex: selectedPanel?.rawValue ?? 0)
}
override func viewDidLoad() {
view.backgroundColor = UIColor.theme.browser.background
buttonContainerView.axis = .horizontal
buttonContainerView.alignment = .fill
buttonContainerView.distribution = .fillEqually
buttonContainerView.spacing = 14
buttonContainerView.clipsToBounds = true
buttonContainerView.accessibilityNavigationStyle = .combined
buttonContainerView.accessibilityLabel = NSLocalizedString("Panel Chooser", comment: "Accessibility label for the Home panel's top toolbar containing list of the home panels (top sites, bookmarsk, history, remote tabs, reading list).")
view.addSubview(buttonContainerView)
buttonContainerView.addSubview(highlightLine)
self.buttonContainerBottomBorderView = UIView()
self.view.addSubview(buttonContainerBottomBorderView)
buttonContainerBottomBorderView.backgroundColor = UIColor.theme.homePanel.buttonContainerBorder
controllerContainerView = UIView()
view.addSubview(controllerContainerView)
buttonContainerView.snp.makeConstraints { make in
make.top.equalTo(self.view)
make.leading.trailing.equalTo(self.view).inset(14)
make.height.equalTo(HomePanelViewControllerUX.ButtonContainerHeight)
}
buttonContainerBottomBorderView.snp.makeConstraints { make in
make.top.equalTo(self.buttonContainerView.snp.bottom).offset(-1)
make.bottom.equalTo(self.buttonContainerView)
make.leading.trailing.equalToSuperview()
}
controllerContainerView.snp.makeConstraints { make in
make.top.equalTo(self.buttonContainerView.snp.bottom)
make.left.right.bottom.equalTo(self.view)
}
self.panels = HomePanels().enabledPanels
updateButtons()
// Gesture recognizer to dismiss the keyboard in the URLBarView when the buttonContainerView is tapped
let dismissKeyboardGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
dismissKeyboardGestureRecognizer.cancelsTouchesInView = false
buttonContainerView.addGestureRecognizer(dismissKeyboardGestureRecognizer)
}
@objc func dismissKeyboard(_ gestureRecognizer: UITapGestureRecognizer) {
view.window?.rootViewController?.view.endEditing(true)
}
var selectedPanel: HomePanelType? = nil {
didSet {
if oldValue == selectedPanel {
// Prevent flicker, allocations, and disk access: avoid duplicate view controllers.
return
}
if let index = oldValue?.rawValue {
if index < buttons.count {
let currentButton = buttons[index]
currentButton.isSelected = false
currentButton.isUserInteractionEnabled = true
}
}
hideCurrentPanel()
if let index = selectedPanel?.rawValue {
if index < buttons.count {
let newButton = buttons[index]
newButton.isSelected = true
newButton.isUserInteractionEnabled = false
}
if index < panels.count {
let panel = self.panels[index].makeViewController(profile)
let accessibilityLabel = self.panels[index].accessibilityLabel
if let panelController = panel as? UINavigationController,
let rootPanel = panelController.viewControllers.first {
setupHomePanel(rootPanel, accessibilityLabel: accessibilityLabel)
self.showPanel(panelController)
} else {
setupHomePanel(panel, accessibilityLabel: accessibilityLabel)
self.showPanel(panel)
}
}
}
self.updateButtonTints()
}
}
func setupHomePanel(_ panel: UIViewController, accessibilityLabel: String) {
(panel as? HomePanel)?.homePanelDelegate = self
panel.view.accessibilityNavigationStyle = .combined
panel.view.accessibilityLabel = accessibilityLabel
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
fileprivate func hideCurrentPanel() {
if let panel = childViewControllers.first {
panel.willMove(toParentViewController: nil)
panel.beginAppearanceTransition(false, animated: false)
panel.view.removeFromSuperview()
panel.endAppearanceTransition()
panel.removeFromParentViewController()
}
}
fileprivate func showPanel(_ panel: UIViewController) {
addChildViewController(panel)
panel.beginAppearanceTransition(true, animated: false)
controllerContainerView.addSubview(panel.view)
panel.endAppearanceTransition()
panel.view.snp.makeConstraints { make in
make.top.equalTo(self.buttonContainerView.snp.bottom)
make.left.right.bottom.equalTo(self.view)
}
panel.didMove(toParentViewController: self)
}
@objc func tappedButton(_ sender: UIButton!) {
for (index, button) in buttons.enumerated() where button == sender {
selectedPanel = HomePanelType(rawValue: index)
delegate?.homePanelViewController(self, didSelectPanel: index)
if selectedPanel == .bookmarks {
UnifiedTelemetry.recordEvent(category: .action, method: .view, object: .bookmarksPanel, value: .homePanelTabButton)
} else if selectedPanel == .downloads {
UnifiedTelemetry.recordEvent(category: .action, method: .view, object: .downloadsPanel, value: .homePanelTabButton)
}
break
}
}
fileprivate func updateButtons() {
for panel in panels {
let button = UIButton()
button.addTarget(self, action: #selector(tappedButton), for: .touchUpInside)
if let image = UIImage.templateImageNamed("panelIcon\(panel.imageName)") {
button.setImage(image, for: .normal)
}
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 4, right: 0)
button.accessibilityLabel = panel.accessibilityLabel
button.accessibilityIdentifier = panel.accessibilityIdentifier
buttons.append(button)
self.buttonContainerView.addArrangedSubview(button)
}
}
func updateButtonTints() {
var selectedbutton: UIView?
for (index, button) in self.buttons.enumerated() {
if index == self.selectedPanel?.rawValue {
button.tintColor = self.buttonSelectedTintColor
selectedbutton = button
} else {
button.tintColor = self.buttonTintColor
}
}
guard let button = selectedbutton else {
return
}
// Calling this before makes sure that only the highlightline animates and not the homepanels
self.view.setNeedsUpdateConstraints()
self.view.layoutIfNeeded()
UIView.animate(withDuration: HomePanelViewControllerUX.ButtonSelectionAnimationDuration, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: {
self.highlightLine.snp.remakeConstraints { make in
make.leading.equalTo(button.snp.leading)
make.trailing.equalTo(button.snp.trailing)
make.bottom.equalToSuperview()
make.height.equalTo(HomePanelViewControllerUX.ButtonHighlightLineHeight)
}
self.view.setNeedsUpdateConstraints()
self.view.layoutIfNeeded()
}, completion: nil)
}
func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType) {
// If we can't get a real URL out of what should be a URL, we let the user's
// default search engine give it a shot.
// Typically we'll be in this state if the user has tapped a bookmarked search template
// (e.g., "http://foo.com/bar/?query=%s"), and this will get them the same behavior as if
// they'd copied and pasted into the URL bar.
// See BrowserViewController.urlBar:didSubmitText:.
guard let url = URIFixup.getURL(url) ?? profile.searchEngines.defaultEngine.searchURLForQuery(url) else {
Logger.browserLogger.warning("Invalid URL, and couldn't generate a search URL for it.")
return
}
return self.homePanel(homePanel, didSelectURL: url, visitType: visitType)
}
func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType) {
delegate?.homePanelViewController(self, didSelectURL: url, visitType: visitType)
dismiss(animated: true, completion: nil)
}
func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel) {
delegate?.homePanelViewControllerDidRequestToCreateAccount(self)
}
func homePanelDidRequestToSignIn(_ homePanel: HomePanel) {
delegate?.homePanelViewControllerDidRequestToSignIn(self)
}
func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) {
delegate?.homePanelViewControllerDidRequestToOpenInNewTab(url, isPrivate: isPrivate)
}
}
// MARK: UIAppearance
extension HomePanelViewController: Themeable {
func applyTheme() {
func apply(_ vc: UIViewController) -> Bool {
guard let vc = vc as? Themeable else { return false }
vc.applyTheme()
return true
}
childViewControllers.forEach {
if !apply($0) {
// BookmarksPanel is nested in a UINavigationController, go one layer deeper
$0.childViewControllers.forEach { _ = apply($0) }
}
}
buttonContainerView.backgroundColor = UIColor.theme.homePanel.toolbarBackground
view.backgroundColor = UIColor.theme.homePanel.toolbarBackground
buttonTintColor = UIColor.theme.homePanel.toolbarTint
buttonSelectedTintColor = UIColor.theme.homePanel.toolbarHighlight
highlightLine.backgroundColor = UIColor.theme.homePanel.toolbarHighlight
updateButtonTints()
}
}
protocol HomePanelContextMenu {
func getSiteDetails(for indexPath: IndexPath) -> Site?
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]?
func presentContextMenu(for indexPath: IndexPath)
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?)
}
extension HomePanelContextMenu {
func presentContextMenu(for indexPath: IndexPath) {
guard let site = getSiteDetails(for: indexPath) else { return }
presentContextMenu(for: site, with: indexPath, completionHandler: {
return self.contextMenu(for: site, with: indexPath)
})
}
func contextMenu(for site: Site, with indexPath: IndexPath) -> PhotonActionSheet? {
guard let actions = self.getContextMenuActions(for: site, with: indexPath) else { return nil }
let contextMenu = PhotonActionSheet(site: site, actions: actions)
contextMenu.modalPresentationStyle = .overFullScreen
contextMenu.modalTransitionStyle = .crossDissolve
return contextMenu
}
func getDefaultContextMenuActions(for site: Site, homePanelDelegate: HomePanelDelegate?) -> [PhotonActionSheetItem]? {
guard let siteURL = URL(string: site.url) else { return nil }
let openInNewTabAction = PhotonActionSheetItem(title: Strings.OpenInNewTabContextMenuTitle, iconString: "quick_action_new_tab") { action in
homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false)
}
let openInNewPrivateTabAction = PhotonActionSheetItem(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "quick_action_new_private_tab") { action in
homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true)
}
return [openInNewTabAction, openInNewPrivateTabAction]
}
}
| mpl-2.0 | 395814c8223e21568b15289d649e6ebe | 41.876056 | 243 | 0.684449 | 5.739442 | false | false | false | false |
e78l/swift-corelibs-foundation | Foundation/NSCharacterSet.swift | 1 | 22795 | // 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
#if _runtime(_ObjC) // if objc_enum works, restore the old names:
let kCFCharacterSetControl = CFCharacterSetPredefinedSet.control
let kCFCharacterSetWhitespace = CFCharacterSetPredefinedSet.whitespace
let kCFCharacterSetWhitespaceAndNewline = CFCharacterSetPredefinedSet.whitespaceAndNewline
let kCFCharacterSetDecimalDigit = CFCharacterSetPredefinedSet.decimalDigit
let kCFCharacterSetLetter = CFCharacterSetPredefinedSet.letter
let kCFCharacterSetLowercaseLetter = CFCharacterSetPredefinedSet.lowercaseLetter
let kCFCharacterSetUppercaseLetter = CFCharacterSetPredefinedSet.uppercaseLetter
let kCFCharacterSetNonBase = CFCharacterSetPredefinedSet.nonBase
let kCFCharacterSetDecomposable = CFCharacterSetPredefinedSet.decomposable
let kCFCharacterSetAlphaNumeric = CFCharacterSetPredefinedSet.alphaNumeric
let kCFCharacterSetPunctuation = CFCharacterSetPredefinedSet.punctuation
let kCFCharacterSetCapitalizedLetter = CFCharacterSetPredefinedSet.capitalizedLetter
let kCFCharacterSetSymbol = CFCharacterSetPredefinedSet.symbol
let kCFCharacterSetNewline = CFCharacterSetPredefinedSet.newline
let kCFCharacterSetIllegal = CFCharacterSetPredefinedSet.illegal
let kCFCharacterSetKeyedCodingTypeBitmap = CFCharacterSetKeyedCodingType.bitmap
let kCFCharacterSetKeyedCodingTypeBuiltin = CFCharacterSetKeyedCodingType.builtin
let kCFCharacterSetKeyedCodingTypeRange = CFCharacterSetKeyedCodingType.range
let kCFCharacterSetKeyedCodingTypeString = CFCharacterSetKeyedCodingType.string
let kCFCharacterSetKeyedCodingTypeBuiltinAndBitmap = CFCharacterSetKeyedCodingType.builtinAndBitmap
#endif
#if _runtime(_ObjC)
fileprivate let lastKnownPredefinedCharacterSetConstant = kCFCharacterSetNewline.rawValue
fileprivate extension Int {
init(_ predefinedSet: CFCharacterSetPredefinedSet) {
self = predefinedSet.rawValue
}
}
#else
fileprivate let lastKnownPredefinedCharacterSetConstant = kCFCharacterSetNewline
#endif
fileprivate func knownPredefinedCharacterSet(rawValue: Int) -> CFCharacterSetPredefinedSet? {
if rawValue > 0 && rawValue <= lastKnownPredefinedCharacterSetConstant {
#if _runtime(_ObjC)
return CFCharacterSetPredefinedSet(rawValue: rawValue)
#else
return CFCharacterSetPredefinedSet(rawValue)
#endif
} else {
return nil
}
}
fileprivate extension String {
static let characterSetBitmapRepresentationKey = "NSBitmap"
static let characterSetAltBitmapRepresentationKey = "NSBitmapObject"
static let characterSetStringKey = "NSString"
static let characterSetAltStringKey = "NSStringObject"
static let characterSetRangeKey = "NSRange"
static let characterSetBuiltinIDKey = "NSBuiltinID"
static let characterSetNewBuiltinIDKey = "NSBuiltinID2"
static let characterSetIsInvertedKey = "NSIsInverted"
static let characterSetNewIsInvertedKey = "NSIsInverted2"
}
open class NSCharacterSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
typealias CFType = CFCharacterSet
private var _base = _CFInfo(typeID: CFCharacterSetGetTypeID())
private var _hashValue = CFHashCode(0)
private var _buffer: UnsafeMutableRawPointer? = nil
private var _length = CFIndex(0)
private var _annex: UnsafeMutableRawPointer? = nil
internal var _cfObject: CFType {
return unsafeBitCast(self, to: CFType.self)
}
internal var _cfMutableObject: CFMutableCharacterSet {
return unsafeBitCast(self, to: CFMutableCharacterSet.self)
}
open override var hash: Int {
return Int(bitPattern: _CFNonObjCHash(_cfObject))
}
open override func isEqual(_ value: Any?) -> Bool {
guard let runtimeClass = _CFRuntimeGetClassWithTypeID(CFCharacterSetGetTypeID()) else {
fatalError("Could not obtain CFRuntimeClass of CFCharacterSet")
}
guard let equalFunction = runtimeClass.pointee.equal else {
fatalError("Could not obtain equal function from CFRuntimeClass of CFCharacterSet")
}
switch value {
case let other as CharacterSet: return equalFunction(self._cfObject, other._cfObject) == true
case let other as NSCharacterSet: return equalFunction(self._cfObject, other._cfObject) == true
default: return false
}
}
open override var description: String {
return CFCopyDescription(_cfObject)._swiftObject
}
public override init() {
super.init()
_CFCharacterSetInitWithCharactersInRange(_cfMutableObject, CFRangeMake(0, 0));
}
deinit {
_CFDeinit(self)
}
open class var controlCharacters: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetControl)._swiftObject
}
open class var whitespaces: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetWhitespace)._swiftObject
}
open class var whitespacesAndNewlines: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetWhitespaceAndNewline)._swiftObject
}
open class var decimalDigits: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetDecimalDigit)._swiftObject
}
public class var letters: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetLetter)._swiftObject
}
open class var lowercaseLetters: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetLowercaseLetter)._swiftObject
}
open class var uppercaseLetters: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetUppercaseLetter)._swiftObject
}
open class var nonBaseCharacters: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetNonBase)._swiftObject
}
open class var alphanumerics: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetAlphaNumeric)._swiftObject
}
open class var decomposables: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetDecomposable)._swiftObject
}
open class var illegalCharacters: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetIllegal)._swiftObject
}
open class var punctuationCharacters: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetPunctuation)._swiftObject
}
open class var capitalizedLetters: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetCapitalizedLetter)._swiftObject
}
open class var symbols: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetSymbol)._swiftObject
}
open class var newlines: CharacterSet {
return CFCharacterSetGetPredefined(kCFCharacterSetNewline)._swiftObject
}
public init(range aRange: NSRange) {
super.init()
_CFCharacterSetInitWithCharactersInRange(_cfMutableObject, CFRangeMake(aRange.location, aRange.length))
}
public init(charactersIn aString: String) {
super.init()
_CFCharacterSetInitWithCharactersInString(_cfMutableObject, aString._cfObject)
}
public init(bitmapRepresentation data: Data) {
super.init()
_CFCharacterSetInitWithBitmapRepresentation(_cfMutableObject, data._cfObject)
}
public convenience init?(contentsOfFile fName: String) {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: fName))
self.init(bitmapRepresentation: data)
} catch {
return nil
}
}
open class var supportsSecureCoding: Bool { return true }
public required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
fatalError("Decoding requires a NSCoder that allows keyed coding.")
}
func fail(code: CocoaError.Code = .coderReadCorrupt, _ message: String) {
aDecoder.failWithError(NSError(domain: NSCocoaErrorDomain, code: code.rawValue, userInfo: [ NSLocalizedDescriptionKey: message ]))
}
let finalSet: CFCharacterSet
var builtinType = aDecoder.decodeInteger(forKey: .characterSetBuiltinIDKey)
if builtinType == 0 {
builtinType = aDecoder.decodeInteger(forKey: .characterSetNewBuiltinIDKey)
}
let isInverted = aDecoder.decodeBool(forKey: .characterSetIsInvertedKey)
let keyedUnarchiver = aDecoder as? NSKeyedUnarchiver
let containsCharacterSetStringKeyName = aDecoder.containsValue(forKey: .characterSetStringKey)
let containsCharacterSetStringAltKeyName = aDecoder.containsValue(forKey: .characterSetAltStringKey)
if let predefinedSet = knownPredefinedCharacterSet(rawValue: builtinType) {
guard let theSet = CFCharacterSetGetPredefined(predefinedSet) else {
fail("CFCharacterSetGetPredefined -- Predefined Character Set not found")
return nil
}
finalSet = theSet
} else if aDecoder.containsValue(forKey: .characterSetRangeKey) {
let range = UInt64(bitPattern: aDecoder.decodeInt64(forKey: .characterSetRangeKey))
guard let theSet = CFCharacterSetCreateWithCharactersInRange(kCFAllocatorSystemDefault, CFRangeMake(CFIndex(range >> 32), CFIndex(range & 0xFFFFFFFF))) else {
fail("CFCharacterSetCreateWithCharactersInRange -- Character Set creation with characters in range failed")
return nil
}
finalSet = theSet
} else if containsCharacterSetStringKeyName || containsCharacterSetStringAltKeyName {
let maybeResult: NSString?
if let keyedUnarchiver = keyedUnarchiver, containsCharacterSetStringKeyName {
maybeResult = keyedUnarchiver._decodePropertyListForKey(.characterSetStringKey) as? NSString
} else {
maybeResult = aDecoder.decodeObject(of: NSString.self, forKey: .characterSetAltStringKey)
}
guard let result = maybeResult else {
fail(code: .coderValueNotFound, "Decoder value not found")
return nil
}
guard let theSet = CFCharacterSetCreateWithCharactersInString(kCFAllocatorSystemDefault, result._cfObject) else {
fail("CFCharacterSetCreateWithCharactersInString -- Character Set creation with characters in string failed")
return nil
}
finalSet = theSet
} else {
let maybeResult: NSData?
if let keyedUnarchiver = keyedUnarchiver, keyedUnarchiver.containsValue(forKey: .characterSetBitmapRepresentationKey) {
maybeResult = keyedUnarchiver._decodePropertyListForKey(.characterSetBitmapRepresentationKey) as? NSData
} else {
maybeResult = aDecoder.decodeObject(of: NSData.self, forKey: .characterSetAltBitmapRepresentationKey)
}
guard let result = maybeResult else {
fail(code: .coderValueNotFound, "Decoder value not found")
return nil
}
guard let theSet = CFCharacterSetCreateWithBitmapRepresentation(kCFAllocatorSystemDefault, result._cfObject) else {
fail("CFCharacterSetCreateWithBitmapRepresentation -- Character Set creation with bitmap representation failed")
return nil
}
finalSet = theSet
}
super.init()
_CFCharacterSetInitCopyingSet(kCFAllocatorSystemDefault, _cfMutableObject, finalSet, type(of: self) is NSMutableCharacterSet.Type, false)
if isInverted {
_CFCharacterSetSetIsInverted(_cfMutableObject, isInverted)
}
}
public func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
fatalError("Encoding requires a NSCoder that allows keyed coding.")
}
var isInverted = _CFCharacterSetIsInverted(_cfObject)
let keyedArchiver = aCoder as? NSKeyedArchiver
switch _CFCharacterSetGetKeyedCodingType(_cfObject) {
case kCFCharacterSetKeyedCodingTypeBuiltin:
aCoder.encode(Int(_CFCharacterSetGetKeyedCodingBuiltinType(_cfObject)), forKey: .characterSetBuiltinIDKey)
case kCFCharacterSetKeyedCodingTypeRange:
let range = _CFCharacterSetGetKeyedCodingRange(_cfObject)
var value = UInt64(range.location)
value <<= 32
value |= UInt64(range.length)
aCoder.encode(Int64(bitPattern: value), forKey: .characterSetRangeKey)
case kCFCharacterSetKeyedCodingTypeString:
let string = _CFCharacterSetCreateKeyedCodingString(_cfObject).takeRetainedValue()
if let keyedArchiver = keyedArchiver {
keyedArchiver._encodePropertyList(string._nsObject, forKey: .characterSetStringKey)
} else {
aCoder.encode(string._nsObject, forKey: .characterSetAltStringKey)
}
case kCFCharacterSetKeyedCodingTypeBuiltinAndBitmap:
aCoder.encode(Int(_CFCharacterSetGetKeyedCodingBuiltinType(_cfObject)), forKey: .characterSetNewBuiltinIDKey)
if isInverted { aCoder.encode(true, forKey: .characterSetNewIsInvertedKey )}
fallthrough
default:
if let keyedArchiver = keyedArchiver {
keyedArchiver._encodePropertyList(bitmapRepresentation._nsObject, forKey: .characterSetBitmapRepresentationKey)
} else {
aCoder.encode(bitmapRepresentation._nsObject, forKey: .characterSetAltBitmapRepresentationKey)
}
isInverted = false
}
if isInverted {
aCoder.encode(true, forKey: .characterSetIsInvertedKey)
}
}
open func characterIsMember(_ aCharacter: unichar) -> Bool {
return longCharacterIsMember(UInt32(aCharacter))
}
open var bitmapRepresentation: Data {
return CFCharacterSetCreateBitmapRepresentation(kCFAllocatorSystemDefault, _cfObject)._swiftObject
}
open var inverted: CharacterSet {
let copy = mutableCopy() as! NSMutableCharacterSet
copy.invert()
return copy._swiftObject
}
open func longCharacterIsMember(_ theLongChar: UInt32) -> Bool {
if type(of: self) == NSCharacterSet.self || type(of: self) == NSMutableCharacterSet.self {
return _CFCharacterSetIsLongCharacterMember(unsafeBitCast(self, to: CFType.self), theLongChar)
} else if type(of: self) == _NSCFCharacterSet.self {
return CFCharacterSetIsLongCharacterMember(_cfObject, theLongChar)
} else {
NSRequiresConcreteImplementation()
}
}
open func isSuperset(of theOtherSet: CharacterSet) -> Bool {
return CFCharacterSetIsSupersetOfSet(_cfObject, theOtherSet._cfObject)
}
open func hasMemberInPlane(_ thePlane: UInt8) -> Bool {
return CFCharacterSetHasMemberInPlane(_cfObject, CFIndex(thePlane))
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) == NSCharacterSet.self || type(of: self) == NSMutableCharacterSet.self {
return _CFCharacterSetCreateCopy(kCFAllocatorSystemDefault, self._cfObject)
} else if type(of: self) == _NSCFCharacterSet.self {
return CFCharacterSetCreateCopy(kCFAllocatorSystemDefault, self._cfObject)
} else {
NSRequiresConcreteImplementation()
}
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) == NSCharacterSet.self || type(of: self) == NSMutableCharacterSet.self {
return _CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, _cfObject)._nsObject
} else if type(of: self) == _NSCFCharacterSet.self {
return CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, _cfObject)._nsObject
} else {
NSRequiresConcreteImplementation()
}
}
}
open class NSMutableCharacterSet : NSCharacterSet {
public convenience required init(coder aDecoder: NSCoder) {
NSUnimplemented()
}
open func addCharacters(in aRange: NSRange) {
CFCharacterSetAddCharactersInRange(_cfMutableObject , CFRangeMake(aRange.location, aRange.length))
}
open func removeCharacters(in aRange: NSRange) {
CFCharacterSetRemoveCharactersInRange(_cfMutableObject , CFRangeMake(aRange.location, aRange.length))
}
open func addCharacters(in aString: String) {
CFCharacterSetAddCharactersInString(_cfMutableObject, aString._cfObject)
}
open func removeCharacters(in aString: String) {
CFCharacterSetRemoveCharactersInString(_cfMutableObject, aString._cfObject)
}
open func formUnion(with otherSet: CharacterSet) {
CFCharacterSetUnion(_cfMutableObject, otherSet._cfObject)
}
open func formIntersection(with otherSet: CharacterSet) {
CFCharacterSetIntersect(_cfMutableObject, otherSet._cfObject)
}
open func invert() {
CFCharacterSetInvert(_cfMutableObject)
}
open class func control() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetControl)), to: NSMutableCharacterSet.self)
}
open class func whitespace() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetWhitespace)), to: NSMutableCharacterSet.self)
}
open class func whitespaceAndNewline() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetWhitespaceAndNewline)), to: NSMutableCharacterSet.self)
}
open class func decimalDigit() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetDecimalDigit)), to: NSMutableCharacterSet.self)
}
public class func letter() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetLetter)), to: NSMutableCharacterSet.self)
}
open class func lowercaseLetter() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetLowercaseLetter)), to: NSMutableCharacterSet.self)
}
open class func uppercaseLetter() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetUppercaseLetter)), to: NSMutableCharacterSet.self)
}
open class func nonBase() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetNonBase)), to: NSMutableCharacterSet.self)
}
open class func alphanumeric() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetAlphaNumeric)), to: NSMutableCharacterSet.self)
}
open class func decomposable() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetDecomposable)), to: NSMutableCharacterSet.self)
}
open class func illegal() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetIllegal)), to: NSMutableCharacterSet.self)
}
open class func punctuation() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetPunctuation)), to: NSMutableCharacterSet.self)
}
open class func capitalizedLetter() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetCapitalizedLetter)), to: NSMutableCharacterSet.self)
}
open class func symbol() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetSymbol)), to: NSMutableCharacterSet.self)
}
open class func newline() -> NSMutableCharacterSet {
return unsafeBitCast(CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, CFCharacterSetGetPredefined(kCFCharacterSetNewline)), to: NSMutableCharacterSet.self)
}
}
extension CharacterSet : _CFBridgeable, _NSBridgeable {
typealias CFType = CFCharacterSet
typealias NSType = NSCharacterSet
internal var _cfObject: CFType {
return _nsObject._cfObject
}
internal var _nsObject: NSType {
return _bridgeToObjectiveC()
}
}
extension CFCharacterSet : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSCharacterSet
typealias SwiftType = CharacterSet
internal var _nsObject: NSType {
return unsafeBitCast(self, to: NSType.self)
}
internal var _swiftObject: SwiftType {
return _nsObject._swiftObject
}
}
extension NSCharacterSet : _SwiftBridgeable {
typealias SwiftType = CharacterSet
internal var _swiftObject: SwiftType {
return CharacterSet(_bridged: self)
}
}
extension NSCharacterSet : _StructTypeBridgeable {
public typealias _StructType = CharacterSet
public func _bridgeToSwift() -> CharacterSet {
return CharacterSet._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | 56b1675046bbb85de964ef2394c50a50 | 41.687266 | 186 | 0.713621 | 6.342515 | false | false | false | false |
towlebooth/watchos-countdown-tutorial | CountdownTutorial WatchKit Extension/ComplicationController.swift | 1 | 8737 | //
// ComplicationController.swift
// CountdownTutorial WatchKit Extension
//
// Created by Chad Towle on 12/23/15.
// Copyright © 2015 Intertech. All rights reserved.
//
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
let userCalendar = NSCalendar.currentCalendar()
let dateFormatter = NSDateFormatter()
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler([.Forward])
}
func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
handler(NSDate())
}
func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
let startDate = getStartDateFromUserDefaults()
let sabbaticalDate = getSabbaticalDate(startDate)
handler(sabbaticalDate)
}
func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
handler(.ShowOnLockScreen)
}
// MARK: - Timeline Population
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
var shortText = ""
if complication.family == .UtilitarianSmall
{
let startDate = getStartDateFromUserDefaults()
let sabbaticalDate = getSabbaticalDate(startDate)
let dateComparisionResult:NSComparisonResult = NSDate().compare(sabbaticalDate)
if dateComparisionResult == NSComparisonResult.OrderedAscending
{
// current date is earlier than the end date
// figure out how many days, months and years remain until sabbatical
let flags: NSCalendarUnit = [.Year, .Month, .Day]
let dateComponents = userCalendar.components(flags, fromDate: NSDate(), toDate: sabbaticalDate, options: [])
let year = dateComponents.year
let month = dateComponents.month
let day = dateComponents.day
// create string to display remaining time
if (year > 0 )
{
shortText = String(format: "%d Y | %d M", year, month)
}
else if (year <= 0 && month > 0)
{
shortText = String(format: "%d M | &d D", month, day)
}
else if (year <= 0 && month <= 0 && day > 0)
{
shortText = String(format: "%d Days", day)
}
}
else if dateComparisionResult == NSComparisonResult.OrderedDescending
{
// Current date is greater than end date.
shortText = "0 Days"
}
// create current timeline entry
let entry = createComplicationEntry(shortText, date: NSDate(), family: complication.family)
handler(entry)
} else {
handler(nil)
}
}
func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries prior to the given date
handler(nil)
}
func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries after to the given date
let startDate = getStartDateFromUserDefaults()
let sabbaticalDate = getSabbaticalDate(startDate)
let componentDay = userCalendar.components(.Day, fromDate: date, toDate: sabbaticalDate, options: [])
let days = min(componentDay.day, 100)
var entries = [CLKComplicationTimelineEntry]()
// create an entry in array for each day remaining
for index in 1...days {
let dateComparisionResult:NSComparisonResult = NSDate().compare(sabbaticalDate)
if dateComparisionResult == NSComparisonResult.OrderedAscending
{
// entryDate is the date of the timeline entry for the complication
let entryDate = userCalendar.dateByAddingUnit([.Day], value: index, toDate: date, options: [])!
let flags: NSCalendarUnit = [.Year, .Month, .Day]
let dateComponents = userCalendar.components(flags, fromDate: entryDate, toDate: sabbaticalDate, options: [])
// number of years, months, days from the timeline entry until sabbatical date
let year = dateComponents.year
let month = dateComponents.month
let day = dateComponents.day
if (year > 0 )
{
let entryText = String(format: "%d Y | %d M", year, month)
let entry = createComplicationEntry(entryText, date: entryDate, family: complication.family)
entries.append(entry)
}
else if (year <= 0 && month > 0)
{
let entryText = String(format: "%d M | &d D", month, day)
let entry = createComplicationEntry(entryText, date: entryDate, family: complication.family)
entries.append(entry)
}
else if (year <= 0 && month <= 0 && day > 0)
{
let entryText = String(format: "%d Days", day)
let entry = createComplicationEntry(entryText, date: entryDate, family: complication.family)
entries.append(entry)
}
}
}
handler(entries)
}
// MARK: - Update Scheduling
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
handler(nil)
}
// MARK: - Placeholder Templates
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
if complication.family == .UtilitarianSmall {
let smallUtil = CLKComplicationTemplateUtilitarianSmallFlat()
smallUtil.textProvider = CLKSimpleTextProvider(text: "7 Y")
handler(smallUtil)
}
}
func createComplicationEntry(shortText: String, date: NSDate, family: CLKComplicationFamily) -> CLKComplicationTimelineEntry {
let smallFlat = CLKComplicationTemplateUtilitarianSmallFlat()
smallFlat.textProvider = CLKSimpleTextProvider(text: shortText)
let newEntry = CLKComplicationTimelineEntry(date: date, complicationTemplate: smallFlat)
return(newEntry)
}
func getSabbaticalDate(startDate: NSDate) -> NSDate {
// set up date formatter
dateFormatter.calendar = userCalendar
dateFormatter.dateFormat = "yyyy-MM-dd"
// create variable to hold 7 years
let sevenYears: NSDateComponents = NSDateComponents()
sevenYears.setValue(7, forComponent: NSCalendarUnit.Year);
// add 7 years to our start date to calculate the date of our sabbatical
var sabbaticalDate = userCalendar.dateByAddingComponents(sevenYears, toDate: startDate, options: NSCalendarOptions(rawValue: 0))
// since we get a sabbatical every 7 years, add 7 years until sabbaticalDate is in the future
while sabbaticalDate!.timeIntervalSinceNow.isSignMinus {
sabbaticalDate = userCalendar.dateByAddingComponents(sevenYears, toDate: sabbaticalDate!, options: NSCalendarOptions(rawValue: 0))
}
return sabbaticalDate!
}
func getStartDateFromUserDefaults() -> NSDate {
let defaults = NSUserDefaults.standardUserDefaults()
dateFormatter.dateFormat = "yyyy-MM-dd"
var startDate = NSDate()
if let dateString = defaults.stringForKey("dateKey")
{
startDate = dateFormatter.dateFromString(dateString)!
}
return startDate
}
}
| mit | f0cdbff3d2055c1102a957e32ada1241 | 43.345178 | 178 | 0.615614 | 5.886792 | false | false | false | false |
chengxianghe/MissGe | MissGe/MissGe/Class/Project/Request/Home/MLLikeRequest.swift | 1 | 1655 | //
// MLLikeRequest.swift
// MissLi
//
// Created by chengxianghe on 16/7/26.
// Copyright © 2016年 cn. All rights reserved.
//
import UIKit
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=post&a=likeit&pid=40298
class MLLikeCommentRequest: MLBaseRequest {
var pid = ""
//c=post&a=likeit&pid=40298
override func requestParameters() -> [String : Any]? {
let dict = ["c":"post","a":"likeit","pid":"\(pid)"]
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
override func requestVerifyResult() -> Bool {
guard let dict = self.responseObject as? NSDictionary else {
return false
}
return (dict["result"] as? String) == "200"
}
}
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=article&a=likeit&aid=7992
class MLLikeArticleRequest: MLBaseRequest {
var aid = ""
//c=post&a=likeit&pid=40298
override func requestParameters() -> [String : Any]? {
let dict = ["c":"article","a":"likeit","aid":"\(aid)"]
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
override func requestVerifyResult() -> Bool {
guard let dict = self.responseObject as? NSDictionary else {
return false
}
return (dict["result"] as? String) == "200"
}
}
| mit | c33d34347b58227326b77d0870e5bf8d | 27.982456 | 160 | 0.62046 | 3.434511 | false | false | false | false |
informmegp2/inform-me | InformME/AddBeaconViewController.swift | 1 | 9302 | //
// BeaconViewController.swift
// InformME
//
// Created by sara on 4/24/1437 AH.
// Copyright © 1437 King Saud University. All rights reserved.
//
import UIKit
class AddBeaconViewController: UIViewController, UITableViewDelegate, UITextFieldDelegate, ESTBeaconManagerDelegate {
var Requested: [String] = [""]
@IBOutlet weak var Label: UITextField!
@IBOutlet weak var Minor: UITextField!
@IBOutlet weak var Major: UITextField!
var cellContent = [String]()
var numRow:Int?
var labels = [String]()
var UID = [String]()
var UserID: Int = NSUserDefaults.standardUserDefaults().integerForKey("id");
//This manager is for ranging
let beaconManager = ESTBeaconManager()
let beaconRegion = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D")!, identifier: "MyBeacon")
// Add beacon
@IBAction func Submit(sender: AnyObject) {
let minor = Minor.text!
let llabel = Label.text!
let major = Major.text!
if (Minor.text == "" || Major.text == "" || llabel == "") {
let alert = UIAlertController(title: "", message: " يرجى إكمال كافة الحقول", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "موافق", style: .Default, handler: { (action) -> Void in
}))
self.presentViewController(alert, animated: true, completion: nil)
}
else {
if UID.contains(String(UserID)) && labels.contains(llabel) {
let alert = UIAlertController(title: "", message: " إسم البيكون مستخدم مسبقا \n الرجاء إختيار إسم أخر ", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "موافق", style: .Default, handler: { (action) -> Void in
}))
self.presentViewController(alert, animated: true, completion: nil)
}
else {
let alertController = UIAlertController(title: "", message: " هل أنت متأكد من رغبتك بحفظ التغييرات؟", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "موافق", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
let b : Beacon = Beacon()
if(Reachability.isConnectedToNetwork()){
b.addBeacon (llabel, major: major,minor:minor){
(flag:Bool) in
//we should perform all segues in the main thread
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("addBeacon", sender:sender)
}}}
else {
self.displayAlert("", message: "الرجاء الاتصال بالانترنت")
}}
let cancelAction = UIAlertAction(title: "إلغاء الأمر", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)
}}
}
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction((UIAlertAction(title: "موافق", style: .Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})))
self.presentViewController(alert, animated: true, completion: nil)
}//end fun display alert
override func viewDidLoad() {
super.viewDidLoad()
Minor.delegate = self
Major.delegate = self
Label.delegate = self
// 3. Set the beacon manager's delegate
self.beaconManager.delegate = self
// 4. We need to request this authorization for every beacon manager
self.beaconManager.requestAlwaysAuthorization()
}
//To start/stop ranging as the view controller appears/disappears
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.beaconManager.startRangingBeaconsInRegion(self.beaconRegion)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.beaconManager.stopRangingBeaconsInRegion(self.beaconRegion)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//This method will be called everytime we are in the range of beacons
func beaconManager(manager: AnyObject, didRangeBeacons beacons: [CLBeacon],
inRegion region: CLBeaconRegion) {
//Get the array of beacons in range
//For each beacon in array
for beacon in beacons {
//Check if the content was requested
if(beaconDiscovered==0){
if (!Requested.contains("\(beacon.major):\(beacon.minor)"))
{//If not request content then add to requested array
loadContent(beacon.major, minor: beacon.minor)
Requested.append("\(beacon.major):\(beacon.minor)")
beaconDiscovered=beaconDiscovered+1;
}}
else if((beacon.major != Int(Major.text!)) && (beacon.minor != Int(Minor.text!)) && !alertOn){
let alert = UIAlertController(title: "", message: " تم اكتشاف أكثر من بيكون، الرجاء قلبها و،المحاولة من جديد لضمان الدقة ", preferredStyle: UIAlertControllerStyle.Alert)
self.alertOn = true
alert.addAction(UIAlertAction(title: "موافق", style: .Default, handler: { (action) -> Void in
self.Minor.text = "";
self.Major.text = "";
self.view.reloadInputViews()
self.beaconDiscovered=0
self.Requested = [""]
// self.dismissViewControllerAnimated(true, completion: nil)
self.alertOn = false
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
var alertOn = false
var beaconDiscovered = 0
func loadContent (major: NSNumber, minor: NSNumber)
{
//Col::(ContentID, Title, Abstract, Sharecounter, Label, EventID)
print("HERE IN PHPget \(major):\(minor)")
Minor.text = String(minor);
Major.text = String(major);
self.view.reloadInputViews()
}
var window:UIWindow!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let containerViewController = ContainerViewController()
containerViewController.centerViewController = mainStoryboard().instantiateViewControllerWithIdentifier("beaconsMng") as? CenterViewController
print(window!.rootViewController)
window!.rootViewController = containerViewController
print(window!.rootViewController)
window!.makeKeyAndVisible()
containerViewController.centerViewController.delegate?.collapseSidePanels!()
}
func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) }
@IBOutlet var scrollView: UIScrollView!
func textFieldDidBeginEditing(textField: UITextField) {
scrollView.setContentOffset((CGPointMake(0, 150)), animated: true)
}
func textFieldDidEndEditing(textField: UITextField) {
scrollView.setContentOffset((CGPointMake(0, 0)), animated: true)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
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 | c08adba136ab8da7562058d3b4796625 | 39.616071 | 189 | 0.588921 | 5.119865 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Pods/Starscream/Sources/Starscream/WebSocket.swift | 2 | 54982 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
// Copyright (c) 2014-2017 Dalton Cherry.
//
// 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 CoreFoundation
import CommonCrypto
public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName"
//Standard WebSocket close codes
public enum CloseCode : UInt16 {
case normal = 1000
case goingAway = 1001
case protocolError = 1002
case protocolUnhandledType = 1003
// 1004 reserved.
case noStatusReceived = 1005
//1006 reserved.
case encoding = 1007
case policyViolated = 1008
case messageTooBig = 1009
}
public enum ErrorType: Error {
case outputStreamWriteError //output stream error during write
case compressionError
case invalidSSLError //Invalid SSL certificate
case writeTimeoutError //The socket timed out waiting to be ready to write
case protocolError //There was an error parsing the WebSocket frames
case upgradeError //There was an error during the HTTP upgrade
case closeError //There was an error during the close (socket probably has been dereferenced)
}
public struct WSError: Error {
public let type: ErrorType
public let message: String
public let code: Int
}
//WebSocketClient is setup to be dependency injection for testing
public protocol WebSocketClient: class {
var delegate: WebSocketDelegate? {get set}
var pongDelegate: WebSocketPongDelegate? {get set}
var disableSSLCertValidation: Bool {get set}
var overrideTrustHostname: Bool {get set}
var desiredTrustHostname: String? {get set}
var sslClientCertificate: SSLClientCertificate? {get set}
#if os(Linux)
#else
var security: SSLTrustValidator? {get set}
var enabledSSLCipherSuites: [SSLCipherSuite]? {get set}
#endif
var isConnected: Bool {get}
func connect()
func disconnect(forceTimeout: TimeInterval?, closeCode: UInt16)
func write(string: String, completion: (() -> ())?)
func write(data: Data, completion: (() -> ())?)
func write(ping: Data, completion: (() -> ())?)
func write(pong: Data, completion: (() -> ())?)
}
//implements some of the base behaviors
extension WebSocketClient {
public func write(string: String) {
write(string: string, completion: nil)
}
public func write(data: Data) {
write(data: data, completion: nil)
}
public func write(ping: Data) {
write(ping: ping, completion: nil)
}
public func write(pong: Data) {
write(pong: pong, completion: nil)
}
public func disconnect() {
disconnect(forceTimeout: nil, closeCode: CloseCode.normal.rawValue)
}
}
//SSL settings for the stream
public struct SSLSettings {
public let useSSL: Bool
public let disableCertValidation: Bool
public var overrideTrustHostname: Bool
public var desiredTrustHostname: String?
public let sslClientCertificate: SSLClientCertificate?
#if os(Linux)
#else
public let cipherSuites: [SSLCipherSuite]?
#endif
}
public protocol WSStreamDelegate: class {
func newBytesInStream()
func streamDidError(error: Error?)
}
//This protocol is to allow custom implemention of the underlining stream. This way custom socket libraries (e.g. linux) can be used
public protocol WSStream {
var delegate: WSStreamDelegate? {get set}
func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void))
func write(data: Data) -> Int
func read() -> Data?
func cleanup()
#if os(Linux) || os(watchOS)
#else
func sslTrust() -> (trust: SecTrust?, domain: String?)
#endif
}
open class FoundationStream : NSObject, WSStream, StreamDelegate {
private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: [])
private var inputStream: InputStream?
private var outputStream: OutputStream?
public weak var delegate: WSStreamDelegate?
let BUFFER_MAX = 4096
public var enableSOCKSProxy = false
public func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h = url.host! as NSString
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if enableSOCKSProxy {
let proxyDict = CFNetworkCopySystemProxySettings()
let socksConfig = CFDictionaryCreateMutableCopy(nil, 0, proxyDict!.takeRetainedValue())
let propertyKey = CFStreamPropertyKey(rawValue: kCFStreamPropertySOCKSProxy)
CFWriteStreamSetProperty(outputStream, propertyKey, socksConfig)
CFReadStreamSetProperty(inputStream, propertyKey, socksConfig)
}
#endif
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if ssl.useSSL {
inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
var settings = [NSObject: NSObject]()
if ssl.disableCertValidation {
settings[kCFStreamSSLValidatesCertificateChain] = NSNumber(value: false)
}
if ssl.overrideTrustHostname {
if let hostname = ssl.desiredTrustHostname {
settings[kCFStreamSSLPeerName] = hostname as NSString
} else {
settings[kCFStreamSSLPeerName] = kCFNull
}
}
if let sslClientCertificate = ssl.sslClientCertificate {
settings[kCFStreamSSLCertificates] = sslClientCertificate.streamSSLCertificates
}
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
#endif
#if os(Linux)
#else
if let cipherSuites = ssl.cipherSuites {
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
completion(WSError(type: .invalidSSLError, message: "Error setting ingoing cypher suites", code: Int(resIn)))
}
if resOut != errSecSuccess {
completion(WSError(type: .invalidSSLError, message: "Error setting outgoing cypher suites", code: Int(resOut)))
}
}
#endif
}
#endif
}
CFReadStreamSetDispatchQueue(inStream, FoundationStream.sharedWorkQueue)
CFWriteStreamSetDispatchQueue(outStream, FoundationStream.sharedWorkQueue)
inStream.open()
outStream.open()
var out = timeout// wait X seconds before giving up
FoundationStream.sharedWorkQueue.async { [weak self] in
while !outStream.hasSpaceAvailable {
usleep(100) // wait until the socket is ready
out -= 100
if out < 0 {
completion(WSError(type: .writeTimeoutError, message: "Timed out waiting for the socket to be ready for a write", code: 0))
return
} else if let error = outStream.streamError {
completion(error)
return // disconnectStream will be called.
} else if self == nil {
completion(WSError(type: .closeError, message: "socket object has been dereferenced", code: 0))
return
}
}
completion(nil) //success!
}
}
public func write(data: Data) -> Int {
guard let outStream = outputStream else {return -1}
let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
return outStream.write(buffer, maxLength: data.count)
}
public func read() -> Data? {
guard let stream = inputStream else {return nil}
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
let length = stream.read(buffer, maxLength: BUFFER_MAX)
if length < 1 {
return nil
}
return Data(bytes: buffer, count: length)
}
public func cleanup() {
if let stream = inputStream {
stream.delegate = nil
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
}
if let stream = outputStream {
stream.delegate = nil
CFWriteStreamSetDispatchQueue(stream, nil)
stream.close()
}
outputStream = nil
inputStream = nil
}
#if os(Linux) || os(watchOS)
#else
public func sslTrust() -> (trust: SecTrust?, domain: String?) {
guard let outputStream = outputStream else { return (nil, nil) }
let trust = outputStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust?
var domain = outputStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as! String?
if domain == nil,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
var peerNameLen: Int = 0
SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen)
var peerName = Data(count: peerNameLen)
let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in
SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen)
}
if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 {
domain = peerDomain
}
}
return (trust, domain)
}
#endif
/**
Delegate for the stream methods. Processes incoming bytes
*/
open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if eventCode == .hasBytesAvailable {
if aStream == inputStream {
delegate?.newBytesInStream()
}
} else if eventCode == .errorOccurred {
delegate?.streamDidError(error: aStream.streamError)
} else if eventCode == .endEncountered {
delegate?.streamDidError(error: nil)
}
}
}
//WebSocket implementation
//standard delegate you should use
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocketClient)
func websocketDidDisconnect(socket: WebSocketClient, error: Error?)
func websocketDidReceiveMessage(socket: WebSocketClient, text: String)
func websocketDidReceiveData(socket: WebSocketClient, data: Data)
}
//got pongs
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocketClient, data: Data?)
}
// A Delegate with more advanced info on messages and connection etc.
public protocol WebSocketAdvancedDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: Error?)
func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse)
func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse)
func websocketHttpUpgrade(socket: WebSocket, request: String)
func websocketHttpUpgrade(socket: WebSocket, response: String)
}
open class WebSocket : NSObject, StreamDelegate, WebSocketClient, WSStreamDelegate {
public enum OpCode : UInt8 {
case continueFrame = 0x0
case textFrame = 0x1
case binaryFrame = 0x2
// 3-7 are reserved.
case connectionClose = 0x8
case ping = 0x9
case pong = 0xA
// B-F reserved.
}
public static let ErrorDomain = "WebSocket"
// Where the callback is executed. It defaults to the main UI thread queue.
public var callbackQueue = DispatchQueue.main
// MARK: - Constants
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSExtensionName = "Sec-WebSocket-Extensions"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let RSV1Mask: UInt8 = 0x40
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
let httpSwitchProtocolCode = 101
let supportedSSLSchemes = ["wss", "https"]
public class WSResponse {
var isFin = false
public var code: OpCode = .continueFrame
var bytesLeft = 0
public var frameCount = 0
public var buffer: NSMutableData?
public let firstFrame = {
return Date()
}()
}
// MARK: - Delegates
/// Responds to callback about new messages coming in over the WebSocket
/// and also connection/disconnect messages.
public weak var delegate: WebSocketDelegate?
/// The optional advanced delegate can be used instead of of the delegate
public weak var advancedDelegate: WebSocketAdvancedDelegate?
/// Receives a callback for each pong message recived.
public weak var pongDelegate: WebSocketPongDelegate?
public var onConnect: (() -> Void)?
public var onDisconnect: ((Error?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((Data) -> Void)?
public var onPong: ((Data?) -> Void)?
public var onHttpResponseHeaders: (([String: String]) -> Void)?
public var disableSSLCertValidation = false
public var overrideTrustHostname = false
public var desiredTrustHostname: String? = nil
public var sslClientCertificate: SSLClientCertificate? = nil
public var enableCompression = true
#if os(Linux)
#else
public var security: SSLTrustValidator?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
#endif
public var isConnected: Bool {
mutex.lock()
let isConnected = connected
mutex.unlock()
return isConnected
}
public var request: URLRequest //this is only public to allow headers, timeout, etc to be modified on reconnect
public var currentURL: URL { return request.url! }
public var respondToPingWithPong: Bool = true
// MARK: - Private
private struct CompressionState {
var supportsCompression = false
var messageNeedsDecompression = false
var serverMaxWindowBits = 15
var clientMaxWindowBits = 15
var clientNoContextTakeover = false
var serverNoContextTakeover = false
var decompressor:Decompressor? = nil
var compressor:Compressor? = nil
}
private var stream: WSStream
private var connected = false
private var isConnecting = false
private let mutex = NSLock()
private var compressionState = CompressionState()
private var writeQueue = OperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [Data]()
private var fragBuffer: Data?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private var headerSecKey = ""
private var canDispatch: Bool {
mutex.lock()
let canWork = readyToWrite
mutex.unlock()
return canWork
}
/// Used for setting protocols.
public init(request: URLRequest, protocols: [String]? = nil, stream: WSStream = FoundationStream()) {
self.request = request
self.stream = stream
if request.value(forHTTPHeaderField: headerOriginName) == nil {
guard let url = request.url else {return}
var origin = url.absoluteString
if let hostUrl = URL (string: "/", relativeTo: url) {
origin = hostUrl.absoluteString
origin.remove(at: origin.index(before: origin.endIndex))
}
self.request.setValue(origin, forHTTPHeaderField: headerOriginName)
}
if let protocols = protocols {
self.request.setValue(protocols.joined(separator: ","), forHTTPHeaderField: headerWSProtocolName)
}
writeQueue.maxConcurrentOperationCount = 1
}
public convenience init(url: URL, protocols: [String]? = nil) {
var request = URLRequest(url: url)
request.timeoutInterval = 5
self.init(request: request, protocols: protocols)
}
// Used for specifically setting the QOS for the write queue.
public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) {
self.init(url: url, protocols: protocols)
writeQueue.qualityOfService = writeQueueQOS
}
/**
Connect to the WebSocket server on a background thread.
*/
open func connect() {
guard !isConnecting else { return }
didDisconnect = false
isConnecting = true
createHTTPRequest()
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
- Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket.
*/
open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
guard isConnected else { return }
switch forceTimeout {
case .some(let seconds) where seconds > 0:
let milliseconds = Int(seconds * 1_000)
callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .none:
writeError(closeCode)
default:
disconnectStream(nil)
break
}
}
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter string: The string to write.
- parameter completion: The (optional) completion handler.
*/
open func write(string: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion)
}
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
open func write(data: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .binaryFrame, writeCompletion: completion)
}
/**
Write a ping to the websocket. This sends it as a control frame.
Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
*/
open func write(ping: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(ping, code: .ping, writeCompletion: completion)
}
/**
Write a pong to the websocket. This sends it as a control frame.
Respond to a Yodel.
*/
open func write(pong: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(pong, code: .pong, writeCompletion: completion)
}
/**
Private method that starts the connection.
*/
private func createHTTPRequest() {
guard let url = request.url else {return}
var port = url.port
if port == nil {
if supportedSSLSchemes.contains(url.scheme!) {
port = 443
} else {
port = 80
}
}
request.setValue(headerWSUpgradeValue, forHTTPHeaderField: headerWSUpgradeName)
request.setValue(headerWSConnectionValue, forHTTPHeaderField: headerWSConnectionName)
headerSecKey = generateWebSocketKey()
request.setValue(headerWSVersionValue, forHTTPHeaderField: headerWSVersionName)
request.setValue(headerSecKey, forHTTPHeaderField: headerWSKeyName)
if enableCompression {
let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15"
request.setValue(val, forHTTPHeaderField: headerWSExtensionName)
}
let hostValue = request.allHTTPHeaderFields?[headerWSHostName] ?? "\(url.host!):\(port!)"
request.setValue(hostValue, forHTTPHeaderField: headerWSHostName)
var path = url.absoluteString
let offset = (url.scheme?.count ?? 2) + 3
path = String(path[path.index(path.startIndex, offsetBy: offset)..<path.endIndex])
if let range = path.range(of: "/") {
path = String(path[range.lowerBound..<path.endIndex])
} else {
path = "/"
if let query = url.query {
path += "?" + query
}
}
var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n"
if let headers = request.allHTTPHeaderFields {
for (key, val) in headers {
httpBody += "\(key): \(val)\r\n"
}
}
httpBody += "\r\n"
initStreamsWithData(httpBody.data(using: .utf8)!, Int(port!))
advancedDelegate?.websocketHttpUpgrade(socket: self, request: httpBody)
}
/**
Generate a WebSocket key as needed in RFC.
*/
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for _ in 0..<seed {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni!))"
}
let data = key.data(using: String.Encoding.utf8)
let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return baseKey!
}
/**
Start the stream connection and write the data to the output stream.
*/
private func initStreamsWithData(_ data: Data, _ port: Int) {
guard let url = request.url else {
disconnectStream(nil, runDelegate: true)
return
}
// Disconnect and clean up any existing streams before setting up a new pair
disconnectStream(nil, runDelegate: false)
let useSSL = supportedSSLSchemes.contains(url.scheme!)
#if os(Linux)
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname),
sslClientCertificate: sslClientCertificate
#else
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname,
sslClientCertificate: sslClientCertificate,
cipherSuites: self.enabledSSLCipherSuites)
#endif
certValidated = !useSSL
let timeout = request.timeoutInterval * 1_000_000
stream.delegate = self
stream.connect(url: url, port: port, timeout: timeout, ssl: settings, completion: { [weak self] (error) in
guard let self = self else {return}
if error != nil {
self.disconnectStream(error)
return
}
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
guard let sOperation = operation, let self = self else { return }
guard !sOperation.isCancelled else { return }
// Do the pinning now if needed
#if os(Linux) || os(watchOS)
self.certValidated = false
#else
if let sec = self.security, !self.certValidated {
let trustObj = self.stream.sslTrust()
if let possibleTrust = trustObj.trust {
self.certValidated = sec.isValid(possibleTrust, domain: trustObj.domain)
} else {
self.certValidated = false
}
if !self.certValidated {
self.disconnectStream(WSError(type: .invalidSSLError, message: "Invalid SSL certificate", code: 0))
return
}
}
#endif
let _ = self.stream.write(data: data)
}
self.writeQueue.addOperation(operation)
})
self.mutex.lock()
self.readyToWrite = true
self.mutex.unlock()
}
/**
Delegate for the stream methods. Processes incoming bytes
*/
public func newBytesInStream() {
processInputStream()
}
public func streamDidError(error: Error?) {
disconnectStream(error)
}
/**
Disconnect the stream object and notifies the delegate.
*/
private func disconnectStream(_ error: Error?, runDelegate: Bool = true) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
mutex.lock()
cleanupStream()
connected = false
mutex.unlock()
if runDelegate {
doDisconnect(error)
}
}
/**
cleanup the streams.
*/
private func cleanupStream() {
stream.cleanup()
fragBuffer = nil
}
/**
Handles the incoming bytes and sending them to the proper processing method.
*/
private func processInputStream() {
let data = stream.read()
guard let d = data else { return }
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(d)
if process {
dequeueInput()
}
}
/**
Dequeue the incoming input so it is processed in order.
*/
private func dequeueInput() {
while !inputQueue.isEmpty {
autoreleasepool {
let data = inputQueue[0]
var work = data
if let buffer = fragBuffer {
var combine = NSData(data: buffer) as Data
combine.append(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
let length = work.count
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{ $0 != data }
}
}
}
/**
Handle checking the inital connection status
*/
private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
break
case -1:
fragBuffer = Data(bytes: buffer, count: bufferLen)
break // do nothing, we are going to collect more data
default:
doDisconnect(WSError(type: .upgradeError, message: "Invalid HTTP upgrade", code: code))
}
}
/**
Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
*/
private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k += 1
if k == 4 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
let code = validateResponse(buffer, bufferLen: totalSize)
if code != 0 {
return code
}
isConnecting = false
mutex.lock()
connected = true
mutex.unlock()
didDisconnect = false
if canDispatch {
callbackQueue.async { [weak self] in
guard let self = self else { return }
self.onConnect?()
self.delegate?.websocketDidConnect(socket: self)
self.advancedDelegate?.websocketDidConnect(socket: self)
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
}
}
//totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
}
return 0 //success
}
return -1 // Was unable to find the full TCP header.
}
/**
Validates the HTTP is a 101 as per the RFC spec.
*/
private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
guard let str = String(data: Data(bytes: buffer, count: bufferLen), encoding: .utf8) else { return -1 }
let splitArr = str.components(separatedBy: "\r\n")
var code = -1
var i = 0
var headers = [String: String]()
for str in splitArr {
if i == 0 {
let responseSplit = str.components(separatedBy: .whitespaces)
guard responseSplit.count > 1 else { return -1 }
if let c = Int(responseSplit[1]) {
code = c
}
} else {
let responseSplit = str.components(separatedBy: ":")
guard responseSplit.count > 1 else { break }
let key = responseSplit[0].trimmingCharacters(in: .whitespaces)
let val = responseSplit[1].trimmingCharacters(in: .whitespaces)
headers[key.lowercased()] = val
}
i += 1
}
advancedDelegate?.websocketHttpUpgrade(socket: self, response: str)
onHttpResponseHeaders?(headers)
if code != httpSwitchProtocolCode {
return code
}
if let extensionHeader = headers[headerWSExtensionName.lowercased()] {
processExtensionHeader(extensionHeader)
}
if let acceptKey = headers[headerWSAcceptName.lowercased()] {
if acceptKey.count > 0 {
if headerSecKey.count > 0 {
let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64()
if sha != acceptKey as String {
return -1
}
}
return 0
}
}
return -1
}
/**
Parses the extension header, setting up the compression parameters.
*/
func processExtensionHeader(_ extensionHeader: String) {
let parts = extensionHeader.components(separatedBy: ";")
for p in parts {
let part = p.trimmingCharacters(in: .whitespaces)
if part == "permessage-deflate" {
compressionState.supportsCompression = true
} else if part.hasPrefix("server_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.serverMaxWindowBits = val
}
} else if part.hasPrefix("client_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.clientMaxWindowBits = val
}
} else if part == "client_no_context_takeover" {
compressionState.clientNoContextTakeover = true
} else if part == "server_no_context_takeover" {
compressionState.serverNoContextTakeover = true
}
}
if compressionState.supportsCompression {
compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits)
compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits)
}
}
/**
Read a 16 bit big endian value from a buffer
*/
private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
/**
Read a 64 bit big endian value from a buffer
*/
private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
var value = UInt64(0)
for i in 0...7 {
value = (value << 8) | UInt64(buffer[offset + i])
}
return value
}
/**
Write a 16-bit big endian value to a buffer.
*/
private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
/**
Write a 64-bit big endian value to a buffer.
*/
private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
for i in 0...7 {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
/**
Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
*/
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last
guard let baseAddress = buffer.baseAddress else {return emptyBuffer}
let bufferLen = buffer.count
if response != nil && bufferLen < 2 {
fragBuffer = Data(buffer: buffer)
return emptyBuffer
}
if let response = response, response.bytesLeft > 0 {
var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
response.bytesLeft -= len
response.buffer?.append(Data(bytes: baseAddress, count: len))
_ = processResponse(response)
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue)
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if compressionState.supportsCompression && receivedOpcode != .continueFrame {
compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0
}
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping)
if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame &&
receivedOpcode != .textFrame && receivedOpcode != .pong) {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "unknown opcode: \(receivedOpcodeRawValue)", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "control frames can't be fragmented", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
var closeCode = CloseCode.normal.rawValue
if receivedOpcode == .connectionClose {
if payloadLen == 1 {
closeCode = CloseCode.protocolError.rawValue
} else if payloadLen > 1 {
closeCode = WebSocket.readUint16(baseAddress, offset: offset)
if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) {
closeCode = CloseCode.protocolError.rawValue
}
}
if payloadLen < 2 {
doDisconnect(WSError(type: .protocolError, message: "connection closed by server", code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
} else if isControlFrame && payloadLen > 125 {
writeError(CloseCode.protocolError.rawValue)
return emptyBuffer
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += MemoryLayout<UInt64>.size
} else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += MemoryLayout<UInt16>.size
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = Data(bytes: baseAddress, count: bufferLen)
return emptyBuffer
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
if receivedOpcode == .connectionClose && len > 0 {
let size = MemoryLayout<UInt16>.size
offset += size
len -= UInt64(size)
}
let data: Data
if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor {
do {
data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0)
if isFin > 0 && compressionState.serverNoContextTakeover {
try decompressor.reset()
}
} catch {
let closeReason = "Decompression failed: \(error)"
let closeCode = CloseCode.encoding.rawValue
doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
} else {
data = Data(bytes: baseAddress+offset, count: Int(len))
}
if receivedOpcode == .connectionClose {
var closeReason = "connection closed by server"
if let customCloseReason = String(data: data, encoding: .utf8) {
closeReason = customCloseReason
} else {
closeCode = CloseCode.protocolError.rawValue
}
doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
if receivedOpcode == .pong {
if canDispatch {
callbackQueue.async { [weak self] in
guard let self = self else { return }
let pongData: Data? = data.count > 0 ? data : nil
self.onPong?(pongData)
self.pongDelegate?.websocketDidReceivePong(socket: self, data: pongData)
}
}
return buffer.fromOffset(offset + Int(len))
}
var response = readStack.last
if isControlFrame {
response = nil // Don't append pings.
}
if isFin == 0 && receivedOpcode == .continueFrame && response == nil {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "continue frame before a binary or text frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
var isNew = false
if response == nil {
if receivedOpcode == .continueFrame {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
isNew = true
response = WSResponse()
response!.code = receivedOpcode!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == .continueFrame {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
response!.buffer!.append(data)
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
}
_ = processResponse(response)
}
let step = Int(offset + numericCast(len))
return buffer.fromOffset(step)
}
}
/**
Process all messages in the buffer if possible.
*/
private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) {
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
repeat {
buffer = processOneRawMessage(inBuffer: buffer)
} while buffer.count >= 2
if buffer.count > 0 {
fragBuffer = Data(buffer: buffer)
}
}
/**
Process the finished response of a buffer.
*/
private func processResponse(_ response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .ping {
if respondToPingWithPong {
let data = response.buffer! // local copy so it is perverse for writing
dequeueWrite(data as Data, code: .pong)
}
} else if response.code == .textFrame {
guard let str = String(data: response.buffer! as Data, encoding: .utf8) else {
writeError(CloseCode.encoding.rawValue)
return false
}
if canDispatch {
callbackQueue.async { [weak self] in
guard let self = self else { return }
self.onText?(str)
self.delegate?.websocketDidReceiveMessage(socket: self, text: str)
self.advancedDelegate?.websocketDidReceiveMessage(socket: self, text: str, response: response)
}
}
} else if response.code == .binaryFrame {
if canDispatch {
let data = response.buffer! // local copy so it is perverse for writing
callbackQueue.async { [weak self] in
guard let self = self else { return }
self.onData?(data as Data)
self.delegate?.websocketDidReceiveData(socket: self, data: data as Data)
self.advancedDelegate?.websocketDidReceiveData(socket: self, data: data as Data, response: response)
}
}
}
readStack.removeLast()
return true
}
return false
}
/**
Write an error to the socket
*/
private func writeError(_ code: UInt16) {
let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose)
}
/**
Used to write things to the stream
*/
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
//stream isn't ready, let's wait
guard let self = self else { return }
guard let sOperation = operation else { return }
var offset = 2
var firstByte:UInt8 = self.FinMask | code.rawValue
var data = data
if [.textFrame, .binaryFrame].contains(code), let compressor = self.compressionState.compressor {
do {
data = try compressor.compress(data)
if self.compressionState.clientNoContextTakeover {
try compressor.reset()
}
firstByte |= self.RSV1Mask
} catch {
// TODO: report error? We can just send the uncompressed frame.
}
}
let dataLength = data.count
let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize)
let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self)
buffer[0] = firstByte
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += MemoryLayout<UInt16>.size
} else {
buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += MemoryLayout<UInt64>.size
}
buffer[1] |= self.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
_ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey)
offset += MemoryLayout<UInt32>.size
for i in 0..<dataLength {
buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size]
offset += 1
}
var total = 0
while !sOperation.isCancelled {
if !self.readyToWrite {
self.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0))
break
}
let stream = self.stream
let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self)
let len = stream.write(data: Data(bytes: writeBuffer, count: offset-total))
if len <= 0 {
self.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0))
break
} else {
total += len
}
if total >= offset {
if let callback = writeCompletion {
self.callbackQueue.async {
callback()
}
}
break
}
}
}
writeQueue.addOperation(operation)
}
/**
Used to preform the disconnect delegate
*/
private func doDisconnect(_ error: Error?) {
guard !didDisconnect else { return }
didDisconnect = true
isConnecting = false
mutex.lock()
connected = false
mutex.unlock()
guard canDispatch else {return}
callbackQueue.async { [weak self] in
guard let self = self else { return }
self.onDisconnect?(error)
self.delegate?.websocketDidDisconnect(socket: self, error: error)
self.advancedDelegate?.websocketDidDisconnect(socket: self, error: error)
let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] }
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo)
}
}
// MARK: - Deinit
deinit {
mutex.lock()
readyToWrite = false
cleanupStream()
mutex.unlock()
writeQueue.cancelAllOperations()
}
}
private extension String {
func sha1Base64() -> String {
let data = self.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
return Data(bytes: digest).base64EncodedString()
}
}
private extension Data {
init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress!, count: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
#if swift(>=4)
#else
fileprivate extension String {
var count: Int {
return self.characters.count
}
}
#endif
| mit | a1e277436b88f3c2d3ce7d378781bd17 | 39.547198 | 226 | 0.587465 | 5.367239 | false | false | false | false |
mcudich/TemplateKit | Source/Core/Element.swift | 1 | 2032 | //
// Element.swift
// TemplateKit
//
// Created by Matias Cudich on 9/3/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import Foundation
import CSSParser
public protocol ElementRepresentable {
var tagName: String { get }
func make(_ element: Element, _ owner: Node?, _ context: Context?) -> Node
func equals(_ other: ElementRepresentable) -> Bool
}
public protocol Element: class, Keyable, StyleElement, ElementProvider {
var type: ElementRepresentable { get }
var children: [Element]? { get }
weak var parent: Element? { get set }
func build(withOwner owner: Node?, context: Context?) -> Node
}
extension ElementProvider where Self: Element {
public func build(with model: Model) -> Element {
return self
}
}
public class ElementData<PropertiesType: Properties>: Element {
public let type: ElementRepresentable
public private(set) var children: [Element]?
public weak var parent: Element?
public var properties: PropertiesType
public var key: String? {
get {
return properties.core.identifier.key
}
set {
properties.core.identifier.key = newValue
}
}
public init(_ type: ElementRepresentable, _ properties: PropertiesType, _ children: [Element]? = nil) {
self.type = type
self.properties = properties
self.children = children
for (index, child) in (self.children ?? []).enumerated() {
self.children?[index].parent = self
self.children?[index].key = child.key ?? "\(index)"
}
}
public func build(withOwner owner: Node?, context: Context? = nil) -> Node {
return type.make(self, owner, context)
}
public func equals(_ other: Element?) -> Bool {
guard let other = other as? ElementData<PropertiesType> else {
return false
}
return type.equals(other.type) && key == other.key && (parent?.equals(other.parent) ?? (other.parent == nil)) && properties == other.properties
}
public func equals(_ other: ElementProvider?) -> Bool {
return equals(other as? Element)
}
}
| mit | 4fc28d4e8d5bac5ed2a0aca2b1599ee7 | 26.821918 | 147 | 0.675529 | 4.062 | false | false | false | false |
CoBug92/MyRestaurant | MyRestraunts/WebViewController.swift | 1 | 2196 | //
// WebViewController.swift
// MyRestaurant
//
// Created by Богдан Костюченко on 24/10/2016.
// Copyright © 2016 Bogdan Kostyuchenko. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController, WKNavigationDelegate {
var url: URL!
var webView: WKWebView!
var progressView: UIProgressView!
deinit {
webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
}
override func viewDidLoad() {
super.viewDidLoad()
webView = WKWebView()
webView.navigationDelegate = self
view = webView
let request = URLRequest(url: url)
webView.load(request)
webView.allowsBackForwardNavigationGestures = true
progressView = UIProgressView(progressViewStyle: .default)
progressView.sizeToFit()
let progressButton = UIBarButtonItem(customView: progressView) //размещая прогрессБаттон вместо одной из кнопок тапбара
let flexibleSpacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) //чтобы разделить кнопку отвечающую за обновления со статус баром
let refreshButton = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
toolbarItems = [progressButton, flexibleSpacer, refreshButton]
navigationController?.isToolbarHidden = false //чтобы тулБар был на экране и не прятался
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "estimatedProgress" {
progressView.progress = Float(webView.estimatedProgress)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
title = webView.title
}
}
| gpl-3.0 | f733f6454de3e1da412a86e63c6e6dd8 | 34.842105 | 173 | 0.684288 | 4.795775 | false | false | false | false |
Chan4iOS/SCMapCatch-Swift | SCMapCatch-Swift/Dictionary+MC.swift | 1 | 1191 | //
// Dictionary+SC.swift
// SCMapCatch-Swift_Demo
//
// Created by 陈世翰 on 17/4/18.
// Copyright © 2017年 Coder Chan. All rights reserved.
//
import Foundation
extension Dictionary{
mutating func mc_set(value:Value?,forkey key:Key)->Dictionary{
var result = self as [Key:Value]
if value != nil{
result[key] = value!
}else{
removeValue(forKey: key)
}
return result
}
func mc_object<T:Hashable>(forKeys keys:Array<T>) -> Any? {
guard keys.count>0 else{
return nil
}
if keys.count == 1{
return self[keys.first as! Key]
}else{
let nextLevel = self[keys.first as! Key] as? [T:Any]
guard nextLevel != nil else{
return nil
}
var nextLevelKeys = keys
nextLevelKeys.remove(at: 0)
return (nextLevel!).mc_object(forKeys: nextLevelKeys)
}
}
/*get object by path
:param:keys path components
:return:result
*/
func mc_object<T:Hashable>(forKeys keys:T...) -> Any? {
return mc_object(forKeys:keys)
}
}
| mit | 64c237108c18b8b2f4d4e7665ffb308a | 24.148936 | 66 | 0.535533 | 3.94 | false | false | false | false |
chanhx/iGithub | iGithub/Models/File.swift | 2 | 1569 | //
// File.swift
// iGithub
//
// Created by Chan Hocheung on 7/24/16.
// Copyright © 2016 Hocheung. All rights reserved.
//
import Foundation
import ObjectMapper
class File: Mappable {
enum FileType: String {
case directory = "dir"
case file = "file"
case submodule = "submodule"
case symlink = "symlink"
}
var type: FileType?
var encoding: String?
var size: Int?
var name: String?
var path: String?
var content: String?
var sha: String?
var link: URL?
var gitLink: URL?
required init?(map: Map) {
mapping(map: map)
}
func mapping(map: Map) {
type <- map["type"]
encoding <- map["encoding"]
size <- map["size"]
name <- map["name"]
path <- map["path"]
content <- map["content"]
sha <- map["sha"]
link <- (map["_links.self"], URLTransform())
gitLink <- (map["_links.git"], URLTransform())
}
lazy var isSubmodule: Bool = {
guard self.type == .file else {
return false
}
guard self.size! <= 0 else {
return false
}
guard let l1 = self.link, let l2 = self.gitLink else {
return true
}
let l1Components = l1.pathComponents
let l2Components = l2.pathComponents
return (l1Components[2] != l2Components[2])
|| (l1Components[3] != l2Components[3])
}()
}
| gpl-3.0 | 37ae7da296d1fc16592ff9cc6d945295 | 22.058824 | 62 | 0.5 | 4.126316 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Picker/Controller/PhotoPeekViewController.swift | 1 | 4618 | //
// PhotoPeekViewController.swift
// HXPHPicker
//
// Created by Slience on 2021/8/4.
//
import UIKit
import AVKit
public protocol PhotoPeekViewControllerDelegate: AnyObject {
func photoPeekViewController(requestSucceed photoPeekViewController: PhotoPeekViewController)
func photoPeekViewController(requestFailed photoPeekViewController: PhotoPeekViewController)
}
public extension PhotoPeekViewControllerDelegate {
func photoPeekViewController(requestSucceed photoPeekViewController: PhotoPeekViewController) { }
func photoPeekViewController(requestFailed photoPeekViewController: PhotoPeekViewController) { }
}
public class PhotoPeekViewController: UIViewController {
weak var delegate: PhotoPeekViewControllerDelegate?
lazy var contentView: PhotoPreviewContentView = {
let type: PhotoPreviewContentView.`Type`
if photoAsset.mediaType == .photo {
if photoAsset.mediaSubType == .livePhoto ||
photoAsset.mediaSubType == .localLivePhoto {
type = .livePhoto
}else {
type = .photo
}
}else {
type = .video
}
let view = PhotoPreviewContentView(type: type)
view.isPeek = true
if let photoAsset = photoAsset {
view.photoAsset = photoAsset
}
view.livePhotoPlayType = .auto
view.videoPlayType = .auto
view.delegate = self
if type == .video {
view.videoView.delegate = self
}
return view
}()
lazy var progressView: UIView = {
let view = UIView()
view.backgroundColor = .white
return view
}()
lazy var captureView: CaptureVideoPreviewView = {
let view = CaptureVideoPreviewView()
return view
}()
var photoAsset: PhotoAsset!
fileprivate var progress: CGFloat = 0
fileprivate var isCamera = false
public init(_ photoAsset: PhotoAsset) {
self.photoAsset = photoAsset
super.init(nibName: nil, bundle: nil)
}
init(isCamera: Bool) {
self.isCamera = isCamera
super.init(nibName: nil, bundle: nil)
}
public override func viewDidLoad() {
super.viewDidLoad()
if photoAsset != nil {
view.addSubview(contentView)
view.addSubview(progressView)
}
if isCamera {
view.addSubview(captureView)
}
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if photoAsset != nil {
contentView.requestPreviewAsset()
}
if isCamera {
captureView.startSession()
}
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if photoAsset != nil {
contentView.cancelRequest()
}
if isCamera {
captureView.stopSession()
}
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if photoAsset != nil {
contentView.frame = view.bounds
progressView.height = 1
progressView.y = view.height - progressView.height
progressView.width = view.width * progress
}
if isCamera {
captureView.frame = view.bounds
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PhotoPeekViewController: PhotoPreviewContentViewDelete {
public func contentView(requestSucceed contentView: PhotoPreviewContentView) {
delegate?.photoPeekViewController(requestSucceed: self)
}
public func contentView(requestFailed contentView: PhotoPreviewContentView) {
delegate?.photoPeekViewController(requestFailed: self)
}
}
extension PhotoPeekViewController: PhotoPreviewVideoViewDelegate {
func videoView(resetPlay videoView: VideoPlayerView) {
progress = 0
setupProgressView()
}
func videoView(_ videoView: VideoPlayerView, didChangedPlayerTime duration: CGFloat) {
photoAsset.playerTime = duration
progress = duration / CGFloat(photoAsset.videoDuration)
setupProgressView()
}
fileprivate func setupProgressView() {
if progress == 0 {
progressView.width = 0
}else {
UIView.animate(withDuration: 0.1, delay: 0, options: .curveLinear) {
self.progressView.width = self.view.width * self.progress
}
}
}
}
| mit | 263f25e785d568681f357d79e62233ee | 29.993289 | 101 | 0.631659 | 5.631707 | false | false | false | false |
bm842/Brokers | Sources/Random.swift | 2 | 18536 | //
// CwlRandom.swift
// CwlUtils
//
// Created by Matt Gallagher on 2016/05/17.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import Foundation
public protocol RandomGenerator {
init()
/// Initializes the provided buffer with randomness
mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int)
// Generates 64 bits of randomness
mutating func random64() -> UInt64
// Generates 32 bits of randomness
mutating func random32() -> UInt32
// Generates a uniform distribution with a maximum value no more than `max`
mutating func random64(max: UInt64) -> UInt64
// Generates a uniform distribution with a maximum value no more than `max`
mutating func random32(max: UInt32) -> UInt32
/// Generates a double with a random 52 bit significand on the half open range [0, 1)
mutating func randomHalfOpen() -> Double
/// Generates a double with a random 52 bit significand on the closed range [0, 1]
mutating func randomClosed() -> Double
/// Generates a double with a random 51 bit significand on the open range (0, 1)
mutating func randomOpen() -> Double
}
public extension RandomGenerator {
mutating func random64() -> UInt64 {
var bits: UInt64 = 0
randomize(buffer: &bits, size: MemoryLayout<UInt64>.size)
return bits
}
mutating func random32() -> UInt32 {
var bits: UInt32 = 0
randomize(buffer: &bits, size: MemoryLayout<UInt32>.size)
return bits
}
mutating func random64(max: UInt64) -> UInt64 {
switch max {
case UInt64.max: return random64()
case 0: return 0
default:
var result: UInt64
repeat {
result = random64()
} while result < UInt64.max % (max + 1)
return result % (max + 1)
}
}
mutating func random32(max: UInt32) -> UInt32 {
switch max {
case UInt32.max: return random32()
case 0: return 0
default:
var result: UInt32
repeat {
result = random32()
} while result < UInt32.max % (max + 1)
return result % (max + 1)
}
}
mutating func randomHalfOpen() -> Double {
return halfOpenDoubleFrom64(bits: random64())
}
mutating func randomClosed() -> Double {
return closedDoubleFrom64(bits: random64())
}
mutating func randomOpen() -> Double {
return openDoubleFrom64(bits: random64())
}
}
public func halfOpenDoubleFrom64(bits: UInt64) -> Double {
return Double(bits & 0x001f_ffff_ffff_ffff) * (1.0 / 9007199254740992.0)
}
public func closedDoubleFrom64(bits: UInt64) -> Double {
return Double(bits & 0x001f_ffff_ffff_ffff) * (1.0 / 9007199254740991.0)
}
public func openDoubleFrom64(bits: UInt64) -> Double {
return (Double(bits & 0x000f_ffff_ffff_ffff) + 0.5) * (1.0 / 9007199254740991.0)
}
public protocol RandomWordGenerator: RandomGenerator {
associatedtype WordType
mutating func randomWord() -> WordType
}
extension RandomWordGenerator {
public mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int) {
let b = buffer.assumingMemoryBound(to: WordType.self)
for i in 0..<(size / MemoryLayout<WordType>.size) {
b[i] = randomWord()
}
let remainder = size % MemoryLayout<WordType>.size
if remainder > 0 {
var final = randomWord()
let b2 = buffer.assumingMemoryBound(to: UInt8.self)
withUnsafePointer(to: &final) { (fin: UnsafePointer<WordType>) in
fin.withMemoryRebound(to: UInt8.self, capacity: remainder) { f in
for i in 0..<remainder {
b2[size - i - 1] = f[i]
}
}
}
}
}
}
public struct DevRandom: RandomGenerator {
class FileDescriptor {
let value: CInt
init() {
value = open("/dev/urandom", O_RDONLY)
precondition(value >= 0)
}
deinit {
close(value)
}
}
let fd: FileDescriptor
public init() {
fd = FileDescriptor()
}
public mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int) {
let result = read(fd.value, buffer, size)
precondition(result == size)
}
public static func random64() -> UInt64 {
var r = DevRandom()
return r.random64()
}
public static func randomize(buffer: UnsafeMutableRawPointer, size: Int) {
var r = DevRandom()
r.randomize(buffer: buffer, size: size)
}
}
public struct Arc4Random: RandomGenerator {
public init() {
}
public mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int) {
arc4random_buf(buffer, size)
}
public mutating func random64() -> UInt64 {
// Generating 2x32-bit appears to be faster than using arc4random_buf on a 64-bit value
var value: UInt64 = 0
arc4random_buf(&value, MemoryLayout<UInt64>.size)
return value
}
public mutating func random32() -> UInt32 {
return arc4random()
}
}
public struct Lfsr258: RandomWordGenerator {
public typealias WordType = UInt64
public typealias StateType = (UInt64, UInt64, UInt64, UInt64, UInt64)
static let k: (UInt64, UInt64, UInt64, UInt64, UInt64) = (1, 9, 12, 17, 23)
static let q: (UInt64, UInt64, UInt64, UInt64, UInt64) = (1, 24, 3, 5, 3)
static let s: (UInt64, UInt64, UInt64, UInt64, UInt64) = (10, 5, 29, 23, 8)
var state: StateType = (0, 0, 0, 0, 0)
public init() {
var r = DevRandom()
repeat {
r.randomize(buffer: &state.0, size: MemoryLayout<UInt64>.size)
} while state.0 < Lfsr258.k.0
repeat {
r.randomize(buffer: &state.1, size: MemoryLayout<UInt64>.size)
} while state.1 < Lfsr258.k.1
repeat {
r.randomize(buffer: &state.2, size: MemoryLayout<UInt64>.size)
} while state.2 < Lfsr258.k.2
repeat {
r.randomize(buffer: &state.3, size: MemoryLayout<UInt64>.size)
} while state.3 < Lfsr258.k.3
repeat {
r.randomize(buffer: &state.4, size: MemoryLayout<UInt64>.size)
} while state.4 < Lfsr258.k.4
}
public init(seed: StateType) {
self.state = seed
}
public mutating func randomWord() -> UInt64 {
return random64()
}
public mutating func random64() -> UInt64 {
// Constants from "Tables of Maximally-Equidistributed Combined LFSR Generators" by Pierre L'Ecuyer:
// http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps
let l: UInt64 = 64
let x0 = (((state.0 << Lfsr258.q.0) ^ state.0) >> (l - Lfsr258.k.0 - Lfsr258.s.0))
state.0 = ((state.0 & (UInt64.max << Lfsr258.k.0)) << Lfsr258.s.0) | x0
let x1 = (((state.1 << Lfsr258.q.1) ^ state.1) >> (l - Lfsr258.k.1 - Lfsr258.s.1))
state.1 = ((state.1 & (UInt64.max << Lfsr258.k.1)) << Lfsr258.s.1) | x1
let x2 = (((state.2 << Lfsr258.q.2) ^ state.2) >> (l - Lfsr258.k.2 - Lfsr258.s.2))
state.2 = ((state.2 & (UInt64.max << Lfsr258.k.2)) << Lfsr258.s.2) | x2
let x3 = (((state.3 << Lfsr258.q.3) ^ state.3) >> (l - Lfsr258.k.3 - Lfsr258.s.3))
state.3 = ((state.3 & (UInt64.max << Lfsr258.k.3)) << Lfsr258.s.3) | x3
let x4 = (((state.4 << Lfsr258.q.4) ^ state.4) >> (l - Lfsr258.k.4 - Lfsr258.s.4))
state.4 = ((state.4 & (UInt64.max << Lfsr258.k.4)) << Lfsr258.s.4) | x4
return (state.0 ^ state.1 ^ state.2 ^ state.3 ^ state.4)
}
}
public struct Lfsr176: RandomWordGenerator {
public typealias WordType = UInt64
public typealias StateType = (UInt64, UInt64, UInt64)
static let k: (UInt64, UInt64, UInt64) = (1, 6, 9)
static let q: (UInt64, UInt64, UInt64) = (5, 19, 24)
static let s: (UInt64, UInt64, UInt64) = (24, 13, 17)
var state: StateType = (0, 0, 0)
public init() {
var r = DevRandom()
repeat {
r.randomize(buffer: &state.0, size: MemoryLayout<UInt64>.size)
} while state.0 < Lfsr176.k.0
repeat {
r.randomize(buffer: &state.1, size: MemoryLayout<UInt64>.size)
} while state.1 < Lfsr176.k.1
repeat {
r.randomize(buffer: &state.2, size: MemoryLayout<UInt64>.size)
} while state.2 < Lfsr176.k.2
}
public init(seed: StateType) {
self.state = seed
}
public mutating func random64() -> UInt64 {
return randomWord()
}
public mutating func randomWord() -> UInt64 {
// Constants from "Tables of Maximally-Equidistributed Combined LFSR Generators" by Pierre L'Ecuyer:
// http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps
let l: UInt64 = 64
let x0 = (((state.0 << Lfsr176.q.0) ^ state.0) >> (l - Lfsr176.k.0 - Lfsr176.s.0))
state.0 = ((state.0 & (UInt64.max << Lfsr176.k.0)) << Lfsr176.s.0) | x0
let x1 = (((state.1 << Lfsr176.q.1) ^ state.1) >> (l - Lfsr176.k.1 - Lfsr176.s.1))
state.1 = ((state.1 & (UInt64.max << Lfsr176.k.1)) << Lfsr176.s.1) | x1
let x2 = (((state.2 << Lfsr176.q.2) ^ state.2) >> (l - Lfsr176.k.2 - Lfsr176.s.2))
state.2 = ((state.2 & (UInt64.max << Lfsr176.k.2)) << Lfsr176.s.2) | x2
return (state.0 ^ state.1 ^ state.2)
}
}
public struct Xoroshiro: RandomWordGenerator {
public typealias WordType = UInt64
public typealias StateType = (UInt64, UInt64)
var state: StateType = (0, 0)
public init() {
DevRandom.randomize(buffer: &state, size: MemoryLayout<StateType>.size)
}
public init(seed: StateType) {
self.state = seed
}
public mutating func random64() -> UInt64 {
return randomWord()
}
public mutating func randomWord() -> UInt64 {
// Directly inspired by public domain implementation here:
// http://xoroshiro.di.unimi.it
// by David Blackman and Sebastiano Vigna
let (l, k0, k1, k2): (UInt64, UInt64, UInt64, UInt64) = (64, 55, 14, 36)
let result = state.0 &+ state.1
let x = state.0 ^ state.1
state.0 = ((state.0 << k0) | (state.0 >> (l - k0))) ^ x ^ (x << k1)
state.1 = (x << k2) | (x >> (l - k2))
return result
}
}
public struct ConstantNonRandom: RandomWordGenerator {
public typealias WordType = UInt64
var state: UInt64 = DevRandom.random64()
public init() {
}
public init(seed: UInt64) {
self.state = seed
}
public mutating func random64() -> UInt64 {
return randomWord()
}
public mutating func randomWord() -> UInt64 {
return state
}
}
public struct MersenneTwister: RandomWordGenerator {
public typealias WordType = UInt64
// 312 is 13 x 6 x 4
private var state_internal: (
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64
) = (
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
)
private var index: Int
private static let stateCount: Int = 312
public init() {
self.init(seed: DevRandom.random64())
}
public init(seed: UInt64) {
index = MersenneTwister.stateCount
withUnsafeMutablePointer(to: &state_internal) { $0.withMemoryRebound(to: UInt64.self, capacity: MersenneTwister.stateCount) { state in
state[0] = seed
for i in 1..<MersenneTwister.stateCount {
state[i] = 6364136223846793005 &* (state[i &- 1] ^ (state[i &- 1] >> 62)) &+ UInt64(i)
}
} }
}
public mutating func randomWord() -> UInt64 {
return random64()
}
private mutating func twist() {
}
public mutating func random64() -> UInt64 {
if index == MersenneTwister.stateCount {
// Really dirty leaking of unsafe pointer outside its closure to ensure inlining in Swift 3 preview 1
let state = withUnsafeMutablePointer(to: &state_internal) { $0.withMemoryRebound(to: UInt64.self, capacity: MersenneTwister.stateCount) { $0 } }
let n = MersenneTwister.stateCount
let m = n / 2
let a: UInt64 = 0xB5026F5AA96619E9
let lowerMask: UInt64 = (1 << 31) - 1
let upperMask: UInt64 = ~lowerMask
var (i, j, stateM) = (0, m, state[m])
repeat {
let x1 = (state[i] & upperMask) | (state[i &+ 1] & lowerMask)
state[i] = state[i &+ m] ^ (x1 >> 1) ^ ((state[i &+ 1] & 1) &* a)
let x2 = (state[j] & upperMask) | (state[j &+ 1] & lowerMask)
state[j] = state[j &- m] ^ (x2 >> 1) ^ ((state[j &+ 1] & 1) &* a)
(i, j) = (i &+ 1, j &+ 1)
} while i != m &- 1
let x3 = (state[m &- 1] & upperMask) | (stateM & lowerMask)
state[m &- 1] = state[n &- 1] ^ (x3 >> 1) ^ ((stateM & 1) &* a)
let x4 = (state[n &- 1] & upperMask) | (state[0] & lowerMask)
state[n &- 1] = state[m &- 1] ^ (x4 >> 1) ^ ((state[0] & 1) &* a)
index = 0
}
var result = withUnsafePointer(to: &state_internal) { $0.withMemoryRebound(to: UInt64.self, capacity: MersenneTwister.stateCount) { ptr in
return ptr[index]
} }
index = index &+ 1
result ^= (result >> 29) & 0x5555555555555555
result ^= (result << 17) & 0x71D67FFFEDA60000
result ^= (result << 37) & 0xFFF7EEE000000000
result ^= result >> 43
return result
}
}
| mit | b3ee962eb6412c54704a9f72d54609a0 | 38.43617 | 156 | 0.57092 | 3.359616 | false | false | false | false |
cuappdev/podcast-ios | old/Podcast/InternalProfileViewController.swift | 1 | 11501 | //
// InternalProfileViewController.swift
// Podcast
//
// Created by Drew Dunne on 3/7/17.
// Copyright © 2017 Cornell App Development. All rights reserved.
//
import UIKit
enum InternalProfileSetting {
case listeningHistory
case downloads
case facebook
case bookmark
case shared
var title: String {
switch self {
case .listeningHistory:
return "Listening History"
case .downloads:
return "Downloads"
case .bookmark:
return "Saved for Later"
case .facebook:
return "Find Facebook Friends"
case .shared:
return "Shared with You"
}
}
}
class InternalProfileViewController: ViewController {
var settingsTableView: UITableView!
var subscriptionsTableView: UITableView!
var internalProfileHeaderView: InternalProfileHeaderView!
var subscriptions: [Series]?
var headerView: UIView!
var settingItems: [InternalProfileSetting] =
[.listeningHistory, .shared, .downloads]
let reusableCellID = "profileLinkCell"
let reusableSubscriptionCellID = "subscriptionCell"
let sectionSpacing: CGFloat = 18
let headerViewHeight: CGFloat = 59.5
let headerLabelSpacing: CGFloat = 12.5
let headerMarginLeft: CGFloat = 18
let nullStatePadding: CGFloat = 30
var subscriptionTableViewHeight: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .paleGrey
navigationItem.title = "My Library"
internalProfileHeaderView = InternalProfileHeaderView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: InternalProfileHeaderView.height))
internalProfileHeaderView.delegate = self
if let currentUser = System.currentUser {
internalProfileHeaderView.setUser(currentUser)
}
let scrollView = ScrollView(frame: view.frame)
scrollView.showsVerticalScrollIndicator = false
view.addSubview(scrollView)
scrollView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
mainScrollView = scrollView
settingsTableView = UITableView(frame: .zero)
settingsTableView.backgroundColor = .paleGrey
settingsTableView.delegate = self
settingsTableView.dataSource = self
settingsTableView.showsVerticalScrollIndicator = false
settingsTableView.allowsSelection = true // NEED THIS
settingsTableView.alwaysBounceVertical = false
settingsTableView.register(InternalProfileTableViewCell.self, forCellReuseIdentifier: reusableCellID)
settingsTableView.tableHeaderView = internalProfileHeaderView
settingsTableView.separatorInset = .zero
scrollView.add(tableView: settingsTableView)
subscriptionsTableView = UITableView(frame: .zero)
subscriptionsTableView.backgroundColor = .paleGrey
subscriptionsTableView.delegate = self
subscriptionsTableView.dataSource = self
subscriptionsTableView.showsVerticalScrollIndicator = false
subscriptionsTableView.separatorStyle = .none
subscriptionsTableView.alwaysBounceVertical = false
subscriptionsTableView.register(SearchSeriesTableViewCell.self, forCellReuseIdentifier: reusableSubscriptionCellID)
scrollView.add(tableView: subscriptionsTableView)
settingsTableView.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
make.height.equalTo(InternalProfileTableViewCell.height * CGFloat(settingItems.count) + InternalProfileHeaderView.height + sectionSpacing)
}
headerView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: headerViewHeight))
headerView.backgroundColor = .paleGrey
let label = UILabel()
label.text = "Subscriptions"
label.sizeToFit()
label.font = ._14SemiboldFont()
label.textColor = .charcoalGrey
headerView.addSubview(label)
label.snp.makeConstraints { make in
make.bottom.equalToSuperview().inset(headerLabelSpacing)
make.leading.equalToSuperview().inset(headerMarginLeft)
}
remakeSubscriptionTableViewContraints()
}
func remakeSubscriptionTableViewContraints() {
if let subs = subscriptions {
subscriptionTableViewHeight = SearchSeriesTableViewCell.height * CGFloat(subs.count) + headerView.frame.height
// so we can see null state background view
if subs.isEmpty {
subscriptionTableViewHeight = view.frame.height - settingsTableView.frame.maxX - headerView.frame.height
}
subscriptionsTableView.snp.remakeConstraints { make in
make.top.equalTo(settingsTableView.snp.bottom)
make.leading.trailing.equalToSuperview()
make.height.equalTo(subscriptionTableViewHeight)
make.bottom.equalToSuperview()
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchSubscriptions()
}
/// Endpoint Requests - Subscriptions
func fetchSubscriptions() {
guard let userID = System.currentUser?.id else { return }
let subscriptionEndpointRequest = FetchSubscriptionsEndpointRequest(userID: userID)
subscriptionEndpointRequest.success = { (endpointRequest: EndpointRequest) in
guard let subscriptions = endpointRequest.processedResponseValue as? [Series] else { return }
self.subscriptions = subscriptions.sorted { $0.lastUpdated ?? Date.distantPast > $1.lastUpdated ?? Date.distantPast}
self.subscriptionsTableView.reloadData()
self.remakeSubscriptionTableViewContraints()
}
subscriptionEndpointRequest.failure = { _ in }
System.endpointRequestQueue.addOperation(subscriptionEndpointRequest)
}
}
// MARK: InternalProfileHeaderView Delegate
extension InternalProfileViewController: InternalProfileHeaderViewDelegate {
func internalProfileHeaderViewDidPressViewProfile(internalProfileHeaderView: InternalProfileHeaderView) {
guard let currentUser = System.currentUser else { return }
let myProfileViewController = UserDetailViewController(user: currentUser)
navigationController?.pushViewController(myProfileViewController, animated: true)
}
func internalProfileHeaderViewDidPressSettingsButton(internalProfileHeaderView: InternalProfileHeaderView) {
navigationController?.pushViewController(MainSettingsPageViewController(), animated: true)
}
}
// MARK: TableView Delegate
extension InternalProfileViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch tableView {
case settingsTableView:
tableView.deselectRow(at: indexPath, animated: true)
let internalSetting = settingItems[indexPath.row]
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let tabBarController = appDelegate.tabBarController else { return }
switch internalSetting {
case .listeningHistory:
navigationController?.pushViewController(ListeningHistoryViewController(), animated: true)
case .downloads:
let downloadsViewController = DownloadsViewController()
navigationController?.pushViewController(downloadsViewController, animated: true)
case .facebook:
navigationController?.pushViewController(FacebookFriendsViewController(), animated: true)
case .bookmark:
tabBarController.selectedIndex = System.bookmarkTab
break
case .shared:
navigationController?.pushViewController(SharedContentViewController(), animated: true)
}
case subscriptionsTableView:
guard let subs = subscriptions else { return }
if !subs.isEmpty {
if let series = subscriptions?[indexPath.row] {
let seriesDetailViewController = SeriesDetailViewController(series: series)
navigationController?.pushViewController(seriesDetailViewController, animated: true)
}
} else {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let tabBarController = appDelegate.tabBarController else { return }
tabBarController.selectedIndex = System.discoverSearchTab
}
default: break
}
}
}
// MARK: TableView Data Source
extension InternalProfileViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch tableView {
case subscriptionsTableView:
return headerView
default:
return nil
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch tableView {
case settingsTableView:
return settingItems.count
case subscriptionsTableView where subscriptions != nil:
return max(1, subscriptions!.count)
default:
return 0
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch tableView {
case settingsTableView:
return InternalProfileTableViewCell.height
case subscriptionsTableView:
return SearchSeriesTableViewCell.height
default:
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch tableView {
case settingsTableView:
let cell = tableView.dequeueReusableCell(withIdentifier: reusableCellID, for: indexPath) as? InternalProfileTableViewCell ?? InternalProfileTableViewCell()
cell.setTitle(settingItems[indexPath.row].title)
cell.selectionStyle = .gray
return cell
case subscriptionsTableView:
guard let subs = subscriptions else { return UITableViewCell() }
if !subs.isEmpty {
let cell = tableView.dequeueReusableCell(withIdentifier: reusableSubscriptionCellID, for: indexPath) as? SearchSeriesTableViewCell ?? SearchSeriesTableViewCell()
if let series = subscriptions?[indexPath.row] {
cell.configure(for: series, index: indexPath.row, showLastUpdatedText: true)
}
cell.backgroundColor = .offWhite
return cell
}
else {
guard let user = System.currentUser else { return UITableViewCell() }
let cell = NullProfileTableViewCell()
cell.setup(for: user, isMe: true)
return cell
}
default:
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch tableView {
case settingsTableView:
return sectionSpacing
case subscriptionsTableView:
return headerViewHeight
default:
return 0
}
}
}
| mit | 612e6f5538e92814d994f28fc3350f9f | 38.930556 | 177 | 0.671478 | 6.17284 | false | false | false | false |
prebid/prebid-mobile-ios | Example/PrebidDemo/PrebidDemoSwift/Examples/In-App/InAppDisplayBannerViewController.swift | 1 | 1984 | /* Copyright 2019-2022 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import PrebidMobile
fileprivate let storedResponseDisplayBanner = "response-prebid-banner-320-50"
fileprivate let storedImpDisplayBanner = "imp-prebid-banner-320-50"
class InAppDisplayBannerViewController: BannerBaseViewController, BannerViewDelegate {
// Prebid
private var prebidBannerView: BannerView!
override func loadView() {
super.loadView()
Prebid.shared.storedAuctionResponse = storedResponseDisplayBanner
createAd()
}
func createAd() {
// 1. Create a BannerView
prebidBannerView = BannerView(frame: CGRect(origin: .zero, size: adSize), configID: storedImpDisplayBanner, adSize: adSize)
// 2. Configure the BannerView
prebidBannerView.delegate = self
prebidBannerView.adFormat = .display
prebidBannerView.videoParameters.placement = .InBanner
// Add Prebid banner view to the app UI
bannerView.addSubview(prebidBannerView)
// 3. Load the banner ad
prebidBannerView.loadAd()
}
// MARK: - BannerViewDelegate
func bannerViewPresentationController() -> UIViewController? {
self
}
func bannerView(_ bannerView: BannerView, didFailToReceiveAdWith error: Error) {
PrebidDemoLogger.shared.error("Banner view did fail to receive ad with error: \(error)")
}
}
| apache-2.0 | fbaea9c1a2696769a64010e8428f660f | 32.627119 | 131 | 0.702117 | 5.074169 | false | false | false | false |
KyoheiG3/PagingView | PagingViewExample/PagingViewExample/DemoViewController.swift | 1 | 1743 | //
// DemoViewController.swift
// PagingViewExample
//
// Created by Kyohei Ito on 2015/09/03.
// Copyright © 2015年 kyohei_ito. All rights reserved.
//
import UIKit
import PagingView
class DemoViewController: UIViewController {
@IBOutlet weak var pagingView: PagingView!
let imageNames: [String] = ["1", "2", "3", "4", "5"]
override func viewDidLoad() {
super.viewDidLoad()
pagingView.dataSource = self
pagingView.delegate = self
pagingView.pagingMargin = 10
pagingView.pagingInset = 30
let nib = UINib(nibName: "DemoViewCell", bundle: nil)
pagingView.registerNib(nib, forCellWithReuseIdentifier: "DemoViewCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension DemoViewController: PagingViewDataSource, PagingViewDelegate, UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let centerCell = pagingView.visibleCenterCell() {
let imageName = imageNames[centerCell.indexPath.item]
title = imageName
}
}
func pagingView(_ pagingView: PagingView, numberOfItemsInSection section: Int) -> Int {
return imageNames.count
}
func pagingView(_ pagingView: PagingView, cellForItemAtIndexPath indexPath: IndexPath) -> PagingViewCell {
let cell = pagingView.dequeueReusableCellWithReuseIdentifier("DemoViewCell")
if let cell = cell as? DemoViewCell {
let imageName = imageNames[indexPath.item]
cell.imageView.image = UIImage(named: imageName)
}
return cell
}
}
| mit | 6a920294469387886eea51a106ac7823 | 30.071429 | 110 | 0.663793 | 5.209581 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Services/Stories/StoryPoster.swift | 2 | 6339 | import Foundation
import UIKit
import WordPressKit
import AutomatticTracks
/// A type representing the Story block
struct Story: Codable {
let mediaFiles: [MediaFile]
}
/// The contents of a Story block
struct MediaFile: Codable {
let alt: String
let caption: String
let id: String
let link: String
let mime: String
let type: String
let url: String
init(alt: String,
caption: String,
id: String,
link: String,
mime: String,
type: String,
url: String) {
self.alt = alt
self.caption = caption
self.id = id
self.link = link
self.mime = mime
self.type = type
self.url = url
}
init(dictionary: [String: Any]) throws {
// We must handle both possible types because the Gutenberg `replaceBlock` method seems to be changing the type of this field.
let id: String
do {
id = try dictionary.value(key: CodingKeys.id.stringValue, type: NSNumber.self).stringValue
} catch {
id = try dictionary.value(key: CodingKeys.id.stringValue, type: String.self)
}
self.init(alt: try dictionary.value(key: CodingKeys.alt.stringValue, type: String.self),
caption: try dictionary.value(key: CodingKeys.caption.stringValue, type: String.self),
id: id,
link: try dictionary.value(key: CodingKeys.link.stringValue, type: String.self),
mime: try dictionary.value(key: CodingKeys.mime.stringValue, type: String.self),
type: try dictionary.value(key: CodingKeys.type.stringValue, type: String.self),
url: try dictionary.value(key: CodingKeys.url.stringValue, type: String.self))
}
static func file(from dictionary: [String: Any]) -> MediaFile? {
do {
return try self.init(dictionary: dictionary)
} catch let error {
DDLogWarn("MediaFile error: \(error)")
return nil
}
}
}
extension Dictionary where Key == String, Value == Any {
enum ValueError: Error, CustomDebugStringConvertible {
case missingKey(String)
case wrongType(String, Any)
var debugDescription: String {
switch self {
case Dictionary.ValueError.missingKey(let key):
return "Dictionary is missing key: \(key)"
case Dictionary.ValueError.wrongType(let key, let value):
return "Dictionary has wrong type for \(key): \(type(of: value))"
}
}
}
func value<T: Any>(key: String, type: T.Type) throws -> T {
let value = self[key]
if let castValue = value as? T {
return castValue
} else {
if let value = value {
throw ValueError.wrongType(key, value)
} else {
throw ValueError.missingKey(key)
}
}
}
}
class StoryPoster {
struct MediaItem {
let url: URL
let size: CGSize
let archive: URL?
let original: URL?
var mimeType: String {
return url.mimeType
}
}
let context: NSManagedObjectContext
private let oldMediaFiles: [MediaFile]?
init(context: NSManagedObjectContext, mediaFiles: [MediaFile]?) {
self.context = context
self.oldMediaFiles = mediaFiles
}
/// Uploads media to a post and updates the post contents upon completion.
/// - Parameters:
/// - mediaItems: The media items to upload.
/// - post: The post to add media items to.
/// - completion: Called on completion with the new post or an error.
/// - Returns: `(String, [Media])` A tuple containing the Block which was added to contain the media and the new uploading Media objects will be returned.
func add(mediaItems: [MediaItem], post: AbstractPost) throws -> (String, [Media]) {
let assets = mediaItems.map { item in
return item.url as ExportableAsset
}
// Uploades the media and notifies upong completion with the updated post.
let media = PostCoordinator.shared.add(assets: assets, to: post).compactMap { return $0 }
// Update set of `MediaItem`s with values from the new added uploading `Media`.
let mediaFiles: [MediaFile] = media.enumerated().map { (idx, media) -> MediaFile in
let item = mediaItems[idx]
return MediaFile(alt: media.alt ?? "",
caption: media.caption ?? "",
id: String(media.gutenbergUploadID),
link: media.remoteURL ?? "",
mime: item.mimeType,
type: String(item.mimeType.split(separator: "/").first ?? ""),
url: item.archive?.absoluteString ?? "")
}
let story = Story(mediaFiles: mediaFiles)
let encoder = JSONEncoder()
let json = String(data: try encoder.encode(story), encoding: .utf8)
let block = StoryBlock.wrap(json ?? "", includeFooter: true)
return (block, media)
}
static var filePath: URL? = {
do {
let media = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("KanvasMedia")
try FileManager.default.createDirectory(at: media, withIntermediateDirectories: true, attributes: nil)
return media
} catch let error {
assertionFailure("Failed to create media file path: \(error)")
return nil
}
}()
}
struct StoryBlock {
private static let openTag = "<!-- wp:jetpack/story"
private static let closeTag = "-->"
private static let footer = """
<div class="wp-story wp-block-jetpack-story"></div>
<!-- /wp:jetpack/story -->
"""
/// Wraps the JSON of a Story into a story block.
/// - Parameter json: The JSON string to wrap in a story block.
/// - Returns: The string containing the full Story block.
static func wrap(_ json: String, includeFooter: Bool) -> String {
let content = """
\(openTag)
\(json)
\(closeTag)
\(includeFooter ? footer : "")
"""
return content
}
}
| gpl-2.0 | e4b70de76f974b2939f3d97e6c66591e | 34.216667 | 171 | 0.589367 | 4.600145 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Plans/PlanComparisonViewController.swift | 2 | 1661 | import UIKit
import Gridicons
import WordPressShared
class PlanComparisonViewController: PagedViewController {
let initialPlan: Plan
let plans: [Plan]
let features: [PlanFeature]
// Keep a more specific reference to the view controllers rather than force
// downcast viewControllers.
fileprivate let detailViewControllers: [PlanDetailViewController]
lazy fileprivate var cancelXButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: .gridicon(.cross), style: .plain, target: self, action: #selector(PlanComparisonViewController.closeTapped))
button.accessibilityLabel = NSLocalizedString("Close", comment: "Dismiss the current view")
return button
}()
init(plans: [Plan], initialPlan: Plan, features: [PlanFeature]) {
self.initialPlan = initialPlan
self.plans = plans
self.features = features
let controllers: [PlanDetailViewController] = plans.map({ plan in
let controller = PlanDetailViewController.controllerWithPlan(plan, features: features)
return controller
})
self.detailViewControllers = controllers
let initialIndex = plans.firstIndex { plan in
return plan == initialPlan
}
super.init(viewControllers: controllers, initialIndex: initialIndex!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBAction func closeTapped() {
dismiss(animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = cancelXButton
}
}
| gpl-2.0 | 58196941c44aed1e7a9fb1c1dafe939d | 30.339623 | 152 | 0.686334 | 5.340836 | false | false | false | false |
burhanaksendir/SwiftWebVC | SwiftWebVC/SwiftModalWebVC.swift | 1 | 2917 | //
// SwiftModalWebVC.swift
//
// Created by Myles Ringle on 24/06/2015.
// Transcribed from code used in SVWebViewController.
// Copyright (c) 2015 Myles Ringle & Oliver Letterer. All rights reserved.
//
import UIKit
class SwiftModalWebVC: UINavigationController {
weak var webViewDelegate: UIWebViewDelegate? = nil
var webViewController: SwiftWebVC!
convenience init(urlString: String) {
self.init(pageURL: NSURL(string: urlString)!, theme: "Light-Blue")
}
convenience init(urlString: String, theme: String) {
self.init(pageURL: NSURL(string: urlString)!, theme: theme)
}
convenience init(pageURL: NSURL) {
self.init(request: NSURLRequest(URL: pageURL), theme: "Light-Blue")
}
convenience init(pageURL: NSURL, theme: String) {
self.init(request: NSURLRequest(URL: pageURL), theme: theme)
}
init(request: NSURLRequest, theme: String) {
webViewController = SwiftWebVC(aRequest: request)
webViewController.storedStatusColor = UINavigationBar.appearance().barStyle
var doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done,
target: webViewController,
action: Selector("doneButtonTapped:"))
switch theme {
case "Light-Black":
doneButton.tintColor = UIColor.darkGrayColor()
webViewController.buttonColor = UIColor.darkGrayColor()
webViewController.titleColor = UIColor.blackColor()
UINavigationBar.appearance().barStyle = UIBarStyle.Default
case "Dark":
doneButton.tintColor = UIColor.whiteColor()
webViewController.buttonColor = UIColor.whiteColor()
webViewController.titleColor = UIColor.groupTableViewBackgroundColor()
UINavigationBar.appearance().barStyle = UIBarStyle.Black
default:
doneButton.tintColor = nil
webViewController.buttonColor = nil
webViewController.titleColor = UIColor.blackColor()
UINavigationBar.appearance().barStyle = UIBarStyle.Default
}
if (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad) {
webViewController.navigationItem.leftBarButtonItem = doneButton
}
else {
webViewController.navigationItem.rightBarButtonItem = doneButton
}
super.init(rootViewController: webViewController)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(false)
}
}
| mit | dced05b0da2b802117294daeb784f688 | 36.397436 | 89 | 0.653754 | 5.609615 | false | false | false | false |
aaaddress1/isuBot-in-Swift | IsuApp/IsuApp/AppDelegate.swift | 1 | 7779 | //
// AppDelegate.swift
// IsuApp
//
// Created by 馬聖豪 on 2015/9/30.
// Copyright © 2015年 adr. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
return true;
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "adr.IsuApp" in the user's Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)
let appSupportURL = urls[urls.count - 1]
return appSupportURL.URLByAppendingPathComponent("adr.IsuApp")
}()
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("IsuApp", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.) This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
let fileManager = NSFileManager.defaultManager()
var failError: NSError? = nil
var shouldFail = false
var failureReason = "There was an error creating or loading the application's saved data."
// Make sure the application files directory is there
do {
let properties = try self.applicationDocumentsDirectory.resourceValuesForKeys([NSURLIsDirectoryKey])
if !properties[NSURLIsDirectoryKey]!.boolValue {
failureReason = "Expected a folder to store application data, found a file \(self.applicationDocumentsDirectory.path)."
shouldFail = true
}
} catch {
let nserror = error as NSError
if nserror.code == NSFileReadNoSuchFileError {
do {
try fileManager.createDirectoryAtPath(self.applicationDocumentsDirectory.path!, withIntermediateDirectories: true, attributes: nil)
} catch {
failError = nserror
}
} else {
failError = nserror
}
}
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = nil
if failError == nil {
coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CocoaAppCD.storedata")
do {
try coordinator!.addPersistentStoreWithType(NSXMLStoreType, configuration: nil, URL: url, options: nil)
} catch {
failError = error as NSError
}
}
if shouldFail || (failError != nil) {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
if failError != nil {
dict[NSUnderlyingErrorKey] = failError
}
let error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSApplication.sharedApplication().presentError(error)
abort()
} else {
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
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving and Undo support
@IBAction func saveAction(sender: AnyObject!) {
// Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user.
if !managedObjectContext.commitEditing() {
NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving")
}
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
NSApplication.sharedApplication().presentError(nserror)
}
}
}
func windowWillReturnUndoManager(window: NSWindow) -> NSUndoManager? {
// Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application.
return managedObjectContext.undoManager
}
func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
// Save changes in the application's managed object context before the application terminates.
if !managedObjectContext.commitEditing() {
NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing to terminate")
return .TerminateCancel
}
if !managedObjectContext.hasChanges {
return .TerminateNow
}
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
// Customize this code block to include application-specific recovery steps.
let result = sender.presentError(nserror)
if (result) {
return .TerminateCancel
}
let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message")
let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info");
let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title")
let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title")
let alert = NSAlert()
alert.messageText = question
alert.informativeText = info
alert.addButtonWithTitle(quitButton)
alert.addButtonWithTitle(cancelButton)
let answer = alert.runModal()
if answer == NSAlertFirstButtonReturn {
return .TerminateCancel
}
}
// If we got here, it is time to quit.
return .TerminateNow
}
}
| gpl-2.0 | 4ba26ecd67b25115357e068e6b683438 | 44.705882 | 347 | 0.655856 | 6.037296 | false | false | false | false |
onevcat/Hedwig | Sources/Mail.swift | 1 | 8801 | //
// Mail.swift
// Hedwig
//
// Created by Wei Wang on 2016/12/31.
//
// Copyright (c) 2017 Wei Wang <[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 Foundation
import AddressParser
/// Possible errors when validating the mail before sending.
///
/// - noSender: The `FROM` field of the mail is not valid or empty.
/// - noRecipient: The `TO`, `CC` and `BCC` fields of the mail is not valid or
/// empty.
public enum MailError: Error {
/// The `FROM` field of the mail is not valid or empty.
case noSender
/// The `TO`, `CC` and `BCC` fields of the mail is not valid or empty.
case noRecipient
}
/// Represents an email. It contains necessary information like `from`, `to` and
/// `text` with which Hedwig could send it with a connection to some SMTP server.
/// The whole type is immutable. You need to create a mail through the initialzer
/// and then feed it to a `Hedwig` instance to send.
public struct Mail {
/// From name and address.
public let from: NameAddressPair?
/// To names and addresses.
public let to: [NameAddressPair]
/// Carbon copy (Cc) names and addresses.
public let cc: [NameAddressPair]?
/// Blind carbon copy (Bcc) names and addresses.
public let bcc: [NameAddressPair]?
/// The title of current email.
public let subject: String
/// The text content of current email.
public let text: String
/// The attachements contained in the email.
public let attachments: [Attachment]
/// The additional headers will be presented in the mail header.
public let additionalHeaders: [String: String]
/// The alternative attachement. The last alternative attachment in
/// `attachments` will be the `alternative` attachement of the whole `Mail`.
public let alternative: Attachment?
/// Message id. It is a UUID string appeneded by `.Hedwig`.
public let messageId = UUID().uuidString + ".Hedwig"
/// Creating date of the mail.
public let date = Date()
/// Initilize an email.
///
/// - Parameters:
/// - text: The plain text of the mail.
/// - from: From name and address.
/// - to: To names and addresses.
/// - cc: Carbon copy (Cc) names and addresses. Default is `nil`.
/// - bcc: Blind carbon copy (Bcc) names and addresses. Default is `nil`.
/// - subject: Subject (title) of the email. Default is empty string.
/// - attachments: Attachements of the mail.
/// - additionalHeaders: Additional headers when sending the mail.
///
/// - Note:
/// - The `from`, `to`, `cc` and `bcc` parameters accept a email specified
/// string as input. Hedwig will try to parse the string and get email
/// addresses. You can find supported string format
/// [here](https://github.com/onevcat/AddressParser).
/// - If you need to customize the mail header field, pass it with
/// `additionalHeaders`.
///
public init(text: String,
from: String,
to: String,
cc: String? = nil,
bcc: String? = nil,
subject: String = "",
attachments: [Attachment]? = nil,
additionalHeaders: [String: String] = [:])
{
self.from = from.parsedAddresses.last
self.to = to.parsedAddresses
self.cc = cc?.parsedAddresses
self.bcc = bcc?.parsedAddresses
self.text = text
self.subject = subject
if let attachments = attachments {
let result = attachments.takeLast { $0.isAlternative }
self.alternative = result.0
self.attachments = result.1
} else {
self.alternative = nil
self.attachments = []
}
self.additionalHeaders = additionalHeaders
}
var hasSender: Bool {
return from != nil
}
var hasRecipient: Bool {
let noCc = self.cc?.isEmpty ?? true
let noBcc = self.bcc?.isEmpty ?? true
let noRecipient = to.isEmpty && noCc && noBcc
return !noRecipient
}
}
extension Mail {
private var headers: [String: String] {
var fields = [String: String]()
fields["MESSAGE-ID"] = messageId
fields["DATE"] = date.smtpFormatted
fields["FROM"] = from?.mime ?? ""
fields["TO"] = to.map { $0.mime }.joined(separator: ", ")
if let cc = cc {
fields["CC"] = cc.map { $0.mime }.joined(separator: ", ")
}
fields["SUBJECT"] = subject.mimeEncoded ?? ""
fields["MIME-VERSION"] = "1.0 (Hedwig)"
for (key, value) in additionalHeaders {
fields[key.uppercased()] = value
}
return fields
}
var headersString: String {
return headers.map { (key, value) in
return "\(key): \(value)"
}.joined(separator: CRLF)
}
var hasAttachment: Bool {
return alternative != nil || !attachments.isEmpty
}
}
/// Name and address used in mail "From", "To", "Cc" and "Bcc" fields.
public struct NameAddressPair {
/// The name of the person. It will be an empty string if no name could be
/// extracted.
public let name: String
/// The email address of the person.
public let address: String
init(name: String, address: String) {
self.name = name
self.address = address
}
var mime: String {
if name.isEmpty {
return address
}
if let nameEncoded = name.mimeEncoded {
return "\(nameEncoded) <\(address)>"
} else {
return address
}
}
}
extension Address {
var allMails: [NameAddressPair] {
var result = [NameAddressPair]()
switch entry {
case .mail(let address):
result.append(NameAddressPair(name: name, address: address))
case .group(let addresses):
let converted = addresses.flatMap { return $0.allMails }
result.append(contentsOf: converted)
}
return result
}
}
extension String {
var parsedAddresses: [NameAddressPair] {
return AddressParser.parse(self).flatMap { $0.allMails }
}
}
extension String {
// A simple but maybe not fully compatible with RFC 2047
// https://tools.ietf.org/html/rfc2047
var mimeEncoded: String? {
guard let encoded = addingPercentEncoding(
withAllowedCharacters: .urlQueryAllowed) else {
return nil
}
let quoted = encoded
.replacingOccurrences(of: "%20", with: "_")
.replacingOccurrences(of: ",", with: "%2C")
.replacingOccurrences(of: "%", with: "=")
return "=?UTF-8?Q?\(quoted)?="
}
}
extension DateFormatter {
static let smtpDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en-US")
formatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss ZZZ"
return formatter
}()
}
extension Date {
var smtpFormatted: String {
return DateFormatter.smtpDateFormatter.string(from: self)
}
}
extension Array {
func takeLast(where condition: (Element) -> Bool) -> (Element?, Array) {
var index: Int? = nil
for i in (0 ..< count).reversed() {
if condition(self[i]) {
index = i
break
}
}
if let index = index {
var array = self
let ele = array.remove(at: index)
return (ele, array)
} else {
return (nil, self)
}
}
}
| mit | 20b40fe6d23249755872fb966c81a730 | 30.772563 | 81 | 0.600045 | 4.37643 | false | false | false | false |
jainanisha90/codepath_Twitter | Twitter/TweetDetailsViewController.swift | 1 | 4240 | //
// TweetDetailsViewController.swift
// Twitter
//
// Created by Anisha Jain on 4/16/17.
// Copyright © 2017 Anisha Jain. All rights reserved.
//
import UIKit
import MBProgressHUD
class TweetDetailsViewController: UIViewController {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var tweetTextLabel: UILabel!
@IBOutlet weak var screenNameLabel: UILabel!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var retweetCountLabel: UILabel!
@IBOutlet weak var favoriteCountLabel: UILabel!
@IBOutlet weak var favoriteButton: UIButton!
var tweet: Tweet?
override func viewDidLoad() {
super.viewDidLoad()
profileImageView.layer.cornerRadius = 3
profileImageView.clipsToBounds = true
favoriteButton.setImage(#imageLiteral(resourceName: "favorite"), for: UIControlState.normal)
favoriteButton.setImage(#imageLiteral(resourceName: "favoriteSelected"), for: UIControlState.selected)
profileImageView.setImageWith((tweet?.user?.profileImageUrl)!)
userNameLabel.text = tweet?.user?.name
screenNameLabel.text = tweet?.user?.screenName
tweetTextLabel.text = tweet?.text
retweetCountLabel.text = String(describing: tweet!.retweetCount!)
favoriteCountLabel.text = String(describing: tweet!.favoriteCount!)
timestampLabel.text = tweet?.timeStamp
favoriteButton.isSelected = tweet!.favorited
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onReplyButton(_ sender: Any) {
print("Reply button tapped")
}
@IBAction func onRetweetButton(_ sender: Any) {
let tweetId = tweet!.tweetId!
MBProgressHUD.showAdded(to: self.view, animated: true)
TwitterClient.sharedInstance.retweet(tweetId: tweetId, success: {
// Updating local retweet count when retweet API return success
self.retweetCountLabel.text = String(describing: (self.tweet!.retweetCount! + 1))
MBProgressHUD.hide(for: self.view, animated: true)
NotificationCenter.default.post(name: reloadHomeTimeline, object: nil)
}, failure: { (error) in
print("Error during posting a tweet", error)
MBProgressHUD.hide(for: self.view, animated: true)
})
}
@IBAction func onFavoriteButton(_ sender: Any) {
let tweetId = tweet!.tweetId!
print("tweetID: \(tweetId)")
let isFavorite = sender as! UIButton
isFavorite.isSelected = !(isFavorite.isSelected)
if isFavorite.isSelected {
TwitterClient.sharedInstance.createFavorite(tweetId: tweetId, success: {
// Updating local favorite count when favorite API return success
self.tweet?.favoriteCount = self.tweet!.favoriteCount! + 1
self.favoriteCountLabel.text = String(describing: self.tweet!.favoriteCount!)
NotificationCenter.default.post(name: reloadHomeTimeline, object: nil)
}, failure: { (error) in
print("Error during posting a tweet", error)
})
} else {
TwitterClient.sharedInstance.removeFavorite(tweetId: tweetId, success: {
self.tweet?.favoriteCount = self.tweet!.favoriteCount! - 1
self.favoriteCountLabel.text = String(describing: self.tweet!.favoriteCount!)
NotificationCenter.default.post(name: reloadHomeTimeline, object: nil)
}, failure: { (error) in
print("Error during posting a tweet", error)
})
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "replyFromDetailSegue" {
let navigationController = segue.destination as! UINavigationController
let rvc = navigationController.topViewController as! ReplyViewController
rvc.tweet = tweet
}
}
}
| mit | efaec799394f2eea8d38f56f6228b39f | 39.759615 | 110 | 0.652276 | 5.292135 | false | false | false | false |
meshangqingchen/LCCDouYuZB | DDYYZZBB/DDYYZZBB/Classes/Tools/Common.swift | 1 | 340 | //
// Common.swift
// DDYYZZBB
//
// Created by 3D on 16/11/28.
// Copyright © 2016年 3D. All rights reserved.
//
import UIKit
let kStatusBarH : CGFloat = 20
let kNavigationBarH : CGFloat = 44
let kTabbarH : CGFloat = 49
let kScreenW : CGFloat = UIScreen.main.bounds.width
let kScreenH : CGFloat = UIScreen.main.bounds.height
| mit | eb455aeee3e7a6ecfdb989e1865319ee | 16.736842 | 52 | 0.697329 | 3.40404 | false | false | false | false |
sunkanmi-akintoye/todayjournal | weather-journal/AppDelegate.swift | 1 | 3617 | //
// AppDelegate.swift
// weather-journal
//
// Created by Luke Geiger on 6/29/15.
// Copyright (c) 2015 Luke J Geiger. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let feedVC = PostFeedTableViewController(style:UITableViewStyle.Grouped);
let feedNavVC = UINavigationController(rootViewController: feedVC)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = feedNavVC
self.window?.makeKeyAndVisible()
self.parse()
self.appearance()
return true
}
func parse(){
// Initialize Parse.
Parse.enableLocalDatastore()
Parse.setApplicationId("bh4nFLofME26mZkgykMiMMrbI3JSZBBYN5QGBFLb",
clientKey: "wdghvXEe1o9ZCH5OdedU2krD5qk7zi5v7BeC5ema")
Post.registerSubclass()
}
func appearance(){
var navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.titleTextAttributes = [NSFontAttributeName:UIFont.boldAppFontOfSize(16)]
var barButtonApperance = UIBarButtonItem.appearance()
barButtonApperance.setTitleTextAttributes( [NSFontAttributeName:UIFont.appFontOfSize(16),
NSForegroundColorAttributeName:UIColor.appBlueColor()]
,forState: UIControlState.Normal)
// NSDictionary *barFont = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor hmDeepBlueColor], NSForegroundColorAttributeName,[UIFont hmFont:14], NSFontAttributeName, nil];
// [[UIBarButtonItem appearance] setTitleTextAttributes:barFont forState:
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 7bc4ea4da00a0943dfe2a8206c497028 | 44.78481 | 285 | 0.709704 | 5.51372 | false | false | false | false |
joemcbride/outlander-osx | src/Outlander/Scripting/TriggerHandler.swift | 1 | 2995 | //
// TriggerHandler.swift
// Outlander
//
// Created by Joseph McBride on 6/7/15.
// Copyright (c) 2015 Joe McBride. All rights reserved.
//
import Foundation
@objc
class TriggerHandler : NSObject, ISubscriber {
class func newInstance(context:GameContext, relay:CommandRelay) -> TriggerHandler {
return TriggerHandler(context: context, relay: relay)
}
let context:GameContext
let relay:CommandRelay
var subId:String?
init(context:GameContext, relay:CommandRelay) {
self.context = context
self.relay = relay
super.init()
self.subId = context.events.subscribe(self, token: "ol:game-parse")
}
func unsubscribe() {
if let subId = self.subId {
self.context.events.unSubscribe(subId)
}
}
func handle(token:String, data:Dictionary<String, AnyObject>) {
if let dict = data as? [String:String] {
let text = dict["text"] ?? ""
if text.characters.count > 0 {
self.checkTriggers(text, context: self.context)
}
}
}
func handle(nodes:[Node], text:String, context:GameContext) {
self.checkTriggers(text, context: context)
}
func checkTriggers(text:String, context:GameContext) {
let disabledClasses = context.classSettings.disabled()
let triggers = context.triggers.filter(NSPredicate { (obj, _) in
let trig = obj as! Trigger
if let c = trig.actionClass {
return !disabledClasses.contains(c.lowercaseString)
}
return true
})
for object in triggers {
let trigger = object as! Trigger
if let triggerText = trigger.trigger {
if let groups = text[triggerText].groups() {
if groups.count > 0 {
let command = self.replaceWithGroups(trigger.action ?? "", groups:groups)
let commands = command.splitToCommands()
for c in commands {
let commandContext = CommandContext()
commandContext.command = c
self.relay.sendCommand(commandContext)
}
}
}
}
}
}
private func replaceWithGroups(input:String, groups:[String]) -> String {
var vars = [String:String]()
for (index, param) in groups.enumerate() {
vars["\(index)"] = param
}
let mutable = RegexMutable(input)
self.replace("\\$", target: mutable, dict: vars)
return mutable as String
}
private func replace(prefix:String, target:NSMutableString, dict:[String:String]) {
for key in dict.keys {
target["\(prefix)\(key)"] ~= dict[key] ?? ""
}
}
}
| mit | 1d3ecb7ec5b67be1312003a3f4b97336 | 28.07767 | 97 | 0.535893 | 4.738924 | false | false | false | false |
seanperez29/GifMaker_PortingObjC | GifMaker_Swift_Template/GifEditorViewController.swift | 1 | 3612 | //
// GifEditorViewController.swift
// GifMaker_Swift_Template
//
// Created by Sean Perez on 10/10/16.
// Copyright © 2016 Gabrielle Miller-Messner. All rights reserved.
//
import UIKit
class GifEditorViewController: UIViewController {
@IBOutlet weak var gifImageView: UIImageView!
@IBOutlet weak var captionTextField: UITextField!
var gif: Gif?
override func viewDidLoad() {
super.viewDidLoad()
captionTextField.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let gif = gif {
gifImageView.image = gif.gifImage
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func presentPreview() {
guard let gif = gif else {
return
}
let previewVC = storyboard?.instantiateViewController(withIdentifier: "GifEditorViewController") as! GifEditorViewController
let regift = Regift(sourceFileURL: gif.videoURL, frameCount: frameCount, delayTime: delayCount, loopCount: loopCount)
let captionFont = captionTextField.font
let gifURL = regift.createGif(caption: captionTextField.text, font: captionFont)
let newGif = Gif(url: gifURL!, videoURL: gif.videoURL, caption: captionTextField.text)
previewVC.gif = newGif
navigationController?.pushViewController(previewVC, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension GifEditorViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
captionTextField.placeholder = ""
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
captionTextField.resignFirstResponder()
return true
}
}
extension GifEditorViewController {
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(GifEditorViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(GifEditorViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func unsubscribeToKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(notification: Notification) {
if view.frame.origin.y >= 0 {
view.frame.origin.y -= getKeyboardHeight(notification: notification)
}
}
func keyboardWillHide(notification: Notification) {
if (self.view.frame.origin.y < 0) {
view.frame.origin.y += getKeyboardHeight(notification: notification)
}
}
func getKeyboardHeight(notification: Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
}
| mit | 1a73dc89afe8336f02909c12e1c34c6b | 36.226804 | 189 | 0.701191 | 5.294721 | false | false | false | false |
jwalapr/Routing | Source/Routable.swift | 1 | 2313 | import Foundation
public protocol RouteOwner: class {}
public typealias RouteUUID = String
public typealias Parameters = [String: String]
/**
The closure type associated with #map
- Parameter Parameters: Any query parameters or dynamic segments found in the URL
- Parameter Any: Any data that could be passed with a routing
- Parameter Completed: Must be called for Routing to continue processing other routes with #open
*/
public typealias RouteHandler = (String, Parameters, Any?, @escaping Completed) -> Void
public typealias Completed = () -> Void
/**
The closure type associated with #proxy
- Parameter String: The route being opened
- Parameter Parameters: Any query parameters or dynamic segments found in the URL
- Parameter Any: Any data that could be passed with a routing
- Parameter Next: Must be called for Routing to continue processing. Calling #Next with
nil arguments will continue executing other matching proxies. Calling #Next with non nil
arguments will continue to process the route.
*/
public typealias ProxyHandler = (String, Parameters, Any?, @escaping Next) -> Void
public typealias ProxyCommit = (route: String, parameters: Parameters, data: Any?)
public typealias Next = (ProxyCommit?) -> Void
internal typealias Route = Routable<RouteHandler>
internal typealias Proxy = Routable<ProxyHandler>
internal struct Routable<T> {
let uuid = { UUID().uuidString }()
let pattern: String
let tags: [String]
weak var owner: RouteOwner?
let queue: DispatchQueue
let handler: T
let dynamicSegments: [String]
init(_ pattern: String, tags: [String], owner: RouteOwner, queue: DispatchQueue, handler: T) {
var pattern = pattern
var dynamicSegments = [String]()
let options: NSString.CompareOptions = [.regularExpression, .caseInsensitive]
while let range = pattern.range(of: ":[a-zA-Z0-9-_]+", options: options) {
dynamicSegments.append(String(pattern[pattern.index(range.lowerBound, offsetBy: 1)..<range.upperBound]))
pattern.replaceSubrange(range, with: "([^/]+)")
}
self.pattern = pattern
self.tags = tags
self.owner = owner
self.queue = queue
self.handler = handler
self.dynamicSegments = dynamicSegments
}
}
| mit | 28b018852b4ed8c8725a0dd091718eb7 | 36.918033 | 116 | 0.707739 | 4.60757 | false | false | false | false |
nathawes/swift | stdlib/public/core/CompilerProtocols.swift | 7 | 40821 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Intrinsic protocols shared with the compiler
//===----------------------------------------------------------------------===//
/// A type that can be converted to and from an associated raw value.
///
/// With a `RawRepresentable` type, you can switch back and forth between a
/// custom type and an associated `RawValue` type without losing the value of
/// the original `RawRepresentable` type. Using the raw value of a conforming
/// type streamlines interoperation with Objective-C and legacy APIs and
/// simplifies conformance to other protocols, such as `Equatable`,
/// `Comparable`, and `Hashable`.
///
/// The `RawRepresentable` protocol is seen mainly in two categories of types:
/// enumerations with raw value types and option sets.
///
/// Enumerations with Raw Values
/// ============================
///
/// For any enumeration with a string, integer, or floating-point raw type, the
/// Swift compiler automatically adds `RawRepresentable` conformance. When
/// defining your own custom enumeration, you give it a raw type by specifying
/// the raw type as the first item in the enumeration's type inheritance list.
/// You can also use literals to specify values for one or more cases.
///
/// For example, the `Counter` enumeration defined here has an `Int` raw value
/// type and gives the first case a raw value of `1`:
///
/// enum Counter: Int {
/// case one = 1, two, three, four, five
/// }
///
/// You can create a `Counter` instance from an integer value between 1 and 5
/// by using the `init?(rawValue:)` initializer declared in the
/// `RawRepresentable` protocol. This initializer is failable because although
/// every case of the `Counter` type has a corresponding `Int` value, there
/// are many `Int` values that *don't* correspond to a case of `Counter`.
///
/// for i in 3...6 {
/// print(Counter(rawValue: i))
/// }
/// // Prints "Optional(Counter.three)"
/// // Prints "Optional(Counter.four)"
/// // Prints "Optional(Counter.five)"
/// // Prints "nil"
///
/// Option Sets
/// ===========
///
/// Option sets all conform to `RawRepresentable` by inheritance using the
/// `OptionSet` protocol. Whether using an option set or creating your own,
/// you use the raw value of an option set instance to store the instance's
/// bitfield. The raw value must therefore be of a type that conforms to the
/// `FixedWidthInteger` protocol, such as `UInt8` or `Int`. For example, the
/// `Direction` type defines an option set for the four directions you can
/// move in a game.
///
/// struct Directions: OptionSet {
/// let rawValue: UInt8
///
/// static let up = Directions(rawValue: 1 << 0)
/// static let down = Directions(rawValue: 1 << 1)
/// static let left = Directions(rawValue: 1 << 2)
/// static let right = Directions(rawValue: 1 << 3)
/// }
///
/// Unlike enumerations, option sets provide a nonfailable `init(rawValue:)`
/// initializer to convert from a raw value, because option sets don't have an
/// enumerated list of all possible cases. Option set values have
/// a one-to-one correspondence with their associated raw values.
///
/// In the case of the `Directions` option set, an instance can contain zero,
/// one, or more of the four defined directions. This example declares a
/// constant with three currently allowed moves. The raw value of the
/// `allowedMoves` instance is the result of the bitwise OR of its three
/// members' raw values:
///
/// let allowedMoves: Directions = [.up, .down, .left]
/// print(allowedMoves.rawValue)
/// // Prints "7"
///
/// Option sets use bitwise operations on their associated raw values to
/// implement their mathematical set operations. For example, the `contains()`
/// method on `allowedMoves` performs a bitwise AND operation to check whether
/// the option set contains an element.
///
/// print(allowedMoves.contains(.right))
/// // Prints "false"
/// print(allowedMoves.rawValue & Directions.right.rawValue)
/// // Prints "0"
public protocol RawRepresentable {
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
associatedtype RawValue
/// Creates a new instance with the specified raw value.
///
/// If there is no value of the type that corresponds with the specified raw
/// value, this initializer returns `nil`. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// print(PaperSize(rawValue: "Legal"))
/// // Prints "Optional("PaperSize.Legal")"
///
/// print(PaperSize(rawValue: "Tabloid"))
/// // Prints "nil"
///
/// - Parameter rawValue: The raw value to use for the new instance.
init?(rawValue: RawValue)
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
var rawValue: RawValue { get }
}
/// Returns a Boolean value indicating whether the two arguments are equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // trivial-implementation
public func == <T: RawRepresentable>(lhs: T, rhs: T) -> Bool
where T.RawValue: Equatable {
return lhs.rawValue == rhs.rawValue
}
/// Returns a Boolean value indicating whether the two arguments are not equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // trivial-implementation
public func != <T: RawRepresentable>(lhs: T, rhs: T) -> Bool
where T.RawValue: Equatable {
return lhs.rawValue != rhs.rawValue
}
// This overload is needed for ambiguity resolution against the
// implementation of != for T: Equatable
/// Returns a Boolean value indicating whether the two arguments are not equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // trivial-implementation
public func != <T: Equatable>(lhs: T, rhs: T) -> Bool
where T: RawRepresentable, T.RawValue: Equatable {
return lhs.rawValue != rhs.rawValue
}
// Ensure that any RawRepresentable types that conform to Hashable without
// providing explicit implementations get hashing that's consistent with the ==
// definition above. (Compiler-synthesized hashing is based on stored properties
// rather than rawValue; the difference is subtle, but it can be fatal.)
extension RawRepresentable where RawValue: Hashable, Self: Hashable {
@inlinable // trivial
public var hashValue: Int {
return rawValue.hashValue
}
@inlinable // trivial
public func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
@inlinable // trivial
public func _rawHashValue(seed: Int) -> Int {
// In 5.0, this used to return rawValue._rawHashValue(seed: seed). This was
// slightly faster, but it interfered with conforming types' ability to
// customize their hashing. The current definition is equivalent to the
// default implementation; however, we need to keep the definition to remain
// ABI compatible with code compiled on 5.0.
//
// Note that unless a type provides a custom hash(into:) implementation,
// this new version returns the same values as the original 5.0 definition,
// so code that used to work in 5.0 remains working whether or not the
// original definition was inlined.
//
// See https://bugs.swift.org/browse/SR-10734
var hasher = Hasher(_seed: seed)
self.hash(into: &hasher)
return hasher._finalize()
}
}
/// A type that provides a collection of all of its values.
///
/// Types that conform to the `CaseIterable` protocol are typically
/// enumerations without associated values. When using a `CaseIterable` type,
/// you can access a collection of all of the type's cases by using the type's
/// `allCases` property.
///
/// For example, the `CompassDirection` enumeration declared in this example
/// conforms to `CaseIterable`. You access the number of cases and the cases
/// themselves through `CompassDirection.allCases`.
///
/// enum CompassDirection: CaseIterable {
/// case north, south, east, west
/// }
///
/// print("There are \(CompassDirection.allCases.count) directions.")
/// // Prints "There are 4 directions."
/// let caseList = CompassDirection.allCases
/// .map({ "\($0)" })
/// .joined(separator: ", ")
/// // caseList == "north, south, east, west"
///
/// Conforming to the CaseIterable Protocol
/// =======================================
///
/// The compiler can automatically provide an implementation of the
/// `CaseIterable` requirements for any enumeration without associated values
/// or `@available` attributes on its cases. The synthesized `allCases`
/// collection provides the cases in order of their declaration.
///
/// You can take advantage of this compiler support when defining your own
/// custom enumeration by declaring conformance to `CaseIterable` in the
/// enumeration's original declaration. The `CompassDirection` example above
/// demonstrates this automatic implementation.
public protocol CaseIterable {
/// A type that can represent a collection of all values of this type.
associatedtype AllCases: Collection = [Self]
where AllCases.Element == Self
/// A collection of all values of this type.
static var allCases: AllCases { get }
}
/// A type that can be initialized using the nil literal, `nil`.
///
/// `nil` has a specific meaning in Swift---the absence of a value. Only the
/// `Optional` type conforms to `ExpressibleByNilLiteral`.
/// `ExpressibleByNilLiteral` conformance for types that use `nil` for other
/// purposes is discouraged.
public protocol ExpressibleByNilLiteral {
/// Creates an instance initialized with `nil`.
init(nilLiteral: ())
}
public protocol _ExpressibleByBuiltinIntegerLiteral {
init(_builtinIntegerLiteral value: Builtin.IntLiteral)
}
/// A type that can be initialized with an integer literal.
///
/// The standard library integer and floating-point types, such as `Int` and
/// `Double`, conform to the `ExpressibleByIntegerLiteral` protocol. You can
/// initialize a variable or constant of any of these types by assigning an
/// integer literal.
///
/// // Type inferred as 'Int'
/// let cookieCount = 12
///
/// // An array of 'Int'
/// let chipsPerCookie = [21, 22, 25, 23, 24, 19]
///
/// // A floating-point value initialized using an integer literal
/// let redPercentage: Double = 1
/// // redPercentage == 1.0
///
/// Conforming to ExpressibleByIntegerLiteral
/// =========================================
///
/// To add `ExpressibleByIntegerLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByIntegerLiteral {
/// A type that represents an integer literal.
///
/// The standard library integer and floating-point types are all valid types
/// for `IntegerLiteralType`.
associatedtype IntegerLiteralType: _ExpressibleByBuiltinIntegerLiteral
/// Creates an instance initialized to the specified integer value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using an integer literal. For example:
///
/// let x = 23
///
/// In this example, the assignment to the `x` constant calls this integer
/// literal initializer behind the scenes.
///
/// - Parameter value: The value to create.
init(integerLiteral value: IntegerLiteralType)
}
public protocol _ExpressibleByBuiltinFloatLiteral {
init(_builtinFloatLiteral value: _MaxBuiltinFloatType)
}
/// A type that can be initialized with a floating-point literal.
///
/// The standard library floating-point types---`Float`, `Double`, and
/// `Float80` where available---all conform to the `ExpressibleByFloatLiteral`
/// protocol. You can initialize a variable or constant of any of these types
/// by assigning a floating-point literal.
///
/// // Type inferred as 'Double'
/// let threshold = 6.0
///
/// // An array of 'Double'
/// let measurements = [2.2, 4.1, 3.65, 4.2, 9.1]
///
/// Conforming to ExpressibleByFloatLiteral
/// =======================================
///
/// To add `ExpressibleByFloatLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByFloatLiteral {
/// A type that represents a floating-point literal.
///
/// Valid types for `FloatLiteralType` are `Float`, `Double`, and `Float80`
/// where available.
associatedtype FloatLiteralType: _ExpressibleByBuiltinFloatLiteral
/// Creates an instance initialized to the specified floating-point value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a floating-point literal. For example:
///
/// let x = 21.5
///
/// In this example, the assignment to the `x` constant calls this
/// floating-point literal initializer behind the scenes.
///
/// - Parameter value: The value to create.
init(floatLiteral value: FloatLiteralType)
}
public protocol _ExpressibleByBuiltinBooleanLiteral {
init(_builtinBooleanLiteral value: Builtin.Int1)
}
/// A type that can be initialized with the Boolean literals `true` and
/// `false`.
///
/// `Bool`, `DarwinBoolean`, `ObjCBool`, and `WindowsBool` are treated as
/// Boolean values. Expanding this set to include types that represent more than
/// simple Boolean values is discouraged.
///
/// To add `ExpressibleByBooleanLiteral` conformance to your custom type,
/// implement the `init(booleanLiteral:)` initializer that creates an instance
/// of your type with the given Boolean value.
public protocol ExpressibleByBooleanLiteral {
/// A type that represents a Boolean literal, such as `Bool`.
associatedtype BooleanLiteralType: _ExpressibleByBuiltinBooleanLiteral
/// Creates an instance initialized to the given Boolean value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using one of the Boolean literals `true` and `false`. For
/// example:
///
/// let twasBrillig = true
///
/// In this example, the assignment to the `twasBrillig` constant calls this
/// Boolean literal initializer behind the scenes.
///
/// - Parameter value: The value of the new instance.
init(booleanLiteral value: BooleanLiteralType)
}
public protocol _ExpressibleByBuiltinUnicodeScalarLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32)
}
/// A type that can be initialized with a string literal containing a single
/// Unicode scalar value.
///
/// The `String`, `StaticString`, `Character`, and `Unicode.Scalar` types all
/// conform to the `ExpressibleByUnicodeScalarLiteral` protocol. You can
/// initialize a variable of any of these types using a string literal that
/// holds a single Unicode scalar.
///
/// let ñ: Unicode.Scalar = "ñ"
/// print(ñ)
/// // Prints "ñ"
///
/// Conforming to ExpressibleByUnicodeScalarLiteral
/// ===============================================
///
/// To add `ExpressibleByUnicodeScalarLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByUnicodeScalarLiteral {
/// A type that represents a Unicode scalar literal.
///
/// Valid types for `UnicodeScalarLiteralType` are `Unicode.Scalar`,
/// `Character`, `String`, and `StaticString`.
associatedtype UnicodeScalarLiteralType: _ExpressibleByBuiltinUnicodeScalarLiteral
/// Creates an instance initialized to the given value.
///
/// - Parameter value: The value of the new instance.
init(unicodeScalarLiteral value: UnicodeScalarLiteralType)
}
public protocol _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
: _ExpressibleByBuiltinUnicodeScalarLiteral {
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
/// A type that can be initialized with a string literal containing a single
/// extended grapheme cluster.
///
/// An *extended grapheme cluster* is a group of one or more Unicode scalar
/// values that approximates a single user-perceived character. Many
/// individual characters, such as "é", "김", and "🇮🇳", can be made up of
/// multiple Unicode scalar values. These code points are combined by
/// Unicode's boundary algorithms into extended grapheme clusters.
///
/// The `String`, `StaticString`, and `Character` types conform to the
/// `ExpressibleByExtendedGraphemeClusterLiteral` protocol. You can initialize
/// a variable or constant of any of these types using a string literal that
/// holds a single character.
///
/// let snowflake: Character = "❄︎"
/// print(snowflake)
/// // Prints "❄︎"
///
/// Conforming to ExpressibleByExtendedGraphemeClusterLiteral
/// =========================================================
///
/// To add `ExpressibleByExtendedGraphemeClusterLiteral` conformance to your
/// custom type, implement the required initializer.
public protocol ExpressibleByExtendedGraphemeClusterLiteral
: ExpressibleByUnicodeScalarLiteral {
/// A type that represents an extended grapheme cluster literal.
///
/// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`,
/// `String`, and `StaticString`.
associatedtype ExtendedGraphemeClusterLiteralType
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
/// Creates an instance initialized to the given value.
///
/// - Parameter value: The value of the new instance.
init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType)
}
extension ExpressibleByExtendedGraphemeClusterLiteral
where ExtendedGraphemeClusterLiteralType == UnicodeScalarLiteralType {
@_transparent
public init(unicodeScalarLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(extendedGraphemeClusterLiteral: value)
}
}
public protocol _ExpressibleByBuiltinStringLiteral
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
/// A type that can be initialized with a string literal.
///
/// The `String` and `StaticString` types conform to the
/// `ExpressibleByStringLiteral` protocol. You can initialize a variable or
/// constant of either of these types using a string literal of any length.
///
/// let picnicGuest = "Deserving porcupine"
///
/// Conforming to ExpressibleByStringLiteral
/// ========================================
///
/// To add `ExpressibleByStringLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByStringLiteral
: ExpressibleByExtendedGraphemeClusterLiteral {
/// A type that represents a string literal.
///
/// Valid types for `StringLiteralType` are `String` and `StaticString`.
associatedtype StringLiteralType: _ExpressibleByBuiltinStringLiteral
/// Creates an instance initialized to the given string value.
///
/// - Parameter value: The value of the new instance.
init(stringLiteral value: StringLiteralType)
}
extension ExpressibleByStringLiteral
where StringLiteralType == ExtendedGraphemeClusterLiteralType {
@_transparent
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(stringLiteral: value)
}
}
/// A type that can be initialized using an array literal.
///
/// An array literal is a simple way of expressing a list of values. Simply
/// surround a comma-separated list of values, instances, or literals with
/// square brackets to create an array literal. You can use an array literal
/// anywhere an instance of an `ExpressibleByArrayLiteral` type is expected: as
/// a value assigned to a variable or constant, as a parameter to a method or
/// initializer, or even as the subject of a nonmutating operation like
/// `map(_:)` or `filter(_:)`.
///
/// Arrays, sets, and option sets all conform to `ExpressibleByArrayLiteral`,
/// and your own custom types can as well. Here's an example of creating a set
/// and an array using array literals:
///
/// let employeesSet: Set<String> = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]
/// print(employeesSet)
/// // Prints "["Amir", "Dave", "Jihye", "Alessia"]"
///
/// let employeesArray: [String] = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]
/// print(employeesArray)
/// // Prints "["Amir", "Jihye", "Dave", "Alessia", "Dave"]"
///
/// The `Set` and `Array` types each handle array literals in their own way to
/// create new instances. In this case, the newly created set drops the
/// duplicate value ("Dave") and doesn't maintain the order of the array
/// literal's elements. The new array, on the other hand, matches the order
/// and number of elements provided.
///
/// - Note: An array literal is not the same as an `Array` instance. You can't
/// initialize a type that conforms to `ExpressibleByArrayLiteral` simply by
/// assigning an existing array.
///
/// let anotherSet: Set = employeesArray
/// // error: cannot convert value of type '[String]' to specified type 'Set'
///
/// Type Inference of Array Literals
/// ================================
///
/// Whenever possible, Swift's compiler infers the full intended type of your
/// array literal. Because `Array` is the default type for an array literal,
/// without writing any other code, you can declare an array with a particular
/// element type by providing one or more values.
///
/// In this example, the compiler infers the full type of each array literal.
///
/// let integers = [1, 2, 3]
/// // 'integers' has type '[Int]'
///
/// let strings = ["a", "b", "c"]
/// // 'strings' has type '[String]'
///
/// An empty array literal alone doesn't provide enough information for the
/// compiler to infer the intended type of the `Array` instance. When using an
/// empty array literal, specify the type of the variable or constant.
///
/// var emptyArray: [Bool] = []
/// // 'emptyArray' has type '[Bool]'
///
/// Because many functions and initializers fully specify the types of their
/// parameters, you can often use an array literal with or without elements as
/// a parameter. For example, the `sum(_:)` function shown here takes an `Int`
/// array as a parameter:
///
/// func sum(values: [Int]) -> Int {
/// return values.reduce(0, +)
/// }
///
/// let sumOfFour = sum([5, 10, 15, 20])
/// // 'sumOfFour' == 50
///
/// let sumOfNone = sum([])
/// // 'sumOfNone' == 0
///
/// When you call a function that does not fully specify its parameters' types,
/// use the type-cast operator (`as`) to specify the type of an array literal.
/// For example, the `log(name:value:)` function shown here has an
/// unconstrained generic `value` parameter.
///
/// func log<T>(name name: String, value: T) {
/// print("\(name): \(value)")
/// }
///
/// log(name: "Four integers", value: [5, 10, 15, 20])
/// // Prints "Four integers: [5, 10, 15, 20]"
///
/// log(name: "Zero integers", value: [] as [Int])
/// // Prints "Zero integers: []"
///
/// Conforming to ExpressibleByArrayLiteral
/// =======================================
///
/// Add the capability to be initialized with an array literal to your own
/// custom types by declaring an `init(arrayLiteral:)` initializer. The
/// following example shows the array literal initializer for a hypothetical
/// `OrderedSet` type, which has setlike semantics but maintains the order of
/// its elements.
///
/// struct OrderedSet<Element: Hashable>: Collection, SetAlgebra {
/// // implementation details
/// }
///
/// extension OrderedSet: ExpressibleByArrayLiteral {
/// init(arrayLiteral: Element...) {
/// self.init()
/// for element in arrayLiteral {
/// self.append(element)
/// }
/// }
/// }
public protocol ExpressibleByArrayLiteral {
/// The type of the elements of an array literal.
associatedtype ArrayLiteralElement
/// Creates an instance initialized with the given elements.
init(arrayLiteral elements: ArrayLiteralElement...)
}
/// A type that can be initialized using a dictionary literal.
///
/// A dictionary literal is a simple way of writing a list of key-value pairs.
/// You write each key-value pair with a colon (`:`) separating the key and
/// the value. The dictionary literal is made up of one or more key-value
/// pairs, separated by commas and surrounded with square brackets.
///
/// To declare a dictionary, assign a dictionary literal to a variable or
/// constant:
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana",
/// "JP": "Japan", "US": "United States"]
/// // 'countryCodes' has type [String: String]
///
/// print(countryCodes["BR"]!)
/// // Prints "Brazil"
///
/// When the context provides enough type information, you can use a special
/// form of the dictionary literal, square brackets surrounding a single
/// colon, to initialize an empty dictionary.
///
/// var frequencies: [String: Int] = [:]
/// print(frequencies.count)
/// // Prints "0"
///
/// - Note:
/// A dictionary literal is *not* the same as an instance of `Dictionary`.
/// You can't initialize a type that conforms to `ExpressibleByDictionaryLiteral`
/// simply by assigning an instance of `Dictionary`, `KeyValuePairs`, or similar.
///
/// Conforming to the ExpressibleByDictionaryLiteral Protocol
/// =========================================================
///
/// To add the capability to be initialized with a dictionary literal to your
/// own custom types, declare an `init(dictionaryLiteral:)` initializer. The
/// following example shows the dictionary literal initializer for a
/// hypothetical `CountedSet` type, which uses setlike semantics while keeping
/// track of the count for duplicate elements:
///
/// struct CountedSet<Element: Hashable>: Collection, SetAlgebra {
/// // implementation details
///
/// /// Updates the count stored in the set for the given element,
/// /// adding the element if necessary.
/// ///
/// /// - Parameter n: The new count for `element`. `n` must be greater
/// /// than or equal to zero.
/// /// - Parameter element: The element to set the new count on.
/// mutating func updateCount(_ n: Int, for element: Element)
/// }
///
/// extension CountedSet: ExpressibleByDictionaryLiteral {
/// init(dictionaryLiteral elements: (Element, Int)...) {
/// self.init()
/// for (element, count) in elements {
/// self.updateCount(count, for: element)
/// }
/// }
/// }
public protocol ExpressibleByDictionaryLiteral {
/// The key type of a dictionary literal.
associatedtype Key
/// The value type of a dictionary literal.
associatedtype Value
/// Creates an instance initialized with the given key-value pairs.
init(dictionaryLiteral elements: (Key, Value)...)
}
/// A type that can be initialized by string interpolation with a string
/// literal that includes expressions.
///
/// Use string interpolation to include one or more expressions in a string
/// literal, wrapped in a set of parentheses and prefixed by a backslash. For
/// example:
///
/// let price = 2
/// let number = 3
/// let message = "One cookie: $\(price), \(number) cookies: $\(price * number)."
/// print(message)
/// // Prints "One cookie: $2, 3 cookies: $6."
///
/// Extending the Default Interpolation Behavior
/// ============================================
///
/// Add new interpolation behavior to existing types by extending
/// `DefaultStringInterpolation`, the type that implements interpolation for
/// types like `String` and `Substring`, to add an overload of
/// `appendInterpolation(_:)` with their new behavior.
///
/// For more information, see the `DefaultStringInterpolation` and
/// `StringInterpolationProtocol` documentation.
///
/// Creating a Type That Supports the Default String Interpolation
/// ==============================================================
///
/// To create a new type that supports string literals and interpolation, but
/// that doesn't need any custom behavior, conform the type to
/// `ExpressibleByStringInterpolation` and implement the
/// `init(stringLiteral: String)` initializer declared by the
/// `ExpressibleByStringLiteral` protocol. Swift will automatically use
/// `DefaultStringInterpolation` as the interpolation type and provide an
/// implementation for `init(stringInterpolation:)` that passes the
/// interpolated literal's contents to `init(stringLiteral:)`, so you don't
/// need to implement anything specific to this protocol.
///
/// Creating a Type That Supports Custom String Interpolation
/// =========================================================
///
/// If you want a conforming type to differentiate between literal and
/// interpolated segments, restrict the types that can be interpolated,
/// support different interpolators from the ones on `String`, or avoid
/// constructing a `String` containing the data, the type must specify a custom
/// `StringInterpolation` associated type. This type must conform to
/// `StringInterpolationProtocol` and have a matching `StringLiteralType`.
///
/// For more information, see the `StringInterpolationProtocol` documentation.
public protocol ExpressibleByStringInterpolation
: ExpressibleByStringLiteral {
/// The type each segment of a string literal containing interpolations
/// should be appended to.
///
/// The `StringLiteralType` of an interpolation type must match the
/// `StringLiteralType` of the conforming type.
associatedtype StringInterpolation: StringInterpolationProtocol
= DefaultStringInterpolation
where StringInterpolation.StringLiteralType == StringLiteralType
/// Creates an instance from a string interpolation.
///
/// Most `StringInterpolation` types will store information about the
/// literals and interpolations appended to them in one or more properties.
/// `init(stringInterpolation:)` should use these properties to initialize
/// the instance.
///
/// - Parameter stringInterpolation: An instance of `StringInterpolation`
/// which has had each segment of the string literal appended
/// to it.
init(stringInterpolation: StringInterpolation)
}
extension ExpressibleByStringInterpolation
where StringInterpolation == DefaultStringInterpolation {
/// Creates a new instance from an interpolated string literal.
///
/// Don't call this initializer directly. It's used by the compiler when
/// you create a string using string interpolation. Instead, use string
/// interpolation to create a new string by including values, literals,
/// variables, or expressions enclosed in parentheses, prefixed by a
/// backslash (`\(`...`)`).
///
/// let price = 2
/// let number = 3
/// let message = """
/// If one cookie costs \(price) dollars, \
/// \(number) cookies cost \(price * number) dollars.
/// """
/// // message == "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
public init(stringInterpolation: DefaultStringInterpolation) {
self.init(stringLiteral: stringInterpolation.make())
}
}
/// Represents the contents of a string literal with interpolations while it's
/// being built up.
///
/// Each `ExpressibleByStringInterpolation` type has an associated
/// `StringInterpolation` type which conforms to `StringInterpolationProtocol`.
/// Swift converts an expression like `"The time is \(time)." as MyString` into
/// a series of statements similar to:
///
/// var interpolation = MyString.StringInterpolation(literalCapacity: 13,
/// interpolationCount: 1)
///
/// interpolation.appendLiteral("The time is ")
/// interpolation.appendInterpolation(time)
/// interpolation.appendLiteral(".")
///
/// MyString(stringInterpolation: interpolation)
///
/// The `StringInterpolation` type is responsible for collecting the segments
/// passed to its `appendLiteral(_:)` and `appendInterpolation` methods and
/// assembling them into a whole, converting as necessary. Once all of the
/// segments are appended, the interpolation is passed to an
/// `init(stringInterpolation:)` initializer on the type being created, which
/// must extract the accumulated data from the `StringInterpolation`.
///
/// In simple cases, you can use `DefaultStringInterpolation` as the
/// interpolation type for types that conform to the
/// `ExpressibleByStringLiteral` protocol. To use the default interpolation,
/// conform a type to `ExpressibleByStringInterpolation` and implement
/// `init(stringLiteral: String)`. Values in interpolations are converted to
/// strings, and then passed to that initializer just like any other string
/// literal.
///
/// Handling String Interpolations
/// ==============================
///
/// With a custom interpolation type, each interpolated segment is translated
/// into a call to a special `appendInterpolation` method. The contents of
/// the interpolation's parentheses are treated as the call's argument list.
/// That argument list can include multiple arguments and argument labels.
///
/// The following examples show how string interpolations are translated into
/// calls to `appendInterpolation`:
///
/// - `\(x)` translates to `appendInterpolation(x)`
/// - `\(x, y)` translates to `appendInterpolation(x, y)`
/// - `\(foo: x)` translates to `appendInterpolation(foo: x)`
/// - `\(x, foo: y)` translates to `appendInterpolation(x, foo: y)`
///
/// The `appendInterpolation` methods in your custom type must be mutating
/// instance methods that return `Void`. This code shows a custom interpolation
/// type's declaration of an `appendInterpolation` method that provides special
/// validation for user input:
///
/// extension MyString.StringInterpolation {
/// mutating func appendInterpolation(validating input: String) {
/// // Perform validation of `input` and store for later use
/// }
/// }
///
/// To use this interpolation method, create a string literal with an
/// interpolation using the `validating` parameter label.
///
/// let userInput = readLine() ?? ""
/// let myString = "The user typed '\(validating: userInput)'." as MyString
///
/// `appendInterpolation` methods support virtually all features of methods:
/// they can have any number of parameters, can specify labels for any or all
/// of their parameters, can provide default values, can have variadic
/// parameters, and can have parameters with generic types. Most importantly,
/// they can be overloaded, so a type that conforms to
/// `StringInterpolationProtocol` can provide several different
/// `appendInterpolation` methods with different behaviors. An
/// `appendInterpolation` method can also throw; when a user writes a literal
/// with one of these interpolations, they must mark the string literal with
/// `try` or one of its variants.
public protocol StringInterpolationProtocol {
/// The type that should be used for literal segments.
associatedtype StringLiteralType: _ExpressibleByBuiltinStringLiteral
/// Creates an empty instance ready to be filled with string literal content.
///
/// Don't call this initializer directly. Instead, initialize a variable or
/// constant using a string literal with interpolated expressions.
///
/// Swift passes this initializer a pair of arguments specifying the size of
/// the literal segments and the number of interpolated segments. Use this
/// information to estimate the amount of storage you will need.
///
/// - Parameter literalCapacity: The approximate size of all literal segments
/// combined. This is meant to be passed to `String.reserveCapacity(_:)`;
/// it may be slightly larger or smaller than the sum of the counts of each
/// literal segment.
/// - Parameter interpolationCount: The number of interpolations which will be
/// appended. Use this value to estimate how much additional capacity will
/// be needed for the interpolated segments.
init(literalCapacity: Int, interpolationCount: Int)
/// Appends a literal segment to the interpolation.
///
/// Don't call this method directly. Instead, initialize a variable or
/// constant using a string literal with interpolated expressions.
///
/// Interpolated expressions don't pass through this method; instead, Swift
/// selects an overload of `appendInterpolation`. For more information, see
/// the top-level `StringInterpolationProtocol` documentation.
///
/// - Parameter literal: A string literal containing the characters
/// that appear next in the string literal.
mutating func appendLiteral(_ literal: StringLiteralType)
// Informal requirement: Any desired appendInterpolation overloads, e.g.:
//
// mutating func appendInterpolation<T>(_: T)
// mutating func appendInterpolation(_: Int, radix: Int)
// mutating func appendInterpolation<T: Encodable>(json: T) throws
}
/// A type that can be initialized using a color literal (e.g.
/// `#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)`).
public protocol _ExpressibleByColorLiteral {
/// Creates an instance initialized with the given properties of a color
/// literal.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a color literal.
init(_colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float)
}
/// A type that can be initialized using an image literal (e.g.
/// `#imageLiteral(resourceName: "hi.png")`).
public protocol _ExpressibleByImageLiteral {
/// Creates an instance initialized with the given resource name.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using an image literal.
init(imageLiteralResourceName path: String)
}
/// A type that can be initialized using a file reference literal (e.g.
/// `#fileLiteral(resourceName: "resource.txt")`).
public protocol _ExpressibleByFileReferenceLiteral {
/// Creates an instance initialized with the given resource name.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a file reference literal.
init(fileReferenceLiteralResourceName path: String)
}
/// A container is destructor safe if whether it may store to memory on
/// destruction only depends on its type parameters destructors.
/// For example, whether `Array<Element>` may store to memory on destruction
/// depends only on `Element`.
/// If `Element` is an `Int` we know the `Array<Int>` does not store to memory
/// during destruction. If `Element` is an arbitrary class
/// `Array<MemoryUnsafeDestructorClass>` then the compiler will deduce may
/// store to memory on destruction because `MemoryUnsafeDestructorClass`'s
/// destructor may store to memory on destruction.
/// If in this example during `Array`'s destructor we would call a method on any
/// type parameter - say `Element.extraCleanup()` - that could store to memory,
/// then Array would no longer be a _DestructorSafeContainer.
public protocol _DestructorSafeContainer {
}
| apache-2.0 | a57f08cacc6fbb984ebc765811ef1d03 | 41.061856 | 85 | 0.687304 | 4.753029 | false | false | false | false |
jpipard/DKImagePickerController | DKImagePickerController/View/DKPermissionView.swift | 2 | 2050 | //
// DKPermissionView.swift
// DKImagePickerControllerDemo
//
// Created by ZhangAo on 15/12/17.
// Copyright © 2015年 ZhangAo. All rights reserved.
//
import UIKit
internal class DKPermissionView: UIView {
private let titleLabel = UILabel()
private let permitButton = UIButton()
internal class func permissionView(style: DKImagePickerControllerSourceType) -> DKPermissionView {
let permissionView = DKPermissionView()
permissionView.addSubview(permissionView.titleLabel)
permissionView.addSubview(permissionView.permitButton)
if style == .Photo {
permissionView.titleLabel.text = DKImageLocalizedStringWithKey("permissionPhoto")
permissionView.titleLabel.textColor = UIColor.grayColor()
} else {
permissionView.titleLabel.textColor = UIColor.whiteColor()
permissionView.titleLabel.text = DKImageLocalizedStringWithKey("permissionCamera")
}
permissionView.titleLabel.sizeToFit()
permissionView.permitButton.setTitle(DKImageLocalizedStringWithKey("permit"), forState: .Normal)
permissionView.permitButton.setTitleColor(UIColor(red: 0, green: 122.0 / 255, blue: 1, alpha: 1), forState: .Normal)
permissionView.permitButton.addTarget(permissionView, action: #selector(DKPermissionView.gotoSettings), forControlEvents: .TouchUpInside)
permissionView.permitButton.titleLabel?.font = UIFont.boldSystemFontOfSize(16)
permissionView.permitButton.sizeToFit()
permissionView.permitButton.center = CGPoint(x: permissionView.titleLabel.center.x,
y: permissionView.titleLabel.bounds.height + 40)
permissionView.frame.size = CGSize(width: max(permissionView.titleLabel.bounds.width, permissionView.permitButton.bounds.width),
height: permissionView.permitButton.frame.maxY)
return permissionView
}
override func didMoveToWindow() {
super.didMoveToWindow()
self.center = self.superview!.center
}
internal func gotoSettings() {
if let appSettings = NSURL(string: UIApplicationOpenSettingsURLString) {
UIApplication.sharedApplication().openURL(appSettings)
}
}
}
| mit | 92f311a38e0dbf62f2c33161ed3e1ec0 | 34.912281 | 139 | 0.783586 | 4.589686 | false | false | false | false |
shhuangtwn/ProjectLynla | Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisXLayerDefault.swift | 1 | 5153 | //
// ChartAxisXLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/// A ChartAxisLayer for X axes
class ChartAxisXLayerDefault: ChartAxisLayerDefault {
override var width: CGFloat {
return self.p2.x - self.p1.x
}
lazy var labelsTotalHeight: CGFloat = {
return self.rowHeights.reduce(0) {sum, height in
sum + height + self.settings.labelsSpacing
}
}()
lazy var rowHeights: [CGFloat] = {
return self.calculateRowHeights()
}()
override var height: CGFloat {
return self.labelsTotalHeight + self.settings.axisStrokeWidth + self.settings.labelsToAxisSpacingX + self.settings.axisTitleLabelsToLabelsSpacing + self.axisTitleLabelsHeight
}
override var length: CGFloat {
return p2.x - p1.x
}
override func chartViewDrawing(context context: CGContextRef, chart: Chart) {
super.chartViewDrawing(context: context, chart: chart)
}
override func generateLineDrawer(offset offset: CGFloat) -> ChartLineDrawer {
let p1 = CGPointMake(self.p1.x, self.p1.y + offset)
let p2 = CGPointMake(self.p2.x, self.p2.y + offset)
return ChartLineDrawer(p1: p1, p2: p2, color: self.settings.lineColor, strokeWidth: self.settings.axisStrokeWidth)
}
override func generateAxisTitleLabelsDrawers(offset offset: CGFloat) -> [ChartLabelDrawer] {
return self.generateAxisTitleLabelsDrawers(self.axisTitleLabels, spacingLabelAxisX: self.settings.labelsToAxisSpacingX, spacingLabelBetweenAxis: self.settings.labelsSpacing, offset: offset)
}
private func generateAxisTitleLabelsDrawers(labels: [ChartAxisLabel], spacingLabelAxisX: CGFloat, spacingLabelBetweenAxis: CGFloat, offset: CGFloat) -> [ChartLabelDrawer] {
let rowHeights = self.rowHeightsForRows(labels.map { [$0] })
return labels.enumerate().map{(index, label) in
let rowY = self.calculateRowY(rowHeights: rowHeights, rowIndex: index, spacing: spacingLabelBetweenAxis)
let labelWidth = ChartUtils.textSize(label.text, font: label.settings.font).width
let x = (self.p2.x - self.p1.x) / 2 + self.p1.x - labelWidth / 2
let y = self.p1.y + offset + rowY
let drawer = ChartLabelDrawer(text: label.text, screenLoc: CGPointMake(x, y), settings: label.settings)
drawer.hidden = label.hidden
return drawer
}
}
override func screenLocForScalar(scalar: Double, firstAxisScalar: Double) -> CGFloat {
return self.p1.x + self.innerScreenLocForScalar(scalar, firstAxisScalar: firstAxisScalar)
}
// calculate row heights (max text height) for each row
private func calculateRowHeights() -> [CGFloat] {
// organize labels in rows
let maxRowCount = self.axisValues.reduce(-1) {maxCount, axisValue in
max(maxCount, axisValue.labels.count)
}
let rows:[[ChartAxisLabel?]] = (0..<maxRowCount).map {row in
self.axisValues.map {axisValue in
let labels = axisValue.labels
return row < labels.count ? labels[row] : nil
}
}
return self.rowHeightsForRows(rows)
}
override func generateLabelDrawers(offset offset: CGFloat) -> [ChartLabelDrawer] {
let spacingLabelBetweenAxis = self.settings.labelsSpacing
let rowHeights = self.rowHeights
// generate all the label drawers, in a flat list
return self.axisValues.flatMap {axisValue in
return Array(axisValue.labels.enumerate()).map {index, label in
let rowY = self.calculateRowY(rowHeights: rowHeights, rowIndex: index, spacing: spacingLabelBetweenAxis)
let x = self.screenLocForScalar(axisValue.scalar)
let y = self.p1.y + offset + rowY
let labelSize = ChartUtils.textSize(label.text, font: label.settings.font)
let labelX = x - (labelSize.width / 2)
let labelDrawer = ChartLabelDrawer(text: label.text, screenLoc: CGPointMake(labelX, y), settings: label.settings)
labelDrawer.hidden = label.hidden
return labelDrawer
}
}
}
// Get the y offset of row relative to the y position of the first row
private func calculateRowY(rowHeights rowHeights: [CGFloat], rowIndex: Int, spacing: CGFloat) -> CGFloat {
return Array(0..<rowIndex).reduce(0) {y, index in
y + rowHeights[index] + spacing
}
}
// Get max text height for each row of axis values
private func rowHeightsForRows(rows: [[ChartAxisLabel?]]) -> [CGFloat] {
return rows.map { row in
row.flatMap { $0 }.reduce(-1) { maxHeight, label in
return max(maxHeight, label.textSize.height)
}
}
}
}
| mit | 250eaad4fa8b77f61a52efdddc2a4cc6 | 38.335878 | 197 | 0.627402 | 4.654923 | false | false | false | false |
FuckBoilerplate/RxCache | watchOS/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift | 12 | 2337 | //
// AsyncLock.swift
// Rx
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
In case nobody holds this lock, the work will be queued and executed immediately
on thread that is requesting lock.
In case there is somebody currently holding that lock, action will be enqueued.
When owned of the lock finishes with it's processing, it will also execute
and pending work.
That means that enqueued work could possibly be executed later on a different thread.
*/
class AsyncLock<I: InvocableType>
: Disposable
, Lock
, SynchronizedDisposeType {
typealias Action = () -> Void
var _lock = SpinLock()
private var _queue: Queue<I> = Queue(capacity: 0)
private var _isExecuting: Bool = false
private var _hasFaulted: Bool = false
// lock {
func lock() {
_lock.lock()
}
func unlock() {
_lock.unlock()
}
// }
private func enqueue(_ action: I) -> I? {
_lock.lock(); defer { _lock.unlock() } // {
if _hasFaulted {
return nil
}
if _isExecuting {
_queue.enqueue(action)
return nil
}
_isExecuting = true
return action
// }
}
private func dequeue() -> I? {
_lock.lock(); defer { _lock.unlock() } // {
if _queue.count > 0 {
return _queue.dequeue()
}
else {
_isExecuting = false
return nil
}
// }
}
func invoke(_ action: I) {
let firstEnqueuedAction = enqueue(action)
if let firstEnqueuedAction = firstEnqueuedAction {
firstEnqueuedAction.invoke()
}
else {
// action is enqueued, it's somebody else's concern now
return
}
while true {
let nextAction = dequeue()
if let nextAction = nextAction {
nextAction.invoke()
}
else {
return
}
}
}
func dispose() {
synchronizedDispose()
}
func _synchronized_dispose() {
_queue = Queue(capacity: 0)
_hasFaulted = true
}
}
| mit | 7b3a32d4d0756a7c813f92dfdbe01f74 | 21.461538 | 85 | 0.52226 | 4.767347 | false | false | false | false |
practicalswift/swift | test/IRGen/vtable_multi_file.swift | 6 | 898 | // RUN: %target-swift-frontend -primary-file %s %S/Inputs/vtable_multi_file_helper.swift -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
func markUsed<T>(_ t: T) {}
// CHECK-LABEL: define hidden swiftcc void @"$s17vtable_multi_file36baseClassVtablesIncludeImplicitInitsyyF"() {{.*}} {
func baseClassVtablesIncludeImplicitInits() {
// CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s17vtable_multi_file8SubclassCMa"(i64 0)
// CHECK: [[T0:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0
// CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to { i64, %swift.bridge* } (%swift.type*)**
// CHECK: [[T2:%.*]] = getelementptr inbounds { i64, %swift.bridge* } (%swift.type*)*, { i64, %swift.bridge* } (%swift.type*)** [[T1]], i64 11
// CHECK: load { i64, %swift.bridge* } (%swift.type*)*, { i64, %swift.bridge* } (%swift.type*)** [[T2]]
markUsed(Subclass.classProp)
}
| apache-2.0 | ce434e8f80ab7354423f43ac42ff4bab | 58.866667 | 144 | 0.642539 | 3.12892 | false | false | false | false |
FitnessKit/DataDecoder | Sources/DataDecoder/Types/MACAddress.swift | 1 | 2395 | //
// MACAddress.swift
// DataDecoder
//
// Created by Kevin Hoogheem on 4/1/17.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct MACAddress {
private(set) public var stringValue: String
public var dataValue: Data {
let substring = stringValue.replacingOccurrences(of: ":", with: "")
//let da = Data(bytes: [Character](substring.characters).byteArray)
return substring.data(using: .utf8)!
}
public init(string: String) {
self.stringValue = string.uppercased()
}
public init(data: Data) {
self.stringValue = "00:00:00:00:00:00"
if data.count == 6 {
self.stringValue = String(format: "%02X:%02X:%02X:%02X:%02X:%02X",
data[0],
data[1],
data[2],
data[3],
data[4],
data[5]).uppercased()
}
}
}
extension MACAddress: Equatable {
public static func ==(lhs: MACAddress, rhs: MACAddress) -> Bool {
return (lhs.stringValue == rhs.stringValue)
}
}
extension MACAddress: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(stringValue)
}
}
| mit | 70d8d8a22b3ea5749e2f72711be01c36 | 31.808219 | 81 | 0.623382 | 4.468284 | false | false | false | false |
AboutObjectsTraining/swift-ios-2015-07-kop | SwiftLabs/UnitTests/Optionals.playground/Contents.swift | 1 | 479 |
//: Optionals
let foo = "Hello World!"
let bar: String? = "Farewell World!"
print(foo)
print(bar)
var baz: String? = nil
print(baz)
if (baz == Optional.None)
{
print("I'm really an optional that's set to None")
}
// let myString: String = baz! // Illegal!
// print(baz!)
print("Got here")
if let myString = baz {
print(myString)
}
else {
print("Failed to unwrap myString")
}
baz = bar
if bar == nil {
print("bar is nil")
}
else {
print(bar!)
}
| mit | f0389d55b29fbb0923412c520627c5c1 | 10.682927 | 54 | 0.60334 | 2.885542 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.