repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
appnexus/mobile-sdk-ios | refs/heads/master | tests/TrackerUITest/IntegrationUITests/VideoAdTests.swift | apache-2.0 | 1 | /* Copyright 2019 APPNEXUS 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 XCTest
class VideoAdTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testVastVideoAd(){
let adObject = AdObject(adType: "Video", accessibilityIdentifier: PlacementTestConstants.VideoAd.testRTBVideo, placement: "19065996")
let videoAdObject = VideoAdObject(isVideo: false , adObject: adObject)
let videoAdObjectString = AdObjectModel.encodeVideoObject(adObject: videoAdObject)
let app = XCUIApplication()
app.launchArguments.append(PlacementTestConstants.VideoAd.testRTBVideo)
app.launchArguments.append(videoAdObjectString)
app.launch()
let webViewsQuery = app.webViews.element(boundBy: 0)
wait(for: webViewsQuery, timeout: 25)
wait(2)
let webview = webViewsQuery.firstMatch
XCTAssertEqual(webview.exists, true)
let adDuration = webViewsQuery.staticTexts["1:06"]
XCTAssertEqual(adDuration.exists, true)
let muteButton = webViewsQuery.buttons[" Mute"]
XCTAssertEqual(muteButton.exists, true)
muteButton.tap()
wait(2)
let unmuteButton = webViewsQuery.buttons[" Unmute"]
XCTAssertEqual(unmuteButton.exists, true)
unmuteButton.tap()
wait(2)
// let adLearnMoreStaticText = app/*@START_MENU_TOKEN@*/.webViews/*[[".otherElements[\"testBannerVideo\"].webViews",".webViews"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.staticTexts["Learn More - Ad"]
// XCTAssertEqual(adLearnMoreStaticText.exists, true)
// let skipText = webViewsQuery.staticTexts["SKIP"]
// XCTAssertEqual(skipText.exists, true)
// XCGlobal.screenshotWithTitle(title: PlacementTestConstants.VideoAd.testRTBVideo)
// wait(2)
}
}
| 39f5c16db6901678b7dae04dbbd9a4aa | 35.493976 | 207 | 0.666226 | false | true | false | false |
lanjing99/RxSwiftDemo | refs/heads/master | 04-observables-in-practice/final/Combinestagram/MainViewController.swift | mit | 1 | /*
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import RxSwift
class MainViewController: UIViewController {
@IBOutlet weak var imagePreview: UIImageView!
@IBOutlet weak var buttonClear: UIButton!
@IBOutlet weak var buttonSave: UIButton!
@IBOutlet weak var itemAdd: UIBarButtonItem!
private let bag = DisposeBag()
private let images = Variable<[UIImage]>([])
override func viewDidLoad() {
super.viewDidLoad()
images.asObservable()
.subscribe(onNext: { [weak self] photos in
guard let preview = self?.imagePreview else { return }
preview.image = UIImage.collage(images: photos,
size: preview.frame.size)
})
.addDisposableTo(bag)
images.asObservable()
.subscribe(onNext: { [weak self] photos in
self?.updateUI(photos: photos)
})
.addDisposableTo(bag)
}
private func updateUI(photos: [UIImage]) {
buttonSave.isEnabled = photos.count > 0 && photos.count % 2 == 0
buttonClear.isEnabled = photos.count > 0
itemAdd.isEnabled = photos.count < 6
title = photos.count > 0 ? "\(photos.count) photos" : "Collage"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("resources: \(RxSwift.Resources.total)")
}
@IBAction func actionClear() {
images.value = []
}
@IBAction func actionSave() {
guard let image = imagePreview.image else { return }
PhotoWriter.save(image)
.subscribe(onError: { [weak self] error in
self?.showMessage("Error", description: error.localizedDescription)
}, onCompleted: { [weak self] in
self?.showMessage("Saved")
self?.actionClear()
})
.addDisposableTo(bag)
}
@IBAction func actionAdd() {
//images.value.append(UIImage(named: "IMG_1907.jpg")!)
let photosViewController = storyboard!.instantiateViewController(
withIdentifier: "PhotosViewController") as! PhotosViewController
photosViewController.selectedPhotos
.subscribe(onNext: { [weak self] newImage in
guard let images = self?.images else { return }
images.value.append(newImage)
}, onDisposed: {
print("completed photo selection")
})
.addDisposableTo(photosViewController.bag)
navigationController!.pushViewController(photosViewController, animated: true)
}
func showMessage(_ title: String, description: String? = nil) {
let alert = UIAlertController(title: title, message: description, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Close", style: .default, handler: { [weak self] _ in self?.dismiss(animated: true, completion: nil)}))
present(alert, animated: true, completion: nil)
}
}
| 54b0879b63ff8272e22c7a619270ab25 | 35.075472 | 144 | 0.696391 | false | false | false | false |
lijuncode/SimpleMemo | refs/heads/master | SimpleMemo/View/MemoCell.swift | mit | 2 | //
// MemoCell.swift
// EverMemo
//
// Created by 李俊 on 15/8/5.
// Copyright (c) 2015年 李俊. All rights reserved.
//
import UIKit
import SnapKit
import SMKit
private let deleteViewWidth: CGFloat = 60
private let UIPanGestureRecognizerStateKeyPath = "state"
class MemoCell: UICollectionViewCell {
var didSelectedMemoAction: ((_ memo: Memo) -> Void)?
var deleteMemoAction: ((_ memo: Memo) -> Void)?
var memo: Memo? {
didSet {
contentLabel.text = memo?.text
}
}
fileprivate var containingView: UICollectionView? {
didSet {
updateContainingView()
}
}
fileprivate var hasCellShowDeleteBtn = false
fileprivate var containingViewPangestureRecognize: UIPanGestureRecognizer?
fileprivate let scrollView = UIScrollView()
fileprivate let deleteView = DeleteView()
fileprivate let contentLabel: MemoLabel = {
let label = MemoLabel()
label.backgroundColor = .white
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 15)
label.verticalAlignment = .top
label.textColor = SMColor.content
label.sizeToFit()
return label
}()
fileprivate var getsureRecognizer: UIGestureRecognizer?
override init(frame: CGRect) {
super.init(frame: frame)
setUI()
NotificationCenter.default.addObserver(self, selector: #selector(hiddenDeleteButtonAnimated), name: SMNotification.MemoCellShouldHiddenDeleteBtn, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(receiveMemoCellDidShowDeleteBtnNotification), name: SMNotification.MemoCellDidShowDeleteBtn, object: nil)
}
override func didMoveToSuperview() {
containingView = nil
var view: UIView = self
while let superview = view.superview {
view = superview
if let collectionView: UICollectionView = view as? UICollectionView {
containingView = collectionView
break
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
scrollView.contentSize = CGSize(width: contentView.width + deleteViewWidth, height: contentView.height)
deleteView.frame = CGRect(x: contentView.width, y: 0, width: deleteViewWidth, height: contentView.height)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
removeObserver()
NotificationCenter.default.removeObserver(self)
}
@objc fileprivate func topLabel() {
if hasCellShowDeleteBtn {
NotificationCenter.default.post(name: SMNotification.MemoCellShouldHiddenDeleteBtn, object: nil)
hasCellShowDeleteBtn = false
return
}
if let memo = memo {
didSelectedMemoAction?(memo)
}
}
@objc fileprivate func deleteMemo() {
if let memo = memo {
deleteMemoAction?(memo)
}
}
@objc fileprivate func receiveMemoCellDidShowDeleteBtnNotification() {
hasCellShowDeleteBtn = true
}
@objc fileprivate func hiddenDeleteButtonAnimated() {
hiddenDeleteButton(withAnimated: true)
hasCellShowDeleteBtn = false
}
override func prepareForReuse() {
memo = nil
hiddenDeleteButton(withAnimated: false)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == UIPanGestureRecognizerStateKeyPath &&
containingViewPangestureRecognize == object as? UIPanGestureRecognizer {
if containingViewPangestureRecognize?.state == .began {
hiddenDeleteButton(withAnimated: true)
}
}
}
}
// MARK: - UI
private extension MemoCell {
func updateContainingView() {
removeObserver()
if let collecionView = containingView {
containingViewPangestureRecognize = collecionView.panGestureRecognizer
containingViewPangestureRecognize?.addObserver(self, forKeyPath: UIPanGestureRecognizerStateKeyPath, options: .new, context: nil)
}
}
func removeObserver() {
containingViewPangestureRecognize?.removeObserver(self, forKeyPath: UIPanGestureRecognizerStateKeyPath)
}
func setUI() {
backgroundColor = UIColor.white
scrollView.bounces = false
scrollView.delegate = self
scrollView.showsHorizontalScrollIndicator = false
contentView.addSubview(scrollView)
scrollView.snp.makeConstraints { (maker) in
maker.top.left.bottom.right.equalToSuperview()
}
getsureRecognizer = UITapGestureRecognizer(target: self, action: #selector(topLabel))
contentLabel.addGestureRecognizer(getsureRecognizer!)
contentLabel.isUserInteractionEnabled = true
scrollView.addSubview(contentLabel)
contentLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(scrollView).offset(5)
maker.left.equalTo(scrollView).offset(5)
maker.bottom.equalTo(contentView).offset(-5)
maker.right.lessThanOrEqualTo(contentView).offset(-5)
maker.width.equalTo(contentView.width - 10)
}
deleteView.backgroundColor = SMColor.backgroundGray
deleteView.deleteBtn.addTarget(self, action: #selector(deleteMemo), for: .touchUpInside)
scrollView.addSubview(deleteView)
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowOpacity = 0.2
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
}
extension MemoCell: UIScrollViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if hasCellShowDeleteBtn {
NotificationCenter.default.post(name: SMNotification.MemoCellShouldHiddenDeleteBtn, object: nil)
hasCellShowDeleteBtn = false
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.x >= deleteViewWidth {
NotificationCenter.default.post(name: SMNotification.MemoCellDidShowDeleteBtn, object: nil)
}
if scrollView.isTracking {
return
}
automateScroll(scrollView)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate {
return
}
automateScroll(scrollView)
}
func automateScroll(_ scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x
let newX = offsetX < deleteViewWidth / 2 ? 0 : deleteViewWidth
UIView.animate(withDuration: 0.1) {
scrollView.contentOffset = CGPoint(x: newX, y: 0)
}
}
func hiddenDeleteButton(withAnimated animated: Bool = true) {
let duration: TimeInterval = animated ? 0.2 : 0
UIView.animate(withDuration: duration) {
self.scrollView.contentOffset = CGPoint(x: 0, y: 0)
}
}
}
// MARK: - DeleteView
private class DeleteView: UIView {
let deleteBtn = UIButton(type: .custom)
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .gray
let image = UIImage(named: "ic_trash")?.withRenderingMode(.alwaysTemplate)
deleteBtn.setImage(image, for: .normal)
deleteBtn.backgroundColor = SMColor.red
deleteBtn.layer.masksToBounds = true
deleteBtn.tintColor = SMColor.backgroundGray
addSubview(deleteBtn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate override func layoutSubviews() {
super.layoutSubviews()
let margin: CGFloat = 12
let btnWidth = width - margin * 2
let btnY = (height - btnWidth) / 2
deleteBtn.frame = CGRect(x: margin, y: btnY, width: btnWidth, height: btnWidth)
deleteBtn.layer.cornerRadius = deleteBtn.width / 2
}
}
| 4e734ed6705818beb03f9ecebd6dde1e | 29.747934 | 174 | 0.722484 | false | false | false | false |
rlisle/Patriot-iOS | refs/heads/master | Patriot/PhotonManager.swift | bsd-3-clause | 1 | //
// PhotonManager.swift
// Patriot
//
// This class manages the collection of Photon devices
//
// Discovery will search for all the Photon devices on the network.
// When a new device is found, it will be added to the photons collection
// and a delegate or notification sent.
// This is the anticipated way of updating displays, etc.
//
// The current activity state will be gleaned from the exposed Activities
// properties of one or more Photons initially, but then tracked directly
// after initialization by subscribing to particle events.
// Subscribing to particle events will also allow detecting new Photons
// as they come online and start issuing 'alive' events.
//
// This file uses the Particle SDK:
// https://docs.particle.io/reference/ios/#common-tasks
//
// Created by Ron Lisle on 11/13/16.
// Copyright © 2016, 2017 Ron Lisle. All rights reserved.
//
import Foundation
import Particle_SDK
import PromiseKit
protocol PhotonDelegate
{
func device(named: String, hasDevices: Set<String>)
func device(named: String, supports: Set<String>)
func device(named: String, hasSeenActivities: [String: Int])
}
enum ParticleSDKError : Error
{
case invalidUserPassword
case invalidToken
}
class PhotonManager: NSObject, HwManager
{
var subscribeHandler: Any?
var deviceDelegate: DeviceNotifying?
var activityDelegate: ActivityNotifying?
var photons: [String: Photon] = [: ] // All the particle devices attached to logged-in user's account
let eventName = "patriot"
var deviceNames = Set<String>() // Names exposed by the "Devices" variables
var supportedNames = Set<String>() // Activity names exposed by the "Supported" variables
var currentActivities: [String: Int] = [: ] // List of currently on activities reported by Master
/**
* Login to the particle.io account
* The particle SDK will use the returned token in subsequent calls.
* We don't have to save it.
*/
func login(user: String, password: String) -> Promise<Void>
{
return Promise { fulfill, reject in
ParticleCloud.sharedInstance().login(withUser: user, password: password) { (error) in
if let error = error {
return reject(error)
}
return fulfill(())
}
}
}
@discardableResult func discoverDevices() -> Promise<Void>
{
return getAllPhotonDevices()
}
/**
* Locate all the particle.io devices
*/
func getAllPhotonDevices() -> Promise<Void>
{
return Promise { fulfill, reject in
ParticleCloud.sharedInstance().getDevices { (devices: [ParticleDevice]?, error: Error?) in
if error != nil {
print("Error: \(error!)")
reject(error!)
}
else
{
self.addAllPhotonsToCollection(devices: devices)
.then { _ -> Void in
print("All photons added to collection")
self.activityDelegate?.supportedListChanged()
fulfill(())
}.catch { error in
reject(error)
}
}
}
}
}
func addAllPhotonsToCollection(devices: [ParticleDevice]?) -> Promise<Void>
{
self.photons = [: ]
var promises = [Promise<Void>]()
if let particleDevices = devices
{
for device in particleDevices
{
if isValidPhoton(device)
{
if let name = device.name?.lowercased()
{
print("Adding photon \(name) to collection")
let photon = Photon(device: device)
photon.delegate = self
self.photons[name] = photon
self.deviceDelegate?.deviceFound(name: name)
let promise = photon.refresh()
promises.append(promise)
}
}
}
return when(fulfilled: promises)
}
return Promise(error: NSError(domain: "No devices", code: 0, userInfo: nil))
}
func isValidPhoton(_ device: ParticleDevice) -> Bool
{
return device.connected
}
func getPhoton(named: String) -> Photon?
{
let lowerCaseName = named.lowercased()
let photon = photons[lowerCaseName]
return photon
}
func sendCommand(activity: String, percent: Int)
{
print("sendCommand: \(activity) percent: \(percent)")
let data = activity + ":" + String(percent)
print("Publishing event: \(eventName) data: \(data)")
ParticleCloud.sharedInstance().publishEvent(withName: eventName, data: data, isPrivate: true, ttl: 60)
{ (error:Error?) in
if let e = error
{
print("Error publishing event \(e.localizedDescription)")
}
}
}
func subscribeToEvents()
{
subscribeHandler = ParticleCloud.sharedInstance().subscribeToMyDevicesEvents(withPrefix: eventName, handler: { (event: ParticleEvent?, error: Error?) in
if let _ = error {
print("Error subscribing to events")
}
else
{
DispatchQueue.main.async(execute: {
//print("Subscribe: received event with data \(String(describing: event?.data))")
if let eventData = event?.data {
let splitArray = eventData.components(separatedBy: ":")
let name = splitArray[0].lowercased()
if let percent: Int = Int(splitArray[1]), percent >= 0, percent <= 100
{
self.activityDelegate?.activityChanged(name: name, percent: percent)
}
else
{
// print("Event data is not a valid number")
}
}
})
}
})
}
}
extension PhotonManager
{
// private func parseSupportedNames(_ supported: String) -> Set<String>
// {
// print("6. Parsing supported names: \(supported)")
// var newSupported: Set<String> = []
// let items = supported.components(separatedBy: ",")
// for item in items
// {
// let lcItem = item.localizedLowercase
// print("7. New supported = \(lcItem)")
// newSupported.insert(lcItem)
// }
//
// return newSupported
// }
// func refreshCurrentActivities()
// {
// print("8. refreshCurrentActivities")
// currentActivities = [: ]
// for (name, photon) in photons
// {
// let particleDevice = photon.particleDevice
// if particleDevice?.variables["Activities"] != nil
// {
// print("9. reading Activities variable from \(name)")
// particleDevice?.getVariable("Activities") { (result: Any?, error: Error?) in
// if error == nil
// {
// if let activities = result as? String, activities != ""
// {
// print("10. Activities = \(activities)")
// let items = activities.components(separatedBy: ",")
// for item in items
// {
// let parts = item.components(separatedBy: ":")
// self.currentActivities[parts[0]] = parts[1]
//// self.activityDelegate?.activityChanged(event: item)
// }
// }
// } else {
// print("Error reading Supported variable. Skipping this device.")
// }
// print("11. Updated Supported names = \(self.supportedNames)")
// self.activityDelegate?.supportedListChanged()
// }
// }
// }
// }
}
// These methods report the capabilities of each photon asynchronously
extension PhotonManager: PhotonDelegate
{
func device(named: String, hasDevices: Set<String>)
{
print("device named \(named) hasDevices \(hasDevices)")
deviceNames = deviceNames.union(hasDevices)
}
func device(named: String, supports: Set<String>)
{
print("device named \(named) supports \(supports)")
supportedNames = supportedNames.union(supports)
}
func device(named: String, hasSeenActivities: [String: Int])
{
print("device named \(named) hasSeenActivities \(hasSeenActivities)")
hasSeenActivities.forEach { (k,v) in currentActivities[k] = v }
}
}
extension PhotonManager
{
func readVariable(device: ParticleDevice, name: String) -> Promise<String>
{
return Promise { fulfill, reject in
device.getVariable("Supported")
{ (result: Any?, error: Error?) in
if let variable = result as? String
{
fulfill(variable)
}
else
{
reject(error!)
}
}
}
}
}
| 2036437c4655ab8c1e03a6056d5093f9 | 32.215753 | 160 | 0.525003 | false | false | false | false |
wl879/SwiftyCss | refs/heads/master | SwiftyCss/SwiftyBox/Debug.swift | mit | 1 | // Created by Wang Liang on 2017/4/8.
// Copyright © 2017年 Wang Liang. All rights reserved.
import Foundation
import QuartzCore
public class Debug: CustomStringConvertible {
public var timeTotal: Float = 0
public var output: String? = nil
public var send: String? = nil
private var value : UInt = 0
private var map = [String : (UInt, String)]()
private var timestamp = [Int: [TimeInterval]]()
private var queue: DispatchQueue? = nil
public var async: Bool {
get { return self.queue != nil }
set {
if newValue {
self.queue = DispatchQueue(label: "SwiftyBox.Debug")
}else{
self.queue = nil
}
}
}
public init( tags: [String: String], output: String? = nil, send: String? = nil, file: String = #file, line: Int = #line) {
for (tag, val) in tags {
self.define(tag: tag, template: val, file: file, line: line)
}
self.output = output
self.send = send
}
public final func define(tag: String, template: String, file: String = #file, line: Int = #line) {
let hash = tag.hashValue
if self.map[tag] != nil {
fatalError( Debug._format(template: "✕ SwiftyBox.Debgu define tag % already exist: %file, line %line", contents: [tag], usetime: 0, file: file, method: "", line: line) )
}
self.map[tag] = (UInt(1 << (map.count+1)), template)
self.timestamp[hash] = []
}
public final func enable(_ tag: String...){
for g in tag {
if g == "all" {
value = 0
for (_, v) in map {
value += v.0
}
return
}else if let v = map[g] {
if value & v.0 != v.0 {
value += v.0
}
}
}
}
public final func enabled(_ tag: String) -> Bool {
if let v = map[tag] {
if value & v.0 == v.0 {
return true
}
}
return false
}
public final func begin(tag: String, id: Int? = nil) {
guard self.enabled(tag) else {
return
}
if id != nil {
if timestamp[id!] == nil {
timestamp[id!] = [CACurrentMediaTime()]
}
}else{
timestamp[tag.hashValue]!.append(CACurrentMediaTime())
}
}
public final func end(tag: String, id: Int? = nil, _ contents: Any?..., file: String = #file, method: String = #function, line: Int = #line) {
guard self.enabled(tag) else {
return
}
let hash = tag.hashValue
var usetime: Float = 0
if id != nil {
if let t = timestamp[id!]?.first {
usetime = Float(Int((CACurrentMediaTime() - t)*100000))/100
}
timestamp[id!] = nil
} else if timestamp[hash]!.count > 0 {
usetime = Float(Int((CACurrentMediaTime() - timestamp[hash]!.removeLast())*100000))/100
}
timeTotal += usetime
let tmp = map[tag]!.1
if self.async {
self.queue?.async {
self.echo( Debug._format(template: tmp, contents: contents, usetime: usetime, file: file, method: method, line: line) )
}
}else{
self.echo( Debug._format(template: tmp, contents: contents, usetime: usetime, file: file, method: method, line: line) )
}
}
public final func log(tag: String, _ contents: Any?..., file: String = #file, method: String = #function, line: Int = #line) {
guard self.enabled(tag) else {
return
}
let tmp = map[tag]!.1
if self.async {
self.queue?.async {
self.echo( Debug._format(template: tmp, contents: contents, usetime: 0, file: file, method: method, line: line) )
}
}else{
self.echo( Debug._format(template: tmp, contents: contents, usetime: 0, file: file, method: method, line: line) )
}
}
public final func log(format: String = "%%", _ contents: Any?..., file: String = #file, method: String = #function, line: Int = #line) {
if self.async {
self.queue?.async {
self.echo( Debug._format(template: format, contents: contents, usetime: 0, file: file, method: method, line: line) )
}
}else{
self.echo( Debug._format(template: format, contents: contents, usetime: 0, file: file, method: method, line: line) )
}
}
public final func error(format: String = "%%", _ contents: Any?..., file: String = #file, method: String = #function, line: Int = #line) {
if self.async {
self.queue?.async {
let msg = Debug._format(template: format, contents: contents, usetime: 0, file: file, method: method, line: line)
self.echo(msg)
}
}else{
let msg = Debug._format(template: format, contents: contents, usetime: 0, file: file, method: method, line: line)
self.echo(msg)
}
}
public final func stringify(_ value: @autoclosure @escaping () -> Any?) -> () -> String {
return { Debug._stringify( value() ) }
}
private final func echo(_ text: String) {
print( text )
if self.output != nil {
self.queue?.async {
if let f = FileHandle(forWritingAtPath: self.output! ) {
f.seekToEndOfFile()
f.write( text.data(using: .utf8, allowLossyConversion: true)! )
f.closeFile()
}
}
}
if self.send != nil {
// TODO: send to server
}
}
public final var description: String {
var names = [String]()
for (name, conf) in map {
if value & conf.0 == conf.0 {
names.append(name)
}
}
return "<SwiftyBox.Debug Enabel: \(names.joined(separator:", "))>"
}
// MARK: -
private static let _format_re = Re("(%ms|%file|%who|%line|%now|%date|%time)\\b|(\\n(?:[^%]*[>:]\\s*|\\s*))?(%\\[\\]|%%|%)")
private static func _format(template:String, contents: [Any?], usetime: Float, file: String, method: String, line: Int) -> String {
var text = ""
var i = 0
var tmp = template
while let m = _format_re.match(tmp) {
if m.index > 0 {
text += tmp.slice(start:0, end: m.index)
}
tmp = tmp.slice(start: m.lastIndex+1 )
if !m[1]!.isEmpty {
switch m[1]! {
case "%file":
text += file
case "%line":
text += line.description
case "%who":
text += method
case "%ms":
text += usetime.description + "ms"
case "%now":
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd HH:mm:ss"
text += format.string( from: Date() ) + "ms"
case "%date":
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd"
text += format.string( from: Date() ) + "ms"
case "%time":
let format = DateFormatter()
format.dateFormat = "HH:mm:ss"
text += format.string( from: Date() ) + "ms"
default:
continue
}
}else{
var temp = ""
let prefix = m[2]!
var indent = prefix.isEmpty ? "" : Re("[^\\s]").replace(prefix, " ")
switch m[3]! {
case "%[]":
if i < contents.count {
if let val = contents[i] {
if val is [Any] {
let arr = val as! [Any]
for i in 0 ..< arr.count {
if i != 0 {
temp += prefix.isEmpty ? "\n" : prefix
}
temp += _stringify(arr[i]).replacingOccurrences(of: "\n", with: indent)
}
indent = ""
}else{
temp = _stringify(val)
}
}else{
temp = "nil"
}
i += 1
}
case "%%":
while i < contents.count {
temp += " " + _stringify(contents[i])
i += 1
}
case "%":
if i < contents.count {
temp = _stringify(contents[i])
i += 1
}
default:
continue
}
if !indent.isEmpty {
temp = temp.replacingOccurrences(of: "\n", with: indent)
}
text += prefix + temp
}
}
text += tmp
return text
}
private static func _stringify(_ value: Any?) -> String {
guard let value = value else {
return "nil"
}
let str = String(describing: value)
if str == "(Function)" {
let type = String(describing: type(of: value))
switch type {
case "() -> String":
return String(describing: (value as! () -> String)())
case "() -> String?":
return String(describing: (value as! () -> String?)() ?? "nil")
default:
return type
}
}
return str
}
}
| b7e3468611bdcbdb21933d9d8164c516 | 34.804196 | 181 | 0.437793 | false | false | false | false |
CNKCQ/oschina | refs/heads/master | Pods/Foundation+/Foundation+/Date+.swift | mit | 1 | //
// Date.swift
// Elegant
//
// Created by Steve on 2017/5/18.
// Copyright © 2017年 KingCQ. All rights reserved.
//
import Foundation
public extension Date {
/// Returns the earlier of the receiver and another given date.
///
/// - Parameter date: The date with which to compare the receiver.
/// - Returns: The earlier of the receiver
func earlierDate(_ date: Date) -> Date {
let now = Date()
return now < date ? now : date
}
/// Returns the later of the receiver and another given date.
///
/// - Parameter date: The date with which to compare the receiver.
/// - Returns: The later of the receiver
func laterDate(_ date: Date) -> Date {
let now = Date()
return now < date ? date : now
}
/// Takes a past Date and creates a string representation of it.
///
/// - Parameters:
/// - date: Past date you wish to create a string representation for.
/// - numericDates: if true, ex: "1 week ago", else ex: "Last week"
/// - Returns: String that represents your date.
static func timeAgoSinceDate(_ date: Date, numericDates: Bool) -> String {
let calendar = Calendar.current
let now = Date()
let earliest = now.earlierDate(date)
let latest = (earliest == now) ? date : now
let components = calendar.dateComponents([.minute, .hour, .day, .weekOfYear, .month, .year, .second], from: earliest, to: latest)
if components.year! >= 2 {
return "\(String(describing: components.year)) years ago"
} else if components.year! >= 1 {
if numericDates {
return "1 year ago"
} else {
return "Last year"
}
} else if components.month! >= 2 {
return "\(String(describing: components.month)) months ago"
} else if components.month! >= 1 {
if numericDates {
return "1 month ago"
} else {
return "Last month"
}
} else if components.weekOfYear! >= 2 {
return "\(String(describing: components.weekOfYear)) weeks ago"
} else if components.weekOfYear! >= 1 {
if numericDates {
return "1 week ago"
} else {
return "Last week"
}
} else if components.day! >= 2 {
return "\(String(describing: components.day)) days ago"
} else if components.day! >= 1 {
if numericDates {
return "1 day ago"
} else {
return "Yesterday"
}
} else if components.hour! >= 2 {
return "\(String(describing: components.hour)) hours ago"
} else if components.hour! >= 1 {
if numericDates {
return "1 hour ago"
} else {
return "An hour ago"
}
} else if components.minute! >= 2 {
return "\(String(describing: components.minute)) minutes ago"
} else if components.minute! >= 1 {
if numericDates {
return "1 minute ago"
} else {
return "A minute ago"
}
} else if components.second! >= 3 {
return "\(String(describing: components.second)) seconds ago"
} else {
return "just now"
}
}
}
| 6c1e8fcb66915c50044e27a88d4ec67b | 34.185567 | 137 | 0.530911 | false | false | false | false |
einsteinx2/iSub | refs/heads/master | Classes/Data Model/CachedImage.swift | gpl-3.0 | 1 | //
// CachedImage.swift
// iSub
//
// Created by Benjamin Baron on 1/4/17.
// Copyright © 2017 Ben Baron. All rights reserved.
//
import Foundation
import Nuke
enum CachedImageSize {
case cell
case player
case original
var pixelSize: Int {
switch self {
case .cell: return 120
case .player: return 640
case .original: return -1
}
}
var name: String {
switch self {
case .cell: return "cell"
case .player: return "player"
case .original: return "original"
}
}
}
struct CachedImage {
static let preheater = Preheater()
static func request(coverArtId: String, serverId: Int64, size: CachedImageSize) -> Request? {
var parameters = ["id": coverArtId]
if size != .original {
parameters["size"] = "\(size.pixelSize)"
}
let fragment = "s_\(serverId)_id_\(coverArtId)_size_\(size.name)"
if let urlRequest = URLRequest(subsonicAction: .getCoverArt, serverId: serverId, parameters: parameters, fragment: fragment) {
var request = Request(urlRequest: urlRequest)
request.cacheKey = fragment
request.loadKey = fragment
return request
}
return nil
}
static func preheat(coverArtId: String, serverId: Int64, size: CachedImageSize) {
if let request = self.request(coverArtId: coverArtId, serverId: serverId, size: size) {
preheater.startPreheating(with: [request])
}
}
static func cached(coverArtId: String, serverId: Int64, size: CachedImageSize) -> UIImage? {
if let request = self.request(coverArtId: coverArtId, serverId: serverId, size: size) {
let image = Cache.shared[request]
return image
}
return nil
}
static func `default`(forSize size: CachedImageSize) -> UIImage {
switch size {
case .cell: return UIImage(named: "default-album-art-small")!
case .player, .original: return UIImage(named: "default-album-art")!
}
}
// static fileprivate func key(forCoverArtId coverArtId: String, serverId: Int, size: CachedImageSize) -> String {
// let fragment = "s_\(serverId)_id_\(coverArtId)_size_\(size.name)"
// }
//
// static fileprivate func imageFromDiskCache(coverArtId: String) -> UIImage {
// return CacheManager.si.imageCache?.object(forKey: coverArtId)
// }
}
| cfd564dab9b4b02058f3ebde26f5b07b | 30.1875 | 134 | 0.608016 | false | false | false | false |
camdenfullmer/UnsplashSwift | refs/heads/master | Source/Extensions.swift | mit | 1 | // Extensions.swift
//
// Copyright (c) 2016 Camden Fullmer (http://camdenfullmer.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 UIColor {
static func colorWithHexString(hex: String) -> UIColor {
guard hex.hasPrefix("#") else {
return UIColor.blackColor()
}
guard let hexString: String = hex.substringFromIndex(hex.startIndex.advancedBy(1)),
var hexValue: UInt32 = 0
where NSScanner(string: hexString).scanHexInt(&hexValue) else {
return UIColor.blackColor()
}
guard hexString.characters.count == 6 else {
return UIColor.blackColor()
}
let divisor = CGFloat(255)
let red = CGFloat((hexValue & 0xFF0000) >> 16) / divisor
let green = CGFloat((hexValue & 0x00FF00) >> 8) / divisor
let blue = CGFloat( hexValue & 0x0000FF ) / divisor
return UIColor(red: red, green: green, blue: blue, alpha: 1)
}
}
extension NSURL {
var queryPairs : [String : String] {
var results = [String: String]()
let pairs = self.query?.componentsSeparatedByString("&") ?? []
for pair in pairs {
let kv = pair.componentsSeparatedByString("=")
results.updateValue(kv[1], forKey: kv[0])
}
return results
}
}
| 2e8412e422212d02aaa12db037e892f0 | 39.416667 | 91 | 0.657732 | false | false | false | false |
Ferrari-lee/News-YC---iPhone | refs/heads/master | HN/CustomViews/Cells/Posts/HNPostsCollectionCell.swift | mit | 5 | //
// HNPostsCollectionCell.swift
// HN
//
// Created by Ben Gordon on 9/9/14.
// Copyright (c) 2014 bennyguitar. All rights reserved.
//
import UIKit
let HNPostsCollectionCellIdentifier = "HNPostsCollectionCellIdentifier"
protocol HNPostsCellDelegate {
func didSelectComments(index: Int)
}
class HNPostsCollectionCell: UITableViewCell {
@IBOutlet var cellTitleLabel : UILabel!
@IBOutlet var cellAuthorLabel : UILabel!
@IBOutlet var cellPointsLabel : UILabel!
@IBOutlet weak var cellBottomBar: UIView!
@IBOutlet weak var commentBubbleButton: UIButton!
@IBOutlet weak var commentCountLabel: UILabel!
@IBOutlet weak var commentButtonOverlay: UIButton!
var index: Int = -1
var del: HNPostsCellDelegate? = nil
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(false, animated: false)
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
super.setHighlighted(false, animated: false)
}
func setContentWithPost(post: HNPost?, indexPath: NSIndexPath?, delegate: HNPostsCellDelegate) {
index = indexPath!.row
del = delegate
cellAuthorLabel.attributedText = postSecondaryAttributedString("\(post!.TimeCreatedString) by \(post!.Username)", matches:post!.Username)
cellTitleLabel.attributedText = postPrimaryAttributedString(post!.Title)
cellBottomBar.backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.Bar)
commentBubbleButton.setImage(HNTheme.currentTheme().imageForCommentBubble(), forState: UIControlState.Normal)
commentCountLabel.text = "\(post!.CommentCount)"
commentBubbleButton.addTarget(self, action: "didSelectCommentsButton", forControlEvents: UIControlEvents.TouchUpInside)
commentButtonOverlay.addTarget(self, action: "didSelectCommentsButton", forControlEvents: UIControlEvents.TouchUpInside)
// Alphas
commentBubbleButton.alpha = 0.25
commentCountLabel.alpha = 1.0
cellTitleLabel.alpha = HNTheme.currentTheme().markAsReadIsActive() && HNManager.sharedManager().hasUserReadPost(post) ? 0.5 : 1.0
//commentCountLabel.textColor = HNOrangeColor
// UI Coloring
// Show HN posts contain "Show HN:" in the title
// Other posts do not. Jobs posts are of type PostType.Jobs
let t = NSString(string: post!.Title)
if (t.contains("Show HN:")) {
// Show HN
backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.ShowHNBackground)
cellBottomBar.backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.ShowHNBar)
}
else {
// Jobs Post
if (post?.Type == PostType.Jobs) {
backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.JobsBackground)
cellBottomBar.backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.JobsBar)
commentBubbleButton.alpha = 0.0
commentCountLabel.alpha = 0.0
cellAuthorLabel.attributedText = postSecondaryAttributedString("HN Jobs", matches: nil)
}
// Normal
else {
backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.BackgroundColor)
}
}
// Backgrounds
cellTitleLabel.backgroundColor = backgroundColor
cellAuthorLabel.backgroundColor = cellBottomBar.backgroundColor
commentCountLabel.textColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.MainFont)
// Set Edge Insets
if (self.respondsToSelector(Selector("layoutMargins"))) {
layoutMargins = UIEdgeInsetsZero
}
}
func postPrimaryAttributedString(t: String!) -> NSAttributedString {
return NSAttributedString(string: t, attributes: [NSForegroundColorAttributeName:HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.MainFont),NSFontAttributeName:UIFont.systemFontOfSize(14.0),NSParagraphStyleAttributeName:NSParagraphStyle.defaultParagraphStyle()])
}
func postSecondaryAttributedString(text: String!, matches: String?) -> NSAttributedString {
return NSAttributedString(string: text, attributes: [NSForegroundColorAttributeName:HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.SubFont),NSFontAttributeName:UIFont.systemFontOfSize(11.0)])
}
func didSelectCommentsButton() {
del?.didSelectComments(index)
}
}
| cc3711cd079a5d44cb5ed1e5419c3362 | 44.951923 | 285 | 0.702867 | false | false | false | false |
toshiapp/toshi-ios-client | refs/heads/master | Toshi/Models/TextTransformer.swift | gpl-3.0 | 1 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import Foundation
public struct TextTransformer {
private static var usernameDetector: NSRegularExpression = {
do {
return try NSRegularExpression(pattern: " ?(@[a-z][a-z0-9_]{2,59}) ?", options: [.caseInsensitive, .useUnicodeWordBoundaries])
} catch {
fatalError("Couldn't instantiate usernameDetector, invalid pattern for regular expression")
}
}()
public static func attributedUsernameString(to string: String?, textColor: UIColor, linkColor: UIColor, font: UIFont) -> NSAttributedString? {
guard let string = string else { return nil }
let attributedText = NSMutableAttributedString(string: string, attributes: [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor])
// string.count returns the number of rendered characters on a string
// but NSAttributedString attributes operate on the utf16 codepoints.
// If a string is using clusters such as emoji, the range will mismatch.
// A visible side-effect of this miscounted string length was usernames
// at the end of strings with emoji not being matched completely.
let range = NSRange(location: 0, length: attributedText.string.utf16.count)
attributedText.addAttributes([.kern: -0.4], range: range)
// Do a link detector first-pass, to avoid creating username links inside URLs that contain an @ sign.
let linkDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let links = linkDetector!.matches(in: attributedText.string, options: [], range: range).reversed()
var excludedRanges = [NSRange]()
for link in links {
excludedRanges.append(link.range)
}
// It's always good practice to traverse and modify strings from the end to the start.
// If any of those changes affect the string length, all the subsequent ranges will be invalidated
// causing all sort of hard to diagnose problems.
let matches = usernameDetector.matches(in: attributedText.string, options: [], range: range).reversed()
for match in matches {
let matchRange = match.range(at: 1)
// Ignore if our username regex matched inside a URL exclusion range.
guard excludedRanges.compactMap({ r -> NSRange? in return matchRange.intersection(r) }).isEmpty else { continue }
let attributes: [NSAttributedStringKey: Any] = [
.link: "toshi://username:\((attributedText.string as NSString).substring(with: matchRange))",
.foregroundColor: linkColor,
.underlineStyle: NSUnderlineStyle.styleSingle.rawValue
]
attributedText.addAttributes(attributes, range: matchRange)
}
return attributedText
}
}
| 199c18775006b1d77d274e0fe88b285b | 50.376812 | 168 | 0.691678 | false | false | false | false |
JGiola/swift-package-manager | refs/heads/master | Sources/PackageDescription4/Version+StringLiteralConvertible.swift | apache-2.0 | 2 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2018 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 Swift project authors
*/
extension Version: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
if let version = Version(value) {
self.init(version)
} else {
// If version can't be initialized using the string literal, report
// the error and initialize with a dummy value. This is done to
// report error to the invoking tool (like swift build) gracefully
// rather than just crashing.
errors.append("Invalid version string: \(value)")
self.init(0, 0, 0)
}
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
}
extension Version {
public init(_ version: Version) {
major = version.major
minor = version.minor
patch = version.patch
prereleaseIdentifiers = version.prereleaseIdentifiers
buildMetadataIdentifiers = version.buildMetadataIdentifiers
}
public init?(_ versionString: String) {
let prereleaseStartIndex = versionString.index(of: "-")
let metadataStartIndex = versionString.index(of: "+")
let requiredEndIndex = prereleaseStartIndex ?? metadataStartIndex ?? versionString.endIndex
let requiredCharacters = versionString.prefix(upTo: requiredEndIndex)
let requiredComponents = requiredCharacters
.split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false)
.map(String.init)
.compactMap({ Int($0) })
.filter({ $0 >= 0 })
guard requiredComponents.count == 3 else { return nil }
self.major = requiredComponents[0]
self.minor = requiredComponents[1]
self.patch = requiredComponents[2]
func identifiers(start: String.Index?, end: String.Index) -> [String] {
guard let start = start else { return [] }
let identifiers = versionString[versionString.index(after: start)..<end]
return identifiers.split(separator: ".").map(String.init)
}
self.prereleaseIdentifiers = identifiers(
start: prereleaseStartIndex,
end: metadataStartIndex ?? versionString.endIndex)
self.buildMetadataIdentifiers = identifiers(start: metadataStartIndex, end: versionString.endIndex)
}
}
| 637e0a978d95824f4fde0a3d7a88897c | 36.135135 | 107 | 0.657569 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/IRGen/class_bounded_generics.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// XFAIL: linux
protocol ClassBound : class {
func classBoundMethod()
}
protocol ClassBound2 : class {
func classBoundMethod2()
}
protocol ClassBoundBinary : ClassBound {
func classBoundBinaryMethod(_ x: Self)
}
@objc protocol ObjCClassBound {
func objCClassBoundMethod()
}
@objc protocol ObjCClassBound2 {
func objCClassBoundMethod2()
}
protocol NotClassBound {
func notClassBoundMethod()
func notClassBoundBinaryMethod(_ x: Self)
}
struct ClassGenericFieldStruct<T:ClassBound> {
var x : Int
var y : T
var z : Int
}
struct ClassProtocolFieldStruct {
var x : Int
var y : ClassBound
var z : Int
}
class ClassGenericFieldClass<T:ClassBound> {
final var x : Int = 0
final var y : T
final var z : Int = 0
init(t: T) {
y = t
}
}
class ClassProtocolFieldClass {
var x : Int = 0
var y : ClassBound
var z : Int = 0
init(classBound cb: ClassBound) {
y = cb
}
}
// CHECK: %T22class_bounded_generics017ClassGenericFieldD0C = type <{ %swift.refcounted, %TSi, %objc_object*, %TSi }>
// CHECK: %T22class_bounded_generics23ClassGenericFieldStructV = type <{ %TSi, %objc_object*, %TSi }>
// CHECK: %T22class_bounded_generics24ClassProtocolFieldStructV = type <{ %TSi, %T22class_bounded_generics10ClassBoundP, %TSi }>
// CHECK-LABEL: define hidden swiftcc %objc_object* @_T022class_bounded_generics0a1_B10_archetype{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T, i8** %T.ClassBound)
func class_bounded_archetype<T : ClassBound>(_ x: T) -> T {
return x
}
class SomeClass {}
class SomeSubclass : SomeClass {}
// CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics9SomeClassC* @_T022class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics9SomeClassC*, %swift.type* %T)
func superclass_bounded_archetype<T : SomeClass>(_ x: T) -> T {
return x
}
// CHECK-LABEL: define hidden swiftcc { %T22class_bounded_generics9SomeClassC*, %T22class_bounded_generics12SomeSubclassC* } @_T022class_bounded_generics011superclass_B15_archetype_call{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics9SomeClassC*, %T22class_bounded_generics12SomeSubclassC*)
func superclass_bounded_archetype_call(_ x: SomeClass, y: SomeSubclass) -> (SomeClass, SomeSubclass) {
return (superclass_bounded_archetype(x),
superclass_bounded_archetype(y));
// CHECK: [[SOMECLASS_RESULT:%.*]] = call swiftcc %T22class_bounded_generics9SomeClassC* @_T022class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics9SomeClassC* {{%.*}}, {{.*}})
// CHECK: [[SOMESUPERCLASS_IN:%.*]] = bitcast %T22class_bounded_generics12SomeSubclassC* {{%.*}} to %T22class_bounded_generics9SomeClassC*
// CHECK: [[SOMESUPERCLASS_RESULT:%.*]] = call swiftcc %T22class_bounded_generics9SomeClassC* @_T022class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics9SomeClassC* [[SOMESUPERCLASS_IN]], {{.*}})
// CHECK: bitcast %T22class_bounded_generics9SomeClassC* [[SOMESUPERCLASS_RESULT]] to %T22class_bounded_generics12SomeSubclassC*
}
// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics0a1_B17_archetype_method{{[_0-9a-zA-Z]*}}F(%objc_object*, %objc_object*, %swift.type* %T, i8** %T.ClassBoundBinary)
func class_bounded_archetype_method<T : ClassBoundBinary>(_ x: T, y: T) {
x.classBoundMethod()
// CHECK: [[INHERITED:%.*]] = load i8*, i8** %T.ClassBoundBinary, align 8
// CHECK: [[INHERITED_WTBL:%.*]] = bitcast i8* [[INHERITED]] to i8**
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[INHERITED_WTBL]], align 8
// CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*, i8**)
// CHECK: call swiftcc void [[WITNESS_FUNC]](%objc_object* swiftself %0, %swift.type* {{.*}}, i8** [[INHERITED_WTBL]])
x.classBoundBinaryMethod(y)
// CHECK: [[WITNESS_ENTRY:%.*]] = getelementptr inbounds i8*, i8** %T.ClassBoundBinary, i32 1
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ENTRY]], align 8
// CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %objc_object*, %swift.type*, i8**)
// CHECK: call %objc_object* @swift_unknownRetain(%objc_object* returned [[Y:%.*]])
// CHECK: call swiftcc void [[WITNESS_FUNC]](%objc_object* [[Y]], %objc_object* swiftself %0, %swift.type* %T, i8** %T.ClassBoundBinary)
}
// CHECK-LABEL: define hidden swiftcc { %objc_object*, %objc_object* } @_T022class_bounded_generics0a1_B16_archetype_tuple{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T, i8** %T.ClassBound)
func class_bounded_archetype_tuple<T : ClassBound>(_ x: T) -> (T, T) {
return (x, x)
}
class ConcreteClass : ClassBoundBinary, NotClassBound {
func classBoundMethod() {}
func classBoundBinaryMethod(_ x: ConcreteClass) {}
func notClassBoundMethod() {}
func notClassBoundBinaryMethod(_ x: ConcreteClass) {}
}
// CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @_T022class_bounded_generics05call_a1_B10_archetype{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics13ConcreteClassC*) {{.*}} {
func call_class_bounded_archetype(_ x: ConcreteClass) -> ConcreteClass {
return class_bounded_archetype(x)
// CHECK: [[IN:%.*]] = bitcast %T22class_bounded_generics13ConcreteClassC* {{%.*}} to %objc_object*
// CHECK: [[OUT_ORIG:%.*]] = call swiftcc %objc_object* @_T022class_bounded_generics0a1_B10_archetype{{[_0-9a-zA-Z]*}}F(%objc_object* [[IN]], {{.*}})
// CHECK: [[OUT:%.*]] = bitcast %objc_object* [[OUT_ORIG]] to %T22class_bounded_generics13ConcreteClassC*
// CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]]
}
// CHECK: define hidden swiftcc void @_T022class_bounded_generics04not_a1_B10_archetype{{[_0-9a-zA-Z]*}}F(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.NotClassBound)
func not_class_bounded_archetype<T : NotClassBound>(_ x: T) -> T {
return x
}
// CHECK-LABEL: define hidden swiftcc %objc_object* @_T022class_bounded_generics0a1_b18_archetype_to_not_a1_B0{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T, i8** %T.ClassBound, i8** %T.NotClassBound) {{.*}} {
func class_bounded_archetype_to_not_class_bounded
<T: ClassBound & NotClassBound>(_ x:T) -> T {
// CHECK: alloca %objc_object*, align 8
return not_class_bounded_archetype(x)
}
/* TODO Abstraction remapping to non-class-bounded witnesses
func class_and_not_class_bounded_archetype_methods
<T: ClassBound & NotClassBound>(_ x:T, y:T) {
x.classBoundMethod()
x.classBoundBinaryMethod(y)
x.notClassBoundMethod()
x.notClassBoundBinaryMethod(y)
}
*/
// CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @_T022class_bounded_generics0a1_B8_erasure{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics13ConcreteClassC*) {{.*}} {
func class_bounded_erasure(_ x: ConcreteClass) -> ClassBound {
return x
// CHECK: [[INSTANCE_OPAQUE:%.*]] = bitcast %T22class_bounded_generics13ConcreteClassC* [[INSTANCE:%.*]] to %objc_object*
// CHECK: [[T0:%.*]] = insertvalue { %objc_object*, i8** } undef, %objc_object* [[INSTANCE_OPAQUE]], 0
// CHECK: [[T1:%.*]] = insertvalue { %objc_object*, i8** } [[T0]], i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @_T022class_bounded_generics13ConcreteClassCAA0E5BoundAAWP, i32 0, i32 0), 1
// CHECK: ret { %objc_object*, i8** } [[T1]]
}
// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics0a1_B16_protocol_method{{[_0-9a-zA-Z]*}}F(%objc_object*, i8**) {{.*}} {
func class_bounded_protocol_method(_ x: ClassBound) {
x.classBoundMethod()
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getObjectType(%objc_object* %0)
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_TABLE:%.*]], align 8
// CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*, i8**)
// CHECK: call swiftcc void [[WITNESS_FN]](%objc_object* swiftself %0, %swift.type* [[METADATA]], i8** [[WITNESS_TABLE]])
}
// CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @_T022class_bounded_generics0a1_B15_archetype_cast{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T, i8** %T.ClassBound)
func class_bounded_archetype_cast<T : ClassBound>(_ x: T) -> ConcreteClass {
return x as! ConcreteClass
// CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8*
// CHECK: [[T0:%.*]] = call %swift.type* @_T022class_bounded_generics13ConcreteClassCMa()
// CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8*
// CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]])
// CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %T22class_bounded_generics13ConcreteClassC*
// CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]]
}
// CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @_T022class_bounded_generics0a1_B14_protocol_cast{{[_0-9a-zA-Z]*}}F(%objc_object*, i8**)
func class_bounded_protocol_cast(_ x: ClassBound) -> ConcreteClass {
return x as! ConcreteClass
// CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8*
// CHECK: [[T0:%.*]] = call %swift.type* @_T022class_bounded_generics13ConcreteClassCMa()
// CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8*
// CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]])
// CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %T22class_bounded_generics13ConcreteClassC*
// CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]]
}
// CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @_T022class_bounded_generics0a1_B22_protocol_conversion_{{.*}}(%objc_object*, i8**, i8**) {{.*}} {
func class_bounded_protocol_conversion_1(_ x: ClassBound & ClassBound2)
-> ClassBound {
return x
}
// CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @_T022class_bounded_generics0a1_B22_protocol_conversion_{{.*}}(%objc_object*, i8**, i8**) {{.*}} {
func class_bounded_protocol_conversion_2(_ x: ClassBound & ClassBound2)
-> ClassBound2 {
return x
}
// CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @_T022class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}(%objc_object*, i8**) {{.*}} {
func objc_class_bounded_protocol_conversion_1
(_ x: ClassBound & ObjCClassBound) -> ClassBound {
return x
}
// CHECK-LABEL: define hidden swiftcc %objc_object* @_T022class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}(%objc_object*, i8**) {{.*}} {
func objc_class_bounded_protocol_conversion_2
(_ x: ClassBound & ObjCClassBound) -> ObjCClassBound {
return x
}
// CHECK-LABEL: define hidden swiftcc %objc_object* @_T022class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}(%objc_object*)
func objc_class_bounded_protocol_conversion_3
(_ x: ObjCClassBound & ObjCClassBound2) -> ObjCClassBound {
return x
}
// CHECK-LABEL: define hidden swiftcc %objc_object* @_T022class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}(%objc_object*)
func objc_class_bounded_protocol_conversion_4
(_ x: ObjCClassBound & ObjCClassBound2) -> ObjCClassBound2 {
return x
}
// CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i64 } @_T022class_bounded_generics0A28_generic_field_struct_fields{{[_0-9a-zA-Z]*}}F(i64, %objc_object*, i64, %swift.type* %T, i8** %T.ClassBound)
func class_generic_field_struct_fields<T>
(_ x:ClassGenericFieldStruct<T>) -> (Int, T, Int) {
return (x.x, x.y, x.z)
}
// CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i8**, i64 } @_T022class_bounded_generics0A29_protocol_field_struct_fields{{[_0-9a-zA-Z]*}}F(i64, %objc_object*, i8**, i64)
func class_protocol_field_struct_fields
(_ x:ClassProtocolFieldStruct) -> (Int, ClassBound, Int) {
return (x.x, x.y, x.z)
}
// CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i64 } @_T022class_bounded_generics0a15_generic_field_A7_fields{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics017ClassGenericFieldD0C*)
func class_generic_field_class_fields<T>
(_ x:ClassGenericFieldClass<T>) -> (Int, T, Int) {
return (x.x, x.y, x.z)
// CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 1
// CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 2
// CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 3
}
// CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i8**, i64 } @_T022class_bounded_generics0a16_protocol_field_A7_fields{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics018ClassProtocolFieldD0C*)
func class_protocol_field_class_fields(_ x: ClassProtocolFieldClass)
-> (Int, ClassBound, Int) {
return (x.x, x.y, x.z)
// CHECK: = call swiftcc i64 %{{[0-9]+}}
// CHECK: = call swiftcc { %objc_object*, i8** } %{{[0-9]+}}
// CHECK: = call swiftcc i64 %{{[0-9]+}}
}
class SomeSwiftClass {
class func foo() {}
}
// T must have a Swift layout, so we can load this metatype with a direct access.
// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics0a1_B9_metatype{{[_0-9a-zA-Z]*}}F
// CHECK: [[T0:%.*]] = getelementptr inbounds %T22class_bounded_generics14SomeSwiftClassC, %T22class_bounded_generics14SomeSwiftClassC* {{%.*}}, i32 0, i32 0, i32 0
// CHECK-NEXT: [[T1:%.*]] = load %swift.type*, %swift.type** [[T0]], align 8
// CHECK-NEXT: [[T2:%.*]] = bitcast %swift.type* [[T1]] to void (%swift.type*)**
// CHECK-NEXT: [[T3:%.*]] = getelementptr inbounds void (%swift.type*)*, void (%swift.type*)** [[T2]], i64 10
// CHECK-NEXT: load void (%swift.type*)*, void (%swift.type*)** [[T3]], align 8
func class_bounded_metatype<T: SomeSwiftClass>(_ t : T) {
type(of: t).foo()
}
class WeakRef<T: AnyObject> {
weak var value: T?
}
class A<T> {
required init() {}
}
class M<T, S: A<T>> {
private var s: S
init() {
// Don't crash generating the reference to 's'.
s = S.init()
}
}
// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics14takes_metatypeyxmlF(%swift.type*, %swift.type* %T)
func takes_metatype<T>(_: T.Type) {}
// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics023archetype_with_generic_A11_constraintyx1t_tAA1ACyq_GRbzr0_lF(%T22class_bounded_generics1AC.2*, %swift.type* %T)
// CHECK: [[ISA_ADDR:%.*]] = bitcast %T22class_bounded_generics1AC.2* %0 to %swift.type**
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK-NEXT: call swiftcc void @_T022class_bounded_generics14takes_metatypeyxmlF(%swift.type* %T, %swift.type* %T)
// CHECK-NEXT: [[ISA_PTR:%.*]] = bitcast %swift.type* [[ISA]] to %swift.type**
// CHECK-NEXT: [[U_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[ISA_PTR]], i64 10
// CHECK-NEXT: [[U:%.*]] = load %swift.type*, %swift.type** [[U_ADDR]]
// CHECK-NEXT: call swiftcc void @_T022class_bounded_generics14takes_metatypeyxmlF(%swift.type* %U, %swift.type* %U)
// CHECK: ret void
func archetype_with_generic_class_constraint<T, U>(t: T) where T : A<U> {
takes_metatype(T.self)
takes_metatype(U.self)
}
// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics029calls_archetype_with_generic_A11_constraintyAA1ACyxG1a_tlF(%T22class_bounded_generics1AC*) #0 {
// CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T22class_bounded_generics1AC, %T22class_bounded_generics1AC* %0, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK: [[SELF:%.*]] = bitcast %T22class_bounded_generics1AC* %0 to %T22class_bounded_generics1AC.2*
// CHECK-NEXT: [[ISA_PTR:%.*]] = bitcast %swift.type* [[ISA]] to %swift.type**
// CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[ISA_PTR]], i64 10
// CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]]
// CHECK-NEXT: [[A_OF_T:%.*]] = call %swift.type* @_T022class_bounded_generics1ACMa(%swift.type* [[T]])
// CHECK-NEXT: call swiftcc void @_T022class_bounded_generics023archetype_with_generic_A11_constraintyx1t_tAA1ACyq_GRbzr0_lF(%T22class_bounded_generics1AC.2* [[SELF]], %swift.type* [[A_OF_T]])
// CHECK: ret void
func calls_archetype_with_generic_class_constraint<T>(a: A<T>) {
archetype_with_generic_class_constraint(t: a)
}
| d4b292bbcb72fc8d4765d6781f167942 | 52.457792 | 287 | 0.685636 | false | false | false | false |
ccrama/Slide-iOS | refs/heads/master | Slide for Reddit/UIImage+Extensions.swift | apache-2.0 | 1 | //
// UIImage+Extensions.swift
// Slide for Reddit
//
// Created by Jonathan Cole on 6/26/18.
// Copyright © 2018 Haptic Apps. All rights reserved.
//
import UIKit
extension UIImage {
func getCopy(withSize size: CGSize) -> UIImage {
let maxWidth = size.width
let maxHeight = size.height
let imgWidth = self.size.width
let imgHeight = self.size.height
let widthRatio = maxWidth / imgWidth
let heightRatio = maxHeight / imgHeight
let bestRatio = min(widthRatio, heightRatio)
let newWidth = imgWidth * bestRatio,
newHeight = imgHeight * bestRatio
let biggerSize = CGSize(width: newWidth, height: newHeight)
var newImage: UIImage
if #available(iOS 10.0, *) {
let renderFormat = UIGraphicsImageRendererFormat.default()
renderFormat.opaque = false
let renderer = UIGraphicsImageRenderer(size: CGSize(width: biggerSize.width, height: biggerSize.height), format: renderFormat)
newImage = renderer.image { (_) in
self.draw(in: CGRect(x: 0, y: 0, width: biggerSize.width, height: biggerSize.height))
}
} else {
UIGraphicsBeginImageContextWithOptions(CGSize(width: biggerSize.width, height: biggerSize.height), false, 0)
self.draw(in: CGRect(x: 0, y: 0, width: biggerSize.width, height: biggerSize.height))
newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
}
return newImage
}
func cropImageByAlpha() -> UIImage {
let cgImage = self.cgImage
let context = createARGBBitmapContextFromImage(inImage: cgImage!)
let height = cgImage!.height
let width = cgImage!.width
var rect: CGRect = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))
context?.draw(cgImage!, in: rect)
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
var minX = width
var minY = height
var maxX: Int = 0
var maxY: Int = 0
//Filter through data and look for non-transparent pixels.
for y in 0..<height {
for x in 0..<width {
let pixelIndex = (width * y + x) * 4 /* 4 for A, R, G, B */
if data[Int(pixelIndex)] != 0 { //Alpha value is not zero pixel is not transparent.
if x < minX {
minX = x
}
if x > maxX {
maxX = x
}
if y < minY {
minY = y
}
if y > maxY {
maxY = y
}
}
}
}
rect = CGRect( x: CGFloat(minX), y: CGFloat(minY), width: CGFloat(maxX - minX), height: CGFloat(maxY - minY))
let imageScale: CGFloat = self.scale
let cgiImage = self.cgImage?.cropping(to: rect)
return UIImage(cgImage: cgiImage!, scale: imageScale, orientation: self.imageOrientation)
}
private func createARGBBitmapContextFromImage(inImage: CGImage) -> CGContext? {
let width = cgImage!.width
let height = cgImage!.height
let bitmapBytesPerRow = width * 4
let bitmapByteCount = bitmapBytesPerRow * height
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapData = malloc(bitmapByteCount)
if bitmapData == nil {
return nil
}
let context = CGContext(data: bitmapData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bitmapBytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)
return context
}
convenience init?(sfString: SFSymbol, overrideString: String) {
if #available(iOS 13, *) {
let config = UIImage.SymbolConfiguration(pointSize: 15, weight: UIImage.SymbolWeight.regular, scale: UIImage.SymbolScale.small)
self.init(systemName: sfString.rawValue, withConfiguration: config)
} else {
self.init(named: overrideString)
}
}
convenience init?(sfStringHQ: SFSymbol, overrideString: String) {
if #available(iOS 13, *) {
let config = UIImage.SymbolConfiguration(pointSize: 30, weight: UIImage.SymbolWeight.regular, scale: UIImage.SymbolScale.large)
self.init(systemName: sfStringHQ.rawValue, withConfiguration: config)
} else {
self.init(named: overrideString)
}
}
func getCopy(withColor color: UIColor) -> UIImage {
if #available(iOS 10, *) {
let renderer = UIGraphicsImageRenderer(size: size)
return renderer.image { context in
color.setFill()
self.draw(at: .zero)
context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height), blendMode: .sourceAtop)
}
} else {
var image = withRenderingMode(.alwaysTemplate)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.set()
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
func getCopy(withSize size: CGSize, withColor color: UIColor) -> UIImage {
return self.getCopy(withSize: size).getCopy(withColor: color)
}
// TODO: - These should make only one copy and do in-place operations on those
func navIcon(_ white: Bool = false) -> UIImage {
return self.getCopy(withSize: CGSize(width: 25, height: 25), withColor: SettingValues.reduceColor && !white ? ColorUtil.theme.navIconColor : .white)
}
func smallIcon() -> UIImage {
return self.getCopy(withSize: CGSize(width: 12, height: 12), withColor: ColorUtil.theme.navIconColor)
}
func toolbarIcon() -> UIImage {
return self.getCopy(withSize: CGSize(width: 25, height: 25), withColor: ColorUtil.theme.navIconColor)
}
func menuIcon() -> UIImage {
return self.getCopy(withSize: CGSize(width: 20, height: 20), withColor: ColorUtil.theme.navIconColor)
}
func cropToBounds(image: UIImage, width: Double, height: Double) -> UIImage {
let contextImage: UIImage = UIImage(cgImage: image.cgImage!)
let contextSize: CGSize = contextImage.size
var posX: CGFloat = 0.0
var posY: CGFloat = 0.0
var cgwidth: CGFloat = CGFloat(width)
var cgheight: CGFloat = CGFloat(height)
// See what size is longer and create the center off of that
if contextSize.width > contextSize.height {
posX = ((contextSize.width - contextSize.height) / 2)
posY = 0
cgwidth = contextSize.height
cgheight = contextSize.height
} else {
posX = 0
posY = ((contextSize.height - contextSize.width) / 2)
cgwidth = contextSize.width
cgheight = contextSize.width
}
let rect: CGRect = CGRect.init(x: posX, y: posY, width: cgwidth, height: cgheight)
// Create bitmap image from context using the rect
let imageRef: CGImage = (contextImage.cgImage?.cropping(to: rect)!)!
// Create a new image based on the imageRef and rotate back to the original orientation
let image: UIImage = UIImage.init(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
return image
}
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
func overlayWith(image: UIImage, posX: CGFloat, posY: CGFloat) -> UIImage {
let newWidth = size.width < posX + image.size.width ? posX + image.size.width : size.width
let newHeight = size.height < posY + image.size.height ? posY + image.size.height : size.height
let newSize = CGSize(width: newWidth, height: newHeight)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
draw(in: CGRect(origin: CGPoint.zero, size: size))
image.draw(in: CGRect(origin: CGPoint(x: posX, y: posY), size: image.size))
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
class func convertGradientToImage(colors: [UIColor], frame: CGSize) -> UIImage {
let rect = CGRect.init(x: 0, y: 0, width: frame.width, height: frame.height)
// start with a CAGradientLayer
let gradientLayer = CAGradientLayer()
gradientLayer.frame = rect
// add colors as CGCologRef to a new array and calculate the distances
var colorsRef = [CGColor]()
var locations = [NSNumber]()
for i in 0 ..< colors.count {
colorsRef.append(colors[i].cgColor as CGColor)
locations.append(NSNumber(value: Float(i) / Float(colors.count - 1)))
}
gradientLayer.colors = colorsRef
let x: CGFloat = 135.0 / 360.0
let a: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.75) / 2.0)), 2.0)
let b: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.00) / 2.0)), 2.0)
let c: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.25) / 2.0)), 2.0)
let d: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.50) / 2.0)), 2.0)
gradientLayer.endPoint = CGPoint(x: c, y: d)
gradientLayer.startPoint = CGPoint(x: a, y: b)
// now build a UIImage from the gradient
UIGraphicsBeginImageContext(gradientLayer.bounds.size)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// return the gradient image
return gradientImage!
}
func areaAverage() -> UIColor {
var bitmap = [UInt8](repeating: 0, count: 4)
if #available(iOS 9.0, *) {
// Get average color.
let context = CIContext()
let inputImage: CIImage = ciImage ?? CoreImage.CIImage(cgImage: cgImage!)
let extent = inputImage.extent
let inputExtent = CIVector(x: extent.origin.x, y: extent.origin.y, z: extent.size.width, w: extent.size.height)
let filter = CIFilter(name: "CIAreaAverage", parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: inputExtent])!
let outputImage = filter.outputImage!
let outputExtent = outputImage.extent
assert(outputExtent.size.width == 1 && outputExtent.size.height == 1)
// Render to bitmap.
context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: CIFormat.RGBA8, colorSpace: CGColorSpaceCreateDeviceRGB())
} else {
// Create 1x1 context that interpolates pixels when drawing to it.
let context = CGContext(data: &bitmap, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
let inputImage = cgImage ?? CIContext().createCGImage(ciImage!, from: ciImage!.extent)
// Render to bitmap.
context.draw(inputImage!, in: CGRect(x: 0, y: 0, width: 1, height: 1))
}
// Compute result.
let result = UIColor(red: CGFloat(bitmap[0]) / 255.0, green: CGFloat(bitmap[1]) / 255.0, blue: CGFloat(bitmap[2]) / 255.0, alpha: CGFloat(bitmap[3]) / 255.0)
return result
}
/**
https://stackoverflow.com/a/62862742/3697225
Rounds corners of UIImage
- Parameter proportion: Proportion to minimum paramter (width or height)
in order to have the same look of corner radius independetly
from aspect ratio and actual size
*/
func roundCorners(proportion: CGFloat) -> UIImage {
let minValue = min(self.size.width, self.size.height)
let radius = minValue/proportion
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: self.size)
UIGraphicsBeginImageContextWithOptions(self.size, false, 1)
UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
self.draw(in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
return image
}
}
extension UIImage {
func withBackground(color: UIColor, opaque: Bool = true) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
guard let ctx = UIGraphicsGetCurrentContext(), let image = cgImage else { return self }
defer { UIGraphicsEndImageContext() }
let rect = CGRect(origin: .zero, size: size)
ctx.setFillColor(color.cgColor)
ctx.fill(rect)
ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height))
ctx.draw(image, in: rect)
return UIGraphicsGetImageFromCurrentImageContext() ?? self
}
}
extension UIImage {
func withPadding(_ padding: CGFloat) -> UIImage? {
return withPadding(x: padding, y: padding)
}
func withPadding(x: CGFloat, y: CGFloat) -> UIImage? {
let newWidth = size.width + 2 * x
let newHeight = size.height + 2 * y
let newSize = CGSize(width: newWidth, height: newHeight)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
let origin = CGPoint(x: (newWidth - size.width) / 2, y: (newHeight - size.height) / 2)
draw(at: origin)
let imageWithPadding = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithPadding
}
}
| bc2e2fd9c32c45f2d05df7758b61971d | 40.065156 | 209 | 0.609547 | false | false | false | false |
calkinssean/TIY-Assignments | refs/heads/master | Day 37/RealmApp/RealmApp/ViewController.swift | cc0-1.0 | 1 | //
// ViewController.swift
// RealmApp
//
// Created by Sean Calkins on 3/23/16.
// Copyright © 2016 Sean Calkins. All rights reserved.
//
import UIKit
import RealmSwift
class ViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
let realm = try! Realm()
var currentUser = User()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
self.usernameTextField.text = ""
self.passwordTextField.text = ""
}
@IBAction func loginTapped(sender: UIButton) {
let searchedUsers = realm.objects(User).filter("username == '\(usernameTextField.text!)'")
var correctLogin = false
for user in searchedUsers {
if user.password == passwordTextField.text! {
correctLogin = true
self.currentUser = user
}
}
if correctLogin == true {
print("logged in")
performSegueWithIdentifier("loggedInSegue", sender: self)
} else {
presentAlert("Incorrect username and password.")
}
}
@IBAction func unwindSegue (segue: UIStoryboardSegue) {}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "loggedInSegue" {
let control = segue.destinationViewController as! NotesTableViewController
control.currentUser = self.currentUser
}
}
func presentAlert(alertMessage: String) {
let alertController = UIAlertController(title: "Oops", message: "\(alertMessage)", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
self.usernameTextField.text = ""
self.passwordTextField.text = ""
}
}
| ee96c1f305050df7ad1df93bfb7e304f | 26.847059 | 114 | 0.584284 | false | false | false | false |
danielgindi/Charts | refs/heads/master | ChartsDemo-iOS/Swift/Formatters/LargeValueFormatter.swift | apache-2.0 | 2 | //
// LargeValueFormatter.swift
// ChartsDemo
// Copyright © 2016 dcg. All rights reserved.
//
import Foundation
import Charts
private let MAX_LENGTH = 5
@objc protocol Testing123 { }
public class LargeValueFormatter: NSObject, ValueFormatter, AxisValueFormatter {
/// Suffix to be appended after the values.
///
/// **default**: suffix: ["", "k", "m", "b", "t"]
public var suffix = ["", "k", "m", "b", "t"]
/// An appendix text to be added at the end of the formatted value.
public var appendix: String?
public init(appendix: String? = nil) {
self.appendix = appendix
}
fileprivate func format(value: Double) -> String {
var sig = value
var length = 0
let maxLength = suffix.count - 1
while sig >= 1000.0 && length < maxLength {
sig /= 1000.0
length += 1
}
var r = String(format: "%2.f", sig) + suffix[length]
if let appendix = appendix {
r += appendix
}
return r
}
public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return format(value: value)
}
public func stringForValue(
_ value: Double,
entry: ChartDataEntry,
dataSetIndex: Int,
viewPortHandler: ViewPortHandler?) -> String {
return format(value: value)
}
}
| 98fa93e58bfc206fae700646c736af02 | 23.637931 | 80 | 0.554934 | false | false | false | false |
tomomura/PasscodeField | refs/heads/master | PasscodeField/Classes/PasscodeField.swift | mit | 1 | //
// PasscodeField.swift
// Pods
//
// Created by TomomuraRyota on 2016/05/30.
//
//
import UIKit
@IBDesignable public class PasscodeField: UIView {
// MARK: - Properties
@IBInspectable public var length: Int = 6 {
didSet {
self.progressView.length = self.length
}
}
@IBInspectable public var progress: Int = 0 {
didSet {
self.progressView.progress = self.progress
}
}
@IBInspectable public var borderHeight: CGFloat = 2.0 {
didSet {
self.progressView.borderHeight = self.borderHeight
}
}
@IBInspectable public var fillColor: UIColor = UIColor.blackColor() {
didSet {
self.progressView.fillColor = self.fillColor
}
}
@IBInspectable public var fillSize: CGFloat = 20 {
didSet {
self.progressView.fillSize = self.fillSize
}
}
private var progressView: ProgressStackView
// MARK: - Initializers
required public init?(coder aDecoder: NSCoder) {
self.progressView = ProgressStackView(
length: self.length,
progress: self.progress,
borderHeight: self.borderHeight,
fillSize: self.fillSize,
fillColor: self.fillColor
)
super.init(coder: aDecoder)
self.setupView()
}
override public init(frame: CGRect) {
self.progressView = ProgressStackView(
length: self.length,
progress: self.progress,
borderHeight: self.borderHeight,
fillSize: self.fillSize,
fillColor: self.fillColor
)
super.init(frame: frame)
self.setupView()
}
// MARK: - LifeCycle
override public func updateConstraints() {
NSLayoutConstraint.activateConstraints([
self.progressView.topAnchor.constraintEqualToAnchor(self.topAnchor),
self.progressView.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor),
self.progressView.leadingAnchor.constraintEqualToAnchor(self.leadingAnchor),
self.progressView.trailingAnchor.constraintEqualToAnchor(self.trailingAnchor),
])
super.updateConstraints()
}
// MARK: - Private Methods
private func setupView() {
self.addSubview(progressView)
}
}
| 4c07d41d2335032f596d64d28ec324d5 | 24.604167 | 90 | 0.588283 | false | false | false | false |
otakisan/SmartToDo | refs/heads/master | SmartToDo/Views/Cells/ToDoEditorPickerBaseTableViewCell.swift | mit | 1 | //
// ToDoEditorPickerBaseTableViewCell.swift
// SmartToDo
//
// Created by takashi on 2014/11/03.
// Copyright (c) 2014年 ti. All rights reserved.
//
import UIKit
class ToDoEditorPickerBaseTableViewCell: ToDoEditorBaseTableViewCell {
lazy var dataLists : [[String]] = self.createPickerDataSource()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func setValueOfCell(value: AnyObject) {
if let entityData = value as? String {
self.setStringValueOfCell(entityData)
}
else if let entityDataNumber = value as? NSNumber {
self.setStringValueOfCell(String(format: "%f", entityDataNumber.floatValue))
}
}
func setStringValueOfCell(valueString : String) {
}
func completeDelegate() -> ((UIView) -> Void)? {
return self.didFinishDetailView
}
func didFinishDetailView(detailView : UIView){
if let view = detailView as? UIPickerView {
// 現在の仕様上は、1区分のみ必要のため、固定で先頭区分から取得
// 区分ごとの個別の値を返却する必要が出たら、タプルにして返却する
let selectedIndex = view.selectedRowInComponent(0)
if selectedIndex >= 0 {
let valueString = self.dataLists[0][selectedIndex]
self.didFinishPickerView(valueString)
}
}
else if let textField = detailView as? UITextField {
self.didFinishPickerView(textField.text ?? "")
}
}
func didFinishPickerView(selectedValue : String) {
}
override func createDetailView() -> UIViewController? {
let vc = self.loadDetailView()
vc?.canFreeText = self.canFreeText()
vc?.syncSelectionAmongComponents = self.syncSelectionAmongComponents()
vc?.setCompleteDeleage(self.completeDelegate())
return vc
}
func loadDetailView() -> CommonPickerViewController? {
let vc = NSBundle.mainBundle().loadNibNamed("CommonPickerViewController", owner: nil, options: nil)[0] as? CommonPickerViewController
return vc
}
override func detailViewController() -> UIViewController? {
let vc = super.detailViewController() as? CommonPickerViewController
vc?.setDataSource(self.dataSource())
vc?.setViewValue(self.detailViewInitValue())
return vc
}
func detailViewInitValue() -> AnyObject? {
return nil
}
func dataSource() -> [[String]] {
return dataLists
}
func createPickerDataSource() -> [[String]] {
return [[]]
}
func canFreeText() -> Bool {
return false
}
func syncSelectionAmongComponents() -> Bool {
return false
}
}
| efb35ab37ca61a6f2305af01d3f5cf90 | 26.759259 | 141 | 0.612408 | false | false | false | false |
alessiobrozzi/firefox-ios | refs/heads/master | Extensions/ShareTo/InitialViewController.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
private let LastUsedShareDestinationsKey = "LastUsedShareDestinations"
@objc(InitialViewController)
class InitialViewController: UIViewController, ShareControllerDelegate {
var shareDialogController: ShareDialogController!
lazy var profile: Profile = {
return BrowserProfile(localName: "profile", app: nil)
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(white: 0.0, alpha: 0.66) // TODO: Is the correct color documented somewhere?
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
ExtensionUtils.extractSharedItemFromExtensionContext(self.extensionContext, completionHandler: { (item, error) -> Void in
if let item = item, error == nil {
DispatchQueue.main.async {
guard item.isShareable else {
let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.finish() })
self.present(alert, animated: true, completion: nil)
return
}
self.presentShareDialog(item)
}
} else {
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
})
}
//
func shareControllerDidCancel(_ shareController: ShareDialogController) {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 0.0
}, completion: { (Bool) -> Void in
self.dismissShareDialog()
self.finish()
})
}
func finish() {
self.profile.shutdown()
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
func shareController(_ shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) {
setLastUsedShareDestinations(destinations)
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 0.0
}, completion: { (Bool) -> Void in
self.dismissShareDialog()
if destinations.contains(ShareDestinationReadingList) {
self.shareToReadingList(item)
}
if destinations.contains(ShareDestinationBookmarks) {
self.shareToBookmarks(item)
}
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
})
}
//
// TODO: use Set.
func getLastUsedShareDestinations() -> NSSet {
if let destinations = UserDefaults.standard.object(forKey: LastUsedShareDestinationsKey) as? NSArray {
return NSSet(array: destinations as [AnyObject])
}
return NSSet(object: ShareDestinationBookmarks)
}
func setLastUsedShareDestinations(_ destinations: NSSet) {
UserDefaults.standard.set(destinations.allObjects, forKey: LastUsedShareDestinationsKey)
UserDefaults.standard.synchronize()
}
func presentShareDialog(_ item: ShareItem) {
shareDialogController = ShareDialogController()
shareDialogController.delegate = self
shareDialogController.item = item
shareDialogController.initialShareDestinations = getLastUsedShareDestinations()
self.addChildViewController(shareDialogController)
shareDialogController.view.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(shareDialogController.view)
shareDialogController.didMove(toParentViewController: self)
// Setup constraints for the dialog. We keep the dialog centered with 16 points of padding on both
// sides. The dialog grows to max 380 points wide so that it does not look too big on landscape or
// iPad devices.
let views: NSDictionary = ["dialog": shareDialogController.view]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(16@751)-[dialog(<=380@1000)]-(16@751)-|",
options: NSLayoutFormatOptions(), metrics: nil, views: (views as? [String : AnyObject])!))
let cx = NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0)
cx.priority = 1000 // TODO: Why does UILayoutPriorityRequired give a linker error? SDK Bug?
view.addConstraint(cx)
view.addConstraint(NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0))
// Fade the dialog in
shareDialogController.view.alpha = 0.0
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 1.0
}, completion: nil)
}
func dismissShareDialog() {
shareDialogController.willMove(toParentViewController: nil)
shareDialogController.view.removeFromSuperview()
shareDialogController.removeFromParentViewController()
}
//
func shareToReadingList(_ item: ShareItem) {
profile.readingList?.createRecordWithURL(item.url, title: item.title ?? "", addedBy: UIDevice.current.name)
}
func shareToBookmarks(_ item: ShareItem) {
profile.bookmarks.shareItem(item)
}
}
| 5ab0c039cab6b673b57fefef0c432c99 | 40.857143 | 147 | 0.65529 | false | false | false | false |
dipen30/Qmote | refs/heads/master | KodiRemote/KodiRemote/Controllers/RemoteController.swift | apache-2.0 | 1 | //
// RemoteController.swift
// Kodi Remote
//
// Created by Quixom Technology on 18/12/15.
// Copyright © 2015 Quixom Technology. All rights reserved.
//
import Foundation
import Kingfisher
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
class RemoteController: ViewController {
@IBOutlet var itemName: UILabel!
@IBOutlet var otherDetails: UILabel!
@IBOutlet var activePlayerImage: UIImageView!
@IBOutlet var nothingPlaying: UILabel!
@IBOutlet var play: UIButton!
@IBOutlet var pause: UIButton!
@IBOutlet var timeLabel: UILabel!
@IBOutlet var totalTimeLabel: UILabel!
@IBOutlet var seekBar: UISlider!
var playerId = 0
var player_repeat = "off"
var shuffle = false
@IBOutlet var musicButtonLeadingSpace: NSLayoutConstraint!
@IBOutlet var videoButtonTrailingSpace: NSLayoutConstraint!
@IBOutlet var repeatButtonLeadingSpace: NSLayoutConstraint!
@IBOutlet var volumUpLeadingSpace: NSLayoutConstraint!
@IBOutlet var playerRepeat: UIButton!
@IBOutlet var playerShuffle: UIButton!
@IBOutlet weak var backgroundImage: UIImageView!
var rc: RemoteCalls!
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer())
}
override func viewDidAppear(_ animated: Bool) {
self.view.viewWithTag(2)?.isHidden = true
self.backgroundImage.layer.opacity = 0.1
self.view.viewWithTag(2)?.layer.opacity = 0.9
self.view.viewWithTag(1)?.layer.opacity = 0.9
let previous_ip = UserDefaults.standard
if let ip = previous_ip.string(forKey: "ip"){
global_ipaddress = ip
}
if let port = previous_ip.string(forKey: "port"){
global_port = port
}
if global_ipaddress == "" {
let discovery = self.storyboard?.instantiateViewController(withIdentifier: "DiscoveryView") as! DiscoveryTableViewController
self.navigationController?.pushViewController(discovery, animated: true)
}
if global_ipaddress != "" {
rc = RemoteCalls(ipaddress: global_ipaddress, port: global_port)
self.syncPlayer()
}
}
func syncPlayer(){
self.rc.jsonRpcCall("Player.GetActivePlayers"){(response: AnyObject?) in
if response!.count == 0 {
DispatchQueue.main.async(execute: {
self.view.viewWithTag(2)?.isHidden = true
self.nothingPlaying.isHidden = false
self.backgroundImage.isHidden = true
})
return
}
DispatchQueue.main.async(execute: {
self.view.viewWithTag(2)?.isHidden = false
self.nothingPlaying.isHidden = true
self.backgroundImage.isHidden = false
})
let response = (response as! NSArray)[0] as? NSDictionary
self.playerId = response!["playerid"] as! Int
self.rc.jsonRpcCall("Player.GetProperties", params: "{\"playerid\":\(self.playerId),\"properties\":[\"percentage\",\"time\",\"totaltime\", \"repeat\",\"shuffled\",\"speed\",\"subtitleenabled\"]}"){(response: AnyObject?) in
DispatchQueue.main.async(execute: {
let response = response as? NSDictionary
self.shuffle = response!["shuffled"] as! Bool
self.player_repeat = response!["repeat"] as! String
let repeateImage = self.player_repeat == "off" ? "Repeat": "RepeatSelected"
self.playerRepeat.imageView?.image = UIImage(named: repeateImage)
let suffleImage = self.shuffle == true ? "shuffleSelected" : "shuffle"
self.playerShuffle.imageView?.image = UIImage(named: suffleImage)
if response!["speed"] as! Int == 0 {
self.play.isHidden = false
self.pause.isHidden = true
}else{
self.play.isHidden = true
self.pause.isHidden = false
}
self.timeLabel.text = self.toMinutes(response!["time"] as! NSDictionary)
self.totalTimeLabel.text = self.toMinutes(response!["totaltime"] as! NSDictionary)
self.seekBar.value = (response!["percentage"] as! Float) / 100
})
self.rc.jsonRpcCall("Player.GetItem", params: "{\"playerid\":\(self.playerId),\"properties\":[\"title\",\"artist\",\"thumbnail\", \"fanart\", \"album\",\"year\"]}"){(response: AnyObject?) in
DispatchQueue.main.async(execute: {
let response = response as? NSDictionary
self.generateResponse(response!)
});
}
}
}
// 1 second trigger Time
let triggerTime = Int64(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(triggerTime) / Double(NSEC_PER_SEC), execute: { () -> Void in
self.syncPlayer()
})
}
@IBAction func sliderTouchUp(_ sender: UISlider) {
// RPC call for seek
let value = Int(sender.value * 100)
self.seekBar.value = sender.value
rc.jsonRpcCall("Player.Seek", params: "{\"playerid\":\(self.playerId), \"value\":\(value)}"){(response: AnyObject?) in
}
}
func generateResponse(_ jsonData: AnyObject){
for(key, value) in jsonData["item"] as! NSDictionary{
if key as! String == "label" {
self.itemName.text = value as? String
}
if key as! String == "artist" {
self.otherDetails.text = ""
if (value as AnyObject).count != 0 {
self.otherDetails.text = (value as! NSArray)[0] as? String
}
}
if key as! String == "thumbnail" {
self.activePlayerImage.contentMode = .scaleAspectFit
let url = URL(string: getThumbnailUrl(value as! String))
self.activePlayerImage.kf.setImage(with: url!)
}
if key as! String == "fanart" {
self.backgroundImage.contentMode = .scaleAspectFill
let url = URL(string: getThumbnailUrl(value as! String))
self.backgroundImage.kf.setImage(with: url!)
}
}
}
func toMinutes(_ temps: NSDictionary ) -> String {
var seconds = String(temps["seconds"] as! Int)
var minutes = String(temps["minutes"] as! Int)
var hours = String(temps["hours"] as! Int)
if (Int(seconds) < 10) {
seconds = "0" + seconds
}
if (Int(minutes) < 10) {
minutes = "0" + minutes
}
if (Int(hours) < 10) {
hours = "0" + hours
}
var time = minutes + ":" + seconds
if Int(hours) != 0 {
time = hours + ":" + minutes + ":" + seconds
}
return time
}
@IBAction func previousButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"skipprevious\"}"){(response: AnyObject?) in
}
}
@IBAction func fastRewindButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"stepback\"}"){(response: AnyObject?) in
}
}
@IBAction func stopButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"stop\"}"){(response: AnyObject?) in
}
}
@IBAction func playButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"play\"}"){(response: AnyObject?) in
}
}
@IBAction func pauseButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"pause\"}"){(response: AnyObject?) in
}
}
@IBAction func fastForwardButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"stepforward\"}"){(response: AnyObject?) in
}
}
@IBAction func nextButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"skipnext\"}"){(response: AnyObject?) in
}
}
@IBAction func leftButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Left"){(response: AnyObject?) in
}
}
@IBAction func rightButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Right"){(response: AnyObject?) in
}
}
@IBAction func downButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Down"){(response: AnyObject?) in
}
}
@IBAction func upButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Up"){(response: AnyObject?) in
}
}
@IBAction func okButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Select"){(response: AnyObject?) in
}
}
@IBAction func homeButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Home"){(response: AnyObject?) in
}
}
@IBAction func backButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Back"){(response: AnyObject?) in
}
}
@IBAction func tvButton(_ sender: AnyObject) {
rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"videos\",\"parameters\":[\"TvShowTitles\"]}"){(response: AnyObject?) in
}
}
@IBAction func moviesButton(_ sender: AnyObject) {
rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"video\",\"parameters\":[\"MovieTitles\"]}"){(response: AnyObject?) in
}
}
@IBAction func musicButton(_ sender: AnyObject) {
rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"music\"}"){(response: AnyObject?) in
}
}
@IBAction func pictureButton(_ sender: AnyObject) {
rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"pictures\"}"){(response: AnyObject?) in
}
}
@IBAction func volumeDownButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"volumedown\"}"){(response: AnyObject?) in
}
}
@IBAction func muteButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"mute\"}"){(response: AnyObject?) in
}
}
@IBAction func volumeUpButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"volumeup\"}"){(response: AnyObject?) in
}
}
@IBAction func repeatButton(_ sender: AnyObject) {
let r = self.player_repeat == "off" ? "all" : "off"
rc.jsonRpcCall("Player.SetRepeat", params: "{\"playerid\":\(self.playerId), \"repeat\":\"\(r)\"}"){(response: AnyObject?) in
}
}
@IBAction func shuffleButton(_ sender: AnyObject) {
let s = self.shuffle == true ? "false": "true"
rc.jsonRpcCall("Player.SetShuffle", params: "{\"playerid\":\(self.playerId), \"shuffle\":\(s)}"){(response: AnyObject?) in
}
}
@IBAction func osdButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ShowOSD"){(response: AnyObject?) in
}
}
@IBAction func contextButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ContextMenu"){(response: AnyObject?) in
}
}
@IBAction func infoButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Info"){(response: AnyObject?) in
}
}
}
| 45c61e67886986298521188ce1f7cc13 | 34.245014 | 234 | 0.547005 | false | false | false | false |
chenxtdo/UPImageMacApp | refs/heads/master | UPImage/AppHelper.swift | mit | 1 | //
// AppHelper.swift
// U图床
//
// Created by Pro.chen on 16/7/13.
// Copyright © 2016年 chenxt. All rights reserved.
//
import Foundation
import AppKit
import TMCache
public enum Result<Value> {
case success(Value)
case failure(Value)
public func Success( success: (_ value: Value) -> Void) -> Result<Value> {
switch self {
case .success(let value):
success(value)
default:
break
}
return self
}
public func Failure( failure: (_ error: Value) -> Void) -> Result<Value> {
switch self {
case .failure(let error):
failure(error)
default:
break
}
return self
}
}
extension NSImage {
func scalingImage() {
let sW = self.size.width
let sH = self.size.height
let nW: CGFloat = 100
let nH = nW * sH / sW
self.size = CGSize(width: nW, height: nH)
}
}
func NotificationMessage(_ message: String, informative: String? = nil, isSuccess: Bool = false) {
let notification = NSUserNotification()
let notificationCenter = NSUserNotificationCenter.default
notificationCenter.delegate = appDelegate as? NSUserNotificationCenterDelegate
notification.title = message
notification.informativeText = informative
if isSuccess {
notification.contentImage = NSImage(named: "success")
notification.informativeText = "链接已经保存在剪贴板里,可以直接粘贴"
} else {
notification.contentImage = NSImage(named: "Failure")
}
notification.soundName = NSUserNotificationDefaultSoundName;
notificationCenter.scheduleNotification(notification)
}
func arc() -> UInt32 { return arc4random() % 100000 }
func timeInterval() -> Int {
return Int(Date(timeIntervalSinceNow: 0).timeIntervalSince1970)
}
func getDateString() -> String {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "YYYYMMdd"
let dataString = dateformatter.string(from: Date(timeInterval: 0, since: Date()))
return dataString
}
func checkImageFile(_ pboard: NSPasteboard) -> Bool {
guard let pasteboard = pboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray,
let path = pasteboard[0] as? String
else { return false }
let image = NSImage(contentsOfFile: path)
guard let _ = image else {
return false
}
return true
}
func getImageType(_ data: Data) -> String {
var c: uint8 = 0
data.copyBytes(to: &c, count: 1)
switch c {
case 0xFF:
return ".jpeg"
case 0x89:
return ".png"
case 0x49:
return ".tiff"
case 0x4D:
return ".tiff"
case 0x52:
guard data.count > 12, let str = String(data: data.subdata(in: 0..<13), encoding: .ascii), str.hasPrefix("RIFF"), str.hasPrefix("WEBP") else {
return ""
}
return ".webp"
default:
return ""
}
}
private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8]
private let jpgHeaderIF: [UInt8] = [0xFF]
private let gifHeader: [UInt8] = [0x47, 0x49, 0x46]
enum ImageFormat : String {
case unknown = ""
case png = ".png"
case jpeg = ".jpg"
case gif = ".gif"
}
extension Data {
var imageFormat: ImageFormat {
var buffer = [UInt8](repeating: 0, count: 8)
(self as NSData).getBytes(&buffer, length: 8)
if buffer == pngHeader {
return .png
} else if buffer[0] == jpgHeaderSOI[0] &&
buffer[1] == jpgHeaderSOI[1] &&
buffer[2] == jpgHeaderIF[0]
{
return .jpeg
} else if buffer[0] == gifHeader[0] &&
buffer[1] == gifHeader[1] &&
buffer[2] == gifHeader[2]
{
return .gif
}
return .unknown
}
}
| 75a91d7208df52c966890132aff706d9 | 23.679245 | 150 | 0.602701 | false | false | false | false |
dvSection8/dvSection8 | refs/heads/master | dvSection8/Classes/API/DVAPIHelper.swift | mit | 1 | //
// APIHelper.swift
// Rush
//
// Created by MJ Roldan on 05/07/2017.
// Copyright © 2017 Mark Joel Roldan. All rights reserved.
//
import Foundation
public struct DVAPIHelper {
public static let shared = DVAPIHelper()
// Appending of keys and values from parameters
public func query(_ parameters: Paremeters) -> String {
var components: StringArray = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key] ?? ""
components += queryComponents(key: key, value: value)
}
return components.map {"\($0)=\($1)"}.joined(separator: "&")
}
// Query components value checker
private func queryComponents(key: String, value: Any) -> StringArray {
var components: StringArray = []
// dictionary
if let dictionary = value as? JSONDictionary {
for (nestedKey, value) in dictionary {
components += queryComponents(key: "\(key)[\(nestedKey)]", value: value)
}
}
// array
else if let array = value as? [Any] {
for (value) in array {
components += queryComponents(key: "\(key)[]", value: value)
}
}
// nsnumber - boolean value replace into string
else if let value = value as? NSNumber {
if value.boolValue {
components.append((key, "\(value.boolValue ? "1" : "0")"))
} else {
components.append((key, "\(value)"))
}
}
// boolean value replace into string
else if let bool = value as? Bool {
if bool {
components.append((key, "\(bool ? "1" : "0")"))
} else {
components.append((key, "\(value)"))
}
}
else { // string value
components.append((key, "\(value)"))
}
return components
}
}
| 27be580bb53607a5a5205da6729e5646 | 29.212121 | 88 | 0.510532 | false | false | false | false |
Pluto-Y/SwiftyEcharts | refs/heads/master | SwiftyEcharts/Models/Type/LineStyle.swift | mit | 1 | //
// LineStyle.swift
// SwiftyEcharts
//
// Created by Pluto Y on 03/01/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
public protocol LineStyleContent: Colorful, Shadowable, Opacitable {
var width: Float? { get set }
var type: LineType? { get set }
}
/// 线条样式
public final class LineStyle: Displayable, Shadowable, Colorful, Opacitable, Jsonable {
/// 是否显示
public var show: Bool?
/// 线的颜色。
public var color: Color?
/// 线宽。
public var width: Float?
/// 线的类型。
public var type: LineType?
/// 图形透明度。支持从 0 到 1 的数字,为 0 时不绘制该图形。
public var opacity: Float? {
didSet {
validateOpacity()
}
}
// MARK: - Shadowable
public var shadowBlur: Float?
public var shadowColor: Color?
public var shadowOffsetX: Float?
public var shadowOffsetY: Float?
public var curveness: Float?
public init() { }
}
extension LineStyle: Enumable {
public enum Enums {
case show(Bool), color(Color), width(Float), type(LineType), shadowBlur(Float), shadowColor(Color), shadowOffsetX(Float), shadowOffsetY(Float), opacity(Float), curveness(Float)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .show(show):
self.show = show
case let .color(color):
self.color = color
case let .width(width):
self.width = width
case let .type(type):
self.type = type
case let .shadowBlur(blur):
self.shadowBlur = blur
case let .shadowColor(color):
self.shadowColor = color
case let .shadowOffsetX(x):
self.shadowOffsetX = x
case let .shadowOffsetY(y):
self.shadowOffsetY = y
case let .opacity(opacity):
self.opacity = opacity
case let .curveness(curveness):
self.curveness = curveness
}
}
}
}
extension LineStyle: Mappable {
public func mapping(_ map: Mapper) {
map["show"] = show
map["color"] = color
map["width"] = width
map["type"] = type
map["shadowBlur"] = shadowBlur
map["shadowColor"] = shadowColor
map["shadowOffsetX"] = shadowOffsetX
map["shadowOffsetY"] = shadowOffsetY
map["opacity"] = opacity
map["curveness"] = curveness
}
}
public final class EmphasisLineStyle: Emphasisable {
public typealias Style = LineStyle
public var normal: Style?
public var emphasis: Style?
public init() { }
}
extension EmphasisLineStyle: Enumable {
public enum Enums {
case normal(Style), emphasis(Style)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .normal(normal):
self.normal = normal
case let .emphasis(emphasis):
self.emphasis = emphasis
}
}
}
}
extension EmphasisLineStyle: Mappable {
public func mapping(_ map: Mapper) {
map["normal"] = normal
map["emphasis"] = emphasis
}
}
| fd93bc6e141013f94acf67584a080778 | 25.114504 | 184 | 0.562701 | false | false | false | false |
Speicher210/wingu-sdk-ios-demoapp | refs/heads/master | Example/Pods/SKPhotoBrowser/SKPhotoBrowser/SKAnimator.swift | apache-2.0 | 1 | //
// SKAnimator.swift
// SKPhotoBrowser
//
// Created by keishi suzuki on 2016/08/09.
// Copyright © 2016 suzuki_keishi. All rights reserved.
//
import UIKit
@objc public protocol SKPhotoBrowserAnimatorDelegate {
func willPresent(_ browser: SKPhotoBrowser)
func willDismiss(_ browser: SKPhotoBrowser)
}
class SKAnimator: NSObject, SKPhotoBrowserAnimatorDelegate {
var resizableImageView: UIImageView?
var senderOriginImage: UIImage!
var senderViewOriginalFrame: CGRect = .zero
var senderViewForAnimation: UIView?
var finalImageViewFrame: CGRect = .zero
var bounceAnimation: Bool = false
var animationDuration: TimeInterval {
if SKPhotoBrowserOptions.bounceAnimation {
return 0.5
}
return 0.35
}
var animationDamping: CGFloat {
if SKPhotoBrowserOptions.bounceAnimation {
return 0.8
}
return 1
}
func willPresent(_ browser: SKPhotoBrowser) {
guard let appWindow = UIApplication.shared.delegate?.window else {
return
}
guard let window = appWindow else {
return
}
guard let sender = browser.delegate?.viewForPhoto?(browser, index: browser.initialPageIndex) ?? senderViewForAnimation else {
presentAnimation(browser)
return
}
let photo = browser.photoAtIndex(browser.currentPageIndex)
let imageFromView = (senderOriginImage ?? browser.getImageFromView(sender)).rotateImageByOrientation()
let imageRatio = imageFromView.size.width / imageFromView.size.height
senderViewOriginalFrame = calcOriginFrame(sender)
finalImageViewFrame = calcFinalFrame(imageRatio)
resizableImageView = UIImageView(image: imageFromView)
resizableImageView!.frame = senderViewOriginalFrame
resizableImageView!.clipsToBounds = true
resizableImageView!.contentMode = photo.contentMode
if sender.layer.cornerRadius != 0 {
let duration = (animationDuration * Double(animationDamping))
resizableImageView!.layer.masksToBounds = true
resizableImageView!.addCornerRadiusAnimation(sender.layer.cornerRadius, to: 0, duration: duration)
}
window.addSubview(resizableImageView!)
presentAnimation(browser)
}
func willDismiss(_ browser: SKPhotoBrowser) {
guard let sender = browser.delegate?.viewForPhoto?(browser, index: browser.currentPageIndex),
let image = browser.photoAtIndex(browser.currentPageIndex).underlyingImage,
let scrollView = browser.pageDisplayedAtIndex(browser.currentPageIndex) else {
senderViewForAnimation?.isHidden = false
browser.dismissPhotoBrowser(animated: false)
return
}
senderViewForAnimation = sender
browser.view.isHidden = true
browser.backgroundView.isHidden = false
browser.backgroundView.alpha = 1
senderViewOriginalFrame = calcOriginFrame(sender)
let photo = browser.photoAtIndex(browser.currentPageIndex)
let contentOffset = scrollView.contentOffset
let scrollFrame = scrollView.photoImageView.frame
let offsetY = scrollView.center.y - (scrollView.bounds.height/2)
let frame = CGRect(
x: scrollFrame.origin.x - contentOffset.x,
y: scrollFrame.origin.y + contentOffset.y + offsetY,
width: scrollFrame.width,
height: scrollFrame.height)
// resizableImageView.image = scrollView.photo?.underlyingImage?.rotateImageByOrientation()
resizableImageView!.image = image.rotateImageByOrientation()
resizableImageView!.frame = frame
resizableImageView!.alpha = 1.0
resizableImageView!.clipsToBounds = true
resizableImageView!.contentMode = photo.contentMode
if let view = senderViewForAnimation, view.layer.cornerRadius != 0 {
let duration = (animationDuration * Double(animationDamping))
resizableImageView!.layer.masksToBounds = true
resizableImageView!.addCornerRadiusAnimation(0, to: view.layer.cornerRadius, duration: duration)
}
dismissAnimation(browser)
}
}
private extension SKAnimator {
func calcOriginFrame(_ sender: UIView) -> CGRect {
if let senderViewOriginalFrameTemp = sender.superview?.convert(sender.frame, to:nil) {
return senderViewOriginalFrameTemp
} else if let senderViewOriginalFrameTemp = sender.layer.superlayer?.convert(sender.frame, to: nil) {
return senderViewOriginalFrameTemp
} else {
return .zero
}
}
func calcFinalFrame(_ imageRatio: CGFloat) -> CGRect {
if SKMesurement.screenRatio < imageRatio {
let width = SKMesurement.screenWidth
let height = width / imageRatio
let yOffset = (SKMesurement.screenHeight - height) / 2
return CGRect(x: 0, y: yOffset, width: width, height: height)
} else {
let height = SKMesurement.screenHeight
let width = height * imageRatio
let xOffset = (SKMesurement.screenWidth - width) / 2
return CGRect(x: xOffset, y: 0, width: width, height: height)
}
}
}
private extension SKAnimator {
func presentAnimation(_ browser: SKPhotoBrowser, completion: (() -> Void)? = nil) {
browser.view.isHidden = true
browser.view.alpha = 0.0
UIView.animate(
withDuration: animationDuration,
delay: 0,
usingSpringWithDamping:animationDamping,
initialSpringVelocity:0,
options:UIViewAnimationOptions(),
animations: {
browser.showButtons()
browser.backgroundView.alpha = 1.0
self.resizableImageView?.frame = self.finalImageViewFrame
},
completion: { (_) -> Void in
browser.view.isHidden = false
browser.view.alpha = 1.0
browser.backgroundView.isHidden = true
self.resizableImageView?.alpha = 0.0
})
}
func dismissAnimation(_ browser: SKPhotoBrowser, completion: (() -> Void)? = nil) {
UIView.animate(
withDuration: animationDuration,
delay:0,
usingSpringWithDamping:animationDamping,
initialSpringVelocity:0,
options:UIViewAnimationOptions(),
animations: {
browser.backgroundView.alpha = 0.0
self.resizableImageView?.layer.frame = self.senderViewOriginalFrame
},
completion: { (_) -> Void in
browser.dismissPhotoBrowser(animated: true) {
self.resizableImageView?.removeFromSuperview()
}
})
}
}
| 3ce3008d5277bfec908ee6bd668f92ff | 37.005376 | 133 | 0.627953 | false | false | false | false |
noppoMan/aws-sdk-swift | refs/heads/main | Sources/Soto/Services/Glacier/Glacier_Error.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for Glacier
public struct GlacierErrorType: AWSErrorType {
enum Code: String {
case insufficientCapacityException = "InsufficientCapacityException"
case invalidParameterValueException = "InvalidParameterValueException"
case limitExceededException = "LimitExceededException"
case missingParameterValueException = "MissingParameterValueException"
case policyEnforcedException = "PolicyEnforcedException"
case requestTimeoutException = "RequestTimeoutException"
case resourceNotFoundException = "ResourceNotFoundException"
case serviceUnavailableException = "ServiceUnavailableException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize Glacier
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// Returned if there is insufficient capacity to process this expedited request. This error only applies to expedited retrievals and not to standard or bulk retrievals.
public static var insufficientCapacityException: Self { .init(.insufficientCapacityException) }
/// Returned if a parameter of the request is incorrectly specified.
public static var invalidParameterValueException: Self { .init(.invalidParameterValueException) }
/// Returned if the request results in a vault or account limit being exceeded.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// Returned if a required header or parameter is missing from the request.
public static var missingParameterValueException: Self { .init(.missingParameterValueException) }
/// Returned if a retrieval job would exceed the current data policy's retrieval rate limit. For more information about data retrieval policies,
public static var policyEnforcedException: Self { .init(.policyEnforcedException) }
/// Returned if, when uploading an archive, Amazon S3 Glacier times out while receiving the upload.
public static var requestTimeoutException: Self { .init(.requestTimeoutException) }
/// Returned if the specified resource (such as a vault, upload ID, or job ID) doesn't exist.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
/// Returned if the service cannot complete the request.
public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) }
}
extension GlacierErrorType: Equatable {
public static func == (lhs: GlacierErrorType, rhs: GlacierErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension GlacierErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| c4312e7a45beb310c7741ef7db988f6e | 46.179487 | 173 | 0.707609 | false | false | false | false |
wikimedia/apps-ios-wikipedia | refs/heads/twn | Wikipedia/Code/HintController.swift | mit | 1 | @objc(WMFHintPresenting)
protocol HintPresenting: AnyObject {
var hintController: HintController? { get set }
}
class HintController: NSObject {
typealias Context = [String: Any]
typealias HintPresentingViewController = UIViewController & HintPresenting
private weak var presenter: HintPresentingViewController?
private let hintViewController: HintViewController
private var containerView = UIView()
private var containerViewConstraint: (top: NSLayoutConstraint?, bottom: NSLayoutConstraint?)
private var task: DispatchWorkItem?
var theme = Theme.standard
//if true, hint will extend below safe area to the bottom of the view, and hint content within will align to safe area
//must also override extendsUnderSafeArea to true in HintViewController
var extendsUnderSafeArea: Bool {
return false
}
init(hintViewController: HintViewController) {
self.hintViewController = hintViewController
super.init()
hintViewController.delegate = self
}
var isHintHidden: Bool {
return containerView.superview == nil
}
private var hintVisibilityTime: TimeInterval = 13 {
didSet {
guard hintVisibilityTime != oldValue else {
return
}
dismissHint()
}
}
func dismissHint() {
self.task?.cancel()
let task = DispatchWorkItem { [weak self] in
self?.setHintHidden(true)
}
DispatchQueue.main.asyncAfter(deadline: .now() + hintVisibilityTime , execute: task)
self.task = task
}
@objc func toggle(presenter: HintPresentingViewController, context: Context?, theme: Theme) {
self.presenter = presenter
apply(theme: theme)
}
private func addHint(to presenter: HintPresentingViewController) {
guard isHintHidden else {
return
}
containerView.translatesAutoresizingMaskIntoConstraints = false
var additionalBottomSpacing: CGFloat = 0
if let wmfVCPresenter = presenter as? WMFViewController { // not ideal, violates encapsulation
wmfVCPresenter.view.insertSubview(containerView, belowSubview: wmfVCPresenter.toolbar)
additionalBottomSpacing = wmfVCPresenter.toolbar.frame.size.height
} else {
presenter.view.addSubview(containerView)
}
var bottomAnchor: NSLayoutYAxisAnchor
bottomAnchor = extendsUnderSafeArea ? presenter.view.bottomAnchor : presenter.view.safeAreaLayoutGuide.bottomAnchor
// `containerBottomConstraint` is activated when the hint is visible
containerViewConstraint.bottom = containerView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0 - additionalBottomSpacing)
// `containerTopConstraint` is activated when the hint is hidden
containerViewConstraint.top = containerView.topAnchor.constraint(equalTo: bottomAnchor)
let leadingConstraint = containerView.leadingAnchor.constraint(equalTo: presenter.view.leadingAnchor)
let trailingConstraint = containerView.trailingAnchor.constraint(equalTo: presenter.view.trailingAnchor)
NSLayoutConstraint.activate([containerViewConstraint.top!, leadingConstraint, trailingConstraint])
if presenter.isKind(of: SearchResultsViewController.self){
presenter.wmf_hideKeyboard()
}
hintViewController.view.setContentHuggingPriority(.required, for: .vertical)
hintViewController.view.setContentCompressionResistancePriority(.required, for: .vertical)
containerView.setContentHuggingPriority(.required, for: .vertical)
containerView.setContentCompressionResistancePriority(.required, for: .vertical)
presenter.wmf_add(childController: hintViewController, andConstrainToEdgesOfContainerView: containerView)
containerView.superview?.layoutIfNeeded()
}
private func removeHint() {
task?.cancel()
hintViewController.willMove(toParent: nil)
hintViewController.view.removeFromSuperview()
hintViewController.removeFromParent()
containerView.removeFromSuperview()
resetHint()
}
func resetHint() {
hintVisibilityTime = 13
hintViewController.viewType = .default
}
func setHintHidden(_ hidden: Bool) {
guard
isHintHidden != hidden,
let presenter = presenter,
presenter.presentedViewController == nil
else {
return
}
presenter.hintController = self
if !hidden {
// add hint before animation starts
addHint(to: presenter)
}
self.adjustSpacingIfPresenterHasSecondToolbar(hintHidden: hidden)
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: {
if hidden {
self.containerViewConstraint.bottom?.isActive = false
self.containerViewConstraint.top?.isActive = true
} else {
self.containerViewConstraint.top?.isActive = false
self.containerViewConstraint.bottom?.isActive = true
}
self.containerView.superview?.layoutIfNeeded()
}, completion: { (_) in
// remove hint after animation is completed
if hidden {
self.adjustSpacingIfPresenterHasSecondToolbar(hintHidden: hidden)
self.removeHint()
} else {
self.dismissHint()
}
})
}
@objc func dismissHintDueToUserInteraction() {
guard !self.isHintHidden else {
return
}
self.hintVisibilityTime = 0
}
private func adjustSpacingIfPresenterHasSecondToolbar(hintHidden: Bool) {
guard
let viewController = presenter as? WMFViewController,
!viewController.isSecondToolbarHidden
else {
return
}
let spacing = hintHidden ? 0 : containerView.frame.height
viewController.setAdditionalSecondToolbarSpacing(spacing, animated: true)
}
}
extension HintController: HintViewControllerDelegate {
func hintViewControllerWillDisappear(_ hintViewController: HintViewController) {
setHintHidden(true)
}
func hintViewControllerHeightDidChange(_ hintViewController: HintViewController) {
adjustSpacingIfPresenterHasSecondToolbar(hintHidden: isHintHidden)
}
func hintViewControllerViewTypeDidChange(_ hintViewController: HintViewController, newViewType: HintViewController.ViewType) {
guard newViewType == .confirmation else {
return
}
setHintHidden(false)
}
func hintViewControllerDidPeformConfirmationAction(_ hintViewController: HintViewController) {
setHintHidden(true)
}
func hintViewControllerDidFailToCompleteDefaultAction(_ hintViewController: HintViewController) {
setHintHidden(true)
}
}
extension HintController: Themeable {
func apply(theme: Theme) {
hintViewController.apply(theme: theme)
}
}
| 9d023ccd9c1f2c76ec53067898cdcf84 | 34 | 140 | 0.679412 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/NewVersion/CoreText/ZSDisplayView.swift | mit | 1 | //
// ZSDisplayView.swift
// CoreTextDemo
//
// Created by caony on 2019/7/12.
// Copyright © 2019 cj. All rights reserved.
//
import UIKit
import Kingfisher
class ZSDisplayView: UIView {
// MARK: - Properties
var ctFrame: CTFrame?
var images: [(image: UIImage, frame: CGRect)] = []
var imageModels:[ZSImageData] = []
// MARK: - Properties
var imageIndex: Int!
var longPress:UILongPressGestureRecognizer!
var originRange = NSRange(location: 0, length: 0)
var selectedRange = NSRange(location: 0, length: 0)
var attributeString:NSMutableAttributedString = NSMutableAttributedString(string: "")
var rects:[CGRect] = []
var leftCursor:ZSTouchAnchorView!
var rightCursor:ZSTouchAnchorView!
// 移动光标
private var isTouchCursor = false
private var touchRightCursor = false
private var touchOriginRange = NSRange(location: 0, length: 0)
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
isUserInteractionEnabled = true
if longPress == nil {
longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(gesture:)))
addGestureRecognizer(longPress)
}
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction(tap:)))
addGestureRecognizer(tap)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc
private func tapAction(tap:UITapGestureRecognizer) {
originRange = NSRange(location: 0, length: 0)
selectedRange = NSRange(location: 0, length: 0)
rects.removeAll()
hideCursor()
setNeedsDisplay()
}
@objc
private func longPressAction(gesture:UILongPressGestureRecognizer) {
var originPoint = CGPoint.zero
switch gesture.state {
case .began:
originPoint = gesture.location(in: self)
originRange = touchLocation(point: originPoint, str: self.attributeString.string)
selectedRange = originRange
rects = rangeRects(range: selectedRange, ctframe: ctFrame)
showCursor()
setNeedsDisplay()
break
case .changed:
let finalRange = touchLocation(point: gesture.location(in: self), str: attributeString.string)
if finalRange.location == 0 || finalRange.location == NSNotFound {
return
}
var range = NSRange(location: 0, length: 0)
range.location = min(finalRange.location, originRange.location)
if finalRange.location > originRange.location {
range.length = finalRange.location - originRange.location + finalRange.length
} else {
range.length = originRange.location - finalRange.location + originRange.length
}
selectedRange = range
rects = rangeRects(range: selectedRange, ctframe: ctFrame)
showCursor()
setNeedsDisplay()
break
case .ended:
break
case .cancelled:
break
default:
break
}
}
func showCursor() {
guard rects.count > 0 else {
return
}
let leftRect = rects.first!
let rightRect = rects.last!
if leftCursor == nil {
let rect = CGRect(x: leftRect.minX - 2, y: bounds.height - leftRect.origin.y - rightRect.height - 6, width: 10, height: leftRect.height + 6)
leftCursor = ZSTouchAnchorView(frame: rect)
addSubview(leftCursor)
} else {
let rect = CGRect(x: leftRect.minX - 2, y: bounds.height - leftRect.origin.y - rightRect.height - 6, width: 10, height: leftRect.height + 6)
leftCursor.frame = rect
}
if rightCursor == nil {
let rect = CGRect(x: rightRect.maxX - 2, y: bounds.height - rightRect.origin.y - rightRect.height - 6, width: 10, height: rightRect.height + 6)
rightCursor = ZSTouchAnchorView(frame: rect)
addSubview(rightCursor)
} else {
rightCursor.frame = CGRect(x: rightRect.maxX - 4, y: bounds.height - rightRect.origin.y - rightRect.height - 6, width: 10, height: rightRect.height + 6)
}
}
func hideCursor() {
if leftCursor != nil {
leftCursor.removeFromSuperview()
leftCursor = nil
}
if rightCursor != nil {
rightCursor.removeFromSuperview()
rightCursor = nil
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let point = touches.first?.location(in: self) else { return }
guard leftCursor != nil && rightCursor != nil else { return }
if rightCursor.frame.insetBy(dx: -30, dy: -30).contains(point) {
touchRightCursor = true
isTouchCursor = true
} else if leftCursor.frame.insetBy(dx: -30, dy: -30).contains(point) {
touchRightCursor = false
isTouchCursor = true
}
touchOriginRange = selectedRange
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let point = touches.first?.location(in: self) else { return }
guard leftCursor != nil && rightCursor != nil else { return }
if isTouchCursor {
let finalRange = touchLocation(point: point, str: attributeString.string)
if (finalRange.location == 0 && finalRange.length == 0) || finalRange.location == NSNotFound {
return
}
var range = NSRange(location: 0, length: 0)
if touchRightCursor { // 移动右边光标
if finalRange.location >= touchOriginRange.location {
range.location = touchOriginRange.location
range.length = finalRange.location - touchOriginRange.location + 1
} else {
range.location = finalRange.location
range.length = touchOriginRange.location - range.location
}
} else { // 移动左边光标
if finalRange.location <= touchOriginRange.location {
range.location = finalRange.location
range.length = touchOriginRange.location - finalRange.location + touchOriginRange.length
} else if finalRange.location > touchOriginRange.location {
if finalRange.location <= touchOriginRange.location + touchOriginRange.length - 1 {
range.location = finalRange.location
range.length = touchOriginRange.location + touchOriginRange.length - finalRange.location
} else {
range.location = touchOriginRange.location + touchOriginRange.length
range.length = finalRange.location - range.location
}
}
}
selectedRange = range
rects = rangeRects(range: selectedRange, ctframe: ctFrame)
// 显示光标
showCursor()
setNeedsDisplay()
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
isTouchCursor = false
touchOriginRange = selectedRange
}
func rangeRects(range:NSRange, ctframe:CTFrame?) ->[CGRect] {
var rects:[CGRect] = []
guard let ctframe = ctframe else {
return rects
}
guard range.location != NSNotFound else {
return rects
}
var lines = CTFrameGetLines(ctframe) as Array
var origins = [CGPoint](repeating: CGPoint.zero, count: lines.count)
CTFrameGetLineOrigins(ctframe, CFRange(location: 0, length: 0), &origins)
for index in 0..<lines.count {
let line = lines[index] as! CTLine
let origin = origins[index]
let lineCFRange = CTLineGetStringRange(line)
if lineCFRange.location != NSNotFound {
let lineRange = NSRange(location: lineCFRange.location, length: lineCFRange.length)
if lineRange.location + lineRange.length > range.location && lineRange.location < (range.location + range.length) {
var ascent: CGFloat = 0
var descent: CGFloat = 0
var startX: CGFloat = 0
var contentRange = NSRange(location: range.location, length: 0)
let end = min(lineRange.location + lineRange.length, range.location + range.length)
contentRange.length = end - contentRange.location
CTLineGetTypographicBounds(line, &ascent, &descent, nil)
let y = origin.y - descent
startX = CTLineGetOffsetForStringIndex(line, contentRange.location, nil)
let endX = CTLineGetOffsetForStringIndex(line, contentRange.location + contentRange.length, nil)
let rect = CGRect(x: origin.x + startX, y: y, width: endX - startX, height: ascent + descent)
rects.append(rect)
}
}
}
return rects
}
func touchLocation(point:CGPoint, str:String = "") ->NSRange {
var touchRange = NSMakeRange(0, 0)
guard let ctFrame = self.ctFrame else {
return touchRange
}
var lines = CTFrameGetLines(ctFrame) as Array
var origins = [CGPoint](repeating: CGPoint.zero, count: lines.count)
CTFrameGetLineOrigins(ctFrame, CFRange(location: 0, length: 0), &origins)
for index in 0..<lines.count {
let line = lines[index] as! CTLine
let origin = origins[index]
var ascent: CGFloat = 0
var descent: CGFloat = 0
CTLineGetTypographicBounds(line, &ascent, &descent, nil)
let lineRect = CGRect(x: origin.x, y: bounds.height - origin.y - (ascent + descent), width: CTLineGetOffsetForStringIndex(line, 100000, nil), height: ascent + descent)
if lineRect.contains(point) {
let lineRange = CTLineGetStringRange(line)
for rangeIndex in 0..<lineRange.length {
let location = lineRange.location + rangeIndex
var offsetX = CTLineGetOffsetForStringIndex(line, location, nil)
var offsetX2 = CTLineGetOffsetForStringIndex(line, location + 1, nil)
offsetX += origin.x
offsetX2 += origin.x
let runs = CTLineGetGlyphRuns(line) as Array
for runIndex in 0..<runs.count {
let run = runs[runIndex] as! CTRun
let runRange = CTRunGetStringRange(run)
if runRange.location <= location && location <= (runRange.location + runRange.length - 1) {
// 说明在当前的run中
var ascent: CGFloat = 0
var descent: CGFloat = 0
CTRunGetTypographicBounds(run, CFRange(location: 0, length: 0), &ascent, &descent, nil)
let frame = CGRect(x: offsetX, y: bounds.height - origin.y - (ascent + descent), width: (offsetX2 - offsetX)*2, height: ascent + descent)
if frame.contains(point) {
touchRange = NSRange(location: location, length: min(2, lineRange.length + lineRange.location - location))
}
}
}
}
}
}
return touchRange
}
func buildContent(attr:NSAttributedString, andImages:[ZSImageData] , settings:CTSettings) {
attributeString = NSMutableAttributedString(attributedString: attr)
imageIndex = 0
let framesetter = CTFramesetterCreateWithAttributedString(attr as CFAttributedString)
let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), nil, CGSize(width: settings.pageRect.size.width, height: CGFloat.greatestFiniteMagnitude), nil)
let path = CGMutablePath()
path.addRect(CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: settings.pageRect.width, height: textSize.height)))
let ctframe = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil)
self.ctFrame = ctframe
self.imageModels = andImages
attachImages(andImages, ctframe: ctframe, margin: settings.margin)
setNeedsDisplay()
}
func build(withAttrString attrString: NSAttributedString,
andImages images: [[String: Any]]) {
imageIndex = 0
//4
let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString)
let settings = CTSettings.shared
let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), nil, CGSize(width: settings.pageRect.size.width, height: CGFloat.greatestFiniteMagnitude), nil)
self.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: textSize.height)
if let parentView = self.superview as? UIScrollView {
parentView.contentSize = CGSize(width: self.bounds.width, height: textSize.height)
}
let path = CGMutablePath()
path.addRect(CGRect(origin: CGPoint(x: 20, y: 20), size: CGSize(width: settings.pageRect.width, height: textSize.height)))
let ctframe = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil)
self.ctFrame = ctframe
attachImagesWithFrame(images, ctframe: ctframe, margin: settings.margin)
}
func attachImages(_ images: [ZSImageData],ctframe: CTFrame,margin: CGFloat) {
if images.count == 0 {
return
}
let lines = CTFrameGetLines(ctframe) as NSArray
var origins = [CGPoint](repeating: .zero, count: lines.count)
CTFrameGetLineOrigins(ctframe, CFRangeMake(0, 0), &origins)
var nextImage:ZSImageData? = imageModels[imageIndex]
for lineIndex in 0..<lines.count {
if nextImage == nil {
break
}
let line = lines[lineIndex] as! CTLine
if let glyphRuns = CTLineGetGlyphRuns(line) as? [CTRun]
{
for run in glyphRuns {
let runAttr = CTRunGetAttributes(run) as? [NSAttributedString.Key:Any]
let delegate = runAttr?[(kCTRunDelegateAttributeName as NSAttributedString.Key)]
if delegate == nil {
continue
}
var imgBounds: CGRect = .zero
var ascent: CGFloat = 0
var descent: CGFloat = 0
imgBounds.size.width = CGFloat(CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, nil))
imgBounds.size.height = ascent + descent
let xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, nil)
imgBounds.origin.x = origins[lineIndex].x + xOffset
imgBounds.origin.y = origins[lineIndex].y
imgBounds.origin.y -= descent;
let pathRef = CTFrameGetPath(ctframe)
let colRect = pathRef.boundingBox
let delegateBounds = imgBounds.offsetBy(dx: colRect.origin.x, dy: colRect.origin.y)
nextImage!.imagePosition = delegateBounds
imageModels[imageIndex].imagePosition = imgBounds
imageIndex! += 1
if imageIndex < images.count {
nextImage = images[imageIndex]
} else {
nextImage = nil
}
}
}
}
}
func attachImagesWithFrame(_ images: [[String: Any]],
ctframe: CTFrame,
margin: CGFloat) {
//1
let lines = CTFrameGetLines(ctframe) as NSArray
//2
var origins = [CGPoint](repeating: .zero, count: lines.count)
CTFrameGetLineOrigins(ctframe, CFRangeMake(0, 0), &origins)
//3
var nextImage = images[imageIndex]
guard var imgLocation = nextImage["location"] as? Int else {
return
}
//4
for lineIndex in 0..<lines.count {
let line = lines[lineIndex] as! CTLine
//5
if let glyphRuns = CTLineGetGlyphRuns(line) as? [CTRun],
let imageFilename = nextImage["filename"] as? String,
let img = UIImage(named: imageFilename) {
for run in glyphRuns {
// 1
let runRange = CTRunGetStringRange(run)
if runRange.location > imgLocation || runRange.location + runRange.length <= imgLocation {
continue
}
//2
var imgBounds: CGRect = .zero
var ascent: CGFloat = 0
imgBounds.size.width = CGFloat(CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, nil, nil))
imgBounds.size.height = ascent
//3
let xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, nil)
imgBounds.origin.x = origins[lineIndex].x + xOffset
imgBounds.origin.y = origins[lineIndex].y
//4
self.images += [(image: img, frame: imgBounds)]
//5
imageIndex! += 1
if imageIndex < images.count {
nextImage = images[imageIndex]
imgLocation = (nextImage["location"] as AnyObject).intValue
}
}
}
}
}
// MARK: - Life Cycle
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
context.textMatrix = .identity
context.translateBy(x: 0, y: bounds.size.height)
context.scaleBy(x: 1.0, y: -1.0)
if rects.count > 0 {
let lineRects = rects.map { rect -> CGRect in
return CGRect(x: rect.origin.x + 2, y: rect.origin.y, width: rect.width, height: rect.height)
}
let fillPath = CGMutablePath()
UIColor(red:0.92, green:0.5, blue:0.5, alpha:1.00).withAlphaComponent(0.5).setFill()
fillPath.addRects(lineRects)
context.addPath(fillPath)
context.fillPath()
}
CTFrameDraw(ctFrame!, context)
for imageData in images {
if let image = imageData.image.cgImage {
let imgBounds = imageData.frame
context.draw(image, in: imgBounds)
}
}
for imageModel in imageModels {
if let image = imageModel.image {
context.draw(image.cgImage!, in: imageModel.imagePosition)
continue
}
if let url = URL(string: imageModel.parse?.url ?? "" ) {
ImageDownloader.default.downloadImage(with: url, options: nil, progressBlock: nil) { [weak self] (result) in
switch result {
case .success(let value):
print(value.image)
self!.imageModels[self?.indexOfModel(model: imageModel, models: self!.imageModels) ?? 0].image = value.image
self?.setNeedsDisplay()
case .failure(let error):
print(error)
}
}
}
}
}
func indexOfModel(model:ZSImageData, models:[ZSImageData]) ->Int {
var index = 0
for data in models {
if data.parse?.url == model.parse?.url {
break
}
index += 1
}
return index
}
}
| fc39ab6e04414dade81b1faa6dc97b61 | 42.285115 | 195 | 0.558047 | false | false | false | false |
WestlakeAPC/game-off-2016 | refs/heads/master | external/Fiber2D/Fiber2D/Scheduling.swift | apache-2.0 | 1 | //
// Scheduling.swift
// Fiber2D
//
// Created by Andrey Volodin on 28.08.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
public typealias Time = Float
extension Timer {
func forEach(block: (Timer) -> Void) {
var timer: Timer? = self
while timer != nil {
block(timer!)
timer = timer!.next
}
}
func removeRecursive(skip: Timer) -> Timer? {
if self === skip {
return self.next
} else {
self.next = self.next?.removeRecursive(skip: skip)
return self
}
}
}
// Targets are things that can have update: and fixedUpdate: methods called by the scheduler.
// Scheduled blocks (Timers) can be associated with a target to inherit their priority and paused state.
internal final class ScheduledTarget {
weak var target: Node?
var timers: Timer?
var actions = [ActionContainer]()
var empty: Bool {
return timers == nil && !enableUpdates
}
var hasActions: Bool {
return !actions.isEmpty
}
var paused = false {
didSet {
if paused != oldValue {
let pause = self.paused
timers?.forEach { $0.paused = pause }
}
}
}
var enableUpdates = false
func invalidateTimers() {
timers?.forEach { $0.invalidate() }
}
func add(action: ActionContainer) {
actions.append(action)
}
func removeAction(by tag: Int) {
actions = actions.filter {
$0.tag != tag
}
}
func remove(timer: Timer) {
timers = timers?.removeRecursive(skip: timer)
}
init(target: Node) {
self.target = target
}
}
| 68bf531f465ce96f87fd69af53a5de52 | 22.917808 | 104 | 0.553265 | false | false | false | false |
rossharper/raspberrysauce-ios | refs/heads/master | raspberrysauce-ios/Authentication/TokenAuthManager.swift | apache-2.0 | 1 | //
// TokenAuthManager.swift
// raspberrysauce-ios
//
// Created by Ross Harper on 20/12/2016.
// Copyright © 2016 rossharper.net. All rights reserved.
//
import Foundation
struct AuthConfig {
let tokenRequestEndpoint: URL
}
class TokenAuthManager : AuthManager {
let config : AuthConfig
let networking : Networking
let tokenStore : TokenStore
weak var observer : AuthObserver?
init(config: AuthConfig, networking: Networking, tokenStore: TokenStore) {
self.config = config
self.networking = networking
self.tokenStore = tokenStore
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue:"SignIn"), object: nil, queue: nil, using:notifySignIn)
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue:"SignInFailed"), object: nil, queue: nil, using:notifySignInFailed)
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue:"SignedOut"), object: nil, queue: nil, using:notifySignedOut)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func isSignedIn() -> Bool {
let token = tokenStore.get()
return token != nil
}
func signIn(username: String, password: String) {
// TODO: extract to SauceAPIClient??
networking.post(url: config.tokenRequestEndpoint, body: "username=\(username)&password=\(password)",
onSuccess: {responseBody in
guard let tokenValue = String(data: responseBody, encoding: .utf8) else {
return
}
self.tokenStore.put(token: Token(value: tokenValue))
self.broadcastSignIn()
},
onError: { _ in
self.broadcastSignInFailed()
})
}
func signOut() {
deleteAccessToken()
broadcastSignedOut()
}
func setAuthObserver(observer: AuthObserver?) {
self.observer = observer
}
func getAccessToken() -> Token? {
return tokenStore.get()
}
func deleteAccessToken() {
tokenStore.remove()
}
private func broadcastSignIn() {
NotificationCenter.default.post(name: Notification.Name(rawValue:"SignIn"), object: nil,userInfo: nil)
}
private func broadcastSignInFailed() {
NotificationCenter.default.post(name: Notification.Name(rawValue:"SignInFailed"), object: nil,userInfo: nil)
}
private func broadcastSignedOut() {
NotificationCenter.default.post(name: Notification.Name(rawValue:"SignedOut"), object: nil,userInfo: nil)
}
@objc func notifySignIn(notification: Notification) {
observer?.onSignedIn()
}
@objc private func notifySignInFailed(notification: Notification) {
observer?.onSignInFailed()
}
@objc private func notifySignedOut(notification: Notification) {
observer?.onSignedOut()
}
}
| e36de84beef3cd7df4ec3b247efbcd81 | 30.712766 | 150 | 0.645421 | false | true | false | false |
apple/swift-nio | refs/heads/main | Sources/NIOCore/IO.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(Windows)
import ucrt
import func WinSDK.FormatMessageW
import func WinSDK.LocalFree
import let WinSDK.FORMAT_MESSAGE_ALLOCATE_BUFFER
import let WinSDK.FORMAT_MESSAGE_FROM_SYSTEM
import let WinSDK.FORMAT_MESSAGE_IGNORE_INSERTS
import let WinSDK.LANG_NEUTRAL
import let WinSDK.SUBLANG_DEFAULT
import typealias WinSDK.DWORD
import typealias WinSDK.WCHAR
import typealias WinSDK.WORD
internal func MAKELANGID(_ p: WORD, _ s: WORD) -> DWORD {
return DWORD((s << 10) | p)
}
#elseif os(Linux) || os(Android)
import Glibc
#elseif os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#endif
/// An `Error` for an IO operation.
public struct IOError: Swift.Error {
@available(*, deprecated, message: "NIO no longer uses FailureDescription.")
public enum FailureDescription {
case function(StaticString)
case reason(String)
}
/// The actual reason (in an human-readable form) for this `IOError`.
private var failureDescription: String
@available(*, deprecated, message: "NIO no longer uses FailureDescription, use IOError.description for a human-readable error description")
public var reason: FailureDescription {
return .reason(self.failureDescription)
}
private enum Error {
#if os(Windows)
case windows(DWORD)
case winsock(CInt)
#endif
case errno(CInt)
}
private let error: Error
/// The `errno` that was set for the operation.
public var errnoCode: CInt {
switch self.error {
case .errno(let code):
return code
#if os(Windows)
default:
fatalError("IOError domain is not `errno`")
#endif
}
}
#if os(Windows)
public init(windows code: DWORD, reason: String) {
self.error = .windows(code)
self.failureDescription = reason
}
public init(winsock code: CInt, reason: String) {
self.error = .winsock(code)
self.failureDescription = reason
}
#endif
/// Creates a new `IOError``
///
/// - parameters:
/// - errorCode: the `errno` that was set for the operation.
/// - reason: the actual reason (in an human-readable form).
public init(errnoCode code: CInt, reason: String) {
self.error = .errno(code)
self.failureDescription = reason
}
/// Creates a new `IOError``
///
/// - parameters:
/// - errorCode: the `errno` that was set for the operation.
/// - function: The function the error happened in, the human readable description will be generated automatically when needed.
@available(*, deprecated, renamed: "init(errnoCode:reason:)")
public init(errnoCode code: CInt, function: StaticString) {
self.error = .errno(code)
self.failureDescription = "\(function)"
}
}
/// Returns a reason to use when constructing a `IOError`.
///
/// - parameters:
/// - errorCode: the `errno` that was set for the operation.
/// - reason: what failed
/// - returns: the constructed reason.
private func reasonForError(errnoCode: CInt, reason: String) -> String {
if let errorDescC = strerror(errnoCode) {
return "\(reason): \(String(cString: errorDescC)) (errno: \(errnoCode))"
} else {
return "\(reason): Broken strerror, unknown error: \(errnoCode)"
}
}
#if os(Windows)
private func reasonForWinError(_ code: DWORD) -> String {
let dwFlags: DWORD = DWORD(FORMAT_MESSAGE_ALLOCATE_BUFFER)
| DWORD(FORMAT_MESSAGE_FROM_SYSTEM)
| DWORD(FORMAT_MESSAGE_IGNORE_INSERTS)
var buffer: UnsafeMutablePointer<WCHAR>?
// We use `FORMAT_MESSAGE_ALLOCATE_BUFFER` in flags which means that the
// buffer will be allocated by the call to `FormatMessageW`. The function
// expects a `LPWSTR` and expects the user to type-pun in this case.
let dwResult: DWORD = withUnsafeMutablePointer(to: &buffer) {
$0.withMemoryRebound(to: WCHAR.self, capacity: 2) {
FormatMessageW(dwFlags, nil, code,
MAKELANGID(WORD(LANG_NEUTRAL), WORD(SUBLANG_DEFAULT)),
$0, 0, nil)
}
}
guard dwResult > 0, let message = buffer else {
return "unknown error \(code)"
}
defer { LocalFree(buffer) }
return String(decodingCString: message, as: UTF16.self)
}
#endif
extension IOError: CustomStringConvertible {
public var description: String {
return self.localizedDescription
}
public var localizedDescription: String {
#if os(Windows)
switch self.error {
case .errno(let errno):
return reasonForError(errnoCode: errno, reason: self.failureDescription)
case .windows(let code):
return reasonForWinError(code)
case .winsock(let code):
return reasonForWinError(DWORD(code))
}
#else
return reasonForError(errnoCode: self.errnoCode, reason: self.failureDescription)
#endif
}
}
// FIXME: Duplicated with NIO.
/// An result for an IO operation that was done on a non-blocking resource.
enum CoreIOResult<T: Equatable>: Equatable {
/// Signals that the IO operation could not be completed as otherwise we would need to block.
case wouldBlock(T)
/// Signals that the IO operation was completed.
case processed(T)
}
internal extension CoreIOResult where T: FixedWidthInteger {
var result: T {
switch self {
case .processed(let value):
return value
case .wouldBlock(_):
fatalError("cannot unwrap CoreIOResult")
}
}
}
| 295bb9a828a606810a64786f7b6f209e | 31.278947 | 143 | 0.633295 | false | false | false | false |
m-alani/contests | refs/heads/master | leetcode/bulbSwitcher.swift | mit | 1 | //
// bulbSwitcher.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/bulb-switcher/
// Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code
//
class Solution {
func bulbSwitch(_ n: Int) -> Int {
return Int(sqrt(Double(n)))
}
}
/* Greedy Initial Solution :
func bulbSwitch(_ n: Int) -> Int {
if n < 2 { return n }
var bulbs = Array(repeating: true, count: n)
var i = 2
while i <= n {
var idx = i - 1
while idx < n {
bulbs[idx] = !bulbs[idx]
idx += i
}
i += 1
}
return bulbs.filter({ $0 }).count
}
*/
| 3c3b84faa9fbf27fd01263cf060d3991 | 20.363636 | 117 | 0.602837 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/Parse/subscripting.swift | apache-2.0 | 6 | // RUN: %target-typecheck-verify-swift
struct X { }
// Simple examples
struct X1 {
var stored: Int
subscript(i: Int) -> Int {
get {
return stored
}
mutating
set {
stored = newValue
}
}
}
struct X2 {
var stored: Int
subscript(i: Int) -> Int {
get {
return stored + i
}
set(v) {
stored = v - i
}
}
}
struct X3 {
var stored: Int
subscript(_: Int) -> Int {
get {
return stored
}
set(v) {
stored = v
}
}
}
struct X4 {
var stored: Int
subscript(i: Int, j: Int) -> Int {
get {
return stored + i + j
}
mutating
set(v) {
stored = v + i - j
}
}
}
struct Y1 {
var stored: Int
subscript(_: i, j: Int) -> Int { // expected-error {{use of undeclared type 'i'}}
get {
return stored + j
}
set {
stored = j
}
}
}
// Mutating getters on constants (https://bugs.swift.org/browse/SR-845)
struct Y2 {
subscript(_: Int) -> Int {
mutating get { return 0 }
}
}
let y2 = Y2() // expected-note{{change 'let' to 'var' to make it mutable}}{{1-4=var}}
_ = y2[0] // expected-error{{cannot use mutating getter on immutable value: 'y2' is a 'let' constant}}
// Parsing errors
struct A0 {
subscript // expected-error {{expected '(' for subscript parameters}}
i : Int
-> Int {
get {
return stored
}
set {
stored = value
}
}
subscript -> Int { // expected-error {{expected '(' for subscript parameters}} {{12-12=()}}
return 1
}
}
struct A1 {
subscript (i : Int) // expected-error{{expected '->' for subscript element type}}
Int {
get {
return stored
}
set {
stored = value
}
}
}
struct A2 {
subscript (i : Int) -> // expected-error{{expected subscripting element type}}
{
get {
return stored
}
set {
stored = value
}
}
}
struct A3 {
subscript(i : Int) // expected-error {{expected '->' for subscript element type}}
{
get {
return i
}
}
}
struct A4 {
subscript(i : Int) { // expected-error {{expected '->' for subscript element type}}
get {
return i
}
}
}
struct A5 {
subscript(i : Int) -> Int // expected-error {{expected '{' in subscript to specify getter and setter implementation}}
}
struct A6 {
subscript(i: Int)(j: Int) -> Int { // expected-error {{expected '->' for subscript element type}}
get {
return i + j
}
}
}
struct A7 {
static subscript(a: Int) -> Int { // expected-error {{subscript cannot be marked 'static'}} {{3-10=}}
get {
return 42
}
}
}
struct A7b {
class subscript(a: Float) -> Int { // expected-error {{subscript cannot be marked 'class'}} {{3-9=}}
get {
return 42
}
}
}
struct A8 {
subscript(i : Int) -> Int // expected-error{{expected '{' in subscript to specify getter and setter implementation}}
get {
return stored
}
set {
stored = value
}
}
struct A9 {
subscript x() -> Int { // expected-error {{subscripts cannot have a name}} {{13-14=}}
return 0
}
}
struct A10 {
subscript x(i: Int) -> Int { // expected-error {{subscripts cannot have a name}} {{13-14=}}
return 0
}
}
struct A11 {
subscript x y : Int -> Int { // expected-error {{expected '(' for subscript parameters}}
return 0
}
}
} // expected-error{{extraneous '}' at top level}} {{1-3=}}
| d5b6633345b2d0bb238688734ca96fa4 | 16.395939 | 119 | 0.550919 | false | false | false | false |
WhisperSystems/Signal-iOS | refs/heads/master | Signal/test/util/ByteParserTest.swift | gpl-3.0 | 1 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import XCTest
@testable import Signal
class ByteParserTest: SignalBaseTest {
override func setUp() {
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testGetShort_Empty() {
let parser = ByteParser(data: Data(), littleEndian: true)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertEqual(0, parser.nextShort())
XCTAssertTrue(parser.hasError)
}
func testGetShort_littleEndian() {
let data = Data([0x01, 0x00, 0x00, 0x01, 0x01, 0x01])
let parser = ByteParser(data: data, littleEndian: true)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertEqual(1, parser.nextShort())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(256, parser.nextShort())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(257, parser.nextShort())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(0, parser.nextShort())
XCTAssertTrue(parser.hasError)
}
func testGetShort_bigEndian() {
let data = Data([0x01, 0x00, 0x00, 0x01, 0x01, 0x01])
let parser = ByteParser(data: data, littleEndian: false)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertEqual(256, parser.nextShort())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(1, parser.nextShort())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(257, parser.nextShort())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(0, parser.nextShort())
XCTAssertTrue(parser.hasError)
}
func testGetInt_Empty() {
let parser = ByteParser(data: Data(), littleEndian: true)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertEqual(0, parser.nextInt())
XCTAssertTrue(parser.hasError)
}
func testGetInt_littleEndian() {
let data = Data([0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00])
let parser = ByteParser(data: data, littleEndian: true)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertEqual(1, parser.nextInt())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(256, parser.nextInt())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(257, parser.nextInt())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(0, parser.nextInt())
XCTAssertTrue(parser.hasError)
}
func testGetInt_bigEndian() {
let data = Data([0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01])
let parser = ByteParser(data: data, littleEndian: false)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertEqual(1, parser.nextInt())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(256, parser.nextInt())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(257, parser.nextInt())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(0, parser.nextInt())
XCTAssertTrue(parser.hasError)
}
func testGetLong_Empty() {
let parser = ByteParser(data: Data(), littleEndian: true)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertEqual(0, parser.nextLong())
XCTAssertTrue(parser.hasError)
}
func testGetLong_littleEndian() {
let data = Data([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
let parser = ByteParser(data: data, littleEndian: true)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertEqual(1, parser.nextLong())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(256, parser.nextLong())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(257, parser.nextLong())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(0, parser.nextLong())
XCTAssertTrue(parser.hasError)
}
func testGetLong_bigEndian() {
let data = Data([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01])
let parser = ByteParser(data: data, littleEndian: false)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertEqual(1, parser.nextLong())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(256, parser.nextLong())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(257, parser.nextLong())
XCTAssertFalse(parser.hasError)
XCTAssertEqual(0, parser.nextLong())
XCTAssertTrue(parser.hasError)
}
func testReadZero_Empty() {
let parser = ByteParser(data: Data(), littleEndian: true)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertFalse(parser.readZero(1))
XCTAssertTrue(parser.hasError)
}
func testReadZero() {
let data = Data([0x00, 0x01, 0x00, 0x00, 0x01, 0x00])
let parser = ByteParser(data: data, littleEndian: true)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertTrue(parser.readZero(1))
XCTAssertFalse(parser.hasError)
XCTAssertFalse(parser.readZero(1))
XCTAssertFalse(parser.hasError)
XCTAssertTrue(parser.readZero(2))
XCTAssertFalse(parser.hasError)
XCTAssertFalse(parser.readZero(2))
XCTAssertFalse(parser.hasError)
XCTAssertFalse(parser.readZero(1))
XCTAssertTrue(parser.hasError)
}
func testReadBytes_Empty() {
let parser = ByteParser(data: Data(), littleEndian: true)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertNil(parser.readBytes(1))
XCTAssertTrue(parser.hasError)
}
func testReadBytes() {
let data = Data([0x00, 0x01, 0x02, 0x03, 0x04, 0x05])
let parser = ByteParser(data: data, littleEndian: true)
XCTAssertNotNil(parser)
XCTAssertFalse(parser.hasError)
XCTAssertEqual(Data([0x00]), parser.readBytes(1))
XCTAssertFalse(parser.hasError)
XCTAssertEqual(Data([0x01]), parser.readBytes(1))
XCTAssertFalse(parser.hasError)
XCTAssertEqual(Data([0x02, 0x03]), parser.readBytes(2))
XCTAssertFalse(parser.hasError)
XCTAssertEqual(Data([0x04, 0x05]), parser.readBytes(2))
XCTAssertFalse(parser.hasError)
XCTAssertNil(parser.readBytes(1))
XCTAssertTrue(parser.hasError)
}
}
| 5223f6414b7b89aab4959a563dfcb6c0 | 30.131222 | 169 | 0.652471 | false | true | false | false |
Antondomashnev/Sourcery | refs/heads/master | SourceryTests/Stub/Performance-Code/Kiosk/Admin/AdminCardTestingViewController.swift | mit | 2 | import Foundation
import RxSwift
import Keys
class AdminCardTestingViewController: UIViewController {
lazy var keys = EidolonKeys()
var cardHandler: CardHandler!
@IBOutlet weak var logTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
self.logTextView.text = ""
if AppSetup.sharedState.useStaging {
cardHandler = CardHandler(apiKey: self.keys.cardflightStagingAPIClientKey(), accountToken: self.keys.cardflightStagingMerchantAccountToken())
} else {
cardHandler = CardHandler(apiKey: self.keys.cardflightProductionAPIClientKey(), accountToken: self.keys.cardflightProductionMerchantAccountToken())
}
cardHandler.cardStatus
.subscribe { (event) in
switch event {
case .next(let message):
self.log("\(message)")
case .error(let error):
self.log("\n====Error====\n\(error)\nThe card reader may have become disconnected.\n\n")
if self.cardHandler.card != nil {
self.log("==\n\(self.cardHandler.card!)\n\n")
}
case .completed:
guard let card = self.cardHandler.card else {
// Restarts the card reader
self.cardHandler.startSearching()
return
}
let cardDetails = "Card: \(card.name) - \(card.last4) \n \(card.cardToken)"
self.log(cardDetails)
}
}
.addDisposableTo(rx_disposeBag)
cardHandler.startSearching()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
cardHandler.end()
}
func log(_ string: String) {
self.logTextView.text = "\(self.logTextView.text ?? "")\n\(string)"
}
@IBAction func backTapped(_ sender: AnyObject) {
_ = navigationController?.popViewController(animated: true)
}
}
| 74ee97469f18f1f986de0330bf0e6017 | 32.629032 | 159 | 0.567866 | false | false | false | false |
vector-im/riot-ios | refs/heads/develop | Riot/Modules/SetPinCode/SetupBiometrics/SetupBiometricsViewModel.swift | apache-2.0 | 1 | // File created from ScreenTemplate
// $ createScreen.sh SetPinCode/SetupBiometrics SetupBiometrics
/*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import LocalAuthentication
final class SetupBiometricsViewModel: SetupBiometricsViewModelType {
// MARK: - Properties
// MARK: Private
private let session: MXSession?
private let viewMode: SetPinCoordinatorViewMode
private let pinCodePreferences: PinCodePreferences
// MARK: Public
weak var viewDelegate: SetupBiometricsViewModelViewDelegate?
weak var coordinatorDelegate: SetupBiometricsViewModelCoordinatorDelegate?
// MARK: - Setup
init(session: MXSession?, viewMode: SetPinCoordinatorViewMode, pinCodePreferences: PinCodePreferences) {
self.session = session
self.viewMode = viewMode
self.pinCodePreferences = pinCodePreferences
}
deinit {
}
// MARK: - Public
func localizedBiometricsName() -> String? {
return pinCodePreferences.localizedBiometricsName()
}
func biometricsIcon() -> UIImage? {
return pinCodePreferences.biometricsIcon()
}
func process(viewAction: SetupBiometricsViewAction) {
switch viewAction {
case .loadData:
loadData()
case .enableDisableTapped:
enableDisableBiometrics()
case .skipOrCancel:
coordinatorDelegate?.setupBiometricsViewModelDidCancel(self)
case .unlock:
unlockWithBiometrics()
case .cantUnlockedAlertResetAction:
coordinatorDelegate?.setupBiometricsViewModelDidCompleteWithReset(self)
}
}
// MARK: - Private
private func enableDisableBiometrics() {
LAContext().evaluatePolicy(.deviceOwnerAuthentication, localizedReason: VectorL10n.biometricsUsageReason) { (success, error) in
if success {
// complete after a little delay
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.coordinatorDelegate?.setupBiometricsViewModelDidComplete(self)
}
}
}
}
private func unlockWithBiometrics() {
LAContext().evaluatePolicy(.deviceOwnerAuthentication, localizedReason: VectorL10n.biometricsUsageReason) { (success, error) in
if success {
// complete after a little delay
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.coordinatorDelegate?.setupBiometricsViewModelDidComplete(self)
}
} else {
if let error = error as NSError?, error.code == LAError.Code.userCancel.rawValue || error.code == LAError.Code.userFallback.rawValue {
self.userCancelledUnlockWithBiometrics()
}
}
}
}
private func userCancelledUnlockWithBiometrics() {
if pinCodePreferences.isPinSet {
// cascade this cancellation, coordinator should take care of it
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.coordinatorDelegate?.setupBiometricsViewModelDidCancel(self)
}
} else {
// show an alert to nowhere to go from here
DispatchQueue.main.async {
self.update(viewState: .cantUnlocked)
}
}
}
private func loadData() {
switch viewMode {
case .setupBiometricsAfterLogin:
self.update(viewState: .setupAfterLogin)
case .setupBiometricsFromSettings:
self.update(viewState: .setupFromSettings)
case .unlock:
self.update(viewState: .unlock)
case .confirmBiometricsToDeactivate:
self.update(viewState: .confirmToDisable)
default:
break
}
}
private func update(viewState: SetupBiometricsViewState) {
self.viewDelegate?.setupBiometricsViewModel(self, didUpdateViewState: viewState)
}
}
| 541307047794f62d7576ad73bc0e98d0 | 33.133333 | 150 | 0.647569 | false | false | false | false |
mhplong/Projects | refs/heads/master | iOS/ServiceTracker/ServiceTimeTracker/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// ServiceTimeTracker
//
// Created by Mark Long on 5/11/16.
// Copyright © 2016 Mark Long. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// 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 "com.ml.ServiceTimeTracker" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
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("ServiceTimeTracker", 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. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| a430820d92dcc10f7bdfe163bf929f57 | 54.054054 | 291 | 0.72034 | false | false | false | false |
atrick/swift | refs/heads/main | validation-test/compiler_crashers_2_fixed/sr9584.swift | apache-2.0 | 3 | // RUN: %target-typecheck-verify-swift -requirement-machine-inferred-signatures=on
struct S<N> {}
protocol P {
associatedtype A: P = Self
static func f(_ x: A) -> A
}
extension S: P where N: P {
static func f<X: P>(_ x: X) -> S<X.A> where A == X, X.A == N {
// expected-error@-1 {{cannot build rewrite system for generic signature; rule length limit exceeded}}
// expected-note@-2 {{failed rewrite rule is τ_0_0.[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[concrete: S<S<S<S<S<S<S<S<S<S<S<S<S<S<τ_0_0>>>>>>>>>>>>>>] => τ_0_0.[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A] [subst↓]}}
// expected-error@-3 {{'A' is not a member type of type 'X'}}
// expected-error@-4 {{'A' is not a member type of type 'X'}}
return S<X.A>()
}
}
| bd080e4c09bdd0e6bf7bebb0e79f019d | 44.277778 | 288 | 0.55092 | false | false | false | false |
chengxianghe/MissGe | refs/heads/master | MissGe/MissGe/Class/Project/UI/Controller/Mine/MLUserFansController.swift | mit | 1 | //
// MLFansController.swift
// MissLi
//
// Created by CXH on 2016/10/11.
// Copyright © 2016年 cn. All rights reserved.
//
import UIKit
class MLUserFansController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet private weak var tableView: UITableView!
var isFans = false
var uid: String = ""
private var dataSource = [MLUserModel]()
private let fansRequest = MLUserFansListRequest()
private let followersRequest = MLUserFollowListRequest()
private var currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
self.loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - 数据请求
func loadData(){
self.showLoading("正在加载...")
var request: MLBaseRequest!
if isFans {
self.fansRequest.uid = self.uid
request = self.fansRequest
} else {
self.followersRequest.uid = self.uid
request = self.followersRequest
}
request.send(success: {[unowned self] (baseRequest, responseObject) in
self.hideHud()
guard let blacklist = ((responseObject as? NSDictionary)?["content"] as? NSDictionary)?["blacklist"] as? [[String:Any]] else {
return
}
guard let modelArray = blacklist.map({ MLUserModel(JSON: $0) }) as? [MLUserModel] else {
return
}
self.dataSource.append(contentsOf: modelArray)
self.tableView.reloadData()
}) { (baseRequest, error) in
print(error)
self.showError("请求出错")
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MLUserFansCell") as? MLUserFansCell
let userModel = self.dataSource[indexPath.row]
cell!.setInfo(model: userModel);
cell!.onFollowButtonTapClosure = {(sender) in
if userModel.relation == 0 {
// 去关注
MLRequestHelper.userFollow(self.uid, succeed: { (base, res) in
self.showSuccess("关注成功")
userModel.relation = 1
self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none)
}, failed: { (base, err) in
self.showError("网络错误")
print(err)
})
} else {
// 取消关注
MLRequestHelper.userFollow(self.uid, succeed: { (base, res) in
self.showSuccess("已取消关注")
userModel.relation = 0
self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none)
}, failed: { (base, err) in
self.showError("网络错误")
print(err)
})
}
}
cell!.onIconButtonTapClosure = {(sender) in
// 进入用户详情
//ToUserDetail
self.performSegue(withIdentifier: "ToUserDetail", sender: userModel)
}
return cell!
}
// func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// return MLTopicCell.height(model)
// }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
// 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.
if segue.identifier == "ToUserDetail" {
let vc = segue.destination as! MLUserController
vc.uid = (sender as! MLUserModel).uid
}
}
}
| fb237582f338509bd7d6341b3e7473b2 | 32.164063 | 138 | 0.560895 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/Generics/slice_test.swift | apache-2.0 | 42 | // RUN: %target-typecheck-verify-swift -parse-stdlib
import Swift
infix operator < : ComparisonPrecedence
precedencegroup ComparisonPrecedence {
associativity: none
higherThan: EqualityPrecedence
}
infix operator == : EqualityPrecedence
infix operator != : EqualityPrecedence
precedencegroup EqualityPrecedence {
associativity: none
higherThan: AssignmentPrecedence
}
precedencegroup AssignmentPrecedence {
assignment: true
}
func testslice(_ s: Array<Int>) {
for i in 0..<s.count { print(s[i]+1) }
for i in s { print(i+1) }
_ = s[0..<2]
_ = s[0...1]
_ = s[...1]
_ = s[1...]
_ = s[..<2]
}
@_silgen_name("malloc") func c_malloc(_ size: Int) -> UnsafeMutableRawPointer
@_silgen_name("free") func c_free(_ p: UnsafeMutableRawPointer)
class Vector<T> {
var length : Int
var capacity : Int
var base : UnsafeMutablePointer<T>!
init() {
length = 0
capacity = 0
base = nil
}
func push_back(_ elem: T) {
if length == capacity {
let newcapacity = capacity * 2 + 2
let size = Int(Builtin.sizeof(T.self))
let newbase = UnsafeMutablePointer<T>(c_malloc(newcapacity * size)
.bindMemory(to: T.self, capacity: newcapacity))
for i in 0..<length {
(newbase + i).initialize(to: (base+i).move())
}
c_free(base)
base = newbase
capacity = newcapacity
}
(base+length).initialize(to: elem)
length += 1
}
func pop_back() -> T {
length -= 1
return (base + length).move()
}
subscript (i : Int) -> T {
get {
if i >= length {
Builtin.int_trap()
}
return (base + i).pointee
}
set {
if i >= length {
Builtin.int_trap()
}
(base + i).pointee = newValue
}
}
deinit {
base.deinitialize(count: length)
c_free(base)
}
}
protocol Comparable {
static func <(lhs: Self, rhs: Self) -> Bool
}
func sort<T : Comparable>(_ array: inout [T]) {
for i in 0..<array.count {
for j in i+1..<array.count {
if array[j] < array[i] {
let temp = array[i]
array[i] = array[j]
array[j] = temp
}
}
}
}
func find<T : Eq>(_ array: [T], value: T) -> Int {
var idx = 0
for elt in array {
if (elt == value) { return idx }
idx += 1
}
return -1
}
func findIf<T>(_ array: [T], fn: (T) -> Bool) -> Int {
var idx = 0
for elt in array {
if (fn(elt)) { return idx }
idx += 1
}
return -1
}
protocol Eq {
static func ==(lhs: Self, rhs: Self) -> Bool
static func !=(lhs: Self, rhs: Self) -> Bool
}
| 3186ec89e45d42e699196bab1ff4bd9b | 19.149606 | 77 | 0.574443 | false | false | false | false |
katsana/katsana-sdk-ios | refs/heads/master | KatsanaSDK/Object/KTUser.swift | apache-2.0 | 1 | //
// DriveMarkSDK.User.swift
// KatsanaSDK
//
// Created by Wan Ahmad Lutfi on 27/01/2017.
// Copyright © 2017 pixelated. All rights reserved.
//
public enum Gender : String{
case unknown
case male
case female
}
@objcMembers
open class KTUser: NSObject {
static let dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
open var email: String
open var userId: String!
open var address: String!
open var phoneHome: String!
open var phoneMobile: String!
open var identification: String!
open var fullname: String!
open var status: Int = 0
open var emergencyFullName: String!
open var emergencyPhoneHome: String!
open var emergencyPhoneMobile: String!
open var imageURL: String!
open var thumbImageURL: String!
open var phoneMobileCountryCode: String!
open var postcode: String!
open var state: String!
open var country: String!
open var gender: Gender = .unknown
open var fleets = [Fleet]()
open var genderText: String!{
get{
if gender == .unknown{
return nil
}
return gender.rawValue.capitalized
}
set{
if let newValue = newValue{
if newValue.lowercased() == "male" {
gender = .male
}
else if newValue.lowercased() == "female" {
gender = .female
}
}else{
gender = .unknown
}
}
}
open var birthday: Date!{
didSet{
if let birthday = birthday {
let dateStr = KTUser.dateFormatter.string(from: birthday)
if let birthdayText = birthdayText, dateStr == birthdayText{
}else{
birthdayText = dateStr
}
}else{
birthdayText = ""
}
}
}
open var birthdayText: String!{
didSet{
if let birthdayText = birthdayText {
let date = KTUser.dateFormatter.date(from: birthdayText)
if let birthday = birthday, date == birthday {
//Do nothing
}else if date != nil{
birthday = date
}
}else{
birthday = nil
}
}
}
open var createdAt: Date!
open var updatedAt: Date!
private(set) open var image : KMImage!
private(set) open var thumbImage : KMImage!
private var imageBlocks = [(image: KMImage) -> Void]()
private var thumbImageBlocks = [(image: KMImage) -> Void]()
private var isLoadingImage = false
private var isLoadingThumbImage = false
///Implemented to satisfy FastCoder and set default value
override init() {
email = ""
}
init(email: String) {
self.email = email
}
override open class func fastCodingKeys() -> [Any]? {
return ["userId", "email", "address", "phoneHome", "phoneMobile", "fullname", "status", "createdAt", "imageURL", "thumbImageURL", "postcode", "phoneMobileCountryCode", "state", "country", "birthdayText", "genderText", "fleets"]
}
open func jsonPatch() -> [String: Any] {
var dicto = [String: Any]()
if let address = address{
dicto["address"] = address
}
if let phoneHome = phoneHome{
dicto["phone_home"] = phoneHome
}
if let phoneMobile = phoneMobile{
dicto["phone_mobile"] = phoneMobile
}
if let fullname = fullname{
dicto["fullname"] = fullname
}
if let emergencyFullName = emergencyFullName{
dicto["meta.emergency.fullname"] = emergencyFullName
}
if let emergencyPhoneHome = emergencyPhoneHome{
dicto["meta.emergency.phone.home"] = emergencyPhoneHome
}
if let emergencyPhoneMobile = emergencyPhoneMobile{
dicto["meta.emergency.phone.mobile"] = emergencyPhoneMobile
}
return dicto
}
// MARK: Image
open func updateImage(_ image: KMImage) {
self.image = image
}
open func image(completion: @escaping (_ image: KMImage) -> Void){
guard imageURL != nil else {
return
}
if let image = image {
completion(image)
}else if let path = NSURL(string: imageURL)?.lastPathComponent, let image = KTCacheManager.shared.image(for: path){
self.image = image
completion(image)
}else{
if isLoadingImage {
imageBlocks.append(completion)
}else{
isLoadingImage = true
ImageRequest.shared.requestImage(path: imageURL, completion: { (image) in
self.image = image
self.isLoadingImage = false
for block in self.imageBlocks{
block(image!)
}
completion(image!)
}, failure: { (error) in
KatsanaAPI.shared.log.error("Error requesting user image \(self.email)")
self.isLoadingImage = false
})
}
}
}
open func thumbImage(completion: @escaping (_ image: KMImage) -> Void){
guard thumbImageURL != nil else {
return
}
if let image = thumbImage {
completion(image)
}else if let path = NSURL(string: thumbImageURL)?.lastPathComponent, let image = KTCacheManager.shared.image(for: path){
completion(image)
}else{
if isLoadingThumbImage {
thumbImageBlocks.append(completion)
}else{
isLoadingThumbImage = true
ImageRequest.shared.requestImage(path: thumbImageURL, completion: { (image) in
self.thumbImage = image
self.isLoadingThumbImage = false
for block in self.thumbImageBlocks{
block(image!)
}
completion(image!)
}, failure: { (error) in
KatsanaAPI.shared.log.error("Error requesting user thumb image \(self.email)")
self.isLoadingThumbImage = false
})
}
}
}
// MARK: helper
open func fleet(id: Int) -> Fleet!{
for fleet in fleets{
if fleet.fleetId == id{
return fleet
}
}
return nil
}
open func profileProgress() -> CGFloat {
var progressCount :CGFloat = 0
let totalCount:CGFloat = 8 - 1
if let fullname = fullname, fullname.count > 0 {
progressCount += 1
}
if let phoneNumber = phoneMobile, phoneNumber.count > 0 {
progressCount += 1
}
// if (birthday) != nil{
// progressCount += 1
// }
if let address = address, address.count > 0{
progressCount += 1
}
if let country = country, country.count > 0{
progressCount += 1
}
if let postcode = postcode, postcode.count > 0{
progressCount += 1
}
if gender != .unknown{
progressCount += 1
}
if let imageURL = imageURL, imageURL.count > 0{
progressCount += 1
}else if image != nil{
progressCount += 1
}
let progress = progressCount/totalCount
return progress
}
func isPhoneNumber(_ text: String) -> Bool {
if text.count < 3 {
return false
}
let set = CharacterSet(charactersIn: "+0123456789 ")
if text.trimmingCharacters(in: set) == ""{
return true
}
return false
}
open func date(from string: String) -> Date! {
return KTUser.dateFormatter.date(from: string)
}
}
| fc698f0e36f160153f19c31eb8f9dfdb | 29.304029 | 235 | 0.520005 | false | false | false | false |
PerfectServers/Perfect-Authentication-Server | refs/heads/master | Sources/PerfectAuthServer/handlers/Handlers.swift | apache-2.0 | 1 | //
// Handlers.swift
// Perfect-App-Template
//
// Created by Jonathan Guthrie on 2017-02-20.
// Copyright (C) 2017 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PerfectHTTP
import StORM
import PerfectLocalAuthentication
class Handlers {
// Basic "main" handler - simply outputs "Hello, world!"
static func main(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let users = Account()
try? users.findAll()
if users.rows().count == 0 {
response.redirect(path: "/initialize")
response.completed()
return
}
var context: [String : Any] = ["title": configTitle]
if let i = request.session?.userid, !i.isEmpty { context["authenticated"] = true }
// add app config vars
for i in Handlers.extras(request) { context[i.0] = i.1 }
for i in Handlers.appExtras(request) { context[i.0] = i.1 }
response.renderMustache(template: request.documentRoot + "/views/index.mustache", context: context)
}
}
}
| e9bb162173e022e798317c299015ed7c | 26.72 | 102 | 0.605339 | false | false | false | false |
royratcliffe/HypertextApplicationLanguage | refs/heads/master | Sources/Link+Equatable.swift | mit | 1 | // HypertextApplicationLanguage Link+Equatable.swift
//
// Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS,” WITHOUT WARRANTY OF ANY KIND, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//------------------------------------------------------------------------------
extension Link: Equatable {
/// - returns: Answers `true` if this `Link` compares equal to another.
public static func == (lhs: Link, rhs: Link) -> Bool {
return lhs.rel == rhs.rel &&
lhs.href == rhs.href &&
lhs.name == rhs.name &&
lhs.title == rhs.title &&
lhs.hreflang == rhs.hreflang &&
lhs.profile == rhs.profile
}
}
| 21e24c79b07f216820e41fc4043b1157 | 45.513514 | 80 | 0.665892 | false | false | false | false |
StravaKit/StravaKit | refs/heads/master | Sources/StravaClub.swift | mit | 2 | //
// StravaClub.swift
// StravaKit
//
// Created by Brennan Stehling on 8/22/16.
// Copyright © 2016 SmallSharpTools LLC. All rights reserved.
//
import Foundation
public enum ClubResourcePath: String {
case Club = "/api/v3/clubs/:id"
case Clubs = "/api/v3/athlete/clubs"
}
public extension Strava {
/**
Gets club detail.
```swift
Strava.getClub(1) { (club, error) in }
```
Docs: http://strava.github.io/api/v3/clubs/#get-details
*/
@discardableResult
public static func getClub(_ clubId: Int, completionHandler:((_ club: Club?, _ error: NSError?) -> ())?) -> URLSessionTask? {
let path = replaceId(id: clubId, in: ClubResourcePath.Club.rawValue)
return request(.GET, authenticated: true, path: path, params: nil) { (response, error) in
if let error = error {
DispatchQueue.main.async {
completionHandler?(nil, error)
}
return
}
handleClubResponse(response, completionHandler: completionHandler)
}
}
/**
Gets clubs for current athlete.
```swift
Strava.getClubs { (clubs, error) in }
```
Docs: http://strava.github.io/api/v3/clubs/#get-athletes
*/
@discardableResult
public static func getClubs(_ page: Page? = nil, completionHandler:((_ clubs: [Club]?, _ error: NSError?) -> ())?) -> URLSessionTask? {
let path = ClubResourcePath.Clubs.rawValue
var params: ParamsDictionary? = nil
if let page = page {
params = [
PageKey: page.page,
PerPageKey: page.perPage
]
}
return request(.GET, authenticated: true, path: path, params: params) { (response, error) in
if let error = error {
DispatchQueue.main.async {
completionHandler?(nil, error)
}
return
}
handleClubsResponse(response, completionHandler: completionHandler)
}
}
// MARK: - Internal Functions -
internal static func handleClubResponse(_ response: Any?, completionHandler:((_ club: Club?, _ error: NSError?) -> ())?) {
if let dictionary = response as? JSONDictionary,
let club = Club(dictionary: dictionary) {
DispatchQueue.main.async {
completionHandler?(club, nil)
}
}
else {
DispatchQueue.main.async {
let error = Strava.error(.invalidResponse, reason: "Invalid Response")
completionHandler?(nil, error)
}
}
}
internal static func handleClubsResponse(_ response: Any?, completionHandler:((_ clubs: [Club]?, _ error: NSError?) -> ())?) {
if let dictionaries = response as? JSONArray {
let clubs = Club.clubs(dictionaries)
DispatchQueue.main.async {
completionHandler?(clubs, nil)
}
}
else {
DispatchQueue.main.async {
let error = Strava.error(.invalidResponse, reason: "Invalid Response")
completionHandler?(nil, error)
}
}
}
}
| 348ed667140766cf37be8f4c0429e75f | 29.12963 | 139 | 0.55378 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Tool/Sources/ToolKit/General/UserPropertyRecorder/StandardUserProperty.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
/// Can be used to keep any key-value that doesn't require obfuscation
public struct StandardUserProperty: UserProperty {
public let key: UserPropertyKey
public let value: String
public let truncatesValueIfNeeded: Bool
public init(key: Key, value: String, truncatesValueIfNeeded: Bool = false) {
self.key = key
self.value = value
self.truncatesValueIfNeeded = truncatesValueIfNeeded
}
}
extension StandardUserProperty: Hashable {
public static func == (lhs: StandardUserProperty, rhs: StandardUserProperty) -> Bool {
lhs.key.rawValue == rhs.key.rawValue
}
public func hash(into hasher: inout Hasher) {
hasher.combine(key.rawValue)
}
}
extension StandardUserProperty {
/// A key for which a hashed user property is being recorded
public enum Key: String, UserPropertyKey {
case walletCreationDate = "creation_date"
case kycCreationDate = "kyc_creation_date"
case kycUpdateDate = "kyc_updated_date"
case kycLevel = "kyc_level"
case emailVerified = "email_verified"
case twoFAEnabled = "two_fa_enabled"
case totalBalance = "total_balance"
case fundedCoins = "funded_coins"
}
}
| 68fe69b344f3898e22b8ab56500b4d14 | 31.04878 | 90 | 0.687976 | false | false | false | false |
shadanan/mado | refs/heads/master | Antlr4Runtime/Sources/Antlr4/BufferedTokenStream.swift | mit | 1 | /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
/// This implementation of {@link org.antlr.v4.runtime.TokenStream} loads tokens from a
/// {@link org.antlr.v4.runtime.TokenSource} on-demand, and places the tokens in a buffer to provide
/// access to any previous token by index.
///
/// <p>
/// This token stream ignores the value of {@link org.antlr.v4.runtime.Token#getChannel}. If your
/// parser requires the token stream filter tokens to only those on a particular
/// channel, such as {@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL} or
/// {@link org.antlr.v4.runtime.Token#HIDDEN_CHANNEL}, use a filtering token stream such a
/// {@link org.antlr.v4.runtime.CommonTokenStream}.</p>
public class BufferedTokenStream: TokenStream {
/// The {@link org.antlr.v4.runtime.TokenSource} from which tokens for this stream are fetched.
internal var tokenSource: TokenSource
/// A collection of all tokens fetched from the token source. The list is
/// considered a complete view of the input once {@link #fetchedEOF} is set
/// to {@code true}.
internal var tokens: Array<Token> = Array<Token>()
// Array<Token>(100
/// The index into {@link #tokens} of the current token (next token to
/// {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be
/// {@link #LT LT(1)}.
///
/// <p>This field is set to -1 when the stream is first constructed or when
/// {@link #setTokenSource} is called, indicating that the first token has
/// not yet been fetched from the token source. For additional information,
/// see the documentation of {@link org.antlr.v4.runtime.IntStream} for a description of
/// Initializing Methods.</p>
internal var p: Int = -1
/// Indicates whether the {@link org.antlr.v4.runtime.Token#EOF} token has been fetched from
/// {@link #tokenSource} and added to {@link #tokens}. This field improves
/// performance for the following cases:
///
/// <ul>
/// <li>{@link #consume}: The lookahead check in {@link #consume} to prevent
/// consuming the EOF symbol is optimized by checking the values of
/// {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li>
/// <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into
/// {@link #tokens} is trivial with this field.</li>
/// <ul>
internal var fetchedEOF: Bool = false
public init(_ tokenSource: TokenSource) {
self.tokenSource = tokenSource
}
public func getTokenSource() -> TokenSource {
return tokenSource
}
public func index() -> Int {
return p
}
public func mark() -> Int {
return 0
}
public func release(_ marker: Int) {
// no resources to release
}
public func reset() throws {
try seek(0)
}
public func seek(_ index: Int) throws {
try lazyInit()
p = try adjustSeekIndex(index)
}
public func size() -> Int {
return tokens.count
}
public func consume() throws {
var skipEofCheck: Bool
if p >= 0 {
if fetchedEOF {
// the last token in tokens is EOF. skip check if p indexes any
// fetched token except the last.
skipEofCheck = p < tokens.count - 1
} else {
// no EOF token in tokens. skip check if p indexes a fetched token.
skipEofCheck = p < tokens.count
}
} else {
// not yet initialized
skipEofCheck = false
}
if try !skipEofCheck && LA(1) == BufferedTokenStream.EOF {
throw ANTLRError.illegalState(msg: "cannot consume EOF")
//RuntimeException("cannot consume EOF")
//throw ANTLRError.IllegalState /* throw IllegalStateException("cannot consume EOF"); */
}
if try sync(p + 1) {
p = try adjustSeekIndex(p + 1)
}
}
/// Make sure index {@code i} in tokens has a token.
///
/// - returns: {@code true} if a token is located at index {@code i}, otherwise
/// {@code false}.
/// - seealso: #get(int i)
@discardableResult
internal func sync(_ i: Int) throws -> Bool {
assert(i >= 0, "Expected: i>=0")
let n: Int = i - tokens.count + 1 // how many more elements we need?
//print("sync("+i+") needs "+n);
if n > 0 {
let fetched: Int = try fetch(n)
return fetched >= n
}
return true
}
/// Add {@code n} elements to buffer.
///
/// - returns: The actual number of elements added to the buffer.
internal func fetch(_ n: Int) throws -> Int {
if fetchedEOF {
return 0
}
for i in 0..<n {
let t: Token = try tokenSource.nextToken()
if t is WritableToken {
(t as! WritableToken).setTokenIndex(tokens.count)
}
tokens.append(t) //add
if t.getType() == BufferedTokenStream.EOF {
fetchedEOF = true
return i + 1
}
}
return n
}
public func get(_ i: Int) throws -> Token {
if i < 0 || i >= tokens.count {
let index = tokens.count - 1
throw ANTLRError.indexOutOfBounds(msg: "token index \(i) out of range 0..\(index)")
}
return tokens[i] //tokens[i]
}
/// Get all tokens from start..stop inclusively
public func get(_ start: Int,_ stop: Int) throws -> Array<Token>? {
var stop = stop
if start < 0 || stop < 0 {
return nil
}
try lazyInit()
var subset: Array<Token> = Array<Token>()
if stop >= tokens.count {
stop = tokens.count - 1
}
for i in start...stop {
let t: Token = tokens[i]
if t.getType() == BufferedTokenStream.EOF {
break
}
subset.append(t)
}
return subset
}
//TODO: LT(i)!.getType();
public func LA(_ i: Int) throws -> Int {
return try LT(i)!.getType()
}
internal func LB(_ k: Int) throws -> Token? {
if (p - k) < 0 {
return nil
}
return tokens[p - k]
}
public func LT(_ k: Int) throws -> Token? {
try lazyInit()
if k == 0 {
return nil
}
if k < 0 {
return try LB(-k)
}
let i: Int = p + k - 1
try sync(i)
if i >= tokens.count {
// return EOF token
// EOF must be last token
return tokens[tokens.count - 1]
}
// if ( i>range ) range = i;
return tokens[i]
}
/// Allowed derived classes to modify the behavior of operations which change
/// the current stream position by adjusting the target token index of a seek
/// operation. The default implementation simply returns {@code i}. If an
/// exception is thrown in this method, the current stream index should not be
/// changed.
///
/// <p>For example, {@link org.antlr.v4.runtime.CommonTokenStream} overrides this method to ensure that
/// the seek target is always an on-channel token.</p>
///
/// - parameter i: The target token index.
/// - returns: The adjusted target token index.
internal func adjustSeekIndex(_ i: Int) throws -> Int {
return i
}
internal final func lazyInit() throws {
if p == -1 {
try setup()
}
}
internal func setup() throws {
try sync(0)
p = try adjustSeekIndex(0)
}
/// Reset this token stream by setting its token source.
public func setTokenSource(_ tokenSource: TokenSource) {
self.tokenSource = tokenSource
tokens.removeAll()
p = -1
fetchedEOF = false
}
public func getTokens() -> Array<Token> {
return tokens
}
public func getTokens(_ start: Int, _ stop: Int) throws -> Array<Token>? {
return try getTokens(start, stop, nil)
}
/// Given a start and stop index, return a List of all tokens in
/// the token type BitSet. Return null if no tokens were found. This
/// method looks at both on and off channel tokens.
public func getTokens(_ start: Int, _ stop: Int, _ types: Set<Int>?) throws -> Array<Token>? {
try lazyInit()
if start < 0 || stop >= tokens.count ||
stop < 0 || start >= tokens.count {
throw ANTLRError.indexOutOfBounds(msg: "start \(start) or stop \(stop) not in 0..\(tokens.count - 1)")
}
if start > stop {
return nil
}
var filteredTokens: Array<Token> = Array<Token>()
for i in start...stop {
let t: Token = tokens[i]
if let types = types , !types.contains(t.getType()) {
}else {
filteredTokens.append(t)
}
}
if filteredTokens.isEmpty {
return nil
//filteredTokens = nil;
}
return filteredTokens
}
public func getTokens(_ start: Int, _ stop: Int, _ ttype: Int) throws -> Array<Token>? {
//TODO Set<Int> initialCapacity
var s: Set<Int> = Set<Int>()
s.insert(ttype)
//s.append(ttype);
return try getTokens(start, stop, s)
}
/// Given a starting index, return the index of the next token on channel.
/// Return {@code i} if {@code tokens[i]} is on channel. Return the index of
/// the EOF token if there are no tokens on channel between {@code i} and
/// EOF.
internal func nextTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int {
var i = i
try sync(i)
if i >= size() {
return size() - 1
}
var token: Token = tokens[i]
while token.getChannel() != channel {
if token.getType() == BufferedTokenStream.EOF {
return i
}
i += 1
try sync(i)
token = tokens[i]
}
return i
}
/// Given a starting index, return the index of the previous token on
/// channel. Return {@code i} if {@code tokens[i]} is on channel. Return -1
/// if there are no tokens on channel between {@code i} and 0.
///
/// <p>
/// If {@code i} specifies an index at or after the EOF token, the EOF token
/// index is returned. This is due to the fact that the EOF token is treated
/// as though it were on every channel.</p>
internal func previousTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int {
var i = i
try sync(i)
if i >= size() {
// the EOF token is on every channel
return size() - 1
}
while i >= 0 {
let token: Token = tokens[i]
if token.getType() == BufferedTokenStream.EOF || token.getChannel() == channel {
return i
}
i -= 1
}
return i
}
/// Collect all tokens on specified channel to the right of
/// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or
/// EOF. If channel is -1, find any non default channel token.
public func getHiddenTokensToRight(_ tokenIndex: Int, _ channel: Int) throws -> Array<Token>? {
try lazyInit()
if tokenIndex < 0 || tokenIndex >= tokens.count {
throw ANTLRError.indexOutOfBounds(msg: "\(tokenIndex) not in 0..\(tokens.count - 1)")
}
let nextOnChannel: Int =
try nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL)
var to: Int
let from: Int = tokenIndex + 1
// if none onchannel to right, nextOnChannel=-1 so set to = last token
if nextOnChannel == -1 {
to = size() - 1
} else {
to = nextOnChannel
}
return filterForChannel(from, to, channel)
}
/// Collect all hidden tokens (any off-default channel) to the right of
/// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL
/// or EOF.
public func getHiddenTokensToRight(_ tokenIndex: Int) throws -> Array<Token>? {
return try getHiddenTokensToRight(tokenIndex, -1)
}
/// Collect all tokens on specified channel to the left of
/// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.
/// If channel is -1, find any non default channel token.
public func getHiddenTokensToLeft(_ tokenIndex: Int, _ channel: Int) throws -> Array<Token>? {
try lazyInit()
if tokenIndex < 0 || tokenIndex >= tokens.count {
throw ANTLRError.indexOutOfBounds(msg: "\(tokenIndex) not in 0..\(tokens.count - 1)")
//RuntimeException("\(tokenIndex) not in 0..\(tokens.count-1)")
//throw ANTLRError.IndexOutOfBounds /* throw IndexOutOfBoundsException(tokenIndex+" not in 0.."+(tokens.count-1)); */
}
if tokenIndex == 0 {
// obviously no tokens can appear before the first token
return nil
}
let prevOnChannel: Int =
try previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL)
if prevOnChannel == tokenIndex - 1 {
return nil
}
// if none onchannel to left, prevOnChannel=-1 then from=0
let from: Int = prevOnChannel + 1
let to: Int = tokenIndex - 1
return filterForChannel(from, to, channel)
}
/// Collect all hidden tokens (any off-default channel) to the left of
/// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.
public func getHiddenTokensToLeft(_ tokenIndex: Int) throws -> Array<Token>? {
return try getHiddenTokensToLeft(tokenIndex, -1)
}
internal func filterForChannel(_ from: Int, _ to: Int, _ channel: Int) -> Array<Token>? {
var hidden: Array<Token> = Array<Token>()
for i in from...to {
let t: Token = tokens[i]
if channel == -1 {
if t.getChannel() != Lexer.DEFAULT_TOKEN_CHANNEL {
hidden.append(t)
}
} else {
if t.getChannel() == channel {
hidden.append(t)
}
}
}
if hidden.count == 0 {
return nil
}
return hidden
}
public func getSourceName() -> String {
return tokenSource.getSourceName()
}
/// Get the text of all tokens in this buffer.
public func getText() throws -> String {
return try getText(Interval.of(0, size() - 1))
}
public func getText(_ interval: Interval) throws -> String {
let start: Int = interval.a
var stop: Int = interval.b
if start < 0 || stop < 0 {
return ""
}
try fill()
if stop >= tokens.count {
stop = tokens.count - 1
}
let buf: StringBuilder = StringBuilder()
for i in start...stop {
let t: Token = tokens[i]
if t.getType() == BufferedTokenStream.EOF {
break
}
buf.append(t.getText()!)
}
return buf.toString()
}
public func getText(_ ctx: RuleContext) throws -> String {
return try getText(ctx.getSourceInterval())
}
public func getText(_ start: Token?, _ stop: Token?) throws -> String {
if let start = start, let stop = stop {
return try getText(Interval.of(start.getTokenIndex(), stop.getTokenIndex()))
}
return ""
}
/// Get all tokens from lexer until EOF
public func fill() throws {
try lazyInit()
let blockSize: Int = 1000
while true {
let fetched: Int = try fetch(blockSize)
if fetched < blockSize {
return
}
}
}
}
| 4e0ac8aa07a8c7b4ebae71ca31b726c9 | 31.005952 | 129 | 0.560598 | false | false | false | false |
Zewo/Zewo | refs/heads/master | Sources/Media/MediaType/MediaType.swift | mit | 1 | import Foundation
enum MediaTypeError : Error {
case malformedMediaTypeString
}
public struct MediaType {
public let type: String
public let subtype: String
public let parameters: [String: String]
public init(type: String, subtype: String, parameters: [String: String] = [:]) {
self.type = type
self.subtype = subtype
self.parameters = parameters
}
public init(string: String) throws {
let mediaTypeTokens = string.components(separatedBy: ";")
guard let mediaType = mediaTypeTokens.first else {
throw MediaTypeError.malformedMediaTypeString
}
var parameters: [String: String] = [:]
if mediaTypeTokens.count == 2 {
let parametersTokens = mediaTypeTokens[1].trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ")
for parametersToken in parametersTokens {
let parameterTokens = parametersToken.components(separatedBy: "=")
if parameterTokens.count == 2 {
let key = parameterTokens[0]
let value = parameterTokens[1]
parameters[key] = value
}
}
}
let tokens = mediaType.components(separatedBy: "/")
guard tokens.count == 2 else {
throw MediaTypeError.malformedMediaTypeString
}
self.init(
type: tokens[0].lowercased(),
subtype: tokens[1].lowercased(),
parameters: parameters
)
}
public static func parse(acceptHeader: String) -> [MediaType] {
var acceptedMediaTypes: [MediaType] = []
let acceptedTypesString = acceptHeader.components(separatedBy: ",")
for acceptedTypeString in acceptedTypesString {
let acceptedTypeTokens = acceptedTypeString.components(separatedBy: ";")
if acceptedTypeTokens.count >= 1 {
let mediaTypeString = acceptedTypeTokens[0].trimmingCharacters(in: .whitespacesAndNewlines)
if let acceptedMediaType = try? MediaType(string: mediaTypeString) {
acceptedMediaTypes.append(acceptedMediaType)
}
}
}
return acceptedMediaTypes
}
public func matches(other mediaType: MediaType) -> Bool {
if type == "*" || mediaType.type == "*" {
return true
}
if type == mediaType.type {
if subtype == "*" || mediaType.subtype == "*" {
return true
}
return subtype == mediaType.subtype
}
return false
}
/// Returns `true` if the media type matches any of the media types
/// in the `mediaTypes` collection.
///
/// - Parameter mediaTypes: Collection of media types.
/// - Returns: Boolean indicating if the media type matches any of the
/// media types in the collection.
public func matches<C : Collection>(
any mediaTypes: C
) -> Bool where C.Iterator.Element == MediaType {
for mediaType in mediaTypes {
if matches(other: mediaType) {
return true
}
}
return false
}
/// Creates a `MediaType` from a file extension, if possible.
///
/// - Parameter fileExtension: File extension (ie., "txt", "json", "html").
/// - Returns: Newly created `MediaType`.
public static func from(fileExtension: String) -> MediaType? {
guard let mediaType = fileExtensionMediaTypeMapping[fileExtension] else {
return nil
}
return try? MediaType(string: mediaType)
}
}
extension MediaType : CustomStringConvertible {
/// :nodoc:
public var description: String {
var string = "\(type)/\(subtype)"
if !parameters.isEmpty {
string += parameters.reduce(";") { $0 + " \($1.0)=\($1.1)" }
}
return string
}
}
extension MediaType : Hashable {
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(type)
hasher.combine(subtype)
}
}
extension MediaType : Equatable {
/// :nodoc:
public static func == (lhs: MediaType, rhs: MediaType) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
public extension MediaType {
/// Any media type (*/*).
static let any = MediaType(type: "*", subtype: "*")
/// Plain text media type.
static let plainText = MediaType(type: "text", subtype: "plain", parameters: ["charset": "utf-8"])
/// HTML media type.
static let html = MediaType(type: "text", subtype: "html", parameters: ["charset": "utf-8"])
/// CSS media type.
static let css = MediaType(type: "text", subtype: "css", parameters: ["charset": "utf-8"])
/// URL encoded form media type.
static let urlEncodedForm = MediaType(type: "application", subtype: "x-www-form-urlencoded", parameters: ["charset": "utf-8"])
/// JSON media type.
static let json = MediaType(type: "application", subtype: "json", parameters: ["charset": "utf-8"])
/// XML media type.
static let xml = MediaType(type: "application", subtype: "xml", parameters: ["charset": "utf-8"])
/// DTD media type.
static let dtd = MediaType(type: "application", subtype: "xml-dtd", parameters: ["charset": "utf-8"])
/// PDF data.
static let pdf = MediaType(type: "application", subtype: "pdf")
/// Zip file.
static let zip = MediaType(type: "application", subtype: "zip")
/// tar file.
static let tar = MediaType(type: "application", subtype: "x-tar")
/// Gzip file.
static let gzip = MediaType(type: "application", subtype: "x-gzip")
/// Bzip2 file.
static let bzip2 = MediaType(type: "application", subtype: "x-bzip2")
/// Binary data.
static let binary = MediaType(type: "application", subtype: "octet-stream")
/// GIF image.
static let gif = MediaType(type: "image", subtype: "gif")
/// JPEG image.
static let jpeg = MediaType(type: "image", subtype: "jpeg")
/// PNG image.
static let png = MediaType(type: "image", subtype: "png")
/// SVG image.
static let svg = MediaType(type: "image", subtype: "svg+xml")
/// Basic audio.
static let audio = MediaType(type: "audio", subtype: "basic")
/// MIDI audio.
static let midi = MediaType(type: "audio", subtype: "x-midi")
/// MP3 audio.
static let mp3 = MediaType(type: "audio", subtype: "mpeg")
/// Wave audio.
static let wave = MediaType(type: "audio", subtype: "wav")
/// OGG audio.
static let ogg = MediaType(type: "audio", subtype: "vorbis")
/// AVI video.
static let avi = MediaType(type: "video", subtype: "avi")
/// MPEG video.
static let mpeg = MediaType(type: "video", subtype: "mpeg")
}
let fileExtensionMediaTypeMapping: [String: String] = [
"ez": "application/andrew-inset",
"anx": "application/annodex",
"atom": "application/atom+xml",
"atomcat": "application/atomcat+xml",
"atomsrv": "application/atomserv+xml",
"lin": "application/bbolin",
"cu": "application/cu-seeme",
"davmount": "application/davmount+xml",
"dcm": "application/dicom",
"tsp": "application/dsptype",
"es": "application/ecmascript",
"spl": "application/futuresplash",
"hta": "application/hta",
"jar": "application/java-archive",
"ser": "application/java-serialized-object",
"class": "application/java-vm",
"js": "application/javascript",
"json": "application/json",
"m3g": "application/m3g",
"hqx": "application/mac-binhex40",
"cpt": "application/mac-compactpro",
"nb": "application/mathematica",
"nbp": "application/mathematica",
"mbox": "application/mbox",
"mdb": "application/msaccess",
"doc": "application/msword",
"dot": "application/msword",
"mxf": "application/mxf",
"bin": "application/octet-stream",
"oda": "application/oda",
"ogx": "application/ogg",
"one": "application/onenote",
"onetoc2": "application/onenote",
"onetmp": "application/onenote",
"onepkg": "application/onenote",
"pdf": "application/pdf",
"pgp": "application/pgp-encrypted",
"key": "application/pgp-keys",
"sig": "application/pgp-signature",
"prf": "application/pics-rules",
"ps": "application/postscript",
"ai": "application/postscript",
"eps": "application/postscript",
"epsi": "application/postscript",
"epsf": "application/postscript",
"eps2": "application/postscript",
"eps3": "application/postscript",
"rar": "application/rar",
"rdf": "application/rdf+xml",
"rtf": "application/rtf",
"stl": "application/sla",
"smi": "application/smil+xml",
"smil": "application/smil+xml",
"xhtml": "application/xhtml+xml",
"xht": "application/xhtml+xml",
"xml": "application/xml",
"xsd": "application/xml",
"xsl": "application/xslt+xml",
"xslt": "application/xslt+xml",
"xspf": "application/xspf+xml",
"zip": "application/zip",
"apk": "application/vnd.android.package-archive",
"cdy": "application/vnd.cinderella",
"kml": "application/vnd.google-earth.kml+xml",
"kmz": "application/vnd.google-earth.kmz",
"xul": "application/vnd.mozilla.xul+xml",
"xls": "application/vnd.ms-excel",
"xlb": "application/vnd.ms-excel",
"xlt": "application/vnd.ms-excel",
"xlam": "application/vnd.ms-excel.addin.macroEnabled.12",
"xlsb": "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
"xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12",
"xltm": "application/vnd.ms-excel.template.macroEnabled.12",
"eot": "application/vnd.ms-fontobject",
"thmx": "application/vnd.ms-officetheme",
"cat": "application/vnd.ms-pki.seccat",
"ppt": "application/vnd.ms-powerpoint",
"pps": "application/vnd.ms-powerpoint",
"ppam": "application/vnd.ms-powerpoint.addin.macroEnabled.12",
"pptm": "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
"sldm": "application/vnd.ms-powerpoint.slide.macroEnabled.12",
"ppsm": "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
"potm": "application/vnd.ms-powerpoint.template.macroEnabled.12",
"docm": "application/vnd.ms-word.document.macroEnabled.12",
"dotm": "application/vnd.ms-word.template.macroEnabled.12",
"odc": "application/vnd.oasis.opendocument.chart",
"odb": "application/vnd.oasis.opendocument.database",
"odf": "application/vnd.oasis.opendocument.formula",
"odg": "application/vnd.oasis.opendocument.graphics",
"otg": "application/vnd.oasis.opendocument.graphics-template",
"odi": "application/vnd.oasis.opendocument.image",
"odp": "application/vnd.oasis.opendocument.presentation",
"otp": "application/vnd.oasis.opendocument.presentation-template",
"ods": "application/vnd.oasis.opendocument.spreadsheet",
"ots": "application/vnd.oasis.opendocument.spreadsheet-template",
"odt": "application/vnd.oasis.opendocument.text",
"odm": "application/vnd.oasis.opendocument.text-master",
"ott": "application/vnd.oasis.opendocument.text-template",
"oth": "application/vnd.oasis.opendocument.text-web",
"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide",
"ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
"potx": "application/vnd.openxmlformats-officedocument.presentationml.template",
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
"cod": "application/vnd.rim.cod",
"mmf": "application/vnd.smaf",
"sdc": "application/vnd.stardivision.calc",
"sds": "application/vnd.stardivision.chart",
"sda": "application/vnd.stardivision.draw",
"sdd": "application/vnd.stardivision.impress",
"sdf": "application/vnd.stardivision.math",
"sdw": "application/vnd.stardivision.writer",
"sgl": "application/vnd.stardivision.writer-global",
"sxc": "application/vnd.sun.xml.calc",
"stc": "application/vnd.sun.xml.calc.template",
"sxd": "application/vnd.sun.xml.draw",
"std": "application/vnd.sun.xml.draw.template",
"sxi": "application/vnd.sun.xml.impress",
"sti": "application/vnd.sun.xml.impress.template",
"sxm": "application/vnd.sun.xml.math",
"sxw": "application/vnd.sun.xml.writer",
"sxg": "application/vnd.sun.xml.writer.global",
"stw": "application/vnd.sun.xml.writer.template",
"sis": "application/vnd.symbian.install",
"cap": "application/vnd.tcpdump.pcap",
"pcap": "application/vnd.tcpdump.pcap",
"vsd": "application/vnd.visio",
"wbxml": "application/vnd.wap.wbxml",
"wmlc": "application/vnd.wap.wmlc",
"wmlsc": "application/vnd.wap.wmlscriptc",
"wpd": "application/vnd.wordperfect",
"wp5": "application/vnd.wordperfect5.1",
"wk": "application/x-123",
"7z": "application/x-7z-compressed",
"abw": "application/x-abiword",
"dmg": "application/x-apple-diskimage",
"bcpio": "application/x-bcpio",
"torrent": "application/x-bittorrent",
"cab": "application/x-cab",
"cbr": "application/x-cbr",
"cbz": "application/x-cbz",
"cdf": "application/x-cdf",
"cda": "application/x-cdf",
"vcd": "application/x-cdlink",
"pgn": "application/x-chess-pgn",
"mph": "application/x-comsol",
"cpio": "application/x-cpio",
"csh": "application/x-csh",
"deb": "application/x-debian-package",
"udeb": "application/x-debian-package",
"dcr": "application/x-director",
"dir": "application/x-director",
"dxr": "application/x-director",
"dms": "application/x-dms",
"wad": "application/x-doom",
"dvi": "application/x-dvi",
"pfa": "application/x-font",
"pfb": "application/x-font",
"gsf": "application/x-font",
"pcf": "application/x-font",
"pcf.Z": "application/x-font",
"woff": "application/x-font-woff",
"mm": "application/x-freemind",
"gan": "application/x-ganttproject",
"gnumeric": "application/x-gnumeric",
"sgf": "application/x-go-sgf",
"gcf": "application/x-graphing-calculator",
"gtar": "application/x-gtar",
"tgz": "application/x-gtar-compressed",
"taz": "application/x-gtar-compressed",
"hdf": "application/x-hdf",
"hwp": "application/x-hwp",
"ica": "application/x-ica",
"info": "application/x-info",
"ins": "application/x-internet-signup",
"isp": "application/x-internet-signup",
"iii": "application/x-iphone",
"iso": "application/x-iso9660-image",
"jam": "application/x-jam",
"jnlp": "application/x-java-jnlp-file",
"jmz": "application/x-jmol",
"chrt": "application/x-kchart",
"kil": "application/x-killustrator",
"skp": "application/x-koan",
"skd": "application/x-koan",
"skt": "application/x-koan",
"skm": "application/x-koan",
"kpr": "application/x-kpresenter",
"kpt": "application/x-kpresenter",
"ksp": "application/x-kspread",
"kwd": "application/x-kword",
"kwt": "application/x-kword",
"latex": "application/x-latex",
"lha": "application/x-lha",
"lyx": "application/x-lyx",
"lzh": "application/x-lzh",
"lzx": "application/x-lzx",
"frm": "application/x-maker",
"maker": "application/x-maker",
"frame": "application/x-maker",
"fm": "application/x-maker",
"fb": "application/x-maker",
"book": "application/x-maker",
"fbdoc": "application/x-maker",
"md5": "application/x-md5",
"mif": "application/x-mif",
"m3u8": "application/x-mpegURL",
"wmd": "application/x-ms-wmd",
"wmz": "application/x-ms-wmz",
"com": "application/x-msdos-program",
"exe": "application/x-msdos-program",
"bat": "application/x-msdos-program",
"dll": "application/x-msdos-program",
"msi": "application/x-msi",
"nc": "application/x-netcdf",
"pac": "application/x-ns-proxy-autoconfig",
"dat": "application/x-ns-proxy-autoconfig",
"nwc": "application/x-nwc",
"o": "application/x-object",
"oza": "application/x-oz-application",
"p7r": "application/x-pkcs7-certreqresp",
"crl": "application/x-pkcs7-crl",
"pyc": "application/x-python-code",
"pyo": "application/x-python-code",
"qgs": "application/x-qgis",
"shp": "application/x-qgis",
"shx": "application/x-qgis",
"qtl": "application/x-quicktimeplayer",
"rdp": "application/x-rdp",
"rpm": "application/x-redhat-package-manager",
"rss": "application/x-rss+xml",
"rb": "application/x-ruby",
"sci": "application/x-scilab",
"sce": "application/x-scilab",
"xcos": "application/x-scilab-xcos",
"sh": "application/x-sh",
"sha1": "application/x-sha1",
"shar": "application/x-shar",
"swf": "application/x-shockwave-flash",
"swfl": "application/x-shockwave-flash",
"scr": "application/x-silverlight",
"sql": "application/x-sql",
"sit": "application/x-stuffit",
"sitx": "application/x-stuffit",
"sv4cpio": "application/x-sv4cpio",
"sv4crc": "application/x-sv4crc",
"tar": "application/x-tar",
"tcl": "application/x-tcl",
"gf": "application/x-tex-gf",
"pk": "application/x-tex-pk",
"texinfo": "application/x-texinfo",
"texi": "application/x-texinfo",
"~": "application/x-trash",
"%": "application/x-trash",
"bak": "application/x-trash",
"old": "application/x-trash",
"sik": "application/x-trash",
"t": "application/x-troff",
"tr": "application/x-troff",
"roff": "application/x-troff",
"man": "application/x-troff-man",
"me": "application/x-troff-me",
"ms": "application/x-troff-ms",
"ustar": "application/x-ustar",
"src": "application/x-wais-source",
"wz": "application/x-wingz",
"crt": "application/x-x509-ca-cert",
"xcf": "application/x-xcf",
"fig": "application/x-xfig",
"xpi": "application/x-xpinstall",
"amr": "audio/amr",
"awb": "audio/amr-wb",
"axa": "audio/annodex",
"au": "audio/basic",
"snd": "audio/basic",
"csd": "audio/csound",
"orc": "audio/csound",
"sco": "audio/csound",
"flac": "audio/flac",
"mid": "audio/midi",
"midi": "audio/midi",
"kar": "audio/midi",
"mpga": "audio/mpeg",
"mpega": "audio/mpeg",
"mp2": "audio/mpeg",
"mp3": "audio/mpeg",
"m4a": "audio/mpeg",
"m3u": "audio/mpegurl",
"oga": "audio/ogg",
"ogg": "audio/ogg",
"opus": "audio/ogg",
"spx": "audio/ogg",
"sid": "audio/prs.sid",
"aif": "audio/x-aiff",
"aiff": "audio/x-aiff",
"aifc": "audio/x-aiff",
"gsm": "audio/x-gsm",
"wma": "audio/x-ms-wma",
"wax": "audio/x-ms-wax",
"ra": "audio/x-pn-realaudio",
"rm": "audio/x-pn-realaudio",
"ram": "audio/x-pn-realaudio",
"pls": "audio/x-scpls",
"sd2": "audio/x-sd2",
"wav": "audio/x-wav",
"alc": "chemical/x-alchemy",
"cac": "chemical/x-cache",
"cache": "chemical/x-cache",
"csf": "chemical/x-cache-csf",
"cbin": "chemical/x-cactvs-binary",
"cascii": "chemical/x-cactvs-binary",
"ctab": "chemical/x-cactvs-binary",
"cdx": "chemical/x-cdx",
"cer": "chemical/x-cerius",
"c3d": "chemical/x-chem3d",
"chm": "chemical/x-chemdraw",
"cif": "chemical/x-cif",
"cmdf": "chemical/x-cmdf",
"cml": "chemical/x-cml",
"cpa": "chemical/x-compass",
"bsd": "chemical/x-crossfire",
"csml": "chemical/x-csml",
"csm": "chemical/x-csml",
"ctx": "chemical/x-ctx",
"cxf": "chemical/x-cxf",
"cef": "chemical/x-cxf",
"emb": "chemical/x-embl-dl-nucleotide",
"embl": "chemical/x-embl-dl-nucleotide",
"spc": "chemical/x-galactic-spc",
"inp": "chemical/x-gamess-input",
"gam": "chemical/x-gamess-input",
"gamin": "chemical/x-gamess-input",
"fch": "chemical/x-gaussian-checkpoint",
"fchk": "chemical/x-gaussian-checkpoint",
"cub": "chemical/x-gaussian-cube",
"gau": "chemical/x-gaussian-input",
"gjc": "chemical/x-gaussian-input",
"gjf": "chemical/x-gaussian-input",
"gal": "chemical/x-gaussian-log",
"gcg": "chemical/x-gcg8-sequence",
"gen": "chemical/x-genbank",
"hin": "chemical/x-hin",
"istr": "chemical/x-isostar",
"ist": "chemical/x-isostar",
"jdx": "chemical/x-jcamp-dx",
"dx": "chemical/x-jcamp-dx",
"kin": "chemical/x-kinemage",
"mcm": "chemical/x-macmolecule",
"mmd": "chemical/x-macromodel-input",
"mmod": "chemical/x-macromodel-input",
"mol": "chemical/x-mdl-molfile",
"rd": "chemical/x-mdl-rdfile",
"rxn": "chemical/x-mdl-rxnfile",
"sd": "chemical/x-mdl-sdfile",
"tgf": "chemical/x-mdl-tgf",
"mcif": "chemical/x-mmcif",
"mol2": "chemical/x-mol2",
"b": "chemical/x-molconn-Z",
"gpt": "chemical/x-mopac-graph",
"mop": "chemical/x-mopac-input",
"mopcrt": "chemical/x-mopac-input",
"mpc": "chemical/x-mopac-input",
"zmt": "chemical/x-mopac-input",
"moo": "chemical/x-mopac-out",
"mvb": "chemical/x-mopac-vib",
"asn": "chemical/x-ncbi-asn1",
"prt": "chemical/x-ncbi-asn1-ascii",
"ent": "chemical/x-ncbi-asn1-ascii",
"val": "chemical/x-ncbi-asn1-binary",
"aso": "chemical/x-ncbi-asn1-binary",
"pdb": "chemical/x-pdb",
"ros": "chemical/x-rosdal",
"sw": "chemical/x-swissprot",
"vms": "chemical/x-vamas-iso14976",
"vmd": "chemical/x-vmd",
"xtel": "chemical/x-xtel",
"xyz": "chemical/x-xyz",
"gif": "image/gif",
"ief": "image/ief",
"jp2": "image/jp2",
"jpg2": "image/jp2",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"jpe": "image/jpeg",
"jpm": "image/jpm",
"jpx": "image/jpx",
"jpf": "image/jpx",
"pcx": "image/pcx",
"png": "image/png",
"svg": "image/svg+xml",
"svgz": "image/svg+xml",
"tiff": "image/tiff",
"tif": "image/tiff",
"djvu": "image/vnd.djvu",
"djv": "image/vnd.djvu",
"ico": "image/vnd.microsoft.icon",
"wbmp": "image/vnd.wap.wbmp",
"cr2": "image/x-canon-cr2",
"crw": "image/x-canon-crw",
"ras": "image/x-cmu-raster",
"cdr": "image/x-coreldraw",
"pat": "image/x-coreldrawpattern",
"cdt": "image/x-coreldrawtemplate",
"erf": "image/x-epson-erf",
"art": "image/x-jg",
"jng": "image/x-jng",
"bmp": "image/x-ms-bmp",
"nef": "image/x-nikon-nef",
"orf": "image/x-olympus-orf",
"psd": "image/x-photoshop",
"pnm": "image/x-portable-anymap",
"pbm": "image/x-portable-bitmap",
"pgm": "image/x-portable-graymap",
"ppm": "image/x-portable-pixmap",
"rgb": "image/x-rgb",
"xbm": "image/x-xbitmap",
"xpm": "image/x-xpixmap",
"xwd": "image/x-xwindowdump",
"eml": "message/rfc822",
"igs": "model/iges",
"iges": "model/iges",
"msh": "model/mesh",
"mesh": "model/mesh",
"silo": "model/mesh",
"wrl": "model/vrml",
"vrml": "model/vrml",
"x3dv": "model/x3d+vrml",
"x3d": "model/x3d+xml",
"x3db": "model/x3d+binary",
"appcache": "text/cache-manifest",
"ics": "text/calendar",
"icz": "text/calendar",
"css": "text/css",
"csv": "text/csv",
"323": "text/h323",
"html": "text/html",
"htm": "text/html",
"shtml": "text/html",
"uls": "text/iuls",
"mml": "text/mathml",
"asc": "text/plain",
"txt": "text/plain",
"text": "text/plain",
"pot": "text/plain",
"brf": "text/plain",
"srt": "text/plain",
"rtx": "text/richtext",
"sct": "text/scriptlet",
"wsc": "text/scriptlet",
"tm": "text/texmacs",
"tsv": "text/tab-separated-values",
"ttl": "text/turtle",
"jad": "text/vnd.sun.j2me.app-descriptor",
"wml": "text/vnd.wap.wml",
"wmls": "text/vnd.wap.wmlscript",
"bib": "text/x-bibtex",
"boo": "text/x-boo",
"h++": "text/x-c++hdr",
"hpp": "text/x-c++hdr",
"hxx": "text/x-c++hdr",
"hh": "text/x-c++hdr",
"c++": "text/x-c++src",
"cpp": "text/x-c++src",
"cxx": "text/x-c++src",
"cc": "text/x-c++src",
"h": "text/x-chdr",
"htc": "text/x-component",
"c": "text/x-csrc",
"d": "text/x-dsrc",
"diff": "text/x-diff",
"patch": "text/x-diff",
"hs": "text/x-haskell",
"java": "text/x-java",
"ly": "text/x-lilypond",
"lhs": "text/x-literate-haskell",
"moc": "text/x-moc",
"p": "text/x-pascal",
"pas": "text/x-pascal",
"gcd": "text/x-pcs-gcd",
"pl": "text/x-perl",
"pm": "text/x-perl",
"py": "text/x-python",
"scala": "text/x-scala",
"etx": "text/x-setext",
"sfv": "text/x-sfv",
"tk": "text/x-tcl",
"tex": "text/x-tex",
"ltx": "text/x-tex",
"sty": "text/x-tex",
"cls": "text/x-tex",
"vcs": "text/x-vcalendar",
"vcf": "text/x-vcard",
"3gp": "video/3gpp",
"axv": "video/annodex",
"dl": "video/dl",
"dif": "video/dv",
"dv": "video/dv",
"fli": "video/fli",
"gl": "video/gl",
"mpeg": "video/mpeg",
"mpg": "video/mpeg",
"mpe": "video/mpeg",
"ts": "video/MP2T",
"mp4": "video/mp4",
"qt": "video/quicktime",
"mov": "video/quicktime",
"ogv": "video/ogg",
"webm": "video/webm",
"mxu": "video/vnd.mpegurl",
"flv": "video/x-flv",
"lsf": "video/x-la-asf",
"lsx": "video/x-la-asf",
"mng": "video/x-mng",
"asf": "video/x-ms-asf",
"asx": "video/x-ms-asf",
"wm": "video/x-ms-wm",
"wmv": "video/x-ms-wmv",
"wmx": "video/x-ms-wmx",
"wvx": "video/x-ms-wvx",
"avi": "video/x-msvideo",
"movie": "video/x-sgi-movie",
"mpv": "video/x-matroska",
"mkv": "video/x-matroska",
"ice": "x-conference/x-cooltalk",
"sisx": "x-epoc/x-sisx-app",
"vrm": "x-world/x-vrml",
]
| 0344d2faf68d64bc41b904d75b56fe80 | 32.336971 | 130 | 0.636438 | false | false | false | false |
ghotjunwoo/Tiat | refs/heads/master | CreateViewController.swift | gpl-3.0 | 1 | //
// CreateViewController.swift
// Tiat
//
// Created by 이종승 on 2016. 8. 3..
// Copyright © 2016년 JW. All rights reserved.
//
import UIKit
import Firebase
import FirebaseStorage
import MobileCoreServices
class CreateViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var nameField: UITextField!
@IBOutlet var emailField: UITextField!
@IBOutlet var passwordField: UITextField!
@IBOutlet var profileImageView: UIImageView!
@IBOutlet var registerButton: UIButton!
//MARK: Declaration
let okAction = UIAlertAction(title: "확인", style: UIAlertActionStyle.default){(ACTION) in
print("B_T")}
let userRef = FIRDatabase.database().reference().child("users")
let user = FIRAuth.auth()?.currentUser
let imagePicker = UIImagePickerController()
let storageRef = FIRStorage.storage().reference(forURL: "gs://tiat-ea6fd.appspot.com")
var userNum = 0
var gender = "남"
var image:UIImage = UIImage(named: "status_green")!
var metadata = FIRStorageMetadata()
func create() {
FIRAuth.auth()?.createUser(withEmail: emailField.text!, password: passwordField.text!, completion: {
user, error in
if error != nil {
let duplAlert = UIAlertController(title: "실패", message: "오류가 발생했습니다", preferredStyle: UIAlertControllerStyle.alert);
print(error?.localizedDescription)
duplAlert.addAction(self.okAction);
self.present(duplAlert, animated: true, completion: nil)
} else {
let profileImageRef = self.storageRef.child("users/\(user!.uid)/profileimage")
self.metadata.contentType = "image/jpeg"
let newImage = UIImageJPEGRepresentation(self.profileImageView.image!, 3.0)
profileImageRef.put(newImage!, metadata: self.metadata) { metadata, error in
if error != nil {
}
}
self.userRef.child("\(user!.uid)/name").setValue(self.nameField.text! as String)
self.userRef.child("\(user!.uid)/point").setValue(0)
self.registerButton.isEnabled = false
}})
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.dismiss(animated: true, completion: nil)
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
profileImageView.image = image
}
override func viewDidLoad() {
super.viewDidLoad()
nameField.delegate = self
emailField.delegate = self
passwordField.delegate = self
imagePicker.delegate = self
userRef.child("usernum").observe(.value) { (snap: FIRDataSnapshot) in
self.userNum = snap.value as! Int
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func nextKeyPressed(_ sender: AnyObject) {
emailField.becomeFirstResponder()
}
@IBAction func emailNextKeyPressed(_ sender: AnyObject) {
passwordField.becomeFirstResponder()
}
@IBAction func passwordNextKeyPressed(_ sender: AnyObject) {
create()
performSegue(withIdentifier: "toMainScreen_2", sender: self)
}
@IBAction func registerButtonTapped(_ sender: AnyObject) {
create()
performSegue(withIdentifier: "toMainScreen_2", sender: self)
}
@IBAction func selectProfilePhoto(_ sender: AnyObject) {
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
self.present(imagePicker, animated: true, completion: nil)
}
}
| dd256ed86770ed9d2436d31c64a6836a | 34.301724 | 132 | 0.63199 | false | false | false | false |
gnachman/iTerm2 | refs/heads/master | sources/Porthole.swift | gpl-2.0 | 2 | //
// Porthole.swift
// iTerm2SharedARC
//
// Created by George Nachman on 4/13/22.
//
import Foundation
@objc
protocol PortholeMarkReading: iTermMarkProtocol {
var uniqueIdentifier: String { get }
}
@objc
class PortholeMark: iTermMark, PortholeMarkReading {
private static let mutex = Mutex()
let uniqueIdentifier: String
private let uniqueIdentifierKey = "PortholeUniqueIdentifier"
override var description: String {
return "<PortholeMark: \(it_addressString) id=\(uniqueIdentifier) \(isDoppelganger ? "IsDop" : "NotDop")>"
}
@objc
init(_ uniqueIdentifier: String) {
self.uniqueIdentifier = uniqueIdentifier
super.init()
PortholeRegistry.instance.set(uniqueIdentifier, mark: doppelganger() as! PortholeMarkReading)
}
required init?(dictionary dict: [AnyHashable : Any]) {
guard let uniqueIdentifier = dict[uniqueIdentifierKey] as? String else {
return nil
}
self.uniqueIdentifier = uniqueIdentifier
super.init()
}
deinit {
if !isDoppelganger {
PortholeRegistry.instance.remove(uniqueIdentifier)
}
}
override func dictionaryValue() -> [AnyHashable : Any]! {
return [uniqueIdentifierKey: uniqueIdentifier].compactMapValues { $0 }
}
}
enum PortholeType: String {
case text = "Text"
static func unwrap(dictionary: [String: AnyObject]) -> (type: PortholeType, info: [String: AnyObject])? {
guard let typeString = dictionary[portholeType] as? String,
let type = PortholeType(rawValue: typeString),
let info = dictionary[portholeInfo] as? [String: AnyObject] else {
return nil
}
return (type: type, info: info)
}
}
struct PortholeConfig: CustomDebugStringConvertible {
var text: String
var colorMap: iTermColorMapReading
var baseDirectory: URL?
var font: NSFont
var type: String?
var filename: String?
var debugDescription: String {
"PortholeConfig(text=\(text) baseDirectory=\(String(describing: baseDirectory)) font=\(font) type=\(String(describing: type)) filename=\(String(describing: filename))"
}
}
protocol PortholeDelegate: AnyObject {
func portholeDidAcquireSelection(_ porthole: Porthole)
func portholeRemove(_ porthole: Porthole)
func portholeResize(_ porthole: Porthole)
func portholeAbsLine(_ porthole: Porthole) -> Int64
func portholeHeight(_ porthole: Porthole) -> Int32
}
@objc(Porthole)
protocol ObjCPorthole: AnyObject {
@objc var view: NSView { get }
@objc var uniqueIdentifier: String { get }
@objc var dictionaryValue: [String: AnyObject] { get }
@objc func desiredHeight(forWidth width: CGFloat) -> CGFloat // includes top and bottom margin
@objc func removeSelection()
@objc func updateColors()
@objc var savedLines: [ScreenCharArray] { get set }
// Inset the view by this amount top and bottom.
@objc var outerMargin: CGFloat { get }
}
enum PortholeCopyMode {
case plainText
case attributedString
case controlSequences
}
protocol Porthole: ObjCPorthole {
static var type: PortholeType { get }
var delegate: PortholeDelegate? { get set }
var config: PortholeConfig { get }
var hasSelection: Bool { get }
func copy(as: PortholeCopyMode)
var mark: PortholeMarkReading? { get }
func set(frame: NSRect)
func find(_ query: String, mode: iTermFindMode) -> [ExternalSearchResult]
func select(searchResult: ExternalSearchResult,
multiple: Bool,
returningRectRelativeTo view: NSView,
scroll: Bool) -> NSRect?
func snippet(for result: ExternalSearchResult,
matchAttributes: [NSAttributedString.Key: Any],
regularAttributes: [NSAttributedString.Key: Any]) -> NSAttributedString?
func removeHighlights()
}
fileprivate let portholeType = "Type"
fileprivate let portholeInfo = "Info"
extension Porthole {
func wrap(dictionary: [String: Any]) -> [String: AnyObject] {
return [portholeType: Self.type.rawValue as NSString,
portholeInfo: dictionary as NSDictionary]
}
}
@objc
class PortholeRegistry: NSObject {
@objc static var instance = PortholeRegistry()
private var portholes = [String: ObjCPorthole]()
private var pending = [String: NSDictionary]()
private var marks = [String: PortholeMarkReading]()
private var _generation: Int = 0
@objc var generation: Int {
get {
return mutex.sync { _generation }
}
set {
return mutex.sync { self._generation = newValue }
}
}
private let mutex = Mutex()
func add(_ porthole: ObjCPorthole) {
DLog("add \(porthole)")
mutex.sync {
portholes[porthole.uniqueIdentifier] = porthole
incrementGeneration()
}
}
func remove(_ key: String) {
DLog("remove \(key)")
mutex.sync {
_ = portholes.removeValue(forKey: key)
_ = marks.removeValue(forKey: key)
incrementGeneration()
}
}
@objc(registerKey:forMark:)
func set(_ key: String, mark: PortholeMarkReading) {
DLog("register mark \(mark) for \(key)")
mutex.sync {
marks[key] = mark
incrementGeneration()
}
}
@objc(markForKey:)
func mark(for key: String) -> PortholeMarkReading? {
return mutex.sync {
marks[key]
}
}
func get(_ key: String, colorMap: iTermColorMapReading, font: NSFont) -> ObjCPorthole? {
mutex.sync {
if let porthole = portholes[key] {
return porthole
}
guard let dict = pending[key] as? [String : AnyObject] else {
return nil
}
pending.removeValue(forKey: key)
DLog("hydrating \(key)")
guard let porthole = PortholeFactory.porthole(dict,
colorMap: colorMap,
font: font) else {
return nil
}
portholes[key] = porthole
incrementGeneration()
return porthole
}
}
@objc subscript(_ key: String) -> ObjCPorthole? {
return mutex.sync {
return portholes[key]
}
}
func incrementGeneration() {
_generation += 1
DispatchQueue.main.async {
NSApp.invalidateRestorableState()
}
}
private let portholesKey = "Portholes"
private let pendingKey = "Pending"
private let generationKey = "Generation"
@objc var dictionaryValue: [String: AnyObject] {
let dicts = portholes.mapValues { porthole in
porthole.dictionaryValue as NSDictionary
}
return [portholesKey: dicts as NSDictionary,
generationKey: NSNumber(value: _generation)]
}
@objc func load(_ dictionary: [String: AnyObject]) {
mutex.sync {
if let pending = dictionary[pendingKey] as? [String: NSDictionary],
let generation = dictionary[generationKey] as? Int,
let portholes = dictionary[portholesKey] as? [String: NSDictionary] {
self.pending = pending.merging(portholes) { lhs, _ in lhs }
self.generation = generation
}
}
}
// Note that marks are not restored. They go through the normal mark restoration process which
// as a side-effect adds them to the porthole registry.
@objc func encodeAsChild(with encoder: iTermGraphEncoder, key: String) {
mutex.sync {
_ = encoder.encodeChild(withKey: key,
identifier: "",
generation: _generation) { subencoder in
let keys = portholes.keys.sorted()
subencoder.encodeArray(withKey: "portholes",
generation: iTermGenerationAlwaysEncode,
identifiers: keys) { identifier, index, subencoder, stop in
let adapter = iTermGraphEncoderAdapter(graphEncoder: subencoder)
let key = keys[index]
adapter.merge(portholes[key]!.dictionaryValue)
return true
}
return true
}
}
}
@objc(decodeRecord:) func decode(record: iTermEncoderGraphRecord) {
mutex.sync {
record.enumerateArray(withKey: "portholes") { identifier, index, plist, stop in
guard let dict = plist as? NSDictionary else {
return
}
pending[identifier] = dict
}
}
}
}
| aff5239a13170d163485117470b1640b | 31.374545 | 175 | 0.598787 | false | false | false | false |
Alloc-Studio/Hypnos | refs/heads/master | Hypnos/Hypnos/Controller/Main/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// Hypnos
//
// Created by Fay on 16/5/18.
// Copyright © 2016年 DMT312. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import SDCycleScrollView
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
view.addSubview(scrollviewM)
scrollviewM.addSubview(search)
cycleScrollView.imageURLStringsGroup = [temp1,temp2,temp3,temp4]
scrollviewM.addSubview(cycleScrollView)
scrollviewM.addSubview(hot)
scrollviewM.addSubview(HotSelectedView.view)
scrollviewM.addSubview(newSongs)
scrollviewM.addSubview(musicSongs.view)
presentMusicItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBarHidden = false
tabBarController?.tabBar.hidden = false
}
func moreBtn() {
navigationController?.pushViewController(MoreArtistsViewController(), animated: true)
}
// 热门精选header
private lazy var hot:UIView = {
let hot = NSBundle.mainBundle().loadNibNamed("Header", owner: self, options: nil).last as! UIView
hot.frame = CGRectMake(0, CGRectGetMaxY(self.cycleScrollView.frame) + 10, SCREEN_WIDTH, 30)
for i in hot.subviews {
if i.isKindOfClass(UIButton.self) {
let btn = i as! UIButton
btn.addTarget(self, action: #selector(HomeViewController.moreBtn), forControlEvents: .TouchUpInside)
}
}
return hot
}()
// 新歌速递header
private lazy var newSongs:UIView = {
let new = NSBundle.mainBundle().loadNibNamed("Header", owner: self, options: nil).first as! UIView
new.frame = CGRectMake(0, CGRectGetMaxY(self.HotSelectedView.view.frame) + 10, SCREEN_WIDTH, 30)
return new
}()
// scrollview
private lazy var scrollviewM:UIScrollView = {
let sv = UIScrollView(frame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 44))
sv.contentSize = CGSizeMake(0, CGRectGetMaxY(self.musicSongs.view.frame))
sv.showsVerticalScrollIndicator = false
return sv
}()
// 新歌速递
private var musicSongs:MusicHallViewController {
let ms = MusicHallViewController()
ms.view.frame = CGRectMake(0, CGRectGetMaxY(self.newSongs.frame), SCREEN_WIDTH, 1190)
addChildViewController(ms)
return ms
}
// 热门精选
private var HotSelectedView:HotSelectedViewController {
let seletView = HotSelectedViewController()
seletView.view.frame = CGRectMake(0, CGRectGetMaxY(self.hot.frame) + 10, SCREEN_WIDTH, 300)
addChildViewController(seletView)
return seletView
}
// 搜索框
private lazy var search:SearchBar = {
let search = SearchBar(frame: CGRectMake(10, 10, SCREEN_WIDTH-20, 30))
return search
}()
// 轮播
private lazy var cycleScrollView:SDCycleScrollView = {
let cyv = SDCycleScrollView(frame: CGRectMake(10, CGRectGetMaxY(self.search.frame) + CGFloat(10), SCREEN_WIDTH-20, 170))
cyv.autoScrollTimeInterval = 5.0
cyv.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
cyv.showPageControl = true;
cyv.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
return cyv
}()
}
extension HomeViewController: MCItemPresentable{
func showMuicController() {
guard let _ = Player.sharedPlayer().musicModel else {
SweetAlert().showAlert("亲~", subTitle: "您还没有选择歌曲哦~~~", style: AlertStyle.CustomImag(imageFile: "recommend_cry"))
return
}
navigationController?.pushViewController(Player.sharedPlayer(), animated: true)
}
}
| 20efe26c68994aebfe6b49d80a84c376 | 31.04878 | 128 | 0.653222 | false | false | false | false |
Sephiroth87/scroll-phat-swift | refs/heads/master | Examples/Snake/main.swift | gpl-2.0 | 1 | //
// main.swift
// sroll-phat-swift
//
// Created by Fabio Ritrovato on 14/01/2016.
// Copyright (c) 2016 orange in a day. All rights reserved.
//
import Glibc
do {
let pHAT = try ScrollpHAT()
try pHAT.setBrightness(2)
var snake = [(x: 0, y: 0, dx: 1), (x: -1, y: 0, dx: 1), (x: -2, y: 0, dx: 1)]
for i in 0..<62 {
for point in snake {
pHAT.setPixel(x: point.x, y: point.y, value: true)
}
try pHAT.update()
usleep(50000)
pHAT.setPixel(x: snake[2].x, y: snake[2].y, value: false)
for (i, point) in snake.enumerated() {
var point = point
point.x += point.dx
if (point.x < 0 && point.dx == -1) || (point.x > 10 && point.dx == 1) {
point.y += 1
point.dx = -point.dx
}
snake[i] = point
}
}
} catch let e as SMBusError {
print(e)
}
| e1dfd5b012dd1f54b48745280a8dcf62 | 25.970588 | 83 | 0.487459 | false | false | false | false |
ospr/UIPlayground | refs/heads/master | UIPlaygroundElements/ThumbSliderView.swift | mit | 1 | //
// ThumbSliderView.swift
// UIPlayground
//
// Created by Kip Nicol on 8/7/16.
// Copyright © 2016 Kip Nicol. All rights reserved.
//
import UIKit
@IBDesignable
public class ThumbSliderView: UIControl {
@IBOutlet private weak var backgroundView: UIView!
@IBOutlet private weak var vibrancyBackgroundView: UIView!
@IBOutlet public private(set) weak var thumbView: UIImageView!
@IBOutlet private weak var informationalLabel: UILabel!
@IBOutlet private weak var backgroundInformationalLabel: UILabel!
@IBOutlet private weak var backgroundLeadingConstraint: NSLayoutConstraint!
@IBOutlet private weak var thumbViewTopPaddingConstraint: NSLayoutConstraint!
public var value: Double = 0 {
didSet {
let previousValue = min(1, max(0, oldValue))
guard previousValue != value else {
return
}
backgroundLeadingConstraint.constant = maxBackgroundLeadingConstraintConstant() * CGFloat(value)
sendActions(for: [.valueChanged])
updatePowerOffLabel()
}
}
@IBInspectable var thumbViewImage: UIImage? {
get { return thumbView.image }
set { thumbView.image = newValue }
}
@IBInspectable var informationalText: String? {
get { return informationalLabel.text }
set {
informationalLabel.text = newValue
backgroundInformationalLabel.text = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
let view = addOwnedViewFrom(nibNamed: String(describing: ThumbSliderView.self))
view.backgroundColor = .clear
setupThumbView()
setupInformationalLabel()
}
private func setupThumbView() {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(thumbViewWasPanned))
thumbView.addGestureRecognizer(panGesture)
panGesture.isEnabled = true
}
private func setupInformationalLabel() {
// Create a mask for the white informational label to glide through
// the label to create a shimmer effect
let shimmerMaskImage = UIImage(named: "ShimmerMask", in: Bundle(for: type(of: self)), compatibleWith: nil)!
let shimmerMaskLayer = CALayer()
let cgImage = shimmerMaskImage.cgImage!
shimmerMaskLayer.contents = cgImage
shimmerMaskLayer.contentsGravity = kCAGravityCenter
shimmerMaskLayer.frame.size = CGSize(width: cgImage.width, height: cgImage.height)
informationalLabel.layer.mask = shimmerMaskLayer
}
// MARK: - View Layout
override public func layoutSubviews() {
super.layoutSubviews()
vibrancyBackgroundView.layer.cornerRadius = vibrancyBackgroundView.bounds.size.height / 2.0
thumbView.roundCornersToFormCircle()
}
public override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
updateShimmerMaskLayerLayout()
}
func maxBackgroundLeadingConstraintConstant() -> CGFloat {
let thumbViewPadding = thumbViewTopPaddingConstraint.constant
return backgroundView.superview!.bounds.width - (thumbViewPadding * 2 + thumbView.frame.width)
}
func updateShimmerMaskLayerLayout() {
guard let shimmerMaskLayer = informationalLabel.layer.mask else {
return
}
// Start the mask just offscreen on the left side of the super layer and centered
shimmerMaskLayer.frame.origin = CGPoint(x: -shimmerMaskLayer.frame.width,
y: informationalLabel.layer.bounds.height / 2.0 - shimmerMaskLayer.bounds.height / 2.0)
// Create the horizontal animation to move the shimmer mask
let shimmerAnimation = CABasicAnimation(keyPath: "position.x")
shimmerAnimation.byValue = informationalLabel.bounds.width + shimmerMaskLayer.frame.width
shimmerAnimation.repeatCount = HUGE
shimmerAnimation.duration = 2.5
shimmerAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
shimmerMaskLayer.add(shimmerAnimation, forKey: "shimmerAnimation")
}
// MARK: - Working with slider value
func updateValue() {
let currentValue = max(0.0, min(1.0, Double(backgroundLeadingConstraint.constant / maxBackgroundLeadingConstraintConstant())))
if value != currentValue {
value = currentValue
sendActions(for: [.valueChanged])
}
}
func updatePowerOffLabel() {
// Hide the power off label when the slider is panned
let desiredPowerOffLabelAlpha: CGFloat = (value == 0) ? 1.0 : 0.0
if self.informationalLabel.alpha != desiredPowerOffLabelAlpha {
UIView.animate(withDuration: 0.10, animations: {
self.informationalLabel.alpha = desiredPowerOffLabelAlpha
self.backgroundInformationalLabel.alpha = desiredPowerOffLabelAlpha
})
}
}
// MARK: - Gesture Handling
func thumbViewWasPanned(_ recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .possible, .began:
break
case .changed:
// Update the leading constraint to move the slider to match
// the user's pan gesture
let translation = recognizer.translation(in: self)
backgroundLeadingConstraint.constant = max(translation.x, 0)
updateValue()
case .ended, .cancelled, .failed:
// Determine whether the user slid the slider far enough to
// either have the slider finish to the end position or slide
// back to the start position
let startValue = value
let shouldSlideToEnd = startValue > 0.5
let _ = DisplayLinkProgressor.run(withDuration: 0.10, update: { (progress) in
let finalValue = shouldSlideToEnd ? 1.0 : 0.0
let nextValue = startValue + progress * (finalValue - startValue)
self.value = nextValue
})
}
}
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
sendActions(for: [.touchDown])
}
}
| 4d852ca9c8cdb1073a1e0da062ad364f | 35.813187 | 135 | 0.635075 | false | false | false | false |
jdbateman/Lendivine | refs/heads/master | Lendivine/KivaUserAccount.swift | mit | 1 | //
// KivaUserAccount.swift
// OAuthSwift
//
// Created by john bateman on 10/29/15.
// Copyright © 2015 John Bateman. All rights reserved.
//
// This model object describes a user account on the Kiva service. There is currently no Kiva.org REST API support for transferring the user's profile image between the client and server in either direction.
import Foundation
class KivaUserAccount {
var firstName: String = ""
var lastName: String = ""
var lenderID: String = ""
var id: NSNumber = -1
var isPublic: Bool = false
var isDeveloper: Bool = false
// designated initializer
init(dictionary: [String: AnyObject]?) {
if let dictionary = dictionary {
if let fname = dictionary["first_name"] as? String {
firstName = fname
}
if let lname = dictionary["last_name"] as? String {
lastName = lname
}
if let liD = dictionary["lender_id"] as? String {
lenderID = liD
}
if let iD = dictionary["id"] as? NSNumber {
id = iD
}
if let isPub = dictionary["is_public"] as? Bool {
isPublic = isPub
}
if let dev = dictionary["is_developer"] as? Bool {
isDeveloper = dev
}
}
}
} | 793fb1ce4be451adb42a23c868e1e9f3 | 30.159091 | 208 | 0.555474 | false | false | false | false |
cconeil/Emojify | refs/heads/master | Emojify/Source/Typeahead.swift | mit | 1 | //
// Typeahead.swift
// Emojify
//
// Created by Chris O'Neil on 4/9/16.
// Copyright © 2016 Because. All rights reserved.
//
import Foundation
final class Typeahead {
private struct Constants {
private static let WordsKey = "words"
}
typealias StoreType = NSMutableDictionary
private let store = StoreType()
func words(startingWith key: String) -> [String] {
if let substore = substore(key: key) {
return wordsFromStore(store: substore)
} else {
return []
}
}
func words(matching key: String) -> [String] {
return substore(key: key)?[Constants.WordsKey] as? [String] ?? []
}
func add(word word: String, forKey key: String) {
var store = self.store
for character in key.characters {
let storeKey = String(character)
var substore = store[storeKey]
if substore == nil {
substore = StoreType()
store[storeKey] = substore
}
store = substore as! StoreType
}
if let words = store[Constants.WordsKey] as? NSMutableArray {
words.addObject(word)
} else {
store[Constants.WordsKey] = NSMutableArray(object: word)
}
}
func remove(word word: String, forKey key: String) {
var store = self.store
for character in key.characters {
let storeKey = String(character)
guard let substore = store[storeKey] else {
return
}
store = substore as! StoreType
}
if let words = store[Constants.WordsKey] as? NSMutableArray {
words.removeObject(word)
}
}
func removeAll() {
store.removeAllObjects()
}
private func wordsFromStore(store store: StoreType) -> [String] {
var allWords: [String] = []
for (key, value) in store {
if let words = value as? [String], let key = key as? String where key == Constants.WordsKey {
allWords += words
} else {
allWords += wordsFromStore(store: value as! StoreType)
}
}
return allWords
}
private func substore(key key: String) -> StoreType? {
var store = self.store
for character in key.characters {
let storeKey = String(character)
guard let substore = store[storeKey] as? StoreType else {
return nil
}
store = substore
}
return store
}
}
| 772fa651657d267ef11f954d4385f97c | 26.489362 | 105 | 0.549536 | false | false | false | false |
accatyyc/Buildasaur | refs/heads/master | Buildasaur/AppDelegate.swift | mit | 2 | //
// AppDelegate.swift
// Buildasaur
//
// Created by Honza Dvorsky on 12/12/2014.
// Copyright (c) 2014 Honza Dvorsky. All rights reserved.
//
import Cocoa
/*
Please report any crashes on GitHub, I may optionally ask you to email them to me. Thanks!
You can find them at ~/Library/Logs/DiagnosticReports/Buildasaur-*
Also, you can find the log at ~/Library/Application Support/Buildasaur/Builda.log
*/
import BuildaUtils
import XcodeServerSDK
import BuildaKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var syncerManager: SyncerManager!
let menuItemManager = MenuItemManager()
var storyboardLoader: StoryboardLoader!
var dashboardViewController: DashboardViewController?
var dashboardWindow: NSWindow?
var windows: Set<NSWindow> = []
func applicationDidFinishLaunching(aNotification: NSNotification) {
#if TESTING
print("Testing configuration, not launching the app")
#else
self.setup()
#endif
}
func setup() {
//uncomment when debugging autolayout
// let defs = NSUserDefaults.standardUserDefaults()
// defs.setBool(true, forKey: "NSConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints")
// defs.synchronize()
self.setupPersistence()
self.storyboardLoader = StoryboardLoader(storyboard: NSStoryboard.mainStoryboard)
self.storyboardLoader.delegate = self
self.menuItemManager.syncerManager = self.syncerManager
self.menuItemManager.setupMenuBarItem()
let dashboard = self.createInitialViewController()
self.dashboardViewController = dashboard
self.presentViewControllerInUniqueWindow(dashboard)
self.dashboardWindow = self.windowForPresentableViewControllerWithIdentifier("dashboard")!.0
}
func migratePersistence(persistence: Persistence) {
let fileManager = NSFileManager.defaultManager()
//before we create the storage manager, attempt migration first
let migrator = CompositeMigrator(persistence: persistence)
if migrator.isMigrationRequired() {
Log.info("Migration required, launching migrator")
do {
try migrator.attemptMigration()
} catch {
Log.error("Migration failed with error \(error), wiping folder...")
//wipe the persistence. start over if we failed to migrate
_ = try? fileManager.removeItemAtURL(persistence.readingFolder)
}
Log.info("Migration finished")
} else {
Log.verbose("No migration necessary, skipping...")
}
}
func setupPersistence() {
let persistence = PersistenceFactory.createStandardPersistence()
//setup logging
Logging.setup(persistence, alsoIntoFile: true)
//migration
self.migratePersistence(persistence)
//create storage manager
let storageManager = StorageManager(persistence: persistence)
let factory = SyncerFactory()
let loginItem = LoginItem()
let syncerManager = SyncerManager(storageManager: storageManager, factory: factory, loginItem: loginItem)
self.syncerManager = syncerManager
}
func createInitialViewController() -> DashboardViewController {
let dashboard: DashboardViewController = self.storyboardLoader
.presentableViewControllerWithStoryboardIdentifier("dashboardViewController", uniqueIdentifier: "dashboard", delegate: self)
dashboard.syncerManager = self.syncerManager
return dashboard
}
func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
self.showMainWindow()
return true
}
func applicationDidBecomeActive(notification: NSNotification) {
self.showMainWindow()
}
func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
let runningCount = self.syncerManager.syncers.filter({ $0.active }).count
if runningCount > 0 {
let confirm = "Are you sure you want to quit Buildasaur? This would stop \(runningCount) running syncers."
UIUtils.showAlertAskingConfirmation(confirm, dangerButton: "Quit") {
(quit) -> () in
NSApp.replyToApplicationShouldTerminate(quit)
}
return NSApplicationTerminateReply.TerminateLater
} else {
return NSApplicationTerminateReply.TerminateNow
}
}
func applicationWillTerminate(aNotification: NSNotification) {
//stop syncers properly
self.syncerManager.stopSyncers()
}
//MARK: Showing Window on Reactivation
func showMainWindow(){
NSApp.activateIgnoringOtherApps(true)
//first window. i wish there was a nicer way (please some tell me there is)
if NSApp.windows.count < 3 {
self.dashboardWindow?.makeKeyAndOrderFront(self)
}
}
}
extension AppDelegate: PresentableViewControllerDelegate {
func configureViewController(viewController: PresentableViewController) {
//
}
func presentViewControllerInUniqueWindow(viewController: PresentableViewController) {
//last chance to config
self.configureViewController(viewController)
//make sure we're the delegate
viewController.presentingDelegate = self
//check for an existing window
let identifier = viewController.uniqueIdentifier
var newWindow: NSWindow?
if let existingPair = self.windowForPresentableViewControllerWithIdentifier(identifier) {
newWindow = existingPair.0
} else {
newWindow = NSWindow(contentViewController: viewController)
newWindow?.autorecalculatesKeyViewLoop = true
//if we already are showing some windows, let's cascade the new one
if self.windows.count > 0 {
//find the right-most window and cascade from it
let rightMost = self.windows.reduce(CGPoint(x: 0.0, y: 0.0), combine: { (right: CGPoint, window: NSWindow) -> CGPoint in
let origin = window.frame.origin
if origin.x > right.x {
return origin
}
return right
})
let newOrigin = newWindow!.cascadeTopLeftFromPoint(rightMost)
newWindow?.setFrameTopLeftPoint(newOrigin)
}
}
guard let window = newWindow else { fatalError("Unable to create window") }
window.delegate = self
self.windows.insert(window)
window.makeKeyAndOrderFront(self)
}
func closeWindowWithViewController(viewController: PresentableViewController) {
if let window = self.windowForPresentableViewControllerWithIdentifier(viewController.uniqueIdentifier)?.0 {
if window.delegate?.windowShouldClose!(window) ?? true {
window.close()
}
}
}
}
extension AppDelegate: StoryboardLoaderDelegate {
func windowForPresentableViewControllerWithIdentifier(identifier: String) -> (NSWindow, PresentableViewController)? {
for window in self.windows {
guard let viewController = window.contentViewController else { continue }
guard let presentableViewController = viewController as? PresentableViewController else { continue }
if presentableViewController.uniqueIdentifier == identifier {
return (window, presentableViewController)
}
}
return nil
}
func storyboardLoaderExistingViewControllerWithIdentifier(identifier: String) -> PresentableViewController? {
//look through our windows and their view controllers to see if we can't find this view controller
let pair = self.windowForPresentableViewControllerWithIdentifier(identifier)
return pair?.1
}
}
extension AppDelegate: NSWindowDelegate {
func windowShouldClose(sender: AnyObject) -> Bool {
if let window = sender as? NSWindow {
self.windows.remove(window)
}
//TODO: based on the editing state, if editing VC (cancel/save)
return true
}
}
| 55832616a55b56f74d4565aa3f541d3c | 33.746032 | 136 | 0.637392 | false | false | false | false |
MichMich/OctoPrintApp | refs/heads/master | OctoPrint/TemperatureTableViewController.swift | mit | 1 | //
// TemperatureTableViewController.swift
// OctoPrint
//
// Created by Michael Teeuw on 27-07-15.
// Copyright © 2015 Michael Teeuw. All rights reserved.
//
import UIKit
class TemperatureTableViewController: UITableViewController {
let sections = ["Bed", "Tools"]
override func viewDidLoad() {
title = "Temperature"
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUI", key: .DidUpdatePrinter, object: OPManager.sharedInstance)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUI", key: .DidUpdateVersion, object: OPManager.sharedInstance)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUI", key: .DidUpdateSettings, object: OPManager.sharedInstance)
OPManager.sharedInstance.updateVersion()
OPManager.sharedInstance.updatePrinter(autoUpdate:1)
OPManager.sharedInstance.updateSettings()
updateUI()
}
func updateUI() {
tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return OPManager.sharedInstance.tools.count
default:
return 0
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == tableView.numberOfSections - 1 {
if let updated = OPManager.sharedInstance.updateTimeStamp {
let formattedDate = NSDateFormatter.localizedStringFromDate(updated,dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: .MediumStyle)
return "Last update: \(formattedDate)"
}
}
return nil
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let shortPath = (indexPath.section, indexPath.row)
switch shortPath {
case (0,_):
let cell = tableView.dequeueReusableCellWithIdentifier("TemperatureCell", forIndexPath: indexPath)
let tool = OPManager.sharedInstance.bed
cell.textLabel?.text = tool.identifier
cell.detailTextLabel?.text = "\(tool.actualTemperature.celciusString()) (\(tool.targetTemperature.celciusString()))"
return cell
case (1,_):
let cell = tableView.dequeueReusableCellWithIdentifier("TemperatureCell", forIndexPath: indexPath)
let tool = OPManager.sharedInstance.tools[indexPath.row]
cell.textLabel?.text = tool.identifier
cell.detailTextLabel?.text = "\(tool.actualTemperature.celciusString()) (\(tool.targetTemperature.celciusString()))"
return cell
default:
let cell = tableView.dequeueReusableCellWithIdentifier("BasicCell", forIndexPath: indexPath)
cell.textLabel?.text = "Unknown cell!"
return cell
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("ShowTemperatureSelector", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowTemperatureSelector" {
if let indexPath = tableView.indexPathForSelectedRow {
let temperatureSelector = segue.destinationViewController as! TemperatureSelectorTableViewController
temperatureSelector.heatedComponent = (indexPath.section == 0) ? OPManager.sharedInstance.bed : OPManager.sharedInstance.tools[indexPath.row]
}
}
}
}
| 20499d40e3fdc9418b96da4a200f24dc | 34.857143 | 157 | 0.636981 | false | false | false | false |
BryanHoke/swift-corelibs-foundation | refs/heads/master | Foundation/NSLocale.swift | apache-2.0 | 5 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
public class NSLocale : NSObject, NSCopying, NSSecureCoding {
typealias CFType = CFLocaleRef
private var _base = _CFInfo(typeID: CFLocaleGetTypeID())
private var _identifier = UnsafeMutablePointer<Void>()
private var _cache = UnsafeMutablePointer<Void>()
private var _prefs = UnsafeMutablePointer<Void>()
#if os(OSX) || os(iOS)
private var _lock = pthread_mutex_t()
#elseif os(Linux)
private var _lock = Int32(0)
#endif
private var _nullLocale = false
internal var _cfObject: CFType {
return unsafeBitCast(self, CFType.self)
}
public func objectForKey(key: String) -> AnyObject? {
return CFLocaleGetValue(_cfObject, key._cfObject)
}
public func displayNameForKey(key: String, value: String) -> String? {
return CFLocaleCopyDisplayNameForPropertyValue(_cfObject, key._cfObject, value._cfObject)?._swiftObject
}
public init(localeIdentifier string: String) {
super.init()
_CFLocaleInit(_cfObject, string._cfObject)
}
public required convenience init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() }
public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() }
public static func supportsSecureCoding() -> Bool {
return true
}
}
extension NSLocale {
public class func currentLocale() -> NSLocale {
return CFLocaleCopyCurrent()._nsObject
}
public class func systemLocale() -> NSLocale {
return CFLocaleGetSystem()._nsObject
}
}
extension NSLocale {
public class func availableLocaleIdentifiers() -> [String] {
var identifiers = Array<String>()
for obj in CFLocaleCopyAvailableLocaleIdentifiers()._nsObject {
identifiers.append((obj as! NSString)._swiftObject)
}
return identifiers
}
public class func ISOLanguageCodes() -> [String] {
var identifiers = Array<String>()
for obj in CFLocaleCopyISOLanguageCodes()._nsObject {
identifiers.append((obj as! NSString)._swiftObject)
}
return identifiers
}
public class func ISOCountryCodes() -> [String] {
var identifiers = Array<String>()
for obj in CFLocaleCopyISOCountryCodes()._nsObject {
identifiers.append((obj as! NSString)._swiftObject)
}
return identifiers
}
public class func ISOCurrencyCodes() -> [String] {
var identifiers = Array<String>()
for obj in CFLocaleCopyISOCurrencyCodes()._nsObject {
identifiers.append((obj as! NSString)._swiftObject)
}
return identifiers
}
public class func commonISOCurrencyCodes() -> [String] {
var identifiers = Array<String>()
for obj in CFLocaleCopyCommonISOCurrencyCodes()._nsObject {
identifiers.append((obj as! NSString)._swiftObject)
}
return identifiers
}
public class func preferredLanguages() -> [String] {
var identifiers = Array<String>()
for obj in CFLocaleCopyPreferredLanguages()._nsObject {
identifiers.append((obj as! NSString)._swiftObject)
}
return identifiers
}
public class func componentsFromLocaleIdentifier(string: String) -> [String : String] {
var comps = Dictionary<String, String>()
CFLocaleCreateComponentsFromLocaleIdentifier(kCFAllocatorSystemDefault, string._cfObject)._nsObject.enumerateKeysAndObjectsUsingBlock { (key: NSObject, object: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
comps[(key as! NSString)._swiftObject] = (object as! NSString)._swiftObject
}
return comps
}
public class func localeIdentifierFromComponents(dict: [String : String]) -> String {
return CFLocaleCreateLocaleIdentifierFromComponents(kCFAllocatorSystemDefault, dict._cfObject)._swiftObject
}
public class func canonicalLocaleIdentifierFromString(string: String) -> String {
return CFLocaleCreateCanonicalLocaleIdentifierFromString(kCFAllocatorSystemDefault, string._cfObject)._swiftObject
}
public class func canonicalLanguageIdentifierFromString(string: String) -> String {
return CFLocaleCreateCanonicalLanguageIdentifierFromString(kCFAllocatorSystemDefault, string._cfObject)._swiftObject
}
public class func localeIdentifierFromWindowsLocaleCode(lcid: UInt32) -> String? {
return CFLocaleCreateLocaleIdentifierFromWindowsLocaleCode(kCFAllocatorSystemDefault, lcid)._swiftObject
}
public class func windowsLocaleCodeFromLocaleIdentifier(localeIdentifier: String) -> UInt32 {
return CFLocaleGetWindowsLocaleCodeFromLocaleIdentifier(localeIdentifier._cfObject)
}
public class func characterDirectionForLanguage(isoLangCode: String) -> NSLocaleLanguageDirection {
let dir = CFLocaleGetLanguageCharacterDirection(isoLangCode._cfObject)
#if os(OSX) || os(iOS)
return NSLocaleLanguageDirection(rawValue: UInt(dir.rawValue))!
#else
return NSLocaleLanguageDirection(rawValue: UInt(dir))!
#endif
}
public class func lineDirectionForLanguage(isoLangCode: String) -> NSLocaleLanguageDirection {
let dir = CFLocaleGetLanguageLineDirection(isoLangCode._cfObject)
#if os(OSX) || os(iOS)
return NSLocaleLanguageDirection(rawValue: UInt(dir.rawValue))!
#else
return NSLocaleLanguageDirection(rawValue: UInt(dir))!
#endif
}
}
public enum NSLocaleLanguageDirection : UInt {
case Unknown
case LeftToRight
case RightToLeft
case TopToBottom
case BottomToTop
}
public let NSCurrentLocaleDidChangeNotification: String = "" // NSUnimplemented
public let NSLocaleIdentifier: String = "kCFLocaleIdentifierKey"
public let NSLocaleLanguageCode: String = "kCFLocaleLanguageCodeKey"
public let NSLocaleCountryCode: String = "kCFLocaleCountryCodeKey"
public let NSLocaleScriptCode: String = "kCFLocaleScriptCodeKey"
public let NSLocaleVariantCode: String = "kCFLocaleVariantCodeKey"
public let NSLocaleExemplarCharacterSet: String = "kCFLocaleExemplarCharacterSetKey"
public let NSLocaleCalendar: String = "kCFLocaleCalendarKey"
public let NSLocaleCollationIdentifier: String = "collation"
public let NSLocaleUsesMetricSystem: String = "kCFLocaleUsesMetricSystemKey"
public let NSLocaleMeasurementSystem: String = "kCFLocaleMeasurementSystemKey"
public let NSLocaleDecimalSeparator: String = "kCFLocaleDecimalSeparatorKey"
public let NSLocaleGroupingSeparator: String = "kCFLocaleGroupingSeparatorKey"
public let NSLocaleCurrencySymbol: String = "kCFLocaleCurrencySymbolKey"
public let NSLocaleCurrencyCode: String = "currency"
public let NSLocaleCollatorIdentifier: String = "" // NSUnimplemented // NSString
public let NSLocaleQuotationBeginDelimiterKey: String = "" // NSUnimplemented // NSString
public let NSLocaleQuotationEndDelimiterKey: String = "" // NSUnimplemented // NSString
public let NSLocaleAlternateQuotationBeginDelimiterKey: String = "" // NSUnimplemented // NSString
public let NSLocaleAlternateQuotationEndDelimiterKey: String = "" // NSUnimplemented // NSString
extension CFLocaleRef : _NSBridgable {
typealias NSType = NSLocale
internal var _nsObject: NSLocale {
return unsafeBitCast(self, NSType.self)
}
} | 70a79842e7ad77ae818ecb2e6ec9877b | 38.454545 | 227 | 0.718474 | false | false | false | false |
JGiola/swift | refs/heads/main | stdlib/public/core/BridgingBuffer.swift | apache-2.0 | 10 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
internal struct _BridgingBufferHeader {
internal var count: Int
internal init(_ count: Int) { self.count = count }
}
// NOTE: older runtimes called this class _BridgingBufferStorage.
// The two must coexist without a conflicting ObjC class name, so it
// was renamed. The old name must not be used in the new runtime.
internal final class __BridgingBufferStorage
: ManagedBuffer<_BridgingBufferHeader, AnyObject> {
}
internal typealias _BridgingBuffer
= ManagedBufferPointer<_BridgingBufferHeader, AnyObject>
@available(OpenBSD, unavailable, message: "malloc_size is unavailable.")
extension ManagedBufferPointer
where Header == _BridgingBufferHeader, Element == AnyObject {
internal init(_ count: Int) {
self.init(
_uncheckedBufferClass: __BridgingBufferStorage.self,
minimumCapacity: count)
self.withUnsafeMutablePointerToHeader {
$0.initialize(to: Header(count))
}
}
internal var count: Int {
@inline(__always)
get {
return header.count
}
@inline(__always)
set {
return header.count = newValue
}
}
internal subscript(i: Int) -> Element {
@inline(__always)
get {
return withUnsafeMutablePointerToElements { $0[i] }
}
}
internal var baseAddress: UnsafeMutablePointer<Element> {
@inline(__always)
get {
return withUnsafeMutablePointerToElements { $0 }
}
}
internal var storage: AnyObject? {
@inline(__always)
get {
return buffer
}
}
}
| 4588351bf4dd033f884e16e7e661ae7f | 26.930556 | 80 | 0.640975 | false | false | false | false |
auth0/Auth0.swift | refs/heads/master | Auth0/NSURLComponents+OAuth2.swift | mit | 1 | #if WEB_AUTH_PLATFORM
import Foundation
extension URLComponents {
var fragmentValues: [String: String] {
var dict: [String: String] = [:]
let items = fragment?.components(separatedBy: "&")
items?.forEach { item in
let parts = item.components(separatedBy: "=")
guard parts.count == 2, let key = parts.first, let value = parts.last else { return }
dict[key] = value
}
return dict
}
var queryValues: [String: String] {
var dict: [String: String] = [:]
self.queryItems?.forEach { dict[$0.name] = $0.value }
return dict
}
}
#endif
| 21963484044227bda8b6399a2d84edd6 | 25.916667 | 97 | 0.569659 | false | false | false | false |
LateralView/swift-lateral-toolbox | refs/heads/master | Example/Tests/UIColorSpec.swift | mit | 1 | import Quick
import Nimble
import UIKit
import swift_lateral_toolbox
class UIColorSpec: QuickSpec {
override func spec() {
describe("creating color from hex number") {
it("works with color #000000") {
let reference = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 1)
let color = UIColor(hex: 0x000000)
expect(reference).to(equal(color))
}
it("works with color #FFFFFF") {
let reference = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 1)
let color = UIColor(hex: 0xFFFFFF)
expect(reference).to(equal(color))
}
}
describe("extracting components") {
it("works with color #123456 and alpha 78") {
let reference = UIColor(colorLiteralRed: 0x12/0xFF, green: 0x34/0xFF, blue: 0x56/0xFF, alpha: 0x78/0xFF)
let c = reference.components
expect(c.red - 0x12/0xFF).to(beLessThan(0.001))
expect(c.green - 0x34/0xFF).to(beLessThan(0.001))
expect(c.blue - 0x56/0xFF).to(beLessThan(0.001))
expect(c.alpha - 0x78/0xFF).to(beLessThan(0.001))
}
}
describe("changing color tones") {
it("returns a 20% darker color than white") {
let reference = UIColor(colorLiteralRed: 0.8, green: 0.8, blue: 0.8, alpha: 1)
let color = UIColor.whiteColor().darker()
expect(color).to(equal(reference))
}
it("returns a 20% brighter color than black") {
let reference = UIColor(colorLiteralRed: 0.2, green: 0.2, blue: 0.2, alpha: 1)
let color = UIColor.blackColor().brighter()
expect(color).to(equal(reference))
}
it("returns white even after trying to make it brighter") {
let white = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 1)
expect(white.brighter()).to(equal(white))
}
it("returns black even after trying to make it darker") {
let black = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 1)
expect(black.darker()).to(equal(black))
}
}
describe("creating an image") {
it("consists of a single pixel") {
let color = UIColor(colorLiteralRed: 0.75, green: 0.50, blue: 0.25, alpha: 1)
var image : UIImage!
image = color.toImage()
expect(image.size.width).to(equal(1))
expect(image.size.height).to(equal(1))
}
}
}
}
| d9cb0aab33e3797998ad3467bb47ecc5 | 34.455696 | 120 | 0.516244 | false | false | false | false |
geekaurora/ReactiveListViewKit | refs/heads/master | Example/ReactiveListViewKitDemo/Data Layer/User.swift | mit | 1 | //
// User.swift
// ReactiveListViewKit
//
// Created by Cheng Zhang on 1/3/17.
// Copyright © 2017 Cheng Zhang. All rights reserved.
//
import CZUtils
import ReactiveListViewKit
/// Model of user
class User: ReactiveListDiffable {
let userId: String
let userName: String
let fullName: String?
let portraitUrl: String?
enum CodingKeys: String, CodingKey {
case userId = "id"
case userName = "username"
case fullName = "full_name"
case portraitUrl = "profile_picture"
}
// MARK: - CZListDiffable
func isEqual(toDiffableObj object: AnyObject) -> Bool {
return isEqual(toCodable: object)
}
// MARK: - NSCopying
func copy(with zone: NSZone? = nil) -> Any {
return codableCopy(with: zone)
}
}
| fd74b64dc5deacb662d0a3090eb5da42 | 20.702703 | 59 | 0.628892 | false | false | false | false |
nheagy/WordPress-iOS | refs/heads/develop | WordPress/WordPressTest/BlogSettingsDiscussionTests.swift | gpl-2.0 | 1 | import Foundation
@testable import WordPress
class BlogSettingsDiscussionTests : XCTestCase
{
private var manager : TestContextManager!
override func setUp() {
manager = TestContextManager()
}
override func tearDown() {
manager = nil
}
func testCommentsAutoapprovalDisabledEnablesManualModerationFlag() {
let settings = newSettings()
settings.commentsAutoapproval = .Disabled
XCTAssertTrue(settings.commentsRequireManualModeration)
XCTAssertFalse(settings.commentsFromKnownUsersWhitelisted)
}
func testCommentsAutoapprovalFromKnownUsersEnablesWhitelistedFlag() {
let settings = newSettings()
settings.commentsAutoapproval = .FromKnownUsers
XCTAssertFalse(settings.commentsRequireManualModeration)
XCTAssertTrue(settings.commentsFromKnownUsersWhitelisted)
}
func testCommentsAutoapprovalEverythingDisablesManualModerationAndWhitelistedFlags() {
let settings = newSettings()
settings.commentsAutoapproval = .Everything
XCTAssertFalse(settings.commentsRequireManualModeration)
XCTAssertFalse(settings.commentsFromKnownUsersWhitelisted)
}
func testCommentsSortingSetsTheCorrectCommentSortOrderIntegerValue() {
let settings = newSettings()
settings.commentsSorting = .Ascending
XCTAssertTrue(settings.commentsSortOrder == Sorting.Ascending.rawValue)
settings.commentsSorting = .Descending
XCTAssertTrue(settings.commentsSortOrder == Sorting.Descending.rawValue)
}
func testCommentsSortOrderAscendingSetsTheCorrectCommentSortOrderIntegerValue() {
let settings = newSettings()
settings.commentsSortOrderAscending = true
XCTAssertTrue(settings.commentsSortOrder == Sorting.Ascending.rawValue)
settings.commentsSortOrderAscending = false
XCTAssertTrue(settings.commentsSortOrder == Sorting.Descending.rawValue)
}
func testCommentsThreadingDisablesSetsThreadingEnabledFalse() {
let settings = newSettings()
settings.commentsThreading = .Disabled
XCTAssertFalse(settings.commentsThreadingEnabled)
}
func testCommentsThreadingEnabledSetsThreadingEnabledTrueAndTheRightDepthValue() {
let settings = newSettings()
settings.commentsThreading = .Enabled(depth: 10)
XCTAssertTrue(settings.commentsThreadingEnabled)
XCTAssert(settings.commentsThreadingDepth == 10)
settings.commentsThreading = .Enabled(depth: 2)
XCTAssertTrue(settings.commentsThreadingEnabled)
XCTAssert(settings.commentsThreadingDepth == 2)
}
// MARK: - Typealiases
typealias Sorting = BlogSettings.CommentsSorting
// MARK: - Private Helpers
private func newSettings() -> BlogSettings {
let context = manager!.mainContext
let name = BlogSettings.classNameWithoutNamespaces()
let entity = NSEntityDescription.insertNewObjectForEntityForName(name, inManagedObjectContext: context)
return entity as! BlogSettings
}
}
| abd30c2bd79c3b36db45646e9518dd96 | 34.6 | 111 | 0.712859 | false | true | false | false |
jpsim/SourceKitten | refs/heads/main | Source/SourceKittenFramework/SwiftVersion.swift | mit | 1 | /// The version triple of the Swift compiler, for example "5.1.3"
struct SwiftVersion: RawRepresentable, Comparable {
typealias RawValue = String
let rawValue: String
init(rawValue: String) {
self.rawValue = rawValue
}
/// Comparable
static func < (lhs: SwiftVersion, rhs: SwiftVersion) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
extension SwiftVersion {
static let beforeFiveDotOne = SwiftVersion(rawValue: "1.0.0")
static let fiveDotOne = SwiftVersion(rawValue: "5.1.0")
/// The version of the Swift compiler providing SourceKit. Accurate only from
/// compiler version 5.1.0: earlier versions return `.beforeFiveDotOne`.
static let current: SwiftVersion = {
if let result = try? Request.compilerVersion.send(),
let major = result["key.version_major"] as? Int64,
let minor = result["key.version_minor"] as? Int64,
let patch = result["key.version_patch"] as? Int64 {
return SwiftVersion(rawValue: "\(major).\(minor).\(patch)")
}
return .beforeFiveDotOne
}()
}
| cfbc3e90f0b1e9dabd032d972b6082e6 | 33.78125 | 82 | 0.645103 | false | false | false | false |
DavidHu0921/LyricsEasy | refs/heads/master | Carthage/Checkouts/FileKit/Sources/Operators.swift | mit | 2 | //
// Operators.swift
// FileKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 Nikolai Vazquez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// swiftlint:disable file_length
import Foundation
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// MARK: - File
/// Returns `true` if both files' paths are the same.
public func ==<DataType: ReadableWritable>(lhs: File<DataType>, rhs: File<DataType>) -> Bool {
return lhs.path == rhs.path
}
/// Returns `true` if `lhs` is smaller than `rhs` in size.
public func < <DataType: ReadableWritable>(lhs: File<DataType>, rhs: File<DataType>) -> Bool {
return lhs.size < rhs.size
}
infix operator |>
/// Writes data to a file.
///
/// - Throws: `FileKitError.WriteToFileFail`
///
public func |> <DataType: ReadableWritable>(data: DataType, file: File<DataType>) throws {
try file.write(data)
}
// MARK: - TextFile
/// Returns `true` if both text files have the same path and encoding.
public func == (lhs: TextFile, rhs: TextFile) -> Bool {
return lhs.path == rhs.path && lhs.encoding == rhs.encoding
}
infix operator |>>
/// Appends a string to a text file.
///
/// If the text file can't be read from, such in the case that it doesn't exist,
/// then it will try to write the data directly to the file.
///
/// - Throws: `FileKitError.WriteToFileFail`
///
public func |>> (data: String, file: TextFile) throws {
var data = data
if let contents = try? file.read() {
data = contents + "\n" + data
}
try data |> file
}
/// Return lines of file that match the motif.
public func | (file: TextFile, motif: String) -> [String] {
return file.grep(motif)
}
infix operator |-
/// Return lines of file that does'nt match the motif.
public func |- (file: TextFile, motif: String) -> [String] {
return file.grep(motif, include: false)
}
infix operator |~
/// Return lines of file that match the regex motif.
public func |~ (file: TextFile, motif: String) -> [String] {
return file.grep(motif, options: NSString.CompareOptions.regularExpression)
}
// MARK: - Path
/// Returns `true` if the standardized form of one path equals that of another
/// path.
public func == (lhs: Path, rhs: Path) -> Bool {
if lhs.isAbsolute || rhs.isAbsolute {
return lhs.absolute.rawValue == rhs.absolute.rawValue
}
return lhs.standardRawValueWithTilde == rhs.standardRawValueWithTilde
}
/// Returns `true` if the standardized form of one path not equals that of another
/// path.
public func != (lhs: Path, rhs: Path) -> Bool {
return !(lhs == rhs)
}
/// Concatenates two `Path` instances and returns the result.
///
/// ```swift
/// let systemLibrary: Path = "/System/Library"
/// print(systemLib + "Fonts") // "/System/Library/Fonts"
/// ```
///
public func + (lhs: Path, rhs: Path) -> Path {
if lhs.rawValue.isEmpty || lhs.rawValue == "." { return rhs }
if rhs.rawValue.isEmpty || rhs.rawValue == "." { return lhs }
switch (lhs.rawValue.hasSuffix(Path.separator), rhs.rawValue.hasPrefix(Path.separator)) {
case (true, true):
let rhsRawValue = rhs.rawValue.substring(from: rhs.rawValue.characters.index(after: rhs.rawValue.startIndex))
return Path("\(lhs.rawValue)\(rhsRawValue)")
case (false, false):
return Path("\(lhs.rawValue)\(Path.separator)\(rhs.rawValue)")
default:
return Path("\(lhs.rawValue)\(rhs.rawValue)")
}
}
/// Converts a `String` to a `Path` and returns the concatenated result.
public func + (lhs: String, rhs: Path) -> Path {
return Path(lhs) + rhs
}
/// Converts a `String` to a `Path` and returns the concatenated result.
public func + (lhs: Path, rhs: String) -> Path {
return lhs + Path(rhs)
}
/// Appends the right path to the left path.
public func += (lhs: inout Path, rhs: Path) {
lhs = lhs + rhs
}
/// Appends the path value of the String to the left path.
public func += (lhs: inout Path, rhs: String) {
lhs = lhs + rhs
}
/// Concatenates two `Path` instances and returns the result.
public func / (lhs: Path, rhs: Path) -> Path {
return lhs + rhs
}
/// Converts a `String` to a `Path` and returns the concatenated result.
public func / (lhs: Path, rhs: String) -> Path {
return lhs + rhs
}
/// Converts a `String` to a `Path` and returns the concatenated result.
public func / (lhs: String, rhs: Path) -> Path {
return lhs + rhs
}
/// Appends the right path to the left path.
public func /= (lhs: inout Path, rhs: Path) {
lhs += rhs
}
/// Appends the path value of the String to the left path.
public func /= (lhs: inout Path, rhs: String) {
lhs += rhs
}
precedencegroup FileCommonAncestorPrecedence {
associativity: left
}
infix operator <^> : FileCommonAncestorPrecedence
/// Returns the common ancestor between the two paths.
public func <^> (lhs: Path, rhs: Path) -> Path {
return lhs.commonAncestor(rhs)
}
infix operator </>
/// Runs `closure` with the path as its current working directory.
public func </> (path: Path, closure: () throws -> ()) rethrows {
try path.changeDirectory(closure)
}
infix operator ->>
/// Moves the file at the left path to a path.
///
/// Throws an error if the file at the left path could not be moved or if a file
/// already exists at the right path.
///
/// - Throws: `FileKitError.FileDoesNotExist`, `FileKitError.MoveFileFail`
///
public func ->> (lhs: Path, rhs: Path) throws {
try lhs.moveFile(to: rhs)
}
/// Moves a file to a path.
///
/// Throws an error if the file could not be moved or if a file already
/// exists at the destination path.
///
/// - Throws: `FileKitError.FileDoesNotExist`, `FileKitError.MoveFileFail`
///
public func ->> <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws {
try lhs.move(to: rhs)
}
infix operator ->!
/// Forcibly moves the file at the left path to the right path.
///
/// - Warning: If a file at the right path already exists, it will be deleted.
///
/// - Throws:
/// `FileKitError.DeleteFileFail`,
/// `FileKitError.FileDoesNotExist`,
/// `FileKitError.CreateSymlinkFail`
///
public func ->! (lhs: Path, rhs: Path) throws {
if rhs.isAny {
try rhs.deleteFile()
}
try lhs ->> rhs
}
/// Forcibly moves a file to a path.
///
/// - Warning: If a file at the right path already exists, it will be deleted.
///
/// - Throws:
/// `FileKitError.DeleteFileFail`,
/// `FileKitError.FileDoesNotExist`,
/// `FileKitError.CreateSymlinkFail`
///
public func ->! <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws {
if rhs.isAny {
try rhs.deleteFile()
}
try lhs ->> rhs
}
infix operator +>>
/// Copies the file at the left path to the right path.
///
/// Throws an error if the file at the left path could not be copied or if a file
/// already exists at the right path.
///
/// - Throws: `FileKitError.FileDoesNotExist`, `FileKitError.CopyFileFail`
///
public func +>> (lhs: Path, rhs: Path) throws {
try lhs.copyFile(to: rhs)
}
/// Copies a file to a path.
///
/// Throws an error if the file could not be copied or if a file already
/// exists at the destination path.
///
/// - Throws: `FileKitError.FileDoesNotExist`, `FileKitError.CopyFileFail`
///
public func +>> <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws {
try lhs.copy(to: rhs)
}
infix operator +>!
/// Forcibly copies the file at the left path to the right path.
///
/// - Warning: If a file at the right path already exists, it will be deleted.
///
/// - Throws:
/// `FileKitError.DeleteFileFail`,
/// `FileKitError.FileDoesNotExist`,
/// `FileKitError.CreateSymlinkFail`
///
public func +>! (lhs: Path, rhs: Path) throws {
if rhs.isAny {
try rhs.deleteFile()
}
try lhs +>> rhs
}
/// Forcibly copies a file to a path.
///
/// - Warning: If a file at the right path already exists, it will be deleted.
///
/// - Throws:
/// `FileKitError.DeleteFileFail`,
/// `FileKitError.FileDoesNotExist`,
/// `FileKitError.CreateSymlinkFail`
///
public func +>! <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws {
if rhs.isAny {
try rhs.deleteFile()
}
try lhs +>> rhs
}
infix operator =>>
/// Creates a symlink of the left path at the right path.
///
/// If the symbolic link path already exists and _is not_ a directory, an
/// error will be thrown and a link will not be created.
///
/// If the symbolic link path already exists and _is_ a directory, the link
/// will be made to a file in that directory.
///
/// - Throws:
/// `FileKitError.FileDoesNotExist`,
/// `FileKitError.CreateSymlinkFail`
///
public func =>> (lhs: Path, rhs: Path) throws {
try lhs.symlinkFile(to: rhs)
}
/// Symlinks a file to a path.
///
/// If the path already exists and _is not_ a directory, an error will be
/// thrown and a link will not be created.
///
/// If the path already exists and _is_ a directory, the link will be made
/// to the file in that directory.
///
/// - Throws: `FileKitError.FileDoesNotExist`, `FileKitError.CreateSymlinkFail`
///
public func =>> <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws {
try lhs.symlink(to: rhs)
}
infix operator =>!
/// Forcibly creates a symlink of the left path at the right path by deleting
/// anything at the right path before creating the symlink.
///
/// - Warning: If the symbolic link path already exists, it will be deleted.
///
/// - Throws:
/// `FileKitError.DeleteFileFail`,
/// `FileKitError.FileDoesNotExist`,
/// `FileKitError.CreateSymlinkFail`
///
public func =>! (lhs: Path, rhs: Path) throws {
// guard lhs.exists else {
// throw FileKitError.FileDoesNotExist(path: lhs)
// }
let linkPath = rhs.isDirectory ? rhs + lhs.fileName : rhs
if linkPath.isAny { try linkPath.deleteFile() }
try lhs =>> rhs
}
/// Forcibly creates a symlink of a file at a path by deleting anything at the
/// path before creating the symlink.
///
/// - Warning: If the path already exists, it will be deleted.
///
/// - Throws:
/// `FileKitError.DeleteFileFail`,
/// `FileKitError.FileDoesNotExist`,
/// `FileKitError.CreateSymlinkFail`
///
public func =>! <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws {
try lhs.path =>! rhs
}
postfix operator %
/// Returns the standardized version of the path.
public postfix func % (path: Path) -> Path {
return path.standardized
}
postfix operator *
/// Returns the resolved version of the path.
public postfix func * (path: Path) -> Path {
return path.resolved
}
postfix operator ^
/// Returns the path's parent path.
public postfix func ^ (path: Path) -> Path {
return path.parent
}
| 28606484880ebfedf1997cf5a9fd221e | 26.548387 | 117 | 0.663349 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/stdlib/TestLocale.swift | apache-2.0 | 16 | // 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
//
//===----------------------------------------------------------------------===//
//
// RUN: %empty-directory(%t)
//
// RUN: %target-clang %S/Inputs/FoundationBridge/FoundationBridge.m -c -o %t/FoundationBridgeObjC.o -g
// RUN: %target-build-swift %s -I %S/Inputs/FoundationBridge/ -Xlinker %t/FoundationBridgeObjC.o -o %t/TestLocale
// RUN: %target-run %t/TestLocale > %t.txt
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import FoundationBridgeObjC
#if FOUNDATION_XCTEST
import XCTest
class TestLocaleSuper : XCTestCase { }
#else
import StdlibUnittest
class TestLocaleSuper { }
#endif
class TestLocale : TestLocaleSuper {
func test_bridgingAutoupdating() {
let tester = LocaleBridgingTester()
do {
let loc = Locale.autoupdatingCurrent
let result = tester.verifyAutoupdating(loc)
expectTrue(result)
}
do {
let loc = tester.autoupdatingCurrentLocale()
let result = tester.verifyAutoupdating(loc)
expectTrue(result)
}
}
func test_equality() {
let autoupdating = Locale.autoupdatingCurrent
let autoupdating2 = Locale.autoupdatingCurrent
expectEqual(autoupdating, autoupdating2)
let current = Locale.current
expectNotEqual(autoupdating, current)
}
func test_localizedStringFunctions() {
let locale = Locale(identifier: "en")
expectEqual("English", locale.localizedString(forIdentifier: "en"))
expectEqual("France", locale.localizedString(forRegionCode: "fr"))
expectEqual("Spanish", locale.localizedString(forLanguageCode: "es"))
expectEqual("Simplified Han", locale.localizedString(forScriptCode: "Hans"))
expectEqual("Computer", locale.localizedString(forVariantCode: "POSIX"))
expectEqual("Buddhist Calendar", locale.localizedString(for: .buddhist))
expectEqual("US Dollar", locale.localizedString(forCurrencyCode: "USD"))
expectEqual("Phonebook Sort Order", locale.localizedString(forCollationIdentifier: "phonebook"))
// Need to find a good test case for collator identifier
// expectEqual("something", locale.localizedString(forCollatorIdentifier: "en"))
}
func test_properties() {
let locale = Locale(identifier: "zh-Hant-HK")
expectEqual("zh-Hant-HK", locale.identifier)
expectEqual("zh", locale.languageCode)
expectEqual("HK", locale.regionCode)
expectEqual("Hant", locale.scriptCode)
expectEqual("POSIX", Locale(identifier: "en_POSIX").variantCode)
expectTrue(locale.exemplarCharacterSet != nil)
// The calendar we get back from Locale has the locale set, but not the one we create with Calendar(identifier:). So we configure our comparison calendar first.
var c = Calendar(identifier: .gregorian)
c.locale = Locale(identifier: "en_US")
expectEqual(c, Locale(identifier: "en_US").calendar)
expectEqual("「", locale.quotationBeginDelimiter)
expectEqual("」", locale.quotationEndDelimiter)
expectEqual("『", locale.alternateQuotationBeginDelimiter)
expectEqual("』", locale.alternateQuotationEndDelimiter)
expectEqual("phonebook", Locale(identifier: "en_US@collation=phonebook").collationIdentifier)
expectEqual(".", locale.decimalSeparator)
expectEqual(".", locale.decimalSeparator)
expectEqual(",", locale.groupingSeparator)
expectEqual("HK$", locale.currencySymbol)
expectEqual("HKD", locale.currencyCode)
expectTrue(Locale.availableIdentifiers.count > 0)
expectTrue(Locale.isoLanguageCodes.count > 0)
expectTrue(Locale.isoRegionCodes.count > 0)
expectTrue(Locale.isoCurrencyCodes.count > 0)
expectTrue(Locale.commonISOCurrencyCodes.count > 0)
expectTrue(Locale.preferredLanguages.count > 0)
// Need to find a good test case for collator identifier
// expectEqual("something", locale.collatorIdentifier)
}
func test_AnyHashableContainingLocale() {
let values: [Locale] = [
Locale(identifier: "en"),
Locale(identifier: "uk"),
Locale(identifier: "uk"),
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(Locale.self, type(of: anyHashables[0].base))
expectEqual(Locale.self, type(of: anyHashables[1].base))
expectEqual(Locale.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
func test_AnyHashableCreatedFromNSLocale() {
let values: [NSLocale] = [
NSLocale(localeIdentifier: "en"),
NSLocale(localeIdentifier: "uk"),
NSLocale(localeIdentifier: "uk"),
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(Locale.self, type(of: anyHashables[0].base))
expectEqual(Locale.self, type(of: anyHashables[1].base))
expectEqual(Locale.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
}
#if !FOUNDATION_XCTEST
var LocaleTests = TestSuite("TestLocale")
LocaleTests.test("test_bridgingAutoupdating") { TestLocale().test_bridgingAutoupdating() }
LocaleTests.test("test_equality") { TestLocale().test_equality() }
LocaleTests.test("test_localizedStringFunctions") { TestLocale().test_localizedStringFunctions() }
LocaleTests.test("test_properties") { TestLocale().test_properties() }
LocaleTests.test("test_AnyHashableContainingLocale") { TestLocale().test_AnyHashableContainingLocale() }
LocaleTests.test("test_AnyHashableCreatedFromNSLocale") { TestLocale().test_AnyHashableCreatedFromNSLocale() }
runAllTests()
#endif
| 6cf915ed32c1da3dd119aa083402af4f | 40.986577 | 168 | 0.669118 | false | true | false | false |
Vayne-Lover/Swift-Filter | refs/heads/master | Median Filter.playground/Contents.swift | mit | 1 | //Setting Start
import UIKit
func getTestValueUInt16()->UInt16{
return UInt16(arc4random_uniform(255))
}
func getTestValueInt()->Int{
return Int(arc4random_uniform(255))
}
//Setting End
//Double Extension Start
extension Double{//If you want to format you can use the extension.
func format(f:String) -> String {
return NSString(format: "%\(f)f",self) as String
}
}
//Double Extension End
//Extension Example Start
//print(Double(3.1415).format(".2"))//There is the example to format Double
//Extension Example End
//Median Filter
//Filter2 Start
var Value2=128.0
func filter2(inout Value:Double)->Double{
var value2:[Int]=[getTestValueInt(),getTestValueInt(),getTestValueInt(),getTestValueInt()]
for i in 0..<3 {
for j in 0..<3-i {
if value2[j]>value2[j+1] {
let temp=value2[j]
value2[j]=value2[j+1]
value2[j+1]=temp
}
}
}
Value=Double(value2[2]+value2[1])/2.0
return Value
}
//Filter2 End
//Filter2 Test Start
print(filter2(&Value2).format(".2"))
//Filter2 Test End | 35665f0a4c547284c92e016dca2cd5e7 | 25.853659 | 94 | 0.641818 | false | true | false | false |
johannescarlen/daterangeview | refs/heads/master | DateRange/ViewController.swift | mit | 1 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Johannes Carlén, Wildberry
//
// 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
class ViewController: UIViewController, DateRangeDelegate {
@IBOutlet weak var upperView: UIView!
@IBOutlet weak var dateRangeContainerView: UIView!
@IBOutlet weak var periodLabel: UILabel!
var dateRangeView: DateRangeView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
upperView.backgroundColor = UIColor(22, 122, 182)
dateRangeView = DateRangeView(frame: CGRectMake(0, 80, self.view.frame.width, 200))
dateRangeView.delegate = self
dateRangeView.setContentOffset(year: 2016, month: 1)
self.view.addSubview(upperView)
self.dateRangeContainerView.addSubview(dateRangeView)
self.view.layoutIfNeeded()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func dateSelected(start start: Int, end: Int) {
print("Start: \(start) End:\(end)")
// Format 201503
var selectedString : (String)
if(start == end && start == 0) {
selectedString = "No filter"
} else {
let formatter = NSDateFormatter()
let month1Index = (start % 100)
let month1: String = formatter.monthSymbols[month1Index - 1]
selectedString = "\(month1) \((start-month1Index)/100)"
if(start != end) {
let month2Index = (end % 100)
let month2: String = formatter.monthSymbols[month2Index - 1]
selectedString += " - \(month2) \((end-month2Index)/100)"
}
}
self.periodLabel!.text = selectedString
}
}
| 7ddac6207aa6de8d3f1dcb2fbdf30173 | 38.346667 | 91 | 0.664521 | false | false | false | false |
spacedrabbit/100-days | refs/heads/master | One00Days/One00Days/Day8ViewController.swift | mit | 1 | //
// Dat8ViewController.swift
// One00Days
//
// Created by Louis Tur on 2/28/16.
// Copyright © 2016 SRLabs. All rights reserved.
//
import UIKit
class Day8ViewController: UIViewController {
let frontCardView: UIView = {
let view: UIView = UIView()
view.backgroundColor = UIColor.lightGray
return view
}()
let backCardView: UIView = {
let view: UIView = UIView()
view.backgroundColor = UIColor.blue
return view
}()
let frontCardText: UILabel = {
let label: UILabel = UILabel()
label.text = "Hello world, how are you"
label.font = UIFont(name: "Menlo", size: 40.0)
label.numberOfLines = 3
label.adjustsFontSizeToFitWidth = true
return label
}()
let insideCardText: UILabel = {
let label: UILabel = UILabel()
label.text = "World keeps turning and I've been better"
label.font = UIFont(name: "Menlo", size: 40.0)
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = 3
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.brown
self.setupViewHierarchy()
self.configureConstraints()
self.applyTransform()
}
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() }
internal func configureConstraints() {
self.frontCardView.snp.makeConstraints { (make) -> Void in
make.width.equalTo(200.0)
make.height.equalTo(170.0)
make.center.equalTo(self.view.snp.center)
}
self.backCardView.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(self.frontCardView.snp.edges)
}
self.frontCardText.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(self.frontCardView.snp.edges)
}
self.insideCardText.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(self.backCardView.snp.edges)
}
}
internal func setupViewHierarchy() {
self.view.addSubview(self.backCardView)
self.view.addSubview(self.frontCardView)
self.frontCardView.addSubview(self.frontCardText)
self.backCardView.addSubview(self.insideCardText)
}
internal func applyTransform() {
let frontCardAngle: CGFloat = degreesToRadians(35.0)
let sideTwist: CGFloat = degreesToRadians(20.0)
self.frontCardView.layer.anchorPoint = CGPoint(x: 0.0, y: 0.0)
// self.frontCardView.layer.position = CGPointMake( CGRectGetMidX(self.frontCardView.frame), CGRectGetMaxY(self.frontCardView.frame))
let rotateForwardOnX = CATransform3DMakeRotation(frontCardAngle, 1.0, 0.0, 0.0)
let rotateLeftOnY = CATransform3DMakeRotation(sideTwist, 0.0, -1.0, 0.0)
self.frontCardView.layer.transform = CATransform3DConcat(rotateForwardOnX, rotateLeftOnY)
}
}
| 43a37becf7fd0fb59afaaad025a169bc | 27.44898 | 136 | 0.688307 | false | false | false | false |
Perfect-Server-Swift-LearnGuide/Today-News-Admin | refs/heads/master | Sources/Handler/UploadArticleImageHandler.swift | apache-2.0 | 1 | //
// UploadArticleImageHandler.swift
// Today-News-Admin
//
// Created by Mac on 17/7/24.
// Copyright © 2017年 lovemo. All rights reserved.
//
import PerfectHTTP
import PerfectLib
import Config
public struct UploadArticleImageHandler {
public init(){}
/// 上传文章缩略图
public static func upload(req: HTTPRequest, res: HTTPResponse) -> String {
var imgs = [[String:Any]]()
if let uploads = req.postFileUploads , uploads.count > 0 {
// 创建路径用于存储已上传文件
let fileDir = Dir(Dir.workingDir.path + req.documentRoot + "/\(app.upload)/")
do {
try fileDir.create()
} catch {
print(error)
}
for upload in uploads {
let judgeResult: (Bool, String) = self.judge(contenType: upload.contentType, fileSize: upload.fileSize)
if judgeResult.0 {
// 将文件转移走,如果目标位置已经有同名文件则进行覆盖操作。
let thisFile = File(upload.tmpFileName)
let path = upload.fieldName + self.ext(contentType: upload.contentType)
do {
let _ = try thisFile.moveTo(path: fileDir.path + path, overWrite: true)
imgs.append(["url" : "./\(app.upload)/" + path])
} catch {
print(error)
}
}
}
}
if imgs.count > 0 {
return try! ["result" : ["msg" : "success", "urls" : imgs]].jsonEncodedString()
} else {
return try! ["result" : ["msg" : "error", "urls" : ""]].jsonEncodedString()
}
}
static func ext(contentType: String) -> String {
let filterStr = ["gif", "jpg", "jpeg", "bmp", "png"];
for str in filterStr {
if contentType.contains(string: str) {
return ".\(str)"
}
}
return ".jpg"
}
static func judge(contenType: String, fileSize: Int) -> (Bool, String) {
let filter = ["gif", "jpg", "jpeg", "bmp", "png"];
var contain = false
for str in filter {
if contenType.contains(string: str) {
contain = true
}
}
if !contain {
return (false, try! ["result" : "上传失败, 图片格式不对"].jsonEncodedString())
}
if fileSize > 1000 * 1000 * 10 {
return (false, try! ["result" : "上传失败, 图片尺寸太大"].jsonEncodedString())
}
return (true, try! ["result" : "上传成功"].jsonEncodedString())
}
}
| 4924913b1a50b5a427095f23ec403e4d | 29.255556 | 119 | 0.47264 | false | false | false | false |
MrMatthias/SwiftColorPicker | refs/heads/master | Source/HuePicker.swift | mit | 1 | // Created by Matthias Schlemm on 05/03/15.
// Copyright (c) 2015 Sixpolys. All rights reserved.
// Licensed under the MIT License.
// URL: https://github.com/MrMatthias/SwiftColorPicker
import UIKit
@IBDesignable open class HuePicker: UIView {
var _h:CGFloat = 0.1111
open var h:CGFloat { // [0,1]
set(value) {
_h = min(1, max(0, value))
currentPoint = CGPoint(x: CGFloat(_h), y: 0)
setNeedsDisplay()
}
get {
return _h
}
}
var image:UIImage?
fileprivate var data:[UInt8]?
fileprivate var currentPoint = CGPoint.zero
open var handleColor:UIColor = UIColor.black
open var onHueChange:((_ hue:CGFloat, _ finished:Bool) -> Void)?
open func setHueFromColor(_ color:UIColor) {
var h:CGFloat = 0
color.getHue(&h, saturation: nil, brightness: nil, alpha: nil)
self.h = h
}
public override init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = true;
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
isUserInteractionEnabled = true
}
func renderBitmap() {
if bounds.isEmpty {
return
}
let width = UInt(bounds.width)
let height = UInt(bounds.height)
if data == nil {
data = [UInt8](repeating: UInt8(255), count: Int(width * height) * 4)
}
var p = 0.0
var q = 0.0
var t = 0.0
var i = 0
//_ = 255
var double_v:Double = 0
var double_s:Double = 0
let widthRatio:Double = 360 / Double(bounds.width)
var d = data!
for hi in 0..<Int(bounds.width) {
let double_h:Double = widthRatio * Double(hi) / 60
let sector:Int = Int(floor(double_h))
let f:Double = double_h - Double(sector)
let f1:Double = 1.0 - f
double_v = Double(1)
double_s = Double(1)
p = double_v * (1.0 - double_s) * 255
q = double_v * (1.0 - double_s * f) * 255
t = double_v * ( 1.0 - double_s * f1) * 255
let v255 = double_v * 255
i = hi * 4
switch(sector) {
case 0:
d[i+1] = UInt8(v255)
d[i+2] = UInt8(t)
d[i+3] = UInt8(p)
case 1:
d[i+1] = UInt8(q)
d[i+2] = UInt8(v255)
d[i+3] = UInt8(p)
case 2:
d[i+1] = UInt8(p)
d[i+2] = UInt8(v255)
d[i+3] = UInt8(t)
case 3:
d[i+1] = UInt8(p)
d[i+2] = UInt8(q)
d[i+3] = UInt8(v255)
case 4:
d[i+1] = UInt8(t)
d[i+2] = UInt8(p)
d[i+3] = UInt8(v255)
default:
d[i+1] = UInt8(v255)
d[i+2] = UInt8(p)
d[i+3] = UInt8(q)
}
}
var sourcei = 0
for v in 1..<Int(bounds.height) {
for s in 0..<Int(bounds.width) {
sourcei = s * 4
i = (v * Int(width) * 4) + sourcei
d[i+1] = d[sourcei+1]
d[i+2] = d[sourcei+2]
d[i+3] = d[sourcei+3]
}
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
let provider = CGDataProvider(data: Data(bytes: d, count: d.count * MemoryLayout<UInt8>.size) as CFData)
let cgimg = CGImage(width: Int(width), height: Int(height), bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: Int(width) * Int(MemoryLayout<UInt8>.size * 4),
space: colorSpace, bitmapInfo: bitmapInfo, provider: provider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
image = UIImage(cgImage: cgimg!)
}
fileprivate func handleTouch(_ touch:UITouch, finished:Bool) {
let point = touch.location(in: self)
currentPoint = CGPoint(x: max(0, min(bounds.width, point.x)) / bounds.width , y: 0)
_h = currentPoint.x
onHueChange?(h, finished)
setNeedsDisplay()
}
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
handleTouch(touches.first! as UITouch, finished: false)
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
handleTouch(touches.first! as UITouch, finished: false)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
handleTouch(touches.first! as UITouch, finished: true)
}
override open func draw(_ rect: CGRect) {
if image == nil {
renderBitmap()
}
if let img = image {
img.draw(in: rect)
}
let handleRect = CGRect(x: bounds.width * currentPoint.x-3, y: 0, width: 6, height: bounds.height)
drawHueDragHandler(frame: handleRect)
}
func drawHueDragHandler(frame: CGRect) {
//// Polygon Drawing
let polygonPath = UIBezierPath()
polygonPath.move(to: CGPoint(x: frame.minX + 4, y: frame.maxY - 6))
polygonPath.addLine(to: CGPoint(x: frame.minX + 7.46, y: frame.maxY))
polygonPath.addLine(to: CGPoint(x: frame.minX + 0.54, y: frame.maxY))
polygonPath.close()
UIColor.black.setFill()
polygonPath.fill()
//// Polygon 2 Drawing
let polygon2Path = UIBezierPath()
polygon2Path.move(to: CGPoint(x: frame.minX + 4, y: frame.minY + 6))
polygon2Path.addLine(to: CGPoint(x: frame.minX + 7.46, y: frame.minY))
polygon2Path.addLine(to: CGPoint(x: frame.minX + 0.54, y: frame.minY))
polygon2Path.close()
UIColor.white.setFill()
polygon2Path.fill()
}
}
| 99d23013d9f9602ba7f939f72088e52f | 31.545455 | 167 | 0.52514 | false | false | false | false |
hgani/ganilib-ios | refs/heads/master | glib/Classes/JsonUi/Actions/JsonAction.swift | mit | 1 | open class JsonAction {
public let spec: Json
// public let screen: GScreen
// public var targetView: UIView? = nil
public let screen: UIViewController
public var targetView: UIView?
public var launch: LaunchHelper {
return LaunchHelper(screen)
}
public var nav: NavHelper {
return NavHelper(navController: GApp.instance.navigationController)
}
public required init(_ spec: Json, _ screen: UIViewController) {
self.spec = spec
self.screen = screen
}
public final func execute() {
if !silentExecute() {
GLog.w("Invalid action spec: \(spec)")
}
}
open func silentExecute() -> Bool {
fatalError("Need implementation")
}
private static func create(spec: Json, screen: UIViewController) -> JsonAction? {
if let klass = JsonUi.loadClass(name: spec["action"].stringValue, type: JsonAction.self) as? JsonAction.Type {
return klass.init(spec, screen)
}
GLog.w("Failed loading action: \(spec)")
return nil
}
public static func execute(spec: Json, screen: UIViewController, creator: UIView?) {
if let instance = create(spec: spec, screen: screen) {
instance.targetView = creator
instance.execute()
}
}
public static func execute(spec: Json, screen: UIViewController, creator: JsonAction) {
if let instance = create(spec: spec, screen: screen) {
instance.targetView = creator.targetView
instance.execute()
}
}
}
| 357632a96b9bac93a16a319ad967d5a3 | 28.867925 | 118 | 0.618446 | false | false | false | false |
leo150/Pelican | refs/heads/develop | Sources/Pelican/API/Types/Type+Custom.swift | mit | 1 |
import Foundation
import Vapor
import FluentProvider
/*
// Defines what the thumbnail is being used for.
enum InlineThumbnailType: String {
case contact
case document
case photo
case GIF // JPEG or GIF.
case mpeg4GIF // JPEG or GIF.
case video // JPEG only.
case location
}
// A thumbnail to represent a preview of an inline file. NOT FOR NORMAL FILE USE.
struct InlineThumbnail {
//var type: ThumbnailType
var url: String = ""
var width: Int = 0
var height: Int = 0
init () {
}
func getQuerySet() -> [String : CustomStringConvertible] {
var keys: [String:CustomStringConvertible] = [
"thumb_url": url]
if width != 0 { keys["thumb_width"] = width }
if height != 0 { keys["thumb_height"] = height }
return keys
}
// NodeRepresentable conforming methods
init(node: Node, in context: Context) throws {
//type = try node.extract("type")
url = try node.extract("thumb_url")
width = try node.extract("thumb_width")
height = try node.extract("thumb_height")
}
func makeNode() throws -> Node {
var keys: [String:NodeRepresentable] = [
"url": url
]
if width != 0 { keys["width"] = width }
if height != 0 { keys["height"] = height }
return try Node(node: keys)
}
func makeNode(context: Context) throws -> Node {
return try self.makeNode()
}
}
enum InputFileType {
case fileID(String)
case url(String)
}
// A type for handling files for sending.
class InputFile: NodeConvertible, JSONConvertible {
var type: InputFileType
// NodeRepresentable conforming methods
required init(node: Node, in context: Context) throws {
let fileID: String = try node.extract("file_id")
if fileID != "" {
type = .fileID(fileID)
}
else {
type = .url(try node.extract("url"))
}
}
func makeNode() throws -> Node {
var keys: [String:NodeRepresentable] = [:]
switch type{
case .fileID(let fileID):
keys["file_id"] = fileID
case .url(let url):
keys["url"] = url
}
return try Node(node: keys)
}
func makeNode(context: Context) throws -> Node {
return try self.makeNode()
}
}
*/
| a2c4a6f113bce9ec884b7351feb9ba0a | 20.980198 | 82 | 0.618468 | false | false | false | false |
dnseitz/YAPI | refs/heads/master | YAPI/YAPI/V2/V2_YelpPhoneSearchRequest.swift | mit | 1 | //
// YelpPhoneSearchRequest.swift
// YAPI
//
// Created by Daniel Seitz on 9/12/16.
// Copyright © 2016 Daniel Seitz. All rights reserved.
//
import Foundation
import OAuthSwift
public final class YelpV2PhoneSearchRequest : YelpRequest {
public typealias Response = YelpV2PhoneSearchResponse
public let oauthVersion: OAuthSwiftCredential.Version = .oauth1
public let path: String = YelpEndpoints.V2.phone
public let parameters: [String: String]
public let session: YelpHTTPClient
public var requestMethod: OAuthSwiftHTTPRequest.Method {
return .GET
}
init(phoneSearch: YelpV2PhoneSearchParameters, session: YelpHTTPClient = YelpHTTPClient.sharedSession) {
var parameters = [String: String]()
parameters.insertParameter(phoneSearch.phone)
if let countryCode = phoneSearch.countryCode {
parameters.insertParameter(countryCode)
}
if let category = phoneSearch.category {
parameters.insertParameter(category)
}
self.parameters = parameters
self.session = session
}
}
| 1578b165d238e689422b60e208ec06d6 | 28.027778 | 106 | 0.745455 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Neocom/Neocom/Killboard/zKillboard/ShipPickerGroups.swift | lgpl-2.1 | 2 | //
// ShipPickerGroups.swift
// Neocom
//
// Created by Artem Shimanski on 4/2/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import CoreData
import Expressible
struct ShipPickerGroups: View {
@Environment(\.managedObjectContext) private var managedObjectContext
@State private var selectedType: SDEInvType?
@Environment(\.self) private var environment
@EnvironmentObject private var sharedState: SharedState
var category: SDEInvCategory
var completion: (NSManagedObject) -> Void
private func getGroups() -> FetchedResultsController<SDEInvGroup> {
let controller = managedObjectContext.from(SDEInvGroup.self)
.filter(/\SDEInvGroup.category == category && /\SDEInvGroup.published == true)
.sort(by: \SDEInvGroup.groupName, ascending: true)
.fetchedResultsController(sectionName: /\SDEInvGroup.published)
return FetchedResultsController(controller)
}
private let groups = Lazy<FetchedResultsController<SDEInvGroup>, Never>()
@State private var searchString: String = ""
@State private var searchResults: [FetchedResultsController<SDEInvType>.Section]? = nil
var body: some View {
let groups = self.groups.get(initial: getGroups())
let predicate = /\SDEInvType.group?.category == self.category && /\SDEInvType.published == true
return TypesSearch(predicate: predicate, searchString: $searchString, searchResults: $searchResults) {
if self.searchResults != nil {
TypePickerTypesContent(types: self.searchResults!, selectedType: self.$selectedType, completion: self.completion)
}
else {
ShipPickerGroupsContent(groups: groups, completion: self.completion)
}
}
.navigationBarTitle(category.categoryName ?? NSLocalizedString("Categories", comment: ""))
.sheet(item: $selectedType) { type in
NavigationView {
TypeInfo(type: type).navigationBarItems(leading: BarButtonItems.close {self.selectedType = nil})
}
.modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState))
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
struct ShipPickerGroupsContent: View {
var groups: FetchedResultsController<SDEInvGroup>
var completion: (NSManagedObject) -> Void
var body: some View {
ForEach(groups.sections, id: \.name) { section in
Section(header: section.name == "0" ? Text("UNPUBLISHED") : Text("PUBLISHED")) {
ForEach(section.objects, id: \.objectID) { group in
NavigationLink(destination: ShipPickerTypes(parentGroup: group, completion: self.completion)) {
HStack {
GroupCell(group: group)
Spacer()
Button(NSLocalizedString("Select", comment: "")) {
self.completion(group)
}.foregroundColor(.blue)
}
}.buttonStyle(PlainButtonStyle())
}
}
}
}
}
struct ShipPickerTypes: View {
var parentGroup: SDEInvGroup
var completion: (SDEInvType) -> Void
@State private var selectedType: SDEInvType?
@Environment(\.managedObjectContext) private var managedObjectContext
@Environment(\.self) private var environment
@EnvironmentObject private var sharedState: SharedState
var predicate: PredicateProtocol {
/\SDEInvType.group == parentGroup && /\SDEInvType.published == true
}
private func getTypes() -> FetchedResultsController<SDEInvType> {
Types.fetchResults(with: predicate, managedObjectContext: managedObjectContext)
}
private let types = Lazy<FetchedResultsController<SDEInvType>, Never>()
@State private var searchString: String = ""
@State private var searchResults: [FetchedResultsController<SDEInvType>.Section]? = nil
var body: some View {
let types = self.types.get(initial: getTypes())
return TypesSearch(predicate: self.predicate, searchString: $searchString, searchResults: $searchResults) {
TypePickerTypesContent(types: self.searchResults ?? types.sections, selectedType: self.$selectedType, completion: self.completion)
}
.navigationBarTitle(parentGroup.groupName ?? "")
.sheet(item: $selectedType) { type in
NavigationView {
TypeInfo(type: type).navigationBarItems(leading: BarButtonItems.close {self.selectedType = nil})
}
.modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState))
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
#if DEBUG
struct ShipPickerGroups_Previews: PreviewProvider {
static var previews: some View {
let category = try? Storage.testStorage.persistentContainer.viewContext.from(SDEInvCategory.self).filter(/\SDEInvCategory.categoryID == SDECategoryID.ship.rawValue).first()
return NavigationView {
ShipPickerGroups(category: category!) { _ in}
}.modifier(ServicesViewModifier.testModifier())
}
}
#endif
| 2e6371107572fce644380abd7f7aa232 | 41.464567 | 180 | 0.6514 | false | false | false | false |
benzhipeng/HardChoice | refs/heads/master | HardChoice/DataKit/Wormhole.swift | mit | 3 | //
// Wormhole.swift
// HardChoice
//
// Created by 杨萧玉 on 15/4/3.
// Copyright (c) 2015年 杨萧玉. All rights reserved.
//
import CoreFoundation
public typealias MessageListenerBlock = (AnyObject) -> Void
let WormholeNotificationName = "WormholeNotificationName"
let center = CFNotificationCenterGetDarwinNotifyCenter()
let helpMethod = HelpMethod()
public class Wormhole: NSObject {
var applicationGroupIdentifier:String!
var directory:String?
var fileManager:NSFileManager!
var listenerBlocks:Dictionary<String, MessageListenerBlock>!
/**
初始化方法
:param: identifier AppGroup的Identifier
:param: dir 可选的文件夹名称
:returns: Wormhole实例对象
*/
public init(applicationGroupIdentifier identifier:String, optionalDirectory dir:String) {
super.init()
applicationGroupIdentifier = identifier
directory = dir
fileManager = NSFileManager()
listenerBlocks = Dictionary()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveMessageNotification:", name: WormholeNotificationName, object: nil)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
CFNotificationCenterRemoveEveryObserver(center, unsafeAddressOf(self))
}
// MARK: - Private File Operation Methods
func messagePassingDirectoryPath() -> String? {
var appGroupContainer = self.fileManager.containerURLForSecurityApplicationGroupIdentifier(applicationGroupIdentifier)
var appGroupContainerPath = appGroupContainer?.path
if directory != nil, var directoryPath = appGroupContainerPath {
directoryPath = directoryPath.stringByAppendingPathComponent(directory!)
fileManager.createDirectoryAtPath(directoryPath, withIntermediateDirectories: true, attributes: nil, error: nil)
return directoryPath
}
return nil
}
func filePathForIdentifier(identifier:String) -> String? {
if count(identifier) != 0, let directoryPath = messagePassingDirectoryPath() {
let fileName = "\(identifier).archive"
return directoryPath.stringByAppendingPathComponent(fileName)
}
return nil
}
func writeMessageObject(messageObject:AnyObject, toFileWithIdentifier identifier:String) {
var data = NSKeyedArchiver.archivedDataWithRootObject(messageObject)
if let filePath = filePathForIdentifier(identifier) {
if !data.writeToFile(filePath, atomically: true) {
return
}
else{
sendNotificationForMessageWithIdentifier(identifier)
}
}
}
func messageObjectFromFileWithIdentifier(identifier:String) -> AnyObject? {
if var data = NSData(contentsOfFile: filePathForIdentifier(identifier) ?? "") {
var messageObject: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(data)
return messageObject
}
return nil
}
func deleteFileForIdentifier(identifier:String) {
if let filePath = filePathForIdentifier(identifier) {
fileManager.removeItemAtPath(filePath, error: nil)
}
}
// MARK: - Private Notification Methods
func sendNotificationForMessageWithIdentifier(identifier:String) {
CFNotificationCenterPostNotification(center, identifier, nil, nil, 1)
}
func registerForNotificationsWithIdentifier(identifier:String) {
CFNotificationCenterAddObserver(center, unsafeAddressOf(self), helpMethod.callback, identifier, nil, CFNotificationSuspensionBehavior.DeliverImmediately)
}
func unregisterForNotificationsWithIdentifier(identifier:String) {
CFNotificationCenterRemoveObserver(center, unsafeAddressOf(self), identifier, nil)
}
// func wormholeNotificationCallback(center:CFNotificationCenter!, observer:UnsafeMutablePointer<Void>, name:CFString!, object:UnsafePointer<Void>, userInfo:CFDictionary!) {
// NSNotificationCenter.defaultCenter().postNotificationName(WormholeNotificationName, object: nil, userInfo: ["identifier":name])
// }
func didReceiveMessageNotification(notification:NSNotification) {
let userInfo = notification.userInfo
if let identifier = userInfo?["identifier"] as? String, let listenerBlock = listenerBlockForIdentifier(identifier), let messageObject: AnyObject = messageObjectFromFileWithIdentifier(identifier) {
listenerBlock(messageObject)
}
}
func listenerBlockForIdentifier(identifier:String) -> MessageListenerBlock? {
return listenerBlocks[identifier]
}
//MARK: - Public Interface Methods
public func passMessageObject(messageObject:AnyObject ,identifier:String) {
writeMessageObject(messageObject, toFileWithIdentifier: identifier)
}
public func messageWithIdentifier(identifier:String) -> AnyObject? {
return messageObjectFromFileWithIdentifier(identifier)
}
public func clearMessageContentsForIdentifier(identifier:String) {
deleteFileForIdentifier(identifier)
}
public func clearAllMessageContents() {
if directory != nil, let directoryPath = messagePassingDirectoryPath(), let messageFiles = fileManager.contentsOfDirectoryAtPath(directoryPath, error: nil) {
for path in messageFiles as! [String] {
fileManager.removeItemAtPath(directoryPath.stringByAppendingPathComponent(path), error: nil)
}
}
}
public func listenForMessageWithIdentifier(identifier:String, listener:MessageListenerBlock) {
listenerBlocks[identifier] = listener
registerForNotificationsWithIdentifier(identifier)
}
public func stopListeningForMessageWithIdentifier(identifier:String) {
listenerBlocks[identifier] = nil
unregisterForNotificationsWithIdentifier(identifier)
}
}
| 9996f32adda823994b608ab2f0b110f7 | 38.715232 | 204 | 0.710522 | false | false | false | false |
audiokit/AudioKit | refs/heads/v5-develop | Tests/AudioKitTests/MIDI Tests/Support/UMPSysex.swift | mit | 1 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
private extension UInt8 {
init(highNibble: UInt8, lowNibble: UInt8) {
self = highNibble << 4 + lowNibble & 0x0F
}
var highNibble: UInt8 {
self >> 4
}
var lowNibble: UInt8 {
self & 0x0F
}
}
// simple convenience struct for creating ump sysex for testing
struct UMPSysex {
enum UMPType: UInt8 {
// from Universal MIDI Packet (UMP) Format spec
case utility = 0 // 1 word
case system = 1 // 1 word
case channelVoice1 = 2 // 1 word
case sysex = 3 // 2 words
case channelVoice2 = 4 // 2 words
case data128 = 5 // 4 words
case reserved6 = 6 // 1 word
case reserved7 = 7 // 1 word
case reserved8 = 8 // 2 words
case reserved9 = 9 // 2 words
case reserved10 = 10 // 2 words
case reserved11 = 11 // 3 words
case reserved12 = 12 // 3 words
case reserved13 = 13 // 4 words
case reserved14 = 14 // 4 words
case reserved15 = 15 // 4 words
init(_ byte0: UInt8) {
self = UMPType(rawValue: byte0.highNibble)!
}
}
enum UMPSysexType: UInt8 {
// from Universal MIDI Packet (UMP) Format spec
case complete = 0
case start = 1
case `continue` = 2
case end = 3
}
struct UMP64 {
var word0: UInt32 = 0
var word1: UInt32 = 0
}
let umpBigEndian: UMP64
init(group: UInt8 = 0, type: UMPSysexType, data: [UInt8]) {
var ump = UMP64()
let numBytes = min(data.count, 6)
let dataRange = 2..<2+numBytes
withUnsafeMutableBytes(of: &ump) {
$0[0] = .init(highNibble: UMPType.sysex.rawValue, lowNibble: group)
$0[1] = .init(highNibble: type.rawValue, lowNibble: UInt8(numBytes))
let buffer = UnsafeMutableRawBufferPointer(rebasing: $0[dataRange])
buffer.copyBytes(from: data[0..<numBytes])
}
self.umpBigEndian = ump
}
init(word0: UInt32, word1: UInt32) {
umpBigEndian = .init(word0: .init(bigEndian:word0),
word1: .init(bigEndian:word1))
}
var umpType: UMPType {
withUnsafeBytes(of: umpBigEndian) { UMPType($0[0]) }
}
var group: UInt8 {
withUnsafeBytes(of: umpBigEndian) { $0[0].lowNibble }
}
var status: UMPSysexType {
withUnsafeBytes(of: umpBigEndian) {
UMPSysexType(rawValue: $0[1].highNibble)!
}
}
var numDataBytes: Int {
withUnsafeBytes(of: umpBigEndian) { Int($0[1].lowNibble) }
}
var dataRange: Range<Int> {
2..<2+numDataBytes
}
var data: [UInt8] {
withUnsafeBytes(of: umpBigEndian) { .init($0[dataRange]) }
}
var word0: UInt32 {
.init(bigEndian: umpBigEndian.word0)
}
var word1: UInt32 {
.init(bigEndian: umpBigEndian.word1)
}
var words: [UInt32] {
[word0, word1]
}
static func sysexComplete(group: UInt8 = 0, data: [UInt8]) -> Self {
.init(group: group, type: .complete, data: data)
}
static func sysexStart(group: UInt8 = 0, data: [UInt8]) -> Self {
.init(group: group, type: .start, data: data)
}
static func sysexContinue(group: UInt8 = 0, data: [UInt8]) -> Self {
.init(group: group, type: .continue, data: data)
}
static func sysexEnd(group: UInt8 = 0, data: [UInt8]) -> Self {
.init(group: group, type: .end, data: data)
}
}
| 7e16a9bd75ff4ea4373a3713f2883208 | 28.148438 | 100 | 0.547038 | false | false | false | false |
martinLilili/JSONModelWithMirror | refs/heads/master | JSONModel/ViewController.swift | mit | 1 | //
// ViewController.swift
// JSONModel
//
// Created by UBT on 2016/12/5.
// Copyright © 2016年 martin. All rights reserved.
//
import UIKit
//电话结构体
struct Telephone {
var title:String //电话标题
var number:String //电话号码
}
extension Telephone: JSON { }
//用户类
class User : JSONModel {
var name:String = "" //姓名
var nickname:String? //昵称
var age:Int = 0 //年龄
var emails:[String]? //邮件地址
// var tels:[Telephone]? //电话
}
class Student: User {
var accountID : Int = 0
}
class SchoolStudent: Student {
var schoolName : String?
var schoolmates : [Student]?
var principal : User?
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// testUser()
//
// testStudent()
var any: Any
// any = nil
var op : String?
op = nil
any = op
print(any)
print(any == nil)
testSchoolStudent()
}
func testUser() {
//创建一个User实例对象
let user = User()
user.name = "hangge"
user.age = 100
user.emails = ["[email protected]","[email protected]"]
//添加动画
// let tel1 = Telephone(title: "手机", number: "123456")
// let tel2 = Telephone(title: "公司座机", number: "001-0358")
// user.tels = [tel1, tel2]
//输出json字符串
print("user = \(user)")
}
func testStudent() {
//创建一个student实例对象
let student = Student()
student.accountID = 2009
student.name = "hangge"
student.age = 100
student.emails = ["[email protected]","[email protected]"]
//添加动画
// let tel1 = Telephone(title: "手机", number: "123456")
// let tel2 = Telephone(title: "公司座机", number: "001-0358")
// student.tels = [tel1, tel2]
//输出json字符串
print("student = \(student)")
}
func testSchoolStudent() {
//创建一个schoolstudent实例对象
let schoolstudent = SchoolStudent()
schoolstudent.schoolName = "清华大学"
schoolstudent.accountID = 1024
schoolstudent.name = "martin"
schoolstudent.age = 20
let principal = User()
principal.name = "校长"
principal.age = 60
principal.emails = ["[email protected]","[email protected]"]
schoolstudent.principal = principal
let student1 = Student()
student1.accountID = 2009
student1.name = "martin"
student1.age = 25
student1.emails = ["[email protected]","[email protected]"]
// //添加手机
// let tel1 = Telephone(title: "手机", number: "123456")
// let tel2 = Telephone(title: "公司座机", number: "001-0358")
// student1.tels = [tel1, tel2]
let student2 = Student()
student2.accountID = 2008
student2.name = "james"
student2.age = 26
student2.emails = ["[email protected]","[email protected]"]
// //添加手机
// let tel3 = Telephone(title: "手机", number: "123456")
// let tel4 = Telephone(title: "公司座机", number: "001-0358")
// student2.tels = [tel3, tel4]
schoolstudent.schoolmates = [student1, student2]
//输出json字符串
print("school student = \(schoolstudent)")
let a = NSKeyedArchiver.archivedData(withRootObject: schoolstudent)
let b = NSKeyedUnarchiver.unarchiveObject(with: a)
print("unarchiveObject = \(b)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 82a485bd938caeda783f9ff3e65352ec | 24.390728 | 80 | 0.547731 | false | false | false | false |
FredrikSjoberg/KFDataStructures | refs/heads/master | KFDataStructures/Swift/UniqueQueue.swift | mit | 1 | //
// UniqueQueue.swift
// KFDataStructures
//
// Created by Fredrik Sjöberg on 24/09/15.
// Copyright © 2015 Fredrik Sjoberg. All rights reserved.
//
import Foundation
public struct UniqueQueue<Element: Hashable> {
fileprivate var contents:[Element]
fileprivate var uniques: Set<Element>
public init() {
contents = []
uniques = Set()
}
}
extension UniqueQueue : DynamicQueueType {
public mutating func push(element: Element) {
if !uniques.contains(element) {
contents.append(element)
uniques.insert(element)
}
}
public mutating func pop() -> Element? {
guard !contents.isEmpty else { return nil }
let element = contents.removeFirst() // NOTE: removeFirst() is O(self.count), we need O(1). Doubly-Linked-List?
uniques.remove(element)
return element
}
public mutating func invalidate(element: Element) {
guard !contents.isEmpty else { return }
guard let index = contents.index(of: element) else { return }
contents.remove(at: index)
uniques.remove(element)
}
public func peek() -> Element? {
return contents.first
}
}
extension UniqueQueue : Collection {
public var startIndex: Int {
return contents.startIndex
}
public var endIndex: Int {
return contents.endIndex
}
public subscript(index: Int) -> Element {
return contents[index]
}
public func index(after i: Int) -> Int {
return i + 1
}
}
extension UniqueQueue : ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Element...) {
uniques = Set(elements)
contents = []
contents += elements.filter{ uniques.contains($0) }
}
}
extension UniqueQueue : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String { return contents.description }
public var debugDescription: String { return contents.debugDescription }
}
| 179bdc4dcdc2ff73f17b3501ffbd027e | 24.45 | 119 | 0.633104 | false | false | false | false |
ScoutHarris/WordPress-iOS | refs/heads/develop | WordPress/Classes/Models/Domain.swift | gpl-2.0 | 2 | import Foundation
import CoreData
import WordPressKit
public typealias Domain = RemoteDomain
extension Domain {
init(managedDomain: ManagedDomain) {
domainName = managedDomain.domainName
isPrimaryDomain = managedDomain.isPrimary
domainType = managedDomain.domainType
}
}
class ManagedDomain: NSManagedObject {
// MARK: - NSManagedObject
override class var entityName: String {
return "Domain"
}
struct Attributes {
static let domainName = "domainName"
static let isPrimary = "isPrimary"
static let domainType = "domainType"
}
struct Relationships {
static let blog = "blog"
}
@NSManaged var domainName: String
@NSManaged var isPrimary: Bool
@NSManaged var domainType: DomainType
@NSManaged var blog: Blog
func updateWith(_ domain: Domain, blog: Blog) {
self.domainName = domain.domainName
self.isPrimary = domain.isPrimaryDomain
self.domainType = domain.domainType
self.blog = blog
}
}
extension Domain: Equatable {}
public func ==(lhs: Domain, rhs: Domain) -> Bool {
return lhs.domainName == rhs.domainName &&
lhs.domainType == rhs.domainType &&
lhs.isPrimaryDomain == rhs.isPrimaryDomain
}
| 2bae0a74f7c585725af76819c5440a1d | 23.596154 | 51 | 0.670055 | false | false | false | false |
josepvaleriano/iOS-practices | refs/heads/master | PetCent/PetCent/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// PetCent
//
// Created by Infraestructura on 14/10/16.
// Copyright © 2016 Valeriano Lopez. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
//let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
//let origen = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PetCent.sqlite")
// 1 Encontrar la unicacion de la BD origen ees en resource con nsbundel
let origen = NSBundle.mainBundle().pathForResource("PetCens", ofType: "sqlite")
// 2 Obtener la ubicacion destino
let destino = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PetCens.sqlite")
//3. valida si la DB no exite en el dfestino
if NSFileManager.defaultManager().fileExistsAtPath(destino.path!){
return true;
}
else{
do{
try NSFileManager.defaultManager().copyItemAtPath(origen!, toPath: destino.path!)
print("\tCopio datos de t \(origen) \t al destino \(destino.path)")
}
catch{
print("\tNo puede copiar de t \(origen) \t al destino \(destino.path)")
abort()
}
}
return true
//4
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let controller = masterNavigationController.topViewController as! MasterViewController
controller.managedObjectContext = self.managedObjectContext
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
// 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 "mx.com.lpz.valeriano.PetCent" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
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("PetCens", 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. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PetCens.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| d6c50585d82afa798597b444e098193e | 53.956522 | 291 | 0.713834 | false | false | false | false |
fahidattique55/FAPanels | refs/heads/master | FAPanels/IQKeyboardManagerSwift/Categories/IQUIWindow+Hierarchy.swift | apache-2.0 | 1 | //
// IQUIWindow+Hierarchy.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// 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
/** @abstract UIWindow hierarchy category. */
public extension UIWindow {
/** @return Returns the current Top Most ViewController in hierarchy. */
public func topMostControllerOfWindow()->UIViewController? {
var topController = rootViewController
while let presentedController = topController?.presentedViewController {
topController = presentedController
}
return topController
}
/** @return Returns the topViewController in stack of topMostController. */
public func currentViewController()->UIViewController? {
var currentViewController = topMostControllerOfWindow()
while currentViewController != nil && currentViewController is UINavigationController && (currentViewController as! UINavigationController).topViewController != nil {
currentViewController = (currentViewController as! UINavigationController).topViewController
}
return currentViewController
}
}
| 981dd03e666ba4be68d0099b43208087 | 41.566038 | 174 | 0.73094 | false | false | false | false |
lanserxt/teamwork-ios-sdk | refs/heads/master | TeamWorkClient/TeamWorkClient/Requests/TWApiClient+PeopleStatuses.swift | mit | 1 | //
// TWApiClient+Invoices.swift
// TeamWorkClient
//
// Created by Anton Gubarenko on 02.02.17.
// Copyright © 2017 Anton Gubarenko. All rights reserved.
//
import Foundation
import Alamofire
extension TWApiClient{
func createStatus(userStatus: UserStatus, _ responseBlock: @escaping (Bool, Int, String?, Error?) -> Void){
let parameters: [String : Any] = ["userstatus" : userStatus.dictionaryRepresentation() as! [String: Any]]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.createStatus.path), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.createStatus.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, JSON.object(forKey: "id") as! String?, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func createStatusForPerson(personId: String, userStatus: UserStatus, _ responseBlock: @escaping (Bool, Int, String?, Error?) -> Void){
let parameters: [String : Any] = ["userstatus" : userStatus.dictionaryRepresentation() as! [String: Any]]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.createStatusForPerson.path, personId), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.createStatusForPerson.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, JSON.object(forKey: "id") as! String?, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func updateStatus(statusId: String, userStatus: UserStatus, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
let parameters: [String : Any] = ["userstatus" : userStatus.dictionaryRepresentation() as! [String: Any]]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updateStatus.path, statusId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.updateStatus.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func updatePeopleStatus(statusId: String, userStatus: UserStatus, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
let parameters: [String : Any] = ["userstatus" : userStatus.dictionaryRepresentation() as! [String: Any]]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updatePeopleStatus.path, statusId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.updatePeopleStatus.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func updateStatusForPeople(personId: String, statusId: String, userStatus: UserStatus, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
let parameters: [String : Any] = ["userstatus" : userStatus.dictionaryRepresentation() as! [String: Any]]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.editUser.path, personId, statusId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.editUser.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func deleteStatus(statusId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteStatus.path, statusId), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.deleteStatus.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func deletePeopleStatus(statusId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deletePeopleStatus.path, statusId), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.deletePeopleStatus.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func deleteStatusForPeople(personId: String, statusId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteStatusForPeople.path, personId, statusId), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.deleteStatusForPeople.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func getCurrentUserStatus(_ responseBlock: @escaping (Bool, Int, [UserStatus]?, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getCurrentUserStatus.path), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = MultipleResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.getCurrentUserStatus.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, responseContainer.rootObjects, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func getPeopleStatus(peopleId: String, _ responseBlock: @escaping (Bool, Int, [UserStatus]?, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getPeopleStatus.path, peopleId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = MultipleResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.getPeopleStatus.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, responseContainer.rootObjects, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func getAllStatuses(_ responseBlock: @escaping (Bool, Int, [UserStatus]?, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getAllStatuses.path), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = MultipleResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.getAllStatuses.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, responseContainer.rootObjects, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
}
| 93fb8085cd73de762bf0a7dea75241d4 | 53.425714 | 223 | 0.533834 | false | false | false | false |
mcxiaoke/learning-ios | refs/heads/master | osx-apps/GeoPhotos/GeoPhotos/DecimalOnlyNumberFormatter.swift | apache-2.0 | 1 | //
// DecimalOnlyNumberFormatter.swift
// GeoPhotos
//
// Created by mcxiaoke on 16/6/9.
// Copyright © 2016年 mcxiaoke. All rights reserved.
//
import Cocoa
class DecimalOnlyNumberFormatter: NSNumberFormatter {
override func awakeFromNib() {
super.awakeFromNib()
self.setUp()
}
private func setUp(){
self.allowsFloats = true
self.numberStyle = NSNumberFormatterStyle.DecimalStyle
self.maximumFractionDigits = 8
}
override func isPartialStringValid(partialStringPtr: AutoreleasingUnsafeMutablePointer<NSString?>, proposedSelectedRange proposedSelRangePtr: NSRangePointer, originalString origString: String, originalSelectedRange origSelRange: NSRange, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool {
guard let partialString = partialStringPtr.memory as? String else { return true }
return !partialString.isEmpty && Double(partialString) != nil
}
}
| 0def6b4c2c6a774c0e6dc2832c23a120 | 30.2 | 319 | 0.762821 | false | false | false | false |
koden-km/dialekt-swift | refs/heads/develop | Dialekt/Parser/ExpressionParser.swift | mit | 1 | public class ExpressionParser: AbstractParser {
public var logicalOrByDefault = false
internal override func parseExpression() -> AbstractExpression! {
startExpression()
var expression = parseUnaryExpression()
if expression != nil {
expression = parseCompoundExpression(expression)
}
if expression == nil {
return nil
}
endExpression(expression)
return expression
}
private func parseUnaryExpression() -> AbstractExpression! {
let foundExpected = expectToken(
TokenType.Text,
TokenType.LogicalNot,
TokenType.OpenBracket
)
if !foundExpected {
return nil
}
if TokenType.LogicalNot == _currentToken.tokenType {
return parseLogicalNot()
} else if TokenType.OpenBracket == _currentToken.tokenType {
return parseNestedExpression()
} else if _currentToken.value.rangeOfString(wildcardString, options: NSStringCompareOptions.LiteralSearch) == nil {
return parseTag()
} else {
return parsePattern()
}
}
private func parseTag() -> AbstractExpression {
startExpression()
let expression = Tag(
_currentToken.value
)
nextToken()
endExpression(expression)
return expression
}
private func parsePattern() -> AbstractExpression {
startExpression()
// Note:
// Could not get regex to escape wildcardString correctly for splitting with capture.
// Using string split for now.
let parts = _currentToken.value.componentsSeparatedByString(wildcardString)
let expression = Pattern()
if _currentToken.value.hasPrefix(wildcardString) {
expression.add(PatternWildcard())
}
var chunks = parts.count - 1
for value in parts {
expression.add(PatternLiteral(value))
if chunks > 1 {
--chunks
expression.add(PatternWildcard())
}
}
if _currentToken.value.hasSuffix(wildcardString) {
expression.add(PatternWildcard())
}
nextToken()
endExpression(expression)
return expression
}
private func parseNestedExpression() -> AbstractExpression! {
startExpression()
nextToken()
let expression = parseExpression()
if expression == nil {
return nil
}
let foundExpected = expectToken(TokenType.CloseBracket)
if !foundExpected {
return nil
}
nextToken()
endExpression(expression)
return expression
}
private func parseLogicalNot() -> AbstractExpression {
startExpression()
nextToken()
let expression = LogicalNot(
parseUnaryExpression()
)
endExpression(expression)
return expression
}
private func parseCompoundExpression(expression: ExpressionProtocol, minimumPrecedence: Int = 0) -> AbstractExpression! {
var leftExpression = expression
var allowCollapse = false
while true {
// Parse the operator and determine whether or not it's explicit ...
let (oper, isExplicit) = parseOperator()
let precedence = operatorPrecedence(oper)
// Abort if the operator's precedence is less than what we're looking for ...
if precedence < minimumPrecedence {
break
}
// Advance the token pointer if an explicit operator token was found ...
if isExplicit {
nextToken()
}
// Parse the expression to the right of the operator ...
var rightExpression = parseUnaryExpression()
if rightExpression == nil {
return nil
}
// Only parse additional compound expressions if their precedence is greater than the
// expression already being parsed ...
let (nextOperator, _) = parseOperator()
if precedence < operatorPrecedence(nextOperator) {
rightExpression = parseCompoundExpression(rightExpression, minimumPrecedence: precedence + 1)
if rightExpression == nil {
return nil
}
}
// Combine the parsed expression with the existing expression ...
// Collapse the expression into an existing expression of the same type ...
if oper == TokenType.LogicalAnd {
if allowCollapse && leftExpression is LogicalAnd {
(leftExpression as LogicalAnd).add(rightExpression)
} else {
leftExpression = LogicalAnd(leftExpression, rightExpression)
allowCollapse = true
}
} else if oper == TokenType.LogicalOr {
if allowCollapse && leftExpression is LogicalOr {
(leftExpression as LogicalOr).add(rightExpression)
} else {
leftExpression = LogicalOr(leftExpression, rightExpression)
allowCollapse = true
}
} else {
fatalError("Unknown operator type.")
}
}
return leftExpression as AbstractExpression
}
private func parseOperator() -> (oper: TokenType?, isExplicit: Bool) {
// End of input ...
if _currentToken == nil {
return (nil, false)
// Closing bracket ...
} else if TokenType.CloseBracket == _currentToken.tokenType {
return (nil, false)
// Explicit logical OR ...
} else if TokenType.LogicalOr == _currentToken.tokenType {
return (TokenType.LogicalOr, true)
// Explicit logical AND ...
} else if TokenType.LogicalAnd == _currentToken.tokenType {
return (TokenType.LogicalAnd, true)
// Implicit logical OR ...
} else if logicalOrByDefault {
return (TokenType.LogicalOr, false)
// Implicit logical AND ...
} else {
return (TokenType.LogicalAnd, false)
}
}
private func operatorPrecedence(oper: TokenType?) -> Int {
if oper == TokenType.LogicalAnd {
return 1
} else if oper == TokenType.LogicalOr {
return 0
} else {
return -1
}
}
}
| 836ee2c4a55021bbeeeaaf8bdb5f59a6 | 29.637209 | 125 | 0.56991 | false | false | false | false |
cybertk/CKTextFieldTableCell | refs/heads/master | CKTextFieldTableCell/CKTextFieldTableCell.swift | mit | 1 | //
// CKTextFieldTableCell.swift
// CKTextFieldTableCell
//
// Copyright © 2015 cybertk. All rights reserved.
//
import UIKit
public class CKTextFieldTableCell : UITableViewCell {
// MARK: Internal Properties
// MARK: APIs
@IBOutlet var textField: UITextField!
@IBInspectable public var enableFixedTitleWidth: Bool = false
@IBInspectable public var titleWidth: Int = 100
// MARK: Initilizers
// MARK: Overrides
public override func awakeFromNib() {
super.awakeFromNib();
guard let textField = textField else {
print("Warnning: You must set textField in IB")
return
}
// Customize TableCell
selectionStyle = .None
textField.translatesAutoresizingMaskIntoConstraints = false
textLabel?.translatesAutoresizingMaskIntoConstraints = false
setupConstraints()
}
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
if (textField!.isFirstResponder() && event?.touchesForView(textField) == nil) {
// textField lost focus
textField!.endEditing(true)
}
}
// MRAK: Priviate
private func constraintsWithVisualFormat(format: String, _ options: NSLayoutFormatOptions) -> [NSLayoutConstraint] {
let views = [
"textLabel": textLabel!,
"textField": textField!,
"superview": contentView
]
return NSLayoutConstraint.constraintsWithVisualFormat(format, options: options, metrics: nil, views: views)
}
private func setupConstraints() {
var constraints: [NSLayoutConstraint] = []
// VFL Syntax, see https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage/VisualFormatLanguage.html#//apple_ref/doc/uid/TP40010853-CH3-SW1
// Horizontal constraints
if enableFixedTitleWidth {
textLabel!.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
constraints += constraintsWithVisualFormat("H:|-15-[textLabel(\(titleWidth))]-20-[textField]-|", .AlignAllCenterY)
} else {
constraints += constraintsWithVisualFormat("H:|-15-[textLabel]-20-[textField]-|", .AlignAllCenterY)
// Remove empty space of textLabel
textLabel!.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Horizontal)
}
// Vertical constraints
constraints += constraintsWithVisualFormat("H:[superview]-(<=1)-[textLabel]", .AlignAllCenterY)
contentView.addConstraints(constraints)
}
}
| de91faa8ab6c0681aac6cd7d5f1957b1 | 31.988372 | 205 | 0.642228 | false | false | false | false |
watson-developer-cloud/ios-sdk | refs/heads/master | Sources/LanguageTranslatorV3/Models/TranslationModel.swift | apache-2.0 | 1 | /**
* (C) Copyright IBM Corp. 2018, 2020.
*
* 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
/**
Response payload for models.
*/
public struct TranslationModel: Codable, Equatable {
/**
Availability of a model.
*/
public enum Status: String {
case uploading = "uploading"
case uploaded = "uploaded"
case dispatching = "dispatching"
case queued = "queued"
case training = "training"
case trained = "trained"
case publishing = "publishing"
case available = "available"
case deleted = "deleted"
case error = "error"
}
/**
A globally unique string that identifies the underlying model that is used for translation.
*/
public var modelID: String
/**
Optional name that can be specified when the model is created.
*/
public var name: String?
/**
Translation source language code.
*/
public var source: String?
/**
Translation target language code.
*/
public var target: String?
/**
Model ID of the base model that was used to customize the model. If the model is not a custom model, this will be
an empty string.
*/
public var baseModelID: String?
/**
The domain of the translation model.
*/
public var domain: String?
/**
Whether this model can be used as a base for customization. Customized models are not further customizable, and
some base models are not customizable.
*/
public var customizable: Bool?
/**
Whether or not the model is a default model. A default model is the model for a given language pair that will be
used when that language pair is specified in the source and target parameters.
*/
public var defaultModel: Bool?
/**
Either an empty string, indicating the model is not a custom model, or the ID of the service instance that created
the model.
*/
public var owner: String?
/**
Availability of a model.
*/
public var status: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case modelID = "model_id"
case name = "name"
case source = "source"
case target = "target"
case baseModelID = "base_model_id"
case domain = "domain"
case customizable = "customizable"
case defaultModel = "default_model"
case owner = "owner"
case status = "status"
}
}
| 0b577a4e796fb8b51ac1e7fd0bf63e82 | 27.518519 | 119 | 0.646104 | false | false | false | false |
hooman/swift | refs/heads/main | test/Interop/Cxx/static/static-var-silgen.swift | apache-2.0 | 5 | // RUN: %target-swift-emit-sil -I %S/Inputs -enable-cxx-interop %s | %FileCheck %s
import StaticVar
func initStaticVars() -> CInt {
return staticVar + staticVarInit + staticVarInlineInit + staticConst + staticConstInit
+ staticConstInlineInit + staticConstexpr + staticNonTrivial.val + staticConstNonTrivial.val
+ staticConstexprNonTrivial.val
}
// Constexpr globals should be inlined and removed.
// CHECK-NOT: sil_global public_external [let] @staticConstexpr : $Int32
// CHECK: // clang name: staticVar
// CHECK: sil_global public_external @staticVar : $Int32
// CHECK: // clang name: staticVarInit
// CHECK: sil_global public_external @staticVarInit : $Int32
// CHECK: // clang name: staticVarInlineInit
// CHECK: sil_global public_external @staticVarInlineInit : $Int32
// CHECK: // clang name: staticConst
// CHECK: sil_global public_external [let] @staticConst : $Int32
// CHECK: // clang name: staticConstInit
// CHECK: sil_global public_external [let] @staticConstInit : $Int32
// CHECK: // clang name: staticConstInlineInit
// CHECK: sil_global public_external [let] @staticConstInlineInit : $Int32
// CHECK: // clang name: staticNonTrivial
// CHECK: sil_global public_external @staticNonTrivial : $NonTrivial
// CHECK: // clang name: staticConstNonTrivial
// CHECK: sil_global public_external [let] @staticConstNonTrivial : $NonTrivial
// CHECK: // clang name: staticConstexprNonTrivial
// CHECK: sil_global public_external [let] @staticConstexprNonTrivial : $NonTrivial
func readStaticVar() -> CInt {
return staticVar
}
// CHECK: sil hidden @$s4main13readStaticVars5Int32VyF : $@convention(thin) () -> Int32
// CHECK: [[ADDR:%.*]] = global_addr @staticVar : $*Int32
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int32
// CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*Int32
// CHECK: return [[VALUE]] : $Int32
func writeStaticVar(_ v: CInt) {
staticVar = v
}
// CHECK: sil hidden @$s4main14writeStaticVaryys5Int32VF : $@convention(thin) (Int32) -> ()
// CHECK: [[ADDR:%.*]] = global_addr @staticVar : $*Int32
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int32
// CHECK: store %0 to [[ACCESS]] : $*Int32
func readStaticNonTrivial() -> NonTrivial {
return staticNonTrivial
}
// CHECK: sil hidden @$s4main20readStaticNonTrivialSo0dE0VyF : $@convention(thin) () -> NonTrivial
// CHECK: [[ADDR:%.*]] = global_addr @staticNonTrivial : $*NonTrivial
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*NonTrivial
// CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*NonTrivial
// CHECK: return [[VALUE]] : $NonTrivial
func writeStaticNonTrivial(_ i: NonTrivial) {
staticNonTrivial = i
}
// CHECK: sil hidden @$s4main21writeStaticNonTrivialyySo0dE0VF : $@convention(thin) (NonTrivial) -> ()
// CHECK: [[ADDR:%.*]] = global_addr @staticNonTrivial : $*NonTrivial
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*NonTrivial
// CHECK: store %0 to [[ACCESS]] : $*NonTrivial
func modifyInout(_ c: inout CInt) {
c = 42
}
func passingVarAsInout() {
modifyInout(&staticVar)
}
// CHECK: sil hidden @$s4main17passingVarAsInoutyyF : $@convention(thin) () -> ()
// CHECK: [[ADDR:%.*]] = global_addr @staticVar : $*Int32
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int32
// CHECK: [[FUNC:%.*]] = function_ref @$s4main11modifyInoutyys5Int32VzF : $@convention(thin) (@inout Int32) -> ()
// CHECK: apply [[FUNC]]([[ACCESS]]) : $@convention(thin) (@inout Int32) -> ()
| 8a047cc0b7e997c38934d7713e17a17c | 41.156627 | 113 | 0.684481 | false | false | false | false |
darina/omim | refs/heads/master | iphone/Maps/UI/PlacePage/Components/ActionBarViewController.swift | apache-2.0 | 5 | protocol ActionBarViewControllerDelegate: AnyObject {
func actionBar(_ actionBar: ActionBarViewController, didPressButton type: ActionBarButtonType)
}
class ActionBarViewController: UIViewController {
@IBOutlet var stackView: UIStackView!
var downloadButton: ActionBarButton? = nil
var popoverSourceView: UIView? {
stackView.arrangedSubviews.last
}
var placePageData: PlacePageData!
var isRoutePlanning = false
var canAddStop = false
private var visibleButtons: [ActionBarButtonType] = []
private var additionalButtons: [ActionBarButtonType] = []
weak var delegate: ActionBarViewControllerDelegate?
private func configureButtons() {
if placePageData.isRoutePoint {
visibleButtons.append(.routeRemoveStop)
} else if placePageData.roadType != .none {
switch placePageData.roadType {
case .toll:
visibleButtons.append(.avoidToll)
case .ferry:
visibleButtons.append(.avoidFerry)
case .dirty:
visibleButtons.append(.avoidDirty)
default:
fatalError()
}
} else {
configButton1()
configButton2()
configButton3()
configButton4()
}
for buttonType in visibleButtons {
let (selected, enabled) = buttonState(buttonType)
let button = ActionBarButton(delegate: self,
buttonType: buttonType,
partnerIndex: placePageData.partnerIndex,
isSelected: selected,
isEnabled: enabled)
stackView.addArrangedSubview(button)
if buttonType == .download {
downloadButton = button
updateDownloadButtonState(placePageData.mapNodeAttributes!.nodeStatus)
}
}
}
func resetButtons() {
stackView.arrangedSubviews.forEach {
stackView.removeArrangedSubview($0)
$0.removeFromSuperview()
}
visibleButtons.removeAll()
additionalButtons.removeAll()
downloadButton = nil
configureButtons()
}
override func viewDidLoad() {
super.viewDidLoad()
configureButtons()
}
func updateDownloadButtonState(_ nodeStatus: MapNodeStatus) {
guard let downloadButton = downloadButton, let mapNodeAttributes = placePageData.mapNodeAttributes else { return }
switch mapNodeAttributes.nodeStatus {
case .downloading:
downloadButton.mapDownloadProgress?.state = .progress
case .applying, .inQueue:
downloadButton.mapDownloadProgress?.state = .spinner
case .error:
downloadButton.mapDownloadProgress?.state = .failed
case .onDisk, .undefined, .onDiskOutOfDate:
downloadButton.mapDownloadProgress?.state = .completed
case .notDownloaded, .partly:
downloadButton.mapDownloadProgress?.state = .normal
@unknown default:
fatalError()
}
}
private func configButton1() {
if let mapNodeAttributes = placePageData.mapNodeAttributes {
switch mapNodeAttributes.nodeStatus {
case .onDiskOutOfDate, .onDisk, .undefined:
break
case .downloading, .applying, .inQueue, .error, .notDownloaded, .partly:
visibleButtons.append(.download)
return
@unknown default:
fatalError()
}
}
var buttons: [ActionBarButtonType] = []
if isRoutePlanning {
buttons.append(.routeFrom)
}
if placePageData.previewData.isBookingPlace {
buttons.append(.booking)
}
if placePageData.isPartner {
buttons.append(.partner)
}
if placePageData.bookingSearchUrl != nil {
buttons.append(.bookingSearch)
}
if placePageData.infoData?.phone != nil, AppInfo.shared().canMakeCalls {
buttons.append(.call)
}
if !isRoutePlanning {
buttons.append(.routeFrom)
}
assert(buttons.count > 0)
visibleButtons.append(buttons[0])
if buttons.count > 1 {
additionalButtons.append(contentsOf: buttons.suffix(from: 1))
}
}
private func configButton2() {
var buttons: [ActionBarButtonType] = []
if canAddStop {
buttons.append(.routeAddStop)
}
buttons.append(.bookmark)
assert(buttons.count > 0)
visibleButtons.append(buttons[0])
if buttons.count > 1 {
additionalButtons.append(contentsOf: buttons.suffix(from: 1))
}
}
private func configButton3() {
visibleButtons.append(.routeTo)
}
private func configButton4() {
if additionalButtons.isEmpty {
visibleButtons.append(.share)
} else {
additionalButtons.append(.share)
visibleButtons.append(.more)
}
}
private func showMore() {
let actionSheet = UIAlertController(title: placePageData.previewData.title,
message: placePageData.previewData.subtitle,
preferredStyle: .actionSheet)
for button in additionalButtons {
let (selected, enabled) = buttonState(button)
let action = UIAlertAction(title: titleForButton(button, placePageData.partnerIndex, selected),
style: .default,
handler: { [weak self] _ in
guard let self = self else { return }
self.delegate?.actionBar(self, didPressButton: button)
})
action.isEnabled = enabled
actionSheet.addAction(action)
}
actionSheet.addAction(UIAlertAction(title: L("cancel"), style: .cancel))
if let popover = actionSheet.popoverPresentationController, let sourceView = stackView.arrangedSubviews.last {
popover.sourceView = sourceView
popover.sourceRect = sourceView.bounds
}
present(actionSheet, animated: true)
}
private func buttonState(_ buttonType: ActionBarButtonType) -> (Bool /* selected */, Bool /* enabled */) {
var selected = false
var enabled = true
if buttonType == .bookmark, let bookmarkData = placePageData.bookmarkData {
selected = true
enabled = bookmarkData.isEditable
}
return (selected, enabled)
}
}
extension ActionBarViewController: ActionBarButtonDelegate {
func tapOnButton(with type: ActionBarButtonType) {
if type == .more {
showMore()
return
}
delegate?.actionBar(self, didPressButton: type)
}
}
| 522a9cbddda35da8bb7af065ddc2cc0e | 30.41 | 118 | 0.65632 | false | true | false | false |
eelcokoelewijn/StepUp | refs/heads/master | StepUp/Modules/Reminder/ReminderViewController.swift | mit | 1 | import UIKit
class ReminderViewController: UIViewController, ReminderViewOutput, UsesReminderViewModel {
internal let reminderViewModel: ReminderViewModel
private lazy var descriptionLabel: UILabel = {
let l = UILabel()
l.translatesAutoresizingMaskIntoConstraints = false
l.textColor = .buttonDisabled
l.font = UIFont.light(withSize: 14)
l.textAlignment = .center
l.numberOfLines = 0
l.lineBreakMode = .byWordWrapping
var text = "Stel hier een reminder in.\nOp het ingestelde tijdstip"
text += " ontvang je elke dag een reminder voor je oefeningen."
l.text = text
l.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .horizontal)
return l
}()
private lazy var switchOnOff: UISwitch = {
let s = UISwitch()
s.translatesAutoresizingMaskIntoConstraints = false
s.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: .horizontal)
s.addTarget(self, action: #selector(switchChanged(sender:)), for: .valueChanged)
return s
}()
private lazy var timePicker: UIDatePicker = {
let p = UIDatePicker()
p.translatesAutoresizingMaskIntoConstraints = false
p.datePickerMode = UIDatePicker.Mode.time
p.isEnabled = false
p.addTarget(self, action: #selector(pickerChanged(sender:)), for: UIControl.Event.valueChanged)
return p
}()
private lazy var noPushMessage: UILabel = {
let l = UILabel()
l.translatesAutoresizingMaskIntoConstraints = false
l.textColor = .buttonDisabled
l.font = UIFont.light(withSize: 14)
l.textAlignment = .center
l.numberOfLines = 0
l.lineBreakMode = .byWordWrapping
var text = "Om een reminder in te stellen, heeft StepUp! Push permissies nodig."
text += " Deze kun je aanzetten bij Instelligen > StepUp!"
l.text = text
l.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .horizontal)
l.isHidden = true
return l
}()
init(viewModel: ReminderViewModel) {
reminderViewModel = viewModel
super.init(nibName: nil, bundle: nil)
reminderViewModel.setModel(output: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
applyViewConstraints()
registerForAppActivationNotification()
reminderViewModel.start()
}
// MARK: view output
func showReminder(_ date: Date) {
timePicker.date = date
}
func pop() {
presentingViewController?.dismiss(animated: true, completion: nil)
}
func timePicker(enabled: Bool) {
timePicker.isEnabled = enabled
}
func controlSwitch(on: Bool) {
switchOnOff.isOn = on
}
func showNoPushMessage() {
noPushMessage.isHidden = false
}
// MARK: view controller helper
@objc func switchChanged(sender: UISwitch) {
reminderViewModel.pushTryTo(enabled: sender.isOn, theDate: timePicker.date)
}
@objc private func cancel(sender: UIBarButtonItem) {
reminderViewModel.cancel()
}
@objc private func pickerChanged(sender: UIDatePicker) {
reminderViewModel.save(theDate: sender.date, pushEnabled: switchOnOff.isOn)
}
private func setupViews() {
view.backgroundColor = .white
view.addSubview(descriptionLabel)
view.addSubview(switchOnOff)
view.addSubview(timePicker)
view.addSubview(noPushMessage)
let leftButton = UIBarButtonItem(title: "Sluiten",
style: .plain,
target: self,
action: #selector(cancel(sender:)))
leftButton.tintColor = .actionGreen
navigationItem.leftBarButtonItem = leftButton
}
private func applyViewConstraints() {
let views: [String: Any] = ["descriptionLabel": descriptionLabel,
"switchOnOff": switchOnOff,
"timePicker": timePicker,
"noPushMessage": noPushMessage]
var constraints: [NSLayoutConstraint] = []
constraints.append(NSLayoutConstraint(item: descriptionLabel,
attribute: .top,
relatedBy: .equal,
toItem: topLayoutGuide,
attribute: .bottom,
multiplier: 1, constant: 10))
constraints.append(NSLayoutConstraint(item: switchOnOff,
attribute: .centerY,
relatedBy: .equal,
toItem: descriptionLabel,
attribute: .centerY,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: timePicker,
attribute: .top,
relatedBy: .equal,
toItem: descriptionLabel,
attribute: .bottom,
multiplier: 1, constant: 10))
constraints.append(NSLayoutConstraint(item: noPushMessage,
attribute: .top,
relatedBy: .equal,
toItem: timePicker,
attribute: .bottom,
multiplier: 1, constant: 10))
NSLayoutConstraint.activate(constraints)
let vsl = "H:|-15-[descriptionLabel]-8-[switchOnOff]-15-|"
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: vsl,
options: [],
metrics: nil, views: views))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[timePicker]-15-|",
options: [],
metrics: nil, views: views))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[noPushMessage]-15-|",
options: [],
metrics: nil, views: views))
}
private func registerForAppActivationNotification() {
NotificationCenter.default.addObserver(self,
selector: #selector(appBecomeActive(notification:)),
name: UIApplication.willEnterForegroundNotification,
object: nil)
}
@objc private func appBecomeActive(notification: Notification) {
reminderViewModel.start()
}
}
| 4c75b44cc90be1ea3483ffc2de48d0cc | 41.005495 | 115 | 0.529235 | false | false | false | false |
Lweek/Formulary | refs/heads/master | Formulary/Forms/TextEntry.swift | mit | 1 | //
// TextEntry.swift
// Formulary
//
// Created by Fabian Canas on 1/17/15.
// Copyright (c) 2015 Fabian Canas. All rights reserved.
//
import Foundation
//MARK: Sub-Types
public enum TextEntryType: String {
case Plain = "Formulary.Plain"
case Number = "Formulary.Number"
case Decimal = "Formulary.Decimal"
case Email = "Formulary.Email"
case Twitter = "Formulary.Twitter"
case URL = "Formulary.URL"
case WebSearch = "Formulary.WebSearch"
case Phone = "Formulary.Phone"
case NamePhone = "Formulary.PhoneName"
}
private let KeyMap :[TextEntryType : UIKeyboardType] = [
TextEntryType.Plain : UIKeyboardType.Default,
TextEntryType.Number : UIKeyboardType.NumberPad,
TextEntryType.Decimal : UIKeyboardType.DecimalPad,
TextEntryType.Email : UIKeyboardType.EmailAddress,
TextEntryType.Twitter : UIKeyboardType.Twitter,
TextEntryType.URL : UIKeyboardType.URL,
TextEntryType.WebSearch : UIKeyboardType.WebSearch,
TextEntryType.Phone : UIKeyboardType.PhonePad,
TextEntryType.NamePhone : UIKeyboardType.NamePhonePad,
]
//MARK: Form Row
public class TextEntryFormRow : FormRow {
public let textType: TextEntryType
public let formatter: NSFormatter?
public init(name: String, tag: String, textType: TextEntryType = .Plain, value: AnyObject? = nil, validation: Validation = PermissiveValidation, formatter: NSFormatter? = nil, action: Action? = nil) {
self.textType = textType
self.formatter = formatter
super.init(name: name, tag: tag, type: .Specialized, value: value, validation: validation, action: action)
}
}
//MARK: Cell
class TextEntryCell: UITableViewCell, FormTableViewCell {
var configured: Bool = false
var action :Action?
var textField :NamedTextField?
var formatterAdapter : FormatterAdapter?
var formRow :FormRow? {
didSet {
if var formRow = formRow as? TextEntryFormRow {
configureTextField(&formRow).keyboardType = KeyMap[formRow.textType]!
}
selectionStyle = .None
}
}
func configureTextField(inout row: TextEntryFormRow) -> UITextField {
if (textField == nil) {
let newTextField = NamedTextField(frame: contentView.bounds)
newTextField.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.addSubview(newTextField)
textField = newTextField
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[textField]-|", options: nil, metrics: nil, views: ["textField":newTextField]))
textField = newTextField
}
formatterAdapter = map(row.formatter) { FormatterAdapter(formatter: $0) }
textField?.text = row.value as? String
textField?.placeholder = row.name
textField?.validation = row.validation
textField?.delegate = formatterAdapter
textField?.enabled = row.enabled
map(textField, { (field :NamedTextField) -> ActionTarget in
ActionTarget.clear(field, controlEvents: .EditingChanged)
return ActionTarget(control: field, controlEvents: .EditingChanged, action: { _ in
row.value = field.text
})
})
configured = true
return textField!
}
}
| ecfeb5511de8ff747365c7a8c88c0c59 | 34.905263 | 204 | 0.662562 | false | false | false | false |
ZoranPandovski/al-go-rithms | refs/heads/master | data_structures/trie/swift/trie.swift | cc0-1.0 | 1 | import Foundation
class TrieNode {
private var charMap: [Character: TrieNode]
public var size: Int
init() {
charMap = [:]
size = 0
}
public func add(c: Character) {
if let _ = self.charMap[c] {
// do nothing if exists
} else {
self.charMap[c] = TrieNode()
}
}
public func getChild(c: Character) -> TrieNode? {
return self.charMap[c]
}
}
class Trie {
private var root: TrieNode
init() {
root = TrieNode()
}
init(words: [String]) {
root = TrieNode()
for word in words {
self.add(word: word)
}
}
public func add(word: String) {
var current = root
for c in word {
current.add(c: c)
current = current.getChild(c: c)!
current.size = current.size + 1
}
}
public func find(prefix: String) -> Int {
var current = root
for c in prefix {
if let childNode = current.getChild(c: c) {
current = childNode
} else {
return 0
}
}
return current.size
}
}
| f5a46ee4bdd4b88a4efd9fee48899250 | 19.131148 | 55 | 0.463355 | false | false | false | false |
123kyky/SteamReader | refs/heads/master | Demo/Pods/AlamofireImage/Source/UIImage+AlamofireImage.swift | apache-2.0 | 25 | // UIImage+AlamofireImage.swift
//
// Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 CoreGraphics
import Foundation
import UIKit
#if os(iOS) || os(tvOS)
import CoreImage
#endif
// MARK: Initialization
private let lock = NSLock()
extension UIImage {
/**
Initializes and returns the image object with the specified data in a thread-safe manner.
It has been reported that there are thread-safety issues when initializing large amounts of images
simultaneously. In the event of these issues occurring, this method can be used in place of
the `init?(data:)` method.
- parameter data: The data object containing the image data.
- returns: An initialized `UIImage` object, or `nil` if the method failed.
*/
public static func af_threadSafeImageWithData(data: NSData) -> UIImage? {
lock.lock()
let image = UIImage(data: data)
lock.unlock()
return image
}
/**
Initializes and returns the image object with the specified data and scale in a thread-safe manner.
It has been reported that there are thread-safety issues when initializing large amounts of images
simultaneously. In the event of these issues occurring, this method can be used in place of
the `init?(data:scale:)` method.
- parameter data: The data object containing the image data.
- parameter scale: The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0
results in an image whose size matches the pixel-based dimensions of the image. Applying a
different scale factor changes the size of the image as reported by the size property.
- returns: An initialized `UIImage` object, or `nil` if the method failed.
*/
public static func af_threadSafeImageWithData(data: NSData, scale: CGFloat) -> UIImage? {
lock.lock()
let image = UIImage(data: data, scale: scale)
lock.unlock()
return image
}
}
// MARK: - Inflation
extension UIImage {
private struct AssociatedKeys {
static var InflatedKey = "af_UIImage.Inflated"
}
/// Returns whether the image is inflated.
public var af_inflated: Bool {
get {
if let inflated = objc_getAssociatedObject(self, &AssociatedKeys.InflatedKey) as? Bool {
return inflated
} else {
return false
}
}
set(inflated) {
objc_setAssociatedObject(self, &AssociatedKeys.InflatedKey, inflated, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/**
Inflates the underlying compressed image data to be backed by an uncompressed bitmap representation.
Inflating compressed image formats (such as PNG or JPEG) can significantly improve drawing performance as it
allows a bitmap representation to be constructed in the background rather than on the main thread.
*/
public func af_inflate() {
guard !af_inflated else { return }
af_inflated = true
CGDataProviderCopyData(CGImageGetDataProvider(CGImage))
}
}
// MARK: - Alpha
extension UIImage {
/// Returns whether the image contains an alpha component.
public var af_containsAlphaComponent: Bool {
let alphaInfo = CGImageGetAlphaInfo(CGImage)
return (
alphaInfo == .First ||
alphaInfo == .Last ||
alphaInfo == .PremultipliedFirst ||
alphaInfo == .PremultipliedLast
)
}
/// Returns whether the image is opaque.
public var af_isOpaque: Bool { return !af_containsAlphaComponent }
}
// MARK: - Scaling
extension UIImage {
/**
Returns a new version of the image scaled to the specified size.
- parameter size: The size to use when scaling the new image.
- returns: A new image object.
*/
public func af_imageScaledToSize(size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0)
drawInRect(CGRect(origin: CGPointZero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
/**
Returns a new version of the image scaled from the center while maintaining the aspect ratio to fit within
a specified size.
The resulting image contains an alpha component used to pad the width or height with the necessary transparent
pixels to fit the specified size. In high performance critical situations, this may not be the optimal approach.
To maintain an opaque image, you could compute the `scaledSize` manually, then use the `af_imageScaledToSize`
method in conjunction with a `.Center` content mode to achieve the same visual result.
- parameter size: The size to use when scaling the new image.
- returns: A new image object.
*/
public func af_imageAspectScaledToFitSize(size: CGSize) -> UIImage {
let imageAspectRatio = self.size.width / self.size.height
let canvasAspectRatio = size.width / size.height
var resizeFactor: CGFloat
if imageAspectRatio > canvasAspectRatio {
resizeFactor = size.width / self.size.width
} else {
resizeFactor = size.height / self.size.height
}
let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor)
let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
drawInRect(CGRect(origin: origin, size: scaledSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
/**
Returns a new version of the image scaled from the center while maintaining the aspect ratio to fill a
specified size. Any pixels that fall outside the specified size are clipped.
- parameter size: The size to use when scaling the new image.
- returns: A new image object.
*/
public func af_imageAspectScaledToFillSize(size: CGSize) -> UIImage {
let imageAspectRatio = self.size.width / self.size.height
let canvasAspectRatio = size.width / size.height
var resizeFactor: CGFloat
if imageAspectRatio > canvasAspectRatio {
resizeFactor = size.height / self.size.height
} else {
resizeFactor = size.width / self.size.width
}
let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor)
let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0)
UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0)
drawInRect(CGRect(origin: origin, size: scaledSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
}
// MARK: - Rounded Corners
extension UIImage {
/**
Returns a new version of the image with the corners rounded to the specified radius.
- parameter radius: The radius to use when rounding the new image.
- parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the
image has the same resolution for all screen scales such as @1x, @2x and
@3x (i.e. single image from web server). Set to `false` for images loaded
from an asset catalog with varying resolutions for each screen scale.
`false` by default.
- returns: A new image object.
*/
public func af_imageWithRoundedCornerRadius(radius: CGFloat, divideRadiusByImageScale: Bool = false) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let scaledRadius = divideRadiusByImageScale ? radius / scale : radius
let clippingPath = UIBezierPath(roundedRect: CGRect(origin: CGPointZero, size: size), cornerRadius: scaledRadius)
clippingPath.addClip()
drawInRect(CGRect(origin: CGPointZero, size: size))
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return roundedImage
}
/**
Returns a new version of the image rounded into a circle.
- returns: A new image object.
*/
public func af_imageRoundedIntoCircle() -> UIImage {
let radius = min(size.width, size.height) / 2.0
var squareImage = self
if size.width != size.height {
let squareDimension = min(size.width, size.height)
let squareSize = CGSize(width: squareDimension, height: squareDimension)
squareImage = af_imageAspectScaledToFillSize(squareSize)
}
UIGraphicsBeginImageContextWithOptions(squareImage.size, false, 0.0)
let clippingPath = UIBezierPath(
roundedRect: CGRect(origin: CGPointZero, size: squareImage.size),
cornerRadius: radius
)
clippingPath.addClip()
squareImage.drawInRect(CGRect(origin: CGPointZero, size: squareImage.size))
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return roundedImage
}
}
#if os(iOS) || os(tvOS)
// MARK: - Core Image Filters
extension UIImage {
/**
Returns a new version of the image using a CoreImage filter with the specified name and parameters.
- parameter filterName: The name of the CoreImage filter to use on the new image.
- parameter filterParameters: The parameters to apply to the CoreImage filter.
- returns: A new image object, or `nil` if the filter failed for any reason.
*/
public func af_imageWithAppliedCoreImageFilter(
filterName: String,
filterParameters: [String: AnyObject]? = nil) -> UIImage?
{
var image: CoreImage.CIImage? = CIImage
if image == nil, let CGImage = self.CGImage {
image = CoreImage.CIImage(CGImage: CGImage)
}
guard let coreImage = image else { return nil }
let context = CIContext(options: [kCIContextPriorityRequestLow: true])
var parameters: [String: AnyObject] = filterParameters ?? [:]
parameters[kCIInputImageKey] = coreImage
guard let filter = CIFilter(name: filterName, withInputParameters: parameters) else { return nil }
guard let outputImage = filter.outputImage else { return nil }
let cgImageRef = context.createCGImage(outputImage, fromRect: outputImage.extent)
return UIImage(CGImage: cgImageRef, scale: scale, orientation: imageOrientation)
}
}
#endif
| 1b93cc671d33fcefeabafa702ab33fa8 | 36.523077 | 121 | 0.666995 | false | false | false | false |
ioscreator/ioscreator | refs/heads/master | IOSSnapBehaviourTutorial/IOSSnapBehaviourTutorial/ViewController.swift | mit | 1 | //
// ViewController.swift
// IOSSnapBehaviourTutorial
//
// Created by Arthur Knopper on 24/02/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var animator:UIDynamicAnimator!
var snapBehaviour:UISnapBehavior!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Create the Tap Gesture Recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(userHasTapped))
self.view.addGestureRecognizer(tapGesture)
// Create the Dynamic Animator
animator = UIDynamicAnimator(referenceView: view)
}
@objc func userHasTapped(tap:UITapGestureRecognizer) {
let touchPoint = tap.location(in: view)
if snapBehaviour != nil {
animator.removeBehavior(snapBehaviour)
}
snapBehaviour = UISnapBehavior(item: imageView, snapTo: touchPoint)
snapBehaviour.damping = 0.3
animator.addBehavior(snapBehaviour)
}
}
| 418548b0295bdb3de4048444ffff296d | 26.725 | 95 | 0.667268 | false | false | false | false |
SvenTiigi/PerfectAPIClient | refs/heads/master | Sources/PerfectAPIClient/Models/APIClientResponse.swift | mit | 1 | //
// APIClientResponse.swift
// PerfectAPIClient
//
// Created by Sven Tiigi on 30.10.17.
//
import Foundation
import PerfectCURL
import PerfectHTTP
import ObjectMapper
/// APIClientResponse represents an API response
public struct APIClientResponse {
/// The url that has been requested
public let url: String
/// The response status
public let status: HTTPResponseStatus
/// The payload
public var payload: String
/// The request
public var request: APIClientRequest
/// Indicating if the response is successful (Status code: 200 - 299)
public var isSuccessful: Bool {
return 200 ... 299 ~= self.status.code
}
/// The curlResponse
private var curlResponse: CURLResponse?
/// The response HTTP headers set via initializer
private var headers: [String: String]?
/// Initializer to construct custom APIClientResponse
///
/// - Parameters:
/// - url: The request url
/// - status: The response status
/// - headers: The response HTTP header fields
/// - payload: The response payload
public init(url: String, status: HTTPResponseStatus, payload: String,
request: APIClientRequest, headers: [String: String]? = nil) {
self.url = url
self.status = status
self.payload = payload
self.request = request
self.headers = headers
}
/// Intitializer with CURLResponse
///
/// - Parameter curlResponse: The CURLResponse
public init(request: APIClientRequest, curlResponse: CURLResponse) {
self.init(
url: curlResponse.url,
status: HTTPResponseStatus.statusFrom(code: curlResponse.responseCode),
payload: curlResponse.bodyString,
request: request
)
self.curlResponse = curlResponse
}
/// Get response HTTP header field
///
/// - Parameter name: The HTTP header response name
/// - Returns: The HTTP header field value
public func getHTTPHeader(name: HTTPResponseHeader.Name) -> String? {
// Check if headers are available by direct initialization
if let headers = self.headers {
// Return HTTP header field
return headers[name.standardName]
} else if let curlResponse = self.curlResponse {
// Return HTTP header field from CURLResponse
return curlResponse.get(name)
} else {
// Unable to return HTTP header field
return nil
}
}
/// Retrieve Payload in JSON/Dictionary format
///
/// - Returns: The payload as Dictionary
public func getPayloadJSON() -> [String: Any]? {
// Instantiate Data object from payload
let data = Data(self.payload.utf8)
// JSONSerialization payload data to Dictionary
guard let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {
// JSONSerialization fails return nil
return nil
}
// Return JSON/Dictionary format
return json
}
/// Retrieve Payload in JSON Array format
///
/// - Returns: The payload as Array
public func getPayloadJSONArray() -> [[String: Any]]? {
// Instantiate Data object from payload
let data = Data(self.payload.utf8)
// JSONSerialization payload data to Array
guard let jsonArray = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [[String: Any]] else {
// JSONSerialization fails return nil
return nil
}
// Return JSON Array
return jsonArray
}
/// Retrieve Payload as Mappable Type
///
/// - Parameters:
/// - type: The mappable type
/// - Returns: The mapped object type
public func getMappablePayload<T: BaseMappable>(type: T.Type) -> T? {
// Try to construct mappable with payload
guard let mappable = Mapper<T>().map(JSONString: self.payload) else {
// Unable to construct return nil
return nil
}
// Return mapped object
return mappable
}
/// Retrieve Payload as Mappable Array Type
///
/// - Parameter type: The mappable type
/// - Returns: The mapped object array
public func getMappablePayloadArray<T: BaseMappable>(type: T.Type) -> [T]? {
// Try to construct mappables with payload
guard let mappables = Mapper<T>().mapArray(JSONString: self.payload) else {
// Unable to construct mappables return nil
return nil
}
// Return mapped objects
return mappables
}
}
// MARK: CustomStringConvertible Extension
extension APIClientResponse: JSONCustomStringConvertible {
/// A JSON representation of this instance
public var json: [String: Any] {
return [
"url": self.url,
"status": self.status.description,
"payload": self.payload,
"request": self.request.description,
"isSuccessful": self.isSuccessful
]
}
}
| f40e8be9c3c52be35d463b1c62de9e59 | 30.864198 | 117 | 0.611003 | false | false | false | false |
KevinCoble/AIToolbox | refs/heads/master | Playgrounds/LinearRegression.playground/Sources/MachineLearningProtocols.swift | apache-2.0 | 1 | //
// MachineLearningProtocols.swift
// AIToolbox
//
// Created by Kevin Coble on 1/16/16.
// Copyright © 2016 Kevin Coble. All rights reserved.
//
import Foundation
public enum MachineLearningError: Error {
case dataNotRegression
case dataWrongDimension
case notEnoughData
case modelNotRegression
case modelNotClassification
case notTrained
case initializationError
case didNotConverge
case continuationNotSupported
case operationTimeout
case continueTrainingClassesNotSame
}
public protocol Classifier {
func getInputDimension() -> Int
func getParameterDimension() -> Int // May only be valid after training
func getNumberOfClasses() -> Int // May only be valid after training
func setParameters(_ parameters: [Double]) throws
func setCustomInitializer(_ function: ((_ trainData: DataSet)->[Double])!)
func getParameters() throws -> [Double]
func trainClassifier(_ trainData: DataSet) throws
func continueTrainingClassifier(_ trainData: DataSet) throws // Trains without initializing parameters first
func classifyOne(_ inputs: [Double]) throws ->Int
func classify(_ testData: DataSet) throws
}
public protocol Regressor {
func getInputDimension() -> Int
func getOutputDimension() -> Int
func getParameterDimension() -> Int
func setParameters(_ parameters: [Double]) throws
func setCustomInitializer(_ function: ((_ trainData: DataSet)->[Double])!)
func getParameters() throws -> [Double]
func trainRegressor(_ trainData: DataSet) throws
func continueTrainingRegressor(_ trainData: DataSet) throws // Trains without initializing parameters first
func predictOne(_ inputs: [Double]) throws ->[Double]
func predict(_ testData: DataSet) throws
}
public protocol NonLinearEquation {
// If output dimension > 1, parameters is a matrix with each row the parameters for one of the outputs
var parameters: [Double] { get set }
func getInputDimension() -> Int
func getOutputDimension() -> Int
func getParameterDimension() -> Int // This must be an integer multiple of output dimension
func setParameters(_ parameters: [Double]) throws
func getOutputs(_ inputs: [Double]) throws -> [Double] // Returns vector outputs sized for outputs
func getGradient(_ inputs: [Double]) throws -> [Double] // Returns vector gradient sized for parameters - can be stubbed for ParameterDelta method
}
extension Classifier {
/// Calculate the precentage correct on a classification network using a test data set
public func getClassificationPercentage(_ testData: DataSet) throws -> Double
{
// Verify the data set is the right type
if (testData.dataType != .classification) { throw DataTypeError.invalidDataType }
var countCorrect = 0
// Do for the entire test set
for index in 0..<testData.size {
// Get the results of a feedForward run
let result = try classifyOne(testData.inputs[index])
if (result == testData.classes![index]) {countCorrect += 1}
}
// Calculate the percentage
return Double(countCorrect) / Double(testData.size)
}
}
extension Regressor {
/// Calculate the total absolute value of error on a regressor using a test data set
public func getTotalAbsError(_ testData: DataSet) throws -> Double
{
// Verify the data set is the right type
if (testData.dataType != .regression) { throw DataTypeError.invalidDataType }
var sum = 0.0
// Do for the entire test set
for index in 0..<testData.size{
// Get the results of a prediction
let results = try predictOne(testData.inputs[index])
// Sum up the differences
for nodeIndex in 0..<results.count {
sum += abs(results[nodeIndex] - testData.outputs![index][nodeIndex])
}
}
return sum
}
}
internal class ClassificationData {
var foundLabels: [Int] = []
var classCount: [Int] = []
var classOffsets: [[Int]] = []
var numClasses: Int
{
return foundLabels.count
}
}
| 4663ab9d52c1c5b5430c7e475f9cfa84 | 34.352459 | 157 | 0.658938 | false | true | false | false |
noppoMan/aws-sdk-swift | refs/heads/main | Sources/Soto/Services/FMS/FMS_Paginator.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension FMS {
/// Returns an array of PolicyComplianceStatus objects. Use PolicyComplianceStatus to get a summary of which member accounts are protected by the specified policy.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listComplianceStatusPaginator<Result>(
_ input: ListComplianceStatusRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListComplianceStatusResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listComplianceStatus,
tokenKey: \ListComplianceStatusResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listComplianceStatusPaginator(
_ input: ListComplianceStatusRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListComplianceStatusResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listComplianceStatus,
tokenKey: \ListComplianceStatusResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a MemberAccounts object that lists the member accounts in the administrator's AWS organization. The ListMemberAccounts must be submitted by the account that is set as the AWS Firewall Manager administrator.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listMemberAccountsPaginator<Result>(
_ input: ListMemberAccountsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListMemberAccountsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listMemberAccounts,
tokenKey: \ListMemberAccountsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listMemberAccountsPaginator(
_ input: ListMemberAccountsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListMemberAccountsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listMemberAccounts,
tokenKey: \ListMemberAccountsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns an array of PolicySummary objects.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listPoliciesPaginator<Result>(
_ input: ListPoliciesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listPolicies,
tokenKey: \ListPoliciesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listPoliciesPaginator(
_ input: ListPoliciesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListPoliciesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listPolicies,
tokenKey: \ListPoliciesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension FMS.ListComplianceStatusRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FMS.ListComplianceStatusRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
policyId: self.policyId
)
}
}
extension FMS.ListMemberAccountsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FMS.ListMemberAccountsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension FMS.ListPoliciesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FMS.ListPoliciesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
| 8cd6420744af83b235cab6888b7431aa | 41.910891 | 223 | 0.643286 | false | false | false | false |
argon/mas | refs/heads/master | MasKit/Formatters/AppListFormatter.swift | mit | 1 | //
// AppListFormatter.swift
// MasKit
//
// Created by Ben Chatelain on 6/7/20.
// Copyright © 2019 mas-cli. All rights reserved.
//
import Foundation
/// Formats text output for the search command.
struct AppListFormatter {
static let idColumnMinWidth = 10
static let nameColumnMinWidth = 50
/// Formats text output with list results.
///
/// - Parameter products: List of sortware products app data.
/// - Returns: Multiliune text outoutp.
static func format(products: [SoftwareProduct]) -> String {
// find longest appName for formatting, default 50
let maxLength = products.map { $0.appNameOrBbundleIdentifier }
.max(by: { $1.count > $0.count })?.count
?? nameColumnMinWidth
var output: String = ""
for product in products {
let appId = product.itemIdentifier.stringValue
.padding(toLength: idColumnMinWidth, withPad: " ", startingAt: 0)
let appName = product.appNameOrBbundleIdentifier.padding(toLength: maxLength, withPad: " ", startingAt: 0)
let version = product.bundleVersion
output += "\(appId) \(appName) (\(version))\n"
}
return output.trimmingCharacters(in: .newlines)
}
}
| bad9f6ea05329c514852dc8dce42883f | 30.725 | 118 | 0.635146 | false | false | false | false |
gobetti/Swift | refs/heads/master | UIImagePickerControllerCameraEditImage/UIImagePickerControllerCameraEditImage/ViewController.swift | mit | 1 | //
// ViewController.swift
// UIImagePickerControllerCameraEditImage
//
// Created by Carlos Butron on 08/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
import MediaPlayer
import MobileCoreServices
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var cutImage: UIImageView!
@IBOutlet weak var myImage: UIImageView!
@IBAction func useCamera(sender: UIButton) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
//to select only camera control, not video
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.showsCameraControls = true
imagePicker.allowsEditing = true
self.presentViewController(imagePicker, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageEdited = info[UIImagePickerControllerEditedImage] as! UIImage
let imageData = UIImagePNGRepresentation(image)! as NSData
//save in photo album
UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
//save in documents
let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last
let filePath = (documentsPath! as NSString).stringByAppendingPathComponent("pic.png")
imageData.writeToFile(filePath, atomically: true)
myImage.image = image
cutImage.image = imageEdited
self.dismissViewControllerAnimated(true, completion: nil)
}
func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo: UnsafePointer<()>){
if(error != nil){
print("ERROR IMAGE \(error.debugDescription)")
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController){
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| f7cff2bce34658ee34315bb33acd57cf | 36.758621 | 154 | 0.708371 | false | false | false | false |
AngryLi/Onmyouji | refs/heads/master | Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesAPI.swift | mit | 4 | //
// GitHubSearchRepositoriesAPI.swift
// RxExample
//
// Created by Krunoslav Zaher on 10/18/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !RX_NO_MODULE
import RxSwift
#endif
import struct Foundation.URL
import struct Foundation.Data
import struct Foundation.URLRequest
import struct Foundation.NSRange
import class Foundation.HTTPURLResponse
import class Foundation.URLSession
import class Foundation.NSRegularExpression
import class Foundation.JSONSerialization
import class Foundation.NSString
/**
Parsed GitHub repository.
*/
struct Repository: CustomDebugStringConvertible {
var name: String
var url: URL
init(name: String, url: URL) {
self.name = name
self.url = url
}
}
extension Repository {
var debugDescription: String {
return "\(name) | \(url)"
}
}
enum GitHubServiceError: Error {
case offline
case githubLimitReached
case networkError
}
typealias SearchRepositoriesResponse = Result<(repositories: [Repository], nextURL: URL?), GitHubServiceError>
class GitHubSearchRepositoriesAPI {
// *****************************************************************************************
// !!! This is defined for simplicity sake, using singletons isn't advised !!!
// !!! This is just a simple way to move services to one location so you can see Rx code !!!
// *****************************************************************************************
static let sharedAPI = GitHubSearchRepositoriesAPI(reachabilityService: try! DefaultReachabilityService())
fileprivate let _reachabilityService: ReachabilityService
private init(reachabilityService: ReachabilityService) {
_reachabilityService = reachabilityService
}
}
extension GitHubSearchRepositoriesAPI {
public func loadSearchURL(_ searchURL: URL) -> Observable<SearchRepositoriesResponse> {
return URLSession.shared
.rx.response(request: URLRequest(url: searchURL))
.retry(3)
.observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler)
.map { httpResponse, data -> SearchRepositoriesResponse in
if httpResponse.statusCode == 403 {
return .failure(.githubLimitReached)
}
let jsonRoot = try GitHubSearchRepositoriesAPI.parseJSON(httpResponse, data: data)
guard let json = jsonRoot as? [String: AnyObject] else {
throw exampleError("Casting to dictionary failed")
}
let repositories = try Repository.parse(json)
let nextURL = try GitHubSearchRepositoriesAPI.parseNextURL(httpResponse)
return .success(repositories: repositories, nextURL: nextURL)
}
.retryOnBecomesReachable(.failure(.offline), reachabilityService: _reachabilityService)
}
}
// MARK: Parsing the response
extension GitHubSearchRepositoriesAPI {
private static let parseLinksPattern = "\\s*,?\\s*<([^\\>]*)>\\s*;\\s*rel=\"([^\"]*)\""
private static let linksRegex = try! NSRegularExpression(pattern: parseLinksPattern, options: [.allowCommentsAndWhitespace])
fileprivate static func parseLinks(_ links: String) throws -> [String: String] {
let length = (links as NSString).length
let matches = GitHubSearchRepositoriesAPI.linksRegex.matches(in: links, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: length))
var result: [String: String] = [:]
for m in matches {
let matches = (1 ..< m.numberOfRanges).map { rangeIndex -> String in
let range = m.rangeAt(rangeIndex)
let startIndex = links.characters.index(links.startIndex, offsetBy: range.location)
let endIndex = links.characters.index(links.startIndex, offsetBy: range.location + range.length)
let stringRange = startIndex ..< endIndex
return links.substring(with: stringRange)
}
if matches.count != 2 {
throw exampleError("Error parsing links")
}
result[matches[1]] = matches[0]
}
return result
}
fileprivate static func parseNextURL(_ httpResponse: HTTPURLResponse) throws -> URL? {
guard let serializedLinks = httpResponse.allHeaderFields["Link"] as? String else {
return nil
}
let links = try GitHubSearchRepositoriesAPI.parseLinks(serializedLinks)
guard let nextPageURL = links["next"] else {
return nil
}
guard let nextUrl = URL(string: nextPageURL) else {
throw exampleError("Error parsing next url `\(nextPageURL)`")
}
return nextUrl
}
fileprivate static func parseJSON(_ httpResponse: HTTPURLResponse, data: Data) throws -> AnyObject {
if !(200 ..< 300 ~= httpResponse.statusCode) {
throw exampleError("Call failed")
}
return try JSONSerialization.jsonObject(with: data, options: []) as AnyObject
}
}
extension Repository {
fileprivate static func parse(_ json: [String: AnyObject]) throws -> [Repository] {
guard let items = json["items"] as? [[String: AnyObject]] else {
throw exampleError("Can't find items")
}
return try items.map { item in
guard let name = item["name"] as? String,
let url = item["url"] as? String else {
throw exampleError("Can't parse repository")
}
return Repository(name: name, url: try URL(string: url).unwrap())
}
}
}
| dd84829d386ca6a1d33f5caabfa5703e | 33.433735 | 172 | 0.626662 | false | false | false | false |
NoodleOfDeath/PastaParser | refs/heads/master | runtime/swift/GrammarKit/Classes/model/io/IO.TokenStream.swift | mit | 1 | //
// The MIT License (MIT)
//
// Copyright © 2020 NoodleOfDeath. All rights reserved.
// NoodleOfDeath
//
// 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
extension IO {
/// Data structure that represents a token stream.
open class TokenStream<T: Token>: NSObject, IOStream {
public typealias Atom = T
public typealias AtomSequence = [T]
// MARK: - CustomStringConvertible Properties
override open var description: String {
return tokens.map({ $0.description }).joined(separator: ", ")
}
// MARK: - IOStream Properties
open var length: Int {
guard let first = tokens.first, let last = tokens.last else { return 0 }
return last.range.max - first.range.location
}
/// Shorthand for `NSMakeRange(0, length)`.
open var range: NSRange {
guard let first = tokens.first else { return .zero }
return NSMakeRange(first.range.location, length)
}
// MARK: - Instance Properties
/// Tokens contained in this token stream.
open var tokens = AtomSequence()
/// Number of tokens
open var tokenCount: Int { return tokens.count }
/// Character stream from which tokens were derived.
public let characterStream: CharacterStream
/// Constructs a new token stream with an initial character stream.
///
/// - Parameters:
/// - characterStream: of the new token stream.
public init(characterStream: CharacterStream) {
self.characterStream = characterStream
}
open subscript(index: Int) -> Atom {
return tokens[index]
}
open subscript(range: Range<Int>) -> AtomSequence {
var subtokens = AtomSequence()
for i in range.lowerBound ..< range.upperBound { subtokens.append(tokens[i]) }
return subtokens
}
open func reduce<Result>(over range: Range<Int>, _ prefix: Result, _ lambda: ((Result, Atom) -> Result)) -> Result {
return self[range].reduce(prefix, lambda)
}
/// Adds a token to this token stream.
///
/// - Parameters:
/// - token: to add to this token stream.
open func add(token: Atom) {
tokens.append(token)
}
}
}
extension IO.TokenStream {
public func reduce<Result>(over range: NSRange, _ prefix: Result, _ lambda: ((Result, Atom) -> Result)) -> Result {
return reduce(over: range.bridgedRange, prefix, lambda)
}
}
| a4acb7c1cc98ae115b948857c81de968 | 33.609524 | 124 | 0.641992 | false | false | false | false |
AlesTsurko/DNMKit | refs/heads/master | DNM_iOS/DNM_iOS/UIBezierPathExtensions.swift | gpl-2.0 | 1 | //
// UIBezierPathExtensions.swift
// denm_view
//
// Created by James Bean on 8/17/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
import DNMModel
extension UIBezierPath {
public func rotate(degrees degrees: Float) {
let bounds = CGPathGetBoundingBox(self.CGPath)
let center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds))
let toOrigin = CGAffineTransformMakeTranslation(-center.x, -center.y)
let rotation = CGAffineTransformMakeRotation(CGFloat(DEGREES_TO_RADIANS(degrees)))
let fromOrigin = CGAffineTransformMakeTranslation(center.x, center.y)
self.applyTransform(toOrigin)
self.applyTransform(rotation)
self.applyTransform(fromOrigin)
}
public func mirror() {
let mirrorOverXOrigin = CGAffineTransformMakeScale(-1, 1)
let translate = CGAffineTransformMakeTranslation(bounds.width, 0)
self.applyTransform(mirrorOverXOrigin)
self.applyTransform(translate)
}
public func scale(sx: CGFloat, sy: CGFloat) {
let scale = CGAffineTransformMakeScale(sx, sy)
let beforeBounds = CGPathGetBoundingBox(self.CGPath)
let beforeCenter = CGPointMake(CGRectGetMidX(beforeBounds), CGRectGetMidY(beforeBounds))
self.applyTransform(scale)
let afterBounds = CGPathGetBoundingBox(self.CGPath)
let afterCenter = CGPointMake(CGRectGetMidX(afterBounds), CGRectGetMidY(afterBounds))
let ΔY: CGFloat = -(afterCenter.y - beforeCenter.y)
let ΔX: CGFloat = -(afterCenter.x - beforeCenter.x)
let backToCenter = CGAffineTransformMakeTranslation(ΔX, ΔY)
self.applyTransform(backToCenter)
}
}
| 38a04eb448e41ee585f26202f88ebdcc | 38.090909 | 96 | 0.704651 | false | false | false | false |
robconrad/fledger-common | refs/heads/master | FledgerCommon/services/models/location/LocationAnnotation.swift | mit | 1 | //
// LocationAnnotation.swift
// fledger-ios
//
// Created by Robert Conrad on 4/26/15.
// Copyright (c) 2015 Robert Conrad. All rights reserved.
//
import Foundation
import MapKit
public class LocationAnnotation: MKPointAnnotation {
public let location: Location
public required init(location: Location) {
self.location = location
super.init()
coordinate = location.coordinate
title = location.title()
subtitle = location.title() == location.address ? nil : location.address
}
} | 446cf657871d4e72be47d39c61dbac2f | 20.222222 | 80 | 0.63986 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.