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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PekanMmd/Pokemon-XD-Code | refs/heads/master | Objects/data types/enumerable/CMType.swift | gpl-2.0 | 1 | //
// CMType.swift
// Colosseum Tool
//
// Created by The Steez on 06/06/2018.
//
import Foundation
var kFirstTypeOffset: Int {
switch region {
case .US: return 0x358500
case .JP: return 0x344C40
case .EU: return 0x3A55C0
case .OtherGame: return 0
}
}
let kCategoryOffset = 0x0
let kTypeIconBigIDOffset = 0x02
let kTypeNameIDOffset = 0x4
let kFirstEffectivenessOffset = 0x9
let kSizeOfTypeData = 0x2C
let kNumberOfTypes = 0x12
// name id list in dol in colo 0x2e2458
final class XGType: NSObject, Codable {
var index = 0
var nameID = 0
var category = XGMoveCategories.none
var effectivenessTable = [XGEffectivenessValues]()
var name : XGString {
get {
return XGFiles.common_rel.stringTable.stringSafelyWithID(self.nameID)
}
}
var startOffset = 0
init(index: Int) {
super.init()
let dol = XGFiles.dol.data!
self.index = index
startOffset = kFirstTypeOffset + (index * kSizeOfTypeData)
self.nameID = dol.getWordAtOffset(startOffset + kTypeNameIDOffset).int
self.category = XGMoveCategories(rawValue: dol.getByteAtOffset(startOffset + kCategoryOffset))!
var offset = startOffset + kFirstEffectivenessOffset
for _ in 0 ..< kNumberOfTypes {
let value = dol.getByteAtOffset(offset)
let effectiveness = XGEffectivenessValues(rawValue: value) ?? .neutral
effectivenessTable.append(effectiveness)
offset += 2
}
}
func save() {
let dol = XGFiles.dol.data!
dol.replaceByteAtOffset(startOffset + kCategoryOffset, withByte: self.category.rawValue)
for i in 0 ..< self.effectivenessTable.count {
let value = effectivenessTable[i].rawValue
dol.replaceByteAtOffset(startOffset + kFirstEffectivenessOffset + (i * 2), withByte: value)
// i*2 because each value is 2 bytes apart
}
dol.save()
}
}
extension XGType: XGEnumerable {
var enumerableName: String {
return name.string
}
var enumerableValue: String? {
return String(format: "%02d", index)
}
static var className: String {
return "Types"
}
static var allValues: [XGType] {
var values = [XGType]()
for i in 0 ..< kNumberOfTypes {
values.append(XGType(index: i))
}
return values
}
}
| 02f0447615724351e23b5cfac5ddbe91 | 19.472222 | 97 | 0.697422 | false | false | false | false |
HabitRPG/habitrpg-ios | refs/heads/develop | HabitRPG/Views/ToastView.swift | gpl-3.0 | 1 | //
// ToastManager.Swift
// Habitica
//
// Created by Collin Ruffenach on 11/6/14.
// Copyright (c) 2014 Notion. All rights reserved.
//
import UIKit
class ToastView: UIView {
@IBOutlet weak var backgroundView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var priceContainer: UIView!
@IBOutlet weak var priceIconLabel: IconLabel!
@IBOutlet weak var statsDiffStackView: UIStackView!
@IBOutlet weak var leftImageView: UIImageView!
@IBOutlet weak var bottomSpacing: NSLayoutConstraint!
@IBOutlet weak var topSpacing: NSLayoutConstraint!
@IBOutlet weak var leadingSpacing: NSLayoutConstraint!
@IBOutlet weak var trailingSpacing: NSLayoutConstraint!
@IBOutlet weak var leftImageWidth: NSLayoutConstraint!
@IBOutlet weak var leftImageHeight: NSLayoutConstraint!
@IBOutlet weak var priceContainerWidth: NSLayoutConstraint!
@IBOutlet weak var priceTrailingPadding: NSLayoutConstraint!
@IBOutlet weak var priceLeadingPadding: NSLayoutConstraint!
@IBOutlet weak var priceIconLabelWidth: NSLayoutConstraint!
var options: ToastOptions = ToastOptions()
public convenience init(title: String, subtitle: String, background: ToastColor, duration: Double? = nil, delay: Double? = nil) {
self.init(frame: CGRect.zero)
options.title = title
options.subtitle = subtitle
options.backgroundColor = background
if let duration = duration {
options.displayDuration = duration
}
if let delay = delay {
options.delayDuration = delay
}
loadOptions()
accessibilityLabel = "\(title), \(subtitle)"
}
public convenience init(title: String, background: ToastColor, duration: Double? = nil, delay: Double? = nil) {
self.init(frame: CGRect.zero)
options.title = title
options.backgroundColor = background
if let duration = duration {
options.displayDuration = duration
}
if let delay = delay {
options.delayDuration = delay
}
loadOptions()
accessibilityLabel = title
}
public convenience init(title: String, subtitle: String, icon: UIImage, background: ToastColor, duration: Double? = nil, delay: Double? = nil) {
self.init(frame: CGRect.zero)
options.title = title
options.subtitle = subtitle
options.leftImage = icon
options.backgroundColor = background
if let duration = duration {
options.displayDuration = duration
}
if let delay = delay {
options.delayDuration = delay
}
loadOptions()
accessibilityLabel = "\(title), \(subtitle)"
}
public convenience init(title: String, icon: UIImage, background: ToastColor, duration: Double? = nil, delay: Double? = nil) {
self.init(frame: CGRect.zero)
options.title = title
options.backgroundColor = background
options.leftImage = icon
if let duration = duration {
options.displayDuration = duration
}
if let delay = delay {
options.delayDuration = delay
}
loadOptions()
accessibilityLabel = title
}
public convenience init(title: String, rightIcon: UIImage, rightText: String, rightTextColor: UIColor, background: ToastColor, duration: Double? = nil, delay: Double? = nil) {
self.init(frame: CGRect.zero)
options.title = title
options.backgroundColor = background
options.rightIcon = rightIcon
options.rightText = rightText
options.rightTextColor = rightTextColor
if let duration = duration {
options.displayDuration = duration
}
if let delay = delay {
options.delayDuration = delay
}
loadOptions()
accessibilityLabel = title
}
public convenience init(healthDiff: Float, magicDiff: Float, expDiff: Float, goldDiff: Float, questDamage: Float, background: ToastColor, duration: Double? = nil, delay: Double? = nil) {
self.init(frame: CGRect.zero)
accessibilityLabel = "You received "
addStatsView(HabiticaIcons.imageOfHeartDarkBg, diff: healthDiff, label: "Health")
addStatsView(HabiticaIcons.imageOfExperience, diff: expDiff, label: "Experience")
addStatsView(HabiticaIcons.imageOfMagic, diff: magicDiff, label: "Mana")
addStatsView(HabiticaIcons.imageOfGold, diff: goldDiff, label: "Gold")
addStatsView(HabiticaIcons.imageOfDamage, diff: questDamage, label: "Damage")
options.backgroundColor = background
loadOptions()
}
private func addStatsView(_ icon: UIImage, diff: Float, label: String) {
if diff != 0 {
let iconLabel = IconLabel()
iconLabel.icon = icon
iconLabel.text = diff > 0 ? String(format: "+%.2f", diff) : String(format: "%.2f", diff)
iconLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
statsDiffStackView.addArrangedSubview(iconLabel)
accessibilityLabel = (accessibilityLabel ?? "") + "\(Int(diff)) \(label), "
}
}
override init(frame: CGRect) {
super.init(frame: frame)
configureViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureViews()
}
private func configureViews() {
self.backgroundColor = .clear
if let view = viewFromNibForClass() {
translatesAutoresizingMaskIntoConstraints = false
view.frame = bounds
addSubview(view)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": view]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": view]))
backgroundView.layer.borderColor = UIColor.black.withAlphaComponent(0.1).cgColor
backgroundView.layer.borderWidth = 1
isUserInteractionEnabled = false
backgroundView.isUserInteractionEnabled = true
isAccessibilityElement = false
}
}
func loadOptions() {
backgroundView.backgroundColor = options.backgroundColor.getUIColor()
backgroundView.layer.borderColor = options.backgroundColor.getUIColor().darker(by: 10).cgColor
topSpacing.constant = 6
bottomSpacing.constant = 6
leadingSpacing.constant = 8
trailingSpacing.constant = 8
configureTitle(options.title)
configureSubtitle(options.subtitle)
configureLeftImage(options.leftImage)
configureRightView(icon: options.rightIcon, text: options.rightText, textColor: options.rightTextColor)
priceContainerWidth.constant = 0
setNeedsUpdateConstraints()
updateConstraints()
setNeedsLayout()
layoutIfNeeded()
}
private func configureTitle(_ title: String?) {
if let title = title {
titleLabel.isHidden = false
titleLabel.text = title
titleLabel.sizeToFit()
titleLabel.numberOfLines = -1
titleLabel.font = UIFont.systemFont(ofSize: 13)
titleLabel.textAlignment = .center
} else {
titleLabel.isHidden = true
titleLabel.text = nil
}
}
private func configureSubtitle(_ subtitle: String?) {
if let subtitle = subtitle {
subtitleLabel.isHidden = false
subtitleLabel.text = subtitle
subtitleLabel.sizeToFit()
subtitleLabel.numberOfLines = -1
titleLabel.font = UIFont.systemFont(ofSize: 16)
titleLabel.textAlignment = .center
} else {
subtitleLabel.isHidden = true
subtitleLabel.text = nil
}
}
private func configureLeftImage(_ leftImage: UIImage?) {
if let leftImage = leftImage {
leftImageView.isHidden = false
leftImageView.image = leftImage
leadingSpacing.constant = 4
leftImageWidth.constant = 46
leftImageHeight.priority = UILayoutPriority(rawValue: 999)
} else {
leftImageView.isHidden = true
leftImageWidth.constant = 0
leftImageHeight.priority = UILayoutPriority(rawValue: 500)
}
}
private func configureRightView(icon: UIImage?, text: String?, textColor: UIColor?) {
if let icon = icon, let text = text, let textColor = textColor {
priceContainer.isHidden = false
priceIconLabel.icon = icon
priceIconLabel.text = text
priceIconLabel.textColor = textColor
trailingSpacing.constant = 0
backgroundView.layer.borderColor = options.backgroundColor.getUIColor().cgColor
} else {
priceContainer.isHidden = true
priceIconLabel.removeFromSuperview()
}
}
}
| fdc4966c450c4e504bd302a15d5d4679 | 37.545082 | 190 | 0.634024 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | refs/heads/master | TranslationEditor/ParagraphBindingView.swift | mit | 1 | //
// ParagraphBindingView.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 11.1.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// This is the view used for querying paragraph binding data
final class ParagraphBindingView: View
{
// TYPES --------------------
typealias Queried = ParagraphBinding
typealias MyQuery = Query<ParagraphBindingView>
// ATTRIBUTES ----------------
static let KEY_CODE = "code"
static let KEY_TARGET_BOOK = "target"
static let KEY_SOURCE_BOOK = "source"
static let KEY_CREATED = "created"
static let instance = ParagraphBindingView()
static let keyNames = [KEY_CODE, KEY_TARGET_BOOK, KEY_SOURCE_BOOK, KEY_CREATED]
let view: CBLView
// INIT ------------------------
private init()
{
view = DATABASE.viewNamed("paragraph_bindings")
view.setMapBlock(createMapBlock
{
binding, emit in
let key = [Book.code(fromId: binding.targetBookId).code, binding.targetBookId, binding.sourceBookId, binding.created] as [Any]
// let value = [binding.idString, binding.created] as [Any]
emit(key, nil)
}/*, reduce:
{
// Finds the most recent id
keys, values, rereduce in
var mostRecentId = ""
var mostRecentTime = 0.0
for value in values
{
let value = value as! [Any]
let created = value[1] as! TimeInterval
if created > mostRecentTime
{
let id = value[0] as! String
mostRecentId = id
mostRecentTime = created
}
}
return [mostRecentId, mostRecentTime]
}*/, version: "6")
}
// OTHER METHODS ---------
func createQuery(targetBookId: String, sourceBookId: String? = nil) -> MyQuery
{
return createQuery(code: Book.code(fromId: targetBookId), targetBookId: targetBookId, sourceBookId: sourceBookId)
}
// Finds the latest existing binding between the two books
func latestBinding(from sourceBookId: String, to targetBookId: String) throws -> ParagraphBinding?
{
return try createQuery(code: Book.code(fromId: targetBookId), targetBookId: targetBookId, sourceBookId: sourceBookId).firstResultObject()
}
// Finds all bindings that have the provided book id as either source or target
func bindings(forBookWithId bookId: String) throws -> [ParagraphBinding]
{
return try createQuery(code: Book.code(fromId: bookId), targetBookId: nil, sourceBookId: nil).resultRows().filter { $0.keys[ParagraphBindingView.KEY_TARGET_BOOK]?.string == bookId || $0.keys[ParagraphBindingView.KEY_SOURCE_BOOK]?.string == bookId }.map { try $0.object() }
}
private func createQuery(code: BookCode?, targetBookId: String?, sourceBookId: String?) -> MyQuery
{
let keys = ParagraphBindingView.makeKeys(from: [code?.code, targetBookId, sourceBookId])
var query = createQuery(withKeys: keys)
query.descending = true
return query
}
}
| 91c6e94819d7ae7fcc70c33a77d524b7 | 26.911765 | 274 | 0.687741 | false | false | false | false |
thanhtrdang/FluentYogaKit | refs/heads/master | FluentYogaKit/CardViewController.swift | apache-2.0 | 1 | //
// CardViewController.swift
// FluentYogaKit
//
// Created by Thanh Dang on 6/12/17.
// Copyright © 2017 Thanh Dang. All rights reserved.
//
import UIKit
import YetAnotherAnimationLibrary
class CardViewController: UIViewController {
let gr = UIPanGestureRecognizer()
var card: UIView!
var backCard: UIView?
fileprivate var cardFrame: CGRect!
func generateCard() -> UIView {
let card = UIView()
view.insertSubview(card, at: 0)
view.yoga
.background(card, edges: [.vertical: 120, .horizontal: 50])
.layout()
card.layer.cornerRadius = 8
card.backgroundColor = .white
card.layer.shadowOffset = .zero
card.layer.shadowOpacity = 0.5
card.layer.shadowRadius = 5
card.yaal.center.value
=> { [weak view] newCenter in
if let view = view {
return (newCenter.x - view.center.x) / view.bounds.width
}
return nil
}
=> card.yaal.rotation
card.yaal.scale.value
=> { $0 * $0 }
=> card.yaal.alpha
return card
}
override func viewDidLoad() {
super.viewDidLoad()
cardFrame = UIEdgeInsetsInsetRect(view.bounds, UIEdgeInsets(top: 120, left: 50, bottom: 120, right: 50))
view.backgroundColor = UIColor(red: 1.0, green: 0.5, blue: 0.5, alpha: 1.0)
gr.addTarget(self, action: #selector(pan(gr:)))
view.addGestureRecognizer(gr)
card = generateCard()
}
@objc func pan(gr: UIPanGestureRecognizer) {
let translation = gr.translation(in: view)
switch gr.state {
case .began:
backCard = generateCard()
backCard!.yaal.scale.setTo(0.7)
fallthrough
case .changed:
card.yaal.center.setTo(CGPoint(x: translation.x + view.center.x, y: translation.y / 10 + view.center.y))
backCard!.yaal.scale.setTo(abs(translation.x) / view.bounds.width * 0.3 + 0.7)
default:
if let backCard = backCard, abs(translation.x) > view.bounds.width / 4 {
let finalX = translation.x < 0 ? -view.bounds.width : view.bounds.width * 2
card.yaal.center.animateTo(CGPoint(x: finalX, y: view.center.y)) { [card] _ in
card?.removeFromSuperview()
}
card = backCard
card.yaal.scale.animateTo(1)
} else {
backCard?.yaal.scale.animateTo(0) { [backCard] _ in
backCard?.removeFromSuperview()
}
card.yaal.center.animateTo(view.center)
}
backCard = nil
}
}
}
| 60a27578a250fbd92935e7ea7c1eaa8a | 26.931034 | 110 | 0.630453 | false | false | false | false |
Skyus/Swiftlog | refs/heads/master | Swiftlog/Utils.swift | gpl-2.0 | 1 | import Foundation
import VPIAssistant
public class Control {
public static func finish() {
vpi_finish();
}
}
extension String {
public var cPointer: (cLiteral: UnsafePointer<CChar>, cMutable: UnsafeMutablePointer<CChar>, mutable: UnsafeMutablePointer<UInt8>, elementCount: Int) {
var utf8Representation = Array(self.utf8)
utf8Representation.append(0) //0 terminator
let mutablePointer = UnsafeMutablePointer<UInt8>.allocate(capacity: utf8Representation.count)
let cMutablePointer = UnsafeMutableRawPointer(mutablePointer).bindMemory(to: CChar.self, capacity: utf8Representation.count)
let immutablePointer = UnsafeRawPointer(mutablePointer).bindMemory(to: CChar.self, capacity: utf8Representation.count)
let _ = UnsafeMutableBufferPointer<UInt8>(start: mutablePointer, count: utf8Representation.count).initialize(from: utf8Representation)
return (cLiteral: immutablePointer, cMutable: cMutablePointer, mutable: mutablePointer, elementCount: utf8Representation.count)
}
} | 36a98ff1ea187432f8ecd3c16a444050 | 52 | 155 | 0.757318 | false | false | false | false |
JWShroyer/CollectionViewTransitions | refs/heads/master | CollectionViewTransitions/CollectionViewTransitions/CollectionViewController.swift | mit | 1 | //
// CollectionViewController.swift
// CollectionViewTransitions
//
// Created by Joshua Shroyer on 7/23/15.
// Copyright (c) 2015 Full Sail University. All rights reserved.
//
import UIKit
let cellIdentifier = "cellReuse"
class CollectionViewController: UICollectionViewController {
var cellCount = 5;
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
//self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
collectionView?.dataSource = self;
collectionView?.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//#warning Incomplete method implementation -- Return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return 5;
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! UICollectionViewCell
// Configure the cell
cell.backgroundColor = UIColor.redColor();
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let tVC = segue.destinationViewController as? TransitionCollectionViewController {
tVC.useLayoutToLayoutNavigationTransitions = true;
}
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
}
| 05ab3119c50dbccc1cab440dceb6972c | 33.046296 | 183 | 0.752244 | false | false | false | false |
kevinvanderlugt/Exercism-Solutions | refs/heads/master | swift/octal/Octal.swift | mit | 1 | //
// Octal.swift
// exercism-test-runner
//
// Created by Kevin VanderLugt on 4/11/15.
// Copyright (c) 2015 Alpine Pipeline, LLC. All rights reserved.
//
//
import Foundation
infix operator ** { }
func ** (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
struct Octal {
private let base = 8
var octalNumbers: String
init(_ octalNumbers: String) {
self.octalNumbers = octalNumbers
}
var toDecimal: Int {
var decimal: Int = 0
if(validOctal) {
for (index, trinary) in enumerate(reverse(octalNumbers)) {
if let digit = String(trinary).toInt() {
decimal += digit*(base**index)
}
}
}
return decimal
}
private var validOctal: Bool {
return filter(octalNumbers) { !contains(self.validNumbers, String($0)) }.isEmpty
}
private var validNumbers: [String] {
return Array(0..<base).map({String($0)})
}
} | ac34384dda7e8b23352683804b6ecf61 | 22.044444 | 88 | 0.557915 | false | false | false | false |
filestack/filestack-ios | refs/heads/master | Sources/Filestack/UI/Internal/Controllers/MonitorViewController.swift | mit | 1 | //
// MonitorViewController.swift
// Filestack
//
// Created by Ruben Nine on 11/9/17.
// Copyright © 2017 Filestack. All rights reserved.
//
import FilestackSDK
import UIKit
final class MonitorViewController: UIViewController {
// MARK: - Private Properties
private let progressable: Cancellable & Monitorizable
private var progressObservers: [NSKeyValueObservation] = []
private lazy var progressView: UIProgressView = {
let progressView = UIProgressView()
progressView.observedProgress = progressable.progress
return progressView
}()
private lazy var activityIndicator: UIActivityIndicatorView = {
let activityIndicator: UIActivityIndicatorView
if #available(iOS 13.0, *) {
activityIndicator = UIActivityIndicatorView(style: .large)
} else {
activityIndicator = UIActivityIndicatorView(style: .white)
}
activityIndicator.hidesWhenStopped = true
return activityIndicator
}()
private let cancelButton: UIButton = {
let button = UIButton()
button.setTitle("Cancel", for: .normal)
button.addTarget(self, action: #selector(cancel), for: .touchUpInside)
return button
}()
private lazy var descriptionLabel: UILabel = {
let label = UILabel()
label.text = progressable.progress.localizedDescription
return label
}()
private lazy var additionalDescriptionLabel: UILabel = {
let label = UILabel()
label.text = progressable.progress.localizedAdditionalDescription
return label
}()
// MARK: - Lifecycle
required init(progressable: Cancellable & Monitorizable) {
self.progressable = progressable
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - View Overrides
extension MonitorViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if progressable.progress.isIndeterminate {
progressView.isHidden = true
activityIndicator.startAnimating()
} else {
progressView.isHidden = false
activityIndicator.stopAnimating()
}
setupObservers()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeObservers()
progressView.observedProgress = nil
}
}
// MARK: - Actions
private extension MonitorViewController {
@IBAction func cancel(_: AnyObject) {
progressable.cancel()
}
}
// MARK: - Private Functions
private extension MonitorViewController {
func setupViews() {
let stackView = UIStackView(arrangedSubviews:
[UIView(), UIView(), descriptionLabel, activityIndicator, progressView, additionalDescriptionLabel, UIView(), cancelButton]
)
progressView.leadingAnchor.constraint(equalTo: stackView.layoutMarginsGuide.leadingAnchor).isActive = true
progressView.trailingAnchor.constraint(equalTo: stackView.layoutMarginsGuide.trailingAnchor).isActive = true
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.alignment = .center
stackView.spacing = 22
stackView.layoutMargins = .init(top: 22, left: 44, bottom: 22, right: 44)
stackView.isLayoutMarginsRelativeArrangement = true
if #available(iOS 13.0, *) {
view.backgroundColor = .systemBackground
} else {
view.backgroundColor = .white
}
view.fill(with: stackView)
}
func setupObservers() {
progressObservers.append(progressable.progress.observe(\.totalUnitCount) { (_, _) in
DispatchQueue.main.async { self.updateUI() }
})
progressObservers.append(progressable.progress.observe(\.completedUnitCount) { (_, _) in
DispatchQueue.main.async { self.updateUI() }
})
progressObservers.append(progressable.progress.observe(\.fractionCompleted) { (_, _) in
DispatchQueue.main.async { self.updateUI() }
})
}
func updateUI() {
if progressable.progress.isIndeterminate && !progressView.isHidden {
UIView.animate(withDuration: 0.25) {
self.activityIndicator.startAnimating()
self.progressView.isHidden = true
}
}
if !progressable.progress.isIndeterminate && !activityIndicator.isHidden {
UIView.animate(withDuration: 0.25) {
self.activityIndicator.stopAnimating()
self.progressView.isHidden = false
}
}
descriptionLabel.text = progressable.progress.localizedDescription
additionalDescriptionLabel.text = progressable.progress.localizedAdditionalDescription
}
func removeObservers() {
progressObservers.removeAll()
}
}
| 9e1251ead2326acfcfd4ead70a1c7e79 | 27.416667 | 135 | 0.65044 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples | refs/heads/main | snippets/MapsSnippets/MapsSnippets/Swift/Markers.swift | apache-2.0 | 1 | // Copyright 2020 Google LLC
//
// 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.
// [START maps_ios_markers_icon_view]
import CoreLocation
import GoogleMaps
class MarkerViewController: UIViewController, GMSMapViewDelegate {
var mapView: GMSMapView!
var london: GMSMarker?
var londonView: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
let camera = GMSCameraPosition.camera(
withLatitude: 51.5,
longitude: -0.127,
zoom: 14
)
let mapView = GMSMapView.map(withFrame: .zero, camera: camera)
view = mapView
mapView.delegate = self
let house = UIImage(named: "House")!.withRenderingMode(.alwaysTemplate)
let markerView = UIImageView(image: house)
markerView.tintColor = .red
londonView = markerView
let position = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.127)
let marker = GMSMarker(position: position)
marker.title = "London"
marker.iconView = markerView
marker.tracksViewChanges = true
marker.map = mapView
london = marker
}
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
UIView.animate(withDuration: 5.0, animations: { () -> Void in
self.londonView?.tintColor = .blue
}, completion: {(finished) in
// Stop tracking view changes to allow CPU to idle.
self.london?.tracksViewChanges = false
})
}
}
// [END maps_ios_markers_icon_view]
var mapView: GMSMapView!
func addMarker() {
// [START maps_ios_markers_add_marker]
let position = CLLocationCoordinate2D(latitude: 10, longitude: 10)
let marker = GMSMarker(position: position)
marker.title = "Hello World"
marker.map = mapView
// [END maps_ios_markers_add_marker]
}
func removeMarker() {
// [START maps_ios_markers_remove_marker]
let camera = GMSCameraPosition.camera(
withLatitude: -33.8683,
longitude: 151.2086,
zoom: 6
)
let mapView = GMSMapView.map(withFrame: .zero, camera: camera)
// ...
mapView.clear()
// [END maps_ios_markers_remove_marker]
// [START maps_ios_markers_remove_marker_modifications]
let position = CLLocationCoordinate2D(latitude: 10, longitude: 10)
let marker = GMSMarker(position: position)
marker.map = mapView
// ...
marker.map = nil
// [END maps_ios_markers_remove_marker_modifications]
// [START maps_ios_markers_customize_marker_color]
marker.icon = GMSMarker.markerImage(with: .black)
// [END maps_ios_markers_customize_marker_color]
// [START maps_ios_markers_customize_marker_image]
let positionLondon = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.127)
let london = GMSMarker(position: positionLondon)
london.title = "London"
london.icon = UIImage(named: "house")
london.map = mapView
// [END maps_ios_markers_customize_marker_image]
// [START maps_ios_markers_opacity]
marker.opacity = 0.6
// [END maps_ios_markers_opacity]
}
func moreCustomizations() {
// [START maps_ios_markers_flatten]
let positionLondon = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.127)
let londonMarker = GMSMarker(position: positionLondon)
londonMarker.isFlat = true
londonMarker.map = mapView
// [END maps_ios_markers_flatten]
// [START maps_ios_markers_rotate]
let degrees = 90.0
londonMarker.groundAnchor = CGPoint(x: 0.5, y: 0.5)
londonMarker.rotation = degrees
londonMarker.map = mapView
// [END maps_ios_markers_rotate]
}
func infoWindow() {
// [START maps_ios_markers_info_window_title]
let position = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.127)
let london = GMSMarker(position: position)
london.title = "London"
london.map = mapView
// [END maps_ios_markers_info_window_title]
// [START maps_ios_markers_info_window_title_and_snippet]
london.title = "London"
london.snippet = "Population: 8,174,100"
london.map = mapView
// [END maps_ios_markers_info_window_title_and_snippet]
// [START maps_ios_markers_info_window_changes]
london.tracksInfoWindowChanges = true
// [END maps_ios_markers_info_window_changes]
// [START maps_ios_markers_info_window_change_position]
london.infoWindowAnchor = CGPoint(x: 0.5, y: 0.5)
london.icon = UIImage(named: "house")
london.map = mapView
// [END maps_ios_markers_info_window_change_position]
// [START maps_ios_markers_info_window_show_hide]
london.title = "London"
london.snippet = "Population: 8,174,100"
london.map = mapView
// Show marker
mapView.selectedMarker = london
// Hide marker
mapView.selectedMarker = nil
// [END maps_ios_markers_info_window_show_hide]
}
| 2627576873d2a8780ba5d9d42ed419cb | 30.7 | 80 | 0.710371 | false | false | false | false |
randallli/material-components-ios | refs/heads/develop | components/Snackbar/tests/unit/MDCSnackbarColorThemerTests.swift | apache-2.0 | 1 | /*
Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
import MaterialComponents.MaterialSnackbar
import MaterialComponents.MaterialSnackbar_ColorThemer
class SnackbarColorThemerTests: XCTestCase {
func testColorThemerChangesTheCorrectParameters() {
// Given
let colorScheme = MDCSemanticColorScheme()
let message = MDCSnackbarMessage()
message.text = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
colorScheme.surfaceColor = .red
colorScheme.onSurfaceColor = .blue
MDCSnackbarManager.snackbarMessageViewBackgroundColor = .white
MDCSnackbarManager.messageTextColor = .white
MDCSnackbarManager.setButtonTitleColor(.white, for: .normal)
MDCSnackbarManager.setButtonTitleColor(.white, for: .highlighted)
// When
MDCSnackbarColorThemer.applySemanticColorScheme(colorScheme)
MDCSnackbarManager.show(message)
// Then
XCTAssertEqual(MDCSnackbarManager.snackbarMessageViewBackgroundColor?.withAlphaComponent(1),
colorScheme.onSurfaceColor)
XCTAssertEqual(MDCSnackbarManager.messageTextColor?.withAlphaComponent(1),
colorScheme.surfaceColor)
XCTAssertEqual(MDCSnackbarManager.buttonTitleColor(for: .normal)?.withAlphaComponent(1),
colorScheme.surfaceColor)
XCTAssertEqual(MDCSnackbarManager.buttonTitleColor(for: .highlighted)?.withAlphaComponent(1),
colorScheme.surfaceColor)
}
}
| 4b6c3526d59e8dc80a7cff4ab9ee2627 | 39.76 | 97 | 0.768891 | false | true | false | false |
dezinezync/YapDatabase | refs/heads/master | YapDatabase/Extensions/View/Swift/YapDatabaseView.swift | bsd-3-clause | 2 | /// Add Swift extensions here
extension YapDatabaseViewConnection {
public func getChanges(forNotifications notifications: [Notification], withMappings mappings: YapDatabaseViewMappings) -> (sectionChanges: [YapDatabaseViewSectionChange], rowChanges: [YapDatabaseViewRowChange]) {
var sectionChanges = NSArray()
var rowChanges = NSArray()
self.__getSectionChanges(§ionChanges, rowChanges: &rowChanges, for: notifications, with: mappings)
return (sectionChanges as! [YapDatabaseViewSectionChange], rowChanges as! [YapDatabaseViewRowChange])
}
}
extension YapDatabaseViewTransaction {
public func getCollectionKey(atIndex index: Int, inGroup group: String) -> (String, String)? {
var key: NSString? = nil
var collection: NSString? = nil
self.__getKey(&key, collection: &collection, at: UInt(index), inGroup: group)
if let collection = collection as String?,
let key = key as String? {
return (collection, key)
}
else {
return nil
}
}
public func getGroupIndex(forKey key: String, inCollection collection: String?) -> (String, Int)? {
var group: NSString? = nil
var index: UInt = 0
self.__getGroup(&group, index: &index, forKey: key, inCollection: collection)
if let group = group as String? {
return (group, Int(index))
} else {
return nil
}
}
// MARK: Iteration
public func iterateKeys(inGroup group: String, using block: (String, String, Int, inout Bool) -> Void) {
self.iterateKeys(inGroup: group, reversed: false, using: block)
}
public func iterateKeys(inGroup group: String, reversed: Bool, using block: (String, String, Int, inout Bool) -> Void) {
let enumBlock = {(collection: String, key: String, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in
var innerStop = false
block(collection, key, Int(index), &innerStop)
if innerStop {
outerStop.pointee = true
}
}
let options: NSEnumerationOptions = reversed ? .reverse : .init()
self.__enumerateKeys(inGroup: group, with: options, using: enumBlock)
}
public func iterateKeys(inGroup group: String, reversed: Bool, range: NSRange, using block: (String, String, Int, inout Bool) -> Void) {
let enumBlock = {(collection: String, key: String, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in
var innerStop = false
block(collection, key, Int(index), &innerStop)
if innerStop {
outerStop.pointee = true
}
}
let options: NSEnumerationOptions = reversed ? .reverse : .init()
self.__enumerateKeys(inGroup: group, with: options, range: range, using: enumBlock)
}
public func iterateKeysAndMetadata(inGroup group: String, using block: (String, String, Any?, Int, inout Bool) -> Void) {
self.iterateKeysAndMetadata(inGroup: group, reversed: false, using: block)
}
public func iterateKeysAndMetadata(inGroup group: String, reversed: Bool, using block: (String, String, Any?, Int, inout Bool) -> Void) {
let enumBlock = {(collection: String, key: String, metadata: Any?, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in
var innerStop = false
block(collection, key, metadata, Int(index), &innerStop)
if innerStop {
outerStop.pointee = true
}
}
let options: NSEnumerationOptions = reversed ? .reverse : .init()
self.__enumerateKeysAndMetadata(inGroup: group, with: options, using: enumBlock)
}
public func iterateKeysAndMetadata(inGroup group: String, reversed: Bool, range: NSRange, using block: (String, String, Any?, Int, inout Bool) -> Void) {
let enumBlock = {(collection: String, key: String, metadata: Any?, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in
var innerStop = false
block(collection, key, metadata, Int(index), &innerStop)
if innerStop {
outerStop.pointee = true
}
}
let options: NSEnumerationOptions = reversed ? .reverse : .init()
self.__enumerateKeysAndMetadata(inGroup: group, with: options, range: range, using: enumBlock)
}
public func iterateKeysAndObjects(inGroup group: String, using block: (String, String, Any, Int, inout Bool) -> Void) {
self.iterateKeysAndObjects(inGroup: group, reversed: false, using: block)
}
public func iterateKeysAndObjects(inGroup group: String, reversed: Bool, using block: (String, String, Any, Int, inout Bool) -> Void) {
let enumBlock = {(collection: String, key: String, object: Any, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in
var innerStop = false
block(collection, key, object, Int(index), &innerStop)
if innerStop {
outerStop.pointee = true
}
}
let options: NSEnumerationOptions = reversed ? .reverse : .init()
self.__enumerateKeysAndObjects(inGroup: group, with: options, using: enumBlock)
}
public func iterateKeysAndObjects(inGroup group: String, reversed: Bool, range: NSRange, using block: (String, String, Any?, Int, inout Bool) -> Void) {
let enumBlock = {(collection: String, key: String, object: Any, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in
var innerStop = false
block(collection, key, object, Int(index), &innerStop)
if innerStop {
outerStop.pointee = true
}
}
let options: NSEnumerationOptions = reversed ? .reverse : .init()
self.__enumerateKeysAndObjects(inGroup: group, with: options, range: range, using: enumBlock)
}
public func iterateRows(inGroup group: String, using block: (String, String, Any, Any?, Int, inout Bool) -> Void) {
self.iterateRows(inGroup: group, reversed: false, using: block)
}
public func iterateRows(inGroup group: String, reversed: Bool, using block: (String, String, Any, Any?, Int, inout Bool) -> Void) {
let enumBlock = {(collection: String, key: String, object: Any, metadata: Any?, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in
var innerStop = false
block(collection, key, object, metadata, Int(index), &innerStop)
if innerStop {
outerStop.pointee = true
}
}
let options: NSEnumerationOptions = reversed ? .reverse : .init()
self.__enumerateRows(inGroup: group, with: options, using: enumBlock)
}
public func iterateRows(inGroup group: String, reversed: Bool, range: NSRange, using block: (String, String, Any, Any?, Int, inout Bool) -> Void) {
let enumBlock = {(collection: String, key: String, object: Any, metadata: Any?, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in
var innerStop = false
block(collection, key, object, metadata, Int(index), &innerStop)
if innerStop {
outerStop.pointee = true
}
}
let options: NSEnumerationOptions = reversed ? .reverse : .init()
self.__enumerateRows(inGroup: group, with: options, range: range, using: enumBlock)
}
// MARK: Mappings
public func getCollectionKey(atIndexPath indexPath: IndexPath, withMappings mappings: YapDatabaseViewMappings) -> (String, String)? {
var key: NSString? = nil
var collection: NSString? = nil
self.__getKey(&key, collection: &collection, at: indexPath, with: mappings)
if let collection = collection as String?,
let key = key as String? {
return (collection, key)
}
else {
return nil
}
}
public func getCollectionKey(forRow row: Int, section: Int, withMappings mappings: YapDatabaseViewMappings) -> (String, String)? {
var key: NSString? = nil
var collection: NSString? = nil
self.__getKey(&key, collection: &collection, forRow: UInt(row), inSection: UInt(section), with: mappings)
if let collection = collection as String?,
let key = key as String? {
return (collection, key)
}
else {
return nil
}
}
}
| 0466e55fd59754301b3deb851a885930 | 31.734177 | 213 | 0.69322 | false | false | false | false |
zning1994/practice | refs/heads/master | Swift学习/code4xcode6/ch10/10.1闭包表达式.playground/section-1.swift | gpl-2.0 | 1 | // 本书网站:http://www.51work6.com/swift.php
// 智捷iOS课堂在线课堂:http://v.51work6.com
// 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973
// 智捷iOS课堂微信公共账号:智捷iOS课堂
// 作者微博:http://weibo.com/516inc
// 官方csdn博客:http://blog.csdn.net/tonny_guan
// Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:[email protected]
func calculate(opr :String)-> (Int,Int)-> Int {
var result : (Int,Int)-> Int
switch (opr) {
case "+" :
result = {(a:Int, b:Int) -> Int in
return a + b
}
default:
result = {(a:Int, b:Int) -> Int in
return a - b
}
}
return result
}
let f1:(Int,Int)-> Int = calculate("+")
println("10 + 5 = \(f1(10,5))")
let f2:(Int,Int)-> Int = calculate("-")
println("10 - 5 = \(f2(10,5))")
| f051605c45bb468a4570e3346b27de1d | 22.78125 | 62 | 0.558476 | false | false | false | false |
OverSwift/VisualReader | refs/heads/develop | MangaReader/Fameworks/MediaManager/MediaManager/Sources/MediaController.swift | bsd-3-clause | 1 | //
// MediaController.swift
// MediaManager
//
// Created by Sergiy Loza on 08.04.17.
// Copyright © 2017 Sergiy Loza. All rights reserved.
//
import Foundation
class ImageStoreOperation: Operation {
private(set) var data: Data
init(data: Data) {
self.data = data
}
}
class DiskCacheManager {
private(set) var diskCapasity = 1024
private let fileManager = FileManager.default
fileprivate func imgesCacheDirectory() -> URL {
let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true);
let path = (paths.first! as NSString).appendingPathComponent("MediaControllerCache")
var isDirectory = ObjCBool(false)
if !FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) {
do {
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories:true, attributes: nil)
} catch {
print("Coudn't create directory at \(path) with error: \(error)")
}
} else if !isDirectory.boolValue {
print("Path \(path) exists but is no directory")
}
let url = URL(fileURLWithPath: path)
self.addSkipBackupAttributeToItemAtURL(url)
return url
}
@discardableResult fileprivate func addSkipBackupAttributeToItemAtURL(_ URL: Foundation.URL) -> Bool {
var isSkiAttributeSet = false
do {
try (URL as NSURL).setResourceValue(true, forKey:URLResourceKey.isExcludedFromBackupKey)
isSkiAttributeSet = true
} catch {
print("Error excluding \(URL) from backup \(error)")
}
return isSkiAttributeSet
}
}
| 74fde6adf72dc6d361097aa7ca535b73 | 30.472727 | 120 | 0.640092 | false | false | false | false |
PJayRushton/stats | refs/heads/master | Stats/NewTeamState.swift | mit | 1 | //
// NewTeamState.swift
// Stats
//
// Created by Parker Rushton on 4/4/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import UIKit
struct Loading<T>: Event {
var object: T?
init(_ object: T? = nil) {
self.object = object
}
}
struct NewTeamState: State {
var imageURL: URL?
var isLoading = false
mutating func react(to event: Event) {
switch event {
case let event as Selected<URL>:
imageURL = event.item
isLoading = false
case _ as Loading<URL>:
isLoading = true
default:
break
}
}
}
| c250c22bfb7aa797180c46e87b7d1297 | 16.648649 | 51 | 0.534456 | false | false | false | false |
DDSwift/SwiftDemos | refs/heads/master | Day01-LoadingADView/LoadingADView/LoadingADView/Class/MainTabBarViewController.swift | gpl-3.0 | 1 | //
// MainTabBarViewController.swift
// LoadingADView
//
// Created by SuperDanny on 16/3/7.
// Copyright © 2016年 SuperDanny. All rights reserved.
//
import UIKit
class MainTabBarViewController: UITabBarController {
private var adImageView: UIImageView?
var adImage: UIImage? {
didSet {
weak var tmpSelf = self
adImageView = UIImageView(frame: ScreenBounds)
adImageView!.image = adImage!
view.addSubview(adImageView!)
UIImageView.animateWithDuration(2.0, animations: { () -> Void in
tmpSelf!.adImageView!.transform = CGAffineTransformMakeScale(1.2, 1.2)
tmpSelf!.adImageView!.alpha = 0
}) { (finsch) -> Void in
tmpSelf!.adImageView!.removeFromSuperview()
tmpSelf!.adImageView = nil
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 73be5b8789d8ff73614f0683ea24d4ed | 28.584906 | 106 | 0.616709 | false | false | false | false |
RMizin/PigeonMessenger-project | refs/heads/main | FalconMessenger/Supporting Files/UIComponents/UIIncrementSlider/UIIncrementSliderView.swift | gpl-3.0 | 1 | //
// UIIncrementSliderView.swift
// FalconMessenger
//
// Created by Roman Mizin on 3/4/19.
// Copyright © 2019 Roman Mizin. All rights reserved.
//
import UIKit
protocol UIIncrementSliderUpdateDelegate: class {
func incrementSliderDidUpdate(to value: CGFloat)
}
class UIIncrementSliderView: UIView {
fileprivate let slider: UIIncrementSlider = {
let slider = UIIncrementSlider()
slider.translatesAutoresizingMaskIntoConstraints = false
return slider
}()
fileprivate let minimumValueImage: UIImageView = {
let minimumValueImage = UIImageView()
minimumValueImage.image = UIImage(named: "FontMinIcon")?.withRenderingMode(.alwaysTemplate)
minimumValueImage.tintColor = ThemeManager.currentTheme().generalTitleColor
minimumValueImage.translatesAutoresizingMaskIntoConstraints = false
return minimumValueImage
}()
fileprivate let maximumValueImage: UIImageView = {
let maximumValueImage = UIImageView()
maximumValueImage.image = UIImage(named: "FontMaxIcon")?.withRenderingMode(.alwaysTemplate)
maximumValueImage.tintColor = ThemeManager.currentTheme().generalTitleColor
maximumValueImage.translatesAutoresizingMaskIntoConstraints = false
return maximumValueImage
}()
weak var delegate: UIIncrementSliderUpdateDelegate?
init(values: [Float], currentValue: Float? = 0) {
super.init(frame: .zero)
addSubview(slider)
addSubview(minimumValueImage)
addSubview(maximumValueImage)
NotificationCenter.default.addObserver(self, selector: #selector(changeTheme), name: .themeUpdated, object: nil)
if #available(iOS 11.0, *) {
NSLayoutConstraint.activate([
minimumValueImage.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 15),
maximumValueImage.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -15)
])
} else {
NSLayoutConstraint.activate([
minimumValueImage.leftAnchor.constraint(equalTo: leftAnchor, constant: 15),
maximumValueImage.rightAnchor.constraint(equalTo: rightAnchor, constant: -15)
])
}
NSLayoutConstraint.activate([
slider.topAnchor.constraint(equalTo: topAnchor),
slider.leftAnchor.constraint(equalTo: minimumValueImage.rightAnchor, constant: 10),
slider.rightAnchor.constraint(equalTo: maximumValueImage.leftAnchor, constant: -10),
minimumValueImage.centerYAnchor.constraint(equalTo: slider.centerYAnchor),
minimumValueImage.widthAnchor.constraint(equalToConstant: (minimumValueImage.image?.size.width ?? 0)),
minimumValueImage.heightAnchor.constraint(equalToConstant: (minimumValueImage.image?.size.height ?? 0)),
maximumValueImage.centerYAnchor.constraint(equalTo: slider.centerYAnchor),
maximumValueImage.widthAnchor.constraint(equalToConstant: (maximumValueImage.image?.size.width ?? 0)),
maximumValueImage.heightAnchor.constraint(equalToConstant: (maximumValueImage.image?.size.height ?? 0))
])
slider.initializeSlider(with: values, currentValue: currentValue ?? 0) { [weak self] actualValue in
self?.delegate?.incrementSliderDidUpdate(to: CGFloat(actualValue))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc fileprivate func changeTheme() {
minimumValueImage.tintColor = ThemeManager.currentTheme().generalTitleColor
maximumValueImage.tintColor = ThemeManager.currentTheme().generalTitleColor
slider.changeTheme()
}
}
| 771c77aab9152fc4847c2a04261c7cdb | 36.48913 | 114 | 0.787765 | false | false | false | false |
dietcoke27/TableVector | refs/heads/master | Example/TableVector/ViewController.swift | mit | 1 | //
// ViewController.swift
// TableVector
//
// Created by Cole Kurkowski on 2/3/16.
// Copyright © 2016 Cole Kurkowski. All rights reserved.
//
import UIKit
import TableVector
final class ViewController: UITableViewController, TableVectorDelegate {
typealias VectorType = TableVector<Container>
var tableVector: VectorType!
var reader: FileReader!
var buffer: VectorBuffer<Container>!
var filterString: String?
var shouldSleep = true
var shouldReadFile = true
override func viewDidLoad() {
super.viewDidLoad()
let compare = {
(lhs: T, rhs: T) -> Bool in
return lhs.string.caseInsensitiveCompare(rhs.string) == .orderedAscending
}
let sectionMember = {
(elem: T, rep: T) -> Bool in
let elemChar = elem.string.substring(to: elem.string.characters.index(after: elem.string.startIndex))
let repChar = rep.string.substring(to: rep.string.characters.index(after: rep.string.startIndex))
return elemChar.caseInsensitiveCompare(repChar) == .orderedSame
}
let sectionCompare = {
(lhs: T, rhs: T) -> Bool in
let elemChar = lhs.string.substring(to: lhs.string.characters.index(after: lhs.string.startIndex))
let repChar = rhs.string.substring(to: rhs.string.characters.index(after: rhs.string.startIndex))
return elemChar.caseInsensitiveCompare(repChar) == .orderedAscending
}
self.tableVector = VectorType(delegate: self, comparator: compare, sectionClosure: sectionMember, sectionComparator: sectionCompare)
self.buffer = VectorBuffer(vector: self.tableVector)
self.tableVector.suspendDelegateCalls = true
if self.shouldReadFile {
self.reader = FileReader()
self.reader.vc = self
}
self.tableView.allowsMultipleSelection = false
let button = UIBarButtonItem(barButtonSystemItem: .bookmarks, target: self, action: #selector(ViewController.filterButton(sender:)))
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ViewController.addButton(sender:)))
self.navigationItem.rightBarButtonItems = [addButton, button]
self.tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "header")
}
func addButton(sender: Any?) {
let alert = UIAlertController(title: "Add", message: nil, preferredStyle: .alert)
alert.addTextField(configurationHandler: nil)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Add", style: .default, handler: {[weak alert] (action) in
if let text = alert?.textFields?.first {
let container = Container(string: text.text ?? "")
self.tableVector.insert(container)
}
}))
self.present(alert, animated: true, completion: nil)
}
func filterButton(sender: Any?) {
let alert = UIAlertController(title: "Filter", message: nil, preferredStyle: .alert)
alert.addTextField { (field) in
field.text = self.filterString
}
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: {[weak alert] (action) in
if let textField = alert?.textFields?.first, let text = textField.text {
if text == "" {
self.tableVector.removeFilter()
} else {
if let previousFilter = self.filterString, text.contains(previousFilter) {
self.tableVector.refineFilter{
(container) -> Bool in
return container.string.contains(text) || text.contains(container.string)
}
} else {
if self.filterString != nil {
self.tableVector.removeFilter()
}
self.tableVector.filter(predicate: { (container) -> Bool in
return container.string.contains(text) || text.contains(container.string)
})
}
}
self.filterString = text
} else {
self.tableVector.removeFilter()
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
self.tableVector.suspendDelegateCalls = false
}
override func viewDidAppear(_ animated: Bool) {
if !(self.reader?.started ?? true) {
self.reader.startReader()
}
let timer = Timer(timeInterval: 1, target: self, selector: #selector(ViewController.timerUpdate(_:)), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: .commonModes)
}
@objc func timerUpdate(_ sender: Any) {
DispatchQueue.global(qos: .background).async {
var total = 0
for section in 0..<(self.tableVector.sectionCount) {
total += self.tableVector.countForSection(section)
}
var secondTotal = 0
for section in 0..<(self.tableView.numberOfSections) {
secondTotal += self.tableView.numberOfRows(inSection: section)
}
DispatchQueue.main.async {
self.title = "\(total) | \(secondTotal)"
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let str = self.tableVector.representative(at: section)?.string
if let str = str
{
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "header")
let char = str.substring(to: str.characters.index(after: str.startIndex))
header?.textLabel?.text = char.uppercased()
return header
}
else
{
return nil
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if self.tableView(tableView, numberOfRowsInSection: section) == 0 {
return 0
}
return 28
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
self.tableVector.remove(at: indexPath)
}
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .delete
}
func elementChangedForVector(_ vector: VectorType, changes: ElementChangeType<Container>, atIndexPaths: [IndexPath]) {
switch changes {
case .inserted:
var newSections = [Int]()
for path in atIndexPaths {
if self.tableView.numberOfRows(inSection: path.section) == 0 {
newSections.append(path.section)
}
}
self.tableView.insertRows(at: atIndexPaths, with: .automatic)
if newSections.count > 0 {
self.tableView.reloadSections(IndexSet(newSections), with: .automatic)
}
case .removed, .filteredOut:
var emptySections = [Int]()
self.tableView.deleteRows(at: atIndexPaths, with: .automatic)
for path in atIndexPaths {
if self.tableView.numberOfRows(inSection: path.section) == 0 {
emptySections.append(path.section)
}
}
if emptySections.count > 0 {
self.tableView.reloadSections(IndexSet(emptySections), with: .automatic)
}
case .updated:
break
}
}
func refresh(sections: IndexSet, inVector: VectorType) {
UIView.transition(with: self.tableView, duration: 0.5, options: .transitionCrossDissolve, animations: {
self.tableView.reloadData()
}, completion: nil)
}
func sectionChangedForVector(_ vector: VectorType, change: SectionChangeType, atIndex: Int) {
if case .inserted = change {
self.tableView.insertSections(IndexSet(integer: atIndex), with: .automatic)
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
let c = self.tableVector.sectionCount
return c
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let c = self.tableVector.countForSection(section)
return c
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let container = self.tableVector[indexPath]!
cell.textLabel?.text = container.string
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? DetailViewController {
if let path = self.tableView.indexPathForSelectedRow {
vc.container = self.tableVector[path]
}
}
}
}
class FileReader {
private var filename = "american"
private var fileHandle: FileHandle?
weak var vc: ViewController!
let queue = DispatchQueue(label: "filereader", attributes: .concurrent, target: .global(qos: .background))
let group = DispatchGroup()
let sem = DispatchSemaphore(value: 0)
var started = false
func startReader()
{
started = true
self.queue.async {
self.readWholeFile()
}
}
private func readWholeFile()
{
if let path = Bundle.main.path(forResource: self.filename, ofType: nil)
{
var count = 0
do {
let str = try String(contentsOfFile: path)
let components = str.components(separatedBy: "\n")
for comp in components
{
weak var vc = self.vc
self.queue.async(group: self.group) {
let contain = Container(string: comp)
if vc?.shouldSleep ?? false
{
let slp = arc4random_uniform(10)
sleep(slp)
}
vc?.buffer.append(contain)
}
count += 1
if count >= 50 {
self.group.notify(queue: self.queue) {
count = 0
self.sem.signal()
}
self.sem.wait()
}
}
}
catch {
}
}
}
}
class Container: CustomStringConvertible {
let string: String
var description: String {
get {
return self.string
}
}
init(string: String)
{
self.string = string
}
}
| 90fd7cabbb471420b01a691781f28f54 | 34.13783 | 140 | 0.557253 | false | false | false | false |
PrashantMangukiya/SwiftPhotoGallery | refs/heads/master | SwiftPhotoGallery/SwiftPhotoGallery/SinglePhotoViewController.swift | mit | 1 | //
// SinglePhotoViewController.swift
// SwiftPhotoGallery
//
// Created by Prashant on 12/09/15.
// Copyright (c) 2015 PrashantKumar Mangukiya. All rights reserved.
//
import UIKit
class SinglePhotoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
// collection view cell default width, height
// final width will be calculated based on screen width and height
var cellWidth: Int = 100
var cellHeight: Int = 100
// variable keep track that view appear or not.
// we have to load collection view after view appear so correct cell size achieved.
var isViewAppear: Bool = false
// clicked photo indexPath (will be set by parent controller)
var clickedPhotoIndexPath : NSIndexPath?
// photo list (will be set by parent controller)
var photoList: [Photo] = [Photo]()
// outlet - photo collection view
@IBOutlet var photoCollectionView: UICollectionView!
// MARK: - view function
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// set collectionview delegate and datasource
self.photoCollectionView.delegate = self
self.photoCollectionView.dataSource = self
}
override func viewDidAppear(animated: Bool) {
// set view as appear
self.isViewAppear = true
// Calculate cell width, height based on screen width
self.calculateCellWidthHeight()
if self.photoList.isEmpty {
self.showAlertMessage(alertTitle: "Error", alertMessage: "Photo list found empty.")
}else{
// reload collection view data
self.photoCollectionView.reloadData()
// scroll collection view at selected photo
self.photoCollectionView.scrollToItemAtIndexPath(clickedPhotoIndexPath!, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)
}
}
// MARK: - Collection view data source
// number of section in collection view
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
// number of photos in collection view
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if self.isViewAppear {
return self.photoList.count
}else{
return 0
}
}
// return width and height of cell
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: self.cellWidth, height: self.cellHeight)
}
// configure cell
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// get reusable cell
let newCell = collectionView.dequeueReusableCellWithReuseIdentifier("CellSinglePhoto", forIndexPath: indexPath) as! SinglePhotoCollectionViewCell
// get current photo from list
let photoRecord = self.photoList[indexPath.row]
// set placeholder until image downloaded from server.
newCell.largeImageView.image = UIImage(named: "placeholder")
// Download photo asynchronously
let imagePath = REMOTE_DATA_FOLDER_PATH + photoRecord.largeImage
// if path convertible to url then load image.
if let imageURL = NSURL(string: imagePath) {
newCell.spinner.startAnimating()
self.downloadCellPhotoInBackground(imageUrl: imageURL, photoCell: newCell )
}
// return cell
return newCell
}
// MARK: - Utility functions
// download Image asynchronously and assign to cell once downloaded
func downloadCellPhotoInBackground( imageUrl imageUrl: NSURL, photoCell: SinglePhotoCollectionViewCell ) {
let task = NSURLSession.sharedSession().dataTaskWithURL(imageUrl, completionHandler:
{
(data, response, error) -> Void in
// if no error then update photo
if (error == nil) {
// update cell photo (GUI must updated in main_queue)
dispatch_async( dispatch_get_main_queue(), {
// conver to NSData
let imageData = NSData(data: data!)
// set image to large image view within cell
photoCell.largeImageView.image = UIImage(data: imageData )
// stop the spinner
photoCell.spinner.stopAnimating()
})
}
})
// important
task.resume()
}
// calculate collection view cell width same as full screen
private func calculateCellWidthHeight() {
// find cell width same as screen width
self.cellWidth = Int(self.photoCollectionView.frame.width)
// find cell height
self.cellHeight = Int(self.photoCollectionView.frame.height) - 64 // deduct nav bar and status bar height
}
// show alert with ok button
private func showAlertMessage(alertTitle alertTitle: String, alertMessage: String ) -> Void {
// create alert controller
let alertCtrl = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert) as UIAlertController
// create action
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:
{ (action: UIAlertAction) -> Void in
// you can add code here if needed
})
// add ok action
alertCtrl.addAction(okAction)
// present alert
self.presentViewController(alertCtrl, animated: true, completion: { (void) -> Void in
// you can add code here if needed
})
}
}
| fcf6797126582bafa1602a409983ce20 | 34.318681 | 171 | 0.612166 | false | false | false | false |
hmily-xinxiang/BBSwiftFramework | refs/heads/master | BBSwiftFramework/Class/Extern/Common-UI/BBTableView/BBTableViewCell.swift | mit | 1 | //
// BBTableViewCell.swift
// BBSwiftFramework
//
// Created by Bei Wang on 10/8/15.
// Copyright © 2015 BooYah. All rights reserved.
//
import UIKit
enum eGroupTableViewCellPosition: Int {
case None
case Top // section中居于顶部
case Middle // section中居于中间
case Bottom // section中居于底部
case Single // 单个cell的section
}
class BBTableViewCell: UITableViewCell {
var separatorLength: CGFloat! = BBDevice.deviceWidth() - 15.0
var separatorColor: UIColor! = BBColor.defaultColor()
private var position: eGroupTableViewCellPosition = .None
private var lineHeight: CGFloat = 0.5
// MARK: - --------------------System--------------------
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
}
// MARK: - --------------------功能函数--------------------
// MARK: 初始化
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let separatorView: BBRootView = BBRootView.init(frame: CGRectMake(BBDevice.deviceWidth()-separatorLength, self.bounds.size.height-lineHeight, separatorLength, lineHeight))
separatorView.backgroundColor = separatorColor
switch self.position {
case .Top:
let topSeparatorView: BBRootView = BBRootView.init(frame: CGRectMake(0, 0.2, BBDevice.deviceWidth(), lineHeight))
topSeparatorView.backgroundColor = separatorColor
self.addSubview(topSeparatorView)
break
case .Middle:
break
case .Bottom:
separatorView.setViewX(0)
separatorView.setViewWidth(BBDevice.deviceWidth())
break
case .Single:
break
default:
break
}
self.addSubview(separatorView)
}
// MARK: - --------------------手势事件--------------------
// MARK: 各种手势处理函数注释
// MARK: - --------------------按钮事件--------------------
// MARK: 按钮点击函数注释
// MARK: - --------------------代理方法--------------------
// MARK: - 代理种类注释
// MARK: 代理函数注释
// MARK: - --------------------属性相关--------------------
// MARK: 属性操作函数注释
// MARK: - --------------------接口API--------------------
func setGroupPositionForIndexPath(indexPath: NSIndexPath, tableView: UITableView) {
let rowsInSection: NSInteger = tableView.numberOfRowsInSection(indexPath.section)
let row = indexPath.row
var position: eGroupTableViewCellPosition = .Bottom
if row == 0 {
position = .Top
} else if (row < rowsInSection-1) {
position = .Middle
} else if (row == 1) {
position = .Single
}
if self.position != position {
self.position = position
}
}
/**
* 从XIB获取cell对象
*
* @param xibName xib名称
*/
class func cellFromXib(xibName: String) -> BBTableViewCell {
let array = NSBundle.mainBundle().loadNibNamed(xibName, owner: nil, options: nil)
var cell: BBTableViewCell!
if (array.count > 0) {
cell = array[0] as! BBTableViewCell
}
if (cell == nil) {
cell = BBTableViewCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
}
return cell;
}
/**
* 从XIB获取第index个对象cell
*
* @param xibName xib名称
* @param index 对象索引
*/
class func cellFromXib(xibName: String, index: NSInteger) -> BBTableViewCell {
let array = NSBundle.mainBundle().loadNibNamed(xibName, owner: nil, options: nil)
var cell: BBTableViewCell!
if (array.count > index) {
cell = array[index] as! BBTableViewCell
}
if (cell == nil) {
cell = BBTableViewCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
}
return cell;
}
/**
* 从XIB获取identifier对象cell
*
* @param xibName xib名称
* @param identifier 对象标识
*/
class func cellFromXib(xibName: String, identifier: String) -> BBTableViewCell {
let array = NSBundle.mainBundle().loadNibNamed(xibName, owner: nil, options: nil)
var cell: BBTableViewCell!
for i in 0 ..< array.count {
let view = array[i]
if ((view as? BBTableViewCell) != nil) {
cell = view as! BBTableViewCell
}
}
if (cell == nil) {
cell = BBTableViewCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
}
return cell
}
}
| 7ad8b2e04bb58bc9f718c0141469fd73 | 28.888199 | 179 | 0.552161 | false | false | false | false |
gb-6k-house/YsSwift | refs/heads/master | Sources/Rabbit/ImageView+Target.swift | mit | 1 | /******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: Rabbit + Image
** Copyright © 2017年 尧尚信息科技(www.yourshares.cn). All rights reserved
******************************************************************************/
import Foundation
#if YSSWIFT_DEBUG
import YsSwift
#endif
import Result
#if os(macOS)
import Cocoa
/// Alias for `NSImageView`
public typealias ImageView = NSImageView
#elseif os(iOS) || os(tvOS)
import UIKit
/// Alias for `UIImageView`
public typealias ImageView = UIImageView
#endif
#if os(macOS) || os(iOS) || os(tvOS)
/// Default implementation of `Target` protocol for `ImageView`.
extension ImageView: Target {
/// Displays an image on success. Runs `opacity` transition if
/// the response was not from the memory cache.
public func handle(response: Result<Image, YsSwift.RequestError>, isFromMemoryCache: Bool) {
guard let image = response.value else { return }
self.image = image
if !isFromMemoryCache {
let animation = CABasicAnimation(keyPath: "opacity")
animation.duration = 0.25
animation.fromValue = 0
animation.toValue = 1
let layer: CALayer? = self.layer // Make compiler happy on macOS
layer?.add(animation, forKey: "imageTransition")
}
}
}
#endif
extension YSSwift where Base: ImageView {
public func loadImage(with url: URL, placeholder placeholderImage: UIImage? = nil) {
//set placehold image
if let image = placeholderImage {
self.base.image = image
}
//load image
Rabbit.loadImage(with: url, into: self.base)
}
}
| 2d00770fd0e7172ceb9a21438c569890 | 29.278689 | 100 | 0.554413 | false | false | false | false |
makingspace/NetworkingServiceKit | refs/heads/develop | NetworkingServiceKit/Classes/Testing/ServiceStub.swift | mit | 1 | //
// Service.swift
// Makespace Inc.
//
// Created by Phillipe Casorla Sagot (@darkzlave) on 2/27/17.
//
//
import Foundation
/// Defines the Behavior of a stub response
///
/// - immediate: the sub returns inmediatly
/// - delayed: the stub returns after a defined number of seconds
public enum ServiceStubBehavior {
/// Return a response immediately.
case immediate
/// Return a response after a delay.
case delayed(seconds: TimeInterval)
}
private let validStatusCodes = (200...299)
/// Used for stubbing responses.
public enum ServiceStubType {
/// Builds a ServiceStubType from a HTTP Code and a local JSON file
///
/// - Parameters:
/// - jsonFile: the name of the bundled json file
/// - code: the http code. Success codes are (200..299)
public init(buildWith jsonFile:String, http code:Int) {
let response = JSONSerialization.JSONObjectWithFileName(fileName: jsonFile)
if validStatusCodes.contains(code) {
self = .success(code: code, response: response)
} else {
self = .failure(code: code, response: response)
}
}
/// The network returned a response, including status code and response.
case success(code:Int, response:[String:Any]?)
/// The network request failed with an error
case failure(code:Int, response:[String:Any]?)
}
/// Defines the scenario case that this request expects
///
/// - authenticated: service is authenticated
/// - unauthenticated: service is unauthenticated
public enum ServiceStubCase {
case authenticated(tokenInfo:[String:Any])
case unauthenticated
}
/// Defines a stub request case
public struct ServiceStubRequest {
/// URL Path to regex against upcoming requests
public let path:String
/// Optional parameters that will get compare as well against requests with the same kinda of parameters
public let parameters:[String:Any]?
public init(path:String, parameters:[String:Any]? = nil) {
self.path = path
self.parameters = parameters
}
}
/// Defines stub response for a matching API path
public struct ServiceStub {
/// A stubbed request
public let request:ServiceStubRequest
/// The type of stubbing we want to do, either a success or a failure
public let stubType:ServiceStubType
/// The behavior for this stub, if we want the request to come back sync or async
public let stubBehavior:ServiceStubBehavior
/// The type of case we want when the request gets executed, either authenticated with a token or unauthenticated
public let stubCase:ServiceStubCase
public init(execute request:ServiceStubRequest,
with type:ServiceStubType,
when stubCase:ServiceStubCase,
react behavior:ServiceStubBehavior)
{
self.request = request
self.stubType = type
self.stubBehavior = behavior
self.stubCase = stubCase
}
}
extension JSONSerialization
{
/// Builds a JSON Dictionary from a bundled json file
///
/// - Parameter fileName: the name of the json file
/// - Returns: returns a JSON dictionary
public class func JSONObjectWithFileName(fileName:String) -> [String:Any]?
{
if let path = Bundle.currentTestBundle?.path(forResource: fileName, ofType: "json"),
let jsonData = NSData(contentsOfFile: path),
let jsonResult = try! JSONSerialization.jsonObject(with: jsonData as Data, options: ReadingOptions.mutableContainers) as? [String:Any]
{
return jsonResult
}
return nil
}
}
extension Bundle {
/// Locates the first bundle with a '.xctest' file extension.
internal static var currentTestBundle: Bundle? {
return allBundles.first { $0.bundlePath.hasSuffix(".xctest") }
}
}
| 0dca590e175ba9e43aa59013e1e32e04 | 30.370968 | 146 | 0.669152 | false | false | false | false |
jpaffrath/mpd-ios | refs/heads/master | mpd-ios/MPD/MPDSong.swift | gpl-3.0 | 1 | //
// MPDSong.swift
// mpd-ios
//
// Created by Julius Paffrath on 17.12.16.
// Copyright © 2016 Julius Paffrath. All rights reserved.
//
import Foundation
class MPDSong: NSObject {
private(set) var artist: String = "No Artist"
private(set) var title: String = "No Title"
private(set) var album: String = "No Album"
private(set) var genre: String = "No Genre"
private(set) var track: Int = -1
private(set) var time: Int = -1
init(input: String) {
for line in input.characters.split(separator: "\n").map(String.init) {
if let sub = line.characters.index(of: ":") {
switch (line.substring(to: sub)) {
case "Artist":
self.artist = line.substring(from: "Artist: ".endIndex)
break
case "Title":
self.title = line.substring(from: "Title: ".endIndex)
break
case "Album":
self.album = line.substring(from: "Album: ".endIndex)
break
case "Genre":
self.genre = line.substring(from: "Genre: ".endIndex)
break
case "Track":
var track = line.substring(from: "Track: ".endIndex)
// parse tracks with
if track.contains("/") {
track = track.substring(to: "/".endIndex)
}
if let trackNr = Int(track) {
self.track = trackNr
}
break
case "Time":
let time = line.substring(from: "Time: ".endIndex)
if let timeInt = Int(time) {
self.time = timeInt
}
break
default:
break
}
}
}
}
/// Returns the length of the song as a formatted string
///
/// This will parse the seconds in MINUTES:SECONDS
/// - returns: length of the song as a string
func getSecondsString() -> String {
if self.time == -1 {
return "00:00"
}
let remain = self.time % 60
let seconds = self.time / 60
if remain / 10 == 0 {
return "\(seconds):0\(remain)"
}
return "\(seconds):\(remain)"
}
override func isEqual(_ object: Any?) -> Bool {
if let obj = object as? MPDSong {
if self === obj {
return true
}
if self.title == obj.title && self.artist == obj.artist &&
self.album == obj.album && self.track == obj.track {
return true
}
}
return false
}
}
| 1d282537eefe3f59c9c67a3d43e86233 | 30.170213 | 78 | 0.440614 | false | false | false | false |
OrlSan/ASViewControllerSwift | refs/heads/master | Sample/DetailCellNode.swift | mit | 1 | //
// DetailCellNode.swift
// Sample
//
// Created by Orlando on 22/07/17.
// Copyright © 2017 Orlando. All rights reserved.
//
import UIKit
import AsyncDisplayKit
class DetailCellNode: ASCellNode {
var row: Int = 0
var imageCategory: String = "abstract"
var imageNode: ASNetworkImageNode?
// The image URL
private var imageURL: URL {
get {
let imageSize: CGSize = self.calculatedSize
let urlWith = Int(imageSize.width)
let urlHeight = Int(imageSize.height)
return URL(string: "https://lorempixel.com/\(urlWith)/\(urlHeight)/\(imageCategory)/\(row)")!
}
}
required init(coder aDecoder: NSCoder) {
fatalError("Texture doest not support Storyboards")
}
override init() {
super.init()
self.automaticallyManagesSubnodes = true
self.imageNode = ASNetworkImageNode()
self.imageNode?.backgroundColor = ASDisplayNodeDefaultPlaceholderColor()
}
//MARK - ASDisplayNode
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
return ASRatioLayoutSpec.init(ratio: 1.0, child: self.imageNode!)
}
override func layoutDidFinish() {
super.layoutDidFinish()
self.imageNode?.url = self.imageURL
}
}
| d9dd5c332dda396594a771d191ae3788 | 25.568627 | 105 | 0.626568 | false | false | false | false |
NitWitStudios/NWSUrlValidator | refs/heads/master | Pod/Classes/NWSUrlValidator.swift | mit | 1 | //
// NWSUrlValidator.swift
// NWSUrlValidator
//
// Created by James Hickman on 08/27/2015.
// Copyright (c) 2015 James Hickman. All rights reserved.
//
public class NWSUrlValidator: NSObject
{
struct ValidationQueue {
static var queue = NSOperationQueue()
}
public class func validateUrl(urlString: String?, completion:(success: Bool, urlString: String? , error: NSString) -> Void)
{
// Description: This function will validate the format of a URL, re-format if necessary, then attempt to make a header request to verify the URL actually exists and responds.
// Return Value: This function has no return value but uses a closure to send the response to the caller.
var formattedUrlString : String?
// Ignore Nils & Empty Strings
if (urlString == nil || urlString == "")
{
completion(success: false, urlString: nil, error: "Url String was empty")
return
}
// Ignore prefixes (including partials)
let prefixes = ["http://www.", "https://www.", "www."]
for prefix in prefixes
{
if ((prefix.rangeOfString(urlString!, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)) != nil){
completion(success: false, urlString: nil, error: "Url String was prefix only")
return
}
}
// Ignore URLs with spaces
let range = urlString!.rangeOfCharacterFromSet(NSCharacterSet.whitespaceCharacterSet())
if let test = range {
completion(success: false, urlString: nil, error: "Url String cannot contain whitespaces")
return
}
// Check that URL already contains required 'http://' or 'https://', prepend if it does not
formattedUrlString = urlString
if (!formattedUrlString!.hasPrefix("http://") && !formattedUrlString!.hasPrefix("https://"))
{
formattedUrlString = "http://"+urlString!
}
// Check that an NSURL can actually be created with the formatted string
if let validatedUrl = NSURL(string: formattedUrlString!)
{
// Test that URL actually exists by sending a URL request that returns only the header response
var request = NSMutableURLRequest(URL: validatedUrl)
request.HTTPMethod = "HEAD"
ValidationQueue.queue.cancelAllOperations()
NSURLConnection.sendAsynchronousRequest(request, queue: ValidationQueue.queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
let url = request.URL!.absoluteString
// URL failed - No Response
if (error != nil)
{
completion(success: false, urlString: url, error: "The url: \(url) received no response")
return
}
// URL Responded - Check Status Code
if let urlResponse = response as? NSHTTPURLResponse
{
if ((urlResponse.statusCode >= 200 && urlResponse.statusCode < 400) || urlResponse.statusCode == 405)// 200-399 = Valid Responses, 405 = Valid Response (Weird Response on some valid URLs)
{
completion(success: true, urlString: url, error: "The url: \(url) is valid!")
return
}
else // Error
{
completion(success: false, urlString: url, error: "The url: \(url) received a \(urlResponse.statusCode) response")
return
}
}
})
}
}
} | ffbef35e0c989ccef099fc1c35a29e0c | 42.258427 | 207 | 0.56768 | false | false | false | false |
IngmarStein/Monolingual | refs/heads/main | Sources/HelperTask.swift | gpl-3.0 | 1 | //
// HelperTask.swift
// Monolingual
//
// Created by Ingmar Stein on 30.12.21.
// Copyright © 2021 Ingmar Stein. All rights reserved.
//
import Foundation
import AppKit
import UserNotifications
import OSLog
class HelperTask: ProgressProtocol, ObservableObject {
private var helperConnection: NSXPCConnection?
private var progress: Progress?
private var progressResetTimer: Timer?
private var progressObserverToken: NSKeyValueObservation?
private let logger = Logger()
@Published var text = ""
@Published var file = ""
@Published var byteCount: Int64 = 0
private lazy var xpcServiceConnection: NSXPCConnection = {
let connection = NSXPCConnection(serviceName: "com.github.IngmarStein.Monolingual.XPCService")
connection.remoteObjectInterface = NSXPCInterface(with: XPCServiceProtocol.self)
connection.resume()
return connection
}()
func checkAndRunHelper(arguments: HelperRequest) {
let xpcService = xpcServiceConnection.remoteObjectProxyWithErrorHandler { error -> Void in
self.logger.error("XPCService error: \(error.localizedDescription, privacy: .public)")
} as? XPCServiceProtocol
if let xpcService = xpcService {
xpcService.connect { endpoint -> Void in
if let endpoint = endpoint {
var performInstallation = false
let connection = NSXPCConnection(listenerEndpoint: endpoint)
let interface = NSXPCInterface(with: HelperProtocol.self)
interface.setInterface(NSXPCInterface(with: ProgressProtocol.self), for: #selector(HelperProtocol.process(request:progress:reply:)), argumentIndex: 1, ofReply: false)
connection.remoteObjectInterface = interface
connection.invalidationHandler = {
self.logger.error("XPC connection to helper invalidated.")
self.helperConnection = nil
if performInstallation {
self.installHelper { success in
if success {
self.checkAndRunHelper(arguments: arguments)
}
}
}
}
connection.resume()
self.helperConnection = connection
if let connection = self.helperConnection {
guard let helper = connection.remoteObjectProxyWithErrorHandler({ error in
self.logger.error("Error connecting to helper: \(error.localizedDescription, privacy: .public)")
}) as? HelperProtocol else {
self.logger.error("Helper does not conform to HelperProtocol")
return
}
helper.getVersion { installedVersion in
xpcService.bundledHelperVersion { bundledVersion in
if installedVersion == bundledVersion {
// helper is current
DispatchQueue.main.async {
self.runHelper(helper, arguments: arguments)
}
} else {
// helper is different version
performInstallation = true
// this triggers rdar://23143866 (duplicate of rdar://19601397)
// helper.uninstall()
helper.exit(code: Int(EXIT_SUCCESS))
connection.invalidate()
xpcService.disconnect()
}
}
}
}
} else {
self.logger.error("Failed to get XPC endpoint.")
self.installHelper { success in
if success {
self.checkAndRunHelper(arguments: arguments)
}
}
}
}
}
}
private func runHelper(_ helper: HelperProtocol, arguments: HelperRequest) {
ProcessInfo.processInfo.disableSuddenTermination()
text = "Removing..."
file = ""
let helperProgress = Progress(totalUnitCount: -1)
helperProgress.becomeCurrent(withPendingUnitCount: -1)
progressObserverToken = helperProgress.observe(\.completedUnitCount) { progress, _ in
if let url = progress.fileURL, let size = progress.userInfo[ProgressUserInfoKey.sizeDifference] as? Int {
self.processProgress(file: url, size: size, appName: progress.userInfo[ProgressUserInfoKey.appName] as? String)
}
}
// DEBUG
// arguments.dryRun = true
helper.process(request: arguments, progress: self) { exitCode in
self.logger.info("helper finished with exit code: \(exitCode, privacy: .public)")
helper.exit(code: exitCode)
if exitCode == Int(EXIT_SUCCESS) {
DispatchQueue.main.async {
self.progressDidEnd(completed: true)
}
}
}
helperProgress.resignCurrent()
progress = helperProgress
progressObserverToken = helperProgress.observe(\.completedUnitCount) { progress, _ in
if let url = progress.fileURL, let size = progress.userInfo[ProgressUserInfoKey.sizeDifference] as? Int {
self.processProgress(file: url, size: size, appName: progress.userInfo[ProgressUserInfoKey.appName] as? String)
}
}
showingProgressView = true
let content = UNMutableNotificationContent()
content.title = NSLocalizedString("Monolingual started", comment: "")
content.body = NSLocalizedString("Started removing files", comment: "")
let now = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second, .timeZone], from: Date())
let trigger = UNCalendarNotificationTrigger(dateMatching: now, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString,
content: content,
trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
func installHelper(reply: @escaping (Bool) -> Void) {
let xpcService = xpcServiceConnection.remoteObjectProxyWithErrorHandler { error -> Void in
self.logger.error("XPCService error: \(error.localizedDescription, privacy: .public)")
} as? XPCServiceProtocol
if let xpcService = xpcService {
xpcService.installHelperTool { error in
if let error = error {
DispatchQueue.main.async {
let alert = NSAlert()
alert.alertStyle = .critical
alert.messageText = error.localizedDescription
alert.informativeText = error.localizedRecoverySuggestion ?? error.localizedFailureReason ?? " "
alert.beginSheetModal(for: self.view.window!, completionHandler: nil)
log.close()
}
reply(false)
} else {
reply(true)
}
}
}
}
func processed(file: String, size: Int, appName: String?) {
if let progress = progress {
let count = progress.userInfo[.fileCompletedCountKey] as? Int ?? 0
progress.setUserInfoObject(count + 1, forKey: .fileCompletedCountKey)
progress.setUserInfoObject(URL(fileURLWithPath: file, isDirectory: false), forKey: .fileURLKey)
progress.setUserInfoObject(size, forKey: ProgressUserInfoKey.sizeDifference)
if let appName = appName {
progress.setUserInfoObject(appName, forKey: ProgressUserInfoKey.appName)
}
progress.completedUnitCount += Int64(size)
// show the file progress even if it has zero bytes
if size == 0 {
progress.willChangeValue(forKey: #keyPath(Progress.completedUnitCount))
progress.didChangeValue(forKey: #keyPath(Progress.completedUnitCount))
}
}
}
public func cancel() {
text = "Canceling operation..."
file = ""
progressDidEnd(completed: false)
}
private func progressDidEnd(completed: Bool) {
guard let progress = progress else { return }
processApplication = nil
showingProgressView = false
progressResetTimer?.invalidate()
progressResetTimer = nil
byteCount = max(progress.completedUnitCount, 0)
progressObserverToken?.invalidate()
self.progress = nil
if !completed {
// cancel the current progress which tells the helper to stop
progress.cancel()
logger.debug("Closing progress connection")
if let helper = helperConnection?.remoteObjectProxy as? HelperProtocol {
helper.exit(code: Int(EXIT_FAILURE))
}
let alert = NSAlert()
alert.alertStyle = .informational
alert.messageText = NSLocalizedString("You cancelled the removal. Some files were erased, some were not.", comment: "")
alert.informativeText = String(format: NSLocalizedString("Space saved: %@.", comment: ""), byteCount)
alert.beginSheetModal(for: view.window!, completionHandler: nil)
} else {
let alert = NSAlert()
alert.alertStyle = .informational
alert.messageText = NSLocalizedString("Files removed.", comment: "")
alert.informativeText = String(format: NSLocalizedString("Space saved: %@.", comment: ""), byteCount)
alert.beginSheetModal(for: view.window!, completionHandler: nil)
let content = UNMutableNotificationContent()
content.title = NSLocalizedString("Monolingual finished", comment: "")
content.body = NSLocalizedString("Finished removing files", comment: "")
let now = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second, .timeZone], from: Date())
let trigger = UNCalendarNotificationTrigger(dateMatching: now, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString,
content: content,
trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
if let connection = helperConnection {
logger.info("Closing connection to helper")
connection.invalidate()
helperConnection = nil
}
log.close()
ProcessInfo.processInfo.enableSuddenTermination()
}
private func processProgress(file: URL, size: Int, appName: String?) {
log.message("\(file.path): \(size)\n")
let message: String
if mode == .architectures {
message = NSLocalizedString("Removing architecture from universal binary", comment: "")
} else {
// parse file name
var lang: String?
if mode == .languages {
for pathComponent in file.pathComponents where (pathComponent as NSString).pathExtension == "lproj" {
for language in self.languages {
if language.folders.contains(pathComponent) {
lang = language.displayName
break
}
}
}
}
if let app = appName, let lang = lang {
message = String(format: NSLocalizedString("Removing language %@ from %@…", comment: ""), lang, app)
} else if let lang = lang {
message = String(format: NSLocalizedString("Removing language %@…", comment: ""), lang)
} else {
message = String(format: NSLocalizedString("Removing %@…", comment: ""), file.absoluteString)
}
}
self.text = message
self.file = file.path
self.progressResetTimer?.invalidate()
self.progressResetTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { _ in
self.text = NSLocalizedString("Removing...", comment: "")
self.file = ""
}
}
}
| 9a86dcea7bc599d292f74323033ecf3b | 34.153584 | 171 | 0.706311 | false | false | false | false |
jatiwn/geocore-tutorial-1 | refs/heads/master | Carthage/Checkouts/geocore-swift/GeocoreKit/Geocore.swift | apache-2.0 | 1 | //
// Geocore.swift
// GeocoreKit
//
// Created by Purbo Mohamad on 4/14/15.
//
//
import Foundation
import Alamofire
import SwiftyJSON
import PromiseKit
/**
GeocoreKit error domain.
*/
public let GeocoreErrorDomain = "jp.geocore.error"
private let MMG_SETKEY_BASE_URL = "GeocoreBaseURL"
private let MMG_SETKEY_PROJECT_ID = "GeocoreProjectId"
private let HTTPHEADER_ACCESS_TOKEN_NAME = "Geocore-Access-Token"
/**
GeocoreKit jjmjjjjjjerror code.
- INVALID_STATE: Unexpected internal state. Possibly a bug.
- INVALID_SERVER_RESPONSE: Unexpected server response. Possibly a bug.
- SERVER_ERROR: Server returns an error.
- TOKEN_UNDEFINED: Token is unavailable. Possibly the library is left uninitialized or user is not logged in.
- UNAUTHORIZED_ACCESS: Access to the specified resource is forbidden. Possibly the user is not logged in.
- INVALID_PARAMETER: One of the parameter passed to the API is invalid
*/
public enum GeocoreError: Int {
case INVALID_STATE
case INVALID_SERVER_RESPONSE
case SERVER_ERROR
case TOKEN_UNDEFINED
case UNAUTHORIZED_ACCESS
case INVALID_PARAMETER
}
/**
Representing an object that can be initialized from JSON data.
*/
public protocol GeocoreInitializableFromJSON {
init(_ json: JSON)
}
/**
Representing an object that can be serialized to JSON.
*/
public protocol GeocoreSerializableToJSON {
func toDictionary() -> [String: AnyObject]
}
/**
A raw JSON value returned by Geocore service.
*/
public class GeocoreGenericResult: GeocoreInitializableFromJSON {
var json: JSON
public required init(_ json: JSON) {
self.json = json
}
}
// Work-around for Swift compiler unimplemented feature error: 'unimplemented IR generation feature non-fixed multi-payload enum layout'
// see:
// http://owensd.io/2014/07/09/error-handling.html
// https://github.com/owensd/SwiftLib/blob/master/Source/Failable.swift
// ultimately this wrapper will not be necessary once the compiler is fixed.
public class GeocoreResultValueWrapper<T> {
let value: T
public init(_ value: T) { self.value = value }
}
/**
Representing a result returned by Geocore service.
- Success: Containing value of the result.
- Failure: Containing an error.
*/
public enum GeocoreResult<T> {
case Success(GeocoreResultValueWrapper<T>)
case Failure(NSError)
public init(_ value: T) {
self = .Success(GeocoreResultValueWrapper(value))
}
public init(_ error: NSError) {
self = .Failure(error)
}
public var failed: Bool {
switch self {
case .Failure(let error):
return true
default:
return false
}
}
public var error: NSError? {
switch self {
case .Failure(let error):
return error
default:
return nil
}
}
public var value: T? {
switch self {
case .Success(let wrapper):
return wrapper.value
default:
return nil
}
}
public func propagateTo(fulfiller: (T) -> Void, rejecter: (NSError) -> Void) -> Void {
switch self {
case .Success(let wrapper):
fulfiller(wrapper.value)
case .Failure(let error):
rejecter(error)
}
}
}
// MARK: -
/**
* Main singleton class.
*/
public class Geocore: NSObject {
/// Singleton instance
public static let sharedInstance = Geocore()
public static let geocoreDateFormatter = NSDateFormatter.dateFormatterForGeocore()
public private(set) var baseURL: String?
public private(set) var projectId: String?
private var token: String?
private override init() {
self.baseURL = NSBundle.mainBundle().objectForInfoDictionaryKey(MMG_SETKEY_BASE_URL) as? String
self.projectId = NSBundle.mainBundle().objectForInfoDictionaryKey(MMG_SETKEY_PROJECT_ID) as? String
}
/**
Setting up the library.
:param: baseURL Geocore server endpoint
:param: projectId Project ID
:returns: Geocore object
*/
public func setup(baseURL: String, projectId: String) -> Geocore {
self.baseURL = baseURL;
self.projectId = projectId;
return self;
}
// MARK: Private utilities
private func path(servicePath: String) -> String? {
if let baseURL = self.baseURL {
return baseURL + servicePath
} else {
return nil
}
}
private func mutableURLRequest(method: Alamofire.Method, path: String, token: String) -> NSMutableURLRequest {
let ret = NSMutableURLRequest(URL: NSURL(string: path)!)
ret.HTTPMethod = method.rawValue
ret.setValue(token, forHTTPHeaderField: HTTPHEADER_ACCESS_TOKEN_NAME)
return ret
}
private func generateMultipartBoundaryConstant() -> String {
return NSString(format: "Boundary+%08X%08X", arc4random(), arc4random()) as String
}
private func multipartURLRequest(method: Alamofire.Method, path: String, token: String, fieldName: String, fileName: String, mimeType: String, fileContents: NSData) -> NSMutableURLRequest {
let mutableURLRequest = self.mutableURLRequest(.POST, path: path, token: token)
let boundaryConstant = self.generateMultipartBoundaryConstant()
let boundaryStart = "--\(boundaryConstant)\r\n"
let boundaryEnd = "--\(boundaryConstant)--\r\n"
let contentDispositionString = "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(fileName)\"\r\n"
let contentTypeString = "Content-Type: \(mimeType)\r\n\r\n"
let requestBodyData : NSMutableData = NSMutableData()
requestBodyData.appendData(boundaryStart.dataUsingEncoding(NSUTF8StringEncoding)!)
requestBodyData.appendData(contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding)!)
requestBodyData.appendData(contentTypeString.dataUsingEncoding(NSUTF8StringEncoding)!)
requestBodyData.appendData(fileContents)
requestBodyData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
requestBodyData.appendData(boundaryEnd.dataUsingEncoding(NSUTF8StringEncoding)!)
mutableURLRequest.setValue("multipart/form-data; boundary=\(boundaryConstant)", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = requestBodyData
return mutableURLRequest
}
private func parameterEncoding(method: Alamofire.Method) -> Alamofire.ParameterEncoding {
switch method {
case .GET, .HEAD, .DELETE:
return .URL
default:
return .JSON
}
}
// from Alamofire internal
func escape(string: String) -> String {
let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*"
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
// from Alamofire internal
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
private func multipartInfo(_ body: [String: AnyObject]? = nil) -> (fileContents: NSData, fileName: String, fieldName: String, mimeType: String)? {
if let fileContents = body?["$fileContents"] as? NSData {
if let fileName = body?["$fileName"] as? String, fieldName = body?["$fieldName"] as? String, mimeType = body?["$mimeType"] as? String {
return (fileContents, fileName, fieldName, mimeType)
}
}
return nil
}
private func validateRequestBody(_ body: [String: AnyObject]? = nil) -> Bool {
if let fileContent = body?["$fileContents"] as? NSData {
// uploading file, make sure all required parameters are specified as well
if let fileName = body?["$fileName"] as? String, fieldName = body?["$fieldName"] as? String, mimeType = body?["$mimeType"] as? String {
return true
} else {
return false
}
} else {
return true
}
}
private func buildQueryParameter(mutableURLRequest: NSMutableURLRequest, parameters: [String: AnyObject]?) -> NSURL? {
if let someParameters = parameters {
// from Alamofire internal
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += self.queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
// since we have both non-nil parameters and body,
// the parameters should go to URL query parameters,
// and the body should go to HTTP body
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(someParameters)
return URLComponents.URL
}
}
return nil
}
/**
Build and customize Alamofire request with Geocore token and optional parameter/body specification.
:param: method Alamofire Method enum representing HTTP request method
:param: parameters parameters to be used as URL query parameters (for GET, DELETE) or POST parameters in the body except is body parameter is not nil. For POST, ff body parameter is not nil it will be encoded as POST body (JSON or multipart) and parameters will become URL query parameters.
:param: body POST JSON or multipart content. For multipart content, the body will have to contain following key-values: ("$fileContents" => NSData), ("$fileName" => String), ("$fieldName" => String), ("$mimeType" => String)
:returns: function that given a URL path will generate appropriate Alamofire Request object.
*/
private func requestBuilder(method: Alamofire.Method, parameters: [String: AnyObject]? = nil, body: [String: AnyObject]? = nil) -> ((String) -> Request)? {
if !self.validateRequestBody(body) {
return nil
}
if let token = self.token {
// if token is available (user already logged-in), use NSMutableURLRequest to customize HTTP header
return { (path: String) -> Request in
// NSMutableURLRequest with customized HTTP header
var mutableURLRequest: NSMutableURLRequest
if let multipartInfo = self.multipartInfo(body) {
mutableURLRequest = self.multipartURLRequest(method, path: path, token: token, fieldName: multipartInfo.fieldName, fileName: multipartInfo.fileName, mimeType: multipartInfo.mimeType, fileContents: multipartInfo.fileContents)
} else {
mutableURLRequest = self.mutableURLRequest(method, path: path, token: token)
}
if let someBody = body {
// pass parameters as query parameters, body to be processed by Alamofire
if let url = self.buildQueryParameter(mutableURLRequest, parameters: parameters) {
mutableURLRequest.URL = url
}
return Alamofire.request(self.parameterEncoding(method).encode(mutableURLRequest, parameters: someBody).0)
} else {
// set parameters according to standard Alamofire's encode processing
return Alamofire.request(self.parameterEncoding(method).encode(mutableURLRequest, parameters: parameters).0)
}
}
} else {
if let someBody = body {
// no token but with body & parameters separate
return { (path: String) -> Request in
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: path)!)
mutableURLRequest.HTTPMethod = method.rawValue
if let url = self.buildQueryParameter(mutableURLRequest, parameters: parameters) {
mutableURLRequest.URL = url
}
return Alamofire.request(self.parameterEncoding(method).encode(mutableURLRequest, parameters: someBody).0)
}
} else {
// otherwise do a normal Alamofire request
return { (path: String) -> Request in Alamofire.request(method, path, parameters: parameters) }
}
}
}
/**
The ultimate generic request method.
:param: path Path relative to base API URL.
:param: requestBuilder Function to be used to create Alamofire request.
:param: onSuccess What to do when the server successfully returned a result.
:param: onError What to do when there is an error.
*/
private func request(
path: String,
requestBuilder: (String) -> Request,
onSuccess: (JSON) -> Void,
onError: (NSError) -> Void) {
requestBuilder(self.path(path)!).response { (_, res, optData, optError) -> Void in
if let error = optError {
println("[ERROR] \(error)")
onError(error)
} else if let data = optData {
if let statusCode = res?.statusCode {
switch statusCode {
case 200:
let json = JSON(data: data)
if let status = json["status"].string {
if status == "success" {
onSuccess(json["result"])
} else {
// pass on server error info as userInfo
onError(
NSError(
domain: GeocoreErrorDomain,
code: GeocoreError.SERVER_ERROR.rawValue,
userInfo: [
"code": json["code"].string ?? "",
"message": json["message"].string ?? ""
]))
}
} else {
onError(NSError(domain: GeocoreErrorDomain, code: GeocoreError.INVALID_SERVER_RESPONSE.rawValue, userInfo: nil))
}
case 403:
onError(NSError(domain: GeocoreErrorDomain, code: GeocoreError.UNAUTHORIZED_ACCESS.rawValue, userInfo: nil))
default:
onError(NSError(domain: GeocoreErrorDomain, code: GeocoreError.INVALID_SERVER_RESPONSE.rawValue, userInfo: ["statusCode": statusCode]))
}
} else {
// TODO: should specify the error futher in userInfo
onError(NSError(domain: GeocoreErrorDomain, code: GeocoreError.INVALID_SERVER_RESPONSE.rawValue, userInfo: nil))
}
}
}
}
/**
Request resulting a single result of type T.
*/
func request<T: GeocoreInitializableFromJSON>(path: String, requestBuilder optRequestBuilder: ((String) -> Request)?, callback: (GeocoreResult<T>) -> Void) {
if let requestBuilder = optRequestBuilder {
self.request(path, requestBuilder: requestBuilder,
onSuccess: { (json: JSON) -> Void in callback(GeocoreResult(T(json))) },
onError: { (error: NSError) -> Void in callback(.Failure(error)) })
} else {
callback(.Failure(NSError(domain: GeocoreErrorDomain, code: GeocoreError.INVALID_PARAMETER.rawValue, userInfo: ["message": "Unable to build request, likely because of unexpected parameters."])))
}
}
/**
Request resulting multiple result in an array of objects of type T
*/
func request<T: GeocoreInitializableFromJSON>(path: String, requestBuilder optRequestBuilder: ((String) -> Request)?, callback: (GeocoreResult<[T]>) -> Void) {
if let requestBuilder = optRequestBuilder {
self.request(path, requestBuilder: requestBuilder,
onSuccess: { (json: JSON) -> Void in
if let result = json.array {
callback(GeocoreResult(result.map { T($0) }))
} else {
callback(GeocoreResult([]))
}
},
onError: { (error: NSError) -> Void in callback(.Failure(error)) })
} else {
callback(.Failure(NSError(domain: GeocoreErrorDomain, code: GeocoreError.INVALID_PARAMETER.rawValue, userInfo: ["message": "Unable to build request, likely because of unexpected parameters."])))
}
}
// MARK: HTTP methods: GET, POST, DELETE, PUT
/**
Do an HTTP GET request expecting one result of type T
*/
func GET<T: GeocoreInitializableFromJSON>(path: String, parameters: [String: AnyObject]? = nil, callback: (GeocoreResult<T>) -> Void) {
self.request(path, requestBuilder: self.requestBuilder(.GET, parameters: parameters), callback: callback)
}
/**
Promise a single result of type T from an HTTP GET request.
*/
func promisedGET<T: GeocoreInitializableFromJSON>(path: String, parameters: [String: AnyObject]? = nil) -> Promise<T> {
return Promise { (fulfiller, rejecter) in
self.GET(path, parameters: parameters) { (result: GeocoreResult<T>) -> Void in
result.propagateTo(fulfiller, rejecter: rejecter)
}
}
}
/**
Do an HTTP GET request expecting an multiple result in an array of objects of type T
*/
func GET<T: GeocoreInitializableFromJSON>(path: String, parameters: [String: AnyObject]? = nil, callback: (GeocoreResult<[T]>) -> Void) {
self.request(path, requestBuilder: self.requestBuilder(.GET, parameters: parameters), callback: callback)
}
/**
Promise multiple result of type T from an HTTP GET request.
*/
func promisedGET<T: GeocoreInitializableFromJSON>(path: String, parameters: [String: AnyObject]? = nil) -> Promise<[T]> {
return Promise { (fulfiller, rejecter) in
self.GET(path, parameters: parameters) { (result: GeocoreResult<[T]>) -> Void in
result.propagateTo(fulfiller, rejecter: rejecter)
}
}
}
/**
Do an HTTP POST request expecting one result of type T
*/
func POST<T: GeocoreInitializableFromJSON>(path: String, parameters: [String: AnyObject]? = nil, body: [String: AnyObject]? = nil, callback: (GeocoreResult<T>) -> Void) {
self.request(path, requestBuilder: self.requestBuilder(.POST, parameters: parameters, body: body), callback: callback)
}
func uploadPOST<T: GeocoreInitializableFromJSON>(path: String, parameters: [String: AnyObject]? = nil, fieldName: String, fileName: String, mimeType: String, fileContents: NSData, callback: (GeocoreResult<T>) -> Void) {
self.POST(path, parameters: parameters, body: ["$fileContents": fileContents, "$fileName": fileName, "$fieldName": fieldName, "$mimeType": mimeType], callback: callback)
}
/**
Promise a single result of type T from an HTTP POST request.
*/
func promisedPOST<T: GeocoreInitializableFromJSON>(path: String, parameters: [String: AnyObject]? = nil, body: [String: AnyObject]? = nil) -> Promise<T> {
return Promise { (fulfiller, rejecter) in
self.POST(path, parameters: parameters, body: body) { (result: GeocoreResult<T>) -> Void in
result.propagateTo(fulfiller, rejecter: rejecter)
}
}
}
func promisedUploadPOST<T: GeocoreInitializableFromJSON>(path: String, parameters: [String: AnyObject]? = nil, fieldName: String, fileName: String, mimeType: String, fileContents: NSData) -> Promise<T> {
return self.promisedPOST(path, parameters: parameters, body: ["$fileContents": fileContents, "$fileName": fileName, "$fieldName": fieldName, "$mimeType": mimeType])
}
/**
Do an HTTP DELETE request expecting one result of type T
*/
func DELETE<T: GeocoreInitializableFromJSON>(path: String, parameters: [String: AnyObject]? = nil, callback: (GeocoreResult<T>) -> Void) {
self.request(path, requestBuilder: self.requestBuilder(.DELETE, parameters: parameters), callback: callback)
}
/**
Promise a single result of type T from an HTTP DELETE request.
*/
func promisedDELETE<T: GeocoreInitializableFromJSON>(path: String, parameters: [String: AnyObject]? = nil) -> Promise<T> {
return Promise { (fulfiller, rejecter) in
self.DELETE(path, parameters: parameters) { (result: GeocoreResult<T>) -> Void in
result.propagateTo(fulfiller, rejecter: rejecter)
}
}
}
// MARK: User management methods (callback version)
/**
Login to Geocore with callback.
:param: userId User's ID to be submitted.
:param: password Password for authorizing user.
:param: callback Closure to be called when the token string or an error is returned.
*/
public func login(userId: String, password: String, callback:(GeocoreResult<String>) -> Void) {
self.POST("/auth", parameters: ["id": userId, "password": password, "project_id": self.projectId!]) { (result: GeocoreResult<GeocoreGenericResult>) -> Void in
switch result {
case .Success(let wrapper):
self.token = wrapper.value.json["token"].string
if let token = self.token {
callback(GeocoreResult(token))
} else {
callback(.Failure(NSError(domain: GeocoreErrorDomain, code: GeocoreError.INVALID_STATE.rawValue, userInfo: nil)))
}
case .Failure(let error):
callback(.Failure(error))
}
}
}
public func loginWithDefaultUser(callback:(GeocoreResult<String>) -> Void) {
// login using default id & password
self.login(GeocoreUser.defaultId(), password: GeocoreUser.defaultPassword()) { result in
switch result {
case .Success(let wrapper):
callback(result)
case .Failure(let error):
// oops! try to register first
if let errorCode = error.userInfo?["code"] as? String {
if errorCode == "Auth.0001" {
// not registered, register the default user first
GeocoreUser.defaultUser().register() { result in
switch result {
case .Success(let wrapper):
// successfully registered, now login again
self.login(GeocoreUser.defaultId(), password: GeocoreUser.defaultPassword()) { result in
callback(result)
}
case .Failure(let error):
callback(.Failure(error))
}
}
} else {
// unexpected error
callback(.Failure(error))
}
} else {
// unexpected error
callback(.Failure(error))
}
}
}
}
// MARK: User management methods (promise version)
/**
Login to Geocore with promise.
:param: userId User's ID to be submitted.
:param: password Password for authorizing user.
:returns: Promise for Geocore Access Token (as String).
*/
public func login(userId: String, password: String) -> Promise<String> {
return Promise { (fulfiller, rejecter) in
self.login(userId, password: password) { result in
result.propagateTo(fulfiller, rejecter: rejecter)
}
}
}
public func loginWithDefaultUser() -> Promise<String> {
return Promise { (fulfiller, rejecter) in
self.loginWithDefaultUser { result in
result.propagateTo(fulfiller, rejecter: rejecter)
}
}
}
}
| b7e10d963406c438ddd88503c03d606a | 42.034711 | 298 | 0.583577 | false | false | false | false |
burhanaksendir/VideoSplash | refs/heads/master | VideoSplash/Source/VideoSplashViewController.swift | mit | 6 | //
// VideoSplashViewController.swift
// VideoSplash
//
// Created by Toygar Dündaralp on 8/3/15.
// Copyright (c) 2015 Toygar Dündaralp. All rights reserved.
//
import UIKit
import MediaPlayer
public enum ScalingMode {
case AspectFill
case AspectFit
case Fill
case None
}
public class VideoSplashViewController: UIViewController {
private let moviePlayer = MPMoviePlayerController()
public var contentURL: NSURL = NSURL() {
didSet {
setMoviePlayer(contentURL)
}
}
public var videoFrame: CGRect = CGRect()
public var startTime: CGFloat = 0.0
public var duration: CGFloat = 0.0
public var backgroundColor: UIColor = UIColor.blackColor() {
didSet {
view.backgroundColor = backgroundColor
}
}
public var alpha: CGFloat = CGFloat() {
didSet {
moviePlayer.view.alpha = alpha
}
}
public var alwaysRepeat: Bool = true {
didSet {
if alwaysRepeat {
moviePlayer.repeatMode = MPMovieRepeatMode.One
}else{
moviePlayer.repeatMode = MPMovieRepeatMode.None
}
}
}
public var fillMode: ScalingMode = .AspectFill {
didSet {
switch fillMode {
case .AspectFill:
moviePlayer.scalingMode = MPMovieScalingMode.AspectFill
case .AspectFit:
moviePlayer.scalingMode = MPMovieScalingMode.AspectFit
case .Fill:
moviePlayer.scalingMode = MPMovieScalingMode.Fill
case .None:
moviePlayer.scalingMode = MPMovieScalingMode.None
default:
moviePlayer.scalingMode = MPMovieScalingMode.None
}
}
}
override public func viewDidAppear(animated: Bool) {
moviePlayer.view.frame = videoFrame
moviePlayer.controlStyle = MPMovieControlStyle.None
moviePlayer.movieSourceType = MPMovieSourceType.File
view.addSubview(moviePlayer.view)
view.sendSubviewToBack(moviePlayer.view)
}
private func setMoviePlayer(url: NSURL){
let videoCutter = VideoCutter()
videoCutter.cropVideoWithUrl(videoUrl: url, startTime: startTime, duration: duration) { (videoPath, error) -> Void in
if let path = videoPath as NSURL? {
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
dispatch_async(dispatch_get_main_queue()) {
self.moviePlayer.contentURL = path
self.moviePlayer.play()
}
}
}
}
}
override public func viewDidLoad() {
super.viewDidLoad()
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 6951f3dc95342175c4f77dafedd852f5 | 25.306122 | 121 | 0.680372 | false | false | false | false |
peterk9/card-2.io-iOS-SDK-master | refs/heads/master | SampleApp-Swift/SampleApp-Swift/FinalViewController.swift | mit | 1 | //
// FinalViewController.swift
// RBCInstaBank
//
// Created by Kevin Peters on 2015-08-14.
// Copyright © 2015 Punskyy, Roman. All rights reserved.
//
import UIKit
class FinalViewController: UIViewController {
@IBOutlet weak var eSignBtn: UIButton!
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var thankyou: UILabel!
@IBOutlet weak var rbcLogi: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.rbcLogi.alpha = 0
self.thankyou.alpha = 0
self.rbcLogi.hidden = true
self.thankyou.hidden = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func eSignButtonPress(sender: AnyObject) {
self.eSignBtn.hidden = true
self.label1.hidden = true
self.label2.hidden = true
UIView.animateWithDuration(1.0, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.rbcLogi.hidden = false
self.thankyou.hidden = false
self.rbcLogi.alpha = 1
self.thankyou.alpha = 1
}, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| f0928888c858f7fd815e1231b46badd6 | 29.785714 | 125 | 0.649072 | false | false | false | false |
bcylin/QuickTableViewController | refs/heads/develop | Example-iOS/SwiftUI/SettingsView.swift | mit | 1 | //
// SettingsView.swift
// Example-iOS
//
// Created by Ben on 14/08/2022.
// Copyright © 2022 bcylin.
//
// 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 SwiftUI
@available(iOS 13.0, *)
struct SettingsView: View {
@ObservedObject var viewModel: SettingsViewModel
var body: some View {
Form {
Section(header: Text("Switch")) {
Toggle(isOn: $viewModel.flag1) {
subtitleCellStyle(title: "Setting 1", subtitle: "Example subtitle")
.leadingIcon("globe")
}
Toggle(isOn: $viewModel.flag2) {
subtitleCellStyle(title: "Setting 2", subtitle: nil)
.leadingIcon("clock.arrow.circlepath")
}
}
Section(header: Text("Tap Action")) {
Button {
viewModel.performTapAction()
} label: {
Text("Tap action").frame(maxWidth: .infinity)
}
}
Section(header: Text("Cell Style"), footer: Text("CellStyle.value2 is not implemented")) {
subtitleCellStyle(title: "CellStyle.default", subtitle: nil)
.leadingIcon("gear")
subtitleCellStyle(title: "CellStyle.default", subtitle: ".subtitle")
.leadingIcon("globe")
value1CellStyle(title: "CellStyle", detailText: ".value1")
.leadingIcon("clock.arrow.circlepath")
.navigationFlow { viewModel.startNavigationFlow() }
}
Section(header: Text("Picker")) {
Picker("Allow multiple selections", selection: $viewModel.allowsMultipleSelection) {
Text("No").tag(false)
Text("Yes").tag(true)
}
}
Section(header: Text("Radio Button")) {
ForEach(SettingsViewModel.Option.allCases) { option in
checkmarkCellStyle(with: option, isSelected: viewModel.isOptionSelected(option))
}
}
}
}
private func subtitleCellStyle(title: String, subtitle: String?) -> some View {
VStack(alignment: .leading) {
Text(title)
if let subtitle = subtitle {
Text(subtitle).font(.caption)
}
}
}
private func value1CellStyle(title: String, detailText: String) -> some View {
HStack {
Text(title).foregroundColor(.primary)
Spacer()
Text(detailText).foregroundColor(.secondary)
}
}
private func checkmarkCellStyle(with option: SettingsViewModel.Option, isSelected: Bool) -> some View {
Button {
viewModel.toggleOption(option)
} label: {
HStack {
Text(option.title).foregroundColor(.primary)
Spacer()
Image(systemName: "checkmark").opacity(isSelected ? 1 : 0)
}
}
}
}
// MARK: -
@available(iOS 13.0, *)
private extension View {
func leadingIcon(_ systemName: String, imageScale: Image.Scale = .large, foregroundColor: Color = .primary) -> some View {
// Label { self } icon: { icon } if #available(iOS 14.0, *)
HStack {
Image(systemName: systemName).imageScale(imageScale).foregroundColor(foregroundColor)
self
}
}
func trailingIcon(_ systemName: String, imageScale: Image.Scale = .small, foregroundColor: Color = .secondary) -> some View {
HStack {
self
Image(systemName: systemName).imageScale(imageScale).foregroundColor(foregroundColor)
}
}
func navigationFlow(action: @escaping () -> Void) -> some View {
Button {
action()
} label: {
self.trailingIcon("chevron.forward")
}
}
}
// MARK: -
@available(iOS 13.0, *)
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView(viewModel: SettingsViewModel())
}
}
| ffb91f07b5df7e017d06f2db5b6c47d6 | 34.8125 | 129 | 0.587745 | false | false | false | false |
s9998373/PHP-SRePS | refs/heads/master | PHP-SRePS/PHP-SRePS/SalesDataSource.swift | mit | 1 | //
// SalesDataSource.swift
// PHP-SRePS
//
// Created by Terry Lewis on 16/08/2016.
// Copyright © 2016 swindp2. All rights reserved.
//
import Foundation
import RealmSwift
extension Results {
/// Allows translation from a Results to an NSArray.
///
/// - returns: The Results in NSArray format.
func toNSArray() -> NSArray {
return self.map{$0}
}
}
extension RealmSwift.List {
/// Allows translation from a Realm list to an NSArray.
///
/// - returns: The Realm list in NSArray format.
func toNSArray() -> NSArray {
return self.map{$0}
}
}
extension NSDate {
/// Determines if a date lies between two dates (inclusive).
///
/// - parameter beginDate: The start date.
/// - parameter endDate: The end date.
///
/// - returns: True if the date lies between each of the provided dates, inclusively, otherwise, false
func dateLiesBetweenDates(beginDate: NSDate, endDate: NSDate) -> Bool {
if self.compare(beginDate) == .OrderedAscending {
return false
}
if self.compare(endDate) == .OrderedDescending {
return false
}
return true
}
}
class SalesDataSource: NSObject {
static let sharedManager = SalesDataSource();
var realm: Realm!;
override init() {
super.init();
self.instateDatabase()
}
/// Adds a Product to the database.
///
/// - parameter item: The product to be added.
///
/// - returns: True if the operation was successful, otherwise, false.
func addSalesProduct(item: Product) -> Bool{
return abstractAdd(item);
}
/// Removes a product from the database.
///
/// - parameter item: The product to be removed.
///
/// - returns: True if the operation was successful, otherwise, false.
func removeSalesProduct(item: Product) -> Bool{
return abstractDelete(item);
}
/// Returns all products contained within the database.
///
/// - returns: An array of all of the products.
func allProducts() -> NSArray{
return realm.objects(Product).toNSArray();
}
/// Adds a transation to the database.
///
/// - parameter item: The transaction to be added.
///
/// - returns: True if the operation was successful, otherwise, false.
func addTransaction(item: Transaction) -> Bool{
return addTransaction(item, write: true)
}
/// Adds a transation to the database.
///
/// - parameter item: The transaction to be added.
///
/// - returns: True if the operation was successful, otherwise, false.
func addTransaction(item: Transaction, write: Bool) -> Bool{
return abstractAdd(item, write: write);
}
/// Returns all transactions contained within the database.
///
/// - returns: An array of all of the transactions.
func allTransactions() -> NSArray{
let result = realm.objects(Transaction).toNSArray();
return result;
}
/// Returns all sales entries contained within the database.
///
/// - returns: An array of all of the sales entries.
func allSalesEntries() -> NSArray{
let result = realm.objects(SalesEntry).toNSArray();
return result;
}
/// Returns all transactions contained within the database during a given month and year.
///
/// - parameter month: The month where transactions were made.
/// - parameter year: The year where transactions were made.
///
/// - returns: An array of all of the transactions that fulfill the date constraints imposed.
func transactionsInMonth(month:Int, year:Int) -> NSArray{
let transactions = allTransactions()
let calendar = DataAdapters.calendar()
let results = NSMutableArray()
for transaction in transactions {
let components = calendar.components([.Month, .Year], fromDate: transaction.date!!)
if (components.year == year && components.month == month) {
results.addObject(transaction as! Transaction)
}
}
return results as NSArray
}
/// Returns all transactions contained within the database during a given week and year.
///
/// - parameter week: The week where transactions were made.
/// - parameter year: The year where transactions were made.
///
/// - returns: An array of all of the transactions that fulfill the date constraints imposed.
func transactionsInWeek(week:Int, year:Int) -> NSArray{
let transactions = allTransactions()
let calendar = DataAdapters.calendar()
let results = NSMutableArray()
for transaction in transactions {
let components = calendar.components([.WeekOfYear, .Year], fromDate: transaction.date!!)
if (components.year == year && components.weekOfYear == week) {
results.addObject(transaction as! Transaction)
}
}
return results as NSArray
}
/// Returns all transactions contained within the database between two given months.
///
/// - parameter start: The start month.
/// - parameter end: The end month.
///
/// - returns: An array of all of the transactions that fulfill the date constraints imposed.
func transactionsBetweenDates(start:NSDate, end:NSDate) -> NSArray{
let transactions = allTransactions()
let results = NSMutableArray()
for transaction in transactions {
if (transaction.date!!.dateLiesBetweenDates(start, endDate: end)) {
results.addObject(transaction as! Transaction)
}
}
return results as NSArray
}
/// Removes a product from the database.
///
/// - parameter item: The product to be removed.
///
/// - returns: True if the operation was successful, otherwise, false.
func removeTransaction(item: Transaction) -> Bool{
return abstractDelete(item);
}
/// Abstract method to add an item to the database.
///
/// - parameter item: The item to be added.
///
/// - returns: True if the operation was successful, otherwise, false.
private func abstractAdd(item: Object) -> Bool{
return abstractAdd(item, write: true)
}
/// Abstract method to add an item to the database.
///
/// - parameter item: The item to be added.
///
/// - returns: True if the operation was successful, otherwise, false.
private func abstractAdd(item: Object, write: Bool) -> Bool{
if write {
SalesDataSource.openWrite();
}
self.realm.add(item);
if write {
return SalesDataSource.closeWrite();
}else{
return true
}
}
/// Abstract method to delete an object from the database.
///
/// - parameter item: The item to be deleted from the database.
///
/// - returns: True if the operation was successful, otherwise, false.
private func abstractDelete(item: Object) -> Bool{
SalesDataSource.openWrite();
self.realm.delete(item);
return SalesDataSource.closeWrite();
}
/// Opens a write transaction.
class func openWrite(){
sharedManager.realm.beginWrite();
}
/// Generic method to end a write transaction.
///
/// - returns: true if the operation was successful, otherwise false.
class func closeWrite() -> Bool{
do{
try sharedManager.realm.commitWrite();
}
catch{
return false;
}
return true;
}
/// Loads the database.
func instateDatabase(){
self.realm = try! Realm();
}
func resetDatabase(){
SalesDataSource.openWrite()
realm.deleteAll()
SalesDataSource.closeWrite()
}
/*
/// Exports the database to CSV and returns the path where the zipped backup was saved.
///
/// - returns: The path of the backup.
func exportToCSV() -> String?{
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let realmBaseFilePath = SalesDataSource.sharedManager.realm.configuration.fileURL!.path! as NSString
// The default Realm database is likely open at the current time, this means we should copy it and backup the copy.
// This is much more reliable than dereferencing the database handles, which may be untracked.
let databaseStagingPath = documentsPath.stringByAppendingPathComponent(".REALM") as NSString
let realmFilePath = databaseStagingPath.stringByAppendingPathComponent(realmBaseFilePath.lastPathComponent)
let outputFolderPath = documentsPath.stringByAppendingPathComponent(".CSV_OUT")
let metaDataPath = (outputFolderPath as NSString).stringByAppendingPathComponent("metadata.plist")
let zipOutputFolderPath = documentsPath.stringByAppendingPathComponent("Backups") as NSString
let dateTimeString = DataAdapters.dateTimeFormatter().stringFromDate(NSDate())
let zipSavePath = zipOutputFolderPath.stringByAppendingPathComponent("backup-export-\(dateTimeString).phpbk")
print(zipSavePath)
var needsToCreateStagingDirectory = false
var needsToCreateBackupDirectory = false
var needsToCreateDatabaseStagingDirectory = false
var isDirectory:ObjCBool = false
var residualFileExists:ObjCBool = false
let fileManager = NSFileManager.defaultManager()
// Determine if we need to create the staging directory in .CSV_OUT
if (!fileManager.fileExistsAtPath(outputFolderPath, isDirectory: &isDirectory) || !isDirectory) {
needsToCreateStagingDirectory = true
}
if (!fileManager.fileExistsAtPath(zipOutputFolderPath as String, isDirectory: &isDirectory) || !isDirectory) {
needsToCreateBackupDirectory = true
}
if (!fileManager.fileExistsAtPath(databaseStagingPath as String, isDirectory: &isDirectory) || !isDirectory) {
needsToCreateDatabaseStagingDirectory = true
}
if fileManager.fileExistsAtPath(realmFilePath){
residualFileExists = true
}
// Create the output directory, also create a copy of the Realm database.
do {
// Cleanup old file, if residual staging file remains from previous ocassion.
if residualFileExists {
print("[*] Removing risidual file...")
try fileManager.removeItemAtPath(realmFilePath)
}
if needsToCreateStagingDirectory {
print("[*] Creating staging directory...")
try fileManager.createDirectoryAtPath(outputFolderPath, withIntermediateDirectories: true, attributes: nil)
}
if needsToCreateDatabaseStagingDirectory {
print("[*] Creating database staging directory...")
try fileManager.createDirectoryAtPath(databaseStagingPath as String, withIntermediateDirectories: true, attributes: nil)
}
if needsToCreateBackupDirectory {
print("[*] Creating backup directory...")
try fileManager.createDirectoryAtPath(zipOutputFolderPath as String, withIntermediateDirectories: true, attributes: nil)
}
// Copy the file
print("[1] Cloning database for translation to CSV...")
try! fileManager.copyItemAtPath(realmBaseFilePath as String, toPath: realmFilePath)
}catch let error as NSError{
print(error.localizedDescription)
return nil
}
print("[2] Opening database for translation to CSV...")
let csvDataExporter = CSVDataExporter(realmFilePath: realmFilePath)
print("[3] Generating CSV files...")
try! csvDataExporter.exportToFolderAtPath(outputFolderPath)
print("[4] Backup to CSV complete!")
print("[5] Creating metadata file...")
let versionNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let metaDataDict:NSDictionary = ["data" : NSDate(),
"version" : versionNumber]
metaDataDict.writeToFile(metaDataPath, atomically: true)
SSZipArchive.createZipFileAtPath(zipSavePath, withContentsOfDirectory: outputFolderPath, keepParentDirectory: false)
// Cleanup
do {
try fileManager.removeItemAtPath(databaseStagingPath as String)
try fileManager.removeItemAtPath(outputFolderPath)
}catch let error as NSError{
print(error.localizedDescription)
return nil
}
return zipSavePath
}
*/
/*
func importFromPath(path: String){
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let realmBaseFilePath = SalesDataSource.sharedManager.realm.configuration.fileURL!.path! as NSString
let databaseStagingPath = documentsPath.stringByAppendingPathComponent(".CSV_IN") as NSString
let databaseRestoreDirectory = documentsPath.stringByAppendingPathComponent("RESTORE") as NSString
let databaseRestorePath = databaseRestoreDirectory.stringByAppendingPathComponent("default.realm")
let fileManager = NSFileManager.defaultManager()
if !fileManager.fileExistsAtPath(databaseRestorePath as String) {
try? fileManager.createDirectoryAtPath(databaseRestoreDirectory as String, withIntermediateDirectories: true, attributes: nil)
}
// SSZipArchive.unzipFileAtPath(path, toDestination: databaseStagingPath as String)
var csvFiles = [String]()
var metaDataFilePath:String? = nil
do{
let files = try fileManager.contentsOfDirectoryAtPath(databaseStagingPath as String)
for file:String in files{
let lowered = file.lowercaseString
if lowered.hasSuffix(".csv") {
csvFiles.append(databaseStagingPath.stringByAppendingPathComponent(file) as String)
}else if(lowered.hasSuffix(".plist")) {
metaDataFilePath = databaseStagingPath.stringByAppendingPathComponent(file)
}
}
}catch let error as NSError{
print(error.localizedDescription)
return
}
if csvFiles.count < 1 {
return
}
let metaDataDictionary = NSDictionary.init(contentsOfFile: metaDataFilePath!)
print(metaDataDictionary)
// let config = Realm.Configuration(
// // Get the URL to the bundled file
// fileURL: NSURL.fileURLWithPath(databaseRestorePath),
// // Open the file in read-only mode as application bundles are not writeable
// readOnly: true)
// let realm = try! Realm(configuration: config)
// Analyze the files and produce a Realm-compatible schema
let generator = ImportSchemaGenerator(files: csvFiles)
let schema = try! generator.generate()
// Use the schema and files to create the Realm file, and import the data
let dataImporter = CSVDataImporter(files: csvFiles)
try! dataImporter.importToPath(databaseRestorePath as String, schema: schema)
}
*/
/// Saves data into the Exports directory contained within the Documents directory.
/// If this directory does not exist it is created.
///
/// - parameter filename: The name of the file that is to be saved.
/// - parameter data: The data to be saved (NSData).
///
/// - returns: <#return value description#>
static func saveDataInExportDirectory(filename: String, data: NSData) -> String{
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let zipOutputFolderPath = documentsPath.stringByAppendingPathComponent("Exports") as NSString
let savefilePath = zipOutputFolderPath.stringByAppendingPathComponent(filename)
var needsToCreateBackupDirectory = false
var isDirectory:ObjCBool = false
let fileManager = NSFileManager.defaultManager()
// Determine if we need to create the backup directory.
if (!fileManager.fileExistsAtPath(zipOutputFolderPath as String, isDirectory: &isDirectory) || !isDirectory) {
needsToCreateBackupDirectory = true
}
// Create the output directory, also create a copy of the Realm database.
do {
if needsToCreateBackupDirectory {
print("[*] Creating export directory...")
try fileManager.createDirectoryAtPath(zipOutputFolderPath as String, withIntermediateDirectories: true, attributes: nil)
}
// Write the file
try data.writeToFile(savefilePath, options: NSDataWritingOptions.AtomicWrite)
}catch let error as NSError{
print(error.localizedDescription)
return ""
}
return savefilePath
}
/// Creates a CSV from the passed transactions.
///
/// - parameter transactions: An NSArray of Transactions.
///
/// - returns: A string representing the location that the CSV file has been saved to.
func createCSVUsingTransactions(transactions : NSArray) -> String{
let sortDescriptor = NSSortDescriptor.init(key: "date", ascending: true)
let sortedArray = transactions.sortedArrayUsingDescriptors([sortDescriptor]) as! [Transaction]
var csvString = "date,item_count,total_cost\n"
for transaction in sortedArray{
let dateString = DataAdapters.dateTimeFormatterStandard().stringFromDate(transaction.date!)
let itemCount = transaction.numberOfItems()
let totalCost = (transaction.totalCost!).stringByReplacingOccurrencesOfString(",", withString: "")
csvString = csvString.stringByAppendingString("\(dateString),\(itemCount),\(totalCost)")
if (sortedArray.last != transaction) {
csvString = csvString.stringByAppendingString("\n")
}
}
let dateTimeString = DataAdapters.dateTimeFormatter().stringFromDate(NSDate())
let saveFilename = "backup-export-\(dateTimeString).csv"
let saveData = csvString.dataUsingEncoding(NSUTF8StringEncoding)
return SalesDataSource.saveDataInExportDirectory(saveFilename, data: saveData!)
}
/// Fills the database with randomised sample data.
func prefillDatabase(numberOfTransactions : Int){
// let NUM_TRANSACTIONS = 2
SalesDataSource.sharedManager.resetDatabase()
var products = [Product?](count: 10, repeatedValue: nil)
products[0] = Product.init(aName: "Lipitor", aPrice: "9.45");
products[1] = Product.init(aName: "Nexium", aPrice: "18.42");
products[2] = Product.init(aName: "Plavix", aPrice: "29.08");
products[3] = Product.init(aName: "Abilify", aPrice: "25.3");
products[4] = Product.init(aName: "Advair Diskus", aPrice: "16.95");
products[5] = Product.init(aName: "Seroquel", aPrice: "29.26");
products[6] = Product.init(aName: "Singulair", aPrice: "22.49");
products[7] = Product.init(aName: "Crestor", aPrice: "20.06");
products[8] = Product.init(aName: "Actos", aPrice: "29.29");
products[9] = Product.init(aName: "Epogen", aPrice: "7.39");
for product in products {
SalesDataSource.sharedManager.addSalesProduct(product!)
}
SalesDataSource.openWrite()
for i in 0..<numberOfTransactions {
let salesEntryCount = arc4random_uniform(5) + 1
var availableProducts = Array(0...9)
var selectedProductIndexes = [Int]()
// print("\(i) pass...")
let transaction = Transaction.init(date: NSDate())
for _ in 0..<salesEntryCount{
let index = Int(arc4random_uniform(UInt32(availableProducts.count)))
selectedProductIndexes.append(availableProducts[index])
let product = products[availableProducts[index]]
let quantity = Int(arc4random_uniform(8)) + 1
let salesEntry = SalesEntry.init(product: product!, quanity: quantity)
transaction.addSalesEntry(salesEntry, write: false)
// print(products[availableProducts[index]]!.name)
availableProducts.removeAtIndex(index)
}
SalesDataSource.sharedManager.addTransaction(transaction, write: false)
if (i % 100 == 0) {
print(i)
}
}
SalesDataSource.closeWrite()
}
}
| 1fdc500cf8a058126f20a7bf5c088b9f | 37.958484 | 138 | 0.624473 | false | false | false | false |
Boilertalk/VaporFacebookBot | refs/heads/master | Sources/VaporFacebookBot/Send/FacebookSend.swift | mit | 1 | //
// FacebookSend.swift
// VaporFacebookBot
//
// Created by Koray Koska on 25/05/2017.
//
//
import Foundation
import Vapor
public final class FacebookSend: JSONConvertible {
public var recipient: FacebookSendRecipient
public var message: FacebookSendMessage?
public var senderAction: FacebookSenderAction?
public var notificationType: FacebookSendNotificationType?
public init(recipient: FacebookSendRecipient, message: FacebookSendMessage, notificationType: FacebookSendNotificationType? = nil) {
self.recipient = recipient
self.message = message
self.notificationType = notificationType
}
public init(recipient: FacebookSendRecipient, senderAction: FacebookSenderAction, notificationType: FacebookSendNotificationType? = nil) {
self.recipient = recipient
self.senderAction = senderAction
self.notificationType = notificationType
}
public convenience init(json: JSON) throws {
let recipient = try FacebookSendRecipient(json: json.get("recipient"))
var notificationType: FacebookSendNotificationType? = nil
if let notificationTypeString = json["notification_type"]?.string {
notificationType = FacebookSendNotificationType(rawValue: notificationTypeString)
}
if let m = json["message"] {
let message = try FacebookSendMessage(json: m)
self.init(recipient: recipient, message: message, notificationType: notificationType)
} else if let s = json["sender_action"]?.string, let senderAction = FacebookSenderAction(rawValue: s) {
self.init(recipient: recipient, senderAction: senderAction, notificationType: notificationType)
} else {
throw Abort(.badRequest, metadata: "Either message or a valid sender_action (FacebookSenderAction) must be set for FacebookSend")
}
}
public func makeJSON() throws -> JSON {
var json = JSON()
try json.set("recipient", recipient)
if let message = message {
try json.set("message", message)
} else if let senderAction = senderAction {
try json.set("sender_action", senderAction)
}
if let notificationType = notificationType {
try json.set("notification_type", notificationType)
}
return json
}
}
public final class FacebookSendRecipient: JSONConvertible {
public var id: String?
public var phoneNumber: String?
public var name: (firstName: String, lastName: String)?
public init(id: String) {
self.id = id
}
public init(phoneNumber: String, name: (firstName: String, lastName: String)? = nil) {
self.phoneNumber = phoneNumber
self.name = name
}
public convenience init(json: JSON) throws {
if let id = json["id"]?.string {
self.init(id: id)
} else if let phoneNumber = json["phone_number"]?.string {
if let firstName = json["name"]?["first_name"]?.string, let lastName = json["name"]?["last_name"]?.string {
let name = (firstName: firstName, lastName: lastName)
self.init(phoneNumber: phoneNumber, name: name)
} else {
self.init(phoneNumber: phoneNumber)
}
} else {
throw Abort(.badRequest, metadata: "FacebookSendObjectRecipient must contain either id or phone_number!")
}
}
public func makeJSON() throws -> JSON {
var json = JSON()
if let id = id {
try json.set("id", id)
} else if let phoneNumber = phoneNumber {
try json.set("phone_number", phoneNumber)
if let name = name {
var nameJson = JSON()
try nameJson.set("first_name", name.firstName)
try nameJson.set("last_name", name.lastName)
try json.set("name", nameJson)
}
}
return json
}
}
public enum FacebookSenderAction: String {
case typingOn = "typing_on"
case typingOff = "typing_off"
case markSeen = "mark_seen"
}
public enum FacebookSendNotificationType: String {
case regular = "REGULAR"
case silentPush = "SILENT_PUSH"
case noPush = "NO_PUSH"
}
| 1377407bde5c8e47b64704a44aae21e4 | 31.869231 | 142 | 0.636789 | false | false | false | false |
nickfrey/knightsapp | refs/heads/master | Newman Knights/DirectoryViewController.swift | mit | 1 | //
// DirectoryViewController.swift
// Newman Knights
//
// Created by Nick Frey on 1/2/16.
// Copyright © 2016 Nick Frey. All rights reserved.
//
import UIKit
import MessageUI
class DirectoryViewController: FetchedViewController, UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate {
fileprivate let directory: Contact.Directory
fileprivate var contacts: Array<Contact> = []
fileprivate weak var tableView: UITableView?
init(directory: Contact.Directory) {
self.directory = directory
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
switch self.directory {
case .administration:
self.title = "Administration"
case .office:
self.title = "Office"
case .faculty:
self.title = "Teachers"
}
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.isHidden = true
tableView.rowHeight = 50
self.view.addSubview(tableView)
self.view.sendSubview(toBack: tableView)
self.tableView = tableView
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.tableView?.frame = self.view.bounds
}
override func viewDidLoad() {
super.viewDidLoad()
self.perform(#selector(fetch), with: nil, afterDelay: 0.2)
}
@objc override func fetch() {
self.tableView?.isHidden = true
super.fetch()
DataSource.fetchContacts(self.directory) { (contacts, error) -> Void in
DispatchQueue.main.async(execute: {
guard let contacts = contacts, error == nil else {
let fallbackError = NSError(
domain: NSURLErrorDomain,
code: NSURLErrorUnknown,
userInfo: [NSLocalizedDescriptionKey: "An unknown error occurred."]
)
return self.fetchFinished(error == nil ? fallbackError : error)
}
self.contacts = contacts
self.fetchFinished(nil)
self.tableView?.reloadData()
self.tableView?.isHidden = false
})
}
}
// MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.contacts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)
cell?.accessoryType = .disclosureIndicator
}
let contact = self.contacts[indexPath.row]
cell!.textLabel?.text = contact.name
cell!.detailTextLabel?.text = contact.title
return cell!
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let contact = self.contacts[indexPath.row]
let email = "\"" + contact.name + "\" <" + contact.email + ">"
if MFMailComposeViewController.canSendMail() {
let viewController = MFMailComposeViewController()
viewController.mailComposeDelegate = self
viewController.setToRecipients([email])
viewController.navigationBar.barStyle = .black
viewController.navigationBar.tintColor = .white
self.present(viewController, animated: true, completion: { () -> Void in
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
})
} else if let mailtoURL = URL(string: "mailto://" + contact.email) {
UIApplication.shared.openURL(mailtoURL)
}
}
// MARK: MFMailComposeViewControllerDelegate
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
self.dismiss(animated: true, completion: nil)
}
}
| c1db2ba997cbfc6af6358699bbf13ab2 | 34.858268 | 135 | 0.610892 | false | false | false | false |
justin999/gitap | refs/heads/master | gitap/GitHubAPIManager.swift | mit | 1 | //
// GitHubAPIManager.swift
// gitap
//
// Created by Koichi Sato on 1/4/17.
// Copyright © 2017 Koichi Sato. All rights reserved.
//
import Foundation
import Alamofire
import Locksmith
let githubBaseURLString = "https://api.github.com"
enum GitHubAPIManagerError: Error {
case network(error: Error)
case apiProvidedError(reason: String)
case authCouldNot(reason: String)
case authLost(reason: String)
case objectSerialization(reason: String)
}
protocol ResultProtocol {
init?(json: [String: Any])
}
let kKeyChainGitHub = "github"
let kMessageFailToObtainToken: String = "Could not obtain an OAuth token"
class GitHubAPIManager {
static let shared = GitHubAPIManager()
var isLoadingOAuthToken: Bool = false
var OAuthTokenCompletionHandler:((Error?) -> Void)?
var OAuthToken: String? {
set {
guard let newValue = newValue else {
let _ = try? Locksmith.deleteDataForUserAccount(userAccount: kKeyChainGitHub)
Utils.setDefaultsValue(value: nil, key: "githubAuthToken")
return
}
Utils.setDefaultsValue(value: newValue, key: "githubAuthToken")
guard let _ = try? Locksmith.updateData(data: ["token": newValue], forUserAccount: kKeyChainGitHub) else {
let _ = try? Locksmith.deleteDataForUserAccount(userAccount: kKeyChainGitHub)
return
}
}
get {
// try to load from keychain
let dictionary = Locksmith.loadDataForUserAccount(userAccount: kKeyChainGitHub)
return dictionary?["token"] as? String
}
}
let clientID: String = Configs.github.clientId
let clientSecret: String = Configs.github.clientSecret
func clearCache() -> Void {
let cache = URLCache.shared
cache.removeAllCachedResponses()
}
func hasOAuthToken() -> Bool {
if let token = self.OAuthToken {
return !token.isEmpty
}
return false
}
func clearOAuthToken() {
if let _ = self.OAuthToken {
self.OAuthToken = nil
self.clearCache()
}
}
// MARK: - OAuth flow
func URLToStartOAuth2Login() -> URL? {
// TODO: change the state for production
let authPath: String = "https://github.com/login/oauth/authorize" +
"?client_id=\(clientID)&scope=user%20repo%20gist"
return URL(string: authPath)
}
func processOAuthStep1Response(_ url: URL) {
// extract the code from the URL
guard let code = extrctCodeFromOauthStep1Response(url) else {
self.isLoadingOAuthToken = false
let error = GitHubAPIManagerError.authCouldNot(reason: kMessageFailToObtainToken)
self.OAuthTokenCompletionHandler?(error)
return
}
swapAuthCodeForToken(code: code)
}
func swapAuthCodeForToken(code: String) {
let getTokenPath: String = "https://github.com/login/oauth/access_token"
let tokenParams = ["client_id": clientID, "client_secret": clientSecret, "code": code]
let jsonHeader = ["Accept": "application/json"]
Alamofire.request(getTokenPath, method: .post, parameters: tokenParams, encoding: URLEncoding.default, headers: jsonHeader)
.responseJSON { response in
guard response.result.error == nil else {
print(response.result.error!)
self.isLoadingOAuthToken = false
let errorMessage = response.result.error?.localizedDescription ?? kMessageFailToObtainToken
let error = GitHubAPIManagerError.authCouldNot(reason: errorMessage)
self.OAuthTokenCompletionHandler?(error)
return
}
guard let value = response.result.value else {
print("no string received in response when swapping oauth code for token")
self.isLoadingOAuthToken = false
let error = GitHubAPIManagerError.authCouldNot(reason: kMessageFailToObtainToken)
self.OAuthTokenCompletionHandler?(error)
return
}
guard let jsonResult = value as? [String: String] else {
print("no data received or data not JSON")
self.isLoadingOAuthToken = false
let error = GitHubAPIManagerError.authCouldNot(reason: kMessageFailToObtainToken)
self.OAuthTokenCompletionHandler?(error)
return
}
self.OAuthToken = self.parseOAuthTokenResponse(jsonResult)
self.isLoadingOAuthToken = false
if (self.hasOAuthToken()) {
self.OAuthTokenCompletionHandler?(nil)
} else {
let error = GitHubAPIManagerError.authCouldNot(reason: kMessageFailToObtainToken)
self.OAuthTokenCompletionHandler?(error)
}
}
}
func extrctCodeFromOauthStep1Response(_ url: URL) -> String? {
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
var code: String?
guard let queryItems = components?.queryItems else {
return nil
}
for queryItem in queryItems {
if (queryItem.name.lowercased() == "code") {
code = queryItem.value
break
}
}
return code
}
func parseOAuthTokenResponse(_ json: [String: String]) -> String? {
var token: String?
for (key, value) in json {
switch key {
case "access_token":
token = value
print("Got Token: \(token ?? "no token")")
case "scope":
// TODO: verify scope
print("SET SCOPE")
print("key: \(key), scope: \(value)")
case "token_type":
// TODO: verify is bearer
print("CHECK IF BEARER")
default:
print("got more than I expected from the OAuth token exchange")
print(key)
}
}
return token
}
// MARK: - API Calls
// MARK: fundamental
func fetch<T: ResultProtocol>(_ urlRequest: URLRequestConvertible, completionHandler: @escaping (Result<[T]>, String?) -> Void) {
Alamofire.request(urlRequest)
.responseJSON { response in
if let urlResponse = response.response,
let authError = self.checkUnauthorized(urlResponse: urlResponse) {
completionHandler(.failure(authError), nil)
return
}
let result: Result<[T]> = self.arrayFromResponse(response: response)
let next = self.parseNextPageFromHeaders(response: response.response)
completionHandler(result, next)
}
}
private func arrayFromResponse<T: ResultProtocol>(response: DataResponse<Any>) -> Result<[T]> {
guard response.result.error == nil else {
return .failure(GitHubAPIManagerError.network(error: response.result.error!))
}
// make sure we got JSON and it's an array
if let jsonArray = response.result.value as? [[String: Any]] {
var datas = [T]()
for item in jsonArray {
if let data = T(json: item) {
datas.append(data)
}
}
return .success(datas)
} else if let jsonData = response.result.value as? [String: Any], let data: T = T(json: jsonData) {
return .success([data])
} else if let jsonDictionary = response.result.value as? [String: Any],
let errorMessage = jsonDictionary["message"] as? String { return .failure(GitHubAPIManagerError.apiProvidedError(reason: errorMessage))
} else {
return .failure(GitHubAPIManagerError.apiProvidedError(reason: "something went wrong"))
}
}
// MARK: - Helpers
// func isAPIOnline(completionHandler: @escaping (Bool) -> Void) {
// Alamofire.request(GistRouter.baseURLString)
// .validate(statusCode: 200 ..< 300)
// .response { response in
// guard response.error == nil else {
// // no internet connection or GitHub API is down
// completionHandler(false)
// return
// }
// completionHandler(true)
// }
// }
func checkUnauthorized(urlResponse: HTTPURLResponse) -> (Error?) {
if (urlResponse.statusCode == 401) {
self.OAuthToken = nil
return GitHubAPIManagerError.authLost(reason: "Not Logged In")
} else if (urlResponse.statusCode == 404) {
return GitHubAPIManagerError.authLost(reason: "Not Found")
} else if (urlResponse.statusCode >= 400 && urlResponse.statusCode < 500) { // TODO: describe this reason more kindly
return GitHubAPIManagerError.apiProvidedError(reason: "400 error")
}
return nil
}
// MARK: - Pagination
private func parseNextPageFromHeaders(response: HTTPURLResponse?) -> String? {
guard let linkHeader = response?.allHeaderFields["Link"] as? String else {
return nil
}
/* looks like: <https://...?page=2>; rel="next", <https://...?page=6>; rel="last" */
// so split on ","
let components = linkHeader.characters.split { $0 == "," }.map { String($0) }
// now we have 2 lines like '<https://...?page=2>; rel="next"'
for item in components {
// see if it's "next"
let rangeOfNext = item.range(of: "rel=\"next\"", options: [])
guard rangeOfNext != nil else {
continue
}
// this is the "next" item, extract the URL
let rangeOfPaddedURL = item.range(of: "<(.*)>;",
options: .regularExpression,
range: nil,
locale: nil)
guard let range = rangeOfPaddedURL else {
return nil
}
let nextURL = item.substring(with: range)
// strip off the < and >;
let start = nextURL.index(range.lowerBound, offsetBy: 1)
let end = nextURL.index(range.upperBound, offsetBy: -2)
let trimmedRange = start ..< end
return nextURL.substring(with: trimmedRange)
}
return nil
}
}
| 1a926afe8f1208a17a5bf8ea28aa9d02 | 38.434783 | 147 | 0.563947 | false | false | false | false |
touyu/SwiftyAttributedString | refs/heads/master | SwiftyAttributedString/Deprecated/Attribute.swift | mit | 1 | //
// Attribute.swift
// SwiftyAttributedString
//
// Created by Yuto Akiba on 2017/05/14.
// Copyright © 2017年 Yuto Akiba. All rights reserved.
//
import UIKit
public enum AttributeValue {
case font(UIFont)
case foregroundColor(UIColor)
case backgroundColor(UIColor)
case kern(NSNumber)
case strikethroughStyle(NSNumber)
case underlineStyle(NSNumber)
case strokeColor(UIColor)
case strokeWidth(NSNumber)
case shadow(NSShadow)
case textEffect(TextEffect)
case link(URL)
case baselineOffset(NSNumber)
case obliqueness(NSNumber)
case expansion(NSNumber)
}
public enum AttributeRange {
case all
case portion(of: Portion)
public enum Portion {
case string(String)
case range(NSRange)
}
public func toNSRange(string: String) -> NSRange {
switch self {
case .all:
let titleRange = (string as NSString).range(of: string)
return titleRange
case .portion(let portion):
switch portion {
case .string(let portionString):
let titleRange = (string as NSString).range(of: portionString)
return titleRange
case .range(let range):
return range
}
}
}
}
public struct Attribute {
public var values: [AttributeValue] = []
public var range: AttributeRange
public init(value: AttributeValue, range: AttributeRange = .all) {
self.values = [value]
self.range = range
}
public init(values: [AttributeValue], range: AttributeRange = .all) {
self.values = values
self.range = range
}
}
public enum TextEffect: String {
case letterPressStyle = "_UIKitNewLetterpressStyle"
}
| 0cecfc4911e212e73851ec78db0ac06a | 23.739726 | 78 | 0.620709 | false | false | false | false |
terietor/GTForms | refs/heads/master | Source/Table Views/TableViewController.swift | mit | 1 | // Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
protocol TableViewType: class {
var formSections: [FormSection] { get set }
var tableView: UITableView! { get }
}
class TableViewController: NSObject, UITableViewDataSource, UITableViewDelegate {
private var datePickerHelper = DatePickerHelper()
fileprivate var textFieldViews = [TextFieldViewType]()
private let tableViewType: TableViewType
private var viewController: UIViewController?
private var tableView: UITableView {
return self.tableViewType.tableView
}
init(tableViewType: TableViewType) {
self.tableViewType = tableViewType
super.init()
commonInit()
}
init(tableViewType: TableViewType, viewController: UIViewController) {
self.tableViewType = tableViewType
self.viewController = viewController
super.init()
commonInit()
}
var formSections: [FormSection] = [FormSection]() {
didSet {
findTextFieldViews()
self.tableView.reloadData()
self.formSections.forEach() {
$0.tableViewType = self.tableViewType
}
}
}
func registerCustomForm(_ customForm: CustomForm) {
self.tableView.register(
customForm.cellClass,
forCellReuseIdentifier: customForm.reuseIdentifier
)
}
func registerNotifications() {
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillAppear),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil
)
}
func unRegisterNotifications() {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return self.formSections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.formSections[section].formItemsForSection().count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell
let cellItem = self.formSections[(indexPath as NSIndexPath).section].formItemsForSection()[(indexPath as NSIndexPath).row]
if let selectionItem = cellItem as? BaseSelectionFormItem {
cell = tableView.dequeueReusableCell(
withIdentifier: selectionItem.cellReuseIdentifier,
for: indexPath
)
cell.selectionStyle = .none
if let selectionItem = selectionItem as? SelectionFormItem {
cell.textLabel?.text = selectionItem.text
cell.detailTextLabel?.text = selectionItem.detailText
cell.accessoryType = selectionItem.selected ? selectionItem.accessoryType : .none
} else if let
selectionItem = selectionItem as? SelectionCustomizedFormItem,
let cell = cell as? SelectionCustomizedFormItemCell
{
cell.configure(
selectionItem.text,
detailText: selectionItem.detailText,
isSelected: selectionItem.selected
)
}
return cell
} else if let datePicker = cellItem as? UIDatePicker {
guard let
datePickerCell = tableView.dequeueReusableCell(
withIdentifier: "DatePickerCell",
for: indexPath
) as? DatePickerTableViewCell
else { return UITableViewCell() }
datePickerCell.datePicker = datePicker
return datePickerCell
}
guard let cellRow = cellItem as? FormRow else { return UITableViewCell() }
if let customForm = cellRow.form as? CustomForm {
let cell = tableView.dequeueReusableCell(withIdentifier: customForm.reuseIdentifier, for: indexPath)
customForm.configureCell(cell)
return cell
} else if let staticForm = cellRow.form as? StaticForm {
cell = tableView.dequeueReusableCell(withIdentifier: "ReadOnlyCell", for: indexPath)
cell.textLabel?.text = staticForm.text
cell.detailTextLabel?.text = staticForm.detailText
} else if let staticForm = cellRow.form as? AttributedStaticForm {
cell = tableView.dequeueReusableCell(withIdentifier: "AttributedReadOnlyCell", for: indexPath)
cell.textLabel?.attributedText = staticForm.text
cell.detailTextLabel?.attributedText = staticForm.detailText
} else if let selectionForm = cellRow.form as? BaseSelectionForm {
cell = tableView.dequeueReusableCell(withIdentifier: selectionForm.cellReuseIdentifier, for: indexPath)
if let selectionForm = selectionForm as? SelectionForm {
cell.textLabel?.text = selectionForm.text
cell.detailTextLabel?.text = selectionForm.detailText
if let textColor = selectionForm.textColor {
cell.textLabel?.textColor = textColor
}
if let textFont = selectionForm.textFont {
cell.textLabel?.font = textFont
}
if let detailTextColor = selectionForm.detailTextColor {
cell.detailTextLabel?.textColor = detailTextColor
}
if let detailTextFont = selectionForm.detailTextFont {
cell.textLabel?.font = detailTextFont
}
} else if let
item = selectionForm as? SelectionCustomizedForm,
let cell = cell as? SelectionCustomizedFormCell
{
cell.configure(item.text, detailText: item.detailText)
}
cell.selectionStyle = .none
} else {
let formCell: FormTableViewCell
if let
f = cellRow.form as? FormViewableType,
let cellIdentifier = f.customCellIdentifier
{
formCell = tableView.dequeueReusableCell(
withIdentifier: cellIdentifier, for: indexPath
) as! FormTableViewCell
} else {
formCell = BaseFormTableViewCell()
}
if let formViewableCell = cellRow.form as? FormViewableType {
formViewableCell.viewController = self.viewController
}
formCell.formRow = cellRow
cell = formCell
}
cell.accessoryType = cellRow.accessoryType
cell.selectionStyle = .none
return cell
}
// MARK: tableview
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cellItems = self.formSections[(indexPath as NSIndexPath).section].formItemsForSection()
SelectionFormHelper.handleAccessory(
cellItems,
tableView: self.tableView,
indexPath: indexPath
)
guard let formRow = cellItems[(indexPath as NSIndexPath).row] as? FormRow else { return }
formRow.didSelectRow?()
SelectionFormHelper.toggleItems(
formRow,
tableView: self.tableView,
indexPath: indexPath
)
guard let
datePickerForm = formRow.form as? FormDatePickerType
else { return }
self.datePickerHelper.currentSelectedDatePickerForm = datePickerForm
self.datePickerHelper.removeAllDatePickers(self.tableViewType)
hideKeyboard()
self.datePickerHelper.showDatePicker(
self.tableView,
cellItems: self.formSections[(indexPath as NSIndexPath).section].formItemsForSection()
)
}
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
let cellItem = self.formSections[(indexPath as NSIndexPath).section].formItemsForSection()[(indexPath as NSIndexPath).row]
if let _ = cellItem as? BaseSelectionFormItem {
return true
}
guard let cellRow = cellItem as? FormRow
else { return false }
if let
_ = cellRow.form as? StaticForm,
let _ = cellRow.didSelectRow
{
return true
} else if let
_ = cellRow.form as? AttributedStaticForm,
let _ = cellRow.didSelectRow
{
return true
} else if let selectionForm = cellRow.form as? BaseSelectionForm
{
return !selectionForm.shouldAlwaysShowAllItems ? true : false
} else if let _ = cellRow.form as? FormDatePickerType {
return true
}
return false
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.formSections[section].title
}
func hideKeyboard() {
self.textFieldViews.forEach() {
if $0.textField.isFirstResponder {
$0.textField.resignFirstResponder()
}
}
}
private func findTextFieldViews() {
self.textFieldViews.removeAll()
for section in self.formSections {
for row in section.rows {
if let form = row.form as? FormTextFieldViewType {
self.textFieldViews.append(form.textFieldViewType)
}
} // end for
} // end for
self.textFieldViews.forEach() { $0.delegate = self }
}
@objc private func keyboardWillAppear() {
let datePicker = self.datePickerHelper.currentSelectedDatePickerForm
self.datePickerHelper.currentSelectedDatePickerForm = nil
self.datePickerHelper.removeAllDatePickers(self.tableViewType)
self.datePickerHelper.currentSelectedDatePickerForm = datePicker
}
private func commonInit() {
self.tableView.estimatedRowHeight = 50
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "ReadOnlyCell")
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "AttributedReadOnlyCell")
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "SelectionCell")
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "SelectionItemCell")
self.tableView.register(FormTableViewCell.self, forCellReuseIdentifier: "formCell")
self.tableView.register(DatePickerTableViewCell.self, forCellReuseIdentifier: "DatePickerCell")
}
}
extension TableViewController: TextFieldViewDelegate {
func textFieldViewShouldReturn(_ textFieldView: TextFieldViewType) -> Bool {
var index = -1
for (i, it) in self.textFieldViews.enumerated() {
if it === textFieldView {
index = i
}
}
if index == -1 {
return false
}
if index + 1 >= self.textFieldViews.count {
return false
}
let nextTextFieldView = self.textFieldViews[index + 1]
return nextTextFieldView.textField.becomeFirstResponder()
}
}
| fbc875fc2ee4781dddff01042a52cc6a | 35.757396 | 130 | 0.635222 | false | false | false | false |
ScoutHarris/WordPress-iOS | refs/heads/develop | WordPress/Classes/Extensions/NSURL+Exporters.swift | gpl-2.0 | 1 | import Foundation
import Photos
import MobileCoreServices
import AVFoundation
extension NSURL: ExportableAsset {
func exportToURL(_ url: URL,
targetUTI: String,
maximumResolution: CGSize,
stripGeoLocation: Bool,
synchronous: Bool,
successHandler: @escaping SuccessHandler,
errorHandler: @escaping ErrorHandler) {
switch assetMediaType {
case .image:
exportImageToURL(url as NSURL,
targetUTI: targetUTI,
maximumResolution: maximumResolution,
stripGeoLocation: stripGeoLocation,
synchronous: synchronous,
successHandler: successHandler,
errorHandler: errorHandler)
case .video:
exportVideoToURL(url as NSURL,
targetUTI: targetUTI,
maximumResolution: maximumResolution,
stripGeoLocation: stripGeoLocation,
successHandler: successHandler,
errorHandler: errorHandler)
default:
errorHandler(errorForCode(errorCode: .UnsupportedAssetType,
failureReason: NSLocalizedString("This media type is not supported on WordPress.",
comment: "Error reason to display when exporting an unknown asset type.")))
}
}
func exportImageToURL(_ url: NSURL,
targetUTI: String,
maximumResolution: CGSize,
stripGeoLocation: Bool,
synchronous: Bool,
successHandler: SuccessHandler,
errorHandler: ErrorHandler) {
let requestedSize = maximumResolution.clamp(min: CGSize.zero, max: pixelSize)
let metadataOptions: [NSString: NSObject] = [kCGImageSourceShouldCache: false as NSObject]
let scaleOptions: [NSString: NSObject] = [
kCGImageSourceThumbnailMaxPixelSize: (requestedSize.width > requestedSize.height ? requestedSize.width : requestedSize.height) as CFNumber,
kCGImageSourceCreateThumbnailFromImageAlways: true as CFBoolean
]
guard let imageSource = CGImageSourceCreateWithURL(self, nil),
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, metadataOptions as CFDictionary?),
let scaledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, scaleOptions as CFDictionary?)
else {
errorHandler(errorForCode(errorCode: .FailedToExport,
failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of a image fails.")
))
return
}
let image = UIImage(cgImage: scaledImage)
var exportMetadata: [String: AnyObject]? = nil
if let metadata = imageProperties as NSDictionary as? [String: AnyObject] {
exportMetadata = metadata
if stripGeoLocation {
let attributesToRemove = [kCGImagePropertyGPSDictionary as String]
exportMetadata = removeAttributes(attributes: attributesToRemove, fromMetadata: metadata)
}
}
do {
try image.writeToURL(url as URL, type: targetUTI, compressionQuality: 0.9, metadata: exportMetadata)
successHandler(image.size)
} catch let error as NSError {
errorHandler(error)
} catch {
errorHandler(errorForCode(errorCode: .FailedToExport,
failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of a image from device library fails")
))
}
}
func exportOriginalImage(_ toURL: URL, successHandler: @escaping SuccessHandler, errorHandler: @escaping ErrorHandler) {
let fileManager = FileManager.default
do {
try fileManager.copyItem(at: self as URL, to: toURL)
} catch let error as NSError {
errorHandler(error)
} catch {
errorHandler(errorForCode(errorCode: .FailedToExport,
failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of a image from device library fails")
))
}
successHandler(pixelSize)
}
func exportVideoToURL(_ url: NSURL,
targetUTI: String,
maximumResolution: CGSize,
stripGeoLocation: Bool,
successHandler: @escaping SuccessHandler,
errorHandler: @escaping ErrorHandler) {
let asset = AVURLAsset(url: self as URL)
guard let track = asset.tracks(withMediaType: AVMediaTypeVideo).first else {
errorHandler(errorForCode(errorCode: .FailedToExport,
failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of an media asset fails")
))
return
}
let size = track.naturalSize.applying(track.preferredTransform)
let pixelWidth = fabs(size.width)
let pixelHeight = fabs(size.height)
guard
let exportSession = AVAssetExportSession(asset: asset, presetName: MediaSettings().maxVideoSizeSetting.videoPreset)
else {
errorHandler(errorForCode(errorCode: .FailedToExport,
failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of an media asset fails")
))
return
}
exportSession.outputFileType = targetUTI
exportSession.shouldOptimizeForNetworkUse = true
exportSession.outputURL = url as URL
if stripGeoLocation {
exportSession.metadataItemFilter = AVMetadataItemFilter.forSharing()
}
exportSession.exportAsynchronously(completionHandler: { () -> Void in
guard exportSession.status == .completed else {
if let error = exportSession.error {
errorHandler(error as NSError)
}
return
}
successHandler(CGSize(width: pixelWidth, height: pixelHeight))
})
}
func exportThumbnailToURL(_ url: URL,
targetSize: CGSize,
synchronous: Bool,
successHandler: @escaping SuccessHandler,
errorHandler: @escaping ErrorHandler) {
if isImage {
exportToURL(url,
targetUTI: defaultThumbnailUTI,
maximumResolution: targetSize,
stripGeoLocation: true,
synchronous: synchronous,
successHandler: successHandler,
errorHandler: errorHandler)
} else if isVideo {
let asset = AVURLAsset(url: self as URL, options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.maximumSize = targetSize
imgGenerator.appliesPreferredTrackTransform = true
imgGenerator.generateCGImagesAsynchronously(forTimes: [NSValue(time: CMTimeMake(0, 1))], completionHandler: { (time, cgImage, actualTime, result, error) in
guard let cgImage = cgImage else {
if let error = error {
errorHandler(error as NSError)
} else {
errorHandler(self.errorForCode(errorCode: .FailedToExport,
failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of a image from device library fails")
))
}
return
}
let uiImage = UIImage(cgImage: cgImage)
do {
try uiImage.writeJPEGToURL(url)
successHandler(uiImage.size)
} catch let error as NSError {
errorHandler(error)
} catch {
errorHandler(self.errorForCode(errorCode: .FailedToExport,
failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of a image from device library fails")
))
}
})
} else {
errorHandler(errorForCode(errorCode: .FailedToExport,
failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of a image from device library fails")
))
}
}
func originalUTI() -> String? {
return typeIdentifier
}
var defaultThumbnailUTI: String {
get {
return kUTTypeJPEG as String
}
}
var assetMediaType: MediaType {
get {
if isImage {
return .image
} else if (isVideo) {
return .video
}
return .document
}
}
// MARK: - Helper methods
var pixelSize: CGSize {
get {
if isVideo {
let asset = AVAsset(url: self as URL)
if let track = asset.tracks(withMediaType: AVMediaTypeVideo).first {
return track.naturalSize.applying(track.preferredTransform)
}
} else if isImage {
let options: [NSString: NSObject] = [kCGImageSourceShouldCache: false as CFBoolean]
if
let imageSource = CGImageSourceCreateWithURL(self, nil),
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, options as CFDictionary?) as NSDictionary?,
let pixelWidth = imageProperties[kCGImagePropertyPixelWidth as NSString] as? Int,
let pixelHeight = imageProperties[kCGImagePropertyPixelHeight as NSString] as? Int
{
return CGSize(width: pixelWidth, height: pixelHeight)
}
}
return CGSize.zero
}
}
var typeIdentifier: String? {
guard isFileURL else { return nil }
do {
let data = try bookmarkData(options: NSURL.BookmarkCreationOptions.minimalBookmark, includingResourceValuesForKeys: [URLResourceKey.typeIdentifierKey], relativeTo: nil)
guard
let resourceValues = NSURL.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey], fromBookmarkData: data),
let typeIdentifier = resourceValues[URLResourceKey.typeIdentifierKey] as? String else {
return nil
}
return typeIdentifier
} catch {
return nil
}
}
var mimeType: String {
guard let uti = typeIdentifier,
let mimeType = UTTypeCopyPreferredTagWithClass(uti as CFString, kUTTagClassMIMEType)?.takeUnretainedValue() as String?
else {
return "application/octet-stream"
}
return mimeType
}
var isVideo: Bool {
guard let uti = typeIdentifier else {
return false
}
return UTTypeConformsTo(uti as CFString, kUTTypeMovie)
}
var isImage: Bool {
guard let uti = typeIdentifier else {
return false
}
return UTTypeConformsTo(uti as CFString, kUTTypeImage)
}
func removeAttributes(attributes: [String], fromMetadata: [String: AnyObject]) -> [String: AnyObject] {
var resultingMetadata = fromMetadata
for attribute in attributes {
resultingMetadata.removeValue(forKey: attribute)
if attribute == kCGImagePropertyOrientation as String {
if let tiffMetadata = resultingMetadata[kCGImagePropertyTIFFDictionary as String] as? [String: AnyObject] {
var newTiffMetadata = tiffMetadata
newTiffMetadata.removeValue(forKey: kCGImagePropertyTIFFOrientation as String)
resultingMetadata[kCGImagePropertyTIFFDictionary as String] = newTiffMetadata as AnyObject?
}
}
}
return resultingMetadata
}
/// Makes sure the metadata of the image is matching the attributes in the Image.
///
/// - Parameters:
/// - metadata: The original metadata of the image.
/// - image: The current image.
///
/// - Returns: A new metadata object where the values match the values on the UIImage
///
func matchMetadata(metadata: [String: AnyObject], image: UIImage) -> [String: AnyObject] {
var resultingMetadata = metadata
let correctOrientation = image.metadataOrientation
resultingMetadata[kCGImagePropertyOrientation as String] = Int(correctOrientation.rawValue) as AnyObject?
if var tiffMetadata = resultingMetadata[kCGImagePropertyTIFFDictionary as String] as? [String: AnyObject] {
tiffMetadata[kCGImagePropertyTIFFOrientation as String] = Int(correctOrientation.rawValue) as AnyObject?
resultingMetadata[kCGImagePropertyTIFFDictionary as String] = tiffMetadata as AnyObject?
}
return resultingMetadata
}
// MARK: - Error Handling
enum ErrorCode: Int {
case UnsupportedAssetType = 1
case FailedToExport = 2
case FailedToExportMetadata = 3
}
private func errorForCode(errorCode: ErrorCode, failureReason: String) -> NSError {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
let error = NSError(domain: "NSURL+ExporterExtensions", code: errorCode.rawValue, userInfo: userInfo)
return error
}
}
| 7a2e0c345ee29a1a6268fc68fe6aeeae | 41.555215 | 201 | 0.60679 | false | false | false | false |
instacrate/tapcrate-api | refs/heads/master | Sources/api/Controllers/ProductController.swift | mit | 1 | //
// ProductController.swift
// polymr-api
//
// Created by Hakon Hanesand on 3/3/17.
//
//
import Vapor
import HTTP
import Fluent
import FluentProvider
import Paginator
final class ProductController: ResourceRepresentable {
func index(_ request: Request) throws -> ResponseRepresentable {
let sort = try request.extract() as Sort
var query: Query<Product> = try Product.makeQuery()
if let maker = request.query?["maker"]?.bool, maker {
let maker = try request.maker()
query = try maker.products().makeQuery()
}
let sortedQuery = try sort.modify(query)
let paginator: Paginator<Product> = try sortedQuery.paginator(15, request: request) { models in
if models.count == 0 {
return Node.array([])
}
if let expander: Expander<Product> = try request.extract() {
return try expander.expand(for: models) { (relation: Relation, identifiers: [Identifier]) -> [[NodeRepresentable]] in
switch relation.path {
case "tags":
return try collect(identifiers: identifiers, base: Product.self, relation: relation) as [[Tag]]
case "makers":
let makerIds = models.map { $0.maker_id }
return try collect(identifiers: makerIds, base: Product.self, relation: relation) as [[Maker]]
case "pictures":
return try collect(identifiers: identifiers, base: Product.self, relation: relation) as [[ProductPicture]]
case "offers":
return try collect(identifiers: identifiers, base: Product.self, relation: relation) as [[Offer]]
case "variants":
return try collect(identifiers: identifiers, base: Product.self, relation: relation) as [[Variant]]
case "reviews":
return try collect(identifiers: identifiers, base: Product.self, relation: relation) as [[Review]]
default:
throw Abort.custom(status: .badRequest, message: "Could not find expansion for \(relation.path) on \(type(of: self)).")
}
}.converted(in: jsonContext)
}
return try models.makeNode(in: jsonContext)
}
return try paginator.makeResponse()
}
func show(_ request: Request, product: Product) throws -> ResponseRepresentable {
try Product.ensure(action: .read, isAllowedOn: product, by: request)
if let expander: Expander<Product> = try request.extract() {
return try expander.expand(for: product, mappings: { (relation, identifier: Identifier) -> [NodeRepresentable] in
switch relation.path {
case "tags":
return try product.tags().all()
case "makers":
return try product.maker().limit(1).all()
case "pictures":
return try product.pictures().all()
case "offers":
return try product.offers().all()
case "variants":
return try product.variants().all()
case "reviews":
return try product.reviews().all()
default:
throw Abort.custom(status: .badRequest, message: "Could not find expansion for \(relation.path) on \(type(of: self)).")
}
}).makeResponse()
}
return try product.makeResponse()
}
func create(_ request: Request) throws -> ResponseRepresentable {
var result: [String : Node] = [:]
let product: Product = try request.extractModel(injecting: request.makerInjectable())
try Product.ensure(action: .read, isAllowedOn: product, by: request)
try product.save()
guard let product_id = product.id else {
throw Abort.custom(status: .internalServerError, message: "Failed to save product.")
}
result["product"] = try product.makeNode(in: emptyContext)
guard let node = request.json?.node else {
return try JSON(result.makeNode(in: jsonContext))
}
if let pictureNode: [Node] = try? node.extract("pictures") {
let context = try ParentContext<Product>(product_id)
let pictures = try pictureNode.map { (object: Node) -> ProductPicture in
let picture: ProductPicture = try ProductPicture(node: Node(object.permit(ProductPicture.permitted).wrapped, in: context))
try picture.save()
return picture
}
result["pictures"] = try pictures.makeNode(in: jsonContext)
}
if let tags: [Int] = try? node.extract("tags") {
let tags = try tags.map { (id: Int) -> Tag? in
guard let tag = try Tag.find(id) else {
return nil
}
let pivot = try Pivot<Tag, Product>(tag, product)
try pivot.save()
return tag
}.flatMap { $0 }
result["tags"] = try tags.makeNode(in: emptyContext)
}
if let variantNodes: [Node] = try? node.extract("variants") {
let context = try SecondaryParentContext<Product, Maker>(product.id, product.maker_id)
let variants = try variantNodes.map { (variantNode: Node) -> Variant in
let variant = try Variant(node: Node(variantNode.permit(Variant.permitted).wrapped, in: context))
try variant.save()
return variant
}
result["variants"] = try variants.makeNode(in: jsonContext)
}
return try JSON(result.makeNode(in: jsonContext))
}
func delete(_ request: Request, product: Product) throws -> ResponseRepresentable {
try Product.ensure(action: .delete, isAllowedOn: product, by: request)
try product.delete()
return Response(status: .noContent)
}
func modify(_ request: Request, product: Product) throws -> ResponseRepresentable {
try Product.ensure(action: .write, isAllowedOn: product, by: request)
let product: Product = try request.patchModel(product)
try product.save()
return try product.makeResponse()
}
func makeResource() -> Resource<Product> {
return Resource(
index: index,
store: create,
show: show,
update: modify,
destroy: delete
)
}
}
| abddb6369f604ff417b97df3937ea273 | 37.17033 | 143 | 0.544264 | false | false | false | false |
ddaguro/clintonconcord | refs/heads/master | OIMApp/Controls/ADVTabSegmentControl/ADVTabSegmentControl.swift | mit | 1 | //
// ADVTabSegmentControl.swift
// Mega
//
// Created by Tope Abayomi on 01/12/2014.
// Copyright (c) 2014 App Design Vault. All rights reserved.
//
import UIKit
@IBDesignable class ADVTabSegmentControl: UIControl {
private var labels = [UILabel]()
private var separators = [UIView]()
var items: [String] = ["Item 1", "Item 2", "Item 3"] {
didSet {
setupLabels()
}
}
var selectedIndex : Int = 0 {
didSet {
displayNewSelectedIndex()
}
}
@IBInspectable var selectedLabelColor : UIColor = UIColor.blackColor() {
didSet {
setSelectedColors()
}
}
@IBInspectable var unselectedLabelColor : UIColor = UIColor(white: 0.47, alpha: 1.0) {
didSet {
setSelectedColors()
}
}
@IBInspectable var borderColor : UIColor = UIColor(white: 0.78, alpha: 1.0) {
didSet {
setSelectedColors()
}
}
@IBInspectable var font : UIFont! = UIFont.systemFontOfSize(12) {
didSet {
setFont()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
func setupView(){
layer.borderColor = borderColor.CGColor
layer.borderWidth = 0.5
backgroundColor = UIColor(white: 0.95, alpha: 1.0)
setupLabels()
addIndividualItemConstraints(labels, mainView: self, padding: 0)
}
func setupLabels(){
for label in labels {
label.removeFromSuperview()
}
labels.removeAll(keepCapacity: true)
for index in 1...items.count {
let label = UILabel(frame: CGRectMake(0, 0, 70, 40))
label.text = items[index - 1]
label.backgroundColor = UIColor.clearColor()
label.textAlignment = .Center
label.font = UIFont(name: MegaTheme.boldFontName, size: 15)
label.textColor = index == 1 ? selectedLabelColor : unselectedLabelColor
label.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(label)
labels.append(label)
//Add separators unless we are at the last label
if index != items.count {
let separator = UIView()
separator.backgroundColor = borderColor
separator.translatesAutoresizingMaskIntoConstraints = false
separators.append(separator)
self.addSubview(separator)
}
}
addIndividualItemConstraints(labels, mainView: self, padding: 0)
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
let location = touch.locationInView(self)
var calculatedIndex : Int?
for (index, item) in labels.enumerate() {
if item.frame.contains(location) {
calculatedIndex = index
}
}
if calculatedIndex != nil {
selectedIndex = calculatedIndex!
sendActionsForControlEvents(.ValueChanged)
}
return false
}
func displayNewSelectedIndex(){
for (index, item) in labels.enumerate() {
item.textColor = unselectedLabelColor
}
let label = labels[selectedIndex]
label.textColor = selectedLabelColor
}
func addIndividualItemConstraints(items: [UIView], mainView: UIView, padding: CGFloat) {
let constraints = mainView.constraints
for (index, button) in items.enumerate() {
let topConstraint = NSLayoutConstraint(item: button, attribute: .Top, relatedBy: .Equal, toItem: mainView, attribute: .Top, multiplier: 1.0, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: mainView, attribute: .Bottom, multiplier: 1.0, constant: 0)
var rightConstraint : NSLayoutConstraint!
if index == items.count - 1 {
rightConstraint = NSLayoutConstraint(item: button, attribute: .Right, relatedBy: NSLayoutRelation.Equal, toItem: mainView, attribute: .Right, multiplier: 1.0, constant: -padding)
}else{
let nextSeparator = separators[index]
rightConstraint = NSLayoutConstraint(item: button, attribute: .Right, relatedBy: .Equal, toItem: nextSeparator, attribute: .Left, multiplier: 1.0, constant: -padding)
}
var leftConstraint : NSLayoutConstraint!
if index == 0 {
leftConstraint = NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: mainView, attribute: .Left, multiplier: 1.0, constant: padding)
}else{
let previousSeparator = separators[index - 1]
leftConstraint = NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: previousSeparator, attribute: .Right, multiplier: 1.0, constant: padding)
let firstItem = items[0]
let widthConstraint = NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: firstItem, attribute: .Width, multiplier: 1.0 , constant: 0)
mainView.addConstraint(widthConstraint)
}
mainView.addConstraints([topConstraint, bottomConstraint, rightConstraint, leftConstraint])
}
for separator in separators {
let widthConstraint = NSLayoutConstraint(item: separator, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0 , constant: 0.5)
separator.addConstraint(widthConstraint)
let topConstraint = NSLayoutConstraint(item: separator, attribute: .Top, relatedBy: .Equal, toItem: mainView, attribute: .Top, multiplier: 1.0, constant: 10)
let bottomConstraint = NSLayoutConstraint(item: separator, attribute: .Bottom, relatedBy: .Equal, toItem: mainView, attribute: .Bottom, multiplier: 1.0, constant: -10)
mainView.addConstraints([topConstraint, bottomConstraint])
}
}
func setSelectedColors(){
for item in labels {
item.textColor = unselectedLabelColor
}
if labels.count > 0 {
labels[0].textColor = selectedLabelColor
}
layer.borderColor = borderColor.CGColor
layer.borderWidth = 1
}
func setFont(){
for item in labels {
item.font = font
}
}
}
| 6d84a441fcd74f55567ba3012a537687 | 32.252294 | 194 | 0.564768 | false | false | false | false |
noahemmet/FingerPaint | refs/heads/master | FingerPaint/CGPoint+Utilities.swift | apache-2.0 | 1 | // Via https://github.com/andrelind/swift-catmullrom
import Foundation
extension CGPoint{
func translate(x: CGFloat, _ y: CGFloat) -> CGPoint {
return CGPointMake(self.x + x, self.y + y)
}
func translateX(x: CGFloat) -> CGPoint {
return CGPointMake(self.x + x, self.y)
}
func translateY(y: CGFloat) -> CGPoint {
return CGPointMake(self.x, self.y + y)
}
func invertY() -> CGPoint {
return CGPointMake(self.x, -self.y)
}
func xAxis() -> CGPoint {
return CGPointMake(0, self.y)
}
func yAxis() -> CGPoint {
return CGPointMake(self.x, 0)
}
func addTo(a: CGPoint) -> CGPoint {
return CGPointMake(self.x + a.x, self.y + a.y)
}
func deltaTo(a: CGPoint) -> CGPoint {
return CGPointMake(self.x - a.x, self.y - a.y)
}
func multiplyBy(value:CGFloat) -> CGPoint{
return CGPointMake(self.x * value, self.y * value)
}
func length() -> CGFloat {
return CGFloat(sqrt(CDouble(
self.x*self.x + self.y*self.y
)))
}
func normalize() -> CGPoint {
let l = self.length()
return CGPointMake(self.x / l, self.y / l)
}
static func fromString(string: String) -> CGPoint {
var s = string.stringByReplacingOccurrencesOfString("{", withString: "")
s = s.stringByReplacingOccurrencesOfString("}", withString: "")
s = s.stringByReplacingOccurrencesOfString(" ", withString: "")
let x = NSString(string: s.componentsSeparatedByString(",").first! as String).doubleValue
let y = NSString(string: s.componentsSeparatedByString(",").last! as String).doubleValue
return CGPointMake(CGFloat(x), CGFloat(y))
}
} | e40ea801312a46b730ec5ecacdcd62ce | 27.730159 | 97 | 0.577114 | false | false | false | false |
Ribeiro/IDZSwiftCommonCrypto | refs/heads/master | IDZSwiftCommonCrypto/README.playground/section-12.swift | mit | 1 | var keys5 = arrayFromHexString("0102030405060708090a0b0c0d0e0f10111213141516171819")
var datas5 : [UInt8] = Array(count:50, repeatedValue:0xcd)
var expecteds5 = arrayFromHexString("4c9007f4026250c6bc8414f9bf50c86c2d7235da")
var hmacs5 = HMAC(algorithm:.SHA1, key:keys5).update(datas5)?.final()
// RFC2202 says this should be 4c9007f4026250c6bc8414f9bf50c86c2d7235da
let expectedRFC2202 = arrayFromHexString("4c9007f4026250c6bc8414f9bf50c86c2d7235da")
assert(hmacs5! == expectedRFC2202)
| 447ed72feee55ec0dfada620f632e8d7 | 59.875 | 84 | 0.835729 | false | false | false | false |
ahbusaidi/ABEmojiSearchView | refs/heads/master | Source/ABEmojiSearchView.swift | mit | 1 | //
// ABEmojiSearchView.swift
// EmoticonSearch
//
// Created by Ahmed Al-Busaidi on 11/9/15.
// Copyright © 2015 Ahmed Al-Busaidi. All rights reserved.
//
import UIKit
protocol ABEmojiSearchViewDelegate:NSObjectProtocol{
func emojiSearchViewWillAppear(emojiSearchView : ABEmojiSearchView)
func emojiSearchViewDidAppear(emojiSearchView:ABEmojiSearchView)
func emojiSearchViewWillDisappear(emojiSearchView:ABEmojiSearchView)
func emojiSearchViewDidDisappear(emojiSearchView:ABEmojiSearchView )
}
class ABEmojiSearchView: UIView,UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate {
var appearAnimationBlock: (() -> Void)?
var disappearAnimationBlock: (() -> Void)?
var textView: UITextView!
var textViewDelegate: UITextViewDelegate!
var textField: UITextField!
var textFieldDelegate: UITextFieldDelegate!
var dividerView: UIView = {
let _dividerView = UIView(frame: CGRectMake(0, 0, 0, 0.5))
_dividerView.backgroundColor = UIColor(white: 205.0/255.0, alpha: 1.0)
_dividerView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
return _dividerView
}()
lazy var manager = ABEmojiManager()
var currentSearchRange: NSRange!
var tableView: UITableView!
var delegate: ABEmojiSearchViewDelegate!
var headerTitle:NSString!{
didSet{
self.tableView.reloadData()
}
}
var font: UIFont! {
didSet{
self.tableView.reloadData()
}
}
var textColor: UIColor! {
didSet{
self.tableView.reloadData()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
tableView = UITableView()
tableView.delegate = self;
tableView.dataSource = self;
tableView.frame = self.bounds;
tableView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth,
UIViewAutoresizing.FlexibleHeight]
tableView.registerClass(ABEmojiSearchResultTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(ABEmojiSearchResultTableViewCell))
tableView.showsVerticalScrollIndicator = false
tableView.rowHeight = 44.0
self.alpha = 0.0
self.font = UIFont.systemFontOfSize(17.0)
self.textColor = UIColor.darkTextColor()
self.addSubview(self.tableView)
self.addSubview(self.dividerView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func searchWithText(searchText: NSString){
self.manager.searchWithText(searchText)
if (self.manager.numberOfSearchResults() > 0){
self.tableView.reloadData()
self.appear()
}else{
self.disappear()
}
}
func installOnTextField(textField: UITextField){
self.textView = nil
self.textViewDelegate = nil
self.textFieldDelegate = textField.delegate
self.textField = textField
self.textField.delegate = self
}
func installOnTextView(textView : UITextView)
{
self.textField = nil
self.textFieldDelegate = nil
self.textViewDelegate = textView.delegate
self.textView = textView
self.textView.delegate = self
}
func appear(){
if self.delegate != nil && self.delegate.respondsToSelector("emojiSearchViewWillAppear:"){
self.delegate.emojiSearchViewWillAppear(self)
}
if (self.appearAnimationBlock != nil){
self.appearAnimationBlock!()
}else{
self.alpha = 1.0
self.appearAnimationDidFinish()
}
}
func appearAnimationDidFinish(){
if self.delegate != nil && self.delegate.respondsToSelector("emojiSearchViewDidAppear:"){
self.delegate.emojiSearchViewDidAppear(self)
}
}
func disappear() {
if ((self.delegate?.respondsToSelector(Selector("emojiSearchViewWillDisappear:"))) != nil) {
self.delegate.emojiSearchViewWillDisappear(self)
}
if (self.disappearAnimationBlock != nil) {
self.disappearAnimationBlock!();
} else {
self.alpha = 0.0;
self.disappearAnimationDidFinish()
}
}
func disappearAnimationDidFinish() {
if self.delegate != nil && self.delegate.respondsToSelector("emojiSearchViewDidDisappear:") {
self.delegate.emojiSearchViewDidDisappear(self)
}
self.manager.clear()
self.currentSearchRange = NSMakeRange(0, 0)
self.tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.manager.numberOfSearchResults()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = NSStringFromClass(ABEmojiSearchResultTableViewCell)
let cell = self.tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! ABEmojiSearchResultTableViewCell
cell.emoji = self.manager.emojiAtIndex(indexPath.row)
cell.textLabel?.font = self.font
cell.textLabel?.textColor = self.textColor
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let replacementString = NSString(format: "%@ ", (self.manager.emojiAtIndex(indexPath.row)?.emoji)!)
let extendedRange = NSMakeRange(self.currentSearchRange.location - 1, self.currentSearchRange.length + 1)
if self.textField != nil {
self.textField.text = (self.textField.text! as NSString).stringByReplacingCharactersInRange(extendedRange, withString: replacementString as String)
}
if self.textView != nil{
self.textView.text = (self.textView.text! as NSString).stringByReplacingCharactersInRange(extendedRange, withString: replacementString as String)
}
self.tableView.deselectRowAtIndexPath(indexPath, animated: false)
self.disappear()
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if self.headerTitle == nil{
return ""
}else{
return self.headerTitle as String
}
}
func textFieldDidBeginEditing(textField: UITextField) {
if self.textFieldDelegate != nil && self.textFieldDelegate.respondsToSelector("textFieldDidBeginEditing:"){
self.textFieldDelegate.textFieldDidBeginEditing!(textField)
}
}
func textFieldDidEndEditing(textField: UITextField) {
if self.textFieldDelegate != nil && self.textFieldDelegate.respondsToSelector("textFieldDidEndEditing:"){
self.textFieldDelegate.textFieldDidBeginEditing!(textField)
}
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
self.handleString(textField.text!, replacementString: string, range: range)
if (self.textFieldDelegate != nil && self.textFieldDelegate.respondsToSelector("textField:shouldChangeCharactersInRange:replacementString:")) {
return self.textFieldDelegate.textField!(textField, shouldChangeCharactersInRange: range, replacementString: string)
} else {
return true
}
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if (self.textFieldDelegate != nil && self.textFieldDelegate.respondsToSelector("textFieldShouldBeginEditing:")) {
return self.textFieldDelegate.textFieldShouldBeginEditing!(textField)
} else {
return true
}
}
func textFieldShouldClear(textField: UITextField) -> Bool {
if (self.textFieldDelegate != nil && self.textFieldDelegate.respondsToSelector("textFieldShouldClear:")) {
return self.textFieldDelegate.textFieldShouldClear!(textField)
} else {
return true
}
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
if (self.textFieldDelegate != nil && self.textFieldDelegate.respondsToSelector("textFieldShouldEndEditing:")) {
return self.textFieldDelegate.textFieldShouldEndEditing!(textField)
} else {
return true
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if (self.textFieldDelegate != nil && self.textFieldDelegate.respondsToSelector("textFieldShouldReturn:")) {
return self.textFieldDelegate.textFieldShouldReturn!(textField)
} else {
return true
}
}
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
if (self.textViewDelegate != nil && self.textViewDelegate.respondsToSelector("textViewShouldBeginEditing:")) {
return self.textViewDelegate.textViewShouldBeginEditing!(textView);
} else {
return true
}
}
func textViewDidBeginEditing(textView: UITextView) {
if (self.textViewDelegate != nil && self.textViewDelegate.respondsToSelector("textViewDidBeginEditing:")) {
self.textViewDelegate.textViewDidBeginEditing!(textView)
}
}
func textViewShouldEndEditing(textView: UITextView) -> Bool {
if (self.textViewDelegate != nil && self.textViewDelegate.respondsToSelector("textViewShouldEndEditing:")) {
return self.textViewDelegate.textViewShouldEndEditing!(textView)
} else {
return true
}
}
func textViewDidEndEditing(textView: UITextView) {
if (self.textViewDelegate != nil && self.textViewDelegate.respondsToSelector("textViewDidEndEditing:")) {
self.textViewDelegate.textViewDidEndEditing!(textView);
}
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
self.handleString(textView.text, replacementString: text, range: range)
if (self.textViewDelegate != nil && self.textViewDelegate.respondsToSelector("textView:shouldChangeTextInRange:replacementText:")) {
return self.textViewDelegate.textView!(textView, shouldChangeTextInRange: range, replacementText: text)
} else {
return true
}
}
func textViewDidChange(textView: UITextView) {
if (self.textViewDelegate != nil && self.textViewDelegate.respondsToSelector("textViewDidChange:")) {
self.textViewDelegate.textViewDidChange!(textView);
}
}
func textViewDidChangeSelection(textView: UITextView) {
if (self.textViewDelegate != nil && self.textViewDelegate.respondsToSelector("textViewDidChangeSelection:")) {
self.textViewDelegate.textViewDidChangeSelection!(textView);
}
}
func textView(textView: UITextView, shouldInteractWithTextAttachment textAttachment: NSTextAttachment, inRange characterRange: NSRange) -> Bool {
if (self.textViewDelegate != nil && self.textViewDelegate.respondsToSelector("textView:shouldInteractWithTextAttachment:inRange:")) {
return self.textViewDelegate.textView!(textView, shouldInteractWithTextAttachment: textAttachment, inRange: characterRange)
} else {
return true
}
}
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
if (self.textViewDelegate != nil && self.textViewDelegate.respondsToSelector("textView:shouldInteractWithURL:inRange:")) {
return self.textViewDelegate.textView!(textView, shouldInteractWithURL: URL, inRange: characterRange)
} else {
return true
}
}
func handleString(string: NSString, replacementString: NSString, range:NSRange){
let newString = string.stringByReplacingCharactersInRange(range, withString: replacementString as String) as NSString
let searchLength = range.location + replacementString.length
let colonRange = newString.rangeOfString("@", options: NSStringCompareOptions.BackwardsSearch, range: NSMakeRange(0, searchLength))
let spaceRange = newString.rangeOfString(" ", options: NSStringCompareOptions.BackwardsSearch, range: NSMakeRange(0, searchLength))
if (colonRange.location != NSNotFound && (spaceRange.location == NSNotFound || colonRange.location > spaceRange.location)) {
self.searchWithColonLocation(colonRange.location, string: newString)
} else {
self.disappear()
}
}
func searchWithColonLocation(colonLocation : Int, string:NSString){
let searchRange = NSMakeRange(colonLocation + 1, string.length - colonLocation - 1);
let spaceRange = string.rangeOfString(" ", options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange)
var searchText:NSString!
if (spaceRange.location == NSNotFound) {
searchText = string.substringFromIndex(colonLocation + 1)
} else {
searchText = string.substringWithRange(NSMakeRange(colonLocation + 1, spaceRange.location - colonLocation - 1))
}
self.currentSearchRange = NSMakeRange(colonLocation + 1, searchText.length)
self.searchWithText(searchText)
}
}
| 2c1cde3b2cafb152612abbbeb10a668e | 39.657738 | 159 | 0.674914 | false | false | false | false |
Drusy/SwiftiumKit | refs/heads/master | SwiftiumKit/StringExtensions.swift | apache-2.0 | 1 | //
// String+SKAdditions.swift
// SwiftiumKit
//
// Created by Richard Bergoin on 10/03/16.
// Copyright © 2016 Openium. All rights reserved.
//
import Foundation
// MARK: Hashes
private typealias SKCryptoFunctionPointer = (UnsafeRawPointer, UInt32, UnsafeRawPointer) -> Void
private enum CryptoAlgorithm {
case md5, sha1, sha224, sha256, sha384, sha512
var cryptoFunction: SKCryptoFunctionPointer {
var result: SKCryptoFunctionPointer
switch self {
case .md5: result = sk_crypto_md5
case .sha1: result = sk_crypto_sha1
case .sha224: result = sk_crypto_sha224
case .sha256: result = sk_crypto_sha256
case .sha384: result = sk_crypto_sha384
case .sha512: result = sk_crypto_sha512
}
return result
}
var digestLength: Int {
var length: Int
switch self {
case .md5: length = Int(SK_MD5_DIGEST_LENGTH)
case .sha1: length = Int(SK_SHA1_DIGEST_LENGTH)
case .sha224: length = Int(SK_SHA224_DIGEST_LENGTH)
case .sha256: length = Int(SK_SHA256_DIGEST_LENGTH)
case .sha384: length = Int(SK_SHA384_DIGEST_LENGTH)
case .sha512: length = Int(SK_SHA512_DIGEST_LENGTH)
}
return length
}
}
extension String.UTF8View {
var md5: Data {
return self.hashUsingAlgorithm(.md5)
}
var sha1: Data {
return self.hashUsingAlgorithm(.sha1)
}
var sha224: Data {
return self.hashUsingAlgorithm(.sha224)
}
var sha256: Data {
return self.hashUsingAlgorithm(.sha256)
}
var sha384: Data {
return self.hashUsingAlgorithm(.sha384)
}
var sha512: Data {
return self.hashUsingAlgorithm(.sha512)
}
fileprivate func hashUsingAlgorithm(_ algorithm: CryptoAlgorithm) -> Data {
let cryptoFunction = algorithm.cryptoFunction
let length = algorithm.digestLength
return self.hash(cryptoFunction, length: length)
}
fileprivate func hash(_ cryptoFunction: SKCryptoFunctionPointer, length: Int) -> Data {
let hashBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
//defer { hashBytes.dealloc(length) }
cryptoFunction(Array<UInt8>(self), UInt32(self.count), hashBytes)
return Data(bytesNoCopy: UnsafeMutablePointer<UInt8>(hashBytes), count: length, deallocator: .free)
}
}
extension String {
public var md5HashData: Data {
return self.utf8.md5
}
/// Converts string UTF8 data to MD5 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing MD5 hash
public var md5: String {
return self.md5HashData.base16EncodedString()
}
public var sha1HashData: Data {
return self.utf8.sha1
}
/// Converts string UTF8 data to SHA1 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing SHA1 hash
public var sha1: String {
return self.sha1HashData.base16EncodedString()
}
public var sha224HashData: Data {
return self.utf8.sha224
}
/// Converts string UTF8 data to SHA224 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing SHA224 hash
public var sha224: String {
return self.sha224HashData.base16EncodedString()
}
public var sha256HashData: Data {
return self.utf8.sha256
}
/// Converts string UTF8 data to SHA256 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing SHA256 hash
public var sha256: String {
return self.sha256HashData.base16EncodedString()
}
public var sha384HashData: Data {
return self.utf8.sha384
}
/// Converts string UTF8 data to SHA384 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing SHA384 hash
public var sha384: String {
return self.sha384HashData.base16EncodedString()
}
public var sha512HashData: Data {
return self.utf8.sha512
}
/// Converts string UTF8 data to SHA512 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing SHA512 hash
public var sha512: String {
return self.sha512HashData.base16EncodedString()
}
public func hmacSha1(_ key: String) -> String {
let keyData = Array<UInt8>(key.utf8)
let length = Int(20)
let hashBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
//defer { hashBytes.dealloc(length) }
sk_crypto_hmac_sha1(Array<UInt8>(self.utf8), UInt32(self.utf8.count), keyData, UInt32(key.utf8.count), hashBytes)
let data = Data(bytesNoCopy: UnsafeMutablePointer<UInt8>(hashBytes), count: length, deallocator: .free)
return data.base16EncodedString()
}
/**
Int subscript to String
Usage example :
````
var somestring = "some string"
let substring = somestring[3]
let substringNegativeIndex = somestring[-1]
````
- Parameter i: index of the string
- Returns: a String containing the character at position i or nil if index is out of string bounds
*/
public subscript(i: Int) -> String? {
get {
guard i >= -characters.count && i < characters.count else { return nil }
let charIndex: Index
if i >= 0 {
charIndex = index(startIndex, offsetBy: i)
} else {
charIndex = index(startIndex, offsetBy: characters.count + i)
}
return String(self[charIndex])
}
set(newValue) {
guard i >= 0 && i < characters.count else {
preconditionFailure("String subscript can only be used if the condition (index >= 0 && index < characters.count) is fulfilled")
}
guard newValue != nil else {
preconditionFailure("String replacement should not be nil")
}
let lowerIndex = index(startIndex, offsetBy: i, limitedBy: endIndex)!
let upperIndex = index(startIndex, offsetBy: i + 1, limitedBy: endIndex)!
let range = Range<String.Index>(uncheckedBounds: (lower: lowerIndex, upper: upperIndex))
if !range.isEmpty {
self = self.replacingCharacters(in: range, with: newValue!)
}
}
}
/**
Int closed range subscript to String
Usage example :
````
let somestring = "some string"
let substring = somestring[0..3]
````
- Parameter range: a closed range of the string
- Returns: a substring containing the characters in the specified closed range
*/
public subscript(range: ClosedRange<Int>) -> String {
let maxLowerBound = max(0, range.lowerBound)
let maxSupportedLowerOffset = maxLowerBound
let maxSupportedUpperOffset = range.upperBound - maxLowerBound + 1
let lowerIndex = index(startIndex, offsetBy: maxSupportedLowerOffset, limitedBy: endIndex) ?? endIndex
let upperIndex = index(lowerIndex, offsetBy: maxSupportedUpperOffset, limitedBy: endIndex) ?? endIndex
return substring(with: lowerIndex..<upperIndex)
}
/**
Int range subscript to String
Usage example :
````
let somestring = "some string"
let substring = somestring[0..<3]
````
- Parameter range: a range of the string
- Returns: a substring containing the characters in the specified range
*/
public subscript(range: Range<Int>) -> String {
let maxLowerBound = max(0, range.lowerBound)
let maxSupportedLowerOffset = maxLowerBound
let maxSupportedUpperOffset = range.upperBound - maxLowerBound
let lowerIndex = index(startIndex, offsetBy: maxSupportedLowerOffset, limitedBy: endIndex) ?? endIndex
let upperIndex = index(lowerIndex, offsetBy: maxSupportedUpperOffset, limitedBy: endIndex) ?? endIndex
return substring(with: lowerIndex..<upperIndex)
}
}
extension String {
public var isEmail: Bool {
let emailRegex = "[_A-Za-z0-9-+]+(?:\\.[_A-Za-z0-9-+]+)*@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
}
public func firstLowercased() -> String {
var firstLowercased = self
if let firstCharLowercased = self[0]?.lowercased() {
firstLowercased[0] = firstCharLowercased
}
return firstLowercased
}
}
| 9737440c14ca77a8c55dbd52a24e297b | 31.723881 | 143 | 0.627252 | false | false | false | false |
WayneEld/Whirl | refs/heads/master | Indicate/Indicate.swift | mit | 1 | //
// Indicate.swift
// Indicate
//
// Created by Wayne Eldridge on 2017/04/15.
// Copyright © 2017 Wayne Eldridge. All rights reserved.
//
import Foundation
import UIKit
//TODO: Make color wheel //
public enum IndicateType {
case labyrinth
case normal
init(fromRawValue: IndicateType){
self = .normal
}
}
public var currentView = UIApplication.shared.windows[0].rootViewController
public class Indicate {
static var activityType = IndicateType(fromRawValue: .normal)
let lab = LabIndicator()
let normal = Normal()
static var indicateType = Indicate.activityType
public init(indicatorType: IndicateType){
Indicate.activityType = indicatorType
}
public func startIndicator(){
constructIndicatorAndStart()
}
private func constructIndicatorAndStart(){
let indicateType = Indicate.activityType
switch indicateType{
case .labyrinth:
print("Lab start")
lab.showIndicator()
case .normal:
normal.showIndicator()
}
}
public func stopIndicator(){
let indicateType = Indicate.activityType
switch indicateType{
case .labyrinth:
print("Lab")
lab.hideIndicator()
case .normal:
normal.hideIndicator()
}
}
//TODO: Still need to work out
public func stopIndicatorAndFade(_ duration: TimeInterval){
let indicateType = Indicate.activityType
switch indicateType{
case .labyrinth:
print("Lab")
lab.hideIndicator()
case .normal:
normal.hideIndicatorAndFade(withDuration: duration)
}
}
}
| fe570336d2c15f0006dd799d75130ee2 | 19.813953 | 75 | 0.598883 | false | false | false | false |
eric1202/LZJ_Coin | refs/heads/master | DinDinShopDemo/Pods/XCGLogger/Sources/XCGLogger/Destinations/BaseQueuedDestination.swift | mit | 3 | //
// BaseQueuedDestination.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2017-04-02.
// Copyright © 2017 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Foundation
import Dispatch
// MARK: - BaseQueuedDestination
/// A base class destination (with a possible DispatchQueue) that doesn't actually output the log anywhere and is intented to be subclassed
open class BaseQueuedDestination: BaseDestination {
// MARK: - Properties
/// The dispatch queue to process the log on
open var logQueue: DispatchQueue? = nil
// MARK: - Life Cycle
// MARK: - Overridden Methods
/// Apply filters and formatters to the message before queuing it to be written by the write method.
///
/// - Parameters:
/// - logDetails: The log details.
/// - message: Message ready to be formatted for output.
///
/// - Returns: Nothing
///
open override func output(logDetails: LogDetails, message: String) {
let outputClosure = {
// Create mutable versions of our parameters
var logDetails = logDetails
var message = message
// Apply filters, if any indicate we should drop the message, we abort before doing the actual logging
guard !self.shouldExclude(logDetails: &logDetails, message: &message) else { return }
self.applyFormatters(logDetails: &logDetails, message: &message)
self.write(message: message)
}
if let logQueue = logQueue {
logQueue.async(execute: outputClosure)
}
else {
outputClosure()
}
}
// MARK: - Methods that must be overriden in subclasses
/// Write the log message to the destination.
///
/// - Parameters:
/// - message: Formatted/processed message ready for output.
///
/// - Returns: Nothing
///
open func write(message: String) {
// Do something with the message in an overridden version of this method
precondition(false, "Must override this")
}
}
| 4ad1946f311adbac0233b3657e19894d | 33.109375 | 139 | 0.640861 | false | false | false | false |
Fenrikur/ef-app_ios | refs/heads/master | Eurofurence/Modules/Login/View/LoginViewController.swift | mit | 1 | import UIKit.UIButton
import UIKit.UIViewController
class LoginViewController: UITableViewController, UITextFieldDelegate, LoginScene {
// MARK: IBOutlets
@IBOutlet private weak var loginButton: UIButton!
@IBOutlet private weak var cancelButton: UIBarButtonItem!
@IBOutlet private weak var registrationNumberTextField: UITextField!
@IBOutlet private weak var usernameTextField: UITextField!
@IBOutlet private weak var passwordTextField: UITextField!
// MARK: IBActions
@IBAction private func loginButtonTapped(_ sender: Any) {
delegate?.loginSceneDidTapLoginButton()
}
@IBAction private func cancelButtonTapped(_ sender: Any) {
delegate?.loginSceneDidTapCancelButton()
}
@IBAction private func registrationNumberDidChange(_ sender: UITextField) {
guard let registrationNumber = sender.text else { return }
delegate?.loginSceneDidUpdateRegistrationNumber(registrationNumber)
}
@IBAction private func usernameDidChange(_ sender: UITextField) {
guard let username = sender.text else { return }
delegate?.loginSceneDidUpdateUsername(username)
}
@IBAction private func passwordDidChange(_ sender: UITextField) {
guard let password = sender.text else { return }
delegate?.loginSceneDidUpdatePassword(password)
}
@IBAction private func passwordPrimaryActionTriggered(_ sender: Any) {
delegate?.loginSceneDidTapLoginButton()
}
// MARK: Overrides
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
delegate?.loginSceneWillAppear()
}
// MARK: LoginScene
var delegate: LoginSceneDelegate?
func setLoginTitle(_ title: String) {
super.title = title
}
func overrideRegistrationNumber(_ registrationNumber: String) {
registrationNumberTextField.text = registrationNumber
}
func disableLoginButton() {
loginButton.isEnabled = false
}
func enableLoginButton() {
loginButton.isEnabled = true
}
}
| c55746dad3a1491b8a63c8b6db538082 | 28.394366 | 83 | 0.706277 | false | false | false | false |
akuraru/SParsers | refs/heads/master | Pod/Classes/DAL.swift | mit | 1 | //
// DAL.swift
// SParsers
//
// Created by akuraru on 2014/08/07.
// Copyright (c) 2014年 akuraru. All rights reserved.
//
import Foundation
/*
#I @"./packages"
#r @"FSharpx.Core.1.8.41/lib/40/FSharpx.Core.dll"
module DSL =
//Full language
type expr =
| CstI of int
| CstB of bool
| Prim of string * expr * expr
let exp1 = Prim("*", Prim("+", CstI 2 , CstI 1), CstI 4)
let rec eval (e:expr) :int =
match e with
| CstI i -> i
| Prim("+",e1, e2) -> eval e1 + eval e2
| Prim("-",e1, e2) -> eval e1 - eval e2
| Prim("*",e1, e2) -> eval e1 * eval e2
| _ -> failwith "dont know how to evaluate"
let val1 = eval exp1
let expKO = Prim("*", Prim("+", CstB true , CstI 1), CstI 4)
//This expression is wrong : substraction is not defined on Booleans !
//- No type system in the target language : we can write stupid expressions
//- Our target language is made of "EXPR" only.. we dont reuse F#
//building AST, type checking, evaluating, is done by us
module ShallowEmbedding =
//we represent the fundamental type of our domain in F#
type CstI = CstI of int
type CstB = CstB of bool
//We build primitive blocks - in valid F#
let plus (CstI a) (CstI b) = CstI (a + b)
let times (CstI a) (CstI b) = CstI (a * b)
let ifbranch (CstB v) a b = if v then a else b
let exp1 = times (plus (CstI 2)(CstI 1)) (CstI 4)
//let expKO = times (plus (CstB true)(CstI 1)) (CstI 4)
module ShallowEmbedding2 =
//a hardware simulator - a signal is a stream of input data
//each component takes some signal in and create some signal out
//we represent the fundamental type of our domain in F#
type Signal<'a> = 'a seq //a signal is a sequence of value, one for each clock cycle
//We build primitive blocks - in valid F#
let low :Signal<bool> = Seq.initInfinite (fun _ -> false) //always false
//a multiplexer
let mux (si:Signal<bool>)(sa:Signal<'a>,sb:Signal<'a>):Signal<'a> =
Seq.zip3 si sa sb |> Seq.map (fun (i,a,b) -> if i then a else b)
// a register delays a signal
let reg init (si:Signal<'a>) :Signal<'a>= seq{ yield init; yield! si}
//add
let plusone (si:Signal<int>) :Signal<int>= Seq.map ((+) 1) si
//Everything which interests us is built from those primitive blocks using the primitive type
//And they are ALSO a valid F# function, so we have a type system : F# type system !
//Program made for our subset will be verified for free.
//counts the number of true
let testSignal = seq{while true do yield! [true;false;false]}
let counter (si:Signal<bool>) = //si is Signal<bool> not int
let rec loop = let d = delay()
mux si (d |> plusone, d)
and delay() = seq{ yield 0; yield! loop}
loop
let testCountOK = counter testSignal |> Seq.take 5 |> Seq.toArray
//Summary : if the primitive types capture our domain, we have a free type system
//(provided the binding and evaluation in our domain is like F#...)
let counterKO (si:Signal<bool>) =
let rec loop = let d = delay()
mux si (d |> plusone, d)
and delay() = reg 0 loop //eager evaluation breaks functional abstraction for co-inductive types
loop
let testCountKO = counterKO testSignal |> Seq.take 5 |> Seq.toArray
module DeepEmbedding =
//previously we built values. from some base signal, we built an output signal
//with deep embedding we build expression representing a computation doing so
//inline replaces at compile time a generic function with the appropriate concrete function
type Return = Return with
static member ($) (Return, t:'a option) = fun (x:'a) -> Some x
static member ($) (Return, t:'a list) = fun (x:'a) -> [x]
let inline return' x : ^R = (Return $ Unchecked.defaultof< ^R> ) x
type Bind = Bind with
static member ($) (Bind, x:option<_>) = fun f -> Option.bind f x
static member ($) (Bind, x:list<_> ) = fun f ->
let rec bind f = function
| x::xs -> f x @ (bind f xs)
| [] -> []
bind f x
let inline (>>=) x f = (Bind $ x) f
let inline add (a:^a ) b = a + b
let a:list<_> = return' 1 ;;
let a:option<_> = return' 1 ;;
//add type class F# for + and *
//we can extract the AST of the expression in the target language from the expression in Fsharp language
type expr =
| CstI of int
| IfBranch of CstB * expr * expr
| Plus of expr * expr
| Times of expr * expr
| Var of string
and CstB = CstB of bool
type TPlus = TPlus with
static member ($) (TPlus, t : int) = (+) t
static member ($) (TPlus, t : expr) = fun (o:expr) -> Plus(t,o)
let inline (+) a b = (TPlus $ a) b
type TConst = TConst with
static member ($) (TConst, t : int) = fun (o:int) -> o
static member ($) (TConst, t : expr) = fun (o:int) -> CstI(o)
let inline return' x : ^R = (TConst $ Unchecked.defaultof< ^R> ) x
type TTimes = TTimes with
static member ($) (TTimes, t : int) = (*) t
static member ($) (TTimes, t : expr) = fun (o:expr) -> Times(t,o)
let inline (*) a b = (TTimes $ a ) b
let res : int = return' 2 + return' 1
let res : expr = (return' 2 + return' 1) * return' 3
let res : int = (return' 2 + return' 1) * return' 3
let inline f1 x = (x + return' 1) * return' 3
let ast = f1 (Var "x")
let res = f1 2
let rec eval (e:expr) :int =
match e with
| CstI i -> i
| Plus(e1, e2) -> eval e1 + eval e2
| Times(e1, e2) -> eval e1 * eval e2
| IfBranch(b1,e1, e2) -> if evalb b1 then eval e1 else eval e2
and evalb (e:CstB) : bool =
match e with
| CstB b -> b
module ScratchPad =
module ShallowEDSL3 =
//a hardware simulator - a signal is a
//type Signal<'a> = Next of (unit -> 'a * Signal<'a>)
type Signal<'a> = Next of 'a * (unit -> Signal<'a>)
let rec low :Signal<bool> = Next (false, fun () -> low)
let rec mux (Next(vi,ni):Signal<bool>)((Next(va,na)),(Next(vb,nb))) = Next((if vi then va else vb), fun () -> mux (ni()) (na(),nb()))
let reg init (si:Signal<'a>) :Signal<'a>= Next(init,fun () -> si)
let rec plusone (Next(vi,ni):Signal<int>) :Signal<int>= Next(vi+1, fun () -> plusone (ni()))
let counter (si:Signal<bool>) =
let rec loop() = mux si (delay() |> plusone, delay())
and delay() = loop() |> reg 0
loop()
let rec toSeq s = seq{ let (Next(v,n)) = s
yield v;yield! toSeq (n()) }
let fromSeq (s:'a seq) =
let a = s.GetEnumerator()
let rec getOne () = let v = a.Current
a.MoveNext() |> ignore
Next(v, fun () -> getOne())
getOne()
let si = seq{while true do yield! [true;false;false]} |> fromSeq
let t = mux si (si,si)
let testCount = counter (fromSeq testSignal) |> toSeq |> Seq.take 5 //|> Seq.toArray
*/ | f1ba58f5ef9826c5ff9de3ff0ef17995 | 30.829146 | 133 | 0.645034 | false | false | false | false |
drewg233/SlackyBeaver | refs/heads/master | Example/Pods/SwiftyBeaver/Sources/GoogleCloudDestination.swift | mit | 1 | //
// GoogleCloudDestination.swift
// SwiftyBeaver
//
// Copyright © 2017 Sebastian Kreutzberger. All rights reserved.
//
import Foundation
public final class GoogleCloudDestination: BaseDestination {
private let serviceName: String
public init(serviceName: String) {
self.serviceName = serviceName
super.init()
}
override public var asynchronously: Bool {
get {
return false
}
set {
return
}
}
override public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String,
file: String, function: String, line: Int) -> String? {
let gcpJSON: [String: Any] = [
"serviceContext": [
"service": serviceName
],
"message": msg,
"severity": level.severity,
"context": [
"reportLocation": ["filePath": file, "lineNumber": line, "functionName": function]
]
]
let finalLogString: String
do {
finalLogString = try jsonString(obj: gcpJSON)
} catch {
let uncrashableLogString = "{\"context\":{\"reportLocation\":{\"filePath\": \"\(file)\"" +
",\"functionName\":\"\(function)\"" +
",\"lineNumber\":\(line)},\"severity\"" +
":\"CRITICAL\",\"message\":\"Error encoding " +
"JSON log entry. You may be losing log messages!\"}"
finalLogString = uncrashableLogString.description
}
print(finalLogString)
return finalLogString
}
private func jsonString(obj: Dictionary<String, Any>) throws -> String {
let json = try JSONSerialization.data(withJSONObject: obj, options: [])
guard let string = String(data: json, encoding: .utf8) else {
throw GCPError.serialization
}
return string
}
}
///
/// https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity
extension SwiftyBeaver.Level {
/// Verbose is reported as Debug to GCP.
/// Recommend you don't bother using it.
var severity: String {
switch self {
// There is only one level below "Debug": "Default", which becomes "Any" and is considered as a potential error as well
case .verbose: return "DEBUG"
case .debug: return "DEBUG"
case .info: return "INFO"
case .warning: return "WARNING"
case .error: return "ERROR"
}
}
}
private enum GCPError: Error {
case serialization
}
| 2559eb05f3f099e6c821743b79ccb02c | 28.609195 | 127 | 0.572205 | false | false | false | false |
LYM-mg/MGDYZB | refs/heads/master | MGDYZB简单封装版/MGDYZB/Class/Tools/Category/NSObject+Extension.swift | mit | 1 | //
// NSObject+Extension.swift
// chart2
//
// Created by i-Techsys.com on 16/12/3.
// Copyright © 2016年 i-Techsys. All rights reserved.
//
import UIKit
// MARK: - 弹框
extension NSObject {
/// 只有是控制器和继承UIView的控件才会弹框
/**
* - 弹框提示
* - @param info 要提醒的内容
*/
func showInfo(info: String) {
if self.isKind(of: UIViewController.self) || self.isKind(of: UIView.self) {
let alertVc = UIAlertController(title: info, message: nil, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "好的", style: .cancel, handler: nil)
alertVc.addAction(cancelAction)
UIApplication.shared.keyWindow?.rootViewController?.present(alertVc, animated: true, completion: nil)
}
}
// iOS在当前屏幕获取第一响应
func getFirstResponder() -> Any? {
let keyWindow: UIWindow? = UIApplication.shared.keyWindow
let firstResponder: UIView? = keyWindow?.subviews.first?.perform(Selector(("firstResponder"))) as? UIView
return firstResponder
}
}
// MARK: - RunTime
extension NSObject {
/**
获取所有的方法和属性
- parameter cls: 当前类
*/
func mg_GetMethodAndPropertiesFromClass(cls: AnyClass) {
debugPrint("方法========================================================")
var methodNum: UInt32 = 0
let methods = class_copyMethodList(cls, &methodNum)
for index in 0..<numericCast(methodNum) {
let met: Method = methods![index]
debugPrint("m_name: \(method_getName(met))")
// debugPrint("m_returnType: \(String(utf8String: method_copyReturnType(met))!)")
// debugPrint("m_type: \(String(utf8String: method_getTypeEncoding(met)!)!)")
}
debugPrint("属性=========================================================")
var propNum: UInt32 = 0
let properties = class_copyPropertyList(cls, &propNum)
for index in 0..<Int(propNum) {
let prop: objc_property_t = properties![index]
debugPrint("p_name: \(String(utf8String: property_getName(prop))!)" + " " + "m_type: \(String(describing: String(utf8String: property_getAttributes(prop)!)!))")
// debugPrint("p_Attr: \(String(utf8String: property_getAttributes(prop))!)")
}
debugPrint("成员变量======================================================")
var ivarNum: UInt32 = 0
let ivars = class_copyIvarList(cls, &ivarNum)
for index in 0..<numericCast(ivarNum) {
let ivar: objc_property_t = ivars![index]
let name = ivar_getName(ivar)
debugPrint("ivar_name: \(String(cString: name!))" + " " + "m_type: \(String(describing: String(utf8String: ivar_getTypeEncoding(ivar)!)!))")
}
}
/**
- parameter cls: : 当前类
- parameter originalSelector: : 原方法
- parameter swizzledSelector: : 要交换的方法
*/
/// RunTime交换方法
class func mg_SwitchMethod(cls: AnyClass, originalSelector: Selector, swizzledSelector: Selector) {
guard let originalMethod = class_getInstanceMethod(cls, originalSelector) else {
return;
}
guard let swizzledMethod = class_getInstanceMethod(cls, swizzledSelector) else {
return;
}
let didAddMethod = class_addMethod(cls, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(cls, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
//
public func ClassIvarsNames(c: AnyClass) -> [Any]? {
var array: [AnyHashable] = []
var ivarNum: UInt32 = 0
let ivars = class_copyIvarList(c, &ivarNum)
for index in 0..<numericCast(ivarNum) {
let ivar: objc_property_t = ivars![index]
if let name:UnsafePointer<Int8> = ivar_getName(ivar) {
debugPrint("ivar_name: \(String(cString: name))" + " " + "m_type: \(String(describing: String(utf8String: ivar_getTypeEncoding(ivar)!)!))")
if let key = String(utf8String:name) {
array.append(key)
array.append("\n")
}
}
}
free(ivars)
return array
}
public func ClassMethodNames(c: AnyClass) -> [Any]? {
var array: [AnyHashable] = []
var methodCount: UInt32 = 0
let methodList = class_copyMethodList(c, &methodCount)
guard let methodArray = methodList else {
return array;
}
for i in 0..<methodCount {
array.append(NSStringFromSelector(method_getName(methodArray[Int(i)])))
}
free(methodArray)
return array
}
}
| 5d0cd9280c42810866f21a01ae5f6145 | 36.541985 | 175 | 0.578081 | false | false | false | false |
geekaurora/ReactiveListViewKit | refs/heads/master | ReactiveListViewKit/ReactiveListViewKit/TemplateViews/CZTextFeedCellView.swift | mit | 1 | //
// CZTextFeedCellView.swift
// ReactiveListViewKit
//
// Created by Cheng Zhang on 2/7/17.
// Copyright © 2017 Cheng Zhang. All rights reserved.
//
import UIKit
/**
Convenience text based CellView class
*/
open class CZTextFeedCell: UICollectionViewCell, CZFeedCellViewSizeCalculatable {
open var onAction: OnAction? {
didSet {
cellView?.onAction = onAction
}
}
open var viewModel: CZFeedViewModelable?
open var cellView: CZTextFeedCellView?
open var diffId: String {
return viewModel?.diffId ?? ""
}
public required init(viewModel: CZFeedViewModelable?, onAction: OnAction?) {
self.viewModel = viewModel
self.onAction = onAction
super.init(frame: .zero)
translatesAutoresizingMaskIntoConstraints = false
config(with: viewModel)
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
public func config(with viewModel: CZFeedViewModelable?) {
if let viewModel = viewModel as? CZTextFeedViewModel {
if cellView == nil {
cellView = CZTextFeedCellView(viewModel: viewModel, onAction: onAction)
cellView?.overlayOnSuperview(self)
}
cellView!.config(with: viewModel)
}
}
public class func sizeThatFits(_ size: CGSize, viewModel: CZFeedViewModelable) -> CGSize {
return CZTextFeedCellView.sizeThatFits(size, viewModel: viewModel)
}
}
public class CZTextFeedCellView: UIView, CZFeedCellViewSizeCalculatable {
public var onAction: OnAction?
private var titleLabel: UILabel!
private lazy var hasSetup: Bool = false
public var viewModel: CZFeedViewModelable?
public var diffId: String {
return viewModel?.diffId ?? ""
}
public required init(viewModel: CZFeedViewModelable?, onAction: OnAction?) {
self.viewModel = viewModel
self.onAction = onAction
super.init(frame: .zero)
translatesAutoresizingMaskIntoConstraints = false
config(with: viewModel)
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
public func setup() {
guard !hasSetup else {return}
hasSetup = true
titleLabel = UILabel(frame: .zero)
titleLabel.font = UIFont.systemFont(ofSize: 17)
titleLabel.overlayOnSuperview(
self,
insets: NSDirectionalEdgeInsets(
top: 5,
leading: 10,
bottom: 5,
trailing: 10))
}
public func config(with viewModel: CZFeedViewModelable?) {
setup()
if let viewModel = viewModel as? CZTextFeedViewModel {
titleLabel.text = viewModel.text
}
}
public class func sizeThatFits(_ containerSize: CGSize, viewModel: CZFeedViewModelable) -> CGSize {
guard let viewModel = viewModel as? CZTextFeedViewModel else { preconditionFailure() }
return CZFacadeViewHelper.sizeThatFits(containerSize,
viewModel: viewModel,
viewClass: CZTextFeedCellView.self,
isHorizontal: viewModel.isHorizontal)
}
}
| 03311ef6721f04e5770ecd2d08a26428 | 29.536364 | 103 | 0.623102 | false | false | false | false |
apple/swift-corelibs-foundation | refs/heads/main | Sources/Foundation/NSURLQueryItem.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// NSURLQueryItem encapsulates a single query name-value pair. The name and value strings of a query name-value pair are not percent encoded. For use with the NSURLComponents queryItems property.
open class NSURLQueryItem: NSObject, NSSecureCoding, NSCopying {
open private(set) var name: String
open private(set) var value: String?
public init(name: String, value: String?) {
self.name = name
self.value = value
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
public static var supportsSecureCoding: Bool {
return true
}
required public init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let encodedName = aDecoder.decodeObject(forKey: "NS.name") as! NSString
self.name = encodedName._swiftObject
let encodedValue = aDecoder.decodeObject(forKey: "NS.value") as? NSString
self.value = encodedValue?._swiftObject
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.name._bridgeToObjectiveC(), forKey: "NS.name")
aCoder.encode(self.value?._bridgeToObjectiveC(), forKey: "NS.value")
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURLQueryItem else { return false }
return other === self
|| (other.name == self.name
&& other.value == self.value)
}
}
extension NSURLQueryItem: _StructTypeBridgeable {
public typealias _StructType = URLQueryItem
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| 197a93351a6f23e95ec45ff1010d64df | 32.333333 | 195 | 0.665652 | false | false | false | false |
wayfindrltd/wayfindr-demo-ios | refs/heads/master | Wayfindr Demo/Classes/Model/WAYInstructionSet.swift | mit | 1 | //
// WAYInstructionSet.swift
// Wayfindr Tests
//
// Created by Wayfindr on 10/11/2015.
// Copyright (c) 2016 Wayfindr (http://www.wayfindr.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import AEXML
/**
* Represents a set of instructions to be associated with a `WAYGraphEdge`.
*/
struct WAYInstructionSet {
// MARK: - Properties
/// The language of the instruction set in BCP-47 code format.
let language: String
/// The instructions for the beginning of the path.
var beginning: String?
/// The instructions for the middle of the path.
var middle: String?
/// The instructions for the end of the path.
var ending: String?
/// The instructions if you are starting the route from with this edge, otherwise unused.
var startingOnly: String?
/**
Keys for the data in the `edge` GraphML element.
*/
enum WAYInstructionKeys: String {
case InstructionBeginning = "beginning"
case InstructionMiddle = "middle"
case InstructionEnd = "ending"
case InstructionStartingOnly = "starting_only"
case Language = "language"
static let allValues = [InstructionBeginning, InstructionMiddle, InstructionEnd, InstructionStartingOnly, Language]
}
// MARK: - Initializers
/**
Initialize a `WAYInstructionSet` from an xml element.
- parameter xmlElement: `AEXMLElement` representing the edge. Must be in GraphML format.
- throws: Throws a `WAYError` if the `xmlElement` is not in the correct format.
*/
init(xmlElement: AEXMLElement) throws {
// Temporary storage for the data elements
var tempLanguage: String?
var tempBeginning: String?
var tempMiddle: String?
var tempEnding: String?
var tempStartingOnly: String?
// Parse the data
for dataItem in xmlElement.children {
if let keyAttribute = dataItem.attributes["key"],
let dataItemType = WAYInstructionKeys(rawValue: keyAttribute) {
switch dataItemType {
case .Language:
tempLanguage = dataItem.string
case .InstructionBeginning:
tempBeginning = dataItem.string
case .InstructionMiddle:
tempMiddle = dataItem.string
case .InstructionEnd:
tempEnding = dataItem.string
case .InstructionStartingOnly:
tempStartingOnly = dataItem.string
}
}
}
// Ensure we have found all elements
guard let myLanguage = tempLanguage else {
throw WAYError.invalidInstructionSet
}
// Permanently store the elements
language = myLanguage
beginning = tempBeginning
middle = tempMiddle
ending = tempEnding
startingOnly = tempStartingOnly
// Check to ensure that the `startingOnly` instruction only exists if no other instructions do.
if (beginning != nil || middle != nil || ending != nil) && startingOnly != nil {
throw WAYError.invalidInstructionSet
}
}
init(language: String, beginning: String? = nil, middle: String? = nil, ending: String? = nil, startingOnly: String? = nil) {
self.language = language
self.beginning = beginning
self.middle = middle
self.ending = ending
self.startingOnly = startingOnly
}
// MARK: - Convenience Getters
func allInstructions() -> [String] {
var result = [String]()
if let myBeginning = beginning {
result.append(myBeginning)
}
if let myMiddle = middle {
result.append(myMiddle)
}
if let myEnding = ending {
result.append(myEnding)
}
return result
}
}
| 13b157230ecbcd2622bb64b6a1aa5af4 | 33.718121 | 129 | 0.61589 | false | false | false | false |
BeckWang0912/GesturePasswordKit | refs/heads/master | GesturePasswordKit/GesturePassword/LockView.swift | mit | 1 | //
// LineView.swift
// GesturePasswordKit
//
// Created by Beck.Wang on 2017/5/14.
// Copyright © 2017年 Beck. All rights reserved.
//
import UIKit
class LineView: UIView {
var options:LockOptions?
fileprivate var itemViews = [LockItemView]()
override func draw(_ rect: CGRect) {
if itemViews.isEmpty { return }
guard let context = UIGraphicsGetCurrentContext() else { return }
context.addRect(rect)
itemViews.forEach { context.addEllipse(in: $0.frame) }
// 剪裁
context.clip()
// 新建路径:管理线条
let path = CGMutablePath()
options?.lockLineColor.set()
context.setLineCap(.round)
context.setLineJoin(.round)
context.setLineWidth(1)
var preItemView: LockItemView? = nil
for (inx, itemView) in itemViews.enumerated() {
let directPoint = itemView.center
if options?.lockLineCenterStart == true {
/// 中心开始绘制线条
if inx == 0 {
path.move(to: directPoint)
} else {
path.addLine(to: directPoint)
}
}else {
/// 边缘开始绘制线条
if preItemView != nil {
let result = self.getMovePointToPoint(preItemView: preItemView!, currentItemView: itemView)
path.move(to: result.movePoint)
path.addLine(to: result.addPoint)
}
preItemView = itemView
}
}
context.addPath(path)
context.strokePath()
}
/// special for tuandaiwang
func caculateSide(lenX: Float, lenY: Float, lenZ: Float) -> Float {
var len = lenZ
len = len / sqrtf(powf(lenX, 2.0) + powf(lenY, 2.0))
len = len * lenY
return len
}
/// special for tuandaiwang
func getMovePointToPoint(preItemView: LockItemView, currentItemView: LockItemView) -> (movePoint: CGPoint, addPoint: CGPoint) {
var movePoint = preItemView.center
var addPoint = currentItemView.center
let lenY = self.caculateSide(lenX: fabsf(Float(preItemView.center.x - currentItemView.center.x)),
lenY: fabsf(Float(preItemView.center.y - currentItemView.center.y)),
lenZ: Float((preItemView.bounds.size.width) / 2.0))
let lenX = self.caculateSide(lenX: fabsf(Float(preItemView.center.y - currentItemView.center.y)),
lenY: fabsf(Float(preItemView.center.x - currentItemView.center.x)),
lenZ: Float((preItemView.bounds.size.width) / 2.0))
if preItemView.direct == LockItemViewDirect.right {
movePoint.x += (preItemView.bounds.size.width) / 2.0
addPoint.x -= (currentItemView.bounds.size.width) / 2.0
}
if preItemView.direct == LockItemViewDirect.left {
movePoint.x -= (preItemView.bounds.size.width) / 2.0
addPoint.x += (currentItemView.bounds.size.width) / 2.0
}
if preItemView.direct == LockItemViewDirect.top {
movePoint.y -= (preItemView.bounds.size.width) / 2.0
addPoint.y += (currentItemView.bounds.size.width) / 2.0
}
if preItemView.direct == LockItemViewDirect.bottom {
movePoint.y += (preItemView.bounds.size.width) / 2.0
addPoint.y -= (currentItemView.bounds.size.width) / 2.0
}
if preItemView.direct == LockItemViewDirect.leftTop {
movePoint.x -= CGFloat(lenX)
movePoint.y -= CGFloat(lenY)
addPoint.x += CGFloat(lenX)
addPoint.y += CGFloat(lenY)
}
if preItemView.direct == LockItemViewDirect.rightTop {
movePoint.x += CGFloat(lenX)
movePoint.y -= CGFloat(lenY)
addPoint.x -= CGFloat(lenX)
addPoint.y += CGFloat(lenY)
}
if preItemView.direct == LockItemViewDirect.leftBottom {
movePoint.x -= CGFloat(lenX)
movePoint.y += CGFloat(lenY)
addPoint.x += CGFloat(lenX)
addPoint.y -= CGFloat(lenY)
}
if preItemView.direct == LockItemViewDirect.rightBottom {
movePoint.x += CGFloat(lenX)
movePoint.y += CGFloat(lenY)
addPoint.x -= CGFloat(lenX)
addPoint.y -= CGFloat(lenY)
}
return (movePoint, addPoint)
}
}
class LockView: UIView {
var type: CoreLockType?
var setPasswordHandle: handle?
var confirmPasswordHandle: handle?
var passwordTooShortHandle: handle?
var passwordTwiceDifferentHandle: ((_ password1: String, _ passwordNow: String) -> Void)?
var passwordFirstRightHandle: strHandle?
var setSuccessHandle: strHandle?
var verifyHandle: boolHandle?
var modifyHandle: boolHandle?
var lineView = LineView()
fileprivate var itemViews = [LockItemView]()
fileprivate var passwordContainer = ""
fileprivate var firstPassword = ""
fileprivate var options: LockOptions!
init(frame: CGRect, options: LockOptions) {
super.init(frame: frame)
self.options = options
backgroundColor = options.backgroundColor
for _ in 0 ..< 9 {
let itemView = LockItemView(options: options)
addSubview(itemView)
}
addSubview(lineView)
lineView.options = options
lineView.frame = frame
lineView.isUserInteractionEnabled = false
lineView.backgroundColor = .clear
lineView.itemViews = itemViews
lineView.setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
lineView.itemViews = itemViews
lineView.setNeedsDisplay()
}
override func layoutSubviews() {
super.layoutSubviews()
let itemViewWH = (frame.width - 4 * ITEM_MARGIN) / 3
for (idx, subview) in subviews.enumerated() {
let row = CGFloat(idx % 3)
let col = CGFloat(idx / 3)
let x = ITEM_MARGIN * (row + 1) + row * itemViewWH
let y = ITEM_MARGIN * (col + 1) + col * itemViewWH
let rect = CGRect(x: x, y: y, width: itemViewWH, height: itemViewWH)
subview.tag = idx
subview.frame = rect
}
lineView.frame = CGRect(origin: .zero, size: self.frame.size)
}
override func touchesBegan(_ touches: Set<UITouch>, with _: UIEvent?) {
lockHandle(touches)
handleBack()
}
override func touchesMoved(_ touches: Set<UITouch>, with _: UIEvent?) {
lockHandle(touches)
}
override func touchesEnded(_: Set<UITouch>, with _: UIEvent?) {
gestureEnd()
}
// 电话等打断触摸过程时,会调用这个方法。
override func touchesCancelled(_: Set<UITouch>?, with _: UIEvent?) {
gestureEnd()
}
func gestureEnd() {
if !passwordContainer.isEmpty {
let count = itemViews.count
if count < LockManager.options.passwordMinCount {
if let passwordTooShortHandle = passwordTooShortHandle {
passwordTooShortHandle()
}
delay(0.4, handle: {
self.resetItem()
})
return
}
if type == .set {
setPassword()
} else if type == .verify {
if let verifyHandle = verifyHandle {
let pwdLocal = LockManager.storage.str(forKey: PASSWORD_KEY + options.passwordKeySuffix)
let result = (pwdLocal == passwordContainer)
verifyHandle(result)
}
} else if type == .modify {
let pwdLocal = LockManager.storage.str(forKey: PASSWORD_KEY + options.passwordKeySuffix)
let result = (pwdLocal == passwordContainer)
if let modifyHandle = modifyHandle {
modifyHandle(result)
}
}
}
resetItem()
}
func handleBack() {
if type == .set {
if firstPassword.isEmpty {
if let setPasswordHandle = setPasswordHandle {
setPasswordHandle()
}
} else {
if let confirmPasswordHandle = confirmPasswordHandle {
confirmPasswordHandle()
}
}
} else if type == .verify {
// if let verifyPasswordHandle = verifyPasswordHandle {
// verifyPasswordHandle()
// }
} else if type == .modify {
// if let modifyPasswordHandle = modifyPasswordHandle {
// modifyPasswordHandle()
// }
}
}
fileprivate func setPassword() {
if firstPassword.isEmpty {
firstPassword = passwordContainer
if let passwordFirstRightHandle = passwordFirstRightHandle {
passwordFirstRightHandle(firstPassword)
}
} else {
if firstPassword != passwordContainer {
firstPassword = ""
passwordContainer = ""
if let passwordTwiceDifferentHandle = passwordTwiceDifferentHandle {
passwordTwiceDifferentHandle(firstPassword, passwordContainer)
}
} else {
if let setSuccessHandle = setSuccessHandle {
setSuccessHandle(firstPassword)
}
}
}
}
func lockHandle(_ touches: Set<UITouch>) {
let location = touches.first!.location(in: self)
if let itemView = itemView(with: location) {
if itemViews.contains(itemView) {
return
}
itemViews.append(itemView)
passwordContainer += itemView.tag.description
calDirect()
itemView.selected = true
setNeedsDisplay()
}
}
func calDirect() {
let count = itemViews.count
if itemViews.count > 1 {
let last_1_ItemView = itemViews.last
let last_2_ItemView = itemViews[count - 2]
let last_1_x = last_1_ItemView!.frame.minX
let last_1_y = last_1_ItemView!.frame.minY
let last_2_x = last_2_ItemView.frame.minX
let last_2_y = last_2_ItemView.frame.minY
if last_2_x == last_1_x && last_2_y > last_1_y {
last_2_ItemView.direct = .top
}
if last_2_y == last_1_y && last_2_x > last_1_x {
last_2_ItemView.direct = .left
}
if last_2_x == last_1_x && last_2_y < last_1_y {
last_2_ItemView.direct = .bottom
}
if last_2_y == last_1_y && last_2_x < last_1_x {
last_2_ItemView.direct = .right
}
if last_2_x > last_1_x && last_2_y > last_1_y {
last_2_ItemView.direct = .leftTop
}
if last_2_x < last_1_x && last_2_y > last_1_y {
last_2_ItemView.direct = .rightTop
}
if last_2_x > last_1_x && last_2_y < last_1_y {
last_2_ItemView.direct = .leftBottom
}
if last_2_x < last_1_x && last_2_y < last_1_y {
last_2_ItemView.direct = .rightBottom
}
}
}
func itemView(with touchLocation: CGPoint) -> LockItemView? {
var item: LockItemView?
for subView in subviews {
if let itemView = (subView as? LockItemView) {
if !itemView.frame.contains(touchLocation) {
continue
}
item = itemView
break
}
}
return item
}
func resetPassword() {
firstPassword = ""
}
fileprivate func resetItem() {
for item in itemViews {
item.selected = false
item.direct = nil
}
itemViews.removeAll()
setNeedsDisplay()
passwordContainer = ""
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 3328bfd25972fad88b3941edde5f80e5 | 33.644628 | 131 | 0.528149 | false | false | false | false |
wikimedia/wikipedia-ios | refs/heads/main | Wikipedia/Code/InsetLabelView.swift | mit | 1 | import UIKit
/// A `UILabel` embedded within a `UIView` to allow easier styling
class InsetLabelView: SetupView {
// MARK: - Properties
let label: UILabel = UILabel()
var insets: NSDirectionalEdgeInsets = .zero {
didSet {
labelLeadingAnchor?.constant = insets.leading
labelTrailingAnchor?.constant = insets.trailing
labelTopAnchor?.constant = insets.top
labelBottomAnchor?.constant = insets.bottom
}
}
fileprivate var labelLeadingAnchor: NSLayoutConstraint?
fileprivate var labelTrailingAnchor: NSLayoutConstraint?
fileprivate var labelTopAnchor: NSLayoutConstraint?
fileprivate var labelBottomAnchor: NSLayoutConstraint?
// MARK: - Setup
override func setup() {
label.translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
labelLeadingAnchor = label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: insets.leading)
labelTrailingAnchor = label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: insets.trailing)
labelTopAnchor = label.topAnchor.constraint(equalTo: topAnchor, constant: insets.top)
labelBottomAnchor = label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: insets.bottom)
NSLayoutConstraint.activate(
[labelLeadingAnchor, labelTrailingAnchor, labelTopAnchor, labelBottomAnchor].compactMap { $0 }
)
}
}
| 638528f70906e92cce6d579ea3e3398b | 31.097561 | 107 | 0.789514 | false | false | false | false |
Antidote-for-Tox/Antidote | refs/heads/develop | Antidote/TextViewController.swift | mpl-2.0 | 1 | // 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 SnapKit
private struct Constants {
static let Offset = 10.0
static let TitleColorKey = "TITLE_COLOR"
static let TextColorKey = "TEXT_COLOR"
}
class TextViewController: UIViewController {
fileprivate let resourceName: String
fileprivate let backgroundColor: UIColor
fileprivate let titleColor: UIColor
fileprivate let textColor: UIColor
fileprivate var textView: UITextView!
init(resourceName: String, backgroundColor: UIColor, titleColor: UIColor, textColor: UIColor) {
self.resourceName = resourceName
self.backgroundColor = backgroundColor
self.titleColor = titleColor
self.textColor = textColor
super.init(nibName: nil, bundle: nil)
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
loadViewWithBackgroundColor(backgroundColor)
createTextView()
installConstraints()
loadHtml()
}
}
private extension TextViewController {
func createTextView() {
textView = UITextView()
textView.isEditable = false
textView.backgroundColor = .clear
view.addSubview(textView)
}
func installConstraints() {
textView.snp.makeConstraints {
$0.leading.top.equalTo(view).offset(Constants.Offset)
$0.trailing.bottom.equalTo(view).offset(-Constants.Offset)
}
}
func loadHtml() {
do {
struct FakeError: Error {}
guard let htmlFilePath = Bundle.main.path(forResource: resourceName, ofType: "html") else {
throw FakeError()
}
var htmlString = try NSString(contentsOfFile: htmlFilePath, encoding: String.Encoding.utf8.rawValue)
htmlString = htmlString.replacingOccurrences(of: Constants.TitleColorKey, with: titleColor.hexString()) as NSString
htmlString = htmlString.replacingOccurrences(of: Constants.TextColorKey, with: textColor.hexString()) as NSString
guard let data = htmlString.data(using: String.Encoding.unicode.rawValue) else {
throw FakeError()
}
let options = [ NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html ]
try textView.attributedText = NSAttributedString(data: data, options: options, documentAttributes: nil)
}
catch {
handleErrorWithType(.cannotLoadHTML)
}
}
}
| 4cd5e3a8eb33a879ff70daedfa85d389 | 32.597561 | 127 | 0.669691 | false | false | false | false |
dche/GLMath | refs/heads/master | Sources/Int.swift | mit | 1 | //
// GLMath - Int.swift
//
// Integer scalars and vectors.
//
// Copyright (c) 2017 The GLMath authors.
// Licensed under MIT License.
public protocol BaseInt: BaseNumber, FixedWidthInteger {
init (_ i: UInt)
}
extension Int32: BaseInt, GenericSignedNumber {
public static let zero: Int32 = 0
public static let one: Int32 = 1
// SWIFT EVOLUTION: `Int32::signum()` might be changed to a property.
public var signum: Int32 {
return self.signum()
}
}
extension UInt32: BaseInt {
public static let zero: UInt32 = 0
public static let one: UInt32 = 1
public var nextPowerOf2: UInt32 {
var v = self - 1
v |= self >> 1
v |= self >> 2
v |= self >> 3
v |= self >> 8
v |= self >> 16
return v + 1
}
}
public protocol IntVector: NumericVector where Component: BaseInt {}
| 33aaae243191a5822d5479b05f73c329 | 20.775 | 73 | 0.6062 | false | false | false | false |
LoopKit/LoopKit | refs/heads/dev | LoopKitUI/Views/ScheduleItemView.swift | mit | 1 | //
// ScheduleItemView.swift
// LoopKitUI
//
// Created by Michael Pangburn on 4/24/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import SwiftUI
struct ScheduleItemView<ValueContent: View, ExpandedContent: View>: View {
var time: TimeInterval
@Binding var isEditing: Bool
var valueContent: ValueContent
var expandedContent: ExpandedContent
private let fixedMidnight = Calendar.current.startOfDay(for: Date(timeIntervalSinceReferenceDate: 0))
init(
time: TimeInterval,
isEditing: Binding<Bool>,
@ViewBuilder valueContent: () -> ValueContent,
@ViewBuilder expandedContent: () -> ExpandedContent
) {
self.time = time
self._isEditing = isEditing
self.valueContent = valueContent()
self.expandedContent = expandedContent()
}
var body: some View {
ExpandableSetting(
isEditing: $isEditing,
leadingValueContent: { timeText },
trailingValueContent: { valueContent },
expandedContent: { self.expandedContent }
)
}
private var timeText: Text {
let dayAtTime = fixedMidnight.addingTimeInterval(time)
return Text(DateFormatter.localizedString(from: dayAtTime, dateStyle: .none, timeStyle: .short))
.foregroundColor(isEditing ? .accentColor : Color(.label))
}
}
extension AnyTransition {
static let fadeInFromTop = move(edge: .top).combined(with: .opacity)
.delayingInsertion(by: 0.1)
.speedingUpRemoval(by: 1.8)
func delayingInsertion(by delay: TimeInterval) -> AnyTransition {
.asymmetric(insertion: animation(Animation.default.delay(delay)), removal: self)
}
func speedingUpRemoval(by factor: Double) -> AnyTransition {
.asymmetric(insertion: self, removal: animation(Animation.default.speed(factor)))
}
}
| c61f6eeb09420be3d323d26fc1985b2f | 30.416667 | 105 | 0.669496 | false | false | false | false |
FlyKite/AwesomeAnimationsDemo | refs/heads/master | AwesomeAnimationsDemo/AwesomeAnimationsDemo/ViewController.swift | gpl-3.0 | 1 | //
// ViewController.swift
// AwesomeAnimationsDemo
//
// Created by 风筝 on 2017/7/14.
// Copyright © 2017年 Doge Studio. All rights reserved.
//
import UIKit
enum AnimationType: String {
case unlimitedTriangle = "Unlimited Triangle"
case playAndPause = "Play and Pause"
case menuAndClose = "Menu and Close"
case hamburgerMenu = "Hamburger Menu"
case waves = "Waves"
case like = "Like"
}
class ViewController: UIViewController {
let animationNames: [AnimationType] = [.unlimitedTriangle, .playAndPause, .menuAndClose, .hamburgerMenu, .waves, .like]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = "Awesome Animations"
let tableView = UITableView(frame: self.view.bounds, style: .plain)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = 50
self.view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return animationNames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell!
if let c = tableView.dequeueReusableCell(withIdentifier: "cell") {
cell = c
} else {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
cell.textLabel?.text = animationNames[indexPath.row].rawValue
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let controller = AnimationViewController()
controller.animationType = animationNames[indexPath.row]
self.navigationController?.pushViewController(controller, animated: true)
}
}
| f82e9ad2c63d73dc897076a076554cd0 | 30.694444 | 123 | 0.668273 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | refs/heads/master | Foundation/NSFileHandle.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
open class FileHandle : NSObject, NSSecureCoding {
internal var _fd: Int32
internal var _closeOnDealloc: Bool
internal var _closed: Bool = false
open var availableData: Data {
return _readDataOfLength(Int.max, untilEOF: false)
}
open func readDataToEndOfFile() -> Data {
return readData(ofLength: Int.max)
}
open func readData(ofLength length: Int) -> Data {
return _readDataOfLength(length, untilEOF: true)
}
internal func _readDataOfLength(_ length: Int, untilEOF: Bool) -> Data {
var statbuf = stat()
var dynamicBuffer: UnsafeMutableRawPointer? = nil
var total = 0
if _closed || fstat(_fd, &statbuf) < 0 {
fatalError("Unable to read file")
}
if statbuf.st_mode & S_IFMT != S_IFREG {
/* We get here on sockets, character special files, FIFOs ... */
var currentAllocationSize: size_t = 1024 * 8
dynamicBuffer = malloc(currentAllocationSize)
var remaining = length
while remaining > 0 {
let amountToRead = min(1024 * 8, remaining)
// Make sure there is always at least amountToRead bytes available in the buffer.
if (currentAllocationSize - total) < amountToRead {
currentAllocationSize *= 2
dynamicBuffer = _CFReallocf(dynamicBuffer!, currentAllocationSize)
if dynamicBuffer == nil {
fatalError("unable to allocate backing buffer")
}
}
let amtRead = read(_fd, dynamicBuffer!.advanced(by: total), amountToRead)
if 0 > amtRead {
free(dynamicBuffer)
fatalError("read failure")
}
if 0 == amtRead {
break // EOF
}
total += amtRead
remaining -= amtRead
if total == length || !untilEOF {
break // We read everything the client asked for.
}
}
} else {
let offset = lseek(_fd, 0, SEEK_CUR)
if offset < 0 {
fatalError("Unable to fetch current file offset")
}
if off_t(statbuf.st_size) > offset {
var remaining = size_t(statbuf.st_size - offset)
remaining = min(remaining, size_t(length))
dynamicBuffer = malloc(remaining)
if dynamicBuffer == nil {
fatalError("Malloc failure")
}
while remaining > 0 {
let count = read(_fd, dynamicBuffer!.advanced(by: total), remaining)
if count < 0 {
free(dynamicBuffer)
fatalError("Unable to read from fd")
}
if count == 0 {
break
}
total += count
remaining -= count
}
}
}
if length == Int.max && total > 0 {
dynamicBuffer = _CFReallocf(dynamicBuffer!, total)
}
if (0 == total) {
free(dynamicBuffer)
}
if total > 0 {
let bytePtr = dynamicBuffer!.bindMemory(to: UInt8.self, capacity: total)
return Data(bytesNoCopy: bytePtr, count: total, deallocator: .none)
}
return Data()
}
open func write(_ data: Data) {
data.enumerateBytes() { (bytes, range, stop) in
do {
try NSData.write(toFileDescriptor: self._fd, path: nil, buf: UnsafeRawPointer(bytes.baseAddress!), length: bytes.count)
} catch {
fatalError("Write failure")
}
}
}
// TODO: Error handling.
open var offsetInFile: UInt64 {
return UInt64(lseek(_fd, 0, SEEK_CUR))
}
open func seekToEndOfFile() -> UInt64 {
return UInt64(lseek(_fd, 0, SEEK_END))
}
open func seek(toFileOffset offset: UInt64) {
lseek(_fd, off_t(offset), SEEK_SET)
}
open func truncateFile(atOffset offset: UInt64) {
if lseek(_fd, off_t(offset), SEEK_SET) == 0 {
ftruncate(_fd, off_t(offset))
}
}
open func synchronizeFile() {
fsync(_fd)
}
open func closeFile() {
if !_closed {
close(_fd)
_closed = true
}
}
public init(fileDescriptor fd: Int32, closeOnDealloc closeopt: Bool) {
_fd = fd
_closeOnDealloc = closeopt
}
internal init?(path: String, flags: Int32, createMode: Int) {
_fd = _CFOpenFileWithMode(path, flags, mode_t(createMode))
_closeOnDealloc = true
super.init()
if _fd < 0 {
return nil
}
}
deinit {
if _fd >= 0 && _closeOnDealloc && !_closed {
close(_fd)
}
}
public required init?(coder: NSCoder) {
NSUnimplemented()
}
open func encode(with aCoder: NSCoder) {
NSUnimplemented()
}
public static var supportsSecureCoding: Bool {
return true
}
}
extension FileHandle {
internal static var _stdinFileHandle: FileHandle = {
return FileHandle(fileDescriptor: STDIN_FILENO, closeOnDealloc: false)
}()
open class var standardInput: FileHandle {
return _stdinFileHandle
}
internal static var _stdoutFileHandle: FileHandle = {
return FileHandle(fileDescriptor: STDOUT_FILENO, closeOnDealloc: false)
}()
open class var standardOutput: FileHandle {
return _stdoutFileHandle
}
internal static var _stderrFileHandle: FileHandle = {
return FileHandle(fileDescriptor: STDERR_FILENO, closeOnDealloc: false)
}()
open class var standardError: FileHandle {
return _stderrFileHandle
}
open class var nullDevice: FileHandle {
NSUnimplemented()
}
public convenience init?(forReadingAtPath path: String) {
self.init(path: path, flags: O_RDONLY, createMode: 0)
}
public convenience init?(forWritingAtPath path: String) {
self.init(path: path, flags: O_WRONLY, createMode: 0)
}
public convenience init?(forUpdatingAtPath path: String) {
self.init(path: path, flags: O_RDWR, createMode: 0)
}
internal static func _openFileDescriptorForURL(_ url : URL, flags: Int32, reading: Bool) throws -> Int32 {
let path = url.path
let fd = _CFOpenFile(path, flags)
if fd < 0 {
throw _NSErrorWithErrno(errno, reading: reading, url: url)
}
return fd
}
public convenience init(forReadingFrom url: URL) throws {
let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_RDONLY, reading: true)
self.init(fileDescriptor: fd, closeOnDealloc: true)
}
public convenience init(forWritingTo url: URL) throws {
let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_WRONLY, reading: false)
self.init(fileDescriptor: fd, closeOnDealloc: true)
}
public convenience init(forUpdating url: URL) throws {
let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_RDWR, reading: false)
self.init(fileDescriptor: fd, closeOnDealloc: true)
}
}
extension NSExceptionName {
public static let fileHandleOperationException = "" // NSUnimplemented
}
extension Notification.Name {
public static let NSFileHandleReadToEndOfFileCompletion = Notification.Name(rawValue: "") // NSUnimplemented
public static let NSFileHandleConnectionAccepted = Notification.Name(rawValue: "") // NSUnimplemented
public static let NSFileHandleDataAvailable = Notification.Name(rawValue: "") // NSUnimplemented
public static let NSFileHandleReadCompletion = Notification.Name(rawValue: "") // NSUnimplemented
}
public let NSFileHandleNotificationDataItem: String = "" // NSUnimplemented
public let NSFileHandleNotificationFileHandleItem: String = "" // NSUnimplemented
extension FileHandle {
open func readInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func readInBackgroundAndNotify() {
NSUnimplemented()
}
open func readToEndOfFileInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func readToEndOfFileInBackgroundAndNotify() {
NSUnimplemented()
}
open func acceptConnectionInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func acceptConnectionInBackgroundAndNotify() {
NSUnimplemented()
}
open func waitForDataInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func waitForDataInBackgroundAndNotify() {
NSUnimplemented()
}
open var readabilityHandler: ((FileHandle) -> Void)? {
NSUnimplemented()
}
open var writeabilityHandler: ((FileHandle) -> Void)? {
NSUnimplemented()
}
}
extension FileHandle {
public convenience init(fileDescriptor fd: Int32) {
self.init(fileDescriptor: fd, closeOnDealloc: false)
}
open var fileDescriptor: Int32 {
return _fd
}
}
open class Pipe: NSObject {
private let readHandle: FileHandle
private let writeHandle: FileHandle
public override init() {
/// the `pipe` system call creates two `fd` in a malloc'ed area
var fds = UnsafeMutablePointer<Int32>.allocate(capacity: 2)
defer {
free(fds)
}
/// If the operating system prevents us from creating file handles, stop
guard pipe(fds) == 0 else { fatalError("Could not open pipe file handles") }
/// The handles below auto-close when the `NSFileHandle` is deallocated, so we
/// don't need to add a `deinit` to this class
/// Create the read handle from the first fd in `fds`
self.readHandle = FileHandle(fileDescriptor: fds.pointee, closeOnDealloc: true)
/// Advance `fds` by one to create the write handle from the second fd
self.writeHandle = FileHandle(fileDescriptor: fds.successor().pointee, closeOnDealloc: true)
super.init()
}
open var fileHandleForReading: FileHandle {
return self.readHandle
}
open var fileHandleForWriting: FileHandle {
return self.writeHandle
}
}
| 8717e1e947afb5d940c9d99c953e59d6 | 30.560224 | 135 | 0.58516 | false | false | false | false |
MounikaAnkam/Thors-Thursday | refs/heads/master | String Playground.playground/section-1.swift | mit | 1 | // Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var word:NSString = "multiply"
word.substringToIndex(3)
// get iply
word.substringFromIndex(4)
// get MULTIPLY
word.uppercaseString
// get Multiply
word.capitalizedString
// get the characters at Index 0, 2, 4, 6 (use a loop)
for var i = 0; i < word.length; i+=2 {
println(word.characterAtIndex(i))
}
// get the length of word
//
word = "multiply 3 by 12"
word.componentsSeparatedByString(" ")
word = "This is a test"
var result = word.rangeOfString("test")
result.location
word.rangeOfString("test").location
var answer:Int?
answer = nil
// var answer2:Int = nil
answer = 12
if(answer != nil){
answer = answer! + 1
}
// answer2 = answer2 + 1
var anotherAnswer:Int! = 42
anotherAnswer = anotherAnswer + 15
| 76cbd31d5079d9fa184ffd83244ae304 | 12.721311 | 54 | 0.689367 | false | false | false | false |
InLefter/Wea | refs/heads/master | Wea/CustomSearchController.swift | mit | 1 | //
// CustomSearchController.swift
// Wea
//
// Created by Howie on 16/3/17.
// Copyright © 2016年 Howie. All rights reserved.
//
import UIKit
protocol CustomSearchControllerDelegate {
//func didStartSearching()
func didTapOnSearchButton()
func didTapOnCancelButton()
func didChangeSearchText(searchText: String)
}
class CustomSearchController: UISearchController, UISearchBarDelegate {
var customSearchBar: CustomSearchBar!
var customDelegate: CustomSearchControllerDelegate!
init(searchResultsController: UIViewController!, searchBarFrame: CGRect, searchBarFont: UIFont, searchBarTextColor: UIColor, searchBarTintColor: UIColor) {
super.init(searchResultsController: searchResultsController)
configureSearchBar(searchBarFrame, font: searchBarFont, textColor: searchBarTextColor, bgColor: searchBarTintColor)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
//customSearchBar.becomeFirstResponder()
// Do any additional setup after loading the view.
}
func configureSearchBar(frame: CGRect, font: UIFont, textColor: UIColor, bgColor: UIColor) {
customSearchBar = CustomSearchBar(frame: frame, font: font , textColor: textColor)
customSearchBar.barTintColor = bgColor
customSearchBar.tintColor = textColor
customSearchBar.showsBookmarkButton = false
customSearchBar.showsCancelButton = true
customSearchBar.delegate = self
//customSearchBar.resignFirstResponder()
//searchBarTextDidBeginEditing(self.searchBar)
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
customSearchBar.becomeFirstResponder()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
customSearchBar.resignFirstResponder()
customDelegate.didTapOnSearchButton()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
customSearchBar.resignFirstResponder()
customDelegate.didTapOnCancelButton()
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
customDelegate.didChangeSearchText(searchText)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| ab214eb2a2b01251c9d7c4957ea71e04 | 30.989474 | 159 | 0.703521 | false | false | false | false |
cloudinary/cloudinary_ios | refs/heads/master | Cloudinary/Classes/Core/Features/UploadWidget/WidgetViewControllers/CLDWidgetViewController.swift | mit | 1 | //
// CLDWidgetViewController.swift
//
// Copyright (c) 2020 Cloudinary (http://cloudinary.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
internal protocol CLDWidgetViewControllerDelegate: AnyObject {
func widgetViewController(_ controller: CLDWidgetViewController, didFinishEditing editedAssets: [CLDWidgetAssetContainer])
func widgetViewControllerDidCancel(_ controller: CLDWidgetViewController)
}
internal class CLDWidgetViewController: UIViewController {
private(set) var configuration : CLDWidgetConfiguration?
private(set) var assets : [CLDWidgetAssetContainer]
internal weak var delegate : CLDWidgetViewControllerDelegate?
private(set) var topButtonsView : UIView!
private(set) var backButton : UIButton!
private(set) var actionButton : UIButton!
private(set) var containerView : UIView!
private(set) var previewViewController : CLDWidgetPreviewViewController!
private(set) var editViewController : CLDWidgetEditViewController!
private(set) var editIsPresented : Bool
private var currentAspectLockState: CLDWidgetConfiguration.AspectRatioLockState
private lazy var previewActionButtonTitle = NSAttributedString(string: "edit ", withSuffix: CLDImageGenerator.generateImage(from: CropRotateIconInstructions()))
private lazy var editActionButtonLockedTitle = NSAttributedString(string: "Aspect ratio locked ", withSuffix: CLDImageGenerator.generateImage(from: RatioLockedIconInstructions()))
private lazy var editActionButtonUnlockedTitle = NSAttributedString(string: "Aspect ratio unlocked ", withSuffix: CLDImageGenerator.generateImage(from: RatioOpenedIconInstructions()))
private lazy var editActionButtonEmptyTitle = NSAttributedString(string: String())
private lazy var transitionDuration = 0.5
// MARK: - init
internal init(
assets : [CLDWidgetAssetContainer],
configuration: CLDWidgetConfiguration? = nil,
delegate : CLDWidgetViewControllerDelegate? = nil
) {
self.configuration = configuration
self.assets = assets
self.delegate = delegate
self.editIsPresented = false
self.currentAspectLockState = .enabledAndOff
super.init(nibName: nil, bundle: nil)
if let initialAspectLockState = configuration?.initialAspectLockState {
currentAspectLockState = initialAspectLockState
}
previewViewController = CLDWidgetPreviewViewController(assets: assets, delegate: self)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
createUI()
}
}
// MARK: - private methods
private extension CLDWidgetViewController {
func moveToPreviewScreen() {
editIsPresented = false
transition(from: editViewController, to: previewViewController, inView: containerView)
updateActionButton(by: .goToEditScreen)
}
func moveToEditScreen(with image: CLDWidgetAssetContainer) {
editIsPresented = true
editViewController = nil
editViewController = CLDWidgetEditViewController(image: image, configuration: configuration, delegate: self, initialAspectLockState: currentAspectLockState)
transition(from: previewViewController, to: editViewController, inView: containerView)
updateActionButton(by: currentAspectLockState)
}
}
// MARK: - CLDWidgetPreviewDelegate
extension CLDWidgetViewController: CLDWidgetPreviewDelegate {
func widgetPreviewViewController(_ controller: CLDWidgetPreviewViewController, didFinishEditing assets: [CLDWidgetAssetContainer]) {
delegate?.widgetViewController(self, didFinishEditing: assets)
}
func widgetPreviewViewControllerDidCancel(_ controller: CLDWidgetPreviewViewController) {
delegate?.widgetViewControllerDidCancel(self)
}
func widgetPreviewViewController(_ controller: CLDWidgetPreviewViewController, didSelect asset: CLDWidgetAssetContainer) {
changeActionButtonState(by: asset)
}
func changeActionButtonState(by asset: CLDWidgetAssetContainer) {
asset.assetType == .image ? updateActionButton(by: .goToEditScreen) : updateActionButton(by: .goToEditScreenDisabled)
}
}
// MARK: - CLDWidgetEditDelegate
extension CLDWidgetViewController: CLDWidgetEditDelegate {
func widgetEditViewController(_ controller: CLDWidgetEditViewController, didFinishEditing image: CLDWidgetAssetContainer) {
previewViewController.selectedImageEdited(newImage: image)
moveToPreviewScreen()
}
func widgetEditViewControllerDidReset(_ controller: CLDWidgetEditViewController) {
if currentAspectLockState != .disabled {
currentAspectLockState = .enabledAndOff
updateActionButton(by: .enabledAndOff)
}
}
func widgetEditViewControllerDidCancel(_ controller: CLDWidgetEditViewController) {
moveToPreviewScreen()
}
}
// MARK: - child presentation
private extension CLDWidgetViewController {
func transition(from oldViewController: UIViewController, to newViewController: UIViewController, inView containerView: UIView) {
// invoke viewWillAppear()...
newViewController.beginAppearanceTransition(true, animated: true)
oldViewController.beginAppearanceTransition(false, animated: true)
// check if its already self child
if newViewController.parent != self {
addChild(newViewController)
newViewController.didMove(toParent: self)
}
// adding newVC.view to fill containerView
newViewController.view.removeFromSuperview()
containerView.addSubview(newViewController.view)
newViewController.view.cld_addConstraintsToFill(containerView)
// prepare for animation
newViewController.view.alpha = 0
containerView.bringSubviewToFront(newViewController.view)
newViewController.view.layoutIfNeeded()
// animate
UIView.animate(withDuration: transitionDuration, delay: 0, options: [], animations: {
newViewController.view.alpha = 1
oldViewController.view.alpha = 0
}) { (complete) in
newViewController.endAppearanceTransition()
oldViewController.endAppearanceTransition()
oldViewController.view.removeFromSuperview()
}
}
func presentAsChild(_ viewController: UIViewController, inView containerView: UIView) {
viewController.beginAppearanceTransition(true, animated: true)
if viewController.parent != self {
addChild(viewController)
viewController.didMove(toParent: self)
}
viewController.view.removeFromSuperview()
containerView.addSubview(viewController.view)
viewController.view.cld_addConstraintsToFill(containerView)
containerView.bringSubviewToFront(viewController.view)
viewController.view.layoutIfNeeded()
viewController.endAppearanceTransition()
}
}
// MARK: - top buttons
private extension CLDWidgetViewController {
enum ActionButtonState: Int {
case aspectRatioEnabledAndOff
case aspectRatioEnabledAndOn
case aspectRatioDisabled
case goToEditScreen
case goToEditScreenDisabled
}
@objc func actionPressed(_ sender: UIButton) {
if editIsPresented {
toggleAspectRatioLockStates()
editViewController.aspectRatioLockPressed()
}
else {
moveToEditScreen(with: previewViewController.selectedImage())
}
}
@objc func backPressed(_ sender: UIButton) {
if editIsPresented {
moveToPreviewScreen()
}
else {
delegate?.widgetViewControllerDidCancel(self)
}
}
func toggleAspectRatioLockStates() {
currentAspectLockState = currentAspectLockState == .enabledAndOff ? .enabledAndOn : .enabledAndOff
updateActionButton(by: currentAspectLockState)
}
func updateActionButton(by aspectLockState: CLDWidgetConfiguration.AspectRatioLockState) {
switch aspectLockState {
case .enabledAndOff: updateActionButton(by: .aspectRatioEnabledAndOff)
case .enabledAndOn : updateActionButton(by: .aspectRatioEnabledAndOn)
case .disabled : updateActionButton(by: .aspectRatioDisabled)
}
}
func updateActionButton(by actionButtonState: ActionButtonState) {
UIView.transition(with: actionButton, duration: transitionDuration, options: .transitionCrossDissolve, animations: {
switch actionButtonState {
case .aspectRatioEnabledAndOff:
self.actionButton.setAttributedTitle(self.editActionButtonUnlockedTitle, for: .normal)
case .aspectRatioEnabledAndOn:
self.actionButton.setAttributedTitle(self.editActionButtonLockedTitle, for: .normal)
case .aspectRatioDisabled : fallthrough
case .goToEditScreenDisabled:
self.actionButton.setAttributedTitle(self.editActionButtonEmptyTitle, for: .normal)
self.actionButton.isEnabled = false
case .goToEditScreen:
self.setActionButtonToGoToEdit()
}
}, completion: nil)
}
func setActionButtonToGoToEdit() {
self.actionButton.setAttributedTitle(previewActionButtonTitle, for: .normal)
self.actionButton.isEnabled = true
}
}
// MARK: - create UI
private extension CLDWidgetViewController {
var topButtonsViewHeight: CGFloat { return 44 }
var backButtonWidthRatio: CGFloat { return 0.25 }
func createUI() {
view.backgroundColor = .black
createAllSubviews()
addAllSubviews()
addAllConstraints()
presentAsChild(previewViewController, inView: containerView)
}
func createAllSubviews() {
// top buttons view
topButtonsView = UIView(frame: CGRect.zero)
// buttons
let buttonImage = CLDImageGenerator.generateImage(from: BackIconInstructions())
backButton = UIButton(type: .custom)
backButton.setImage(buttonImage, for: .normal)
backButton.contentHorizontalAlignment = .left
backButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0)
backButton.addTarget(self, action: #selector(backPressed), for: .touchUpInside)
actionButton = UIButton(type: .custom)
actionButton.accessibilityIdentifier = "widgetViewControllerActionButton"
changeActionButtonState(by: assets[0])
actionButton.contentHorizontalAlignment = .right
actionButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 15)
actionButton.addTarget(self, action: #selector(actionPressed), for: .touchUpInside)
// container view
containerView = UIView(frame: CGRect.zero)
}
func addAllSubviews() {
view.addSubview(topButtonsView)
topButtonsView.addSubview(backButton)
topButtonsView.addSubview(actionButton)
view.addSubview(containerView)
}
func addAllConstraints() {
topButtonsView.translatesAutoresizingMaskIntoConstraints = false
backButton .translatesAutoresizingMaskIntoConstraints = false
actionButton .translatesAutoresizingMaskIntoConstraints = false
containerView .translatesAutoresizingMaskIntoConstraints = false
// top buttons view
var collectionConstraints = [
NSLayoutConstraint(item: topButtonsView!, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: topButtonsView!, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0),
]
if #available(iOS 11.0, *) {
collectionConstraints.append(topButtonsView!.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0))
} else {
collectionConstraints.append(NSLayoutConstraint(item: topButtonsView!,
attribute: .top , relatedBy: .equal, toItem: topLayoutGuide,
attribute: .bottom, multiplier: 1, constant: 0))
}
collectionConstraints.append(NSLayoutConstraint(item: topButtonsView!,
attribute: .height , relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1, constant: topButtonsViewHeight))
NSLayoutConstraint.activate(collectionConstraints)
// buttons
let backButtonConstraints = [
NSLayoutConstraint(item: backButton!, attribute: .leading, relatedBy: .equal, toItem: topButtonsView, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: backButton!, attribute: .top, relatedBy: .equal, toItem: topButtonsView, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: backButton!, attribute: .bottom, relatedBy: .equal, toItem: topButtonsView, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: backButton!, attribute: .width
, relatedBy: .equal, toItem: topButtonsView, attribute: .width, multiplier: backButtonWidthRatio, constant: 0)
]
NSLayoutConstraint.activate(backButtonConstraints)
backButton.setContentHuggingPriority(.defaultHigh, for: .horizontal)
let actionButtonConstraints = [
NSLayoutConstraint(item: actionButton!, attribute: .trailing, relatedBy: .equal, toItem: topButtonsView, attribute: .trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: actionButton!, attribute: .top, relatedBy: .equal, toItem: topButtonsView, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: actionButton!, attribute: .bottom, relatedBy: .equal, toItem: topButtonsView, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: actionButton!, attribute: .leading, relatedBy: .lessThanOrEqual, toItem: backButton, attribute: .trailing, multiplier: 1, constant: view.frame.width * 0.25),
]
NSLayoutConstraint.activate(actionButtonConstraints)
// container view
var containerViewConstraints = [
NSLayoutConstraint(item: containerView!, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: containerView!, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: containerView!, attribute: .top, relatedBy: .equal, toItem: topButtonsView, attribute: .bottom, multiplier: 1, constant: 0),
]
if #available(iOS 11.0, *) {
containerViewConstraints.append(containerView!.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0))
} else {
containerViewConstraints.append(NSLayoutConstraint(item: containerView!,
attribute: .bottom, relatedBy : .equal, toItem: bottomLayoutGuide,
attribute: .top , multiplier: 1, constant: 0))
}
NSLayoutConstraint.activate(containerViewConstraints)
}
}
// MARK: - extension UIView
extension UIView {
func cld_addConstraintsToFill(_ parentView: UIView) {
translatesAutoresizingMaskIntoConstraints = false
let constraints = [
NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: parentView, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: parentView, attribute: .trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: parentView, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: parentView, attribute: .bottom, multiplier: 1, constant: 0)
]
NSLayoutConstraint.activate(constraints)
}
func cld_addConstraintsToCenter(_ parentView: UIView) {
translatesAutoresizingMaskIntoConstraints = false
let constraints = [
NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 80),
NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 80),
NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: parentView, attribute: .centerX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: parentView, attribute: .centerY, multiplier: 1, constant: 0),
]
NSLayoutConstraint.activate(constraints)
}
}
// MARK: - extension NSAttributedString
private extension NSAttributedString {
convenience init(string: String, color: UIColor = .white, withSuffix image: UIImage? = nil) {
if let image = image {
// Create Attachment
let imageAttachment = NSTextAttachment()
imageAttachment.image = image
// Set bound to reposition
let imageOffsetY: CGFloat = -5.0
imageAttachment.bounds = CGRect(x: 0, y: imageOffsetY, width: image.size.width, height: image.size.height)
// Create string with attachment
let attachmentString = NSAttributedString(attachment: imageAttachment)
// Initialize mutable string
let completeText = NSMutableAttributedString(string: string, attributes: [NSAttributedString.Key.foregroundColor: color])
// Add image to mutable string
completeText.append(attachmentString)
self.init(attributedString: completeText)
}
else {
self.init(string: string)
}
}
}
| 0ac804b5fcb6050ba40604d2c3d32037 | 43.281046 | 194 | 0.66647 | false | false | false | false |
ryanherman/intro | refs/heads/master | intro/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// intro
//
// Created by Ryan Herman on 9/17/15.
// Copyright © 2015 Miller Program. All rights reserved.
//
import UIKit
import SlideMenuControllerSwift
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private func createMenuView() {
// create viewController code...
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController = storyboard.instantiateViewControllerWithIdentifier("MainViewController") as! MainViewController
let leftViewController = storyboard.instantiateViewControllerWithIdentifier("LeftViewController") as! LeftViewController
let rightViewController = storyboard.instantiateViewControllerWithIdentifier("RightViewController") as! RightViewController
let nvc: UINavigationController = UINavigationController(rootViewController: mainViewController)
leftViewController.mainViewController = nvc
let slideMenuController = SlideMenuController(mainViewController:nvc, leftMenuViewController: leftViewController, rightMenuViewController: rightViewController)
self.window?.backgroundColor = UIColor(red: 236.0, green: 238.0, blue: 241.0, alpha: 1.0)
self.window?.rootViewController = slideMenuController
self.window?.makeKeyAndVisible()
}
override init() {
super.init()
Firebase.defaultConfig().persistenceEnabled = true
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.createMenuView()
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:.
}
}
| 886f674678e6157790be22b594705771 | 45.958333 | 285 | 0.743271 | false | false | false | false |
NickAger/elm-slider | refs/heads/master | Modules/OpenSSL/Sources/OpenSSL/IO.swift | mit | 4 | import COpenSSL
import Axis
public enum SSLIOError: Error {
case io(description: String)
case shouldRetry(description: String)
case unsupportedMethod(description: String)
}
public class IO {
public enum Method {
case memory
var method: UnsafeMutablePointer<BIO_METHOD> {
switch self {
case .memory:
return BIO_s_mem()
}
}
}
var bio: UnsafeMutablePointer<BIO>?
public init(method: Method = .memory) throws {
initialize()
bio = BIO_new(method.method)
if bio == nil {
throw SSLIOError.io(description: lastSSLErrorDescription)
}
}
public convenience init(buffer: BufferRepresentable) throws {
try self.init()
_ = try buffer.buffer.bytes.withUnsafeBufferPointer {
try write($0)
}
}
// TODO: crash???
// deinit {
// BIO_free(bio)
// }
public var pending: Int {
return BIO_ctrl_pending(bio)
}
public var shouldRetry: Bool {
return (bio!.pointee.flags & BIO_FLAGS_SHOULD_RETRY) != 0
}
// Make this all or nothing
public func write(_ buffer: UnsafeBufferPointer<UInt8>) throws -> Int {
guard !buffer.isEmpty else {
return 0
}
let bytesWritten = BIO_write(bio, buffer.baseAddress!, Int32(buffer.count))
guard bytesWritten >= 0 else {
if shouldRetry {
throw SSLIOError.shouldRetry(description: lastSSLErrorDescription)
} else {
throw SSLIOError.io(description: lastSSLErrorDescription)
}
}
return Int(bytesWritten)
}
public func read(into: UnsafeMutableBufferPointer<UInt8>) throws -> Int {
guard !into.isEmpty else {
return 0
}
let bytesRead = BIO_read(bio, into.baseAddress!, Int32(into.count))
guard bytesRead >= 0 else {
if shouldRetry {
throw SSLIOError.shouldRetry(description: lastSSLErrorDescription)
} else {
throw SSLIOError.io(description: lastSSLErrorDescription)
}
}
return Int(bytesRead)
}
}
| d57f569f23f1d076b39f5736bf9a1d6a | 22.766667 | 83 | 0.601216 | false | false | false | false |
deuiore/mpv | refs/heads/master | video/out/mac/common.swift | gpl-2.0 | 1 | /*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* mpv 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
import IOKit.pwr_mgt
class Common: NSObject {
var mpv: MPVHelper?
var log: LogHelper
let queue: DispatchQueue = DispatchQueue(label: "io.mpv.queue")
var window: Window?
var view: View?
var titleBar: TitleBar?
var link: CVDisplayLink?
let eventsLock = NSLock()
var events: Int = 0
var lightSensor: io_connect_t = 0
var lastLmu: UInt64 = 0
var lightSensorIOPort: IONotificationPortRef?
var displaySleepAssertion: IOPMAssertionID = IOPMAssertionID(0)
var cursorVisibilityWanted: Bool = true
var title: String = "mpv" {
didSet { if let window = window { window.title = title } }
}
init(_ mpLog: OpaquePointer?) {
log = LogHelper(mpLog)
}
func initMisc(_ vo: UnsafeMutablePointer<vo>) {
guard let mpv = mpv else {
log.sendError("Something went wrong, no MPVHelper was initialized")
exit(1)
}
startDisplayLink(vo)
initLightSensor()
addDisplayReconfigureObserver()
mpv.setMacOptionCallback(macOptsWakeupCallback, context: self)
}
func initApp() {
NSApp.setActivationPolicy(.regular)
setAppIcon()
}
func initWindow(_ vo: UnsafeMutablePointer<vo>) {
let (mpv, targetScreen, wr) = getInitProperties(vo)
guard let view = self.view else {
log.sendError("Something went wrong, no View was initialized")
exit(1)
}
window = Window(contentRect: wr, screen: targetScreen, view: view, common: self)
guard let window = self.window else {
log.sendError("Something went wrong, no Window was initialized")
exit(1)
}
window.setOnTop(Bool(mpv.opts.ontop), Int(mpv.opts.ontop_level))
window.keepAspect = Bool(mpv.opts.keepaspect_window)
window.title = title
window.border = Bool(mpv.opts.border)
titleBar = TitleBar(frame: wr, window: window, common: self)
let minimized = Bool(mpv.opts.window_minimized)
window.isRestorable = false
window.isReleasedWhenClosed = false
window.setMaximized(minimized ? false : Bool(mpv.opts.window_maximized))
window.setMinimized(minimized)
window.makeMain()
window.makeKey()
if !minimized {
window.orderFront(nil)
}
NSApp.activate(ignoringOtherApps: true)
}
func initView(_ vo: UnsafeMutablePointer<vo>, _ layer: CALayer) {
let (_, _, wr) = getInitProperties(vo)
view = View(frame: wr, common: self)
guard let view = self.view else {
log.sendError("Something went wrong, no View was initialized")
exit(1)
}
view.layer = layer
view.wantsLayer = true
view.layerContentsPlacement = .scaleProportionallyToFit
}
func initWindowState() {
if mpv?.opts.fullscreen ?? false {
DispatchQueue.main.async {
self.window?.toggleFullScreen(nil)
}
} else {
window?.isMovableByWindowBackground = true
}
}
func uninitCommon() {
setCursorVisiblility(true)
stopDisplaylink()
uninitLightSensor()
removeDisplayReconfigureObserver()
enableDisplaySleep()
window?.orderOut(nil)
titleBar?.removeFromSuperview()
view?.removeFromSuperview()
}
let linkCallback: CVDisplayLinkOutputCallback = {
(displayLink: CVDisplayLink,
inNow: UnsafePointer<CVTimeStamp>,
inOutputTime: UnsafePointer<CVTimeStamp>,
flagsIn: CVOptionFlags,
flagsOut: UnsafeMutablePointer<CVOptionFlags>,
displayLinkContext: UnsafeMutableRawPointer?) -> CVReturn in
let com = unsafeBitCast(displayLinkContext, to: Common.self)
return com.displayLinkCallback(displayLink, inNow, inOutputTime, flagsIn, flagsOut)
}
func displayLinkCallback(_ displayLink: CVDisplayLink,
_ inNow: UnsafePointer<CVTimeStamp>,
_ inOutputTime: UnsafePointer<CVTimeStamp>,
_ flagsIn: CVOptionFlags,
_ flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn
{
return kCVReturnSuccess
}
func startDisplayLink(_ vo: UnsafeMutablePointer<vo>) {
CVDisplayLinkCreateWithActiveCGDisplays(&link)
guard let opts: mp_vo_opts = mpv?.opts,
let screen = getScreenBy(id: Int(opts.screen_id)) ?? NSScreen.main,
let link = self.link else
{
log.sendWarning("Couldn't start DisplayLink, no MPVHelper, Screen or DisplayLink available")
return
}
CVDisplayLinkSetCurrentCGDisplay(link, screen.displayID)
if #available(macOS 10.12, *) {
CVDisplayLinkSetOutputHandler(link) { link, now, out, inFlags, outFlags -> CVReturn in
return self.displayLinkCallback(link, now, out, inFlags, outFlags)
}
} else {
CVDisplayLinkSetOutputCallback(link, linkCallback, MPVHelper.bridge(obj: self))
}
CVDisplayLinkStart(link)
}
func stopDisplaylink() {
if let link = self.link, CVDisplayLinkIsRunning(link) {
CVDisplayLinkStop(link)
}
}
func updateDisplaylink() {
guard let screen = window?.screen, let link = self.link else {
log.sendWarning("Couldn't update DisplayLink, no Screen or DisplayLink available")
return
}
CVDisplayLinkSetCurrentCGDisplay(link, screen.displayID)
queue.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.flagEvents(VO_EVENT_WIN_STATE)
}
}
func currentFps() -> Double {
if let link = self.link {
var actualFps = CVDisplayLinkGetActualOutputVideoRefreshPeriod(link)
let nominalData = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(link)
if (nominalData.flags & Int32(CVTimeFlags.isIndefinite.rawValue)) < 1 {
let nominalFps = Double(nominalData.timeScale) / Double(nominalData.timeValue)
if actualFps > 0 {
actualFps = 1/actualFps
}
if fabs(actualFps - nominalFps) > 0.1 {
log.sendVerbose("Falling back to nominal display refresh rate: \(nominalFps)")
return nominalFps
} else {
return actualFps
}
}
} else {
log.sendWarning("No DisplayLink available")
}
log.sendWarning("Falling back to standard display refresh rate: 60Hz")
return 60.0
}
func enableDisplaySleep() {
IOPMAssertionRelease(displaySleepAssertion)
displaySleepAssertion = IOPMAssertionID(0)
}
func disableDisplaySleep() {
if displaySleepAssertion != IOPMAssertionID(0) { return }
IOPMAssertionCreateWithName(
kIOPMAssertionTypePreventUserIdleDisplaySleep as CFString,
IOPMAssertionLevel(kIOPMAssertionLevelOn),
"io.mpv.video_playing_back" as CFString,
&displaySleepAssertion)
}
func lmuToLux(_ v: UInt64) -> Int {
// the polinomial approximation for apple lmu value -> lux was empirically
// derived by firefox developers (Apple provides no documentation).
// https://bugzilla.mozilla.org/show_bug.cgi?id=793728
let power_c4: Double = 1 / pow(10, 27)
let power_c3: Double = 1 / pow(10, 19)
let power_c2: Double = 1 / pow(10, 12)
let power_c1: Double = 1 / pow(10, 5)
let lum = Double(v)
let term4: Double = -3.0 * power_c4 * pow(lum, 4.0)
let term3: Double = 2.6 * power_c3 * pow(lum, 3.0)
let term2: Double = -3.4 * power_c2 * pow(lum, 2.0)
let term1: Double = 3.9 * power_c1 * lum
let lux = Int(ceil(term4 + term3 + term2 + term1 - 0.19))
return lux > 0 ? lux : 0
}
var lightSensorCallback: IOServiceInterestCallback = { (ctx, service, messageType, messageArgument) -> Void in
let com = unsafeBitCast(ctx, to: Common.self)
var outputs: UInt32 = 2
var values: [UInt64] = [0, 0]
var kr = IOConnectCallMethod(com.lightSensor, 0, nil, 0, nil, 0, &values, &outputs, nil, nil)
if kr == KERN_SUCCESS {
var mean = (values[0] + values[1]) / 2
if com.lastLmu != mean {
com.lastLmu = mean
com.lightSensorUpdate()
}
}
}
func lightSensorUpdate() {
log.sendWarning("lightSensorUpdate not implemented")
}
func initLightSensor() {
let srv = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleLMUController"))
if srv == IO_OBJECT_NULL {
log.sendVerbose("Can't find an ambient light sensor")
return
}
lightSensorIOPort = IONotificationPortCreate(kIOMasterPortDefault)
IONotificationPortSetDispatchQueue(lightSensorIOPort, queue)
var n = io_object_t()
IOServiceAddInterestNotification(lightSensorIOPort, srv, kIOGeneralInterest, lightSensorCallback, MPVHelper.bridge(obj: self), &n)
let kr = IOServiceOpen(srv, mach_task_self_, 0, &lightSensor)
IOObjectRelease(srv)
if kr != KERN_SUCCESS {
log.sendVerbose("Can't start ambient light sensor connection")
return
}
lightSensorCallback(MPVHelper.bridge(obj: self), 0, 0, nil)
}
func uninitLightSensor() {
if lightSensorIOPort != nil {
IONotificationPortDestroy(lightSensorIOPort)
IOObjectRelease(lightSensor)
}
}
var reconfigureCallback: CGDisplayReconfigurationCallBack = { (display, flags, userInfo) in
if flags.contains(.setModeFlag) {
let com = unsafeBitCast(userInfo, to: Common.self)
let displayID = com.window?.screen?.displayID ?? display
if displayID == display {
com.log.sendVerbose("Detected display mode change, updating screen refresh rate")
com.flagEvents(VO_EVENT_WIN_STATE)
}
}
}
func addDisplayReconfigureObserver() {
CGDisplayRegisterReconfigurationCallback(reconfigureCallback, MPVHelper.bridge(obj: self))
}
func removeDisplayReconfigureObserver() {
CGDisplayRemoveReconfigurationCallback(reconfigureCallback, MPVHelper.bridge(obj: self))
}
func setAppIcon() {
if let app = NSApp as? Application,
ProcessInfo.processInfo.environment["MPVBUNDLE"] != "true"
{
NSApp.applicationIconImage = app.getMPVIcon()
}
}
func updateCursorVisibility() {
setCursorVisiblility(cursorVisibilityWanted)
}
func setCursorVisiblility(_ visible: Bool) {
NSCursor.setHiddenUntilMouseMoves(!visible && (view?.canHideCursor() ?? false))
}
func updateICCProfile() {
log.sendWarning("updateICCProfile not implemented")
}
func getScreenBy(id screenID: Int) -> NSScreen? {
if screenID >= NSScreen.screens.count {
log.sendInfo("Screen ID \(screenID) does not exist, falling back to current device")
return nil
} else if screenID < 0 {
return nil
}
return NSScreen.screens[screenID]
}
func getTargetScreen(forFullscreen fs: Bool) -> NSScreen? {
let screenID = fs ? (mpv?.opts.fsscreen_id ?? 0) : (mpv?.opts.screen_id ?? 0)
return getScreenBy(id: Int(screenID))
}
func getCurrentScreen() -> NSScreen? {
return window != nil ? window?.screen :
getTargetScreen(forFullscreen: false) ??
NSScreen.main
}
func getWindowGeometry(forScreen targetScreen: NSScreen,
videoOut vo: UnsafeMutablePointer<vo>) -> NSRect {
let r = targetScreen.convertRectToBacking(targetScreen.frame)
var screenRC: mp_rect = mp_rect(x0: Int32(0),
y0: Int32(0),
x1: Int32(r.size.width),
y1: Int32(r.size.height))
var geo: vo_win_geometry = vo_win_geometry()
vo_calc_window_geometry2(vo, &screenRC, Double(targetScreen.backingScaleFactor), &geo)
// flip y coordinates
geo.win.y1 = Int32(r.size.height) - geo.win.y1
geo.win.y0 = Int32(r.size.height) - geo.win.y0
let wr = NSMakeRect(CGFloat(geo.win.x0), CGFloat(geo.win.y1),
CGFloat(geo.win.x1 - geo.win.x0),
CGFloat(geo.win.y0 - geo.win.y1))
return targetScreen.convertRectFromBacking(wr)
}
func getInitProperties(_ vo: UnsafeMutablePointer<vo>) -> (MPVHelper, NSScreen, NSRect) {
guard let mpv = mpv else {
log.sendError("Something went wrong, no MPVHelper was initialized")
exit(1)
}
guard let targetScreen = getScreenBy(id: Int(mpv.opts.screen_id)) ?? NSScreen.main else {
log.sendError("Something went wrong, no Screen was found")
exit(1)
}
let wr = getWindowGeometry(forScreen: targetScreen, videoOut: vo)
return (mpv, targetScreen, wr)
}
func flagEvents(_ ev: Int) {
eventsLock.lock()
events |= ev
eventsLock.unlock()
guard let vout = mpv?.vo else {
log.sendWarning("vo nil in flagEvents")
return
}
vo_wakeup(vout)
}
func checkEvents() -> Int {
eventsLock.lock()
let ev = events
events = 0
eventsLock.unlock()
return ev
}
func windowDidEndAnimation() {}
func windowSetToFullScreen() {}
func windowSetToWindow() {}
func windowDidUpdateFrame() {}
func windowDidChangeScreen() {}
func windowDidChangeScreenProfile() {}
func windowDidChangeBackingProperties() {}
func windowWillStartLiveResize() {}
func windowDidEndLiveResize() {}
func windowDidResize() {}
func windowDidChangeOcclusionState() {}
@objc func control(_ vo: UnsafeMutablePointer<vo>,
events: UnsafeMutablePointer<Int32>,
request: UInt32,
data: UnsafeMutableRawPointer) -> Int32
{
guard let mpv = mpv else {
log.sendWarning("Unexpected nil value in Control Callback")
return VO_FALSE
}
switch mp_voctrl(request) {
case VOCTRL_CHECK_EVENTS:
events.pointee |= Int32(checkEvents())
return VO_TRUE
case VOCTRL_VO_OPTS_CHANGED:
var o: UnsafeMutableRawPointer?
while mpv.nextChangedOption(property: &o) {
guard let opt = o else {
log.sendError("No changed options was retrieved")
return VO_TRUE
}
if opt == UnsafeMutableRawPointer(&mpv.optsPtr.pointee.border) {
DispatchQueue.main.async {
self.window?.border = Bool(mpv.opts.border)
}
}
if opt == UnsafeMutableRawPointer(&mpv.optsPtr.pointee.fullscreen) {
DispatchQueue.main.async {
self.window?.toggleFullScreen(nil)
}
}
if opt == UnsafeMutableRawPointer(&mpv.optsPtr.pointee.ontop) ||
opt == UnsafeMutableRawPointer(&mpv.optsPtr.pointee.ontop_level) {
DispatchQueue.main.async {
self.window?.setOnTop(Bool(mpv.opts.ontop), Int(mpv.opts.ontop_level))
}
}
if opt == UnsafeMutableRawPointer(&mpv.optsPtr.pointee.keepaspect_window) {
DispatchQueue.main.async {
self.window?.keepAspect = Bool(mpv.opts.keepaspect_window)
}
}
if opt == UnsafeMutableRawPointer(&mpv.optsPtr.pointee.window_minimized) {
DispatchQueue.main.async {
self.window?.setMinimized(Bool(mpv.opts.window_minimized))
}
}
if opt == UnsafeMutableRawPointer(&mpv.optsPtr.pointee.window_maximized) {
DispatchQueue.main.async {
self.window?.setMaximized(Bool(mpv.opts.window_maximized))
}
}
}
return VO_TRUE
case VOCTRL_GET_DISPLAY_FPS:
let fps = data.assumingMemoryBound(to: CDouble.self)
fps.pointee = currentFps()
return VO_TRUE
case VOCTRL_GET_HIDPI_SCALE:
let scaleFactor = data.assumingMemoryBound(to: CDouble.self)
let screen = getCurrentScreen()
let factor = window?.backingScaleFactor ??
screen?.backingScaleFactor ?? 1.0
scaleFactor.pointee = Double(factor)
return VO_TRUE
case VOCTRL_RESTORE_SCREENSAVER:
enableDisplaySleep()
return VO_TRUE
case VOCTRL_KILL_SCREENSAVER:
disableDisplaySleep()
return VO_TRUE
case VOCTRL_SET_CURSOR_VISIBILITY:
let cursorVisibility = data.assumingMemoryBound(to: CBool.self)
cursorVisibilityWanted = cursorVisibility.pointee
DispatchQueue.main.async {
self.setCursorVisiblility(self.cursorVisibilityWanted)
}
return VO_TRUE
case VOCTRL_GET_ICC_PROFILE:
let screen = getCurrentScreen()
guard var iccData = screen?.colorSpace?.iccProfileData else {
log.sendWarning("No Screen available to retrieve ICC profile")
return VO_TRUE
}
let icc = data.assumingMemoryBound(to: bstr.self)
iccData.withUnsafeMutableBytes { (ptr: UnsafeMutableRawBufferPointer) in
guard let baseAddress = ptr.baseAddress, ptr.count > 0 else { return }
let u8Ptr = baseAddress.assumingMemoryBound(to: UInt8.self)
icc.pointee = bstrdup(nil, bstr(start: u8Ptr, len: ptr.count))
}
return VO_TRUE
case VOCTRL_GET_AMBIENT_LUX:
if lightSensor != 0 {
let lux = data.assumingMemoryBound(to: Int32.self)
lux.pointee = Int32(lmuToLux(lastLmu))
return VO_TRUE;
}
return VO_NOTIMPL
case VOCTRL_GET_UNFS_WINDOW_SIZE:
let sizeData = data.assumingMemoryBound(to: Int32.self)
let size = UnsafeMutableBufferPointer(start: sizeData, count: 2)
var rect = window?.unfsContentFrame ?? NSRect(x: 0, y: 0, width: 1280, height: 720)
if let screen = window?.currentScreen, !Bool(mpv.opts.hidpi_window_scale) {
rect = screen.convertRectToBacking(rect)
}
size[0] = Int32(rect.size.width)
size[1] = Int32(rect.size.height)
return VO_TRUE
case VOCTRL_SET_UNFS_WINDOW_SIZE:
let sizeData = data.assumingMemoryBound(to: Int32.self)
let size = UnsafeBufferPointer(start: sizeData, count: 2)
var rect = NSMakeRect(0, 0, CGFloat(size[0]), CGFloat(size[1]))
DispatchQueue.main.async {
if let screen = self.window?.currentScreen, !Bool(self.mpv?.opts.hidpi_window_scale ?? 1) {
rect = screen.convertRectFromBacking(rect)
}
self.window?.updateSize(rect.size)
}
return VO_TRUE
case VOCTRL_GET_DISPLAY_NAMES:
let dnames = data.assumingMemoryBound(to: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?.self)
var array: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>? = nil
var count: Int32 = 0
let displayName = getCurrentScreen()?.displayName ?? "Unknown"
SWIFT_TARRAY_STRING_APPEND(nil, &array, &count, ta_xstrdup(nil, displayName))
SWIFT_TARRAY_STRING_APPEND(nil, &array, &count, nil)
dnames.pointee = array
return VO_TRUE
case VOCTRL_UPDATE_WINDOW_TITLE:
let titleData = data.assumingMemoryBound(to: Int8.self)
DispatchQueue.main.async {
let title = NSString(utf8String: titleData) as String?
self.title = title ?? "Unknown Title"
}
return VO_TRUE
default:
return VO_NOTIMPL
}
}
let macOptsWakeupCallback: swift_wakeup_cb_fn = { ( ctx ) in
let com = unsafeBitCast(ctx, to: Common.self)
DispatchQueue.main.async {
com.macOptsUpdate()
}
}
func macOptsUpdate() {
guard let mpv = mpv else {
log.sendWarning("Unexpected nil value in mac opts update")
return
}
var o: UnsafeMutableRawPointer?
while mpv.nextChangedMacOption(property: &o) {
guard let opt = o else {
log.sendWarning("Could not retrieve changed mac option")
return
}
switch opt {
case UnsafeMutableRawPointer(&mpv.macOptsPtr.pointee.macos_title_bar_appearance):
titleBar?.set(appearance: Int(mpv.macOpts.macos_title_bar_appearance))
case UnsafeMutableRawPointer(&mpv.macOptsPtr.pointee.macos_title_bar_material):
titleBar?.set(material: Int(mpv.macOpts.macos_title_bar_material))
case UnsafeMutableRawPointer(&mpv.macOptsPtr.pointee.macos_title_bar_color):
titleBar?.set(color: mpv.macOpts.macos_title_bar_color)
default:
break
}
}
}
}
| c4ca003854780fa871306bfbd9782764 | 36.415033 | 138 | 0.587999 | false | false | false | false |
ArthurKK/TextFieldEffects | refs/heads/master | Clubber/TextFieldEffects/JiroTextField.swift | apache-2.0 | 10 | //
// JiroTextField.swift
// TextFieldEffects
//
// Created by Raúl Riera on 24/01/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
@IBDesignable public class JiroTextField: TextFieldEffects {
@IBInspectable public var borderColor: UIColor? {
didSet {
updateBorder()
}
}
@IBInspectable public var placeholderColor: UIColor? {
didSet {
updatePlaceholder()
}
}
override public var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override public var bounds: CGRect {
didSet {
updateBorder()
updatePlaceholder()
}
}
private let borderThickness: CGFloat = 2
private let placeholderInsets = CGPoint(x: 8, y: 8)
private let textFieldInsets = CGPoint(x: 8, y: 12)
private let borderLayer = CALayer()
// MARK: - TextFieldsEffectsProtocol
override public func drawViewsForRect(rect: CGRect) {
let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height))
placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y)
placeholderLabel.font = placeholderFontFromFont(font!)
updateBorder()
updatePlaceholder()
layer.addSublayer(borderLayer)
addSubview(placeholderLabel)
}
private func updateBorder() {
borderLayer.frame = rectForBorder(borderThickness, isFilled: false)
borderLayer.backgroundColor = borderColor?.CGColor
}
private func updatePlaceholder() {
placeholderLabel.text = placeholder
placeholderLabel.textColor = placeholderColor
placeholderLabel.sizeToFit()
layoutPlaceholderInTextRect()
if isFirstResponder() || text!.isNotEmpty {
animateViewsForTextEntry()
}
}
private func placeholderFontFromFont(font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.65)
return smallerFont
}
private func rectForBorder(thickness: CGFloat, isFilled: Bool) -> CGRect {
if isFilled {
return CGRect(origin: CGPoint(x: 0, y: placeholderLabel.frame.origin.y + placeholderLabel.font.lineHeight), size: CGSize(width: CGRectGetWidth(frame), height: CGRectGetHeight(frame)))
} else {
return CGRect(origin: CGPoint(x: 0, y: CGRectGetHeight(frame)-thickness), size: CGSize(width: CGRectGetWidth(frame), height: thickness))
}
}
private func layoutPlaceholderInTextRect() {
if text!.isNotEmpty {
return
}
let textRect = textRectForBounds(bounds)
var originX = textRect.origin.x
switch self.textAlignment {
case .Center:
originX += textRect.size.width/2 - placeholderLabel.bounds.width/2
case .Right:
originX += textRect.size.width - placeholderLabel.bounds.width
default:
break
}
placeholderLabel.frame = CGRect(x: originX, y: textRect.size.height/2,
width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height)
}
override public func animateViewsForTextEntry() {
borderLayer.frame.origin = CGPoint(x: 0, y: font!.lineHeight)
UIView.animateWithDuration(0.2, delay: 0.3, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: .BeginFromCurrentState, animations: ({
self.placeholderLabel.frame.origin = CGPoint(x: self.placeholderInsets.x, y: self.borderLayer.frame.origin.y - self.placeholderLabel.bounds.height)
self.borderLayer.frame = self.rectForBorder(self.borderThickness, isFilled: true)
}), completion:nil)
}
override public func animateViewsForTextDisplay() {
if text!.isEmpty {
UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: .BeginFromCurrentState, animations: ({
self.layoutPlaceholderInTextRect()
self.placeholderLabel.alpha = 1
}), completion: nil)
borderLayer.frame = rectForBorder(borderThickness, isFilled: false)
}
}
// MARK: - Overrides
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
return CGRectOffset(bounds, textFieldInsets.x, textFieldInsets.y)
}
override public func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRectOffset(bounds, textFieldInsets.x, textFieldInsets.y)
}
}
| a6770b4402631a1861d0a90cd7b5d4fc | 33.746377 | 195 | 0.632325 | false | false | false | false |
Andgfaria/MiniGitClient-iOS | refs/heads/master | Brejas/Pods/Nimble/Sources/Nimble/Matchers/BeCloseTo.swift | apache-2.0 | 33 | import Foundation
internal let DefaultDelta = 0.0001
internal func isCloseTo(_ actualValue: NMBDoubleConvertible?,
expectedValue: NMBDoubleConvertible,
delta: Double)
-> PredicateResult {
let errorMessage = "be close to <\(stringify(expectedValue))> (within \(stringify(delta)))"
return PredicateResult(
bool: actualValue != nil &&
abs(actualValue!.doubleValue - expectedValue.doubleValue) < delta,
message: .expectedCustomValueTo(errorMessage, "<\(stringify(actualValue))>")
)
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(_ expectedValue: Double, within delta: Double = DefaultDelta) -> Predicate<Double> {
return Predicate.define { actualExpression in
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta)
}
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(_ expectedValue: NMBDoubleConvertible, within delta: Double = DefaultDelta) -> Predicate<NMBDoubleConvertible> {
return Predicate.define { actualExpression in
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta)
}
}
#if _runtime(_ObjC)
public class NMBObjCBeCloseToMatcher: NSObject, NMBMatcher {
var _expected: NSNumber
var _delta: CDouble
init(expected: NSNumber, within: CDouble) {
_expected = expected
_delta = within
}
public func matches(_ actualExpression: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let matcher = beCloseTo(self._expected, within: self._delta)
return try! matcher.matches(expr, failureMessage: failureMessage)
}
public func doesNotMatch(_ actualExpression: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let matcher = beCloseTo(self._expected, within: self._delta)
return try! matcher.doesNotMatch(expr, failureMessage: failureMessage)
}
public var within: (CDouble) -> NMBObjCBeCloseToMatcher {
return ({ delta in
return NMBObjCBeCloseToMatcher(expected: self._expected, within: delta)
})
}
}
extension NMBObjCMatcher {
public class func beCloseToMatcher(_ expected: NSNumber, within: CDouble) -> NMBObjCBeCloseToMatcher {
return NMBObjCBeCloseToMatcher(expected: expected, within: within)
}
}
#endif
public func beCloseTo(_ expectedValues: [Double], within delta: Double = DefaultDelta) -> Predicate<[Double]> {
let errorMessage = "be close to <\(stringify(expectedValues))> (each within \(stringify(delta)))"
return Predicate.simple(errorMessage) { actualExpression in
if let actual = try actualExpression.evaluate() {
if actual.count != expectedValues.count {
return .doesNotMatch
} else {
for (index, actualItem) in actual.enumerated() {
if fabs(actualItem - expectedValues[index]) > delta {
return .doesNotMatch
}
}
return .matches
}
}
return .doesNotMatch
}
}
// MARK: - Operators
infix operator ≈ : ComparisonPrecedence
public func ≈(lhs: Expectation<[Double]>, rhs: [Double]) {
lhs.to(beCloseTo(rhs))
}
public func ≈(lhs: Expectation<NMBDoubleConvertible>, rhs: NMBDoubleConvertible) {
lhs.to(beCloseTo(rhs))
}
public func ≈(lhs: Expectation<NMBDoubleConvertible>, rhs: (expected: NMBDoubleConvertible, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
public func == (lhs: Expectation<NMBDoubleConvertible>, rhs: (expected: NMBDoubleConvertible, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
// make this higher precedence than exponents so the Doubles either end aren't pulled in
// unexpectantly
precedencegroup PlusMinusOperatorPrecedence {
higherThan: BitwiseShiftPrecedence
}
infix operator ± : PlusMinusOperatorPrecedence
public func ±(lhs: NMBDoubleConvertible, rhs: Double) -> (expected: NMBDoubleConvertible, delta: Double) {
return (expected: lhs, delta: rhs)
}
| 0a357675e0d35e9c316fca29113e5499 | 38.460317 | 143 | 0.679606 | false | false | false | false |
cwwise/CWWeChat | refs/heads/master | CWWeChat/Application/AppDelegate.swift | mit | 2 | //
// AppDelegate.swift
// CWWeChat
//
// Created by chenwei on 16/6/22.
// Copyright © 2016年 chenwei. All rights reserved.
//
import UIKit
import SwiftyBeaver
import UserNotifications
let log = SwiftyBeaver.self
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//设置logger
self.window = UIWindow(frame: UIScreen.main.bounds)
setupController()
self.window?.backgroundColor = UIColor.white
self.window?.makeKeyAndVisible()
setupLogger()
//注册推送信息
registerRemoteNotification()
DispatchQueue.main.async {
if let window = self.window {
let label = FPSLabel(frame: CGRect(x: window.bounds.width - 55 - 8, y: 20, width: 55, height: 20))
label.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
window.addSubview(label)
}
}
return true
}
func setupController() {
// 如果当前已经登录
var account: CWAccount?
do {
account = try CWAccount.userAccount()
} catch {
}
guard let current = account else {
let loginVC = UIStoryboard.welcomeViewController()
self.window?.rootViewController = loginVC
return
}
if current.isLogin {
let tabBarController = CWChatTabBarController()
self.window?.rootViewController = tabBarController
loginChatWithAccount(current)
} else {
let loginVC = UIStoryboard.welcomeViewController()
self.window?.rootViewController = loginVC
}
}
func loginChatWithAccount(_ account: CWAccount) {
let options = CWChatClientOptions(host: "cwwise.com", domain: "cwwise.com")
let chatClient = CWChatClient.share
chatClient.initialize(with: options)
chatClient.loginManager.login(username: account.username,
password: account.password) { (username, error) in
if let username = username {
log.debug("登录成功...\(username)")
}
}
}
func loginSuccess() {
let tabBarController = CWChatTabBarController()
self.window?.rootViewController = tabBarController
}
func loginMap() {
let map = MapShowController()
self.window?.rootViewController = CWChatNavigationController(rootViewController: map)
}
func loginEmoticonSuccess() {
let emoticonController = CWEmoticonListController()
self.window?.rootViewController = CWChatNavigationController(rootViewController: emoticonController)
}
func loginMomentSuccess() {
let momentController = CWMomentController()
self.window?.rootViewController = CWChatNavigationController(rootViewController: momentController)
}
func logoutSuccess() {
let loginVC = UIStoryboard.welcomeViewController()
self.window?.rootViewController = loginVC
}
///设置Log日志
func setupLogger() {
// add log destinations. at least one is needed!
let console = ConsoleDestination() // log to Xcode Console
console.minLevel = .debug // just log .info, .warning & .error
let file = FileDestination() // log to default swiftybeaver.log file
log.addDestination(console)
log.addDestination(file)
}
/// 注册通知
func registerRemoteNotification() {
UIApplication.shared.registerForRemoteNotifications()
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.badge,.alert,.sound]) { (result, error) in
}
} else {
let userSetting = UIUserNotificationSettings(types: [.sound,.alert, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(userSetting)
}
}
}
| 8e8e4239b57e3afb02970faf9f12fdb3 | 32.410853 | 144 | 0.603016 | false | false | false | false |
EMart86/WhitelabelApp | refs/heads/master | Whitelabel/Observable.swift | apache-2.0 | 1 | //
// Observable.swift
// Whitelabel
//
// Created by Martin Eberl on 17.04.17.
// Copyright © 2017 Martin Eberl. All rights reserved.
//
import Foundation
protocol Destroyable {
var identifier: Date { get }
func destroy()
}
func ==(lhs: Destroyable, rhs: Destroyable) -> Bool {
return lhs.identifier == rhs.identifier
}
struct ObserverBlock<T> {
private(set) var object: T?
init(object: T) {
self.object = object
}
}
struct DestroyableObserver<T>: Destroyable {
private var object: Observable<T>
private(set) var block: ObserverBlock<(T) -> Void>?
let identifier = Date()
init(object: Observable<T>, block: ObserverBlock<(T) -> Void>) {
self.object = object
self.block = block
}
func destroy() {
object.destroy(destroyable: self)
}
}
open class Observable<T>: NSObject {
internal var observers = [DestroyableObserver<T>]()
var value: T? {
didSet {
notifyObservers()
}
}
func onValueChanged(closure: @escaping (T) -> Void) -> Destroyable {
let observerBlock = DestroyableObserver<T>(object: self, block: ObserverBlock<(T) -> Void>(object: closure))
observers.append(observerBlock)
return observerBlock
}
internal func destroy(destroyable: Destroyable) {
guard let index = observers.index(where: { return $0 == destroyable } ) else {
return
}
observers.remove(at: index)
}
//MARK: - Private
private func notifyObservers() {
guard let value = value else { return }
observers
.flatMap { return $0.block?.object }
.forEach { $0(value) }
}
}
| 97daca7f11d8d9bbc25852f78a0a081e | 22.835616 | 116 | 0.595402 | false | false | false | false |
sudiptasahoo/IVP-Luncheon | refs/heads/master | IVP Luncheon/SSNetworkHandshake.swift | apache-2.0 | 1 | //
// SSNetworkHandshake.swift
// IVP Luncheon
//
// Created by Sudipta Sahoo on 22/05/17.
// Copyright © 2017 Sudipta Sahoo <[email protected]>. This file is part of Indus Valley Partners interview process. This file can not be copied and/or distributed without the express permission of Sudipta Sahoo. All rights reserved.
//
import UIKit
import Foundation
//This is the Network Interceptor and single point of entry/exit for any network call throughout the app
class SSNetworkHandshake: NSObject {
func getJsonResponse(fromRequest request: URLRequest, success: @escaping (_ data: Data) -> Void, failure:@escaping (_ error: Error)->Void){
print(String(describing: request.url))
let session = URLSession.shared
if(currentReachabilityState != .notReachable){
//Network connectivity present
//This cud have been achieved through AlamofireNetworkActivityIndicator
//But below is my custom implimentation to handle iOS Network Indicator effectively
SSCommonUtilities.addTaskToNetworkQueue()
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
SSCommonUtilities.removeTaskFromNetworkQueue()
if(error == nil) {
success(data!);
} else {
failure(error!);
}
})
task.resume()
} else {
//Network connectivity not present
let userInfo: [String : AnyHashable] =
[
NSLocalizedDescriptionKey : NSLocalizedString("Internet Not Available", value: "", comment: "Please check your network."),
]
let err = NSError(domain: "com.sudipta.apiResponseErrorDomain", code: 400, userInfo: userInfo)
failure(err)
}
}
}
| 7acbb31482521f26c767e9caf75fd189 | 38.04 | 236 | 0.609631 | false | false | false | false |
albertjo/FitbitSwift | refs/heads/master | FitbitSwift/Classes/FitbitUser.swift | mit | 1 | //
// FitbitUser.swift
// FitFilter
//
// Created by Albert Jo on 2/5/16.
// Copyright © 2016 FitFilter. All rights reserved.
//
import SwiftyJSON
public enum Gender : String {
case Female, Male, Na
public init(gender: String) {
switch(gender) {
case "FEMALE": self = .Female
case "MALE": self = .Male
default: self = .Na
}
}
}
public enum WeightUnit {
case Pounds, Metric
}
public class FitbitUser {
// MARK : Properties
public private(set) var json : JSON?
public private(set) var aboutMe : String?
public private(set) var avatar : String?
public private(set) var avatar150 : String?
public private(set) var city : String?
public private(set) var country : String?
public private(set) var dateOfBirth : String?
public private(set) var displayName : String?
public private(set) var distanceUnit : String?
public private(set) var encodedId : String?
public private(set) var foodsLocale : String?
public private(set) var fullName : String?
public private(set) var gender : Gender
public private(set) var glucoseUnit : String?
public private(set) var height : Float?
public private(set) var heightUnit : String?
public private(set) var locale : String?
public private(set) var memberSince : String?
public private(set) var nickname : String?
public private(set) var offsetFromUTCMillis : String?
public private(set) var startDayOfWeek : String?
public private(set) var state : String?
public private(set) var strideLengthRunning : String?
public private(set) var strideLengthWalking : String?
public private(set) var timezone : String?
public private(set) var waterUnit : String?
public private(set) var weight : Float?
public private(set) var weightUnit : String?
public required init(json : JSON) {
self.json = json
self.aboutMe = json["aboutMe"].string
self.avatar = json["avatar"].string
self.avatar150 = json["avatar150"].string
self.city = json["city"].string
self.country = json["country"].string
self.dateOfBirth = json["dateOfBirth"].string
self.displayName = json["displayName"].string
self.distanceUnit = json["distanceUnit"].string
self.encodedId = json["encodedId"].string
self.foodsLocale = json["foodsLocale"].string
self.fullName = json["fullName"].string
self.gender = Gender(gender: json["gender"].string!)
self.glucoseUnit = json["glucoseUnit"].string
self.height = json["height"].float
self.heightUnit = json["heightUnit"].string
self.locale = json["locale"].string
self.memberSince = json["memberSince"].string
self.nickname = json["nickname"].string
self.offsetFromUTCMillis = json["offsetFromUTCMillis"].string
self.startDayOfWeek = json["startDayOfWeek"].string
self.state = json["state"].string
self.strideLengthRunning = json["strideLengthRunning"].string
self.strideLengthWalking = json["strideLengthWalking"].string
self.timezone = json["timezone"].string
self.waterUnit = json["waterUnit"].string
self.weight = json["weight"].float
self.weightUnit = json["weightUnit"].string
}
}
extension FitbitClient {
public func getCurrentUser(completionHandler: (FitbitUser?, NSError?) -> Void ) {
getUser("-", completionHandler: completionHandler)
}
public func getUser(userId : String, completionHandler: (FitbitUser?, NSError?) -> Void ) {
let url = "https://api.fitbit.com/1/user/\(userId)/profile.json"
FitbitClient.sharedClient.URLRequestWithMethod(.GET, url: url, optionalHeaders: nil, parameters: nil) {
(json, error) in
var user : FitbitUser?
if (error == nil) {
user = FitbitUser(json: json!)
}
completionHandler(user, error)
}
}
}
| 7bf80ba925c3d4dd6b19dbb3344435d1 | 35.963303 | 111 | 0.6483 | false | false | false | false |
marksands/SwiftLensLuncheon | refs/heads/lens4 | UserListValueTypes/UserController.swift | mit | 1 | //
// Created by Christopher Trott on 1/14/16.
// Copyright © 2016 twocentstudios. All rights reserved.
//
import Foundation
import ReactiveCocoa
import LoremIpsum
/// UserController is the data source for User objects. The underlying data source could be disk, network, etc.
///
/// In this architecture, Controller objects obscure the data source from the ViewModel layer and provide
/// a consistent interface. Controller objects cannot access members of the View or ViewModel layers.
///
/// UserController is a reference-type because it may implement its own layer of caching.
class UserController {
/// Asynchronous fetch.
func fetchRandomUsersProducer(count: Int = 100) -> SignalProducer<[User], NoError> {
return SignalProducer { observer, disposable in
observer.sendNext(UserController.fetchRandomUsers(count))
observer.sendCompleted()
}
// .delay(2, onScheduler: QueueScheduler()) /// Simulate a network delay.
}
/// Generate the specified number of random User objects.
private static func fetchRandomUsers(count: Int) -> [User] {
return (0..<count).map { i in
let name = LoremIpsum.name()
let avatarURL = NSURL(string: "http://dummyimage.com/96x96/000/fff.jpg&text=\(i)")!
let user = User(name: name, avatarURL: avatarURL)
return user
}
}
}
| 3da98099bbfa5224b22380749a8bce17 | 38.942857 | 111 | 0.680973 | false | false | false | false |
oozyjoo/AZPopMenu | refs/heads/master | AZPopMenu/AZPopMenu.swift | mit | 1 | //
// AZPopMenu.swift
//
// Created by Aaron Zhu on 15/6/4.
// Copyright (c) 2015年 Aaron Zhu All rights reserved.
/******************************************
*作用:
创建一个pop菜单。
*使用方法:
AZPopMenu.show
*方法声明:
class func show(superView:UIView, startPoint: CGPoint, items: [String], colors: [UIColor], selected: (itemSelected: Int) -> Void)
*方法参数:
superView: 父View,请使用ViewController.view,方便计算坐标
startPoint: pop菜单上方的箭头位置,使用superView的坐标
items: 要显示的菜单项
colors: 菜单项前显示的色块
selected: 选中菜单项后调用的闭包
******************************************/
import UIKit
import CoreGraphics
let AZ_SELL_WIDTH : CGFloat = 120 //Cell宽度
let AZ_SELL_HEIGHT: CGFloat = 40 //Cell高度
let AZ_ARROW_WIDTH: CGFloat = 10 //Table上方箭头的宽度
let AZ_ARROW_HEIGHT: CGFloat = 10 //Table上方箭头的高度
let AZ_ARROW_FROM_EDGE: CGFloat = 35 //Table上方箭头距离Table边界的最小距离
let AZ_TABLE_WIDTH = AZ_SELL_WIDTH //Table的宽度(同Cell宽度)
let AZ_TABLE_FROM_EDGE: CGFloat = 10 //Table距离手机边界的最小距离
let AZ_SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width
let AZ_SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height
class SelectCell : UITableViewCell{
var colorView :UIView!
var nameLabel :UILabel!
func setUpItem(item: String, withColor: UIColor){
//构造cell上的内容
colorView = UIView(frame: CGRectMake(18,13,14,14))
colorView.layer.cornerRadius = 2
colorView.layer.masksToBounds = true
self.addSubview(colorView)
nameLabel = UILabel(frame: CGRectMake(42, 15, 100, 10))
nameLabel.backgroundColor = UIColor.clearColor()
nameLabel.textColor = UIColor(red:192/255, green: 193/255, blue: 195/255, alpha: 1.0)
self.addSubview(nameLabel)
self.backgroundColor = UIColor(red: 57/255, green: 60/255, blue: 66/255, alpha: 1.0)
nameLabel.text = item
colorView.backgroundColor = withColor
}
}
class ArrowView: UIView{
var arrowPoint: CGPoint
init(frame: CGRect, arrowPoint: CGPoint) {
//转换箭头的坐标 相对super坐标 -> 本view坐标
self.arrowPoint = arrowPoint
self.arrowPoint.y = 0
self.arrowPoint.x = arrowPoint.x - frame.origin.x
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//画顶部的三角形
override func drawRect(rect: CGRect) {
super.drawRect(rect)
var context = UIGraphicsGetCurrentContext()
CGContextSetRGBFillColor(context, 57/255, 60/255, 66/255, 1.0) //设置填充颜色
var sPoints: [CGPoint] = [arrowPoint,
CGPoint(x: arrowPoint.x-AZ_ARROW_WIDTH/2, y: arrowPoint.y+AZ_ARROW_HEIGHT),
CGPoint(x: arrowPoint.x+AZ_ARROW_WIDTH/2, y: arrowPoint.y+AZ_ARROW_HEIGHT)]
CGContextAddLines(context, sPoints, 3)
CGContextClosePath(context)
CGContextDrawPath(context, kCGPathFill)
}
}
class AZPopMenu: UIView,UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate{
var superView: UIView! //父View,使用ViewController.view,方便计算坐标。
var startPoint: CGPoint = CGPoint(x: 0,y: 0) //箭头位置
var items: [String] = [] //cell中使用字符串
var colors: [UIColor] = [] //cell中使用颜色框
var selected: ((itemSelected: Int) -> Void)? //点击选项后调用的闭包
//第一层,self, 全屏透明view,用于接收tabGuesture手势来关闭自己。
var popViewArrow: ArrowView! //第二层,小View,用来画三角箭头
var popTable: UITableView! //第三层,TableView,显示内容和接收点击事件
var tabGuesture: UITapGestureRecognizer!
class func show(superView:UIView, startPoint: CGPoint, items: [String], colors: [UIColor], selected: (itemSelected: Int) -> Void){
var p = AZPopMenu()
p.showPopMenu(superView, startPoint: startPoint, items: items, colors: colors, selected: selected)
}
init(){
super.init(frame: CGRectMake(0, 0, AZ_SCREEN_WIDTH, AZ_SCREEN_HEIGHT))
self.backgroundColor = UIColor(white: 0.0, alpha: 0.0)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func showPopMenu (superView:UIView, startPoint: CGPoint, items: [String], colors: [UIColor], selected: (itemSelected: Int) -> Void) {
if items.isEmpty {
println("error: items为空。函数结束。")
return
}
if items.count != colors.count {
println("error: items和colors项目数量不同。函数结束。")
return
}
self.superView = superView
self.startPoint = startPoint
self.items = items
self.colors = colors
self.selected = selected
//调整箭头位置, 距离屏幕两边35个点以上
if self.startPoint.x < AZ_ARROW_FROM_EDGE {
self.startPoint.x = AZ_ARROW_FROM_EDGE
}else if self.startPoint.x > (AZ_SCREEN_WIDTH-AZ_ARROW_FROM_EDGE){
self.startPoint.x = AZ_SCREEN_WIDTH-AZ_ARROW_FROM_EDGE
}
//调整popmenu的frame 默认箭头置中, table距离屏幕两边10个点以上。
var width = AZ_TABLE_WIDTH
var height = AZ_ARROW_HEIGHT + AZ_SELL_HEIGHT * CGFloat(items.count) - 1.0 //隐藏掉最后一个像素的白线
var tableX = self.startPoint.x - AZ_SELL_WIDTH/2
if tableX < AZ_TABLE_FROM_EDGE {
tableX = AZ_TABLE_FROM_EDGE
}else if tableX > (AZ_SCREEN_WIDTH-AZ_SELL_WIDTH-AZ_TABLE_FROM_EDGE){
tableX = AZ_SCREEN_WIDTH-AZ_SELL_WIDTH-AZ_TABLE_FROM_EDGE
}
popViewArrow = ArrowView(frame: CGRectMake(tableX, startPoint.y, width, height), arrowPoint: self.startPoint)
popViewArrow.backgroundColor = UIColor.clearColor()
//popViewArrow.backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.3)
//放置table
popTable = UITableView(frame: CGRectMake(0, AZ_ARROW_HEIGHT, width, height-AZ_ARROW_HEIGHT), style: UITableViewStyle.Plain)
popTable.delegate = self
popTable.dataSource = self
popTable.layer.cornerRadius = 5
popTable.layer.masksToBounds = true
popTable.scrollEnabled = false //禁止滚动
popTable.separatorStyle = UITableViewCellSeparatorStyle.None //去掉cell分割线
popViewArrow.addSubview(popTable)
self.addSubview(popViewArrow)
superView.addSubview(self)
//UITapGestureRecognizer! 用于关闭popmenu
tabGuesture = UITapGestureRecognizer(target: self, action: "tabAction:")
tabGuesture.numberOfTapsRequired = 1
tabGuesture.delegate = self
self.addGestureRecognizer(tabGuesture)
//动画打开效果
animationShowPopMenu()
}
func animationShowPopMenu(){
//改变popTable
var done = false
//popTable.alpha = 0.0
var toRect = popTable.frame
popTable.frame = CGRectMake(startPoint.x-popViewArrow.frame.origin.x, 0, 1, 1)
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.popTable.frame = toRect
//self.popTable.alpha = 1.0
}) { (b: Bool) -> Void in
done = true
}
while !done{
NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.01))
}
}
func tabAction(sender: UITapGestureRecognizer){
//关闭本身
self.removeGestureRecognizer(tabGuesture)
self.removeFromSuperview()
self.selected?(itemSelected: -1)
}
//UITableViewDelegate/UITableViewDataSource
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.0
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.0
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return AZ_SELL_HEIGHT
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
let cell = SelectCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
//cell.setUpView(indexPath.row)
cell.setUpItem(items[indexPath.row], withColor: colors[indexPath.row])
return cell;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
tableView.deselectRowAtIndexPath(indexPath, animated: true)
//关闭本身
self.removeGestureRecognizer(tabGuesture)
self.removeFromSuperview()
self.selected?(itemSelected: indexPath.row)
}
//UIGestureRecognizerDelegate 用于过滤tableview
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool{
if touch.view is AZPopMenu {
return true
}else{
return false
}
}
}
| 4f0ff3f9762637d81996a11a89eef393 | 35.962963 | 137 | 0.634269 | false | false | false | false |
tavultesoft/keymanweb | refs/heads/master | ios/engine/KMEI/KeymanEngine/Classes/TextFieldDelegateProxy.swift | apache-2.0 | 1 | //
// TextFieldDelegateProxy.swift
// KeymanEngine
//
// Created by Gabriel Wong on 2017-10-06.
// Copyright © 2017 SIL International. All rights reserved.
//
// Proxies delegate messages for a TextField.
// This allows the TextField to hook into these calls while allowing a developer to still
// use the delegate as normal (albeit with a different name: 'keymanDelegate')
//
// This class is required because at the time of writing, setting a UITextField as it's
// own delegate caused an infinite loop in Apple's code, repeatedly calling the selectionDidChange callback
// See: http://lists.apple.com/archives/cocoa-dev/2010/Feb/msg01391.html
import UIKit
public protocol TextFieldDelegate: UITextFieldDelegate { }
class TextFieldDelegateProxy: NSObject, UITextFieldDelegate {
weak var keymanDelegate: TextFieldDelegate?
private unowned let textField: UITextFieldDelegate
init(_ textField: TextField) {
self.textField = textField
super.init()
}
// MARK: - UITextFieldDelegate
// NOTE: Return values from the TextField hooks are ignored
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
_ = self.textField.textFieldShouldBeginEditing?(textField)
return keymanDelegate?.textFieldShouldBeginEditing?(textField) ?? true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.textField.textFieldDidBeginEditing?(textField)
keymanDelegate?.textFieldDidBeginEditing?(textField)
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
_ = self.textField.textFieldShouldEndEditing?(textField)
return keymanDelegate?.textFieldShouldEndEditing?(textField) ?? true
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.textField.textFieldDidEndEditing?(textField)
keymanDelegate?.textFieldDidEndEditing?(textField)
}
@available(iOS 10.0, *)
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
self.textField.textFieldDidEndEditing?(textField, reason: reason)
keymanDelegate?.textFieldDidEndEditing?(textField, reason: reason)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
_ = self.textField.textField?(textField, shouldChangeCharactersIn: range, replacementString: string)
return keymanDelegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
_ = self.textField.textFieldShouldClear?(textField)
return keymanDelegate?.textFieldShouldClear?(textField) ?? true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
_ = self.textField.textFieldShouldReturn?(textField)
return keymanDelegate?.textFieldShouldReturn?(textField) ?? true
}
}
| 3f6909e94c010e268651f4c571b19141 | 38.534247 | 116 | 0.759529 | false | false | false | false |
PerrchicK/swift-app | refs/heads/master | SomeApp/SomeApp/Utilities/Sharing/SharingTextSource.swift | apache-2.0 | 1 | //
// SharingTextSource.swift
// SomeApp
//
// Created by Perry on 4/14/16.
// Copyright © 2016 PerrchicK. All rights reserved.
//
import UIKit
class SharingTextSource: NSObject, UIActivityItemSource {
// Don’t rely on that so easily, this might change at any version WhatsApp are distributing
let activityTypeWhatsApp = "net.whatsapp.WhatsApp.ShareExtension"
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return ""
}
func activityViewController(_ activityViewController: UIActivityViewController,
itemForActivityType activityType: UIActivityType?) -> Any? {
var shareText = "Yo check this out!"
switch activityType?.rawValue {
case activityTypeWhatsApp?:
shareText = "Whazzzzup? 😝" + shareText
case UIActivityType.message.rawValue?:
shareText += " (I hope your iMessage is on)"
case UIActivityType.mail.rawValue?:
fallthrough // Consider building an HTML body
case UIActivityType.postToFacebook.rawValue?:
fallthrough // Consider taking a sharing URL in facebook
default:
shareText = MainViewController.projectLocationInsideGitHub
}
return shareText
}
func activityViewController(_ activityViewController: UIActivityViewController,
subjectForActivityType activityType: UIActivityType?) -> String {
return "Shared from SomeApp"
}
}
| 768012c030fc004df2636414987eb281 | 35.023256 | 107 | 0.67011 | false | false | false | false |
zambelz48/swift-sample-dependency-injection | refs/heads/master | SampleDI/Core/Reusables/NavigationBar/Entities/NavigationBarImageItem.swift | mit | 1 | //
// NavigationBarImageItem.swift
// My Blue Bird
//
// Created by Nanda Julianda Akbar on 8/23/17.
// Copyright © 2017 Nanda Julianda Akbar. All rights reserved.
//
import Foundation
import UIKit
struct NavigationBarImageItem: NavigationBarItem {
var image: UIImage?
var enabled: Bool
var onTapEvent: (() -> Void)?
init(_ image: UIImage? = nil,
enabled: Bool = true,
onTapEvent: (() -> Void)? = nil) {
self.image = image
self.enabled = enabled
self.onTapEvent = onTapEvent
}
}
| 675c5a6885a557de5b87ad8c83777c29 | 18.111111 | 63 | 0.666667 | false | false | false | false |
Rauleinstein/iSWAD | refs/heads/master | iSWAD/iSWAD/NotificationsDetailViewController.swift | apache-2.0 | 1 | //
// NotificationsDetailViewController.swift
// iSWAD
//
// Created by Raul Alvarez on 16/05/16.
// Copyright © 2016 Raul Alvarez. All rights reserved.
//
import UIKit
import SWXMLHash
class NotificationsDetailViewController: UIViewController {
@IBOutlet var subjectsButton: UIButton!
@IBOutlet var notificationsContent: UITextView!
@IBOutlet var personImage: UIImageView!
@IBOutlet var from: UILabel!
@IBOutlet var subject: UILabel!
@IBOutlet var summary: UILabel!
@IBOutlet var date: UILabel!
@IBOutlet var toolbar: UIToolbar!
var detailItem: AnyObject? {
didSet(detailItem) {
self.configureView()
}
}
func configureView() {
if let detail = self.detailItem {
if self.notificationsContent != nil {
var not = notification()
not = detail as! notification
self.notificationsContent.text = not.content.html2String
self.notificationsContent.font = UIFont(name: "Helvetica", size: 20)
self.from.text = not.from
self.subject.text = not.location
self.date.text = not.date
self.summary.text = not.summary
let url = NSURL(string: not.userPhoto)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let data = NSData(contentsOfURL: url!)
dispatch_async(dispatch_get_main_queue(), {
self.personImage.image = UIImage(data: data!)
});
}
self.title = not.type
if not.type == "Mensaje" {
let answerButton = UIBarButtonItem(title: "Responder", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(NotificationsDetailViewController.onTouchAnswer(_:)))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil);
toolbar.items = [flexibleSpace, flexibleSpace, answerButton]
}
let client = SyedAbsarClient()
let defaults = NSUserDefaults.standardUserDefaults()
let requestReadNotification = MarkNotificationsAsRead()
requestReadNotification.cpWsKey = defaults.stringForKey(Constants.wsKey)
requestReadNotification.cpNotifications = not.id
client.opMarkNotificationsAsRead(requestReadNotification){(error, response2: XMLIndexer?) in
print(response2)
}
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let destinationVC = segue.destinationViewController as! MessagesViewController
destinationVC.contentFromNotification = detailItem
}
override func viewDidLoad() {
super.viewDidLoad()
self.configureView()
}
override func viewDidAppear(animated: Bool) {
}
override func loadView() {
super.loadView()
self.subjectsButton.titleLabel?.font = UIFont.fontAwesomeOfSize(25)
self.subjectsButton.setTitle(String.fontAwesomeIconWithName(.FolderOpen), forState: .Normal)
self.subjectsButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
self.subjectsButton.setTitleColor(UIColor.blueColor(), forState: .Highlighted)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func onTouchAnswer(sender: AnyObject){
performSegueWithIdentifier("showAnswer", sender: nil)
}
@IBAction func onTouchSubjects(sender: AnyObject) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("CoursesView") as! UISplitViewController
vc.minimumPrimaryColumnWidth = 0
vc.maximumPrimaryColumnWidth = 600
vc.preferredPrimaryColumnWidthFraction = 0.6
let navigationController = vc.viewControllers[vc.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = vc.displayModeButtonItem()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window!.rootViewController = vc
}
}
| 1800bc1e249bcfd822d0120e33fe456f | 29.603175 | 180 | 0.747407 | false | false | false | false |
mspvirajpatel/SwiftyBase | refs/heads/master | SwiftyBase/Classes/Controller/SideMenu/SideMenuTransition.swift | mit | 1 | //
// SideMenuTransition.swift
// Pods
//
// Created by MacMini-2 on 30/08/17.
//
//
import UIKit
open class SideMenuTransition: UIPercentDrivenInteractiveTransition {
fileprivate var presenting = false
fileprivate var interactive = false
fileprivate static weak var originalSuperview: UIView?
fileprivate static weak var activeGesture: UIGestureRecognizer?
fileprivate static var switchMenus = false
internal static let singleton = SideMenuTransition()
internal static var presentDirection: UIRectEdge = .left
internal static weak var tapView: UIView? {
didSet {
guard let tapView = tapView else {
return
}
tapView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
let exitPanGesture = UIPanGestureRecognizer()
exitPanGesture.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handleHideMenuPan(_:)))
let exitTapGesture = UITapGestureRecognizer()
exitTapGesture.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handleHideMenuTap(_:)))
tapView.addGestureRecognizer(exitPanGesture)
tapView.addGestureRecognizer(exitTapGesture)
}
}
internal static weak var statusBarView: UIView? {
didSet {
guard let statusBarView = statusBarView else {
return
}
if let menuShrinkBackgroundColor = SideMenuManager.menuAnimationBackgroundColor {
statusBarView.backgroundColor = menuShrinkBackgroundColor
} else {
statusBarView.backgroundColor = UIColor.black
}
statusBarView.isUserInteractionEnabled = false
}
}
// prevent instantiation
fileprivate override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(SideMenuTransition.handleNotification), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SideMenuTransition.handleNotification), name: UIApplication.willChangeStatusBarFrameNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(SideMenuTransition.singleton)
}
fileprivate class var presentingViewControllerForMenu: UIViewController? {
get {
return SideMenuManager.menuLeftNavigationController?.presentingViewController ?? SideMenuManager.menuRightNavigationController?.presentingViewController
}
}
fileprivate class var viewControllerForMenu: UISideMenuNavigationController? {
get {
return SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController
}
}
fileprivate class var visibleViewController: UIViewController? {
get {
return getVisibleViewControllerFromViewController(UIApplication.shared.keyWindow?.rootViewController)
}
}
fileprivate class func getVisibleViewControllerFromViewController(_ viewController: UIViewController?) -> UIViewController? {
if let navigationController = viewController as? UINavigationController {
return getVisibleViewControllerFromViewController(navigationController.visibleViewController)
} else if let tabBarController = viewController as? UITabBarController {
return getVisibleViewControllerFromViewController(tabBarController.selectedViewController)
} else if let presentedViewController = viewController?.presentedViewController {
return getVisibleViewControllerFromViewController(presentedViewController)
}
return viewController
}
@objc internal class func handlePresentMenuLeftScreenEdge(_ edge: UIScreenEdgePanGestureRecognizer) {
SideMenuTransition.presentDirection = .left
handlePresentMenuPan(edge)
}
@objc internal class func handlePresentMenuRightScreenEdge(_ edge: UIScreenEdgePanGestureRecognizer) {
SideMenuTransition.presentDirection = .right
handlePresentMenuPan(edge)
}
@objc internal class func handlePresentMenuPan(_ pan: UIPanGestureRecognizer) {
if activeGesture == nil {
activeGesture = pan
} else if pan != activeGesture {
pan.isEnabled = false
pan.isEnabled = true
return
}
// how much distance have we panned in reference to the parent view?
guard let view = presentingViewControllerForMenu?.view ?? pan.view else {
return
}
let transform = view.transform
view.transform = .identity
let translation = pan.translation(in: pan.view!)
view.transform = transform
// do some math to translate this to a percentage based value
if !singleton.interactive {
if translation.x == 0 {
return // not sure which way the user is swiping yet, so do nothing
}
if !(pan is UIScreenEdgePanGestureRecognizer) {
SideMenuTransition.presentDirection = translation.x > 0 ? .left : .right
}
if let menuViewController = viewControllerForMenu, let visibleViewController = visibleViewController {
singleton.interactive = true
visibleViewController.present(menuViewController, animated: true, completion: nil)
} else {
return
}
}
let direction: CGFloat = SideMenuTransition.presentDirection == .left ? 1 : -1
let distance = translation.x / SideMenuManager.menuWidth
// now lets deal with different states that the gesture recognizer sends
switch (pan.state) {
case .began, .changed:
if pan is UIScreenEdgePanGestureRecognizer {
singleton.update(min(distance * direction, 1))
} else if distance > 0 && SideMenuTransition.presentDirection == .right && SideMenuManager.menuLeftNavigationController != nil {
SideMenuTransition.presentDirection = .left
switchMenus = true
singleton.cancel()
} else if distance < 0 && SideMenuTransition.presentDirection == .left && SideMenuManager.menuRightNavigationController != nil {
SideMenuTransition.presentDirection = .right
switchMenus = true
singleton.cancel()
} else {
singleton.update(min(distance * direction, 1))
}
default:
singleton.interactive = false
view.transform = .identity
let velocity = pan.velocity(in: pan.view!).x * direction
view.transform = transform
if velocity >= 100 || velocity >= -50 && abs(distance) >= 0.5 {
// bug workaround: animation briefly resets after call to finishInteractiveTransition() but before animateTransition completion is called.
if ProcessInfo().operatingSystemVersion.majorVersion == 8 && singleton.percentComplete > 1 - CGFloat.ulpOfOne {
singleton.update(0.9999)
}
singleton.finish()
activeGesture = nil
} else {
singleton.cancel()
activeGesture = nil
}
}
}
@objc internal class func handleHideMenuPan(_ pan: UIPanGestureRecognizer) {
if activeGesture == nil {
activeGesture = pan
} else if pan != activeGesture {
pan.isEnabled = false
pan.isEnabled = true
return
}
let translation = pan.translation(in: pan.view!)
let direction: CGFloat = SideMenuTransition.presentDirection == .left ? -1 : 1
let distance = translation.x / SideMenuManager.menuWidth * direction
switch (pan.state) {
case .began:
singleton.interactive = true
presentingViewControllerForMenu?.dismiss(animated: true, completion: nil)
case .changed:
singleton.update(max(min(distance, 1), 0))
default:
singleton.interactive = false
let velocity = pan.velocity(in: pan.view!).x * direction
if velocity >= 100 || velocity >= -50 && distance >= 0.5 {
// bug workaround: animation briefly resets after call to finishInteractiveTransition() but before animateTransition completion is called.
if ProcessInfo().operatingSystemVersion.majorVersion == 8 && singleton.percentComplete > 1 - CGFloat.ulpOfOne {
singleton.update(0.9999)
}
singleton.finish()
activeGesture = nil
} else {
singleton.cancel()
activeGesture = nil
}
}
}
@objc internal class func handleHideMenuTap(_ tap: UITapGestureRecognizer) {
presentingViewControllerForMenu?.dismiss(animated: true, completion: nil)
}
internal class func hideMenuStart() {
guard let mainViewController = presentingViewControllerForMenu,
let menuView = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController?.view : SideMenuManager.menuRightNavigationController?.view else {
return
}
mainViewController.view.transform = .identity
mainViewController.view.alpha = 1
mainViewController.view.frame.origin.y = 0
menuView.transform = .identity
menuView.frame.origin.y = 0
menuView.frame.size.width = SideMenuManager.menuWidth
menuView.frame.size.height = mainViewController.view.frame.height // in case status bar height changed
var statusBarFrame = UIApplication.shared.statusBarFrame
let statusBarOffset = SideMenuManager.appScreenRect.size.height - mainViewController.view.frame.maxY
// For in-call status bar, height is normally 40, which overlaps view. Instead, calculate height difference
// of view and set height to fill in remaining space.
if statusBarOffset >= CGFloat.ulpOfOne {
statusBarFrame.size.height = statusBarOffset
}
SideMenuTransition.statusBarView?.frame = statusBarFrame
SideMenuTransition.statusBarView?.alpha = 0
switch SideMenuManager.menuPresentMode {
case .viewSlideOut:
menuView.alpha = 1 - SideMenuManager.menuAnimationFadeStrength
menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth
mainViewController.view.frame.origin.x = 0
menuView.transform = CGAffineTransform(scaleX: SideMenuManager.menuAnimationTransformScaleFactor, y: SideMenuManager.menuAnimationTransformScaleFactor)
case .viewSlideInOut:
menuView.alpha = 1
menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? -menuView.frame.width : mainViewController.view.frame.width
mainViewController.view.frame.origin.x = 0
case .menuSlideIn:
menuView.alpha = 1
menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? -menuView.frame.width : mainViewController.view.frame.width
case .menuDissolveIn:
menuView.alpha = 0
menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth
mainViewController.view.frame.origin.x = 0
}
}
internal class func hideMenuComplete() {
guard let mainViewController = presentingViewControllerForMenu,
let menuView = viewControllerForMenu?.view else {
return
}
SideMenuTransition.tapView?.removeFromSuperview()
SideMenuTransition.statusBarView?.removeFromSuperview()
mainViewController.view.motionEffects.removeAll()
mainViewController.view.layer.shadowOpacity = 0
menuView.layer.shadowOpacity = 0
if let topNavigationController = mainViewController as? UINavigationController {
topNavigationController.interactivePopGestureRecognizer!.isEnabled = true
}
if let originalSuperview = originalSuperview {
originalSuperview.addSubview(mainViewController.view)
let y = originalSuperview.bounds.height - mainViewController.view.frame.size.height
mainViewController.view.frame.origin.y = max(y, 0)
}
}
internal class func presentMenuStart() {
guard let menuView = viewControllerForMenu?.view,
let mainViewController = presentingViewControllerForMenu else {
return
}
menuView.alpha = 1
menuView.transform = .identity
menuView.frame.size.width = SideMenuManager.menuWidth
let size = SideMenuManager.appScreenRect.size
menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? 0 : size.width - SideMenuManager.menuWidth
mainViewController.view.transform = .identity
mainViewController.view.frame.size.width = size.width
let statusBarOffset = size.height - menuView.bounds.height
mainViewController.view.bounds.size.height = size.height - max(statusBarOffset, 0)
mainViewController.view.frame.origin.y = 0
var statusBarFrame = UIApplication.shared.statusBarFrame
// For in-call status bar, height is normally 40, which overlaps view. Instead, calculate height difference
// of view and set height to fill in remaining space.
if statusBarOffset >= CGFloat.ulpOfOne {
statusBarFrame.size.height = statusBarOffset
}
SideMenuTransition.tapView?.transform = .identity
SideMenuTransition.tapView?.bounds = mainViewController.view.bounds
SideMenuTransition.statusBarView?.frame = statusBarFrame
SideMenuTransition.statusBarView?.alpha = 1
switch SideMenuManager.menuPresentMode {
case .viewSlideOut, .viewSlideInOut:
mainViewController.view.layer.shadowColor = SideMenuManager.menuShadowColor.cgColor
mainViewController.view.layer.shadowRadius = SideMenuManager.menuShadowRadius
mainViewController.view.layer.shadowOpacity = SideMenuManager.menuShadowOpacity
mainViewController.view.layer.shadowOffset = CGSize(width: 0, height: 0)
let direction: CGFloat = SideMenuTransition.presentDirection == .left ? 1 : -1
mainViewController.view.frame.origin.x = direction * (menuView.frame.width)
case .menuSlideIn, .menuDissolveIn:
if SideMenuManager.menuBlurEffectStyle == nil {
menuView.layer.shadowColor = SideMenuManager.menuShadowColor.cgColor
menuView.layer.shadowRadius = SideMenuManager.menuShadowRadius
menuView.layer.shadowOpacity = SideMenuManager.menuShadowOpacity
menuView.layer.shadowOffset = CGSize(width: 0, height: 0)
}
mainViewController.view.frame.origin.x = 0
}
if SideMenuManager.menuPresentMode != .viewSlideOut {
mainViewController.view.transform = CGAffineTransform(scaleX: SideMenuManager.menuAnimationTransformScaleFactor, y: SideMenuManager.menuAnimationTransformScaleFactor)
if SideMenuManager.menuAnimationTransformScaleFactor > 1 {
SideMenuTransition.tapView?.transform = mainViewController.view.transform
}
mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength
}
}
internal class func presentMenuComplete() {
guard let mainViewController = presentingViewControllerForMenu else {
return
}
switch SideMenuManager.menuPresentMode {
case .menuSlideIn, .menuDissolveIn, .viewSlideInOut:
if SideMenuManager.menuParallaxStrength != 0 {
let horizontal = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
horizontal.minimumRelativeValue = -SideMenuManager.menuParallaxStrength
horizontal.maximumRelativeValue = SideMenuManager.menuParallaxStrength
let vertical = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis)
vertical.minimumRelativeValue = -SideMenuManager.menuParallaxStrength
vertical.maximumRelativeValue = SideMenuManager.menuParallaxStrength
let group = UIMotionEffectGroup()
group.motionEffects = [horizontal, vertical]
mainViewController.view.addMotionEffect(group)
}
case .viewSlideOut: break
}
if let topNavigationController = mainViewController as? UINavigationController {
topNavigationController.interactivePopGestureRecognizer!.isEnabled = false
}
}
@objc internal func handleNotification(notification: NSNotification) {
guard let mainViewController = SideMenuTransition.presentingViewControllerForMenu,
let menuViewController = SideMenuTransition.viewControllerForMenu,
menuViewController.presentedViewController == nil && menuViewController.presentingViewController != nil else {
return
}
if let originalSuperview = SideMenuTransition.originalSuperview {
originalSuperview.addSubview(mainViewController.view)
}
if notification.name == UIApplication.didEnterBackgroundNotification {
SideMenuTransition.hideMenuStart()
SideMenuTransition.hideMenuComplete()
menuViewController.dismiss(animated: false, completion: nil)
return
}
UIView.animate(withDuration: SideMenuManager.menuAnimationDismissDuration,
delay: 0,
usingSpringWithDamping: SideMenuManager.menuAnimationUsingSpringWithDamping,
initialSpringVelocity: SideMenuManager.menuAnimationInitialSpringVelocity,
options: SideMenuManager.menuAnimationOptions,
animations: {
SideMenuTransition.hideMenuStart()
}) { (finished) -> Void in
SideMenuTransition.hideMenuComplete()
menuViewController.dismiss(animated: false, completion: nil)
}
}
}
extension SideMenuTransition: UIViewControllerAnimatedTransitioning {
// animate a change from one viewcontroller to another
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// get reference to our fromView, toView and the container view that we should perform the transition in
let container = transitionContext.containerView
// prevent any other menu gestures from firing
container.isUserInteractionEnabled = false
if let menuBackgroundColor = SideMenuManager.menuAnimationBackgroundColor {
container.backgroundColor = menuBackgroundColor
}
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
// assign references to our menu view controller and the 'bottom' view controller from the tuple
// remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing
let menuViewController = presenting ? toViewController : fromViewController
let topViewController = presenting ? fromViewController : toViewController
let menuView = menuViewController.view!
let topView = topViewController.view!
// prepare menu items to slide in
if presenting {
SideMenuTransition.originalSuperview = topView.superview
// add the both views to our view controller
switch SideMenuManager.menuPresentMode {
case .viewSlideOut, .viewSlideInOut:
container.addSubview(menuView)
container.addSubview(topView)
case .menuSlideIn, .menuDissolveIn:
container.addSubview(topView)
container.addSubview(menuView)
}
if SideMenuManager.menuFadeStatusBar {
let statusBarView = UIView()
SideMenuTransition.statusBarView = statusBarView
container.addSubview(statusBarView)
}
SideMenuTransition.hideMenuStart()
}
let animate = {
if self.presenting {
SideMenuTransition.presentMenuStart()
} else {
SideMenuTransition.hideMenuStart()
}
}
let complete = {
container.isUserInteractionEnabled = true
// tell our transitionContext object that we've finished animating
if transitionContext.transitionWasCancelled {
let viewControllerForPresentedMenu = SideMenuTransition.presentingViewControllerForMenu
if self.presenting {
SideMenuTransition.hideMenuComplete()
} else {
SideMenuTransition.presentMenuComplete()
}
transitionContext.completeTransition(false)
if SideMenuTransition.switchMenus {
SideMenuTransition.switchMenus = false
viewControllerForPresentedMenu?.present(SideMenuTransition.viewControllerForMenu!, animated: true, completion: nil)
}
return
}
if self.presenting {
SideMenuTransition.presentMenuComplete()
transitionContext.completeTransition(true)
switch SideMenuManager.menuPresentMode {
case .viewSlideOut, .viewSlideInOut:
container.addSubview(topView)
case .menuSlideIn, .menuDissolveIn:
container.insertSubview(topView, at: 0)
}
if !SideMenuManager.menuPresentingViewControllerUserInteractionEnabled {
let tapView = UIView()
container.insertSubview(tapView, aboveSubview: topView)
tapView.bounds = container.bounds
tapView.center = topView.center
if SideMenuManager.menuAnimationTransformScaleFactor > 1 {
tapView.transform = topView.transform
}
SideMenuTransition.tapView = tapView
}
if let statusBarView = SideMenuTransition.statusBarView {
container.bringSubviewToFront(statusBarView)
}
return
}
SideMenuTransition.hideMenuComplete()
transitionContext.completeTransition(true)
menuView.removeFromSuperview()
}
// perform the animation!
let duration = transitionDuration(using: transitionContext)
if interactive {
UIView.animate(withDuration: duration,
delay: 0,
options: .curveLinear,
animations: {
animate()
}, completion: { (finished) in
complete()
})
} else {
UIView.animate(withDuration: duration,
delay: 0,
usingSpringWithDamping: SideMenuManager.menuAnimationUsingSpringWithDamping,
initialSpringVelocity: SideMenuManager.menuAnimationInitialSpringVelocity,
options: SideMenuManager.menuAnimationOptions,
animations: {
animate()
}) { (finished) -> Void in
complete()
}
}
}
// return how many seconds the transiton animation will take
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
if interactive {
return SideMenuManager.menuAnimationCompleteGestureDuration
}
return presenting ? SideMenuManager.menuAnimationPresentDuration : SideMenuManager.menuAnimationDismissDuration
}
}
extension SideMenuTransition: UIViewControllerTransitioningDelegate {
// return the animator when presenting a viewcontroller
// rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol
open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
SideMenuTransition.presentDirection = presented == SideMenuManager.menuLeftNavigationController ? .left : .right
return self
}
// return the animator used when dismissing from a viewcontroller
open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
presenting = false
return self
}
open func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
// if our interactive flag is true, return the transition manager object
// otherwise return nil
return interactive ? SideMenuTransition.singleton : nil
}
open func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactive ? SideMenuTransition.singleton : nil
}
}
| 8fa052b863cfcc0b95c183bff095a199 | 44.863636 | 185 | 0.659602 | false | false | false | false |
babedev/Food-Swift | refs/heads/master | Food-Swift-iOS/FoodSwift/FoodSwift/ViewController.swift | unlicense | 1 | //
// ViewController.swift
// FoodSwift
//
// Created by NiM on 3/4/2560 BE.
// Copyright © 2560 tryswift. All rights reserved.
//
import UIKit
import Firebase
import FirebaseFacebookAuthUI
import GeoFire
let kFirebaseTermsOfService = URL(string: "https://firebase.google.com/terms/")!
let kDefaultRadius = 1.0;
class ViewController: UIViewController {
var auth: FIRAuth?;// = FIRAuth.auth()
var authUI: FUIAuth? ;//= FUIAuth.defaultAuthUI()
var handle: FIRAuthStateDidChangeListenerHandle?
var tryLogOut = true;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.auth = FIRAuth.auth();
self.authUI = FUIAuth.defaultAuthUI();
self.authUI?.tosurl = kFirebaseTermsOfService
self.authUI?.isSignInWithEmailHidden = true;
self.authUI?.providers = [FUIFacebookAuth()];
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil);
self.requestLocation();
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
handle = self.auth?.addStateDidChangeListener() { (auth, user) in
print("Login as \(user?.displayName)");
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated);
if self.auth?.currentUser == nil {
self.showLoginView();
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated);
FIRAuth.auth()?.removeStateDidChangeListener(handle!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 35.6942891, 139.7649778
// MARK:
// MARK: New post
@IBAction func addNewPost(_ sender: Any) {
if let currentUser = self.auth?.currentUser {
if let currentLocation = FoodLocation.defaultManager.currentLocation {
let imagePicker = FoodPhoto.imagePickerViewController { (image, error) in
if let selectedImage = image {
if let photoConfirmView = self.storyboard?.instantiateViewController(withIdentifier: "PhotoConfirmViewController") as? PhotoConfirmViewController {
photoConfirmView.image = selectedImage;
photoConfirmView.userID = currentUser.uid;
photoConfirmView.location = currentLocation;
self.navigationController?.pushViewController(photoConfirmView, animated: false);
self.dismiss(animated: true, completion: nil);
}
} else {
self.dismiss(animated: true, completion: nil);
}
};
self.present(imagePicker, animated: true, completion: nil);
}
}
}
// MARK:
// MARK: Authentication
func showLoginView() {
tryLogOut = false;
let controller = self.authUI!.authViewController()
// controller.navigationBar.isHidden = self.customAuthorizationSwitch.isOn
self.present(controller, animated: true, completion: nil)
}
// MARK:
// MARK: Location
func requestLocation() {
FoodLocation.defaultManager.requestLocation { (place) in
print("You are near \(place)");
let geofireRef = FIRDatabase.database().reference().child("location")
let geoFire = GeoFire(firebaseRef: geofireRef)!
if let currentLocation = FoodLocation.defaultManager.currentLocation {
let center = CLLocation(latitude: currentLocation.latitude, longitude: currentLocation.longitude)
let circleQuery = geoFire.query(at: center, withRadius: kDefaultRadius)
circleQuery?.observe(.keyEntered, with: { (key: String?, location: CLLocation?) in
print("\(key) ===== \(location?.coordinate.latitude), \(location?.coordinate.longitude)")
})
}
}
}
}
| 220d2e575feef159e9de865b18063a0e | 34.144 | 171 | 0.593672 | false | false | false | false |
tensorflow/examples | refs/heads/master | lite/examples/object_detection/ios/ObjectDetection/ViewControllers/ViewController.swift | apache-2.0 | 1 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import TensorFlowLiteTaskVision
import UIKit
class ViewController: UIViewController {
// MARK: Storyboards Connections
@IBOutlet weak var previewView: PreviewView!
@IBOutlet weak var overlayView: OverlayView!
@IBOutlet weak var resumeButton: UIButton!
@IBOutlet weak var cameraUnavailableLabel: UILabel!
@IBOutlet weak var bottomSheetStateImageView: UIImageView!
@IBOutlet weak var bottomSheetView: UIView!
@IBOutlet weak var bottomSheetViewBottomSpace: NSLayoutConstraint!
// MARK: Constants
private let displayFont = UIFont.systemFont(ofSize: 14.0, weight: .medium)
private let edgeOffset: CGFloat = 2.0
private let labelOffset: CGFloat = 10.0
private let animationDuration = 0.5
private let collapseTransitionThreshold: CGFloat = -30.0
private let expandTransitionThreshold: CGFloat = 30.0
private let colors = [
UIColor.red,
UIColor(displayP3Red: 90.0 / 255.0, green: 200.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0),
UIColor.green,
UIColor.orange,
UIColor.blue,
UIColor.purple,
UIColor.magenta,
UIColor.yellow,
UIColor.cyan,
UIColor.brown,
]
// MARK: Model config variables
private var threadCount: Int = 1
private var detectionModel: ModelType = ConstantsDefault.modelType
private var scoreThreshold: Float = ConstantsDefault.scoreThreshold
private var maxResults: Int = ConstantsDefault.maxResults
// MARK: Instance Variables
private var initialBottomSpace: CGFloat = 0.0
// Holds the results at any time
private var result: Result?
private let inferenceQueue = DispatchQueue(label: "org.tensorflow.lite.inferencequeue")
private var isInferenceQueueBusy = false
// MARK: Controllers that manage functionality
private lazy var cameraFeedManager = CameraFeedManager(previewView: previewView)
private var objectDetectionHelper: ObjectDetectionHelper? = ObjectDetectionHelper(
modelFileInfo: ConstantsDefault.modelType.modelFileInfo,
threadCount: ConstantsDefault.threadCount,
scoreThreshold: ConstantsDefault.scoreThreshold,
maxResults: ConstantsDefault.maxResults
)
private var inferenceViewController: InferenceViewController?
// MARK: View Handling Methods
override func viewDidLoad() {
super.viewDidLoad()
guard objectDetectionHelper != nil else {
fatalError("Failed to create the ObjectDetectionHelper. See the console for the error.")
}
cameraFeedManager.delegate = self
overlayView.clearsContextBeforeDrawing = true
addPanGesture()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
changeBottomViewState()
cameraFeedManager.checkCameraConfigurationAndStartSession()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
cameraFeedManager.stopSession()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: Button Actions
@IBAction func onClickResumeButton(_ sender: Any) {
cameraFeedManager.resumeInterruptedSession { (complete) in
if complete {
self.resumeButton.isHidden = true
self.cameraUnavailableLabel.isHidden = true
} else {
self.presentUnableToResumeSessionAlert()
}
}
}
func presentUnableToResumeSessionAlert() {
let alert = UIAlertController(
title: "Unable to Resume Session",
message: "There was an error while attempting to resume session.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}
// MARK: Storyboard Segue Handlers
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == "EMBED" {
inferenceViewController = segue.destination as? InferenceViewController
inferenceViewController?.currentThreadCount = threadCount
inferenceViewController?.maxResults = maxResults
inferenceViewController?.scoreThreshold = scoreThreshold
inferenceViewController?.modelSelectIndex =
ModelType.allCases.firstIndex(where: { $0 == detectionModel }) ?? 0
inferenceViewController?.delegate = self
guard let tempResult = result else {
return
}
inferenceViewController?.inferenceTime = tempResult.inferenceTime
}
}
}
// MARK: InferenceViewControllerDelegate Methods
extension ViewController: InferenceViewControllerDelegate {
func viewController(
_ viewController: InferenceViewController,
didReceiveAction action: InferenceViewController.Action
) {
switch action {
case .changeThreadCount(let threadCount):
if self.threadCount == threadCount { return }
self.threadCount = threadCount
case .changeMaxResults(let maxResults):
if self.maxResults == maxResults { return }
self.maxResults = maxResults
case .changeModel(let detectionModel):
if self.detectionModel == detectionModel { return }
self.detectionModel = detectionModel
case .changeScoreThreshold(let scoreThreshold):
if self.scoreThreshold == scoreThreshold { return }
self.scoreThreshold = scoreThreshold
}
inferenceQueue.async {
self.objectDetectionHelper = ObjectDetectionHelper(
modelFileInfo: self.detectionModel.modelFileInfo,
threadCount: self.threadCount,
scoreThreshold: self.scoreThreshold,
maxResults: self.maxResults
)
}
}
}
// MARK: CameraFeedManagerDelegate Methods
extension ViewController: CameraFeedManagerDelegate {
func didOutput(pixelBuffer: CVPixelBuffer) {
// Drop current frame if the previous frame is still being processed.
guard !self.isInferenceQueueBusy else { return }
inferenceQueue.async {
self.isInferenceQueueBusy = true
self.detect(pixelBuffer: pixelBuffer)
self.isInferenceQueueBusy = false
}
}
// MARK: Session Handling Alerts
func sessionRunTimeErrorOccurred() {
// Handles session run time error by updating the UI and providing a button if session can be manually resumed.
self.resumeButton.isHidden = false
}
func sessionWasInterrupted(canResumeManually resumeManually: Bool) {
// Updates the UI when session is interrupted.
if resumeManually {
self.resumeButton.isHidden = false
} else {
self.cameraUnavailableLabel.isHidden = false
}
}
func sessionInterruptionEnded() {
// Updates UI once session interruption has ended.
if !self.cameraUnavailableLabel.isHidden {
self.cameraUnavailableLabel.isHidden = true
}
if !self.resumeButton.isHidden {
self.resumeButton.isHidden = true
}
}
func presentVideoConfigurationErrorAlert() {
let alertController = UIAlertController(
title: "Configuration Failed", message: "Configuration of camera has failed.",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
func presentCameraPermissionsDeniedAlert() {
let alertController = UIAlertController(
title: "Camera Permissions Denied",
message:
"Camera permissions have been denied for this app. You can change this by going to Settings",
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (action) in
UIApplication.shared.open(
URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
}
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
present(alertController, animated: true, completion: nil)
}
/** This method runs the live camera pixelBuffer through tensorFlow to get the result.
*/
func detect(pixelBuffer: CVPixelBuffer) {
result = self.objectDetectionHelper?.detect(frame: pixelBuffer)
guard let displayResult = result else {
return
}
let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)
DispatchQueue.main.async {
// Display results by handing off to the InferenceViewController
self.inferenceViewController?.resolution = CGSize(width: width, height: height)
var inferenceTime: Double = 0
if let resultInferenceTime = self.result?.inferenceTime {
inferenceTime = resultInferenceTime
}
self.inferenceViewController?.inferenceTime = inferenceTime
self.inferenceViewController?.tableView.reloadData()
// Draws the bounding boxes and displays class names and confidence scores.
self.drawAfterPerformingCalculations(
onDetections: displayResult.detections,
withImageSize: CGSize(width: CGFloat(width), height: CGFloat(height)))
}
}
/**
This method takes the results, translates the bounding box rects to the current view, draws the bounding boxes, classNames and confidence scores of inferences.
*/
func drawAfterPerformingCalculations(
onDetections detections: [Detection], withImageSize imageSize: CGSize
) {
self.overlayView.objectOverlays = []
self.overlayView.setNeedsDisplay()
guard !detections.isEmpty else {
return
}
var objectOverlays: [ObjectOverlay] = []
for detection in detections {
guard let category = detection.categories.first else { continue }
// Translates bounding box rect to current view.
var convertedRect = detection.boundingBox.applying(
CGAffineTransform(
scaleX: self.overlayView.bounds.size.width / imageSize.width,
y: self.overlayView.bounds.size.height / imageSize.height))
if convertedRect.origin.x < 0 {
convertedRect.origin.x = self.edgeOffset
}
if convertedRect.origin.y < 0 {
convertedRect.origin.y = self.edgeOffset
}
if convertedRect.maxY > self.overlayView.bounds.maxY {
convertedRect.size.height =
self.overlayView.bounds.maxY - convertedRect.origin.y - self.edgeOffset
}
if convertedRect.maxX > self.overlayView.bounds.maxX {
convertedRect.size.width =
self.overlayView.bounds.maxX - convertedRect.origin.x - self.edgeOffset
}
let objectDescription = String(
format: "\(category.label ?? "Unknown") (%.2f)",
category.score)
let displayColor = colors[category.index % colors.count]
let size = objectDescription.size(withAttributes: [.font: self.displayFont])
let objectOverlay = ObjectOverlay(
name: objectDescription, borderRect: convertedRect, nameStringSize: size,
color: displayColor,
font: self.displayFont)
objectOverlays.append(objectOverlay)
}
// Hands off drawing to the OverlayView
self.draw(objectOverlays: objectOverlays)
}
/** Calls methods to update overlay view with detected bounding boxes and class names.
*/
func draw(objectOverlays: [ObjectOverlay]) {
self.overlayView.objectOverlays = objectOverlays
self.overlayView.setNeedsDisplay()
}
}
// MARK: Bottom Sheet Interaction Methods
extension ViewController {
// MARK: Bottom Sheet Interaction Methods
/**
This method adds a pan gesture to make the bottom sheet interactive.
*/
private func addPanGesture() {
let panGesture = UIPanGestureRecognizer(
target: self, action: #selector(ViewController.didPan(panGesture:)))
bottomSheetView.addGestureRecognizer(panGesture)
}
/** Change whether bottom sheet should be in expanded or collapsed state.
*/
private func changeBottomViewState() {
guard let inferenceVC = inferenceViewController else {
return
}
if bottomSheetViewBottomSpace.constant == inferenceVC.collapsedHeight
- bottomSheetView.bounds.size.height
{
bottomSheetViewBottomSpace.constant = 0.0
} else {
bottomSheetViewBottomSpace.constant =
inferenceVC.collapsedHeight - bottomSheetView.bounds.size.height
}
setImageBasedOnBottomViewState()
}
/**
Set image of the bottom sheet icon based on whether it is expanded or collapsed
*/
private func setImageBasedOnBottomViewState() {
if bottomSheetViewBottomSpace.constant == 0.0 {
bottomSheetStateImageView.image = UIImage(named: "down_icon")
} else {
bottomSheetStateImageView.image = UIImage(named: "up_icon")
}
}
/**
This method responds to the user panning on the bottom sheet.
*/
@objc func didPan(panGesture: UIPanGestureRecognizer) {
// Opens or closes the bottom sheet based on the user's interaction with the bottom sheet.
let translation = panGesture.translation(in: view)
switch panGesture.state {
case .began:
initialBottomSpace = bottomSheetViewBottomSpace.constant
translateBottomSheet(withVerticalTranslation: translation.y)
case .changed:
translateBottomSheet(withVerticalTranslation: translation.y)
case .cancelled:
setBottomSheetLayout(withBottomSpace: initialBottomSpace)
case .ended:
translateBottomSheetAtEndOfPan(withVerticalTranslation: translation.y)
setImageBasedOnBottomViewState()
initialBottomSpace = 0.0
default:
break
}
}
/**
This method sets bottom sheet translation while pan gesture state is continuously changing.
*/
private func translateBottomSheet(withVerticalTranslation verticalTranslation: CGFloat) {
let bottomSpace = initialBottomSpace - verticalTranslation
guard
(bottomSpace <= 0.0)
&& (bottomSpace >=
inferenceViewController!.collapsedHeight - bottomSheetView.bounds.size.height)
else {
return
}
setBottomSheetLayout(withBottomSpace: bottomSpace)
}
/**
This method changes bottom sheet state to either fully expanded or closed at the end of pan.
*/
private func translateBottomSheetAtEndOfPan(withVerticalTranslation verticalTranslation: CGFloat)
{
// Changes bottom sheet state to either fully open or closed at the end of pan.
let bottomSpace = bottomSpaceAtEndOfPan(withVerticalTranslation: verticalTranslation)
setBottomSheetLayout(withBottomSpace: bottomSpace)
}
/**
Return the final state of the bottom sheet view (whether fully collapsed or expanded) that is to be retained.
*/
private func bottomSpaceAtEndOfPan(withVerticalTranslation verticalTranslation: CGFloat)
-> CGFloat
{
// Calculates whether to fully expand or collapse bottom sheet when pan gesture ends.
var bottomSpace = initialBottomSpace - verticalTranslation
var height: CGFloat = 0.0
if initialBottomSpace == 0.0 {
height = bottomSheetView.bounds.size.height
} else {
height = inferenceViewController!.collapsedHeight
}
let currentHeight = bottomSheetView.bounds.size.height + bottomSpace
if currentHeight - height <= collapseTransitionThreshold {
bottomSpace = inferenceViewController!.collapsedHeight - bottomSheetView.bounds.size.height
} else if currentHeight - height >= expandTransitionThreshold {
bottomSpace = 0.0
} else {
bottomSpace = initialBottomSpace
}
return bottomSpace
}
/**
This method layouts the change of the bottom space of bottom sheet with respect to the view managed by this controller.
*/
func setBottomSheetLayout(withBottomSpace bottomSpace: CGFloat) {
view.setNeedsLayout()
bottomSheetViewBottomSpace.constant = bottomSpace
view.setNeedsLayout()
}
}
// MARK: - Display handler function
/// TFLite model types
enum ModelType: CaseIterable {
case efficientDetLite0
case efficientDetLite1
case efficientDetLite2
case ssdMobileNetV1
var modelFileInfo: FileInfo {
switch self {
case .ssdMobileNetV1:
return FileInfo("ssd_mobilenet_v1", "tflite")
case .efficientDetLite0:
return FileInfo("efficientdet_lite0", "tflite")
case .efficientDetLite1:
return FileInfo("efficientdet_lite1", "tflite")
case .efficientDetLite2:
return FileInfo("efficientdet_lite2", "tflite")
}
}
var title: String {
switch self {
case .ssdMobileNetV1:
return "SSD-MobileNetV1"
case .efficientDetLite0:
return "EfficientDet-Lite0"
case .efficientDetLite1:
return "EfficientDet-Lite1"
case .efficientDetLite2:
return "EfficientDet-Lite2"
}
}
}
/// Default configuration
struct ConstantsDefault {
static let modelType: ModelType = .efficientDetLite0
static let threadCount = 1
static let scoreThreshold: Float = 0.5
static let maxResults: Int = 3
static let theadCountLimit = 10
}
| d899a437cfb645450f41a929e302a7f2 | 31.73694 | 162 | 0.724226 | false | false | false | false |
exercism/xswift | refs/heads/master | exercises/rotational-cipher/Sources/RotationalCipher/RotationalCipherExample.swift | mit | 2 | struct RotationalCipher {
static func rotate(_ target: String, ROT: Int) -> String {
var result = ""
target.unicodeScalars.forEach { unicode in
switch unicode.value {
case 65...90: // A to Z
var scalar = unicode.value + UInt32(ROT)
if scalar > 90 { scalar -= 26 }
result.append(Character(UnicodeScalar(scalar)!))
case 97...122: // a to z
var scalar = unicode.value + UInt32(ROT)
if scalar > 122 { scalar -= 26 }
result.append(Character(UnicodeScalar(scalar)!))
default:
result.append(Character(unicode))
}
}
return result
}
}
| 11b35900533901a9d69186a2f22c6439 | 23.933333 | 64 | 0.5 | false | false | false | false |
ziyang0621/ZTDropDownTextField | refs/heads/master | ZTDropDownTextField/ZTDropDownTextField.swift | mit | 1 | //
// ZTDropDownTextField.swift
// ZTDropDownTextField
//
// Created by Ziyang Tan on 7/30/15.
// Copyright (c) 2015 Ziyang Tan. All rights reserved.
//
import UIKit
// MARK: Animation Style Enum
public enum ZTDropDownAnimationStyle {
case Basic
case Slide
case Expand
case Flip
}
// MARK: Dropdown Delegate
public protocol ZTDropDownTextFieldDataSourceDelegate: NSObjectProtocol {
func dropDownTextField(dropDownTextField: ZTDropDownTextField, numberOfRowsInSection section: Int) -> Int
func dropDownTextField(dropDownTextField: ZTDropDownTextField, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
func dropDownTextField(dropDownTextField: ZTDropDownTextField, didSelectRowAtIndexPath indexPath: NSIndexPath)
}
public class ZTDropDownTextField: UITextField {
// MARK: Instance Variables
public var dropDownTableView: UITableView!
public var rowHeight:CGFloat = 50
public var dropDownTableViewHeight: CGFloat = 150
public var animationStyle: ZTDropDownAnimationStyle = .Basic
public weak var dataSourceDelegate: ZTDropDownTextFieldDataSourceDelegate?
private var heightConstraint: NSLayoutConstraint!
// MARK: Init Methods
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupTextField()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupTextField()
}
// MARK: Setup Methods
private func setupTextField() {
addTarget(self, action: #selector(ZTDropDownTextField.editingChanged(_:)), forControlEvents:.EditingChanged)
}
private func setupTableView() {
if dropDownTableView == nil {
dropDownTableView = UITableView()
dropDownTableView.backgroundColor = UIColor.whiteColor()
dropDownTableView.layer.cornerRadius = 10.0
dropDownTableView.layer.borderColor = UIColor.lightGrayColor().CGColor
dropDownTableView.layer.borderWidth = 1.0
dropDownTableView.showsVerticalScrollIndicator = false
dropDownTableView.delegate = self
dropDownTableView.dataSource = self
dropDownTableView.estimatedRowHeight = rowHeight
superview!.addSubview(dropDownTableView)
superview!.bringSubviewToFront(dropDownTableView)
dropDownTableView.translatesAutoresizingMaskIntoConstraints = false
let leftConstraint = NSLayoutConstraint(item: dropDownTableView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0)
let rightConstraint = NSLayoutConstraint(item: dropDownTableView, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: 0)
heightConstraint = NSLayoutConstraint(item: dropDownTableView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: dropDownTableViewHeight)
let topConstraint = NSLayoutConstraint(item: dropDownTableView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 1)
NSLayoutConstraint.activateConstraints([leftConstraint, rightConstraint, heightConstraint, topConstraint])
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ZTDropDownTextField.tapped(_:)))
tapGesture.numberOfTapsRequired = 1
tapGesture.cancelsTouchesInView = false
superview!.addGestureRecognizer(tapGesture)
}
}
private func tableViewAppearanceChange(appear: Bool) {
switch animationStyle {
case .Basic:
let basicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
basicAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
basicAnimation.toValue = appear ? 1 : 0
dropDownTableView.pop_addAnimation(basicAnimation, forKey: "basic")
case .Slide:
let basicAnimation = POPBasicAnimation(propertyNamed: kPOPLayoutConstraintConstant)
basicAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
basicAnimation.toValue = appear ? dropDownTableViewHeight : 0
heightConstraint.pop_addAnimation(basicAnimation, forKey: "heightConstraint")
case .Expand:
let springAnimation = POPSpringAnimation(propertyNamed: kPOPViewSize)
springAnimation.springSpeed = dropDownTableViewHeight / 100
springAnimation.springBounciness = 10.0
let width = appear ? CGRectGetWidth(frame) : 0
let height = appear ? dropDownTableViewHeight : 0
springAnimation.toValue = NSValue(CGSize: CGSize(width: width, height: height))
dropDownTableView.pop_addAnimation(springAnimation, forKey: "expand")
case .Flip:
var identity = CATransform3DIdentity
identity.m34 = -1.0/1000
let angle = appear ? CGFloat(0) : CGFloat(M_PI_2)
let rotationTransform = CATransform3DRotate(identity, angle, 0.0, 1.0, 0.0)
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.dropDownTableView.layer.transform = rotationTransform
})
}
}
// MARK: Target Methods
func tapped(gesture: UIGestureRecognizer) {
let location = gesture.locationInView(superview)
if !CGRectContainsPoint(dropDownTableView.frame, location) {
if (dropDownTableView) != nil {
self.tableViewAppearanceChange(false)
}
}
}
func editingChanged(textField: UITextField) {
if textField.text!.characters.count > 0 {
setupTableView()
self.tableViewAppearanceChange(true)
} else {
if (dropDownTableView) != nil {
self.tableViewAppearanceChange(false)
}
}
}
}
// Mark: UITableViewDataSoruce
extension ZTDropDownTextField: UITableViewDataSource {
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let dataSourceDelegate = dataSourceDelegate {
if dataSourceDelegate.respondsToSelector(Selector("dropDownTextField:numberOfRowsInSection:")) {
return dataSourceDelegate.dropDownTextField(self, numberOfRowsInSection: section)
}
}
return 0
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let dataSourceDelegate = dataSourceDelegate {
if dataSourceDelegate.respondsToSelector(Selector("dropDownTextField:cellForRowAtIndexPath:")) {
return dataSourceDelegate.dropDownTextField(self, cellForRowAtIndexPath: indexPath)
}
}
return UITableViewCell()
}
}
// Mark: UITableViewDelegate
extension ZTDropDownTextField: UITableViewDelegate {
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let dataSourceDelegate = dataSourceDelegate {
if dataSourceDelegate.respondsToSelector(Selector("dropDownTextField:didSelectRowAtIndexPath:")) {
dataSourceDelegate.dropDownTextField(self, didSelectRowAtIndexPath: indexPath)
}
}
self.tableViewAppearanceChange(false)
}
} | bf2272d45f529e53df33da052fa252a1 | 43.409357 | 204 | 0.68629 | false | false | false | false |
iosprogrammingwithswift/iosprogrammingwithswift | refs/heads/master | 04_Swift2015.playground/Pages/03_Strings And Characters.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous) | [Next](@next)
//: Fun Fact: Swift’s String type is bridged with Foundation’s NSString class. If you are working with the Foundation framework in Cocoa, the entire NSString API is available to call on any String value you create when type cast to NSString, as described in AnyObject. You can also use a String value with any API that requires an NSString instance.
//: String Literals
let someString = "Some string literal value"
// these two strings are both empty, and are equivalent to each other
// variableString is now "Horse and carriage"
// this reports a compile-time error - a constant string cannot be modified
//: Strings Are Value Types
//: String Interpolation
//: Counting Characters
// prints "unusualMenagerie has 40 characters"
//: Character access
// G
// !
// u
// a
//: Comparing Strings
// prints "These two strings are considered equal"
//: Prefix and Suffix Equality
let romeoAndJuliet = [
"Act 1 Scene 1: Verona, A public place",
"Act 1 Scene 2: Capulet's mansion",
"Act 1 Scene 3: A room in Capulet's mansion",
"Act 1 Scene 4: A street outside Capulet's mansion",
"Act 1 Scene 5: The Great Hall in Capulet's mansion",
"Act 2 Scene 1: Outside Capulet's mansion",
"Act 2 Scene 2: Capulet's orchard",
"Act 2 Scene 3: Outside Friar Lawrence's cell",
"Act 2 Scene 4: A street in Verona",
"Act 2 Scene 5: Capulet's mansion",
"Act 2 Scene 6: Friar Lawrence's cell"
]
var act1SceneCount = 0
print("There are \(act1SceneCount) scenes in Act 1")
var mansionCount = 0
var cellCount = 0
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
/*:
largely Based of [Apple's Swift Language Guide: Strings And Characters](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-ID285 ) & [Apple's A Swift Tour](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1 )
*/
//: [Previous](@previous) | [Next](@next)
| 3e2b28cf09db1911e629848f002be168 | 26.139241 | 418 | 0.71875 | false | false | false | false |
google/JacquardSDKiOS | refs/heads/main | Example/JacquardSDK/UIControls/LoadingViewController/LoadingViewController.swift | apache-2.0 | 1 | // Copyright 2021 Google LLC
//
// 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 MaterialComponents
import UIKit
/// An Overlayed ViewController that covers the entire window, used as an ActivityIndicator.
final class LoadingViewController: UIViewController {
private enum Constants {
static let animationDuration = 0.5
static let pairingAnimationDuration = 3.0
}
@IBOutlet private weak var indicator: MDCActivityIndicator!
@IBOutlet private weak var indicatorImage: UIImageView!
@IBOutlet private weak var indicatorLabel: UILabel!
@IBOutlet private weak var transparentView: UIView!
static let instance = LoadingViewController(nibName: "LoadingViewController", bundle: nil)
func indicatorProgress(_ progress: Float) {
if let indicator = indicator {
indicator.progress = progress
}
}
func startLoading(withMessage text: String) {
if let indicator = indicator {
indicator.startAnimating()
indicatorImage.isHidden = true
indicatorLabel.text = text
UIView.animate(withDuration: Constants.animationDuration) { self.transparentView.alpha = 1.0 }
}
}
func stopLoading(withMessage text: String, completion: (() -> Void)? = nil) {
if let indicator = indicator {
indicator.stopAnimating()
indicatorImage.isHidden = false
indicatorLabel.text = text
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Constants.pairingAnimationDuration
) {
self.indicatorImage.isHidden = true
self.dismiss(animated: false, completion: completion)
}
}
}
func stopLoading(
message: String = "",
timeout: TimeInterval = 0.0,
animated: Bool = true,
completion: (() -> Void)? = nil
) {
indicator.stopAnimating()
indicatorImage.isHidden = true
indicatorLabel.text = message
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + timeout) {
self.dismiss(animated: animated, completion: completion)
}
}
}
| 17555c6bdad328b2d252599600604810 | 32.333333 | 100 | 0.716 | false | false | false | false |
qkrqjadn/SoonChat | refs/heads/master | source/LoginCell.swift | mit | 2 | //
// LoginCell.swift
// audible
//
// Created by 박범우 on 2016. 12. 6..
// Copyright © 2016년 Lets Build That App. All rights reserved.
//
import UIKit
import Firebase
import NVActivityIndicatorView
class LoginCell : UICollectionViewCell
{
let logoImageView : UIImageView = {
let image = UIImage(named: "logo")
let imageview = UIImageView(image: image)
return imageview
}()
let emailTextField : LeftPaddedTextField = {
let tf = LeftPaddedTextField()
tf.placeholder = "Enter email"
tf.layer.borderColor = UIColor.lightGray.cgColor
tf.layer.borderWidth = 0.5
tf.keyboardType = .emailAddress
return tf
}()
let passwordTextField : LeftPaddedTextField = {
let tf = LeftPaddedTextField()
tf.placeholder = "passwd"
tf.layer.borderColor = UIColor.lightGray.cgColor
tf.layer.borderWidth = 0.5
tf.isSecureTextEntry = true
return tf
}()
lazy var loginButton : UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .orange
button.setTitle("로그인", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(handleLogin), for: .touchUpInside)
button.layer.cornerRadius = 5
return button
}()
lazy var registerButton : UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .blue
button.setTitle("회원가입", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(registered), for: .touchUpInside)
button.layer.cornerRadius = 5
return button
}()
let activityindicator : NVActivityIndicatorView = {
let ai = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 60, height: 60), type: .ballPulse, color: UIColor(r: 250, g: 156, b: 0), padding: NVActivityIndicatorView.DEFAULT_PADDING)
ai.translatesAutoresizingMaskIntoConstraints = false
return ai
}()
func registered()
{
delegate?.registerClick()
}
weak var delegate : LoginControllerDelegate?
func handleLogin(){
activityindicator.startAnimating()
DispatchQueue.global().async {
guard let email = self.emailTextField.text,let passwd = self.passwordTextField.text else {
return
}
FIRAuth.auth()?.signIn(withEmail: email, password: passwd, completion: { (user, error) in
if error != nil {
self.activityindicator.stopAnimating()
let alertview = UIAlertController(title: "에러", message: error?.localizedDescription, preferredStyle: .alert)
alertview.addAction(UIAlertAction(title: "취소", style: .cancel, handler: { (_) in }))
self.delegate?.errmessage(alertview: alertview)
return
}
self.activityindicator.stopAnimating()
self.delegate?.finishLoggingIn()
})
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(logoImageView)
addSubview(emailTextField)
addSubview(passwordTextField)
addSubview(loginButton)
addSubview(registerButton)
addSubview(activityindicator)
_ = logoImageView.anchor(centerYAnchor, left: nil, bottom: nil, right: nil, topConstant: -250, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 160, heightConstant: 160)
logoImageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
_ = emailTextField.anchor(logoImageView.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 8, leftConstant: 32, bottomConstant: 0, rightConstant: 32, widthConstant: 0, heightConstant: 50)
_ = passwordTextField.anchor(emailTextField.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 16, leftConstant: 32, bottomConstant: 0, rightConstant: 32, widthConstant: 0, heightConstant: 50)
_ = loginButton.anchor(passwordTextField.bottomAnchor, left: leftAnchor, bottom: nil, right:rightAnchor , topConstant: 16, leftConstant: 32, bottomConstant: 0, rightConstant: 32, widthConstant: 0, heightConstant: 50)
_ = registerButton.anchor(loginButton.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 16, leftConstant: 32, bottomConstant: 0, rightConstant: 32, widthConstant: 0, heightConstant: 50)
activityindicator.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
activityindicator.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
activityindicator.widthAnchor.constraint(equalToConstant: 50).isActive = true
activityindicator.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/**
* 텍스트뷰의 Placeholder의 위치를 변경하기 위해 클래스 오버라이딩
*/
class LeftPaddedTextField : UITextField {
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.width + 10, height: bounds.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.width + 10, height: bounds.height)
}
}
| e31738de7714cdf41af3b02fb4063f7b | 38.061644 | 227 | 0.645099 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | refs/heads/master | Pod/Classes/Sources.Api/MessagingCallbackImpl.swift | apache-2.0 | 1 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Interface for Managing the Messaging responses
Auto-generated implementation of IMessagingCallback specification.
*/
public class MessagingCallbackImpl : BaseCallbackImpl, IMessagingCallback {
/**
Constructor with callback id.
@param id The id of the callback.
*/
public override init(id : Int64) {
super.init(id: id)
}
/**
This method is called on Error
@param error returned by the platform
@since v2.0
*/
public func onError(error : IMessagingCallbackError) {
let param0 : String = "Adaptive.IMessagingCallbackError.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(error.toString())\\\"}\"))"
var callbackId : Int64 = -1
if (getId() != nil) {
callbackId = getId()!
}
AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleMessagingCallbackError( \(callbackId), \(param0))")
}
/**
This method is called on Result
@param success true if sent;false otherwise
@since v2.0
*/
public func onResult(success : Bool) {
let param0 : String = "\(success)"
var callbackId : Int64 = -1
if (getId() != nil) {
callbackId = getId()!
}
AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleMessagingCallbackResult( \(callbackId), \(param0))")
}
/**
This method is called on Warning
@param success true if sent;false otherwise
@param warning returned by the platform
@since v2.0
*/
public func onWarning(success : Bool, warning : IMessagingCallbackWarning) {
let param0 : String = "\(success)"
let param1 : String = "Adaptive.IMessagingCallbackWarning.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(warning.toString())\\\"}\"))"
var callbackId : Int64 = -1
if (getId() != nil) {
callbackId = getId()!
}
AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleMessagingCallbackWarning( \(callbackId), \(param0), \(param1))")
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| bbc12a2b2a0072bcfbb277da3211e443 | 34.254902 | 163 | 0.603726 | false | false | false | false |
DianQK/TrelloNavigation | refs/heads/master | Source/TrelloListTableView.swift | mit | 1 | //
// TrelloListTableView.swift
// TrelloNavigation
//
// Created by DianQK on 15/11/8.
// Copyright © 2015年 Qing. All rights reserved.
//
import UIKit
public typealias HeaderDidFolded = (Bool) -> Void
public class TrelloListTableView<T>: UITableView {
public var listItems: [T]?
public var headerDidFolded: HeaderDidFolded?
public var tab: String?
override public var contentOffset: CGPoint {
willSet {
if contentOffset.y != 0 {
headerDidFolded?(contentOffset.y > 0)
}
}
}
public override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 30.0))
footerView.backgroundColor = TrelloGray
let maskPath = UIBezierPath(roundedRect: footerView.bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: 5, height: 5))
let maskLayer = CAShapeLayer()
maskLayer.frame = footerView.bounds
maskLayer.path = maskPath.cgPath
footerView.layer.mask = maskLayer
tableFooterView = footerView
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| ebd19b9dc9f8a443d2b59b10a4eddd9f | 30.214286 | 157 | 0.649886 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/decl/func/constructor.swift | apache-2.0 | 10 | // RUN: %target-parse-verify-swift
// User-written default constructor
struct X {
init() {}
}
X() // expected-warning{{unused}}
// User-written memberwise constructor
struct Y {
var i : Int, f : Float
init(i : Int, f : Float) {}
}
Y(i: 1, f: 1.5) // expected-warning{{unused}}
// User-written memberwise constructor with default
struct Z {
var a : Int
var b : Int
init(a : Int, b : Int = 5) {
self.a = a
self.b = b
}
}
Z(a: 1, b: 2) // expected-warning{{unused}}
// User-written init suppresses implicit constructors.
struct A {
var i, j : Int
init(x : Int) {
i = x
j = x
}
}
A() // expected-error{{missing argument for parameter 'x'}}
A(x: 1) // expected-warning{{unused}}
A(1, 1) // expected-error{{extra argument in call}}
// No user-written constructors; implicit constructors are available.
struct B {
var i : Int = 0, j : Float = 0.0
}
extension B {
init(x : Int) {
self.i = x
self.j = 1.5
}
}
B() // expected-warning{{unused}}
B(x: 1) // expected-warning{{unused}}
B(i: 1, j: 2.5) // expected-warning{{unused}}
struct F {
var d : D
var b : B
var c : C
}
struct C {
var d : D
init(d : D) { } // suppress implicit constructors
}
struct D {
var i : Int
init(i : Int) { }
}
extension D {
init() { i = 17 }
}
F() // expected-error{{missing argument for parameter 'd'}}
D() // okay // expected-warning{{unused}}
B() // okay // expected-warning{{unused}}
C() // expected-error{{missing argument for parameter 'd'}}
struct E {
init(x : Wonka) { } // expected-error{{use of undeclared type 'Wonka'}}
}
var e : E
//----------------------------------------------------------------------------
// Argument/parameter name separation
//----------------------------------------------------------------------------
class ArgParamSep {
init(_ b: Int, _: Int, forInt int: Int, c _: Int, d: Int) { }
}
// Tests for crashes.
// rdar://14082378
struct NoCrash1a {
init(_: NoCrash1b) {} // expected-error {{use of undeclared type 'NoCrash1b'}}
}
var noCrash1c : NoCrash1a
class MissingDef {
init() // expected-error{{initializer requires a body}}
}
| 8e50ebd8598a2de70b201f6eb9a58b03 | 18.75 | 80 | 0.564932 | false | false | false | false |
PureSwift/Bluetooth | refs/heads/master | Sources/BluetoothGAP/GAPPublicTargetAddress.swift | mit | 1 | //
// GAPPublicTargetAddress.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/13/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// The Public Target Address data type defines the address of one or more intended recipients of an advertisement when one or more devices were bonded using a public address.
/// This data type is intended to be used to avoid a situation where a bonded device unnecessarily responds to an advertisement intended for another bonded device.
///
/// Size: Multiples of 6 octets
/// The format of each 6 octet address is the same as the Public Device Address defined in Vol. 6, Part B, Section 1.3.
///
/// The public device address is divided into the following two fields:
/// company_assigned field is contained in the 24 least significant bits
/// company_id field is contained in the 24 most significant bits
@frozen
public struct GAPPublicTargetAddress: GAPData, Equatable {
public static let dataType: GAPDataType = .publicTargetAddress
public let addresses: [BluetoothAddress]
public init(addresses: [BluetoothAddress]) {
self.addresses = addresses
}
}
public extension GAPPublicTargetAddress {
init?(data: Data) {
guard data.count % BluetoothAddress.length == 0
else { return nil }
let count = data.count / BluetoothAddress.length
let addresses: [BluetoothAddress] = (0 ..< count).map {
let index = $0 * BluetoothAddress.length
return BluetoothAddress(littleEndian: BluetoothAddress(bytes: (data[index], data[index+1], data[index+2], data[index+3], data[index+4], data[index+5])))
}
self.init(addresses: addresses)
}
var dataLength: Int {
return addresses.count * BluetoothAddress.length
}
func append(to data: inout Data) {
addresses.forEach { data += $0.littleEndian }
}
}
// MARK: - CustomStringConvertible
extension GAPPublicTargetAddress: CustomStringConvertible {
public var description: String {
return addresses.description
}
}
// MARK: - ExpressibleByArrayLiteral
extension GAPPublicTargetAddress: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: BluetoothAddress...) {
self.init(addresses: elements)
}
}
| 1a857218d2678ad3e9dd20469b00676a | 29.961039 | 175 | 0.67953 | false | false | false | false |
CNKCQ/oschina | refs/heads/master | Carthage/Checkouts/SnapKit/Source/ConstraintOffsetTarget.swift | mit | 3 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public protocol ConstraintOffsetTarget: ConstraintConstantTarget {
}
extension Int: ConstraintOffsetTarget {
}
extension UInt: ConstraintOffsetTarget {
}
extension Float: ConstraintOffsetTarget {
}
extension Double: ConstraintOffsetTarget {
}
extension CGFloat: ConstraintOffsetTarget {
}
extension ConstraintOffsetTarget {
internal var constraintOffsetTargetValue: CGFloat {
let offset: CGFloat
if let amount = self as? Float {
offset = CGFloat(amount)
} else if let amount = self as? Double {
offset = CGFloat(amount)
} else if let amount = self as? CGFloat {
offset = CGFloat(amount)
} else if let amount = self as? Int {
offset = CGFloat(amount)
} else if let amount = self as? UInt {
offset = CGFloat(amount)
} else {
offset = 0.0
}
return offset
}
}
| b9994ec58b05a3d221143ae0f700c854 | 31.38806 | 81 | 0.694931 | false | false | false | false |
jakarmy/swift-summary | refs/heads/master | The Swift Summary Book.playground/Pages/12 Subscripts.xcplaygroundpage/Contents.swift | mit | 1 |
// |=------------------------------------------------------=|
// Copyright (c) 2016 Juan Antonio Karmy.
// Licensed under MIT License
//
// See https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ for Swift Language Reference
//
// See Juan Antonio Karmy - http://karmy.co | http://twitter.com/jkarmy
//
// |=------------------------------------------------------=|
import UIKit
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
/*
This is how you define subscripts.
In this case, the matrix is accessed via subscripts i.e. matrix[1,2]
*/
subscript(row: Int, column: Int) -> Double {
//Subcripts can be read-write or read-only (no need for getters and setters in that case)
get {
assert(indexIsValidForRow(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
//newValue is provided by default, but you can change the name of the received value.
set {
assert(indexIsValidForRow(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
class ViewController: UIViewController {
var matrix = Matrix(rows: 2, columns: 2)
override func viewDidLoad() {
super.viewDidLoad()
//This is setting up the first position of the matrix
matrix[0, 0] = 2.5
let number = matrix[0,0]
print(number)
//This call will fail, since it's out of bounds.
matrix[3, 3] = 4.5
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| a67d65acc7bf943c9262ab2097bfb3ff | 30.590909 | 135 | 0.568345 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Serialization/search-paths-prefix-map.swift | apache-2.0 | 10 | // RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule)
// RUN: %target-swift-frontend -emit-module -o %t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule/%target-swiftmodule-name %S/Inputs/alias.swift -module-name has_alias
// RUN: %empty-directory(%t/secret)
// RUN: %target-swift-frontend -emit-module -o %t/secret %S/Inputs/struct_with_operators.swift
// RUN: %target-swift-frontend -emit-module -o %t -I %t/secret -F %t/Frameworks -Fsystem %t/SystemFrameworks %S/Inputs/has_xref.swift
// RUN: %empty-directory(%t/workingdir)
// RUN: cd %t/workingdir && %target-swift-frontend -sdk %t/sdk %s -emit-module -o %t/prefixed.swiftmodule \
// RUN: -I %t -I %t/secret -F %t/Frameworks -Fsystem %t/SystemFrameworks \
// RUN: -Xcc -I -Xcc %t/include -Xcc -isystem -Xcc %t/system -Xcc -F -Xcc %t/fw \
// RUN: -Xcc -I%t/includejoined -Xcc -isystem%t/systemjoined -Xcc -F%t/fwjoined \
// RUN: -Xcc -D -Xcc donotprefixme -prefix-serialized-debugging-options \
// RUN: -debug-prefix-map %t/sdk=SDKROOT -debug-prefix-map %t=SRC -debug-prefix-map donotprefixme=ERROR
// RUN: llvm-bcanalyzer -dump %t/prefixed.swiftmodule | %FileCheck %s
import has_xref
numeric(42)
// CHECK-LABEL: <OPTIONS_BLOCK
// CHECK: <SDK_PATH abbrevid={{[0-9]+}}/> blob data = 'SDKROOT'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-working-directory'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = 'SRC{{[\/\\]}}workingdir'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-I'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = 'SRC/include'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-isystem'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = 'SRC/system'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-F'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = 'SRC/fw'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-ISRC/includejoined'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-isystemSRC/systemjoined'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-FSRC/fwjoined'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-D'
// CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = 'donotprefixme'
// CHECK-NOT: <XCC abbrevid={{[0-9]+}}/> blob data = '-fdebug-prefix-map
// CHECK: </OPTIONS_BLOCK>
// CHECK-LABEL: <INPUT_BLOCK
// CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=1 op1=0/> blob data = 'SRC{{[\/\\]}}Frameworks'
// CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=1 op1=1/> blob data = 'SRC{{[\/\\]}}SystemFrameworks'
// CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=0 op1=0/> blob data = 'SRC'
// CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=0 op1=0/> blob data = 'SRC{{[\/\\]}}secret'
// CHECK: </INPUT_BLOCK>
// RUN: cd %t/workingdir && %target-swift-frontend -sdk %t/sdk %s -emit-module -o %t/unprefixed.swiftmodule \
// RUN: -I %t -F %t/Frameworks \
// RUN: -Xcc -I -Xcc %t/include \
// RUN: -debug-prefix-map %t=TESTPREFIX
// RUN: llvm-bcanalyzer -dump %t/unprefixed.swiftmodule | %FileCheck --check-prefix=UNPREFIXED %s
// UNPREFIXED-NOT: TESTPREFIX | 621cc7fc95f6bdcac621dc07f264f0a0 | 58.490196 | 180 | 0.642928 | false | false | false | false |
Jnosh/swift | refs/heads/master | test/SILGen/switch_var.swift | apache-2.0 | 14 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int, Int), y: (Int, Int)) -> Bool {
return x.0 == y.0 && x.1 == y.1
}
// Some fake predicates for pattern guards.
func runced() -> Bool { return true }
func funged() -> Bool { return true }
func ansed() -> Bool { return true }
func runced(x x: Int) -> Bool { return true }
func funged(x x: Int) -> Bool { return true }
func ansed(x x: Int) -> Bool { return true }
func foo() -> Int { return 0 }
func bar() -> Int { return 0 }
func foobar() -> (Int, Int) { return (0, 0) }
func foos() -> String { return "" }
func bars() -> String { return "" }
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func f() {}
func g() {}
func a(x x: Int) {}
func b(x x: Int) {}
func c(x x: Int) {}
func d(x x: Int) {}
func a(x x: String) {}
func b(x x: String) {}
func aa(x x: (Int, Int)) {}
func bb(x x: (Int, Int)) {}
func cc(x x: (Int, Int)) {}
// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_1yyF
func test_var_1() {
// CHECK: function_ref @_T010switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK-NOT: br bb
case var x:
// CHECK: function_ref @_T010switch_var1aySi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_T010switch_var1byyF
b()
}
// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_2yyF
func test_var_2() {
// CHECK: function_ref @_T010switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: function_ref @_T010switch_var6runcedSbSi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
// -- TODO: Clean up these empty waypoint bbs.
case var x where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: function_ref @_T010switch_var1aySi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: function_ref @_T010switch_var6fungedSbSi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case var y where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: function_ref @_T010switch_var1bySi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: br [[CASE3:bb[0-9]+]]
case var z:
// CHECK: [[CASE3]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: function_ref @_T010switch_var1cySi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: destroy_value [[ZADDR]]
// CHECK: br [[CONT]]
c(x: z)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_T010switch_var1dyyF
d()
}
// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_3yyF
func test_var_3() {
// CHECK: function_ref @_T010switch_var3fooSiyF
// CHECK: function_ref @_T010switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: function_ref @_T010switch_var6runcedSbSi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: function_ref @_T010switch_var2aaySi_Sit1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
aa(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: br [[NO_CASE1_TARGET:bb[0-9]+]]
// CHECK: [[NO_CASE1_TARGET]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: function_ref @_T010switch_var6fungedSbSi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: function_ref @_T010switch_var1aySi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var1bySi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
a(x: y)
b(x: z)
// CHECK: [[NO_CASE2]]:
// CHECK: [[WADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: function_ref @_T010switch_var5ansedSbSi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case var w where ansed(x: w.0):
// CHECK: [[CASE3]]:
// CHECK: function_ref @_T010switch_var2bbySi_Sit1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: br [[CONT]]
bb(x: w)
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[WADDR]]
// CHECK: br [[CASE4:bb[0-9]+]]
case var v:
// CHECK: [[CASE4]]:
// CHECK: [[VADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%.*]] = project_box [[VADDR]]
// CHECK: function_ref @_T010switch_var2ccySi_Sit1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[V]]
// CHECK: load [trivial] [[READ]]
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[CONT]]
cc(x: v)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_T010switch_var1dyyF
d()
}
protocol P { func p() }
struct X : P { func p() {} }
struct Y : P { func p() {} }
struct Z : P { func p() {} }
// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_4yAA1P_p1p_tF
func test_var_4(p p: P) {
// CHECK: function_ref @_T010switch_var3fooSiyF
switch (p, foo()) {
// CHECK: [[PAIR:%.*]] = alloc_stack $(P, Int)
// CHECK: store
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[T0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 1
// CHECK: [[PAIR_1:%.*]] = load [trivial] [[T0]] : $*Int
// CHECK: [[TMP:%.*]] = alloc_stack $X
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to X in [[TMP]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
// CHECK: [[IS_X]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*X
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[X]]
// CHECK: function_ref @_T010switch_var6runcedSbSi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case (is X, var x) where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: function_ref @_T010switch_var1aySi1x_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_X]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[TMP:%.*]] = alloc_stack $Y
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to Y in [[TMP]] : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*Y
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[Y]]
// CHECK: function_ref @_T010switch_var6fungedSbSi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (is Y, var y) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: function_ref @_T010switch_var1bySi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_Y]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var (P, Int) }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: function_ref @_T010switch_var5ansedSbSi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[DFLT_NO_CASE3:bb[0-9]+]]
case var z where ansed(x: z.1):
// CHECK: [[CASE3]]:
// CHECK: function_ref @_T010switch_var1cySi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: destroy_value [[ZADDR]]
// CHECK-NEXT: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
c(x: z.1)
// CHECK: [[DFLT_NO_CASE3]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: br [[CASE4:bb[0-9]+]]
case (_, var w):
// CHECK: [[CASE4]]:
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[WADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: function_ref @_T010switch_var1dySi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: destroy_value [[WADDR]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
d(x: w)
}
e()
}
// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_5yyF : $@convention(thin) () -> () {
func test_var_5() {
// CHECK: function_ref @_T010switch_var3fooSiyF
// CHECK: function_ref @_T010switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b()
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case (_, _) where runced():
// CHECK: [[CASE3]]:
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: br [[CASE4:bb[0-9]+]]
case _:
// CHECK: [[CASE4]]:
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
e()
}
// CHECK-LABEL: sil hidden @_T010switch_var05test_B7_returnyyF : $@convention(thin) () -> () {
func test_var_return() {
switch (foo(), bar()) {
case var x where runced():
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%[0-9]+]] = project_box [[XADDR]]
// CHECK: function_ref @_T010switch_var1ayyF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[EPILOG:bb[0-9]+]]
a()
return
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
case (var y, var z) where funged():
// CHECK: function_ref @_T010switch_var1byyF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[EPILOG]]
b()
return
case var w where ansed():
// CHECK: [[WADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%[0-9]+]] = project_box [[WADDR]]
// CHECK: function_ref @_T010switch_var1cyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[WADDR]]
// CHECK: br [[EPILOG]]
c()
return
case var v:
// CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%[0-9]+]] = project_box [[VADDR]]
// CHECK: function_ref @_T010switch_var1dyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[EPILOG]]
d()
return
}
}
// When all of the bindings in a column are immutable, don't emit a mutable
// box. <rdar://problem/15873365>
// CHECK-LABEL: sil hidden @_T010switch_var8test_letyyF : $@convention(thin) () -> () {
func test_let() {
// CHECK: [[FOOS:%.*]] = function_ref @_T010switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @_T010switch_var6runcedSbyF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
switch foos() {
case let x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[A:%.*]] = function_ref @_T010switch_var1aySS1x_tF
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[VAL_COPY_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY]]
// CHECK: apply [[A]]([[VAL_COPY_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY]] from [[VAL_COPY]]
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[TRY_CASE2:bb[0-9]+]]
// CHECK: [[TRY_CASE2]]:
// CHECK: [[VAL_COPY_2:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @_T010switch_var6fungedSbyF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[B:%.*]] = function_ref @_T010switch_var1bySS1x_tF
// CHECK: [[BORROWED_VAL_COPY_2:%.*]] = begin_borrow [[VAL_COPY_2]]
// CHECK: [[VAL_COPY_2_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY_2]]
// CHECK: apply [[B]]([[VAL_COPY_2_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY_2]] from [[VAL_COPY_2]]
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: br [[NEXT_CASE:bb6]]
// CHECK: [[NEXT_CASE]]:
// CHECK: [[VAL_COPY_3:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @_T010switch_var4barsSSyF
// CHECK: [[BORROWED_VAL_COPY_3:%.*]] = begin_borrow [[VAL_COPY_3]]
// CHECK: [[VAL_COPY_3_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY_3]]
// CHECK: store [[VAL_COPY_3_COPY]] to [init] [[IN_ARG:%.*]] :
// CHECK: apply {{%.*}}<String>({{.*}}, [[IN_ARG]])
// CHECK: cond_br {{%.*}}, [[YES_CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// ExprPatterns implicitly contain a 'let' binding.
case bars():
// CHECK: [[YES_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: destroy_value [[VAL]]
// CHECK: function_ref @_T010switch_var1cyyF
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: br [[NEXT_CASE:bb9+]]
// CHECK: [[NEXT_CASE]]:
case _:
// CHECK: destroy_value [[VAL]]
// CHECK: function_ref @_T010switch_var1dyyF
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '_T010switch_var8test_letyyF'
// If one of the bindings is a "var", allocate a box for the column.
// CHECK-LABEL: sil hidden @_T010switch_var015test_mixed_let_B0yyF : $@convention(thin) () -> () {
func test_mixed_let_var() {
// CHECK: bb0:
// CHECK: [[FOOS:%.*]] = function_ref @_T010switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
switch foos() {
// First pattern.
// CHECK: [[BOX:%.*]] = alloc_box ${ var String }, var, name "x"
// CHECK: [[PBOX:%.*]] = project_box [[BOX]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: store [[VAL_COPY]] to [init] [[PBOX]]
// CHECK: cond_br {{.*}}, [[CASE1:bb[0-9]+]], [[NOCASE1:bb[0-9]+]]
case var x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[A:%.*]] = function_ref @_T010switch_var1aySS1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOX]]
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: apply [[A]]([[X]])
// CHECK: destroy_value [[BOX]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NOCASE1]]:
// CHECK: destroy_value [[BOX]]
// CHECK: br [[NEXT_PATTERN:bb[0-9]+]]
// CHECK: [[NEXT_PATTERN]]:
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: cond_br {{.*}}, [[CASE2:bb[0-9]+]], [[NOCASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[B:%.*]] = function_ref @_T010switch_var1bySS1x_tF
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[VAL_COPY_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY]]
// CHECK: apply [[B]]([[VAL_COPY_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY]] from [[VAL_COPY]]
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NOCASE2]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[NEXT_CASE:bb[0-9]+]]
// CHECK: [[NEXT_CASE]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[VAL_COPY_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY]]
// CHECK: store [[VAL_COPY_COPY]] to [init] [[TMP_VAL_COPY_ADDR:%.*]] : $*String
// CHECK: apply {{.*}}<String>({{.*}}, [[TMP_VAL_COPY_ADDR]])
// CHECK: cond_br {{.*}}, [[CASE3:bb[0-9]+]], [[NOCASE3:bb[0-9]+]]
case bars():
// CHECK: [[CASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: [[FUNC:%.*]] = function_ref @_T010switch_var1cyyF : $@convention(thin) () -> ()
// CHECK: apply [[FUNC]]()
// CHECK: br [[CONT]]
c()
// CHECK: [[NOCASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[NEXT_CASE:bb[0-9]+]]
// CHECK: [[NEXT_CASE]]:
// CHECK: destroy_value [[VAL]]
// CHECK: [[D_FUNC:%.*]] = function_ref @_T010switch_var1dyyF : $@convention(thin) () -> ()
// CHECK: apply [[D_FUNC]]()
// CHECK: br [[CONT]]
case _:
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '_T010switch_var015test_mixed_let_B0yyF'
// CHECK-LABEL: sil hidden @_T010switch_var23test_multiple_patterns1yyF : $@convention(thin) () -> () {
func test_multiple_patterns1() {
// CHECK: function_ref @_T010switch_var6foobarSi_SityF
switch foobar() {
// CHECK-NOT: br bb
case (0, let x), (let x, 0):
// CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// CHECK: [[FIRST_MATCH_CASE]]:
// CHECK: debug_value [[FIRST_X:%.*]] :
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int)
// CHECK: [[FIRST_FAIL]]:
// CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// CHECK: [[SECOND_MATCH_CASE]]:
// CHECK: debug_value [[SECOND_X:%.*]] :
// CHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// CHECK: [[A:%.*]] = function_ref @_T010switch_var1aySi1x_tF
// CHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// CHECK: [[SECOND_FAIL]]:
// CHECK: function_ref @_T010switch_var1byyF
b()
}
}
// FIXME(integers): the following checks should be updated for the new integer
// protocols. <rdar://problem/29939484>
// XCHECK-LABEL: sil hidden @_T010switch_var23test_multiple_patterns2yyF : $@convention(thin) () -> () {
func test_multiple_patterns2() {
let t1 = 2
let t2 = 4
// XCHECK: debug_value [[T1:%.*]] :
// XCHECK: debug_value [[T2:%.*]] :
switch (0,0) {
// XCHECK-NOT: br bb
case (_, let x) where x > t1, (let x, _) where x > t2:
// XCHECK: [[FIRST_X:%.*]] = tuple_extract {{%.*}} : $(Int, Int), 1
// XCHECK: debug_value [[FIRST_X]] :
// XCHECK: apply {{%.*}}([[FIRST_X]], [[T1]])
// XCHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// XCHECK: [[FIRST_MATCH_CASE]]:
// XCHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int)
// XCHECK: [[FIRST_FAIL]]:
// XCHECK: debug_value [[SECOND_X:%.*]] :
// XCHECK: apply {{%.*}}([[SECOND_X]], [[T2]])
// XCHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// XCHECK: [[SECOND_MATCH_CASE]]:
// XCHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int)
// XCHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// XCHECK: [[A:%.*]] = function_ref @_T010switch_var1aySi1x_tF
// XCHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// XCHECK: [[SECOND_FAIL]]:
// XCHECK: function_ref @_T010switch_var1byyF
b()
}
}
enum Foo {
case A(Int, Double)
case B(Double, Int)
case C(Int, Int, Double)
}
// CHECK-LABEL: sil hidden @_T010switch_var23test_multiple_patterns3yyF : $@convention(thin) () -> () {
func test_multiple_patterns3() {
let f = Foo.C(0, 1, 2.0)
switch f {
// CHECK: switch_enum {{%.*}} : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
case .A(let x, let n), .B(let n, let x), .C(_, let x, let n):
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int, [[A_N]] : $Double)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int, [[B_N]] : $Double)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: [[C__:%.*]] = tuple_extract
// CHECK: [[C_X:%.*]] = tuple_extract
// CHECK: [[C_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[C_X]] : $Int, [[C_N]] : $Double)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int, [[BODY_N:%.*]] : $Double):
// CHECK: [[FUNC_A:%.*]] = function_ref @_T010switch_var1aySi1x_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
enum Bar {
case Y(Foo, Int)
case Z(Int, Foo)
}
// CHECK-LABEL: sil hidden @_T010switch_var23test_multiple_patterns4yyF : $@convention(thin) () -> () {
func test_multiple_patterns4() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(let x, _), _), .Y(.B(_, let x), _), .Y(.C, let x), .Z(let x, _):
// CHECK: [[Y]]({{%.*}} : $(Foo, Int)):
// CHECK: [[Y_F:%.*]] = tuple_extract
// CHECK: [[Y_X:%.*]] = tuple_extract
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]({{%.*}} : $(Int, Foo)):
// CHECK: [[Z_X:%.*]] = tuple_extract
// CHECK: [[Z_F:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: [[FUNC_A:%.*]] = function_ref @_T010switch_var1aySi1x_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
func aaa(x x: inout Int) {}
// CHECK-LABEL: sil hidden @_T010switch_var23test_multiple_patterns5yyF : $@convention(thin) () -> () {
func test_multiple_patterns5() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(var x, _), _), .Y(.B(_, var x), _), .Y(.C, var x), .Z(var x, _):
// CHECK: [[Y]]({{%.*}} : $(Foo, Int)):
// CHECK: [[Y_F:%.*]] = tuple_extract
// CHECK: [[Y_X:%.*]] = tuple_extract
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]({{%.*}} : $(Int, Foo)):
// CHECK: [[Z_X:%.*]] = tuple_extract
// CHECK: [[Z_F:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: store [[BODY_X]] to [trivial] [[BOX_X:%.*]] : $*Int
// CHECK: [[FUNC_AAA:%.*]] = function_ref @_T010switch_var3aaaySiz1x_tF
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOX_X]]
// CHECK: apply [[FUNC_AAA]]([[WRITE]])
aaa(x: &x)
}
}
// rdar://problem/29252758 -- local decls must not be reemitted.
func test_against_reemission(x: Bar) {
switch x {
case .Y(let a, _), .Z(_, let a):
let b = a
}
}
class C {}
class D: C {}
func f(_: D) -> Bool { return true }
// CHECK-LABEL: sil hidden @{{.*}}test_multiple_patterns_value_semantics
func test_multiple_patterns_value_semantics(_ y: C) {
switch y {
// CHECK: checked_cast_br {{%.*}} : $C to $D, [[AS_D:bb[0-9]+]], [[NOT_AS_D:bb[0-9]+]]
// CHECK: [[AS_D]]({{.*}}):
// CHECK: cond_br {{%.*}}, [[F_TRUE:bb[0-9]+]], [[F_FALSE:bb[0-9]+]]
// CHECK: [[F_TRUE]]:
// CHECK: [[BINDING:%.*]] = copy_value [[ORIG:%.*]] :
// CHECK: destroy_value [[ORIG]]
// CHECK: br {{bb[0-9]+}}([[BINDING]]
case let x as D where f(x), let x as D: break
default: break
}
}
| f8638f508f29b0b3d4ba4db2615e1c32 | 36.634921 | 161 | 0.51188 | false | false | false | false |
SusanDoggie/Doggie | refs/heads/main | Sources/DoggieMath/Accelerate/Radix2CooleyTukey/cooleytukey_16.swift | mit | 1 | //
// cooleytukey_16.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// 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.
//
@inlinable
@inline(__always)
func cooleytukey_forward_16<T: BinaryFloatingPoint>(_ input: UnsafePointer<T>, _ in_stride: Int, _ in_count: Int, _ out_real: UnsafeMutablePointer<T>, _ out_imag: UnsafeMutablePointer<T>, _ out_stride: Int) {
var input = input
var out_real = out_real
var out_imag = out_imag
let a1 = input.pointee
input += in_stride
let i1 = in_count > 1 ? input.pointee : 0
input += in_stride
let e1 = in_count > 2 ? input.pointee : 0
input += in_stride
let m1 = in_count > 3 ? input.pointee : 0
input += in_stride
let c1 = in_count > 4 ? input.pointee : 0
input += in_stride
let k1 = in_count > 5 ? input.pointee : 0
input += in_stride
let g1 = in_count > 6 ? input.pointee : 0
input += in_stride
let o1 = in_count > 7 ? input.pointee : 0
input += in_stride
let b1 = in_count > 8 ? input.pointee : 0
input += in_stride
let j1 = in_count > 9 ? input.pointee : 0
input += in_stride
let f1 = in_count > 10 ? input.pointee : 0
input += in_stride
let n1 = in_count > 11 ? input.pointee : 0
input += in_stride
let d1 = in_count > 12 ? input.pointee : 0
input += in_stride
let l1 = in_count > 13 ? input.pointee : 0
input += in_stride
let h1 = in_count > 14 ? input.pointee : 0
input += in_stride
let p1 = in_count > 15 ? input.pointee : 0
let a3 = a1 + b1
let b3 = a1 - b1
let c3 = c1 + d1
let d3 = c1 - d1
let e3 = e1 + f1
let f3 = e1 - f1
let g3 = g1 + h1
let h3 = g1 - h1
let i3 = i1 + j1
let j3 = i1 - j1
let k3 = k1 + l1
let l3 = k1 - l1
let m3 = m1 + n1
let n3 = m1 - n1
let o3 = o1 + p1
let p3 = o1 - p1
let a5 = a3 + c3
let c5 = a3 - c3
let e5 = e3 + g3
let g5 = e3 - g3
let i5 = i3 + k3
let k5 = i3 - k3
let m5 = m3 + o3
let o5 = m3 - o3
let M_SQRT1_2 = 0.7071067811865475244008443621048490392848359376884740 as T
let q = M_SQRT1_2 * (f3 - h3)
let r = M_SQRT1_2 * (h3 + f3)
let w = M_SQRT1_2 * (n3 - p3)
let x = M_SQRT1_2 * (p3 + n3)
let a7 = a5 + e5
let b7 = b3 + q
let b8 = d3 + r
let d7 = b3 - q
let d8 = d3 - r
let e7 = a5 - e5
let i7 = i5 + m5
let p7 = j3 + w
let j8 = l3 + x
let l7 = j3 - w
let l8 = l3 - x
let m7 = i5 - m5
let M_SIN_22_5 = 0.3826834323650897717284599840303988667613445624856270 as T
let M_COS_22_5 = 0.9238795325112867561281831893967882868224166258636424 as T
let q2 = M_SQRT1_2 * (k5 - o5)
let r2 = M_SQRT1_2 * (k5 + o5)
let w2 = M_COS_22_5 * p7 - M_SIN_22_5 * j8
let w3 = M_COS_22_5 * j8 + M_SIN_22_5 * p7
let x2 = M_SIN_22_5 * l7 + M_COS_22_5 * l8
let x3 = M_SIN_22_5 * l8 - M_COS_22_5 * l7
out_real.pointee = a7 + i7
out_imag.pointee = 0
out_real += out_stride
out_imag += out_stride
out_real.pointee = b7 + w2
out_imag.pointee = -b8 - w3
out_real += out_stride
out_imag += out_stride
out_real.pointee = c5 + q2
out_imag.pointee = -g5 - r2
out_real += out_stride
out_imag += out_stride
out_real.pointee = d7 + x2
out_imag.pointee = d8 + x3
out_real += out_stride
out_imag += out_stride
out_real.pointee = e7
out_imag.pointee = -m7
out_real += out_stride
out_imag += out_stride
out_real.pointee = d7 - x2
out_imag.pointee = x3 - d8
out_real += out_stride
out_imag += out_stride
out_real.pointee = c5 - q2
out_imag.pointee = g5 - r2
out_real += out_stride
out_imag += out_stride
out_real.pointee = b7 - w2
out_imag.pointee = b8 - w3
out_real += out_stride
out_imag += out_stride
out_real.pointee = a7 - i7
out_imag.pointee = 0
out_real += out_stride
out_imag += out_stride
out_real.pointee = b7 - w2
out_imag.pointee = w3 - b8
out_real += out_stride
out_imag += out_stride
out_real.pointee = c5 - q2
out_imag.pointee = r2 - g5
out_real += out_stride
out_imag += out_stride
out_real.pointee = d7 - x2
out_imag.pointee = d8 - x3
out_real += out_stride
out_imag += out_stride
out_real.pointee = e7
out_imag.pointee = m7
out_real += out_stride
out_imag += out_stride
out_real.pointee = d7 + x2
out_imag.pointee = -x3 - d8
out_real += out_stride
out_imag += out_stride
out_real.pointee = c5 + q2
out_imag.pointee = g5 + r2
out_real += out_stride
out_imag += out_stride
out_real.pointee = b7 + w2
out_imag.pointee = b8 + w3
}
@inlinable
@inline(__always)
func cooleytukey_forward_16<T: BinaryFloatingPoint>(_ in_real: UnsafePointer<T>, _ in_imag: UnsafePointer<T>, _ in_stride: Int, _ in_count: (Int, Int), _ out_real: UnsafeMutablePointer<T>, _ out_imag: UnsafeMutablePointer<T>, _ out_stride: Int) {
var in_real = in_real
var in_imag = in_imag
var out_real = out_real
var out_imag = out_imag
let a1 = in_real.pointee
let a2 = in_imag.pointee
in_real += in_stride
in_imag += in_stride
let i1 = in_count.0 > 1 ? in_real.pointee : 0
let i2 = in_count.1 > 1 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let e1 = in_count.0 > 2 ? in_real.pointee : 0
let e2 = in_count.1 > 2 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let m1 = in_count.0 > 3 ? in_real.pointee : 0
let m2 = in_count.1 > 3 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let c1 = in_count.0 > 4 ? in_real.pointee : 0
let c2 = in_count.1 > 4 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let k1 = in_count.0 > 5 ? in_real.pointee : 0
let k2 = in_count.1 > 5 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let g1 = in_count.0 > 6 ? in_real.pointee : 0
let g2 = in_count.1 > 6 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let o1 = in_count.0 > 7 ? in_real.pointee : 0
let o2 = in_count.1 > 7 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let b1 = in_count.0 > 8 ? in_real.pointee : 0
let b2 = in_count.1 > 8 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let j1 = in_count.0 > 9 ? in_real.pointee : 0
let j2 = in_count.1 > 9 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let f1 = in_count.0 > 10 ? in_real.pointee : 0
let f2 = in_count.1 > 10 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let n1 = in_count.0 > 11 ? in_real.pointee : 0
let n2 = in_count.1 > 11 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let d1 = in_count.0 > 12 ? in_real.pointee : 0
let d2 = in_count.1 > 12 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let l1 = in_count.0 > 13 ? in_real.pointee : 0
let l2 = in_count.1 > 13 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let h1 = in_count.0 > 14 ? in_real.pointee : 0
let h2 = in_count.1 > 14 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
let p1 = in_count.0 > 15 ? in_real.pointee : 0
let p2 = in_count.1 > 15 ? in_imag.pointee : 0
let a3 = a1 + b1
let a4 = a2 + b2
let b3 = a1 - b1
let b4 = a2 - b2
let c3 = c1 + d1
let c4 = c2 + d2
let d3 = c1 - d1
let d4 = c2 - d2
let e3 = e1 + f1
let e4 = e2 + f2
let f3 = e1 - f1
let f4 = e2 - f2
let g3 = g1 + h1
let g4 = g2 + h2
let h3 = g1 - h1
let h4 = g2 - h2
let i3 = i1 + j1
let i4 = i2 + j2
let j3 = i1 - j1
let j4 = i2 - j2
let k3 = k1 + l1
let k4 = k2 + l2
let l3 = k1 - l1
let l4 = k2 - l2
let m3 = m1 + n1
let m4 = m2 + n2
let n3 = m1 - n1
let n4 = m2 - n2
let o3 = o1 + p1
let o4 = o2 + p2
let p3 = o1 - p1
let p4 = o2 - p2
let a5 = a3 + c3
let a6 = a4 + c4
let b5 = b3 + d4
let b6 = b4 - d3
let c5 = a3 - c3
let c6 = a4 - c4
let d5 = b3 - d4
let d6 = b4 + d3
let e5 = e3 + g3
let e6 = e4 + g4
let f5 = f3 + h4
let f6 = f4 - h3
let g5 = e3 - g3
let g6 = e4 - g4
let h5 = f3 - h4
let h6 = f4 + h3
let i5 = i3 + k3
let i6 = i4 + k4
let j5 = j3 + l4
let j6 = j4 - l3
let k5 = i3 - k3
let k6 = i4 - k4
let l5 = j3 - l4
let l6 = j4 + l3
let m5 = m3 + o3
let m6 = m4 + o4
let n5 = n3 + p4
let n6 = n4 - p3
let o5 = m3 - o3
let o6 = m4 - o4
let p5 = n3 - p4
let p6 = n4 + p3
let M_SQRT1_2 = 0.7071067811865475244008443621048490392848359376884740 as T
let q = M_SQRT1_2 * (f5 + f6)
let r = M_SQRT1_2 * (f6 - f5)
let s = M_SQRT1_2 * (h5 - h6)
let t = M_SQRT1_2 * (h6 + h5)
let w = M_SQRT1_2 * (n5 + n6)
let x = M_SQRT1_2 * (n6 - n5)
let y = M_SQRT1_2 * (p5 - p6)
let z = M_SQRT1_2 * (p6 + p5)
let a7 = a5 + e5
let a8 = a6 + e6
let b7 = b5 + q
let b8 = b6 + r
let c7 = c5 + g6
let c8 = c6 - g5
let d7 = d5 - s
let d8 = d6 - t
let e7 = a5 - e5
let e8 = a6 - e6
let f7 = b5 - q
let f8 = b6 - r
let g7 = c5 - g6
let g8 = c6 + g5
let h7 = d5 + s
let h8 = d6 + t
let i7 = i5 + m5
let i8 = i6 + m6
let j7 = j5 + w
let j8 = j6 + x
let k7 = k5 + o6
let k8 = k6 - o5
let l7 = l5 - y
let l8 = l6 - z
let m7 = i5 - m5
let m8 = i6 - m6
let n7 = j5 - w
let n8 = j6 - x
let o7 = k5 - o6
let o8 = k6 + o5
let p7 = l5 + y
let p8 = l6 + z
let M_SIN_22_5 = 0.3826834323650897717284599840303988667613445624856270 as T
let M_COS_22_5 = 0.9238795325112867561281831893967882868224166258636424 as T
let q2 = M_SQRT1_2 * (k7 + k8)
let r2 = M_SQRT1_2 * (k8 - k7)
let s2 = M_SQRT1_2 * (o8 - o7)
let t2 = M_SQRT1_2 * (o7 + o8)
let w2 = M_COS_22_5 * j7 + M_SIN_22_5 * j8
let w3 = M_COS_22_5 * j8 - M_SIN_22_5 * j7
let x2 = M_SIN_22_5 * l7 + M_COS_22_5 * l8
let x3 = M_SIN_22_5 * l8 - M_COS_22_5 * l7
let y2 = M_COS_22_5 * n8 - M_SIN_22_5 * n7
let y3 = M_COS_22_5 * n7 + M_SIN_22_5 * n8
let z2 = M_SIN_22_5 * p8 - M_COS_22_5 * p7
let z3 = M_SIN_22_5 * p7 + M_COS_22_5 * p8
out_real.pointee = a7 + i7
out_imag.pointee = a8 + i8
out_real += out_stride
out_imag += out_stride
out_real.pointee = b7 + w2
out_imag.pointee = b8 + w3
out_real += out_stride
out_imag += out_stride
out_real.pointee = c7 + q2
out_imag.pointee = c8 + r2
out_real += out_stride
out_imag += out_stride
out_real.pointee = d7 + x2
out_imag.pointee = d8 + x3
out_real += out_stride
out_imag += out_stride
out_real.pointee = e7 + m8
out_imag.pointee = e8 - m7
out_real += out_stride
out_imag += out_stride
out_real.pointee = f7 + y2
out_imag.pointee = f8 - y3
out_real += out_stride
out_imag += out_stride
out_real.pointee = g7 + s2
out_imag.pointee = g8 - t2
out_real += out_stride
out_imag += out_stride
out_real.pointee = h7 + z2
out_imag.pointee = h8 - z3
out_real += out_stride
out_imag += out_stride
out_real.pointee = a7 - i7
out_imag.pointee = a8 - i8
out_real += out_stride
out_imag += out_stride
out_real.pointee = b7 - w2
out_imag.pointee = b8 - w3
out_real += out_stride
out_imag += out_stride
out_real.pointee = c7 - q2
out_imag.pointee = c8 - r2
out_real += out_stride
out_imag += out_stride
out_real.pointee = d7 - x2
out_imag.pointee = d8 - x3
out_real += out_stride
out_imag += out_stride
out_real.pointee = e7 - m8
out_imag.pointee = e8 + m7
out_real += out_stride
out_imag += out_stride
out_real.pointee = f7 - y2
out_imag.pointee = f8 + y3
out_real += out_stride
out_imag += out_stride
out_real.pointee = g7 - s2
out_imag.pointee = g8 + t2
out_real += out_stride
out_imag += out_stride
out_real.pointee = h7 - z2
out_imag.pointee = h8 + z3
}
@inlinable
@inline(__always)
func cooleytukey_inverse_16<T: BinaryFloatingPoint>(_ input: UnsafePointer<T>, _ in_stride: Int, _ in_count: Int, _ out_real: UnsafeMutablePointer<T>, _ out_imag: UnsafeMutablePointer<T>, _ out_stride: Int) {
var input = input
var out_real = out_real
var out_imag = out_imag
let a1 = input.pointee
input += in_stride
let i1 = in_count > 1 ? input.pointee : 0
input += in_stride
let e1 = in_count > 2 ? input.pointee : 0
input += in_stride
let m1 = in_count > 3 ? input.pointee : 0
input += in_stride
let c1 = in_count > 4 ? input.pointee : 0
input += in_stride
let k1 = in_count > 5 ? input.pointee : 0
input += in_stride
let g1 = in_count > 6 ? input.pointee : 0
input += in_stride
let o1 = in_count > 7 ? input.pointee : 0
input += in_stride
let b1 = in_count > 8 ? input.pointee : 0
input += in_stride
let j1 = in_count > 9 ? input.pointee : 0
input += in_stride
let f1 = in_count > 10 ? input.pointee : 0
input += in_stride
let n1 = in_count > 11 ? input.pointee : 0
input += in_stride
let d1 = in_count > 12 ? input.pointee : 0
input += in_stride
let l1 = in_count > 13 ? input.pointee : 0
input += in_stride
let h1 = in_count > 14 ? input.pointee : 0
input += in_stride
let p1 = in_count > 15 ? input.pointee : 0
let a3 = a1 + b1
let b3 = a1 - b1
let c3 = c1 + d1
let d3 = c1 - d1
let e3 = e1 + f1
let f3 = e1 - f1
let g3 = g1 + h1
let h3 = g1 - h1
let i3 = i1 + j1
let j3 = i1 - j1
let k3 = k1 + l1
let l3 = k1 - l1
let m3 = m1 + n1
let n3 = m1 - n1
let o3 = o1 + p1
let p3 = o1 - p1
let a5 = a3 + c3
let c5 = a3 - c3
let e5 = e3 + g3
let g5 = e3 - g3
let i5 = i3 + k3
let k5 = i3 - k3
let m5 = m3 + o3
let o5 = m3 - o3
let M_SQRT1_2 = 0.7071067811865475244008443621048490392848359376884740 as T
let q = M_SQRT1_2 * (f3 - h3)
let r = M_SQRT1_2 * (h3 + f3)
let w = M_SQRT1_2 * (n3 - p3)
let x = M_SQRT1_2 * (p3 + n3)
let a7 = a5 + e5
let b7 = b3 + q
let b8 = d3 + r
let d7 = b3 - q
let d8 = d3 - r
let e7 = a5 - e5
let i7 = i5 + m5
let j7 = j3 + w
let j8 = l3 + x
let l7 = j3 - w
let l8 = l3 - x
let m7 = i5 - m5
let M_SIN_22_5 = 0.3826834323650897717284599840303988667613445624856270 as T
let M_COS_22_5 = 0.9238795325112867561281831893967882868224166258636424 as T
let q2 = M_SQRT1_2 * (k5 - o5)
let r2 = M_SQRT1_2 * (o5 + k5)
let w2 = M_COS_22_5 * j7 - M_SIN_22_5 * j8
let w3 = M_COS_22_5 * j8 + M_SIN_22_5 * j7
let x2 = M_SIN_22_5 * l7 + M_COS_22_5 * l8
let x3 = M_COS_22_5 * l7 - M_SIN_22_5 * l8
out_real.pointee = a7 + i7
out_imag.pointee = 0
out_real += out_stride
out_imag += out_stride
out_real.pointee = b7 + w2
out_imag.pointee = b8 + w3
out_real += out_stride
out_imag += out_stride
out_real.pointee = c5 + q2
out_imag.pointee = g5 + r2
out_real += out_stride
out_imag += out_stride
out_real.pointee = d7 + x2
out_imag.pointee = x3 - d8
out_real += out_stride
out_imag += out_stride
out_real.pointee = e7
out_imag.pointee = m7
out_real += out_stride
out_imag += out_stride
out_real.pointee = d7 - x2
out_imag.pointee = d8 + x3
out_real += out_stride
out_imag += out_stride
out_real.pointee = c5 - q2
out_imag.pointee = r2 - g5
out_real += out_stride
out_imag += out_stride
out_real.pointee = b7 - w2
out_imag.pointee = w3 - b8
out_real += out_stride
out_imag += out_stride
out_real.pointee = a7 - i7
out_imag.pointee = 0
out_real += out_stride
out_imag += out_stride
out_real.pointee = b7 - w2
out_imag.pointee = b8 - w3
out_real += out_stride
out_imag += out_stride
out_real.pointee = c5 - q2
out_imag.pointee = g5 - r2
out_real += out_stride
out_imag += out_stride
out_real.pointee = d7 - x2
out_imag.pointee = -d8 - x3
out_real += out_stride
out_imag += out_stride
out_real.pointee = e7
out_imag.pointee = -m7
out_real += out_stride
out_imag += out_stride
out_real.pointee = d7 + x2
out_imag.pointee = d8 - x3
out_real += out_stride
out_imag += out_stride
out_real.pointee = c5 + q2
out_imag.pointee = -g5 - r2
out_real += out_stride
out_imag += out_stride
out_real.pointee = b7 + w2
out_imag.pointee = -b8 - w3
}
@inlinable
@inline(__always)
func cooleytukey_forward_reorderd_16<T: BinaryFloatingPoint>(_ real: UnsafeMutablePointer<T>, _ imag: UnsafeMutablePointer<T>, _ stride: Int) {
var in_real = real
var in_imag = imag
var out_real = real
var out_imag = imag
let a1 = in_real.pointee
let a2 = in_imag.pointee
in_real += stride
in_imag += stride
let b1 = in_real.pointee
let b2 = in_imag.pointee
in_real += stride
in_imag += stride
let c1 = in_real.pointee
let c2 = in_imag.pointee
in_real += stride
in_imag += stride
let d1 = in_real.pointee
let d2 = in_imag.pointee
in_real += stride
in_imag += stride
let e1 = in_real.pointee
let e2 = in_imag.pointee
in_real += stride
in_imag += stride
let f1 = in_real.pointee
let f2 = in_imag.pointee
in_real += stride
in_imag += stride
let g1 = in_real.pointee
let g2 = in_imag.pointee
in_real += stride
in_imag += stride
let h1 = in_real.pointee
let h2 = in_imag.pointee
in_real += stride
in_imag += stride
let i1 = in_real.pointee
let i2 = in_imag.pointee
in_real += stride
in_imag += stride
let j1 = in_real.pointee
let j2 = in_imag.pointee
in_real += stride
in_imag += stride
let k1 = in_real.pointee
let k2 = in_imag.pointee
in_real += stride
in_imag += stride
let l1 = in_real.pointee
let l2 = in_imag.pointee
in_real += stride
in_imag += stride
let m1 = in_real.pointee
let m2 = in_imag.pointee
in_real += stride
in_imag += stride
let n1 = in_real.pointee
let n2 = in_imag.pointee
in_real += stride
in_imag += stride
let o1 = in_real.pointee
let o2 = in_imag.pointee
in_real += stride
in_imag += stride
let p1 = in_real.pointee
let p2 = in_imag.pointee
let a3 = a1 + b1
let a4 = a2 + b2
let b3 = a1 - b1
let b4 = a2 - b2
let c3 = c1 + d1
let c4 = c2 + d2
let d3 = c1 - d1
let d4 = c2 - d2
let e3 = e1 + f1
let e4 = e2 + f2
let f3 = e1 - f1
let f4 = e2 - f2
let g3 = g1 + h1
let g4 = g2 + h2
let h3 = g1 - h1
let h4 = g2 - h2
let i3 = i1 + j1
let i4 = i2 + j2
let j3 = i1 - j1
let j4 = i2 - j2
let k3 = k1 + l1
let k4 = k2 + l2
let l3 = k1 - l1
let l4 = k2 - l2
let m3 = m1 + n1
let m4 = m2 + n2
let n3 = m1 - n1
let n4 = m2 - n2
let o3 = o1 + p1
let o4 = o2 + p2
let p3 = o1 - p1
let p4 = o2 - p2
let a5 = a3 + c3
let a6 = a4 + c4
let b5 = b3 + d4
let b6 = b4 - d3
let c5 = a3 - c3
let c6 = a4 - c4
let d5 = b3 - d4
let d6 = b4 + d3
let e5 = e3 + g3
let e6 = e4 + g4
let f5 = f3 + h4
let f6 = f4 - h3
let g5 = e3 - g3
let g6 = e4 - g4
let h5 = f3 - h4
let h6 = f4 + h3
let i5 = i3 + k3
let i6 = i4 + k4
let j5 = j3 + l4
let j6 = j4 - l3
let k5 = i3 - k3
let k6 = i4 - k4
let l5 = j3 - l4
let l6 = j4 + l3
let m5 = m3 + o3
let m6 = m4 + o4
let n5 = n3 + p4
let n6 = n4 - p3
let o5 = m3 - o3
let o6 = m4 - o4
let p5 = n3 - p4
let p6 = n4 + p3
let M_SQRT1_2 = 0.7071067811865475244008443621048490392848359376884740 as T
let q = M_SQRT1_2 * (f5 + f6)
let r = M_SQRT1_2 * (f6 - f5)
let s = M_SQRT1_2 * (h5 - h6)
let t = M_SQRT1_2 * (h6 + h5)
let w = M_SQRT1_2 * (n5 + n6)
let x = M_SQRT1_2 * (n6 - n5)
let y = M_SQRT1_2 * (p5 - p6)
let z = M_SQRT1_2 * (p6 + p5)
let a7 = a5 + e5
let a8 = a6 + e6
let b7 = b5 + q
let b8 = b6 + r
let c7 = c5 + g6
let c8 = c6 - g5
let d7 = d5 - s
let d8 = d6 - t
let e7 = a5 - e5
let e8 = a6 - e6
let f7 = b5 - q
let f8 = b6 - r
let g7 = c5 - g6
let g8 = c6 + g5
let h7 = d5 + s
let h8 = d6 + t
let i7 = i5 + m5
let i8 = i6 + m6
let j7 = j5 + w
let j8 = j6 + x
let k7 = k5 + o6
let k8 = k6 - o5
let l7 = l5 - y
let l8 = l6 - z
let m7 = i5 - m5
let m8 = i6 - m6
let n7 = j5 - w
let n8 = j6 - x
let o7 = k5 - o6
let o8 = k6 + o5
let p7 = l5 + y
let p8 = l6 + z
let M_SIN_22_5 = 0.3826834323650897717284599840303988667613445624856270 as T
let M_COS_22_5 = 0.9238795325112867561281831893967882868224166258636424 as T
let q2 = M_SQRT1_2 * (k7 + k8)
let r2 = M_SQRT1_2 * (k8 - k7)
let s2 = M_SQRT1_2 * (o8 - o7)
let t2 = M_SQRT1_2 * (o7 + o8)
let w2 = M_COS_22_5 * j7 + M_SIN_22_5 * j8
let w3 = M_COS_22_5 * j8 - M_SIN_22_5 * j7
let x2 = M_SIN_22_5 * l7 + M_COS_22_5 * l8
let x3 = M_SIN_22_5 * l8 - M_COS_22_5 * l7
let y2 = M_COS_22_5 * n8 - M_SIN_22_5 * n7
let y3 = M_COS_22_5 * n7 + M_SIN_22_5 * n8
let z2 = M_SIN_22_5 * p8 - M_COS_22_5 * p7
let z3 = M_SIN_22_5 * p7 + M_COS_22_5 * p8
out_real.pointee = a7 + i7
out_imag.pointee = a8 + i8
out_real += stride
out_imag += stride
out_real.pointee = b7 + w2
out_imag.pointee = b8 + w3
out_real += stride
out_imag += stride
out_real.pointee = c7 + q2
out_imag.pointee = c8 + r2
out_real += stride
out_imag += stride
out_real.pointee = d7 + x2
out_imag.pointee = d8 + x3
out_real += stride
out_imag += stride
out_real.pointee = e7 + m8
out_imag.pointee = e8 - m7
out_real += stride
out_imag += stride
out_real.pointee = f7 + y2
out_imag.pointee = f8 - y3
out_real += stride
out_imag += stride
out_real.pointee = g7 + s2
out_imag.pointee = g8 - t2
out_real += stride
out_imag += stride
out_real.pointee = h7 + z2
out_imag.pointee = h8 - z3
out_real += stride
out_imag += stride
out_real.pointee = a7 - i7
out_imag.pointee = a8 - i8
out_real += stride
out_imag += stride
out_real.pointee = b7 - w2
out_imag.pointee = b8 - w3
out_real += stride
out_imag += stride
out_real.pointee = c7 - q2
out_imag.pointee = c8 - r2
out_real += stride
out_imag += stride
out_real.pointee = d7 - x2
out_imag.pointee = d8 - x3
out_real += stride
out_imag += stride
out_real.pointee = e7 - m8
out_imag.pointee = e8 + m7
out_real += stride
out_imag += stride
out_real.pointee = f7 - y2
out_imag.pointee = f8 + y3
out_real += stride
out_imag += stride
out_real.pointee = g7 - s2
out_imag.pointee = g8 + t2
out_real += stride
out_imag += stride
out_real.pointee = h7 - z2
out_imag.pointee = h8 + z3
}
| ea1ed986148fba7f796b381a01bb3ca0 | 24.537994 | 246 | 0.538721 | false | false | false | false |
usharif/GrapeVyne | refs/heads/master | Pods/TKSubmitTransitionSwift3/SubmitTransition/Classes/TransitionSubmitButton.swift | mit | 1 | import Foundation
import UIKit
@IBDesignable
open class TKTransitionSubmitButton : UIButton, UIViewControllerTransitioningDelegate, CAAnimationDelegate {
lazy var spiner: SpinerLayer! = {
let s = SpinerLayer(frame: self.frame)
self.layer.addSublayer(s)
return s
}()
@IBInspectable open var spinnerColor: UIColor = UIColor.white {
didSet {
spiner.spinnerColor = spinnerColor
}
}
//Normal state bg and border
@IBInspectable var normalBorderColor: UIColor? {
didSet {
layer.borderColor = normalBorderColor?.cgColor
}
}
@IBInspectable var normalBackgroundColor: UIColor? {
didSet {
setBgColorForState(color: normalBackgroundColor, forState: .normal)
}
}
//Highlighted state bg and border
@IBInspectable var highlightedBorderColor: UIColor?
@IBInspectable var highlightedBackgroundColor: UIColor? {
didSet {
setBgColorForState(color: highlightedBackgroundColor, forState: .highlighted)
}
}
private func setBgColorForState(color: UIColor?, forState: UIControlState){
if color != nil {
setBackgroundImage(UIImage.imageWithColor(color: color!), for: forState)
} else {
setBackgroundImage(nil, for: forState)
}
}
open var didEndFinishAnimation : (()->())? = nil
let springGoEase = CAMediaTimingFunction(controlPoints: 0.45, -0.36, 0.44, 0.92)
let shrinkCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
let expandCurve = CAMediaTimingFunction(controlPoints: 0.95, 0.02, 1, 0.05)
let shrinkDuration: CFTimeInterval = 0.1
@IBInspectable open var normalCornerRadius:CGFloat? = 0.0{
didSet {
self.layer.cornerRadius = normalCornerRadius!
}
}
var cachedTitle: String?
public override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
public required init!(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.setup()
}
func setup() {
self.clipsToBounds = true
spiner.spinnerColor = spinnerColor
}
open func startLoadingAnimation() {
self.cachedTitle = title(for: UIControlState())
self.setTitle("", for: UIControlState())
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.layer.cornerRadius = self.frame.height / 2
}, completion: { (done) -> Void in
self.shrink()
_ = Timer.schedule(delay: self.shrinkDuration - 0.25) { _ in
self.spiner.animation()
}
})
}
open func startFinishAnimation(_ delay: TimeInterval, completion:(()->())?) {
_ = Timer.schedule(delay: delay) { _ in
self.didEndFinishAnimation = completion
self.expand()
self.spiner.stopAnimation()
}
}
open func animate(_ duration: TimeInterval, completion:(()->())?) {
startLoadingAnimation()
startFinishAnimation(duration, completion: completion)
}
open func setOriginalState() {
self.returnToOriginalState()
self.spiner.stopAnimation()
}
open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
let a = anim as! CABasicAnimation
if a.keyPath == "transform.scale" {
didEndFinishAnimation?()
_ = Timer.schedule(delay: 1) { _ in
self.returnToOriginalState()
}
}
}
open func returnToOriginalState() {
self.layer.removeAllAnimations()
self.setTitle(self.cachedTitle, for: UIControlState())
self.spiner.stopAnimation()
}
func shrink() {
let shrinkAnim = CABasicAnimation(keyPath: "bounds.size.width")
shrinkAnim.fromValue = frame.width
shrinkAnim.toValue = frame.height
shrinkAnim.duration = shrinkDuration
shrinkAnim.timingFunction = shrinkCurve
shrinkAnim.fillMode = kCAFillModeForwards
shrinkAnim.isRemovedOnCompletion = false
layer.add(shrinkAnim, forKey: shrinkAnim.keyPath)
}
func expand() {
let expandAnim = CABasicAnimation(keyPath: "transform.scale")
expandAnim.fromValue = 1.0
expandAnim.toValue = 26.0
expandAnim.timingFunction = expandCurve
expandAnim.duration = 0.3
expandAnim.delegate = self
expandAnim.fillMode = kCAFillModeForwards
expandAnim.isRemovedOnCompletion = false
layer.add(expandAnim, forKey: expandAnim.keyPath)
}
}
| 1620dba0645913bb7af6c3af8a8aec2b | 30.039216 | 108 | 0.614445 | false | false | false | false |
brunojppb/Loggerithm | refs/heads/master | Source/Type.swift | mit | 2 | //
// Type.swift
// Loggerithm
//
// Created by Honghao Zhang on 2015-08-13.
// Copyright (c) 2015 Honghao Zhang (张宏昊)
//
// 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
/**
Log level used in Loggerithm logger.
- All: Log with any level will be logged out
- Verbose: Log out string with level greate than or equal to .Verbose
- Debug: Log out string with level greate than or equal to .Debug
- Info: Log out string with level greate than or equal to .Info
- Warning: Log out string with level greate than or equal to .Warning
- Error: Log out string with level greate than or equal to .Error
- Off: Log is turned off
*/
public enum LogLevel: Int {
case All = 0
case Verbose = 1
case Debug = 2
case Info = 3
case Warning = 4
case Error = 5
case Off = 6
/**
Get string description for log level.
:param: logLevel A LogLevel
:returns: A string.
*/
static public func descritionForLogLevel(logLevel: LogLevel) -> String {
switch logLevel {
case .Verbose: return "Verbose"
case .Debug: return "Debug"
case .Info: return "Info"
case .Warning: return "Warning"
case .Error: return "Error"
default: assertionFailure("Invalid level")
return "Null"
}
}
/// Defualt log level
/// Be sure to set the "DEBUG" symbol.
/// Set it in the "Swift Compiler - Custom Flags" section, "Other Swift Flags" line. Add "-D DEBUG" entry.
#if DEBUG
static public let defaultLevel = LogLevel.All
#else
static public let defaultLevel = LogLevel.Warning
#endif
}
// MARK: - Comparable
extension LogLevel: Comparable {}
public func <(lhs: LogLevel, rhs: LogLevel) -> Bool {
return lhs.rawValue < rhs.rawValue
}
public func <=(lhs: LogLevel, rhs: LogLevel) -> Bool {
return lhs.rawValue <= rhs.rawValue
}
public func >=(lhs: LogLevel, rhs: LogLevel) -> Bool {
return lhs.rawValue >= rhs.rawValue
}
| 97c504d7601ce83e96f99494d395049e | 33.255556 | 110 | 0.674992 | false | false | false | false |
JunDang/SwiftFoundation | refs/heads/develop | Sources/UnitTests/DateComponentsTest.swift | mit | 1 | //
// DateComponentsTest.swift
// SwiftFoundation
//
// Created by David Ask on 07/12/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
import XCTest
import SwiftFoundation
final class DateComponentsTest: XCTestCase {
lazy var allTests: [(String, () -> ())] = [("testBuildDate", self.testBuildDate)]
func testBuildDate() {
var dateComponents = DateComponents()
dateComponents.year = 1987
dateComponents.month = 10
dateComponents.dayOfMonth = 10
let assertionDate = Date(timeIntervalSince1970: 560822400)
let madeDate = dateComponents.date
print(assertionDate, madeDate)
XCTAssert(assertionDate == madeDate)
}
} | cce53cb3942e27dde33eba63d13d55ec | 23.933333 | 85 | 0.637216 | false | true | false | false |
Ivacker/swift | refs/heads/master | test/expr/cast/array_iteration.swift | apache-2.0 | 9 | // RUN: %target-parse-verify-swift
func doFoo() {}
class View {
var subviews: Array<AnyObject>! = []
}
var rootView = View()
var v = [View(), View()]
rootView.subviews = v
rootView.subviews as! [View]
for view in rootView.subviews as! [View] {
doFoo()
}
for view:View in rootView.subviews { // expected-error{{'AnyObject' is not convertible to 'View'}}
doFoo()
}
(rootView.subviews!) as! [View]
(rootView.subviews) as! [View]
var ao: [AnyObject] = []
ao as! [View] // works
var b = Array<(String, Int)>()
for x in b {
doFoo()
}
var c : Array<(String, Int)>! = Array()
for x in c {
doFoo()
}
var d : Array<(String, Int)>? = Array()
for x in d! {
doFoo()
}
| 65eba3f726d76e3f9c5f5e2519e9ba98 | 13.531915 | 98 | 0.61347 | false | false | false | false |
xuech/OMS-WH | refs/heads/master | OMS-WH/Classes/StockSearch/View/StockOnRoadTableView.swift | mit | 1 | //
// StockOnRoadTableView.swift
// OMS-WH
//
// Created by ___Gwy on 2017/9/14.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
class StockOnRoadTableView: UITableView {
var parsentViewController :UIViewController?
fileprivate let viewModel = StockInWHSearchViewModel()
// 当前页码
fileprivate var currentPage : Int = 1
// 是否加载更多
fileprivate var toLoadMore :Bool = false
private let whName = UserDefaults.Global.readString(forKey: .orgName) ?? ""
var stockModel:[StockInWHModel] = [StockInWHModel](){
didSet{
self.reloadData()
}
}
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
setUp()
requstData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUp(){
self.delegate = self
self.dataSource = self
self.estimatedRowHeight = 200
self.rowHeight = UITableViewAutomaticDimension
self.register(StockOnRoadTableViewCell.self)
self.tableHeaderView = headerView
headerView.addSubview(searchBtn)
headerView.addSubview(whNameLB)
whNameLB.text = "仓配中心:\(whName)"
headerView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(gotoSearch)))
}
lazy var headerView:UIView = {
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 70))
headerView.backgroundColor = UIColor.white
return headerView
}()
lazy var searchBtn:UISearchBar = {
let search = UISearchBar(frame: CGRect(x: 0, y: 5, width: kScreenWidth, height: 30))
search.placeholder = "点击搜索"
search.searchBarStyle = .minimal
search.isUserInteractionEnabled = false
return search
}()
lazy var whNameLB:UILabel = {
let whNameLB = UILabel(frame: CGRect(x: 10, y: 45, width: kScreenWidth-20, height: 20))
whNameLB.font = UIFont.systemFont(ofSize: 14)
return whNameLB
}()
@objc func gotoSearch(){
let searchVC = StockOnRoadSearchViewController()
searchVC.getData = {(arr:[StockInWHModel]?) in
self.stockModel = arr!
}
parsentViewController?.navigationController?.pushViewController(searchVC, animated: true)
}
fileprivate func requstData(){
let param = ["pageNum":"\(currentPage)","pageSize":"10"]
viewModel.requstStockOnRoad(param) { (result,hasNextPage, error) in
if result.count > 0{
var child = [StockInWHModel]()
for item in result{
child.append(StockInWHModel.init(dict: item))
}
if hasNextPage && self.toLoadMore{
self.toLoadMore = false
self.currentPage -= 1
self.stockModel += child
}else{
self.toLoadMore = true
self.stockModel += child
}
}
}
}
}
extension StockOnRoadTableView:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "StockOnRoadTableViewCell") as! StockOnRoadTableViewCell
let model = stockModel[indexPath.row]
if stockModel.count > 0 && indexPath.row == stockModel.count-1 && toLoadMore{
currentPage+=1
requstData()
}
cell.stockModel = model
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stockModel.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.01
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
}
| 8014a59a744861df14996f8b912711dd | 30.763359 | 121 | 0.605624 | false | false | false | false |
vakoc/particle-swift-cli | refs/heads/master | Sources/ProductCommands.swift | apache-2.0 | 1 | // This source file is part of the vakoc.com open source project(s)
//
// Copyright © 2017 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See http://www.vakoc.com/LICENSE.txt for license information
import Foundation
import ParticleSwift
fileprivate let productIdArgument = Argument(name: .productId, helpText: "Product ID or slug", options: [.hasValue])
fileprivate let requiredProductIdArgument = Argument(name: .productId, helpText: "Product ID or slug", options: [.required, .hasValue])
fileprivate let usernameArgument = Argument(name: .username, helpText: "Username of the invitee. Must be a valid email associated with an Particle user", options: [.required, .hasValue])
let productsCommand = Command(name: .products, summary: "List the available products", arguments: [productIdArgument], subHelp: nil) {(arguments, extras, callback) in
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.products(arguments[productIdArgument]) { (result) in
switch (result) {
case .success(let products):
let stringValue = "\(products)"
callback( .success(string: stringValue, json: products.map { $0.dictionary} ))
case .failure(let err):
callback( .failure(Errors.productsFailed(err)))
}
}
}
let productTeamMembersCommand = Command(name: .productTeamMembers, summary: "List the product team members", arguments: [requiredProductIdArgument], subHelp: nil) {(arguments, extras, callback) in
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.productTeamMembers(arguments[requiredProductIdArgument]!) { (result) in
switch (result) {
case .success(let productTeamMembers):
let stringValue = "\(productTeamMembers)"
callback( .success(string: stringValue, json: productTeamMembers.map { $0.dictionary} ))
case .failure(let err):
callback( .failure(Errors.productTeamMembersFailed(err)))
}
}
}
let productInviteTeamMember = Command(name: .productInviteTeamMember, summary: "Invite the specified team member to a product", arguments: [requiredProductIdArgument, usernameArgument], subHelp: nil) {(arguments, extras, callback) in
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.inviteTeamMember(arguments[requiredProductIdArgument]!, username: arguments[usernameArgument]!) { (result) in
switch (result) {
case .success(let productTeamInvite):
let stringValue = "\(productTeamInvite)"
callback( .success(string: stringValue, json: productTeamInvite.dictionary ))
case .failure(let err):
callback( .failure(Errors.productInviteTeamMemberFailed(err)))
}
}
}
let productRemoveTeamMember = Command(name: .productRemoveTeamMember, summary: "Remove the specified team member from a product", arguments: [requiredProductIdArgument, usernameArgument], subHelp: nil) {(arguments, extras, callback) in
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.removeTeamMember(arguments[requiredProductIdArgument]!, username: arguments[usernameArgument]!) { (result) in
switch (result) {
case .success(let result):
let stringValue = "\(result)"
callback( .success(string: stringValue, json: ["ok" : true] ))
case .failure(let err):
callback( .failure(Errors.productRemoveTeamMemberFailed(err)))
}
}
}
| be3ba65ef2b2f6446d553c427abd9c93 | 46.272727 | 236 | 0.701923 | false | false | false | false |
qinting513/SwiftNote | refs/heads/master | youtube/YouTube/Model/Video.swift | apache-2.0 | 1 | //
// Video.swift
// YouTube
//
// Created by Haik Aslanyan on 7/26/16.
// Copyright © 2016 Haik Aslanyan. All rights reserved.
//
import Foundation
import UIKit
class Video {
//MARK: Properties
let videoLink: URL
let title: String
let viewCount: Int
let likes: Int
let disLikes: Int
let channelTitle: String
let channelPic: UIImage
let channelSubscribers: Int
var suggestedVideos = [SuggestedVideo]()
//MARK: Inits
init(videoLink: URL, title: String, viewCount: Int, likes: Int, disLikes: Int, channelTitle: String, channelPic: UIImage, channelSubscribers: Int, suggestedVideos: [SuggestedVideo]) {
self.videoLink = videoLink
self.title = title
self.viewCount = viewCount
self.likes = likes
self.disLikes = disLikes
self.channelTitle = channelTitle
self.channelPic = channelPic
self.channelSubscribers = channelSubscribers
self.suggestedVideos = suggestedVideos
}
//MARK: Methods
class func download(link: URL, completiotion: @escaping ((Video) -> Void)) {
URLSession.shared.dataTask(with: link) { (data, _, error) in
if error == nil {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
let videoLink = URL.init(string: (json["videoLink"] as! String))
let title = json["title"] as! String
let viewCount = json["viewCount"] as! Int
let likes = json["likes"] as! Int
let disLikes = json["disLikes"] as! Int
let channelTitle = json["channelTitle"] as! String
let channelPic = UIImage.contentOfURL(link: (json["channelPic"] as! String))
let channelSubscribers = json["channelSubscribers"] as! Int
let suggestedVideosList = json["suggestedVideos"] as! [[String : String]]
var suggestedVideos = [SuggestedVideo]()
for item in suggestedVideosList {
let videoTitle = item["title"]!
let thumbnail = UIImage.contentOfURL(link: item["thumbnail_image_name"]!)
let name = item["name"]!
let suggestedItem = SuggestedVideo.init(title: videoTitle, name: name, thumbnail: thumbnail)
suggestedVideos.append(suggestedItem)
}
let video = Video.init(videoLink: videoLink!,
title: title,
viewCount: viewCount,
likes: likes,
disLikes: disLikes,
channelTitle: channelTitle,
channelPic: channelPic,
channelSubscribers: channelSubscribers,
suggestedVideos: suggestedVideos)
completiotion(video)
} catch _ {
showNotification()
}
}
}.resume()
}
}
| 99b58893eddbffca50d9e8643b0cc8cf | 42.012821 | 187 | 0.518033 | false | false | false | false |
Subsets and Splits